ssl.c 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526
  1. /* ssl.c
  2. *
  3. * Copyright (C) 2006-2022 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. #if defined(OPENSSL_EXTRA) && !defined(_WIN32)
  26. /* turn on GNU extensions for XISASCII */
  27. #undef _GNU_SOURCE
  28. #define _GNU_SOURCE
  29. #endif
  30. #if !defined(WOLFCRYPT_ONLY) || defined(OPENSSL_EXTRA) || \
  31. defined(OPENSSL_EXTRA_X509_SMALL)
  32. #include <wolfssl/internal.h>
  33. #include <wolfssl/error-ssl.h>
  34. #include <wolfssl/wolfcrypt/coding.h>
  35. #include <wolfssl/wolfcrypt/kdf.h>
  36. #ifdef NO_INLINE
  37. #include <wolfssl/wolfcrypt/misc.h>
  38. #else
  39. #define WOLFSSL_MISC_INCLUDED
  40. #include <wolfcrypt/src/misc.c>
  41. #endif
  42. #ifdef HAVE_ERRNO_H
  43. #include <errno.h>
  44. #endif
  45. #if !defined(WOLFSSL_ALLOW_NO_SUITES) && !defined(WOLFCRYPT_ONLY)
  46. #if defined(NO_DH) && !defined(HAVE_ECC) && !defined(WOLFSSL_STATIC_RSA) \
  47. && !defined(WOLFSSL_STATIC_DH) && !defined(WOLFSSL_STATIC_PSK) \
  48. && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448)
  49. #error "No cipher suites defined because DH disabled, ECC disabled, and no static suites defined. Please see top of README"
  50. #endif
  51. #ifdef WOLFSSL_CERT_GEN
  52. /* need access to Cert struct for creating certificate */
  53. #include <wolfssl/wolfcrypt/asn_public.h>
  54. #endif
  55. #endif
  56. #if !defined(WOLFCRYPT_ONLY) && (defined(OPENSSL_EXTRA) \
  57. || defined(OPENSSL_EXTRA_X509_SMALL) \
  58. || defined(HAVE_WEBSERVER) || defined(WOLFSSL_KEY_GEN))
  59. #include <wolfssl/openssl/evp.h>
  60. /* openssl headers end, wolfssl internal headers next */
  61. #endif
  62. #include <wolfssl/wolfcrypt/wc_encrypt.h>
  63. #ifndef NO_RSA
  64. #include <wolfssl/wolfcrypt/rsa.h>
  65. #endif
  66. #ifdef OPENSSL_EXTRA
  67. /* openssl headers begin */
  68. #include <wolfssl/openssl/ssl.h>
  69. #include <wolfssl/openssl/aes.h>
  70. #ifndef WOLFCRYPT_ONLY
  71. #include <wolfssl/openssl/hmac.h>
  72. #include <wolfssl/openssl/cmac.h>
  73. #endif
  74. #include <wolfssl/openssl/crypto.h>
  75. #include <wolfssl/openssl/des.h>
  76. #include <wolfssl/openssl/bn.h>
  77. #include <wolfssl/openssl/buffer.h>
  78. #include <wolfssl/openssl/dh.h>
  79. #include <wolfssl/openssl/rsa.h>
  80. #include <wolfssl/openssl/fips_rand.h>
  81. #ifndef WOLFCRYPT_ONLY
  82. #include <wolfssl/openssl/pem.h>
  83. #endif
  84. #include <wolfssl/openssl/ec.h>
  85. #include <wolfssl/openssl/ec25519.h>
  86. #include <wolfssl/openssl/ed25519.h>
  87. #include <wolfssl/openssl/ec448.h>
  88. #include <wolfssl/openssl/ed448.h>
  89. #include <wolfssl/openssl/ecdsa.h>
  90. #include <wolfssl/openssl/ecdh.h>
  91. #include <wolfssl/openssl/err.h>
  92. #include <wolfssl/openssl/modes.h>
  93. #include <wolfssl/openssl/opensslv.h>
  94. #include <wolfssl/openssl/rc4.h>
  95. #include <wolfssl/openssl/stack.h>
  96. #include <wolfssl/openssl/x509_vfy.h>
  97. /* openssl headers end, wolfssl internal headers next */
  98. #include <wolfssl/wolfcrypt/hmac.h>
  99. #include <wolfssl/wolfcrypt/random.h>
  100. #include <wolfssl/wolfcrypt/des3.h>
  101. #include <wolfssl/wolfcrypt/ecc.h>
  102. #include <wolfssl/wolfcrypt/md4.h>
  103. #include <wolfssl/wolfcrypt/md5.h>
  104. #include <wolfssl/wolfcrypt/arc4.h>
  105. #include <wolfssl/wolfcrypt/curve25519.h>
  106. #include <wolfssl/wolfcrypt/ed25519.h>
  107. #include <wolfssl/wolfcrypt/curve448.h>
  108. #if defined(HAVE_PQC)
  109. #if defined(HAVE_FALCON)
  110. #include <wolfssl/wolfcrypt/falcon.h>
  111. #endif /* HAVE_FALCON */
  112. #if defined(HAVE_DILITHIUM)
  113. #include <wolfssl/wolfcrypt/dilithium.h>
  114. #endif /* HAVE_DILITHIUM */
  115. #endif /* HAVE_PQC */
  116. #if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL)
  117. #ifdef HAVE_OCSP
  118. #include <wolfssl/openssl/ocsp.h>
  119. #endif
  120. #include <wolfssl/openssl/lhash.h>
  121. #include <wolfssl/openssl/txt_db.h>
  122. #endif /* WITH_STUNNEL */
  123. #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
  124. #include <wolfssl/wolfcrypt/sha512.h>
  125. #endif
  126. #if defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256) \
  127. && !defined(WC_NO_RNG)
  128. #include <wolfssl/wolfcrypt/srp.h>
  129. #endif
  130. #if defined(HAVE_FIPS) || defined(HAVE_SELFTEST)
  131. #include <wolfssl/wolfcrypt/pkcs7.h>
  132. #endif
  133. #if defined(OPENSSL_ALL) && defined(HAVE_PKCS7)
  134. #include <wolfssl/openssl/pkcs7.h>
  135. #endif /* OPENSSL_ALL && HAVE_PKCS7 */
  136. #endif
  137. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  138. #include <wolfssl/openssl/x509v3.h>
  139. int SetIndividualInternal(WOLFSSL_BIGNUM* bn, mp_int* mpi);
  140. int SetIndividualExternal(WOLFSSL_BIGNUM** bn, mp_int* mpi);
  141. #endif
  142. #if defined(WOLFSSL_QT)
  143. #include <wolfssl/wolfcrypt/sha.h>
  144. #endif
  145. #ifdef NO_ASN
  146. #include <wolfssl/wolfcrypt/dh.h>
  147. #endif
  148. #endif /* !WOLFCRYPT_ONLY || OPENSSL_EXTRA */
  149. /*
  150. * OPENSSL_COMPATIBLE_DEFAULTS:
  151. * Enable default behaviour that is compatible with OpenSSL. For example
  152. * SSL_CTX by default doesn't verify the loaded certs. Enabling this
  153. * should make porting to new projects easier.
  154. * WOLFSSL_CHECK_ALERT_ON_ERR:
  155. * Check for alerts during the handshake in the event of an error.
  156. * NO_SESSION_CACHE_REF:
  157. * wolfSSL_get_session on a client will return a reference to the internal
  158. * ClientCache by default for backwards compatibility. This define will
  159. * make wolfSSL_get_session return a reference to ssl->session. The returned
  160. * pointer will be freed with the related WOLFSSL object.
  161. */
  162. #define WOLFSSL_EVP_INCLUDED
  163. #include "wolfcrypt/src/evp.c"
  164. #ifndef WOLFCRYPT_ONLY
  165. #define WOLFSSL_PK_INCLUDED
  166. #include "src/pk.c"
  167. #ifdef OPENSSL_EXTRA
  168. /* Global pointer to constant BN on */
  169. static WOLFSSL_BIGNUM* bn_one = NULL;
  170. /* WOLFSSL_NO_OPENSSL_RAND_CB: Allows way to reduce code size for
  171. * OPENSSL_EXTRA where RAND callbacks are not used */
  172. #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
  173. static const WOLFSSL_RAND_METHOD* gRandMethods = NULL;
  174. static int gRandMethodsInit = 0;
  175. static wolfSSL_Mutex gRandMethodMutex;
  176. #endif /* !WOLFSSL_NO_OPENSSL_RAND_CB */
  177. #endif /* OPENSSL_EXTRA */
  178. #if defined(OPENSSL_EXTRA) && defined(HAVE_ECC)
  179. const WOLF_EC_NIST_NAME kNistCurves[] = {
  180. {XSTR_SIZEOF("P-192"), "P-192", NID_X9_62_prime192v1},
  181. {XSTR_SIZEOF("P-256"), "P-256", NID_X9_62_prime256v1},
  182. {XSTR_SIZEOF("P-112"), "P-112", NID_secp112r1},
  183. {XSTR_SIZEOF("P-112-2"), "P-112-2", NID_secp112r2},
  184. {XSTR_SIZEOF("P-128"), "P-128", NID_secp128r1},
  185. {XSTR_SIZEOF("P-128-2"), "P-128-2", NID_secp128r2},
  186. {XSTR_SIZEOF("P-160"), "P-160", NID_secp160r1},
  187. {XSTR_SIZEOF("P-160-2"), "P-160-2", NID_secp160r2},
  188. {XSTR_SIZEOF("P-224"), "P-224", NID_secp224r1},
  189. {XSTR_SIZEOF("P-384"), "P-384", NID_secp384r1},
  190. {XSTR_SIZEOF("P-521"), "P-521", NID_secp521r1},
  191. {XSTR_SIZEOF("K-160"), "K-160", NID_secp160k1},
  192. {XSTR_SIZEOF("K-192"), "K-192", NID_secp192k1},
  193. {XSTR_SIZEOF("K-224"), "K-224", NID_secp224k1},
  194. {XSTR_SIZEOF("K-256"), "K-256", NID_secp256k1},
  195. {XSTR_SIZEOF("B-160"), "B-160", NID_brainpoolP160r1},
  196. {XSTR_SIZEOF("B-192"), "B-192", NID_brainpoolP192r1},
  197. {XSTR_SIZEOF("B-224"), "B-224", NID_brainpoolP224r1},
  198. {XSTR_SIZEOF("B-256"), "B-256", NID_brainpoolP256r1},
  199. {XSTR_SIZEOF("B-320"), "B-320", NID_brainpoolP320r1},
  200. {XSTR_SIZEOF("B-384"), "B-384", NID_brainpoolP384r1},
  201. {XSTR_SIZEOF("B-512"), "B-512", NID_brainpoolP512r1},
  202. #ifdef HAVE_PQC
  203. {XSTR_SIZEOF("KYBER_LEVEL1"), "KYBER_LEVEL1", WOLFSSL_KYBER_LEVEL1},
  204. {XSTR_SIZEOF("KYBER_LEVEL3"), "KYBER_LEVEL3", WOLFSSL_KYBER_LEVEL3},
  205. {XSTR_SIZEOF("KYBER_LEVEL5"), "KYBER_LEVEL5", WOLFSSL_KYBER_LEVEL5},
  206. {XSTR_SIZEOF("NTRU_HPS_LEVEL1"), "NTRU_HPS_LEVEL1", WOLFSSL_NTRU_HPS_LEVEL1},
  207. {XSTR_SIZEOF("NTRU_HPS_LEVEL3"), "NTRU_HPS_LEVEL3", WOLFSSL_NTRU_HPS_LEVEL3},
  208. {XSTR_SIZEOF("NTRU_HPS_LEVEL5"), "NTRU_HPS_LEVEL5", WOLFSSL_NTRU_HPS_LEVEL5},
  209. {XSTR_SIZEOF("NTRU_HRSS_LEVEL3"), "NTRU_HRSS_LEVEL3", WOLFSSL_NTRU_HRSS_LEVEL3},
  210. {XSTR_SIZEOF("SABER_LEVEL1"), "SABER_LEVEL1", WOLFSSL_SABER_LEVEL1},
  211. {XSTR_SIZEOF("SABER_LEVEL3"), "SABER_LEVEL3", WOLFSSL_SABER_LEVEL3},
  212. {XSTR_SIZEOF("SABER_LEVEL5"), "SABER_LEVEL5", WOLFSSL_SABER_LEVEL5},
  213. {XSTR_SIZEOF("KYBER_90S_LEVEL1"), "KYBER_90S_LEVEL1", WOLFSSL_KYBER_90S_LEVEL1},
  214. {XSTR_SIZEOF("KYBER_90S_LEVEL3"), "KYBER_90S_LEVEL3", WOLFSSL_KYBER_90S_LEVEL3},
  215. {XSTR_SIZEOF("KYBER_90S_LEVEL5"), "KYBER_90S_LEVEL5", WOLFSSL_KYBER_90S_LEVEL5},
  216. {XSTR_SIZEOF("P256_NTRU_HPS_LEVEL1"), "P256_NTRU_HPS_LEVEL1", WOLFSSL_P256_NTRU_HPS_LEVEL1},
  217. {XSTR_SIZEOF("P384_NTRU_HPS_LEVEL3"), "P384_NTRU_HPS_LEVEL3", WOLFSSL_P384_NTRU_HPS_LEVEL3},
  218. {XSTR_SIZEOF("P521_NTRU_HPS_LEVEL5"), "P521_NTRU_HPS_LEVEL5", WOLFSSL_P521_NTRU_HPS_LEVEL5},
  219. {XSTR_SIZEOF("P384_NTRU_HRSS_LEVEL3"), "P384_NTRU_HRSS_LEVEL3", WOLFSSL_P384_NTRU_HRSS_LEVEL3},
  220. {XSTR_SIZEOF("P256_SABER_LEVEL1"), "P256_SABER_LEVEL1", WOLFSSL_P256_SABER_LEVEL1},
  221. {XSTR_SIZEOF("P384_SABER_LEVEL3"), "P384_SABER_LEVEL3", WOLFSSL_P384_SABER_LEVEL3},
  222. {XSTR_SIZEOF("P521_SABER_LEVEL5"), "P521_SABER_LEVEL5", WOLFSSL_P521_SABER_LEVEL5},
  223. {XSTR_SIZEOF("P256_KYBER_LEVEL1"), "P256_KYBER_LEVEL1", WOLFSSL_P256_KYBER_LEVEL1},
  224. {XSTR_SIZEOF("P384_KYBER_LEVEL3"), "P384_KYBER_LEVEL3", WOLFSSL_P384_KYBER_LEVEL3},
  225. {XSTR_SIZEOF("P521_KYBER_LEVEL5"), "P521_KYBER_LEVEL5", WOLFSSL_P521_KYBER_LEVEL5},
  226. {XSTR_SIZEOF("P256_KYBER_90S_LEVEL1"), "P256_KYBER_90S_LEVEL1", WOLFSSL_P256_KYBER_90S_LEVEL1},
  227. {XSTR_SIZEOF("P384_KYBER_90S_LEVEL3"), "P384_KYBER_90S_LEVEL3", WOLFSSL_P384_KYBER_90S_LEVEL3},
  228. {XSTR_SIZEOF("P521_KYBER_90S_LEVEL5"), "P521_KYBER_90S_LEVEL5", WOLFSSL_P521_KYBER_90S_LEVEL5},
  229. #endif
  230. {0, NULL, 0},
  231. };
  232. #endif
  233. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  234. #include <wolfssl/wolfcrypt/port/Renesas/renesas_cmn.h>
  235. #endif
  236. #ifdef WOLFSSL_SESSION_EXPORT
  237. /* Used to import a serialized TLS session.
  238. * WARNING: buf contains sensitive information about the state and is best to be
  239. * encrypted before storing if stored.
  240. *
  241. * @param ssl WOLFSSL structure to import the session into
  242. * @param buf serialized session
  243. * @param sz size of buffer 'buf'
  244. * @return the number of bytes read from buffer 'buf'
  245. */
  246. int wolfSSL_tls_import(WOLFSSL* ssl, const unsigned char* buf, unsigned int sz)
  247. {
  248. if (ssl == NULL || buf == NULL) {
  249. return BAD_FUNC_ARG;
  250. }
  251. return wolfSSL_session_import_internal(ssl, buf, sz, WOLFSSL_EXPORT_TLS);
  252. }
  253. /* Used to export a serialized TLS session.
  254. * WARNING: buf contains sensitive information about the state and is best to be
  255. * encrypted before storing if stored.
  256. *
  257. * @param ssl WOLFSSL structure to export the session from
  258. * @param buf output of serialized session
  259. * @param sz size in bytes set in 'buf'
  260. * @return the number of bytes written into buffer 'buf'
  261. */
  262. int wolfSSL_tls_export(WOLFSSL* ssl, unsigned char* buf, unsigned int* sz)
  263. {
  264. if (ssl == NULL || sz == NULL) {
  265. return BAD_FUNC_ARG;
  266. }
  267. return wolfSSL_session_export_internal(ssl, buf, sz, WOLFSSL_EXPORT_TLS);
  268. }
  269. #ifdef WOLFSSL_DTLS
  270. int wolfSSL_dtls_import(WOLFSSL* ssl, const unsigned char* buf, unsigned int sz)
  271. {
  272. WOLFSSL_ENTER("wolfSSL_session_import");
  273. if (ssl == NULL || buf == NULL) {
  274. return BAD_FUNC_ARG;
  275. }
  276. /* sanity checks on buffer and protocol are done in internal function */
  277. return wolfSSL_session_import_internal(ssl, buf, sz, WOLFSSL_EXPORT_DTLS);
  278. }
  279. /* Sets the function to call for serializing the session. This function is
  280. * called right after the handshake is completed. */
  281. int wolfSSL_CTX_dtls_set_export(WOLFSSL_CTX* ctx, wc_dtls_export func)
  282. {
  283. WOLFSSL_ENTER("wolfSSL_CTX_dtls_set_export");
  284. /* purposefully allow func to be NULL */
  285. if (ctx == NULL) {
  286. return BAD_FUNC_ARG;
  287. }
  288. ctx->dtls_export = func;
  289. return WOLFSSL_SUCCESS;
  290. }
  291. /* Sets the function in WOLFSSL struct to call for serializing the session. This
  292. * function is called right after the handshake is completed. */
  293. int wolfSSL_dtls_set_export(WOLFSSL* ssl, wc_dtls_export func)
  294. {
  295. WOLFSSL_ENTER("wolfSSL_dtls_set_export");
  296. /* purposefully allow func to be NULL */
  297. if (ssl == NULL) {
  298. return BAD_FUNC_ARG;
  299. }
  300. ssl->dtls_export = func;
  301. return WOLFSSL_SUCCESS;
  302. }
  303. /* This function allows for directly serializing a session rather than using
  304. * callbacks. It has less overhead by removing a temporary buffer and gives
  305. * control over when the session gets serialized. When using callbacks the
  306. * session is always serialized immediately after the handshake is finished.
  307. *
  308. * buf is the argument to contain the serialized session
  309. * sz is the size of the buffer passed in
  310. * ssl is the WOLFSSL struct to serialize
  311. * returns the size of serialized session on success, 0 on no action, and
  312. * negative value on error */
  313. int wolfSSL_dtls_export(WOLFSSL* ssl, unsigned char* buf, unsigned int* sz)
  314. {
  315. WOLFSSL_ENTER("wolfSSL_dtls_export");
  316. if (ssl == NULL || sz == NULL) {
  317. return BAD_FUNC_ARG;
  318. }
  319. if (buf == NULL) {
  320. *sz = MAX_EXPORT_BUFFER;
  321. return 0;
  322. }
  323. /* if not DTLS do nothing */
  324. if (!ssl->options.dtls) {
  325. WOLFSSL_MSG("Currently only DTLS export is supported");
  326. return 0;
  327. }
  328. /* copy over keys, options, and dtls state struct */
  329. return wolfSSL_session_export_internal(ssl, buf, sz, WOLFSSL_EXPORT_DTLS);
  330. }
  331. /* This function is similar to wolfSSL_dtls_export but only exports the portion
  332. * of the WOLFSSL structure related to the state of the connection, i.e. peer
  333. * sequence number, epoch, AEAD state etc.
  334. *
  335. * buf is the argument to contain the serialized state, if null then set "sz" to
  336. * buffer size required
  337. * sz is the size of the buffer passed in
  338. * ssl is the WOLFSSL struct to serialize
  339. * returns the size of serialized session on success, 0 on no action, and
  340. * negative value on error */
  341. int wolfSSL_dtls_export_state_only(WOLFSSL* ssl, unsigned char* buf,
  342. unsigned int* sz)
  343. {
  344. WOLFSSL_ENTER("wolfSSL_dtls_export_state_only");
  345. if (ssl == NULL || sz == NULL) {
  346. return BAD_FUNC_ARG;
  347. }
  348. if (buf == NULL) {
  349. *sz = MAX_EXPORT_STATE_BUFFER;
  350. return 0;
  351. }
  352. /* if not DTLS do nothing */
  353. if (!ssl->options.dtls) {
  354. WOLFSSL_MSG("Currently only DTLS export state is supported");
  355. return 0;
  356. }
  357. /* copy over keys, options, and dtls state struct */
  358. return wolfSSL_dtls_export_state_internal(ssl, buf, *sz);
  359. }
  360. /* returns 0 on success */
  361. int wolfSSL_send_session(WOLFSSL* ssl)
  362. {
  363. int ret;
  364. byte* buf;
  365. word32 bufSz = MAX_EXPORT_BUFFER;
  366. WOLFSSL_ENTER("wolfSSL_send_session");
  367. if (ssl == NULL) {
  368. return BAD_FUNC_ARG;
  369. }
  370. buf = (byte*)XMALLOC(bufSz, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  371. if (buf == NULL) {
  372. return MEMORY_E;
  373. }
  374. /* if not DTLS do nothing */
  375. if (!ssl->options.dtls) {
  376. XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  377. WOLFSSL_MSG("Currently only DTLS export is supported");
  378. return 0;
  379. }
  380. /* copy over keys, options, and dtls state struct */
  381. ret = wolfSSL_session_export_internal(ssl, buf, &bufSz, WOLFSSL_EXPORT_DTLS);
  382. if (ret < 0) {
  383. XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  384. return ret;
  385. }
  386. /* if no error ret has size of buffer */
  387. ret = ssl->dtls_export(ssl, buf, ret, NULL);
  388. if (ret != WOLFSSL_SUCCESS) {
  389. XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  390. return ret;
  391. }
  392. XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  393. return 0;
  394. }
  395. #endif /* WOLFSSL_DTLS */
  396. #endif /* WOLFSSL_SESSION_EXPORT */
  397. /* prevent multiple mutex initializations */
  398. static volatile WOLFSSL_GLOBAL int initRefCount = 0;
  399. static WOLFSSL_GLOBAL wolfSSL_Mutex count_mutex; /* init ref count mutex */
  400. static WOLFSSL_GLOBAL int count_mutex_valid = 0;
  401. /* Create a new WOLFSSL_CTX struct and return the pointer to created struct.
  402. WOLFSSL_METHOD pointer passed in is given to ctx to manage.
  403. This function frees the passed in WOLFSSL_METHOD struct on failure and on
  404. success is freed when ctx is freed.
  405. */
  406. WOLFSSL_CTX* wolfSSL_CTX_new_ex(WOLFSSL_METHOD* method, void* heap)
  407. {
  408. WOLFSSL_CTX* ctx = NULL;
  409. WOLFSSL_ENTER("wolfSSL_CTX_new_ex");
  410. if (initRefCount == 0) {
  411. /* user no longer forced to call Init themselves */
  412. int ret = wolfSSL_Init();
  413. if (ret != WOLFSSL_SUCCESS) {
  414. WOLFSSL_MSG("wolfSSL_Init failed");
  415. WOLFSSL_LEAVE("WOLFSSL_CTX_new", 0);
  416. if (method != NULL) {
  417. XFREE(method, heap, DYNAMIC_TYPE_METHOD);
  418. }
  419. return NULL;
  420. }
  421. }
  422. if (method == NULL)
  423. return ctx;
  424. ctx = (WOLFSSL_CTX*)XMALLOC(sizeof(WOLFSSL_CTX), heap, DYNAMIC_TYPE_CTX);
  425. if (ctx) {
  426. int ret;
  427. ret = InitSSL_Ctx(ctx, method, heap);
  428. #ifdef WOLFSSL_STATIC_MEMORY
  429. if (heap != NULL) {
  430. ctx->onHeapHint = 1; /* free the memory back to heap when done */
  431. }
  432. #endif
  433. if (ret < 0) {
  434. WOLFSSL_MSG("Init CTX failed");
  435. wolfSSL_CTX_free(ctx);
  436. ctx = NULL;
  437. }
  438. #if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) \
  439. && !defined(NO_SHA256) && !defined(WC_NO_RNG)
  440. else {
  441. ctx->srp = (Srp*)XMALLOC(sizeof(Srp), heap, DYNAMIC_TYPE_SRP);
  442. if (ctx->srp == NULL){
  443. WOLFSSL_MSG("Init CTX failed");
  444. wolfSSL_CTX_free(ctx);
  445. return NULL;
  446. }
  447. XMEMSET(ctx->srp, 0, sizeof(Srp));
  448. }
  449. #endif
  450. }
  451. else {
  452. WOLFSSL_MSG("Alloc CTX failed, method freed");
  453. XFREE(method, heap, DYNAMIC_TYPE_METHOD);
  454. }
  455. #ifdef OPENSSL_COMPATIBLE_DEFAULTS
  456. if (ctx) {
  457. wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
  458. wolfSSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
  459. if (wolfSSL_CTX_set_min_proto_version(ctx,
  460. (method->version.major == DTLS_MAJOR) ?
  461. DTLS1_VERSION : SSL3_VERSION) != WOLFSSL_SUCCESS ||
  462. #ifdef HAVE_ANON
  463. wolfSSL_CTX_allow_anon_cipher(ctx) != WOLFSSL_SUCCESS ||
  464. #endif
  465. wolfSSL_CTX_set_group_messages(ctx) != WOLFSSL_SUCCESS) {
  466. WOLFSSL_MSG("Setting OpenSSL CTX defaults failed");
  467. wolfSSL_CTX_free(ctx);
  468. ctx = NULL;
  469. }
  470. }
  471. #endif
  472. WOLFSSL_LEAVE("WOLFSSL_CTX_new", 0);
  473. return ctx;
  474. }
  475. WOLFSSL_ABI
  476. WOLFSSL_CTX* wolfSSL_CTX_new(WOLFSSL_METHOD* method)
  477. {
  478. #ifdef WOLFSSL_HEAP_TEST
  479. /* if testing the heap hint then set top level CTX to have test value */
  480. return wolfSSL_CTX_new_ex(method, (void*)WOLFSSL_HEAP_TEST);
  481. #else
  482. return wolfSSL_CTX_new_ex(method, NULL);
  483. #endif
  484. }
  485. /* increases CTX reference count to track proper time to "free" */
  486. int wolfSSL_CTX_up_ref(WOLFSSL_CTX* ctx)
  487. {
  488. int refCount = SSL_CTX_RefCount(ctx, 1);
  489. return ((refCount > 1) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE);
  490. }
  491. WOLFSSL_ABI
  492. void wolfSSL_CTX_free(WOLFSSL_CTX* ctx)
  493. {
  494. WOLFSSL_ENTER("SSL_CTX_free");
  495. if (ctx) {
  496. #if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) \
  497. && !defined(NO_SHA256) && !defined(WC_NO_RNG)
  498. if (ctx->srp != NULL) {
  499. if (ctx->srp_password != NULL){
  500. XFREE(ctx->srp_password, ctx->heap, DYNAMIC_TYPE_SRP);
  501. ctx->srp_password = NULL;
  502. }
  503. wc_SrpTerm(ctx->srp);
  504. XFREE(ctx->srp, ctx->heap, DYNAMIC_TYPE_SRP);
  505. ctx->srp = NULL;
  506. }
  507. #endif
  508. FreeSSL_Ctx(ctx);
  509. }
  510. WOLFSSL_LEAVE("SSL_CTX_free", 0);
  511. }
  512. #ifdef HAVE_ENCRYPT_THEN_MAC
  513. /**
  514. * Sets whether Encrypt-Then-MAC extension can be negotiated against context.
  515. * The default value: enabled.
  516. *
  517. * ctx SSL/TLS context.
  518. * set Whether to allow or not: 1 is allow and 0 is disallow.
  519. * returns WOLFSSL_SUCCESS
  520. */
  521. int wolfSSL_CTX_AllowEncryptThenMac(WOLFSSL_CTX *ctx, int set)
  522. {
  523. ctx->disallowEncThenMac = !set;
  524. return WOLFSSL_SUCCESS;
  525. }
  526. /**
  527. * Sets whether Encrypt-Then-MAC extension can be negotiated against context.
  528. * The default value comes from context.
  529. *
  530. * ctx SSL/TLS context.
  531. * set Whether to allow or not: 1 is allow and 0 is disallow.
  532. * returns WOLFSSL_SUCCESS
  533. */
  534. int wolfSSL_AllowEncryptThenMac(WOLFSSL *ssl, int set)
  535. {
  536. ssl->options.disallowEncThenMac = !set;
  537. return WOLFSSL_SUCCESS;
  538. }
  539. #endif
  540. #ifdef SINGLE_THREADED
  541. /* no locking in single threaded mode, allow a CTX level rng to be shared with
  542. * WOLFSSL objects, WOLFSSL_SUCCESS on ok */
  543. int wolfSSL_CTX_new_rng(WOLFSSL_CTX* ctx)
  544. {
  545. WC_RNG* rng;
  546. int ret;
  547. if (ctx == NULL) {
  548. return BAD_FUNC_ARG;
  549. }
  550. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), ctx->heap, DYNAMIC_TYPE_RNG);
  551. if (rng == NULL) {
  552. return MEMORY_E;
  553. }
  554. #ifndef HAVE_FIPS
  555. ret = wc_InitRng_ex(rng, ctx->heap, ctx->devId);
  556. #else
  557. ret = wc_InitRng(rng);
  558. #endif
  559. if (ret != 0) {
  560. XFREE(rng, ctx->heap, DYNAMIC_TYPE_RNG);
  561. return ret;
  562. }
  563. ctx->rng = rng;
  564. return WOLFSSL_SUCCESS;
  565. }
  566. #endif
  567. WOLFSSL_ABI
  568. WOLFSSL* wolfSSL_new(WOLFSSL_CTX* ctx)
  569. {
  570. WOLFSSL* ssl = NULL;
  571. int ret = 0;
  572. WOLFSSL_ENTER("SSL_new");
  573. if (ctx == NULL)
  574. return ssl;
  575. ssl = (WOLFSSL*) XMALLOC(sizeof(WOLFSSL), ctx->heap, DYNAMIC_TYPE_SSL);
  576. if (ssl)
  577. if ( (ret = InitSSL(ssl, ctx, 0)) < 0) {
  578. FreeSSL(ssl, ctx->heap);
  579. ssl = 0;
  580. }
  581. WOLFSSL_LEAVE("SSL_new", ret);
  582. (void)ret;
  583. return ssl;
  584. }
  585. WOLFSSL_ABI
  586. void wolfSSL_free(WOLFSSL* ssl)
  587. {
  588. WOLFSSL_ENTER("SSL_free");
  589. if (ssl)
  590. FreeSSL(ssl, ssl->ctx->heap);
  591. WOLFSSL_LEAVE("SSL_free", 0);
  592. }
  593. int wolfSSL_is_server(WOLFSSL* ssl)
  594. {
  595. if (ssl == NULL)
  596. return BAD_FUNC_ARG;
  597. return ssl->options.side == WOLFSSL_SERVER_END;
  598. }
  599. #ifdef HAVE_WRITE_DUP
  600. /*
  601. * Release resources around WriteDup object
  602. *
  603. * ssl WOLFSSL object
  604. *
  605. * no return, destruction so make best attempt
  606. */
  607. void FreeWriteDup(WOLFSSL* ssl)
  608. {
  609. int doFree = 0;
  610. WOLFSSL_ENTER("FreeWriteDup");
  611. if (ssl->dupWrite) {
  612. if (wc_LockMutex(&ssl->dupWrite->dupMutex) == 0) {
  613. ssl->dupWrite->dupCount--;
  614. if (ssl->dupWrite->dupCount == 0) {
  615. doFree = 1;
  616. } else {
  617. WOLFSSL_MSG("WriteDup count not zero, no full free");
  618. }
  619. wc_UnLockMutex(&ssl->dupWrite->dupMutex);
  620. }
  621. }
  622. if (doFree) {
  623. WOLFSSL_MSG("Doing WriteDup full free, count to zero");
  624. wc_FreeMutex(&ssl->dupWrite->dupMutex);
  625. XFREE(ssl->dupWrite, ssl->heap, DYNAMIC_TYPE_WRITEDUP);
  626. }
  627. }
  628. /*
  629. * duplicate existing ssl members into dup needed for writing
  630. *
  631. * dup write only WOLFSSL
  632. * ssl existing WOLFSSL
  633. *
  634. * 0 on success
  635. */
  636. static int DupSSL(WOLFSSL* dup, WOLFSSL* ssl)
  637. {
  638. /* shared dupWrite setup */
  639. ssl->dupWrite = (WriteDup*)XMALLOC(sizeof(WriteDup), ssl->heap,
  640. DYNAMIC_TYPE_WRITEDUP);
  641. if (ssl->dupWrite == NULL) {
  642. return MEMORY_E;
  643. }
  644. XMEMSET(ssl->dupWrite, 0, sizeof(WriteDup));
  645. if (wc_InitMutex(&ssl->dupWrite->dupMutex) != 0) {
  646. XFREE(ssl->dupWrite, ssl->heap, DYNAMIC_TYPE_WRITEDUP);
  647. ssl->dupWrite = NULL;
  648. return BAD_MUTEX_E;
  649. }
  650. ssl->dupWrite->dupCount = 2; /* both sides have a count to start */
  651. dup->dupWrite = ssl->dupWrite; /* each side uses */
  652. /* copy write parts over to dup writer */
  653. XMEMCPY(&dup->specs, &ssl->specs, sizeof(CipherSpecs));
  654. XMEMCPY(&dup->options, &ssl->options, sizeof(Options));
  655. XMEMCPY(&dup->keys, &ssl->keys, sizeof(Keys));
  656. XMEMCPY(&dup->encrypt, &ssl->encrypt, sizeof(Ciphers));
  657. XMEMCPY(&dup->version, &ssl->version, sizeof(ProtocolVersion));
  658. XMEMCPY(&dup->chVersion, &ssl->chVersion, sizeof(ProtocolVersion));
  659. /* dup side now owns encrypt/write ciphers */
  660. XMEMSET(&ssl->encrypt, 0, sizeof(Ciphers));
  661. dup->IOCB_WriteCtx = ssl->IOCB_WriteCtx;
  662. dup->CBIOSend = ssl->CBIOSend;
  663. #ifdef OPENSSL_EXTRA
  664. dup->cbioFlag = ssl->cbioFlag;
  665. #endif
  666. dup->wfd = ssl->wfd;
  667. dup->wflags = ssl->wflags;
  668. #ifndef WOLFSSL_AEAD_ONLY
  669. dup->hmac = ssl->hmac;
  670. #endif
  671. #ifdef HAVE_TRUNCATED_HMAC
  672. dup->truncated_hmac = ssl->truncated_hmac;
  673. #endif
  674. /* unique side dup setup */
  675. dup->dupSide = WRITE_DUP_SIDE;
  676. ssl->dupSide = READ_DUP_SIDE;
  677. return 0;
  678. }
  679. /*
  680. * duplicate a WOLFSSL object post handshake for writing only
  681. * turn existing object into read only. Allows concurrent access from two
  682. * different threads.
  683. *
  684. * ssl existing WOLFSSL object
  685. *
  686. * return dup'd WOLFSSL object on success
  687. */
  688. WOLFSSL* wolfSSL_write_dup(WOLFSSL* ssl)
  689. {
  690. WOLFSSL* dup = NULL;
  691. int ret = 0;
  692. (void)ret;
  693. WOLFSSL_ENTER("wolfSSL_write_dup");
  694. if (ssl == NULL) {
  695. return ssl;
  696. }
  697. if (ssl->options.handShakeDone == 0) {
  698. WOLFSSL_MSG("wolfSSL_write_dup called before handshake complete");
  699. return NULL;
  700. }
  701. if (ssl->dupWrite) {
  702. WOLFSSL_MSG("wolfSSL_write_dup already called once");
  703. return NULL;
  704. }
  705. dup = (WOLFSSL*) XMALLOC(sizeof(WOLFSSL), ssl->ctx->heap, DYNAMIC_TYPE_SSL);
  706. if (dup) {
  707. if ( (ret = InitSSL(dup, ssl->ctx, 1)) < 0) {
  708. FreeSSL(dup, ssl->ctx->heap);
  709. dup = NULL;
  710. } else if ( (ret = DupSSL(dup, ssl)) < 0) {
  711. FreeSSL(dup, ssl->ctx->heap);
  712. dup = NULL;
  713. }
  714. }
  715. WOLFSSL_LEAVE("wolfSSL_write_dup", ret);
  716. return dup;
  717. }
  718. /*
  719. * Notify write dup side of fatal error or close notify
  720. *
  721. * ssl WOLFSSL object
  722. * err Notify err
  723. *
  724. * 0 on success
  725. */
  726. int NotifyWriteSide(WOLFSSL* ssl, int err)
  727. {
  728. int ret;
  729. WOLFSSL_ENTER("NotifyWriteSide");
  730. ret = wc_LockMutex(&ssl->dupWrite->dupMutex);
  731. if (ret == 0) {
  732. ssl->dupWrite->dupErr = err;
  733. ret = wc_UnLockMutex(&ssl->dupWrite->dupMutex);
  734. }
  735. return ret;
  736. }
  737. #endif /* HAVE_WRITE_DUP */
  738. #ifdef HAVE_POLY1305
  739. /* set if to use old poly 1 for yes 0 to use new poly */
  740. int wolfSSL_use_old_poly(WOLFSSL* ssl, int value)
  741. {
  742. (void)ssl;
  743. (void)value;
  744. #ifndef WOLFSSL_NO_TLS12
  745. WOLFSSL_ENTER("SSL_use_old_poly");
  746. WOLFSSL_MSG("Warning SSL connection auto detects old/new and this function"
  747. "is depreciated");
  748. ssl->options.oldPoly = (word16)value;
  749. WOLFSSL_LEAVE("SSL_use_old_poly", 0);
  750. #endif
  751. return 0;
  752. }
  753. #endif
  754. WOLFSSL_ABI
  755. int wolfSSL_set_fd(WOLFSSL* ssl, int fd)
  756. {
  757. int ret;
  758. WOLFSSL_ENTER("SSL_set_fd");
  759. if (ssl == NULL) {
  760. return BAD_FUNC_ARG;
  761. }
  762. ret = wolfSSL_set_read_fd(ssl, fd);
  763. if (ret == WOLFSSL_SUCCESS) {
  764. ret = wolfSSL_set_write_fd(ssl, fd);
  765. }
  766. return ret;
  767. }
  768. #ifdef WOLFSSL_DTLS
  769. int wolfSSL_set_dtls_fd_connected(WOLFSSL* ssl, int fd)
  770. {
  771. int ret;
  772. WOLFSSL_ENTER("SSL_set_dtls_fd_connected");
  773. if (ssl == NULL) {
  774. return BAD_FUNC_ARG;
  775. }
  776. ret = wolfSSL_set_fd(ssl, fd);
  777. if (ret == WOLFSSL_SUCCESS)
  778. ssl->buffers.dtlsCtx.connected = 1;
  779. return ret;
  780. }
  781. #endif
  782. int wolfSSL_set_read_fd(WOLFSSL* ssl, int fd)
  783. {
  784. WOLFSSL_ENTER("SSL_set_read_fd");
  785. if (ssl == NULL) {
  786. return BAD_FUNC_ARG;
  787. }
  788. ssl->rfd = fd; /* not used directly to allow IO callbacks */
  789. ssl->IOCB_ReadCtx = &ssl->rfd;
  790. #ifdef WOLFSSL_DTLS
  791. ssl->buffers.dtlsCtx.connected = 0;
  792. if (ssl->options.dtls) {
  793. ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx;
  794. ssl->buffers.dtlsCtx.rfd = fd;
  795. }
  796. #endif
  797. WOLFSSL_LEAVE("SSL_set_read_fd", WOLFSSL_SUCCESS);
  798. return WOLFSSL_SUCCESS;
  799. }
  800. int wolfSSL_set_write_fd(WOLFSSL* ssl, int fd)
  801. {
  802. WOLFSSL_ENTER("SSL_set_write_fd");
  803. if (ssl == NULL) {
  804. return BAD_FUNC_ARG;
  805. }
  806. ssl->wfd = fd; /* not used directly to allow IO callbacks */
  807. ssl->IOCB_WriteCtx = &ssl->wfd;
  808. #ifdef WOLFSSL_DTLS
  809. ssl->buffers.dtlsCtx.connected = 0;
  810. if (ssl->options.dtls) {
  811. ssl->IOCB_WriteCtx = &ssl->buffers.dtlsCtx;
  812. ssl->buffers.dtlsCtx.wfd = fd;
  813. }
  814. #endif
  815. WOLFSSL_LEAVE("SSL_set_write_fd", WOLFSSL_SUCCESS);
  816. return WOLFSSL_SUCCESS;
  817. }
  818. /**
  819. * Get the name of cipher at priority level passed in.
  820. */
  821. char* wolfSSL_get_cipher_list(int priority)
  822. {
  823. const CipherSuiteInfo* ciphers = GetCipherNames();
  824. if (priority >= GetCipherNamesSize() || priority < 0) {
  825. return 0;
  826. }
  827. return (char*)ciphers[priority].name;
  828. }
  829. /**
  830. * Get the name of cipher at priority level passed in.
  831. */
  832. char* wolfSSL_get_cipher_list_ex(WOLFSSL* ssl, int priority)
  833. {
  834. if (ssl == NULL) {
  835. return NULL;
  836. }
  837. else {
  838. const char* cipher;
  839. if ((cipher = wolfSSL_get_cipher_name_internal(ssl)) != NULL) {
  840. if (priority == 0) {
  841. return (char*)cipher;
  842. }
  843. else {
  844. return NULL;
  845. }
  846. }
  847. else {
  848. return wolfSSL_get_cipher_list(priority);
  849. }
  850. }
  851. }
  852. int wolfSSL_get_ciphers(char* buf, int len)
  853. {
  854. const CipherSuiteInfo* ciphers = GetCipherNames();
  855. int ciphersSz = GetCipherNamesSize();
  856. int i;
  857. int cipherNameSz;
  858. if (buf == NULL || len <= 0)
  859. return BAD_FUNC_ARG;
  860. /* Add each member to the buffer delimited by a : */
  861. for (i = 0; i < ciphersSz; i++) {
  862. cipherNameSz = (int)XSTRLEN(ciphers[i].name);
  863. if (cipherNameSz + 1 < len) {
  864. XSTRNCPY(buf, ciphers[i].name, len);
  865. buf += cipherNameSz;
  866. if (i < ciphersSz - 1)
  867. *buf++ = ':';
  868. *buf = 0;
  869. len -= cipherNameSz + 1;
  870. }
  871. else
  872. return BUFFER_E;
  873. }
  874. return WOLFSSL_SUCCESS;
  875. }
  876. #ifndef NO_ERROR_STRINGS
  877. /* places a list of all supported cipher suites in TLS_* format into "buf"
  878. * return WOLFSSL_SUCCESS on success */
  879. int wolfSSL_get_ciphers_iana(char* buf, int len)
  880. {
  881. const CipherSuiteInfo* ciphers = GetCipherNames();
  882. int ciphersSz = GetCipherNamesSize();
  883. int i;
  884. int cipherNameSz;
  885. if (buf == NULL || len <= 0)
  886. return BAD_FUNC_ARG;
  887. /* Add each member to the buffer delimited by a : */
  888. for (i = 0; i < ciphersSz; i++) {
  889. #ifndef NO_CIPHER_SUITE_ALIASES
  890. if (ciphers[i].flags & WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS)
  891. continue;
  892. #endif
  893. cipherNameSz = (int)XSTRLEN(ciphers[i].name_iana);
  894. if (cipherNameSz + 1 < len) {
  895. XSTRNCPY(buf, ciphers[i].name_iana, len);
  896. buf += cipherNameSz;
  897. if (i < ciphersSz - 1)
  898. *buf++ = ':';
  899. *buf = 0;
  900. len -= cipherNameSz + 1;
  901. }
  902. else
  903. return BUFFER_E;
  904. }
  905. return WOLFSSL_SUCCESS;
  906. }
  907. #endif /* NO_ERROR_STRINGS */
  908. const char* wolfSSL_get_shared_ciphers(WOLFSSL* ssl, char* buf, int len)
  909. {
  910. const char* cipher;
  911. if (ssl == NULL)
  912. return NULL;
  913. cipher = wolfSSL_get_cipher_name_iana(ssl);
  914. len = min(len, (int)(XSTRLEN(cipher) + 1));
  915. XMEMCPY(buf, cipher, len);
  916. return buf;
  917. }
  918. int wolfSSL_get_fd(const WOLFSSL* ssl)
  919. {
  920. int fd = -1;
  921. WOLFSSL_ENTER("SSL_get_fd");
  922. if (ssl) {
  923. fd = ssl->rfd;
  924. }
  925. WOLFSSL_LEAVE("SSL_get_fd", fd);
  926. return fd;
  927. }
  928. int wolfSSL_dtls(WOLFSSL* ssl)
  929. {
  930. int dtlsOpt = 0;
  931. if (ssl)
  932. dtlsOpt = ssl->options.dtls;
  933. return dtlsOpt;
  934. }
  935. #if !defined(NO_CERTS)
  936. /* Set whether mutual authentication is required for connections.
  937. * Server side only.
  938. *
  939. * ctx The SSL/TLS CTX object.
  940. * req 1 to indicate required and 0 when not.
  941. * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
  942. * 0 on success.
  943. */
  944. int wolfSSL_CTX_mutual_auth(WOLFSSL_CTX* ctx, int req)
  945. {
  946. if (ctx == NULL)
  947. return BAD_FUNC_ARG;
  948. if (ctx->method->side == WOLFSSL_CLIENT_END)
  949. return SIDE_ERROR;
  950. ctx->mutualAuth = (byte)req;
  951. return 0;
  952. }
  953. /* Set whether mutual authentication is required for the connection.
  954. * Server side only.
  955. *
  956. * ssl The SSL/TLS object.
  957. * req 1 to indicate required and 0 when not.
  958. * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
  959. * SIDE_ERROR when not a client and 0 on success.
  960. */
  961. int wolfSSL_mutual_auth(WOLFSSL* ssl, int req)
  962. {
  963. if (ssl == NULL)
  964. return BAD_FUNC_ARG;
  965. if (ssl->options.side == WOLFSSL_SERVER_END)
  966. return SIDE_ERROR;
  967. ssl->options.mutualAuth = (word16)req;
  968. return 0;
  969. }
  970. #endif /* NO_CERTS */
  971. #ifdef WOLFSSL_WOLFSENTRY_HOOKS
  972. int wolfSSL_CTX_set_AcceptFilter(
  973. WOLFSSL_CTX *ctx,
  974. NetworkFilterCallback_t AcceptFilter,
  975. void *AcceptFilter_arg)
  976. {
  977. if (ctx == NULL)
  978. return BAD_FUNC_ARG;
  979. ctx->AcceptFilter = AcceptFilter;
  980. ctx->AcceptFilter_arg = AcceptFilter_arg;
  981. return 0;
  982. }
  983. int wolfSSL_set_AcceptFilter(
  984. WOLFSSL *ssl,
  985. NetworkFilterCallback_t AcceptFilter,
  986. void *AcceptFilter_arg)
  987. {
  988. if (ssl == NULL)
  989. return BAD_FUNC_ARG;
  990. ssl->AcceptFilter = AcceptFilter;
  991. ssl->AcceptFilter_arg = AcceptFilter_arg;
  992. return 0;
  993. }
  994. int wolfSSL_CTX_set_ConnectFilter(
  995. WOLFSSL_CTX *ctx,
  996. NetworkFilterCallback_t ConnectFilter,
  997. void *ConnectFilter_arg)
  998. {
  999. if (ctx == NULL)
  1000. return BAD_FUNC_ARG;
  1001. ctx->ConnectFilter = ConnectFilter;
  1002. ctx->ConnectFilter_arg = ConnectFilter_arg;
  1003. return 0;
  1004. }
  1005. int wolfSSL_set_ConnectFilter(
  1006. WOLFSSL *ssl,
  1007. NetworkFilterCallback_t ConnectFilter,
  1008. void *ConnectFilter_arg)
  1009. {
  1010. if (ssl == NULL)
  1011. return BAD_FUNC_ARG;
  1012. ssl->ConnectFilter = ConnectFilter;
  1013. ssl->ConnectFilter_arg = ConnectFilter_arg;
  1014. return 0;
  1015. }
  1016. #endif /* WOLFSSL_WOLFSENTRY_HOOKS */
  1017. #ifndef WOLFSSL_LEANPSK
  1018. #if defined(WOLFSSL_DTLS) && defined(XINET_PTON) && \
  1019. !defined(WOLFSSL_NO_SOCK) && defined(HAVE_SOCKADDR)
  1020. void* wolfSSL_dtls_create_peer(int port, char* ip)
  1021. {
  1022. SOCKADDR_IN *addr;
  1023. addr = (SOCKADDR_IN*)XMALLOC(sizeof(*addr), NULL,
  1024. DYNAMIC_TYPE_SOCKADDR);
  1025. if (addr == NULL) {
  1026. return NULL;
  1027. }
  1028. addr->sin_family = AF_INET;
  1029. addr->sin_port = htons(port);
  1030. if (XINET_PTON(AF_INET, ip, &addr->sin_addr) < 1) {
  1031. XFREE(addr, NULL, DYNAMIC_TYPE_SOCKADDR);
  1032. return NULL;
  1033. }
  1034. return addr;
  1035. }
  1036. int wolfSSL_dtls_free_peer(void* addr)
  1037. {
  1038. XFREE(addr, NULL, DYNAMIC_TYPE_SOCKADDR);
  1039. return WOLFSSL_SUCCESS;
  1040. }
  1041. #endif
  1042. int wolfSSL_dtls_set_peer(WOLFSSL* ssl, void* peer, unsigned int peerSz)
  1043. {
  1044. #ifdef WOLFSSL_DTLS
  1045. void* sa;
  1046. if (ssl == NULL)
  1047. return WOLFSSL_FAILURE;
  1048. if (peer == NULL || peerSz == 0) {
  1049. if (ssl->buffers.dtlsCtx.peer.sa != NULL)
  1050. XFREE(ssl->buffers.dtlsCtx.peer.sa,ssl->heap,DYNAMIC_TYPE_SOCKADDR);
  1051. ssl->buffers.dtlsCtx.peer.sa = NULL;
  1052. ssl->buffers.dtlsCtx.peer.sz = 0;
  1053. ssl->buffers.dtlsCtx.peer.bufSz = 0;
  1054. ssl->buffers.dtlsCtx.userSet = 0;
  1055. return WOLFSSL_SUCCESS;
  1056. }
  1057. sa = (void*)XMALLOC(peerSz, ssl->heap, DYNAMIC_TYPE_SOCKADDR);
  1058. if (sa != NULL) {
  1059. if (ssl->buffers.dtlsCtx.peer.sa != NULL) {
  1060. XFREE(ssl->buffers.dtlsCtx.peer.sa,ssl->heap,DYNAMIC_TYPE_SOCKADDR);
  1061. ssl->buffers.dtlsCtx.peer.sa = NULL;
  1062. }
  1063. XMEMCPY(sa, peer, peerSz);
  1064. ssl->buffers.dtlsCtx.peer.sa = sa;
  1065. ssl->buffers.dtlsCtx.peer.sz = peerSz;
  1066. ssl->buffers.dtlsCtx.peer.bufSz = peerSz;
  1067. ssl->buffers.dtlsCtx.userSet = 1;
  1068. return WOLFSSL_SUCCESS;
  1069. }
  1070. return WOLFSSL_FAILURE;
  1071. #else
  1072. (void)ssl;
  1073. (void)peer;
  1074. (void)peerSz;
  1075. return WOLFSSL_NOT_IMPLEMENTED;
  1076. #endif
  1077. }
  1078. int wolfSSL_dtls_get_peer(WOLFSSL* ssl, void* peer, unsigned int* peerSz)
  1079. {
  1080. #ifdef WOLFSSL_DTLS
  1081. if (ssl == NULL) {
  1082. return WOLFSSL_FAILURE;
  1083. }
  1084. if (peer != NULL && peerSz != NULL
  1085. && *peerSz >= ssl->buffers.dtlsCtx.peer.sz
  1086. && ssl->buffers.dtlsCtx.peer.sa != NULL) {
  1087. *peerSz = ssl->buffers.dtlsCtx.peer.sz;
  1088. XMEMCPY(peer, ssl->buffers.dtlsCtx.peer.sa, *peerSz);
  1089. return WOLFSSL_SUCCESS;
  1090. }
  1091. return WOLFSSL_FAILURE;
  1092. #else
  1093. (void)ssl;
  1094. (void)peer;
  1095. (void)peerSz;
  1096. return WOLFSSL_NOT_IMPLEMENTED;
  1097. #endif
  1098. }
  1099. #if defined(WOLFSSL_SCTP) && defined(WOLFSSL_DTLS)
  1100. int wolfSSL_CTX_dtls_set_sctp(WOLFSSL_CTX* ctx)
  1101. {
  1102. WOLFSSL_ENTER("wolfSSL_CTX_dtls_set_sctp()");
  1103. if (ctx == NULL)
  1104. return BAD_FUNC_ARG;
  1105. ctx->dtlsSctp = 1;
  1106. return WOLFSSL_SUCCESS;
  1107. }
  1108. int wolfSSL_dtls_set_sctp(WOLFSSL* ssl)
  1109. {
  1110. WOLFSSL_ENTER("wolfSSL_dtls_set_sctp()");
  1111. if (ssl == NULL)
  1112. return BAD_FUNC_ARG;
  1113. ssl->options.dtlsSctp = 1;
  1114. return WOLFSSL_SUCCESS;
  1115. }
  1116. #endif /* WOLFSSL_DTLS && WOLFSSL_SCTP */
  1117. #if (defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU)) && \
  1118. defined(WOLFSSL_DTLS)
  1119. int wolfSSL_CTX_dtls_set_mtu(WOLFSSL_CTX* ctx, word16 newMtu)
  1120. {
  1121. if (ctx == NULL || newMtu > MAX_RECORD_SIZE)
  1122. return BAD_FUNC_ARG;
  1123. ctx->dtlsMtuSz = newMtu;
  1124. return WOLFSSL_SUCCESS;
  1125. }
  1126. int wolfSSL_dtls_set_mtu(WOLFSSL* ssl, word16 newMtu)
  1127. {
  1128. if (ssl == NULL)
  1129. return BAD_FUNC_ARG;
  1130. if (newMtu > MAX_RECORD_SIZE) {
  1131. ssl->error = BAD_FUNC_ARG;
  1132. return WOLFSSL_FAILURE;
  1133. }
  1134. ssl->dtlsMtuSz = newMtu;
  1135. return WOLFSSL_SUCCESS;
  1136. }
  1137. #endif /* WOLFSSL_DTLS && (WOLFSSL_SCTP || WOLFSSL_DTLS_MTU) */
  1138. #ifdef WOLFSSL_SRTP
  1139. static const WOLFSSL_SRTP_PROTECTION_PROFILE gSrtpProfiles[] = {
  1140. /* AES CCM 128, Salt:112-bits, Auth HMAC-SHA1 Tag: 80-bits
  1141. * (master_key:128bits + master_salt:112bits) * 2 = 480 bits (60) */
  1142. {"SRTP_AES128_CM_SHA1_80", SRTP_AES128_CM_SHA1_80, (((128 + 112) * 2) / 8) },
  1143. /* AES CCM 128, Salt:112-bits, Auth HMAC-SHA1 Tag: 32-bits
  1144. * (master_key:128bits + master_salt:112bits) * 2 = 480 bits (60) */
  1145. {"SRTP_AES128_CM_SHA1_32", SRTP_AES128_CM_SHA1_32, (((128 + 112) * 2) / 8) },
  1146. /* NULL Cipher, Salt:112-bits, Auth HMAC-SHA1 Tag 80-bits */
  1147. {"SRTP_NULL_SHA1_80", SRTP_NULL_SHA1_80, ((112 * 2) / 8)},
  1148. /* NULL Cipher, Salt:112-bits, Auth HMAC-SHA1 Tag 32-bits */
  1149. {"SRTP_NULL_SHA1_32", SRTP_NULL_SHA1_32, ((112 * 2) / 8)},
  1150. /* AES GCM 128, Salt: 96-bits, Auth GCM Tag 128-bits
  1151. * (master_key:128bits + master_salt:96bits) * 2 = 448 bits (56) */
  1152. {"SRTP_AEAD_AES_128_GCM", SRTP_AEAD_AES_128_GCM, (((128 + 96) * 2) / 8) },
  1153. /* AES GCM 256, Salt: 96-bits, Auth GCM Tag 128-bits
  1154. * (master_key:256bits + master_salt:96bits) * 2 = 704 bits (88) */
  1155. {"SRTP_AEAD_AES_256_GCM", SRTP_AEAD_AES_256_GCM, (((256 + 96) * 2) / 8) },
  1156. };
  1157. static const WOLFSSL_SRTP_PROTECTION_PROFILE* DtlsSrtpFindProfile(
  1158. const char* profile_str, word32 profile_str_len, unsigned long id)
  1159. {
  1160. int i;
  1161. const WOLFSSL_SRTP_PROTECTION_PROFILE* profile = NULL;
  1162. for (i=0;
  1163. i<(int)(sizeof(gSrtpProfiles)/sizeof(WOLFSSL_SRTP_PROTECTION_PROFILE));
  1164. i++) {
  1165. if (profile_str != NULL) {
  1166. word32 srtp_profile_len = (word32)XSTRLEN(gSrtpProfiles[i].name);
  1167. if (srtp_profile_len == profile_str_len &&
  1168. XMEMCMP(gSrtpProfiles[i].name, profile_str, profile_str_len)
  1169. == 0) {
  1170. profile = &gSrtpProfiles[i];
  1171. break;
  1172. }
  1173. }
  1174. else if (id != 0 && gSrtpProfiles[i].id == id) {
  1175. profile = &gSrtpProfiles[i];
  1176. break;
  1177. }
  1178. }
  1179. return profile;
  1180. }
  1181. /* profile_str: accepts ":" colon separated list of SRTP profiles */
  1182. static int DtlsSrtpSelProfiles(word16* id, const char* profile_str)
  1183. {
  1184. const WOLFSSL_SRTP_PROTECTION_PROFILE* profile;
  1185. const char *current, *next = NULL;
  1186. word32 length = 0, current_length;
  1187. *id = 0; /* reset destination ID's */
  1188. if (profile_str == NULL) {
  1189. return WOLFSSL_FAILURE;
  1190. }
  1191. /* loop on end of line or colon ":" */
  1192. next = profile_str;
  1193. length = (word32)XSTRLEN(profile_str);
  1194. do {
  1195. current = next;
  1196. next = XSTRSTR(current, ":");
  1197. current_length = (!next) ? (word32)XSTRLEN(current)
  1198. : (word32)(next - current);
  1199. if (current_length < length)
  1200. length = current_length;
  1201. profile = DtlsSrtpFindProfile(current, current_length, 0);
  1202. if (profile != NULL) {
  1203. *id |= (1 << profile->id); /* selected bit based on ID */
  1204. }
  1205. } while (next != NULL && next++); /* ++ needed to skip ':' */
  1206. return WOLFSSL_SUCCESS;
  1207. }
  1208. int wolfSSL_CTX_set_tlsext_use_srtp(WOLFSSL_CTX* ctx, const char* profile_str)
  1209. {
  1210. int ret = WOLFSSL_FAILURE;
  1211. if (ctx != NULL) {
  1212. ret = DtlsSrtpSelProfiles(&ctx->dtlsSrtpProfiles, profile_str);
  1213. }
  1214. return ret;
  1215. }
  1216. int wolfSSL_set_tlsext_use_srtp(WOLFSSL* ssl, const char* profile_str)
  1217. {
  1218. int ret = WOLFSSL_FAILURE;
  1219. if (ssl != NULL) {
  1220. ret = DtlsSrtpSelProfiles(&ssl->dtlsSrtpProfiles, profile_str);
  1221. }
  1222. return ret;
  1223. }
  1224. const WOLFSSL_SRTP_PROTECTION_PROFILE* wolfSSL_get_selected_srtp_profile(
  1225. WOLFSSL* ssl)
  1226. {
  1227. const WOLFSSL_SRTP_PROTECTION_PROFILE* profile = NULL;
  1228. if (ssl) {
  1229. profile = DtlsSrtpFindProfile(NULL, 0, ssl->dtlsSrtpId);
  1230. }
  1231. return profile;
  1232. }
  1233. #ifndef NO_WOLFSSL_STUB
  1234. WOLF_STACK_OF(WOLFSSL_SRTP_PROTECTION_PROFILE)* wolfSSL_get_srtp_profiles(
  1235. WOLFSSL* ssl)
  1236. {
  1237. /* Not yet implemented - should return list of available SRTP profiles
  1238. * ssl->dtlsSrtpProfiles */
  1239. (void)ssl;
  1240. return NULL;
  1241. }
  1242. #endif
  1243. int wolfSSL_export_dtls_srtp_keying_material(WOLFSSL* ssl,
  1244. unsigned char* out, size_t* olen)
  1245. {
  1246. int ret = WOLFSSL_FAILURE;
  1247. const char* label = "EXTRACTOR-dtls_srtp";
  1248. const WOLFSSL_SRTP_PROTECTION_PROFILE* profile = NULL;
  1249. byte seed[SEED_LEN];
  1250. if (ssl == NULL || olen == NULL) {
  1251. return BAD_FUNC_ARG;
  1252. }
  1253. profile = DtlsSrtpFindProfile(NULL, 0, ssl->dtlsSrtpId);
  1254. if (profile == NULL) {
  1255. WOLFSSL_MSG("Not using DTLS SRTP");
  1256. return EXT_MISSING;
  1257. }
  1258. if (out == NULL) {
  1259. *olen = profile->kdfBits;
  1260. return LENGTH_ONLY_E;
  1261. }
  1262. if (*olen < (size_t)profile->kdfBits) {
  1263. return BUFFER_E;
  1264. }
  1265. #ifdef WOLFSSL_HAVE_PRF
  1266. XMEMCPY(seed, ssl->arrays->clientRandom, RAN_LEN);
  1267. XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
  1268. PRIVATE_KEY_UNLOCK();
  1269. ret = wc_PRF_TLS(out, profile->kdfBits, /* out: generated keys / salt */
  1270. ssl->arrays->masterSecret, SECRET_LEN, /* existing master secret */
  1271. (const byte*)label, (int)XSTRLEN(label),/* label */
  1272. seed, SEED_LEN, /* seed: client/server random */
  1273. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  1274. ssl->heap, INVALID_DEVID);
  1275. if (ret == 0) {
  1276. *olen = profile->kdfBits;
  1277. ret = WOLFSSL_SUCCESS;
  1278. }
  1279. PRIVATE_KEY_LOCK();
  1280. #else
  1281. /* Pseudo random function must be enabled in the configuration */
  1282. ret = PRF_MISSING;
  1283. #endif
  1284. return ret;
  1285. }
  1286. #endif /* WOLFSSL_SRTP */
  1287. #ifdef WOLFSSL_DTLS_DROP_STATS
  1288. int wolfSSL_dtls_get_drop_stats(WOLFSSL* ssl,
  1289. word32* macDropCount, word32* replayDropCount)
  1290. {
  1291. int ret;
  1292. WOLFSSL_ENTER("wolfSSL_dtls_get_drop_stats()");
  1293. if (ssl == NULL)
  1294. ret = BAD_FUNC_ARG;
  1295. else {
  1296. ret = WOLFSSL_SUCCESS;
  1297. if (macDropCount != NULL)
  1298. *macDropCount = ssl->macDropCount;
  1299. if (replayDropCount != NULL)
  1300. *replayDropCount = ssl->replayDropCount;
  1301. }
  1302. WOLFSSL_LEAVE("wolfSSL_dtls_get_drop_stats()", ret);
  1303. return ret;
  1304. }
  1305. #endif /* WOLFSSL_DTLS_DROP_STATS */
  1306. #if defined(WOLFSSL_MULTICAST)
  1307. int wolfSSL_CTX_mcast_set_member_id(WOLFSSL_CTX* ctx, word16 id)
  1308. {
  1309. int ret = 0;
  1310. WOLFSSL_ENTER("wolfSSL_CTX_mcast_set_member_id()");
  1311. if (ctx == NULL || id > 255)
  1312. ret = BAD_FUNC_ARG;
  1313. if (ret == 0) {
  1314. ctx->haveEMS = 0;
  1315. ctx->haveMcast = 1;
  1316. ctx->mcastID = (byte)id;
  1317. #ifndef WOLFSSL_USER_IO
  1318. ctx->CBIORecv = EmbedReceiveFromMcast;
  1319. #endif /* WOLFSSL_USER_IO */
  1320. ret = WOLFSSL_SUCCESS;
  1321. }
  1322. WOLFSSL_LEAVE("wolfSSL_CTX_mcast_set_member_id()", ret);
  1323. return ret;
  1324. }
  1325. int wolfSSL_mcast_get_max_peers(void)
  1326. {
  1327. return WOLFSSL_MULTICAST_PEERS;
  1328. }
  1329. #ifdef WOLFSSL_DTLS
  1330. static WC_INLINE word32 UpdateHighwaterMark(word32 cur, word32 first,
  1331. word32 second, word32 high)
  1332. {
  1333. word32 newCur = 0;
  1334. if (cur < first)
  1335. newCur = first;
  1336. else if (cur < second)
  1337. newCur = second;
  1338. else if (cur < high)
  1339. newCur = high;
  1340. return newCur;
  1341. }
  1342. #endif /* WOLFSSL_DTLS */
  1343. int wolfSSL_set_secret(WOLFSSL* ssl, word16 epoch,
  1344. const byte* preMasterSecret, word32 preMasterSz,
  1345. const byte* clientRandom, const byte* serverRandom,
  1346. const byte* suite)
  1347. {
  1348. int ret = 0;
  1349. WOLFSSL_ENTER("wolfSSL_set_secret()");
  1350. if (ssl == NULL || preMasterSecret == NULL ||
  1351. preMasterSz == 0 || preMasterSz > ENCRYPT_LEN ||
  1352. clientRandom == NULL || serverRandom == NULL || suite == NULL) {
  1353. ret = BAD_FUNC_ARG;
  1354. }
  1355. if (ret == 0 && ssl->arrays->preMasterSecret == NULL) {
  1356. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  1357. ssl->arrays->preMasterSecret = (byte*)XMALLOC(ENCRYPT_LEN, ssl->heap,
  1358. DYNAMIC_TYPE_SECRET);
  1359. if (ssl->arrays->preMasterSecret == NULL) {
  1360. ret = MEMORY_E;
  1361. }
  1362. }
  1363. if (ret == 0) {
  1364. XMEMCPY(ssl->arrays->preMasterSecret, preMasterSecret, preMasterSz);
  1365. XMEMSET(ssl->arrays->preMasterSecret + preMasterSz, 0, ENCRYPT_LEN - preMasterSz);
  1366. ssl->arrays->preMasterSz = preMasterSz;
  1367. XMEMCPY(ssl->arrays->clientRandom, clientRandom, RAN_LEN);
  1368. XMEMCPY(ssl->arrays->serverRandom, serverRandom, RAN_LEN);
  1369. ssl->options.cipherSuite0 = suite[0];
  1370. ssl->options.cipherSuite = suite[1];
  1371. ret = SetCipherSpecs(ssl);
  1372. }
  1373. if (ret == 0)
  1374. ret = MakeTlsMasterSecret(ssl);
  1375. if (ret == 0) {
  1376. ssl->keys.encryptionOn = 1;
  1377. ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE);
  1378. }
  1379. if (ret == 0) {
  1380. if (ssl->options.dtls) {
  1381. #ifdef WOLFSSL_DTLS
  1382. WOLFSSL_DTLS_PEERSEQ* peerSeq;
  1383. int i;
  1384. ssl->keys.dtls_epoch = epoch;
  1385. for (i = 0, peerSeq = ssl->keys.peerSeq;
  1386. i < WOLFSSL_DTLS_PEERSEQ_SZ;
  1387. i++, peerSeq++) {
  1388. peerSeq->nextEpoch = epoch;
  1389. peerSeq->prevSeq_lo = peerSeq->nextSeq_lo;
  1390. peerSeq->prevSeq_hi = peerSeq->nextSeq_hi;
  1391. peerSeq->nextSeq_lo = 0;
  1392. peerSeq->nextSeq_hi = 0;
  1393. XMEMCPY(peerSeq->prevWindow, peerSeq->window, DTLS_SEQ_SZ);
  1394. XMEMSET(peerSeq->window, 0, DTLS_SEQ_SZ);
  1395. peerSeq->highwaterMark = UpdateHighwaterMark(0,
  1396. ssl->ctx->mcastFirstSeq,
  1397. ssl->ctx->mcastSecondSeq,
  1398. ssl->ctx->mcastMaxSeq);
  1399. }
  1400. #else
  1401. (void)epoch;
  1402. #endif
  1403. }
  1404. FreeHandshakeResources(ssl);
  1405. ret = WOLFSSL_SUCCESS;
  1406. }
  1407. else {
  1408. if (ssl)
  1409. ssl->error = ret;
  1410. ret = WOLFSSL_FATAL_ERROR;
  1411. }
  1412. WOLFSSL_LEAVE("wolfSSL_set_secret()", ret);
  1413. return ret;
  1414. }
  1415. #ifdef WOLFSSL_DTLS
  1416. int wolfSSL_mcast_peer_add(WOLFSSL* ssl, word16 peerId, int sub)
  1417. {
  1418. WOLFSSL_DTLS_PEERSEQ* p = NULL;
  1419. int ret = WOLFSSL_SUCCESS;
  1420. int i;
  1421. WOLFSSL_ENTER("wolfSSL_mcast_peer_add()");
  1422. if (ssl == NULL || peerId > 255)
  1423. return BAD_FUNC_ARG;
  1424. if (!sub) {
  1425. /* Make sure it isn't already present, while keeping the first
  1426. * open spot. */
  1427. for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++) {
  1428. if (ssl->keys.peerSeq[i].peerId == INVALID_PEER_ID)
  1429. p = &ssl->keys.peerSeq[i];
  1430. if (ssl->keys.peerSeq[i].peerId == peerId) {
  1431. WOLFSSL_MSG("Peer ID already in multicast peer list.");
  1432. p = NULL;
  1433. }
  1434. }
  1435. if (p != NULL) {
  1436. XMEMSET(p, 0, sizeof(WOLFSSL_DTLS_PEERSEQ));
  1437. p->peerId = peerId;
  1438. p->highwaterMark = UpdateHighwaterMark(0,
  1439. ssl->ctx->mcastFirstSeq,
  1440. ssl->ctx->mcastSecondSeq,
  1441. ssl->ctx->mcastMaxSeq);
  1442. }
  1443. else {
  1444. WOLFSSL_MSG("No room in peer list.");
  1445. ret = -1;
  1446. }
  1447. }
  1448. else {
  1449. for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++) {
  1450. if (ssl->keys.peerSeq[i].peerId == peerId)
  1451. p = &ssl->keys.peerSeq[i];
  1452. }
  1453. if (p != NULL) {
  1454. p->peerId = INVALID_PEER_ID;
  1455. }
  1456. else {
  1457. WOLFSSL_MSG("Peer not found in list.");
  1458. }
  1459. }
  1460. WOLFSSL_LEAVE("wolfSSL_mcast_peer_add()", ret);
  1461. return ret;
  1462. }
  1463. /* If peerId is in the list of peers and its last sequence number is non-zero,
  1464. * return 1, otherwise return 0. */
  1465. int wolfSSL_mcast_peer_known(WOLFSSL* ssl, unsigned short peerId)
  1466. {
  1467. int known = 0;
  1468. int i;
  1469. WOLFSSL_ENTER("wolfSSL_mcast_peer_known()");
  1470. if (ssl == NULL || peerId > 255) {
  1471. return BAD_FUNC_ARG;
  1472. }
  1473. for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++) {
  1474. if (ssl->keys.peerSeq[i].peerId == peerId) {
  1475. if (ssl->keys.peerSeq[i].nextSeq_hi ||
  1476. ssl->keys.peerSeq[i].nextSeq_lo) {
  1477. known = 1;
  1478. }
  1479. break;
  1480. }
  1481. }
  1482. WOLFSSL_LEAVE("wolfSSL_mcast_peer_known()", known);
  1483. return known;
  1484. }
  1485. int wolfSSL_CTX_mcast_set_highwater_cb(WOLFSSL_CTX* ctx, word32 maxSeq,
  1486. word32 first, word32 second,
  1487. CallbackMcastHighwater cb)
  1488. {
  1489. if (ctx == NULL || (second && first > second) ||
  1490. first > maxSeq || second > maxSeq || cb == NULL) {
  1491. return BAD_FUNC_ARG;
  1492. }
  1493. ctx->mcastHwCb = cb;
  1494. ctx->mcastFirstSeq = first;
  1495. ctx->mcastSecondSeq = second;
  1496. ctx->mcastMaxSeq = maxSeq;
  1497. return WOLFSSL_SUCCESS;
  1498. }
  1499. int wolfSSL_mcast_set_highwater_ctx(WOLFSSL* ssl, void* ctx)
  1500. {
  1501. if (ssl == NULL || ctx == NULL)
  1502. return BAD_FUNC_ARG;
  1503. ssl->mcastHwCbCtx = ctx;
  1504. return WOLFSSL_SUCCESS;
  1505. }
  1506. #endif /* WOLFSSL_DTLS */
  1507. #endif /* WOLFSSL_MULTICAST */
  1508. #endif /* WOLFSSL_LEANPSK */
  1509. /* return underlying connect or accept, WOLFSSL_SUCCESS on ok */
  1510. int wolfSSL_negotiate(WOLFSSL* ssl)
  1511. {
  1512. int err = WOLFSSL_FATAL_ERROR;
  1513. WOLFSSL_ENTER("wolfSSL_negotiate");
  1514. if (ssl == NULL)
  1515. return WOLFSSL_FATAL_ERROR;
  1516. #ifndef NO_WOLFSSL_SERVER
  1517. if (ssl->options.side == WOLFSSL_SERVER_END) {
  1518. #ifdef WOLFSSL_TLS13
  1519. if (IsAtLeastTLSv1_3(ssl->version))
  1520. err = wolfSSL_accept_TLSv13(ssl);
  1521. else
  1522. #endif
  1523. err = wolfSSL_accept(ssl);
  1524. }
  1525. #endif
  1526. #ifndef NO_WOLFSSL_CLIENT
  1527. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  1528. #ifdef WOLFSSL_TLS13
  1529. if (IsAtLeastTLSv1_3(ssl->version))
  1530. err = wolfSSL_connect_TLSv13(ssl);
  1531. else
  1532. #endif
  1533. err = wolfSSL_connect(ssl);
  1534. }
  1535. #endif
  1536. (void)ssl;
  1537. WOLFSSL_LEAVE("wolfSSL_negotiate", err);
  1538. return err;
  1539. }
  1540. WOLFSSL_ABI
  1541. WC_RNG* wolfSSL_GetRNG(WOLFSSL* ssl)
  1542. {
  1543. if (ssl) {
  1544. return ssl->rng;
  1545. }
  1546. return NULL;
  1547. }
  1548. #ifndef WOLFSSL_LEANPSK
  1549. /* object size based on build */
  1550. int wolfSSL_GetObjectSize(void)
  1551. {
  1552. #ifdef SHOW_SIZES
  1553. printf("sizeof suites = %lu\n", (unsigned long)sizeof(Suites));
  1554. printf("sizeof ciphers(2) = %lu\n", (unsigned long)sizeof(Ciphers));
  1555. #ifndef NO_RC4
  1556. printf("\tsizeof arc4 = %lu\n", (unsigned long)sizeof(Arc4));
  1557. #endif
  1558. printf("\tsizeof aes = %lu\n", (unsigned long)sizeof(Aes));
  1559. #ifndef NO_DES3
  1560. printf("\tsizeof des3 = %lu\n", (unsigned long)sizeof(Des3));
  1561. #endif
  1562. #ifdef HAVE_CHACHA
  1563. printf("\tsizeof chacha = %lu\n", (unsigned long)sizeof(ChaCha));
  1564. #endif
  1565. printf("sizeof cipher specs = %lu\n", (unsigned long)sizeof(CipherSpecs));
  1566. printf("sizeof keys = %lu\n", (unsigned long)sizeof(Keys));
  1567. printf("sizeof Hashes(2) = %lu\n", (unsigned long)sizeof(Hashes));
  1568. #ifndef NO_MD5
  1569. printf("\tsizeof MD5 = %lu\n", (unsigned long)sizeof(wc_Md5));
  1570. #endif
  1571. #ifndef NO_SHA
  1572. printf("\tsizeof SHA = %lu\n", (unsigned long)sizeof(wc_Sha));
  1573. #endif
  1574. #ifdef WOLFSSL_SHA224
  1575. printf("\tsizeof SHA224 = %lu\n", (unsigned long)sizeof(wc_Sha224));
  1576. #endif
  1577. #ifndef NO_SHA256
  1578. printf("\tsizeof SHA256 = %lu\n", (unsigned long)sizeof(wc_Sha256));
  1579. #endif
  1580. #ifdef WOLFSSL_SHA384
  1581. printf("\tsizeof SHA384 = %lu\n", (unsigned long)sizeof(wc_Sha384));
  1582. #endif
  1583. #ifdef WOLFSSL_SHA384
  1584. printf("\tsizeof SHA512 = %lu\n", (unsigned long)sizeof(wc_Sha512));
  1585. #endif
  1586. printf("sizeof Buffers = %lu\n", (unsigned long)sizeof(Buffers));
  1587. printf("sizeof Options = %lu\n", (unsigned long)sizeof(Options));
  1588. printf("sizeof Arrays = %lu\n", (unsigned long)sizeof(Arrays));
  1589. #ifndef NO_RSA
  1590. printf("sizeof RsaKey = %lu\n", (unsigned long)sizeof(RsaKey));
  1591. #endif
  1592. #ifdef HAVE_ECC
  1593. printf("sizeof ecc_key = %lu\n", (unsigned long)sizeof(ecc_key));
  1594. #endif
  1595. printf("sizeof WOLFSSL_CIPHER = %lu\n", (unsigned long)sizeof(WOLFSSL_CIPHER));
  1596. printf("sizeof WOLFSSL_SESSION = %lu\n", (unsigned long)sizeof(WOLFSSL_SESSION));
  1597. printf("sizeof WOLFSSL = %lu\n", (unsigned long)sizeof(WOLFSSL));
  1598. printf("sizeof WOLFSSL_CTX = %lu\n", (unsigned long)sizeof(WOLFSSL_CTX));
  1599. #endif
  1600. return sizeof(WOLFSSL);
  1601. }
  1602. int wolfSSL_CTX_GetObjectSize(void)
  1603. {
  1604. return sizeof(WOLFSSL_CTX);
  1605. }
  1606. int wolfSSL_METHOD_GetObjectSize(void)
  1607. {
  1608. return sizeof(WOLFSSL_METHOD);
  1609. }
  1610. #endif
  1611. #ifdef WOLFSSL_STATIC_MEMORY
  1612. int wolfSSL_CTX_load_static_memory(WOLFSSL_CTX** ctx, wolfSSL_method_func method,
  1613. unsigned char* buf, unsigned int sz,
  1614. int flag, int maxSz)
  1615. {
  1616. WOLFSSL_HEAP* heap;
  1617. WOLFSSL_HEAP_HINT* hint;
  1618. word32 idx = 0;
  1619. if (ctx == NULL || buf == NULL) {
  1620. return BAD_FUNC_ARG;
  1621. }
  1622. if (*ctx == NULL && method == NULL) {
  1623. return BAD_FUNC_ARG;
  1624. }
  1625. if (*ctx == NULL || (*ctx)->heap == NULL) {
  1626. if (sizeof(WOLFSSL_HEAP) + sizeof(WOLFSSL_HEAP_HINT) > sz - idx) {
  1627. return BUFFER_E; /* not enough memory for structures */
  1628. }
  1629. heap = (WOLFSSL_HEAP*)buf;
  1630. idx += sizeof(WOLFSSL_HEAP);
  1631. if (wolfSSL_init_memory_heap(heap) != 0) {
  1632. return WOLFSSL_FAILURE;
  1633. }
  1634. hint = (WOLFSSL_HEAP_HINT*)(buf + idx);
  1635. idx += sizeof(WOLFSSL_HEAP_HINT);
  1636. XMEMSET(hint, 0, sizeof(WOLFSSL_HEAP_HINT));
  1637. hint->memory = heap;
  1638. if (*ctx && (*ctx)->heap == NULL) {
  1639. (*ctx)->heap = (void*)hint;
  1640. }
  1641. }
  1642. else {
  1643. #ifdef WOLFSSL_HEAP_TEST
  1644. /* do not load in memory if test has been set */
  1645. if ((*ctx)->heap == (void*)WOLFSSL_HEAP_TEST) {
  1646. return WOLFSSL_SUCCESS;
  1647. }
  1648. #endif
  1649. hint = (WOLFSSL_HEAP_HINT*)((*ctx)->heap);
  1650. heap = hint->memory;
  1651. }
  1652. if (wolfSSL_load_static_memory(buf + idx, sz - idx, flag, heap) != 1) {
  1653. WOLFSSL_MSG("Error partitioning memory");
  1654. return WOLFSSL_FAILURE;
  1655. }
  1656. /* create ctx if needed */
  1657. if (*ctx == NULL) {
  1658. *ctx = wolfSSL_CTX_new_ex(method(hint), hint);
  1659. if (*ctx == NULL) {
  1660. WOLFSSL_MSG("Error creating ctx");
  1661. return WOLFSSL_FAILURE;
  1662. }
  1663. }
  1664. /* determine what max applies too */
  1665. if (flag & WOLFMEM_IO_POOL || flag & WOLFMEM_IO_POOL_FIXED) {
  1666. heap->maxIO = maxSz;
  1667. }
  1668. else { /* general memory used in handshakes */
  1669. heap->maxHa = maxSz;
  1670. }
  1671. heap->flag |= flag;
  1672. (void)maxSz;
  1673. (void)method;
  1674. return WOLFSSL_SUCCESS;
  1675. }
  1676. int wolfSSL_is_static_memory(WOLFSSL* ssl, WOLFSSL_MEM_CONN_STATS* mem_stats)
  1677. {
  1678. if (ssl == NULL) {
  1679. return BAD_FUNC_ARG;
  1680. }
  1681. WOLFSSL_ENTER("wolfSSL_is_static_memory");
  1682. /* fill out statistics if wanted and WOLFMEM_TRACK_STATS flag */
  1683. if (mem_stats != NULL && ssl->heap != NULL) {
  1684. WOLFSSL_HEAP_HINT* hint = ((WOLFSSL_HEAP_HINT*)(ssl->heap));
  1685. WOLFSSL_HEAP* heap = hint->memory;
  1686. if (heap->flag & WOLFMEM_TRACK_STATS && hint->stats != NULL) {
  1687. XMEMCPY(mem_stats, hint->stats, sizeof(WOLFSSL_MEM_CONN_STATS));
  1688. }
  1689. }
  1690. return (ssl->heap) ? 1 : 0;
  1691. }
  1692. int wolfSSL_CTX_is_static_memory(WOLFSSL_CTX* ctx, WOLFSSL_MEM_STATS* mem_stats)
  1693. {
  1694. if (ctx == NULL) {
  1695. return BAD_FUNC_ARG;
  1696. }
  1697. WOLFSSL_ENTER("wolfSSL_CTX_is_static_memory");
  1698. /* fill out statistics if wanted */
  1699. if (mem_stats != NULL && ctx->heap != NULL) {
  1700. WOLFSSL_HEAP* heap = ((WOLFSSL_HEAP_HINT*)(ctx->heap))->memory;
  1701. if (wolfSSL_GetMemStats(heap, mem_stats) != 1) {
  1702. return MEMORY_E;
  1703. }
  1704. }
  1705. return (ctx->heap) ? 1 : 0;
  1706. }
  1707. #endif /* WOLFSSL_STATIC_MEMORY */
  1708. /* return max record layer size plaintext input size */
  1709. int wolfSSL_GetMaxOutputSize(WOLFSSL* ssl)
  1710. {
  1711. WOLFSSL_ENTER("wolfSSL_GetMaxOutputSize");
  1712. if (ssl == NULL)
  1713. return BAD_FUNC_ARG;
  1714. if (ssl->options.handShakeState != HANDSHAKE_DONE) {
  1715. WOLFSSL_MSG("Handshake not complete yet");
  1716. return BAD_FUNC_ARG;
  1717. }
  1718. return wolfSSL_GetMaxFragSize(ssl, OUTPUT_RECORD_SIZE);
  1719. }
  1720. /* return record layer size of plaintext input size */
  1721. int wolfSSL_GetOutputSize(WOLFSSL* ssl, int inSz)
  1722. {
  1723. int maxSize;
  1724. WOLFSSL_ENTER("wolfSSL_GetOutputSize");
  1725. if (inSz < 0)
  1726. return BAD_FUNC_ARG;
  1727. maxSize = wolfSSL_GetMaxOutputSize(ssl);
  1728. if (maxSize < 0)
  1729. return maxSize; /* error */
  1730. if (inSz > maxSize)
  1731. return INPUT_SIZE_E;
  1732. return BuildMessage(ssl, NULL, 0, NULL, inSz, application_data, 0, 1, 0, CUR_ORDER);
  1733. }
  1734. #ifdef HAVE_ECC
  1735. int wolfSSL_CTX_SetMinEccKey_Sz(WOLFSSL_CTX* ctx, short keySz)
  1736. {
  1737. if (ctx == NULL || keySz < 0 || keySz % 8 != 0) {
  1738. WOLFSSL_MSG("Key size must be divisible by 8 or ctx was null");
  1739. return BAD_FUNC_ARG;
  1740. }
  1741. ctx->minEccKeySz = keySz / 8;
  1742. #ifndef NO_CERTS
  1743. ctx->cm->minEccKeySz = keySz / 8;
  1744. #endif
  1745. return WOLFSSL_SUCCESS;
  1746. }
  1747. int wolfSSL_SetMinEccKey_Sz(WOLFSSL* ssl, short keySz)
  1748. {
  1749. if (ssl == NULL || keySz < 0 || keySz % 8 != 0) {
  1750. WOLFSSL_MSG("Key size must be divisible by 8 or ssl was null");
  1751. return BAD_FUNC_ARG;
  1752. }
  1753. ssl->options.minEccKeySz = keySz / 8;
  1754. return WOLFSSL_SUCCESS;
  1755. }
  1756. #endif /* HAVE_ECC */
  1757. #ifndef NO_RSA
  1758. int wolfSSL_CTX_SetMinRsaKey_Sz(WOLFSSL_CTX* ctx, short keySz)
  1759. {
  1760. if (ctx == NULL || keySz < 0 || keySz % 8 != 0) {
  1761. WOLFSSL_MSG("Key size must be divisible by 8 or ctx was null");
  1762. return BAD_FUNC_ARG;
  1763. }
  1764. ctx->minRsaKeySz = keySz / 8;
  1765. ctx->cm->minRsaKeySz = keySz / 8;
  1766. return WOLFSSL_SUCCESS;
  1767. }
  1768. int wolfSSL_SetMinRsaKey_Sz(WOLFSSL* ssl, short keySz)
  1769. {
  1770. if (ssl == NULL || keySz < 0 || keySz % 8 != 0) {
  1771. WOLFSSL_MSG("Key size must be divisible by 8 or ssl was null");
  1772. return BAD_FUNC_ARG;
  1773. }
  1774. ssl->options.minRsaKeySz = keySz / 8;
  1775. return WOLFSSL_SUCCESS;
  1776. }
  1777. #endif /* !NO_RSA */
  1778. #ifndef NO_DH
  1779. /* server Diffie-Hellman parameters, WOLFSSL_SUCCESS on ok */
  1780. int wolfSSL_SetTmpDH(WOLFSSL* ssl, const unsigned char* p, int pSz,
  1781. const unsigned char* g, int gSz)
  1782. {
  1783. WOLFSSL_ENTER("wolfSSL_SetTmpDH");
  1784. if (ssl == NULL || p == NULL || g == NULL)
  1785. return BAD_FUNC_ARG;
  1786. if ((word16)pSz < ssl->options.minDhKeySz)
  1787. return DH_KEY_SIZE_E;
  1788. if ((word16)pSz > ssl->options.maxDhKeySz)
  1789. return DH_KEY_SIZE_E;
  1790. /* this function is for server only */
  1791. if (ssl->options.side == WOLFSSL_CLIENT_END)
  1792. return SIDE_ERROR;
  1793. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
  1794. !defined(HAVE_SELFTEST)
  1795. ssl->options.dhKeyTested = 0;
  1796. ssl->options.dhDoKeyTest = 1;
  1797. #endif
  1798. if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) {
  1799. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  1800. ssl->buffers.serverDH_P.buffer = NULL;
  1801. }
  1802. if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) {
  1803. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  1804. ssl->buffers.serverDH_G.buffer = NULL;
  1805. }
  1806. ssl->buffers.weOwnDH = 1; /* SSL owns now */
  1807. ssl->buffers.serverDH_P.buffer = (byte*)XMALLOC(pSz, ssl->heap,
  1808. DYNAMIC_TYPE_PUBLIC_KEY);
  1809. if (ssl->buffers.serverDH_P.buffer == NULL)
  1810. return MEMORY_E;
  1811. ssl->buffers.serverDH_G.buffer = (byte*)XMALLOC(gSz, ssl->heap,
  1812. DYNAMIC_TYPE_PUBLIC_KEY);
  1813. if (ssl->buffers.serverDH_G.buffer == NULL) {
  1814. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  1815. ssl->buffers.serverDH_P.buffer = NULL;
  1816. return MEMORY_E;
  1817. }
  1818. ssl->buffers.serverDH_P.length = pSz;
  1819. ssl->buffers.serverDH_G.length = gSz;
  1820. XMEMCPY(ssl->buffers.serverDH_P.buffer, p, pSz);
  1821. XMEMCPY(ssl->buffers.serverDH_G.buffer, g, gSz);
  1822. ssl->options.haveDH = 1;
  1823. if (ssl->options.side != WOLFSSL_NEITHER_END) {
  1824. word16 havePSK;
  1825. word16 haveRSA;
  1826. int keySz = 0;
  1827. #ifndef NO_PSK
  1828. havePSK = ssl->options.havePSK;
  1829. #else
  1830. havePSK = 0;
  1831. #endif
  1832. #ifdef NO_RSA
  1833. haveRSA = 0;
  1834. #else
  1835. haveRSA = 1;
  1836. #endif
  1837. #ifndef NO_CERTS
  1838. keySz = ssl->buffers.keySz;
  1839. #endif
  1840. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
  1841. ssl->options.haveDH, ssl->options.haveECDSAsig,
  1842. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  1843. ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
  1844. ssl->options.haveAnon, TRUE, ssl->options.side);
  1845. }
  1846. WOLFSSL_LEAVE("wolfSSL_SetTmpDH", 0);
  1847. return WOLFSSL_SUCCESS;
  1848. }
  1849. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
  1850. !defined(HAVE_SELFTEST)
  1851. /* Enables or disables the session's DH key prime test. */
  1852. int wolfSSL_SetEnableDhKeyTest(WOLFSSL* ssl, int enable)
  1853. {
  1854. WOLFSSL_ENTER("wolfSSL_SetEnableDhKeyTest");
  1855. if (ssl == NULL)
  1856. return BAD_FUNC_ARG;
  1857. if (!enable)
  1858. ssl->options.dhDoKeyTest = 0;
  1859. else
  1860. ssl->options.dhDoKeyTest = 1;
  1861. WOLFSSL_LEAVE("wolfSSL_SetEnableDhKeyTest", WOLFSSL_SUCCESS);
  1862. return WOLFSSL_SUCCESS;
  1863. }
  1864. #endif
  1865. /* server ctx Diffie-Hellman parameters, WOLFSSL_SUCCESS on ok */
  1866. int wolfSSL_CTX_SetTmpDH(WOLFSSL_CTX* ctx, const unsigned char* p, int pSz,
  1867. const unsigned char* g, int gSz)
  1868. {
  1869. WOLFSSL_ENTER("wolfSSL_CTX_SetTmpDH");
  1870. if (ctx == NULL || p == NULL || g == NULL) return BAD_FUNC_ARG;
  1871. if ((word16)pSz < ctx->minDhKeySz)
  1872. return DH_KEY_SIZE_E;
  1873. if ((word16)pSz > ctx->maxDhKeySz)
  1874. return DH_KEY_SIZE_E;
  1875. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
  1876. !defined(HAVE_SELFTEST)
  1877. {
  1878. WC_RNG rng;
  1879. int error, freeKey = 0;
  1880. #ifdef WOLFSSL_SMALL_STACK
  1881. DhKey *checkKey = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH);
  1882. if (checkKey == NULL)
  1883. return MEMORY_E;
  1884. #else
  1885. DhKey checkKey[1];
  1886. #endif
  1887. error = wc_InitRng(&rng);
  1888. if (!error)
  1889. error = wc_InitDhKey(checkKey);
  1890. if (!error) {
  1891. freeKey = 1;
  1892. error = wc_DhSetCheckKey(checkKey,
  1893. p, pSz, g, gSz, NULL, 0, 0, &rng);
  1894. }
  1895. if (freeKey)
  1896. wc_FreeDhKey(checkKey);
  1897. #ifdef WOLFSSL_SMALL_STACK
  1898. XFREE(checkKey, NULL, DYNAMIC_TYPE_DH);
  1899. #endif
  1900. wc_FreeRng(&rng);
  1901. if (error)
  1902. return error;
  1903. ctx->dhKeyTested = 1;
  1904. }
  1905. #endif
  1906. XFREE(ctx->serverDH_P.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  1907. ctx->serverDH_P.buffer = NULL;
  1908. XFREE(ctx->serverDH_G.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  1909. ctx->serverDH_G.buffer = NULL;
  1910. ctx->serverDH_P.buffer = (byte*)XMALLOC(pSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  1911. if (ctx->serverDH_P.buffer == NULL)
  1912. return MEMORY_E;
  1913. ctx->serverDH_G.buffer = (byte*)XMALLOC(gSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  1914. if (ctx->serverDH_G.buffer == NULL) {
  1915. XFREE(ctx->serverDH_P.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  1916. ctx->serverDH_P.buffer = NULL;
  1917. return MEMORY_E;
  1918. }
  1919. ctx->serverDH_P.length = pSz;
  1920. ctx->serverDH_G.length = gSz;
  1921. XMEMCPY(ctx->serverDH_P.buffer, p, pSz);
  1922. XMEMCPY(ctx->serverDH_G.buffer, g, gSz);
  1923. ctx->haveDH = 1;
  1924. WOLFSSL_LEAVE("wolfSSL_CTX_SetTmpDH", 0);
  1925. return WOLFSSL_SUCCESS;
  1926. }
  1927. int wolfSSL_CTX_SetMinDhKey_Sz(WOLFSSL_CTX* ctx, word16 keySz_bits)
  1928. {
  1929. if (ctx == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
  1930. return BAD_FUNC_ARG;
  1931. ctx->minDhKeySz = keySz_bits / 8;
  1932. return WOLFSSL_SUCCESS;
  1933. }
  1934. int wolfSSL_SetMinDhKey_Sz(WOLFSSL* ssl, word16 keySz_bits)
  1935. {
  1936. if (ssl == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
  1937. return BAD_FUNC_ARG;
  1938. ssl->options.minDhKeySz = keySz_bits / 8;
  1939. return WOLFSSL_SUCCESS;
  1940. }
  1941. int wolfSSL_CTX_SetMaxDhKey_Sz(WOLFSSL_CTX* ctx, word16 keySz_bits)
  1942. {
  1943. if (ctx == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
  1944. return BAD_FUNC_ARG;
  1945. ctx->maxDhKeySz = keySz_bits / 8;
  1946. return WOLFSSL_SUCCESS;
  1947. }
  1948. int wolfSSL_SetMaxDhKey_Sz(WOLFSSL* ssl, word16 keySz_bits)
  1949. {
  1950. if (ssl == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
  1951. return BAD_FUNC_ARG;
  1952. ssl->options.maxDhKeySz = keySz_bits / 8;
  1953. return WOLFSSL_SUCCESS;
  1954. }
  1955. int wolfSSL_GetDhKey_Sz(WOLFSSL* ssl)
  1956. {
  1957. if (ssl == NULL)
  1958. return BAD_FUNC_ARG;
  1959. return (ssl->options.dhKeySz * 8);
  1960. }
  1961. #endif /* !NO_DH */
  1962. WOLFSSL_ABI
  1963. int wolfSSL_write(WOLFSSL* ssl, const void* data, int sz)
  1964. {
  1965. int ret;
  1966. WOLFSSL_ENTER("SSL_write()");
  1967. if (ssl == NULL || data == NULL || sz < 0)
  1968. return BAD_FUNC_ARG;
  1969. #ifdef WOLFSSL_QUIC
  1970. if (WOLFSSL_IS_QUIC(ssl)) {
  1971. WOLFSSL_MSG("SSL_write() on QUIC not allowed");
  1972. return BAD_FUNC_ARG;
  1973. }
  1974. #endif
  1975. #ifdef WOLFSSL_EARLY_DATA
  1976. if (ssl->earlyData != no_early_data && (ret = wolfSSL_negotiate(ssl)) < 0) {
  1977. ssl->error = ret;
  1978. return WOLFSSL_FATAL_ERROR;
  1979. }
  1980. ssl->earlyData = no_early_data;
  1981. #endif
  1982. #ifdef HAVE_WRITE_DUP
  1983. { /* local variable scope */
  1984. int dupErr = 0; /* local copy */
  1985. ret = 0;
  1986. if (ssl->dupWrite && ssl->dupSide == READ_DUP_SIDE) {
  1987. WOLFSSL_MSG("Read dup side cannot write");
  1988. return WRITE_DUP_WRITE_E;
  1989. }
  1990. if (ssl->dupWrite) {
  1991. if (wc_LockMutex(&ssl->dupWrite->dupMutex) != 0) {
  1992. return BAD_MUTEX_E;
  1993. }
  1994. dupErr = ssl->dupWrite->dupErr;
  1995. ret = wc_UnLockMutex(&ssl->dupWrite->dupMutex);
  1996. }
  1997. if (ret != 0) {
  1998. ssl->error = ret; /* high priority fatal error */
  1999. return WOLFSSL_FATAL_ERROR;
  2000. }
  2001. if (dupErr != 0) {
  2002. WOLFSSL_MSG("Write dup error from other side");
  2003. ssl->error = dupErr;
  2004. return WOLFSSL_FATAL_ERROR;
  2005. }
  2006. }
  2007. #endif
  2008. #ifdef HAVE_ERRNO_H
  2009. errno = 0;
  2010. #endif
  2011. #ifdef OPENSSL_EXTRA
  2012. if (ssl->CBIS != NULL) {
  2013. ssl->CBIS(ssl, SSL_CB_WRITE, WOLFSSL_SUCCESS);
  2014. ssl->cbmode = SSL_CB_WRITE;
  2015. }
  2016. #endif
  2017. ret = SendData(ssl, data, sz);
  2018. WOLFSSL_LEAVE("SSL_write()", ret);
  2019. if (ret < 0)
  2020. return WOLFSSL_FATAL_ERROR;
  2021. else
  2022. return ret;
  2023. }
  2024. static int wolfSSL_read_internal(WOLFSSL* ssl, void* data, int sz, int peek)
  2025. {
  2026. int ret;
  2027. WOLFSSL_ENTER("wolfSSL_read_internal()");
  2028. if (ssl == NULL || data == NULL || sz < 0)
  2029. return BAD_FUNC_ARG;
  2030. #ifdef WOLFSSL_QUIC
  2031. if (WOLFSSL_IS_QUIC(ssl)) {
  2032. WOLFSSL_MSG("SSL_read() on QUIC not allowed");
  2033. return BAD_FUNC_ARG;
  2034. }
  2035. #endif
  2036. #if defined(WOLFSSL_ERROR_CODE_OPENSSL) && defined(OPENSSL_EXTRA)
  2037. /* This additional logic is meant to simulate following openSSL behavior:
  2038. * After bidirectional SSL_shutdown complete, SSL_read returns 0 and
  2039. * SSL_get_error_code returns SSL_ERROR_ZERO_RETURN.
  2040. * This behavior is used to know the disconnect of the underlying
  2041. * transport layer.
  2042. *
  2043. * In this logic, CBIORecv is called with a read size of 0 to check the
  2044. * transport layer status. It also returns WOLFSSL_FAILURE so that
  2045. * SSL_read does not return a positive number on failure.
  2046. */
  2047. /* make sure bidirectional TLS shutdown completes */
  2048. if (ssl->error == WOLFSSL_ERROR_SYSCALL) {
  2049. /* ask the underlying transport the connection is closed */
  2050. if (ssl->CBIORecv(ssl, (char*)data, 0, ssl->IOCB_ReadCtx) ==
  2051. WOLFSSL_CBIO_ERR_CONN_CLOSE) {
  2052. ssl->options.isClosed = 1;
  2053. ssl->error = WOLFSSL_ERROR_ZERO_RETURN;
  2054. }
  2055. return WOLFSSL_FAILURE;
  2056. }
  2057. #endif
  2058. #ifdef HAVE_WRITE_DUP
  2059. if (ssl->dupWrite && ssl->dupSide == WRITE_DUP_SIDE) {
  2060. WOLFSSL_MSG("Write dup side cannot read");
  2061. return WRITE_DUP_READ_E;
  2062. }
  2063. #endif
  2064. #ifdef HAVE_ERRNO_H
  2065. errno = 0;
  2066. #endif
  2067. #ifdef WOLFSSL_DTLS
  2068. if (ssl->options.dtls) {
  2069. ssl->dtls_expected_rx = max(sz + DTLS_MTU_ADDITIONAL_READ_BUFFER,
  2070. MAX_MTU);
  2071. #ifdef WOLFSSL_SCTP
  2072. if (ssl->options.dtlsSctp)
  2073. #endif
  2074. #if defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU)
  2075. /* Add some bytes so that we can operate with slight difference
  2076. * in set MTU size on each peer */
  2077. ssl->dtls_expected_rx = max(ssl->dtls_expected_rx,
  2078. ssl->dtlsMtuSz + (word32)DTLS_MTU_ADDITIONAL_READ_BUFFER);
  2079. #endif
  2080. }
  2081. #endif
  2082. ret = ReceiveData(ssl, (byte*)data, sz, peek);
  2083. #ifdef HAVE_WRITE_DUP
  2084. if (ssl->dupWrite) {
  2085. if (ssl->error != 0 && ssl->error != WANT_READ
  2086. #ifdef WOLFSSL_ASYNC_CRYPT
  2087. && ssl->error != WC_PENDING_E
  2088. #endif
  2089. ) {
  2090. int notifyErr;
  2091. WOLFSSL_MSG("Notifying write side of fatal read error");
  2092. notifyErr = NotifyWriteSide(ssl, ssl->error);
  2093. if (notifyErr < 0) {
  2094. ret = ssl->error = notifyErr;
  2095. }
  2096. }
  2097. }
  2098. #endif
  2099. WOLFSSL_LEAVE("wolfSSL_read_internal()", ret);
  2100. if (ret < 0)
  2101. return WOLFSSL_FATAL_ERROR;
  2102. else
  2103. return ret;
  2104. }
  2105. int wolfSSL_peek(WOLFSSL* ssl, void* data, int sz)
  2106. {
  2107. WOLFSSL_ENTER("wolfSSL_peek()");
  2108. return wolfSSL_read_internal(ssl, data, sz, TRUE);
  2109. }
  2110. WOLFSSL_ABI
  2111. int wolfSSL_read(WOLFSSL* ssl, void* data, int sz)
  2112. {
  2113. WOLFSSL_ENTER("wolfSSL_read()");
  2114. #ifdef OPENSSL_EXTRA
  2115. if (ssl == NULL) {
  2116. return BAD_FUNC_ARG;
  2117. }
  2118. if (ssl->CBIS != NULL) {
  2119. ssl->CBIS(ssl, SSL_CB_READ, WOLFSSL_SUCCESS);
  2120. ssl->cbmode = SSL_CB_READ;
  2121. }
  2122. #endif
  2123. return wolfSSL_read_internal(ssl, data, sz, FALSE);
  2124. }
  2125. #ifdef WOLFSSL_MULTICAST
  2126. int wolfSSL_mcast_read(WOLFSSL* ssl, word16* id, void* data, int sz)
  2127. {
  2128. int ret = 0;
  2129. WOLFSSL_ENTER("wolfSSL_mcast_read()");
  2130. if (ssl == NULL)
  2131. return BAD_FUNC_ARG;
  2132. ret = wolfSSL_read_internal(ssl, data, sz, FALSE);
  2133. if (ssl->options.dtls && ssl->options.haveMcast && id != NULL)
  2134. *id = ssl->keys.curPeerId;
  2135. return ret;
  2136. }
  2137. #endif /* WOLFSSL_MULTICAST */
  2138. /* helpers to set the device id, WOLFSSL_SUCCESS on ok */
  2139. WOLFSSL_ABI
  2140. int wolfSSL_SetDevId(WOLFSSL* ssl, int devId)
  2141. {
  2142. if (ssl == NULL)
  2143. return BAD_FUNC_ARG;
  2144. ssl->devId = devId;
  2145. return WOLFSSL_SUCCESS;
  2146. }
  2147. WOLFSSL_ABI
  2148. int wolfSSL_CTX_SetDevId(WOLFSSL_CTX* ctx, int devId)
  2149. {
  2150. if (ctx == NULL)
  2151. return BAD_FUNC_ARG;
  2152. ctx->devId = devId;
  2153. return WOLFSSL_SUCCESS;
  2154. }
  2155. /* helpers to get device id and heap */
  2156. WOLFSSL_ABI
  2157. int wolfSSL_CTX_GetDevId(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
  2158. {
  2159. int devId = INVALID_DEVID;
  2160. if (ssl != NULL)
  2161. devId = ssl->devId;
  2162. if (ctx != NULL && devId == INVALID_DEVID)
  2163. devId = ctx->devId;
  2164. return devId;
  2165. }
  2166. void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
  2167. {
  2168. void* heap = NULL;
  2169. if (ctx != NULL)
  2170. heap = ctx->heap;
  2171. else if (ssl != NULL)
  2172. heap = ssl->heap;
  2173. return heap;
  2174. }
  2175. #ifdef HAVE_SNI
  2176. WOLFSSL_ABI
  2177. int wolfSSL_UseSNI(WOLFSSL* ssl, byte type, const void* data, word16 size)
  2178. {
  2179. if (ssl == NULL)
  2180. return BAD_FUNC_ARG;
  2181. return TLSX_UseSNI(&ssl->extensions, type, data, size, ssl->heap);
  2182. }
  2183. WOLFSSL_ABI
  2184. int wolfSSL_CTX_UseSNI(WOLFSSL_CTX* ctx, byte type, const void* data,
  2185. word16 size)
  2186. {
  2187. if (ctx == NULL)
  2188. return BAD_FUNC_ARG;
  2189. return TLSX_UseSNI(&ctx->extensions, type, data, size, ctx->heap);
  2190. }
  2191. #ifndef NO_WOLFSSL_SERVER
  2192. void wolfSSL_SNI_SetOptions(WOLFSSL* ssl, byte type, byte options)
  2193. {
  2194. if (ssl && ssl->extensions)
  2195. TLSX_SNI_SetOptions(ssl->extensions, type, options);
  2196. }
  2197. void wolfSSL_CTX_SNI_SetOptions(WOLFSSL_CTX* ctx, byte type, byte options)
  2198. {
  2199. if (ctx && ctx->extensions)
  2200. TLSX_SNI_SetOptions(ctx->extensions, type, options);
  2201. }
  2202. byte wolfSSL_SNI_Status(WOLFSSL* ssl, byte type)
  2203. {
  2204. return TLSX_SNI_Status(ssl ? ssl->extensions : NULL, type);
  2205. }
  2206. word16 wolfSSL_SNI_GetRequest(WOLFSSL* ssl, byte type, void** data)
  2207. {
  2208. if (data)
  2209. *data = NULL;
  2210. if (ssl && ssl->extensions)
  2211. return TLSX_SNI_GetRequest(ssl->extensions, type, data);
  2212. return 0;
  2213. }
  2214. int wolfSSL_SNI_GetFromBuffer(const byte* clientHello, word32 helloSz,
  2215. byte type, byte* sni, word32* inOutSz)
  2216. {
  2217. if (clientHello && helloSz > 0 && sni && inOutSz && *inOutSz > 0)
  2218. return TLSX_SNI_GetFromBuffer(clientHello, helloSz, type, sni, inOutSz);
  2219. return BAD_FUNC_ARG;
  2220. }
  2221. #endif /* NO_WOLFSSL_SERVER */
  2222. #endif /* HAVE_SNI */
  2223. #ifdef HAVE_TRUSTED_CA
  2224. WOLFSSL_API int wolfSSL_UseTrustedCA(WOLFSSL* ssl, byte type,
  2225. const byte* certId, word32 certIdSz)
  2226. {
  2227. if (ssl == NULL)
  2228. return BAD_FUNC_ARG;
  2229. if (type == WOLFSSL_TRUSTED_CA_PRE_AGREED) {
  2230. if (certId != NULL || certIdSz != 0)
  2231. return BAD_FUNC_ARG;
  2232. }
  2233. else if (type == WOLFSSL_TRUSTED_CA_X509_NAME) {
  2234. if (certId == NULL || certIdSz == 0)
  2235. return BAD_FUNC_ARG;
  2236. }
  2237. #ifndef NO_SHA
  2238. else if (type == WOLFSSL_TRUSTED_CA_KEY_SHA1 ||
  2239. type == WOLFSSL_TRUSTED_CA_CERT_SHA1) {
  2240. if (certId == NULL || certIdSz != WC_SHA_DIGEST_SIZE)
  2241. return BAD_FUNC_ARG;
  2242. }
  2243. #endif
  2244. else
  2245. return BAD_FUNC_ARG;
  2246. return TLSX_UseTrustedCA(&ssl->extensions,
  2247. type, certId, certIdSz, ssl->heap);
  2248. }
  2249. #endif /* HAVE_TRUSTED_CA */
  2250. #ifdef HAVE_MAX_FRAGMENT
  2251. #ifndef NO_WOLFSSL_CLIENT
  2252. int wolfSSL_UseMaxFragment(WOLFSSL* ssl, byte mfl)
  2253. {
  2254. if (ssl == NULL)
  2255. return BAD_FUNC_ARG;
  2256. #ifdef WOLFSSL_ALLOW_MAX_FRAGMENT_ADJUST
  2257. /* The following is a non-standard way to reconfigure the max packet size
  2258. post-handshake for wolfSSL_write/wolfSSL_read */
  2259. if (ssl->options.handShakeState == HANDSHAKE_DONE) {
  2260. switch (mfl) {
  2261. case WOLFSSL_MFL_2_8 : ssl->max_fragment = 256; break;
  2262. case WOLFSSL_MFL_2_9 : ssl->max_fragment = 512; break;
  2263. case WOLFSSL_MFL_2_10: ssl->max_fragment = 1024; break;
  2264. case WOLFSSL_MFL_2_11: ssl->max_fragment = 2048; break;
  2265. case WOLFSSL_MFL_2_12: ssl->max_fragment = 4096; break;
  2266. case WOLFSSL_MFL_2_13: ssl->max_fragment = 8192; break;
  2267. default: ssl->max_fragment = MAX_RECORD_SIZE; break;
  2268. }
  2269. return WOLFSSL_SUCCESS;
  2270. }
  2271. #endif /* WOLFSSL_MAX_FRAGMENT_ADJUST */
  2272. /* This call sets the max fragment TLS extension, which gets sent to server.
  2273. The server_hello response is what sets the `ssl->max_fragment` in
  2274. TLSX_MFL_Parse */
  2275. return TLSX_UseMaxFragment(&ssl->extensions, mfl, ssl->heap);
  2276. }
  2277. int wolfSSL_CTX_UseMaxFragment(WOLFSSL_CTX* ctx, byte mfl)
  2278. {
  2279. if (ctx == NULL)
  2280. return BAD_FUNC_ARG;
  2281. return TLSX_UseMaxFragment(&ctx->extensions, mfl, ctx->heap);
  2282. }
  2283. #endif /* NO_WOLFSSL_CLIENT */
  2284. #endif /* HAVE_MAX_FRAGMENT */
  2285. #ifdef HAVE_TRUNCATED_HMAC
  2286. #ifndef NO_WOLFSSL_CLIENT
  2287. int wolfSSL_UseTruncatedHMAC(WOLFSSL* ssl)
  2288. {
  2289. if (ssl == NULL)
  2290. return BAD_FUNC_ARG;
  2291. return TLSX_UseTruncatedHMAC(&ssl->extensions, ssl->heap);
  2292. }
  2293. int wolfSSL_CTX_UseTruncatedHMAC(WOLFSSL_CTX* ctx)
  2294. {
  2295. if (ctx == NULL)
  2296. return BAD_FUNC_ARG;
  2297. return TLSX_UseTruncatedHMAC(&ctx->extensions, ctx->heap);
  2298. }
  2299. #endif /* NO_WOLFSSL_CLIENT */
  2300. #endif /* HAVE_TRUNCATED_HMAC */
  2301. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  2302. int wolfSSL_UseOCSPStapling(WOLFSSL* ssl, byte status_type, byte options)
  2303. {
  2304. WOLFSSL_ENTER("wolfSSL_UseOCSPStapling");
  2305. if (ssl == NULL || ssl->options.side != WOLFSSL_CLIENT_END)
  2306. return BAD_FUNC_ARG;
  2307. return TLSX_UseCertificateStatusRequest(&ssl->extensions, status_type,
  2308. options, NULL, ssl->heap, ssl->devId);
  2309. }
  2310. int wolfSSL_CTX_UseOCSPStapling(WOLFSSL_CTX* ctx, byte status_type,
  2311. byte options)
  2312. {
  2313. WOLFSSL_ENTER("wolfSSL_CTX_UseOCSPStapling");
  2314. if (ctx == NULL || ctx->method->side != WOLFSSL_CLIENT_END)
  2315. return BAD_FUNC_ARG;
  2316. return TLSX_UseCertificateStatusRequest(&ctx->extensions, status_type,
  2317. options, NULL, ctx->heap, ctx->devId);
  2318. }
  2319. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
  2320. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  2321. int wolfSSL_UseOCSPStaplingV2(WOLFSSL* ssl, byte status_type, byte options)
  2322. {
  2323. if (ssl == NULL || ssl->options.side != WOLFSSL_CLIENT_END)
  2324. return BAD_FUNC_ARG;
  2325. return TLSX_UseCertificateStatusRequestV2(&ssl->extensions, status_type,
  2326. options, ssl->heap, ssl->devId);
  2327. }
  2328. int wolfSSL_CTX_UseOCSPStaplingV2(WOLFSSL_CTX* ctx, byte status_type,
  2329. byte options)
  2330. {
  2331. if (ctx == NULL || ctx->method->side != WOLFSSL_CLIENT_END)
  2332. return BAD_FUNC_ARG;
  2333. return TLSX_UseCertificateStatusRequestV2(&ctx->extensions, status_type,
  2334. options, ctx->heap, ctx->devId);
  2335. }
  2336. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  2337. /* Elliptic Curves */
  2338. #if defined(HAVE_SUPPORTED_CURVES)
  2339. static int isValidCurveGroup(word16 name)
  2340. {
  2341. switch (name) {
  2342. case WOLFSSL_ECC_SECP160K1:
  2343. case WOLFSSL_ECC_SECP160R1:
  2344. case WOLFSSL_ECC_SECP160R2:
  2345. case WOLFSSL_ECC_SECP192K1:
  2346. case WOLFSSL_ECC_SECP192R1:
  2347. case WOLFSSL_ECC_SECP224K1:
  2348. case WOLFSSL_ECC_SECP224R1:
  2349. case WOLFSSL_ECC_SECP256K1:
  2350. case WOLFSSL_ECC_SECP256R1:
  2351. case WOLFSSL_ECC_SECP384R1:
  2352. case WOLFSSL_ECC_SECP521R1:
  2353. case WOLFSSL_ECC_BRAINPOOLP256R1:
  2354. case WOLFSSL_ECC_BRAINPOOLP384R1:
  2355. case WOLFSSL_ECC_BRAINPOOLP512R1:
  2356. case WOLFSSL_ECC_X25519:
  2357. case WOLFSSL_ECC_X448:
  2358. case WOLFSSL_FFDHE_2048:
  2359. case WOLFSSL_FFDHE_3072:
  2360. case WOLFSSL_FFDHE_4096:
  2361. case WOLFSSL_FFDHE_6144:
  2362. case WOLFSSL_FFDHE_8192:
  2363. #ifdef HAVE_PQC
  2364. case WOLFSSL_KYBER_LEVEL1:
  2365. case WOLFSSL_KYBER_LEVEL3:
  2366. case WOLFSSL_KYBER_LEVEL5:
  2367. case WOLFSSL_NTRU_HPS_LEVEL1:
  2368. case WOLFSSL_NTRU_HPS_LEVEL3:
  2369. case WOLFSSL_NTRU_HPS_LEVEL5:
  2370. case WOLFSSL_NTRU_HRSS_LEVEL3:
  2371. case WOLFSSL_SABER_LEVEL1:
  2372. case WOLFSSL_SABER_LEVEL3:
  2373. case WOLFSSL_SABER_LEVEL5:
  2374. case WOLFSSL_KYBER_90S_LEVEL1:
  2375. case WOLFSSL_KYBER_90S_LEVEL3:
  2376. case WOLFSSL_KYBER_90S_LEVEL5:
  2377. case WOLFSSL_P256_NTRU_HPS_LEVEL1:
  2378. case WOLFSSL_P384_NTRU_HPS_LEVEL3:
  2379. case WOLFSSL_P521_NTRU_HPS_LEVEL5:
  2380. case WOLFSSL_P384_NTRU_HRSS_LEVEL3:
  2381. case WOLFSSL_P256_SABER_LEVEL1:
  2382. case WOLFSSL_P384_SABER_LEVEL3:
  2383. case WOLFSSL_P521_SABER_LEVEL5:
  2384. case WOLFSSL_P256_KYBER_LEVEL1:
  2385. case WOLFSSL_P384_KYBER_LEVEL3:
  2386. case WOLFSSL_P521_KYBER_LEVEL5:
  2387. case WOLFSSL_P256_KYBER_90S_LEVEL1:
  2388. case WOLFSSL_P384_KYBER_90S_LEVEL3:
  2389. case WOLFSSL_P521_KYBER_90S_LEVEL5:
  2390. #endif
  2391. return 1;
  2392. default:
  2393. return 0;
  2394. }
  2395. }
  2396. int wolfSSL_UseSupportedCurve(WOLFSSL* ssl, word16 name)
  2397. {
  2398. if (ssl == NULL || !isValidCurveGroup(name))
  2399. return BAD_FUNC_ARG;
  2400. ssl->options.userCurves = 1;
  2401. #if defined(NO_TLS)
  2402. return WOLFSSL_FAILURE;
  2403. #else
  2404. return TLSX_UseSupportedCurve(&ssl->extensions, name, ssl->heap);
  2405. #endif /* NO_TLS */
  2406. }
  2407. int wolfSSL_CTX_UseSupportedCurve(WOLFSSL_CTX* ctx, word16 name)
  2408. {
  2409. if (ctx == NULL || !isValidCurveGroup(name))
  2410. return BAD_FUNC_ARG;
  2411. ctx->userCurves = 1;
  2412. #if defined(NO_TLS)
  2413. return WOLFSSL_FAILURE;
  2414. #else
  2415. return TLSX_UseSupportedCurve(&ctx->extensions, name, ctx->heap);
  2416. #endif /* NO_TLS */
  2417. }
  2418. #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_TLS13)
  2419. int wolfSSL_CTX_set1_groups(WOLFSSL_CTX* ctx, int* groups,
  2420. int count)
  2421. {
  2422. int i;
  2423. int _groups[WOLFSSL_MAX_GROUP_COUNT];
  2424. WOLFSSL_ENTER("wolfSSL_CTX_set1_groups");
  2425. if (count == 0) {
  2426. WOLFSSL_MSG("Group count is zero");
  2427. return WOLFSSL_FAILURE;
  2428. }
  2429. for (i = 0; i < count; i++) {
  2430. if (isValidCurveGroup((word16)groups[i])) {
  2431. _groups[i] = groups[i];
  2432. }
  2433. #ifdef HAVE_ECC
  2434. else {
  2435. /* groups may be populated with curve NIDs */
  2436. int oid = nid2oid(groups[i], oidCurveType);
  2437. int name = (int)GetCurveByOID(oid);
  2438. if (name == 0) {
  2439. WOLFSSL_MSG("Invalid group name");
  2440. return WOLFSSL_FAILURE;
  2441. }
  2442. _groups[i] = name;
  2443. }
  2444. #else
  2445. else {
  2446. WOLFSSL_MSG("Invalid group name");
  2447. return WOLFSSL_FAILURE;
  2448. }
  2449. #endif
  2450. }
  2451. return wolfSSL_CTX_set_groups(ctx, _groups, count) == WOLFSSL_SUCCESS ?
  2452. WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
  2453. }
  2454. int wolfSSL_set1_groups(WOLFSSL* ssl, int* groups, int count)
  2455. {
  2456. int i;
  2457. int _groups[WOLFSSL_MAX_GROUP_COUNT];
  2458. WOLFSSL_ENTER("wolfSSL_CTX_set1_groups");
  2459. if (count == 0) {
  2460. WOLFSSL_MSG("Group count is zero");
  2461. return WOLFSSL_FAILURE;
  2462. }
  2463. for (i = 0; i < count; i++) {
  2464. if (isValidCurveGroup((word16)groups[i])) {
  2465. _groups[i] = groups[i];
  2466. }
  2467. #ifdef HAVE_ECC
  2468. else {
  2469. /* groups may be populated with curve NIDs */
  2470. int oid = nid2oid(groups[i], oidCurveType);
  2471. int name = (int)GetCurveByOID(oid);
  2472. if (name == 0) {
  2473. WOLFSSL_MSG("Invalid group name");
  2474. return WOLFSSL_FAILURE;
  2475. }
  2476. _groups[i] = name;
  2477. }
  2478. #else
  2479. else {
  2480. WOLFSSL_MSG("Invalid group name");
  2481. return WOLFSSL_FAILURE;
  2482. }
  2483. #endif
  2484. }
  2485. return wolfSSL_set_groups(ssl, _groups, count) == WOLFSSL_SUCCESS ?
  2486. WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
  2487. }
  2488. #endif /* OPENSSL_EXTRA && WOLFSSL_TLS13 */
  2489. #endif /* HAVE_SUPPORTED_CURVES */
  2490. /* Application-Layer Protocol Negotiation */
  2491. #ifdef HAVE_ALPN
  2492. WOLFSSL_ABI
  2493. int wolfSSL_UseALPN(WOLFSSL* ssl, char *protocol_name_list,
  2494. word32 protocol_name_listSz, byte options)
  2495. {
  2496. char *list, *ptr, **token;
  2497. word16 len;
  2498. int idx = 0;
  2499. int ret = WOLFSSL_FAILURE;
  2500. WOLFSSL_ENTER("wolfSSL_UseALPN");
  2501. if (ssl == NULL || protocol_name_list == NULL)
  2502. return BAD_FUNC_ARG;
  2503. if (protocol_name_listSz > (WOLFSSL_MAX_ALPN_NUMBER *
  2504. WOLFSSL_MAX_ALPN_PROTO_NAME_LEN +
  2505. WOLFSSL_MAX_ALPN_NUMBER)) {
  2506. WOLFSSL_MSG("Invalid arguments, protocol name list too long");
  2507. return BAD_FUNC_ARG;
  2508. }
  2509. if (!(options & WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) &&
  2510. !(options & WOLFSSL_ALPN_FAILED_ON_MISMATCH)) {
  2511. WOLFSSL_MSG("Invalid arguments, options not supported");
  2512. return BAD_FUNC_ARG;
  2513. }
  2514. list = (char *)XMALLOC(protocol_name_listSz+1, ssl->heap,
  2515. DYNAMIC_TYPE_ALPN);
  2516. if (list == NULL) {
  2517. WOLFSSL_MSG("Memory failure");
  2518. return MEMORY_ERROR;
  2519. }
  2520. token = (char **)XMALLOC(sizeof(char *) * (WOLFSSL_MAX_ALPN_NUMBER+1), ssl->heap, DYNAMIC_TYPE_ALPN);
  2521. if (token == NULL) {
  2522. XFREE(list, ssl->heap, DYNAMIC_TYPE_ALPN);
  2523. WOLFSSL_MSG("Memory failure");
  2524. return MEMORY_ERROR;
  2525. }
  2526. XMEMSET(token, 0, sizeof(char *) * (WOLFSSL_MAX_ALPN_NUMBER+1));
  2527. XSTRNCPY(list, protocol_name_list, protocol_name_listSz);
  2528. list[protocol_name_listSz] = '\0';
  2529. /* read all protocol name from the list */
  2530. token[idx] = XSTRTOK(list, ",", &ptr);
  2531. while (idx < WOLFSSL_MAX_ALPN_NUMBER && token[idx] != NULL)
  2532. token[++idx] = XSTRTOK(NULL, ",", &ptr);
  2533. /* add protocol name list in the TLS extension in reverse order */
  2534. while ((idx--) > 0) {
  2535. len = (word16)XSTRLEN(token[idx]);
  2536. ret = TLSX_UseALPN(&ssl->extensions, token[idx], len, options,
  2537. ssl->heap);
  2538. if (ret != WOLFSSL_SUCCESS) {
  2539. WOLFSSL_MSG("TLSX_UseALPN failure");
  2540. break;
  2541. }
  2542. }
  2543. XFREE(token, ssl->heap, DYNAMIC_TYPE_ALPN);
  2544. XFREE(list, ssl->heap, DYNAMIC_TYPE_ALPN);
  2545. return ret;
  2546. }
  2547. int wolfSSL_ALPN_GetProtocol(WOLFSSL* ssl, char **protocol_name, word16 *size)
  2548. {
  2549. return TLSX_ALPN_GetRequest(ssl ? ssl->extensions : NULL,
  2550. (void **)protocol_name, size);
  2551. }
  2552. int wolfSSL_ALPN_GetPeerProtocol(WOLFSSL* ssl, char **list, word16 *listSz)
  2553. {
  2554. if (list == NULL || listSz == NULL)
  2555. return BAD_FUNC_ARG;
  2556. if (ssl->alpn_client_list == NULL)
  2557. return BUFFER_ERROR;
  2558. *listSz = (word16)XSTRLEN(ssl->alpn_client_list);
  2559. if (*listSz == 0)
  2560. return BUFFER_ERROR;
  2561. *list = (char *)XMALLOC((*listSz)+1, ssl->heap, DYNAMIC_TYPE_TLSX);
  2562. if (*list == NULL)
  2563. return MEMORY_ERROR;
  2564. XSTRNCPY(*list, ssl->alpn_client_list, (*listSz)+1);
  2565. (*list)[*listSz] = 0;
  2566. return WOLFSSL_SUCCESS;
  2567. }
  2568. /* used to free memory allocated by wolfSSL_ALPN_GetPeerProtocol */
  2569. int wolfSSL_ALPN_FreePeerProtocol(WOLFSSL* ssl, char **list)
  2570. {
  2571. if (ssl == NULL) {
  2572. return BAD_FUNC_ARG;
  2573. }
  2574. XFREE(*list, ssl->heap, DYNAMIC_TYPE_TLSX);
  2575. *list = NULL;
  2576. return WOLFSSL_SUCCESS;
  2577. }
  2578. #endif /* HAVE_ALPN */
  2579. /* Secure Renegotiation */
  2580. #ifdef HAVE_SERVER_RENEGOTIATION_INFO
  2581. /* user is forcing ability to use secure renegotiation, we discourage it */
  2582. int wolfSSL_UseSecureRenegotiation(WOLFSSL* ssl)
  2583. {
  2584. int ret = BAD_FUNC_ARG;
  2585. #if defined(NO_TLS)
  2586. (void)ssl;
  2587. #else
  2588. if (ssl)
  2589. ret = TLSX_UseSecureRenegotiation(&ssl->extensions, ssl->heap);
  2590. if (ret == WOLFSSL_SUCCESS) {
  2591. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_RENEGOTIATION_INFO);
  2592. if (extension)
  2593. ssl->secure_renegotiation = (SecureRenegotiation*)extension->data;
  2594. }
  2595. #endif /* !NO_TLS */
  2596. return ret;
  2597. }
  2598. int wolfSSL_CTX_UseSecureRenegotiation(WOLFSSL_CTX* ctx)
  2599. {
  2600. if (ctx == NULL)
  2601. return BAD_FUNC_ARG;
  2602. ctx->useSecureReneg = 1;
  2603. return WOLFSSL_SUCCESS;
  2604. }
  2605. /* do a secure renegotiation handshake, user forced, we discourage */
  2606. static int _Rehandshake(WOLFSSL* ssl)
  2607. {
  2608. int ret;
  2609. if (ssl == NULL)
  2610. return BAD_FUNC_ARG;
  2611. if (ssl->secure_renegotiation == NULL) {
  2612. WOLFSSL_MSG("Secure Renegotiation not forced on by user");
  2613. return SECURE_RENEGOTIATION_E;
  2614. }
  2615. if (ssl->secure_renegotiation->enabled == 0) {
  2616. WOLFSSL_MSG("Secure Renegotiation not enabled at extension level");
  2617. return SECURE_RENEGOTIATION_E;
  2618. }
  2619. /* If the client started the renegotiation, the server will already
  2620. * have processed the client's hello. */
  2621. if (ssl->options.side != WOLFSSL_SERVER_END ||
  2622. ssl->options.acceptState != ACCEPT_FIRST_REPLY_DONE) {
  2623. if (ssl->options.handShakeState != HANDSHAKE_DONE) {
  2624. if (!ssl->options.handShakeDone) {
  2625. WOLFSSL_MSG("Can't renegotiate until initial "
  2626. "handshake complete");
  2627. return SECURE_RENEGOTIATION_E;
  2628. }
  2629. else {
  2630. WOLFSSL_MSG("Renegotiation already started. "
  2631. "Moving it forward.");
  2632. ret = wolfSSL_negotiate(ssl);
  2633. if (ret == WOLFSSL_SUCCESS)
  2634. ssl->secure_rene_count++;
  2635. return ret;
  2636. }
  2637. }
  2638. #ifndef NO_FORCE_SCR_SAME_SUITE
  2639. /* force same suite */
  2640. if (ssl->suites) {
  2641. ssl->suites->suiteSz = SUITE_LEN;
  2642. ssl->suites->suites[0] = ssl->options.cipherSuite0;
  2643. ssl->suites->suites[1] = ssl->options.cipherSuite;
  2644. }
  2645. #endif
  2646. /* reset handshake states */
  2647. ssl->options.sendVerify = 0;
  2648. ssl->options.serverState = NULL_STATE;
  2649. ssl->options.clientState = NULL_STATE;
  2650. ssl->options.connectState = CONNECT_BEGIN;
  2651. ssl->options.acceptState = ACCEPT_BEGIN_RENEG;
  2652. ssl->options.handShakeState = NULL_STATE;
  2653. ssl->options.processReply = 0; /* TODO, move states in internal.h */
  2654. XMEMSET(&ssl->msgsReceived, 0, sizeof(ssl->msgsReceived));
  2655. ssl->secure_renegotiation->cache_status = SCR_CACHE_NEEDED;
  2656. #if !defined(NO_WOLFSSL_SERVER) && defined(HAVE_SECURE_RENEGOTIATION)
  2657. if (ssl->options.side == WOLFSSL_SERVER_END) {
  2658. ret = SendHelloRequest(ssl);
  2659. if (ret != 0) {
  2660. ssl->error = ret;
  2661. return WOLFSSL_FATAL_ERROR;
  2662. }
  2663. }
  2664. #endif /* !NO_WOLFSSL_SERVER && HAVE_SECURE_RENEGOTIATION */
  2665. ret = InitHandshakeHashes(ssl);
  2666. if (ret != 0) {
  2667. ssl->error = ret;
  2668. return WOLFSSL_FATAL_ERROR;
  2669. }
  2670. }
  2671. ret = wolfSSL_negotiate(ssl);
  2672. if (ret == WOLFSSL_SUCCESS)
  2673. ssl->secure_rene_count++;
  2674. return ret;
  2675. }
  2676. /* do a secure renegotiation handshake, user forced, we discourage */
  2677. int wolfSSL_Rehandshake(WOLFSSL* ssl)
  2678. {
  2679. int ret;
  2680. WOLFSSL_ENTER("wolfSSL_Rehandshake");
  2681. if (ssl == NULL)
  2682. return WOLFSSL_FAILURE;
  2683. #ifdef HAVE_SESSION_TICKET
  2684. ret = WOLFSSL_SUCCESS;
  2685. #endif
  2686. if (ssl->options.side == WOLFSSL_SERVER_END) {
  2687. /* Reset option to send certificate verify. */
  2688. ssl->options.sendVerify = 0;
  2689. }
  2690. else {
  2691. /* Reset resuming flag to do full secure handshake. */
  2692. ssl->options.resuming = 0;
  2693. #ifdef HAVE_SESSION_TICKET
  2694. /* Clearing the ticket. */
  2695. ret = wolfSSL_UseSessionTicket(ssl);
  2696. #endif
  2697. }
  2698. /* CLIENT/SERVER: Reset peer authentication for full secure handshake. */
  2699. ssl->options.peerAuthGood = 0;
  2700. #ifdef HAVE_SESSION_TICKET
  2701. if (ret == WOLFSSL_SUCCESS)
  2702. #endif
  2703. ret = _Rehandshake(ssl);
  2704. return ret;
  2705. }
  2706. #ifndef NO_WOLFSSL_CLIENT
  2707. /* do a secure resumption handshake, user forced, we discourage */
  2708. int wolfSSL_SecureResume(WOLFSSL* ssl)
  2709. {
  2710. WOLFSSL_ENTER("wolfSSL_SecureResume");
  2711. if (ssl == NULL)
  2712. return BAD_FUNC_ARG;
  2713. if (ssl->options.side == WOLFSSL_SERVER_END) {
  2714. ssl->error = SIDE_ERROR;
  2715. return WOLFSSL_FATAL_ERROR;
  2716. }
  2717. return _Rehandshake(ssl);
  2718. }
  2719. #endif /* NO_WOLFSSL_CLIENT */
  2720. long wolfSSL_SSL_get_secure_renegotiation_support(WOLFSSL* ssl)
  2721. {
  2722. WOLFSSL_ENTER("wolfSSL_SSL_get_secure_renegotiation_support");
  2723. if (!ssl || !ssl->secure_renegotiation)
  2724. return WOLFSSL_FAILURE;
  2725. return ssl->secure_renegotiation->enabled;
  2726. }
  2727. #endif /* HAVE_SECURE_RENEGOTIATION_INFO */
  2728. #if defined(HAVE_SESSION_TICKET)
  2729. /* Session Ticket */
  2730. #if !defined(NO_WOLFSSL_SERVER)
  2731. int wolfSSL_CTX_NoTicketTLSv12(WOLFSSL_CTX* ctx)
  2732. {
  2733. if (ctx == NULL)
  2734. return BAD_FUNC_ARG;
  2735. ctx->noTicketTls12 = 1;
  2736. return WOLFSSL_SUCCESS;
  2737. }
  2738. int wolfSSL_NoTicketTLSv12(WOLFSSL* ssl)
  2739. {
  2740. if (ssl == NULL)
  2741. return BAD_FUNC_ARG;
  2742. ssl->options.noTicketTls12 = 1;
  2743. return WOLFSSL_SUCCESS;
  2744. }
  2745. /* WOLFSSL_SUCCESS on ok */
  2746. int wolfSSL_CTX_set_TicketEncCb(WOLFSSL_CTX* ctx, SessionTicketEncCb cb)
  2747. {
  2748. if (ctx == NULL)
  2749. return BAD_FUNC_ARG;
  2750. ctx->ticketEncCb = cb;
  2751. return WOLFSSL_SUCCESS;
  2752. }
  2753. /* set hint interval, WOLFSSL_SUCCESS on ok */
  2754. int wolfSSL_CTX_set_TicketHint(WOLFSSL_CTX* ctx, int hint)
  2755. {
  2756. if (ctx == NULL)
  2757. return BAD_FUNC_ARG;
  2758. ctx->ticketHint = hint;
  2759. return WOLFSSL_SUCCESS;
  2760. }
  2761. /* set user context, WOLFSSL_SUCCESS on ok */
  2762. int wolfSSL_CTX_set_TicketEncCtx(WOLFSSL_CTX* ctx, void* userCtx)
  2763. {
  2764. if (ctx == NULL)
  2765. return BAD_FUNC_ARG;
  2766. ctx->ticketEncCtx = userCtx;
  2767. return WOLFSSL_SUCCESS;
  2768. }
  2769. /* get user context - returns userCtx on success, NULL on failure */
  2770. void* wolfSSL_CTX_get_TicketEncCtx(WOLFSSL_CTX* ctx)
  2771. {
  2772. if (ctx == NULL)
  2773. return NULL;
  2774. return ctx->ticketEncCtx;
  2775. }
  2776. #ifdef WOLFSSL_TLS13
  2777. /* set the maximum number of tickets to send
  2778. * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on fail
  2779. */
  2780. int wolfSSL_CTX_set_num_tickets(WOLFSSL_CTX* ctx, size_t mxTickets)
  2781. {
  2782. if (ctx == NULL)
  2783. return WOLFSSL_FAILURE;
  2784. ctx->maxTicketTls13 = (unsigned int)mxTickets;
  2785. return WOLFSSL_SUCCESS;
  2786. }
  2787. /* get the maximum number of tickets to send
  2788. * return number of tickets set to be sent
  2789. */
  2790. size_t wolfSSL_CTX_get_num_tickets(WOLFSSL_CTX* ctx)
  2791. {
  2792. if (ctx == NULL)
  2793. return 0;
  2794. return (size_t)ctx->maxTicketTls13;
  2795. }
  2796. #endif /* WOLFSSL_TLS13 */
  2797. #endif /* !NO_WOLFSSL_SERVER */
  2798. #if !defined(NO_WOLFSSL_CLIENT)
  2799. int wolfSSL_UseSessionTicket(WOLFSSL* ssl)
  2800. {
  2801. if (ssl == NULL)
  2802. return BAD_FUNC_ARG;
  2803. return TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  2804. }
  2805. int wolfSSL_CTX_UseSessionTicket(WOLFSSL_CTX* ctx)
  2806. {
  2807. if (ctx == NULL)
  2808. return BAD_FUNC_ARG;
  2809. return TLSX_UseSessionTicket(&ctx->extensions, NULL, ctx->heap);
  2810. }
  2811. WOLFSSL_API int wolfSSL_get_SessionTicket(WOLFSSL* ssl,
  2812. byte* buf, word32* bufSz)
  2813. {
  2814. if (ssl == NULL || buf == NULL || bufSz == NULL || *bufSz == 0)
  2815. return BAD_FUNC_ARG;
  2816. if (ssl->session->ticketLen <= *bufSz) {
  2817. XMEMCPY(buf, ssl->session->ticket, ssl->session->ticketLen);
  2818. *bufSz = ssl->session->ticketLen;
  2819. }
  2820. else
  2821. *bufSz = 0;
  2822. return WOLFSSL_SUCCESS;
  2823. }
  2824. WOLFSSL_API int wolfSSL_set_SessionTicket(WOLFSSL* ssl, const byte* buf,
  2825. word32 bufSz)
  2826. {
  2827. if (ssl == NULL || (buf == NULL && bufSz > 0))
  2828. return BAD_FUNC_ARG;
  2829. if (bufSz > 0) {
  2830. /* Ticket will fit into static ticket */
  2831. if (bufSz <= SESSION_TICKET_LEN) {
  2832. if (ssl->session->ticketLenAlloc > 0) {
  2833. XFREE(ssl->session->ticket, ssl->session->heap,
  2834. DYNAMIC_TYPE_SESSION_TICK);
  2835. ssl->session->ticketLenAlloc = 0;
  2836. ssl->session->ticket = ssl->session->staticTicket;
  2837. }
  2838. }
  2839. else { /* Ticket requires dynamic ticket storage */
  2840. if (ssl->session->ticketLen < bufSz) { /* is dyn buffer big enough */
  2841. if (ssl->session->ticketLenAlloc > 0) {
  2842. XFREE(ssl->session->ticket, ssl->session->heap,
  2843. DYNAMIC_TYPE_SESSION_TICK);
  2844. }
  2845. ssl->session->ticket = (byte*)XMALLOC(bufSz, ssl->session->heap,
  2846. DYNAMIC_TYPE_SESSION_TICK);
  2847. if(ssl->session->ticket == NULL) {
  2848. ssl->session->ticket = ssl->session->staticTicket;
  2849. ssl->session->ticketLenAlloc = 0;
  2850. return MEMORY_ERROR;
  2851. }
  2852. ssl->session->ticketLenAlloc = (word16)bufSz;
  2853. }
  2854. }
  2855. XMEMCPY(ssl->session->ticket, buf, bufSz);
  2856. }
  2857. ssl->session->ticketLen = (word16)bufSz;
  2858. return WOLFSSL_SUCCESS;
  2859. }
  2860. WOLFSSL_API int wolfSSL_set_SessionTicket_cb(WOLFSSL* ssl,
  2861. CallbackSessionTicket cb, void* ctx)
  2862. {
  2863. if (ssl == NULL)
  2864. return BAD_FUNC_ARG;
  2865. ssl->session_ticket_cb = cb;
  2866. ssl->session_ticket_ctx = ctx;
  2867. return WOLFSSL_SUCCESS;
  2868. }
  2869. #endif /* !NO_WOLFSSL_CLIENT */
  2870. #endif /* HAVE_SESSION_TICKET */
  2871. #ifdef HAVE_EXTENDED_MASTER
  2872. #ifndef NO_WOLFSSL_CLIENT
  2873. int wolfSSL_CTX_DisableExtendedMasterSecret(WOLFSSL_CTX* ctx)
  2874. {
  2875. if (ctx == NULL)
  2876. return BAD_FUNC_ARG;
  2877. ctx->haveEMS = 0;
  2878. return WOLFSSL_SUCCESS;
  2879. }
  2880. int wolfSSL_DisableExtendedMasterSecret(WOLFSSL* ssl)
  2881. {
  2882. if (ssl == NULL)
  2883. return BAD_FUNC_ARG;
  2884. ssl->options.haveEMS = 0;
  2885. return WOLFSSL_SUCCESS;
  2886. }
  2887. #endif
  2888. #endif
  2889. #ifndef WOLFSSL_LEANPSK
  2890. int wolfSSL_send(WOLFSSL* ssl, const void* data, int sz, int flags)
  2891. {
  2892. int ret;
  2893. int oldFlags;
  2894. WOLFSSL_ENTER("wolfSSL_send()");
  2895. if (ssl == NULL || data == NULL || sz < 0)
  2896. return BAD_FUNC_ARG;
  2897. oldFlags = ssl->wflags;
  2898. ssl->wflags = flags;
  2899. ret = wolfSSL_write(ssl, data, sz);
  2900. ssl->wflags = oldFlags;
  2901. WOLFSSL_LEAVE("wolfSSL_send()", ret);
  2902. return ret;
  2903. }
  2904. int wolfSSL_recv(WOLFSSL* ssl, void* data, int sz, int flags)
  2905. {
  2906. int ret;
  2907. int oldFlags;
  2908. WOLFSSL_ENTER("wolfSSL_recv()");
  2909. if (ssl == NULL || data == NULL || sz < 0)
  2910. return BAD_FUNC_ARG;
  2911. oldFlags = ssl->rflags;
  2912. ssl->rflags = flags;
  2913. ret = wolfSSL_read(ssl, data, sz);
  2914. ssl->rflags = oldFlags;
  2915. WOLFSSL_LEAVE("wolfSSL_recv()", ret);
  2916. return ret;
  2917. }
  2918. #endif
  2919. /* WOLFSSL_SUCCESS on ok */
  2920. WOLFSSL_ABI
  2921. int wolfSSL_shutdown(WOLFSSL* ssl)
  2922. {
  2923. int ret = WOLFSSL_FATAL_ERROR;
  2924. WOLFSSL_ENTER("SSL_shutdown()");
  2925. if (ssl == NULL)
  2926. return WOLFSSL_FATAL_ERROR;
  2927. if (ssl->options.quietShutdown) {
  2928. WOLFSSL_MSG("quiet shutdown, no close notify sent");
  2929. ret = WOLFSSL_SUCCESS;
  2930. }
  2931. else {
  2932. /* try to send close notify, not an error if can't */
  2933. if (!ssl->options.isClosed && !ssl->options.connReset &&
  2934. !ssl->options.sentNotify) {
  2935. ssl->error = SendAlert(ssl, alert_warning, close_notify);
  2936. if (ssl->error < 0) {
  2937. WOLFSSL_ERROR(ssl->error);
  2938. return WOLFSSL_FATAL_ERROR;
  2939. }
  2940. ssl->options.sentNotify = 1; /* don't send close_notify twice */
  2941. if (ssl->options.closeNotify)
  2942. ret = WOLFSSL_SUCCESS;
  2943. else {
  2944. ret = WOLFSSL_SHUTDOWN_NOT_DONE;
  2945. WOLFSSL_LEAVE("SSL_shutdown()", ret);
  2946. return ret;
  2947. }
  2948. }
  2949. #ifdef WOLFSSL_SHUTDOWNONCE
  2950. if (ssl->options.isClosed || ssl->options.connReset) {
  2951. /* Shutdown has already occurred.
  2952. * Caller is free to ignore this error. */
  2953. return SSL_SHUTDOWN_ALREADY_DONE_E;
  2954. }
  2955. #endif
  2956. /* call wolfSSL_shutdown again for bidirectional shutdown */
  2957. if (ssl->options.sentNotify && !ssl->options.closeNotify) {
  2958. ret = ProcessReply(ssl);
  2959. if (ret == ZERO_RETURN) {
  2960. /* simulate OpenSSL behavior */
  2961. ssl->error = WOLFSSL_ERROR_SYSCALL;
  2962. ret = WOLFSSL_SUCCESS;
  2963. } else if (ssl->error == WOLFSSL_ERROR_NONE) {
  2964. ret = WOLFSSL_SHUTDOWN_NOT_DONE;
  2965. } else {
  2966. WOLFSSL_ERROR(ssl->error);
  2967. ret = WOLFSSL_FATAL_ERROR;
  2968. }
  2969. }
  2970. }
  2971. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  2972. /* reset WOLFSSL structure state for possible re-use */
  2973. if (ret == WOLFSSL_SUCCESS) {
  2974. if (wolfSSL_clear(ssl) != WOLFSSL_SUCCESS) {
  2975. WOLFSSL_MSG("could not clear WOLFSSL");
  2976. ret = WOLFSSL_FATAL_ERROR;
  2977. }
  2978. }
  2979. #endif
  2980. WOLFSSL_LEAVE("SSL_shutdown()", ret);
  2981. return ret;
  2982. }
  2983. /* get current error state value */
  2984. int wolfSSL_state(WOLFSSL* ssl)
  2985. {
  2986. if (ssl == NULL) {
  2987. return BAD_FUNC_ARG;
  2988. }
  2989. return ssl->error;
  2990. }
  2991. WOLFSSL_ABI
  2992. int wolfSSL_get_error(WOLFSSL* ssl, int ret)
  2993. {
  2994. WOLFSSL_ENTER("SSL_get_error");
  2995. if (ret > 0)
  2996. return WOLFSSL_ERROR_NONE;
  2997. if (ssl == NULL)
  2998. return BAD_FUNC_ARG;
  2999. WOLFSSL_LEAVE("SSL_get_error", ssl->error);
  3000. /* make sure converted types are handled in SetErrorString() too */
  3001. if (ssl->error == WANT_READ)
  3002. return WOLFSSL_ERROR_WANT_READ; /* convert to OpenSSL type */
  3003. else if (ssl->error == WANT_WRITE)
  3004. return WOLFSSL_ERROR_WANT_WRITE; /* convert to OpenSSL type */
  3005. else if (ssl->error == ZERO_RETURN)
  3006. return WOLFSSL_ERROR_ZERO_RETURN; /* convert to OpenSSL type */
  3007. return ssl->error;
  3008. }
  3009. /* retrieve alert history, WOLFSSL_SUCCESS on ok */
  3010. int wolfSSL_get_alert_history(WOLFSSL* ssl, WOLFSSL_ALERT_HISTORY *h)
  3011. {
  3012. if (ssl && h) {
  3013. *h = ssl->alert_history;
  3014. }
  3015. return WOLFSSL_SUCCESS;
  3016. }
  3017. #ifdef OPENSSL_EXTRA
  3018. /* returns SSL_WRITING, SSL_READING or SSL_NOTHING */
  3019. int wolfSSL_want(WOLFSSL* ssl)
  3020. {
  3021. int rw_state = SSL_NOTHING;
  3022. if (ssl) {
  3023. if (ssl->error == WANT_READ)
  3024. rw_state = SSL_READING;
  3025. else if (ssl->error == WANT_WRITE)
  3026. rw_state = SSL_WRITING;
  3027. }
  3028. return rw_state;
  3029. }
  3030. #endif
  3031. /* return TRUE if current error is want read */
  3032. int wolfSSL_want_read(WOLFSSL* ssl)
  3033. {
  3034. WOLFSSL_ENTER("SSL_want_read");
  3035. if (ssl->error == WANT_READ)
  3036. return 1;
  3037. return 0;
  3038. }
  3039. /* return TRUE if current error is want write */
  3040. int wolfSSL_want_write(WOLFSSL* ssl)
  3041. {
  3042. WOLFSSL_ENTER("SSL_want_write");
  3043. if (ssl->error == WANT_WRITE)
  3044. return 1;
  3045. return 0;
  3046. }
  3047. char* wolfSSL_ERR_error_string(unsigned long errNumber, char* data)
  3048. {
  3049. static char tmp[WOLFSSL_MAX_ERROR_SZ] = {0};
  3050. WOLFSSL_ENTER("ERR_error_string");
  3051. if (data) {
  3052. SetErrorString((int)errNumber, data);
  3053. return data;
  3054. }
  3055. else {
  3056. SetErrorString((int)errNumber, tmp);
  3057. return tmp;
  3058. }
  3059. }
  3060. void wolfSSL_ERR_error_string_n(unsigned long e, char* buf, unsigned long len)
  3061. {
  3062. WOLFSSL_ENTER("wolfSSL_ERR_error_string_n");
  3063. if (len >= WOLFSSL_MAX_ERROR_SZ)
  3064. wolfSSL_ERR_error_string(e, buf);
  3065. else {
  3066. char tmp[WOLFSSL_MAX_ERROR_SZ];
  3067. WOLFSSL_MSG("Error buffer too short, truncating");
  3068. if (len) {
  3069. wolfSSL_ERR_error_string(e, tmp);
  3070. XMEMCPY(buf, tmp, len-1);
  3071. buf[len-1] = '\0';
  3072. }
  3073. }
  3074. }
  3075. /* don't free temporary arrays at end of handshake */
  3076. void wolfSSL_KeepArrays(WOLFSSL* ssl)
  3077. {
  3078. if (ssl)
  3079. ssl->options.saveArrays = 1;
  3080. }
  3081. /* user doesn't need temporary arrays anymore, Free */
  3082. void wolfSSL_FreeArrays(WOLFSSL* ssl)
  3083. {
  3084. if (ssl && ssl->options.handShakeState == HANDSHAKE_DONE) {
  3085. ssl->options.saveArrays = 0;
  3086. FreeArrays(ssl, 1);
  3087. }
  3088. }
  3089. /* Set option to indicate that the resources are not to be freed after
  3090. * handshake.
  3091. *
  3092. * ssl The SSL/TLS object.
  3093. * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
  3094. */
  3095. int wolfSSL_KeepHandshakeResources(WOLFSSL* ssl)
  3096. {
  3097. if (ssl == NULL)
  3098. return BAD_FUNC_ARG;
  3099. ssl->options.keepResources = 1;
  3100. return 0;
  3101. }
  3102. /* Free the handshake resources after handshake.
  3103. *
  3104. * ssl The SSL/TLS object.
  3105. * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
  3106. */
  3107. int wolfSSL_FreeHandshakeResources(WOLFSSL* ssl)
  3108. {
  3109. if (ssl == NULL)
  3110. return BAD_FUNC_ARG;
  3111. FreeHandshakeResources(ssl);
  3112. return 0;
  3113. }
  3114. /* Use the client's order of preference when matching cipher suites.
  3115. *
  3116. * ssl The SSL/TLS context object.
  3117. * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
  3118. */
  3119. int wolfSSL_CTX_UseClientSuites(WOLFSSL_CTX* ctx)
  3120. {
  3121. if (ctx == NULL)
  3122. return BAD_FUNC_ARG;
  3123. ctx->useClientOrder = 1;
  3124. return 0;
  3125. }
  3126. /* Use the client's order of preference when matching cipher suites.
  3127. *
  3128. * ssl The SSL/TLS object.
  3129. * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
  3130. */
  3131. int wolfSSL_UseClientSuites(WOLFSSL* ssl)
  3132. {
  3133. if (ssl == NULL)
  3134. return BAD_FUNC_ARG;
  3135. ssl->options.useClientOrder = 1;
  3136. return 0;
  3137. }
  3138. #ifdef WOLFSSL_DTLS
  3139. const byte* wolfSSL_GetDtlsMacSecret(WOLFSSL* ssl, int verify, int epochOrder)
  3140. {
  3141. #ifndef WOLFSSL_AEAD_ONLY
  3142. Keys* keys = NULL;
  3143. (void)epochOrder;
  3144. if (ssl == NULL)
  3145. return NULL;
  3146. #ifdef HAVE_SECURE_RENEGOTIATION
  3147. switch (epochOrder) {
  3148. case PEER_ORDER:
  3149. if (IsDtlsMsgSCRKeys(ssl))
  3150. keys = &ssl->secure_renegotiation->tmp_keys;
  3151. else
  3152. keys = &ssl->keys;
  3153. break;
  3154. case PREV_ORDER:
  3155. keys = &ssl->keys;
  3156. break;
  3157. case CUR_ORDER:
  3158. if (DtlsUseSCRKeys(ssl))
  3159. keys = &ssl->secure_renegotiation->tmp_keys;
  3160. else
  3161. keys = &ssl->keys;
  3162. break;
  3163. default:
  3164. WOLFSSL_MSG("Unknown epoch order");
  3165. return NULL;
  3166. }
  3167. #else
  3168. keys = &ssl->keys;
  3169. #endif
  3170. if ( (ssl->options.side == WOLFSSL_CLIENT_END && !verify) ||
  3171. (ssl->options.side == WOLFSSL_SERVER_END && verify) )
  3172. return keys->client_write_MAC_secret;
  3173. else
  3174. return keys->server_write_MAC_secret;
  3175. #else
  3176. (void)ssl;
  3177. (void)verify;
  3178. (void)epochOrder;
  3179. return NULL;
  3180. #endif
  3181. }
  3182. #endif /* WOLFSSL_DTLS */
  3183. const byte* wolfSSL_GetMacSecret(WOLFSSL* ssl, int verify)
  3184. {
  3185. #ifndef WOLFSSL_AEAD_ONLY
  3186. if (ssl == NULL)
  3187. return NULL;
  3188. if ( (ssl->options.side == WOLFSSL_CLIENT_END && !verify) ||
  3189. (ssl->options.side == WOLFSSL_SERVER_END && verify) )
  3190. return ssl->keys.client_write_MAC_secret;
  3191. else
  3192. return ssl->keys.server_write_MAC_secret;
  3193. #else
  3194. (void)ssl;
  3195. (void)verify;
  3196. return NULL;
  3197. #endif
  3198. }
  3199. #ifdef ATOMIC_USER
  3200. void wolfSSL_CTX_SetMacEncryptCb(WOLFSSL_CTX* ctx, CallbackMacEncrypt cb)
  3201. {
  3202. if (ctx)
  3203. ctx->MacEncryptCb = cb;
  3204. }
  3205. void wolfSSL_SetMacEncryptCtx(WOLFSSL* ssl, void *ctx)
  3206. {
  3207. if (ssl)
  3208. ssl->MacEncryptCtx = ctx;
  3209. }
  3210. void* wolfSSL_GetMacEncryptCtx(WOLFSSL* ssl)
  3211. {
  3212. if (ssl)
  3213. return ssl->MacEncryptCtx;
  3214. return NULL;
  3215. }
  3216. void wolfSSL_CTX_SetDecryptVerifyCb(WOLFSSL_CTX* ctx, CallbackDecryptVerify cb)
  3217. {
  3218. if (ctx)
  3219. ctx->DecryptVerifyCb = cb;
  3220. }
  3221. void wolfSSL_SetDecryptVerifyCtx(WOLFSSL* ssl, void *ctx)
  3222. {
  3223. if (ssl)
  3224. ssl->DecryptVerifyCtx = ctx;
  3225. }
  3226. void* wolfSSL_GetDecryptVerifyCtx(WOLFSSL* ssl)
  3227. {
  3228. if (ssl)
  3229. return ssl->DecryptVerifyCtx;
  3230. return NULL;
  3231. }
  3232. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  3233. /**
  3234. * Set the callback, against the context, that encrypts then MACs.
  3235. *
  3236. * ctx SSL/TLS context.
  3237. * cb Callback function to use with Encrypt-Then-MAC.
  3238. */
  3239. void wolfSSL_CTX_SetEncryptMacCb(WOLFSSL_CTX* ctx, CallbackEncryptMac cb)
  3240. {
  3241. if (ctx)
  3242. ctx->EncryptMacCb = cb;
  3243. }
  3244. /**
  3245. * Set the context to use with callback that encrypts then MACs.
  3246. *
  3247. * ssl SSL/TLS object.
  3248. * ctx Callback function's context.
  3249. */
  3250. void wolfSSL_SetEncryptMacCtx(WOLFSSL* ssl, void *ctx)
  3251. {
  3252. if (ssl)
  3253. ssl->EncryptMacCtx = ctx;
  3254. }
  3255. /**
  3256. * Get the context being used with callback that encrypts then MACs.
  3257. *
  3258. * ssl SSL/TLS object.
  3259. * returns callback function's context or NULL if SSL/TLS object is NULL.
  3260. */
  3261. void* wolfSSL_GetEncryptMacCtx(WOLFSSL* ssl)
  3262. {
  3263. if (ssl)
  3264. return ssl->EncryptMacCtx;
  3265. return NULL;
  3266. }
  3267. /**
  3268. * Set the callback, against the context, that MAC verifies then decrypts.
  3269. *
  3270. * ctx SSL/TLS context.
  3271. * cb Callback function to use with Encrypt-Then-MAC.
  3272. */
  3273. void wolfSSL_CTX_SetVerifyDecryptCb(WOLFSSL_CTX* ctx, CallbackVerifyDecrypt cb)
  3274. {
  3275. if (ctx)
  3276. ctx->VerifyDecryptCb = cb;
  3277. }
  3278. /**
  3279. * Set the context to use with callback that MAC verifies then decrypts.
  3280. *
  3281. * ssl SSL/TLS object.
  3282. * ctx Callback function's context.
  3283. */
  3284. void wolfSSL_SetVerifyDecryptCtx(WOLFSSL* ssl, void *ctx)
  3285. {
  3286. if (ssl)
  3287. ssl->VerifyDecryptCtx = ctx;
  3288. }
  3289. /**
  3290. * Get the context being used with callback that MAC verifies then decrypts.
  3291. *
  3292. * ssl SSL/TLS object.
  3293. * returns callback function's context or NULL if SSL/TLS object is NULL.
  3294. */
  3295. void* wolfSSL_GetVerifyDecryptCtx(WOLFSSL* ssl)
  3296. {
  3297. if (ssl)
  3298. return ssl->VerifyDecryptCtx;
  3299. return NULL;
  3300. }
  3301. #endif /* HAVE_ENCRYPT_THEN_MAC !WOLFSSL_AEAD_ONLY */
  3302. const byte* wolfSSL_GetClientWriteKey(WOLFSSL* ssl)
  3303. {
  3304. if (ssl)
  3305. return ssl->keys.client_write_key;
  3306. return NULL;
  3307. }
  3308. const byte* wolfSSL_GetClientWriteIV(WOLFSSL* ssl)
  3309. {
  3310. if (ssl)
  3311. return ssl->keys.client_write_IV;
  3312. return NULL;
  3313. }
  3314. const byte* wolfSSL_GetServerWriteKey(WOLFSSL* ssl)
  3315. {
  3316. if (ssl)
  3317. return ssl->keys.server_write_key;
  3318. return NULL;
  3319. }
  3320. const byte* wolfSSL_GetServerWriteIV(WOLFSSL* ssl)
  3321. {
  3322. if (ssl)
  3323. return ssl->keys.server_write_IV;
  3324. return NULL;
  3325. }
  3326. int wolfSSL_GetKeySize(WOLFSSL* ssl)
  3327. {
  3328. if (ssl)
  3329. return ssl->specs.key_size;
  3330. return BAD_FUNC_ARG;
  3331. }
  3332. int wolfSSL_GetIVSize(WOLFSSL* ssl)
  3333. {
  3334. if (ssl)
  3335. return ssl->specs.iv_size;
  3336. return BAD_FUNC_ARG;
  3337. }
  3338. int wolfSSL_GetBulkCipher(WOLFSSL* ssl)
  3339. {
  3340. if (ssl)
  3341. return ssl->specs.bulk_cipher_algorithm;
  3342. return BAD_FUNC_ARG;
  3343. }
  3344. int wolfSSL_GetCipherType(WOLFSSL* ssl)
  3345. {
  3346. if (ssl == NULL)
  3347. return BAD_FUNC_ARG;
  3348. #ifndef WOLFSSL_AEAD_ONLY
  3349. if (ssl->specs.cipher_type == block)
  3350. return WOLFSSL_BLOCK_TYPE;
  3351. if (ssl->specs.cipher_type == stream)
  3352. return WOLFSSL_STREAM_TYPE;
  3353. #endif
  3354. if (ssl->specs.cipher_type == aead)
  3355. return WOLFSSL_AEAD_TYPE;
  3356. return -1;
  3357. }
  3358. int wolfSSL_GetCipherBlockSize(WOLFSSL* ssl)
  3359. {
  3360. if (ssl == NULL)
  3361. return BAD_FUNC_ARG;
  3362. return ssl->specs.block_size;
  3363. }
  3364. int wolfSSL_GetAeadMacSize(WOLFSSL* ssl)
  3365. {
  3366. if (ssl == NULL)
  3367. return BAD_FUNC_ARG;
  3368. return ssl->specs.aead_mac_size;
  3369. }
  3370. int wolfSSL_IsTLSv1_1(WOLFSSL* ssl)
  3371. {
  3372. if (ssl == NULL)
  3373. return BAD_FUNC_ARG;
  3374. if (ssl->options.tls1_1)
  3375. return 1;
  3376. return 0;
  3377. }
  3378. int wolfSSL_GetSide(WOLFSSL* ssl)
  3379. {
  3380. if (ssl)
  3381. return ssl->options.side;
  3382. return BAD_FUNC_ARG;
  3383. }
  3384. int wolfSSL_GetHmacSize(WOLFSSL* ssl)
  3385. {
  3386. /* AEAD ciphers don't have HMAC keys */
  3387. if (ssl)
  3388. return (ssl->specs.cipher_type != aead) ? ssl->specs.hash_size : 0;
  3389. return BAD_FUNC_ARG;
  3390. }
  3391. #ifdef WORD64_AVAILABLE
  3392. int wolfSSL_GetPeerSequenceNumber(WOLFSSL* ssl, word64 *seq)
  3393. {
  3394. if ((ssl == NULL) || (seq == NULL))
  3395. return BAD_FUNC_ARG;
  3396. *seq = ((word64)ssl->keys.peer_sequence_number_hi << 32) |
  3397. ssl->keys.peer_sequence_number_lo;
  3398. return !(*seq);
  3399. }
  3400. int wolfSSL_GetSequenceNumber(WOLFSSL* ssl, word64 *seq)
  3401. {
  3402. if ((ssl == NULL) || (seq == NULL))
  3403. return BAD_FUNC_ARG;
  3404. *seq = ((word64)ssl->keys.sequence_number_hi << 32) |
  3405. ssl->keys.sequence_number_lo;
  3406. return !(*seq);
  3407. }
  3408. #endif
  3409. #endif /* ATOMIC_USER */
  3410. #ifndef NO_CERTS
  3411. WOLFSSL_CERT_MANAGER* wolfSSL_CTX_GetCertManager(WOLFSSL_CTX* ctx)
  3412. {
  3413. WOLFSSL_CERT_MANAGER* cm = NULL;
  3414. if (ctx)
  3415. cm = ctx->cm;
  3416. return cm;
  3417. }
  3418. WOLFSSL_CERT_MANAGER* wolfSSL_CertManagerNew_ex(void* heap)
  3419. {
  3420. WOLFSSL_CERT_MANAGER* cm;
  3421. WOLFSSL_ENTER("wolfSSL_CertManagerNew");
  3422. cm = (WOLFSSL_CERT_MANAGER*) XMALLOC(sizeof(WOLFSSL_CERT_MANAGER), heap,
  3423. DYNAMIC_TYPE_CERT_MANAGER);
  3424. if (cm) {
  3425. XMEMSET(cm, 0, sizeof(WOLFSSL_CERT_MANAGER));
  3426. cm->refCount = 1;
  3427. if (wc_InitMutex(&cm->caLock) != 0) {
  3428. WOLFSSL_MSG("Bad mutex init");
  3429. wolfSSL_CertManagerFree(cm);
  3430. return NULL;
  3431. }
  3432. #ifndef SINGLE_THREADED
  3433. if (wc_InitMutex(&cm->refMutex) != 0) {
  3434. WOLFSSL_MSG("Bad mutex init");
  3435. wolfSSL_CertManagerFree(cm);
  3436. return NULL;
  3437. }
  3438. #endif
  3439. #ifdef WOLFSSL_TRUST_PEER_CERT
  3440. if (wc_InitMutex(&cm->tpLock) != 0) {
  3441. WOLFSSL_MSG("Bad mutex init");
  3442. wolfSSL_CertManagerFree(cm);
  3443. return NULL;
  3444. }
  3445. #endif
  3446. /* set default minimum key size allowed */
  3447. #ifndef NO_RSA
  3448. cm->minRsaKeySz = MIN_RSAKEY_SZ;
  3449. #endif
  3450. #ifdef HAVE_ECC
  3451. cm->minEccKeySz = MIN_ECCKEY_SZ;
  3452. #endif
  3453. #ifdef HAVE_PQC
  3454. #ifdef HAVE_FALCON
  3455. cm->minFalconKeySz = MIN_FALCONKEY_SZ;
  3456. #endif /* HAVE_FALCON */
  3457. #ifdef HAVE_DILITHIUM
  3458. cm->minDilithiumKeySz = MIN_DILITHIUMKEY_SZ;
  3459. #endif /* HAVE_DILITHIUM */
  3460. #endif /* HAVE_PQC */
  3461. cm->heap = heap;
  3462. }
  3463. return cm;
  3464. }
  3465. WOLFSSL_CERT_MANAGER* wolfSSL_CertManagerNew(void)
  3466. {
  3467. return wolfSSL_CertManagerNew_ex(NULL);
  3468. }
  3469. void wolfSSL_CertManagerFree(WOLFSSL_CERT_MANAGER* cm)
  3470. {
  3471. int doFree = 0;
  3472. WOLFSSL_ENTER("wolfSSL_CertManagerFree");
  3473. if (cm) {
  3474. #ifndef SINGLE_THREADED
  3475. if (wc_LockMutex(&cm->refMutex) != 0) {
  3476. WOLFSSL_MSG("Couldn't lock cm mutex");
  3477. }
  3478. #endif
  3479. cm->refCount--;
  3480. if (cm->refCount == 0)
  3481. doFree = 1;
  3482. #ifndef SINGLE_THREADED
  3483. wc_UnLockMutex(&cm->refMutex);
  3484. #endif
  3485. if (doFree) {
  3486. #ifdef HAVE_CRL
  3487. if (cm->crl)
  3488. FreeCRL(cm->crl, 1);
  3489. #endif
  3490. #ifdef HAVE_OCSP
  3491. if (cm->ocsp)
  3492. FreeOCSP(cm->ocsp, 1);
  3493. XFREE(cm->ocspOverrideURL, cm->heap, DYNAMIC_TYPE_URL);
  3494. #if !defined(NO_WOLFSSL_SERVER) && \
  3495. (defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
  3496. defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))
  3497. if (cm->ocsp_stapling)
  3498. FreeOCSP(cm->ocsp_stapling, 1);
  3499. #endif
  3500. #endif
  3501. FreeSignerTable(cm->caTable, CA_TABLE_SIZE, cm->heap);
  3502. wc_FreeMutex(&cm->caLock);
  3503. #ifdef WOLFSSL_TRUST_PEER_CERT
  3504. FreeTrustedPeerTable(cm->tpTable, TP_TABLE_SIZE, cm->heap);
  3505. wc_FreeMutex(&cm->tpLock);
  3506. #endif
  3507. #ifndef SINGLE_THREADED
  3508. if (wc_FreeMutex(&cm->refMutex) != 0) {
  3509. WOLFSSL_MSG("Couldn't free refMutex mutex");
  3510. }
  3511. #endif
  3512. XFREE(cm, cm->heap, DYNAMIC_TYPE_CERT_MANAGER);
  3513. }
  3514. }
  3515. }
  3516. int wolfSSL_CertManager_up_ref(WOLFSSL_CERT_MANAGER* cm)
  3517. {
  3518. if (cm) {
  3519. #ifndef SINGLE_THREADED
  3520. if (wc_LockMutex(&cm->refMutex) != 0) {
  3521. WOLFSSL_MSG("Failed to lock cm mutex");
  3522. return WOLFSSL_FAILURE;
  3523. }
  3524. #endif
  3525. cm->refCount++;
  3526. #ifndef SINGLE_THREADED
  3527. wc_UnLockMutex(&cm->refMutex);
  3528. #endif
  3529. return WOLFSSL_SUCCESS;
  3530. }
  3531. return WOLFSSL_FAILURE;
  3532. }
  3533. #if defined(OPENSSL_EXTRA) && !defined(NO_FILESYSTEM)
  3534. #if defined(WOLFSSL_SIGNER_DER_CERT)
  3535. /******************************************************************************
  3536. * wolfSSL_CertManagerGetCerts - retrieve stack of X509 certificates in a
  3537. * certificate manager (CM).
  3538. *
  3539. * RETURNS:
  3540. * returns stack of X509 certs on success, otherwise returns a NULL.
  3541. */
  3542. WOLFSSL_STACK* wolfSSL_CertManagerGetCerts(WOLFSSL_CERT_MANAGER* cm)
  3543. {
  3544. WOLFSSL_STACK* sk = NULL;
  3545. int numCerts = 0;
  3546. DerBuffer** certBuffers = NULL;
  3547. const byte* derBuffer = NULL;
  3548. Signer* signers = NULL;
  3549. word32 row = 0;
  3550. WOLFSSL_X509* x509 = NULL;
  3551. int i = 0;
  3552. int ret = 0;
  3553. if (cm == NULL)
  3554. return NULL;
  3555. sk = wolfSSL_sk_X509_new();
  3556. if (sk == NULL)
  3557. goto error;
  3558. if (wc_LockMutex(&cm->caLock) != 0)
  3559. goto error;
  3560. /* Iterate once to get the number of certs, for memory allocation
  3561. purposes. */
  3562. for (row = 0; row < CA_TABLE_SIZE; row++) {
  3563. signers = cm->caTable[row];
  3564. while (signers && signers->derCert && signers->derCert->buffer) {
  3565. ++numCerts;
  3566. signers = signers->next;
  3567. }
  3568. }
  3569. if (numCerts == 0) {
  3570. wc_UnLockMutex(&cm->caLock);
  3571. goto error;
  3572. }
  3573. certBuffers = (DerBuffer**)XMALLOC(sizeof(DerBuffer*) * numCerts, cm->heap,
  3574. DYNAMIC_TYPE_TMP_BUFFER);
  3575. if (certBuffers == NULL) {
  3576. wc_UnLockMutex(&cm->caLock);
  3577. goto error;
  3578. }
  3579. XMEMSET(certBuffers, 0, sizeof(DerBuffer*) * numCerts);
  3580. /* Copy the certs locally so that we can release the caLock. If the lock is
  3581. held when wolfSSL_d2i_X509 is called, GetCA will also try to get the
  3582. lock, leading to deadlock. */
  3583. for (row = 0; row < CA_TABLE_SIZE; row++) {
  3584. signers = cm->caTable[row];
  3585. while (signers && signers->derCert && signers->derCert->buffer) {
  3586. ret = AllocDer(&certBuffers[i], signers->derCert->length, CA_TYPE,
  3587. cm->heap);
  3588. if (ret < 0) {
  3589. wc_UnLockMutex(&cm->caLock);
  3590. goto error;
  3591. }
  3592. XMEMCPY(certBuffers[i]->buffer, signers->derCert->buffer,
  3593. signers->derCert->length);
  3594. certBuffers[i]->length = signers->derCert->length;
  3595. ++i;
  3596. signers = signers->next;
  3597. }
  3598. }
  3599. wc_UnLockMutex(&cm->caLock);
  3600. for (i = 0; i < numCerts; ++i) {
  3601. derBuffer = certBuffers[i]->buffer;
  3602. wolfSSL_d2i_X509(&x509, &derBuffer, certBuffers[i]->length);
  3603. if (x509 == NULL)
  3604. goto error;
  3605. if (wolfSSL_sk_X509_push(sk, x509) != WOLFSSL_SUCCESS)
  3606. goto error;
  3607. }
  3608. for (i = 0; i < numCerts && certBuffers[i] != NULL; ++i) {
  3609. FreeDer(&certBuffers[i]);
  3610. }
  3611. XFREE(certBuffers, cm->heap, DYNAMIC_TYPE_TMP_BUFFER);
  3612. return sk;
  3613. error:
  3614. if (sk)
  3615. wolfSSL_sk_X509_pop_free(sk, NULL);
  3616. if (certBuffers != NULL) {
  3617. for (i = 0; i < numCerts && certBuffers[i] != NULL; ++i) {
  3618. FreeDer(&certBuffers[i]);
  3619. }
  3620. }
  3621. if (certBuffers)
  3622. XFREE(certBuffers, cm->heap, DYNAMIC_TYPE_TMP_BUFFER);
  3623. return NULL;
  3624. }
  3625. #endif /* WOLFSSL_SIGNER_DER_CERT */
  3626. #endif /* OPENSSL_EXTRA && !NO_FILESYSTEM */
  3627. /* Unload the CA signer list */
  3628. int wolfSSL_CertManagerUnloadCAs(WOLFSSL_CERT_MANAGER* cm)
  3629. {
  3630. WOLFSSL_ENTER("wolfSSL_CertManagerUnloadCAs");
  3631. if (cm == NULL)
  3632. return BAD_FUNC_ARG;
  3633. if (wc_LockMutex(&cm->caLock) != 0)
  3634. return BAD_MUTEX_E;
  3635. FreeSignerTable(cm->caTable, CA_TABLE_SIZE, cm->heap);
  3636. wc_UnLockMutex(&cm->caLock);
  3637. return WOLFSSL_SUCCESS;
  3638. }
  3639. #ifdef WOLFSSL_TRUST_PEER_CERT
  3640. int wolfSSL_CertManagerUnload_trust_peers(WOLFSSL_CERT_MANAGER* cm)
  3641. {
  3642. WOLFSSL_ENTER("wolfSSL_CertManagerUnload_trust_peers");
  3643. if (cm == NULL)
  3644. return BAD_FUNC_ARG;
  3645. if (wc_LockMutex(&cm->tpLock) != 0)
  3646. return BAD_MUTEX_E;
  3647. FreeTrustedPeerTable(cm->tpTable, TP_TABLE_SIZE, cm->heap);
  3648. wc_UnLockMutex(&cm->tpLock);
  3649. return WOLFSSL_SUCCESS;
  3650. }
  3651. #endif /* WOLFSSL_TRUST_PEER_CERT */
  3652. #endif /* NO_CERTS */
  3653. #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM)
  3654. void wolfSSL_ERR_print_errors_fp(XFILE fp, int err)
  3655. {
  3656. char data[WOLFSSL_MAX_ERROR_SZ + 1];
  3657. WOLFSSL_ENTER("wolfSSL_ERR_print_errors_fp");
  3658. SetErrorString(err, data);
  3659. if (XFPRINTF(fp, "%s", data) < 0)
  3660. WOLFSSL_MSG("fprintf failed in wolfSSL_ERR_print_errors_fp");
  3661. }
  3662. #if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE)
  3663. void wolfSSL_ERR_dump_errors_fp(XFILE fp)
  3664. {
  3665. wc_ERR_print_errors_fp(fp);
  3666. }
  3667. void wolfSSL_ERR_print_errors_cb (int (*cb)(const char *str, size_t len,
  3668. void *u), void *u)
  3669. {
  3670. wc_ERR_print_errors_cb(cb, u);
  3671. }
  3672. #endif
  3673. #endif
  3674. /*
  3675. * TODO This ssl parameter needs to be changed to const once our ABI checker
  3676. * stops flagging qualifier additions as ABI breaking.
  3677. */
  3678. WOLFSSL_ABI
  3679. int wolfSSL_pending(WOLFSSL* ssl)
  3680. {
  3681. WOLFSSL_ENTER("SSL_pending");
  3682. if (ssl == NULL)
  3683. return WOLFSSL_FAILURE;
  3684. return ssl->buffers.clearOutputBuffer.length;
  3685. }
  3686. int wolfSSL_has_pending(const WOLFSSL* ssl)
  3687. {
  3688. WOLFSSL_ENTER("wolfSSL_has_pending");
  3689. if (ssl == NULL)
  3690. return WOLFSSL_FAILURE;
  3691. return ssl->buffers.clearOutputBuffer.length > 0;
  3692. }
  3693. #ifndef WOLFSSL_LEANPSK
  3694. /* turn on handshake group messages for context */
  3695. int wolfSSL_CTX_set_group_messages(WOLFSSL_CTX* ctx)
  3696. {
  3697. if (ctx == NULL)
  3698. return BAD_FUNC_ARG;
  3699. ctx->groupMessages = 1;
  3700. return WOLFSSL_SUCCESS;
  3701. }
  3702. #endif
  3703. #ifndef NO_WOLFSSL_CLIENT
  3704. /* connect enough to get peer cert chain */
  3705. int wolfSSL_connect_cert(WOLFSSL* ssl)
  3706. {
  3707. int ret;
  3708. if (ssl == NULL)
  3709. return WOLFSSL_FAILURE;
  3710. ssl->options.certOnly = 1;
  3711. ret = wolfSSL_connect(ssl);
  3712. ssl->options.certOnly = 0;
  3713. return ret;
  3714. }
  3715. #endif
  3716. #ifndef WOLFSSL_LEANPSK
  3717. /* turn on handshake group messages for ssl object */
  3718. int wolfSSL_set_group_messages(WOLFSSL* ssl)
  3719. {
  3720. if (ssl == NULL)
  3721. return BAD_FUNC_ARG;
  3722. ssl->options.groupMessages = 1;
  3723. return WOLFSSL_SUCCESS;
  3724. }
  3725. /* make minVersion the internal equivalent SSL version */
  3726. static int SetMinVersionHelper(byte* minVersion, int version)
  3727. {
  3728. #ifdef NO_TLS
  3729. (void)minVersion;
  3730. #endif
  3731. switch (version) {
  3732. #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
  3733. case WOLFSSL_SSLV3:
  3734. *minVersion = SSLv3_MINOR;
  3735. break;
  3736. #endif
  3737. #ifndef NO_TLS
  3738. #ifndef NO_OLD_TLS
  3739. #ifdef WOLFSSL_ALLOW_TLSV10
  3740. case WOLFSSL_TLSV1:
  3741. *minVersion = TLSv1_MINOR;
  3742. break;
  3743. #endif
  3744. case WOLFSSL_TLSV1_1:
  3745. *minVersion = TLSv1_1_MINOR;
  3746. break;
  3747. #endif
  3748. #ifndef WOLFSSL_NO_TLS12
  3749. case WOLFSSL_TLSV1_2:
  3750. *minVersion = TLSv1_2_MINOR;
  3751. break;
  3752. #endif
  3753. #endif
  3754. #ifdef WOLFSSL_TLS13
  3755. case WOLFSSL_TLSV1_3:
  3756. *minVersion = TLSv1_3_MINOR;
  3757. break;
  3758. #endif
  3759. #ifdef WOLFSSL_DTLS
  3760. case WOLFSSL_DTLSV1:
  3761. *minVersion = DTLS_MINOR;
  3762. break;
  3763. case WOLFSSL_DTLSV1_2:
  3764. *minVersion = DTLSv1_2_MINOR;
  3765. break;
  3766. #ifdef WOLFSSL_DTLS13
  3767. case WOLFSSL_DTLSV1_3:
  3768. *minVersion = DTLSv1_3_MINOR;
  3769. break;
  3770. #endif /* WOLFSSL_DTLS13 */
  3771. #endif /* WOLFSSL_DTLS */
  3772. default:
  3773. WOLFSSL_MSG("Bad function argument");
  3774. return BAD_FUNC_ARG;
  3775. }
  3776. return WOLFSSL_SUCCESS;
  3777. }
  3778. /* Set minimum downgrade version allowed, WOLFSSL_SUCCESS on ok */
  3779. WOLFSSL_ABI
  3780. int wolfSSL_CTX_SetMinVersion(WOLFSSL_CTX* ctx, int version)
  3781. {
  3782. WOLFSSL_ENTER("wolfSSL_CTX_SetMinVersion");
  3783. if (ctx == NULL) {
  3784. WOLFSSL_MSG("Bad function argument");
  3785. return BAD_FUNC_ARG;
  3786. }
  3787. return SetMinVersionHelper(&ctx->minDowngrade, version);
  3788. }
  3789. /* Set minimum downgrade version allowed, WOLFSSL_SUCCESS on ok */
  3790. int wolfSSL_SetMinVersion(WOLFSSL* ssl, int version)
  3791. {
  3792. WOLFSSL_ENTER("wolfSSL_SetMinVersion");
  3793. if (ssl == NULL) {
  3794. WOLFSSL_MSG("Bad function argument");
  3795. return BAD_FUNC_ARG;
  3796. }
  3797. return SetMinVersionHelper(&ssl->options.minDowngrade, version);
  3798. }
  3799. /* Function to get version as WOLFSSL_ enum value for wolfSSL_SetVersion */
  3800. int wolfSSL_GetVersion(const WOLFSSL* ssl)
  3801. {
  3802. if (ssl == NULL)
  3803. return BAD_FUNC_ARG;
  3804. if (ssl->version.major == SSLv3_MAJOR) {
  3805. switch (ssl->version.minor) {
  3806. case SSLv3_MINOR :
  3807. return WOLFSSL_SSLV3;
  3808. case TLSv1_MINOR :
  3809. return WOLFSSL_TLSV1;
  3810. case TLSv1_1_MINOR :
  3811. return WOLFSSL_TLSV1_1;
  3812. case TLSv1_2_MINOR :
  3813. return WOLFSSL_TLSV1_2;
  3814. case TLSv1_3_MINOR :
  3815. return WOLFSSL_TLSV1_3;
  3816. default:
  3817. break;
  3818. }
  3819. }
  3820. return VERSION_ERROR;
  3821. }
  3822. int wolfSSL_SetVersion(WOLFSSL* ssl, int version)
  3823. {
  3824. word16 haveRSA = 1;
  3825. word16 havePSK = 0;
  3826. int keySz = 0;
  3827. WOLFSSL_ENTER("wolfSSL_SetVersion");
  3828. if (ssl == NULL) {
  3829. WOLFSSL_MSG("Bad function argument");
  3830. return BAD_FUNC_ARG;
  3831. }
  3832. switch (version) {
  3833. #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
  3834. case WOLFSSL_SSLV3:
  3835. ssl->version = MakeSSLv3();
  3836. break;
  3837. #endif
  3838. #ifndef NO_TLS
  3839. #ifndef NO_OLD_TLS
  3840. #ifdef WOLFSSL_ALLOW_TLSV10
  3841. case WOLFSSL_TLSV1:
  3842. ssl->version = MakeTLSv1();
  3843. break;
  3844. #endif
  3845. case WOLFSSL_TLSV1_1:
  3846. ssl->version = MakeTLSv1_1();
  3847. break;
  3848. #endif
  3849. #ifndef WOLFSSL_NO_TLS12
  3850. case WOLFSSL_TLSV1_2:
  3851. ssl->version = MakeTLSv1_2();
  3852. break;
  3853. #endif
  3854. #ifdef WOLFSSL_TLS13
  3855. case WOLFSSL_TLSV1_3:
  3856. ssl->version = MakeTLSv1_3();
  3857. break;
  3858. #endif /* WOLFSSL_TLS13 */
  3859. #endif
  3860. default:
  3861. WOLFSSL_MSG("Bad function argument");
  3862. return BAD_FUNC_ARG;
  3863. }
  3864. #ifdef NO_RSA
  3865. haveRSA = 0;
  3866. #endif
  3867. #ifndef NO_PSK
  3868. havePSK = ssl->options.havePSK;
  3869. #endif
  3870. #ifndef NO_CERTS
  3871. keySz = ssl->buffers.keySz;
  3872. #endif
  3873. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
  3874. ssl->options.haveDH, ssl->options.haveECDSAsig,
  3875. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  3876. ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
  3877. ssl->options.haveAnon, TRUE, ssl->options.side);
  3878. return WOLFSSL_SUCCESS;
  3879. }
  3880. #endif /* !leanpsk */
  3881. #ifndef NO_CERTS
  3882. /* hash is the SHA digest of name, just use first 32 bits as hash */
  3883. static WC_INLINE word32 HashSigner(const byte* hash)
  3884. {
  3885. return MakeWordFromHash(hash) % CA_TABLE_SIZE;
  3886. }
  3887. /* does CA already exist on signer list */
  3888. int AlreadySigner(WOLFSSL_CERT_MANAGER* cm, byte* hash)
  3889. {
  3890. Signer* signers;
  3891. int ret = 0;
  3892. word32 row;
  3893. if (cm == NULL || hash == NULL) {
  3894. return ret;
  3895. }
  3896. row = HashSigner(hash);
  3897. if (wc_LockMutex(&cm->caLock) != 0) {
  3898. return ret;
  3899. }
  3900. signers = cm->caTable[row];
  3901. while (signers) {
  3902. byte* subjectHash;
  3903. #ifndef NO_SKID
  3904. subjectHash = signers->subjectKeyIdHash;
  3905. #else
  3906. subjectHash = signers->subjectNameHash;
  3907. #endif
  3908. if (XMEMCMP(hash, subjectHash, SIGNER_DIGEST_SIZE) == 0) {
  3909. ret = 1; /* success */
  3910. break;
  3911. }
  3912. signers = signers->next;
  3913. }
  3914. wc_UnLockMutex(&cm->caLock);
  3915. return ret;
  3916. }
  3917. #ifdef WOLFSSL_TRUST_PEER_CERT
  3918. /* hash is the SHA digest of name, just use first 32 bits as hash */
  3919. static WC_INLINE word32 TrustedPeerHashSigner(const byte* hash)
  3920. {
  3921. return MakeWordFromHash(hash) % TP_TABLE_SIZE;
  3922. }
  3923. /* does trusted peer already exist on signer list */
  3924. int AlreadyTrustedPeer(WOLFSSL_CERT_MANAGER* cm, DecodedCert* cert)
  3925. {
  3926. TrustedPeerCert* tp;
  3927. int ret = 0;
  3928. word32 row = TrustedPeerHashSigner(cert->subjectHash);
  3929. if (wc_LockMutex(&cm->tpLock) != 0)
  3930. return ret;
  3931. tp = cm->tpTable[row];
  3932. while (tp) {
  3933. if (XMEMCMP(cert->subjectHash, tp->subjectNameHash,
  3934. SIGNER_DIGEST_SIZE) == 0)
  3935. ret = 1;
  3936. #ifndef NO_SKID
  3937. if (cert->extSubjKeyIdSet) {
  3938. /* Compare SKID as well if available */
  3939. if (ret == 1 && XMEMCMP(cert->extSubjKeyId, tp->subjectKeyIdHash,
  3940. SIGNER_DIGEST_SIZE) != 0)
  3941. ret = 0;
  3942. }
  3943. #endif
  3944. if (ret == 1)
  3945. break;
  3946. tp = tp->next;
  3947. }
  3948. wc_UnLockMutex(&cm->tpLock);
  3949. return ret;
  3950. }
  3951. /* return Trusted Peer if found, otherwise NULL
  3952. type is what to match on
  3953. */
  3954. TrustedPeerCert* GetTrustedPeer(void* vp, DecodedCert* cert)
  3955. {
  3956. WOLFSSL_CERT_MANAGER* cm = (WOLFSSL_CERT_MANAGER*)vp;
  3957. TrustedPeerCert* ret = NULL;
  3958. TrustedPeerCert* tp = NULL;
  3959. word32 row;
  3960. if (cm == NULL || cert == NULL)
  3961. return NULL;
  3962. row = TrustedPeerHashSigner(cert->subjectHash);
  3963. if (wc_LockMutex(&cm->tpLock) != 0)
  3964. return ret;
  3965. tp = cm->tpTable[row];
  3966. while (tp) {
  3967. if (XMEMCMP(cert->subjectHash, tp->subjectNameHash,
  3968. SIGNER_DIGEST_SIZE) == 0)
  3969. ret = tp;
  3970. #ifndef NO_SKID
  3971. if (cert->extSubjKeyIdSet) {
  3972. /* Compare SKID as well if available */
  3973. if (ret != NULL && XMEMCMP(cert->extSubjKeyId, tp->subjectKeyIdHash,
  3974. SIGNER_DIGEST_SIZE) != 0)
  3975. ret = NULL;
  3976. }
  3977. #endif
  3978. if (ret != NULL)
  3979. break;
  3980. tp = tp->next;
  3981. }
  3982. wc_UnLockMutex(&cm->tpLock);
  3983. return ret;
  3984. }
  3985. int MatchTrustedPeer(TrustedPeerCert* tp, DecodedCert* cert)
  3986. {
  3987. if (tp == NULL || cert == NULL)
  3988. return BAD_FUNC_ARG;
  3989. /* subject key id or subject hash has been compared when searching
  3990. tpTable for the cert from function GetTrustedPeer */
  3991. /* compare signatures */
  3992. if (tp->sigLen == cert->sigLength) {
  3993. if (XMEMCMP(tp->sig, cert->signature, cert->sigLength)) {
  3994. return WOLFSSL_FAILURE;
  3995. }
  3996. }
  3997. else {
  3998. return WOLFSSL_FAILURE;
  3999. }
  4000. return WOLFSSL_SUCCESS;
  4001. }
  4002. #endif /* WOLFSSL_TRUST_PEER_CERT */
  4003. /* return CA if found, otherwise NULL */
  4004. Signer* GetCA(void* vp, byte* hash)
  4005. {
  4006. WOLFSSL_CERT_MANAGER* cm = (WOLFSSL_CERT_MANAGER*)vp;
  4007. Signer* ret = NULL;
  4008. Signer* signers;
  4009. word32 row = 0;
  4010. if (cm == NULL || hash == NULL)
  4011. return NULL;
  4012. row = HashSigner(hash);
  4013. if (wc_LockMutex(&cm->caLock) != 0)
  4014. return ret;
  4015. signers = cm->caTable[row];
  4016. while (signers) {
  4017. byte* subjectHash;
  4018. #ifndef NO_SKID
  4019. subjectHash = signers->subjectKeyIdHash;
  4020. #else
  4021. subjectHash = signers->subjectNameHash;
  4022. #endif
  4023. if (XMEMCMP(hash, subjectHash, SIGNER_DIGEST_SIZE) == 0) {
  4024. ret = signers;
  4025. break;
  4026. }
  4027. signers = signers->next;
  4028. }
  4029. wc_UnLockMutex(&cm->caLock);
  4030. return ret;
  4031. }
  4032. #ifndef NO_SKID
  4033. /* return CA if found, otherwise NULL. Walk through hash table. */
  4034. Signer* GetCAByName(void* vp, byte* hash)
  4035. {
  4036. WOLFSSL_CERT_MANAGER* cm = (WOLFSSL_CERT_MANAGER*)vp;
  4037. Signer* ret = NULL;
  4038. Signer* signers;
  4039. word32 row;
  4040. if (cm == NULL)
  4041. return NULL;
  4042. if (wc_LockMutex(&cm->caLock) != 0)
  4043. return ret;
  4044. for (row = 0; row < CA_TABLE_SIZE && ret == NULL; row++) {
  4045. signers = cm->caTable[row];
  4046. while (signers && ret == NULL) {
  4047. if (XMEMCMP(hash, signers->subjectNameHash,
  4048. SIGNER_DIGEST_SIZE) == 0) {
  4049. ret = signers;
  4050. }
  4051. signers = signers->next;
  4052. }
  4053. }
  4054. wc_UnLockMutex(&cm->caLock);
  4055. return ret;
  4056. }
  4057. #endif
  4058. #ifdef WOLFSSL_TRUST_PEER_CERT
  4059. /* add a trusted peer cert to linked list */
  4060. int AddTrustedPeer(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int verify)
  4061. {
  4062. int ret, row;
  4063. TrustedPeerCert* peerCert;
  4064. DecodedCert* cert;
  4065. DerBuffer* der = *pDer;
  4066. WOLFSSL_MSG("Adding a Trusted Peer Cert");
  4067. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cm->heap,
  4068. DYNAMIC_TYPE_DCERT);
  4069. if (cert == NULL) {
  4070. FreeDer(&der);
  4071. return MEMORY_E;
  4072. }
  4073. InitDecodedCert(cert, der->buffer, der->length, cm->heap);
  4074. if ((ret = ParseCert(cert, TRUSTED_PEER_TYPE, verify, cm)) != 0) {
  4075. FreeDecodedCert(cert);
  4076. XFREE(cert, NULL, DYNAMIC_TYPE_DCERT);
  4077. FreeDer(&der);
  4078. return ret;
  4079. }
  4080. WOLFSSL_MSG("\tParsed new trusted peer cert");
  4081. peerCert = (TrustedPeerCert*)XMALLOC(sizeof(TrustedPeerCert), cm->heap,
  4082. DYNAMIC_TYPE_CERT);
  4083. if (peerCert == NULL) {
  4084. FreeDecodedCert(cert);
  4085. XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
  4086. FreeDer(&der);
  4087. return MEMORY_E;
  4088. }
  4089. XMEMSET(peerCert, 0, sizeof(TrustedPeerCert));
  4090. #ifndef IGNORE_NAME_CONSTRAINTS
  4091. if (peerCert->permittedNames)
  4092. FreeNameSubtrees(peerCert->permittedNames, cm->heap);
  4093. if (peerCert->excludedNames)
  4094. FreeNameSubtrees(peerCert->excludedNames, cm->heap);
  4095. #endif
  4096. if (AlreadyTrustedPeer(cm, cert)) {
  4097. WOLFSSL_MSG("\tAlready have this CA, not adding again");
  4098. FreeTrustedPeer(peerCert, cm->heap);
  4099. (void)ret;
  4100. }
  4101. else {
  4102. /* add trusted peer signature */
  4103. peerCert->sigLen = cert->sigLength;
  4104. peerCert->sig = (byte *)XMALLOC(cert->sigLength, cm->heap,
  4105. DYNAMIC_TYPE_SIGNATURE);
  4106. if (peerCert->sig == NULL) {
  4107. FreeDecodedCert(cert);
  4108. XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
  4109. FreeTrustedPeer(peerCert, cm->heap);
  4110. FreeDer(&der);
  4111. return MEMORY_E;
  4112. }
  4113. XMEMCPY(peerCert->sig, cert->signature, cert->sigLength);
  4114. /* add trusted peer name */
  4115. peerCert->nameLen = cert->subjectCNLen;
  4116. peerCert->name = cert->subjectCN;
  4117. #ifndef IGNORE_NAME_CONSTRAINTS
  4118. peerCert->permittedNames = cert->permittedNames;
  4119. peerCert->excludedNames = cert->excludedNames;
  4120. #endif
  4121. /* add SKID when available and hash of name */
  4122. #ifndef NO_SKID
  4123. XMEMCPY(peerCert->subjectKeyIdHash, cert->extSubjKeyId,
  4124. SIGNER_DIGEST_SIZE);
  4125. #endif
  4126. XMEMCPY(peerCert->subjectNameHash, cert->subjectHash,
  4127. SIGNER_DIGEST_SIZE);
  4128. peerCert->next = NULL; /* If Key Usage not set, all uses valid. */
  4129. cert->subjectCN = 0;
  4130. #ifndef IGNORE_NAME_CONSTRAINTS
  4131. cert->permittedNames = NULL;
  4132. cert->excludedNames = NULL;
  4133. #endif
  4134. row = TrustedPeerHashSigner(peerCert->subjectNameHash);
  4135. if (wc_LockMutex(&cm->tpLock) == 0) {
  4136. peerCert->next = cm->tpTable[row];
  4137. cm->tpTable[row] = peerCert; /* takes ownership */
  4138. wc_UnLockMutex(&cm->tpLock);
  4139. }
  4140. else {
  4141. WOLFSSL_MSG("\tTrusted Peer Cert Mutex Lock failed");
  4142. FreeDecodedCert(cert);
  4143. XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
  4144. FreeTrustedPeer(peerCert, cm->heap);
  4145. FreeDer(&der);
  4146. return BAD_MUTEX_E;
  4147. }
  4148. }
  4149. WOLFSSL_MSG("\tFreeing parsed trusted peer cert");
  4150. FreeDecodedCert(cert);
  4151. XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
  4152. WOLFSSL_MSG("\tFreeing der trusted peer cert");
  4153. FreeDer(&der);
  4154. WOLFSSL_MSG("\t\tOK Freeing der trusted peer cert");
  4155. WOLFSSL_LEAVE("AddTrustedPeer", ret);
  4156. return WOLFSSL_SUCCESS;
  4157. }
  4158. #endif /* WOLFSSL_TRUST_PEER_CERT */
  4159. /* owns der, internal now uses too */
  4160. /* type flag ids from user or from chain received during verify
  4161. don't allow chain ones to be added w/o isCA extension */
  4162. int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify)
  4163. {
  4164. int ret;
  4165. Signer* signer = NULL;
  4166. word32 row;
  4167. byte* subjectHash;
  4168. #ifdef WOLFSSL_SMALL_STACK
  4169. DecodedCert* cert = NULL;
  4170. #else
  4171. DecodedCert cert[1];
  4172. #endif
  4173. DerBuffer* der = *pDer;
  4174. WOLFSSL_MSG("Adding a CA");
  4175. if (cm == NULL) {
  4176. FreeDer(pDer);
  4177. return BAD_FUNC_ARG;
  4178. }
  4179. #ifdef WOLFSSL_SMALL_STACK
  4180. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  4181. DYNAMIC_TYPE_DCERT);
  4182. if (cert == NULL) {
  4183. FreeDer(pDer);
  4184. return MEMORY_E;
  4185. }
  4186. #endif
  4187. InitDecodedCert(cert, der->buffer, der->length, cm->heap);
  4188. ret = ParseCert(cert, CA_TYPE, verify, cm);
  4189. WOLFSSL_MSG("\tParsed new CA");
  4190. #ifndef NO_SKID
  4191. subjectHash = cert->extSubjKeyId;
  4192. #else
  4193. subjectHash = cert->subjectHash;
  4194. #endif
  4195. /* check CA key size */
  4196. if (verify) {
  4197. switch (cert->keyOID) {
  4198. #ifndef NO_RSA
  4199. #ifdef WC_RSA_PSS
  4200. case RSAPSSk:
  4201. #endif
  4202. case RSAk:
  4203. if (cm->minRsaKeySz < 0 ||
  4204. cert->pubKeySize < (word16)cm->minRsaKeySz) {
  4205. ret = RSA_KEY_SIZE_E;
  4206. WOLFSSL_MSG("\tCA RSA key size error");
  4207. }
  4208. break;
  4209. #endif /* !NO_RSA */
  4210. #ifdef HAVE_ECC
  4211. case ECDSAk:
  4212. if (cm->minEccKeySz < 0 ||
  4213. cert->pubKeySize < (word16)cm->minEccKeySz) {
  4214. ret = ECC_KEY_SIZE_E;
  4215. WOLFSSL_MSG("\tCA ECC key size error");
  4216. }
  4217. break;
  4218. #endif /* HAVE_ECC */
  4219. #ifdef HAVE_ED25519
  4220. case ED25519k:
  4221. if (cm->minEccKeySz < 0 ||
  4222. ED25519_KEY_SIZE < (word16)cm->minEccKeySz) {
  4223. ret = ECC_KEY_SIZE_E;
  4224. WOLFSSL_MSG("\tCA ECC key size error");
  4225. }
  4226. break;
  4227. #endif /* HAVE_ED25519 */
  4228. #ifdef HAVE_ED448
  4229. case ED448k:
  4230. if (cm->minEccKeySz < 0 ||
  4231. ED448_KEY_SIZE < (word16)cm->minEccKeySz) {
  4232. ret = ECC_KEY_SIZE_E;
  4233. WOLFSSL_MSG("\tCA ECC key size error");
  4234. }
  4235. break;
  4236. #endif /* HAVE_ED448 */
  4237. #if defined(HAVE_PQC)
  4238. #if defined(HAVE_FALCON)
  4239. case FALCON_LEVEL1k:
  4240. if (cm->minFalconKeySz < 0 ||
  4241. FALCON_LEVEL1_KEY_SIZE < (word16)cm->minFalconKeySz) {
  4242. ret = FALCON_KEY_SIZE_E;
  4243. WOLFSSL_MSG("\tCA Falcon level 1 key size error");
  4244. }
  4245. break;
  4246. case FALCON_LEVEL5k:
  4247. if (cm->minFalconKeySz < 0 ||
  4248. FALCON_LEVEL5_KEY_SIZE < (word16)cm->minFalconKeySz) {
  4249. ret = FALCON_KEY_SIZE_E;
  4250. WOLFSSL_MSG("\tCA Falcon level 5 key size error");
  4251. }
  4252. break;
  4253. #endif /* HAVE_FALCON */
  4254. #if defined(HAVE_DILITHIUM)
  4255. case DILITHIUM_LEVEL2k:
  4256. case DILITHIUM_AES_LEVEL2k:
  4257. if (cm->minDilithiumKeySz < 0 ||
  4258. DILITHIUM_LEVEL2_KEY_SIZE < (word16)cm->minDilithiumKeySz) {
  4259. ret = DILITHIUM_KEY_SIZE_E;
  4260. WOLFSSL_MSG("\tCA Dilithium level 2 key size error");
  4261. }
  4262. break;
  4263. case DILITHIUM_LEVEL3k:
  4264. case DILITHIUM_AES_LEVEL3k:
  4265. if (cm->minDilithiumKeySz < 0 ||
  4266. DILITHIUM_LEVEL3_KEY_SIZE < (word16)cm->minDilithiumKeySz) {
  4267. ret = DILITHIUM_KEY_SIZE_E;
  4268. WOLFSSL_MSG("\tCA Dilithium level 3 key size error");
  4269. }
  4270. break;
  4271. case DILITHIUM_LEVEL5k:
  4272. case DILITHIUM_AES_LEVEL5k:
  4273. if (cm->minDilithiumKeySz < 0 ||
  4274. DILITHIUM_LEVEL5_KEY_SIZE < (word16)cm->minDilithiumKeySz) {
  4275. ret = DILITHIUM_KEY_SIZE_E;
  4276. WOLFSSL_MSG("\tCA Dilithium level 5 key size error");
  4277. }
  4278. break;
  4279. #endif /* HAVE_DILITHIUM */
  4280. #endif /* HAVE_PQC */
  4281. default:
  4282. WOLFSSL_MSG("\tNo key size check done on CA");
  4283. break; /* no size check if key type is not in switch */
  4284. }
  4285. }
  4286. if (ret == 0 && cert->isCA == 0 && type != WOLFSSL_USER_CA) {
  4287. WOLFSSL_MSG("\tCan't add as CA if not actually one");
  4288. ret = NOT_CA_ERROR;
  4289. }
  4290. #ifndef ALLOW_INVALID_CERTSIGN
  4291. else if (ret == 0 && cert->isCA == 1 && type != WOLFSSL_USER_CA &&
  4292. !cert->selfSigned && (cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) == 0) {
  4293. /* Intermediate CA certs are required to have the keyCertSign
  4294. * extension set. User loaded root certs are not. */
  4295. WOLFSSL_MSG("\tDoesn't have key usage certificate signing");
  4296. ret = NOT_CA_ERROR;
  4297. }
  4298. #endif
  4299. else if (ret == 0 && AlreadySigner(cm, subjectHash)) {
  4300. WOLFSSL_MSG("\tAlready have this CA, not adding again");
  4301. (void)ret;
  4302. }
  4303. else if (ret == 0) {
  4304. /* take over signer parts */
  4305. signer = MakeSigner(cm->heap);
  4306. if (!signer)
  4307. ret = MEMORY_ERROR;
  4308. }
  4309. if (ret == 0 && signer != NULL) {
  4310. #ifdef WOLFSSL_SIGNER_DER_CERT
  4311. ret = AllocDer(&signer->derCert, der->length, der->type, NULL);
  4312. }
  4313. if (ret == 0 && signer != NULL) {
  4314. XMEMCPY(signer->derCert->buffer, der->buffer, der->length);
  4315. #endif
  4316. signer->keyOID = cert->keyOID;
  4317. if (cert->pubKeyStored) {
  4318. signer->publicKey = cert->publicKey;
  4319. signer->pubKeySize = cert->pubKeySize;
  4320. }
  4321. if (cert->subjectCNStored) {
  4322. signer->nameLen = cert->subjectCNLen;
  4323. signer->name = cert->subjectCN;
  4324. }
  4325. signer->pathLength = cert->pathLength;
  4326. signer->maxPathLen = cert->maxPathLen;
  4327. signer->pathLengthSet = cert->pathLengthSet;
  4328. signer->selfSigned = cert->selfSigned;
  4329. #ifndef IGNORE_NAME_CONSTRAINTS
  4330. signer->permittedNames = cert->permittedNames;
  4331. signer->excludedNames = cert->excludedNames;
  4332. #endif
  4333. #ifndef NO_SKID
  4334. XMEMCPY(signer->subjectKeyIdHash, cert->extSubjKeyId,
  4335. SIGNER_DIGEST_SIZE);
  4336. #endif
  4337. XMEMCPY(signer->subjectNameHash, cert->subjectHash,
  4338. SIGNER_DIGEST_SIZE);
  4339. #ifdef HAVE_OCSP
  4340. XMEMCPY(signer->subjectKeyHash, cert->subjectKeyHash,
  4341. KEYID_SIZE);
  4342. #endif
  4343. signer->keyUsage = cert->extKeyUsageSet ? cert->extKeyUsage
  4344. : 0xFFFF;
  4345. signer->next = NULL; /* If Key Usage not set, all uses valid. */
  4346. cert->publicKey = 0; /* in case lock fails don't free here. */
  4347. cert->subjectCN = 0;
  4348. #ifndef IGNORE_NAME_CONSTRAINTS
  4349. cert->permittedNames = NULL;
  4350. cert->excludedNames = NULL;
  4351. #endif
  4352. #ifndef NO_SKID
  4353. row = HashSigner(signer->subjectKeyIdHash);
  4354. #else
  4355. row = HashSigner(signer->subjectNameHash);
  4356. #endif
  4357. if (wc_LockMutex(&cm->caLock) == 0) {
  4358. signer->next = cm->caTable[row];
  4359. cm->caTable[row] = signer; /* takes ownership */
  4360. wc_UnLockMutex(&cm->caLock);
  4361. if (cm->caCacheCallback)
  4362. cm->caCacheCallback(der->buffer, (int)der->length, type);
  4363. }
  4364. else {
  4365. WOLFSSL_MSG("\tCA Mutex Lock failed");
  4366. ret = BAD_MUTEX_E;
  4367. FreeSigner(signer, cm->heap);
  4368. }
  4369. }
  4370. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  4371. /* Verify CA by TSIP so that generated tsip key is going to be able to */
  4372. /* be used for peer's cert verification */
  4373. /* TSIP is only able to handle USER CA, and only one CA. */
  4374. /* Therefore, it doesn't need to call TSIP again if there is already */
  4375. /* verified CA. */
  4376. if ( ret == 0 && signer != NULL ) {
  4377. signer->cm_idx = row;
  4378. if (type == WOLFSSL_USER_CA) {
  4379. if ((ret = wc_Renesas_cmn_RootCertVerify(cert->source, cert->maxIdx,
  4380. cert->sigCtx.CertAtt.pubkey_n_start,
  4381. cert->sigCtx.CertAtt.pubkey_n_len - 1,
  4382. cert->sigCtx.CertAtt.pubkey_e_start,
  4383. cert->sigCtx.CertAtt.pubkey_e_len - 1,
  4384. row/* cm index */))
  4385. < 0)
  4386. WOLFSSL_MSG("Renesas_RootCertVerify() failed");
  4387. else
  4388. WOLFSSL_MSG("Renesas_RootCertVerify() succeed or skipped");
  4389. }
  4390. }
  4391. #endif /* TSIP or SCE */
  4392. WOLFSSL_MSG("\tFreeing Parsed CA");
  4393. FreeDecodedCert(cert);
  4394. #ifdef WOLFSSL_SMALL_STACK
  4395. XFREE(cert, NULL, DYNAMIC_TYPE_DCERT);
  4396. #endif
  4397. WOLFSSL_MSG("\tFreeing der CA");
  4398. FreeDer(pDer);
  4399. WOLFSSL_MSG("\t\tOK Freeing der CA");
  4400. WOLFSSL_LEAVE("AddCA", ret);
  4401. return ret == 0 ? WOLFSSL_SUCCESS : ret;
  4402. }
  4403. #endif /* !NO_CERTS */
  4404. #ifndef NO_SESSION_CACHE
  4405. /* basic config gives a cache with 33 sessions, adequate for clients and
  4406. embedded servers
  4407. TITAN_SESSION_CACHE allows just over 2 million sessions, for servers
  4408. with titanic amounts of memory with long session ID timeouts and high
  4409. levels of traffic.
  4410. ENABLE_SESSION_CACHE_ROW_LOCK: Allows row level locking for increased
  4411. performance with large session caches
  4412. HUGE_SESSION_CACHE yields 65,791 sessions, for servers under heavy load,
  4413. allows over 13,000 new sessions per minute or over 200 new sessions per
  4414. second
  4415. BIG_SESSION_CACHE yields 20,027 sessions
  4416. MEDIUM_SESSION_CACHE allows 1055 sessions, adequate for servers that
  4417. aren't under heavy load, basically allows 200 new sessions per minute
  4418. SMALL_SESSION_CACHE only stores 6 sessions, good for embedded clients
  4419. or systems where the default of nearly 3kB is too much RAM, this define
  4420. uses less than 500 bytes RAM
  4421. default SESSION_CACHE stores 33 sessions (no XXX_SESSION_CACHE defined)
  4422. */
  4423. #if defined(TITAN_SESSION_CACHE)
  4424. #define SESSIONS_PER_ROW 31
  4425. #define SESSION_ROWS 64937
  4426. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  4427. #define ENABLE_SESSION_CACHE_ROW_LOCK
  4428. #endif
  4429. #elif defined(HUGE_SESSION_CACHE)
  4430. #define SESSIONS_PER_ROW 11
  4431. #define SESSION_ROWS 5981
  4432. #elif defined(BIG_SESSION_CACHE)
  4433. #define SESSIONS_PER_ROW 7
  4434. #define SESSION_ROWS 2861
  4435. #elif defined(MEDIUM_SESSION_CACHE)
  4436. #define SESSIONS_PER_ROW 5
  4437. #define SESSION_ROWS 211
  4438. #elif defined(SMALL_SESSION_CACHE)
  4439. #define SESSIONS_PER_ROW 2
  4440. #define SESSION_ROWS 3
  4441. #else
  4442. #define SESSIONS_PER_ROW 3
  4443. #define SESSION_ROWS 11
  4444. #endif
  4445. #define INVALID_SESSION_ROW (-1)
  4446. #ifdef NO_SESSION_CACHE_ROW_LOCK
  4447. #undef ENABLE_SESSION_CACHE_ROW_LOCK
  4448. #endif
  4449. typedef struct SessionRow {
  4450. int nextIdx; /* where to place next one */
  4451. int totalCount; /* sessions ever on this row */
  4452. WOLFSSL_SESSION Sessions[SESSIONS_PER_ROW];
  4453. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  4454. /* not included in import/export */
  4455. wolfSSL_Mutex row_mutex;
  4456. int mutex_valid;
  4457. #endif
  4458. } SessionRow;
  4459. #define SIZEOF_SESSION_ROW (sizeof(WOLFSSL_SESSION) + (sizeof(int) * 2))
  4460. static WOLFSSL_GLOBAL SessionRow SessionCache[SESSION_ROWS];
  4461. #if defined(WOLFSSL_SESSION_STATS) && defined(WOLFSSL_PEAK_SESSIONS)
  4462. static WOLFSSL_GLOBAL word32 PeakSessions;
  4463. #endif
  4464. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  4465. #define SESSION_ROW_LOCK(row) wc_LockMutex(&(row)->row_mutex)
  4466. #define SESSION_ROW_UNLOCK(row) wc_UnLockMutex(&(row)->row_mutex);
  4467. #else
  4468. static WOLFSSL_GLOBAL wolfSSL_Mutex session_mutex; /* SessionCache mutex */
  4469. static WOLFSSL_GLOBAL int session_mutex_valid = 0;
  4470. #define SESSION_ROW_LOCK(row) wc_LockMutex(&session_mutex)
  4471. #define SESSION_ROW_UNLOCK(row) wc_UnLockMutex(&session_mutex);
  4472. #endif
  4473. #if !defined(NO_SESSION_CACHE_REF) && defined(NO_CLIENT_CACHE)
  4474. #error ClientCache is required when not using NO_SESSION_CACHE_REF
  4475. #endif
  4476. #ifndef NO_CLIENT_CACHE
  4477. #ifndef CLIENT_SESSIONS_MULTIPLIER
  4478. #ifdef NO_SESSION_CACHE_REF
  4479. #define CLIENT_SESSIONS_MULTIPLIER 1
  4480. #else
  4481. /* ClientSession objects are lightweight (compared to
  4482. * WOLFSSL_SESSION) so to decrease chance that user will reuse
  4483. * thse wrong session, increase the ClientCache size. This will
  4484. * make the entire ClientCache about the size of one
  4485. * WOLFSSL_SESSION object. */
  4486. #define CLIENT_SESSIONS_MULTIPLIER 8
  4487. #endif
  4488. #endif
  4489. #define CLIENT_SESSIONS_PER_ROW \
  4490. (SESSIONS_PER_ROW * CLIENT_SESSIONS_MULTIPLIER)
  4491. #define CLIENT_SESSION_ROWS (SESSION_ROWS * CLIENT_SESSIONS_MULTIPLIER)
  4492. #if CLIENT_SESSIONS_PER_ROW > 65535
  4493. #error CLIENT_SESSIONS_PER_ROW too big
  4494. #endif
  4495. #if CLIENT_SESSION_ROWS > 65535
  4496. #error CLIENT_SESSION_ROWS too big
  4497. #endif
  4498. struct ClientSession {
  4499. word16 serverRow; /* SessionCache Row id */
  4500. word16 serverIdx; /* SessionCache Idx (column) */
  4501. word32 sessionIDHash;
  4502. };
  4503. #ifndef WOLFSSL_CLIENT_SESSION_DEFINED
  4504. typedef struct ClientSession ClientSession;
  4505. #define WOLFSSL_CLIENT_SESSION_DEFINED
  4506. #endif
  4507. typedef struct ClientRow {
  4508. int nextIdx; /* where to place next one */
  4509. int totalCount; /* sessions ever on this row */
  4510. ClientSession Clients[CLIENT_SESSIONS_PER_ROW];
  4511. } ClientRow;
  4512. static WOLFSSL_GLOBAL ClientRow ClientCache[CLIENT_SESSION_ROWS];
  4513. /* Client Cache */
  4514. /* uses session mutex */
  4515. static WOLFSSL_GLOBAL wolfSSL_Mutex clisession_mutex; /* ClientCache mutex */
  4516. static WOLFSSL_GLOBAL int clisession_mutex_valid = 0;
  4517. #endif /* !NO_CLIENT_CACHE */
  4518. #endif /* !NO_SESSION_CACHE */
  4519. #if !defined(WC_NO_RNG) && (defined(OPENSSL_EXTRA) || \
  4520. (defined(OPENSSL_EXTRA_X509_SMALL) && !defined(NO_RSA)))
  4521. #define HAVE_GLOBAL_RNG /* consolidate flags for using globalRNG */
  4522. static WC_RNG globalRNG;
  4523. static int initGlobalRNG = 0;
  4524. static wolfSSL_Mutex globalRNGMutex;
  4525. static int globalRNGMutex_valid = 0;
  4526. #if defined(OPENSSL_EXTRA) && defined(HAVE_HASHDRBG)
  4527. static WOLFSSL_DRBG_CTX* gDrbgDefCtx = NULL;
  4528. #endif
  4529. WC_RNG* wolfssl_get_global_rng(void)
  4530. {
  4531. WC_RNG* ret = NULL;
  4532. if (initGlobalRNG == 0)
  4533. WOLFSSL_MSG("Global RNG no Init");
  4534. else
  4535. ret = &globalRNG;
  4536. return ret;
  4537. }
  4538. #endif
  4539. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB)
  4540. static int wolfSSL_RAND_InitMutex(void);
  4541. #endif
  4542. #if defined(OPENSSL_EXTRA) && defined(HAVE_ATEXIT)
  4543. static void AtExitCleanup(void)
  4544. {
  4545. if (initRefCount > 0) {
  4546. initRefCount = 1;
  4547. (void)wolfSSL_Cleanup();
  4548. }
  4549. }
  4550. #endif
  4551. WOLFSSL_ABI
  4552. int wolfSSL_Init(void)
  4553. {
  4554. int ret = WOLFSSL_SUCCESS;
  4555. #if !defined(NO_SESSION_CACHE) && defined(ENABLE_SESSION_CACHE_ROW_LOCK)
  4556. int i;
  4557. #endif
  4558. WOLFSSL_ENTER("wolfSSL_Init");
  4559. #if FIPS_VERSION_GE(5,1)
  4560. ret = wolfCrypt_SetPrivateKeyReadEnable_fips(1, WC_KEYTYPE_ALL);
  4561. if (ret != 0)
  4562. return ret;
  4563. else
  4564. ret = WOLFSSL_SUCCESS;
  4565. #endif
  4566. if (initRefCount == 0) {
  4567. /* Initialize crypto for use with TLS connection */
  4568. if (wolfCrypt_Init() != 0) {
  4569. WOLFSSL_MSG("Bad wolfCrypt Init");
  4570. ret = WC_INIT_E;
  4571. }
  4572. #ifdef HAVE_GLOBAL_RNG
  4573. if (ret == WOLFSSL_SUCCESS) {
  4574. if (wc_InitMutex(&globalRNGMutex) != 0) {
  4575. WOLFSSL_MSG("Bad Init Mutex rng");
  4576. ret = BAD_MUTEX_E;
  4577. }
  4578. else {
  4579. globalRNGMutex_valid = 1;
  4580. }
  4581. }
  4582. #endif
  4583. #ifdef WC_RNG_SEED_CB
  4584. wc_SetSeed_Cb(wc_GenerateSeed);
  4585. #endif
  4586. #ifdef OPENSSL_EXTRA
  4587. #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
  4588. if ((ret == WOLFSSL_SUCCESS) && (wolfSSL_RAND_InitMutex() != 0)) {
  4589. ret = BAD_MUTEX_E;
  4590. }
  4591. #endif
  4592. if ((ret == WOLFSSL_SUCCESS) &&
  4593. (wolfSSL_RAND_seed(NULL, 0) != WOLFSSL_SUCCESS)) {
  4594. WOLFSSL_MSG("wolfSSL_RAND_Seed failed");
  4595. ret = WC_INIT_E;
  4596. }
  4597. #endif
  4598. #ifndef NO_SESSION_CACHE
  4599. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  4600. for (i = 0; i < SESSION_ROWS; ++i) {
  4601. SessionCache[i].mutex_valid = 0;
  4602. }
  4603. for (i = 0; (ret == WOLFSSL_SUCCESS) && (i < SESSION_ROWS); ++i) {
  4604. if (wc_InitMutex(&SessionCache[i].row_mutex) != 0) {
  4605. WOLFSSL_MSG("Bad Init Mutex session");
  4606. ret = BAD_MUTEX_E;
  4607. }
  4608. else {
  4609. SessionCache[i].mutex_valid = 1;
  4610. }
  4611. }
  4612. #else
  4613. if (ret == WOLFSSL_SUCCESS) {
  4614. if (wc_InitMutex(&session_mutex) != 0) {
  4615. WOLFSSL_MSG("Bad Init Mutex session");
  4616. ret = BAD_MUTEX_E;
  4617. }
  4618. else {
  4619. session_mutex_valid = 1;
  4620. }
  4621. }
  4622. #endif
  4623. #ifndef NO_CLIENT_CACHE
  4624. if (ret == WOLFSSL_SUCCESS) {
  4625. if (wc_InitMutex(&clisession_mutex) != 0) {
  4626. WOLFSSL_MSG("Bad Init Mutex session");
  4627. ret = BAD_MUTEX_E;
  4628. }
  4629. else {
  4630. clisession_mutex_valid = 1;
  4631. }
  4632. }
  4633. #endif
  4634. #endif
  4635. if (ret == WOLFSSL_SUCCESS) {
  4636. if (wc_InitMutex(&count_mutex) != 0) {
  4637. WOLFSSL_MSG("Bad Init Mutex count");
  4638. ret = BAD_MUTEX_E;
  4639. }
  4640. else {
  4641. count_mutex_valid = 1;
  4642. }
  4643. }
  4644. #if defined(OPENSSL_EXTRA) && defined(HAVE_ATEXIT)
  4645. /* OpenSSL registers cleanup using atexit */
  4646. if ((ret == WOLFSSL_SUCCESS) && (atexit(AtExitCleanup) != 0)) {
  4647. WOLFSSL_MSG("Bad atexit registration");
  4648. ret = WC_INIT_E;
  4649. }
  4650. #endif
  4651. }
  4652. if (ret == WOLFSSL_SUCCESS) {
  4653. if (wc_LockMutex(&count_mutex) != 0) {
  4654. WOLFSSL_MSG("Bad Lock Mutex count");
  4655. ret = BAD_MUTEX_E;
  4656. }
  4657. else {
  4658. initRefCount++;
  4659. wc_UnLockMutex(&count_mutex);
  4660. }
  4661. }
  4662. if (ret != WOLFSSL_SUCCESS) {
  4663. initRefCount = 1; /* Force cleanup */
  4664. (void)wolfSSL_Cleanup(); /* Ignore any error from cleanup */
  4665. }
  4666. return ret;
  4667. }
  4668. #ifndef NO_CERTS
  4669. /* process user cert chain to pass during the handshake */
  4670. static int ProcessUserChain(WOLFSSL_CTX* ctx, const unsigned char* buff,
  4671. long sz, int format, int type, WOLFSSL* ssl,
  4672. long* used, EncryptedInfo* info, int verify)
  4673. {
  4674. int ret = 0;
  4675. void* heap = wolfSSL_CTX_GetHeap(ctx, ssl);
  4676. #ifdef WOLFSSL_TLS13
  4677. int cnt = 0;
  4678. #endif
  4679. if ((type == CA_TYPE) && (ctx == NULL)) {
  4680. WOLFSSL_MSG("Need context for CA load");
  4681. return BAD_FUNC_ARG;
  4682. }
  4683. /* we may have a user cert chain, try to consume */
  4684. if ((type == CERT_TYPE || type == CA_TYPE) && (info->consumed < sz)) {
  4685. #ifdef WOLFSSL_SMALL_STACK
  4686. byte staticBuffer[1]; /* force heap usage */
  4687. #else
  4688. byte staticBuffer[FILE_BUFFER_SIZE]; /* tmp chain buffer */
  4689. #endif
  4690. byte* chainBuffer = staticBuffer;
  4691. int dynamicBuffer = 0;
  4692. word32 bufferSz;
  4693. long consumed = info->consumed;
  4694. word32 idx = 0;
  4695. int gotOne = 0;
  4696. /* Calculate max possible size, including max headers */
  4697. bufferSz = (word32)(sz - consumed) + (CERT_HEADER_SZ * MAX_CHAIN_DEPTH);
  4698. if (bufferSz > sizeof(staticBuffer)) {
  4699. WOLFSSL_MSG("Growing Tmp Chain Buffer");
  4700. /* will shrink to actual size */
  4701. chainBuffer = (byte*)XMALLOC(bufferSz, heap, DYNAMIC_TYPE_FILE);
  4702. if (chainBuffer == NULL) {
  4703. return MEMORY_E;
  4704. }
  4705. dynamicBuffer = 1;
  4706. }
  4707. WOLFSSL_MSG("Processing Cert Chain");
  4708. while (consumed < sz) {
  4709. DerBuffer* part = NULL;
  4710. word32 remain = (word32)(sz - consumed);
  4711. info->consumed = 0;
  4712. if (format == WOLFSSL_FILETYPE_PEM) {
  4713. #ifdef WOLFSSL_PEM_TO_DER
  4714. ret = PemToDer(buff + consumed, remain, type, &part,
  4715. heap, info, NULL);
  4716. #else
  4717. ret = NOT_COMPILED_IN;
  4718. #endif
  4719. }
  4720. else {
  4721. int length = remain;
  4722. if (format == WOLFSSL_FILETYPE_ASN1) {
  4723. /* get length of der (read sequence) */
  4724. word32 inOutIdx = 0;
  4725. if (GetSequence(buff + consumed, &inOutIdx, &length,
  4726. remain) < 0) {
  4727. ret = ASN_NO_PEM_HEADER;
  4728. }
  4729. length += inOutIdx; /* include leading sequence */
  4730. }
  4731. info->consumed = length;
  4732. if (ret == 0) {
  4733. ret = AllocDer(&part, length, type, heap);
  4734. if (ret == 0) {
  4735. XMEMCPY(part->buffer, buff + consumed, length);
  4736. }
  4737. }
  4738. }
  4739. if (ret == 0) {
  4740. gotOne = 1;
  4741. #ifdef WOLFSSL_TLS13
  4742. cnt++;
  4743. #endif
  4744. if ((idx + part->length + CERT_HEADER_SZ) > bufferSz) {
  4745. WOLFSSL_MSG(" Cert Chain bigger than buffer. "
  4746. "Consider increasing MAX_CHAIN_DEPTH");
  4747. ret = BUFFER_E;
  4748. }
  4749. else {
  4750. c32to24(part->length, &chainBuffer[idx]);
  4751. idx += CERT_HEADER_SZ;
  4752. XMEMCPY(&chainBuffer[idx], part->buffer, part->length);
  4753. idx += part->length;
  4754. consumed += info->consumed;
  4755. if (used)
  4756. *used += info->consumed;
  4757. }
  4758. /* add CA's to certificate manager */
  4759. if (ret == 0 && type == CA_TYPE) {
  4760. /* verify CA unless user set to no verify */
  4761. ret = AddCA(ctx->cm, &part, WOLFSSL_USER_CA, verify);
  4762. if (ret == WOLFSSL_SUCCESS) {
  4763. ret = 0; /* converted success case */
  4764. }
  4765. gotOne = 0; /* don't exit loop for CA type */
  4766. }
  4767. }
  4768. FreeDer(&part);
  4769. if (ret == ASN_NO_PEM_HEADER && gotOne) {
  4770. WOLFSSL_MSG("We got one good cert, so stuff at end ok");
  4771. break;
  4772. }
  4773. if (ret < 0) {
  4774. WOLFSSL_MSG(" Error in Cert in Chain");
  4775. if (dynamicBuffer)
  4776. XFREE(chainBuffer, heap, DYNAMIC_TYPE_FILE);
  4777. return ret;
  4778. }
  4779. WOLFSSL_MSG(" Consumed another Cert in Chain");
  4780. }
  4781. WOLFSSL_MSG("Finished Processing Cert Chain");
  4782. /* only retain actual size used */
  4783. ret = 0;
  4784. if (idx > 0) {
  4785. if (ssl) {
  4786. if (ssl->buffers.weOwnCertChain) {
  4787. FreeDer(&ssl->buffers.certChain);
  4788. }
  4789. ret = AllocDer(&ssl->buffers.certChain, idx, type, heap);
  4790. if (ret == 0) {
  4791. XMEMCPY(ssl->buffers.certChain->buffer, chainBuffer,
  4792. idx);
  4793. ssl->buffers.weOwnCertChain = 1;
  4794. }
  4795. #ifdef WOLFSSL_TLS13
  4796. ssl->buffers.certChainCnt = cnt;
  4797. #endif
  4798. } else if (ctx) {
  4799. FreeDer(&ctx->certChain);
  4800. ret = AllocDer(&ctx->certChain, idx, type, heap);
  4801. if (ret == 0) {
  4802. XMEMCPY(ctx->certChain->buffer, chainBuffer, idx);
  4803. }
  4804. #ifdef WOLFSSL_TLS13
  4805. ctx->certChainCnt = cnt;
  4806. #endif
  4807. }
  4808. }
  4809. if (dynamicBuffer)
  4810. XFREE(chainBuffer, heap, DYNAMIC_TYPE_FILE);
  4811. }
  4812. return ret;
  4813. }
  4814. static int ProcessBufferTryDecode(WOLFSSL_CTX* ctx, WOLFSSL* ssl, DerBuffer* der,
  4815. int* keySz, word32* idx, int* resetSuites, int* keyFormat, void* heap, int devId)
  4816. {
  4817. int ret = 0;
  4818. (void)heap;
  4819. (void)devId;
  4820. if (ctx == NULL && ssl == NULL)
  4821. return BAD_FUNC_ARG;
  4822. if (!der || !keySz || !idx || !resetSuites || !keyFormat)
  4823. return BAD_FUNC_ARG;
  4824. #ifndef NO_RSA
  4825. if ((*keyFormat == 0 || *keyFormat == RSAk)) {
  4826. /* make sure RSA key can be used */
  4827. #ifdef WOLFSSL_SMALL_STACK
  4828. RsaKey* key;
  4829. #else
  4830. RsaKey key[1];
  4831. #endif
  4832. #ifdef WOLFSSL_SMALL_STACK
  4833. key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA);
  4834. if (key == NULL)
  4835. return MEMORY_E;
  4836. #endif
  4837. ret = wc_InitRsaKey_ex(key, heap, devId);
  4838. if (ret == 0) {
  4839. *idx = 0;
  4840. ret = wc_RsaPrivateKeyDecode(der->buffer, idx, key, der->length);
  4841. #ifdef WOLF_PRIVATE_KEY_ID
  4842. if (ret != 0 && (devId != INVALID_DEVID
  4843. #ifdef HAVE_PK_CALLBACKS
  4844. || wolfSSL_CTX_IsPrivatePkSet(ctx)
  4845. #endif
  4846. )) {
  4847. /* if using crypto or PK callbacks, try public key decode */
  4848. *idx = 0;
  4849. ret = wc_RsaPublicKeyDecode(der->buffer, idx, key, der->length);
  4850. }
  4851. #endif
  4852. if (ret != 0) {
  4853. #if !defined(HAVE_ECC) && !defined(HAVE_ED25519) && \
  4854. !defined(HAVE_ED448) && !defined(HAVE_PQC)
  4855. WOLFSSL_MSG("RSA decode failed and other algorithms "
  4856. "not enabled to try");
  4857. ret = WOLFSSL_BAD_FILE;
  4858. #else
  4859. ret = 0; /* continue trying other algorithms */
  4860. #endif
  4861. }
  4862. else {
  4863. /* check that the size of the RSA key is enough */
  4864. int minRsaSz = ssl ? ssl->options.minRsaKeySz :
  4865. ctx->minRsaKeySz;
  4866. *keySz = wc_RsaEncryptSize((RsaKey*)key);
  4867. if (*keySz < minRsaSz) {
  4868. ret = RSA_KEY_SIZE_E;
  4869. WOLFSSL_MSG("Private Key size too small");
  4870. }
  4871. if (ssl) {
  4872. ssl->buffers.keyType = rsa_sa_algo;
  4873. ssl->buffers.keySz = *keySz;
  4874. }
  4875. else {
  4876. ctx->privateKeyType = rsa_sa_algo;
  4877. ctx->privateKeySz = *keySz;
  4878. }
  4879. *keyFormat = RSAk;
  4880. if (ssl && ssl->options.side == WOLFSSL_SERVER_END) {
  4881. ssl->options.haveStaticECC = 0;
  4882. *resetSuites = 1;
  4883. }
  4884. }
  4885. wc_FreeRsaKey(key);
  4886. }
  4887. #ifdef WOLFSSL_SMALL_STACK
  4888. XFREE(key, heap, DYNAMIC_TYPE_RSA);
  4889. #endif
  4890. if (ret != 0)
  4891. return ret;
  4892. }
  4893. #endif
  4894. #ifdef HAVE_ECC
  4895. if ((*keyFormat == 0 || *keyFormat == ECDSAk)) {
  4896. /* make sure ECC key can be used */
  4897. #ifdef WOLFSSL_SMALL_STACK
  4898. ecc_key* key;
  4899. #else
  4900. ecc_key key[1];
  4901. #endif
  4902. #ifdef WOLFSSL_SMALL_STACK
  4903. key = (ecc_key*)XMALLOC(sizeof(ecc_key), heap, DYNAMIC_TYPE_ECC);
  4904. if (key == NULL)
  4905. return MEMORY_E;
  4906. #endif
  4907. if (wc_ecc_init_ex(key, heap, devId) == 0) {
  4908. *idx = 0;
  4909. ret = wc_EccPrivateKeyDecode(der->buffer, idx, key, der->length);
  4910. #ifdef WOLF_PRIVATE_KEY_ID
  4911. if (ret != 0 && (devId != INVALID_DEVID
  4912. #ifdef HAVE_PK_CALLBACKS
  4913. || wolfSSL_CTX_IsPrivatePkSet(ctx)
  4914. #endif
  4915. )) {
  4916. /* if using crypto or PK callbacks, try public key decode */
  4917. *idx = 0;
  4918. ret = wc_EccPublicKeyDecode(der->buffer, idx, key, der->length);
  4919. }
  4920. #endif
  4921. if (ret == 0) {
  4922. /* check for minimum ECC key size and then free */
  4923. int minKeySz = ssl ? ssl->options.minEccKeySz :
  4924. ctx->minEccKeySz;
  4925. *keySz = wc_ecc_size(key);
  4926. if (*keySz < minKeySz) {
  4927. WOLFSSL_MSG("ECC private key too small");
  4928. ret = ECC_KEY_SIZE_E;
  4929. }
  4930. *keyFormat = ECDSAk;
  4931. if (ssl) {
  4932. ssl->options.haveStaticECC = 1;
  4933. ssl->buffers.keyType = ecc_dsa_sa_algo;
  4934. ssl->buffers.keySz = *keySz;
  4935. }
  4936. else {
  4937. ctx->haveStaticECC = 1;
  4938. ctx->privateKeyType = ecc_dsa_sa_algo;
  4939. ctx->privateKeySz = *keySz;
  4940. }
  4941. if (ssl && ssl->options.side == WOLFSSL_SERVER_END) {
  4942. *resetSuites = 1;
  4943. }
  4944. }
  4945. else {
  4946. ret = 0; /* continue trying other algorithms */
  4947. }
  4948. wc_ecc_free(key);
  4949. }
  4950. #ifdef WOLFSSL_SMALL_STACK
  4951. XFREE(key, heap, DYNAMIC_TYPE_ECC);
  4952. #endif
  4953. if (ret != 0)
  4954. return ret;
  4955. }
  4956. #endif /* HAVE_ECC */
  4957. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  4958. if ((*keyFormat == 0 || *keyFormat == ED25519k)) {
  4959. /* make sure Ed25519 key can be used */
  4960. #ifdef WOLFSSL_SMALL_STACK
  4961. ed25519_key* key;
  4962. #else
  4963. ed25519_key key[1];
  4964. #endif
  4965. #ifdef WOLFSSL_SMALL_STACK
  4966. key = (ed25519_key*)XMALLOC(sizeof(ed25519_key), heap,
  4967. DYNAMIC_TYPE_ED25519);
  4968. if (key == NULL)
  4969. return MEMORY_E;
  4970. #endif
  4971. ret = wc_ed25519_init_ex(key, heap, devId);
  4972. if (ret == 0) {
  4973. *idx = 0;
  4974. ret = wc_Ed25519PrivateKeyDecode(der->buffer, idx, key, der->length);
  4975. #ifdef WOLF_PRIVATE_KEY_ID
  4976. if (ret != 0 && (devId != INVALID_DEVID
  4977. #ifdef HAVE_PK_CALLBACKS
  4978. || wolfSSL_CTX_IsPrivatePkSet(ctx)
  4979. #endif
  4980. )) {
  4981. /* if using crypto or PK callbacks, try public key decode */
  4982. *idx = 0;
  4983. ret = wc_Ed25519PublicKeyDecode(der->buffer, idx, key,
  4984. der->length);
  4985. }
  4986. #endif
  4987. if (ret == 0) {
  4988. /* check for minimum key size and then free */
  4989. int minKeySz = ssl ? ssl->options.minEccKeySz :
  4990. ctx->minEccKeySz;
  4991. *keySz = ED25519_KEY_SIZE;
  4992. if (*keySz < minKeySz) {
  4993. WOLFSSL_MSG("ED25519 private key too small");
  4994. ret = ECC_KEY_SIZE_E;
  4995. }
  4996. if (ret == 0) {
  4997. if (ssl) {
  4998. ssl->buffers.keyType = ed25519_sa_algo;
  4999. ssl->buffers.keySz = *keySz;
  5000. }
  5001. else if (ctx) {
  5002. ctx->privateKeyType = ed25519_sa_algo;
  5003. ctx->privateKeySz = *keySz;
  5004. }
  5005. *keyFormat = ED25519k;
  5006. if (ssl != NULL) {
  5007. /* ED25519 requires caching enabled for tracking message
  5008. * hash used in EdDSA_Update for signing */
  5009. ssl->options.cacheMessages = 1;
  5010. if (ssl->options.side == WOLFSSL_SERVER_END) {
  5011. *resetSuites = 1;
  5012. }
  5013. }
  5014. }
  5015. }
  5016. else {
  5017. ret = 0; /* continue trying other algorithms */
  5018. }
  5019. wc_ed25519_free(key);
  5020. }
  5021. #ifdef WOLFSSL_SMALL_STACK
  5022. XFREE(key, heap, DYNAMIC_TYPE_ED25519);
  5023. #endif
  5024. if (ret != 0)
  5025. return ret;
  5026. }
  5027. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */
  5028. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  5029. if ((*keyFormat == 0 || *keyFormat == ED448k)) {
  5030. /* make sure Ed448 key can be used */
  5031. #ifdef WOLFSSL_SMALL_STACK
  5032. ed448_key* key = NULL;
  5033. #else
  5034. ed448_key key[1];
  5035. #endif
  5036. #ifdef WOLFSSL_SMALL_STACK
  5037. key = (ed448_key*)XMALLOC(sizeof(ed448_key), heap, DYNAMIC_TYPE_ED448);
  5038. if (key == NULL)
  5039. return MEMORY_E;
  5040. #endif
  5041. ret = wc_ed448_init(key);
  5042. if (ret == 0) {
  5043. *idx = 0;
  5044. ret = wc_Ed448PrivateKeyDecode(der->buffer, idx, key, der->length);
  5045. #ifdef WOLF_PRIVATE_KEY_ID
  5046. if (ret != 0 && (devId != INVALID_DEVID
  5047. #ifdef HAVE_PK_CALLBACKS
  5048. || wolfSSL_CTX_IsPrivatePkSet(ctx)
  5049. #endif
  5050. )) {
  5051. /* if using crypto or PK callbacks, try public key decode */
  5052. *idx = 0;
  5053. ret = wc_Ed448PublicKeyDecode(der->buffer, idx, key,
  5054. der->length);
  5055. }
  5056. #endif
  5057. if (ret == 0) {
  5058. /* check for minimum key size and then free */
  5059. int minKeySz = ssl ? ssl->options.minEccKeySz :
  5060. ctx->minEccKeySz;
  5061. *keySz = ED448_KEY_SIZE;
  5062. if (*keySz < minKeySz) {
  5063. WOLFSSL_MSG("ED448 private key too small");
  5064. ret = ECC_KEY_SIZE_E;
  5065. }
  5066. }
  5067. if (ret == 0) {
  5068. if (ssl) {
  5069. ssl->buffers.keyType = ed448_sa_algo;
  5070. ssl->buffers.keySz = *keySz;
  5071. }
  5072. else if (ctx) {
  5073. ctx->privateKeyType = ed448_sa_algo;
  5074. ctx->privateKeySz = *keySz;
  5075. }
  5076. *keyFormat = ED448k;
  5077. if (ssl != NULL) {
  5078. /* ED448 requires caching enabled for tracking message
  5079. * hash used in EdDSA_Update for signing */
  5080. ssl->options.cacheMessages = 1;
  5081. if (ssl->options.side == WOLFSSL_SERVER_END) {
  5082. *resetSuites = 1;
  5083. }
  5084. }
  5085. }
  5086. wc_ed448_free(key);
  5087. }
  5088. #ifdef WOLFSSL_SMALL_STACK
  5089. XFREE(key, heap, DYNAMIC_TYPE_ED448);
  5090. #endif
  5091. if (ret != 0)
  5092. return ret;
  5093. }
  5094. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */
  5095. #if defined(HAVE_PQC)
  5096. #if defined(HAVE_FALCON)
  5097. if (((*keyFormat == 0) || (*keyFormat == FALCON_LEVEL1k) ||
  5098. (*keyFormat == FALCON_LEVEL5k))) {
  5099. /* make sure Falcon key can be used */
  5100. falcon_key* key = (falcon_key*)XMALLOC(sizeof(falcon_key), heap,
  5101. DYNAMIC_TYPE_FALCON);
  5102. if (key == NULL) {
  5103. return MEMORY_E;
  5104. }
  5105. ret = wc_falcon_init(key);
  5106. if (ret == 0) {
  5107. if (*keyFormat == FALCON_LEVEL1k) {
  5108. ret = wc_falcon_set_level(key, 1);
  5109. }
  5110. else if (*keyFormat == FALCON_LEVEL5k) {
  5111. ret = wc_falcon_set_level(key, 5);
  5112. }
  5113. else {
  5114. /* What if *keyformat is 0? We might want to do something more
  5115. * graceful here. */
  5116. wc_falcon_free(key);
  5117. ret = ALGO_ID_E;
  5118. }
  5119. }
  5120. if (ret == 0) {
  5121. *idx = 0;
  5122. ret = wc_falcon_import_private_only(der->buffer, der->length, key);
  5123. if (ret == 0) {
  5124. /* check for minimum key size and then free */
  5125. int minKeySz = ssl ? ssl->options.minFalconKeySz :
  5126. ctx->minFalconKeySz;
  5127. *keySz = FALCON_MAX_KEY_SIZE;
  5128. if (*keySz < minKeySz) {
  5129. WOLFSSL_MSG("Falcon private key too small");
  5130. ret = FALCON_KEY_SIZE_E;
  5131. }
  5132. if (ssl) {
  5133. if (*keyFormat == FALCON_LEVEL1k) {
  5134. ssl->buffers.keyType = falcon_level1_sa_algo;
  5135. }
  5136. else {
  5137. ssl->buffers.keyType = falcon_level5_sa_algo;
  5138. }
  5139. ssl->buffers.keySz = *keySz;
  5140. }
  5141. else {
  5142. if (*keyFormat == FALCON_LEVEL1k) {
  5143. ctx->privateKeyType = falcon_level1_sa_algo;
  5144. }
  5145. else {
  5146. ctx->privateKeyType = falcon_level5_sa_algo;
  5147. }
  5148. ctx->privateKeySz = *keySz;
  5149. }
  5150. if (ssl && ssl->options.side == WOLFSSL_SERVER_END) {
  5151. *resetSuites = 1;
  5152. }
  5153. }
  5154. wc_falcon_free(key);
  5155. }
  5156. XFREE(key, heap, DYNAMIC_TYPE_FALCON);
  5157. if (ret != 0)
  5158. return ret;
  5159. }
  5160. #endif /* HAVE_FALCON */
  5161. #if defined(HAVE_DILITHIUM)
  5162. if ((*keyFormat == 0) ||
  5163. (*keyFormat == DILITHIUM_LEVEL2k) ||
  5164. (*keyFormat == DILITHIUM_LEVEL3k) ||
  5165. (*keyFormat == DILITHIUM_LEVEL5k) ||
  5166. (*keyFormat == DILITHIUM_AES_LEVEL2k) ||
  5167. (*keyFormat == DILITHIUM_AES_LEVEL3k) ||
  5168. (*keyFormat == DILITHIUM_AES_LEVEL5k)) {
  5169. /* make sure Dilithium key can be used */
  5170. dilithium_key* key = (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  5171. heap,
  5172. DYNAMIC_TYPE_DILITHIUM);
  5173. if (key == NULL) {
  5174. return MEMORY_E;
  5175. }
  5176. ret = wc_dilithium_init(key);
  5177. if (ret == 0) {
  5178. if (*keyFormat == DILITHIUM_LEVEL2k) {
  5179. ret = wc_dilithium_set_level_and_sym(key, 2, SHAKE_VARIANT);
  5180. }
  5181. else if (*keyFormat == DILITHIUM_LEVEL3k) {
  5182. ret = wc_dilithium_set_level_and_sym(key, 3, SHAKE_VARIANT);
  5183. }
  5184. else if (*keyFormat == DILITHIUM_LEVEL5k) {
  5185. ret = wc_dilithium_set_level_and_sym(key, 5, SHAKE_VARIANT);
  5186. }
  5187. else if (*keyFormat == DILITHIUM_AES_LEVEL2k) {
  5188. ret = wc_dilithium_set_level_and_sym(key, 2, AES_VARIANT);
  5189. }
  5190. else if (*keyFormat == DILITHIUM_AES_LEVEL3k) {
  5191. ret = wc_dilithium_set_level_and_sym(key, 3, AES_VARIANT);
  5192. }
  5193. else if (*keyFormat == DILITHIUM_AES_LEVEL5k) {
  5194. ret = wc_dilithium_set_level_and_sym(key, 5, AES_VARIANT);
  5195. }
  5196. else {
  5197. /* What if *keyformat is 0? We might want to do something more
  5198. * graceful here. */
  5199. wc_dilithium_free(key);
  5200. ret = ALGO_ID_E;
  5201. }
  5202. }
  5203. if (ret == 0) {
  5204. *idx = 0;
  5205. ret = wc_dilithium_import_private_only(der->buffer, der->length,
  5206. key);
  5207. if (ret == 0) {
  5208. /* check for minimum key size and then free */
  5209. int minKeySz = ssl ? ssl->options.minDilithiumKeySz :
  5210. ctx->minDilithiumKeySz;
  5211. *keySz = DILITHIUM_MAX_KEY_SIZE;
  5212. if (*keySz < minKeySz) {
  5213. WOLFSSL_MSG("Dilithium private key too small");
  5214. ret = DILITHIUM_KEY_SIZE_E;
  5215. }
  5216. if (ssl) {
  5217. if (*keyFormat == DILITHIUM_LEVEL2k) {
  5218. ssl->buffers.keyType = dilithium_level2_sa_algo;
  5219. }
  5220. else if (*keyFormat == DILITHIUM_LEVEL3k) {
  5221. ssl->buffers.keyType = dilithium_level3_sa_algo;
  5222. }
  5223. else if (*keyFormat == DILITHIUM_LEVEL5k) {
  5224. ssl->buffers.keyType = dilithium_level5_sa_algo;
  5225. }
  5226. else if (*keyFormat == DILITHIUM_AES_LEVEL2k) {
  5227. ssl->buffers.keyType = dilithium_aes_level2_sa_algo;
  5228. }
  5229. else if (*keyFormat == DILITHIUM_AES_LEVEL3k) {
  5230. ssl->buffers.keyType = dilithium_aes_level3_sa_algo;
  5231. }
  5232. else if (*keyFormat == DILITHIUM_AES_LEVEL5k) {
  5233. ssl->buffers.keyType = dilithium_aes_level5_sa_algo;
  5234. }
  5235. ssl->buffers.keySz = *keySz;
  5236. }
  5237. else {
  5238. if (*keyFormat == DILITHIUM_LEVEL2k) {
  5239. ctx->privateKeyType = dilithium_level2_sa_algo;
  5240. }
  5241. else if (*keyFormat == DILITHIUM_LEVEL3k) {
  5242. ctx->privateKeyType = dilithium_level3_sa_algo;
  5243. }
  5244. else if (*keyFormat == DILITHIUM_LEVEL5k) {
  5245. ctx->privateKeyType = dilithium_level5_sa_algo;
  5246. }
  5247. else if (*keyFormat == DILITHIUM_AES_LEVEL2k) {
  5248. ctx->privateKeyType = dilithium_aes_level2_sa_algo;
  5249. }
  5250. else if (*keyFormat == DILITHIUM_AES_LEVEL3k) {
  5251. ctx->privateKeyType = dilithium_aes_level3_sa_algo;
  5252. }
  5253. else if (*keyFormat == DILITHIUM_AES_LEVEL5k) {
  5254. ctx->privateKeyType = dilithium_aes_level5_sa_algo;
  5255. }
  5256. ctx->privateKeySz = *keySz;
  5257. }
  5258. if (ssl && ssl->options.side == WOLFSSL_SERVER_END) {
  5259. *resetSuites = 1;
  5260. }
  5261. }
  5262. wc_dilithium_free(key);
  5263. }
  5264. XFREE(key, heap, DYNAMIC_TYPE_DILITHIUM);
  5265. if (ret != 0) {
  5266. return ret;
  5267. }
  5268. }
  5269. #endif /* HAVE_DILITHIUM */
  5270. #endif /* HAVE_PQC */
  5271. return ret;
  5272. }
  5273. /* process the buffer buff, length sz, into ctx of format and type
  5274. used tracks bytes consumed, userChain specifies a user cert chain
  5275. to pass during the handshake */
  5276. int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff,
  5277. long sz, int format, int type, WOLFSSL* ssl,
  5278. long* used, int userChain, int verify)
  5279. {
  5280. DerBuffer* der = NULL;
  5281. int ret = 0;
  5282. int done = 0;
  5283. int keyFormat = 0;
  5284. int resetSuites = 0;
  5285. void* heap = wolfSSL_CTX_GetHeap(ctx, ssl);
  5286. int devId = wolfSSL_CTX_GetDevId(ctx, ssl);
  5287. word32 idx = 0;
  5288. int keySz = 0;
  5289. #if (defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)) || \
  5290. defined(HAVE_PKCS8)
  5291. word32 algId = 0;
  5292. #endif
  5293. #ifdef WOLFSSL_SMALL_STACK
  5294. EncryptedInfo* info = NULL;
  5295. #else
  5296. EncryptedInfo info[1];
  5297. #endif
  5298. (void)devId;
  5299. (void)idx;
  5300. (void)keySz;
  5301. if (used)
  5302. *used = sz; /* used bytes default to sz, PEM chain may shorten*/
  5303. /* check args */
  5304. if (format != WOLFSSL_FILETYPE_ASN1 && format != WOLFSSL_FILETYPE_PEM)
  5305. return WOLFSSL_BAD_FILETYPE;
  5306. if (ctx == NULL && ssl == NULL)
  5307. return BAD_FUNC_ARG;
  5308. #ifdef WOLFSSL_SMALL_STACK
  5309. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), heap,
  5310. DYNAMIC_TYPE_ENCRYPTEDINFO);
  5311. if (info == NULL)
  5312. return MEMORY_E;
  5313. #endif
  5314. XMEMSET(info, 0, sizeof(EncryptedInfo));
  5315. #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)
  5316. if (ctx) {
  5317. info->passwd_cb = ctx->passwd_cb;
  5318. info->passwd_userdata = ctx->passwd_userdata;
  5319. }
  5320. #endif
  5321. if (format == WOLFSSL_FILETYPE_PEM) {
  5322. #ifdef WOLFSSL_PEM_TO_DER
  5323. ret = PemToDer(buff, sz, type, &der, heap, info, &keyFormat);
  5324. #else
  5325. ret = NOT_COMPILED_IN;
  5326. #endif
  5327. }
  5328. else {
  5329. /* ASN1 (DER) */
  5330. int length = (int)sz;
  5331. if (format == WOLFSSL_FILETYPE_ASN1) {
  5332. /* get length of der (read sequence or octet string) */
  5333. word32 inOutIdx = 0;
  5334. if (GetSequence(buff, &inOutIdx, &length, (word32)sz) >= 0) {
  5335. length += inOutIdx; /* include leading sequence */
  5336. }
  5337. /* get length using octect string (allowed for private key types) */
  5338. else if (type == PRIVATEKEY_TYPE &&
  5339. GetOctetString(buff, &inOutIdx, &length, (word32)sz) >= 0) {
  5340. length += inOutIdx; /* include leading oct string */
  5341. }
  5342. else {
  5343. ret = ASN_PARSE_E;
  5344. }
  5345. }
  5346. info->consumed = length;
  5347. if (ret == 0) {
  5348. ret = AllocDer(&der, (word32)length, type, heap);
  5349. if (ret == 0) {
  5350. XMEMCPY(der->buffer, buff, length);
  5351. }
  5352. #ifdef HAVE_PKCS8
  5353. /* if private key try and remove PKCS8 header */
  5354. if (type == PRIVATEKEY_TYPE) {
  5355. if ((ret = ToTraditional_ex(der->buffer, der->length,
  5356. &algId)) > 0) {
  5357. /* Found PKCS8 header */
  5358. /* ToTraditional_ex moves buff and returns adjusted length */
  5359. der->length = ret;
  5360. keyFormat = algId;
  5361. }
  5362. ret = 0; /* failures should be ignored */
  5363. }
  5364. #endif
  5365. }
  5366. }
  5367. if (used) {
  5368. *used = info->consumed;
  5369. }
  5370. /* process user chain */
  5371. if (ret >= 0) {
  5372. /* Chain should have server cert first, then intermediates, then root.
  5373. * First certificate in chain is processed below after ProcessUserChain
  5374. * and is loaded into ssl->buffers.certificate.
  5375. * Remainder are processed using ProcessUserChain and are loaded into
  5376. * ssl->buffers.certChain. */
  5377. if (userChain) {
  5378. ret = ProcessUserChain(ctx, buff, sz, format, type, ssl, used, info,
  5379. verify);
  5380. if (ret == ASN_NO_PEM_HEADER) { /* Additional chain is optional */
  5381. unsigned long pemErr;
  5382. CLEAR_ASN_NO_PEM_HEADER_ERROR(pemErr);
  5383. ret = 0;
  5384. }
  5385. }
  5386. }
  5387. /* info is only used for private key with DER or PEM, so free now */
  5388. if (ret < 0 || type != PRIVATEKEY_TYPE) {
  5389. #ifdef WOLFSSL_SMALL_STACK
  5390. XFREE(info, heap, DYNAMIC_TYPE_ENCRYPTEDINFO);
  5391. #endif
  5392. }
  5393. /* check for error */
  5394. if (ret < 0) {
  5395. FreeDer(&der);
  5396. done = 1;
  5397. }
  5398. if (done == 1) {
  5399. /* No operation, just skip the next section */
  5400. }
  5401. /* Handle DER owner */
  5402. else if (type == CA_TYPE) {
  5403. if (ctx == NULL) {
  5404. WOLFSSL_MSG("Need context for CA load");
  5405. FreeDer(&der);
  5406. return BAD_FUNC_ARG;
  5407. }
  5408. /* verify CA unless user set to no verify */
  5409. ret = AddCA(ctx->cm, &der, WOLFSSL_USER_CA, verify);
  5410. done = 1;
  5411. }
  5412. #ifdef WOLFSSL_TRUST_PEER_CERT
  5413. else if (type == TRUSTED_PEER_TYPE) {
  5414. /* add trusted peer cert. der is freed within */
  5415. if (ctx != NULL)
  5416. ret = AddTrustedPeer(ctx->cm, &der, !ctx->verifyNone);
  5417. else
  5418. ret = AddTrustedPeer(SSL_CM(ssl), &der, !ssl->options.verifyNone);
  5419. if (ret != WOLFSSL_SUCCESS) {
  5420. WOLFSSL_MSG("Error adding trusted peer");
  5421. }
  5422. done = 1;
  5423. }
  5424. #endif /* WOLFSSL_TRUST_PEER_CERT */
  5425. else if (type == CERT_TYPE) {
  5426. if (ssl != NULL) {
  5427. /* Make sure previous is free'd */
  5428. if (ssl->buffers.weOwnCert) {
  5429. FreeDer(&ssl->buffers.certificate);
  5430. #ifdef KEEP_OUR_CERT
  5431. wolfSSL_X509_free(ssl->ourCert);
  5432. ssl->ourCert = NULL;
  5433. #endif
  5434. }
  5435. ssl->buffers.certificate = der;
  5436. #ifdef KEEP_OUR_CERT
  5437. ssl->keepCert = 1; /* hold cert for ssl lifetime */
  5438. #endif
  5439. ssl->buffers.weOwnCert = 1;
  5440. }
  5441. else if (ctx != NULL) {
  5442. FreeDer(&ctx->certificate); /* Make sure previous is free'd */
  5443. #ifdef KEEP_OUR_CERT
  5444. if (ctx->ourCert) {
  5445. if (ctx->ownOurCert)
  5446. wolfSSL_X509_free(ctx->ourCert);
  5447. ctx->ourCert = NULL;
  5448. }
  5449. #endif
  5450. ctx->certificate = der;
  5451. }
  5452. }
  5453. else if (type == PRIVATEKEY_TYPE) {
  5454. if (ssl != NULL) {
  5455. /* Make sure previous is free'd */
  5456. if (ssl->buffers.weOwnKey) {
  5457. ForceZero(ssl->buffers.key->buffer, ssl->buffers.key->length);
  5458. FreeDer(&ssl->buffers.key);
  5459. }
  5460. ssl->buffers.key = der;
  5461. #ifdef WOLFSSL_CHECK_MEM_ZERO
  5462. wc_MemZero_Add("SSL Buffers key", der->buffer, der->length);
  5463. #endif
  5464. ssl->buffers.weOwnKey = 1;
  5465. }
  5466. else if (ctx != NULL) {
  5467. if (ctx->privateKey != NULL && ctx->privateKey->buffer != NULL) {
  5468. ForceZero(ctx->privateKey->buffer, ctx->privateKey->length);
  5469. }
  5470. FreeDer(&ctx->privateKey);
  5471. ctx->privateKey = der;
  5472. #ifdef WOLFSSL_CHECK_MEM_ZERO
  5473. wc_MemZero_Add("CTX private key", der->buffer, der->length);
  5474. #endif
  5475. }
  5476. }
  5477. else {
  5478. FreeDer(&der);
  5479. return WOLFSSL_BAD_CERTTYPE;
  5480. }
  5481. if (done == 1) {
  5482. /* No operation, just skip the next section */
  5483. }
  5484. else if (type == PRIVATEKEY_TYPE) {
  5485. ret = ProcessBufferTryDecode(ctx, ssl, der, &keySz, &idx, &resetSuites,
  5486. &keyFormat, heap, devId);
  5487. #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)
  5488. /* for WOLFSSL_FILETYPE_PEM, PemToDer manages the decryption */
  5489. /* If private key type PKCS8 header wasn't already removed (algoId == 0) */
  5490. if ((ret != 0 || keyFormat == 0)
  5491. && format != WOLFSSL_FILETYPE_PEM && info->passwd_cb && algId == 0)
  5492. {
  5493. int passwordSz = NAME_SZ;
  5494. #ifndef WOLFSSL_SMALL_STACK
  5495. char password[NAME_SZ];
  5496. #else
  5497. char* password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING);
  5498. if (password == NULL) {
  5499. XFREE(info, heap, DYNAMIC_TYPE_ENCRYPTEDINFO);
  5500. FreeDer(&der);
  5501. return MEMORY_E;
  5502. }
  5503. #endif
  5504. /* get password */
  5505. ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ,
  5506. info->passwd_userdata);
  5507. if (ret >= 0) {
  5508. passwordSz = ret;
  5509. #ifdef WOLFSSL_CHECK_MEM_ZERO
  5510. wc_MemZero_Add("ProcessBuffer password", password, passwordSz);
  5511. #endif
  5512. /* PKCS8 decrypt */
  5513. ret = ToTraditionalEnc(der->buffer, der->length,
  5514. password, passwordSz, &algId);
  5515. if (ret >= 0) {
  5516. ForceZero(der->buffer + ret, der->length - ret);
  5517. der->length = ret;
  5518. }
  5519. /* ignore failures and try parsing as unencrypted */
  5520. ForceZero(password, passwordSz);
  5521. }
  5522. #ifdef WOLFSSL_SMALL_STACK
  5523. XFREE(password, heap, DYNAMIC_TYPE_STRING);
  5524. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  5525. wc_MemZero_Check(password, NAME_SZ);
  5526. #endif
  5527. ret = ProcessBufferTryDecode(ctx, ssl, der, &keySz, &idx,
  5528. &resetSuites, &keyFormat, heap, devId);
  5529. }
  5530. #endif /* WOLFSSL_ENCRYPTED_KEYS && !NO_PWDBASED */
  5531. #ifdef WOLFSSL_SMALL_STACK
  5532. XFREE(info, heap, DYNAMIC_TYPE_ENCRYPTEDINFO);
  5533. #endif
  5534. if (ret != 0)
  5535. return ret;
  5536. if (keyFormat == 0) {
  5537. #ifdef OPENSSL_EXTRA
  5538. /* Reaching this point probably means that the
  5539. * decryption password is wrong */
  5540. if (info->passwd_cb)
  5541. EVPerr(0, EVP_R_BAD_DECRYPT);
  5542. #endif
  5543. WOLFSSL_ERROR(WOLFSSL_BAD_FILE);
  5544. return WOLFSSL_BAD_FILE;
  5545. }
  5546. (void)devId;
  5547. }
  5548. else if (type == CERT_TYPE) {
  5549. #ifdef WOLFSSL_SMALL_STACK
  5550. DecodedCert* cert;
  5551. #else
  5552. DecodedCert cert[1];
  5553. #endif
  5554. #ifdef WOLF_PRIVATE_KEY_ID
  5555. int keyType = 0;
  5556. #endif
  5557. #ifdef WOLFSSL_SMALL_STACK
  5558. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap,
  5559. DYNAMIC_TYPE_DCERT);
  5560. if (cert == NULL)
  5561. return MEMORY_E;
  5562. #endif
  5563. WOLFSSL_MSG("Checking cert signature type");
  5564. InitDecodedCert(cert, der->buffer, der->length, heap);
  5565. if (DecodeToKey(cert, 0) < 0) {
  5566. WOLFSSL_MSG("Decode to key failed");
  5567. FreeDecodedCert(cert);
  5568. #ifdef WOLFSSL_SMALL_STACK
  5569. XFREE(cert, heap, DYNAMIC_TYPE_DCERT);
  5570. #endif
  5571. return WOLFSSL_BAD_FILE;
  5572. }
  5573. if (ssl && ssl->options.side == WOLFSSL_SERVER_END) {
  5574. resetSuites = 1;
  5575. }
  5576. if (ssl && ssl->ctx->haveECDSAsig) {
  5577. WOLFSSL_MSG("SSL layer setting cert, CTX had ECDSA, turning off");
  5578. ssl->options.haveECDSAsig = 0; /* may turn back on next */
  5579. }
  5580. switch (cert->signatureOID) {
  5581. case CTC_SHAwECDSA:
  5582. case CTC_SHA256wECDSA:
  5583. case CTC_SHA384wECDSA:
  5584. case CTC_SHA512wECDSA:
  5585. case CTC_ED25519:
  5586. case CTC_ED448:
  5587. WOLFSSL_MSG("ECDSA/ED25519/ED448 cert signature");
  5588. if (ssl)
  5589. ssl->options.haveECDSAsig = 1;
  5590. else if (ctx)
  5591. ctx->haveECDSAsig = 1;
  5592. break;
  5593. case CTC_FALCON_LEVEL1:
  5594. case CTC_FALCON_LEVEL5:
  5595. WOLFSSL_MSG("Falcon cert signature");
  5596. if (ssl)
  5597. ssl->options.haveFalconSig = 1;
  5598. else if (ctx)
  5599. ctx->haveFalconSig = 1;
  5600. break;
  5601. case CTC_DILITHIUM_LEVEL2:
  5602. case CTC_DILITHIUM_LEVEL3:
  5603. case CTC_DILITHIUM_LEVEL5:
  5604. case CTC_DILITHIUM_AES_LEVEL2:
  5605. case CTC_DILITHIUM_AES_LEVEL3:
  5606. case CTC_DILITHIUM_AES_LEVEL5:
  5607. WOLFSSL_MSG("Dilithium cert signature");
  5608. if (ssl)
  5609. ssl->options.haveDilithiumSig = 1;
  5610. else if (ctx)
  5611. ctx->haveDilithiumSig = 1;
  5612. break;
  5613. default:
  5614. WOLFSSL_MSG("Not ECDSA cert signature");
  5615. break;
  5616. }
  5617. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  5618. defined(HAVE_PQC) || !defined(NO_RSA)
  5619. if (ssl) {
  5620. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  5621. (defined(HAVE_CURVE448) && defined(HAVE_ED448))
  5622. ssl->pkCurveOID = cert->pkCurveOID;
  5623. #endif
  5624. #ifndef WC_STRICT_SIG
  5625. if (cert->keyOID == ECDSAk) {
  5626. ssl->options.haveECC = 1;
  5627. }
  5628. #ifndef NO_RSA
  5629. else if (cert->keyOID == RSAk) {
  5630. ssl->options.haveRSA = 1;
  5631. }
  5632. #ifdef WC_RSA_PSS
  5633. else if (cert->keyOID == RSAPSSk) {
  5634. ssl->options.haveRSA = 1;
  5635. }
  5636. #endif
  5637. #endif
  5638. #ifdef HAVE_ED25519
  5639. else if (cert->keyOID == ED25519k) {
  5640. ssl->options.haveECC = 1;
  5641. }
  5642. #endif
  5643. #ifdef HAVE_ED448
  5644. else if (cert->keyOID == ED448k) {
  5645. ssl->options.haveECC = 1;
  5646. }
  5647. #endif
  5648. #ifdef HAVE_PQC
  5649. #ifdef HAVE_FALCON
  5650. else if (cert->keyOID == FALCON_LEVEL1k ||
  5651. cert->keyOID == FALCON_LEVEL5k) {
  5652. ssl->options.haveFalconSig = 1;
  5653. }
  5654. #endif /* HAVE_FALCON */
  5655. #ifdef HAVE_DILITHIUM
  5656. else if (cert->keyOID == DILITHIUM_LEVEL2k ||
  5657. cert->keyOID == DILITHIUM_LEVEL3k ||
  5658. cert->keyOID == DILITHIUM_LEVEL5k ||
  5659. cert->keyOID == DILITHIUM_AES_LEVEL2k ||
  5660. cert->keyOID == DILITHIUM_AES_LEVEL3k ||
  5661. cert->keyOID == DILITHIUM_AES_LEVEL5k) {
  5662. ssl->options.haveDilithiumSig = 1;
  5663. }
  5664. #endif /* HAVE_DILITHIUM */
  5665. #endif /* HAVE_PQC */
  5666. #else
  5667. ssl->options.haveECC = ssl->options.haveECDSAsig;
  5668. #endif
  5669. }
  5670. else if (ctx) {
  5671. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  5672. ctx->pkCurveOID = cert->pkCurveOID;
  5673. #endif
  5674. #ifndef WC_STRICT_SIG
  5675. if (cert->keyOID == ECDSAk) {
  5676. ctx->haveECC = 1;
  5677. }
  5678. #ifndef NO_RSA
  5679. else if (cert->keyOID == RSAk) {
  5680. ctx->haveRSA = 1;
  5681. }
  5682. #ifdef WC_RSA_PSS
  5683. else if (cert->keyOID == RSAPSSk) {
  5684. ctx->haveRSA = 1;
  5685. }
  5686. #endif
  5687. #endif
  5688. #ifdef HAVE_ED25519
  5689. else if (cert->keyOID == ED25519k) {
  5690. ctx->haveECC = 1;
  5691. }
  5692. #endif
  5693. #ifdef HAVE_ED448
  5694. else if (cert->keyOID == ED448k) {
  5695. ctx->haveECC = 1;
  5696. }
  5697. #endif
  5698. #ifdef HAVE_PQC
  5699. #ifdef HAVE_FALCON
  5700. else if (cert->keyOID == FALCON_LEVEL1k ||
  5701. cert->keyOID == FALCON_LEVEL5k) {
  5702. ctx->haveFalconSig = 1;
  5703. }
  5704. #endif /* HAVE_FALCON */
  5705. #ifdef HAVE_DILITHIUM
  5706. else if (cert->keyOID == DILITHIUM_LEVEL2k ||
  5707. cert->keyOID == DILITHIUM_LEVEL3k ||
  5708. cert->keyOID == DILITHIUM_LEVEL5k ||
  5709. cert->keyOID == DILITHIUM_AES_LEVEL2k ||
  5710. cert->keyOID == DILITHIUM_AES_LEVEL3k ||
  5711. cert->keyOID == DILITHIUM_AES_LEVEL5k) {
  5712. ctx->haveDilithiumSig = 1;
  5713. }
  5714. #endif /* HAVE_DILITHIUM */
  5715. #endif /* HAVE_PQC */
  5716. #else
  5717. ctx->haveECC = ctx->haveECDSAsig;
  5718. #endif
  5719. }
  5720. #endif
  5721. /* check key size of cert unless specified not to */
  5722. switch (cert->keyOID) {
  5723. #ifndef NO_RSA
  5724. #ifdef WC_RSA_PSS
  5725. case RSAPSSk:
  5726. #endif
  5727. case RSAk:
  5728. #ifdef WOLF_PRIVATE_KEY_ID
  5729. keyType = rsa_sa_algo;
  5730. #endif
  5731. /* Determine RSA key size by parsing public key */
  5732. idx = 0;
  5733. ret = wc_RsaPublicKeyDecode_ex(cert->publicKey, &idx,
  5734. cert->pubKeySize, NULL, (word32*)&keySz, NULL, NULL);
  5735. if (ret < 0)
  5736. break;
  5737. if (ssl && !ssl->options.verifyNone) {
  5738. if (ssl->options.minRsaKeySz < 0 ||
  5739. keySz < (int)ssl->options.minRsaKeySz ||
  5740. keySz > (RSA_MAX_SIZE / 8)) {
  5741. ret = RSA_KEY_SIZE_E;
  5742. WOLFSSL_MSG("Certificate RSA key size too small");
  5743. }
  5744. }
  5745. else if (ctx && !ctx->verifyNone) {
  5746. if (ctx->minRsaKeySz < 0 ||
  5747. keySz < (int)ctx->minRsaKeySz ||
  5748. keySz > (RSA_MAX_SIZE / 8)) {
  5749. ret = RSA_KEY_SIZE_E;
  5750. WOLFSSL_MSG("Certificate RSA key size too small");
  5751. }
  5752. }
  5753. break;
  5754. #endif /* !NO_RSA */
  5755. #ifdef HAVE_ECC
  5756. case ECDSAk:
  5757. #ifdef WOLF_PRIVATE_KEY_ID
  5758. keyType = ecc_dsa_sa_algo;
  5759. #endif
  5760. /* Determine ECC key size based on curve */
  5761. keySz = wc_ecc_get_curve_size_from_id(
  5762. wc_ecc_get_oid(cert->pkCurveOID, NULL, NULL));
  5763. if (ssl && !ssl->options.verifyNone) {
  5764. if (ssl->options.minEccKeySz < 0 ||
  5765. keySz < (int)ssl->options.minEccKeySz) {
  5766. ret = ECC_KEY_SIZE_E;
  5767. WOLFSSL_MSG("Certificate ECC key size error");
  5768. }
  5769. }
  5770. else if (ctx && !ctx->verifyNone) {
  5771. if (ctx->minEccKeySz < 0 ||
  5772. keySz < (int)ctx->minEccKeySz) {
  5773. ret = ECC_KEY_SIZE_E;
  5774. WOLFSSL_MSG("Certificate ECC key size error");
  5775. }
  5776. }
  5777. break;
  5778. #endif /* HAVE_ECC */
  5779. #ifdef HAVE_ED25519
  5780. case ED25519k:
  5781. #ifdef WOLF_PRIVATE_KEY_ID
  5782. keyType = ed25519_sa_algo;
  5783. #endif
  5784. /* ED25519 is fixed key size */
  5785. keySz = ED25519_KEY_SIZE;
  5786. if (ssl && !ssl->options.verifyNone) {
  5787. if (ssl->options.minEccKeySz < 0 ||
  5788. keySz < (int)ssl->options.minEccKeySz) {
  5789. ret = ECC_KEY_SIZE_E;
  5790. WOLFSSL_MSG("Certificate Ed key size error");
  5791. }
  5792. }
  5793. else if (ctx && !ctx->verifyNone) {
  5794. if (ctx->minEccKeySz < 0 ||
  5795. keySz < (int)ctx->minEccKeySz) {
  5796. ret = ECC_KEY_SIZE_E;
  5797. WOLFSSL_MSG("Certificate ECC key size error");
  5798. }
  5799. }
  5800. break;
  5801. #endif /* HAVE_ED25519 */
  5802. #ifdef HAVE_ED448
  5803. case ED448k:
  5804. #ifdef WOLF_PRIVATE_KEY_ID
  5805. keyType = ed448_sa_algo;
  5806. #endif
  5807. /* ED448 is fixed key size */
  5808. keySz = ED448_KEY_SIZE;
  5809. if (ssl && !ssl->options.verifyNone) {
  5810. if (ssl->options.minEccKeySz < 0 ||
  5811. keySz < (int)ssl->options.minEccKeySz) {
  5812. ret = ECC_KEY_SIZE_E;
  5813. WOLFSSL_MSG("Certificate Ed key size error");
  5814. }
  5815. }
  5816. else if (ctx && !ctx->verifyNone) {
  5817. if (ctx->minEccKeySz < 0 ||
  5818. keySz < (int)ctx->minEccKeySz) {
  5819. ret = ECC_KEY_SIZE_E;
  5820. WOLFSSL_MSG("Certificate ECC key size error");
  5821. }
  5822. }
  5823. break;
  5824. #endif /* HAVE_ED448 */
  5825. #if defined(HAVE_PQC)
  5826. #if defined(HAVE_FALCON)
  5827. case FALCON_LEVEL1k:
  5828. case FALCON_LEVEL5k:
  5829. /* Falcon is fixed key size */
  5830. keySz = FALCON_MAX_KEY_SIZE;
  5831. if (ssl && !ssl->options.verifyNone) {
  5832. if (ssl->options.minFalconKeySz < 0 ||
  5833. keySz < (int)ssl->options.minFalconKeySz) {
  5834. ret = FALCON_KEY_SIZE_E;
  5835. WOLFSSL_MSG("Certificate Falcon key size error");
  5836. }
  5837. }
  5838. else if (ctx && !ctx->verifyNone) {
  5839. if (ctx->minFalconKeySz < 0 ||
  5840. keySz < (int)ctx->minFalconKeySz) {
  5841. ret = FALCON_KEY_SIZE_E;
  5842. WOLFSSL_MSG("Certificate Falcon key size error");
  5843. }
  5844. }
  5845. break;
  5846. #endif /* HAVE_FALCON */
  5847. #if defined(HAVE_DILITHIUM)
  5848. case DILITHIUM_LEVEL2k:
  5849. case DILITHIUM_LEVEL3k:
  5850. case DILITHIUM_LEVEL5k:
  5851. case DILITHIUM_AES_LEVEL2k:
  5852. case DILITHIUM_AES_LEVEL3k:
  5853. case DILITHIUM_AES_LEVEL5k:
  5854. /* Dilithium is fixed key size */
  5855. keySz = DILITHIUM_MAX_KEY_SIZE;
  5856. if (ssl && !ssl->options.verifyNone) {
  5857. if (ssl->options.minDilithiumKeySz < 0 ||
  5858. keySz < (int)ssl->options.minDilithiumKeySz) {
  5859. ret = DILITHIUM_KEY_SIZE_E;
  5860. WOLFSSL_MSG("Certificate Dilithium key size error");
  5861. }
  5862. }
  5863. else if (ctx && !ctx->verifyNone) {
  5864. if (ctx->minDilithiumKeySz < 0 ||
  5865. keySz < (int)ctx->minDilithiumKeySz) {
  5866. ret = DILITHIUM_KEY_SIZE_E;
  5867. WOLFSSL_MSG("Certificate Dilithium key size error");
  5868. }
  5869. }
  5870. break;
  5871. #endif /* HAVE_DILITHIUM */
  5872. #endif /* HAVE_PQC */
  5873. default:
  5874. WOLFSSL_MSG("No key size check done on certificate");
  5875. break; /* do no check if not a case for the key */
  5876. }
  5877. #ifdef WOLF_PRIVATE_KEY_ID
  5878. if (ssl != NULL && ssl->buffers.keyType == 0) {
  5879. ssl->buffers.keyType = keyType;
  5880. ssl->buffers.keySz = keySz;
  5881. }
  5882. else if (ctx != NULL && ctx->privateKeyType == 0) {
  5883. ctx->privateKeyType = keyType;
  5884. ctx->privateKeySz = keySz;
  5885. }
  5886. #endif
  5887. FreeDecodedCert(cert);
  5888. #ifdef WOLFSSL_SMALL_STACK
  5889. XFREE(cert, heap, DYNAMIC_TYPE_DCERT);
  5890. #endif
  5891. if (ret != 0) {
  5892. done = 1;
  5893. }
  5894. }
  5895. if (done == 1) {
  5896. #if !defined(NO_WOLFSSL_CM_VERIFY) && (!defined(NO_WOLFSSL_CLIENT) || \
  5897. !defined(WOLFSSL_NO_CLIENT_AUTH))
  5898. if ((type == CA_TYPE) || (type == CERT_TYPE)) {
  5899. /* Call to over-ride status */
  5900. if ((ctx != NULL) && (ctx->cm != NULL) &&
  5901. (ctx->cm->verifyCallback != NULL)) {
  5902. ret = CM_VerifyBuffer_ex(ctx->cm, buff,
  5903. sz, format, (ret == WOLFSSL_SUCCESS ? 0 : ret));
  5904. }
  5905. }
  5906. #endif /* NO_WOLFSSL_CM_VERIFY */
  5907. return ret;
  5908. }
  5909. if (ssl && resetSuites) {
  5910. word16 havePSK = 0;
  5911. word16 haveRSA = 0;
  5912. #ifndef NO_PSK
  5913. if (ssl->options.havePSK) {
  5914. havePSK = 1;
  5915. }
  5916. #endif
  5917. #ifndef NO_RSA
  5918. haveRSA = 1;
  5919. #endif
  5920. keySz = ssl->buffers.keySz;
  5921. /* let's reset suites */
  5922. InitSuites(ssl->suites, ssl->version, keySz, haveRSA,
  5923. havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig,
  5924. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  5925. ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
  5926. ssl->options.haveAnon, TRUE, ssl->options.side);
  5927. }
  5928. return WOLFSSL_SUCCESS;
  5929. }
  5930. /* CA PEM file for verification, may have multiple/chain certs to process */
  5931. static int ProcessChainBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff,
  5932. long sz, int format, int type, WOLFSSL* ssl, int verify)
  5933. {
  5934. long used = 0;
  5935. int ret = 0;
  5936. int gotOne = 0;
  5937. WOLFSSL_MSG("Processing CA PEM file");
  5938. while (used < sz) {
  5939. long consumed = 0;
  5940. ret = ProcessBuffer(ctx, buff + used, sz - used, format, type, ssl,
  5941. &consumed, 0, verify);
  5942. if (ret < 0) {
  5943. #if defined(WOLFSSL_WPAS) && defined(HAVE_CRL)
  5944. DerBuffer* der = NULL;
  5945. EncryptedInfo info;
  5946. WOLFSSL_MSG("Trying a CRL");
  5947. if (PemToDer(buff + used, sz - used, CRL_TYPE, &der, NULL, &info,
  5948. NULL) == 0) {
  5949. WOLFSSL_MSG(" Processed a CRL");
  5950. wolfSSL_CertManagerLoadCRLBuffer(ctx->cm, der->buffer,
  5951. der->length, WOLFSSL_FILETYPE_ASN1);
  5952. FreeDer(&der);
  5953. used += info.consumed;
  5954. continue;
  5955. }
  5956. #endif
  5957. if (consumed > 0) { /* Made progress in file */
  5958. WOLFSSL_ERROR(ret);
  5959. WOLFSSL_MSG("CA Parse failed, with progress in file.");
  5960. WOLFSSL_MSG("Search for other certs in file");
  5961. }
  5962. else {
  5963. WOLFSSL_MSG("CA Parse failed, no progress in file.");
  5964. WOLFSSL_MSG("Do not continue search for other certs in file");
  5965. break;
  5966. }
  5967. }
  5968. else {
  5969. WOLFSSL_MSG(" Processed a CA");
  5970. gotOne = 1;
  5971. }
  5972. used += consumed;
  5973. }
  5974. if (gotOne) {
  5975. WOLFSSL_MSG("Processed at least one valid CA. Other stuff OK");
  5976. return WOLFSSL_SUCCESS;
  5977. }
  5978. return ret;
  5979. }
  5980. static WC_INLINE WOLFSSL_METHOD* cm_pick_method(void)
  5981. {
  5982. #ifndef NO_WOLFSSL_CLIENT
  5983. #if !defined(NO_OLD_TLS) && defined(WOLFSSL_ALLOW_SSLV3)
  5984. return wolfSSLv3_client_method();
  5985. #elif !defined(NO_OLD_TLS) && defined(WOLFSSL_ALLOW_TLSV10)
  5986. return wolfTLSv1_client_method();
  5987. #elif !defined(NO_OLD_TLS)
  5988. return wolfTLSv1_1_client_method();
  5989. #elif !defined(WOLFSSL_NO_TLS12)
  5990. return wolfTLSv1_2_client_method();
  5991. #elif defined(WOLFSSL_TLS13)
  5992. return wolfTLSv1_3_client_method();
  5993. #else
  5994. return NULL;
  5995. #endif
  5996. #elif !defined(NO_WOLFSSL_SERVER)
  5997. #if !defined(NO_OLD_TLS) && defined(WOLFSSL_ALLOW_SSLV3)
  5998. return wolfSSLv3_server_method();
  5999. #elif !defined(NO_OLD_TLS) && defined(WOLFSSL_ALLOW_TLSV10)
  6000. return wolfTLSv1_server_method();
  6001. #elif !defined(NO_OLD_TLS)
  6002. return wolfTLSv1_1_server_method();
  6003. #elif !defined(WOLFSSL_NO_TLS12)
  6004. return wolfTLSv1_2_server_method();
  6005. #elif defined(WOLFSSL_TLS13)
  6006. return wolfTLSv1_3_server_method();
  6007. #else
  6008. return NULL;
  6009. #endif
  6010. #else
  6011. return NULL;
  6012. #endif
  6013. }
  6014. /* like load verify locations, 1 for success, < 0 for error */
  6015. int wolfSSL_CertManagerLoadCABuffer(WOLFSSL_CERT_MANAGER* cm,
  6016. const unsigned char* in, long sz, int format)
  6017. {
  6018. int ret = WOLFSSL_FATAL_ERROR;
  6019. WOLFSSL_CTX* tmp;
  6020. WOLFSSL_ENTER("wolfSSL_CertManagerLoadCABuffer");
  6021. if (cm == NULL) {
  6022. WOLFSSL_MSG("No CertManager error");
  6023. return ret;
  6024. }
  6025. tmp = wolfSSL_CTX_new(cm_pick_method());
  6026. if (tmp == NULL) {
  6027. WOLFSSL_MSG("CTX new failed");
  6028. return ret;
  6029. }
  6030. /* for tmp use */
  6031. wolfSSL_CertManagerFree(tmp->cm);
  6032. tmp->cm = cm;
  6033. ret = wolfSSL_CTX_load_verify_buffer(tmp, in, sz, format);
  6034. /* don't loose our good one */
  6035. tmp->cm = NULL;
  6036. wolfSSL_CTX_free(tmp);
  6037. return ret;
  6038. }
  6039. #ifdef HAVE_CRL
  6040. int wolfSSL_CertManagerLoadCRLBuffer(WOLFSSL_CERT_MANAGER* cm,
  6041. const unsigned char* buff, long sz, int type)
  6042. {
  6043. WOLFSSL_ENTER("wolfSSL_CertManagerLoadCRLBuffer");
  6044. if (cm == NULL)
  6045. return BAD_FUNC_ARG;
  6046. if (cm->crl == NULL) {
  6047. if (wolfSSL_CertManagerEnableCRL(cm, 0) != WOLFSSL_SUCCESS) {
  6048. WOLFSSL_MSG("Enable CRL failed");
  6049. return WOLFSSL_FATAL_ERROR;
  6050. }
  6051. }
  6052. return BufferLoadCRL(cm->crl, buff, sz, type, VERIFY);
  6053. }
  6054. int wolfSSL_CertManagerFreeCRL(WOLFSSL_CERT_MANAGER* cm)
  6055. {
  6056. WOLFSSL_ENTER("wolfSSL_CertManagerFreeCRL");
  6057. if (cm == NULL)
  6058. return BAD_FUNC_ARG;
  6059. if (cm->crl != NULL){
  6060. FreeCRL(cm->crl, 1);
  6061. cm->crl = NULL;
  6062. }
  6063. return WOLFSSL_SUCCESS;
  6064. }
  6065. int wolfSSL_CTX_LoadCRLBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff,
  6066. long sz, int type)
  6067. {
  6068. WOLFSSL_ENTER("wolfSSL_CTX_LoadCRLBuffer");
  6069. if (ctx == NULL)
  6070. return BAD_FUNC_ARG;
  6071. return wolfSSL_CertManagerLoadCRLBuffer(ctx->cm, buff, sz, type);
  6072. }
  6073. int wolfSSL_LoadCRLBuffer(WOLFSSL* ssl, const unsigned char* buff,
  6074. long sz, int type)
  6075. {
  6076. WOLFSSL_ENTER("wolfSSL_LoadCRLBuffer");
  6077. if (ssl == NULL || ssl->ctx == NULL)
  6078. return BAD_FUNC_ARG;
  6079. return wolfSSL_CertManagerLoadCRLBuffer(SSL_CM(ssl), buff, sz, type);
  6080. }
  6081. #endif /* HAVE_CRL */
  6082. /* turn on CRL if off and compiled in, set options */
  6083. int wolfSSL_CertManagerEnableCRL(WOLFSSL_CERT_MANAGER* cm, int options)
  6084. {
  6085. int ret = WOLFSSL_SUCCESS;
  6086. (void)options;
  6087. WOLFSSL_ENTER("wolfSSL_CertManagerEnableCRL");
  6088. if (cm == NULL)
  6089. return BAD_FUNC_ARG;
  6090. #ifdef HAVE_CRL
  6091. if (cm->crl == NULL) {
  6092. cm->crl = (WOLFSSL_CRL*)XMALLOC(sizeof(WOLFSSL_CRL), cm->heap,
  6093. DYNAMIC_TYPE_CRL);
  6094. if (cm->crl == NULL)
  6095. return MEMORY_E;
  6096. if (InitCRL(cm->crl, cm) != 0) {
  6097. WOLFSSL_MSG("Init CRL failed");
  6098. FreeCRL(cm->crl, 1);
  6099. cm->crl = NULL;
  6100. return WOLFSSL_FAILURE;
  6101. }
  6102. #if defined(HAVE_CRL_IO) && defined(USE_WOLFSSL_IO)
  6103. cm->crl->crlIOCb = EmbedCrlLookup;
  6104. #endif
  6105. }
  6106. cm->crlEnabled = 1;
  6107. if (options & WOLFSSL_CRL_CHECKALL)
  6108. cm->crlCheckAll = 1;
  6109. #else
  6110. ret = NOT_COMPILED_IN;
  6111. #endif
  6112. return ret;
  6113. }
  6114. int wolfSSL_CertManagerDisableCRL(WOLFSSL_CERT_MANAGER* cm)
  6115. {
  6116. WOLFSSL_ENTER("wolfSSL_CertManagerDisableCRL");
  6117. if (cm == NULL)
  6118. return BAD_FUNC_ARG;
  6119. cm->crlEnabled = 0;
  6120. return WOLFSSL_SUCCESS;
  6121. }
  6122. #ifndef NO_WOLFSSL_CM_VERIFY
  6123. void wolfSSL_CertManagerSetVerify(WOLFSSL_CERT_MANAGER* cm, VerifyCallback vc)
  6124. {
  6125. WOLFSSL_ENTER("wolfSSL_CertManagerSetVerify");
  6126. if (cm == NULL)
  6127. return;
  6128. cm->verifyCallback = vc;
  6129. }
  6130. #endif /* NO_WOLFSSL_CM_VERIFY */
  6131. #if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
  6132. /* Verify the certificate, WOLFSSL_SUCCESS for ok, < 0 for error */
  6133. int CM_VerifyBuffer_ex(WOLFSSL_CERT_MANAGER* cm, const byte* buff,
  6134. long sz, int format, int err_val)
  6135. {
  6136. int ret = 0;
  6137. DerBuffer* der = NULL;
  6138. #ifdef WOLFSSL_SMALL_STACK
  6139. DecodedCert* cert;
  6140. #else
  6141. DecodedCert cert[1];
  6142. #endif
  6143. WOLFSSL_ENTER("wolfSSL_CertManagerVerifyBuffer");
  6144. #ifdef WOLFSSL_SMALL_STACK
  6145. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cm->heap,
  6146. DYNAMIC_TYPE_DCERT);
  6147. if (cert == NULL)
  6148. return MEMORY_E;
  6149. #endif
  6150. if (format == WOLFSSL_FILETYPE_PEM) {
  6151. #ifdef WOLFSSL_PEM_TO_DER
  6152. ret = PemToDer(buff, sz, CERT_TYPE, &der, cm->heap, NULL, NULL);
  6153. if (ret != 0) {
  6154. FreeDer(&der);
  6155. #ifdef WOLFSSL_SMALL_STACK
  6156. XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
  6157. #endif
  6158. return ret;
  6159. }
  6160. InitDecodedCert(cert, der->buffer, der->length, cm->heap);
  6161. #else
  6162. ret = NOT_COMPILED_IN;
  6163. #endif
  6164. }
  6165. else {
  6166. InitDecodedCert(cert, buff, (word32)sz, cm->heap);
  6167. }
  6168. if (ret == 0)
  6169. ret = ParseCertRelative(cert, CERT_TYPE, 1, cm);
  6170. #ifdef HAVE_CRL
  6171. if (ret == 0 && cm->crlEnabled)
  6172. ret = CheckCertCRL(cm->crl, cert);
  6173. #endif
  6174. #ifndef NO_WOLFSSL_CM_VERIFY
  6175. /* if verify callback has been set */
  6176. if (cm->verifyCallback) {
  6177. buffer certBuf;
  6178. #ifdef WOLFSSL_SMALL_STACK
  6179. ProcPeerCertArgs* args;
  6180. args = (ProcPeerCertArgs*)XMALLOC(
  6181. sizeof(ProcPeerCertArgs), cm->heap, DYNAMIC_TYPE_TMP_BUFFER);
  6182. if (args == NULL) {
  6183. XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
  6184. return MEMORY_E;
  6185. }
  6186. #else
  6187. ProcPeerCertArgs args[1];
  6188. #endif
  6189. certBuf.buffer = (byte*)buff;
  6190. certBuf.length = (unsigned int)sz;
  6191. XMEMSET(args, 0, sizeof(ProcPeerCertArgs));
  6192. args->totalCerts = 1;
  6193. args->certs = &certBuf;
  6194. args->dCert = cert;
  6195. args->dCertInit = 1;
  6196. if (err_val != 0) {
  6197. ret = err_val;
  6198. }
  6199. ret = DoVerifyCallback(cm, NULL, ret, args);
  6200. #ifdef WOLFSSL_SMALL_STACK
  6201. XFREE(args, cm->heap, DYNAMIC_TYPE_TMP_BUFFER);
  6202. #endif
  6203. }
  6204. #else
  6205. (void)err_val;
  6206. #endif
  6207. FreeDecodedCert(cert);
  6208. FreeDer(&der);
  6209. #ifdef WOLFSSL_SMALL_STACK
  6210. XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
  6211. #endif
  6212. return ret == 0 ? WOLFSSL_SUCCESS : ret;
  6213. }
  6214. /* Verify the certificate, WOLFSSL_SUCCESS for ok, < 0 for error */
  6215. int wolfSSL_CertManagerVerifyBuffer(WOLFSSL_CERT_MANAGER* cm, const byte* buff,
  6216. long sz, int format)
  6217. {
  6218. return CM_VerifyBuffer_ex(cm, buff, sz, format, 0);
  6219. }
  6220. #endif /* !NO_WOLFSSL_CLIENT || !WOLFSSL_NO_CLIENT_AUTH */
  6221. /* turn on OCSP if off and compiled in, set options */
  6222. int wolfSSL_CertManagerEnableOCSP(WOLFSSL_CERT_MANAGER* cm, int options)
  6223. {
  6224. int ret = WOLFSSL_SUCCESS;
  6225. (void)options;
  6226. WOLFSSL_ENTER("wolfSSL_CertManagerEnableOCSP");
  6227. if (cm == NULL)
  6228. return BAD_FUNC_ARG;
  6229. #ifdef HAVE_OCSP
  6230. if (cm->ocsp == NULL) {
  6231. cm->ocsp = (WOLFSSL_OCSP*)XMALLOC(sizeof(WOLFSSL_OCSP), cm->heap,
  6232. DYNAMIC_TYPE_OCSP);
  6233. if (cm->ocsp == NULL)
  6234. return MEMORY_E;
  6235. if (InitOCSP(cm->ocsp, cm) != 0) {
  6236. WOLFSSL_MSG("Init OCSP failed");
  6237. FreeOCSP(cm->ocsp, 1);
  6238. cm->ocsp = NULL;
  6239. return WOLFSSL_FAILURE;
  6240. }
  6241. }
  6242. cm->ocspEnabled = 1;
  6243. if (options & WOLFSSL_OCSP_URL_OVERRIDE)
  6244. cm->ocspUseOverrideURL = 1;
  6245. if (options & WOLFSSL_OCSP_NO_NONCE)
  6246. cm->ocspSendNonce = 0;
  6247. else
  6248. cm->ocspSendNonce = 1;
  6249. if (options & WOLFSSL_OCSP_CHECKALL)
  6250. cm->ocspCheckAll = 1;
  6251. #ifndef WOLFSSL_USER_IO
  6252. cm->ocspIOCb = EmbedOcspLookup;
  6253. cm->ocspRespFreeCb = EmbedOcspRespFree;
  6254. cm->ocspIOCtx = cm->heap;
  6255. #endif /* WOLFSSL_USER_IO */
  6256. #else
  6257. ret = NOT_COMPILED_IN;
  6258. #endif
  6259. return ret;
  6260. }
  6261. int wolfSSL_CertManagerDisableOCSP(WOLFSSL_CERT_MANAGER* cm)
  6262. {
  6263. WOLFSSL_ENTER("wolfSSL_CertManagerDisableOCSP");
  6264. if (cm == NULL)
  6265. return BAD_FUNC_ARG;
  6266. cm->ocspEnabled = 0;
  6267. return WOLFSSL_SUCCESS;
  6268. }
  6269. /* turn on OCSP Stapling if off and compiled in, set options */
  6270. int wolfSSL_CertManagerEnableOCSPStapling(WOLFSSL_CERT_MANAGER* cm)
  6271. {
  6272. int ret = WOLFSSL_SUCCESS;
  6273. WOLFSSL_ENTER("wolfSSL_CertManagerEnableOCSPStapling");
  6274. if (cm == NULL)
  6275. return BAD_FUNC_ARG;
  6276. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  6277. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  6278. #ifndef NO_WOLFSSL_SERVER
  6279. if (cm->ocsp_stapling == NULL) {
  6280. cm->ocsp_stapling = (WOLFSSL_OCSP*)XMALLOC(sizeof(WOLFSSL_OCSP),
  6281. cm->heap, DYNAMIC_TYPE_OCSP);
  6282. if (cm->ocsp_stapling == NULL)
  6283. return MEMORY_E;
  6284. if (InitOCSP(cm->ocsp_stapling, cm) != 0) {
  6285. WOLFSSL_MSG("Init OCSP failed");
  6286. FreeOCSP(cm->ocsp_stapling, 1);
  6287. cm->ocsp_stapling = NULL;
  6288. return WOLFSSL_FAILURE;
  6289. }
  6290. }
  6291. #ifndef WOLFSSL_USER_IO
  6292. cm->ocspIOCb = EmbedOcspLookup;
  6293. cm->ocspRespFreeCb = EmbedOcspRespFree;
  6294. cm->ocspIOCtx = cm->heap;
  6295. #endif /* WOLFSSL_USER_IO */
  6296. #endif /* NO_WOLFSSL_SERVER */
  6297. cm->ocspStaplingEnabled = 1;
  6298. #else
  6299. ret = NOT_COMPILED_IN;
  6300. #endif
  6301. return ret;
  6302. }
  6303. int wolfSSL_CertManagerDisableOCSPStapling(WOLFSSL_CERT_MANAGER* cm)
  6304. {
  6305. int ret = WOLFSSL_SUCCESS;
  6306. WOLFSSL_ENTER("wolfSSL_CertManagerDisableOCSPStapling");
  6307. if (cm == NULL)
  6308. return BAD_FUNC_ARG;
  6309. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  6310. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  6311. cm->ocspStaplingEnabled = 0;
  6312. #else
  6313. ret = NOT_COMPILED_IN;
  6314. #endif
  6315. return ret;
  6316. }
  6317. /* require OCSP stapling response */
  6318. int wolfSSL_CertManagerEnableOCSPMustStaple(WOLFSSL_CERT_MANAGER* cm)
  6319. {
  6320. int ret;
  6321. WOLFSSL_ENTER("wolfSSL_CertManagerEnableOCSPMustStaple");
  6322. if (cm == NULL)
  6323. return BAD_FUNC_ARG;
  6324. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  6325. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  6326. #ifndef NO_WOLFSSL_CLIENT
  6327. cm->ocspMustStaple = 1;
  6328. #endif
  6329. ret = WOLFSSL_SUCCESS;
  6330. #else
  6331. ret = NOT_COMPILED_IN;
  6332. #endif
  6333. return ret;
  6334. }
  6335. int wolfSSL_CertManagerDisableOCSPMustStaple(WOLFSSL_CERT_MANAGER* cm)
  6336. {
  6337. int ret;
  6338. WOLFSSL_ENTER("wolfSSL_CertManagerDisableOCSPMustStaple");
  6339. if (cm == NULL)
  6340. return BAD_FUNC_ARG;
  6341. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  6342. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  6343. #ifndef NO_WOLFSSL_CLIENT
  6344. cm->ocspMustStaple = 0;
  6345. #endif
  6346. ret = WOLFSSL_SUCCESS;
  6347. #else
  6348. ret = NOT_COMPILED_IN;
  6349. #endif
  6350. return ret;
  6351. }
  6352. #ifdef HAVE_OCSP
  6353. /* check CRL if enabled, WOLFSSL_SUCCESS */
  6354. int wolfSSL_CertManagerCheckOCSP(WOLFSSL_CERT_MANAGER* cm, byte* der, int sz)
  6355. {
  6356. int ret;
  6357. #ifdef WOLFSSL_SMALL_STACK
  6358. DecodedCert* cert = NULL;
  6359. #else
  6360. DecodedCert cert[1];
  6361. #endif
  6362. WOLFSSL_ENTER("wolfSSL_CertManagerCheckOCSP");
  6363. if (cm == NULL)
  6364. return BAD_FUNC_ARG;
  6365. if (cm->ocspEnabled == 0)
  6366. return WOLFSSL_SUCCESS;
  6367. #ifdef WOLFSSL_SMALL_STACK
  6368. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cm->heap, DYNAMIC_TYPE_DCERT);
  6369. if (cert == NULL)
  6370. return MEMORY_E;
  6371. #endif
  6372. InitDecodedCert(cert, der, sz, NULL);
  6373. if ((ret = ParseCertRelative(cert, CERT_TYPE, VERIFY_OCSP, cm)) != 0) {
  6374. WOLFSSL_MSG("ParseCert failed");
  6375. }
  6376. else if ((ret = CheckCertOCSP(cm->ocsp, cert, NULL)) != 0) {
  6377. WOLFSSL_MSG("CheckCertOCSP failed");
  6378. }
  6379. FreeDecodedCert(cert);
  6380. #ifdef WOLFSSL_SMALL_STACK
  6381. XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
  6382. #endif
  6383. return ret == 0 ? WOLFSSL_SUCCESS : ret;
  6384. }
  6385. WOLFSSL_API int wolfSSL_CertManagerCheckOCSPResponse(WOLFSSL_CERT_MANAGER *cm,
  6386. byte *response, int responseSz, buffer *responseBuffer,
  6387. CertStatus *status, OcspEntry *entry, OcspRequest *ocspRequest)
  6388. {
  6389. int ret;
  6390. WOLFSSL_ENTER("wolfSSL_CertManagerCheckOCSPResponse");
  6391. if (cm == NULL || response == NULL)
  6392. return BAD_FUNC_ARG;
  6393. if (cm->ocspEnabled == 0)
  6394. return WOLFSSL_SUCCESS;
  6395. ret = CheckOcspResponse(cm->ocsp, response, responseSz, responseBuffer, status,
  6396. entry, ocspRequest);
  6397. return ret == 0 ? WOLFSSL_SUCCESS : ret;
  6398. }
  6399. int wolfSSL_CertManagerSetOCSPOverrideURL(WOLFSSL_CERT_MANAGER* cm,
  6400. const char* url)
  6401. {
  6402. WOLFSSL_ENTER("wolfSSL_CertManagerSetOCSPOverrideURL");
  6403. if (cm == NULL)
  6404. return BAD_FUNC_ARG;
  6405. XFREE(cm->ocspOverrideURL, cm->heap, DYNAMIC_TYPE_URL);
  6406. if (url != NULL) {
  6407. int urlSz = (int)XSTRLEN(url) + 1;
  6408. cm->ocspOverrideURL = (char*)XMALLOC(urlSz, cm->heap, DYNAMIC_TYPE_URL);
  6409. if (cm->ocspOverrideURL != NULL) {
  6410. XMEMCPY(cm->ocspOverrideURL, url, urlSz);
  6411. }
  6412. else
  6413. return MEMORY_E;
  6414. }
  6415. else
  6416. cm->ocspOverrideURL = NULL;
  6417. return WOLFSSL_SUCCESS;
  6418. }
  6419. int wolfSSL_CertManagerSetOCSP_Cb(WOLFSSL_CERT_MANAGER* cm,
  6420. CbOCSPIO ioCb, CbOCSPRespFree respFreeCb, void* ioCbCtx)
  6421. {
  6422. WOLFSSL_ENTER("wolfSSL_CertManagerSetOCSP_Cb");
  6423. if (cm == NULL)
  6424. return BAD_FUNC_ARG;
  6425. cm->ocspIOCb = ioCb;
  6426. cm->ocspRespFreeCb = respFreeCb;
  6427. cm->ocspIOCtx = ioCbCtx;
  6428. return WOLFSSL_SUCCESS;
  6429. }
  6430. int wolfSSL_EnableOCSP(WOLFSSL* ssl, int options)
  6431. {
  6432. WOLFSSL_ENTER("wolfSSL_EnableOCSP");
  6433. if (ssl)
  6434. return wolfSSL_CertManagerEnableOCSP(SSL_CM(ssl), options);
  6435. else
  6436. return BAD_FUNC_ARG;
  6437. }
  6438. int wolfSSL_DisableOCSP(WOLFSSL* ssl)
  6439. {
  6440. WOLFSSL_ENTER("wolfSSL_DisableOCSP");
  6441. if (ssl)
  6442. return wolfSSL_CertManagerDisableOCSP(SSL_CM(ssl));
  6443. else
  6444. return BAD_FUNC_ARG;
  6445. }
  6446. int wolfSSL_EnableOCSPStapling(WOLFSSL* ssl)
  6447. {
  6448. WOLFSSL_ENTER("wolfSSL_EnableOCSPStapling");
  6449. if (ssl)
  6450. return wolfSSL_CertManagerEnableOCSPStapling(SSL_CM(ssl));
  6451. else
  6452. return BAD_FUNC_ARG;
  6453. }
  6454. int wolfSSL_DisableOCSPStapling(WOLFSSL* ssl)
  6455. {
  6456. WOLFSSL_ENTER("wolfSSL_DisableOCSPStapling");
  6457. if (ssl)
  6458. return wolfSSL_CertManagerDisableOCSPStapling(SSL_CM(ssl));
  6459. else
  6460. return BAD_FUNC_ARG;
  6461. }
  6462. int wolfSSL_SetOCSP_OverrideURL(WOLFSSL* ssl, const char* url)
  6463. {
  6464. WOLFSSL_ENTER("wolfSSL_SetOCSP_OverrideURL");
  6465. if (ssl)
  6466. return wolfSSL_CertManagerSetOCSPOverrideURL(SSL_CM(ssl), url);
  6467. else
  6468. return BAD_FUNC_ARG;
  6469. }
  6470. int wolfSSL_SetOCSP_Cb(WOLFSSL* ssl,
  6471. CbOCSPIO ioCb, CbOCSPRespFree respFreeCb, void* ioCbCtx)
  6472. {
  6473. WOLFSSL_ENTER("wolfSSL_SetOCSP_Cb");
  6474. if (ssl) {
  6475. ssl->ocspIOCtx = ioCbCtx; /* use SSL specific ioCbCtx */
  6476. return wolfSSL_CertManagerSetOCSP_Cb(SSL_CM(ssl),
  6477. ioCb, respFreeCb, NULL);
  6478. }
  6479. else
  6480. return BAD_FUNC_ARG;
  6481. }
  6482. int wolfSSL_CTX_EnableOCSP(WOLFSSL_CTX* ctx, int options)
  6483. {
  6484. WOLFSSL_ENTER("wolfSSL_CTX_EnableOCSP");
  6485. if (ctx)
  6486. return wolfSSL_CertManagerEnableOCSP(ctx->cm, options);
  6487. else
  6488. return BAD_FUNC_ARG;
  6489. }
  6490. int wolfSSL_CTX_DisableOCSP(WOLFSSL_CTX* ctx)
  6491. {
  6492. WOLFSSL_ENTER("wolfSSL_CTX_DisableOCSP");
  6493. if (ctx)
  6494. return wolfSSL_CertManagerDisableOCSP(ctx->cm);
  6495. else
  6496. return BAD_FUNC_ARG;
  6497. }
  6498. int wolfSSL_CTX_SetOCSP_OverrideURL(WOLFSSL_CTX* ctx, const char* url)
  6499. {
  6500. WOLFSSL_ENTER("wolfSSL_SetOCSP_OverrideURL");
  6501. if (ctx)
  6502. return wolfSSL_CertManagerSetOCSPOverrideURL(ctx->cm, url);
  6503. else
  6504. return BAD_FUNC_ARG;
  6505. }
  6506. int wolfSSL_CTX_SetOCSP_Cb(WOLFSSL_CTX* ctx, CbOCSPIO ioCb,
  6507. CbOCSPRespFree respFreeCb, void* ioCbCtx)
  6508. {
  6509. WOLFSSL_ENTER("wolfSSL_CTX_SetOCSP_Cb");
  6510. if (ctx)
  6511. return wolfSSL_CertManagerSetOCSP_Cb(ctx->cm, ioCb,
  6512. respFreeCb, ioCbCtx);
  6513. else
  6514. return BAD_FUNC_ARG;
  6515. }
  6516. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  6517. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  6518. int wolfSSL_CTX_EnableOCSPStapling(WOLFSSL_CTX* ctx)
  6519. {
  6520. WOLFSSL_ENTER("wolfSSL_CTX_EnableOCSPStapling");
  6521. if (ctx)
  6522. return wolfSSL_CertManagerEnableOCSPStapling(ctx->cm);
  6523. else
  6524. return BAD_FUNC_ARG;
  6525. }
  6526. int wolfSSL_CTX_DisableOCSPStapling(WOLFSSL_CTX* ctx)
  6527. {
  6528. WOLFSSL_ENTER("wolfSSL_CTX_DisableOCSPStapling");
  6529. if (ctx)
  6530. return wolfSSL_CertManagerDisableOCSPStapling(ctx->cm);
  6531. else
  6532. return BAD_FUNC_ARG;
  6533. }
  6534. int wolfSSL_CTX_EnableOCSPMustStaple(WOLFSSL_CTX* ctx)
  6535. {
  6536. WOLFSSL_ENTER("wolfSSL_CTX_EnableOCSPMustStaple");
  6537. if (ctx)
  6538. return wolfSSL_CertManagerEnableOCSPMustStaple(ctx->cm);
  6539. else
  6540. return BAD_FUNC_ARG;
  6541. }
  6542. int wolfSSL_CTX_DisableOCSPMustStaple(WOLFSSL_CTX* ctx)
  6543. {
  6544. WOLFSSL_ENTER("wolfSSL_CTX_DisableOCSPMustStaple");
  6545. if (ctx)
  6546. return wolfSSL_CertManagerDisableOCSPMustStaple(ctx->cm);
  6547. else
  6548. return BAD_FUNC_ARG;
  6549. }
  6550. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST || HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  6551. #endif /* HAVE_OCSP */
  6552. /* macro to get verify settings for AddCA */
  6553. #define GET_VERIFY_SETTING_CTX(ctx) \
  6554. ((ctx) && (ctx)->verifyNone ? NO_VERIFY : VERIFY)
  6555. #define GET_VERIFY_SETTING_SSL(ssl) \
  6556. ((ssl)->options.verifyNone ? NO_VERIFY : VERIFY)
  6557. #ifndef NO_FILESYSTEM
  6558. /* process a file with name fname into ctx of format and type
  6559. userChain specifies a user certificate chain to pass during handshake */
  6560. int ProcessFile(WOLFSSL_CTX* ctx, const char* fname, int format, int type,
  6561. WOLFSSL* ssl, int userChain, WOLFSSL_CRL* crl, int verify)
  6562. {
  6563. #ifdef WOLFSSL_SMALL_STACK
  6564. byte staticBuffer[1]; /* force heap usage */
  6565. #else
  6566. byte staticBuffer[FILE_BUFFER_SIZE];
  6567. #endif
  6568. byte* myBuffer = staticBuffer;
  6569. int dynamic = 0;
  6570. int ret;
  6571. long sz = 0;
  6572. XFILE file;
  6573. void* heapHint = wolfSSL_CTX_GetHeap(ctx, ssl);
  6574. #ifndef NO_CODING
  6575. const char* header = NULL;
  6576. const char* footer = NULL;
  6577. #endif
  6578. (void)crl;
  6579. (void)heapHint;
  6580. if (fname == NULL) return WOLFSSL_BAD_FILE;
  6581. file = XFOPEN(fname, "rb");
  6582. if (file == XBADFILE) return WOLFSSL_BAD_FILE;
  6583. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  6584. XFCLOSE(file);
  6585. return WOLFSSL_BAD_FILE;
  6586. }
  6587. sz = XFTELL(file);
  6588. XREWIND(file);
  6589. if (sz > MAX_WOLFSSL_FILE_SIZE || sz <= 0) {
  6590. WOLFSSL_MSG("ProcessFile file size error");
  6591. XFCLOSE(file);
  6592. return WOLFSSL_BAD_FILE;
  6593. }
  6594. if (sz > (long)sizeof(staticBuffer)) {
  6595. WOLFSSL_MSG("Getting dynamic buffer");
  6596. myBuffer = (byte*)XMALLOC(sz, heapHint, DYNAMIC_TYPE_FILE);
  6597. if (myBuffer == NULL) {
  6598. XFCLOSE(file);
  6599. return WOLFSSL_BAD_FILE;
  6600. }
  6601. dynamic = 1;
  6602. }
  6603. if ((size_t)XFREAD(myBuffer, 1, sz, file) != (size_t)sz)
  6604. ret = WOLFSSL_BAD_FILE;
  6605. else {
  6606. /* Try to detect type by parsing cert header and footer */
  6607. if (type == DETECT_CERT_TYPE) {
  6608. #ifndef NO_CODING
  6609. if (wc_PemGetHeaderFooter(CA_TYPE, &header, &footer) == 0 &&
  6610. (XSTRNSTR((char*)myBuffer, header, (int)sz) != NULL)) {
  6611. type = CA_TYPE;
  6612. }
  6613. #ifdef HAVE_CRL
  6614. else if (wc_PemGetHeaderFooter(CRL_TYPE, &header, &footer) == 0 &&
  6615. (XSTRNSTR((char*)myBuffer, header, (int)sz) != NULL)) {
  6616. type = CRL_TYPE;
  6617. }
  6618. #endif
  6619. else if (wc_PemGetHeaderFooter(CERT_TYPE, &header, &footer) == 0 &&
  6620. (XSTRNSTR((char*)myBuffer, header, (int)sz) != NULL)) {
  6621. type = CERT_TYPE;
  6622. }
  6623. else
  6624. #endif
  6625. {
  6626. WOLFSSL_MSG("Failed to detect certificate type");
  6627. if (dynamic)
  6628. XFREE(myBuffer, heapHint, DYNAMIC_TYPE_FILE);
  6629. XFCLOSE(file);
  6630. return WOLFSSL_BAD_CERTTYPE;
  6631. }
  6632. }
  6633. if ((type == CA_TYPE || type == TRUSTED_PEER_TYPE)
  6634. && format == WOLFSSL_FILETYPE_PEM) {
  6635. ret = ProcessChainBuffer(ctx, myBuffer, sz, format, type, ssl,
  6636. verify);
  6637. }
  6638. #ifdef HAVE_CRL
  6639. else if (type == CRL_TYPE)
  6640. ret = BufferLoadCRL(crl, myBuffer, sz, format, verify);
  6641. #endif
  6642. else
  6643. ret = ProcessBuffer(ctx, myBuffer, sz, format, type, ssl, NULL,
  6644. userChain, verify);
  6645. }
  6646. XFCLOSE(file);
  6647. if (dynamic)
  6648. XFREE(myBuffer, heapHint, DYNAMIC_TYPE_FILE);
  6649. return ret;
  6650. }
  6651. /* loads file then loads each file in path, no c_rehash */
  6652. int wolfSSL_CTX_load_verify_locations_ex(WOLFSSL_CTX* ctx, const char* file,
  6653. const char* path, word32 flags)
  6654. {
  6655. int ret = WOLFSSL_SUCCESS;
  6656. #ifndef NO_WOLFSSL_DIR
  6657. int fileRet;
  6658. int successCount = 0;
  6659. int failCount = 0;
  6660. #endif
  6661. int verify;
  6662. WOLFSSL_MSG("wolfSSL_CTX_load_verify_locations_ex");
  6663. if (ctx == NULL || (file == NULL && path == NULL)) {
  6664. return WOLFSSL_FAILURE;
  6665. }
  6666. verify = GET_VERIFY_SETTING_CTX(ctx);
  6667. if (flags & WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY)
  6668. verify = VERIFY_SKIP_DATE;
  6669. if (file) {
  6670. ret = ProcessFile(ctx, file, WOLFSSL_FILETYPE_PEM, CA_TYPE, NULL, 0,
  6671. NULL, verify);
  6672. #ifndef NO_WOLFSSL_DIR
  6673. if (ret == WOLFSSL_SUCCESS)
  6674. successCount++;
  6675. #endif
  6676. #if defined(WOLFSSL_TRUST_PEER_CERT) && defined(OPENSSL_COMPATIBLE_DEFAULTS)
  6677. ret = wolfSSL_CTX_trust_peer_cert(ctx, file, WOLFSSL_FILETYPE_PEM);
  6678. if (ret != WOLFSSL_SUCCESS) {
  6679. WOLFSSL_MSG("wolfSSL_CTX_trust_peer_cert error");
  6680. }
  6681. #endif
  6682. }
  6683. if (ret == WOLFSSL_SUCCESS && path) {
  6684. #ifndef NO_WOLFSSL_DIR
  6685. char* name = NULL;
  6686. #ifdef WOLFSSL_SMALL_STACK
  6687. ReadDirCtx* readCtx;
  6688. readCtx = (ReadDirCtx*)XMALLOC(sizeof(ReadDirCtx), ctx->heap,
  6689. DYNAMIC_TYPE_DIRCTX);
  6690. if (readCtx == NULL)
  6691. return MEMORY_E;
  6692. #else
  6693. ReadDirCtx readCtx[1];
  6694. #endif
  6695. /* try to load each regular file in path */
  6696. fileRet = wc_ReadDirFirst(readCtx, path, &name);
  6697. while (fileRet == 0 && name) {
  6698. WOLFSSL_MSG(name); /* log file name */
  6699. ret = ProcessFile(ctx, name, WOLFSSL_FILETYPE_PEM, CA_TYPE,
  6700. NULL, 0, NULL, verify);
  6701. if (ret != WOLFSSL_SUCCESS) {
  6702. /* handle flags for ignoring errors, skipping expired certs or
  6703. by PEM certificate header error */
  6704. if ( (flags & WOLFSSL_LOAD_FLAG_IGNORE_ERR) ||
  6705. ((flags & WOLFSSL_LOAD_FLAG_PEM_CA_ONLY) &&
  6706. (ret == ASN_NO_PEM_HEADER))) {
  6707. /* Do not fail here if a certificate fails to load,
  6708. continue to next file */
  6709. unsigned long err;
  6710. CLEAR_ASN_NO_PEM_HEADER_ERROR(err);
  6711. #if defined(WOLFSSL_QT)
  6712. ret = WOLFSSL_SUCCESS;
  6713. #endif
  6714. }
  6715. else {
  6716. WOLFSSL_ERROR(ret);
  6717. WOLFSSL_MSG("Load CA file failed, continuing");
  6718. failCount++;
  6719. }
  6720. }
  6721. else {
  6722. #if defined(WOLFSSL_TRUST_PEER_CERT) && defined(OPENSSL_COMPATIBLE_DEFAULTS)
  6723. ret = wolfSSL_CTX_trust_peer_cert(ctx, file, WOLFSSL_FILETYPE_PEM);
  6724. if (ret != WOLFSSL_SUCCESS) {
  6725. WOLFSSL_MSG("wolfSSL_CTX_trust_peer_cert error. Ignoring"
  6726. "this error.");
  6727. }
  6728. #endif
  6729. successCount++;
  6730. }
  6731. fileRet = wc_ReadDirNext(readCtx, path, &name);
  6732. }
  6733. wc_ReadDirClose(readCtx);
  6734. /* pass directory read failure to response code */
  6735. if (fileRet != WC_READDIR_NOFILE) {
  6736. ret = fileRet;
  6737. #if defined(WOLFSSL_QT)
  6738. if (ret == BAD_PATH_ERROR &&
  6739. flags & WOLFSSL_LOAD_FLAG_IGNORE_BAD_PATH_ERR) {
  6740. /* QSslSocket always loads certs in system folder
  6741. * when it is initialized.
  6742. * Compliant with OpenSSL when flag sets.
  6743. */
  6744. ret = WOLFSSL_SUCCESS;
  6745. }
  6746. else {
  6747. /* qssl socket wants to know errors. */
  6748. WOLFSSL_ERROR(ret);
  6749. }
  6750. #endif
  6751. }
  6752. /* report failure if no files were loaded or there were failures */
  6753. else if (successCount == 0 || failCount > 0) {
  6754. /* use existing error code if exists */
  6755. #if defined(WOLFSSL_QT)
  6756. /* compliant with OpenSSL when flag sets*/
  6757. if (!(flags & WOLFSSL_LOAD_FLAG_IGNORE_ZEROFILE))
  6758. #endif
  6759. {
  6760. ret = WOLFSSL_FAILURE;
  6761. }
  6762. }
  6763. else {
  6764. ret = WOLFSSL_SUCCESS;
  6765. }
  6766. #ifdef WOLFSSL_SMALL_STACK
  6767. XFREE(readCtx, ctx->heap, DYNAMIC_TYPE_DIRCTX);
  6768. #endif
  6769. #else
  6770. ret = NOT_COMPILED_IN;
  6771. (void)flags;
  6772. #endif
  6773. }
  6774. return ret;
  6775. }
  6776. WOLFSSL_ABI
  6777. int wolfSSL_CTX_load_verify_locations(WOLFSSL_CTX* ctx, const char* file,
  6778. const char* path)
  6779. {
  6780. int ret = wolfSSL_CTX_load_verify_locations_ex(ctx, file, path,
  6781. WOLFSSL_LOAD_VERIFY_DEFAULT_FLAGS);
  6782. return WS_RETURN_CODE(ret,WOLFSSL_FAILURE);
  6783. }
  6784. #ifdef WOLFSSL_TRUST_PEER_CERT
  6785. /* Used to specify a peer cert to match when connecting
  6786. ctx : the ctx structure to load in peer cert
  6787. file: the string name of cert file
  6788. type: type of format such as PEM/DER
  6789. */
  6790. int wolfSSL_CTX_trust_peer_cert(WOLFSSL_CTX* ctx, const char* file, int type)
  6791. {
  6792. WOLFSSL_ENTER("wolfSSL_CTX_trust_peer_cert");
  6793. if (ctx == NULL || file == NULL) {
  6794. return WOLFSSL_FAILURE;
  6795. }
  6796. return ProcessFile(ctx, file, type, TRUSTED_PEER_TYPE, NULL, 0, NULL,
  6797. GET_VERIFY_SETTING_CTX(ctx));
  6798. }
  6799. int wolfSSL_trust_peer_cert(WOLFSSL* ssl, const char* file, int type)
  6800. {
  6801. WOLFSSL_ENTER("wolfSSL_trust_peer_cert");
  6802. if (ssl == NULL || file == NULL) {
  6803. return WOLFSSL_FAILURE;
  6804. }
  6805. return ProcessFile(NULL, file, type, TRUSTED_PEER_TYPE, ssl, 0, NULL,
  6806. GET_VERIFY_SETTING_SSL(ssl));
  6807. }
  6808. #endif /* WOLFSSL_TRUST_PEER_CERT */
  6809. #if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
  6810. /* Verify the certificate, WOLFSSL_SUCCESS for ok, < 0 for error */
  6811. int wolfSSL_CertManagerVerify(WOLFSSL_CERT_MANAGER* cm, const char* fname,
  6812. int format)
  6813. {
  6814. int ret = WOLFSSL_FATAL_ERROR;
  6815. #ifdef WOLFSSL_SMALL_STACK
  6816. byte staticBuffer[1]; /* force heap usage */
  6817. #else
  6818. byte staticBuffer[FILE_BUFFER_SIZE];
  6819. #endif
  6820. byte* myBuffer = staticBuffer;
  6821. int dynamic = 0;
  6822. long sz = 0;
  6823. XFILE file = XFOPEN(fname, "rb");
  6824. WOLFSSL_ENTER("wolfSSL_CertManagerVerify");
  6825. if (file == XBADFILE) return WOLFSSL_BAD_FILE;
  6826. if(XFSEEK(file, 0, XSEEK_END) != 0) {
  6827. XFCLOSE(file);
  6828. return WOLFSSL_BAD_FILE;
  6829. }
  6830. sz = XFTELL(file);
  6831. XREWIND(file);
  6832. if (sz > MAX_WOLFSSL_FILE_SIZE || sz <= 0) {
  6833. WOLFSSL_MSG("CertManagerVerify file size error");
  6834. XFCLOSE(file);
  6835. return WOLFSSL_BAD_FILE;
  6836. }
  6837. if (sz > (long)sizeof(staticBuffer)) {
  6838. WOLFSSL_MSG("Getting dynamic buffer");
  6839. myBuffer = (byte*) XMALLOC(sz, cm->heap, DYNAMIC_TYPE_FILE);
  6840. if (myBuffer == NULL) {
  6841. XFCLOSE(file);
  6842. return WOLFSSL_BAD_FILE;
  6843. }
  6844. dynamic = 1;
  6845. }
  6846. if ((size_t)XFREAD(myBuffer, 1, sz, file) != (size_t)sz)
  6847. ret = WOLFSSL_BAD_FILE;
  6848. else
  6849. ret = wolfSSL_CertManagerVerifyBuffer(cm, myBuffer, sz, format);
  6850. XFCLOSE(file);
  6851. if (dynamic)
  6852. XFREE(myBuffer, cm->heap, DYNAMIC_TYPE_FILE);
  6853. return ret;
  6854. }
  6855. #endif
  6856. /* like load verify locations, 1 for success, < 0 for error */
  6857. int wolfSSL_CertManagerLoadCA(WOLFSSL_CERT_MANAGER* cm, const char* file,
  6858. const char* path)
  6859. {
  6860. int ret = WOLFSSL_FATAL_ERROR;
  6861. WOLFSSL_CTX* tmp;
  6862. WOLFSSL_ENTER("wolfSSL_CertManagerLoadCA");
  6863. if (cm == NULL) {
  6864. WOLFSSL_MSG("No CertManager error");
  6865. return ret;
  6866. }
  6867. tmp = wolfSSL_CTX_new(cm_pick_method());
  6868. if (tmp == NULL) {
  6869. WOLFSSL_MSG("CTX new failed");
  6870. return ret;
  6871. }
  6872. /* for tmp use */
  6873. wolfSSL_CertManagerFree(tmp->cm);
  6874. tmp->cm = cm;
  6875. ret = wolfSSL_CTX_load_verify_locations(tmp, file, path);
  6876. /* don't lose our good one */
  6877. tmp->cm = NULL;
  6878. wolfSSL_CTX_free(tmp);
  6879. return ret;
  6880. }
  6881. #endif /* NO_FILESYSTEM */
  6882. #ifdef HAVE_CRL
  6883. /* check CRL if enabled, WOLFSSL_SUCCESS */
  6884. int wolfSSL_CertManagerCheckCRL(WOLFSSL_CERT_MANAGER* cm, byte* der, int sz)
  6885. {
  6886. int ret = 0;
  6887. #ifdef WOLFSSL_SMALL_STACK
  6888. DecodedCert* cert = NULL;
  6889. #else
  6890. DecodedCert cert[1];
  6891. #endif
  6892. WOLFSSL_ENTER("wolfSSL_CertManagerCheckCRL");
  6893. if (cm == NULL)
  6894. return BAD_FUNC_ARG;
  6895. if (cm->crlEnabled == 0)
  6896. return WOLFSSL_SUCCESS;
  6897. #ifdef WOLFSSL_SMALL_STACK
  6898. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL, DYNAMIC_TYPE_DCERT);
  6899. if (cert == NULL)
  6900. return MEMORY_E;
  6901. #endif
  6902. InitDecodedCert(cert, der, sz, NULL);
  6903. if ((ret = ParseCertRelative(cert, CERT_TYPE, VERIFY_CRL, cm)) != 0) {
  6904. WOLFSSL_MSG("ParseCert failed");
  6905. }
  6906. else if ((ret = CheckCertCRL(cm->crl, cert)) != 0) {
  6907. WOLFSSL_MSG("CheckCertCRL failed");
  6908. }
  6909. FreeDecodedCert(cert);
  6910. #ifdef WOLFSSL_SMALL_STACK
  6911. XFREE(cert, NULL, DYNAMIC_TYPE_DCERT);
  6912. #endif
  6913. return ret == 0 ? WOLFSSL_SUCCESS : ret;
  6914. }
  6915. int wolfSSL_CertManagerSetCRL_Cb(WOLFSSL_CERT_MANAGER* cm, CbMissingCRL cb)
  6916. {
  6917. WOLFSSL_ENTER("wolfSSL_CertManagerSetCRL_Cb");
  6918. if (cm == NULL)
  6919. return BAD_FUNC_ARG;
  6920. cm->cbMissingCRL = cb;
  6921. return WOLFSSL_SUCCESS;
  6922. }
  6923. #ifdef HAVE_CRL_IO
  6924. int wolfSSL_CertManagerSetCRL_IOCb(WOLFSSL_CERT_MANAGER* cm, CbCrlIO cb)
  6925. {
  6926. if (cm == NULL)
  6927. return BAD_FUNC_ARG;
  6928. cm->crl->crlIOCb = cb;
  6929. return WOLFSSL_SUCCESS;
  6930. }
  6931. #endif
  6932. #ifndef NO_FILESYSTEM
  6933. int wolfSSL_CertManagerLoadCRL(WOLFSSL_CERT_MANAGER* cm, const char* path,
  6934. int type, int monitor)
  6935. {
  6936. WOLFSSL_ENTER("wolfSSL_CertManagerLoadCRL");
  6937. if (cm == NULL)
  6938. return BAD_FUNC_ARG;
  6939. if (cm->crl == NULL) {
  6940. if (wolfSSL_CertManagerEnableCRL(cm, 0) != WOLFSSL_SUCCESS) {
  6941. WOLFSSL_MSG("Enable CRL failed");
  6942. return WOLFSSL_FATAL_ERROR;
  6943. }
  6944. }
  6945. return LoadCRL(cm->crl, path, type, monitor);
  6946. }
  6947. int wolfSSL_CertManagerLoadCRLFile(WOLFSSL_CERT_MANAGER* cm, const char* file,
  6948. int type)
  6949. {
  6950. WOLFSSL_ENTER("wolfSSL_CertManagerLoadCRLFile");
  6951. if (cm == NULL || file == NULL)
  6952. return BAD_FUNC_ARG;
  6953. if (cm->crl == NULL) {
  6954. if (wolfSSL_CertManagerEnableCRL(cm, 0) != WOLFSSL_SUCCESS) {
  6955. WOLFSSL_MSG("Enable CRL failed");
  6956. return WOLFSSL_FATAL_ERROR;
  6957. }
  6958. }
  6959. return ProcessFile(NULL, file, type, CRL_TYPE, NULL, 0, cm->crl,
  6960. VERIFY);
  6961. }
  6962. #endif
  6963. int wolfSSL_EnableCRL(WOLFSSL* ssl, int options)
  6964. {
  6965. WOLFSSL_ENTER("wolfSSL_EnableCRL");
  6966. if (ssl)
  6967. return wolfSSL_CertManagerEnableCRL(SSL_CM(ssl), options);
  6968. else
  6969. return BAD_FUNC_ARG;
  6970. }
  6971. int wolfSSL_DisableCRL(WOLFSSL* ssl)
  6972. {
  6973. WOLFSSL_ENTER("wolfSSL_DisableCRL");
  6974. if (ssl)
  6975. return wolfSSL_CertManagerDisableCRL(SSL_CM(ssl));
  6976. else
  6977. return BAD_FUNC_ARG;
  6978. }
  6979. #ifndef NO_FILESYSTEM
  6980. int wolfSSL_LoadCRL(WOLFSSL* ssl, const char* path, int type, int monitor)
  6981. {
  6982. WOLFSSL_ENTER("wolfSSL_LoadCRL");
  6983. if (ssl)
  6984. return wolfSSL_CertManagerLoadCRL(SSL_CM(ssl), path, type, monitor);
  6985. else
  6986. return BAD_FUNC_ARG;
  6987. }
  6988. int wolfSSL_LoadCRLFile(WOLFSSL* ssl, const char* file, int type)
  6989. {
  6990. WOLFSSL_ENTER("wolfSSL_LoadCRL");
  6991. if (ssl)
  6992. return wolfSSL_CertManagerLoadCRLFile(SSL_CM(ssl), file, type);
  6993. else
  6994. return BAD_FUNC_ARG;
  6995. }
  6996. #endif
  6997. int wolfSSL_SetCRL_Cb(WOLFSSL* ssl, CbMissingCRL cb)
  6998. {
  6999. WOLFSSL_ENTER("wolfSSL_SetCRL_Cb");
  7000. if (ssl)
  7001. return wolfSSL_CertManagerSetCRL_Cb(SSL_CM(ssl), cb);
  7002. else
  7003. return BAD_FUNC_ARG;
  7004. }
  7005. #ifdef HAVE_CRL_IO
  7006. int wolfSSL_SetCRL_IOCb(WOLFSSL* ssl, CbCrlIO cb)
  7007. {
  7008. WOLFSSL_ENTER("wolfSSL_SetCRL_Cb");
  7009. if (ssl)
  7010. return wolfSSL_CertManagerSetCRL_IOCb(SSL_CM(ssl), cb);
  7011. else
  7012. return BAD_FUNC_ARG;
  7013. }
  7014. #endif
  7015. int wolfSSL_CTX_EnableCRL(WOLFSSL_CTX* ctx, int options)
  7016. {
  7017. WOLFSSL_ENTER("wolfSSL_CTX_EnableCRL");
  7018. if (ctx)
  7019. return wolfSSL_CertManagerEnableCRL(ctx->cm, options);
  7020. else
  7021. return BAD_FUNC_ARG;
  7022. }
  7023. int wolfSSL_CTX_DisableCRL(WOLFSSL_CTX* ctx)
  7024. {
  7025. WOLFSSL_ENTER("wolfSSL_CTX_DisableCRL");
  7026. if (ctx)
  7027. return wolfSSL_CertManagerDisableCRL(ctx->cm);
  7028. else
  7029. return BAD_FUNC_ARG;
  7030. }
  7031. #ifndef NO_FILESYSTEM
  7032. int wolfSSL_CTX_LoadCRL(WOLFSSL_CTX* ctx, const char* path,
  7033. int type, int monitor)
  7034. {
  7035. WOLFSSL_ENTER("wolfSSL_CTX_LoadCRL");
  7036. if (ctx)
  7037. return wolfSSL_CertManagerLoadCRL(ctx->cm, path, type, monitor);
  7038. else
  7039. return BAD_FUNC_ARG;
  7040. }
  7041. int wolfSSL_CTX_LoadCRLFile(WOLFSSL_CTX* ctx, const char* file,
  7042. int type)
  7043. {
  7044. WOLFSSL_ENTER("wolfSSL_CTX_LoadCRL");
  7045. if (ctx)
  7046. return wolfSSL_CertManagerLoadCRLFile(ctx->cm, file, type);
  7047. else
  7048. return BAD_FUNC_ARG;
  7049. }
  7050. #endif
  7051. int wolfSSL_CTX_SetCRL_Cb(WOLFSSL_CTX* ctx, CbMissingCRL cb)
  7052. {
  7053. WOLFSSL_ENTER("wolfSSL_CTX_SetCRL_Cb");
  7054. if (ctx)
  7055. return wolfSSL_CertManagerSetCRL_Cb(ctx->cm, cb);
  7056. else
  7057. return BAD_FUNC_ARG;
  7058. }
  7059. #ifdef HAVE_CRL_IO
  7060. int wolfSSL_CTX_SetCRL_IOCb(WOLFSSL_CTX* ctx, CbCrlIO cb)
  7061. {
  7062. WOLFSSL_ENTER("wolfSSL_CTX_SetCRL_IOCb");
  7063. if (ctx)
  7064. return wolfSSL_CertManagerSetCRL_IOCb(ctx->cm, cb);
  7065. else
  7066. return BAD_FUNC_ARG;
  7067. }
  7068. #endif
  7069. #endif /* HAVE_CRL */
  7070. #ifndef NO_FILESYSTEM
  7071. #ifdef WOLFSSL_DER_LOAD
  7072. /* Add format parameter to allow DER load of CA files */
  7073. int wolfSSL_CTX_der_load_verify_locations(WOLFSSL_CTX* ctx, const char* file,
  7074. int format)
  7075. {
  7076. WOLFSSL_ENTER("wolfSSL_CTX_der_load_verify_locations");
  7077. if (ctx == NULL || file == NULL)
  7078. return WOLFSSL_FAILURE;
  7079. if (ProcessFile(ctx, file, format, CA_TYPE, NULL, 0, NULL,
  7080. GET_VERIFY_SETTING_CTX(ctx)) == WOLFSSL_SUCCESS) {
  7081. return WOLFSSL_SUCCESS;
  7082. }
  7083. return WOLFSSL_FAILURE;
  7084. }
  7085. #endif /* WOLFSSL_DER_LOAD */
  7086. WOLFSSL_ABI
  7087. int wolfSSL_CTX_use_certificate_file(WOLFSSL_CTX* ctx, const char* file,
  7088. int format)
  7089. {
  7090. WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_file");
  7091. if (ProcessFile(ctx, file, format, CERT_TYPE, NULL, 0, NULL,
  7092. GET_VERIFY_SETTING_CTX(ctx)) == WOLFSSL_SUCCESS) {
  7093. return WOLFSSL_SUCCESS;
  7094. }
  7095. return WOLFSSL_FAILURE;
  7096. }
  7097. WOLFSSL_ABI
  7098. int wolfSSL_CTX_use_PrivateKey_file(WOLFSSL_CTX* ctx, const char* file,
  7099. int format)
  7100. {
  7101. WOLFSSL_ENTER("wolfSSL_CTX_use_PrivateKey_file");
  7102. if (ProcessFile(ctx, file, format, PRIVATEKEY_TYPE, NULL, 0, NULL,
  7103. GET_VERIFY_SETTING_CTX(ctx)) == WOLFSSL_SUCCESS) {
  7104. return WOLFSSL_SUCCESS;
  7105. }
  7106. return WOLFSSL_FAILURE;
  7107. }
  7108. #endif /* NO_FILESYSTEM */
  7109. /* Sets the max chain depth when verifying a certificate chain. Default depth
  7110. * is set to MAX_CHAIN_DEPTH.
  7111. *
  7112. * ctx WOLFSSL_CTX structure to set depth in
  7113. * depth max depth
  7114. */
  7115. void wolfSSL_CTX_set_verify_depth(WOLFSSL_CTX *ctx, int depth) {
  7116. WOLFSSL_ENTER("wolfSSL_CTX_set_verify_depth");
  7117. if (ctx == NULL || depth < 0 || depth > MAX_CHAIN_DEPTH) {
  7118. WOLFSSL_MSG("Bad depth argument, too large or less than 0");
  7119. return;
  7120. }
  7121. ctx->verifyDepth = (byte)depth;
  7122. }
  7123. /* get cert chaining depth using ssl struct */
  7124. long wolfSSL_get_verify_depth(WOLFSSL* ssl)
  7125. {
  7126. if(ssl == NULL) {
  7127. return BAD_FUNC_ARG;
  7128. }
  7129. #ifndef OPENSSL_EXTRA
  7130. return MAX_CHAIN_DEPTH;
  7131. #else
  7132. return ssl->options.verifyDepth;
  7133. #endif
  7134. }
  7135. /* get cert chaining depth using ctx struct */
  7136. long wolfSSL_CTX_get_verify_depth(WOLFSSL_CTX* ctx)
  7137. {
  7138. if (ctx == NULL) {
  7139. return BAD_FUNC_ARG;
  7140. }
  7141. #ifndef OPENSSL_EXTRA
  7142. return MAX_CHAIN_DEPTH;
  7143. #else
  7144. return ctx->verifyDepth;
  7145. #endif
  7146. }
  7147. #ifndef NO_FILESYSTEM
  7148. WOLFSSL_ABI
  7149. int wolfSSL_CTX_use_certificate_chain_file(WOLFSSL_CTX* ctx, const char* file)
  7150. {
  7151. /* process up to MAX_CHAIN_DEPTH plus subject cert */
  7152. WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_chain_file");
  7153. if (ProcessFile(ctx, file, WOLFSSL_FILETYPE_PEM, CERT_TYPE, NULL, 1, NULL,
  7154. GET_VERIFY_SETTING_CTX(ctx)) == WOLFSSL_SUCCESS) {
  7155. return WOLFSSL_SUCCESS;
  7156. }
  7157. return WOLFSSL_FAILURE;
  7158. }
  7159. int wolfSSL_CTX_use_certificate_chain_file_format(WOLFSSL_CTX* ctx,
  7160. const char* file, int format)
  7161. {
  7162. /* process up to MAX_CHAIN_DEPTH plus subject cert */
  7163. WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_chain_file_format");
  7164. if (ProcessFile(ctx, file, format, CERT_TYPE, NULL, 1, NULL,
  7165. GET_VERIFY_SETTING_CTX(ctx)) == WOLFSSL_SUCCESS) {
  7166. return WOLFSSL_SUCCESS;
  7167. }
  7168. return WOLFSSL_FAILURE;
  7169. }
  7170. #ifndef NO_DH
  7171. /* server Diffie-Hellman parameters */
  7172. static int wolfSSL_SetTmpDH_file_wrapper(WOLFSSL_CTX* ctx, WOLFSSL* ssl,
  7173. const char* fname, int format)
  7174. {
  7175. #ifdef WOLFSSL_SMALL_STACK
  7176. byte staticBuffer[1]; /* force heap usage */
  7177. #else
  7178. byte staticBuffer[FILE_BUFFER_SIZE];
  7179. #endif
  7180. byte* myBuffer = staticBuffer;
  7181. int dynamic = 0;
  7182. int ret;
  7183. long sz = 0;
  7184. XFILE file;
  7185. if (ctx == NULL || fname == NULL)
  7186. return BAD_FUNC_ARG;
  7187. file = XFOPEN(fname, "rb");
  7188. if (file == XBADFILE) return WOLFSSL_BAD_FILE;
  7189. if(XFSEEK(file, 0, XSEEK_END) != 0) {
  7190. XFCLOSE(file);
  7191. return WOLFSSL_BAD_FILE;
  7192. }
  7193. sz = XFTELL(file);
  7194. XREWIND(file);
  7195. if (sz > MAX_WOLFSSL_FILE_SIZE || sz <= 0) {
  7196. WOLFSSL_MSG("SetTmpDH file size error");
  7197. XFCLOSE(file);
  7198. return WOLFSSL_BAD_FILE;
  7199. }
  7200. if (sz > (long)sizeof(staticBuffer)) {
  7201. WOLFSSL_MSG("Getting dynamic buffer");
  7202. myBuffer = (byte*) XMALLOC(sz, ctx->heap, DYNAMIC_TYPE_FILE);
  7203. if (myBuffer == NULL) {
  7204. XFCLOSE(file);
  7205. return WOLFSSL_BAD_FILE;
  7206. }
  7207. dynamic = 1;
  7208. }
  7209. if ((size_t)XFREAD(myBuffer, 1, sz, file) != (size_t)sz)
  7210. ret = WOLFSSL_BAD_FILE;
  7211. else {
  7212. if (ssl)
  7213. ret = wolfSSL_SetTmpDH_buffer(ssl, myBuffer, sz, format);
  7214. else
  7215. ret = wolfSSL_CTX_SetTmpDH_buffer(ctx, myBuffer, sz, format);
  7216. }
  7217. XFCLOSE(file);
  7218. if (dynamic)
  7219. XFREE(myBuffer, ctx->heap, DYNAMIC_TYPE_FILE);
  7220. return ret;
  7221. }
  7222. /* server Diffie-Hellman parameters */
  7223. int wolfSSL_SetTmpDH_file(WOLFSSL* ssl, const char* fname, int format)
  7224. {
  7225. if (ssl == NULL)
  7226. return BAD_FUNC_ARG;
  7227. return wolfSSL_SetTmpDH_file_wrapper(ssl->ctx, ssl, fname, format);
  7228. }
  7229. /* server Diffie-Hellman parameters */
  7230. int wolfSSL_CTX_SetTmpDH_file(WOLFSSL_CTX* ctx, const char* fname, int format)
  7231. {
  7232. return wolfSSL_SetTmpDH_file_wrapper(ctx, NULL, fname, format);
  7233. }
  7234. #endif /* NO_DH */
  7235. #endif /* NO_FILESYSTEM */
  7236. #ifndef NO_CHECK_PRIVATE_KEY
  7237. /* Check private against public in certificate for match
  7238. *
  7239. * Returns WOLFSSL_SUCCESS on good private key
  7240. * WOLFSSL_FAILURE if mismatched */
  7241. static int check_cert_key(DerBuffer* cert, DerBuffer* key, void* heap,
  7242. int devId, int isKeyLabel, int isKeyId)
  7243. {
  7244. #ifdef WOLFSSL_SMALL_STACK
  7245. DecodedCert* der = NULL;
  7246. #else
  7247. DecodedCert der[1];
  7248. #endif
  7249. word32 size;
  7250. byte* buff;
  7251. int ret = WOLFSSL_FAILURE;
  7252. WOLFSSL_ENTER("check_cert_key");
  7253. if (cert == NULL || key == NULL) {
  7254. return WOLFSSL_FAILURE;
  7255. }
  7256. #ifdef WOLFSSL_SMALL_STACK
  7257. der = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL, DYNAMIC_TYPE_DCERT);
  7258. if (der == NULL)
  7259. return MEMORY_E;
  7260. #endif
  7261. size = cert->length;
  7262. buff = cert->buffer;
  7263. InitDecodedCert(der, buff, size, heap);
  7264. if (ParseCertRelative(der, CERT_TYPE, NO_VERIFY, NULL) != 0) {
  7265. FreeDecodedCert(der);
  7266. #ifdef WOLFSSL_SMALL_STACK
  7267. XFREE(der, NULL, DYNAMIC_TYPE_DCERT);
  7268. #endif
  7269. return WOLFSSL_FAILURE;
  7270. }
  7271. size = key->length;
  7272. buff = key->buffer;
  7273. #ifdef WOLF_PRIVATE_KEY_ID
  7274. if (devId != INVALID_DEVID) {
  7275. int type = 0;
  7276. void *pkey = NULL;
  7277. #ifndef NO_RSA
  7278. if (der->keyOID == RSAk) {
  7279. type = DYNAMIC_TYPE_RSA;
  7280. }
  7281. #ifdef WC_RSA_PSS
  7282. if (der->keyOID == RSAPSSk) {
  7283. type = DYNAMIC_TYPE_RSA;
  7284. }
  7285. #endif
  7286. #endif
  7287. #ifdef HAVE_ECC
  7288. if (der->keyOID == ECDSAk) {
  7289. type = DYNAMIC_TYPE_ECC;
  7290. }
  7291. #endif
  7292. ret = CreateDevPrivateKey(&pkey, buff, size, type,
  7293. isKeyLabel, isKeyId, heap, devId);
  7294. #ifdef WOLF_CRYPTO_CB
  7295. if (ret == 0) {
  7296. #ifndef NO_RSA
  7297. if (der->keyOID == RSAk
  7298. #ifdef WC_RSA_PSS
  7299. || der->keyOID == RSAPSSk
  7300. #endif
  7301. ) {
  7302. ret = wc_CryptoCb_RsaCheckPrivKey((RsaKey*)pkey,
  7303. der->publicKey, der->pubKeySize);
  7304. }
  7305. #endif
  7306. #ifdef HAVE_ECC
  7307. if (der->keyOID == ECDSAk) {
  7308. ret = wc_CryptoCb_EccCheckPrivKey((ecc_key*)pkey,
  7309. der->publicKey, der->pubKeySize);
  7310. }
  7311. #endif
  7312. }
  7313. #else
  7314. /* devId was set, don't check, for now */
  7315. /* TODO: Add callback for private key check? */
  7316. #endif
  7317. if (pkey != NULL) {
  7318. #ifndef NO_RSA
  7319. if (der->keyOID == RSAk
  7320. #ifdef WC_RSA_PSS
  7321. || der->keyOID == RSAPSSk
  7322. #endif
  7323. ) {
  7324. wc_FreeRsaKey((RsaKey*)pkey);
  7325. }
  7326. #endif
  7327. #ifdef HAVE_ECC
  7328. if (der->keyOID == ECDSAk) {
  7329. wc_ecc_free((ecc_key*)pkey);
  7330. }
  7331. #endif
  7332. XFREE(pkey, heap, type);
  7333. }
  7334. if (ret != CRYPTOCB_UNAVAILABLE) {
  7335. ret = (ret == 0) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE;
  7336. }
  7337. }
  7338. else {
  7339. /* fall through if unavailable */
  7340. ret = CRYPTOCB_UNAVAILABLE;
  7341. }
  7342. if (ret == CRYPTOCB_UNAVAILABLE)
  7343. #endif /* WOLF_PRIVATE_KEY_ID */
  7344. {
  7345. ret = wc_CheckPrivateKeyCert(buff, size, der);
  7346. ret = (ret == 1) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE;
  7347. }
  7348. FreeDecodedCert(der);
  7349. #ifdef WOLFSSL_SMALL_STACK
  7350. XFREE(der, NULL, DYNAMIC_TYPE_DCERT);
  7351. #endif
  7352. (void)devId;
  7353. (void)isKeyLabel;
  7354. (void)isKeyId;
  7355. return ret;
  7356. }
  7357. /* Check private against public in certificate for match
  7358. *
  7359. * ctx WOLFSSL_CTX structure to check private key in
  7360. *
  7361. * Returns WOLFSSL_SUCCESS on good private key
  7362. * WOLFSSL_FAILURE if mismatched. */
  7363. int wolfSSL_CTX_check_private_key(const WOLFSSL_CTX* ctx)
  7364. {
  7365. if (ctx == NULL) {
  7366. return WOLFSSL_FAILURE;
  7367. }
  7368. return check_cert_key(ctx->certificate, ctx->privateKey, ctx->heap,
  7369. ctx->privateKeyDevId, ctx->privateKeyLabel, ctx->privateKeyId);
  7370. }
  7371. #endif /* !NO_CHECK_PRIVATE_KEY */
  7372. #ifdef OPENSSL_ALL
  7373. /**
  7374. * Return the private key of the WOLFSSL_CTX struct
  7375. * @return WOLFSSL_EVP_PKEY* The caller doesn *NOT*` free the returned object.
  7376. */
  7377. WOLFSSL_EVP_PKEY* wolfSSL_CTX_get0_privatekey(const WOLFSSL_CTX* ctx)
  7378. {
  7379. const unsigned char *key;
  7380. int type;
  7381. WOLFSSL_ENTER("wolfSSL_CTX_get0_privatekey");
  7382. if (ctx == NULL || ctx->privateKey == NULL ||
  7383. ctx->privateKey->buffer == NULL) {
  7384. WOLFSSL_MSG("Bad parameter or key not set");
  7385. return NULL;
  7386. }
  7387. switch (ctx->privateKeyType) {
  7388. #ifndef NO_RSA
  7389. case rsa_sa_algo:
  7390. type = EVP_PKEY_RSA;
  7391. break;
  7392. #endif
  7393. #ifdef HAVE_ECC
  7394. case ecc_dsa_sa_algo:
  7395. type = EVP_PKEY_EC;
  7396. break;
  7397. #endif
  7398. default:
  7399. /* Other key types not supported either as ssl private keys
  7400. * or in the EVP layer */
  7401. WOLFSSL_MSG("Unsupported key type");
  7402. return NULL;
  7403. }
  7404. key = ctx->privateKey->buffer;
  7405. if (ctx->privateKeyPKey != NULL)
  7406. return ctx->privateKeyPKey;
  7407. else
  7408. return wolfSSL_d2i_PrivateKey(type,
  7409. (WOLFSSL_EVP_PKEY**)&ctx->privateKeyPKey, &key,
  7410. (long)ctx->privateKey->length);
  7411. }
  7412. #endif
  7413. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  7414. static WOLFSSL_EVP_PKEY* d2iGenericKey(WOLFSSL_EVP_PKEY** out,
  7415. const unsigned char** in, long inSz, int priv)
  7416. {
  7417. WOLFSSL_EVP_PKEY* pkey = NULL;
  7418. const unsigned char* mem;
  7419. long memSz = inSz;
  7420. WOLFSSL_ENTER("d2iGenericKey");
  7421. if (in == NULL || *in == NULL || inSz < 0) {
  7422. WOLFSSL_MSG("Bad argument");
  7423. return NULL;
  7424. }
  7425. mem = *in;
  7426. #if !defined(NO_RSA)
  7427. {
  7428. word32 keyIdx = 0;
  7429. int isRsaKey;
  7430. #ifdef WOLFSSL_SMALL_STACK
  7431. RsaKey *rsa = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  7432. if (rsa == NULL)
  7433. return NULL;
  7434. #else
  7435. RsaKey rsa[1];
  7436. #endif
  7437. XMEMSET(rsa, 0, sizeof(RsaKey));
  7438. /* test if RSA key */
  7439. if (priv)
  7440. isRsaKey = wc_InitRsaKey(rsa, NULL) == 0 &&
  7441. wc_RsaPrivateKeyDecode(mem, &keyIdx, rsa, (word32)memSz) == 0;
  7442. else
  7443. isRsaKey = wc_InitRsaKey(rsa, NULL) == 0 &&
  7444. wc_RsaPublicKeyDecode(mem, &keyIdx, rsa, (word32)memSz) == 0;
  7445. wc_FreeRsaKey(rsa);
  7446. #ifdef WOLFSSL_SMALL_STACK
  7447. XFREE(rsa, NULL, DYNAMIC_TYPE_RSA);
  7448. #endif
  7449. if (isRsaKey) {
  7450. pkey = wolfSSL_EVP_PKEY_new();
  7451. if (pkey != NULL) {
  7452. pkey->pkey_sz = keyIdx;
  7453. pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL,
  7454. priv ? DYNAMIC_TYPE_PRIVATE_KEY :
  7455. DYNAMIC_TYPE_PUBLIC_KEY);
  7456. if (pkey->pkey.ptr == NULL) {
  7457. wolfSSL_EVP_PKEY_free(pkey);
  7458. return NULL;
  7459. }
  7460. XMEMCPY(pkey->pkey.ptr, mem, keyIdx);
  7461. pkey->type = EVP_PKEY_RSA;
  7462. if (out != NULL) {
  7463. *out = pkey;
  7464. }
  7465. pkey->ownRsa = 1;
  7466. pkey->rsa = wolfSSL_RSA_new();
  7467. if (pkey->rsa == NULL) {
  7468. wolfSSL_EVP_PKEY_free(pkey);
  7469. return NULL;
  7470. }
  7471. if (wolfSSL_RSA_LoadDer_ex(pkey->rsa,
  7472. (const unsigned char*)pkey->pkey.ptr,
  7473. pkey->pkey_sz, priv ? WOLFSSL_RSA_LOAD_PRIVATE
  7474. : WOLFSSL_RSA_LOAD_PUBLIC) != 1) {
  7475. wolfSSL_EVP_PKEY_free(pkey);
  7476. return NULL;
  7477. }
  7478. return pkey;
  7479. }
  7480. else {
  7481. WOLFSSL_MSG("RSA wolfSSL_EVP_PKEY_new error");
  7482. }
  7483. }
  7484. }
  7485. #endif /* NO_RSA */
  7486. #if defined(HAVE_ECC) && defined(OPENSSL_EXTRA)
  7487. {
  7488. word32 keyIdx = 0;
  7489. int isEccKey;
  7490. #ifdef WOLFSSL_SMALL_STACK
  7491. ecc_key *ecc = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC);
  7492. if (ecc == NULL)
  7493. return NULL;
  7494. #else
  7495. ecc_key ecc[1];
  7496. #endif
  7497. XMEMSET(ecc, 0, sizeof(ecc_key));
  7498. if (priv)
  7499. isEccKey = wc_ecc_init(ecc) == 0 &&
  7500. wc_EccPrivateKeyDecode(mem, &keyIdx, ecc, (word32)memSz) == 0;
  7501. else
  7502. isEccKey = wc_ecc_init(ecc) == 0 &&
  7503. wc_EccPublicKeyDecode(mem, &keyIdx, ecc, (word32)memSz) == 0;
  7504. wc_ecc_free(ecc);
  7505. #ifdef WOLFSSL_SMALL_STACK
  7506. XFREE(ecc, NULL, DYNAMIC_TYPE_ECC);
  7507. #endif
  7508. if (isEccKey) {
  7509. pkey = wolfSSL_EVP_PKEY_new();
  7510. if (pkey != NULL) {
  7511. pkey->pkey_sz = keyIdx;
  7512. pkey->pkey.ptr = (char*)XMALLOC(keyIdx, NULL,
  7513. priv ? DYNAMIC_TYPE_PRIVATE_KEY :
  7514. DYNAMIC_TYPE_PUBLIC_KEY);
  7515. if (pkey->pkey.ptr == NULL) {
  7516. wolfSSL_EVP_PKEY_free(pkey);
  7517. return NULL;
  7518. }
  7519. XMEMCPY(pkey->pkey.ptr, mem, keyIdx);
  7520. pkey->type = EVP_PKEY_EC;
  7521. if (out != NULL) {
  7522. *out = pkey;
  7523. }
  7524. pkey->ownEcc = 1;
  7525. pkey->ecc = wolfSSL_EC_KEY_new();
  7526. if (pkey->ecc == NULL) {
  7527. wolfSSL_EVP_PKEY_free(pkey);
  7528. return NULL;
  7529. }
  7530. if (wolfSSL_EC_KEY_LoadDer_ex(pkey->ecc,
  7531. (const unsigned char*)pkey->pkey.ptr,
  7532. pkey->pkey_sz, priv ? WOLFSSL_RSA_LOAD_PRIVATE
  7533. : WOLFSSL_RSA_LOAD_PUBLIC) != 1) {
  7534. wolfSSL_EVP_PKEY_free(pkey);
  7535. return NULL;
  7536. }
  7537. return pkey;
  7538. }
  7539. else {
  7540. WOLFSSL_MSG("ECC wolfSSL_EVP_PKEY_new error");
  7541. }
  7542. }
  7543. }
  7544. #endif /* HAVE_ECC && OPENSSL_EXTRA */
  7545. #if !defined(NO_DSA)
  7546. {
  7547. word32 keyIdx = 0;
  7548. int isDsaKey;
  7549. #ifdef WOLFSSL_SMALL_STACK
  7550. DsaKey *dsa = (DsaKey*)XMALLOC(sizeof(DsaKey), NULL, DYNAMIC_TYPE_DSA);
  7551. if (dsa == NULL)
  7552. return NULL;
  7553. #else
  7554. DsaKey dsa[1];
  7555. #endif
  7556. XMEMSET(dsa, 0, sizeof(DsaKey));
  7557. if (priv)
  7558. isDsaKey = wc_InitDsaKey(dsa) == 0 &&
  7559. wc_DsaPrivateKeyDecode(mem, &keyIdx, dsa, (word32)memSz) == 0;
  7560. else
  7561. isDsaKey = wc_InitDsaKey(dsa) == 0 &&
  7562. wc_DsaPublicKeyDecode(mem, &keyIdx, dsa, (word32)memSz) == 0;
  7563. wc_FreeDsaKey(dsa);
  7564. #ifdef WOLFSSL_SMALL_STACK
  7565. XFREE(dsa, NULL, DYNAMIC_TYPE_DSA);
  7566. #endif
  7567. /* test if DSA key */
  7568. if (isDsaKey) {
  7569. pkey = wolfSSL_EVP_PKEY_new();
  7570. if (pkey != NULL) {
  7571. pkey->pkey_sz = keyIdx;
  7572. pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL,
  7573. priv ? DYNAMIC_TYPE_PRIVATE_KEY :
  7574. DYNAMIC_TYPE_PUBLIC_KEY);
  7575. if (pkey->pkey.ptr == NULL) {
  7576. wolfSSL_EVP_PKEY_free(pkey);
  7577. return NULL;
  7578. }
  7579. XMEMCPY(pkey->pkey.ptr, mem, keyIdx);
  7580. pkey->type = EVP_PKEY_DSA;
  7581. if (out != NULL) {
  7582. *out = pkey;
  7583. }
  7584. pkey->ownDsa = 1;
  7585. pkey->dsa = wolfSSL_DSA_new();
  7586. if (pkey->dsa == NULL) {
  7587. wolfSSL_EVP_PKEY_free(pkey);
  7588. return NULL;
  7589. }
  7590. if (wolfSSL_DSA_LoadDer_ex(pkey->dsa,
  7591. (const unsigned char*)pkey->pkey.ptr,
  7592. pkey->pkey_sz, priv ? WOLFSSL_RSA_LOAD_PRIVATE
  7593. : WOLFSSL_RSA_LOAD_PUBLIC) != 1) {
  7594. wolfSSL_EVP_PKEY_free(pkey);
  7595. return NULL;
  7596. }
  7597. return pkey;
  7598. }
  7599. else {
  7600. WOLFSSL_MSG("DSA wolfSSL_EVP_PKEY_new error");
  7601. }
  7602. }
  7603. }
  7604. #endif /* NO_DSA */
  7605. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  7606. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \
  7607. (HAVE_FIPS_VERSION > 2))
  7608. {
  7609. int isDhKey;
  7610. word32 keyIdx = 0;
  7611. #ifdef WOLFSSL_SMALL_STACK
  7612. DhKey *dh = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH);
  7613. if (dh == NULL)
  7614. return NULL;
  7615. #else
  7616. DhKey dh[1];
  7617. #endif
  7618. XMEMSET(dh, 0, sizeof(DhKey));
  7619. isDhKey = wc_InitDhKey(dh) == 0 &&
  7620. wc_DhKeyDecode(mem, &keyIdx, dh, (word32)memSz) == 0;
  7621. wc_FreeDhKey(dh);
  7622. #ifdef WOLFSSL_SMALL_STACK
  7623. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  7624. #endif
  7625. /* test if DH key */
  7626. if (isDhKey) {
  7627. pkey = wolfSSL_EVP_PKEY_new();
  7628. if (pkey != NULL) {
  7629. pkey->pkey_sz = (int)memSz;
  7630. pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL,
  7631. priv ? DYNAMIC_TYPE_PRIVATE_KEY :
  7632. DYNAMIC_TYPE_PUBLIC_KEY);
  7633. if (pkey->pkey.ptr == NULL) {
  7634. wolfSSL_EVP_PKEY_free(pkey);
  7635. return NULL;
  7636. }
  7637. XMEMCPY(pkey->pkey.ptr, mem, memSz);
  7638. pkey->type = EVP_PKEY_DH;
  7639. if (out != NULL) {
  7640. *out = pkey;
  7641. }
  7642. pkey->ownDh = 1;
  7643. pkey->dh = wolfSSL_DH_new();
  7644. if (pkey->dh == NULL) {
  7645. wolfSSL_EVP_PKEY_free(pkey);
  7646. return NULL;
  7647. }
  7648. if (wolfSSL_DH_LoadDer(pkey->dh,
  7649. (const unsigned char*)pkey->pkey.ptr,
  7650. pkey->pkey_sz) != WOLFSSL_SUCCESS) {
  7651. wolfSSL_EVP_PKEY_free(pkey);
  7652. return NULL;
  7653. }
  7654. return pkey;
  7655. }
  7656. else {
  7657. WOLFSSL_MSG("DH wolfSSL_EVP_PKEY_new error");
  7658. }
  7659. }
  7660. }
  7661. #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
  7662. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  7663. #if !defined(NO_DH) && defined(OPENSSL_EXTRA) && defined(WOLFSSL_DH_EXTRA)
  7664. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \
  7665. (HAVE_FIPS_VERSION > 2))
  7666. {
  7667. word32 keyIdx = 0;
  7668. DhKey* key = NULL;
  7669. int ret;
  7670. int elements;
  7671. #ifdef WOLFSSL_SMALL_STACK
  7672. DhKey* dh = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH);
  7673. if (dh == NULL)
  7674. return NULL;
  7675. #else
  7676. DhKey dh[1];
  7677. #endif
  7678. XMEMSET(dh, 0, sizeof(DhKey));
  7679. /* test if DH-public key */
  7680. if (wc_InitDhKey(dh) != 0)
  7681. return NULL;
  7682. ret = wc_DhKeyDecode(mem, &keyIdx, dh, (word32)memSz);
  7683. wc_FreeDhKey(dh);
  7684. #ifdef WOLFSSL_SMALL_STACK
  7685. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  7686. #endif
  7687. if (ret == 0) {
  7688. pkey = wolfSSL_EVP_PKEY_new();
  7689. if (pkey != NULL) {
  7690. pkey->type = EVP_PKEY_DH;
  7691. pkey->pkey_sz = (int)memSz;
  7692. pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL,
  7693. priv ? DYNAMIC_TYPE_PRIVATE_KEY :
  7694. DYNAMIC_TYPE_PUBLIC_KEY);
  7695. if (pkey->pkey.ptr == NULL) {
  7696. wolfSSL_EVP_PKEY_free(pkey);
  7697. return NULL;
  7698. }
  7699. XMEMCPY(pkey->pkey.ptr, mem, memSz);
  7700. if (out != NULL) {
  7701. *out = pkey;
  7702. }
  7703. pkey->ownDh = 1;
  7704. pkey->dh = wolfSSL_DH_new();
  7705. if (pkey->dh == NULL) {
  7706. wolfSSL_EVP_PKEY_free(pkey);
  7707. return NULL;
  7708. }
  7709. key = (DhKey*)pkey->dh->internal;
  7710. keyIdx = 0;
  7711. if (wc_DhKeyDecode(mem, &keyIdx, key, (word32)memSz) == 0)
  7712. {
  7713. elements = ELEMENT_P | ELEMENT_G | ELEMENT_Q | ELEMENT_PUB;
  7714. if (priv)
  7715. elements |= ELEMENT_PRV;
  7716. if(SetDhExternal_ex(pkey->dh, elements)
  7717. == WOLFSSL_SUCCESS ) {
  7718. return pkey;
  7719. }
  7720. }
  7721. else {
  7722. wolfSSL_EVP_PKEY_free(pkey);
  7723. return NULL;
  7724. }
  7725. }
  7726. }
  7727. }
  7728. #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
  7729. #endif /* !NO_DH && OPENSSL_EXTRA && WOLFSSL_DH_EXTRA */
  7730. #ifdef HAVE_PQC
  7731. #ifdef HAVE_FALCON
  7732. {
  7733. int isFalcon = 0;
  7734. #ifdef WOLFSSL_SMALL_STACK
  7735. falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(falcon_key), NULL,
  7736. DYNAMIC_TYPE_FALCON);
  7737. if (falcon == NULL) {
  7738. return NULL;
  7739. }
  7740. #else
  7741. falcon_key falcon[1];
  7742. #endif
  7743. if (wc_falcon_init(falcon) == 0) {
  7744. /* test if Falcon key */
  7745. if (priv) {
  7746. /* Try level 1 */
  7747. isFalcon = wc_falcon_set_level(falcon, 1) == 0 &&
  7748. wc_falcon_import_private_only(mem, (word32)memSz,
  7749. falcon) == 0;
  7750. if (!isFalcon) {
  7751. /* Try level 5 */
  7752. isFalcon = wc_falcon_set_level(falcon, 5) == 0 &&
  7753. wc_falcon_import_private_only(mem, (word32)memSz,
  7754. falcon) == 0;
  7755. }
  7756. } else {
  7757. /* Try level 1 */
  7758. isFalcon = wc_falcon_set_level(falcon, 1) == 0 &&
  7759. wc_falcon_import_public(mem, (word32)memSz, falcon)
  7760. == 0;
  7761. if (!isFalcon) {
  7762. /* Try level 5 */
  7763. isFalcon = wc_falcon_set_level(falcon, 5) == 0 &&
  7764. wc_falcon_import_public(mem, (word32)memSz,
  7765. falcon) == 0;
  7766. }
  7767. }
  7768. wc_falcon_free(falcon);
  7769. }
  7770. #ifdef WOLFSSL_SMALL_STACK
  7771. XFREE(falcon, NULL, DYNAMIC_TYPE_FALCON);
  7772. #endif
  7773. if (isFalcon) {
  7774. /* Create a fake Falcon EVP_PKEY. In the future, we might integrate
  7775. * Falcon into the compatibility layer. */
  7776. pkey = wolfSSL_EVP_PKEY_new();
  7777. if (pkey == NULL) {
  7778. WOLFSSL_MSG("Falcon wolfSSL_EVP_PKEY_new error");
  7779. return NULL;
  7780. }
  7781. pkey->type = EVP_PKEY_FALCON;
  7782. pkey->pkey.ptr = NULL;
  7783. pkey->pkey_sz = 0;
  7784. return pkey;
  7785. }
  7786. }
  7787. #endif /* HAVE_FALCON */
  7788. #ifdef HAVE_DILITHIUM
  7789. {
  7790. int isDilithium = 0;
  7791. #ifdef WOLFSSL_SMALL_STACK
  7792. dilithium_key *dilithium = (dilithium_key *)
  7793. XMALLOC(sizeof(dilithium_key), NULL, DYNAMIC_TYPE_DILITHIUM);
  7794. if (dilithium == NULL) {
  7795. return NULL;
  7796. }
  7797. #else
  7798. dilithium_key dilithium[1];
  7799. #endif
  7800. if (wc_dilithium_init(dilithium) == 0) {
  7801. /* Test if Dilithium key. Try all levels for both SHAKE and AES */
  7802. if (priv) {
  7803. isDilithium = wc_dilithium_set_level_and_sym(dilithium, 2,
  7804. SHAKE_VARIANT) == 0 &&
  7805. wc_dilithium_import_private_only(mem,
  7806. (word32)memSz, dilithium) == 0;
  7807. if (!isDilithium) {
  7808. isDilithium = wc_dilithium_set_level_and_sym(dilithium, 3,
  7809. SHAKE_VARIANT) == 0 &&
  7810. wc_dilithium_import_private_only(mem,
  7811. (word32)memSz, dilithium) == 0;
  7812. }
  7813. if (!isDilithium) {
  7814. isDilithium = wc_dilithium_set_level_and_sym(dilithium, 5,
  7815. SHAKE_VARIANT) == 0 &&
  7816. wc_dilithium_import_private_only(mem,
  7817. (word32)memSz, dilithium) == 0;
  7818. }
  7819. if (!isDilithium) {
  7820. isDilithium = wc_dilithium_set_level_and_sym(dilithium, 2,
  7821. AES_VARIANT) == 0 &&
  7822. wc_dilithium_import_private_only(mem,
  7823. (word32)memSz, dilithium) == 0;
  7824. }
  7825. if (!isDilithium) {
  7826. isDilithium = wc_dilithium_set_level_and_sym(dilithium, 3,
  7827. AES_VARIANT) == 0 &&
  7828. wc_dilithium_import_private_only(mem,
  7829. (word32)memSz, dilithium) == 0;
  7830. }
  7831. if (!isDilithium) {
  7832. isDilithium = wc_dilithium_set_level_and_sym(dilithium, 5,
  7833. AES_VARIANT) == 0 &&
  7834. wc_dilithium_import_private_only(mem,
  7835. (word32)memSz, dilithium) == 0;
  7836. }
  7837. } else {
  7838. isDilithium = wc_dilithium_set_level_and_sym(dilithium, 2,
  7839. SHAKE_VARIANT) == 0 &&
  7840. wc_dilithium_import_public(mem, (word32)memSz,
  7841. dilithium) == 0;
  7842. if (!isDilithium) {
  7843. isDilithium = wc_dilithium_set_level_and_sym(dilithium, 3,
  7844. SHAKE_VARIANT) == 0 &&
  7845. wc_dilithium_import_public(mem, (word32)memSz,
  7846. dilithium) == 0;
  7847. }
  7848. if (!isDilithium) {
  7849. isDilithium = wc_dilithium_set_level_and_sym(dilithium, 5,
  7850. SHAKE_VARIANT) == 0 &&
  7851. wc_dilithium_import_public(mem, (word32)memSz,
  7852. dilithium) == 0;
  7853. }
  7854. if (!isDilithium) {
  7855. isDilithium = wc_dilithium_set_level_and_sym(dilithium, 2,
  7856. AES_VARIANT) == 0 &&
  7857. wc_dilithium_import_public(mem, (word32)memSz,
  7858. dilithium) == 0;
  7859. }
  7860. if (!isDilithium) {
  7861. isDilithium = wc_dilithium_set_level_and_sym(dilithium, 3,
  7862. AES_VARIANT) == 0 &&
  7863. wc_dilithium_import_public(mem, (word32)memSz,
  7864. dilithium) == 0;
  7865. }
  7866. if (!isDilithium) {
  7867. isDilithium = wc_dilithium_set_level_and_sym(dilithium, 5,
  7868. AES_VARIANT) == 0 &&
  7869. wc_dilithium_import_public(mem, (word32)memSz,
  7870. dilithium) == 0;
  7871. }
  7872. }
  7873. wc_dilithium_free(dilithium);
  7874. }
  7875. #ifdef WOLFSSL_SMALL_STACK
  7876. XFREE(dilithium, NULL, DYNAMIC_TYPE_DILITHIUM);
  7877. #endif
  7878. if (isDilithium) {
  7879. /* Create a fake Dilithium EVP_PKEY. In the future, we might
  7880. * integrate Dilithium into the compatibility layer. */
  7881. pkey = wolfSSL_EVP_PKEY_new();
  7882. if (pkey == NULL) {
  7883. WOLFSSL_MSG("Dilithium wolfSSL_EVP_PKEY_new error");
  7884. return NULL;
  7885. }
  7886. pkey->type = EVP_PKEY_DILITHIUM;
  7887. pkey->pkey.ptr = NULL;
  7888. pkey->pkey_sz = 0;
  7889. return pkey;
  7890. }
  7891. }
  7892. #endif /* HAVE_DILITHIUM */
  7893. #endif /* HAVE_PQC */
  7894. if (pkey == NULL) {
  7895. WOLFSSL_MSG("wolfSSL_d2i_PUBKEY couldn't determine key type");
  7896. }
  7897. return pkey;
  7898. }
  7899. #endif /* OPENSSL_EXTRA || WPA_SMALL */
  7900. #ifdef OPENSSL_EXTRA
  7901. WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_d2i_PKCS8_PKEY(
  7902. WOLFSSL_PKCS8_PRIV_KEY_INFO** pkey, const unsigned char** keyBuf, long keyLen)
  7903. {
  7904. WOLFSSL_PKCS8_PRIV_KEY_INFO* pkcs8 = NULL;
  7905. #ifdef WOLFSSL_PEM_TO_DER
  7906. int ret;
  7907. DerBuffer* der = NULL;
  7908. if (keyBuf == NULL || *keyBuf == NULL || keyLen <= 0) {
  7909. WOLFSSL_MSG("Bad key PEM/DER args");
  7910. return NULL;
  7911. }
  7912. ret = PemToDer(*keyBuf, keyLen, PRIVATEKEY_TYPE, &der, NULL, NULL, NULL);
  7913. if (ret < 0) {
  7914. WOLFSSL_MSG("Not PEM format");
  7915. ret = AllocDer(&der, (word32)keyLen, PRIVATEKEY_TYPE, NULL);
  7916. if (ret == 0) {
  7917. XMEMCPY(der->buffer, *keyBuf, keyLen);
  7918. }
  7919. }
  7920. if (ret == 0) {
  7921. /* Verify this is PKCS8 Key */
  7922. word32 inOutIdx = 0;
  7923. word32 algId;
  7924. ret = ToTraditionalInline_ex(der->buffer, &inOutIdx, der->length, &algId);
  7925. if (ret >= 0) {
  7926. ret = 0; /* good DER */
  7927. }
  7928. }
  7929. if (ret == 0) {
  7930. pkcs8 = wolfSSL_EVP_PKEY_new();
  7931. if (pkcs8 == NULL)
  7932. ret = MEMORY_E;
  7933. }
  7934. if (ret == 0) {
  7935. pkcs8->pkey.ptr = (char*)XMALLOC(der->length, NULL,
  7936. DYNAMIC_TYPE_PUBLIC_KEY);
  7937. if (pkcs8->pkey.ptr == NULL)
  7938. ret = MEMORY_E;
  7939. }
  7940. if (ret == 0) {
  7941. XMEMCPY(pkcs8->pkey.ptr, der->buffer, der->length);
  7942. pkcs8->pkey_sz = der->length;
  7943. }
  7944. FreeDer(&der);
  7945. if (ret != 0) {
  7946. wolfSSL_EVP_PKEY_free(pkcs8);
  7947. pkcs8 = NULL;
  7948. }
  7949. if (pkey != NULL) {
  7950. *pkey = pkcs8;
  7951. }
  7952. #else
  7953. (void)bio;
  7954. (void)pkey;
  7955. #endif /* WOLFSSL_PEM_TO_DER */
  7956. return pkcs8;
  7957. }
  7958. #ifndef NO_BIO
  7959. /* put SSL type in extra for now, not very common */
  7960. /* Converts a DER format key read from "bio" to a PKCS8 structure.
  7961. *
  7962. * bio input bio to read DER from
  7963. * pkey If not NULL then this pointer will be overwritten with a new PKCS8
  7964. * structure.
  7965. *
  7966. * returns a WOLFSSL_PKCS8_PRIV_KEY_INFO pointer on success and NULL in fail
  7967. * case.
  7968. */
  7969. WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_d2i_PKCS8_PKEY_bio(WOLFSSL_BIO* bio,
  7970. WOLFSSL_PKCS8_PRIV_KEY_INFO** pkey)
  7971. {
  7972. WOLFSSL_PKCS8_PRIV_KEY_INFO* pkcs8 = NULL;
  7973. #ifdef WOLFSSL_PEM_TO_DER
  7974. unsigned char* mem = NULL;
  7975. int memSz;
  7976. WOLFSSL_ENTER("wolfSSL_d2i_PKCS8_PKEY_bio");
  7977. if (bio == NULL) {
  7978. return NULL;
  7979. }
  7980. if ((memSz = wolfSSL_BIO_get_mem_data(bio, &mem)) < 0) {
  7981. return NULL;
  7982. }
  7983. pkcs8 = wolfSSL_d2i_PKCS8_PKEY(pkey, (const unsigned char**)&mem, memSz);
  7984. #else
  7985. (void)bio;
  7986. (void)pkey;
  7987. #endif /* WOLFSSL_PEM_TO_DER */
  7988. return pkcs8;
  7989. }
  7990. /* expecting DER format public key
  7991. *
  7992. * bio input bio to read DER from
  7993. * out If not NULL then this pointer will be overwritten with a new
  7994. * WOLFSSL_EVP_PKEY pointer
  7995. *
  7996. * returns a WOLFSSL_EVP_PKEY pointer on success and NULL in fail case.
  7997. */
  7998. WOLFSSL_EVP_PKEY* wolfSSL_d2i_PUBKEY_bio(WOLFSSL_BIO* bio,
  7999. WOLFSSL_EVP_PKEY** out)
  8000. {
  8001. unsigned char* mem;
  8002. long memSz;
  8003. WOLFSSL_EVP_PKEY* pkey = NULL;
  8004. WOLFSSL_ENTER("wolfSSL_d2i_PUBKEY_bio()");
  8005. if (bio == NULL) {
  8006. return NULL;
  8007. }
  8008. (void)out;
  8009. memSz = wolfSSL_BIO_get_len(bio);
  8010. if (memSz <= 0) {
  8011. return NULL;
  8012. }
  8013. mem = (unsigned char*)XMALLOC(memSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8014. if (mem == NULL) {
  8015. return NULL;
  8016. }
  8017. if (wolfSSL_BIO_read(bio, mem, (int)memSz) == memSz) {
  8018. pkey = wolfSSL_d2i_PUBKEY(NULL, (const unsigned char**)&mem, memSz);
  8019. if (out != NULL && pkey != NULL) {
  8020. *out = pkey;
  8021. }
  8022. }
  8023. XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8024. return pkey;
  8025. }
  8026. #endif /* !NO_BIO */
  8027. /* Converts a DER encoded public key to a WOLFSSL_EVP_PKEY structure.
  8028. *
  8029. * out pointer to new WOLFSSL_EVP_PKEY structure. Can be NULL
  8030. * in DER buffer to convert
  8031. * inSz size of in buffer
  8032. *
  8033. * returns a pointer to a new WOLFSSL_EVP_PKEY structure on success and NULL
  8034. * on fail
  8035. */
  8036. WOLFSSL_EVP_PKEY* wolfSSL_d2i_PUBKEY(WOLFSSL_EVP_PKEY** out,
  8037. const unsigned char** in, long inSz)
  8038. {
  8039. WOLFSSL_ENTER("wolfSSL_d2i_PUBKEY");
  8040. return d2iGenericKey(out, in, inSz, 0);
  8041. }
  8042. /* helper function to get raw pointer to DER buffer from WOLFSSL_EVP_PKEY */
  8043. static int wolfSSL_EVP_PKEY_get_der(const WOLFSSL_EVP_PKEY* key, unsigned char** der)
  8044. {
  8045. unsigned char* pt;
  8046. int sz;
  8047. word16 pkcs8HeaderSz;
  8048. if (!key || !key->pkey_sz)
  8049. return WOLFSSL_FATAL_ERROR;
  8050. /* return the key without PKCS8 for compatibility */
  8051. /* if pkcs8HeaderSz is invalid, use 0 and return all of pkey */
  8052. pkcs8HeaderSz = 0;
  8053. if (key->pkey_sz > key->pkcs8HeaderSz)
  8054. pkcs8HeaderSz = key->pkcs8HeaderSz;
  8055. sz = key->pkey_sz - pkcs8HeaderSz;
  8056. if (der) {
  8057. pt = (unsigned char*)key->pkey.ptr;
  8058. if (*der) {
  8059. /* since this function signature has no size value passed in it is
  8060. * assumed that the user has allocated a large enough buffer */
  8061. XMEMCPY(*der, pt + pkcs8HeaderSz, sz);
  8062. *der += sz;
  8063. }
  8064. else {
  8065. *der = (unsigned char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_OPENSSL);
  8066. if (*der == NULL) {
  8067. return WOLFSSL_FATAL_ERROR;
  8068. }
  8069. XMEMCPY(*der, pt + pkcs8HeaderSz, sz);
  8070. }
  8071. }
  8072. return sz;
  8073. }
  8074. int wolfSSL_i2d_PUBKEY(const WOLFSSL_EVP_PKEY *key, unsigned char **der)
  8075. {
  8076. return wolfSSL_EVP_PKEY_get_der(key, der);
  8077. }
  8078. static WOLFSSL_EVP_PKEY* _d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** out,
  8079. const unsigned char **in, long inSz, int priv)
  8080. {
  8081. int ret = 0;
  8082. word32 idx = 0, algId;
  8083. word16 pkcs8HeaderSz = 0;
  8084. WOLFSSL_EVP_PKEY* local;
  8085. int opt;
  8086. (void)opt;
  8087. if (in == NULL || inSz < 0) {
  8088. WOLFSSL_MSG("Bad argument");
  8089. return NULL;
  8090. }
  8091. if (priv == 1) {
  8092. /* Check if input buffer has PKCS8 header. In the case that it does not
  8093. * have a PKCS8 header then do not error out. */
  8094. if ((ret = ToTraditionalInline_ex((const byte*)(*in), &idx,
  8095. (word32)inSz, &algId)) > 0) {
  8096. WOLFSSL_MSG("Found PKCS8 header");
  8097. pkcs8HeaderSz = (word16)idx;
  8098. if ((type == EVP_PKEY_RSA && algId != RSAk
  8099. #ifdef WC_RSA_PSS
  8100. && algId != RSAPSSk
  8101. #endif
  8102. ) ||
  8103. (type == EVP_PKEY_EC && algId != ECDSAk) ||
  8104. (type == EVP_PKEY_DSA && algId != DSAk) ||
  8105. (type == EVP_PKEY_DH && algId != DHk)) {
  8106. WOLFSSL_MSG("PKCS8 does not match EVP key type");
  8107. return NULL;
  8108. }
  8109. (void)idx; /* not used */
  8110. }
  8111. else {
  8112. if (ret != ASN_PARSE_E) {
  8113. WOLFSSL_MSG("Unexpected error with trying to remove PKCS8 "
  8114. "header");
  8115. return NULL;
  8116. }
  8117. }
  8118. }
  8119. if (out != NULL && *out != NULL) {
  8120. wolfSSL_EVP_PKEY_free(*out);
  8121. *out = NULL;
  8122. }
  8123. local = wolfSSL_EVP_PKEY_new();
  8124. if (local == NULL) {
  8125. return NULL;
  8126. }
  8127. local->type = type;
  8128. local->pkey_sz = (int)inSz;
  8129. local->pkcs8HeaderSz = pkcs8HeaderSz;
  8130. local->pkey.ptr = (char*)XMALLOC(inSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  8131. if (local->pkey.ptr == NULL) {
  8132. wolfSSL_EVP_PKEY_free(local);
  8133. local = NULL;
  8134. return NULL;
  8135. }
  8136. else {
  8137. XMEMCPY(local->pkey.ptr, *in, inSz);
  8138. }
  8139. switch (type) {
  8140. #ifndef NO_RSA
  8141. case EVP_PKEY_RSA:
  8142. local->ownRsa = 1;
  8143. local->rsa = wolfSSL_RSA_new();
  8144. if (local->rsa == NULL) {
  8145. wolfSSL_EVP_PKEY_free(local);
  8146. return NULL;
  8147. }
  8148. opt = priv ? WOLFSSL_RSA_LOAD_PRIVATE : WOLFSSL_RSA_LOAD_PUBLIC;
  8149. if (wolfSSL_RSA_LoadDer_ex(local->rsa,
  8150. (const unsigned char*)local->pkey.ptr, local->pkey_sz,
  8151. opt) != WOLFSSL_SUCCESS) {
  8152. wolfSSL_EVP_PKEY_free(local);
  8153. return NULL;
  8154. }
  8155. break;
  8156. #endif /* NO_RSA */
  8157. #ifdef HAVE_ECC
  8158. case EVP_PKEY_EC:
  8159. local->ownEcc = 1;
  8160. local->ecc = wolfSSL_EC_KEY_new();
  8161. if (local->ecc == NULL) {
  8162. wolfSSL_EVP_PKEY_free(local);
  8163. return NULL;
  8164. }
  8165. opt = priv ? WOLFSSL_EC_KEY_LOAD_PRIVATE :
  8166. WOLFSSL_EC_KEY_LOAD_PUBLIC;
  8167. if (wolfSSL_EC_KEY_LoadDer_ex(local->ecc,
  8168. (const unsigned char*)local->pkey.ptr, local->pkey_sz,
  8169. opt)
  8170. != WOLFSSL_SUCCESS) {
  8171. wolfSSL_EVP_PKEY_free(local);
  8172. return NULL;
  8173. }
  8174. break;
  8175. #endif /* HAVE_ECC */
  8176. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_OPENSSH)
  8177. #ifndef NO_DSA
  8178. case EVP_PKEY_DSA:
  8179. local->ownDsa = 1;
  8180. local->dsa = wolfSSL_DSA_new();
  8181. if (local->dsa == NULL) {
  8182. wolfSSL_EVP_PKEY_free(local);
  8183. return NULL;
  8184. }
  8185. opt = priv ? WOLFSSL_DSA_LOAD_PRIVATE : WOLFSSL_DSA_LOAD_PUBLIC;
  8186. if (wolfSSL_DSA_LoadDer_ex(local->dsa,
  8187. (const unsigned char*)local->pkey.ptr, local->pkey_sz,
  8188. opt)
  8189. != WOLFSSL_SUCCESS) {
  8190. wolfSSL_EVP_PKEY_free(local);
  8191. return NULL;
  8192. }
  8193. break;
  8194. #endif /* NO_DSA */
  8195. #ifndef NO_DH
  8196. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION>2))
  8197. case EVP_PKEY_DH:
  8198. local->ownDh = 1;
  8199. local->dh = wolfSSL_DH_new();
  8200. if (local->dh == NULL) {
  8201. wolfSSL_EVP_PKEY_free(local);
  8202. return NULL;
  8203. }
  8204. if (wolfSSL_DH_LoadDer(local->dh,
  8205. (const unsigned char*)local->pkey.ptr, local->pkey_sz)
  8206. != WOLFSSL_SUCCESS) {
  8207. wolfSSL_EVP_PKEY_free(local);
  8208. return NULL;
  8209. }
  8210. break;
  8211. #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
  8212. #endif /* HAVE_DH */
  8213. #endif /* WOLFSSL_QT || OPENSSL_ALL || WOLFSSL_OPENSSH */
  8214. default:
  8215. WOLFSSL_MSG("Unsupported key type");
  8216. wolfSSL_EVP_PKEY_free(local);
  8217. return NULL;
  8218. }
  8219. /* advance pointer with success */
  8220. if (local != NULL) {
  8221. if (local->pkey_sz <= (int)inSz) {
  8222. *in += local->pkey_sz;
  8223. }
  8224. if (out != NULL) {
  8225. *out = local;
  8226. }
  8227. }
  8228. return local;
  8229. }
  8230. WOLFSSL_EVP_PKEY* wolfSSL_d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** out,
  8231. const unsigned char **in, long inSz)
  8232. {
  8233. WOLFSSL_ENTER("wolfSSL_d2i_PublicKey");
  8234. return _d2i_PublicKey(type, out, in, inSz, 0);
  8235. }
  8236. /* Reads in a DER format key. If PKCS8 headers are found they are stripped off.
  8237. *
  8238. * type type of key
  8239. * out newly created WOLFSSL_EVP_PKEY structure
  8240. * in pointer to input key DER
  8241. * inSz size of in buffer
  8242. *
  8243. * On success a non null pointer is returned and the pointer in is advanced the
  8244. * same number of bytes read.
  8245. */
  8246. WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey(int type, WOLFSSL_EVP_PKEY** out,
  8247. const unsigned char **in, long inSz)
  8248. {
  8249. WOLFSSL_ENTER("wolfSSL_d2i_PrivateKey");
  8250. return _d2i_PublicKey(type, out, in, inSz, 1);
  8251. }
  8252. #ifdef WOLF_PRIVATE_KEY_ID
  8253. /* Create an EVP structure for use with crypto callbacks */
  8254. WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_id(int type, WOLFSSL_EVP_PKEY** out,
  8255. void* heap, int devId)
  8256. {
  8257. WOLFSSL_EVP_PKEY* local;
  8258. if (out != NULL && *out != NULL) {
  8259. wolfSSL_EVP_PKEY_free(*out);
  8260. *out = NULL;
  8261. }
  8262. local = wolfSSL_EVP_PKEY_new_ex(heap);
  8263. if (local == NULL) {
  8264. return NULL;
  8265. }
  8266. local->type = type;
  8267. local->pkey_sz = 0;
  8268. local->pkcs8HeaderSz = 0;
  8269. switch (type) {
  8270. #ifndef NO_RSA
  8271. case EVP_PKEY_RSA:
  8272. {
  8273. RsaKey* key;
  8274. local->ownRsa = 1;
  8275. local->rsa = wolfSSL_RSA_new_ex(heap, devId);
  8276. if (local->rsa == NULL) {
  8277. wolfSSL_EVP_PKEY_free(local);
  8278. return NULL;
  8279. }
  8280. key = (RsaKey*)local->rsa->internal;
  8281. #ifdef WOLF_CRYPTO_CB
  8282. key->devId = devId;
  8283. #endif
  8284. (void)key;
  8285. local->rsa->inSet = 1;
  8286. break;
  8287. }
  8288. #endif /* !NO_RSA */
  8289. #ifdef HAVE_ECC
  8290. case EVP_PKEY_EC:
  8291. {
  8292. ecc_key* key;
  8293. local->ownEcc = 1;
  8294. local->ecc = wolfSSL_EC_KEY_new_ex(heap, devId);
  8295. if (local->ecc == NULL) {
  8296. wolfSSL_EVP_PKEY_free(local);
  8297. return NULL;
  8298. }
  8299. key = (ecc_key*)local->ecc->internal;
  8300. #ifdef WOLF_CRYPTO_CB
  8301. key->devId = devId;
  8302. #endif
  8303. key->type = ECC_PRIVATEKEY;
  8304. /* key is required to have a key size / curve set, although
  8305. * actual one used is determined by devId callback function */
  8306. wc_ecc_set_curve(key, ECDHE_SIZE, ECC_CURVE_DEF);
  8307. local->ecc->inSet = 1;
  8308. break;
  8309. }
  8310. #endif /* HAVE_ECC */
  8311. default:
  8312. WOLFSSL_MSG("Unsupported private key id type");
  8313. wolfSSL_EVP_PKEY_free(local);
  8314. return NULL;
  8315. }
  8316. if (local != NULL && out != NULL) {
  8317. *out = local;
  8318. }
  8319. return local;
  8320. }
  8321. #endif /* WOLF_PRIVATE_KEY_ID */
  8322. #ifndef NO_CERTS // NOLINT(readability-redundant-preprocessor)
  8323. #ifndef NO_CHECK_PRIVATE_KEY
  8324. /* Check private against public in certificate for match
  8325. *
  8326. * ssl WOLFSSL structure to check private key in
  8327. *
  8328. * Returns WOLFSSL_SUCCESS on good private key
  8329. * WOLFSSL_FAILURE if mismatched. */
  8330. int wolfSSL_check_private_key(const WOLFSSL* ssl)
  8331. {
  8332. if (ssl == NULL) {
  8333. return WOLFSSL_FAILURE;
  8334. }
  8335. return check_cert_key(ssl->buffers.certificate, ssl->buffers.key, ssl->heap,
  8336. ssl->buffers.keyDevId, ssl->buffers.keyLabel, ssl->buffers.keyId);
  8337. }
  8338. #endif /* !NO_CHECK_PRIVATE_KEY */
  8339. #if defined(OPENSSL_ALL)
  8340. int wolfSSL_ASN1_BIT_STRING_set_bit(WOLFSSL_ASN1_BIT_STRING* str, int pos,
  8341. int val)
  8342. {
  8343. int bytes_cnt, bit;
  8344. byte* temp;
  8345. if (!str || (val != 0 && val != 1) || pos < 0) {
  8346. return WOLFSSL_FAILURE;
  8347. }
  8348. bytes_cnt = pos/8;
  8349. bit = 1<<(7-(pos%8));
  8350. if (bytes_cnt+1 > str->length) {
  8351. if (!(temp = (byte*)XREALLOC(str->data, bytes_cnt+1, NULL,
  8352. DYNAMIC_TYPE_OPENSSL))) {
  8353. return WOLFSSL_FAILURE;
  8354. }
  8355. XMEMSET(temp+str->length, 0, bytes_cnt+1 - str->length);
  8356. str->data = temp;
  8357. str->length = bytes_cnt+1;
  8358. }
  8359. str->data[bytes_cnt] &= ~bit;
  8360. str->data[bytes_cnt] |= val ? bit : 0;
  8361. return WOLFSSL_SUCCESS;
  8362. }
  8363. #endif /* OPENSSL_ALL */
  8364. #endif /* !NO_CERTS */
  8365. #endif /* OPENSSL_EXTRA */
  8366. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  8367. WOLFSSL_ASN1_BIT_STRING* wolfSSL_ASN1_BIT_STRING_new(void)
  8368. {
  8369. WOLFSSL_ASN1_BIT_STRING* str;
  8370. str = (WOLFSSL_ASN1_BIT_STRING*)XMALLOC(sizeof(WOLFSSL_ASN1_BIT_STRING),
  8371. NULL, DYNAMIC_TYPE_OPENSSL);
  8372. if (str) {
  8373. XMEMSET(str, 0, sizeof(WOLFSSL_ASN1_BIT_STRING));
  8374. }
  8375. return str;
  8376. }
  8377. void wolfSSL_ASN1_BIT_STRING_free(WOLFSSL_ASN1_BIT_STRING* str)
  8378. {
  8379. if (str) {
  8380. if (str->data) {
  8381. XFREE(str->data, NULL, DYNAMIC_TYPE_OPENSSL);
  8382. str->data = NULL;
  8383. }
  8384. XFREE(str, NULL, DYNAMIC_TYPE_OPENSSL);
  8385. }
  8386. }
  8387. int wolfSSL_ASN1_BIT_STRING_get_bit(const WOLFSSL_ASN1_BIT_STRING* str, int i)
  8388. {
  8389. if (!str || !str->data || str->length <= (i/8) || i < 0) {
  8390. return WOLFSSL_FAILURE;
  8391. }
  8392. return (str->data[i/8] & (1<<(7-(i%8)))) ? 1 : 0;
  8393. }
  8394. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  8395. #ifdef OPENSSL_EXTRA
  8396. int wolfSSL_use_PrivateKey(WOLFSSL* ssl, WOLFSSL_EVP_PKEY* pkey)
  8397. {
  8398. WOLFSSL_ENTER("wolfSSL_use_PrivateKey");
  8399. if (ssl == NULL || pkey == NULL ) {
  8400. return WOLFSSL_FAILURE;
  8401. }
  8402. return wolfSSL_use_PrivateKey_buffer(ssl, (unsigned char*)pkey->pkey.ptr,
  8403. pkey->pkey_sz, WOLFSSL_FILETYPE_ASN1);
  8404. }
  8405. int wolfSSL_use_PrivateKey_ASN1(int pri, WOLFSSL* ssl, const unsigned char* der,
  8406. long derSz)
  8407. {
  8408. WOLFSSL_ENTER("wolfSSL_use_PrivateKey_ASN1");
  8409. if (ssl == NULL || der == NULL ) {
  8410. return WOLFSSL_FAILURE;
  8411. }
  8412. (void)pri; /* type of private key */
  8413. return wolfSSL_use_PrivateKey_buffer(ssl, der, derSz, WOLFSSL_FILETYPE_ASN1);
  8414. }
  8415. /******************************************************************************
  8416. * wolfSSL_CTX_use_PrivateKey_ASN1 - loads a private key buffer into the SSL ctx
  8417. *
  8418. * RETURNS:
  8419. * returns WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE
  8420. */
  8421. int wolfSSL_CTX_use_PrivateKey_ASN1(int pri, WOLFSSL_CTX* ctx,
  8422. unsigned char* der, long derSz)
  8423. {
  8424. WOLFSSL_ENTER("wolfSSL_CTX_use_PrivateKey_ASN1");
  8425. if (ctx == NULL || der == NULL ) {
  8426. return WOLFSSL_FAILURE;
  8427. }
  8428. (void)pri; /* type of private key */
  8429. return wolfSSL_CTX_use_PrivateKey_buffer(ctx, der, derSz, WOLFSSL_FILETYPE_ASN1);
  8430. }
  8431. #ifndef NO_RSA
  8432. int wolfSSL_use_RSAPrivateKey_ASN1(WOLFSSL* ssl, unsigned char* der, long derSz)
  8433. {
  8434. WOLFSSL_ENTER("wolfSSL_use_RSAPrivateKey_ASN1");
  8435. if (ssl == NULL || der == NULL ) {
  8436. return WOLFSSL_FAILURE;
  8437. }
  8438. return wolfSSL_use_PrivateKey_buffer(ssl, der, derSz, WOLFSSL_FILETYPE_ASN1);
  8439. }
  8440. #endif
  8441. int wolfSSL_use_certificate(WOLFSSL* ssl, WOLFSSL_X509* x509)
  8442. {
  8443. long idx;
  8444. WOLFSSL_ENTER("wolfSSL_use_certificate");
  8445. if (x509 != NULL && ssl != NULL && x509->derCert != NULL) {
  8446. if (ProcessBuffer(NULL, x509->derCert->buffer, x509->derCert->length,
  8447. WOLFSSL_FILETYPE_ASN1, CERT_TYPE, ssl, &idx, 0,
  8448. GET_VERIFY_SETTING_SSL(ssl)) == WOLFSSL_SUCCESS) {
  8449. return WOLFSSL_SUCCESS;
  8450. }
  8451. }
  8452. (void)idx;
  8453. return WOLFSSL_FAILURE;
  8454. }
  8455. #endif /* OPENSSL_EXTRA */
  8456. int wolfSSL_use_certificate_ASN1(WOLFSSL* ssl, const unsigned char* der,
  8457. int derSz)
  8458. {
  8459. long idx;
  8460. WOLFSSL_ENTER("wolfSSL_use_certificate_ASN1");
  8461. if (der != NULL && ssl != NULL) {
  8462. if (ProcessBuffer(NULL, der, derSz, WOLFSSL_FILETYPE_ASN1, CERT_TYPE,
  8463. ssl, &idx, 0, GET_VERIFY_SETTING_SSL(ssl)) == WOLFSSL_SUCCESS) {
  8464. return WOLFSSL_SUCCESS;
  8465. }
  8466. }
  8467. (void)idx;
  8468. return WOLFSSL_FAILURE;
  8469. }
  8470. #ifndef NO_FILESYSTEM
  8471. WOLFSSL_ABI
  8472. int wolfSSL_use_certificate_file(WOLFSSL* ssl, const char* file, int format)
  8473. {
  8474. WOLFSSL_ENTER("wolfSSL_use_certificate_file");
  8475. if (ssl == NULL) {
  8476. return BAD_FUNC_ARG;
  8477. }
  8478. if (ProcessFile(ssl->ctx, file, format, CERT_TYPE,
  8479. ssl, 0, NULL, GET_VERIFY_SETTING_SSL(ssl)) == WOLFSSL_SUCCESS) {
  8480. return WOLFSSL_SUCCESS;
  8481. }
  8482. return WOLFSSL_FAILURE;
  8483. }
  8484. WOLFSSL_ABI
  8485. int wolfSSL_use_PrivateKey_file(WOLFSSL* ssl, const char* file, int format)
  8486. {
  8487. WOLFSSL_ENTER("wolfSSL_use_PrivateKey_file");
  8488. if (ssl == NULL) {
  8489. return BAD_FUNC_ARG;
  8490. }
  8491. if (ProcessFile(ssl->ctx, file, format, PRIVATEKEY_TYPE,
  8492. ssl, 0, NULL, GET_VERIFY_SETTING_SSL(ssl)) == WOLFSSL_SUCCESS) {
  8493. return WOLFSSL_SUCCESS;
  8494. }
  8495. return WOLFSSL_FAILURE;
  8496. }
  8497. WOLFSSL_ABI
  8498. int wolfSSL_use_certificate_chain_file(WOLFSSL* ssl, const char* file)
  8499. {
  8500. /* process up to MAX_CHAIN_DEPTH plus subject cert */
  8501. WOLFSSL_ENTER("wolfSSL_use_certificate_chain_file");
  8502. if (ssl == NULL) {
  8503. return BAD_FUNC_ARG;
  8504. }
  8505. if (ProcessFile(ssl->ctx, file, WOLFSSL_FILETYPE_PEM, CERT_TYPE,
  8506. ssl, 1, NULL, GET_VERIFY_SETTING_SSL(ssl)) == WOLFSSL_SUCCESS) {
  8507. return WOLFSSL_SUCCESS;
  8508. }
  8509. return WOLFSSL_FAILURE;
  8510. }
  8511. int wolfSSL_use_certificate_chain_file_format(WOLFSSL* ssl, const char* file,
  8512. int format)
  8513. {
  8514. /* process up to MAX_CHAIN_DEPTH plus subject cert */
  8515. WOLFSSL_ENTER("wolfSSL_use_certificate_chain_file_format");
  8516. if (ssl == NULL) {
  8517. return BAD_FUNC_ARG;
  8518. }
  8519. if (ProcessFile(ssl->ctx, file, format, CERT_TYPE, ssl, 1,
  8520. NULL, GET_VERIFY_SETTING_SSL(ssl)) == WOLFSSL_SUCCESS) {
  8521. return WOLFSSL_SUCCESS;
  8522. }
  8523. return WOLFSSL_FAILURE;
  8524. }
  8525. #endif /* !NO_FILESYSTEM */
  8526. #ifdef HAVE_ECC
  8527. /* Set Temp CTX EC-DHE size in octets, can be 14 - 66 (112 - 521 bit) */
  8528. int wolfSSL_CTX_SetTmpEC_DHE_Sz(WOLFSSL_CTX* ctx, word16 sz)
  8529. {
  8530. if (ctx == NULL)
  8531. return BAD_FUNC_ARG;
  8532. /* if 0 then get from loaded private key */
  8533. if (sz == 0) {
  8534. /* applies only to ECDSA */
  8535. if (ctx->privateKeyType != ecc_dsa_sa_algo)
  8536. return WOLFSSL_SUCCESS;
  8537. if (ctx->privateKeySz == 0) {
  8538. WOLFSSL_MSG("Must set private key/cert first");
  8539. return BAD_FUNC_ARG;
  8540. }
  8541. sz = (word16)ctx->privateKeySz;
  8542. }
  8543. /* check size */
  8544. if (sz < ECC_MINSIZE || sz > ECC_MAXSIZE)
  8545. return BAD_FUNC_ARG;
  8546. ctx->eccTempKeySz = sz;
  8547. return WOLFSSL_SUCCESS;
  8548. }
  8549. /* Set Temp SSL EC-DHE size in octets, can be 14 - 66 (112 - 521 bit) */
  8550. int wolfSSL_SetTmpEC_DHE_Sz(WOLFSSL* ssl, word16 sz)
  8551. {
  8552. if (ssl == NULL)
  8553. return BAD_FUNC_ARG;
  8554. /* check size */
  8555. if (sz < ECC_MINSIZE || sz > ECC_MAXSIZE)
  8556. return BAD_FUNC_ARG;
  8557. ssl->eccTempKeySz = sz;
  8558. return WOLFSSL_SUCCESS;
  8559. }
  8560. #endif /* HAVE_ECC */
  8561. #ifdef OPENSSL_EXTRA
  8562. #ifndef NO_FILESYSTEM
  8563. int wolfSSL_CTX_use_RSAPrivateKey_file(WOLFSSL_CTX* ctx,const char* file,
  8564. int format)
  8565. {
  8566. WOLFSSL_ENTER("SSL_CTX_use_RSAPrivateKey_file");
  8567. return wolfSSL_CTX_use_PrivateKey_file(ctx, file, format);
  8568. }
  8569. int wolfSSL_use_RSAPrivateKey_file(WOLFSSL* ssl, const char* file, int format)
  8570. {
  8571. WOLFSSL_ENTER("wolfSSL_use_RSAPrivateKey_file");
  8572. return wolfSSL_use_PrivateKey_file(ssl, file, format);
  8573. }
  8574. #endif /* NO_FILESYSTEM */
  8575. /* Copies the master secret over to out buffer. If outSz is 0 returns the size
  8576. * of master secret.
  8577. *
  8578. * ses : a session from completed TLS/SSL handshake
  8579. * out : buffer to hold copy of master secret
  8580. * outSz : size of out buffer
  8581. * returns : number of bytes copied into out buffer on success
  8582. * less then or equal to 0 is considered a failure case
  8583. */
  8584. int wolfSSL_SESSION_get_master_key(const WOLFSSL_SESSION* ses,
  8585. unsigned char* out, int outSz)
  8586. {
  8587. int size;
  8588. ses = ClientSessionToSession(ses);
  8589. if (outSz == 0) {
  8590. return SECRET_LEN;
  8591. }
  8592. if (ses == NULL || out == NULL || outSz < 0) {
  8593. return 0;
  8594. }
  8595. if (outSz > SECRET_LEN) {
  8596. size = SECRET_LEN;
  8597. }
  8598. else {
  8599. size = outSz;
  8600. }
  8601. XMEMCPY(out, ses->masterSecret, size);
  8602. return size;
  8603. }
  8604. int wolfSSL_SESSION_get_master_key_length(const WOLFSSL_SESSION* ses)
  8605. {
  8606. (void)ses;
  8607. return SECRET_LEN;
  8608. }
  8609. #ifdef WOLFSSL_EARLY_DATA
  8610. unsigned int wolfSSL_SESSION_get_max_early_data(const WOLFSSL_SESSION *session)
  8611. {
  8612. return session->maxEarlyDataSz;
  8613. }
  8614. #endif /* WOLFSSL_EARLY_DATA */
  8615. #endif /* OPENSSL_EXTRA */
  8616. typedef struct {
  8617. byte verifyPeer:1;
  8618. byte verifyNone:1;
  8619. byte failNoCert:1;
  8620. byte failNoCertxPSK:1;
  8621. byte verifyPostHandshake:1;
  8622. } SetVerifyOptions;
  8623. static SetVerifyOptions ModeToVerifyOptions(int mode)
  8624. {
  8625. SetVerifyOptions opts;
  8626. XMEMSET(&opts, 0, sizeof(SetVerifyOptions));
  8627. if (mode != WOLFSSL_VERIFY_DEFAULT) {
  8628. opts.verifyNone = (mode == WOLFSSL_VERIFY_NONE);
  8629. if (!opts.verifyNone) {
  8630. opts.verifyPeer =
  8631. (mode & WOLFSSL_VERIFY_PEER) != 0;
  8632. opts.failNoCertxPSK =
  8633. (mode & WOLFSSL_VERIFY_FAIL_EXCEPT_PSK) != 0;
  8634. opts.failNoCert =
  8635. (mode & WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT) != 0;
  8636. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  8637. opts.verifyPostHandshake =
  8638. (mode & WOLFSSL_VERIFY_POST_HANDSHAKE) != 0;
  8639. #endif
  8640. }
  8641. }
  8642. return opts;
  8643. }
  8644. WOLFSSL_ABI
  8645. void wolfSSL_CTX_set_verify(WOLFSSL_CTX* ctx, int mode, VerifyCallback vc)
  8646. {
  8647. SetVerifyOptions opts;
  8648. WOLFSSL_ENTER("wolfSSL_CTX_set_verify");
  8649. if (ctx == NULL)
  8650. return;
  8651. opts = ModeToVerifyOptions(mode);
  8652. ctx->verifyNone = opts.verifyNone;
  8653. ctx->verifyPeer = opts.verifyPeer;
  8654. ctx->failNoCert = opts.failNoCert;
  8655. ctx->failNoCertxPSK = opts.failNoCertxPSK;
  8656. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  8657. ctx->verifyPostHandshake = opts.verifyPostHandshake;
  8658. #endif
  8659. ctx->verifyCallback = vc;
  8660. }
  8661. #ifdef OPENSSL_ALL
  8662. void wolfSSL_CTX_set_cert_verify_callback(WOLFSSL_CTX* ctx,
  8663. CertVerifyCallback cb, void* arg)
  8664. {
  8665. WOLFSSL_ENTER("SSL_CTX_set_cert_verify_callback");
  8666. if (ctx == NULL)
  8667. return;
  8668. ctx->verifyCertCb = cb;
  8669. ctx->verifyCertCbArg = arg;
  8670. }
  8671. #endif
  8672. void wolfSSL_set_verify(WOLFSSL* ssl, int mode, VerifyCallback vc)
  8673. {
  8674. SetVerifyOptions opts;
  8675. WOLFSSL_ENTER("wolfSSL_set_verify");
  8676. if (ssl == NULL)
  8677. return;
  8678. opts = ModeToVerifyOptions(mode);
  8679. ssl->options.verifyNone = opts.verifyNone;
  8680. ssl->options.verifyPeer = opts.verifyPeer;
  8681. ssl->options.failNoCert = opts.failNoCert;
  8682. ssl->options.failNoCertxPSK = opts.failNoCertxPSK;
  8683. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  8684. ssl->options.verifyPostHandshake = opts.verifyPostHandshake;
  8685. #endif
  8686. ssl->verifyCallback = vc;
  8687. }
  8688. void wolfSSL_set_verify_result(WOLFSSL *ssl, long v)
  8689. {
  8690. WOLFSSL_ENTER("wolfSSL_set_verify_result");
  8691. if (ssl == NULL)
  8692. return;
  8693. #ifdef OPENSSL_ALL
  8694. ssl->verifyCallbackResult = v;
  8695. #else
  8696. (void)v;
  8697. WOLFSSL_STUB("wolfSSL_set_verify_result");
  8698. #endif
  8699. }
  8700. #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \
  8701. defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  8702. /* For TLS v1.3 send handshake messages after handshake completes. */
  8703. /* Returns 1=WOLFSSL_SUCCESS or 0=WOLFSSL_FAILURE */
  8704. int wolfSSL_verify_client_post_handshake(WOLFSSL* ssl)
  8705. {
  8706. int ret = wolfSSL_request_certificate(ssl);
  8707. if (ret != WOLFSSL_SUCCESS) {
  8708. if (!IsAtLeastTLSv1_3(ssl->version)) {
  8709. /* specific error of wrong version expected */
  8710. WOLFSSL_ERROR(UNSUPPORTED_PROTO_VERSION);
  8711. }
  8712. else {
  8713. WOLFSSL_ERROR(ret); /* log the error in the error queue */
  8714. }
  8715. }
  8716. return (ret == WOLFSSL_SUCCESS) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
  8717. }
  8718. int wolfSSL_CTX_set_post_handshake_auth(WOLFSSL_CTX* ctx, int val)
  8719. {
  8720. int ret = wolfSSL_CTX_allow_post_handshake_auth(ctx);
  8721. if (ret == 0) {
  8722. ctx->postHandshakeAuth = (val != 0);
  8723. }
  8724. return (ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
  8725. }
  8726. int wolfSSL_set_post_handshake_auth(WOLFSSL* ssl, int val)
  8727. {
  8728. int ret = wolfSSL_allow_post_handshake_auth(ssl);
  8729. if (ret == 0) {
  8730. ssl->options.postHandshakeAuth = (val != 0);
  8731. }
  8732. return (ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
  8733. }
  8734. #endif /* OPENSSL_EXTRA && !NO_CERTS && WOLFSSL_TLS13 && WOLFSSL_POST_HANDSHAKE_AUTH */
  8735. /* store user ctx for verify callback */
  8736. void wolfSSL_SetCertCbCtx(WOLFSSL* ssl, void* ctx)
  8737. {
  8738. WOLFSSL_ENTER("wolfSSL_SetCertCbCtx");
  8739. if (ssl)
  8740. ssl->verifyCbCtx = ctx;
  8741. }
  8742. /* store user ctx for verify callback */
  8743. void wolfSSL_CTX_SetCertCbCtx(WOLFSSL_CTX* ctx, void* userCtx)
  8744. {
  8745. WOLFSSL_ENTER("wolfSSL_CTX_SetCertCbCtx");
  8746. if (ctx)
  8747. ctx->verifyCbCtx = userCtx;
  8748. }
  8749. /* store context CA Cache addition callback */
  8750. void wolfSSL_CTX_SetCACb(WOLFSSL_CTX* ctx, CallbackCACache cb)
  8751. {
  8752. if (ctx && ctx->cm)
  8753. ctx->cm->caCacheCallback = cb;
  8754. }
  8755. #if defined(PERSIST_CERT_CACHE)
  8756. #if !defined(NO_FILESYSTEM)
  8757. /* Persist cert cache to file */
  8758. int wolfSSL_CTX_save_cert_cache(WOLFSSL_CTX* ctx, const char* fname)
  8759. {
  8760. WOLFSSL_ENTER("wolfSSL_CTX_save_cert_cache");
  8761. if (ctx == NULL || fname == NULL)
  8762. return BAD_FUNC_ARG;
  8763. return CM_SaveCertCache(ctx->cm, fname);
  8764. }
  8765. /* Persist cert cache from file */
  8766. int wolfSSL_CTX_restore_cert_cache(WOLFSSL_CTX* ctx, const char* fname)
  8767. {
  8768. WOLFSSL_ENTER("wolfSSL_CTX_restore_cert_cache");
  8769. if (ctx == NULL || fname == NULL)
  8770. return BAD_FUNC_ARG;
  8771. return CM_RestoreCertCache(ctx->cm, fname);
  8772. }
  8773. #endif /* NO_FILESYSTEM */
  8774. /* Persist cert cache to memory */
  8775. int wolfSSL_CTX_memsave_cert_cache(WOLFSSL_CTX* ctx, void* mem,
  8776. int sz, int* used)
  8777. {
  8778. WOLFSSL_ENTER("wolfSSL_CTX_memsave_cert_cache");
  8779. if (ctx == NULL || mem == NULL || used == NULL || sz <= 0)
  8780. return BAD_FUNC_ARG;
  8781. return CM_MemSaveCertCache(ctx->cm, mem, sz, used);
  8782. }
  8783. /* Restore cert cache from memory */
  8784. int wolfSSL_CTX_memrestore_cert_cache(WOLFSSL_CTX* ctx, const void* mem, int sz)
  8785. {
  8786. WOLFSSL_ENTER("wolfSSL_CTX_memrestore_cert_cache");
  8787. if (ctx == NULL || mem == NULL || sz <= 0)
  8788. return BAD_FUNC_ARG;
  8789. return CM_MemRestoreCertCache(ctx->cm, mem, sz);
  8790. }
  8791. /* get how big the the cert cache save buffer needs to be */
  8792. int wolfSSL_CTX_get_cert_cache_memsize(WOLFSSL_CTX* ctx)
  8793. {
  8794. WOLFSSL_ENTER("wolfSSL_CTX_get_cert_cache_memsize");
  8795. if (ctx == NULL)
  8796. return BAD_FUNC_ARG;
  8797. return CM_GetCertCacheMemSize(ctx->cm);
  8798. }
  8799. #endif /* PERSIST_CERT_CACHE */
  8800. #endif /* !NO_CERTS */
  8801. #ifndef NO_SESSION_CACHE
  8802. WOLFSSL_ABI
  8803. WOLFSSL_SESSION* wolfSSL_get_session(WOLFSSL* ssl)
  8804. {
  8805. WOLFSSL_ENTER("SSL_get_session");
  8806. if (ssl) {
  8807. #ifdef NO_SESSION_CACHE_REF
  8808. return ssl->session;
  8809. #else
  8810. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  8811. /* On the client side we want to return a persistant reference for
  8812. * backwards compatibility. */
  8813. #ifndef NO_CLIENT_CACHE
  8814. if (ssl->clientSession) {
  8815. return (WOLFSSL_SESSION*)ssl->clientSession;
  8816. }
  8817. else {
  8818. /* Try to add a ClientCache entry to associate with the current
  8819. * session. Ignore any session cache options. */
  8820. int err;
  8821. const byte* id = ssl->session->sessionID;
  8822. byte idSz = ssl->session->sessionIDSz;
  8823. if (ssl->session->haveAltSessionID) {
  8824. id = ssl->session->altSessionID;
  8825. idSz = ID_LEN;
  8826. }
  8827. err = AddSessionToCache(ssl->ctx, ssl->session, id, idSz,
  8828. NULL, ssl->session->side,
  8829. #ifdef HAVE_SESSION_TICKET
  8830. ssl->session->ticketLen > 0,
  8831. #else
  8832. 0,
  8833. #endif
  8834. &ssl->clientSession);
  8835. if (err == 0) {
  8836. return (WOLFSSL_SESSION*)ssl->clientSession;
  8837. }
  8838. }
  8839. #endif
  8840. }
  8841. else {
  8842. return ssl->session;
  8843. }
  8844. #endif
  8845. }
  8846. return NULL;
  8847. }
  8848. /* The get1 version requires caller to call SSL_SESSION_free */
  8849. WOLFSSL_SESSION* wolfSSL_get1_session(WOLFSSL* ssl)
  8850. {
  8851. WOLFSSL_SESSION* sess = NULL;
  8852. WOLFSSL_ENTER("SSL_get1_session");
  8853. if (ssl != NULL) {
  8854. sess = ssl->session;
  8855. if (sess != NULL) {
  8856. /* increase reference count if allocated session */
  8857. if (sess->type == WOLFSSL_SESSION_TYPE_HEAP) {
  8858. if (wolfSSL_SESSION_up_ref(sess) != WOLFSSL_SUCCESS)
  8859. sess = NULL;
  8860. }
  8861. }
  8862. }
  8863. return sess;
  8864. }
  8865. /*
  8866. * Sets the session object to use when establishing a TLS/SSL session using
  8867. * the ssl object. Therefore, this function must be called before
  8868. * wolfSSL_connect. The session object to use can be obtained in a previous
  8869. * TLS/SSL connection using wolfSSL_get_session.
  8870. *
  8871. * This function rejects the session if it has been expired when this function
  8872. * is called. Note that this expiration check is wolfSSL specific and differs
  8873. * from OpenSSL return code behavior.
  8874. *
  8875. * By default, wolfSSL_set_session returns WOLFSSL_SUCCESS on successfully
  8876. * setting the session, WOLFSSL_FAILURE on failure due to the session cache
  8877. * being disabled, or the session has expired.
  8878. *
  8879. * To match OpenSSL return code behavior when session is expired, define
  8880. * OPENSSL_EXTRA and WOLFSSL_ERROR_CODE_OPENSSL. This behavior will return
  8881. * WOLFSSL_SUCCESS even when the session is expired and rejected.
  8882. */
  8883. WOLFSSL_ABI
  8884. int wolfSSL_set_session(WOLFSSL* ssl, WOLFSSL_SESSION* session)
  8885. {
  8886. WOLFSSL_ENTER("SSL_set_session");
  8887. if (session)
  8888. return wolfSSL_SetSession(ssl, session);
  8889. return WOLFSSL_FAILURE;
  8890. }
  8891. #ifndef NO_CLIENT_CACHE
  8892. /* Associate client session with serverID, find existing or store for saving
  8893. if newSession flag on, don't reuse existing session
  8894. WOLFSSL_SUCCESS on ok */
  8895. int wolfSSL_SetServerID(WOLFSSL* ssl, const byte* id, int len, int newSession)
  8896. {
  8897. WOLFSSL_SESSION* session = NULL;
  8898. WOLFSSL_ENTER("wolfSSL_SetServerID");
  8899. if (ssl == NULL || id == NULL || len <= 0)
  8900. return BAD_FUNC_ARG;
  8901. if (newSession == 0) {
  8902. session = wolfSSL_GetSessionClient(ssl, id, len);
  8903. if (session) {
  8904. if (wolfSSL_SetSession(ssl, session) != WOLFSSL_SUCCESS) {
  8905. #ifdef HAVE_EXT_CACHE
  8906. wolfSSL_FreeSession(ssl->ctx, session);
  8907. #endif
  8908. WOLFSSL_MSG("wolfSSL_SetSession failed");
  8909. session = NULL;
  8910. }
  8911. }
  8912. }
  8913. if (session == NULL) {
  8914. WOLFSSL_MSG("Valid ServerID not cached already");
  8915. ssl->session->idLen = (word16)min(SERVER_ID_LEN, (word32)len);
  8916. XMEMCPY(ssl->session->serverID, id, ssl->session->idLen);
  8917. }
  8918. #ifdef HAVE_EXT_CACHE
  8919. else {
  8920. wolfSSL_FreeSession(ssl->ctx, session);
  8921. }
  8922. #endif
  8923. return WOLFSSL_SUCCESS;
  8924. }
  8925. #endif /* !NO_CLIENT_CACHE */
  8926. #if defined(PERSIST_SESSION_CACHE)
  8927. /* for persistence, if changes to layout need to increment and modify
  8928. save_session_cache() and restore_session_cache and memory versions too */
  8929. #define WOLFSSL_CACHE_VERSION 2
  8930. /* Session Cache Header information */
  8931. typedef struct {
  8932. int version; /* cache layout version id */
  8933. int rows; /* session rows */
  8934. int columns; /* session columns */
  8935. int sessionSz; /* sizeof WOLFSSL_SESSION */
  8936. } cache_header_t;
  8937. /* current persistence layout is:
  8938. 1) cache_header_t
  8939. 2) SessionCache
  8940. 3) ClientCache
  8941. update WOLFSSL_CACHE_VERSION if change layout for the following
  8942. PERSISTENT_SESSION_CACHE functions
  8943. */
  8944. /* get how big the the session cache save buffer needs to be */
  8945. int wolfSSL_get_session_cache_memsize(void)
  8946. {
  8947. int sz = (int)(sizeof(SessionCache) + sizeof(cache_header_t));
  8948. #ifndef NO_CLIENT_CACHE
  8949. sz += (int)(sizeof(ClientCache));
  8950. #endif
  8951. return sz;
  8952. }
  8953. /* Persist session cache to memory */
  8954. int wolfSSL_memsave_session_cache(void* mem, int sz)
  8955. {
  8956. int i;
  8957. cache_header_t cache_header;
  8958. SessionRow* row = (SessionRow*)((byte*)mem + sizeof(cache_header));
  8959. WOLFSSL_ENTER("wolfSSL_memsave_session_cache");
  8960. if (sz < wolfSSL_get_session_cache_memsize()) {
  8961. WOLFSSL_MSG("Memory buffer too small");
  8962. return BUFFER_E;
  8963. }
  8964. cache_header.version = WOLFSSL_CACHE_VERSION;
  8965. cache_header.rows = SESSION_ROWS;
  8966. cache_header.columns = SESSIONS_PER_ROW;
  8967. cache_header.sessionSz = (int)sizeof(WOLFSSL_SESSION);
  8968. XMEMCPY(mem, &cache_header, sizeof(cache_header));
  8969. #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
  8970. if (wc_LockMutex(&session_mutex) != 0) {
  8971. WOLFSSL_MSG("Session cache mutex lock failed");
  8972. return BAD_MUTEX_E;
  8973. }
  8974. #endif
  8975. for (i = 0; i < cache_header.rows; ++i) {
  8976. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  8977. if (SESSION_ROW_LOCK(&SessionCache[i]) != 0) {
  8978. WOLFSSL_MSG("Session row cache mutex lock failed");
  8979. return BAD_MUTEX_E;
  8980. }
  8981. #endif
  8982. XMEMCPY(row++, &SessionCache[i], SIZEOF_SESSION_ROW);
  8983. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  8984. SESSION_ROW_UNLOCK(&SessionCache[i]);
  8985. #endif
  8986. }
  8987. #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
  8988. wc_UnLockMutex(&session_mutex);
  8989. #endif
  8990. #ifndef NO_CLIENT_CACHE
  8991. if (wc_LockMutex(&clisession_mutex) != 0) {
  8992. WOLFSSL_MSG("Client cache mutex lock failed");
  8993. return BAD_MUTEX_E;
  8994. }
  8995. XMEMCPY(row, ClientCache, sizeof(ClientCache));
  8996. wc_UnLockMutex(&clisession_mutex);
  8997. #endif
  8998. WOLFSSL_LEAVE("wolfSSL_memsave_session_cache", WOLFSSL_SUCCESS);
  8999. return WOLFSSL_SUCCESS;
  9000. }
  9001. /* Restore the persistent session cache from memory */
  9002. int wolfSSL_memrestore_session_cache(const void* mem, int sz)
  9003. {
  9004. int i;
  9005. cache_header_t cache_header;
  9006. SessionRow* row = (SessionRow*)((byte*)mem + sizeof(cache_header));
  9007. WOLFSSL_ENTER("wolfSSL_memrestore_session_cache");
  9008. if (sz < wolfSSL_get_session_cache_memsize()) {
  9009. WOLFSSL_MSG("Memory buffer too small");
  9010. return BUFFER_E;
  9011. }
  9012. XMEMCPY(&cache_header, mem, sizeof(cache_header));
  9013. if (cache_header.version != WOLFSSL_CACHE_VERSION ||
  9014. cache_header.rows != SESSION_ROWS ||
  9015. cache_header.columns != SESSIONS_PER_ROW ||
  9016. cache_header.sessionSz != (int)sizeof(WOLFSSL_SESSION)) {
  9017. WOLFSSL_MSG("Session cache header match failed");
  9018. return CACHE_MATCH_ERROR;
  9019. }
  9020. #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
  9021. if (wc_LockMutex(&session_mutex) != 0) {
  9022. WOLFSSL_MSG("Session cache mutex lock failed");
  9023. return BAD_MUTEX_E;
  9024. }
  9025. #endif
  9026. for (i = 0; i < cache_header.rows; ++i) {
  9027. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  9028. if (SESSION_ROW_LOCK(&SessionCache[i]) != 0) {
  9029. WOLFSSL_MSG("Session row cache mutex lock failed");
  9030. return BAD_MUTEX_E;
  9031. }
  9032. #endif
  9033. XMEMCPY(&SessionCache[i], row++, SIZEOF_SESSION_ROW);
  9034. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  9035. SESSION_ROW_UNLOCK(&SessionCache[i]);
  9036. #endif
  9037. }
  9038. #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
  9039. wc_UnLockMutex(&session_mutex);
  9040. #endif
  9041. #ifndef NO_CLIENT_CACHE
  9042. if (wc_LockMutex(&clisession_mutex) != 0) {
  9043. WOLFSSL_MSG("Client cache mutex lock failed");
  9044. return BAD_MUTEX_E;
  9045. }
  9046. XMEMCPY(ClientCache, row, sizeof(ClientCache));
  9047. wc_UnLockMutex(&clisession_mutex);
  9048. #endif
  9049. WOLFSSL_LEAVE("wolfSSL_memrestore_session_cache", WOLFSSL_SUCCESS);
  9050. return WOLFSSL_SUCCESS;
  9051. }
  9052. #if !defined(NO_FILESYSTEM)
  9053. /* Persist session cache to file */
  9054. /* doesn't use memsave because of additional memory use */
  9055. int wolfSSL_save_session_cache(const char *fname)
  9056. {
  9057. XFILE file;
  9058. int ret;
  9059. int rc = WOLFSSL_SUCCESS;
  9060. int i;
  9061. cache_header_t cache_header;
  9062. WOLFSSL_ENTER("wolfSSL_save_session_cache");
  9063. file = XFOPEN(fname, "w+b");
  9064. if (file == XBADFILE) {
  9065. WOLFSSL_MSG("Couldn't open session cache save file");
  9066. return WOLFSSL_BAD_FILE;
  9067. }
  9068. cache_header.version = WOLFSSL_CACHE_VERSION;
  9069. cache_header.rows = SESSION_ROWS;
  9070. cache_header.columns = SESSIONS_PER_ROW;
  9071. cache_header.sessionSz = (int)sizeof(WOLFSSL_SESSION);
  9072. /* cache header */
  9073. ret = (int)XFWRITE(&cache_header, sizeof cache_header, 1, file);
  9074. if (ret != 1) {
  9075. WOLFSSL_MSG("Session cache header file write failed");
  9076. XFCLOSE(file);
  9077. return FWRITE_ERROR;
  9078. }
  9079. #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
  9080. if (wc_LockMutex(&session_mutex) != 0) {
  9081. WOLFSSL_MSG("Session cache mutex lock failed");
  9082. XFCLOSE(file);
  9083. return BAD_MUTEX_E;
  9084. }
  9085. #endif
  9086. /* session cache */
  9087. for (i = 0; i < cache_header.rows; ++i) {
  9088. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  9089. if (SESSION_ROW_LOCK(&SessionCache[i]) != 0) {
  9090. WOLFSSL_MSG("Session row cache mutex lock failed");
  9091. XFCLOSE(file);
  9092. return BAD_MUTEX_E;
  9093. }
  9094. #endif
  9095. ret = (int)XFWRITE(&SessionCache[i], SIZEOF_SESSION_ROW, 1, file);
  9096. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  9097. SESSION_ROW_UNLOCK(&SessionCache[i]);
  9098. #endif
  9099. if (ret != 1) {
  9100. WOLFSSL_MSG("Session cache member file write failed");
  9101. rc = FWRITE_ERROR;
  9102. break;
  9103. }
  9104. }
  9105. #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
  9106. wc_UnLockMutex(&session_mutex);
  9107. #endif
  9108. #ifndef NO_CLIENT_CACHE
  9109. /* client cache */
  9110. if (wc_LockMutex(&clisession_mutex) != 0) {
  9111. WOLFSSL_MSG("Client cache mutex lock failed");
  9112. XFCLOSE(file);
  9113. return BAD_MUTEX_E;
  9114. }
  9115. ret = (int)XFWRITE(ClientCache, sizeof(ClientCache), 1, file);
  9116. if (ret != 1) {
  9117. WOLFSSL_MSG("Client cache member file write failed");
  9118. rc = FWRITE_ERROR;
  9119. }
  9120. wc_UnLockMutex(&clisession_mutex);
  9121. #endif /* !NO_CLIENT_CACHE */
  9122. XFCLOSE(file);
  9123. WOLFSSL_LEAVE("wolfSSL_save_session_cache", rc);
  9124. return rc;
  9125. }
  9126. /* Restore the persistent session cache from file */
  9127. /* doesn't use memstore because of additional memory use */
  9128. int wolfSSL_restore_session_cache(const char *fname)
  9129. {
  9130. XFILE file;
  9131. int rc = WOLFSSL_SUCCESS;
  9132. int ret;
  9133. int i;
  9134. cache_header_t cache_header;
  9135. WOLFSSL_ENTER("wolfSSL_restore_session_cache");
  9136. file = XFOPEN(fname, "rb");
  9137. if (file == XBADFILE) {
  9138. WOLFSSL_MSG("Couldn't open session cache save file");
  9139. return WOLFSSL_BAD_FILE;
  9140. }
  9141. /* cache header */
  9142. ret = (int)XFREAD(&cache_header, sizeof(cache_header), 1, file);
  9143. if (ret != 1) {
  9144. WOLFSSL_MSG("Session cache header file read failed");
  9145. XFCLOSE(file);
  9146. return FREAD_ERROR;
  9147. }
  9148. if (cache_header.version != WOLFSSL_CACHE_VERSION ||
  9149. cache_header.rows != SESSION_ROWS ||
  9150. cache_header.columns != SESSIONS_PER_ROW ||
  9151. cache_header.sessionSz != (int)sizeof(WOLFSSL_SESSION)) {
  9152. WOLFSSL_MSG("Session cache header match failed");
  9153. XFCLOSE(file);
  9154. return CACHE_MATCH_ERROR;
  9155. }
  9156. #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
  9157. if (wc_LockMutex(&session_mutex) != 0) {
  9158. WOLFSSL_MSG("Session cache mutex lock failed");
  9159. XFCLOSE(file);
  9160. return BAD_MUTEX_E;
  9161. }
  9162. #endif
  9163. /* session cache */
  9164. for (i = 0; i < cache_header.rows; ++i) {
  9165. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  9166. if (SESSION_ROW_LOCK(&SessionCache[i]) != 0) {
  9167. WOLFSSL_MSG("Session row cache mutex lock failed");
  9168. XFCLOSE(file);
  9169. return BAD_MUTEX_E;
  9170. }
  9171. #endif
  9172. ret = (int)XFREAD(&SessionCache[i], SIZEOF_SESSION_ROW, 1, file);
  9173. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  9174. SESSION_ROW_UNLOCK(&SessionCache[i]);
  9175. #endif
  9176. if (ret != 1) {
  9177. WOLFSSL_MSG("Session cache member file read failed");
  9178. XMEMSET(SessionCache, 0, sizeof SessionCache);
  9179. rc = FREAD_ERROR;
  9180. break;
  9181. }
  9182. }
  9183. #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
  9184. wc_UnLockMutex(&session_mutex);
  9185. #endif
  9186. #ifndef NO_CLIENT_CACHE
  9187. /* client cache */
  9188. if (wc_LockMutex(&clisession_mutex) != 0) {
  9189. WOLFSSL_MSG("Client cache mutex lock failed");
  9190. XFCLOSE(file);
  9191. return BAD_MUTEX_E;
  9192. }
  9193. ret = (int)XFREAD(ClientCache, sizeof(ClientCache), 1, file);
  9194. if (ret != 1) {
  9195. WOLFSSL_MSG("Client cache member file read failed");
  9196. XMEMSET(ClientCache, 0, sizeof ClientCache);
  9197. rc = FREAD_ERROR;
  9198. }
  9199. wc_UnLockMutex(&clisession_mutex);
  9200. #endif /* !NO_CLIENT_CACHE */
  9201. XFCLOSE(file);
  9202. WOLFSSL_LEAVE("wolfSSL_restore_session_cache", rc);
  9203. return rc;
  9204. }
  9205. #endif /* !NO_FILESYSTEM */
  9206. #endif /* PERSIST_SESSION_CACHE */
  9207. #endif /* NO_SESSION_CACHE */
  9208. void wolfSSL_load_error_strings(void)
  9209. {
  9210. /* compatibility only */
  9211. }
  9212. int wolfSSL_library_init(void)
  9213. {
  9214. WOLFSSL_ENTER("SSL_library_init");
  9215. if (wolfSSL_Init() == WOLFSSL_SUCCESS)
  9216. return WOLFSSL_SUCCESS;
  9217. else
  9218. return WOLFSSL_FATAL_ERROR;
  9219. }
  9220. #ifdef HAVE_SECRET_CALLBACK
  9221. int wolfSSL_set_session_secret_cb(WOLFSSL* ssl, SessionSecretCb cb, void* ctx)
  9222. {
  9223. WOLFSSL_ENTER("wolfSSL_set_session_secret_cb");
  9224. if (ssl == NULL)
  9225. return WOLFSSL_FATAL_ERROR;
  9226. ssl->sessionSecretCb = cb;
  9227. ssl->sessionSecretCtx = ctx;
  9228. if (cb != NULL) {
  9229. /* If using a pre-set key, assume session resumption. */
  9230. ssl->session->sessionIDSz = 0;
  9231. ssl->options.resuming = 1;
  9232. }
  9233. return WOLFSSL_SUCCESS;
  9234. }
  9235. #endif
  9236. #ifndef NO_SESSION_CACHE
  9237. /* on by default if built in but allow user to turn off */
  9238. WOLFSSL_ABI
  9239. long wolfSSL_CTX_set_session_cache_mode(WOLFSSL_CTX* ctx, long mode)
  9240. {
  9241. WOLFSSL_ENTER("SSL_CTX_set_session_cache_mode");
  9242. if (ctx == NULL)
  9243. return WOLFSSL_FAILURE;
  9244. if (mode == WOLFSSL_SESS_CACHE_OFF)
  9245. ctx->sessionCacheOff = 1;
  9246. if ((mode & WOLFSSL_SESS_CACHE_NO_AUTO_CLEAR) != 0)
  9247. ctx->sessionCacheFlushOff = 1;
  9248. #ifdef HAVE_EXT_CACHE
  9249. if ((mode & WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE) != 0)
  9250. ctx->internalCacheOff = 1;
  9251. if ((mode & WOLFSSL_SESS_CACHE_NO_INTERNAL_LOOKUP) != 0)
  9252. ctx->internalCacheLookupOff = 1;
  9253. #endif
  9254. return WOLFSSL_SUCCESS;
  9255. }
  9256. #endif /* NO_SESSION_CACHE */
  9257. #if !defined(NO_CERTS)
  9258. #if defined(PERSIST_CERT_CACHE)
  9259. #define WOLFSSL_CACHE_CERT_VERSION 1
  9260. typedef struct {
  9261. int version; /* cache cert layout version id */
  9262. int rows; /* hash table rows, CA_TABLE_SIZE */
  9263. int columns[CA_TABLE_SIZE]; /* columns per row on list */
  9264. int signerSz; /* sizeof Signer object */
  9265. } CertCacheHeader;
  9266. /* current cert persistence layout is:
  9267. 1) CertCacheHeader
  9268. 2) caTable
  9269. update WOLFSSL_CERT_CACHE_VERSION if change layout for the following
  9270. PERSIST_CERT_CACHE functions
  9271. */
  9272. /* Return memory needed to persist this signer, have lock */
  9273. static WC_INLINE int GetSignerMemory(Signer* signer)
  9274. {
  9275. int sz = sizeof(signer->pubKeySize) + sizeof(signer->keyOID)
  9276. + sizeof(signer->nameLen) + sizeof(signer->subjectNameHash);
  9277. #if !defined(NO_SKID)
  9278. sz += (int)sizeof(signer->subjectKeyIdHash);
  9279. #endif
  9280. /* add dynamic bytes needed */
  9281. sz += signer->pubKeySize;
  9282. sz += signer->nameLen;
  9283. return sz;
  9284. }
  9285. /* Return memory needed to persist this row, have lock */
  9286. static WC_INLINE int GetCertCacheRowMemory(Signer* row)
  9287. {
  9288. int sz = 0;
  9289. while (row) {
  9290. sz += GetSignerMemory(row);
  9291. row = row->next;
  9292. }
  9293. return sz;
  9294. }
  9295. /* get the size of persist cert cache, have lock */
  9296. static WC_INLINE int GetCertCacheMemSize(WOLFSSL_CERT_MANAGER* cm)
  9297. {
  9298. int sz;
  9299. int i;
  9300. sz = sizeof(CertCacheHeader);
  9301. for (i = 0; i < CA_TABLE_SIZE; i++)
  9302. sz += GetCertCacheRowMemory(cm->caTable[i]);
  9303. return sz;
  9304. }
  9305. /* Store cert cache header columns with number of items per list, have lock */
  9306. static WC_INLINE void SetCertHeaderColumns(WOLFSSL_CERT_MANAGER* cm, int* columns)
  9307. {
  9308. int i;
  9309. Signer* row;
  9310. for (i = 0; i < CA_TABLE_SIZE; i++) {
  9311. int count = 0;
  9312. row = cm->caTable[i];
  9313. while (row) {
  9314. ++count;
  9315. row = row->next;
  9316. }
  9317. columns[i] = count;
  9318. }
  9319. }
  9320. /* Restore whole cert row from memory, have lock, return bytes consumed,
  9321. < 0 on error, have lock */
  9322. static WC_INLINE int RestoreCertRow(WOLFSSL_CERT_MANAGER* cm, byte* current,
  9323. int row, int listSz, const byte* end)
  9324. {
  9325. int idx = 0;
  9326. if (listSz < 0) {
  9327. WOLFSSL_MSG("Row header corrupted, negative value");
  9328. return PARSE_ERROR;
  9329. }
  9330. while (listSz) {
  9331. Signer* signer;
  9332. byte* publicKey;
  9333. byte* start = current + idx; /* for end checks on this signer */
  9334. int minSz = sizeof(signer->pubKeySize) + sizeof(signer->keyOID) +
  9335. sizeof(signer->nameLen) + sizeof(signer->subjectNameHash);
  9336. #ifndef NO_SKID
  9337. minSz += (int)sizeof(signer->subjectKeyIdHash);
  9338. #endif
  9339. if (start + minSz > end) {
  9340. WOLFSSL_MSG("Would overread restore buffer");
  9341. return BUFFER_E;
  9342. }
  9343. signer = MakeSigner(cm->heap);
  9344. if (signer == NULL)
  9345. return MEMORY_E;
  9346. /* pubKeySize */
  9347. XMEMCPY(&signer->pubKeySize, current + idx, sizeof(signer->pubKeySize));
  9348. idx += (int)sizeof(signer->pubKeySize);
  9349. /* keyOID */
  9350. XMEMCPY(&signer->keyOID, current + idx, sizeof(signer->keyOID));
  9351. idx += (int)sizeof(signer->keyOID);
  9352. /* publicKey */
  9353. if (start + minSz + signer->pubKeySize > end) {
  9354. WOLFSSL_MSG("Would overread restore buffer");
  9355. FreeSigner(signer, cm->heap);
  9356. return BUFFER_E;
  9357. }
  9358. publicKey = (byte*)XMALLOC(signer->pubKeySize, cm->heap,
  9359. DYNAMIC_TYPE_KEY);
  9360. if (publicKey == NULL) {
  9361. FreeSigner(signer, cm->heap);
  9362. return MEMORY_E;
  9363. }
  9364. XMEMCPY(publicKey, current + idx, signer->pubKeySize);
  9365. signer->publicKey = publicKey;
  9366. idx += signer->pubKeySize;
  9367. /* nameLen */
  9368. XMEMCPY(&signer->nameLen, current + idx, sizeof(signer->nameLen));
  9369. idx += (int)sizeof(signer->nameLen);
  9370. /* name */
  9371. if (start + minSz + signer->pubKeySize + signer->nameLen > end) {
  9372. WOLFSSL_MSG("Would overread restore buffer");
  9373. FreeSigner(signer, cm->heap);
  9374. return BUFFER_E;
  9375. }
  9376. signer->name = (char*)XMALLOC(signer->nameLen, cm->heap,
  9377. DYNAMIC_TYPE_SUBJECT_CN);
  9378. if (signer->name == NULL) {
  9379. FreeSigner(signer, cm->heap);
  9380. return MEMORY_E;
  9381. }
  9382. XMEMCPY(signer->name, current + idx, signer->nameLen);
  9383. idx += signer->nameLen;
  9384. /* subjectNameHash */
  9385. XMEMCPY(signer->subjectNameHash, current + idx, SIGNER_DIGEST_SIZE);
  9386. idx += SIGNER_DIGEST_SIZE;
  9387. #ifndef NO_SKID
  9388. /* subjectKeyIdHash */
  9389. XMEMCPY(signer->subjectKeyIdHash, current + idx,SIGNER_DIGEST_SIZE);
  9390. idx += SIGNER_DIGEST_SIZE;
  9391. #endif
  9392. signer->next = cm->caTable[row];
  9393. cm->caTable[row] = signer;
  9394. --listSz;
  9395. }
  9396. return idx;
  9397. }
  9398. /* Store whole cert row into memory, have lock, return bytes added */
  9399. static WC_INLINE int StoreCertRow(WOLFSSL_CERT_MANAGER* cm, byte* current, int row)
  9400. {
  9401. int added = 0;
  9402. Signer* list = cm->caTable[row];
  9403. while (list) {
  9404. XMEMCPY(current + added, &list->pubKeySize, sizeof(list->pubKeySize));
  9405. added += (int)sizeof(list->pubKeySize);
  9406. XMEMCPY(current + added, &list->keyOID, sizeof(list->keyOID));
  9407. added += (int)sizeof(list->keyOID);
  9408. XMEMCPY(current + added, list->publicKey, list->pubKeySize);
  9409. added += list->pubKeySize;
  9410. XMEMCPY(current + added, &list->nameLen, sizeof(list->nameLen));
  9411. added += (int)sizeof(list->nameLen);
  9412. XMEMCPY(current + added, list->name, list->nameLen);
  9413. added += list->nameLen;
  9414. XMEMCPY(current + added, list->subjectNameHash, SIGNER_DIGEST_SIZE);
  9415. added += SIGNER_DIGEST_SIZE;
  9416. #ifndef NO_SKID
  9417. XMEMCPY(current + added, list->subjectKeyIdHash,SIGNER_DIGEST_SIZE);
  9418. added += SIGNER_DIGEST_SIZE;
  9419. #endif
  9420. list = list->next;
  9421. }
  9422. return added;
  9423. }
  9424. /* Persist cert cache to memory, have lock */
  9425. static WC_INLINE int DoMemSaveCertCache(WOLFSSL_CERT_MANAGER* cm,
  9426. void* mem, int sz)
  9427. {
  9428. int realSz;
  9429. int ret = WOLFSSL_SUCCESS;
  9430. int i;
  9431. WOLFSSL_ENTER("DoMemSaveCertCache");
  9432. realSz = GetCertCacheMemSize(cm);
  9433. if (realSz > sz) {
  9434. WOLFSSL_MSG("Mem output buffer too small");
  9435. ret = BUFFER_E;
  9436. }
  9437. else {
  9438. byte* current;
  9439. CertCacheHeader hdr;
  9440. hdr.version = WOLFSSL_CACHE_CERT_VERSION;
  9441. hdr.rows = CA_TABLE_SIZE;
  9442. SetCertHeaderColumns(cm, hdr.columns);
  9443. hdr.signerSz = (int)sizeof(Signer);
  9444. XMEMCPY(mem, &hdr, sizeof(CertCacheHeader));
  9445. current = (byte*)mem + sizeof(CertCacheHeader);
  9446. for (i = 0; i < CA_TABLE_SIZE; ++i)
  9447. current += StoreCertRow(cm, current, i);
  9448. }
  9449. return ret;
  9450. }
  9451. #if !defined(NO_FILESYSTEM)
  9452. /* Persist cert cache to file */
  9453. int CM_SaveCertCache(WOLFSSL_CERT_MANAGER* cm, const char* fname)
  9454. {
  9455. XFILE file;
  9456. int rc = WOLFSSL_SUCCESS;
  9457. int memSz;
  9458. byte* mem;
  9459. WOLFSSL_ENTER("CM_SaveCertCache");
  9460. file = XFOPEN(fname, "w+b");
  9461. if (file == XBADFILE) {
  9462. WOLFSSL_MSG("Couldn't open cert cache save file");
  9463. return WOLFSSL_BAD_FILE;
  9464. }
  9465. if (wc_LockMutex(&cm->caLock) != 0) {
  9466. WOLFSSL_MSG("wc_LockMutex on caLock failed");
  9467. XFCLOSE(file);
  9468. return BAD_MUTEX_E;
  9469. }
  9470. memSz = GetCertCacheMemSize(cm);
  9471. mem = (byte*)XMALLOC(memSz, cm->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9472. if (mem == NULL) {
  9473. WOLFSSL_MSG("Alloc for tmp buffer failed");
  9474. rc = MEMORY_E;
  9475. } else {
  9476. rc = DoMemSaveCertCache(cm, mem, memSz);
  9477. if (rc == WOLFSSL_SUCCESS) {
  9478. int ret = (int)XFWRITE(mem, memSz, 1, file);
  9479. if (ret != 1) {
  9480. WOLFSSL_MSG("Cert cache file write failed");
  9481. rc = FWRITE_ERROR;
  9482. }
  9483. }
  9484. XFREE(mem, cm->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9485. }
  9486. wc_UnLockMutex(&cm->caLock);
  9487. XFCLOSE(file);
  9488. return rc;
  9489. }
  9490. /* Restore cert cache from file */
  9491. int CM_RestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const char* fname)
  9492. {
  9493. XFILE file;
  9494. int rc = WOLFSSL_SUCCESS;
  9495. int ret;
  9496. int memSz;
  9497. byte* mem;
  9498. WOLFSSL_ENTER("CM_RestoreCertCache");
  9499. file = XFOPEN(fname, "rb");
  9500. if (file == XBADFILE) {
  9501. WOLFSSL_MSG("Couldn't open cert cache save file");
  9502. return WOLFSSL_BAD_FILE;
  9503. }
  9504. if(XFSEEK(file, 0, XSEEK_END) != 0) {
  9505. XFCLOSE(file);
  9506. return WOLFSSL_BAD_FILE;
  9507. }
  9508. memSz = (int)XFTELL(file);
  9509. XREWIND(file);
  9510. if (memSz > MAX_WOLFSSL_FILE_SIZE || memSz <= 0) {
  9511. WOLFSSL_MSG("CM_RestoreCertCache file size error");
  9512. XFCLOSE(file);
  9513. return WOLFSSL_BAD_FILE;
  9514. }
  9515. mem = (byte*)XMALLOC(memSz, cm->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9516. if (mem == NULL) {
  9517. WOLFSSL_MSG("Alloc for tmp buffer failed");
  9518. XFCLOSE(file);
  9519. return MEMORY_E;
  9520. }
  9521. ret = (int)XFREAD(mem, memSz, 1, file);
  9522. if (ret != 1) {
  9523. WOLFSSL_MSG("Cert file read error");
  9524. rc = FREAD_ERROR;
  9525. } else {
  9526. rc = CM_MemRestoreCertCache(cm, mem, memSz);
  9527. if (rc != WOLFSSL_SUCCESS) {
  9528. WOLFSSL_MSG("Mem restore cert cache failed");
  9529. }
  9530. }
  9531. XFREE(mem, cm->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9532. XFCLOSE(file);
  9533. return rc;
  9534. }
  9535. #endif /* NO_FILESYSTEM */
  9536. /* Persist cert cache to memory */
  9537. int CM_MemSaveCertCache(WOLFSSL_CERT_MANAGER* cm, void* mem, int sz, int* used)
  9538. {
  9539. int ret = WOLFSSL_SUCCESS;
  9540. WOLFSSL_ENTER("CM_MemSaveCertCache");
  9541. if (wc_LockMutex(&cm->caLock) != 0) {
  9542. WOLFSSL_MSG("wc_LockMutex on caLock failed");
  9543. return BAD_MUTEX_E;
  9544. }
  9545. ret = DoMemSaveCertCache(cm, mem, sz);
  9546. if (ret == WOLFSSL_SUCCESS)
  9547. *used = GetCertCacheMemSize(cm);
  9548. wc_UnLockMutex(&cm->caLock);
  9549. return ret;
  9550. }
  9551. /* Restore cert cache from memory */
  9552. int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const void* mem, int sz)
  9553. {
  9554. int ret = WOLFSSL_SUCCESS;
  9555. int i;
  9556. CertCacheHeader* hdr = (CertCacheHeader*)mem;
  9557. byte* current = (byte*)mem + sizeof(CertCacheHeader);
  9558. byte* end = (byte*)mem + sz; /* don't go over */
  9559. WOLFSSL_ENTER("CM_MemRestoreCertCache");
  9560. if (current > end) {
  9561. WOLFSSL_MSG("Cert Cache Memory buffer too small");
  9562. return BUFFER_E;
  9563. }
  9564. if (hdr->version != WOLFSSL_CACHE_CERT_VERSION ||
  9565. hdr->rows != CA_TABLE_SIZE ||
  9566. hdr->signerSz != (int)sizeof(Signer)) {
  9567. WOLFSSL_MSG("Cert Cache Memory header mismatch");
  9568. return CACHE_MATCH_ERROR;
  9569. }
  9570. if (wc_LockMutex(&cm->caLock) != 0) {
  9571. WOLFSSL_MSG("wc_LockMutex on caLock failed");
  9572. return BAD_MUTEX_E;
  9573. }
  9574. FreeSignerTable(cm->caTable, CA_TABLE_SIZE, cm->heap);
  9575. for (i = 0; i < CA_TABLE_SIZE; ++i) {
  9576. int added = RestoreCertRow(cm, current, i, hdr->columns[i], end);
  9577. if (added < 0) {
  9578. WOLFSSL_MSG("RestoreCertRow error");
  9579. ret = added;
  9580. break;
  9581. }
  9582. current += added;
  9583. }
  9584. wc_UnLockMutex(&cm->caLock);
  9585. return ret;
  9586. }
  9587. /* get how big the the cert cache save buffer needs to be */
  9588. int CM_GetCertCacheMemSize(WOLFSSL_CERT_MANAGER* cm)
  9589. {
  9590. int sz;
  9591. WOLFSSL_ENTER("CM_GetCertCacheMemSize");
  9592. if (wc_LockMutex(&cm->caLock) != 0) {
  9593. WOLFSSL_MSG("wc_LockMutex on caLock failed");
  9594. return BAD_MUTEX_E;
  9595. }
  9596. sz = GetCertCacheMemSize(cm);
  9597. wc_UnLockMutex(&cm->caLock);
  9598. return sz;
  9599. }
  9600. #endif /* PERSIST_CERT_CACHE */
  9601. #endif /* NO_CERTS */
  9602. #ifdef OPENSSL_EXTRA
  9603. /*
  9604. * build enabled cipher list w/ TLS13 or w/o TLS13 suites
  9605. * @param ctx a pointer to WOLFSSL_CTX structure
  9606. * @param suites currently enabled suites
  9607. * @param onlytlsv13suites flag whether correcting w/ TLS13 suites
  9608. * or w/o TLS13 suties
  9609. * @param list suites list that user wants to update
  9610. * @return suites list on success, otherwise NULL
  9611. */
  9612. static char* buildEnabledCipherList(WOLFSSL_CTX* ctx, Suites* suites,
  9613. int tls13Only, const char* list)
  9614. {
  9615. word32 idx = 0;
  9616. word32 listsz = 0;
  9617. word32 len = 0;
  9618. word32 ianasz = 0;
  9619. const char* enabledcs = NULL;
  9620. char* locallist = NULL;
  9621. char* head = NULL;
  9622. byte cipherSuite0;
  9623. byte cipherSuite;
  9624. /* sanity check */
  9625. if (ctx == NULL || suites == NULL || list == NULL)
  9626. return NULL;
  9627. if (!suites->setSuites)
  9628. return NULL;
  9629. listsz = (word32)XSTRLEN(list);
  9630. /* calculate necessary buffer length */
  9631. for(idx = 0; idx < suites->suiteSz; idx++) {
  9632. cipherSuite0 = suites->suites[idx];
  9633. cipherSuite = suites->suites[++idx];
  9634. if (tls13Only && cipherSuite0 == TLS13_BYTE) {
  9635. enabledcs = GetCipherNameInternal(cipherSuite0, cipherSuite);
  9636. }
  9637. else if (!tls13Only && cipherSuite0 != TLS13_BYTE) {
  9638. enabledcs = GetCipherNameInternal(cipherSuite0, cipherSuite);
  9639. }
  9640. else
  9641. continue;
  9642. if (XSTRCMP(enabledcs, "None") != 0) {
  9643. len += (word32)XSTRLEN(enabledcs) + 2;
  9644. }
  9645. }
  9646. len += listsz + 2;
  9647. /* build string */
  9648. if (len > (listsz + 2)) {
  9649. locallist = (char*)XMALLOC(len, ctx->heap,
  9650. DYNAMIC_TYPE_TMP_BUFFER);
  9651. /* sanity check */
  9652. if (!locallist)
  9653. return NULL;
  9654. XMEMSET(locallist, 0, len);
  9655. head = locallist;
  9656. if (!tls13Only)
  9657. {
  9658. /* always tls13 suites in the head position */
  9659. XSTRNCPY(locallist, list, len);
  9660. locallist += listsz;
  9661. *locallist++ = ':';
  9662. *locallist = 0;
  9663. len -= listsz + 1;
  9664. }
  9665. for(idx = 0; idx < suites->suiteSz; idx++) {
  9666. cipherSuite0 = suites->suites[idx];
  9667. cipherSuite = suites->suites[++idx];
  9668. if (tls13Only && cipherSuite0 == TLS13_BYTE) {
  9669. enabledcs = GetCipherNameInternal(cipherSuite0, cipherSuite);
  9670. }
  9671. else if (!tls13Only && cipherSuite0 != TLS13_BYTE) {
  9672. enabledcs = GetCipherNameInternal(cipherSuite0, cipherSuite);
  9673. }
  9674. else
  9675. continue;
  9676. ianasz = (int)XSTRLEN(enabledcs);
  9677. if (ianasz + 1 < len) {
  9678. XSTRNCPY(locallist, enabledcs, len);
  9679. locallist += ianasz;
  9680. *locallist++ = ':';
  9681. *locallist = 0;
  9682. len -= ianasz + 1;
  9683. }
  9684. else{
  9685. XFREE(locallist, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9686. return NULL;
  9687. }
  9688. }
  9689. if (tls13Only) {
  9690. XSTRNCPY(locallist, list, len);
  9691. locallist += listsz;
  9692. *locallist = 0;
  9693. }
  9694. return head;
  9695. }
  9696. else
  9697. return NULL;
  9698. }
  9699. /*
  9700. * check if the list has TLS13 and pre-TLS13 suites
  9701. * @param list cipher suite list that user want to set
  9702. * @return mixed: 0, only pre-TLS13: 1, only TLS13: 2
  9703. */
  9704. static int CheckcipherList(const char* list)
  9705. {
  9706. int ret;
  9707. int findTLSv13Suites = 0;
  9708. int findbeforeSuites = 0;
  9709. byte cipherSuite0;
  9710. byte cipherSuite1;
  9711. int flags;
  9712. char* next = (char*)list;
  9713. do {
  9714. char* current = next;
  9715. char name[MAX_SUITE_NAME + 1];
  9716. word32 length = MAX_SUITE_NAME;
  9717. word32 current_length;
  9718. next = XSTRSTR(next, ":");
  9719. current_length = (!next) ? (word32)XSTRLEN(current)
  9720. : (word32)(next - current);
  9721. if (current_length < length) {
  9722. length = current_length;
  9723. }
  9724. XMEMCPY(name, current, length);
  9725. name[length] = 0;
  9726. ret = wolfSSL_get_cipher_suite_from_name(name, &cipherSuite0,
  9727. &cipherSuite1, &flags);
  9728. if (ret == 0) {
  9729. if (cipherSuite0 == TLS13_BYTE) {
  9730. /* TLSv13 suite */
  9731. findTLSv13Suites = 1;
  9732. break;
  9733. }
  9734. else {
  9735. findbeforeSuites = 1;
  9736. break;
  9737. }
  9738. }
  9739. if (findTLSv13Suites == 1 && findbeforeSuites == 1) {
  9740. /* list has mixed suites */
  9741. return 0;
  9742. }
  9743. } while (next++); /* ++ needed to skip ':' */
  9744. if (findTLSv13Suites == 0 && findbeforeSuites == 1) {
  9745. return 1;/* only before TLSv13 suites */
  9746. }
  9747. else if (findTLSv13Suites == 1 && findbeforeSuites == 0) {
  9748. return 2;/* only TLSv13 suties */
  9749. }
  9750. else {
  9751. return 0;/* handle as mixed */
  9752. }
  9753. }
  9754. /* parse some bulk lists like !eNULL / !aNULL
  9755. *
  9756. * returns WOLFSSL_SUCCESS on success and sets the cipher suite list
  9757. */
  9758. static int wolfSSL_parse_cipher_list(WOLFSSL_CTX* ctx, Suites* suites,
  9759. const char* list)
  9760. {
  9761. int ret = 0;
  9762. int listattribute = 0;
  9763. char* buildcipherList = NULL;
  9764. int tls13Only = 0;
  9765. if (suites == NULL || list == NULL) {
  9766. WOLFSSL_MSG("NULL argument");
  9767. return WOLFSSL_FAILURE;
  9768. }
  9769. listattribute = CheckcipherList(list);
  9770. if (listattribute == 0) {
  9771. /* list has mixed(pre-TLSv13 and TLSv13) suites
  9772. * update cipher suites the same as before
  9773. */
  9774. return (SetCipherList(ctx, suites, list)) ? WOLFSSL_SUCCESS :
  9775. WOLFSSL_FAILURE;
  9776. }
  9777. else if (listattribute == 1) {
  9778. /* list has only pre-TLSv13 suites.
  9779. * Only update before TLSv13 suites.
  9780. */
  9781. tls13Only = 1;
  9782. }
  9783. else if (listattribute == 2) {
  9784. /* list has only TLSv13 suites. Only update TLv13 suites
  9785. * simulate set_ciphersuites() compatibility layer API
  9786. */
  9787. tls13Only = 0;
  9788. }
  9789. buildcipherList = buildEnabledCipherList(ctx, ctx->suites,
  9790. tls13Only, list);
  9791. if (buildcipherList) {
  9792. ret = SetCipherList(ctx, suites, buildcipherList);
  9793. XFREE(buildcipherList, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9794. }
  9795. else {
  9796. ret = SetCipherList(ctx, suites, list);
  9797. }
  9798. return ret;
  9799. }
  9800. #endif
  9801. int wolfSSL_CTX_set_cipher_list(WOLFSSL_CTX* ctx, const char* list)
  9802. {
  9803. WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list");
  9804. if (ctx == NULL)
  9805. return WOLFSSL_FAILURE;
  9806. /* alloc/init on demand only */
  9807. if (ctx->suites == NULL) {
  9808. ctx->suites = (Suites*)XMALLOC(sizeof(Suites), ctx->heap,
  9809. DYNAMIC_TYPE_SUITES);
  9810. if (ctx->suites == NULL) {
  9811. WOLFSSL_MSG("Memory alloc for Suites failed");
  9812. return WOLFSSL_FAILURE;
  9813. }
  9814. XMEMSET(ctx->suites, 0, sizeof(Suites));
  9815. }
  9816. #ifdef OPENSSL_EXTRA
  9817. return wolfSSL_parse_cipher_list(ctx, ctx->suites, list);
  9818. #else
  9819. return (SetCipherList(ctx, ctx->suites, list)) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
  9820. #endif
  9821. }
  9822. int wolfSSL_set_cipher_list(WOLFSSL* ssl, const char* list)
  9823. {
  9824. WOLFSSL_ENTER("wolfSSL_set_cipher_list");
  9825. #ifdef SINGLE_THREADED
  9826. if (ssl->ctx->suites == ssl->suites) {
  9827. ssl->suites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap,
  9828. DYNAMIC_TYPE_SUITES);
  9829. if (ssl->suites == NULL) {
  9830. WOLFSSL_MSG("Suites Memory error");
  9831. return MEMORY_E;
  9832. }
  9833. *ssl->suites = *ssl->ctx->suites;
  9834. ssl->options.ownSuites = 1;
  9835. }
  9836. #endif
  9837. #ifdef OPENSSL_EXTRA
  9838. return wolfSSL_parse_cipher_list(ssl->ctx, ssl->suites, list);
  9839. #else
  9840. return (SetCipherList(ssl->ctx, ssl->suites, list)) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
  9841. #endif
  9842. }
  9843. #ifdef HAVE_KEYING_MATERIAL
  9844. #define TLS_PRF_LABEL_CLIENT_FINISHED "client finished"
  9845. #define TLS_PRF_LABEL_SERVER_FINISHED "server finished"
  9846. #define TLS_PRF_LABEL_MASTER_SECRET "master secret"
  9847. #define TLS_PRF_LABEL_EXT_MASTER_SECRET "extended master secret"
  9848. #define TLS_PRF_LABEL_KEY_EXPANSION "key expansion"
  9849. static const struct ForbiddenLabels {
  9850. const char* label;
  9851. size_t labelLen;
  9852. } forbiddenLabels[] = {
  9853. {TLS_PRF_LABEL_CLIENT_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_CLIENT_FINISHED)},
  9854. {TLS_PRF_LABEL_SERVER_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_SERVER_FINISHED)},
  9855. {TLS_PRF_LABEL_MASTER_SECRET, XSTR_SIZEOF(TLS_PRF_LABEL_MASTER_SECRET)},
  9856. {TLS_PRF_LABEL_EXT_MASTER_SECRET, XSTR_SIZEOF(TLS_PRF_LABEL_EXT_MASTER_SECRET)},
  9857. {TLS_PRF_LABEL_KEY_EXPANSION, XSTR_SIZEOF(TLS_PRF_LABEL_KEY_EXPANSION)},
  9858. {NULL, 0},
  9859. };
  9860. /**
  9861. * Implement RFC 5705
  9862. * TLS 1.3 uses a different exporter definition (section 7.5 of RFC 8446)
  9863. * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error
  9864. */
  9865. int wolfSSL_export_keying_material(WOLFSSL *ssl,
  9866. unsigned char *out, size_t outLen,
  9867. const char *label, size_t labelLen,
  9868. const unsigned char *context, size_t contextLen,
  9869. int use_context)
  9870. {
  9871. byte* seed = NULL;
  9872. word32 seedLen;
  9873. const struct ForbiddenLabels* fl;
  9874. WOLFSSL_ENTER("wolfSSL_export_keying_material");
  9875. if (ssl == NULL || out == NULL || label == NULL ||
  9876. (use_context && contextLen && context == NULL)) {
  9877. WOLFSSL_MSG("Bad argument");
  9878. return WOLFSSL_FAILURE;
  9879. }
  9880. /* clientRandom + serverRandom
  9881. * OR
  9882. * clientRandom + serverRandom + ctx len encoding + ctx */
  9883. seedLen = !use_context ? (word32)SEED_LEN :
  9884. (word32)SEED_LEN + 2 + (word32)contextLen;
  9885. if (ssl->options.saveArrays == 0 || ssl->arrays == NULL) {
  9886. WOLFSSL_MSG("To export keying material wolfSSL needs to keep handshake "
  9887. "data. Call wolfSSL_KeepArrays before attempting to "
  9888. "export keyid material.");
  9889. return WOLFSSL_FAILURE;
  9890. }
  9891. /* check forbidden labels */
  9892. for (fl = &forbiddenLabels[0]; fl->label != NULL; fl++) {
  9893. if (labelLen >= fl->labelLen &&
  9894. XMEMCMP(label, fl->label, fl->labelLen) == 0) {
  9895. WOLFSSL_MSG("Forbidden label");
  9896. return WOLFSSL_FAILURE;
  9897. }
  9898. }
  9899. #ifdef WOLFSSL_TLS13
  9900. if (IsAtLeastTLSv1_3(ssl->version)) {
  9901. /* Path for TLS 1.3 */
  9902. if (!use_context) {
  9903. contextLen = 0;
  9904. context = (byte*)""; /* Give valid pointer for 0 length memcpy */
  9905. }
  9906. if (Tls13_Exporter(ssl, out, (word32)outLen, label, labelLen,
  9907. context, contextLen) != 0) {
  9908. WOLFSSL_MSG("Tls13_Exporter error");
  9909. return WOLFSSL_FAILURE;
  9910. }
  9911. return WOLFSSL_SUCCESS;
  9912. }
  9913. #endif
  9914. /* Path for <=TLS 1.2 */
  9915. seed = (byte*)XMALLOC(seedLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9916. if (seed == NULL) {
  9917. WOLFSSL_MSG("malloc error");
  9918. return WOLFSSL_FAILURE;
  9919. }
  9920. XMEMCPY(seed, ssl->arrays->clientRandom, RAN_LEN);
  9921. XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
  9922. if (use_context) {
  9923. /* Encode len in big endian */
  9924. seed[SEED_LEN ] = (contextLen >> 8) & 0xFF;
  9925. seed[SEED_LEN + 1] = (contextLen) & 0xFF;
  9926. if (contextLen) {
  9927. /* 0 length context is allowed */
  9928. XMEMCPY(seed + SEED_LEN + 2, context, contextLen);
  9929. }
  9930. }
  9931. PRIVATE_KEY_UNLOCK();
  9932. if (wc_PRF_TLS(out, (word32)outLen, ssl->arrays->masterSecret, SECRET_LEN,
  9933. (byte*)label, (word32)labelLen, seed, seedLen, IsAtLeastTLSv1_2(ssl),
  9934. ssl->specs.mac_algorithm, ssl->heap, ssl->devId) != 0) {
  9935. WOLFSSL_MSG("wc_PRF_TLS error");
  9936. PRIVATE_KEY_LOCK();
  9937. XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9938. return WOLFSSL_FAILURE;
  9939. }
  9940. PRIVATE_KEY_LOCK();
  9941. XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9942. return WOLFSSL_SUCCESS;
  9943. }
  9944. #endif /* HAVE_KEYING_MATERIAL */
  9945. int wolfSSL_dtls_get_using_nonblock(WOLFSSL* ssl)
  9946. {
  9947. int useNb = 0;
  9948. if (ssl == NULL)
  9949. return WOLFSSL_FAILURE;
  9950. WOLFSSL_ENTER("wolfSSL_dtls_get_using_nonblock");
  9951. if (ssl->options.dtls) {
  9952. #ifdef WOLFSSL_DTLS
  9953. useNb = ssl->options.dtlsUseNonblock;
  9954. #endif
  9955. }
  9956. else {
  9957. WOLFSSL_MSG("wolfSSL_dtls_get_using_nonblock() is "
  9958. "DEPRECATED for non-DTLS use.");
  9959. }
  9960. return useNb;
  9961. }
  9962. #ifndef WOLFSSL_LEANPSK
  9963. void wolfSSL_dtls_set_using_nonblock(WOLFSSL* ssl, int nonblock)
  9964. {
  9965. (void)nonblock;
  9966. WOLFSSL_ENTER("wolfSSL_dtls_set_using_nonblock");
  9967. if (ssl == NULL)
  9968. return;
  9969. if (ssl->options.dtls) {
  9970. #ifdef WOLFSSL_DTLS
  9971. ssl->options.dtlsUseNonblock = (nonblock != 0);
  9972. #endif
  9973. }
  9974. else {
  9975. WOLFSSL_MSG("wolfSSL_dtls_set_using_nonblock() is "
  9976. "DEPRECATED for non-DTLS use.");
  9977. }
  9978. }
  9979. #ifdef WOLFSSL_DTLS
  9980. int wolfSSL_dtls_get_current_timeout(WOLFSSL* ssl)
  9981. {
  9982. int timeout = 0;
  9983. if (ssl)
  9984. timeout = ssl->dtls_timeout;
  9985. WOLFSSL_LEAVE("wolfSSL_dtls_get_current_timeout()", timeout);
  9986. return timeout;
  9987. }
  9988. #ifdef WOLFSSL_DTLS13
  9989. /*
  9990. * This API returns 1 when the user should set a short timeout for receiving
  9991. * data. It is recommended that it is at most 1/4 the value returned by
  9992. * wolfSSL_dtls_get_current_timeout().
  9993. */
  9994. int wolfSSL_dtls13_use_quick_timeout(WOLFSSL* ssl)
  9995. {
  9996. return ssl->dtls13FastTimeout;
  9997. }
  9998. /*
  9999. * When this is set, a DTLS 1.3 connection will send acks immediately when a
  10000. * disruption is detected to shortcut timeouts. This results in potentially
  10001. * more traffic but may make the handshake quicker.
  10002. */
  10003. void wolfSSL_dtls13_set_send_more_acks(WOLFSSL* ssl, int value)
  10004. {
  10005. if (ssl != NULL)
  10006. ssl->options.dtls13SendMoreAcks = !!value;
  10007. }
  10008. #endif /* WOLFSSL_DTLS13 */
  10009. int wolfSSL_DTLSv1_get_timeout(WOLFSSL* ssl, WOLFSSL_TIMEVAL* timeleft)
  10010. {
  10011. if (ssl && timeleft) {
  10012. XMEMSET(timeleft, 0, sizeof(WOLFSSL_TIMEVAL));
  10013. timeleft->tv_sec = ssl->dtls_timeout;
  10014. }
  10015. return 0;
  10016. }
  10017. #ifndef NO_WOLFSSL_STUB
  10018. int wolfSSL_DTLSv1_handle_timeout(WOLFSSL* ssl)
  10019. {
  10020. WOLFSSL_STUB("SSL_DTLSv1_handle_timeout");
  10021. (void)ssl;
  10022. return 0;
  10023. }
  10024. #endif
  10025. #ifndef NO_WOLFSSL_STUB
  10026. void wolfSSL_DTLSv1_set_initial_timeout_duration(WOLFSSL* ssl, word32 duration_ms)
  10027. {
  10028. WOLFSSL_STUB("SSL_DTLSv1_set_initial_timeout_duration");
  10029. (void)ssl;
  10030. (void)duration_ms;
  10031. }
  10032. #endif
  10033. /* user may need to alter init dtls recv timeout, WOLFSSL_SUCCESS on ok */
  10034. int wolfSSL_dtls_set_timeout_init(WOLFSSL* ssl, int timeout)
  10035. {
  10036. if (ssl == NULL || timeout < 0)
  10037. return BAD_FUNC_ARG;
  10038. if (timeout > ssl->dtls_timeout_max) {
  10039. WOLFSSL_MSG("Can't set dtls timeout init greater than dtls timeout max");
  10040. return BAD_FUNC_ARG;
  10041. }
  10042. ssl->dtls_timeout_init = timeout;
  10043. ssl->dtls_timeout = timeout;
  10044. return WOLFSSL_SUCCESS;
  10045. }
  10046. /* user may need to alter max dtls recv timeout, WOLFSSL_SUCCESS on ok */
  10047. int wolfSSL_dtls_set_timeout_max(WOLFSSL* ssl, int timeout)
  10048. {
  10049. if (ssl == NULL || timeout < 0)
  10050. return BAD_FUNC_ARG;
  10051. if (timeout < ssl->dtls_timeout_init) {
  10052. WOLFSSL_MSG("Can't set dtls timeout max less than dtls timeout init");
  10053. return BAD_FUNC_ARG;
  10054. }
  10055. ssl->dtls_timeout_max = timeout;
  10056. return WOLFSSL_SUCCESS;
  10057. }
  10058. int wolfSSL_dtls_got_timeout(WOLFSSL* ssl)
  10059. {
  10060. int result = WOLFSSL_SUCCESS;
  10061. WOLFSSL_ENTER("wolfSSL_dtls_got_timeout()");
  10062. if (ssl == NULL)
  10063. return WOLFSSL_FATAL_ERROR;
  10064. #ifdef WOLFSSL_DTLS13
  10065. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) {
  10066. result = Dtls13RtxTimeout(ssl);
  10067. if (result < 0) {
  10068. if (result == WANT_WRITE)
  10069. ssl->dtls13SendingAckOrRtx = 1;
  10070. ssl->error = result;
  10071. WOLFSSL_ERROR(result);
  10072. return WOLFSSL_FATAL_ERROR;
  10073. }
  10074. return WOLFSSL_SUCCESS;
  10075. }
  10076. #endif /* WOLFSSL_DTLS13 */
  10077. if ((IsSCR(ssl) || !ssl->options.handShakeDone)) {
  10078. if (DtlsMsgPoolTimeout(ssl) < 0){
  10079. ssl->error = SOCKET_ERROR_E;
  10080. WOLFSSL_ERROR(ssl->error);
  10081. result = WOLFSSL_FATAL_ERROR;
  10082. }
  10083. else if ((result = DtlsMsgPoolSend(ssl, 0)) < 0) {
  10084. ssl->error = result;
  10085. WOLFSSL_ERROR(result);
  10086. result = WOLFSSL_FATAL_ERROR;
  10087. }
  10088. else {
  10089. /* Reset return value to success */
  10090. result = WOLFSSL_SUCCESS;
  10091. }
  10092. }
  10093. WOLFSSL_LEAVE("wolfSSL_dtls_got_timeout()", result);
  10094. return result;
  10095. }
  10096. /* retransmit all the saves messages, WOLFSSL_SUCCESS on ok */
  10097. int wolfSSL_dtls_retransmit(WOLFSSL* ssl)
  10098. {
  10099. WOLFSSL_ENTER("wolfSSL_dtls_retransmit()");
  10100. if (ssl == NULL)
  10101. return WOLFSSL_FATAL_ERROR;
  10102. if (!ssl->options.handShakeDone) {
  10103. int result = DtlsMsgPoolSend(ssl, 0);
  10104. if (result < 0) {
  10105. ssl->error = result;
  10106. WOLFSSL_ERROR(result);
  10107. return WOLFSSL_FATAL_ERROR;
  10108. }
  10109. }
  10110. return 0;
  10111. }
  10112. #endif /* DTLS */
  10113. #endif /* LEANPSK */
  10114. #if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
  10115. /* Not an SSL function, return 0 for success, error code otherwise */
  10116. /* Prereq: ssl's RNG needs to be initialized. */
  10117. int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl,
  10118. const byte* secret, word32 secretSz)
  10119. {
  10120. int ret = 0;
  10121. WOLFSSL_ENTER("wolfSSL_DTLS_SetCookieSecret");
  10122. if (ssl == NULL) {
  10123. WOLFSSL_MSG("need a SSL object");
  10124. return BAD_FUNC_ARG;
  10125. }
  10126. if (secret != NULL && secretSz == 0) {
  10127. WOLFSSL_MSG("can't have a new secret without a size");
  10128. return BAD_FUNC_ARG;
  10129. }
  10130. /* If secretSz is 0, use the default size. */
  10131. if (secretSz == 0)
  10132. secretSz = COOKIE_SECRET_SZ;
  10133. if (secretSz != ssl->buffers.dtlsCookieSecret.length) {
  10134. byte* newSecret;
  10135. if (ssl->buffers.dtlsCookieSecret.buffer != NULL) {
  10136. ForceZero(ssl->buffers.dtlsCookieSecret.buffer,
  10137. ssl->buffers.dtlsCookieSecret.length);
  10138. XFREE(ssl->buffers.dtlsCookieSecret.buffer,
  10139. ssl->heap, DYNAMIC_TYPE_NONE);
  10140. }
  10141. newSecret = (byte*)XMALLOC(secretSz, ssl->heap,DYNAMIC_TYPE_COOKIE_PWD);
  10142. if (newSecret == NULL) {
  10143. ssl->buffers.dtlsCookieSecret.buffer = NULL;
  10144. ssl->buffers.dtlsCookieSecret.length = 0;
  10145. WOLFSSL_MSG("couldn't allocate new cookie secret");
  10146. return MEMORY_ERROR;
  10147. }
  10148. ssl->buffers.dtlsCookieSecret.buffer = newSecret;
  10149. ssl->buffers.dtlsCookieSecret.length = secretSz;
  10150. #ifdef WOLFSSL_CHECK_MEM_ZERO
  10151. wc_MemZero_Add("wolfSSL_DTLS_SetCookieSecret secret",
  10152. ssl->buffers.dtlsCookieSecret.buffer,
  10153. ssl->buffers.dtlsCookieSecret.length);
  10154. #endif
  10155. }
  10156. /* If the supplied secret is NULL, randomly generate a new secret. */
  10157. if (secret == NULL) {
  10158. ret = wc_RNG_GenerateBlock(ssl->rng,
  10159. ssl->buffers.dtlsCookieSecret.buffer, secretSz);
  10160. }
  10161. else
  10162. XMEMCPY(ssl->buffers.dtlsCookieSecret.buffer, secret, secretSz);
  10163. WOLFSSL_LEAVE("wolfSSL_DTLS_SetCookieSecret", 0);
  10164. return ret;
  10165. }
  10166. #endif /* WOLFSSL_DTLS && !NO_WOLFSSL_SERVER */
  10167. /* EITHER SIDE METHODS */
  10168. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
  10169. WOLFSSL_METHOD* wolfSSLv23_method(void)
  10170. {
  10171. return wolfSSLv23_method_ex(NULL);
  10172. }
  10173. WOLFSSL_METHOD* wolfSSLv23_method_ex(void* heap)
  10174. {
  10175. WOLFSSL_METHOD* m = NULL;
  10176. WOLFSSL_ENTER("SSLv23_method");
  10177. #if !defined(NO_WOLFSSL_CLIENT)
  10178. m = wolfSSLv23_client_method_ex(heap);
  10179. #elif !defined(NO_WOLFSSL_SERVER)
  10180. m = wolfSSLv23_server_method_ex(heap);
  10181. #else
  10182. (void)heap;
  10183. #endif
  10184. if (m != NULL) {
  10185. m->side = WOLFSSL_NEITHER_END;
  10186. }
  10187. return m;
  10188. }
  10189. #ifdef WOLFSSL_ALLOW_SSLV3
  10190. WOLFSSL_METHOD* wolfSSLv3_method(void)
  10191. {
  10192. return wolfSSLv3_method_ex(NULL);
  10193. }
  10194. WOLFSSL_METHOD* wolfSSLv3_method_ex(void* heap)
  10195. {
  10196. WOLFSSL_METHOD* m = NULL;
  10197. WOLFSSL_ENTER("SSLv3_method");
  10198. #if !defined(NO_WOLFSSL_CLIENT)
  10199. m = wolfSSLv3_client_method_ex(heap);
  10200. #elif !defined(NO_WOLFSSL_SERVER)
  10201. m = wolfSSLv3_server_method_ex(heap);
  10202. #endif
  10203. if (m != NULL) {
  10204. m->side = WOLFSSL_NEITHER_END;
  10205. }
  10206. return m;
  10207. }
  10208. #endif
  10209. #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
  10210. /* client only parts */
  10211. #ifndef NO_WOLFSSL_CLIENT
  10212. #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS)
  10213. WOLFSSL_METHOD* wolfSSLv2_client_method(void)
  10214. {
  10215. WOLFSSL_STUB("wolfSSLv2_client_method");
  10216. return NULL;
  10217. }
  10218. #endif
  10219. #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
  10220. WOLFSSL_METHOD* wolfSSLv3_client_method(void)
  10221. {
  10222. return wolfSSLv3_client_method_ex(NULL);
  10223. }
  10224. WOLFSSL_METHOD* wolfSSLv3_client_method_ex(void* heap)
  10225. {
  10226. WOLFSSL_METHOD* method =
  10227. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  10228. heap, DYNAMIC_TYPE_METHOD);
  10229. (void)heap;
  10230. WOLFSSL_ENTER("SSLv3_client_method_ex");
  10231. if (method)
  10232. InitSSL_Method(method, MakeSSLv3());
  10233. return method;
  10234. }
  10235. #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
  10236. WOLFSSL_METHOD* wolfSSLv23_client_method(void)
  10237. {
  10238. return wolfSSLv23_client_method_ex(NULL);
  10239. }
  10240. WOLFSSL_METHOD* wolfSSLv23_client_method_ex(void* heap)
  10241. {
  10242. WOLFSSL_METHOD* method =
  10243. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  10244. heap, DYNAMIC_TYPE_METHOD);
  10245. (void)heap;
  10246. WOLFSSL_ENTER("SSLv23_client_method_ex");
  10247. if (method) {
  10248. #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512)
  10249. #if defined(WOLFSSL_TLS13)
  10250. InitSSL_Method(method, MakeTLSv1_3());
  10251. #elif !defined(WOLFSSL_NO_TLS12)
  10252. InitSSL_Method(method, MakeTLSv1_2());
  10253. #elif !defined(NO_OLD_TLS)
  10254. InitSSL_Method(method, MakeTLSv1_1());
  10255. #endif
  10256. #else
  10257. #ifndef NO_OLD_TLS
  10258. InitSSL_Method(method, MakeTLSv1_1());
  10259. #endif
  10260. #endif
  10261. #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13)
  10262. method->downgrade = 1;
  10263. #endif
  10264. }
  10265. return method;
  10266. }
  10267. /* please see note at top of README if you get an error from connect */
  10268. WOLFSSL_ABI
  10269. int wolfSSL_connect(WOLFSSL* ssl)
  10270. {
  10271. #if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && defined(WOLFSSL_TLS13))
  10272. int neededState;
  10273. byte advanceState;
  10274. #endif
  10275. int ret = 0;
  10276. (void)ret;
  10277. #ifdef HAVE_ERRNO_H
  10278. errno = 0;
  10279. #endif
  10280. if (ssl == NULL)
  10281. return BAD_FUNC_ARG;
  10282. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
  10283. if (ssl->options.side == WOLFSSL_NEITHER_END) {
  10284. ssl->error = InitSSL_Side(ssl, WOLFSSL_CLIENT_END);
  10285. if (ssl->error != WOLFSSL_SUCCESS) {
  10286. WOLFSSL_ERROR(ssl->error);
  10287. return WOLFSSL_FATAL_ERROR;
  10288. }
  10289. ssl->error = 0; /* expected to be zero here */
  10290. }
  10291. #ifdef OPENSSL_EXTRA
  10292. if (ssl->CBIS != NULL) {
  10293. ssl->CBIS(ssl, SSL_ST_CONNECT, WOLFSSL_SUCCESS);
  10294. ssl->cbmode = SSL_CB_WRITE;
  10295. }
  10296. #endif
  10297. #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
  10298. #if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && defined(WOLFSSL_TLS13)
  10299. return wolfSSL_connect_TLSv13(ssl);
  10300. #else
  10301. #ifdef WOLFSSL_TLS13
  10302. if (ssl->options.tls1_3)
  10303. return wolfSSL_connect_TLSv13(ssl);
  10304. #endif
  10305. WOLFSSL_ENTER("SSL_connect()");
  10306. /* make sure this wolfSSL object has arrays and rng setup. Protects
  10307. * case where the WOLFSSL object is re-used via wolfSSL_clear() */
  10308. if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
  10309. return ret;
  10310. }
  10311. #ifdef WOLFSSL_WOLFSENTRY_HOOKS
  10312. if ((ssl->ConnectFilter != NULL) &&
  10313. (ssl->options.connectState == CONNECT_BEGIN)) {
  10314. wolfSSL_netfilter_decision_t res;
  10315. if ((ssl->ConnectFilter(ssl, ssl->ConnectFilter_arg, &res) ==
  10316. WOLFSSL_SUCCESS) &&
  10317. (res == WOLFSSL_NETFILTER_REJECT)) {
  10318. ssl->error = SOCKET_FILTERED_E;
  10319. WOLFSSL_ERROR(ssl->error);
  10320. return WOLFSSL_FATAL_ERROR;
  10321. }
  10322. }
  10323. #endif /* WOLFSSL_WOLFSENTRY_HOOKS */
  10324. if (ssl->options.side != WOLFSSL_CLIENT_END) {
  10325. ssl->error = SIDE_ERROR;
  10326. WOLFSSL_ERROR(ssl->error);
  10327. return WOLFSSL_FATAL_ERROR;
  10328. }
  10329. #ifdef WOLFSSL_DTLS
  10330. if (ssl->version.major == DTLS_MAJOR) {
  10331. ssl->options.dtls = 1;
  10332. ssl->options.tls = 1;
  10333. ssl->options.tls1_1 = 1;
  10334. }
  10335. #endif
  10336. /* fragOffset is non-zero when sending fragments. On the last
  10337. * fragment, fragOffset is zero again, and the state can be
  10338. * advanced. */
  10339. advanceState = ssl->fragOffset == 0 &&
  10340. (ssl->options.connectState == CONNECT_BEGIN ||
  10341. ssl->options.connectState == HELLO_AGAIN ||
  10342. (ssl->options.connectState >= FIRST_REPLY_DONE &&
  10343. ssl->options.connectState <= FIRST_REPLY_FOURTH));
  10344. #ifdef WOLFSSL_DTLS13
  10345. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version))
  10346. advanceState = advanceState && !ssl->dtls13SendingAckOrRtx;
  10347. #endif /* WOLFSSL_DTLS13 */
  10348. if (ssl->buffers.outputBuffer.length > 0
  10349. #ifdef WOLFSSL_ASYNC_CRYPT
  10350. /* do not send buffered or advance state if last error was an
  10351. async pending operation */
  10352. && ssl->error != WC_PENDING_E
  10353. #endif
  10354. ) {
  10355. ret = SendBuffered(ssl);
  10356. if (ret == 0) {
  10357. if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
  10358. if (advanceState) {
  10359. ssl->options.connectState++;
  10360. WOLFSSL_MSG("connect state: "
  10361. "Advanced from last buffered fragment send");
  10362. #ifdef WOLFSSL_ASYNC_IO
  10363. /* Cleanup async */
  10364. FreeAsyncCtx(ssl, 0);
  10365. #endif
  10366. }
  10367. }
  10368. else {
  10369. WOLFSSL_MSG("connect state: "
  10370. "Not advanced, more fragments to send");
  10371. }
  10372. }
  10373. else {
  10374. ssl->error = ret;
  10375. WOLFSSL_ERROR(ssl->error);
  10376. return WOLFSSL_FATAL_ERROR;
  10377. }
  10378. }
  10379. ret = RetrySendAlert(ssl);
  10380. if (ret != 0) {
  10381. ssl->error = ret;
  10382. WOLFSSL_ERROR(ssl->error);
  10383. return WOLFSSL_FATAL_ERROR;
  10384. }
  10385. switch (ssl->options.connectState) {
  10386. case CONNECT_BEGIN :
  10387. /* always send client hello first */
  10388. if ( (ssl->error = SendClientHello(ssl)) != 0) {
  10389. WOLFSSL_ERROR(ssl->error);
  10390. return WOLFSSL_FATAL_ERROR;
  10391. }
  10392. ssl->options.connectState = CLIENT_HELLO_SENT;
  10393. WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT");
  10394. FALL_THROUGH;
  10395. case CLIENT_HELLO_SENT :
  10396. neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE :
  10397. SERVER_HELLODONE_COMPLETE;
  10398. #ifdef WOLFSSL_DTLS
  10399. /* In DTLS, when resuming, we can go straight to FINISHED,
  10400. * or do a cookie exchange and then skip to FINISHED, assume
  10401. * we need the cookie exchange first. */
  10402. if (IsDtlsNotSctpMode(ssl))
  10403. neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
  10404. #endif
  10405. /* get response */
  10406. while (ssl->options.serverState < neededState) {
  10407. #ifdef WOLFSSL_TLS13
  10408. if (ssl->options.tls1_3)
  10409. return wolfSSL_connect_TLSv13(ssl);
  10410. #endif
  10411. if ( (ssl->error = ProcessReply(ssl)) < 0) {
  10412. WOLFSSL_ERROR(ssl->error);
  10413. return WOLFSSL_FATAL_ERROR;
  10414. }
  10415. /* if resumption failed, reset needed state */
  10416. else if (neededState == SERVER_FINISHED_COMPLETE)
  10417. if (!ssl->options.resuming) {
  10418. #ifdef WOLFSSL_DTLS
  10419. if (IsDtlsNotSctpMode(ssl))
  10420. neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
  10421. else
  10422. #endif
  10423. neededState = SERVER_HELLODONE_COMPLETE;
  10424. }
  10425. #ifdef WOLFSSL_DTLS13
  10426. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)
  10427. && ssl->dtls13Rtx.sendAcks == 1) {
  10428. ssl->dtls13Rtx.sendAcks = 0;
  10429. /* we aren't negotiated the version yet, so we aren't sure
  10430. * the other end can speak v1.3. On the other side we have
  10431. * received a unified records, assuming that the
  10432. * ServerHello got lost, we will send an empty ACK. In case
  10433. * the server is a DTLS with version less than 1.3, it
  10434. * should just ignore the message */
  10435. if ((ssl->error = SendDtls13Ack(ssl)) < 0) {
  10436. if (ssl->error == WANT_WRITE)
  10437. ssl->dtls13SendingAckOrRtx = 1;
  10438. WOLFSSL_ERROR(ssl->error);
  10439. return WOLFSSL_FATAL_ERROR;
  10440. }
  10441. }
  10442. #endif /* WOLFSSL_DTLS13 */
  10443. }
  10444. ssl->options.connectState = HELLO_AGAIN;
  10445. WOLFSSL_MSG("connect state: HELLO_AGAIN");
  10446. FALL_THROUGH;
  10447. case HELLO_AGAIN :
  10448. #ifdef WOLFSSL_TLS13
  10449. if (ssl->options.tls1_3)
  10450. return wolfSSL_connect_TLSv13(ssl);
  10451. #endif
  10452. #ifdef WOLFSSL_DTLS
  10453. if (ssl->options.serverState ==
  10454. SERVER_HELLOVERIFYREQUEST_COMPLETE) {
  10455. if (IsDtlsNotSctpMode(ssl)) {
  10456. /* re-init hashes, exclude first hello and verify request */
  10457. if ((ssl->error = InitHandshakeHashes(ssl)) != 0) {
  10458. WOLFSSL_ERROR(ssl->error);
  10459. return WOLFSSL_FATAL_ERROR;
  10460. }
  10461. if ( (ssl->error = SendClientHello(ssl)) != 0) {
  10462. WOLFSSL_ERROR(ssl->error);
  10463. return WOLFSSL_FATAL_ERROR;
  10464. }
  10465. }
  10466. }
  10467. #endif
  10468. ssl->options.connectState = HELLO_AGAIN_REPLY;
  10469. WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY");
  10470. FALL_THROUGH;
  10471. case HELLO_AGAIN_REPLY :
  10472. #ifdef WOLFSSL_DTLS
  10473. if (IsDtlsNotSctpMode(ssl)) {
  10474. neededState = ssl->options.resuming ?
  10475. SERVER_FINISHED_COMPLETE : SERVER_HELLODONE_COMPLETE;
  10476. /* get response */
  10477. while (ssl->options.serverState < neededState) {
  10478. if ( (ssl->error = ProcessReply(ssl)) < 0) {
  10479. WOLFSSL_ERROR(ssl->error);
  10480. return WOLFSSL_FATAL_ERROR;
  10481. }
  10482. /* if resumption failed, reset needed state */
  10483. if (neededState == SERVER_FINISHED_COMPLETE) {
  10484. if (!ssl->options.resuming)
  10485. neededState = SERVER_HELLODONE_COMPLETE;
  10486. }
  10487. }
  10488. }
  10489. #endif
  10490. ssl->options.connectState = FIRST_REPLY_DONE;
  10491. WOLFSSL_MSG("connect state: FIRST_REPLY_DONE");
  10492. FALL_THROUGH;
  10493. case FIRST_REPLY_DONE :
  10494. if (ssl->options.certOnly)
  10495. return WOLFSSL_SUCCESS;
  10496. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
  10497. #ifdef WOLFSSL_TLS13
  10498. if (ssl->options.tls1_3)
  10499. return wolfSSL_connect_TLSv13(ssl);
  10500. #endif
  10501. if (ssl->options.sendVerify) {
  10502. if ( (ssl->error = SendCertificate(ssl)) != 0) {
  10503. #ifdef WOLFSSL_CHECK_ALERT_ON_ERR
  10504. ProcessReplyEx(ssl, 1); /* See if an alert was sent. */
  10505. #endif
  10506. WOLFSSL_ERROR(ssl->error);
  10507. return WOLFSSL_FATAL_ERROR;
  10508. }
  10509. WOLFSSL_MSG("sent: certificate");
  10510. }
  10511. #endif
  10512. ssl->options.connectState = FIRST_REPLY_FIRST;
  10513. WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST");
  10514. FALL_THROUGH;
  10515. case FIRST_REPLY_FIRST :
  10516. #ifdef WOLFSSL_TLS13
  10517. if (ssl->options.tls1_3)
  10518. return wolfSSL_connect_TLSv13(ssl);
  10519. #endif
  10520. if (!ssl->options.resuming) {
  10521. if ( (ssl->error = SendClientKeyExchange(ssl)) != 0) {
  10522. #ifdef WOLFSSL_CHECK_ALERT_ON_ERR
  10523. ProcessReplyEx(ssl, 1); /* See if an alert was sent. */
  10524. #endif
  10525. WOLFSSL_ERROR(ssl->error);
  10526. return WOLFSSL_FATAL_ERROR;
  10527. }
  10528. WOLFSSL_MSG("sent: client key exchange");
  10529. }
  10530. ssl->options.connectState = FIRST_REPLY_SECOND;
  10531. WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
  10532. FALL_THROUGH;
  10533. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  10534. case FIRST_REPLY_SECOND :
  10535. /* CLIENT: Fail-safe for Server Authentication. */
  10536. if (!ssl->options.peerAuthGood) {
  10537. WOLFSSL_MSG("Server authentication did not happen");
  10538. ssl->error = NO_PEER_VERIFY;
  10539. return WOLFSSL_FATAL_ERROR;
  10540. }
  10541. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
  10542. if (ssl->options.sendVerify) {
  10543. if ( (ssl->error = SendCertificateVerify(ssl)) != 0) {
  10544. #ifdef WOLFSSL_CHECK_ALERT_ON_ERR
  10545. ProcessReplyEx(ssl, 1); /* See if an alert was sent. */
  10546. #endif
  10547. WOLFSSL_ERROR(ssl->error);
  10548. return WOLFSSL_FATAL_ERROR;
  10549. }
  10550. WOLFSSL_MSG("sent: certificate verify");
  10551. }
  10552. #endif /* !NO_CERTS && !WOLFSSL_NO_CLIENT_AUTH */
  10553. ssl->options.connectState = FIRST_REPLY_THIRD;
  10554. WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
  10555. FALL_THROUGH;
  10556. case FIRST_REPLY_THIRD :
  10557. if ( (ssl->error = SendChangeCipher(ssl)) != 0) {
  10558. #ifdef WOLFSSL_CHECK_ALERT_ON_ERR
  10559. ProcessReplyEx(ssl, 1); /* See if an alert was sent. */
  10560. #endif
  10561. WOLFSSL_ERROR(ssl->error);
  10562. return WOLFSSL_FATAL_ERROR;
  10563. }
  10564. WOLFSSL_MSG("sent: change cipher spec");
  10565. ssl->options.connectState = FIRST_REPLY_FOURTH;
  10566. WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH");
  10567. FALL_THROUGH;
  10568. case FIRST_REPLY_FOURTH :
  10569. if ( (ssl->error = SendFinished(ssl)) != 0) {
  10570. #ifdef WOLFSSL_CHECK_ALERT_ON_ERR
  10571. ProcessReplyEx(ssl, 1); /* See if an alert was sent. */
  10572. #endif
  10573. WOLFSSL_ERROR(ssl->error);
  10574. return WOLFSSL_FATAL_ERROR;
  10575. }
  10576. WOLFSSL_MSG("sent: finished");
  10577. ssl->options.connectState = FINISHED_DONE;
  10578. WOLFSSL_MSG("connect state: FINISHED_DONE");
  10579. FALL_THROUGH;
  10580. #ifdef WOLFSSL_DTLS13
  10581. case WAIT_FINISHED_ACK:
  10582. ssl->options.connectState = FINISHED_DONE;
  10583. FALL_THROUGH;
  10584. #endif /* WOLFSSL_DTLS13 */
  10585. case FINISHED_DONE :
  10586. /* get response */
  10587. while (ssl->options.serverState < SERVER_FINISHED_COMPLETE)
  10588. if ( (ssl->error = ProcessReply(ssl)) < 0) {
  10589. WOLFSSL_ERROR(ssl->error);
  10590. return WOLFSSL_FATAL_ERROR;
  10591. }
  10592. ssl->options.connectState = SECOND_REPLY_DONE;
  10593. WOLFSSL_MSG("connect state: SECOND_REPLY_DONE");
  10594. FALL_THROUGH;
  10595. case SECOND_REPLY_DONE:
  10596. #ifndef NO_HANDSHAKE_DONE_CB
  10597. if (ssl->hsDoneCb) {
  10598. int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
  10599. if (cbret < 0) {
  10600. ssl->error = cbret;
  10601. WOLFSSL_MSG("HandShake Done Cb don't continue error");
  10602. return WOLFSSL_FATAL_ERROR;
  10603. }
  10604. }
  10605. #endif /* NO_HANDSHAKE_DONE_CB */
  10606. if (!ssl->options.dtls) {
  10607. if (!ssl->options.keepResources) {
  10608. FreeHandshakeResources(ssl);
  10609. }
  10610. }
  10611. #ifdef WOLFSSL_DTLS
  10612. else {
  10613. ssl->options.dtlsHsRetain = 1;
  10614. }
  10615. #endif /* WOLFSSL_DTLS */
  10616. #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION)
  10617. /* This may be necessary in async so that we don't try to
  10618. * renegotiate again */
  10619. if (ssl->secure_renegotiation && ssl->secure_renegotiation->startScr) {
  10620. ssl->secure_renegotiation->startScr = 0;
  10621. }
  10622. #endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */
  10623. #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
  10624. /* Free the remaining async context if not using it for crypto */
  10625. FreeAsyncCtx(ssl, 1);
  10626. #endif
  10627. ssl->error = 0; /* clear the error */
  10628. WOLFSSL_LEAVE("SSL_connect()", WOLFSSL_SUCCESS);
  10629. return WOLFSSL_SUCCESS;
  10630. #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS */
  10631. default:
  10632. WOLFSSL_MSG("Unknown connect state ERROR");
  10633. return WOLFSSL_FATAL_ERROR; /* unknown connect state */
  10634. }
  10635. #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS || !WOLFSSL_TLS13 */
  10636. }
  10637. #endif /* NO_WOLFSSL_CLIENT */
  10638. /* server only parts */
  10639. #ifndef NO_WOLFSSL_SERVER
  10640. #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS)
  10641. WOLFSSL_METHOD* wolfSSLv2_server_method(void)
  10642. {
  10643. WOLFSSL_STUB("wolfSSLv2_server_method");
  10644. return 0;
  10645. }
  10646. #endif
  10647. #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
  10648. WOLFSSL_METHOD* wolfSSLv3_server_method(void)
  10649. {
  10650. return wolfSSLv3_server_method_ex(NULL);
  10651. }
  10652. WOLFSSL_METHOD* wolfSSLv3_server_method_ex(void* heap)
  10653. {
  10654. WOLFSSL_METHOD* method =
  10655. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  10656. heap, DYNAMIC_TYPE_METHOD);
  10657. (void)heap;
  10658. WOLFSSL_ENTER("SSLv3_server_method_ex");
  10659. if (method) {
  10660. InitSSL_Method(method, MakeSSLv3());
  10661. method->side = WOLFSSL_SERVER_END;
  10662. }
  10663. return method;
  10664. }
  10665. #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
  10666. WOLFSSL_METHOD* wolfSSLv23_server_method(void)
  10667. {
  10668. return wolfSSLv23_server_method_ex(NULL);
  10669. }
  10670. WOLFSSL_METHOD* wolfSSLv23_server_method_ex(void* heap)
  10671. {
  10672. WOLFSSL_METHOD* method =
  10673. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  10674. heap, DYNAMIC_TYPE_METHOD);
  10675. (void)heap;
  10676. WOLFSSL_ENTER("SSLv23_server_method_ex");
  10677. if (method) {
  10678. #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512)
  10679. #ifdef WOLFSSL_TLS13
  10680. InitSSL_Method(method, MakeTLSv1_3());
  10681. #elif !defined(WOLFSSL_NO_TLS12)
  10682. InitSSL_Method(method, MakeTLSv1_2());
  10683. #elif !defined(NO_OLD_TLS)
  10684. InitSSL_Method(method, MakeTLSv1_1());
  10685. #endif
  10686. #else
  10687. #ifndef NO_OLD_TLS
  10688. InitSSL_Method(method, MakeTLSv1_1());
  10689. #else
  10690. #error Must have SHA256, SHA384 or SHA512 enabled for TLS 1.2
  10691. #endif
  10692. #endif
  10693. #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13)
  10694. method->downgrade = 1;
  10695. #endif
  10696. method->side = WOLFSSL_SERVER_END;
  10697. }
  10698. return method;
  10699. }
  10700. WOLFSSL_ABI
  10701. int wolfSSL_accept(WOLFSSL* ssl)
  10702. {
  10703. #if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && defined(WOLFSSL_TLS13))
  10704. word16 havePSK = 0;
  10705. word16 haveAnon = 0;
  10706. word16 haveMcast = 0;
  10707. #endif
  10708. int ret = 0;
  10709. (void)ret;
  10710. if (ssl == NULL)
  10711. return WOLFSSL_FATAL_ERROR;
  10712. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
  10713. if (ssl->options.side == WOLFSSL_NEITHER_END) {
  10714. WOLFSSL_MSG("Setting WOLFSSL_SSL to be server side");
  10715. ssl->error = InitSSL_Side(ssl, WOLFSSL_SERVER_END);
  10716. if (ssl->error != WOLFSSL_SUCCESS) {
  10717. WOLFSSL_ERROR(ssl->error);
  10718. return WOLFSSL_FATAL_ERROR;
  10719. }
  10720. ssl->error = 0; /* expected to be zero here */
  10721. }
  10722. #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
  10723. #if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && defined(WOLFSSL_TLS13)
  10724. return wolfSSL_accept_TLSv13(ssl);
  10725. #else
  10726. #ifdef WOLFSSL_TLS13
  10727. if (ssl->options.tls1_3)
  10728. return wolfSSL_accept_TLSv13(ssl);
  10729. #endif
  10730. WOLFSSL_ENTER("SSL_accept()");
  10731. /* make sure this wolfSSL object has arrays and rng setup. Protects
  10732. * case where the WOLFSSL object is re-used via wolfSSL_clear() */
  10733. if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
  10734. return ret;
  10735. }
  10736. #ifdef WOLFSSL_WOLFSENTRY_HOOKS
  10737. if ((ssl->AcceptFilter != NULL) &&
  10738. ((ssl->options.acceptState == ACCEPT_BEGIN)
  10739. #ifdef HAVE_SECURE_RENEGOTIATION
  10740. || (ssl->options.acceptState == ACCEPT_BEGIN_RENEG)
  10741. #endif
  10742. ))
  10743. {
  10744. wolfSSL_netfilter_decision_t res;
  10745. if ((ssl->AcceptFilter(ssl, ssl->AcceptFilter_arg, &res) ==
  10746. WOLFSSL_SUCCESS) &&
  10747. (res == WOLFSSL_NETFILTER_REJECT)) {
  10748. ssl->error = SOCKET_FILTERED_E;
  10749. WOLFSSL_ERROR(ssl->error);
  10750. return WOLFSSL_FATAL_ERROR;
  10751. }
  10752. }
  10753. #endif /* WOLFSSL_WOLFSENTRY_HOOKS */
  10754. #ifdef HAVE_ERRNO_H
  10755. errno = 0;
  10756. #endif
  10757. #ifndef NO_PSK
  10758. havePSK = ssl->options.havePSK;
  10759. #endif
  10760. (void)havePSK;
  10761. #ifdef HAVE_ANON
  10762. haveAnon = ssl->options.haveAnon;
  10763. #endif
  10764. (void)haveAnon;
  10765. #ifdef WOLFSSL_MULTICAST
  10766. haveMcast = ssl->options.haveMcast;
  10767. #endif
  10768. (void)haveMcast;
  10769. if (ssl->options.side != WOLFSSL_SERVER_END) {
  10770. ssl->error = SIDE_ERROR;
  10771. WOLFSSL_ERROR(ssl->error);
  10772. return WOLFSSL_FATAL_ERROR;
  10773. }
  10774. #ifndef NO_CERTS
  10775. /* in case used set_accept_state after init */
  10776. if (!havePSK && !haveAnon && !haveMcast) {
  10777. #ifdef OPENSSL_EXTRA
  10778. if (ssl->ctx->certSetupCb != NULL) {
  10779. WOLFSSL_MSG("CertSetupCb set. server cert and "
  10780. "key not checked");
  10781. }
  10782. else
  10783. #endif
  10784. {
  10785. if (!ssl->buffers.certificate ||
  10786. !ssl->buffers.certificate->buffer) {
  10787. WOLFSSL_MSG("accept error: server cert required");
  10788. ssl->error = NO_PRIVATE_KEY;
  10789. WOLFSSL_ERROR(ssl->error);
  10790. return WOLFSSL_FATAL_ERROR;
  10791. }
  10792. if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
  10793. /* allow no private key if using existing key */
  10794. #ifdef WOLF_PRIVATE_KEY_ID
  10795. if (ssl->devId != INVALID_DEVID
  10796. #ifdef HAVE_PK_CALLBACKS
  10797. || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
  10798. #endif
  10799. ) {
  10800. WOLFSSL_MSG("Allowing no server private key "
  10801. "(external)");
  10802. }
  10803. else
  10804. #endif
  10805. {
  10806. WOLFSSL_MSG("accept error: server key required");
  10807. ssl->error = NO_PRIVATE_KEY;
  10808. WOLFSSL_ERROR(ssl->error);
  10809. return WOLFSSL_FATAL_ERROR;
  10810. }
  10811. }
  10812. }
  10813. }
  10814. #endif
  10815. #ifdef WOLFSSL_DTLS
  10816. if (ssl->version.major == DTLS_MAJOR) {
  10817. ssl->options.dtls = 1;
  10818. ssl->options.tls = 1;
  10819. ssl->options.tls1_1 = 1;
  10820. }
  10821. #endif
  10822. if (ssl->buffers.outputBuffer.length > 0
  10823. #ifdef WOLFSSL_ASYNC_CRYPT
  10824. /* do not send buffered or advance state if last error was an
  10825. async pending operation */
  10826. && ssl->error != WC_PENDING_E
  10827. #endif
  10828. ) {
  10829. ret = SendBuffered(ssl);
  10830. if (ret == 0) {
  10831. /* fragOffset is non-zero when sending fragments. On the last
  10832. * fragment, fragOffset is zero again, and the state can be
  10833. * advanced. */
  10834. if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
  10835. if (ssl->options.acceptState == ACCEPT_FIRST_REPLY_DONE ||
  10836. ssl->options.acceptState == SERVER_HELLO_SENT ||
  10837. ssl->options.acceptState == CERT_SENT ||
  10838. ssl->options.acceptState == CERT_STATUS_SENT ||
  10839. ssl->options.acceptState == KEY_EXCHANGE_SENT ||
  10840. ssl->options.acceptState == CERT_REQ_SENT ||
  10841. ssl->options.acceptState == ACCEPT_SECOND_REPLY_DONE ||
  10842. ssl->options.acceptState == TICKET_SENT ||
  10843. ssl->options.acceptState == CHANGE_CIPHER_SENT) {
  10844. ssl->options.acceptState++;
  10845. WOLFSSL_MSG("accept state: "
  10846. "Advanced from last buffered fragment send");
  10847. #ifdef WOLFSSL_ASYNC_IO
  10848. /* Cleanup async */
  10849. FreeAsyncCtx(ssl, 0);
  10850. #endif
  10851. }
  10852. }
  10853. else {
  10854. WOLFSSL_MSG("accept state: "
  10855. "Not advanced, more fragments to send");
  10856. }
  10857. }
  10858. else {
  10859. ssl->error = ret;
  10860. WOLFSSL_ERROR(ssl->error);
  10861. return WOLFSSL_FATAL_ERROR;
  10862. }
  10863. }
  10864. ret = RetrySendAlert(ssl);
  10865. if (ret != 0) {
  10866. ssl->error = ret;
  10867. WOLFSSL_ERROR(ssl->error);
  10868. return WOLFSSL_FATAL_ERROR;
  10869. }
  10870. switch (ssl->options.acceptState) {
  10871. case ACCEPT_BEGIN :
  10872. #ifdef HAVE_SECURE_RENEGOTIATION
  10873. case ACCEPT_BEGIN_RENEG:
  10874. #endif
  10875. /* get response */
  10876. while (ssl->options.clientState < CLIENT_HELLO_COMPLETE)
  10877. if ( (ssl->error = ProcessReply(ssl)) < 0) {
  10878. WOLFSSL_ERROR(ssl->error);
  10879. return WOLFSSL_FATAL_ERROR;
  10880. }
  10881. #ifdef WOLFSSL_TLS13
  10882. ssl->options.acceptState = ACCEPT_CLIENT_HELLO_DONE;
  10883. WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
  10884. FALL_THROUGH;
  10885. case ACCEPT_CLIENT_HELLO_DONE :
  10886. if (ssl->options.tls1_3) {
  10887. return wolfSSL_accept_TLSv13(ssl);
  10888. }
  10889. #endif
  10890. #ifdef WOLFSSL_DTLS
  10891. if (ssl->chGoodCb != NULL && !IsSCR(ssl)) {
  10892. int cbret = ssl->chGoodCb(ssl, ssl->chGoodCtx);
  10893. if (cbret < 0) {
  10894. ssl->error = cbret;
  10895. WOLFSSL_MSG("ClientHello Good Cb don't continue error");
  10896. return WOLFSSL_FATAL_ERROR;
  10897. }
  10898. }
  10899. #endif
  10900. ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
  10901. WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
  10902. FALL_THROUGH;
  10903. case ACCEPT_FIRST_REPLY_DONE :
  10904. if ( (ssl->error = SendServerHello(ssl)) != 0) {
  10905. WOLFSSL_ERROR(ssl->error);
  10906. return WOLFSSL_FATAL_ERROR;
  10907. }
  10908. ssl->options.acceptState = SERVER_HELLO_SENT;
  10909. WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
  10910. FALL_THROUGH;
  10911. case SERVER_HELLO_SENT :
  10912. #ifdef WOLFSSL_TLS13
  10913. if (ssl->options.tls1_3) {
  10914. return wolfSSL_accept_TLSv13(ssl);
  10915. }
  10916. #endif
  10917. #ifndef NO_CERTS
  10918. if (!ssl->options.resuming)
  10919. if ( (ssl->error = SendCertificate(ssl)) != 0) {
  10920. WOLFSSL_ERROR(ssl->error);
  10921. return WOLFSSL_FATAL_ERROR;
  10922. }
  10923. #endif
  10924. ssl->options.acceptState = CERT_SENT;
  10925. WOLFSSL_MSG("accept state CERT_SENT");
  10926. FALL_THROUGH;
  10927. case CERT_SENT :
  10928. #ifndef NO_CERTS
  10929. if (!ssl->options.resuming)
  10930. if ( (ssl->error = SendCertificateStatus(ssl)) != 0) {
  10931. WOLFSSL_ERROR(ssl->error);
  10932. return WOLFSSL_FATAL_ERROR;
  10933. }
  10934. #endif
  10935. ssl->options.acceptState = CERT_STATUS_SENT;
  10936. WOLFSSL_MSG("accept state CERT_STATUS_SENT");
  10937. FALL_THROUGH;
  10938. case CERT_STATUS_SENT :
  10939. #ifdef WOLFSSL_TLS13
  10940. if (ssl->options.tls1_3) {
  10941. return wolfSSL_accept_TLSv13(ssl);
  10942. }
  10943. #endif
  10944. if (!ssl->options.resuming)
  10945. if ( (ssl->error = SendServerKeyExchange(ssl)) != 0) {
  10946. WOLFSSL_ERROR(ssl->error);
  10947. return WOLFSSL_FATAL_ERROR;
  10948. }
  10949. ssl->options.acceptState = KEY_EXCHANGE_SENT;
  10950. WOLFSSL_MSG("accept state KEY_EXCHANGE_SENT");
  10951. FALL_THROUGH;
  10952. case KEY_EXCHANGE_SENT :
  10953. #ifndef NO_CERTS
  10954. if (!ssl->options.resuming) {
  10955. if (ssl->options.verifyPeer) {
  10956. if ( (ssl->error = SendCertificateRequest(ssl)) != 0) {
  10957. WOLFSSL_ERROR(ssl->error);
  10958. return WOLFSSL_FATAL_ERROR;
  10959. }
  10960. }
  10961. else {
  10962. /* SERVER: Peer auth good if not verifying client. */
  10963. ssl->options.peerAuthGood = 1;
  10964. }
  10965. }
  10966. #endif
  10967. ssl->options.acceptState = CERT_REQ_SENT;
  10968. WOLFSSL_MSG("accept state CERT_REQ_SENT");
  10969. FALL_THROUGH;
  10970. case CERT_REQ_SENT :
  10971. if (!ssl->options.resuming)
  10972. if ( (ssl->error = SendServerHelloDone(ssl)) != 0) {
  10973. WOLFSSL_ERROR(ssl->error);
  10974. return WOLFSSL_FATAL_ERROR;
  10975. }
  10976. ssl->options.acceptState = SERVER_HELLO_DONE;
  10977. WOLFSSL_MSG("accept state SERVER_HELLO_DONE");
  10978. FALL_THROUGH;
  10979. case SERVER_HELLO_DONE :
  10980. if (!ssl->options.resuming) {
  10981. while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE)
  10982. if ( (ssl->error = ProcessReply(ssl)) < 0) {
  10983. WOLFSSL_ERROR(ssl->error);
  10984. return WOLFSSL_FATAL_ERROR;
  10985. }
  10986. }
  10987. ssl->options.acceptState = ACCEPT_SECOND_REPLY_DONE;
  10988. WOLFSSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE");
  10989. FALL_THROUGH;
  10990. case ACCEPT_SECOND_REPLY_DONE :
  10991. #ifndef NO_CERTS
  10992. /* SERVER: When not resuming and verifying peer but no certificate
  10993. * received and not failing when not received then peer auth good.
  10994. */
  10995. if (!ssl->options.resuming && ssl->options.verifyPeer &&
  10996. !ssl->options.havePeerCert && !ssl->options.failNoCert) {
  10997. ssl->options.peerAuthGood = 1;
  10998. }
  10999. #endif /* !NO_CERTS */
  11000. #ifdef WOLFSSL_NO_CLIENT_AUTH
  11001. if (!ssl->options.resuming) {
  11002. ssl->options.peerAuthGood = 1;
  11003. }
  11004. #endif
  11005. #ifdef HAVE_SESSION_TICKET
  11006. if (ssl->options.createTicket && !ssl->options.noTicketTls12) {
  11007. if ( (ssl->error = SendTicket(ssl)) != 0) {
  11008. WOLFSSL_ERROR(ssl->error);
  11009. return WOLFSSL_FATAL_ERROR;
  11010. }
  11011. }
  11012. #endif /* HAVE_SESSION_TICKET */
  11013. ssl->options.acceptState = TICKET_SENT;
  11014. WOLFSSL_MSG("accept state TICKET_SENT");
  11015. FALL_THROUGH;
  11016. case TICKET_SENT:
  11017. /* SERVER: Fail-safe for CLient Authentication. */
  11018. if (!ssl->options.peerAuthGood) {
  11019. WOLFSSL_MSG("Client authentication did not happen");
  11020. return WOLFSSL_FATAL_ERROR;
  11021. }
  11022. if ( (ssl->error = SendChangeCipher(ssl)) != 0) {
  11023. WOLFSSL_ERROR(ssl->error);
  11024. return WOLFSSL_FATAL_ERROR;
  11025. }
  11026. ssl->options.acceptState = CHANGE_CIPHER_SENT;
  11027. WOLFSSL_MSG("accept state CHANGE_CIPHER_SENT");
  11028. FALL_THROUGH;
  11029. case CHANGE_CIPHER_SENT :
  11030. if ( (ssl->error = SendFinished(ssl)) != 0) {
  11031. WOLFSSL_ERROR(ssl->error);
  11032. return WOLFSSL_FATAL_ERROR;
  11033. }
  11034. ssl->options.acceptState = ACCEPT_FINISHED_DONE;
  11035. WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
  11036. FALL_THROUGH;
  11037. case ACCEPT_FINISHED_DONE :
  11038. if (ssl->options.resuming) {
  11039. while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
  11040. if ( (ssl->error = ProcessReply(ssl)) < 0) {
  11041. WOLFSSL_ERROR(ssl->error);
  11042. return WOLFSSL_FATAL_ERROR;
  11043. }
  11044. }
  11045. }
  11046. ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE;
  11047. WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
  11048. FALL_THROUGH;
  11049. case ACCEPT_THIRD_REPLY_DONE :
  11050. #ifndef NO_HANDSHAKE_DONE_CB
  11051. if (ssl->hsDoneCb) {
  11052. int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
  11053. if (cbret < 0) {
  11054. ssl->error = cbret;
  11055. WOLFSSL_MSG("HandShake Done Cb don't continue error");
  11056. return WOLFSSL_FATAL_ERROR;
  11057. }
  11058. }
  11059. #endif /* NO_HANDSHAKE_DONE_CB */
  11060. if (!ssl->options.dtls) {
  11061. if (!ssl->options.keepResources) {
  11062. FreeHandshakeResources(ssl);
  11063. }
  11064. }
  11065. #ifdef WOLFSSL_DTLS
  11066. else {
  11067. ssl->options.dtlsHsRetain = 1;
  11068. }
  11069. #endif /* WOLFSSL_DTLS */
  11070. #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION)
  11071. /* This may be necessary in async so that we don't try to
  11072. * renegotiate again */
  11073. if (ssl->secure_renegotiation && ssl->secure_renegotiation->startScr) {
  11074. ssl->secure_renegotiation->startScr = 0;
  11075. }
  11076. #endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */
  11077. #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
  11078. /* Free the remaining async context if not using it for crypto */
  11079. FreeAsyncCtx(ssl, 1);
  11080. #endif
  11081. #if defined(WOLFSSL_SESSION_EXPORT) && defined(WOLFSSL_DTLS)
  11082. if (ssl->dtls_export) {
  11083. if ((ssl->error = wolfSSL_send_session(ssl)) != 0) {
  11084. WOLFSSL_MSG("Export DTLS session error");
  11085. WOLFSSL_ERROR(ssl->error);
  11086. return WOLFSSL_FATAL_ERROR;
  11087. }
  11088. }
  11089. #endif
  11090. ssl->error = 0; /* clear the error */
  11091. WOLFSSL_LEAVE("SSL_accept()", WOLFSSL_SUCCESS);
  11092. return WOLFSSL_SUCCESS;
  11093. default :
  11094. WOLFSSL_MSG("Unknown accept state ERROR");
  11095. return WOLFSSL_FATAL_ERROR;
  11096. }
  11097. #endif /* !WOLFSSL_NO_TLS12 */
  11098. }
  11099. #endif /* NO_WOLFSSL_SERVER */
  11100. #if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
  11101. int wolfDTLS_SetChGoodCb(WOLFSSL* ssl, ClientHelloGoodCb cb, void* user_ctx)
  11102. {
  11103. WOLFSSL_ENTER("wolfDTLS_SetChGoodCb");
  11104. if (ssl == NULL)
  11105. return BAD_FUNC_ARG;
  11106. ssl->chGoodCb = cb;
  11107. ssl->chGoodCtx = user_ctx;
  11108. return WOLFSSL_SUCCESS;
  11109. }
  11110. #endif
  11111. #ifndef NO_HANDSHAKE_DONE_CB
  11112. int wolfSSL_SetHsDoneCb(WOLFSSL* ssl, HandShakeDoneCb cb, void* user_ctx)
  11113. {
  11114. WOLFSSL_ENTER("wolfSSL_SetHsDoneCb");
  11115. if (ssl == NULL)
  11116. return BAD_FUNC_ARG;
  11117. ssl->hsDoneCb = cb;
  11118. ssl->hsDoneCtx = user_ctx;
  11119. return WOLFSSL_SUCCESS;
  11120. }
  11121. #endif /* NO_HANDSHAKE_DONE_CB */
  11122. WOLFSSL_ABI
  11123. int wolfSSL_Cleanup(void)
  11124. {
  11125. int ret = WOLFSSL_SUCCESS; /* Only the first error will be returned */
  11126. int release = 0;
  11127. #if !defined(NO_SESSION_CACHE) && defined(ENABLE_SESSION_CACHE_ROW_LOCK)
  11128. int i;
  11129. #endif
  11130. WOLFSSL_ENTER("wolfSSL_Cleanup");
  11131. if (initRefCount == 0)
  11132. return ret; /* possibly no init yet, but not failure either way */
  11133. if ((count_mutex_valid == 1) && (wc_LockMutex(&count_mutex) != 0)) {
  11134. WOLFSSL_MSG("Bad Lock Mutex count");
  11135. ret = BAD_MUTEX_E;
  11136. }
  11137. release = initRefCount-- == 1;
  11138. if (initRefCount < 0)
  11139. initRefCount = 0;
  11140. if (count_mutex_valid == 1) {
  11141. wc_UnLockMutex(&count_mutex);
  11142. }
  11143. if (!release)
  11144. return ret;
  11145. #ifdef OPENSSL_EXTRA
  11146. if (bn_one) {
  11147. wolfSSL_BN_free(bn_one);
  11148. bn_one = NULL;
  11149. }
  11150. #endif
  11151. #ifndef NO_SESSION_CACHE
  11152. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  11153. for (i = 0; i < SESSION_ROWS; ++i) {
  11154. if ((SessionCache[i].mutex_valid == 1) &&
  11155. (wc_FreeMutex(&SessionCache[i].row_mutex) != 0)) {
  11156. if (ret == WOLFSSL_SUCCESS)
  11157. ret = BAD_MUTEX_E;
  11158. }
  11159. SessionCache[i].mutex_valid = 0;
  11160. }
  11161. #else
  11162. if ((session_mutex_valid == 1) && (wc_FreeMutex(&session_mutex) != 0)) {
  11163. if (ret == WOLFSSL_SUCCESS)
  11164. ret = BAD_MUTEX_E;
  11165. }
  11166. session_mutex_valid = 0;
  11167. #endif
  11168. #ifndef NO_CLIENT_CACHE
  11169. if ((clisession_mutex_valid == 1) &&
  11170. (wc_FreeMutex(&clisession_mutex) != 0)) {
  11171. if (ret == WOLFSSL_SUCCESS)
  11172. ret = BAD_MUTEX_E;
  11173. }
  11174. clisession_mutex_valid = 0;
  11175. #endif
  11176. #endif /* !NO_SESSION_CACHE */
  11177. if ((count_mutex_valid == 1) && (wc_FreeMutex(&count_mutex) != 0)) {
  11178. if (ret == WOLFSSL_SUCCESS)
  11179. ret = BAD_MUTEX_E;
  11180. }
  11181. count_mutex_valid = 0;
  11182. #ifdef OPENSSL_EXTRA
  11183. wolfSSL_RAND_Cleanup();
  11184. #endif
  11185. if (wolfCrypt_Cleanup() != 0) {
  11186. WOLFSSL_MSG("Error with wolfCrypt_Cleanup call");
  11187. if (ret == WOLFSSL_SUCCESS)
  11188. ret = WC_CLEANUP_E;
  11189. }
  11190. #if FIPS_VERSION_GE(5,1)
  11191. if (wolfCrypt_SetPrivateKeyReadEnable_fips(0, WC_KEYTYPE_ALL) < 0) {
  11192. if (ret == WOLFSSL_SUCCESS)
  11193. ret = WC_CLEANUP_E;
  11194. }
  11195. #endif
  11196. #ifdef HAVE_GLOBAL_RNG
  11197. if ((globalRNGMutex_valid == 1) && (wc_FreeMutex(&globalRNGMutex) != 0)) {
  11198. if (ret == WOLFSSL_SUCCESS)
  11199. ret = BAD_MUTEX_E;
  11200. }
  11201. globalRNGMutex_valid = 0;
  11202. #if defined(OPENSSL_EXTRA) && defined(HAVE_HASHDRBG)
  11203. wolfSSL_FIPS_drbg_free(gDrbgDefCtx);
  11204. gDrbgDefCtx = NULL;
  11205. #endif
  11206. #endif
  11207. return ret;
  11208. }
  11209. #ifndef NO_SESSION_CACHE
  11210. WOLFSSL_ABI
  11211. void wolfSSL_flush_sessions(WOLFSSL_CTX* ctx, long tm)
  11212. {
  11213. /* static table now, no flushing needed */
  11214. (void)ctx;
  11215. (void)tm;
  11216. }
  11217. /* set ssl session timeout in seconds */
  11218. WOLFSSL_ABI
  11219. int wolfSSL_set_timeout(WOLFSSL* ssl, unsigned int to)
  11220. {
  11221. if (ssl == NULL)
  11222. return BAD_FUNC_ARG;
  11223. if (to == 0)
  11224. to = WOLFSSL_SESSION_TIMEOUT;
  11225. ssl->timeout = to;
  11226. return WOLFSSL_SUCCESS;
  11227. }
  11228. /**
  11229. * Sets ctx session timeout in seconds.
  11230. * The timeout value set here should be reflected in the
  11231. * "session ticket lifetime hint" if this API works in the openssl compat-layer.
  11232. * Therefore wolfSSL_CTX_set_TicketHint is called internally.
  11233. * Arguments:
  11234. * - ctx WOLFSSL_CTX object which the timeout is set to
  11235. * - to timeout value in second
  11236. * Returns:
  11237. * WOLFSSL_SUCCESS on success, BAD_FUNC_ARG on failure.
  11238. * When WOLFSSL_ERROR_CODE_OPENSSL is defined, returns previous timeout value
  11239. * on success, BAD_FUNC_ARG on failure.
  11240. */
  11241. WOLFSSL_ABI
  11242. int wolfSSL_CTX_set_timeout(WOLFSSL_CTX* ctx, unsigned int to)
  11243. {
  11244. #if defined(WOLFSSL_ERROR_CODE_OPENSSL)
  11245. word32 prev_timeout = 0;
  11246. #endif
  11247. int ret = WOLFSSL_SUCCESS;
  11248. (void)ret;
  11249. if (ctx == NULL)
  11250. ret = BAD_FUNC_ARG;
  11251. if (ret == WOLFSSL_SUCCESS) {
  11252. #if defined(WOLFSSL_ERROR_CODE_OPENSSL)
  11253. prev_timeout = ctx->timeout;
  11254. #endif
  11255. if (to == 0) {
  11256. ctx->timeout = WOLFSSL_SESSION_TIMEOUT;
  11257. }
  11258. else {
  11259. ctx->timeout = to;
  11260. }
  11261. }
  11262. #if defined(OPENSSL_EXTRA) && defined(HAVE_SESSION_TICKET) && \
  11263. !defined(NO_WOLFSSL_SERVER)
  11264. if (ret == WOLFSSL_SUCCESS) {
  11265. if (to == 0) {
  11266. ret = wolfSSL_CTX_set_TicketHint(ctx, SESSION_TICKET_HINT_DEFAULT);
  11267. }
  11268. else {
  11269. ret = wolfSSL_CTX_set_TicketHint(ctx, to);
  11270. }
  11271. }
  11272. #endif /* OPENSSL_EXTRA && HAVE_SESSION_TICKET && !NO_WOLFSSL_SERVER */
  11273. #if defined(WOLFSSL_ERROR_CODE_OPENSSL)
  11274. if (ret == WOLFSSL_SUCCESS) {
  11275. return prev_timeout;
  11276. }
  11277. else {
  11278. return ret;
  11279. }
  11280. #else
  11281. return ret;
  11282. #endif /* WOLFSSL_ERROR_CODE_OPENSSL */
  11283. }
  11284. #ifndef NO_CLIENT_CACHE
  11285. /* Get Session from Client cache based on id/len, return NULL on failure */
  11286. WOLFSSL_SESSION* wolfSSL_GetSessionClient(WOLFSSL* ssl, const byte* id, int len)
  11287. {
  11288. WOLFSSL_SESSION* ret = NULL;
  11289. word32 row;
  11290. int idx;
  11291. int count;
  11292. int error = 0;
  11293. ClientSession* clSess;
  11294. WOLFSSL_ENTER("GetSessionClient");
  11295. if (ssl->ctx->sessionCacheOff) {
  11296. WOLFSSL_MSG("Session Cache off");
  11297. return NULL;
  11298. }
  11299. if (ssl->options.side == WOLFSSL_SERVER_END)
  11300. return NULL;
  11301. len = min(SERVER_ID_LEN, (word32)len);
  11302. #ifdef HAVE_EXT_CACHE
  11303. if (ssl->ctx->get_sess_cb != NULL) {
  11304. int copy = 0;
  11305. WOLFSSL_MSG("Calling external session cache");
  11306. ret = ssl->ctx->get_sess_cb(ssl, (byte*)id, len, &copy);
  11307. if (ret != NULL) {
  11308. WOLFSSL_MSG("Session found in external cache");
  11309. return ret;
  11310. }
  11311. WOLFSSL_MSG("Session not found in external cache");
  11312. }
  11313. if (ssl->ctx->internalCacheLookupOff) {
  11314. WOLFSSL_MSG("Internal cache turned off");
  11315. return NULL;
  11316. }
  11317. #endif
  11318. row = HashObject(id, len, &error) % CLIENT_SESSION_ROWS;
  11319. if (error != 0) {
  11320. WOLFSSL_MSG("Hash session failed");
  11321. return NULL;
  11322. }
  11323. if (wc_LockMutex(&clisession_mutex) != 0) {
  11324. WOLFSSL_MSG("Client cache mutex lock failed");
  11325. return NULL;
  11326. }
  11327. /* start from most recently used */
  11328. count = min((word32)ClientCache[row].totalCount, CLIENT_SESSIONS_PER_ROW);
  11329. idx = ClientCache[row].nextIdx - 1;
  11330. if (idx < 0 || idx >= CLIENT_SESSIONS_PER_ROW) {
  11331. idx = CLIENT_SESSIONS_PER_ROW - 1; /* if back to front, the previous was end */
  11332. }
  11333. clSess = ClientCache[row].Clients;
  11334. for (; count > 0; --count) {
  11335. WOLFSSL_SESSION* current;
  11336. SessionRow* sessRow;
  11337. if (clSess[idx].serverRow >= SESSION_ROWS) {
  11338. WOLFSSL_MSG("Client cache serverRow invalid");
  11339. break;
  11340. }
  11341. /* lock row */
  11342. sessRow = &SessionCache[clSess[idx].serverRow];
  11343. if (SESSION_ROW_LOCK(sessRow) != 0) {
  11344. WOLFSSL_MSG("Session cache row lock failure");
  11345. break;
  11346. }
  11347. current = &sessRow->Sessions[clSess[idx].serverIdx];
  11348. if (XMEMCMP(current->serverID, id, len) == 0) {
  11349. WOLFSSL_MSG("Found a serverid match for client");
  11350. if (LowResTimer() < (current->bornOn + current->timeout)) {
  11351. WOLFSSL_MSG("Session valid");
  11352. ret = current;
  11353. SESSION_ROW_UNLOCK(sessRow);
  11354. break;
  11355. } else {
  11356. WOLFSSL_MSG("Session timed out"); /* could have more for id */
  11357. }
  11358. } else {
  11359. WOLFSSL_MSG("ServerID not a match from client table");
  11360. }
  11361. SESSION_ROW_UNLOCK(sessRow);
  11362. idx = idx > 0 ? idx - 1 : CLIENT_SESSIONS_PER_ROW - 1;
  11363. }
  11364. wc_UnLockMutex(&clisession_mutex);
  11365. return ret;
  11366. }
  11367. #endif /* !NO_CLIENT_CACHE */
  11368. static int SslSessionCacheOff(const WOLFSSL* ssl, const WOLFSSL_SESSION* session)
  11369. {
  11370. (void)session;
  11371. return ssl->options.sessionCacheOff
  11372. #if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_FORCE_CACHE_ON_TICKET)
  11373. && session->ticketLen == 0
  11374. #endif
  11375. #ifdef OPENSSL_EXTRA
  11376. && ssl->options.side != WOLFSSL_CLIENT_END
  11377. #endif
  11378. ;
  11379. }
  11380. int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output)
  11381. {
  11382. WOLFSSL_SESSION* sess = NULL;
  11383. const byte* id = NULL;
  11384. word32 row;
  11385. int idx;
  11386. int count;
  11387. int error = 0;
  11388. SessionRow* sessRow;
  11389. #ifdef HAVE_SESSION_TICKET
  11390. #ifndef WOLFSSL_SMALL_STACK
  11391. byte tmpTicket[PREALLOC_SESSION_TICKET_LEN];
  11392. #else
  11393. byte* tmpTicket = NULL;
  11394. #endif
  11395. byte tmpBufSet = 0;
  11396. #endif
  11397. #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
  11398. WOLFSSL_X509* peer = NULL;
  11399. #endif
  11400. byte bogusID[ID_LEN];
  11401. byte bogusIDSz = 0;
  11402. WOLFSSL_ENTER("wolfSSL_GetSessionFromCache");
  11403. if (output == NULL) {
  11404. WOLFSSL_MSG("NULL output");
  11405. return WOLFSSL_FAILURE;
  11406. }
  11407. if (SslSessionCacheOff(ssl, ssl->session))
  11408. return WOLFSSL_FAILURE;
  11409. if (ssl->options.haveSessionId == 0)
  11410. return WOLFSSL_FAILURE;
  11411. #ifdef HAVE_SESSION_TICKET
  11412. if (ssl->options.side == WOLFSSL_SERVER_END && ssl->options.useTicket == 1)
  11413. return WOLFSSL_FAILURE;
  11414. #endif
  11415. XMEMSET(bogusID, 0, sizeof(bogusID));
  11416. if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL)
  11417. id = ssl->arrays->sessionID;
  11418. else if (ssl->session->haveAltSessionID) {
  11419. id = ssl->session->altSessionID;
  11420. /* We want to restore the bogus ID for TLS compatibility */
  11421. if (output == ssl->session) {
  11422. XMEMCPY(bogusID, ssl->session->sessionID, ID_LEN);
  11423. bogusIDSz = ssl->session->sessionIDSz;
  11424. }
  11425. }
  11426. else
  11427. id = ssl->session->sessionID;
  11428. #ifdef HAVE_EXT_CACHE
  11429. if (ssl->ctx->get_sess_cb != NULL) {
  11430. int copy = 0;
  11431. /* Attempt to retrieve the session from the external cache. */
  11432. WOLFSSL_MSG("Calling external session cache");
  11433. sess = ssl->ctx->get_sess_cb(ssl, (byte*)id, ID_LEN, &copy);
  11434. if (sess != NULL) {
  11435. WOLFSSL_MSG("Session found in external cache");
  11436. error = wolfSSL_DupSession(sess, output, 0);
  11437. #ifdef HAVE_EX_DATA
  11438. output->ownExData = 0; /* Session cache owns external data */
  11439. #endif
  11440. /* If copy not set then free immediately */
  11441. if (!copy)
  11442. wolfSSL_FreeSession(ssl->ctx, sess);
  11443. /* We want to restore the bogus ID for TLS compatibility */
  11444. if (ssl->session->haveAltSessionID &&
  11445. output == ssl->session) {
  11446. XMEMCPY(ssl->session->sessionID, bogusID, ID_LEN);
  11447. ssl->session->sessionIDSz = bogusIDSz;
  11448. }
  11449. return error;
  11450. }
  11451. WOLFSSL_MSG("Session not found in external cache");
  11452. }
  11453. if (ssl->ctx->internalCacheLookupOff) {
  11454. WOLFSSL_MSG("Internal cache lookup turned off");
  11455. return WOLFSSL_FAILURE;
  11456. }
  11457. #endif
  11458. row = HashObject(id, ID_LEN, &error) % SESSION_ROWS;
  11459. if (error != 0) {
  11460. WOLFSSL_MSG("Hash session failed");
  11461. return WOLFSSL_FAILURE;
  11462. }
  11463. #ifdef HAVE_SESSION_TICKET
  11464. if (output->ticket == NULL ||
  11465. output->ticketLenAlloc < PREALLOC_SESSION_TICKET_LEN) {
  11466. #ifdef WOLFSSL_SMALL_STACK
  11467. tmpTicket = (byte*)XMALLOC(PREALLOC_SESSION_TICKET_LEN, output->heap,
  11468. DYNAMIC_TYPE_TMP_BUFFER);
  11469. if (tmpTicket == NULL) {
  11470. WOLFSSL_MSG("tmpTicket malloc failed");
  11471. return WOLFSSL_FAILURE;
  11472. }
  11473. #endif
  11474. if (output->ticketLenAlloc)
  11475. XFREE(output->ticket, output->heap, DYNAMIC_TYPE_SESSION_TICK);
  11476. output->ticket = tmpTicket;
  11477. output->ticketLenAlloc = PREALLOC_SESSION_TICKET_LEN;
  11478. output->ticketLen = 0;
  11479. tmpBufSet = 1;
  11480. }
  11481. #endif
  11482. #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
  11483. if (output->peer != NULL) {
  11484. wolfSSL_X509_free(output->peer);
  11485. output->peer = NULL;
  11486. }
  11487. #endif
  11488. /* lock row */
  11489. sessRow = &SessionCache[row];
  11490. if (SESSION_ROW_LOCK(sessRow) != 0) {
  11491. WOLFSSL_MSG("Session cache row lock failure");
  11492. #ifdef HAVE_SESSION_TICKET
  11493. if (tmpBufSet) {
  11494. output->ticket = output->staticTicket;
  11495. output->ticketLenAlloc = 0;
  11496. }
  11497. #ifdef WOLFSSL_SMALL_STACK
  11498. if (tmpTicket != NULL)
  11499. XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11500. #endif
  11501. #endif
  11502. return WOLFSSL_FAILURE;
  11503. }
  11504. /* start from most recently used */
  11505. count = min((word32)sessRow->totalCount, SESSIONS_PER_ROW);
  11506. idx = sessRow->nextIdx - 1;
  11507. if (idx < 0 || idx >= SESSIONS_PER_ROW) {
  11508. idx = SESSIONS_PER_ROW - 1; /* if back to front, the previous was end */
  11509. }
  11510. for (; count > 0; --count) {
  11511. WOLFSSL_SESSION* current;
  11512. current = &sessRow->Sessions[idx];
  11513. if (XMEMCMP(current->sessionID, id, ID_LEN) == 0 &&
  11514. current->side == ssl->options.side) {
  11515. WOLFSSL_MSG("Found a session match");
  11516. if (LowResTimer() < (current->bornOn + current->timeout)) {
  11517. WOLFSSL_MSG("Session valid");
  11518. sess = current;
  11519. } else {
  11520. WOLFSSL_MSG("Session timed out");
  11521. }
  11522. break; /* no more sessionIDs whether valid or not that match */
  11523. } else {
  11524. WOLFSSL_MSG("SessionID not a match at this idx");
  11525. }
  11526. idx = idx > 0 ? idx - 1 : SESSIONS_PER_ROW - 1;
  11527. }
  11528. if (sess != NULL) {
  11529. #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
  11530. /* We don't want the peer member. We will free it at the end. */
  11531. if (sess->peer != NULL) {
  11532. peer = sess->peer;
  11533. sess->peer = NULL;
  11534. }
  11535. #endif
  11536. error = wolfSSL_DupSession(sess, output, 1);
  11537. #ifdef HAVE_EX_DATA
  11538. output->ownExData = 0; /* Session cache owns external data */
  11539. #endif
  11540. }
  11541. else {
  11542. error = WOLFSSL_FAILURE;
  11543. }
  11544. SESSION_ROW_UNLOCK(sessRow);
  11545. /* We want to restore the bogus ID for TLS compatibility */
  11546. if (ssl->session->haveAltSessionID &&
  11547. output == ssl->session) {
  11548. XMEMCPY(ssl->session->sessionID, bogusID, ID_LEN);
  11549. ssl->session->sessionIDSz = bogusIDSz;
  11550. }
  11551. #ifdef HAVE_SESSION_TICKET
  11552. if (tmpBufSet) {
  11553. if (error == WOLFSSL_SUCCESS) {
  11554. if (output->ticketLen > SESSION_TICKET_LEN) {
  11555. output->ticket = (byte*)XMALLOC(output->ticketLen, output->heap,
  11556. DYNAMIC_TYPE_SESSION_TICK);
  11557. if (output->ticket == NULL) {
  11558. error = WOLFSSL_FAILURE;
  11559. output->ticket = output->staticTicket;
  11560. output->ticketLenAlloc = 0;
  11561. output->ticketLen = 0;
  11562. }
  11563. }
  11564. else {
  11565. output->ticket = output->staticTicket;
  11566. output->ticketLenAlloc = 0;
  11567. }
  11568. }
  11569. else {
  11570. output->ticket = output->staticTicket;
  11571. output->ticketLenAlloc = 0;
  11572. output->ticketLen = 0;
  11573. }
  11574. if (error == WOLFSSL_SUCCESS) {
  11575. XMEMCPY(output->ticket, tmpTicket, output->ticketLen);
  11576. }
  11577. }
  11578. #ifdef WOLFSSL_SMALL_STACK
  11579. if (tmpTicket != NULL)
  11580. XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11581. #endif
  11582. #endif
  11583. #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
  11584. if (peer != NULL) {
  11585. wolfSSL_X509_free(peer);
  11586. }
  11587. #endif
  11588. return error;
  11589. }
  11590. WOLFSSL_SESSION* wolfSSL_GetSession(WOLFSSL* ssl, byte* masterSecret,
  11591. byte restoreSessionCerts)
  11592. {
  11593. WOLFSSL_SESSION* ret = NULL;
  11594. (void)restoreSessionCerts; /* Kept for compatibility */
  11595. if (wolfSSL_GetSessionFromCache(ssl, ssl->session) == WOLFSSL_SUCCESS) {
  11596. ret = ssl->session;
  11597. }
  11598. else {
  11599. WOLFSSL_MSG("wolfSSL_GetSessionFromCache did not return a session");
  11600. }
  11601. if (ret != NULL && masterSecret != NULL)
  11602. XMEMCPY(masterSecret, ret->masterSecret, SECRET_LEN);
  11603. return ret;
  11604. }
  11605. int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session)
  11606. {
  11607. SessionRow* sessRow = NULL;
  11608. int ret = WOLFSSL_SUCCESS;
  11609. session = ClientSessionToSession(session);
  11610. if (ssl == NULL || session == NULL) {
  11611. return WOLFSSL_FAILURE;
  11612. }
  11613. if (session->type == WOLFSSL_SESSION_TYPE_CACHE) {
  11614. if (session->cacheRow < SESSION_ROWS) {
  11615. sessRow = &SessionCache[session->cacheRow];
  11616. if (SESSION_ROW_LOCK(sessRow) != 0) {
  11617. WOLFSSL_MSG("Session row lock failed");
  11618. return WOLFSSL_FAILURE;
  11619. }
  11620. }
  11621. }
  11622. if (ret == WOLFSSL_SUCCESS && SslSessionCacheOff(ssl, session)) {
  11623. WOLFSSL_MSG("Session cache off");
  11624. ret = WOLFSSL_FAILURE;
  11625. }
  11626. if (ret == WOLFSSL_SUCCESS && ssl->options.side != WOLFSSL_NEITHER_END &&
  11627. (byte)ssl->options.side != session->side) {
  11628. WOLFSSL_MSG("Setting session for wrong role");
  11629. ret = WOLFSSL_FAILURE;
  11630. }
  11631. if (ret == WOLFSSL_SUCCESS &&
  11632. wolfSSL_DupSession(session, ssl->session, 0) != WOLFSSL_SUCCESS) {
  11633. WOLFSSL_MSG("Session duplicate failed");
  11634. ret = WOLFSSL_FAILURE;
  11635. }
  11636. /* Let's copy over the altSessionID for local cache purposes */
  11637. if (ret == WOLFSSL_SUCCESS && session->haveAltSessionID) {
  11638. ssl->session->haveAltSessionID = 1;
  11639. XMEMCPY(ssl->session->altSessionID, session->altSessionID, ID_LEN);
  11640. }
  11641. if (sessRow != NULL) {
  11642. SESSION_ROW_UNLOCK(sessRow);
  11643. sessRow = NULL;
  11644. }
  11645. /* Note: the `session` variable cannot be used below, since the row is
  11646. * un-locked */
  11647. if (ret != WOLFSSL_SUCCESS)
  11648. return ret;
  11649. #ifdef OPENSSL_EXTRA
  11650. /* check for application context id */
  11651. if (ssl->sessionCtxSz > 0) {
  11652. if (XMEMCMP(ssl->sessionCtx, ssl->session->sessionCtx, ssl->sessionCtxSz)) {
  11653. /* context id did not match! */
  11654. WOLFSSL_MSG("Session context did not match");
  11655. return WOLFSSL_FAILURE;
  11656. }
  11657. }
  11658. #endif /* OPENSSL_EXTRA */
  11659. if (LowResTimer() < (ssl->session->bornOn + ssl->session->timeout)) {
  11660. ssl->options.resuming = 1;
  11661. ssl->options.haveEMS = ssl->session->haveEMS;
  11662. #if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \
  11663. defined(HAVE_SESSION_TICKET))
  11664. ssl->version = ssl->session->version;
  11665. if (IsAtLeastTLSv1_3(ssl->version))
  11666. ssl->options.tls1_3 = 1;
  11667. #endif
  11668. #if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \
  11669. (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
  11670. ssl->options.cipherSuite0 = ssl->session->cipherSuite0;
  11671. ssl->options.cipherSuite = ssl->session->cipherSuite;
  11672. #endif
  11673. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  11674. ssl->peerVerifyRet = (unsigned long)ssl->session->peerVerifyRet;
  11675. #endif
  11676. ret = WOLFSSL_SUCCESS;
  11677. }
  11678. else {
  11679. #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_ERROR_CODE_OPENSSL)
  11680. WOLFSSL_MSG("Session is expired but return success for \
  11681. OpenSSL compatibility");
  11682. ret = WOLFSSL_SUCCESS;
  11683. #else
  11684. ret = WOLFSSL_FAILURE; /* session timed out */
  11685. #endif /* OPENSSL_EXTRA && WOLFSSL_ERROR_CODE_OPENSSL */
  11686. }
  11687. return ret;
  11688. }
  11689. #ifdef WOLFSSL_SESSION_STATS
  11690. static int get_locked_session_stats(word32* active, word32* total,
  11691. word32* peak);
  11692. #endif
  11693. #ifndef NO_CLIENT_CACHE
  11694. ClientSession* AddSessionToClientCache(int side, int row, int idx, byte* serverID,
  11695. word16 idLen, const byte* sessionID,
  11696. word16 useTicket)
  11697. {
  11698. int error = -1;
  11699. word32 clientRow = 0, clientIdx = 0, sessionIDHash = 0;
  11700. (void)useTicket;
  11701. if (side == WOLFSSL_CLIENT_END
  11702. && row != INVALID_SESSION_ROW
  11703. && (idLen
  11704. #ifdef HAVE_SESSION_TICKET
  11705. || useTicket == 1
  11706. #endif
  11707. || serverID != NULL
  11708. )) {
  11709. WOLFSSL_MSG("Trying to add client cache entry");
  11710. if (idLen) {
  11711. clientRow = HashObject(serverID,
  11712. idLen, &error) % CLIENT_SESSION_ROWS;
  11713. }
  11714. else if (serverID != NULL) {
  11715. clientRow = HashObject(sessionID,
  11716. ID_LEN, &error) % CLIENT_SESSION_ROWS;
  11717. }
  11718. else {
  11719. error = -1;
  11720. }
  11721. if (error == 0 && wc_LockMutex(&clisession_mutex) == 0) {
  11722. clientIdx = ClientCache[clientRow].nextIdx;
  11723. if (clientIdx < CLIENT_SESSIONS_PER_ROW) {
  11724. ClientCache[clientRow].Clients[clientIdx].serverRow =
  11725. (word16)row;
  11726. ClientCache[clientRow].Clients[clientIdx].serverIdx =
  11727. (word16)idx;
  11728. if (sessionID != NULL) {
  11729. sessionIDHash = HashObject(sessionID, ID_LEN, &error);
  11730. if (error == 0) {
  11731. ClientCache[clientRow].Clients[clientIdx].sessionIDHash
  11732. = sessionIDHash;
  11733. }
  11734. }
  11735. }
  11736. else {
  11737. error = -1;
  11738. ClientCache[clientRow].nextIdx = 0; /* reset index as saftey */
  11739. WOLFSSL_MSG("Invalid client cache index! "
  11740. "Possible corrupted memory");
  11741. }
  11742. if (error == 0) {
  11743. WOLFSSL_MSG("Adding client cache entry");
  11744. if (ClientCache[clientRow].totalCount < CLIENT_SESSIONS_PER_ROW)
  11745. ClientCache[clientRow].totalCount++;
  11746. ClientCache[clientRow].nextIdx++;
  11747. ClientCache[clientRow].nextIdx %= CLIENT_SESSIONS_PER_ROW;
  11748. }
  11749. wc_UnLockMutex(&clisession_mutex);
  11750. }
  11751. else {
  11752. WOLFSSL_MSG("Hash session or lock failed");
  11753. error = -1;
  11754. }
  11755. }
  11756. else {
  11757. WOLFSSL_MSG("Skipping client cache");
  11758. }
  11759. if (error == 0)
  11760. return &ClientCache[clientRow].Clients[clientIdx];
  11761. else
  11762. return NULL;
  11763. }
  11764. #endif
  11765. /**
  11766. * For backwards compatibility, this API needs to be used in *ALL* functions
  11767. * that access the WOLFSSL_SESSION members directly.
  11768. *
  11769. * This API checks if the passed in session is actually a ClientSession object
  11770. * and returns the matching session cache object. Otherwise just return the
  11771. * input. ClientSession objects only occur in the ClientCache. They are not
  11772. * allocated anywhere else.
  11773. */
  11774. WOLFSSL_SESSION* ClientSessionToSession(const WOLFSSL_SESSION* session)
  11775. {
  11776. WOLFSSL_ENTER("ClientSessionToSession");
  11777. #ifdef NO_SESSION_CACHE_REF
  11778. return (WOLFSSL_SESSION*)session;
  11779. #else
  11780. #ifndef NO_CLIENT_CACHE
  11781. if (session == NULL)
  11782. return NULL;
  11783. /* Check if session points into ClientCache */
  11784. if ((byte*)session >= (byte*)ClientCache &&
  11785. /* Cast to byte* to make pointer arithmetic work per byte */
  11786. (byte*)session < ((byte*)ClientCache) + sizeof(ClientCache)) {
  11787. ClientSession* clientSession = (ClientSession*)session;
  11788. SessionRow* sessRow = NULL;
  11789. WOLFSSL_SESSION* cacheSession = NULL;
  11790. word32 sessionIDHash = 0;
  11791. int error = 0;
  11792. session = NULL; /* Default to NULL for failure case */
  11793. if (wc_LockMutex(&clisession_mutex) != 0) {
  11794. WOLFSSL_MSG("Client cache mutex lock failed");
  11795. return NULL;
  11796. }
  11797. if (clientSession->serverRow >= SESSION_ROWS ||
  11798. clientSession->serverIdx >= SESSIONS_PER_ROW) {
  11799. WOLFSSL_MSG("Client cache serverRow or serverIdx invalid");
  11800. error = -1;
  11801. }
  11802. if (error == 0) {
  11803. /* Lock row */
  11804. sessRow = &SessionCache[clientSession->serverRow];
  11805. error = SESSION_ROW_LOCK(sessRow);
  11806. if (error != 0) {
  11807. WOLFSSL_MSG("Session cache row lock failure");
  11808. sessRow = NULL;
  11809. }
  11810. }
  11811. if (error == 0) {
  11812. cacheSession = &sessRow->Sessions[clientSession->serverIdx];
  11813. if (cacheSession->sessionIDSz == 0) {
  11814. cacheSession = NULL;
  11815. WOLFSSL_MSG("Session cache entry not set");
  11816. error = -1;
  11817. }
  11818. }
  11819. if (error == 0) {
  11820. /* Calculate the hash of the session ID */
  11821. sessionIDHash = HashObject(cacheSession->sessionID, ID_LEN,
  11822. &error);
  11823. }
  11824. if (error == 0) {
  11825. /* Check the session ID hash matches */
  11826. error = clientSession->sessionIDHash != sessionIDHash;
  11827. }
  11828. if (error == 0) {
  11829. /* Hashes match */
  11830. session = cacheSession;
  11831. WOLFSSL_MSG("Found session cache matching client session object");
  11832. }
  11833. if (sessRow != NULL) {
  11834. SESSION_ROW_UNLOCK(sessRow);
  11835. }
  11836. wc_UnLockMutex(&clisession_mutex);
  11837. return (WOLFSSL_SESSION*)session;
  11838. }
  11839. else {
  11840. /* Plain WOLFSSL_SESSION object */
  11841. return (WOLFSSL_SESSION*)session;
  11842. }
  11843. #else
  11844. return (WOLFSSL_SESSION*)session;
  11845. #endif
  11846. #endif
  11847. }
  11848. int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession,
  11849. const byte* id, byte idSz, int* sessionIndex, int side,
  11850. word16 useTicket, ClientSession** clientCacheEntry)
  11851. {
  11852. WOLFSSL_SESSION* cacheSession = NULL;
  11853. SessionRow* sessRow = NULL;
  11854. word32 idx = 0;
  11855. #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
  11856. WOLFSSL_X509* peer = NULL;
  11857. #endif
  11858. #ifdef HAVE_SESSION_TICKET
  11859. byte* cacheTicBuff = NULL;
  11860. byte ticBuffUsed = 0;
  11861. byte* ticBuff = NULL;
  11862. int ticLen = 0;
  11863. #endif
  11864. int ret = 0;
  11865. int row;
  11866. int i;
  11867. int overwrite = 0;
  11868. (void)ctx;
  11869. (void)sessionIndex;
  11870. (void)useTicket;
  11871. (void)clientCacheEntry;
  11872. if (idSz == 0) {
  11873. WOLFSSL_MSG("AddSessionToCache idSz == 0");
  11874. return BAD_FUNC_ARG;
  11875. }
  11876. addSession = ClientSessionToSession(addSession);
  11877. if (addSession == NULL) {
  11878. WOLFSSL_MSG("AddSessionToCache is NULL");
  11879. return MEMORY_E;
  11880. }
  11881. /* Find a position for the new session in cache and use that */
  11882. #ifdef HAVE_SESSION_TICKET
  11883. ticLen = addSession->ticketLen;
  11884. /* Alloc Memory here to avoid syscalls during lock */
  11885. if (ticLen > SESSION_TICKET_LEN) {
  11886. ticBuff = (byte*)XMALLOC(ticLen, NULL,
  11887. DYNAMIC_TYPE_SESSION_TICK);
  11888. if (ticBuff == NULL) {
  11889. return MEMORY_E;
  11890. }
  11891. }
  11892. #endif
  11893. /* Use the session object in the cache for external cache if required */
  11894. row = (int)(HashObject(id, ID_LEN, &ret) % SESSION_ROWS);
  11895. if (ret != 0) {
  11896. WOLFSSL_MSG("Hash session failed");
  11897. #ifdef HAVE_SESSION_TICKET
  11898. XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK);
  11899. #endif
  11900. return ret;
  11901. }
  11902. sessRow = &SessionCache[row];
  11903. if (SESSION_ROW_LOCK(sessRow) != 0) {
  11904. #ifdef HAVE_SESSION_TICKET
  11905. XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK);
  11906. #endif
  11907. WOLFSSL_MSG("Session row lock failed");
  11908. return BAD_MUTEX_E;
  11909. }
  11910. for (i = 0; i < SESSIONS_PER_ROW && i < sessRow->totalCount; i++) {
  11911. if (XMEMCMP(id,
  11912. sessRow->Sessions[i].sessionID, ID_LEN) == 0 &&
  11913. sessRow->Sessions[i].side == side) {
  11914. WOLFSSL_MSG("Session already exists. Overwriting.");
  11915. overwrite = 1;
  11916. idx = i;
  11917. break;
  11918. }
  11919. }
  11920. if (!overwrite)
  11921. idx = sessRow->nextIdx;
  11922. #ifdef SESSION_INDEX
  11923. if (sessionIndex != NULL)
  11924. *sessionIndex = (row << SESSIDX_ROW_SHIFT) | idx;
  11925. #endif
  11926. cacheSession = &sessRow->Sessions[idx];
  11927. #ifdef HAVE_EX_DATA
  11928. if (cacheSession->rem_sess_cb && cacheSession->ownExData) {
  11929. cacheSession->rem_sess_cb(NULL, cacheSession);
  11930. /* Make sure not to call remove functions again */
  11931. cacheSession->ownExData = 0;
  11932. cacheSession->rem_sess_cb = NULL;
  11933. }
  11934. #endif
  11935. cacheSession->type = WOLFSSL_SESSION_TYPE_CACHE;
  11936. cacheSession->cacheRow = row;
  11937. #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
  11938. /* Save the peer field to free after unlocking the row */
  11939. if (cacheSession->peer != NULL)
  11940. peer = cacheSession->peer;
  11941. cacheSession->peer = NULL;
  11942. #endif
  11943. #ifdef HAVE_SESSION_TICKET
  11944. /* If we can re-use the existing buffer in cacheSession then we won't touch
  11945. * ticBuff at all making it a very cheap malloc/free. The page on a modern
  11946. * OS will most likely not even be allocated to the process. */
  11947. if (ticBuff != NULL && cacheSession->ticketLenAlloc < ticLen) {
  11948. /* Save pointer only if separately allocated */
  11949. if (cacheSession->ticket != cacheSession->staticTicket)
  11950. cacheTicBuff = cacheSession->ticket;
  11951. ticBuffUsed = 1;
  11952. cacheSession->ticket = ticBuff;
  11953. cacheSession->ticketLenAlloc = (word16) ticLen;
  11954. }
  11955. #endif
  11956. #ifdef SESSION_CERTS
  11957. if (overwrite &&
  11958. addSession->chain.count == 0 &&
  11959. cacheSession->chain.count > 0) {
  11960. /* Copy in the certs from the session */
  11961. addSession->chain.count = cacheSession->chain.count;
  11962. XMEMCPY(addSession->chain.certs, cacheSession->chain.certs,
  11963. sizeof(x509_buffer) * cacheSession->chain.count);
  11964. }
  11965. #endif /* SESSION_CERTS */
  11966. cacheSession->heap = NULL;
  11967. /* Copy data into the cache object */
  11968. ret = wolfSSL_DupSession(addSession, cacheSession, 1) == WOLFSSL_FAILURE;
  11969. if (ret == 0) {
  11970. /* Increment the totalCount and the nextIdx */
  11971. if (sessRow->totalCount < SESSIONS_PER_ROW)
  11972. sessRow->totalCount++;
  11973. sessRow->nextIdx = (sessRow->nextIdx + 1) % SESSIONS_PER_ROW;
  11974. if (id != addSession->sessionID) {
  11975. /* ssl->session->sessionID may contain the bogus ID or we want the
  11976. * ID from the arrays object */
  11977. XMEMCPY(cacheSession->sessionID, id, ID_LEN);
  11978. cacheSession->sessionIDSz = ID_LEN;
  11979. }
  11980. #ifdef HAVE_EX_DATA
  11981. if (ctx->rem_sess_cb != NULL) {
  11982. addSession->ownExData = 0;
  11983. cacheSession->ownExData = 1;
  11984. cacheSession->rem_sess_cb = ctx->rem_sess_cb;
  11985. }
  11986. #endif
  11987. }
  11988. #ifdef HAVE_SESSION_TICKET
  11989. else if (ticBuffUsed) {
  11990. /* Error occured. Need to clean up the ticket buffer. */
  11991. cacheSession->ticket = cacheSession->staticTicket;
  11992. cacheSession->ticketLenAlloc = 0;
  11993. cacheSession->ticketLen = 0;
  11994. }
  11995. #endif
  11996. SESSION_ROW_UNLOCK(sessRow);
  11997. cacheSession = NULL; /* Can't access after unlocked */
  11998. #ifndef NO_CLIENT_CACHE
  11999. if (ret == 0 && clientCacheEntry != NULL) {
  12000. ClientSession* clientCache = AddSessionToClientCache(side, row, idx,
  12001. addSession->serverID, addSession->idLen, id, useTicket);
  12002. if (clientCache != NULL)
  12003. *clientCacheEntry = clientCache;
  12004. }
  12005. #endif
  12006. #ifdef HAVE_SESSION_TICKET
  12007. if (ticBuff != NULL && !ticBuffUsed)
  12008. XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK);
  12009. if (cacheTicBuff != NULL)
  12010. XFREE(cacheTicBuff, NULL, DYNAMIC_TYPE_SESSION_TICK);
  12011. #endif
  12012. #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
  12013. if (peer != NULL) {
  12014. wolfSSL_X509_free(peer);
  12015. peer = NULL; /* Make sure not use after this point */
  12016. }
  12017. #endif
  12018. return ret;
  12019. }
  12020. #ifndef NO_CLIENT_CACHE
  12021. #endif
  12022. void AddSession(WOLFSSL* ssl)
  12023. {
  12024. int error = 0;
  12025. const byte* id = NULL;
  12026. byte idSz = 0;
  12027. WOLFSSL_SESSION* session = ssl->session;
  12028. #ifdef HAVE_EXT_CACHE
  12029. int cbRet = 0;
  12030. #endif
  12031. (void)error;
  12032. WOLFSSL_ENTER("AddSession");
  12033. if (SslSessionCacheOff(ssl, session)) {
  12034. WOLFSSL_MSG("Cache off");
  12035. return;
  12036. }
  12037. if (ssl->options.haveSessionId == 0) {
  12038. WOLFSSL_MSG("Don't have session id");
  12039. return;
  12040. }
  12041. #if defined(HAVE_SESSION_TICKET) && !defined(OPENSSL_EXTRA)
  12042. /* For the compat layer generate a session object to use */
  12043. if (ssl->options.side == WOLFSSL_SERVER_END && ssl->options.useTicket == 1) {
  12044. WOLFSSL_MSG("Using tickets instead of cache");
  12045. return;
  12046. }
  12047. #endif
  12048. if (session->haveAltSessionID) {
  12049. id = session->altSessionID;
  12050. idSz = ID_LEN;
  12051. }
  12052. else {
  12053. if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL) {
  12054. /* Make sure the session ID is available when the user calls any
  12055. * get_session API */
  12056. XMEMCPY(session->sessionID, ssl->arrays->sessionID, ID_LEN);
  12057. session->sessionIDSz = ssl->arrays->sessionIDSz;
  12058. }
  12059. id = session->sessionID;
  12060. idSz = session->sessionIDSz;
  12061. }
  12062. session->timeout = ssl->timeout;
  12063. session->side = (byte)ssl->options.side;
  12064. if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL)
  12065. XMEMCPY(session->masterSecret, ssl->arrays->masterSecret, SECRET_LEN);
  12066. session->haveEMS = ssl->options.haveEMS;
  12067. #ifdef OPENSSL_EXTRA
  12068. /* If using compatibility layer then check for and copy over session context
  12069. * id. */
  12070. if (ssl->sessionCtxSz > 0 && ssl->sessionCtxSz < ID_LEN) {
  12071. XMEMCPY(ssl->session->sessionCtx, ssl->sessionCtx, ssl->sessionCtxSz);
  12072. session->sessionCtxSz = ssl->sessionCtxSz;
  12073. }
  12074. #endif
  12075. session->timeout = ssl->timeout;
  12076. session->bornOn = LowResTimer();
  12077. #if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \
  12078. defined(HAVE_SESSION_TICKET))
  12079. session->version = ssl->version;
  12080. #endif
  12081. #if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \
  12082. (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
  12083. session->cipherSuite0 = ssl->options.cipherSuite0;
  12084. session->cipherSuite = ssl->options.cipherSuite;
  12085. #endif
  12086. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  12087. session->peerVerifyRet = (byte)ssl->peerVerifyRet;
  12088. #endif
  12089. /* Do this last so that if it fails, the rest of the session is setup. Do
  12090. * this only for the client because if the server doesn't have an ID at
  12091. * this point, it won't on resumption. */
  12092. if (idSz == 0 && ssl->options.side == WOLFSSL_CLIENT_END) {
  12093. WC_RNG* rng = NULL;
  12094. if (ssl->rng != NULL)
  12095. rng = ssl->rng;
  12096. #if defined(HAVE_GLOBAL_RNG) && defined(OPENSSL_EXTRA)
  12097. else if (initGlobalRNG == 1 || wolfSSL_RAND_Init() == WOLFSSL_SUCCESS) {
  12098. rng = &globalRNG;
  12099. }
  12100. #endif
  12101. if (wc_RNG_GenerateBlock(rng, ssl->session->altSessionID,
  12102. ID_LEN) != 0)
  12103. return;
  12104. ssl->session->haveAltSessionID = 1;
  12105. id = ssl->session->altSessionID;
  12106. idSz = ID_LEN;
  12107. }
  12108. /* Setup done */
  12109. if (ssl->options.side == WOLFSSL_SERVER_END /* No point in adding a
  12110. * client session */
  12111. #ifdef HAVE_EXT_CACHE
  12112. && !ssl->options.internalCacheOff
  12113. #endif
  12114. )
  12115. {
  12116. /* Try to add the session to cache. Its ok if we don't succeed. */
  12117. (void)AddSessionToCache(ssl->ctx, session, id, idSz,
  12118. #ifdef SESSION_INDEX
  12119. &ssl->sessionIndex,
  12120. #else
  12121. NULL,
  12122. #endif
  12123. ssl->options.side,
  12124. #ifdef HAVE_SESSION_TICKET
  12125. ssl->options.useTicket,
  12126. #else
  12127. 0,
  12128. #endif
  12129. NULL
  12130. );
  12131. }
  12132. #ifdef HAVE_EXT_CACHE
  12133. if (error == 0 && ssl->ctx->new_sess_cb != NULL) {
  12134. wolfSSL_SESSION_up_ref(session);
  12135. cbRet = ssl->ctx->new_sess_cb(ssl, session);
  12136. if (cbRet == 0)
  12137. wolfSSL_FreeSession(ssl->ctx, session);
  12138. }
  12139. #endif
  12140. #if defined(WOLFSSL_SESSION_STATS) && defined(WOLFSSL_PEAK_SESSIONS)
  12141. if (error == 0) {
  12142. word32 active = 0;
  12143. error = get_locked_session_stats(&active, NULL, NULL);
  12144. if (error == WOLFSSL_SUCCESS) {
  12145. error = 0; /* back to this function ok */
  12146. if (PeakSessions < active) {
  12147. PeakSessions = active;
  12148. }
  12149. }
  12150. }
  12151. #endif /* WOLFSSL_SESSION_STATS && WOLFSSL_PEAK_SESSIONS */
  12152. (void)error;
  12153. }
  12154. #ifdef SESSION_INDEX
  12155. int wolfSSL_GetSessionIndex(WOLFSSL* ssl)
  12156. {
  12157. WOLFSSL_ENTER("wolfSSL_GetSessionIndex");
  12158. WOLFSSL_LEAVE("wolfSSL_GetSessionIndex", ssl->sessionIndex);
  12159. return ssl->sessionIndex;
  12160. }
  12161. int wolfSSL_GetSessionAtIndex(int idx, WOLFSSL_SESSION* session)
  12162. {
  12163. int row, col, result = WOLFSSL_FAILURE;
  12164. SessionRow* sessRow;
  12165. WOLFSSL_ENTER("wolfSSL_GetSessionAtIndex");
  12166. session = ClientSessionToSession(session);
  12167. row = idx >> SESSIDX_ROW_SHIFT;
  12168. col = idx & SESSIDX_IDX_MASK;
  12169. if (session == NULL ||
  12170. row < 0 || row >= SESSION_ROWS || col >= SESSIONS_PER_ROW) {
  12171. return WOLFSSL_FAILURE;
  12172. }
  12173. sessRow = &SessionCache[row];
  12174. if (SESSION_ROW_LOCK(sessRow) != 0) {
  12175. return BAD_MUTEX_E;
  12176. }
  12177. XMEMCPY(session, &sessRow->Sessions[col], sizeof(WOLFSSL_SESSION));
  12178. result = WOLFSSL_SUCCESS;
  12179. SESSION_ROW_UNLOCK(sessRow);
  12180. WOLFSSL_LEAVE("wolfSSL_GetSessionAtIndex", result);
  12181. return result;
  12182. }
  12183. #endif /* SESSION_INDEX */
  12184. #if defined(SESSION_CERTS)
  12185. WOLFSSL_X509_CHAIN* wolfSSL_SESSION_get_peer_chain(WOLFSSL_SESSION* session)
  12186. {
  12187. WOLFSSL_X509_CHAIN* chain = NULL;
  12188. WOLFSSL_ENTER("wolfSSL_SESSION_get_peer_chain");
  12189. session = ClientSessionToSession(session);
  12190. if (session)
  12191. chain = &session->chain;
  12192. WOLFSSL_LEAVE("wolfSSL_SESSION_get_peer_chain", chain ? 1 : 0);
  12193. return chain;
  12194. }
  12195. #ifdef OPENSSL_EXTRA
  12196. /* gets the peer certificate associated with the session passed in
  12197. * returns null on failure, the caller should not free the returned pointer */
  12198. WOLFSSL_X509* wolfSSL_SESSION_get0_peer(WOLFSSL_SESSION* session)
  12199. {
  12200. WOLFSSL_ENTER("wolfSSL_SESSION_get_peer_chain");
  12201. session = ClientSessionToSession(session);
  12202. if (session) {
  12203. int count;
  12204. count = wolfSSL_get_chain_count(&session->chain);
  12205. if (count < 1 || count >= MAX_CHAIN_DEPTH) {
  12206. WOLFSSL_MSG("bad count found");
  12207. return NULL;
  12208. }
  12209. if (session->peer == NULL) {
  12210. session->peer = wolfSSL_get_chain_X509(&session->chain, 0);
  12211. }
  12212. return session->peer;
  12213. }
  12214. WOLFSSL_MSG("No session passed in");
  12215. return NULL;
  12216. }
  12217. #endif /* OPENSSL_EXTRA */
  12218. #endif /* SESSION_INDEX && SESSION_CERTS */
  12219. #ifdef WOLFSSL_SESSION_STATS
  12220. static int get_locked_session_stats(word32* active, word32* total, word32* peak)
  12221. {
  12222. int result = WOLFSSL_SUCCESS;
  12223. int i;
  12224. int count;
  12225. int idx;
  12226. word32 now = 0;
  12227. word32 seen = 0;
  12228. word32 ticks = LowResTimer();
  12229. WOLFSSL_ENTER("get_locked_session_stats");
  12230. #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
  12231. wc_LockMutex(&session_mutex);
  12232. #endif
  12233. for (i = 0; i < SESSION_ROWS; i++) {
  12234. SessionRow* row = &SessionCache[i];
  12235. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  12236. if (SESSION_ROW_LOCK(row) != 0) {
  12237. WOLFSSL_MSG("Session row cache mutex lock failed");
  12238. return BAD_MUTEX_E;
  12239. }
  12240. #endif
  12241. seen += row->totalCount;
  12242. if (active == NULL) {
  12243. SESSION_ROW_UNLOCK(row);
  12244. continue;
  12245. }
  12246. count = min((word32)row->totalCount, SESSIONS_PER_ROW);
  12247. idx = row->nextIdx - 1;
  12248. if (idx < 0 || idx >= SESSIONS_PER_ROW) {
  12249. idx = SESSIONS_PER_ROW - 1; /* if back to front previous was end */
  12250. }
  12251. for (; count > 0; --count) {
  12252. /* if not expired then good */
  12253. if (ticks < (row->Sessions[idx].bornOn +
  12254. row->Sessions[idx].timeout) ) {
  12255. now++;
  12256. }
  12257. idx = idx > 0 ? idx - 1 : SESSIONS_PER_ROW - 1;
  12258. }
  12259. #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
  12260. SESSION_ROW_UNLOCK(row);
  12261. #endif
  12262. }
  12263. #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
  12264. wc_UnLockMutex(&session_mutex);
  12265. #endif
  12266. if (active) {
  12267. *active = now;
  12268. }
  12269. if (total) {
  12270. *total = seen;
  12271. }
  12272. #ifdef WOLFSSL_PEAK_SESSIONS
  12273. if (peak) {
  12274. *peak = PeakSessions;
  12275. }
  12276. #else
  12277. (void)peak;
  12278. #endif
  12279. WOLFSSL_LEAVE("get_locked_session_stats", result);
  12280. return result;
  12281. }
  12282. /* return WOLFSSL_SUCCESS on ok */
  12283. int wolfSSL_get_session_stats(word32* active, word32* total, word32* peak,
  12284. word32* maxSessions)
  12285. {
  12286. int result = WOLFSSL_SUCCESS;
  12287. WOLFSSL_ENTER("wolfSSL_get_session_stats");
  12288. if (maxSessions) {
  12289. *maxSessions = SESSIONS_PER_ROW * SESSION_ROWS;
  12290. if (active == NULL && total == NULL && peak == NULL)
  12291. return result; /* we're done */
  12292. }
  12293. /* user must provide at least one query value */
  12294. if (active == NULL && total == NULL && peak == NULL) {
  12295. return BAD_FUNC_ARG;
  12296. }
  12297. result = get_locked_session_stats(active, total, peak);
  12298. WOLFSSL_LEAVE("wolfSSL_get_session_stats", result);
  12299. return result;
  12300. }
  12301. #endif /* WOLFSSL_SESSION_STATS */
  12302. #ifdef PRINT_SESSION_STATS
  12303. /* WOLFSSL_SUCCESS on ok */
  12304. int wolfSSL_PrintSessionStats(void)
  12305. {
  12306. word32 totalSessionsSeen = 0;
  12307. word32 totalSessionsNow = 0;
  12308. word32 peak = 0;
  12309. word32 maxSessions = 0;
  12310. int i;
  12311. int ret;
  12312. double E; /* expected freq */
  12313. double chiSquare = 0;
  12314. ret = wolfSSL_get_session_stats(&totalSessionsNow, &totalSessionsSeen,
  12315. &peak, &maxSessions);
  12316. if (ret != WOLFSSL_SUCCESS)
  12317. return ret;
  12318. printf("Total Sessions Seen = %u\n", totalSessionsSeen);
  12319. printf("Total Sessions Now = %u\n", totalSessionsNow);
  12320. #ifdef WOLFSSL_PEAK_SESSIONS
  12321. printf("Peak Sessions = %u\n", peak);
  12322. #endif
  12323. printf("Max Sessions = %u\n", maxSessions);
  12324. E = (double)totalSessionsSeen / SESSION_ROWS;
  12325. for (i = 0; i < SESSION_ROWS; i++) {
  12326. double diff = SessionCache[i].totalCount - E;
  12327. diff *= diff; /* square */
  12328. diff /= E; /* normalize */
  12329. chiSquare += diff;
  12330. }
  12331. printf(" chi-square = %5.1f, d.f. = %d\n", chiSquare,
  12332. SESSION_ROWS - 1);
  12333. #if (SESSION_ROWS == 11)
  12334. printf(" .05 p value = 18.3, chi-square should be less\n");
  12335. #elif (SESSION_ROWS == 211)
  12336. printf(".05 p value = 244.8, chi-square should be less\n");
  12337. #elif (SESSION_ROWS == 5981)
  12338. printf(".05 p value = 6161.0, chi-square should be less\n");
  12339. #elif (SESSION_ROWS == 3)
  12340. printf(".05 p value = 6.0, chi-square should be less\n");
  12341. #elif (SESSION_ROWS == 2861)
  12342. printf(".05 p value = 2985.5, chi-square should be less\n");
  12343. #endif
  12344. printf("\n");
  12345. return ret;
  12346. }
  12347. #endif /* SESSION_STATS */
  12348. #else /* NO_SESSION_CACHE */
  12349. WOLFSSL_SESSION* ClientSessionToSession(const WOLFSSL_SESSION* session)
  12350. {
  12351. return (WOLFSSL_SESSION*)session;
  12352. }
  12353. /* No session cache version */
  12354. WOLFSSL_SESSION* wolfSSL_GetSession(WOLFSSL* ssl, byte* masterSecret,
  12355. byte restoreSessionCerts)
  12356. {
  12357. (void)ssl;
  12358. (void)masterSecret;
  12359. (void)restoreSessionCerts;
  12360. return NULL;
  12361. }
  12362. #endif /* NO_SESSION_CACHE */
  12363. /* call before SSL_connect, if verifying will add name check to
  12364. date check and signature check */
  12365. WOLFSSL_ABI
  12366. int wolfSSL_check_domain_name(WOLFSSL* ssl, const char* dn)
  12367. {
  12368. WOLFSSL_ENTER("wolfSSL_check_domain_name");
  12369. if (ssl == NULL || dn == NULL) {
  12370. WOLFSSL_MSG("Bad function argument: NULL");
  12371. return WOLFSSL_FAILURE;
  12372. }
  12373. if (ssl->buffers.domainName.buffer)
  12374. XFREE(ssl->buffers.domainName.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
  12375. ssl->buffers.domainName.length = (word32)XSTRLEN(dn);
  12376. ssl->buffers.domainName.buffer = (byte*)XMALLOC(
  12377. ssl->buffers.domainName.length + 1, ssl->heap, DYNAMIC_TYPE_DOMAIN);
  12378. if (ssl->buffers.domainName.buffer) {
  12379. unsigned char* domainName = ssl->buffers.domainName.buffer;
  12380. XMEMCPY(domainName, dn, ssl->buffers.domainName.length);
  12381. domainName[ssl->buffers.domainName.length] = '\0';
  12382. return WOLFSSL_SUCCESS;
  12383. }
  12384. else {
  12385. ssl->error = MEMORY_ERROR;
  12386. return WOLFSSL_FAILURE;
  12387. }
  12388. }
  12389. /* turn on wolfSSL zlib compression
  12390. returns WOLFSSL_SUCCESS for success, else error (not built in)
  12391. */
  12392. int wolfSSL_set_compression(WOLFSSL* ssl)
  12393. {
  12394. WOLFSSL_ENTER("wolfSSL_set_compression");
  12395. (void)ssl;
  12396. #ifdef HAVE_LIBZ
  12397. ssl->options.usingCompression = 1;
  12398. return WOLFSSL_SUCCESS;
  12399. #else
  12400. return NOT_COMPILED_IN;
  12401. #endif
  12402. }
  12403. #ifndef USE_WINDOWS_API
  12404. #ifndef NO_WRITEV
  12405. /* simulate writev semantics, doesn't actually do block at a time though
  12406. because of SSL_write behavior and because front adds may be small */
  12407. int wolfSSL_writev(WOLFSSL* ssl, const struct iovec* iov, int iovcnt)
  12408. {
  12409. #ifdef WOLFSSL_SMALL_STACK
  12410. byte staticBuffer[1]; /* force heap usage */
  12411. #else
  12412. byte staticBuffer[FILE_BUFFER_SIZE];
  12413. #endif
  12414. byte* myBuffer = staticBuffer;
  12415. int dynamic = 0;
  12416. int sending = 0;
  12417. int idx = 0;
  12418. int i;
  12419. int ret;
  12420. WOLFSSL_ENTER("wolfSSL_writev");
  12421. for (i = 0; i < iovcnt; i++)
  12422. sending += (int)iov[i].iov_len;
  12423. if (sending > (int)sizeof(staticBuffer)) {
  12424. myBuffer = (byte*)XMALLOC(sending, ssl->heap,
  12425. DYNAMIC_TYPE_WRITEV);
  12426. if (!myBuffer)
  12427. return MEMORY_ERROR;
  12428. dynamic = 1;
  12429. }
  12430. for (i = 0; i < iovcnt; i++) {
  12431. XMEMCPY(&myBuffer[idx], iov[i].iov_base, iov[i].iov_len);
  12432. idx += (int)iov[i].iov_len;
  12433. }
  12434. /* myBuffer may not be initialized fully, but the span up to the
  12435. * sending length will be.
  12436. */
  12437. PRAGMA_GCC_DIAG_PUSH;
  12438. PRAGMA_GCC("GCC diagnostic ignored \"-Wmaybe-uninitialized\"");
  12439. ret = wolfSSL_write(ssl, myBuffer, sending);
  12440. PRAGMA_GCC_DIAG_POP;
  12441. if (dynamic)
  12442. XFREE(myBuffer, ssl->heap, DYNAMIC_TYPE_WRITEV);
  12443. return ret;
  12444. }
  12445. #endif
  12446. #endif
  12447. #ifdef WOLFSSL_CALLBACKS
  12448. typedef struct itimerval Itimerval;
  12449. /* don't keep calling simple functions while setting up timer and signals
  12450. if no inlining these are the next best */
  12451. #define AddTimes(a, b, c) \
  12452. do { \
  12453. c.tv_sec = a.tv_sec + b.tv_sec; \
  12454. c.tv_usec = a.tv_usec + b.tv_usec; \
  12455. if (c.tv_usec >= 1000000) { \
  12456. c.tv_sec++; \
  12457. c.tv_usec -= 1000000; \
  12458. } \
  12459. } while (0)
  12460. #define SubtractTimes(a, b, c) \
  12461. do { \
  12462. c.tv_sec = a.tv_sec - b.tv_sec; \
  12463. c.tv_usec = a.tv_usec - b.tv_usec; \
  12464. if (c.tv_usec < 0) { \
  12465. c.tv_sec--; \
  12466. c.tv_usec += 1000000; \
  12467. } \
  12468. } while (0)
  12469. #define CmpTimes(a, b, cmp) \
  12470. ((a.tv_sec == b.tv_sec) ? \
  12471. (a.tv_usec cmp b.tv_usec) : \
  12472. (a.tv_sec cmp b.tv_sec)) \
  12473. /* do nothing handler */
  12474. static void myHandler(int signo)
  12475. {
  12476. (void)signo;
  12477. return;
  12478. }
  12479. static int wolfSSL_ex_wrapper(WOLFSSL* ssl, HandShakeCallBack hsCb,
  12480. TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
  12481. {
  12482. int ret = WOLFSSL_FATAL_ERROR;
  12483. int oldTimerOn = 0; /* was timer already on */
  12484. WOLFSSL_TIMEVAL startTime;
  12485. WOLFSSL_TIMEVAL endTime;
  12486. WOLFSSL_TIMEVAL totalTime;
  12487. Itimerval myTimeout;
  12488. Itimerval oldTimeout; /* if old timer adjust from total time to reset */
  12489. struct sigaction act, oact;
  12490. #define ERR_OUT(x) { ssl->hsInfoOn = 0; ssl->toInfoOn = 0; return x; }
  12491. if (hsCb) {
  12492. ssl->hsInfoOn = 1;
  12493. InitHandShakeInfo(&ssl->handShakeInfo, ssl);
  12494. }
  12495. if (toCb) {
  12496. ssl->toInfoOn = 1;
  12497. InitTimeoutInfo(&ssl->timeoutInfo);
  12498. if (gettimeofday(&startTime, 0) < 0)
  12499. ERR_OUT(GETTIME_ERROR);
  12500. /* use setitimer to simulate getitimer, init 0 myTimeout */
  12501. myTimeout.it_interval.tv_sec = 0;
  12502. myTimeout.it_interval.tv_usec = 0;
  12503. myTimeout.it_value.tv_sec = 0;
  12504. myTimeout.it_value.tv_usec = 0;
  12505. if (setitimer(ITIMER_REAL, &myTimeout, &oldTimeout) < 0)
  12506. ERR_OUT(SETITIMER_ERROR);
  12507. if (oldTimeout.it_value.tv_sec || oldTimeout.it_value.tv_usec) {
  12508. oldTimerOn = 1;
  12509. /* is old timer going to expire before ours */
  12510. if (CmpTimes(oldTimeout.it_value, timeout, <)) {
  12511. timeout.tv_sec = oldTimeout.it_value.tv_sec;
  12512. timeout.tv_usec = oldTimeout.it_value.tv_usec;
  12513. }
  12514. }
  12515. myTimeout.it_value.tv_sec = timeout.tv_sec;
  12516. myTimeout.it_value.tv_usec = timeout.tv_usec;
  12517. /* set up signal handler, don't restart socket send/recv */
  12518. act.sa_handler = myHandler;
  12519. sigemptyset(&act.sa_mask);
  12520. act.sa_flags = 0;
  12521. #ifdef SA_INTERRUPT
  12522. act.sa_flags |= SA_INTERRUPT;
  12523. #endif
  12524. if (sigaction(SIGALRM, &act, &oact) < 0)
  12525. ERR_OUT(SIGACT_ERROR);
  12526. if (setitimer(ITIMER_REAL, &myTimeout, 0) < 0)
  12527. ERR_OUT(SETITIMER_ERROR);
  12528. }
  12529. /* do main work */
  12530. #ifndef NO_WOLFSSL_CLIENT
  12531. if (ssl->options.side == WOLFSSL_CLIENT_END)
  12532. ret = wolfSSL_connect(ssl);
  12533. #endif
  12534. #ifndef NO_WOLFSSL_SERVER
  12535. if (ssl->options.side == WOLFSSL_SERVER_END)
  12536. ret = wolfSSL_accept(ssl);
  12537. #endif
  12538. /* do callbacks */
  12539. if (toCb) {
  12540. if (oldTimerOn) {
  12541. gettimeofday(&endTime, 0);
  12542. SubtractTimes(endTime, startTime, totalTime);
  12543. /* adjust old timer for elapsed time */
  12544. if (CmpTimes(totalTime, oldTimeout.it_value, <))
  12545. SubtractTimes(oldTimeout.it_value, totalTime,
  12546. oldTimeout.it_value);
  12547. else {
  12548. /* reset value to interval, may be off */
  12549. oldTimeout.it_value.tv_sec = oldTimeout.it_interval.tv_sec;
  12550. oldTimeout.it_value.tv_usec =oldTimeout.it_interval.tv_usec;
  12551. }
  12552. /* keep iter the same whether there or not */
  12553. }
  12554. /* restore old handler */
  12555. if (sigaction(SIGALRM, &oact, 0) < 0)
  12556. ret = SIGACT_ERROR; /* more pressing error, stomp */
  12557. else
  12558. /* use old settings which may turn off (expired or not there) */
  12559. if (setitimer(ITIMER_REAL, &oldTimeout, 0) < 0)
  12560. ret = SETITIMER_ERROR;
  12561. /* if we had a timeout call callback */
  12562. if (ssl->timeoutInfo.timeoutName[0]) {
  12563. ssl->timeoutInfo.timeoutValue.tv_sec = timeout.tv_sec;
  12564. ssl->timeoutInfo.timeoutValue.tv_usec = timeout.tv_usec;
  12565. (toCb)(&ssl->timeoutInfo);
  12566. }
  12567. ssl->toInfoOn = 0;
  12568. }
  12569. /* clean up buffers allocated by AddPacketInfo */
  12570. FreeTimeoutInfo(&ssl->timeoutInfo, ssl->heap);
  12571. if (hsCb) {
  12572. FinishHandShakeInfo(&ssl->handShakeInfo);
  12573. (hsCb)(&ssl->handShakeInfo);
  12574. ssl->hsInfoOn = 0;
  12575. }
  12576. return ret;
  12577. }
  12578. #ifndef NO_WOLFSSL_CLIENT
  12579. int wolfSSL_connect_ex(WOLFSSL* ssl, HandShakeCallBack hsCb,
  12580. TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
  12581. {
  12582. WOLFSSL_ENTER("wolfSSL_connect_ex");
  12583. return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout);
  12584. }
  12585. #endif
  12586. #ifndef NO_WOLFSSL_SERVER
  12587. int wolfSSL_accept_ex(WOLFSSL* ssl, HandShakeCallBack hsCb,
  12588. TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
  12589. {
  12590. WOLFSSL_ENTER("wolfSSL_accept_ex");
  12591. return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout);
  12592. }
  12593. #endif
  12594. #endif /* WOLFSSL_CALLBACKS */
  12595. #ifndef NO_PSK
  12596. void wolfSSL_CTX_set_psk_client_callback(WOLFSSL_CTX* ctx,
  12597. wc_psk_client_callback cb)
  12598. {
  12599. WOLFSSL_ENTER("SSL_CTX_set_psk_client_callback");
  12600. if (ctx == NULL)
  12601. return;
  12602. ctx->havePSK = 1;
  12603. ctx->client_psk_cb = cb;
  12604. }
  12605. void wolfSSL_set_psk_client_callback(WOLFSSL* ssl,wc_psk_client_callback cb)
  12606. {
  12607. byte haveRSA = 1;
  12608. int keySz = 0;
  12609. WOLFSSL_ENTER("SSL_set_psk_client_callback");
  12610. if (ssl == NULL)
  12611. return;
  12612. ssl->options.havePSK = 1;
  12613. ssl->options.client_psk_cb = cb;
  12614. #ifdef NO_RSA
  12615. haveRSA = 0;
  12616. #endif
  12617. #ifndef NO_CERTS
  12618. keySz = ssl->buffers.keySz;
  12619. #endif
  12620. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
  12621. ssl->options.haveDH, ssl->options.haveECDSAsig,
  12622. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  12623. ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
  12624. ssl->options.haveAnon, TRUE, ssl->options.side);
  12625. }
  12626. #ifdef OPENSSL_EXTRA
  12627. /**
  12628. * set call back function for psk session use
  12629. * @param ssl a pointer to WOLFSSL structure
  12630. * @param cb a function pointer to wc_psk_use_session_cb
  12631. * @return none
  12632. */
  12633. void wolfSSL_set_psk_use_session_callback(WOLFSSL* ssl,
  12634. wc_psk_use_session_cb_func cb)
  12635. {
  12636. WOLFSSL_ENTER("wolfSSL_set_psk_use_session_callback");
  12637. ssl->options.havePSK = 1;
  12638. ssl->options.session_psk_cb = cb;
  12639. WOLFSSL_LEAVE("wolfSSL_set_psk_use_session_callback", WOLFSSL_SUCCESS);
  12640. }
  12641. #endif
  12642. void wolfSSL_CTX_set_psk_server_callback(WOLFSSL_CTX* ctx,
  12643. wc_psk_server_callback cb)
  12644. {
  12645. WOLFSSL_ENTER("SSL_CTX_set_psk_server_callback");
  12646. if (ctx == NULL)
  12647. return;
  12648. ctx->havePSK = 1;
  12649. ctx->server_psk_cb = cb;
  12650. }
  12651. void wolfSSL_set_psk_server_callback(WOLFSSL* ssl,wc_psk_server_callback cb)
  12652. {
  12653. byte haveRSA = 1;
  12654. int keySz = 0;
  12655. WOLFSSL_ENTER("SSL_set_psk_server_callback");
  12656. if (ssl == NULL)
  12657. return;
  12658. ssl->options.havePSK = 1;
  12659. ssl->options.server_psk_cb = cb;
  12660. #ifdef NO_RSA
  12661. haveRSA = 0;
  12662. #endif
  12663. #ifndef NO_CERTS
  12664. keySz = ssl->buffers.keySz;
  12665. #endif
  12666. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
  12667. ssl->options.haveDH, ssl->options.haveECDSAsig,
  12668. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  12669. ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
  12670. ssl->options.haveAnon, TRUE, ssl->options.side);
  12671. }
  12672. const char* wolfSSL_get_psk_identity_hint(const WOLFSSL* ssl)
  12673. {
  12674. WOLFSSL_ENTER("SSL_get_psk_identity_hint");
  12675. if (ssl == NULL || ssl->arrays == NULL)
  12676. return NULL;
  12677. return ssl->arrays->server_hint;
  12678. }
  12679. const char* wolfSSL_get_psk_identity(const WOLFSSL* ssl)
  12680. {
  12681. WOLFSSL_ENTER("SSL_get_psk_identity");
  12682. if (ssl == NULL || ssl->arrays == NULL)
  12683. return NULL;
  12684. return ssl->arrays->client_identity;
  12685. }
  12686. int wolfSSL_CTX_use_psk_identity_hint(WOLFSSL_CTX* ctx, const char* hint)
  12687. {
  12688. WOLFSSL_ENTER("SSL_CTX_use_psk_identity_hint");
  12689. if (hint == 0)
  12690. ctx->server_hint[0] = '\0';
  12691. else {
  12692. /* Qt does not call CTX_set_*_psk_callbacks where havePSK is set */
  12693. #ifdef WOLFSSL_QT
  12694. ctx->havePSK=1;
  12695. #endif
  12696. XSTRNCPY(ctx->server_hint, hint, MAX_PSK_ID_LEN);
  12697. ctx->server_hint[MAX_PSK_ID_LEN] = '\0'; /* null term */
  12698. }
  12699. return WOLFSSL_SUCCESS;
  12700. }
  12701. int wolfSSL_use_psk_identity_hint(WOLFSSL* ssl, const char* hint)
  12702. {
  12703. WOLFSSL_ENTER("SSL_use_psk_identity_hint");
  12704. if (ssl == NULL || ssl->arrays == NULL)
  12705. return WOLFSSL_FAILURE;
  12706. if (hint == 0)
  12707. ssl->arrays->server_hint[0] = 0;
  12708. else {
  12709. XSTRNCPY(ssl->arrays->server_hint, hint,
  12710. sizeof(ssl->arrays->server_hint)-1);
  12711. ssl->arrays->server_hint[sizeof(ssl->arrays->server_hint)-1] = '\0';
  12712. }
  12713. return WOLFSSL_SUCCESS;
  12714. }
  12715. void* wolfSSL_get_psk_callback_ctx(WOLFSSL* ssl)
  12716. {
  12717. return ssl ? ssl->options.psk_ctx : NULL;
  12718. }
  12719. void* wolfSSL_CTX_get_psk_callback_ctx(WOLFSSL_CTX* ctx)
  12720. {
  12721. return ctx ? ctx->psk_ctx : NULL;
  12722. }
  12723. int wolfSSL_set_psk_callback_ctx(WOLFSSL* ssl, void* psk_ctx)
  12724. {
  12725. if (ssl == NULL)
  12726. return WOLFSSL_FAILURE;
  12727. ssl->options.psk_ctx = psk_ctx;
  12728. return WOLFSSL_SUCCESS;
  12729. }
  12730. int wolfSSL_CTX_set_psk_callback_ctx(WOLFSSL_CTX* ctx, void* psk_ctx)
  12731. {
  12732. if (ctx == NULL)
  12733. return WOLFSSL_FAILURE;
  12734. ctx->psk_ctx = psk_ctx;
  12735. return WOLFSSL_SUCCESS;
  12736. }
  12737. #endif /* NO_PSK */
  12738. #ifdef HAVE_ANON
  12739. int wolfSSL_CTX_allow_anon_cipher(WOLFSSL_CTX* ctx)
  12740. {
  12741. WOLFSSL_ENTER("wolfSSL_CTX_allow_anon_cipher");
  12742. if (ctx == NULL)
  12743. return WOLFSSL_FAILURE;
  12744. ctx->haveAnon = 1;
  12745. return WOLFSSL_SUCCESS;
  12746. }
  12747. #endif /* HAVE_ANON */
  12748. #ifndef NO_CERTS
  12749. /* used to be defined on NO_FILESYSTEM only, but are generally useful */
  12750. int wolfSSL_CTX_load_verify_buffer_ex(WOLFSSL_CTX* ctx,
  12751. const unsigned char* in,
  12752. long sz, int format, int userChain,
  12753. word32 flags)
  12754. {
  12755. int verify;
  12756. int ret = WOLFSSL_FAILURE;
  12757. WOLFSSL_ENTER("wolfSSL_CTX_load_verify_buffer_ex");
  12758. verify = GET_VERIFY_SETTING_CTX(ctx);
  12759. if (flags & WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY)
  12760. verify = VERIFY_SKIP_DATE;
  12761. if (format == WOLFSSL_FILETYPE_PEM)
  12762. ret = ProcessChainBuffer(ctx, in, sz, format, CA_TYPE, NULL,
  12763. verify);
  12764. else
  12765. ret = ProcessBuffer(ctx, in, sz, format, CA_TYPE, NULL, NULL,
  12766. userChain, verify);
  12767. #if defined(WOLFSSL_TRUST_PEER_CERT) && defined(OPENSSL_COMPATIBLE_DEFAULTS)
  12768. if (ret == WOLFSSL_SUCCESS)
  12769. ret = wolfSSL_CTX_trust_peer_buffer(ctx, in, sz, format);
  12770. #endif
  12771. WOLFSSL_LEAVE("wolfSSL_CTX_load_verify_buffer_ex", ret);
  12772. return ret;
  12773. }
  12774. /* wolfSSL extension allows DER files to be loaded from buffers as well */
  12775. int wolfSSL_CTX_load_verify_buffer(WOLFSSL_CTX* ctx,
  12776. const unsigned char* in,
  12777. long sz, int format)
  12778. {
  12779. return wolfSSL_CTX_load_verify_buffer_ex(ctx, in, sz, format, 0,
  12780. WOLFSSL_LOAD_VERIFY_DEFAULT_FLAGS);
  12781. }
  12782. int wolfSSL_CTX_load_verify_chain_buffer_format(WOLFSSL_CTX* ctx,
  12783. const unsigned char* in,
  12784. long sz, int format)
  12785. {
  12786. return wolfSSL_CTX_load_verify_buffer_ex(ctx, in, sz, format, 1,
  12787. WOLFSSL_LOAD_VERIFY_DEFAULT_FLAGS);
  12788. }
  12789. #ifdef WOLFSSL_TRUST_PEER_CERT
  12790. int wolfSSL_CTX_trust_peer_buffer(WOLFSSL_CTX* ctx,
  12791. const unsigned char* in,
  12792. long sz, int format)
  12793. {
  12794. WOLFSSL_ENTER("wolfSSL_CTX_trust_peer_buffer");
  12795. /* sanity check on arguments */
  12796. if (sz < 0 || in == NULL || ctx == NULL) {
  12797. return BAD_FUNC_ARG;
  12798. }
  12799. if (format == WOLFSSL_FILETYPE_PEM)
  12800. return ProcessChainBuffer(ctx, in, sz, format, TRUSTED_PEER_TYPE,
  12801. NULL, GET_VERIFY_SETTING_CTX(ctx));
  12802. else
  12803. return ProcessBuffer(ctx, in, sz, format, TRUSTED_PEER_TYPE, NULL,
  12804. NULL, 0, GET_VERIFY_SETTING_CTX(ctx));
  12805. }
  12806. #endif /* WOLFSSL_TRUST_PEER_CERT */
  12807. int wolfSSL_CTX_use_certificate_buffer(WOLFSSL_CTX* ctx,
  12808. const unsigned char* in, long sz, int format)
  12809. {
  12810. int ret = WOLFSSL_FAILURE;
  12811. WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_buffer");
  12812. ret = ProcessBuffer(ctx, in, sz, format, CERT_TYPE, NULL, NULL, 0,
  12813. GET_VERIFY_SETTING_CTX(ctx));
  12814. WOLFSSL_LEAVE("wolfSSL_CTX_use_certificate_buffer", ret);
  12815. return ret;
  12816. }
  12817. int wolfSSL_CTX_use_PrivateKey_buffer(WOLFSSL_CTX* ctx,
  12818. const unsigned char* in, long sz, int format)
  12819. {
  12820. int ret = WOLFSSL_FAILURE;
  12821. WOLFSSL_ENTER("wolfSSL_CTX_use_PrivateKey_buffer");
  12822. ret = ProcessBuffer(ctx, in, sz, format, PRIVATEKEY_TYPE, NULL, NULL,
  12823. 0, GET_VERIFY_SETTING_CTX(ctx));
  12824. WOLFSSL_LEAVE("wolfSSL_CTX_use_PrivateKey_buffer", ret);
  12825. return ret;
  12826. }
  12827. #ifdef WOLF_PRIVATE_KEY_ID
  12828. int wolfSSL_CTX_use_PrivateKey_id(WOLFSSL_CTX* ctx, const unsigned char* id,
  12829. long sz, int devId, long keySz)
  12830. {
  12831. int ret = wolfSSL_CTX_use_PrivateKey_Id(ctx, id, sz, devId);
  12832. if (ret == WOLFSSL_SUCCESS)
  12833. ctx->privateKeySz = (word32)keySz;
  12834. return ret;
  12835. }
  12836. int wolfSSL_CTX_use_PrivateKey_Id(WOLFSSL_CTX* ctx, const unsigned char* id,
  12837. long sz, int devId)
  12838. {
  12839. int ret = WOLFSSL_FAILURE;
  12840. FreeDer(&ctx->privateKey);
  12841. if (AllocDer(&ctx->privateKey, (word32)sz, PRIVATEKEY_TYPE,
  12842. ctx->heap) == 0) {
  12843. XMEMCPY(ctx->privateKey->buffer, id, sz);
  12844. ctx->privateKeyId = 1;
  12845. if (devId != INVALID_DEVID)
  12846. ctx->privateKeyDevId = devId;
  12847. else
  12848. ctx->privateKeyDevId = ctx->devId;
  12849. ret = WOLFSSL_SUCCESS;
  12850. }
  12851. return ret;
  12852. }
  12853. int wolfSSL_CTX_use_PrivateKey_Label(WOLFSSL_CTX* ctx, const char* label,
  12854. int devId)
  12855. {
  12856. int ret = WOLFSSL_FAILURE;
  12857. word32 sz = (word32)XSTRLEN(label) + 1;
  12858. FreeDer(&ctx->privateKey);
  12859. if (AllocDer(&ctx->privateKey, (word32)sz, PRIVATEKEY_TYPE,
  12860. ctx->heap) == 0) {
  12861. XMEMCPY(ctx->privateKey->buffer, label, sz);
  12862. ctx->privateKeyLabel = 1;
  12863. if (devId != INVALID_DEVID)
  12864. ctx->privateKeyDevId = devId;
  12865. else
  12866. ctx->privateKeyDevId = ctx->devId;
  12867. ret = WOLFSSL_SUCCESS;
  12868. }
  12869. return ret;
  12870. }
  12871. #endif /* WOLF_PRIVATE_KEY_ID */
  12872. int wolfSSL_CTX_use_certificate_chain_buffer_format(WOLFSSL_CTX* ctx,
  12873. const unsigned char* in, long sz, int format)
  12874. {
  12875. WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_chain_buffer_format");
  12876. return ProcessBuffer(ctx, in, sz, format, CERT_TYPE, NULL, NULL, 1,
  12877. GET_VERIFY_SETTING_CTX(ctx));
  12878. }
  12879. int wolfSSL_CTX_use_certificate_chain_buffer(WOLFSSL_CTX* ctx,
  12880. const unsigned char* in, long sz)
  12881. {
  12882. return wolfSSL_CTX_use_certificate_chain_buffer_format(ctx, in, sz,
  12883. WOLFSSL_FILETYPE_PEM);
  12884. }
  12885. #ifndef NO_DH
  12886. /* server wrapper for ctx or ssl Diffie-Hellman parameters */
  12887. static int wolfSSL_SetTmpDH_buffer_wrapper(WOLFSSL_CTX* ctx, WOLFSSL* ssl,
  12888. const unsigned char* buf,
  12889. long sz, int format)
  12890. {
  12891. DerBuffer* der = NULL;
  12892. int ret = 0;
  12893. word32 pSz = MAX_DH_SIZE;
  12894. word32 gSz = MAX_DH_SIZE;
  12895. #ifdef WOLFSSL_SMALL_STACK
  12896. byte* p = NULL;
  12897. byte* g = NULL;
  12898. #else
  12899. byte p[MAX_DH_SIZE];
  12900. byte g[MAX_DH_SIZE];
  12901. #endif
  12902. if (ctx == NULL || buf == NULL)
  12903. return BAD_FUNC_ARG;
  12904. ret = AllocDer(&der, 0, DH_PARAM_TYPE, ctx->heap);
  12905. if (ret != 0) {
  12906. return ret;
  12907. }
  12908. der->buffer = (byte*)buf;
  12909. der->length = (word32)sz;
  12910. #ifdef WOLFSSL_SMALL_STACK
  12911. p = (byte*)XMALLOC(pSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  12912. g = (byte*)XMALLOC(gSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  12913. if (p == NULL || g == NULL) {
  12914. XFREE(p, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  12915. XFREE(g, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  12916. return MEMORY_E;
  12917. }
  12918. #endif
  12919. if (format != WOLFSSL_FILETYPE_ASN1 && format != WOLFSSL_FILETYPE_PEM)
  12920. ret = WOLFSSL_BAD_FILETYPE;
  12921. else {
  12922. if (format == WOLFSSL_FILETYPE_PEM) {
  12923. #ifdef WOLFSSL_PEM_TO_DER
  12924. FreeDer(&der);
  12925. ret = PemToDer(buf, sz, DH_PARAM_TYPE, &der, ctx->heap,
  12926. NULL, NULL);
  12927. if (ret < 0) {
  12928. /* Also try X9.42 format */
  12929. ret = PemToDer(buf, sz, X942_PARAM_TYPE, &der, ctx->heap,
  12930. NULL, NULL);
  12931. }
  12932. #ifdef WOLFSSL_WPAS
  12933. #ifndef NO_DSA
  12934. if (ret < 0) {
  12935. ret = PemToDer(buf, sz, DSA_PARAM_TYPE, &der, ctx->heap,
  12936. NULL, NULL);
  12937. }
  12938. #endif
  12939. #endif /* WOLFSSL_WPAS */
  12940. #else
  12941. ret = NOT_COMPILED_IN;
  12942. #endif /* WOLFSSL_PEM_TO_DER */
  12943. }
  12944. if (ret == 0) {
  12945. if (wc_DhParamsLoad(der->buffer, der->length, p, &pSz, g, &gSz) < 0)
  12946. ret = WOLFSSL_BAD_FILETYPE;
  12947. else if (ssl)
  12948. ret = wolfSSL_SetTmpDH(ssl, p, pSz, g, gSz);
  12949. else
  12950. ret = wolfSSL_CTX_SetTmpDH(ctx, p, pSz, g, gSz);
  12951. }
  12952. }
  12953. FreeDer(&der);
  12954. #ifdef WOLFSSL_SMALL_STACK
  12955. XFREE(p, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  12956. XFREE(g, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  12957. #endif
  12958. return ret;
  12959. }
  12960. /* server Diffie-Hellman parameters, WOLFSSL_SUCCESS on ok */
  12961. int wolfSSL_SetTmpDH_buffer(WOLFSSL* ssl, const unsigned char* buf, long sz,
  12962. int format)
  12963. {
  12964. if (ssl == NULL)
  12965. return BAD_FUNC_ARG;
  12966. return wolfSSL_SetTmpDH_buffer_wrapper(ssl->ctx, ssl, buf, sz, format);
  12967. }
  12968. /* server ctx Diffie-Hellman parameters, WOLFSSL_SUCCESS on ok */
  12969. int wolfSSL_CTX_SetTmpDH_buffer(WOLFSSL_CTX* ctx, const unsigned char* buf,
  12970. long sz, int format)
  12971. {
  12972. return wolfSSL_SetTmpDH_buffer_wrapper(ctx, NULL, buf, sz, format);
  12973. }
  12974. #endif /* NO_DH */
  12975. int wolfSSL_use_certificate_buffer(WOLFSSL* ssl,
  12976. const unsigned char* in, long sz, int format)
  12977. {
  12978. WOLFSSL_ENTER("wolfSSL_use_certificate_buffer");
  12979. if (ssl == NULL)
  12980. return BAD_FUNC_ARG;
  12981. return ProcessBuffer(ssl->ctx, in, sz, format, CERT_TYPE, ssl, NULL, 0,
  12982. GET_VERIFY_SETTING_SSL(ssl));
  12983. }
  12984. int wolfSSL_use_PrivateKey_buffer(WOLFSSL* ssl,
  12985. const unsigned char* in, long sz, int format)
  12986. {
  12987. WOLFSSL_ENTER("wolfSSL_use_PrivateKey_buffer");
  12988. if (ssl == NULL)
  12989. return BAD_FUNC_ARG;
  12990. return ProcessBuffer(ssl->ctx, in, sz, format, PRIVATEKEY_TYPE,
  12991. ssl, NULL, 0, GET_VERIFY_SETTING_SSL(ssl));
  12992. }
  12993. #ifdef WOLF_PRIVATE_KEY_ID
  12994. int wolfSSL_use_PrivateKey_id(WOLFSSL* ssl, const unsigned char* id,
  12995. long sz, int devId, long keySz)
  12996. {
  12997. int ret = wolfSSL_use_PrivateKey_Id(ssl, id, sz, devId);
  12998. if (ret == WOLFSSL_SUCCESS)
  12999. ssl->buffers.keySz = (word32)keySz;
  13000. return ret;
  13001. }
  13002. int wolfSSL_use_PrivateKey_Id(WOLFSSL* ssl, const unsigned char* id,
  13003. long sz, int devId)
  13004. {
  13005. int ret = WOLFSSL_FAILURE;
  13006. if (ssl->buffers.weOwnKey)
  13007. FreeDer(&ssl->buffers.key);
  13008. if (AllocDer(&ssl->buffers.key, (word32)sz, PRIVATEKEY_TYPE,
  13009. ssl->heap) == 0) {
  13010. XMEMCPY(ssl->buffers.key->buffer, id, sz);
  13011. ssl->buffers.weOwnKey = 1;
  13012. ssl->buffers.keyId = 1;
  13013. if (devId != INVALID_DEVID)
  13014. ssl->buffers.keyDevId = devId;
  13015. else
  13016. ssl->buffers.keyDevId = ssl->devId;
  13017. ret = WOLFSSL_SUCCESS;
  13018. }
  13019. return ret;
  13020. }
  13021. int wolfSSL_use_PrivateKey_Label(WOLFSSL* ssl, const char* label, int devId)
  13022. {
  13023. int ret = WOLFSSL_FAILURE;
  13024. word32 sz = (word32)XSTRLEN(label) + 1;
  13025. if (ssl->buffers.weOwnKey)
  13026. FreeDer(&ssl->buffers.key);
  13027. if (AllocDer(&ssl->buffers.key, (word32)sz, PRIVATEKEY_TYPE,
  13028. ssl->heap) == 0) {
  13029. XMEMCPY(ssl->buffers.key->buffer, label, sz);
  13030. ssl->buffers.weOwnKey = 1;
  13031. ssl->buffers.keyLabel = 1;
  13032. if (devId != INVALID_DEVID)
  13033. ssl->buffers.keyDevId = devId;
  13034. else
  13035. ssl->buffers.keyDevId = ssl->devId;
  13036. ret = WOLFSSL_SUCCESS;
  13037. }
  13038. return ret;
  13039. }
  13040. #endif /* WOLF_PRIVATE_KEY_ID */
  13041. int wolfSSL_use_certificate_chain_buffer_format(WOLFSSL* ssl,
  13042. const unsigned char* in, long sz, int format)
  13043. {
  13044. WOLFSSL_ENTER("wolfSSL_use_certificate_chain_buffer_format");
  13045. if (ssl == NULL)
  13046. return BAD_FUNC_ARG;
  13047. return ProcessBuffer(ssl->ctx, in, sz, format, CERT_TYPE,
  13048. ssl, NULL, 1, GET_VERIFY_SETTING_SSL(ssl));
  13049. }
  13050. int wolfSSL_use_certificate_chain_buffer(WOLFSSL* ssl,
  13051. const unsigned char* in, long sz)
  13052. {
  13053. return wolfSSL_use_certificate_chain_buffer_format(ssl, in, sz,
  13054. WOLFSSL_FILETYPE_PEM);
  13055. }
  13056. /* unload any certs or keys that SSL owns, leave CTX as is
  13057. WOLFSSL_SUCCESS on ok */
  13058. int wolfSSL_UnloadCertsKeys(WOLFSSL* ssl)
  13059. {
  13060. if (ssl == NULL) {
  13061. WOLFSSL_MSG("Null function arg");
  13062. return BAD_FUNC_ARG;
  13063. }
  13064. if (ssl->buffers.weOwnCert && !ssl->keepCert) {
  13065. WOLFSSL_MSG("Unloading cert");
  13066. FreeDer(&ssl->buffers.certificate);
  13067. #ifdef KEEP_OUR_CERT
  13068. wolfSSL_X509_free(ssl->ourCert);
  13069. ssl->ourCert = NULL;
  13070. #endif
  13071. ssl->buffers.weOwnCert = 0;
  13072. }
  13073. if (ssl->buffers.weOwnCertChain) {
  13074. WOLFSSL_MSG("Unloading cert chain");
  13075. FreeDer(&ssl->buffers.certChain);
  13076. ssl->buffers.weOwnCertChain = 0;
  13077. }
  13078. if (ssl->buffers.weOwnKey) {
  13079. WOLFSSL_MSG("Unloading key");
  13080. ForceZero(ssl->buffers.key->buffer, ssl->buffers.key->length);
  13081. FreeDer(&ssl->buffers.key);
  13082. ssl->buffers.weOwnKey = 0;
  13083. }
  13084. return WOLFSSL_SUCCESS;
  13085. }
  13086. int wolfSSL_CTX_UnloadCAs(WOLFSSL_CTX* ctx)
  13087. {
  13088. WOLFSSL_ENTER("wolfSSL_CTX_UnloadCAs");
  13089. if (ctx == NULL)
  13090. return BAD_FUNC_ARG;
  13091. return wolfSSL_CertManagerUnloadCAs(ctx->cm);
  13092. }
  13093. #ifdef WOLFSSL_TRUST_PEER_CERT
  13094. int wolfSSL_CTX_Unload_trust_peers(WOLFSSL_CTX* ctx)
  13095. {
  13096. WOLFSSL_ENTER("wolfSSL_CTX_Unload_trust_peers");
  13097. if (ctx == NULL)
  13098. return BAD_FUNC_ARG;
  13099. return wolfSSL_CertManagerUnload_trust_peers(ctx->cm);
  13100. }
  13101. #ifdef WOLFSSL_LOCAL_X509_STORE
  13102. int wolfSSL_Unload_trust_peers(WOLFSSL* ssl)
  13103. {
  13104. WOLFSSL_ENTER("wolfSSL_CTX_Unload_trust_peers");
  13105. if (ssl == NULL)
  13106. return BAD_FUNC_ARG;
  13107. return wolfSSL_CertManagerUnload_trust_peers(SSL_CM(ssl));
  13108. }
  13109. #endif /* WOLFSSL_LOCAL_X509_STORE */
  13110. #endif /* WOLFSSL_TRUST_PEER_CERT */
  13111. /* old NO_FILESYSTEM end */
  13112. #endif /* !NO_CERTS */
  13113. #ifdef OPENSSL_EXTRA
  13114. int wolfSSL_add_all_algorithms(void)
  13115. {
  13116. WOLFSSL_ENTER("wolfSSL_add_all_algorithms");
  13117. if (initRefCount != 0 || wolfSSL_Init() == WOLFSSL_SUCCESS)
  13118. return WOLFSSL_SUCCESS;
  13119. else
  13120. return WOLFSSL_FATAL_ERROR;
  13121. }
  13122. int wolfSSL_OpenSSL_add_all_algorithms_noconf(void)
  13123. {
  13124. WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_noconf");
  13125. if (wolfSSL_add_all_algorithms() == WOLFSSL_FATAL_ERROR)
  13126. return WOLFSSL_FATAL_ERROR;
  13127. return WOLFSSL_SUCCESS;
  13128. }
  13129. int wolfSSL_OpenSSL_add_all_algorithms_conf(void)
  13130. {
  13131. WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_conf");
  13132. /* This function is currently the same as
  13133. wolfSSL_OpenSSL_add_all_algorithms_noconf since we do not employ
  13134. the use of a wolfssl.cnf type configuration file and is only used for
  13135. OpenSSL compatability. */
  13136. if (wolfSSL_add_all_algorithms() == WOLFSSL_FATAL_ERROR) {
  13137. return WOLFSSL_FATAL_ERROR;
  13138. }
  13139. return WOLFSSL_SUCCESS;
  13140. }
  13141. /* returns previous set cache size which stays constant */
  13142. long wolfSSL_CTX_sess_set_cache_size(WOLFSSL_CTX* ctx, long sz)
  13143. {
  13144. /* cache size fixed at compile time in wolfSSL */
  13145. (void)ctx;
  13146. (void)sz;
  13147. WOLFSSL_MSG("session cache is set at compile time");
  13148. #ifndef NO_SESSION_CACHE
  13149. return (long)(SESSIONS_PER_ROW * SESSION_ROWS);
  13150. #else
  13151. return 0;
  13152. #endif
  13153. }
  13154. #endif
  13155. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  13156. void wolfSSL_CTX_set_quiet_shutdown(WOLFSSL_CTX* ctx, int mode)
  13157. {
  13158. WOLFSSL_ENTER("wolfSSL_CTX_set_quiet_shutdown");
  13159. if (mode)
  13160. ctx->quietShutdown = 1;
  13161. }
  13162. void wolfSSL_set_quiet_shutdown(WOLFSSL* ssl, int mode)
  13163. {
  13164. WOLFSSL_ENTER("wolfSSL_CTX_set_quiet_shutdown");
  13165. if (mode)
  13166. ssl->options.quietShutdown = 1;
  13167. }
  13168. #endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  13169. #ifdef OPENSSL_EXTRA
  13170. #ifndef NO_BIO
  13171. void wolfSSL_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr)
  13172. {
  13173. WOLFSSL_ENTER("wolfSSL_set_bio");
  13174. if (ssl == NULL) {
  13175. WOLFSSL_MSG("Bad argument, ssl was NULL");
  13176. return;
  13177. }
  13178. /* free any existing WOLFSSL_BIOs in use but don't free those in
  13179. * a chain */
  13180. if (ssl->biord != NULL) {
  13181. if (ssl->biord != ssl->biowr) {
  13182. if (ssl->biowr != NULL && ssl->biowr->prev != NULL)
  13183. wolfSSL_BIO_free(ssl->biowr);
  13184. ssl->biowr = NULL;
  13185. }
  13186. if (ssl->biord->prev != NULL)
  13187. wolfSSL_BIO_free(ssl->biord);
  13188. ssl->biord = NULL;
  13189. }
  13190. /* set flag obviously */
  13191. if (rd && !(rd->flags & WOLFSSL_BIO_FLAG_READ))
  13192. rd->flags |= WOLFSSL_BIO_FLAG_READ;
  13193. if (wr && !(wr->flags & WOLFSSL_BIO_FLAG_WRITE))
  13194. wr->flags |= WOLFSSL_BIO_FLAG_WRITE;
  13195. ssl->biord = rd;
  13196. ssl->biowr = wr;
  13197. /* set SSL to use BIO callbacks instead */
  13198. if (((ssl->cbioFlag & WOLFSSL_CBIO_RECV) == 0)) {
  13199. ssl->CBIORecv = BioReceive;
  13200. }
  13201. if (((ssl->cbioFlag & WOLFSSL_CBIO_SEND) == 0)) {
  13202. ssl->CBIOSend = BioSend;
  13203. }
  13204. /* User programs should always retry reading from these BIOs */
  13205. if (rd) {
  13206. /* User writes to rd */
  13207. BIO_set_retry_write(rd);
  13208. }
  13209. if (wr) {
  13210. /* User reads from wr */
  13211. BIO_set_retry_read(wr);
  13212. }
  13213. }
  13214. #endif /* !NO_BIO */
  13215. #endif /* OPENSSL_EXTRA */
  13216. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA)
  13217. void wolfSSL_CTX_set_client_CA_list(WOLFSSL_CTX* ctx,
  13218. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names)
  13219. {
  13220. WOLFSSL_ENTER("wolfSSL_CTX_set_client_CA_list");
  13221. if (ctx != NULL) {
  13222. wolfSSL_sk_X509_NAME_pop_free(ctx->ca_names, NULL);
  13223. ctx->ca_names = names;
  13224. }
  13225. }
  13226. void wolfSSL_set_client_CA_list(WOLFSSL* ssl,
  13227. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names)
  13228. {
  13229. WOLFSSL_ENTER("wolfSSL_set_client_CA_list");
  13230. if (ssl != NULL) {
  13231. if (ssl->ca_names != ssl->ctx->ca_names)
  13232. wolfSSL_sk_X509_NAME_pop_free(ssl->ca_names, NULL);
  13233. ssl->ca_names = names;
  13234. }
  13235. }
  13236. #ifdef OPENSSL_EXTRA
  13237. /* registers client cert callback, called during handshake if server
  13238. requests client auth but user has not loaded client cert/key */
  13239. void wolfSSL_CTX_set_client_cert_cb(WOLFSSL_CTX *ctx, client_cert_cb cb)
  13240. {
  13241. WOLFSSL_ENTER("wolfSSL_CTX_set_client_cert_cb");
  13242. if (ctx != NULL) {
  13243. ctx->CBClientCert = cb;
  13244. }
  13245. }
  13246. void wolfSSL_CTX_set_cert_cb(WOLFSSL_CTX* ctx,
  13247. CertSetupCallback cb, void *arg)
  13248. {
  13249. WOLFSSL_ENTER("wolfSSL_CTX_set_cert_cb");
  13250. if (ctx == NULL)
  13251. return;
  13252. ctx->certSetupCb = cb;
  13253. ctx->certSetupCbArg = arg;
  13254. }
  13255. /**
  13256. * Internal wrapper for calling certSetupCb
  13257. * @param ssl The SSL/TLS Object
  13258. * @return 0 on success
  13259. */
  13260. int CertSetupCbWrapper(WOLFSSL* ssl)
  13261. {
  13262. int ret = 0;
  13263. if (ssl->ctx->certSetupCb != NULL) {
  13264. WOLFSSL_MSG("Calling user cert setup callback");
  13265. ret = ssl->ctx->certSetupCb(ssl, ssl->ctx->certSetupCbArg);
  13266. if (ret == 1) {
  13267. WOLFSSL_MSG("User cert callback returned success");
  13268. ret = 0;
  13269. }
  13270. else if (ret == 0) {
  13271. SendAlert(ssl, alert_fatal, internal_error);
  13272. ret = CLIENT_CERT_CB_ERROR;
  13273. }
  13274. else if (ret < 0) {
  13275. ret = WOLFSSL_ERROR_WANT_X509_LOOKUP;
  13276. }
  13277. else {
  13278. WOLFSSL_MSG("Unexpected user callback return");
  13279. ret = CLIENT_CERT_CB_ERROR;
  13280. }
  13281. }
  13282. return ret;
  13283. }
  13284. #endif /* OPENSSL_EXTRA */
  13285. #endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || HAVE_WEBSERVER */
  13286. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA)
  13287. WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_CTX_get_client_CA_list(
  13288. const WOLFSSL_CTX *ctx)
  13289. {
  13290. WOLFSSL_ENTER("wolfSSL_CTX_get_client_CA_list");
  13291. if (ctx == NULL) {
  13292. WOLFSSL_MSG("Bad argument passed to wolfSSL_CTX_get_client_CA_list");
  13293. return NULL;
  13294. }
  13295. return ctx->ca_names;
  13296. }
  13297. /* returns the CA's set on server side or the CA's sent from server when
  13298. * on client side */
  13299. WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_get_client_CA_list(
  13300. const WOLFSSL* ssl)
  13301. {
  13302. WOLFSSL_ENTER("wolfSSL_get_client_CA_list");
  13303. if (ssl == NULL) {
  13304. WOLFSSL_MSG("Bad argument passed to wolfSSL_get_client_CA_list");
  13305. return NULL;
  13306. }
  13307. return SSL_CA_NAMES(ssl);
  13308. }
  13309. #if !defined(NO_CERTS)
  13310. int wolfSSL_CTX_add_client_CA(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509)
  13311. {
  13312. WOLFSSL_X509_NAME *nameCopy = NULL;
  13313. WOLFSSL_ENTER("wolfSSL_CTX_add_client_CA");
  13314. if (ctx == NULL || x509 == NULL){
  13315. WOLFSSL_MSG("Bad argument");
  13316. return WOLFSSL_FAILURE;
  13317. }
  13318. if (ctx->ca_names == NULL) {
  13319. ctx->ca_names = wolfSSL_sk_X509_NAME_new(NULL);
  13320. if (ctx->ca_names == NULL) {
  13321. WOLFSSL_MSG("wolfSSL_sk_X509_NAME_new error");
  13322. return WOLFSSL_FAILURE;
  13323. }
  13324. }
  13325. nameCopy = wolfSSL_X509_NAME_dup(wolfSSL_X509_get_subject_name(x509));
  13326. if (nameCopy == NULL) {
  13327. WOLFSSL_MSG("wolfSSL_X509_NAME_dup error");
  13328. return WOLFSSL_FAILURE;
  13329. }
  13330. if (wolfSSL_sk_X509_NAME_push(ctx->ca_names, nameCopy) != WOLFSSL_SUCCESS) {
  13331. WOLFSSL_MSG("wolfSSL_sk_X509_NAME_push error");
  13332. wolfSSL_X509_NAME_free(nameCopy);
  13333. return WOLFSSL_FAILURE;
  13334. }
  13335. return WOLFSSL_SUCCESS;
  13336. }
  13337. #endif
  13338. #ifndef NO_BIO
  13339. #if !defined(NO_RSA) && !defined(NO_CERTS)
  13340. WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_load_client_CA_file(const char* fname)
  13341. {
  13342. /* The webserver build is using this to load a CA into the server
  13343. * for client authentication as an option. Have this return NULL in
  13344. * that case. If OPENSSL_EXTRA is enabled, go ahead and include
  13345. * the function. */
  13346. #ifdef OPENSSL_EXTRA
  13347. WOLFSSL_STACK *list = NULL;
  13348. WOLFSSL_BIO* bio = NULL;
  13349. WOLFSSL_X509 *cert = NULL;
  13350. WOLFSSL_X509_NAME *nameCopy = NULL;
  13351. unsigned long err = WOLFSSL_FAILURE;
  13352. WOLFSSL_ENTER("wolfSSL_load_client_CA_file");
  13353. bio = wolfSSL_BIO_new_file(fname, "rb");
  13354. if (bio == NULL) {
  13355. WOLFSSL_MSG("wolfSSL_BIO_new_file error");
  13356. goto cleanup;
  13357. }
  13358. list = wolfSSL_sk_X509_NAME_new(NULL);
  13359. if (list == NULL) {
  13360. WOLFSSL_MSG("wolfSSL_sk_X509_NAME_new error");
  13361. goto cleanup;
  13362. }
  13363. /* Read each certificate in the chain out of the file. */
  13364. while (wolfSSL_PEM_read_bio_X509(bio, &cert, NULL, NULL) != NULL) {
  13365. /* Need a persistent copy of the subject name. */
  13366. nameCopy = wolfSSL_X509_NAME_dup(
  13367. wolfSSL_X509_get_subject_name(cert));
  13368. if (nameCopy == NULL) {
  13369. WOLFSSL_MSG("wolfSSL_X509_NAME_dup error");
  13370. goto cleanup;
  13371. }
  13372. /*
  13373. * Original cert will be freed so make sure not to try to access
  13374. * it in the future.
  13375. */
  13376. nameCopy->x509 = NULL;
  13377. if (wolfSSL_sk_X509_NAME_push(list, nameCopy) !=
  13378. WOLFSSL_SUCCESS) {
  13379. WOLFSSL_MSG("wolfSSL_sk_X509_NAME_push error");
  13380. /* Do free in loop because nameCopy is now responsibility
  13381. * of list to free and adding jumps to cleanup after this
  13382. * might result in a double free. */
  13383. wolfSSL_X509_NAME_free(nameCopy);
  13384. goto cleanup;
  13385. }
  13386. wolfSSL_X509_free(cert);
  13387. cert = NULL;
  13388. }
  13389. CLEAR_ASN_NO_PEM_HEADER_ERROR(err);
  13390. err = WOLFSSL_SUCCESS;
  13391. cleanup:
  13392. wolfSSL_X509_free(cert);
  13393. wolfSSL_BIO_free(bio);
  13394. if (err != WOLFSSL_SUCCESS) {
  13395. /* We failed so return NULL */
  13396. wolfSSL_sk_X509_NAME_pop_free(list, NULL);
  13397. list = NULL;
  13398. }
  13399. return list;
  13400. #else
  13401. (void)fname;
  13402. return NULL;
  13403. #endif
  13404. }
  13405. #endif
  13406. #endif /* !NO_BIO */
  13407. #endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA */
  13408. #ifdef OPENSSL_EXTRA
  13409. #ifndef NO_WOLFSSL_STUB
  13410. int wolfSSL_CTX_set_default_verify_paths(WOLFSSL_CTX* ctx)
  13411. {
  13412. /* TODO:, not needed in goahead */
  13413. (void)ctx;
  13414. WOLFSSL_STUB("SSL_CTX_set_default_verify_paths");
  13415. return SSL_NOT_IMPLEMENTED;
  13416. }
  13417. #endif
  13418. #if defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256) \
  13419. && !defined(WC_NO_RNG)
  13420. static const byte srp_N[] = {
  13421. 0xEE, 0xAF, 0x0A, 0xB9, 0xAD, 0xB3, 0x8D, 0xD6, 0x9C, 0x33, 0xF8,
  13422. 0x0A, 0xFA, 0x8F, 0xC5, 0xE8, 0x60, 0x72, 0x61, 0x87, 0x75, 0xFF,
  13423. 0x3C, 0x0B, 0x9E, 0xA2, 0x31, 0x4C, 0x9C, 0x25, 0x65, 0x76, 0xD6,
  13424. 0x74, 0xDF, 0x74, 0x96, 0xEA, 0x81, 0xD3, 0x38, 0x3B, 0x48, 0x13,
  13425. 0xD6, 0x92, 0xC6, 0xE0, 0xE0, 0xD5, 0xD8, 0xE2, 0x50, 0xB9, 0x8B,
  13426. 0xE4, 0x8E, 0x49, 0x5C, 0x1D, 0x60, 0x89, 0xDA, 0xD1, 0x5D, 0xC7,
  13427. 0xD7, 0xB4, 0x61, 0x54, 0xD6, 0xB6, 0xCE, 0x8E, 0xF4, 0xAD, 0x69,
  13428. 0xB1, 0x5D, 0x49, 0x82, 0x55, 0x9B, 0x29, 0x7B, 0xCF, 0x18, 0x85,
  13429. 0xC5, 0x29, 0xF5, 0x66, 0x66, 0x0E, 0x57, 0xEC, 0x68, 0xED, 0xBC,
  13430. 0x3C, 0x05, 0x72, 0x6C, 0xC0, 0x2F, 0xD4, 0xCB, 0xF4, 0x97, 0x6E,
  13431. 0xAA, 0x9A, 0xFD, 0x51, 0x38, 0xFE, 0x83, 0x76, 0x43, 0x5B, 0x9F,
  13432. 0xC6, 0x1D, 0x2F, 0xC0, 0xEB, 0x06, 0xE3
  13433. };
  13434. static const byte srp_g[] = {
  13435. 0x02
  13436. };
  13437. int wolfSSL_CTX_set_srp_username(WOLFSSL_CTX* ctx, char* username)
  13438. {
  13439. int r = 0;
  13440. SrpSide srp_side = SRP_CLIENT_SIDE;
  13441. byte salt[SRP_SALT_SIZE];
  13442. WOLFSSL_ENTER("wolfSSL_CTX_set_srp_username");
  13443. if (ctx == NULL || ctx->srp == NULL || username==NULL)
  13444. return SSL_FAILURE;
  13445. if (ctx->method->side == WOLFSSL_SERVER_END){
  13446. srp_side = SRP_SERVER_SIDE;
  13447. } else if (ctx->method->side == WOLFSSL_CLIENT_END){
  13448. srp_side = SRP_CLIENT_SIDE;
  13449. } else {
  13450. WOLFSSL_MSG("Init CTX failed");
  13451. return SSL_FAILURE;
  13452. }
  13453. if (wc_SrpInit(ctx->srp, SRP_TYPE_SHA256, srp_side) < 0) {
  13454. WOLFSSL_MSG("Init SRP CTX failed");
  13455. XFREE(ctx->srp, ctx->heap, DYNAMIC_TYPE_SRP);
  13456. ctx->srp = NULL;
  13457. return SSL_FAILURE;
  13458. }
  13459. r = wc_SrpSetUsername(ctx->srp, (const byte*)username,
  13460. (word32)XSTRLEN(username));
  13461. if (r < 0) {
  13462. WOLFSSL_MSG("fail to set srp username.");
  13463. return SSL_FAILURE;
  13464. }
  13465. /* if wolfSSL_CTX_set_srp_password has already been called, */
  13466. /* execute wc_SrpSetPassword here */
  13467. if (ctx->srp_password != NULL) {
  13468. WC_RNG rng;
  13469. if (wc_InitRng(&rng) < 0){
  13470. WOLFSSL_MSG("wc_InitRng failed");
  13471. return SSL_FAILURE;
  13472. }
  13473. XMEMSET(salt, 0, sizeof(salt)/sizeof(salt[0]));
  13474. r = wc_RNG_GenerateBlock(&rng, salt, sizeof(salt)/sizeof(salt[0]));
  13475. wc_FreeRng(&rng);
  13476. if (r < 0) {
  13477. WOLFSSL_MSG("wc_RNG_GenerateBlock failed");
  13478. return SSL_FAILURE;
  13479. }
  13480. if (wc_SrpSetParams(ctx->srp, srp_N, sizeof(srp_N)/sizeof(srp_N[0]),
  13481. srp_g, sizeof(srp_g)/sizeof(srp_g[0]),
  13482. salt, sizeof(salt)/sizeof(salt[0])) < 0) {
  13483. WOLFSSL_MSG("wc_SrpSetParam failed");
  13484. return SSL_FAILURE;
  13485. }
  13486. r = wc_SrpSetPassword(ctx->srp,
  13487. (const byte*)ctx->srp_password,
  13488. (word32)XSTRLEN((char *)ctx->srp_password));
  13489. if (r < 0) {
  13490. WOLFSSL_MSG("fail to set srp password.");
  13491. return SSL_FAILURE;
  13492. }
  13493. XFREE(ctx->srp_password, ctx->heap, DYNAMIC_TYPE_SRP);
  13494. ctx->srp_password = NULL;
  13495. }
  13496. return WOLFSSL_SUCCESS;
  13497. }
  13498. int wolfSSL_CTX_set_srp_password(WOLFSSL_CTX* ctx, char* password)
  13499. {
  13500. int r;
  13501. byte salt[SRP_SALT_SIZE];
  13502. WOLFSSL_ENTER("wolfSSL_CTX_set_srp_password");
  13503. if (ctx == NULL || ctx->srp == NULL || password == NULL)
  13504. return SSL_FAILURE;
  13505. if (ctx->srp->user != NULL) {
  13506. WC_RNG rng;
  13507. if (wc_InitRng(&rng) < 0) {
  13508. WOLFSSL_MSG("wc_InitRng failed");
  13509. return SSL_FAILURE;
  13510. }
  13511. XMEMSET(salt, 0, sizeof(salt)/sizeof(salt[0]));
  13512. r = wc_RNG_GenerateBlock(&rng, salt, sizeof(salt)/sizeof(salt[0]));
  13513. wc_FreeRng(&rng);
  13514. if (r < 0) {
  13515. WOLFSSL_MSG("wc_RNG_GenerateBlock failed");
  13516. return SSL_FAILURE;
  13517. }
  13518. if (wc_SrpSetParams(ctx->srp, srp_N, sizeof(srp_N)/sizeof(srp_N[0]),
  13519. srp_g, sizeof(srp_g)/sizeof(srp_g[0]),
  13520. salt, sizeof(salt)/sizeof(salt[0])) < 0){
  13521. WOLFSSL_MSG("wc_SrpSetParam failed");
  13522. wc_FreeRng(&rng);
  13523. return SSL_FAILURE;
  13524. }
  13525. r = wc_SrpSetPassword(ctx->srp, (const byte*)password,
  13526. (word32)XSTRLEN(password));
  13527. if (r < 0) {
  13528. WOLFSSL_MSG("wc_SrpSetPassword failed.");
  13529. wc_FreeRng(&rng);
  13530. return SSL_FAILURE;
  13531. }
  13532. if (ctx->srp_password != NULL){
  13533. XFREE(ctx->srp_password,NULL,
  13534. DYNAMIC_TYPE_SRP);
  13535. ctx->srp_password = NULL;
  13536. }
  13537. wc_FreeRng(&rng);
  13538. } else {
  13539. /* save password for wolfSSL_set_srp_username */
  13540. if (ctx->srp_password != NULL)
  13541. XFREE(ctx->srp_password,ctx->heap, DYNAMIC_TYPE_SRP);
  13542. ctx->srp_password = (byte*)XMALLOC(XSTRLEN(password) + 1, ctx->heap,
  13543. DYNAMIC_TYPE_SRP);
  13544. if (ctx->srp_password == NULL){
  13545. WOLFSSL_MSG("memory allocation error");
  13546. return SSL_FAILURE;
  13547. }
  13548. XMEMCPY(ctx->srp_password, password, XSTRLEN(password) + 1);
  13549. }
  13550. return WOLFSSL_SUCCESS;
  13551. }
  13552. /**
  13553. * The modulus passed to wc_SrpSetParams in ssl.c is constant so check
  13554. * that the requested strength is less than or equal to the size of the
  13555. * static modulus size.
  13556. * @param ctx Not used
  13557. * @param strength Minimum number of bits for the modulus
  13558. * @return 1 if strength is less than or equal to static modulus
  13559. * 0 if strength is greater than static modulus
  13560. */
  13561. int wolfSSL_CTX_set_srp_strength(WOLFSSL_CTX *ctx, int strength)
  13562. {
  13563. (void)ctx;
  13564. WOLFSSL_ENTER("wolfSSL_CTX_set_srp_strength");
  13565. if (strength > (int)(sizeof(srp_N)*8)) {
  13566. WOLFSSL_MSG("Bad Parameter");
  13567. return WOLFSSL_FAILURE;
  13568. }
  13569. return WOLFSSL_SUCCESS;
  13570. }
  13571. char* wolfSSL_get_srp_username(WOLFSSL *ssl)
  13572. {
  13573. if (ssl && ssl->ctx && ssl->ctx->srp) {
  13574. return (char*) ssl->ctx->srp->user;
  13575. }
  13576. return NULL;
  13577. }
  13578. #endif /* WOLFCRYPT_HAVE_SRP && !NO_SHA256 && !WC_NO_RNG */
  13579. /* keyblock size in bytes or -1 */
  13580. int wolfSSL_get_keyblock_size(WOLFSSL* ssl)
  13581. {
  13582. if (ssl == NULL)
  13583. return WOLFSSL_FATAL_ERROR;
  13584. return 2 * (ssl->specs.key_size + ssl->specs.iv_size +
  13585. ssl->specs.hash_size);
  13586. }
  13587. #endif /* OPENSSL_EXTRA */
  13588. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  13589. /* store keys returns WOLFSSL_SUCCESS or -1 on error */
  13590. int wolfSSL_get_keys(WOLFSSL* ssl, unsigned char** ms, unsigned int* msLen,
  13591. unsigned char** sr, unsigned int* srLen,
  13592. unsigned char** cr, unsigned int* crLen)
  13593. {
  13594. if (ssl == NULL || ssl->arrays == NULL)
  13595. return WOLFSSL_FATAL_ERROR;
  13596. *ms = ssl->arrays->masterSecret;
  13597. *sr = ssl->arrays->serverRandom;
  13598. *cr = ssl->arrays->clientRandom;
  13599. *msLen = SECRET_LEN;
  13600. *srLen = RAN_LEN;
  13601. *crLen = RAN_LEN;
  13602. return WOLFSSL_SUCCESS;
  13603. }
  13604. void wolfSSL_set_accept_state(WOLFSSL* ssl)
  13605. {
  13606. WOLFSSL_ENTER("wolfSSL_set_accept_state");
  13607. if (ssl == NULL)
  13608. return;
  13609. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  13610. #ifdef HAVE_ECC
  13611. #ifdef WOLFSSL_SMALL_STACK
  13612. ecc_key* key = NULL;
  13613. #else
  13614. ecc_key key[1];
  13615. #endif
  13616. word32 idx = 0;
  13617. #ifdef WOLFSSL_SMALL_STACK
  13618. key = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap,
  13619. DYNAMIC_TYPE_ECC);
  13620. if (key == NULL) {
  13621. WOLFSSL_MSG("Error allocating memory for ecc_key");
  13622. }
  13623. #endif
  13624. if (ssl->options.haveStaticECC && ssl->buffers.key != NULL) {
  13625. if (wc_ecc_init(key) >= 0) {
  13626. if (wc_EccPrivateKeyDecode(ssl->buffers.key->buffer, &idx,
  13627. key, ssl->buffers.key->length) != 0) {
  13628. ssl->options.haveECDSAsig = 0;
  13629. ssl->options.haveECC = 0;
  13630. ssl->options.haveStaticECC = 0;
  13631. }
  13632. wc_ecc_free(key);
  13633. }
  13634. }
  13635. #ifdef WOLFSSL_SMALL_STACK
  13636. XFREE(key, ssl->heap, DYNAMIC_TYPE_ECC);
  13637. #endif
  13638. #endif
  13639. #ifndef NO_DH
  13640. if (!ssl->options.haveDH && ssl->ctx->haveDH) {
  13641. ssl->buffers.serverDH_P = ssl->ctx->serverDH_P;
  13642. ssl->buffers.serverDH_G = ssl->ctx->serverDH_G;
  13643. ssl->options.haveDH = 1;
  13644. }
  13645. #endif
  13646. }
  13647. if (InitSSL_Side(ssl, WOLFSSL_SERVER_END) != WOLFSSL_SUCCESS) {
  13648. WOLFSSL_MSG("Error initializing server side");
  13649. }
  13650. }
  13651. #endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  13652. /* return true if connection established */
  13653. int wolfSSL_is_init_finished(WOLFSSL* ssl)
  13654. {
  13655. if (ssl == NULL)
  13656. return 0;
  13657. if (ssl->options.handShakeState == HANDSHAKE_DONE)
  13658. return 1;
  13659. return 0;
  13660. }
  13661. #ifdef OPENSSL_EXTRA
  13662. void wolfSSL_CTX_set_tmp_rsa_callback(WOLFSSL_CTX* ctx,
  13663. WOLFSSL_RSA*(*f)(WOLFSSL*, int, int))
  13664. {
  13665. /* wolfSSL verifies all these internally */
  13666. (void)ctx;
  13667. (void)f;
  13668. }
  13669. void wolfSSL_set_shutdown(WOLFSSL* ssl, int opt)
  13670. {
  13671. WOLFSSL_ENTER("wolfSSL_set_shutdown");
  13672. if(ssl==NULL) {
  13673. WOLFSSL_MSG("Shutdown not set. ssl is null");
  13674. return;
  13675. }
  13676. ssl->options.sentNotify = (opt&WOLFSSL_SENT_SHUTDOWN) > 0;
  13677. ssl->options.closeNotify = (opt&WOLFSSL_RECEIVED_SHUTDOWN) > 0;
  13678. }
  13679. #endif
  13680. long wolfSSL_CTX_get_options(WOLFSSL_CTX* ctx)
  13681. {
  13682. WOLFSSL_ENTER("wolfSSL_CTX_get_options");
  13683. WOLFSSL_MSG("wolfSSL options are set through API calls and macros");
  13684. if(ctx == NULL)
  13685. return BAD_FUNC_ARG;
  13686. return ctx->mask;
  13687. }
  13688. static long wolf_set_options(long old_op, long op);
  13689. long wolfSSL_CTX_set_options(WOLFSSL_CTX* ctx, long opt)
  13690. {
  13691. WOLFSSL_ENTER("SSL_CTX_set_options");
  13692. if (ctx == NULL)
  13693. return BAD_FUNC_ARG;
  13694. ctx->mask = wolf_set_options(ctx->mask, opt);
  13695. return ctx->mask;
  13696. }
  13697. long wolfSSL_CTX_clear_options(WOLFSSL_CTX* ctx, long opt)
  13698. {
  13699. WOLFSSL_ENTER("SSL_CTX_clear_options");
  13700. if(ctx == NULL)
  13701. return BAD_FUNC_ARG;
  13702. ctx->mask &= ~opt;
  13703. return ctx->mask;
  13704. }
  13705. #ifdef OPENSSL_EXTRA
  13706. int wolfSSL_set_rfd(WOLFSSL* ssl, int rfd)
  13707. {
  13708. WOLFSSL_ENTER("SSL_set_rfd");
  13709. ssl->rfd = rfd; /* not used directly to allow IO callbacks */
  13710. ssl->IOCB_ReadCtx = &ssl->rfd;
  13711. #ifdef WOLFSSL_DTLS
  13712. if (ssl->options.dtls) {
  13713. ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx;
  13714. ssl->buffers.dtlsCtx.rfd = rfd;
  13715. }
  13716. #endif
  13717. return WOLFSSL_SUCCESS;
  13718. }
  13719. int wolfSSL_set_wfd(WOLFSSL* ssl, int wfd)
  13720. {
  13721. WOLFSSL_ENTER("SSL_set_wfd");
  13722. ssl->wfd = wfd; /* not used directly to allow IO callbacks */
  13723. ssl->IOCB_WriteCtx = &ssl->wfd;
  13724. return WOLFSSL_SUCCESS;
  13725. }
  13726. #endif /* OPENSSL_EXTRA */
  13727. #if !defined(NO_CERTS) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL))
  13728. #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
  13729. /**
  13730. * Implemented in a similar way that ngx_ssl_ocsp_validate does it when
  13731. * SSL_get0_verified_chain is not available.
  13732. * @param ssl WOLFSSL object to extract certs from
  13733. * @return Stack of verified certs
  13734. */
  13735. WOLF_STACK_OF(WOLFSSL_X509) *wolfSSL_get0_verified_chain(const WOLFSSL *ssl)
  13736. {
  13737. WOLF_STACK_OF(WOLFSSL_X509)* chain = NULL;
  13738. WOLFSSL_X509_STORE_CTX* storeCtx = NULL;
  13739. WOLFSSL_X509* peerCert = NULL;
  13740. WOLFSSL_ENTER("wolfSSL_get0_verified_chain");
  13741. if (ssl == NULL || ssl->ctx == NULL) {
  13742. WOLFSSL_MSG("Bad parameter");
  13743. return NULL;
  13744. }
  13745. peerCert = wolfSSL_get_peer_certificate((WOLFSSL*)ssl);
  13746. if (peerCert == NULL) {
  13747. WOLFSSL_MSG("wolfSSL_get_peer_certificate error");
  13748. return NULL;
  13749. }
  13750. /* wolfSSL_get_peer_certificate returns a copy. We want the internal
  13751. * member so that we don't have to worry about free'ing it. We call
  13752. * wolfSSL_get_peer_certificate so that we don't have to worry about
  13753. * setting up the internal pointer. */
  13754. wolfSSL_X509_free(peerCert);
  13755. peerCert = (WOLFSSL_X509*)&ssl->peerCert;
  13756. chain = wolfSSL_get_peer_cert_chain(ssl);
  13757. if (chain == NULL) {
  13758. WOLFSSL_MSG("wolfSSL_get_peer_cert_chain error");
  13759. return NULL;
  13760. }
  13761. storeCtx = wolfSSL_X509_STORE_CTX_new();
  13762. if (storeCtx == NULL) {
  13763. WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_new error");
  13764. return NULL;
  13765. }
  13766. if (wolfSSL_X509_STORE_CTX_init(storeCtx, SSL_STORE(ssl),
  13767. peerCert, chain) != WOLFSSL_SUCCESS) {
  13768. WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_init error");
  13769. wolfSSL_X509_STORE_CTX_free(storeCtx);
  13770. return NULL;
  13771. }
  13772. if (wolfSSL_X509_verify_cert(storeCtx) <= 0) {
  13773. WOLFSSL_MSG("wolfSSL_X509_verify_cert error");
  13774. wolfSSL_X509_STORE_CTX_free(storeCtx);
  13775. return NULL;
  13776. }
  13777. wolfSSL_X509_STORE_CTX_free(storeCtx);
  13778. return chain;
  13779. }
  13780. #endif /* SESSION_CERTS && OPENSSL_EXTRA */
  13781. WOLFSSL_X509_STORE* wolfSSL_CTX_get_cert_store(WOLFSSL_CTX* ctx)
  13782. {
  13783. if (ctx == NULL) {
  13784. return NULL;
  13785. }
  13786. if (ctx->x509_store_pt != NULL)
  13787. return ctx->x509_store_pt;
  13788. return &ctx->x509_store;
  13789. }
  13790. void wolfSSL_CTX_set_cert_store(WOLFSSL_CTX* ctx, WOLFSSL_X509_STORE* str)
  13791. {
  13792. WOLFSSL_ENTER("wolfSSL_CTX_set_cert_store");
  13793. if (ctx == NULL || str == NULL || ctx->cm == str->cm) {
  13794. return;
  13795. }
  13796. if (wolfSSL_CertManager_up_ref(str->cm) != WOLFSSL_SUCCESS) {
  13797. WOLFSSL_MSG("wolfSSL_CertManager_up_ref error");
  13798. return;
  13799. }
  13800. /* free cert manager if have one */
  13801. if (ctx->cm != NULL) {
  13802. wolfSSL_CertManagerFree(ctx->cm);
  13803. }
  13804. ctx->cm = str->cm;
  13805. ctx->x509_store.cm = str->cm;
  13806. /* free existing store if it exists */
  13807. wolfSSL_X509_STORE_free(ctx->x509_store_pt);
  13808. ctx->x509_store.cache = str->cache;
  13809. ctx->x509_store_pt = str; /* take ownership of store and free it
  13810. with CTX free */
  13811. ctx->cm->x509_store_p = ctx->x509_store_pt;/* CTX has onwership
  13812. and free it with CTX free*/
  13813. }
  13814. int wolfSSL_set0_verify_cert_store(WOLFSSL *ssl, WOLFSSL_X509_STORE* str)
  13815. {
  13816. WOLFSSL_ENTER("wolfSSL_set0_verify_cert_store");
  13817. if (ssl == NULL || str == NULL) {
  13818. WOLFSSL_MSG("Bad parameter");
  13819. return WOLFSSL_FAILURE;
  13820. }
  13821. /* NO-OP when setting existing store */
  13822. if (str == SSL_STORE(ssl))
  13823. return WOLFSSL_SUCCESS;
  13824. /* free existing store if it exists */
  13825. wolfSSL_X509_STORE_free(ssl->x509_store_pt);
  13826. if (str == ssl->ctx->x509_store_pt)
  13827. ssl->x509_store_pt = NULL; /* if setting ctx store then just revert
  13828. to using that instead */
  13829. else
  13830. ssl->x509_store_pt = str; /* take ownership of store and free it
  13831. with SSL free */
  13832. return WOLFSSL_SUCCESS;
  13833. }
  13834. int wolfSSL_set1_verify_cert_store(WOLFSSL *ssl, WOLFSSL_X509_STORE* str)
  13835. {
  13836. WOLFSSL_ENTER("wolfSSL_set1_verify_cert_store");
  13837. if (ssl == NULL || str == NULL) {
  13838. WOLFSSL_MSG("Bad parameter");
  13839. return WOLFSSL_FAILURE;
  13840. }
  13841. /* NO-OP when setting existing store */
  13842. if (str == SSL_STORE(ssl))
  13843. return WOLFSSL_SUCCESS;
  13844. if (wolfSSL_X509_STORE_up_ref(str) != WOLFSSL_SUCCESS) {
  13845. WOLFSSL_MSG("wolfSSL_X509_STORE_up_ref error");
  13846. return WOLFSSL_FAILURE;
  13847. }
  13848. /* free existing store if it exists */
  13849. wolfSSL_X509_STORE_free(ssl->x509_store_pt);
  13850. if (str == ssl->ctx->x509_store_pt)
  13851. ssl->x509_store_pt = NULL; /* if setting ctx store then just revert
  13852. to using that instead */
  13853. else
  13854. ssl->x509_store_pt = str; /* take ownership of store and free it
  13855. with SSL free */
  13856. return WOLFSSL_SUCCESS;
  13857. }
  13858. #endif /* !NO_CERTS && (OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL) */
  13859. #ifdef WOLFSSL_ENCRYPTED_KEYS
  13860. void wolfSSL_CTX_set_default_passwd_cb_userdata(WOLFSSL_CTX* ctx,
  13861. void* userdata)
  13862. {
  13863. WOLFSSL_ENTER("SSL_CTX_set_default_passwd_cb_userdata");
  13864. if (ctx)
  13865. ctx->passwd_userdata = userdata;
  13866. }
  13867. void wolfSSL_CTX_set_default_passwd_cb(WOLFSSL_CTX* ctx, wc_pem_password_cb*
  13868. cb)
  13869. {
  13870. WOLFSSL_ENTER("SSL_CTX_set_default_passwd_cb");
  13871. if (ctx)
  13872. ctx->passwd_cb = cb;
  13873. }
  13874. wc_pem_password_cb* wolfSSL_CTX_get_default_passwd_cb(WOLFSSL_CTX *ctx)
  13875. {
  13876. if (ctx == NULL || ctx->passwd_cb == NULL) {
  13877. return NULL;
  13878. }
  13879. return ctx->passwd_cb;
  13880. }
  13881. void* wolfSSL_CTX_get_default_passwd_cb_userdata(WOLFSSL_CTX *ctx)
  13882. {
  13883. if (ctx == NULL) {
  13884. return NULL;
  13885. }
  13886. return ctx->passwd_userdata;
  13887. }
  13888. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  13889. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
  13890. int wolfSSL_num_locks(void)
  13891. {
  13892. return 0;
  13893. }
  13894. void wolfSSL_set_locking_callback(void (*f)(int, int, const char*, int))
  13895. {
  13896. WOLFSSL_ENTER("wolfSSL_set_locking_callback");
  13897. if (wc_SetMutexCb(f) != 0) {
  13898. WOLFSSL_MSG("Error when setting mutex call back");
  13899. }
  13900. }
  13901. typedef unsigned long (idCb)(void);
  13902. static idCb* inner_idCb = NULL;
  13903. unsigned long wolfSSL_thread_id(void)
  13904. {
  13905. if (inner_idCb != NULL) {
  13906. return inner_idCb();
  13907. }
  13908. else {
  13909. return 0;
  13910. }
  13911. }
  13912. void wolfSSL_set_id_callback(unsigned long (*f)(void))
  13913. {
  13914. inner_idCb = f;
  13915. }
  13916. unsigned long wolfSSL_ERR_get_error(void)
  13917. {
  13918. int ret;
  13919. WOLFSSL_ENTER("wolfSSL_ERR_get_error");
  13920. #ifdef WOLFSSL_HAVE_ERROR_QUEUE
  13921. ret = wc_PullErrorNode(NULL, NULL, NULL);
  13922. if (ret < 0) {
  13923. if (ret == BAD_STATE_E) {
  13924. ret = 0; /* no errors in queue */
  13925. }
  13926. else {
  13927. WOLFSSL_MSG("Error with pulling error node!");
  13928. WOLFSSL_LEAVE("wolfSSL_ERR_get_error", ret);
  13929. ret = 0 - ret; /* return absolute value of error */
  13930. /* panic and try to clear out nodes */
  13931. wc_ClearErrorNodes();
  13932. }
  13933. }
  13934. else {
  13935. wc_RemoveErrorNode(0);
  13936. }
  13937. return ret;
  13938. #else
  13939. (void)ret;
  13940. return (unsigned long)(0 - NOT_COMPILED_IN);
  13941. #endif /* WOLFSSL_HAVE_ERROR_QUEUE */
  13942. }
  13943. #ifdef WOLFSSL_HAVE_ERROR_QUEUE
  13944. #ifndef NO_BIO
  13945. /* print out and clear all errors */
  13946. void wolfSSL_ERR_print_errors(WOLFSSL_BIO* bio)
  13947. {
  13948. const char* file = NULL;
  13949. const char* reason = NULL;
  13950. int ret;
  13951. int line = 0;
  13952. char buf[WOLFSSL_MAX_ERROR_SZ * 2];
  13953. WOLFSSL_ENTER("wolfSSL_ERR_print_errors");
  13954. if (bio == NULL) {
  13955. WOLFSSL_MSG("BIO passed in was null");
  13956. return;
  13957. }
  13958. do {
  13959. ret = wc_PeekErrorNode(0, &file, &reason, &line);
  13960. if (ret >= 0) {
  13961. const char* r = wolfSSL_ERR_reason_error_string(0 - ret);
  13962. if (XSNPRINTF(buf, sizeof(buf),
  13963. "error:%d:wolfSSL library:%s:%s:%d\n",
  13964. ret, r, file, line)
  13965. >= (int)sizeof(buf))
  13966. {
  13967. WOLFSSL_MSG("Buffer overrun formatting error message");
  13968. }
  13969. wolfSSL_BIO_write(bio, buf, (int)XSTRLEN(buf));
  13970. wc_RemoveErrorNode(0);
  13971. }
  13972. } while (ret >= 0);
  13973. if (wolfSSL_BIO_write(bio, "", 1) != 1) {
  13974. WOLFSSL_MSG("Issue writing final string terminator");
  13975. }
  13976. }
  13977. #endif /* !NO_BIO */
  13978. #endif /* WOLFSSL_HAVE_ERROR_QUEUE */
  13979. #endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
  13980. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
  13981. defined(HAVE_SECRET_CALLBACK)
  13982. #if !defined(NO_WOLFSSL_SERVER)
  13983. /* Return the amount of random bytes copied over or error case.
  13984. * ssl : ssl struct after handshake
  13985. * out : buffer to hold random bytes
  13986. * outSz : either 0 (return max buffer sz) or size of out buffer
  13987. */
  13988. size_t wolfSSL_get_server_random(const WOLFSSL *ssl, unsigned char *out,
  13989. size_t outSz)
  13990. {
  13991. size_t size;
  13992. /* return max size of buffer */
  13993. if (outSz == 0) {
  13994. return RAN_LEN;
  13995. }
  13996. if (ssl == NULL || out == NULL) {
  13997. return 0;
  13998. }
  13999. if (ssl->arrays == NULL) {
  14000. WOLFSSL_MSG("Arrays struct not saved after handshake");
  14001. return 0;
  14002. }
  14003. if (outSz > RAN_LEN) {
  14004. size = RAN_LEN;
  14005. }
  14006. else {
  14007. size = outSz;
  14008. }
  14009. XMEMCPY(out, ssl->arrays->serverRandom, size);
  14010. return size;
  14011. }
  14012. #endif /* !NO_WOLFSSL_SERVER */
  14013. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */
  14014. #ifdef OPENSSL_EXTRA
  14015. #if !defined(NO_WOLFSSL_SERVER)
  14016. /* Used to get the peer ephemeral public key sent during the connection
  14017. * NOTE: currently wolfSSL_KeepHandshakeResources(WOLFSSL* ssl) must be called
  14018. * before the ephemeral key is stored.
  14019. * return WOLFSSL_SUCCESS on success */
  14020. int wolfSSL_get_server_tmp_key(const WOLFSSL* ssl, WOLFSSL_EVP_PKEY** pkey)
  14021. {
  14022. WOLFSSL_EVP_PKEY* ret = NULL;
  14023. WOLFSSL_ENTER("wolfSSL_get_server_tmp_key");
  14024. if (ssl == NULL || pkey == NULL) {
  14025. WOLFSSL_MSG("Bad argument passed in");
  14026. return WOLFSSL_FAILURE;
  14027. }
  14028. #ifdef HAVE_ECC
  14029. if (ssl->peerEccKey != NULL) {
  14030. unsigned char* der;
  14031. const unsigned char* pt;
  14032. unsigned int derSz = 0;
  14033. int sz;
  14034. PRIVATE_KEY_UNLOCK();
  14035. if (wc_ecc_export_x963(ssl->peerEccKey, NULL, &derSz) !=
  14036. LENGTH_ONLY_E) {
  14037. WOLFSSL_MSG("get ecc der size failed");
  14038. PRIVATE_KEY_LOCK();
  14039. return WOLFSSL_FAILURE;
  14040. }
  14041. PRIVATE_KEY_LOCK();
  14042. derSz += MAX_SEQ_SZ + (2 * MAX_ALGO_SZ) + MAX_SEQ_SZ + TRAILING_ZERO;
  14043. der = (unsigned char*)XMALLOC(derSz, ssl->heap, DYNAMIC_TYPE_KEY);
  14044. if (der == NULL) {
  14045. WOLFSSL_MSG("Memory error");
  14046. return WOLFSSL_FAILURE;
  14047. }
  14048. if ((sz = wc_EccPublicKeyToDer(ssl->peerEccKey, der, derSz, 1)) <= 0) {
  14049. WOLFSSL_MSG("get ecc der failed");
  14050. XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY);
  14051. return WOLFSSL_FAILURE;
  14052. }
  14053. pt = der; /* in case pointer gets advanced */
  14054. ret = wolfSSL_d2i_PUBKEY(NULL, &pt, sz);
  14055. XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY);
  14056. }
  14057. #endif
  14058. *pkey = ret;
  14059. #ifdef HAVE_ECC
  14060. if (ret != NULL)
  14061. return WOLFSSL_SUCCESS;
  14062. else
  14063. #endif
  14064. return WOLFSSL_FAILURE;
  14065. }
  14066. #endif /* !NO_WOLFSSL_SERVER */
  14067. /**
  14068. * This function checks if any compiled in protocol versions are
  14069. * left enabled after calls to set_min or set_max API.
  14070. * @param major The SSL/TLS major version
  14071. * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
  14072. * protocol versions are left enabled.
  14073. */
  14074. static int CheckSslMethodVersion(byte major, unsigned long options)
  14075. {
  14076. int sanityConfirmed = 0;
  14077. (void)options;
  14078. switch (major) {
  14079. #ifndef NO_TLS
  14080. case SSLv3_MAJOR:
  14081. #ifdef WOLFSSL_ALLOW_SSLV3
  14082. if (!(options & WOLFSSL_OP_NO_SSLv3)) {
  14083. sanityConfirmed = 1;
  14084. }
  14085. #endif
  14086. #ifndef NO_OLD_TLS
  14087. if (!(options & WOLFSSL_OP_NO_TLSv1))
  14088. sanityConfirmed = 1;
  14089. if (!(options & WOLFSSL_OP_NO_TLSv1_1))
  14090. sanityConfirmed = 1;
  14091. #endif
  14092. #ifndef WOLFSSL_NO_TLS12
  14093. if (!(options & WOLFSSL_OP_NO_TLSv1_2))
  14094. sanityConfirmed = 1;
  14095. #endif
  14096. #ifdef WOLFSSL_TLS13
  14097. if (!(options & WOLFSSL_OP_NO_TLSv1_3))
  14098. sanityConfirmed = 1;
  14099. #endif
  14100. break;
  14101. #endif
  14102. #ifdef WOLFSSL_DTLS
  14103. case DTLS_MAJOR:
  14104. sanityConfirmed = 1;
  14105. break;
  14106. #endif
  14107. default:
  14108. WOLFSSL_MSG("Invalid major version");
  14109. return WOLFSSL_FAILURE;
  14110. }
  14111. if (!sanityConfirmed) {
  14112. WOLFSSL_MSG("All compiled in TLS versions disabled");
  14113. return WOLFSSL_FAILURE;
  14114. }
  14115. return WOLFSSL_SUCCESS;
  14116. }
  14117. /**
  14118. * protoVerTbl holds (D)TLS version numbers in ascending order.
  14119. * Except DTLS versions, the newer version is located in the latter part of
  14120. * the table. This table is referred by wolfSSL_CTX_set_min_proto_version and
  14121. * wolfSSL_CTX_set_max_proto_version.
  14122. */
  14123. static const int protoVerTbl[] = {
  14124. SSL3_VERSION,
  14125. TLS1_VERSION,
  14126. TLS1_1_VERSION,
  14127. TLS1_2_VERSION,
  14128. TLS1_3_VERSION,
  14129. DTLS1_VERSION,
  14130. DTLS1_2_VERSION
  14131. };
  14132. /* number of protocol versions listed in protoVerTbl */
  14133. #define NUMBER_OF_PROTOCOLS (sizeof(protoVerTbl)/sizeof(int))
  14134. /**
  14135. * wolfSSL_CTX_set_min_proto_version attempts to set the minimum protocol
  14136. * version to use by SSL objects created from this WOLFSSL_CTX.
  14137. * This API guarantees that a version of SSL/TLS lower than specified
  14138. * here will not be allowed. If the version specified is not compiled in
  14139. * then this API sets the lowest compiled in protocol version.
  14140. * This API also accept 0 as version, to set the minimum version automatically.
  14141. * CheckSslMethodVersion() is called to check if any remaining protocol versions
  14142. * are enabled.
  14143. * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects
  14144. * @param version Any of the following
  14145. * * 0
  14146. * * SSL3_VERSION
  14147. * * TLS1_VERSION
  14148. * * TLS1_1_VERSION
  14149. * * TLS1_2_VERSION
  14150. * * TLS1_3_VERSION
  14151. * * DTLS1_VERSION
  14152. * * DTLS1_2_VERSION
  14153. * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
  14154. * protocol versions are left enabled.
  14155. */
  14156. static int Set_CTX_min_proto_version(WOLFSSL_CTX* ctx, int version)
  14157. {
  14158. WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version_ex");
  14159. if (ctx == NULL) {
  14160. return WOLFSSL_FAILURE;
  14161. }
  14162. switch (version) {
  14163. #ifndef NO_TLS
  14164. case SSL3_VERSION:
  14165. #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
  14166. ctx->minDowngrade = SSLv3_MINOR;
  14167. break;
  14168. #endif
  14169. case TLS1_VERSION:
  14170. #ifdef WOLFSSL_ALLOW_TLSV10
  14171. ctx->minDowngrade = TLSv1_MINOR;
  14172. break;
  14173. #endif
  14174. case TLS1_1_VERSION:
  14175. #ifndef NO_OLD_TLS
  14176. ctx->minDowngrade = TLSv1_1_MINOR;
  14177. break;
  14178. #endif
  14179. case TLS1_2_VERSION:
  14180. #ifndef WOLFSSL_NO_TLS12
  14181. ctx->minDowngrade = TLSv1_2_MINOR;
  14182. break;
  14183. #endif
  14184. case TLS1_3_VERSION:
  14185. #ifdef WOLFSSL_TLS13
  14186. ctx->minDowngrade = TLSv1_3_MINOR;
  14187. break;
  14188. #endif
  14189. #endif
  14190. #ifdef WOLFSSL_DTLS
  14191. case DTLS1_VERSION:
  14192. #ifndef NO_OLD_TLS
  14193. ctx->minDowngrade = DTLS_MINOR;
  14194. break;
  14195. #endif
  14196. case DTLS1_2_VERSION:
  14197. ctx->minDowngrade = DTLSv1_2_MINOR;
  14198. break;
  14199. #endif
  14200. default:
  14201. WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
  14202. return WOLFSSL_FAILURE;
  14203. }
  14204. switch (version) {
  14205. #ifndef NO_TLS
  14206. case TLS1_3_VERSION:
  14207. wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2);
  14208. FALL_THROUGH;
  14209. case TLS1_2_VERSION:
  14210. wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1);
  14211. FALL_THROUGH;
  14212. case TLS1_1_VERSION:
  14213. wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1);
  14214. FALL_THROUGH;
  14215. case TLS1_VERSION:
  14216. wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_SSLv3);
  14217. break;
  14218. case SSL3_VERSION:
  14219. case SSL2_VERSION:
  14220. /* Nothing to do here */
  14221. break;
  14222. #endif
  14223. #ifdef WOLFSSL_DTLS
  14224. case DTLS1_VERSION:
  14225. case DTLS1_2_VERSION:
  14226. break;
  14227. #endif
  14228. default:
  14229. WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
  14230. return WOLFSSL_FAILURE;
  14231. }
  14232. return CheckSslMethodVersion(ctx->method->version.major, ctx->mask);
  14233. }
  14234. /* Sets the min protocol version allowed with WOLFSSL_CTX
  14235. * returns WOLFSSL_SUCCESS on success */
  14236. int wolfSSL_CTX_set_min_proto_version(WOLFSSL_CTX* ctx, int version)
  14237. {
  14238. int ret;
  14239. int proto = 0;
  14240. int maxProto = 0;
  14241. int i;
  14242. int idx = 0;
  14243. WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version");
  14244. if (ctx == NULL) {
  14245. return WOLFSSL_FAILURE;
  14246. }
  14247. if (version != 0) {
  14248. proto = version;
  14249. ctx->minProto = 0; /* turn min proto flag off */
  14250. for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
  14251. if (protoVerTbl[i] == version) {
  14252. break;
  14253. }
  14254. }
  14255. }
  14256. else {
  14257. /* when 0 is specified as version, try to find out the min version */
  14258. for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
  14259. ret = Set_CTX_min_proto_version(ctx, protoVerTbl[i]);
  14260. if (ret == WOLFSSL_SUCCESS) {
  14261. proto = protoVerTbl[i];
  14262. ctx->minProto = 1; /* turn min proto flag on */
  14263. break;
  14264. }
  14265. }
  14266. }
  14267. /* check case where max > min , if so then clear the NO_* options
  14268. * i is the index into the table for proto version used, see if the max
  14269. * proto version index found is smaller */
  14270. maxProto = wolfSSL_CTX_get_max_proto_version(ctx);
  14271. for (idx = 0; (unsigned)idx < NUMBER_OF_PROTOCOLS; idx++) {
  14272. if (protoVerTbl[idx] == maxProto) {
  14273. break;
  14274. }
  14275. }
  14276. if (idx < i) {
  14277. wolfSSL_CTX_clear_options(ctx, WOLFSSL_OP_NO_TLSv1 |
  14278. WOLFSSL_OP_NO_TLSv1_1 | WOLFSSL_OP_NO_TLSv1_2 |
  14279. WOLFSSL_OP_NO_TLSv1_3);
  14280. }
  14281. ret = Set_CTX_min_proto_version(ctx, proto);
  14282. return ret;
  14283. }
  14284. /**
  14285. * wolfSSL_CTX_set_max_proto_version attempts to set the maximum protocol
  14286. * version to use by SSL objects created from this WOLFSSL_CTX.
  14287. * This API guarantees that a version of SSL/TLS higher than specified
  14288. * here will not be allowed. If the version specified is not compiled in
  14289. * then this API sets the highest compiled in protocol version.
  14290. * This API also accept 0 as version, to set the maximum version automatically.
  14291. * CheckSslMethodVersion() is called to check if any remaining protocol versions
  14292. * are enabled.
  14293. * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects
  14294. * @param ver Any of the following
  14295. * * 0
  14296. * * SSL3_VERSION
  14297. * * TLS1_VERSION
  14298. * * TLS1_1_VERSION
  14299. * * TLS1_2_VERSION
  14300. * * TLS1_3_VERSION
  14301. * * DTLS1_VERSION
  14302. * * DTLS1_2_VERSION
  14303. * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
  14304. * protocol versions are left enabled.
  14305. */
  14306. static int Set_CTX_max_proto_version(WOLFSSL_CTX* ctx, int ver)
  14307. {
  14308. WOLFSSL_ENTER("Set_CTX_max_proto_version");
  14309. if (!ctx || !ctx->method) {
  14310. WOLFSSL_MSG("Bad parameter");
  14311. return WOLFSSL_FAILURE;
  14312. }
  14313. switch (ver) {
  14314. case SSL2_VERSION:
  14315. WOLFSSL_MSG("wolfSSL does not support SSLv2");
  14316. return WOLFSSL_FAILURE;
  14317. #ifndef NO_TLS
  14318. case SSL3_VERSION:
  14319. wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1);
  14320. FALL_THROUGH;
  14321. case TLS1_VERSION:
  14322. wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1);
  14323. FALL_THROUGH;
  14324. case TLS1_1_VERSION:
  14325. wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2);
  14326. FALL_THROUGH;
  14327. case TLS1_2_VERSION:
  14328. wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_3);
  14329. FALL_THROUGH;
  14330. case TLS1_3_VERSION:
  14331. /* Nothing to do here */
  14332. break;
  14333. #endif
  14334. #ifdef WOLFSSL_DTLS
  14335. case DTLS1_VERSION:
  14336. case DTLS1_2_VERSION:
  14337. break;
  14338. #endif
  14339. default:
  14340. WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
  14341. return WOLFSSL_FAILURE;
  14342. }
  14343. return CheckSslMethodVersion(ctx->method->version.major, ctx->mask);
  14344. }
  14345. /* Sets the max protocol version allowed with WOLFSSL_CTX
  14346. * returns WOLFSSL_SUCCESS on success */
  14347. int wolfSSL_CTX_set_max_proto_version(WOLFSSL_CTX* ctx, int version)
  14348. {
  14349. int i;
  14350. int ret = WOLFSSL_FAILURE;
  14351. int minProto;
  14352. WOLFSSL_ENTER("wolfSSL_CTX_set_max_proto_version");
  14353. if (ctx == NULL) {
  14354. return ret;
  14355. }
  14356. /* clear out flags and reset min protocol version */
  14357. minProto = wolfSSL_CTX_get_min_proto_version(ctx);
  14358. wolfSSL_CTX_clear_options(ctx,
  14359. WOLFSSL_OP_NO_TLSv1 | WOLFSSL_OP_NO_TLSv1_1 |
  14360. WOLFSSL_OP_NO_TLSv1_2 | WOLFSSL_OP_NO_TLSv1_3);
  14361. wolfSSL_CTX_set_min_proto_version(ctx, minProto);
  14362. if (version != 0) {
  14363. ctx->maxProto = 0; /* turn max proto flag off */
  14364. return Set_CTX_max_proto_version(ctx, version);
  14365. }
  14366. /* when 0 is specified as version, try to find out the min version from
  14367. * the bottom to top of the protoverTbl.
  14368. */
  14369. for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) {
  14370. ret = Set_CTX_max_proto_version(ctx, protoVerTbl[i]);
  14371. if (ret == WOLFSSL_SUCCESS) {
  14372. ctx->maxProto = 1; /* turn max proto flag on */
  14373. break;
  14374. }
  14375. }
  14376. return ret;
  14377. }
  14378. static int Set_SSL_min_proto_version(WOLFSSL* ssl, int ver)
  14379. {
  14380. WOLFSSL_ENTER("Set_SSL_min_proto_version");
  14381. if (ssl == NULL) {
  14382. return WOLFSSL_FAILURE;
  14383. }
  14384. switch (ver) {
  14385. #ifndef NO_TLS
  14386. case SSL3_VERSION:
  14387. #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
  14388. ssl->options.minDowngrade = SSLv3_MINOR;
  14389. break;
  14390. #endif
  14391. case TLS1_VERSION:
  14392. #ifdef WOLFSSL_ALLOW_TLSV10
  14393. ssl->options.minDowngrade = TLSv1_MINOR;
  14394. break;
  14395. #endif
  14396. case TLS1_1_VERSION:
  14397. #ifndef NO_OLD_TLS
  14398. ssl->options.minDowngrade = TLSv1_1_MINOR;
  14399. break;
  14400. #endif
  14401. case TLS1_2_VERSION:
  14402. #ifndef WOLFSSL_NO_TLS12
  14403. ssl->options.minDowngrade = TLSv1_2_MINOR;
  14404. break;
  14405. #endif
  14406. case TLS1_3_VERSION:
  14407. #ifdef WOLFSSL_TLS13
  14408. ssl->options.minDowngrade = TLSv1_3_MINOR;
  14409. break;
  14410. #endif
  14411. #endif
  14412. #ifdef WOLFSSL_DTLS
  14413. case DTLS1_VERSION:
  14414. #ifndef NO_OLD_TLS
  14415. ssl->options.minDowngrade = DTLS_MINOR;
  14416. break;
  14417. #endif
  14418. case DTLS1_2_VERSION:
  14419. ssl->options.minDowngrade = DTLSv1_2_MINOR;
  14420. break;
  14421. #endif
  14422. default:
  14423. WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
  14424. return WOLFSSL_FAILURE;
  14425. }
  14426. switch (ver) {
  14427. #ifndef NO_TLS
  14428. case TLS1_3_VERSION:
  14429. ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2;
  14430. FALL_THROUGH;
  14431. case TLS1_2_VERSION:
  14432. ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1;
  14433. FALL_THROUGH;
  14434. case TLS1_1_VERSION:
  14435. ssl->options.mask |= WOLFSSL_OP_NO_TLSv1;
  14436. FALL_THROUGH;
  14437. case TLS1_VERSION:
  14438. ssl->options.mask |= WOLFSSL_OP_NO_SSLv3;
  14439. break;
  14440. case SSL3_VERSION:
  14441. case SSL2_VERSION:
  14442. /* Nothing to do here */
  14443. break;
  14444. #endif
  14445. #ifdef WOLFSSL_DTLS
  14446. case DTLS1_VERSION:
  14447. case DTLS1_2_VERSION:
  14448. break;
  14449. #endif
  14450. default:
  14451. WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
  14452. return WOLFSSL_FAILURE;
  14453. }
  14454. return CheckSslMethodVersion(ssl->version.major, ssl->options.mask);
  14455. }
  14456. int wolfSSL_set_min_proto_version(WOLFSSL* ssl, int version)
  14457. {
  14458. int i;
  14459. int ret = WOLFSSL_FAILURE;;
  14460. WOLFSSL_ENTER("wolfSSL_set_min_proto_version");
  14461. if (ssl == NULL) {
  14462. return WOLFSSL_FAILURE;
  14463. }
  14464. if (version != 0) {
  14465. return Set_SSL_min_proto_version(ssl, version);
  14466. }
  14467. /* when 0 is specified as version, try to find out the min version */
  14468. for (i= 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
  14469. ret = Set_SSL_min_proto_version(ssl, protoVerTbl[i]);
  14470. if (ret == WOLFSSL_SUCCESS)
  14471. break;
  14472. }
  14473. return ret;
  14474. }
  14475. static int Set_SSL_max_proto_version(WOLFSSL* ssl, int ver)
  14476. {
  14477. WOLFSSL_ENTER("Set_SSL_max_proto_version");
  14478. if (!ssl) {
  14479. WOLFSSL_MSG("Bad parameter");
  14480. return WOLFSSL_FAILURE;
  14481. }
  14482. switch (ver) {
  14483. case SSL2_VERSION:
  14484. WOLFSSL_MSG("wolfSSL does not support SSLv2");
  14485. return WOLFSSL_FAILURE;
  14486. #ifndef NO_TLS
  14487. case SSL3_VERSION:
  14488. ssl->options.mask |= WOLFSSL_OP_NO_TLSv1;
  14489. FALL_THROUGH;
  14490. case TLS1_VERSION:
  14491. ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1;
  14492. FALL_THROUGH;
  14493. case TLS1_1_VERSION:
  14494. ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2;
  14495. FALL_THROUGH;
  14496. case TLS1_2_VERSION:
  14497. ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_3;
  14498. FALL_THROUGH;
  14499. case TLS1_3_VERSION:
  14500. /* Nothing to do here */
  14501. break;
  14502. #endif
  14503. #ifdef WOLFSSL_DTLS
  14504. case DTLS1_VERSION:
  14505. case DTLS1_2_VERSION:
  14506. break;
  14507. #endif
  14508. default:
  14509. WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
  14510. return WOLFSSL_FAILURE;
  14511. }
  14512. return CheckSslMethodVersion(ssl->version.major, ssl->options.mask);
  14513. }
  14514. int wolfSSL_set_max_proto_version(WOLFSSL* ssl, int version)
  14515. {
  14516. int i;
  14517. int ret = WOLFSSL_FAILURE;;
  14518. WOLFSSL_ENTER("wolfSSL_set_max_proto_version");
  14519. if (ssl == NULL) {
  14520. return WOLFSSL_FAILURE;
  14521. }
  14522. if (version != 0) {
  14523. return Set_SSL_max_proto_version(ssl, version);
  14524. }
  14525. /* when 0 is specified as version, try to find out the min version from
  14526. * the bottom to top of the protoverTbl.
  14527. */
  14528. for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) {
  14529. ret = Set_SSL_max_proto_version(ssl, protoVerTbl[i]);
  14530. if (ret == WOLFSSL_SUCCESS)
  14531. break;
  14532. }
  14533. return ret;
  14534. }
  14535. static int GetMinProtoVersion(int minDowngrade)
  14536. {
  14537. int ret;
  14538. switch (minDowngrade) {
  14539. #ifndef NO_OLD_TLS
  14540. #ifdef WOLFSSL_ALLOW_SSLV3
  14541. case SSLv3_MINOR:
  14542. ret = SSL3_VERSION;
  14543. break;
  14544. #endif
  14545. #ifdef WOLFSSL_ALLOW_TLSV10
  14546. case TLSv1_MINOR:
  14547. ret = TLS1_VERSION;
  14548. break;
  14549. #endif
  14550. case TLSv1_1_MINOR:
  14551. ret = TLS1_1_VERSION;
  14552. break;
  14553. #endif
  14554. #ifndef WOLFSSL_NO_TLS12
  14555. case TLSv1_2_MINOR:
  14556. ret = TLS1_2_VERSION;
  14557. break;
  14558. #endif
  14559. #ifdef WOLFSSL_TLS13
  14560. case TLSv1_3_MINOR:
  14561. ret = TLS1_3_VERSION;
  14562. break;
  14563. #endif
  14564. default:
  14565. ret = 0;
  14566. break;
  14567. }
  14568. return ret;
  14569. }
  14570. WOLFSSL_API int wolfSSL_CTX_get_min_proto_version(WOLFSSL_CTX* ctx)
  14571. {
  14572. int ret = 0;
  14573. WOLFSSL_ENTER("wolfSSL_CTX_get_min_proto_version");
  14574. if (ctx != NULL) {
  14575. if (ctx->minProto) {
  14576. ret = 0;
  14577. }
  14578. else {
  14579. ret = GetMinProtoVersion(ctx->minDowngrade);
  14580. }
  14581. }
  14582. else {
  14583. ret = GetMinProtoVersion(WOLFSSL_MIN_DOWNGRADE);
  14584. }
  14585. WOLFSSL_LEAVE("wolfSSL_CTX_get_min_proto_version", ret);
  14586. return ret;
  14587. }
  14588. /* returns the maximum allowed protocol version given the 'options' used
  14589. * returns WOLFSSL_FATAL_ERROR on no match */
  14590. static int GetMaxProtoVersion(long options)
  14591. {
  14592. #ifndef NO_TLS
  14593. #ifdef WOLFSSL_TLS13
  14594. if (!(options & WOLFSSL_OP_NO_TLSv1_3))
  14595. return TLS1_3_VERSION;
  14596. #endif
  14597. #ifndef WOLFSSL_NO_TLS12
  14598. if (!(options & WOLFSSL_OP_NO_TLSv1_2))
  14599. return TLS1_2_VERSION;
  14600. #endif
  14601. #ifndef NO_OLD_TLS
  14602. if (!(options & WOLFSSL_OP_NO_TLSv1_1))
  14603. return TLS1_1_VERSION;
  14604. #ifdef WOLFSSL_ALLOW_TLSV10
  14605. if (!(options & WOLFSSL_OP_NO_TLSv1))
  14606. return TLS1_VERSION;
  14607. #endif
  14608. #ifdef WOLFSSL_ALLOW_SSLV3
  14609. if (!(options & WOLFSSL_OP_NO_SSLv3))
  14610. return SSL3_VERSION;
  14611. #endif
  14612. #endif
  14613. #else
  14614. (void)options;
  14615. #endif /* NO_TLS */
  14616. return WOLFSSL_FATAL_ERROR;
  14617. }
  14618. /* returns the maximum protocol version for 'ctx' */
  14619. int wolfSSL_CTX_get_max_proto_version(WOLFSSL_CTX* ctx)
  14620. {
  14621. int ret = 0;
  14622. long options = 0; /* default to nothing set */
  14623. WOLFSSL_ENTER("wolfSSL_CTX_get_max_proto_version");
  14624. if (ctx != NULL) {
  14625. options = wolfSSL_CTX_get_options(ctx);
  14626. }
  14627. if ((ctx != NULL) && ctx->maxProto) {
  14628. ret = 0;
  14629. }
  14630. else {
  14631. ret = GetMaxProtoVersion(options);
  14632. }
  14633. WOLFSSL_LEAVE("wolfSSL_CTX_get_max_proto_version", ret);
  14634. if (ret == WOLFSSL_FATAL_ERROR) {
  14635. WOLFSSL_MSG("Error getting max proto version");
  14636. ret = 0; /* setting ret to 0 to match compat return */
  14637. }
  14638. return ret;
  14639. }
  14640. #endif /* OPENSSL_EXTRA */
  14641. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
  14642. defined(HAVE_SECRET_CALLBACK)
  14643. #if !defined(NO_WOLFSSL_CLIENT)
  14644. /* Return the amount of random bytes copied over or error case.
  14645. * ssl : ssl struct after handshake
  14646. * out : buffer to hold random bytes
  14647. * outSz : either 0 (return max buffer sz) or size of out buffer
  14648. */
  14649. size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
  14650. size_t outSz)
  14651. {
  14652. size_t size;
  14653. /* return max size of buffer */
  14654. if (outSz == 0) {
  14655. return RAN_LEN;
  14656. }
  14657. if (ssl == NULL || out == NULL) {
  14658. return 0;
  14659. }
  14660. if (ssl->arrays == NULL) {
  14661. WOLFSSL_MSG("Arrays struct not saved after handshake");
  14662. return 0;
  14663. }
  14664. if (outSz > RAN_LEN) {
  14665. size = RAN_LEN;
  14666. }
  14667. else {
  14668. size = outSz;
  14669. }
  14670. XMEMCPY(out, ssl->arrays->clientRandom, size);
  14671. return size;
  14672. }
  14673. #endif /* !NO_WOLFSSL_CLIENT */
  14674. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */
  14675. #ifdef OPENSSL_EXTRA
  14676. unsigned long wolfSSLeay(void)
  14677. {
  14678. return SSLEAY_VERSION_NUMBER;
  14679. }
  14680. unsigned long wolfSSL_OpenSSL_version_num(void)
  14681. {
  14682. return OPENSSL_VERSION_NUMBER;
  14683. }
  14684. const char* wolfSSLeay_version(int type)
  14685. {
  14686. (void)type;
  14687. #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
  14688. return wolfSSL_OpenSSL_version(type);
  14689. #else
  14690. return wolfSSL_OpenSSL_version();
  14691. #endif
  14692. }
  14693. #ifndef NO_MD5
  14694. int wolfSSL_MD5_Init(WOLFSSL_MD5_CTX* md5)
  14695. {
  14696. int ret;
  14697. typedef char md5_test[sizeof(MD5_CTX) >= sizeof(wc_Md5) ? 1 : -1];
  14698. (void)sizeof(md5_test);
  14699. WOLFSSL_ENTER("MD5_Init");
  14700. ret = wc_InitMd5((wc_Md5*)md5);
  14701. /* return 1 on success, 0 otherwise */
  14702. if (ret == 0)
  14703. return 1;
  14704. return 0;
  14705. }
  14706. int wolfSSL_MD5_Update(WOLFSSL_MD5_CTX* md5, const void* input,
  14707. unsigned long sz)
  14708. {
  14709. int ret;
  14710. WOLFSSL_ENTER("wolfSSL_MD5_Update");
  14711. ret = wc_Md5Update((wc_Md5*)md5, (const byte*)input, (word32)sz);
  14712. /* return 1 on success, 0 otherwise */
  14713. if (ret == 0)
  14714. return 1;
  14715. return 0;
  14716. }
  14717. int wolfSSL_MD5_Final(byte* output, WOLFSSL_MD5_CTX* md5)
  14718. {
  14719. int ret;
  14720. WOLFSSL_ENTER("MD5_Final");
  14721. ret = wc_Md5Final((wc_Md5*)md5, output);
  14722. /* have to actually free the resources (if any) here, because the
  14723. * OpenSSL API doesn't include SHA*_Free().
  14724. */
  14725. wc_Md5Free((wc_Md5*)md5);
  14726. /* return 1 on success, 0 otherwise */
  14727. if (ret == 0)
  14728. return 1;
  14729. return 0;
  14730. }
  14731. /* Apply MD5 transformation to the data */
  14732. int wolfSSL_MD5_Transform(WOLFSSL_MD5_CTX* md5, const unsigned char* data)
  14733. {
  14734. int ret;
  14735. WOLFSSL_ENTER("MD5_Transform");
  14736. /* sanity check */
  14737. if (md5 == NULL || data == NULL) {
  14738. return 0;
  14739. }
  14740. #if defined(BIG_ENDIAN_ORDER)
  14741. {
  14742. ByteReverseWords((word32*)data, (word32*)data, WC_MD5_BLOCK_SIZE);
  14743. }
  14744. #endif
  14745. ret = wc_Md5Transform((wc_Md5*)md5, data);
  14746. /* return 1 on success, 0 otherwise */
  14747. if (ret == 0)
  14748. return 1;
  14749. else
  14750. return 0;
  14751. }
  14752. unsigned char *wolfSSL_MD5(const unsigned char* data, size_t len,
  14753. unsigned char* hash)
  14754. {
  14755. static unsigned char out[WC_MD5_DIGEST_SIZE];
  14756. WOLFSSL_ENTER("wolfSSL_MD5");
  14757. if (hash == NULL)
  14758. hash = out;
  14759. if (wc_Md5Hash(data, (word32)len, hash) != 0) {
  14760. WOLFSSL_MSG("wc_Md5Hash error");
  14761. return NULL;
  14762. }
  14763. return hash;
  14764. }
  14765. #endif /* !NO_MD5 */
  14766. #ifndef NO_SHA
  14767. int wolfSSL_SHA_Init(WOLFSSL_SHA_CTX* sha)
  14768. {
  14769. int ret;
  14770. typedef char sha_test[sizeof(SHA_CTX) >= sizeof(wc_Sha) ? 1 : -1];
  14771. (void)sizeof(sha_test);
  14772. WOLFSSL_ENTER("SHA_Init");
  14773. ret = wc_InitSha((wc_Sha*)sha);
  14774. /* return 1 on success, 0 otherwise */
  14775. if (ret == 0)
  14776. return 1;
  14777. return 0;
  14778. }
  14779. int wolfSSL_SHA_Update(WOLFSSL_SHA_CTX* sha, const void* input,
  14780. unsigned long sz)
  14781. {
  14782. int ret;
  14783. WOLFSSL_ENTER("SHA_Update");
  14784. ret = wc_ShaUpdate((wc_Sha*)sha, (const byte*)input, (word32)sz);
  14785. /* return 1 on success, 0 otherwise */
  14786. if (ret == 0)
  14787. return 1;
  14788. return 0;
  14789. }
  14790. int wolfSSL_SHA_Final(byte* output, WOLFSSL_SHA_CTX* sha)
  14791. {
  14792. int ret;
  14793. WOLFSSL_ENTER("SHA_Final");
  14794. ret = wc_ShaFinal((wc_Sha*)sha, output);
  14795. /* have to actually free the resources (if any) here, because the
  14796. * OpenSSL API doesn't include SHA*_Free().
  14797. */
  14798. wc_ShaFree((wc_Sha*)sha);
  14799. /* return 1 on success, 0 otherwise */
  14800. if (ret == 0)
  14801. return 1;
  14802. return 0;
  14803. }
  14804. #if defined(OPENSSL_EXTRA)
  14805. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
  14806. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2)))
  14807. /* Apply SHA1 transformation to the data */
  14808. int wolfSSL_SHA_Transform(WOLFSSL_SHA_CTX* sha,
  14809. const unsigned char* data)
  14810. {
  14811. int ret;
  14812. WOLFSSL_ENTER("SHA_Transform");
  14813. /* sanity check */
  14814. if (sha == NULL || data == NULL) {
  14815. return 0;
  14816. }
  14817. #if defined(LITTLE_ENDIAN_ORDER)
  14818. {
  14819. ByteReverseWords((word32*)data, (word32*)data, WC_SHA_BLOCK_SIZE);
  14820. }
  14821. #endif
  14822. ret = wc_ShaTransform((wc_Sha*)sha, data);
  14823. /* return 1 on success, 0 otherwise */
  14824. if (ret == 0)
  14825. return 1;
  14826. else
  14827. return 0;
  14828. }
  14829. #endif
  14830. #endif
  14831. int wolfSSL_SHA1_Init(WOLFSSL_SHA_CTX* sha)
  14832. {
  14833. WOLFSSL_ENTER("SHA1_Init");
  14834. return SHA_Init(sha);
  14835. }
  14836. int wolfSSL_SHA1_Update(WOLFSSL_SHA_CTX* sha, const void* input,
  14837. unsigned long sz)
  14838. {
  14839. WOLFSSL_ENTER("SHA1_Update");
  14840. return SHA_Update(sha, input, sz);
  14841. }
  14842. int wolfSSL_SHA1_Final(byte* output, WOLFSSL_SHA_CTX* sha)
  14843. {
  14844. WOLFSSL_ENTER("SHA1_Final");
  14845. return SHA_Final(output, sha);
  14846. }
  14847. #if defined(OPENSSL_EXTRA)
  14848. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
  14849. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2)))
  14850. /* Apply SHA1 transformation to the data */
  14851. int wolfSSL_SHA1_Transform(WOLFSSL_SHA_CTX* sha,
  14852. const unsigned char* data)
  14853. {
  14854. WOLFSSL_ENTER("SHA1_Transform");
  14855. return (wolfSSL_SHA_Transform(sha, data));
  14856. }
  14857. #endif
  14858. #endif
  14859. #endif /* !NO_SHA */
  14860. #ifdef WOLFSSL_SHA224
  14861. int wolfSSL_SHA224_Init(WOLFSSL_SHA224_CTX* sha)
  14862. {
  14863. int ret;
  14864. typedef char sha_test[sizeof(SHA224_CTX) >= sizeof(wc_Sha224) ? 1 : -1];
  14865. (void)sizeof(sha_test);
  14866. WOLFSSL_ENTER("SHA224_Init");
  14867. ret = wc_InitSha224((wc_Sha224*)sha);
  14868. /* return 1 on success, 0 otherwise */
  14869. if (ret == 0)
  14870. return 1;
  14871. return 0;
  14872. }
  14873. int wolfSSL_SHA224_Update(WOLFSSL_SHA224_CTX* sha, const void* input,
  14874. unsigned long sz)
  14875. {
  14876. int ret;
  14877. WOLFSSL_ENTER("SHA224_Update");
  14878. ret = wc_Sha224Update((wc_Sha224*)sha, (const byte*)input, (word32)sz);
  14879. /* return 1 on success, 0 otherwise */
  14880. if (ret == 0)
  14881. return 1;
  14882. return 0;
  14883. }
  14884. int wolfSSL_SHA224_Final(byte* output, WOLFSSL_SHA224_CTX* sha)
  14885. {
  14886. int ret;
  14887. WOLFSSL_ENTER("SHA224_Final");
  14888. ret = wc_Sha224Final((wc_Sha224*)sha, output);
  14889. /* have to actually free the resources (if any) here, because the
  14890. * OpenSSL API doesn't include SHA*_Free().
  14891. */
  14892. wc_Sha224Free((wc_Sha224*)sha);
  14893. /* return 1 on success, 0 otherwise */
  14894. if (ret == 0)
  14895. return 1;
  14896. return 0;
  14897. }
  14898. #endif /* WOLFSSL_SHA224 */
  14899. int wolfSSL_SHA256_Init(WOLFSSL_SHA256_CTX* sha256)
  14900. {
  14901. int ret;
  14902. typedef char sha_test[sizeof(SHA256_CTX) >= sizeof(wc_Sha256) ? 1 : -1];
  14903. (void)sizeof(sha_test);
  14904. WOLFSSL_ENTER("SHA256_Init");
  14905. ret = wc_InitSha256((wc_Sha256*)sha256);
  14906. /* return 1 on success, 0 otherwise */
  14907. if (ret == 0)
  14908. return 1;
  14909. return 0;
  14910. }
  14911. int wolfSSL_SHA256_Update(WOLFSSL_SHA256_CTX* sha, const void* input,
  14912. unsigned long sz)
  14913. {
  14914. int ret;
  14915. WOLFSSL_ENTER("SHA256_Update");
  14916. ret = wc_Sha256Update((wc_Sha256*)sha, (const byte*)input, (word32)sz);
  14917. /* return 1 on success, 0 otherwise */
  14918. if (ret == 0)
  14919. return 1;
  14920. return 0;
  14921. }
  14922. int wolfSSL_SHA256_Final(byte* output, WOLFSSL_SHA256_CTX* sha)
  14923. {
  14924. int ret;
  14925. WOLFSSL_ENTER("SHA256_Final");
  14926. ret = wc_Sha256Final((wc_Sha256*)sha, output);
  14927. /* have to actually free the resources (if any) here, because the
  14928. * OpenSSL API doesn't include SHA*_Free().
  14929. */
  14930. wc_Sha256Free((wc_Sha256*)sha);
  14931. /* return 1 on success, 0 otherwise */
  14932. if (ret == 0)
  14933. return 1;
  14934. return 0;
  14935. }
  14936. #if defined(OPENSSL_EXTRA)
  14937. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
  14938. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))) && \
  14939. !defined(WOLFSSL_DEVCRYPTO_HASH) && !defined(WOLFSSL_AFALG_HASH)
  14940. /* Apply SHA256 transformation to the data */
  14941. int wolfSSL_SHA256_Transform(WOLFSSL_SHA256_CTX* sha256,
  14942. const unsigned char* data)
  14943. {
  14944. int ret;
  14945. WOLFSSL_ENTER("SHA256_Transform");
  14946. /* sanity check */
  14947. if (sha256 == NULL || data == NULL) {
  14948. return 0;
  14949. }
  14950. #if defined(LITTLE_ENDIAN_ORDER)
  14951. {
  14952. ByteReverseWords((word32*)data, (word32*)data, WC_SHA256_BLOCK_SIZE);
  14953. }
  14954. #endif
  14955. ret = wc_Sha256Transform((wc_Sha256*)sha256, data);
  14956. /* return 1 on success, 0 otherwise */
  14957. if (ret == 0)
  14958. return 1;
  14959. else
  14960. return 0;
  14961. }
  14962. #endif
  14963. #endif
  14964. #ifdef WOLFSSL_SHA384
  14965. int wolfSSL_SHA384_Init(WOLFSSL_SHA384_CTX* sha)
  14966. {
  14967. int ret;
  14968. typedef char sha_test[sizeof(SHA384_CTX) >= sizeof(wc_Sha384) ? 1 : -1];
  14969. (void)sizeof(sha_test);
  14970. WOLFSSL_ENTER("SHA384_Init");
  14971. ret = wc_InitSha384((wc_Sha384*)sha);
  14972. /* return 1 on success, 0 otherwise */
  14973. if (ret == 0)
  14974. return 1;
  14975. return 0;
  14976. }
  14977. int wolfSSL_SHA384_Update(WOLFSSL_SHA384_CTX* sha, const void* input,
  14978. unsigned long sz)
  14979. {
  14980. int ret;
  14981. WOLFSSL_ENTER("SHA384_Update");
  14982. ret = wc_Sha384Update((wc_Sha384*)sha, (const byte*)input, (word32)sz);
  14983. /* return 1 on success, 0 otherwise */
  14984. if (ret == 0)
  14985. return 1;
  14986. return 0;
  14987. }
  14988. int wolfSSL_SHA384_Final(byte* output, WOLFSSL_SHA384_CTX* sha)
  14989. {
  14990. int ret;
  14991. WOLFSSL_ENTER("SHA384_Final");
  14992. ret = wc_Sha384Final((wc_Sha384*)sha, output);
  14993. /* have to actually free the resources (if any) here, because the
  14994. * OpenSSL API doesn't include SHA*_Free().
  14995. */
  14996. wc_Sha384Free((wc_Sha384*)sha);
  14997. /* return 1 on success, 0 otherwise */
  14998. if (ret == 0)
  14999. return 1;
  15000. return 0;
  15001. }
  15002. #endif /* WOLFSSL_SHA384 */
  15003. #ifdef WOLFSSL_SHA512
  15004. int wolfSSL_SHA512_Init(WOLFSSL_SHA512_CTX* sha)
  15005. {
  15006. int ret;
  15007. typedef char sha_test[sizeof(SHA512_CTX) >= sizeof(wc_Sha512) ? 1 : -1];
  15008. (void)sizeof(sha_test);
  15009. WOLFSSL_ENTER("SHA512_Init");
  15010. ret = wc_InitSha512((wc_Sha512*)sha);
  15011. /* return 1 on success, 0 otherwise */
  15012. if (ret == 0)
  15013. return 1;
  15014. return 0;
  15015. }
  15016. int wolfSSL_SHA512_Update(WOLFSSL_SHA512_CTX* sha, const void* input,
  15017. unsigned long sz)
  15018. {
  15019. int ret;
  15020. WOLFSSL_ENTER("SHA512_Update");
  15021. ret = wc_Sha512Update((wc_Sha512*)sha, (const byte*)input, (word32)sz);
  15022. /* return 1 on success, 0 otherwise */
  15023. if (ret == 0)
  15024. return 1;
  15025. return 0;
  15026. }
  15027. int wolfSSL_SHA512_Final(byte* output, WOLFSSL_SHA512_CTX* sha)
  15028. {
  15029. int ret;
  15030. WOLFSSL_ENTER("SHA512_Final");
  15031. ret = wc_Sha512Final((wc_Sha512*)sha, output);
  15032. /* have to actually free the resources (if any) here, because the
  15033. * OpenSSL API doesn't include SHA*_Free().
  15034. */
  15035. wc_Sha512Free((wc_Sha512*)sha);
  15036. /* return 1 on success, 0 otherwise */
  15037. if (ret == 0)
  15038. return 1;
  15039. return 0;
  15040. }
  15041. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
  15042. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2)))
  15043. /* Apply SHA512 transformation to the data */
  15044. int wolfSSL_SHA512_Transform(WOLFSSL_SHA512_CTX* sha512,
  15045. const unsigned char* data)
  15046. {
  15047. int ret;
  15048. WOLFSSL_ENTER("SHA512_Transform");
  15049. /* sanity check */
  15050. if (sha512 == NULL || data == NULL) {
  15051. return WOLFSSL_FAILURE;
  15052. }
  15053. ret = wc_Sha512Transform((wc_Sha512*)sha512, data);
  15054. /* return 1 on success, 0 otherwise */
  15055. if (ret == 0)
  15056. return WOLFSSL_SUCCESS;
  15057. else
  15058. return WOLFSSL_FAILURE;
  15059. }
  15060. #endif /* !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \
  15061. (HAVE_FIPS_VERSION > 2)) */
  15062. #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  15063. #if !defined(WOLFSSL_NOSHA512_224)
  15064. int wolfSSL_SHA512_224_Init(WOLFSSL_SHA512_224_CTX* sha)
  15065. {
  15066. int ret;
  15067. WOLFSSL_ENTER("wolfSSL_SHA512_224_Init");
  15068. ret = wc_InitSha512_224((wc_Sha512*)sha);
  15069. /* return WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE otherwise */
  15070. if (ret == 0)
  15071. return WOLFSSL_SUCCESS;
  15072. return WOLFSSL_FAILURE;
  15073. }
  15074. int wolfSSL_SHA512_224_Update(WOLFSSL_SHA512_224_CTX* sha,
  15075. const void* input, unsigned long sz)
  15076. {
  15077. int ret;
  15078. WOLFSSL_ENTER("wolfSSL_SHA512_224_Update");
  15079. ret = wc_Sha512_224Update((wc_Sha512*)sha, (const byte*)input, (word32)sz);
  15080. /* return WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE otherwise */
  15081. if (ret == 0)
  15082. return WOLFSSL_SUCCESS;
  15083. return WOLFSSL_FAILURE;
  15084. }
  15085. int wolfSSL_SHA512_224_Final(byte* output, WOLFSSL_SHA512_224_CTX* sha)
  15086. {
  15087. int ret;
  15088. WOLFSSL_ENTER("wolfSSL_SHA512_224_Final");
  15089. ret = wc_Sha512_224Final((wc_Sha512*)sha, output);
  15090. /* return WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE otherwise */
  15091. if (ret == 0)
  15092. return WOLFSSL_SUCCESS;
  15093. return WOLFSSL_FAILURE;
  15094. }
  15095. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
  15096. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2)))
  15097. /* Apply SHA512 transformation to the data */
  15098. int wolfSSL_SHA512_224_Transform(WOLFSSL_SHA512_CTX* sha512,
  15099. const unsigned char* data)
  15100. {
  15101. int ret;
  15102. WOLFSSL_ENTER("SHA512_224_Transform");
  15103. /* sanity check */
  15104. if (sha512 == NULL || data == NULL) {
  15105. return WOLFSSL_FAILURE;
  15106. }
  15107. ret = wc_Sha512_224Transform((wc_Sha512*)sha512, data);
  15108. /* return 1 on success, 0 otherwise */
  15109. if (ret == 0)
  15110. return WOLFSSL_SUCCESS;
  15111. else
  15112. return WOLFSSL_FAILURE;
  15113. }
  15114. #endif /* !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \
  15115. (HAVE_FIPS_VERSION > 2)) */
  15116. #endif /* !WOLFSSL_NOSHA512_224 */
  15117. #if !defined(WOLFSSL_NOSHA512_256)
  15118. int wolfSSL_SHA512_256_Init(WOLFSSL_SHA512_256_CTX* sha)
  15119. {
  15120. int ret;
  15121. WOLFSSL_ENTER("wolfSSL_SHA512_256_Init");
  15122. ret = wc_InitSha512_256((wc_Sha512*)sha);
  15123. /* return WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE otherwise */
  15124. if (ret == 0)
  15125. return WOLFSSL_SUCCESS;
  15126. return WOLFSSL_FAILURE;
  15127. }
  15128. int wolfSSL_SHA512_256_Update(WOLFSSL_SHA512_256_CTX* sha,
  15129. const void* input, unsigned long sz)
  15130. {
  15131. int ret;
  15132. WOLFSSL_ENTER("wolfSSL_SHA512_256_Update");
  15133. ret = wc_Sha512_256Update((wc_Sha512*)sha, (const byte*)input, (word32)sz);
  15134. /* return WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE otherwise */
  15135. if (ret == 0)
  15136. return WOLFSSL_SUCCESS;
  15137. return WOLFSSL_FAILURE;
  15138. }
  15139. int wolfSSL_SHA512_256_Final(byte* output, WOLFSSL_SHA512_256_CTX* sha)
  15140. {
  15141. int ret;
  15142. WOLFSSL_ENTER("wolfSSL_SHA512_256_Final");
  15143. ret = wc_Sha512_256Final((wc_Sha512*)sha, output);
  15144. /* return WOLFSSL_SUCCESS on success, 0 otherwise */
  15145. if (ret == 0)
  15146. return WOLFSSL_SUCCESS;
  15147. return WOLFSSL_FAILURE;
  15148. }
  15149. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
  15150. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2)))
  15151. /* Apply SHA512 transformation to the data */
  15152. int wolfSSL_SHA512_256_Transform(WOLFSSL_SHA512_CTX* sha512,
  15153. const unsigned char* data)
  15154. {
  15155. int ret;
  15156. WOLFSSL_ENTER("SHA512_256_Transform");
  15157. /* sanity check */
  15158. if (sha512 == NULL || data == NULL) {
  15159. return WOLFSSL_FAILURE;
  15160. }
  15161. ret = wc_Sha512_256Transform((wc_Sha512*)sha512, data);
  15162. /* return 1 on success, 0 otherwise */
  15163. if (ret == 0)
  15164. return WOLFSSL_SUCCESS;
  15165. else
  15166. return WOLFSSL_FAILURE;
  15167. }
  15168. #endif /* !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \
  15169. (HAVE_FIPS_VERSION > 2)) */
  15170. #endif /* !WOLFSSL_NOSHA512_256 */
  15171. #endif /* !HAVE_FIPS && !HAVE_SELFTEST */
  15172. #endif /* WOLFSSL_SHA512 */
  15173. #ifdef WOLFSSL_SHA3
  15174. #ifndef WOLFSSL_NOSHA3_224
  15175. int wolfSSL_SHA3_224_Init(WOLFSSL_SHA3_224_CTX* sha)
  15176. {
  15177. int ret;
  15178. typedef char sha_test[sizeof(SHA3_224_CTX) >= sizeof(wc_Sha3) ? 1 : -1];
  15179. (void)sizeof(sha_test);
  15180. WOLFSSL_ENTER("SHA3_224_Init");
  15181. ret = wc_InitSha3_224((wc_Sha3*)sha, NULL, INVALID_DEVID);
  15182. /* return 1 on success, 0 otherwise */
  15183. if (ret == 0)
  15184. return 1;
  15185. return 0;
  15186. }
  15187. int wolfSSL_SHA3_224_Update(WOLFSSL_SHA3_224_CTX* sha, const void* input,
  15188. unsigned long sz)
  15189. {
  15190. int ret;
  15191. WOLFSSL_ENTER("SHA3_224_Update");
  15192. ret = wc_Sha3_224_Update((wc_Sha3*)sha, (const byte*)input, (word32)sz);
  15193. /* return 1 on success, 0 otherwise */
  15194. if (ret == 0)
  15195. return 1;
  15196. return 0;
  15197. }
  15198. int wolfSSL_SHA3_224_Final(byte* output, WOLFSSL_SHA3_224_CTX* sha)
  15199. {
  15200. int ret;
  15201. WOLFSSL_ENTER("SHA3_224_Final");
  15202. ret = wc_Sha3_224_Final((wc_Sha3*)sha, output);
  15203. /* have to actually free the resources (if any) here, because the
  15204. * OpenSSL API doesn't include SHA*_Free().
  15205. */
  15206. wc_Sha3_224_Free((wc_Sha3*)sha);
  15207. /* return 1 on success, 0 otherwise */
  15208. if (ret == 0)
  15209. return 1;
  15210. return 0;
  15211. }
  15212. #endif /* WOLFSSL_NOSHA3_224 */
  15213. #ifndef WOLFSSL_NOSHA3_256
  15214. int wolfSSL_SHA3_256_Init(WOLFSSL_SHA3_256_CTX* sha3_256)
  15215. {
  15216. int ret;
  15217. typedef char sha_test[sizeof(SHA3_256_CTX) >= sizeof(wc_Sha3) ? 1 : -1];
  15218. (void)sizeof(sha_test);
  15219. WOLFSSL_ENTER("SHA3_256_Init");
  15220. ret = wc_InitSha3_256((wc_Sha3*)sha3_256, NULL, INVALID_DEVID);
  15221. /* return 1 on success, 0 otherwise */
  15222. if (ret == 0)
  15223. return 1;
  15224. return 0;
  15225. }
  15226. int wolfSSL_SHA3_256_Update(WOLFSSL_SHA3_256_CTX* sha, const void* input,
  15227. unsigned long sz)
  15228. {
  15229. int ret;
  15230. WOLFSSL_ENTER("SHA3_256_Update");
  15231. ret = wc_Sha3_256_Update((wc_Sha3*)sha, (const byte*)input, (word32)sz);
  15232. /* return 1 on success, 0 otherwise */
  15233. if (ret == 0)
  15234. return 1;
  15235. return 0;
  15236. }
  15237. int wolfSSL_SHA3_256_Final(byte* output, WOLFSSL_SHA3_256_CTX* sha)
  15238. {
  15239. int ret;
  15240. WOLFSSL_ENTER("SHA3_256_Final");
  15241. ret = wc_Sha3_256_Final((wc_Sha3*)sha, output);
  15242. /* have to actually free the resources (if any) here, because the
  15243. * OpenSSL API doesn't include SHA*_Free().
  15244. */
  15245. wc_Sha3_256_Free((wc_Sha3*)sha);
  15246. /* return 1 on success, 0 otherwise */
  15247. if (ret == 0)
  15248. return 1;
  15249. return 0;
  15250. }
  15251. #endif /* WOLFSSL_NOSHA3_256 */
  15252. int wolfSSL_SHA3_384_Init(WOLFSSL_SHA3_384_CTX* sha)
  15253. {
  15254. int ret;
  15255. typedef char sha_test[sizeof(SHA3_384_CTX) >= sizeof(wc_Sha3) ? 1 : -1];
  15256. (void)sizeof(sha_test);
  15257. WOLFSSL_ENTER("SHA3_384_Init");
  15258. ret = wc_InitSha3_384((wc_Sha3*)sha, NULL, INVALID_DEVID);
  15259. /* return 1 on success, 0 otherwise */
  15260. if (ret == 0)
  15261. return 1;
  15262. return 0;
  15263. }
  15264. int wolfSSL_SHA3_384_Update(WOLFSSL_SHA3_384_CTX* sha, const void* input,
  15265. unsigned long sz)
  15266. {
  15267. int ret;
  15268. WOLFSSL_ENTER("SHA3_384_Update");
  15269. ret = wc_Sha3_384_Update((wc_Sha3*)sha, (const byte*)input, (word32)sz);
  15270. /* return 1 on success, 0 otherwise */
  15271. if (ret == 0)
  15272. return 1;
  15273. return 0;
  15274. }
  15275. int wolfSSL_SHA3_384_Final(byte* output, WOLFSSL_SHA3_384_CTX* sha)
  15276. {
  15277. int ret;
  15278. WOLFSSL_ENTER("SHA3_384_Final");
  15279. ret = wc_Sha3_384_Final((wc_Sha3*)sha, output);
  15280. /* have to actually free the resources (if any) here, because the
  15281. * OpenSSL API doesn't include SHA*_Free().
  15282. */
  15283. wc_Sha3_384_Free((wc_Sha3*)sha);
  15284. /* return 1 on success, 0 otherwise */
  15285. if (ret == 0)
  15286. return 1;
  15287. return 0;
  15288. }
  15289. #ifndef WOLFSSL_NOSHA3_512
  15290. int wolfSSL_SHA3_512_Init(WOLFSSL_SHA3_512_CTX* sha)
  15291. {
  15292. int ret;
  15293. typedef char sha_test[sizeof(SHA3_512_CTX) >= sizeof(wc_Sha3) ? 1 : -1];
  15294. (void)sizeof(sha_test);
  15295. WOLFSSL_ENTER("SHA3_512_Init");
  15296. ret = wc_InitSha3_512((wc_Sha3*)sha, NULL, INVALID_DEVID);
  15297. /* return 1 on success, 0 otherwise */
  15298. if (ret == 0)
  15299. return 1;
  15300. return 0;
  15301. }
  15302. int wolfSSL_SHA3_512_Update(WOLFSSL_SHA3_512_CTX* sha, const void* input,
  15303. unsigned long sz)
  15304. {
  15305. int ret;
  15306. WOLFSSL_ENTER("SHA3_512_Update");
  15307. ret = wc_Sha3_512_Update((wc_Sha3*)sha, (const byte*)input, (word32)sz);
  15308. /* return 1 on success, 0 otherwise */
  15309. if (ret == 0)
  15310. return 1;
  15311. return 0;
  15312. }
  15313. int wolfSSL_SHA3_512_Final(byte* output, WOLFSSL_SHA3_512_CTX* sha)
  15314. {
  15315. int ret;
  15316. WOLFSSL_ENTER("SHA3_512_Final");
  15317. ret = wc_Sha3_512_Final((wc_Sha3*)sha, output);
  15318. /* have to actually free the resources (if any) here, because the
  15319. * OpenSSL API doesn't include SHA*_Free().
  15320. */
  15321. wc_Sha3_512_Free((wc_Sha3*)sha);
  15322. /* return 1 on success, 0 otherwise */
  15323. if (ret == 0)
  15324. return 1;
  15325. return 0;
  15326. }
  15327. #endif /* WOLFSSL_NOSHA3_512 */
  15328. #endif /* WOLFSSL_SHA3 */
  15329. unsigned char* wolfSSL_HMAC(const WOLFSSL_EVP_MD* evp_md, const void* key,
  15330. int key_len, const unsigned char* d, int n,
  15331. unsigned char* md, unsigned int* md_len)
  15332. {
  15333. int type;
  15334. int mdlen;
  15335. unsigned char* ret = NULL;
  15336. #ifdef WOLFSSL_SMALL_STACK
  15337. Hmac* hmac = NULL;
  15338. #else
  15339. Hmac hmac[1];
  15340. #endif
  15341. void* heap = NULL;
  15342. WOLFSSL_ENTER("wolfSSL_HMAC");
  15343. if (!md) {
  15344. WOLFSSL_MSG("Static buffer not supported, pass in md buffer");
  15345. return NULL; /* no static buffer support */
  15346. }
  15347. #ifndef NO_MD5
  15348. if (XSTRCMP(evp_md, "MD5") == 0) {
  15349. type = WC_MD5;
  15350. mdlen = WC_MD5_DIGEST_SIZE;
  15351. } else
  15352. #endif
  15353. #ifdef WOLFSSL_SHA224
  15354. if (XSTRCMP(evp_md, "SHA224") == 0) {
  15355. type = WC_SHA224;
  15356. mdlen = WC_SHA224_DIGEST_SIZE;
  15357. } else
  15358. #endif
  15359. #ifndef NO_SHA256
  15360. if (XSTRCMP(evp_md, "SHA256") == 0) {
  15361. type = WC_SHA256;
  15362. mdlen = WC_SHA256_DIGEST_SIZE;
  15363. } else
  15364. #endif
  15365. #ifdef WOLFSSL_SHA384
  15366. if (XSTRCMP(evp_md, "SHA384") == 0) {
  15367. type = WC_SHA384;
  15368. mdlen = WC_SHA384_DIGEST_SIZE;
  15369. } else
  15370. #endif
  15371. #ifdef WOLFSSL_SHA512
  15372. if (XSTRCMP(evp_md, "SHA512") == 0) {
  15373. type = WC_SHA512;
  15374. mdlen = WC_SHA512_DIGEST_SIZE;
  15375. } else
  15376. #endif
  15377. #ifdef WOLFSSL_SHA3
  15378. #ifndef WOLFSSL_NOSHA3_224
  15379. if (XSTRCMP(evp_md, "SHA3_224") == 0) {
  15380. type = WC_SHA3_224;
  15381. mdlen = WC_SHA3_224_DIGEST_SIZE;
  15382. } else
  15383. #endif
  15384. #ifndef WOLFSSL_NOSHA3_256
  15385. if (XSTRCMP(evp_md, "SHA3_256") == 0) {
  15386. type = WC_SHA3_256;
  15387. mdlen = WC_SHA3_256_DIGEST_SIZE;
  15388. } else
  15389. #endif
  15390. if (XSTRCMP(evp_md, "SHA3_384") == 0) {
  15391. type = WC_SHA3_384;
  15392. mdlen = WC_SHA3_384_DIGEST_SIZE;
  15393. } else
  15394. #ifndef WOLFSSL_NOSHA3_512
  15395. if (XSTRCMP(evp_md, "SHA3_512") == 0) {
  15396. type = WC_SHA3_512;
  15397. mdlen = WC_SHA3_512_DIGEST_SIZE;
  15398. } else
  15399. #endif
  15400. #endif
  15401. #ifndef NO_SHA
  15402. if (XSTRCMP(evp_md, "SHA") == 0) {
  15403. type = WC_SHA;
  15404. mdlen = WC_SHA_DIGEST_SIZE;
  15405. } else
  15406. #endif
  15407. {
  15408. return NULL;
  15409. }
  15410. #ifdef WOLFSSL_SMALL_STACK
  15411. hmac = (Hmac*)XMALLOC(sizeof(Hmac), heap, DYNAMIC_TYPE_HMAC);
  15412. if (hmac == NULL)
  15413. return NULL;
  15414. #endif
  15415. if (wc_HmacInit(hmac, heap, INVALID_DEVID) == 0) {
  15416. if (wc_HmacSetKey(hmac, type, (const byte*)key, key_len) == 0) {
  15417. if (wc_HmacUpdate(hmac, d, n) == 0) {
  15418. if (wc_HmacFinal(hmac, md) == 0) {
  15419. if (md_len)
  15420. *md_len = mdlen;
  15421. ret = md;
  15422. }
  15423. }
  15424. }
  15425. wc_HmacFree(hmac);
  15426. }
  15427. #ifdef WOLFSSL_SMALL_STACK
  15428. XFREE(hmac, heap, DYNAMIC_TYPE_HMAC);
  15429. #endif
  15430. (void)evp_md;
  15431. return ret;
  15432. }
  15433. #ifndef NO_DES3
  15434. /* 0 on ok */
  15435. int wolfSSL_DES_key_sched(WOLFSSL_const_DES_cblock* key,
  15436. WOLFSSL_DES_key_schedule* schedule)
  15437. {
  15438. WOLFSSL_ENTER("wolfSSL_DES_key_sched");
  15439. if (key == NULL || schedule == NULL) {
  15440. WOLFSSL_MSG("Null argument passed in");
  15441. }
  15442. else {
  15443. XMEMCPY(schedule, key, sizeof(WOLFSSL_const_DES_cblock));
  15444. }
  15445. return 0;
  15446. }
  15447. /* intended to behave similar to Kerberos mit_des_cbc_cksum
  15448. * return the last 4 bytes of cipher text */
  15449. WOLFSSL_DES_LONG wolfSSL_DES_cbc_cksum(const unsigned char* in,
  15450. WOLFSSL_DES_cblock* out, long length, WOLFSSL_DES_key_schedule* sc,
  15451. WOLFSSL_const_DES_cblock* iv)
  15452. {
  15453. WOLFSSL_DES_LONG ret;
  15454. unsigned char* tmp;
  15455. unsigned char* data = (unsigned char*)in;
  15456. long dataSz = length;
  15457. byte dynamicFlag = 0; /* when padding the buffer created needs free'd */
  15458. WOLFSSL_ENTER("wolfSSL_DES_cbc_cksum");
  15459. if (in == NULL || out == NULL || sc == NULL || iv == NULL) {
  15460. WOLFSSL_MSG("Bad argument passed in");
  15461. return 0;
  15462. }
  15463. /* if input length is not a multiple of DES_BLOCK_SIZE pad with 0s */
  15464. if (dataSz % DES_BLOCK_SIZE) {
  15465. dataSz += DES_BLOCK_SIZE - (dataSz % DES_BLOCK_SIZE);
  15466. data = (unsigned char*)XMALLOC(dataSz, NULL,
  15467. DYNAMIC_TYPE_TMP_BUFFER);
  15468. if (data == NULL) {
  15469. WOLFSSL_MSG("Issue creating temporary buffer");
  15470. return 0;
  15471. }
  15472. dynamicFlag = 1; /* set to free buffer at end */
  15473. XMEMCPY(data, in, length);
  15474. XMEMSET(data + length, 0, dataSz - length); /* padding */
  15475. }
  15476. tmp = (unsigned char*)XMALLOC(dataSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  15477. if (tmp == NULL) {
  15478. WOLFSSL_MSG("Issue creating temporary buffer");
  15479. if (dynamicFlag == 1) {
  15480. XFREE(data, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  15481. }
  15482. return 0;
  15483. }
  15484. wolfSSL_DES_cbc_encrypt(data, tmp, dataSz, sc,
  15485. (WOLFSSL_DES_cblock*)iv, 1);
  15486. XMEMCPY((unsigned char*)out, tmp + (dataSz - DES_BLOCK_SIZE),
  15487. DES_BLOCK_SIZE);
  15488. ret = (((*((unsigned char*)out + 4) & 0xFF) << 24)|
  15489. ((*((unsigned char*)out + 5) & 0xFF) << 16)|
  15490. ((*((unsigned char*)out + 6) & 0xFF) << 8) |
  15491. (*((unsigned char*)out + 7) & 0xFF));
  15492. XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  15493. if (dynamicFlag == 1) {
  15494. XFREE(data, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  15495. }
  15496. return ret;
  15497. }
  15498. void wolfSSL_DES_cbc_encrypt(const unsigned char* input,
  15499. unsigned char* output, long length,
  15500. WOLFSSL_DES_key_schedule* schedule,
  15501. WOLFSSL_DES_cblock* ivec, int enc)
  15502. {
  15503. Des myDes;
  15504. byte lastblock[DES_BLOCK_SIZE];
  15505. int lb_sz;
  15506. long blk;
  15507. WOLFSSL_ENTER("DES_cbc_encrypt");
  15508. /* OpenSSL compat, no ret */
  15509. if (wc_Des_SetKey(&myDes, (const byte*)schedule, (const byte*)ivec,
  15510. !enc) != 0) {
  15511. WOLFSSL_MSG("wc_Des_SetKey return error.");
  15512. return;
  15513. }
  15514. lb_sz = length%DES_BLOCK_SIZE;
  15515. blk = length/DES_BLOCK_SIZE;
  15516. if (enc == DES_ENCRYPT){
  15517. wc_Des_CbcEncrypt(&myDes, output, input, (word32)blk*DES_BLOCK_SIZE);
  15518. if(lb_sz){
  15519. XMEMSET(lastblock, 0, DES_BLOCK_SIZE);
  15520. XMEMCPY(lastblock, input+length-lb_sz, lb_sz);
  15521. wc_Des_CbcEncrypt(&myDes, output+blk*DES_BLOCK_SIZE,
  15522. lastblock, (word32)DES_BLOCK_SIZE);
  15523. }
  15524. }
  15525. else {
  15526. wc_Des_CbcDecrypt(&myDes, output, input, (word32)blk*DES_BLOCK_SIZE);
  15527. if(lb_sz){
  15528. wc_Des_CbcDecrypt(&myDes, lastblock, input+length-lb_sz, (word32)DES_BLOCK_SIZE);
  15529. XMEMCPY(output+length-lb_sz, lastblock, lb_sz);
  15530. }
  15531. }
  15532. }
  15533. /* WOLFSSL_DES_key_schedule is a unsigned char array of size 8 */
  15534. void wolfSSL_DES_ede3_cbc_encrypt(const unsigned char* input,
  15535. unsigned char* output, long sz,
  15536. WOLFSSL_DES_key_schedule* ks1,
  15537. WOLFSSL_DES_key_schedule* ks2,
  15538. WOLFSSL_DES_key_schedule* ks3,
  15539. WOLFSSL_DES_cblock* ivec, int enc)
  15540. {
  15541. int ret;
  15542. Des3 des;
  15543. byte key[24];/* EDE uses 24 size key */
  15544. byte lastblock[DES_BLOCK_SIZE];
  15545. int lb_sz;
  15546. long blk;
  15547. WOLFSSL_ENTER("wolfSSL_DES_ede3_cbc_encrypt");
  15548. XMEMSET(key, 0, sizeof(key));
  15549. XMEMCPY(key, *ks1, DES_BLOCK_SIZE);
  15550. XMEMCPY(&key[DES_BLOCK_SIZE], *ks2, DES_BLOCK_SIZE);
  15551. XMEMCPY(&key[DES_BLOCK_SIZE * 2], *ks3, DES_BLOCK_SIZE);
  15552. lb_sz = sz%DES_BLOCK_SIZE;
  15553. blk = sz/DES_BLOCK_SIZE;
  15554. /* OpenSSL compat, no ret */
  15555. (void)wc_Des3Init(&des, NULL, INVALID_DEVID);
  15556. if (enc == DES_ENCRYPT) {
  15557. if (wc_Des3_SetKey(&des, key, (const byte*)ivec,
  15558. DES_ENCRYPTION) == 0) {
  15559. ret = wc_Des3_CbcEncrypt(&des, output, input, (word32)blk*DES_BLOCK_SIZE);
  15560. #if defined(WOLFSSL_ASYNC_CRYPT)
  15561. ret = wc_AsyncWait(ret, &des.asyncDev, WC_ASYNC_FLAG_NONE);
  15562. #endif
  15563. (void)ret; /* ignore return codes for processing */
  15564. if(lb_sz){
  15565. XMEMSET(lastblock, 0, DES_BLOCK_SIZE);
  15566. XMEMCPY(lastblock, input+sz-lb_sz, lb_sz);
  15567. ret = wc_Des3_CbcEncrypt(&des, output+blk*DES_BLOCK_SIZE,
  15568. lastblock, (word32)DES_BLOCK_SIZE);
  15569. #if defined(WOLFSSL_ASYNC_CRYPT)
  15570. ret = wc_AsyncWait(ret, &des.asyncDev, WC_ASYNC_FLAG_NONE);
  15571. #endif
  15572. (void)ret; /* ignore return codes for processing */
  15573. }
  15574. }
  15575. }
  15576. else {
  15577. if (wc_Des3_SetKey(&des, key, (const byte*)ivec,
  15578. DES_DECRYPTION) == 0) {
  15579. ret = wc_Des3_CbcDecrypt(&des, output, input, (word32)blk*DES_BLOCK_SIZE);
  15580. #if defined(WOLFSSL_ASYNC_CRYPT)
  15581. ret = wc_AsyncWait(ret, &des.asyncDev, WC_ASYNC_FLAG_NONE);
  15582. #endif
  15583. (void)ret; /* ignore return codes for processing */
  15584. if(lb_sz){
  15585. ret = wc_Des3_CbcDecrypt(&des, lastblock, input+sz-lb_sz, (word32)DES_BLOCK_SIZE);
  15586. #if defined(WOLFSSL_ASYNC_CRYPT)
  15587. ret = wc_AsyncWait(ret, &des.asyncDev, WC_ASYNC_FLAG_NONE);
  15588. #endif
  15589. (void)ret; /* ignore return codes for processing */
  15590. XMEMCPY(output+sz-lb_sz, lastblock, lb_sz);
  15591. }
  15592. }
  15593. }
  15594. wc_Des3Free(&des);
  15595. }
  15596. /* correctly sets ivec for next call */
  15597. void wolfSSL_DES_ncbc_encrypt(const unsigned char* input,
  15598. unsigned char* output, long length,
  15599. WOLFSSL_DES_key_schedule* schedule, WOLFSSL_DES_cblock* ivec,
  15600. int enc)
  15601. {
  15602. Des myDes;
  15603. byte lastblock[DES_BLOCK_SIZE];
  15604. int lb_sz;
  15605. long idx = length;
  15606. long blk;
  15607. WOLFSSL_ENTER("DES_ncbc_encrypt");
  15608. /* OpenSSL compat, no ret */
  15609. if (wc_Des_SetKey(&myDes, (const byte*)schedule,
  15610. (const byte*)ivec, !enc) != 0) {
  15611. WOLFSSL_MSG("wc_Des_SetKey return error.");
  15612. return;
  15613. }
  15614. lb_sz = length%DES_BLOCK_SIZE;
  15615. blk = length/DES_BLOCK_SIZE;
  15616. idx -= sizeof(DES_cblock);
  15617. if (lb_sz) {
  15618. idx += DES_BLOCK_SIZE - lb_sz;
  15619. }
  15620. if (enc == DES_ENCRYPT){
  15621. wc_Des_CbcEncrypt(&myDes, output, input,
  15622. (word32)blk * DES_BLOCK_SIZE);
  15623. if (lb_sz){
  15624. XMEMSET(lastblock, 0, DES_BLOCK_SIZE);
  15625. XMEMCPY(lastblock, input+length-lb_sz, lb_sz);
  15626. wc_Des_CbcEncrypt(&myDes, output + blk * DES_BLOCK_SIZE,
  15627. lastblock, (word32)DES_BLOCK_SIZE);
  15628. }
  15629. XMEMCPY(ivec, output + idx, sizeof(DES_cblock));
  15630. } else {
  15631. WOLFSSL_DES_cblock tmp;
  15632. XMEMCPY(tmp, input + idx, sizeof(DES_cblock));
  15633. wc_Des_CbcDecrypt(&myDes, output, input,
  15634. (word32)blk * DES_BLOCK_SIZE);
  15635. if (lb_sz){
  15636. wc_Des_CbcDecrypt(&myDes, lastblock, input + length - lb_sz,
  15637. (word32)DES_BLOCK_SIZE);
  15638. XMEMCPY(output+length-lb_sz, lastblock, lb_sz);
  15639. }
  15640. XMEMCPY(ivec, tmp, sizeof(WOLFSSL_DES_cblock));
  15641. }
  15642. }
  15643. #endif /* NO_DES3 */
  15644. void wolfSSL_ERR_free_strings(void)
  15645. {
  15646. /* handled internally */
  15647. }
  15648. void wolfSSL_cleanup_all_ex_data(void)
  15649. {
  15650. /* nothing to do here */
  15651. }
  15652. #endif /* OPENSSL_EXTRA */
  15653. #if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE)
  15654. void wolfSSL_ERR_clear_error(void)
  15655. {
  15656. WOLFSSL_ENTER("wolfSSL_ERR_clear_error");
  15657. wc_ClearErrorNodes();
  15658. }
  15659. #endif
  15660. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  15661. int wolfSSL_clear(WOLFSSL* ssl)
  15662. {
  15663. WOLFSSL_ENTER("wolfSSL_clear");
  15664. if (ssl == NULL) {
  15665. return WOLFSSL_FAILURE;
  15666. }
  15667. if (!ssl->options.handShakeDone) {
  15668. /* Only reset the session if we didn't complete a handshake */
  15669. wolfSSL_SESSION_free(ssl->session);
  15670. ssl->session = wolfSSL_NewSession(ssl->heap);
  15671. if (ssl->session == NULL) {
  15672. return WOLFSSL_FAILURE;
  15673. }
  15674. }
  15675. /* reset option bits */
  15676. ssl->options.isClosed = 0;
  15677. ssl->options.connReset = 0;
  15678. ssl->options.sentNotify = 0;
  15679. ssl->options.closeNotify = 0;
  15680. ssl->options.sendVerify = 0;
  15681. ssl->options.serverState = NULL_STATE;
  15682. ssl->options.clientState = NULL_STATE;
  15683. ssl->options.connectState = CONNECT_BEGIN;
  15684. ssl->options.acceptState = ACCEPT_BEGIN;
  15685. ssl->options.handShakeState = NULL_STATE;
  15686. ssl->options.handShakeDone = 0;
  15687. ssl->options.processReply = 0; /* doProcessInit */
  15688. ssl->options.havePeerVerify = 0;
  15689. ssl->options.havePeerCert = 0;
  15690. ssl->options.peerAuthGood = 0;
  15691. ssl->options.tls1_3 = 0;
  15692. ssl->options.haveSessionId = 0;
  15693. ssl->options.tls = 0;
  15694. ssl->options.tls1_1 = 0;
  15695. ssl->options.noPskDheKe = 0;
  15696. #ifdef HAVE_SESSION_TICKET
  15697. #ifdef WOLFSSL_TLS13
  15698. ssl->options.ticketsSent = 0;
  15699. #endif
  15700. ssl->options.rejectTicket = 0;
  15701. #endif
  15702. #ifdef WOLFSSL_EARLY_DATA
  15703. ssl->earlyData = no_early_data;
  15704. ssl->earlyDataSz = 0;
  15705. #endif
  15706. #if defined(HAVE_TLS_EXTENSIONS) && !defined(NO_TLS)
  15707. TLSX_FreeAll(ssl->extensions, ssl->heap);
  15708. ssl->extensions = NULL;
  15709. #endif
  15710. ssl->keys.encryptionOn = 0;
  15711. XMEMSET(&ssl->msgsReceived, 0, sizeof(ssl->msgsReceived));
  15712. if (InitHandshakeHashes(ssl) != 0)
  15713. return WOLFSSL_FAILURE;
  15714. #ifdef KEEP_PEER_CERT
  15715. FreeX509(&ssl->peerCert);
  15716. InitX509(&ssl->peerCert, 0, ssl->heap);
  15717. #endif
  15718. #ifdef WOLFSSL_QUIC
  15719. wolfSSL_quic_clear(ssl);
  15720. #endif
  15721. return WOLFSSL_SUCCESS;
  15722. }
  15723. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  15724. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
  15725. long wolfSSL_CTX_set_mode(WOLFSSL_CTX* ctx, long mode)
  15726. {
  15727. /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */
  15728. WOLFSSL_ENTER("SSL_CTX_set_mode");
  15729. switch(mode) {
  15730. case SSL_MODE_ENABLE_PARTIAL_WRITE:
  15731. ctx->partialWrite = 1;
  15732. break;
  15733. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  15734. case SSL_MODE_RELEASE_BUFFERS:
  15735. WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented.");
  15736. break;
  15737. #endif
  15738. case SSL_MODE_AUTO_RETRY:
  15739. ctx->autoRetry = 1;
  15740. break;
  15741. default:
  15742. WOLFSSL_MSG("Mode Not Implemented");
  15743. }
  15744. /* SSL_MODE_AUTO_RETRY
  15745. * Should not return -1 with renegotiation on read/write */
  15746. return mode;
  15747. }
  15748. long wolfSSL_CTX_clear_mode(WOLFSSL_CTX* ctx, long mode)
  15749. {
  15750. /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */
  15751. WOLFSSL_ENTER("SSL_CTX_set_mode");
  15752. switch(mode) {
  15753. case SSL_MODE_ENABLE_PARTIAL_WRITE:
  15754. ctx->partialWrite = 0;
  15755. break;
  15756. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  15757. case SSL_MODE_RELEASE_BUFFERS:
  15758. WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented.");
  15759. break;
  15760. #endif
  15761. case SSL_MODE_AUTO_RETRY:
  15762. ctx->autoRetry = 0;
  15763. break;
  15764. default:
  15765. WOLFSSL_MSG("Mode Not Implemented");
  15766. }
  15767. /* SSL_MODE_AUTO_RETRY
  15768. * Should not return -1 with renegotiation on read/write */
  15769. return 0;
  15770. }
  15771. #endif
  15772. #ifdef OPENSSL_EXTRA
  15773. #ifndef NO_WOLFSSL_STUB
  15774. long wolfSSL_SSL_get_mode(WOLFSSL* ssl)
  15775. {
  15776. /* TODO: */
  15777. (void)ssl;
  15778. WOLFSSL_STUB("SSL_get_mode");
  15779. return 0;
  15780. }
  15781. #endif
  15782. #ifndef NO_WOLFSSL_STUB
  15783. long wolfSSL_CTX_get_mode(WOLFSSL_CTX* ctx)
  15784. {
  15785. /* TODO: */
  15786. (void)ctx;
  15787. WOLFSSL_STUB("SSL_CTX_get_mode");
  15788. return 0;
  15789. }
  15790. #endif
  15791. #ifndef NO_WOLFSSL_STUB
  15792. void wolfSSL_CTX_set_default_read_ahead(WOLFSSL_CTX* ctx, int m)
  15793. {
  15794. /* TODO: maybe? */
  15795. (void)ctx;
  15796. (void)m;
  15797. WOLFSSL_STUB("SSL_CTX_set_default_read_ahead");
  15798. }
  15799. #endif
  15800. /* Storing app session context id, this value is inherited by WOLFSSL
  15801. * objects created from WOLFSSL_CTX. Any session that is imported with a
  15802. * different session context id will be rejected.
  15803. *
  15804. * ctx structure to set context in
  15805. * sid_ctx value of context to set
  15806. * sid_ctx_len length of sid_ctx buffer
  15807. *
  15808. * Returns WOLFSSL_SUCCESS in success case and SSL_FAILURE when failing
  15809. */
  15810. int wolfSSL_CTX_set_session_id_context(WOLFSSL_CTX* ctx,
  15811. const unsigned char* sid_ctx,
  15812. unsigned int sid_ctx_len)
  15813. {
  15814. WOLFSSL_ENTER("SSL_CTX_set_session_id_context");
  15815. /* No application specific context needed for wolfSSL */
  15816. if (sid_ctx_len > ID_LEN || ctx == NULL || sid_ctx == NULL) {
  15817. return SSL_FAILURE;
  15818. }
  15819. XMEMCPY(ctx->sessionCtx, sid_ctx, sid_ctx_len);
  15820. ctx->sessionCtxSz = (byte)sid_ctx_len;
  15821. return WOLFSSL_SUCCESS;
  15822. }
  15823. /* Storing app session context id. Any session that is imported with a
  15824. * different session context id will be rejected.
  15825. *
  15826. * ssl structure to set context in
  15827. * id value of context to set
  15828. * len length of sid_ctx buffer
  15829. *
  15830. * Returns WOLFSSL_SUCCESS in success case and SSL_FAILURE when failing
  15831. */
  15832. int wolfSSL_set_session_id_context(WOLFSSL* ssl, const unsigned char* id,
  15833. unsigned int len)
  15834. {
  15835. WOLFSSL_ENTER("wolfSSL_set_session_id_context");
  15836. if (len > ID_LEN || ssl == NULL || id == NULL) {
  15837. return SSL_FAILURE;
  15838. }
  15839. XMEMCPY(ssl->sessionCtx, id, len);
  15840. ssl->sessionCtxSz = (byte)len;
  15841. return WOLFSSL_SUCCESS;
  15842. }
  15843. long wolfSSL_CTX_sess_get_cache_size(WOLFSSL_CTX* ctx)
  15844. {
  15845. (void)ctx;
  15846. #ifndef NO_SESSION_CACHE
  15847. return (long)(SESSIONS_PER_ROW * SESSION_ROWS);
  15848. #else
  15849. return 0;
  15850. #endif
  15851. }
  15852. /* returns the unsigned error value and increments the pointer into the
  15853. * error queue.
  15854. *
  15855. * file pointer to file name
  15856. * line gets set to line number of error when not NULL
  15857. */
  15858. unsigned long wolfSSL_ERR_get_error_line(const char** file, int* line)
  15859. {
  15860. #ifdef WOLFSSL_HAVE_ERROR_QUEUE
  15861. int ret = wc_PullErrorNode(file, NULL, line);
  15862. if (ret < 0) {
  15863. if (ret == BAD_STATE_E) return 0; /* no errors in queue */
  15864. WOLFSSL_MSG("Issue getting error node");
  15865. WOLFSSL_LEAVE("wolfSSL_ERR_get_error_line", ret);
  15866. ret = 0 - ret; /* return absolute value of error */
  15867. /* panic and try to clear out nodes */
  15868. wc_ClearErrorNodes();
  15869. }
  15870. return (unsigned long)ret;
  15871. #else
  15872. (void)file;
  15873. (void)line;
  15874. return 0;
  15875. #endif
  15876. }
  15877. #if (defined(DEBUG_WOLFSSL) || defined(OPENSSL_EXTRA)) && \
  15878. (!defined(_WIN32) && !defined(NO_ERROR_QUEUE))
  15879. static const char WOLFSSL_SYS_ACCEPT_T[] = "accept";
  15880. static const char WOLFSSL_SYS_BIND_T[] = "bind";
  15881. static const char WOLFSSL_SYS_CONNECT_T[] = "connect";
  15882. static const char WOLFSSL_SYS_FOPEN_T[] = "fopen";
  15883. static const char WOLFSSL_SYS_FREAD_T[] = "fread";
  15884. static const char WOLFSSL_SYS_GETADDRINFO_T[] = "getaddrinfo";
  15885. static const char WOLFSSL_SYS_GETSOCKOPT_T[] = "getsockopt";
  15886. static const char WOLFSSL_SYS_GETSOCKNAME_T[] = "getsockname";
  15887. static const char WOLFSSL_SYS_GETHOSTBYNAME_T[] = "gethostbyname";
  15888. static const char WOLFSSL_SYS_GETNAMEINFO_T[] = "getnameinfo";
  15889. static const char WOLFSSL_SYS_GETSERVBYNAME_T[] = "getservbyname";
  15890. static const char WOLFSSL_SYS_IOCTLSOCKET_T[] = "ioctlsocket";
  15891. static const char WOLFSSL_SYS_LISTEN_T[] = "listen";
  15892. static const char WOLFSSL_SYS_OPENDIR_T[] = "opendir";
  15893. static const char WOLFSSL_SYS_SETSOCKOPT_T[] = "setsockopt";
  15894. static const char WOLFSSL_SYS_SOCKET_T[] = "socket";
  15895. /* switch with int mapped to function name for compatibility */
  15896. static const char* wolfSSL_ERR_sys_func(int fun)
  15897. {
  15898. switch (fun) {
  15899. case WOLFSSL_SYS_ACCEPT: return WOLFSSL_SYS_ACCEPT_T;
  15900. case WOLFSSL_SYS_BIND: return WOLFSSL_SYS_BIND_T;
  15901. case WOLFSSL_SYS_CONNECT: return WOLFSSL_SYS_CONNECT_T;
  15902. case WOLFSSL_SYS_FOPEN: return WOLFSSL_SYS_FOPEN_T;
  15903. case WOLFSSL_SYS_FREAD: return WOLFSSL_SYS_FREAD_T;
  15904. case WOLFSSL_SYS_GETADDRINFO: return WOLFSSL_SYS_GETADDRINFO_T;
  15905. case WOLFSSL_SYS_GETSOCKOPT: return WOLFSSL_SYS_GETSOCKOPT_T;
  15906. case WOLFSSL_SYS_GETSOCKNAME: return WOLFSSL_SYS_GETSOCKNAME_T;
  15907. case WOLFSSL_SYS_GETHOSTBYNAME: return WOLFSSL_SYS_GETHOSTBYNAME_T;
  15908. case WOLFSSL_SYS_GETNAMEINFO: return WOLFSSL_SYS_GETNAMEINFO_T;
  15909. case WOLFSSL_SYS_GETSERVBYNAME: return WOLFSSL_SYS_GETSERVBYNAME_T;
  15910. case WOLFSSL_SYS_IOCTLSOCKET: return WOLFSSL_SYS_IOCTLSOCKET_T;
  15911. case WOLFSSL_SYS_LISTEN: return WOLFSSL_SYS_LISTEN_T;
  15912. case WOLFSSL_SYS_OPENDIR: return WOLFSSL_SYS_OPENDIR_T;
  15913. case WOLFSSL_SYS_SETSOCKOPT: return WOLFSSL_SYS_SETSOCKOPT_T;
  15914. case WOLFSSL_SYS_SOCKET: return WOLFSSL_SYS_SOCKET_T;
  15915. default:
  15916. return "NULL";
  15917. }
  15918. }
  15919. #endif /* DEBUG_WOLFSSL */
  15920. void wolfSSL_ERR_put_error(int lib, int fun, int err, const char* file,
  15921. int line)
  15922. {
  15923. WOLFSSL_ENTER("wolfSSL_ERR_put_error");
  15924. #if !defined(DEBUG_WOLFSSL) && !defined(OPENSSL_EXTRA)
  15925. (void)fun;
  15926. (void)err;
  15927. (void)file;
  15928. (void)line;
  15929. WOLFSSL_MSG("Not compiled in debug mode");
  15930. #elif defined(OPENSSL_EXTRA) && \
  15931. (defined(_WIN32) || defined(NO_ERROR_QUEUE))
  15932. (void)fun;
  15933. (void)file;
  15934. (void)line;
  15935. WOLFSSL_ERROR(err);
  15936. #else
  15937. WOLFSSL_ERROR_LINE(err, wolfSSL_ERR_sys_func(fun), (unsigned int)line,
  15938. file, NULL);
  15939. #endif
  15940. (void)lib;
  15941. }
  15942. /* Similar to wolfSSL_ERR_get_error_line but takes in a flags argument for
  15943. * more flexibility.
  15944. *
  15945. * file output pointer to file where error happened
  15946. * line output to line number of error
  15947. * data output data. Is a string if ERR_TXT_STRING flag is used
  15948. * flags output format of output
  15949. *
  15950. * Returns the error value or 0 if no errors are in the queue
  15951. */
  15952. unsigned long wolfSSL_ERR_get_error_line_data(const char** file, int* line,
  15953. const char** data, int *flags)
  15954. {
  15955. #ifdef WOLFSSL_HAVE_ERROR_QUEUE
  15956. int ret;
  15957. WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data");
  15958. if (flags != NULL)
  15959. *flags = ERR_TXT_STRING; /* Clear the flags */
  15960. ret = wc_PullErrorNode(file, data, line);
  15961. if (ret < 0) {
  15962. if (ret == BAD_STATE_E) return 0; /* no errors in queue */
  15963. WOLFSSL_MSG("Error with pulling error node!");
  15964. WOLFSSL_LEAVE("wolfSSL_ERR_get_error_line_data", ret);
  15965. ret = 0 - ret; /* return absolute value of error */
  15966. /* panic and try to clear out nodes */
  15967. wc_ClearErrorNodes();
  15968. }
  15969. return (unsigned long)ret;
  15970. #else
  15971. WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data");
  15972. WOLFSSL_MSG("Error queue turned off, can not get error line");
  15973. (void)file;
  15974. (void)line;
  15975. (void)data;
  15976. (void)flags;
  15977. return 0;
  15978. #endif
  15979. }
  15980. #endif /* OPENSSL_EXTRA */
  15981. #if (defined(KEEP_PEER_CERT) && defined(SESSION_CERTS)) || \
  15982. (defined(OPENSSL_EXTRA) && defined(SESSION_CERTS))
  15983. /* Decode the X509 DER encoded certificate into a WOLFSSL_X509 object.
  15984. *
  15985. * x509 WOLFSSL_X509 object to decode into.
  15986. * in X509 DER data.
  15987. * len Length of the X509 DER data.
  15988. * returns the new certificate on success, otherwise NULL.
  15989. */
  15990. static int DecodeToX509(WOLFSSL_X509* x509, const byte* in, int len)
  15991. {
  15992. int ret;
  15993. #ifdef WOLFSSL_SMALL_STACK
  15994. DecodedCert* cert;
  15995. #else
  15996. DecodedCert cert[1];
  15997. #endif
  15998. if (x509 == NULL || in == NULL || len <= 0)
  15999. return BAD_FUNC_ARG;
  16000. #ifdef WOLFSSL_SMALL_STACK
  16001. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  16002. DYNAMIC_TYPE_DCERT);
  16003. if (cert == NULL)
  16004. return MEMORY_E;
  16005. #endif
  16006. /* Create a DecodedCert object and copy fields into WOLFSSL_X509 object.
  16007. */
  16008. InitDecodedCert(cert, (byte*)in, len, NULL);
  16009. if ((ret = ParseCertRelative(cert, CERT_TYPE, 0, NULL)) == 0) {
  16010. /* Check if x509 was not previously initialized by wolfSSL_X509_new() */
  16011. if (x509->dynamicMemory != TRUE)
  16012. InitX509(x509, 0, NULL);
  16013. ret = CopyDecodedToX509(x509, cert);
  16014. FreeDecodedCert(cert);
  16015. }
  16016. #ifdef WOLFSSL_SMALL_STACK
  16017. XFREE(cert, NULL, DYNAMIC_TYPE_DCERT);
  16018. #endif
  16019. return ret;
  16020. }
  16021. #endif /* (KEEP_PEER_CERT & SESSION_CERTS) || (OPENSSL_EXTRA & SESSION_CERTS) */
  16022. #ifdef KEEP_PEER_CERT
  16023. WOLFSSL_ABI
  16024. WOLFSSL_X509* wolfSSL_get_peer_certificate(WOLFSSL* ssl)
  16025. {
  16026. WOLFSSL_X509* ret = NULL;
  16027. WOLFSSL_ENTER("SSL_get_peer_certificate");
  16028. if (ssl != NULL) {
  16029. if (ssl->peerCert.issuer.sz)
  16030. ret = wolfSSL_X509_dup(&ssl->peerCert);
  16031. #ifdef SESSION_CERTS
  16032. else if (ssl->session->chain.count > 0) {
  16033. if (DecodeToX509(&ssl->peerCert, ssl->session->chain.certs[0].buffer,
  16034. ssl->session->chain.certs[0].length) == 0) {
  16035. ret = wolfSSL_X509_dup(&ssl->peerCert);
  16036. }
  16037. }
  16038. #endif
  16039. }
  16040. WOLFSSL_LEAVE("SSL_get_peer_certificate", ret != NULL);
  16041. return ret;
  16042. }
  16043. #endif /* KEEP_PEER_CERT */
  16044. #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
  16045. /* Return stack of peer certs.
  16046. * Caller does not need to free return. The stack is Free'd when WOLFSSL* ssl is.
  16047. */
  16048. WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_get_peer_cert_chain(const WOLFSSL* ssl)
  16049. {
  16050. WOLFSSL_ENTER("wolfSSL_get_peer_cert_chain");
  16051. if (ssl == NULL)
  16052. return NULL;
  16053. /* Try to populate if NULL or empty */
  16054. if (ssl->peerCertChain == NULL ||
  16055. wolfSSL_sk_X509_num(ssl->peerCertChain) == 0)
  16056. wolfSSL_set_peer_cert_chain((WOLFSSL*) ssl);
  16057. return ssl->peerCertChain;
  16058. }
  16059. #ifndef WOLFSSL_QT
  16060. static int x509GetIssuerFromCM(WOLFSSL_X509 **issuer, WOLFSSL_CERT_MANAGER* cm,
  16061. WOLFSSL_X509 *x);
  16062. /**
  16063. * Recursively push the issuer CA chain onto the stack
  16064. * @param cm The cert manager that is queried for the issuer
  16065. * @param x This cert's issuer will be queried in cm
  16066. * @param sk The issuer is pushed onto this stack
  16067. * @return WOLFSSL_SUCCESS on success
  16068. * WOLFSSL_FAILURE on no issuer found
  16069. * WOLFSSL_FATAL_ERROR on a fatal error
  16070. */
  16071. static int PushCAx509Chain(WOLFSSL_CERT_MANAGER* cm,
  16072. WOLFSSL_X509 *x, WOLFSSL_STACK* sk)
  16073. {
  16074. WOLFSSL_X509* issuer[MAX_CHAIN_DEPTH];
  16075. int i;
  16076. int push = 1;
  16077. int ret = WOLFSSL_SUCCESS;
  16078. for (i = 0; i < MAX_CHAIN_DEPTH; i++) {
  16079. if (x509GetIssuerFromCM(&issuer[i], cm, x)
  16080. != WOLFSSL_SUCCESS)
  16081. break;
  16082. x = issuer[i];
  16083. }
  16084. if (i == 0) /* No further chain found */
  16085. return WOLFSSL_FAILURE;
  16086. i--;
  16087. for (; i >= 0; i--) {
  16088. if (push) {
  16089. if (wolfSSL_sk_X509_push(sk, issuer[i]) != WOLFSSL_SUCCESS) {
  16090. wolfSSL_X509_free(issuer[i]);
  16091. ret = WOLFSSL_FATAL_ERROR;
  16092. push = 0; /* Free the rest of the unpushed certs */
  16093. }
  16094. }
  16095. else {
  16096. wolfSSL_X509_free(issuer[i]);
  16097. }
  16098. }
  16099. return ret;
  16100. }
  16101. #endif /* !WOLFSSL_QT */
  16102. /* Builds up and creates a stack of peer certificates for ssl->peerCertChain
  16103. based off of the ssl session chain. Attempts to place CA certificates
  16104. at the bottom of the stack. Returns stack of WOLFSSL_X509 certs or
  16105. NULL on failure */
  16106. WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_set_peer_cert_chain(WOLFSSL* ssl)
  16107. {
  16108. WOLFSSL_STACK* sk;
  16109. WOLFSSL_X509* x509;
  16110. int i = 0;
  16111. int ret;
  16112. WOLFSSL_ENTER("wolfSSL_set_peer_cert_chain");
  16113. if ((ssl == NULL) || (ssl->session->chain.count == 0))
  16114. return NULL;
  16115. sk = wolfSSL_sk_X509_new();
  16116. i = ssl->session->chain.count-1;
  16117. for (; i >= 0; i--) {
  16118. x509 = wolfSSL_X509_new();
  16119. if (x509 == NULL) {
  16120. WOLFSSL_MSG("Error Creating X509");
  16121. wolfSSL_sk_X509_pop_free(sk, NULL);
  16122. return NULL;
  16123. }
  16124. ret = DecodeToX509(x509, ssl->session->chain.certs[i].buffer,
  16125. ssl->session->chain.certs[i].length);
  16126. #if !defined(WOLFSSL_QT)
  16127. if (ret == 0 && i == ssl->session->chain.count-1) {
  16128. /* On the last element in the chain try to add the CA chain
  16129. * first if we have one for this cert */
  16130. if (PushCAx509Chain(SSL_CM(ssl), x509, sk)
  16131. == WOLFSSL_FATAL_ERROR) {
  16132. ret = WOLFSSL_FATAL_ERROR;
  16133. }
  16134. }
  16135. #endif
  16136. if (ret != 0 || wolfSSL_sk_X509_push(sk, x509) != WOLFSSL_SUCCESS) {
  16137. WOLFSSL_MSG("Error decoding cert");
  16138. wolfSSL_X509_free(x509);
  16139. wolfSSL_sk_X509_pop_free(sk, NULL);
  16140. return NULL;
  16141. }
  16142. }
  16143. if (sk == NULL) {
  16144. WOLFSSL_MSG("Null session chain");
  16145. }
  16146. #if defined(OPENSSL_ALL)
  16147. else if (ssl->options.side == WOLFSSL_SERVER_END) {
  16148. /* to be compliant with openssl
  16149. first element is kept as peer cert on server side.*/
  16150. wolfSSL_sk_X509_shift(sk);
  16151. }
  16152. #endif
  16153. if (ssl->peerCertChain != NULL)
  16154. wolfSSL_sk_X509_pop_free(ssl->peerCertChain, NULL);
  16155. /* This is Free'd when ssl is Free'd */
  16156. ssl->peerCertChain = sk;
  16157. return sk;
  16158. }
  16159. #endif /* SESSION_CERTS && OPENSSL_EXTRA */
  16160. #ifndef NO_CERTS
  16161. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  16162. /* create a generic wolfSSL stack node
  16163. * returns a new WOLFSSL_STACK structure on success */
  16164. WOLFSSL_STACK* wolfSSL_sk_new_node(void* heap)
  16165. {
  16166. WOLFSSL_STACK* sk;
  16167. WOLFSSL_ENTER("wolfSSL_sk_new_node");
  16168. sk = (WOLFSSL_STACK*)XMALLOC(sizeof(WOLFSSL_STACK), heap,
  16169. DYNAMIC_TYPE_OPENSSL);
  16170. if (sk != NULL) {
  16171. XMEMSET(sk, 0, sizeof(*sk));
  16172. sk->heap = heap;
  16173. }
  16174. return sk;
  16175. }
  16176. /* free's node but does not free internal data such as in->data.x509 */
  16177. void wolfSSL_sk_free_node(WOLFSSL_STACK* in)
  16178. {
  16179. if (in != NULL) {
  16180. XFREE(in, in->heap, DYNAMIC_TYPE_OPENSSL);
  16181. }
  16182. }
  16183. /* pushes node "in" onto "stack" and returns pointer to the new stack on success
  16184. * also handles internal "num" for number of nodes on stack
  16185. * return WOLFSSL_SUCCESS on success
  16186. */
  16187. int wolfSSL_sk_push_node(WOLFSSL_STACK** stack, WOLFSSL_STACK* in)
  16188. {
  16189. if (stack == NULL || in == NULL) {
  16190. return WOLFSSL_FAILURE;
  16191. }
  16192. if (*stack == NULL) {
  16193. in->num = 1;
  16194. *stack = in;
  16195. return WOLFSSL_SUCCESS;
  16196. }
  16197. in->num = (*stack)->num + 1;
  16198. in->next = *stack;
  16199. *stack = in;
  16200. return WOLFSSL_SUCCESS;
  16201. }
  16202. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16203. static WC_INLINE int compare_WOLFSSL_CIPHER(
  16204. WOLFSSL_CIPHER *a,
  16205. WOLFSSL_CIPHER *b)
  16206. {
  16207. if ((a->cipherSuite0 == b->cipherSuite0) &&
  16208. (a->cipherSuite == b->cipherSuite) &&
  16209. (a->ssl == b->ssl) &&
  16210. (XMEMCMP(a->description, b->description, sizeof a->description) == 0) &&
  16211. (a->offset == b->offset) &&
  16212. (a->in_stack == b->in_stack) &&
  16213. (a->bits == b->bits))
  16214. return 0;
  16215. else
  16216. return -1;
  16217. }
  16218. #endif /* OPENSSL_ALL || WOLFSSL_QT */
  16219. /* return 1 on success 0 on fail */
  16220. int wolfSSL_sk_push(WOLFSSL_STACK* sk, const void *data)
  16221. {
  16222. WOLFSSL_STACK* node;
  16223. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16224. WOLFSSL_CIPHER ciph;
  16225. #endif
  16226. WOLFSSL_ENTER("wolfSSL_sk_push");
  16227. if (!sk) {
  16228. return WOLFSSL_FAILURE;
  16229. }
  16230. /* Check if empty data */
  16231. switch (sk->type) {
  16232. case STACK_TYPE_CIPHER:
  16233. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16234. /* check if entire struct is zero */
  16235. XMEMSET(&ciph, 0, sizeof(WOLFSSL_CIPHER));
  16236. if (compare_WOLFSSL_CIPHER(&sk->data.cipher, &ciph) == 0) {
  16237. sk->data.cipher = *(WOLFSSL_CIPHER*)data;
  16238. sk->num = 1;
  16239. if (sk->hash_fn) {
  16240. sk->hash = sk->hash_fn(&sk->data.cipher);
  16241. }
  16242. return WOLFSSL_SUCCESS;
  16243. }
  16244. break;
  16245. #endif
  16246. case STACK_TYPE_X509:
  16247. case STACK_TYPE_GEN_NAME:
  16248. case STACK_TYPE_BIO:
  16249. case STACK_TYPE_OBJ:
  16250. case STACK_TYPE_STRING:
  16251. case STACK_TYPE_ACCESS_DESCRIPTION:
  16252. case STACK_TYPE_X509_EXT:
  16253. case STACK_TYPE_X509_REQ_ATTR:
  16254. case STACK_TYPE_NULL:
  16255. case STACK_TYPE_X509_NAME:
  16256. case STACK_TYPE_X509_NAME_ENTRY:
  16257. case STACK_TYPE_CONF_VALUE:
  16258. case STACK_TYPE_X509_INFO:
  16259. case STACK_TYPE_BY_DIR_entry:
  16260. case STACK_TYPE_BY_DIR_hash:
  16261. case STACK_TYPE_X509_OBJ:
  16262. case STACK_TYPE_DIST_POINT:
  16263. case STACK_TYPE_X509_CRL:
  16264. default:
  16265. /* All other types are pointers */
  16266. if (!sk->data.generic) {
  16267. sk->data.generic = (void*)data;
  16268. sk->num = 1;
  16269. #ifdef OPENSSL_ALL
  16270. if (sk->hash_fn) {
  16271. sk->hash = sk->hash_fn(sk->data.generic);
  16272. }
  16273. #endif
  16274. return WOLFSSL_SUCCESS;
  16275. }
  16276. break;
  16277. }
  16278. /* stack already has value(s) create a new node and add more */
  16279. node = wolfSSL_sk_new_node(sk->heap);
  16280. if (!node) {
  16281. WOLFSSL_MSG("Memory error");
  16282. return WOLFSSL_FAILURE;
  16283. }
  16284. /* push new x509 onto head of stack */
  16285. node->next = sk->next;
  16286. node->type = sk->type;
  16287. sk->next = node;
  16288. sk->num += 1;
  16289. #ifdef OPENSSL_ALL
  16290. node->comp = sk->comp;
  16291. node->hash_fn = sk->hash_fn;
  16292. node->hash = sk->hash;
  16293. sk->hash = 0;
  16294. #endif
  16295. switch (sk->type) {
  16296. case STACK_TYPE_CIPHER:
  16297. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16298. node->data.cipher = sk->data.cipher;
  16299. sk->data.cipher = *(WOLFSSL_CIPHER*)data;
  16300. if (sk->hash_fn) {
  16301. sk->hash = sk->hash_fn(&sk->data.cipher);
  16302. }
  16303. break;
  16304. #endif
  16305. case STACK_TYPE_X509:
  16306. case STACK_TYPE_GEN_NAME:
  16307. case STACK_TYPE_BIO:
  16308. case STACK_TYPE_OBJ:
  16309. case STACK_TYPE_STRING:
  16310. case STACK_TYPE_ACCESS_DESCRIPTION:
  16311. case STACK_TYPE_X509_EXT:
  16312. case STACK_TYPE_X509_REQ_ATTR:
  16313. case STACK_TYPE_NULL:
  16314. case STACK_TYPE_X509_NAME:
  16315. case STACK_TYPE_X509_NAME_ENTRY:
  16316. case STACK_TYPE_CONF_VALUE:
  16317. case STACK_TYPE_X509_INFO:
  16318. case STACK_TYPE_BY_DIR_entry:
  16319. case STACK_TYPE_BY_DIR_hash:
  16320. case STACK_TYPE_X509_OBJ:
  16321. case STACK_TYPE_DIST_POINT:
  16322. case STACK_TYPE_X509_CRL:
  16323. default:
  16324. /* All other types are pointers */
  16325. node->data.generic = sk->data.generic;
  16326. sk->data.generic = (void*)data;
  16327. #ifdef OPENSSL_ALL
  16328. if (sk->hash_fn) {
  16329. sk->hash = sk->hash_fn(sk->data.generic);
  16330. }
  16331. #endif
  16332. break;
  16333. }
  16334. return WOLFSSL_SUCCESS;
  16335. }
  16336. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  16337. #ifdef OPENSSL_EXTRA
  16338. /* returns the node at index "idx", NULL if not found */
  16339. WOLFSSL_STACK* wolfSSL_sk_get_node(WOLFSSL_STACK* sk, int idx)
  16340. {
  16341. int i;
  16342. WOLFSSL_STACK* ret = NULL;
  16343. WOLFSSL_STACK* current;
  16344. current = sk;
  16345. for (i = 0; i <= idx && current != NULL; i++) {
  16346. if (i == idx) {
  16347. ret = current;
  16348. break;
  16349. }
  16350. current = current->next;
  16351. }
  16352. return ret;
  16353. }
  16354. #endif /* OPENSSL_EXTRA */
  16355. #ifdef OPENSSL_EXTRA
  16356. #if defined(OPENSSL_ALL)
  16357. void *wolfSSL_lh_retrieve(WOLFSSL_STACK *sk, void *data)
  16358. {
  16359. unsigned long hash;
  16360. WOLFSSL_ENTER("wolfSSL_lh_retrieve");
  16361. if (!sk || !data) {
  16362. WOLFSSL_MSG("Bad parameters");
  16363. return NULL;
  16364. }
  16365. if (!sk->hash_fn) {
  16366. WOLFSSL_MSG("No hash function defined");
  16367. return NULL;
  16368. }
  16369. hash = sk->hash_fn(data);
  16370. while (sk) {
  16371. /* Calc hash if not done so yet */
  16372. if (!sk->hash) {
  16373. switch (sk->type) {
  16374. case STACK_TYPE_CIPHER:
  16375. sk->hash = sk->hash_fn(&sk->data.cipher);
  16376. break;
  16377. case STACK_TYPE_X509:
  16378. case STACK_TYPE_GEN_NAME:
  16379. case STACK_TYPE_BIO:
  16380. case STACK_TYPE_OBJ:
  16381. case STACK_TYPE_STRING:
  16382. case STACK_TYPE_ACCESS_DESCRIPTION:
  16383. case STACK_TYPE_X509_EXT:
  16384. case STACK_TYPE_X509_REQ_ATTR:
  16385. case STACK_TYPE_NULL:
  16386. case STACK_TYPE_X509_NAME:
  16387. case STACK_TYPE_X509_NAME_ENTRY:
  16388. case STACK_TYPE_CONF_VALUE:
  16389. case STACK_TYPE_X509_INFO:
  16390. case STACK_TYPE_BY_DIR_entry:
  16391. case STACK_TYPE_BY_DIR_hash:
  16392. case STACK_TYPE_X509_OBJ:
  16393. case STACK_TYPE_DIST_POINT:
  16394. case STACK_TYPE_X509_CRL:
  16395. default:
  16396. sk->hash = sk->hash_fn(sk->data.generic);
  16397. break;
  16398. }
  16399. }
  16400. if (sk->hash == hash) {
  16401. switch (sk->type) {
  16402. case STACK_TYPE_CIPHER:
  16403. return &sk->data.cipher;
  16404. case STACK_TYPE_X509:
  16405. case STACK_TYPE_GEN_NAME:
  16406. case STACK_TYPE_BIO:
  16407. case STACK_TYPE_OBJ:
  16408. case STACK_TYPE_STRING:
  16409. case STACK_TYPE_ACCESS_DESCRIPTION:
  16410. case STACK_TYPE_X509_EXT:
  16411. case STACK_TYPE_X509_REQ_ATTR:
  16412. case STACK_TYPE_NULL:
  16413. case STACK_TYPE_X509_NAME:
  16414. case STACK_TYPE_X509_NAME_ENTRY:
  16415. case STACK_TYPE_CONF_VALUE:
  16416. case STACK_TYPE_X509_INFO:
  16417. case STACK_TYPE_BY_DIR_entry:
  16418. case STACK_TYPE_BY_DIR_hash:
  16419. case STACK_TYPE_X509_OBJ:
  16420. case STACK_TYPE_DIST_POINT:
  16421. case STACK_TYPE_X509_CRL:
  16422. default:
  16423. return sk->data.generic;
  16424. }
  16425. }
  16426. sk = sk->next;
  16427. }
  16428. return NULL;
  16429. }
  16430. #endif /* OPENSSL_ALL */
  16431. #endif /* OPENSSL_EXTRA */
  16432. /* OPENSSL_EXTRA is needed for wolfSSL_X509_d21 function
  16433. KEEP_OUR_CERT is to insure ability for returning ssl certificate */
  16434. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  16435. defined(KEEP_OUR_CERT)
  16436. WOLFSSL_X509* wolfSSL_get_certificate(WOLFSSL* ssl)
  16437. {
  16438. if (ssl == NULL) {
  16439. return NULL;
  16440. }
  16441. if (ssl->buffers.weOwnCert) {
  16442. if (ssl->ourCert == NULL) {
  16443. if (ssl->buffers.certificate == NULL) {
  16444. WOLFSSL_MSG("Certificate buffer not set!");
  16445. return NULL;
  16446. }
  16447. #ifndef WOLFSSL_X509_STORE_CERTS
  16448. ssl->ourCert = wolfSSL_X509_d2i(NULL,
  16449. ssl->buffers.certificate->buffer,
  16450. ssl->buffers.certificate->length);
  16451. #endif
  16452. }
  16453. return ssl->ourCert;
  16454. }
  16455. else { /* if cert not owned get parent ctx cert or return null */
  16456. if (ssl->ctx) {
  16457. if (ssl->ctx->ourCert == NULL) {
  16458. if (ssl->ctx->certificate == NULL) {
  16459. WOLFSSL_MSG("Ctx Certificate buffer not set!");
  16460. return NULL;
  16461. }
  16462. #ifndef WOLFSSL_X509_STORE_CERTS
  16463. ssl->ctx->ourCert = wolfSSL_X509_d2i(NULL,
  16464. ssl->ctx->certificate->buffer,
  16465. ssl->ctx->certificate->length);
  16466. #endif
  16467. ssl->ctx->ownOurCert = 1;
  16468. }
  16469. return ssl->ctx->ourCert;
  16470. }
  16471. }
  16472. return NULL;
  16473. }
  16474. WOLFSSL_X509* wolfSSL_CTX_get0_certificate(WOLFSSL_CTX* ctx)
  16475. {
  16476. if (ctx) {
  16477. if (ctx->ourCert == NULL) {
  16478. if (ctx->certificate == NULL) {
  16479. WOLFSSL_MSG("Ctx Certificate buffer not set!");
  16480. return NULL;
  16481. }
  16482. #ifndef WOLFSSL_X509_STORE_CERTS
  16483. ctx->ourCert = wolfSSL_X509_d2i(NULL,
  16484. ctx->certificate->buffer,
  16485. ctx->certificate->length);
  16486. #endif
  16487. ctx->ownOurCert = 1;
  16488. }
  16489. return ctx->ourCert;
  16490. }
  16491. return NULL;
  16492. }
  16493. #endif /* OPENSSL_EXTRA && KEEP_OUR_CERT */
  16494. #endif /* NO_CERTS */
  16495. #if !defined(NO_ASN) && (defined(OPENSSL_EXTRA) || \
  16496. defined(OPENSSL_EXTRA_X509_SMALL))
  16497. void wolfSSL_ASN1_OBJECT_free(WOLFSSL_ASN1_OBJECT* obj)
  16498. {
  16499. if (obj == NULL) {
  16500. return;
  16501. }
  16502. if ((obj->obj != NULL) && ((obj->dynamic & WOLFSSL_ASN1_DYNAMIC_DATA) != 0)) {
  16503. #ifdef WOLFSSL_DEBUG_OPENSSL
  16504. WOLFSSL_MSG("Freeing ASN1 data");
  16505. #endif
  16506. XFREE((void*)obj->obj, obj->heap, DYNAMIC_TYPE_ASN1);
  16507. obj->obj = NULL;
  16508. }
  16509. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
  16510. if (obj->pathlen != NULL) {
  16511. wolfSSL_ASN1_INTEGER_free(obj->pathlen);
  16512. obj->pathlen = NULL;
  16513. }
  16514. #endif
  16515. if ((obj->dynamic & WOLFSSL_ASN1_DYNAMIC) != 0) {
  16516. #ifdef WOLFSSL_DEBUG_OPENSSL
  16517. WOLFSSL_MSG("Freeing ASN1 OBJECT");
  16518. #endif
  16519. XFREE(obj, NULL, DYNAMIC_TYPE_ASN1);
  16520. }
  16521. }
  16522. WOLFSSL_ASN1_OBJECT* wolfSSL_ASN1_OBJECT_new(void)
  16523. {
  16524. WOLFSSL_ASN1_OBJECT* obj;
  16525. obj = (WOLFSSL_ASN1_OBJECT*)XMALLOC(sizeof(WOLFSSL_ASN1_OBJECT), NULL,
  16526. DYNAMIC_TYPE_ASN1);
  16527. if (obj == NULL) {
  16528. return NULL;
  16529. }
  16530. XMEMSET(obj, 0, sizeof(WOLFSSL_ASN1_OBJECT));
  16531. obj->d.ia5 = &(obj->d.ia5_internal);
  16532. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
  16533. obj->d.iPAddress = &(obj->d.iPAddress_internal);
  16534. #endif
  16535. obj->dynamic |= WOLFSSL_ASN1_DYNAMIC;
  16536. return obj;
  16537. }
  16538. WOLFSSL_ASN1_OBJECT* wolfSSL_ASN1_OBJECT_dup(WOLFSSL_ASN1_OBJECT* obj)
  16539. {
  16540. WOLFSSL_ASN1_OBJECT* dupl = NULL;
  16541. WOLFSSL_ENTER("wolfSSL_ASN1_OBJECT_dup");
  16542. if (!obj) {
  16543. WOLFSSL_MSG("Bad parameter");
  16544. return NULL;
  16545. }
  16546. dupl = wolfSSL_ASN1_OBJECT_new();
  16547. if (!dupl) {
  16548. WOLFSSL_MSG("wolfSSL_ASN1_OBJECT_new error");
  16549. return NULL;
  16550. }
  16551. /* Copy data */
  16552. XMEMCPY(dupl->sName, obj->sName, WOLFSSL_MAX_SNAME);
  16553. dupl->type = obj->type;
  16554. dupl->grp = obj->grp;
  16555. dupl->nid = obj->nid;
  16556. dupl->objSz = obj->objSz;
  16557. if (obj->obj) {
  16558. dupl->obj = (const unsigned char*)XMALLOC(
  16559. obj->objSz, NULL, DYNAMIC_TYPE_ASN1);
  16560. if (!dupl->obj) {
  16561. WOLFSSL_MSG("ASN1 obj malloc error");
  16562. wolfSSL_ASN1_OBJECT_free(dupl);
  16563. return NULL;
  16564. }
  16565. XMEMCPY((byte*)dupl->obj, obj->obj, obj->objSz);
  16566. dupl->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA;
  16567. }
  16568. return dupl;
  16569. }
  16570. #endif /* !NO_ASN && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */
  16571. #ifndef NO_ASN
  16572. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  16573. /* Creates and returns a new WOLFSSL_CIPHER stack. */
  16574. WOLFSSL_STACK* wolfSSL_sk_new_asn1_obj(void)
  16575. {
  16576. WOLFSSL_STACK* sk;
  16577. WOLFSSL_ENTER("wolfSSL_sk_new_asn1_obj");
  16578. sk = wolfSSL_sk_new_null();
  16579. if (sk == NULL)
  16580. return NULL;
  16581. sk->type = STACK_TYPE_OBJ;
  16582. return sk;
  16583. }
  16584. /* return 1 on success 0 on fail */
  16585. int wolfSSL_sk_ASN1_OBJECT_push(WOLF_STACK_OF(WOLFSSL_ASN1_OBJECT)* sk,
  16586. WOLFSSL_ASN1_OBJECT* obj)
  16587. {
  16588. WOLFSSL_ENTER("wolfSSL_sk_ASN1_OBJECT_push");
  16589. if (sk == NULL || obj == NULL) {
  16590. return WOLFSSL_FAILURE;
  16591. }
  16592. return wolfSSL_sk_push(sk, obj);
  16593. }
  16594. WOLFSSL_ASN1_OBJECT* wolfSSL_sk_ASN1_OBJECT_pop(
  16595. WOLF_STACK_OF(WOLFSSL_ASN1_OBJECT)* sk)
  16596. {
  16597. WOLFSSL_STACK* node;
  16598. WOLFSSL_ASN1_OBJECT* obj;
  16599. if (sk == NULL) {
  16600. return NULL;
  16601. }
  16602. node = sk->next;
  16603. obj = sk->data.obj;
  16604. if (node != NULL) { /* update sk and remove node from stack */
  16605. sk->data.obj = node->data.obj;
  16606. sk->next = node->next;
  16607. XFREE(node, NULL, DYNAMIC_TYPE_ASN1);
  16608. }
  16609. else { /* last obj in stack */
  16610. sk->data.obj = NULL;
  16611. }
  16612. if (sk->num > 0) {
  16613. sk->num -= 1;
  16614. }
  16615. return obj;
  16616. }
  16617. /* Free the structure for ASN1_OBJECT stack
  16618. *
  16619. * sk stack to free nodes in
  16620. */
  16621. void wolfSSL_sk_ASN1_OBJECT_free(WOLF_STACK_OF(WOLFSSL_ASN1_OBJECT)* sk)
  16622. {
  16623. wolfSSL_sk_free(sk);
  16624. }
  16625. /* Free's all nodes in ASN1_OBJECT stack.
  16626. * This is different then wolfSSL_ASN1_OBJECT_free in that it allows for
  16627. * choosing the function to use when freeing an ASN1_OBJECT stack.
  16628. *
  16629. * sk stack to free nodes in
  16630. * f X509 free function
  16631. */
  16632. void wolfSSL_sk_ASN1_OBJECT_pop_free(WOLF_STACK_OF(WOLFSSL_ASN1_OBJECT)* sk,
  16633. void (*f) (WOLFSSL_ASN1_OBJECT*))
  16634. {
  16635. WOLFSSL_ENTER("wolfSSL_sk_ASN1_OBJECT_pop_free");
  16636. wolfSSL_sk_pop_free(sk, (wolfSSL_sk_freefunc)f);
  16637. }
  16638. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  16639. #endif /* !NO_ASN */
  16640. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16641. #ifndef NO_ASN
  16642. int wolfSSL_ASN1_STRING_to_UTF8(unsigned char **out, WOLFSSL_ASN1_STRING *in)
  16643. {
  16644. /*
  16645. ASN1_STRING_to_UTF8() converts the string in to UTF8 format,
  16646. the converted data is allocated in a buffer in *out.
  16647. The length of out is returned or a negative error code.
  16648. The buffer *out should be free using OPENSSL_free().
  16649. */
  16650. unsigned char* buf;
  16651. unsigned char* inPtr;
  16652. int inLen;
  16653. if (!out || !in) {
  16654. return -1;
  16655. }
  16656. inPtr = wolfSSL_ASN1_STRING_data(in);
  16657. inLen = wolfSSL_ASN1_STRING_length(in);
  16658. if (!inPtr || inLen < 0) {
  16659. return -1;
  16660. }
  16661. buf = (unsigned char*)XMALLOC(inLen + 1, NULL, DYNAMIC_TYPE_OPENSSL);
  16662. if (!buf) {
  16663. return -1;
  16664. }
  16665. XMEMCPY(buf, inPtr, inLen + 1);
  16666. *out = buf;
  16667. return inLen;
  16668. }
  16669. #endif /* !NO_ASN */
  16670. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  16671. #if defined(OPENSSL_EXTRA)
  16672. #ifndef NO_ASN
  16673. int wolfSSL_ASN1_UNIVERSALSTRING_to_string(WOLFSSL_ASN1_STRING *s)
  16674. {
  16675. char *idx;
  16676. char *copy;
  16677. WOLFSSL_ENTER("wolfSSL_ASN1_UNIVERSALSTRING_to_string");
  16678. if (!s) {
  16679. WOLFSSL_MSG("Bad parameter");
  16680. return WOLFSSL_FAILURE;
  16681. }
  16682. if (s->type != V_ASN1_UNIVERSALSTRING) {
  16683. WOLFSSL_MSG("Input is not a universal string");
  16684. return WOLFSSL_FAILURE;
  16685. }
  16686. if ((s->length % 4) != 0) {
  16687. WOLFSSL_MSG("Input string must be divisible by 4");
  16688. return WOLFSSL_FAILURE;
  16689. }
  16690. for (idx = s->data; idx < s->data + s->length; idx += 4)
  16691. if ((idx[0] != '\0') || (idx[1] != '\0') || (idx[2] != '\0'))
  16692. break;
  16693. if (idx != s->data + s->length) {
  16694. WOLFSSL_MSG("Wrong string format");
  16695. return WOLFSSL_FAILURE;
  16696. }
  16697. for (copy = idx = s->data; idx < s->data + s->length; idx += 4)
  16698. *copy++ = idx[3];
  16699. *copy = '\0';
  16700. s->length /= 4;
  16701. s->type = V_ASN1_PRINTABLESTRING;
  16702. return WOLFSSL_SUCCESS;
  16703. }
  16704. /* Returns string representation of ASN1_STRING */
  16705. char* wolfSSL_i2s_ASN1_STRING(WOLFSSL_v3_ext_method *method,
  16706. const WOLFSSL_ASN1_STRING *s)
  16707. {
  16708. int i;
  16709. int tmpSz = 100;
  16710. int valSz = 5;
  16711. char* tmp;
  16712. char val[5];
  16713. unsigned char* str;
  16714. WOLFSSL_ENTER("wolfSSL_i2s_ASN1_STRING");
  16715. (void)method;
  16716. if(s == NULL || s->data == NULL) {
  16717. WOLFSSL_MSG("Bad Function Argument");
  16718. return NULL;
  16719. }
  16720. str = (unsigned char*)XMALLOC(s->length, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  16721. if (str == NULL) {
  16722. WOLFSSL_MSG("Memory Error");
  16723. return NULL;
  16724. }
  16725. XMEMCPY(str, (unsigned char*)s->data, s->length);
  16726. tmp = (char*)XMALLOC(tmpSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  16727. if (tmp == NULL) {
  16728. WOLFSSL_MSG("Memory Error");
  16729. XFREE(str, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  16730. return NULL;
  16731. }
  16732. XMEMSET(tmp, 0, tmpSz);
  16733. for (i = 0; i < tmpSz && i < (s->length - 1); i++) {
  16734. if (XSNPRINTF(val, valSz, "%02X:", str[i])
  16735. >= valSz)
  16736. {
  16737. WOLFSSL_MSG("Buffer overrun");
  16738. XFREE(str, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  16739. return NULL;
  16740. }
  16741. XSTRNCAT(tmp, val, valSz);
  16742. }
  16743. if (XSNPRINTF(val, valSz, "%02X", str[i])
  16744. >= valSz)
  16745. {
  16746. WOLFSSL_MSG("Buffer overrun");
  16747. XFREE(str, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  16748. return NULL;
  16749. }
  16750. XSTRNCAT(tmp, val, valSz);
  16751. XFREE(str, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  16752. return tmp;
  16753. }
  16754. #endif /* NO_ASN */
  16755. #endif /* OPENSSL_EXTRA */
  16756. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  16757. void wolfSSL_set_connect_state(WOLFSSL* ssl)
  16758. {
  16759. WOLFSSL_ENTER("wolfSSL_set_connect_state");
  16760. if (ssl == NULL) {
  16761. WOLFSSL_MSG("WOLFSSL struct pointer passed in was null");
  16762. return;
  16763. }
  16764. #ifndef NO_DH
  16765. /* client creates its own DH parameters on handshake */
  16766. if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) {
  16767. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  16768. DYNAMIC_TYPE_PUBLIC_KEY);
  16769. }
  16770. ssl->buffers.serverDH_P.buffer = NULL;
  16771. if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) {
  16772. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  16773. DYNAMIC_TYPE_PUBLIC_KEY);
  16774. }
  16775. ssl->buffers.serverDH_G.buffer = NULL;
  16776. #endif
  16777. if (InitSSL_Side(ssl, WOLFSSL_CLIENT_END) != WOLFSSL_SUCCESS) {
  16778. WOLFSSL_MSG("Error initializing client side");
  16779. }
  16780. }
  16781. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  16782. int wolfSSL_get_shutdown(const WOLFSSL* ssl)
  16783. {
  16784. int isShutdown = 0;
  16785. WOLFSSL_ENTER("wolfSSL_get_shutdown");
  16786. if (ssl) {
  16787. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  16788. if (ssl->options.handShakeState == NULL_STATE) {
  16789. /* The SSL object was possibly cleared with wolfSSL_clear after
  16790. * a successful shutdown. Simulate a response for a full
  16791. * bidirectional shutdown. */
  16792. isShutdown = WOLFSSL_SENT_SHUTDOWN | WOLFSSL_RECEIVED_SHUTDOWN;
  16793. }
  16794. else
  16795. #endif
  16796. {
  16797. /* in OpenSSL, WOLFSSL_SENT_SHUTDOWN = 1, when closeNotifySent *
  16798. * WOLFSSL_RECEIVED_SHUTDOWN = 2, from close notify or fatal err */
  16799. if (ssl->options.sentNotify)
  16800. isShutdown |= WOLFSSL_SENT_SHUTDOWN;
  16801. if (ssl->options.closeNotify||ssl->options.connReset)
  16802. isShutdown |= WOLFSSL_RECEIVED_SHUTDOWN;
  16803. }
  16804. }
  16805. return isShutdown;
  16806. }
  16807. int wolfSSL_session_reused(WOLFSSL* ssl)
  16808. {
  16809. int resuming = 0;
  16810. WOLFSSL_ENTER("wolfSSL_session_reused");
  16811. if (ssl)
  16812. resuming = ssl->options.resuming;
  16813. WOLFSSL_LEAVE("wolfSSL_session_reused", resuming);
  16814. return resuming;
  16815. }
  16816. /* return a new malloc'd session with default settings on success */
  16817. WOLFSSL_SESSION* wolfSSL_NewSession(void* heap)
  16818. {
  16819. WOLFSSL_SESSION* ret = NULL;
  16820. ret = (WOLFSSL_SESSION*)XMALLOC(sizeof(WOLFSSL_SESSION), heap,
  16821. DYNAMIC_TYPE_SESSION);
  16822. if (ret != NULL) {
  16823. XMEMSET(ret, 0, sizeof(WOLFSSL_SESSION));
  16824. #ifndef SINGLE_THREADED
  16825. if (wc_InitMutex(&ret->refMutex) != 0) {
  16826. WOLFSSL_MSG("Error setting up session reference mutex");
  16827. XFREE(ret, ret->heap, DYNAMIC_TYPE_SESSION);
  16828. return NULL;
  16829. }
  16830. #endif
  16831. ret->refCount = 1;
  16832. #ifndef NO_SESSION_CACHE
  16833. ret->cacheRow = INVALID_SESSION_ROW; /* not in cache */
  16834. #endif
  16835. ret->type = WOLFSSL_SESSION_TYPE_HEAP;
  16836. ret->heap = heap;
  16837. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16838. wc_MemZero_Add("SESSION master secret", ret->masterSecret, SECRET_LEN);
  16839. wc_MemZero_Add("SESSION id", ret->sessionID, ID_LEN);
  16840. #endif
  16841. #ifdef HAVE_SESSION_TICKET
  16842. ret->ticket = ret->staticTicket;
  16843. #endif
  16844. #ifdef HAVE_STUNNEL
  16845. /* stunnel has this funny mechanism of storing the "is_authenticated"
  16846. * session info in the session ex data. This is basically their
  16847. * default so let's just hard code it. */
  16848. if (wolfSSL_SESSION_set_ex_data(ret, 0, (void *)(-1))
  16849. != WOLFSSL_SUCCESS) {
  16850. WOLFSSL_MSG("Error setting up ex data for stunnel");
  16851. XFREE(ret, NULL, DYNAMIC_TYPE_SESSION);
  16852. return NULL;
  16853. }
  16854. #endif
  16855. #ifdef HAVE_EX_DATA
  16856. ret->ownExData = 1;
  16857. #endif
  16858. }
  16859. return ret;
  16860. }
  16861. WOLFSSL_SESSION* wolfSSL_SESSION_new_ex(void* heap)
  16862. {
  16863. return wolfSSL_NewSession(heap);
  16864. }
  16865. WOLFSSL_SESSION* wolfSSL_SESSION_new(void)
  16866. {
  16867. return wolfSSL_SESSION_new_ex(NULL);
  16868. }
  16869. /* add one to session reference count
  16870. * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error */
  16871. int wolfSSL_SESSION_up_ref(WOLFSSL_SESSION* session)
  16872. {
  16873. session = ClientSessionToSession(session);
  16874. if (session == NULL || session->type != WOLFSSL_SESSION_TYPE_HEAP)
  16875. return WOLFSSL_FAILURE;
  16876. #ifndef SINGLE_THREADED
  16877. if (wc_LockMutex(&session->refMutex) != 0) {
  16878. WOLFSSL_MSG("Failed to lock session mutex");
  16879. return WOLFSSL_FAILURE;
  16880. }
  16881. #endif
  16882. session->refCount++;
  16883. #ifndef SINGLE_THREADED
  16884. wc_UnLockMutex(&session->refMutex);
  16885. #endif
  16886. return WOLFSSL_SUCCESS;
  16887. }
  16888. /**
  16889. * Deep copy the contents from input to output.
  16890. * @param input The source of the copy.
  16891. * @param output The destination of the copy.
  16892. * @param avoidSysCalls If true, then system calls will be avoided or an error
  16893. * will be returned if it is not possible to proceed
  16894. * without a system call. This is useful for fetching
  16895. * sessions from cache. When a cache row is locked, we
  16896. * don't want to block other threads with long running
  16897. * system calls.
  16898. * @return WOLFSSL_SUCCESS on success
  16899. * WOLFSSL_FAILURE on failure
  16900. */
  16901. int wolfSSL_DupSession(const WOLFSSL_SESSION* input, WOLFSSL_SESSION* output,
  16902. int avoidSysCalls)
  16903. {
  16904. #ifdef HAVE_SESSION_TICKET
  16905. int ticLenAlloc = 0;
  16906. byte *ticBuff = NULL;
  16907. #endif
  16908. const size_t copyOffset = OFFSETOF(WOLFSSL_SESSION, heap) + sizeof(input->heap);
  16909. int ret = WOLFSSL_SUCCESS;
  16910. (void)avoidSysCalls;
  16911. input = ClientSessionToSession(input);
  16912. output = ClientSessionToSession(output);
  16913. if (input == NULL || output == NULL || input == output) {
  16914. WOLFSSL_MSG("input or output are null or same");
  16915. return WOLFSSL_FAILURE;
  16916. }
  16917. #ifdef HAVE_SESSION_TICKET
  16918. if (output->ticket != output->staticTicket) {
  16919. ticBuff = output->ticket;
  16920. ticLenAlloc = output->ticketLenAlloc;
  16921. }
  16922. #endif
  16923. #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
  16924. if (output->peer != NULL) {
  16925. if (avoidSysCalls) {
  16926. WOLFSSL_MSG("Can't free cert when avoiding syscalls");
  16927. return WOLFSSL_FAILURE;
  16928. }
  16929. wolfSSL_X509_free(output->peer);
  16930. output->peer = NULL;
  16931. }
  16932. #endif
  16933. XMEMCPY((byte*)output + copyOffset, (byte*)input + copyOffset,
  16934. sizeof(WOLFSSL_SESSION) - copyOffset);
  16935. /* Set sane values for copy */
  16936. #ifndef NO_SESSION_CACHE
  16937. if (output->type != WOLFSSL_SESSION_TYPE_CACHE)
  16938. output->cacheRow = INVALID_SESSION_ROW;
  16939. #endif
  16940. #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
  16941. if (input->peer != NULL && input->peer->dynamicMemory) {
  16942. if (wolfSSL_X509_up_ref(input->peer) != WOLFSSL_SUCCESS) {
  16943. WOLFSSL_MSG("Can't increase peer cert ref count");
  16944. output->peer = NULL;
  16945. }
  16946. }
  16947. else if (!avoidSysCalls)
  16948. output->peer = wolfSSL_X509_dup(input->peer);
  16949. else
  16950. /* output->peer is not that important to copy */
  16951. output->peer = NULL;
  16952. #endif
  16953. #ifdef HAVE_SESSION_TICKET
  16954. if (input->ticketLen > SESSION_TICKET_LEN) {
  16955. /* Need dynamic buffer */
  16956. if (ticBuff == NULL || ticLenAlloc < input->ticketLen) {
  16957. /* allocate new one */
  16958. byte* tmp;
  16959. if (avoidSysCalls) {
  16960. WOLFSSL_MSG("Failed to allocate memory for ticket when avoiding"
  16961. " syscalls");
  16962. output->ticket = ticBuff;
  16963. output->ticketLenAlloc = (word16) ticLenAlloc;
  16964. output->ticketLen = 0;
  16965. ret = WOLFSSL_FAILURE;
  16966. }
  16967. else {
  16968. tmp = (byte*)XREALLOC(ticBuff, input->ticketLen,
  16969. output->heap, DYNAMIC_TYPE_SESSION_TICK);
  16970. if (tmp == NULL) {
  16971. WOLFSSL_MSG("Failed to allocate memory for ticket");
  16972. XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK);
  16973. output->ticket = NULL;
  16974. output->ticketLen = 0;
  16975. output->ticketLenAlloc = 0;
  16976. ret = WOLFSSL_FAILURE;
  16977. }
  16978. else {
  16979. ticBuff = tmp;
  16980. ticLenAlloc = input->ticketLen;
  16981. }
  16982. }
  16983. }
  16984. if (ticBuff != NULL && ret == WOLFSSL_SUCCESS) {
  16985. XMEMCPY(ticBuff, input->ticket, input->ticketLen);
  16986. output->ticket = ticBuff;
  16987. output->ticketLenAlloc = (word16) ticLenAlloc;
  16988. }
  16989. }
  16990. else {
  16991. /* Default ticket to non dynamic */
  16992. if (avoidSysCalls) {
  16993. /* Try to use ticBuf if available. Caller can later move it to
  16994. * the static buffer. */
  16995. if (ticBuff != NULL) {
  16996. if (ticLenAlloc >= input->ticketLen) {
  16997. output->ticket = output->staticTicket;
  16998. output->ticketLenAlloc = 0;
  16999. }
  17000. else {
  17001. WOLFSSL_MSG("ticket dynamic buffer too small but we are "
  17002. "avoiding system calls");
  17003. ret = WOLFSSL_FAILURE;
  17004. output->ticket = ticBuff;
  17005. output->ticketLenAlloc = (word16) ticLenAlloc;
  17006. output->ticketLen = 0;
  17007. }
  17008. }
  17009. else {
  17010. output->ticket = output->staticTicket;
  17011. output->ticketLenAlloc = 0;
  17012. }
  17013. }
  17014. else {
  17015. if (ticBuff != NULL)
  17016. XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK);
  17017. output->ticket = output->staticTicket;
  17018. output->ticketLenAlloc = 0;
  17019. }
  17020. if (input->ticketLenAlloc > 0 && ret == WOLFSSL_SUCCESS) {
  17021. /* Shouldn't happen as session should have placed this in
  17022. * the static buffer */
  17023. XMEMCPY(output->ticket, input->ticket,
  17024. input->ticketLen);
  17025. }
  17026. }
  17027. ticBuff = NULL;
  17028. #endif /* HAVE_SESSION_TICKET */
  17029. return ret;
  17030. }
  17031. WOLFSSL_SESSION* wolfSSL_SESSION_dup(WOLFSSL_SESSION* session)
  17032. {
  17033. #ifdef HAVE_EXT_CACHE
  17034. WOLFSSL_SESSION* copy;
  17035. WOLFSSL_ENTER("wolfSSL_SESSION_dup");
  17036. session = ClientSessionToSession(session);
  17037. if (session == NULL)
  17038. return NULL;
  17039. #ifdef HAVE_SESSION_TICKET
  17040. if (session->ticketLenAlloc > 0 && !session->ticket) {
  17041. WOLFSSL_MSG("Session dynamic flag is set but ticket pointer is null");
  17042. return NULL;
  17043. }
  17044. #endif
  17045. copy = wolfSSL_NewSession(session->heap);
  17046. if (copy != NULL &&
  17047. wolfSSL_DupSession(session, copy, 0) != WOLFSSL_SUCCESS) {
  17048. wolfSSL_FreeSession(NULL, copy);
  17049. copy = NULL;
  17050. }
  17051. return copy;
  17052. #else
  17053. WOLFSSL_MSG("wolfSSL_SESSION_dup feature not compiled in");
  17054. (void)session;
  17055. return NULL;
  17056. #endif /* HAVE_EXT_CACHE */
  17057. }
  17058. void wolfSSL_FreeSession(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session)
  17059. {
  17060. session = ClientSessionToSession(session);
  17061. if (session == NULL)
  17062. return;
  17063. (void)ctx;
  17064. /* refCount will always be 1 or more if created externally.
  17065. * Internal cache sessions don't initialize a refMutex. */
  17066. if (session->refCount > 0) {
  17067. #ifndef SINGLE_THREADED
  17068. if (wc_LockMutex(&session->refMutex) != 0) {
  17069. WOLFSSL_MSG("Failed to lock session mutex");
  17070. return;
  17071. }
  17072. #endif
  17073. if (session->refCount > 1) {
  17074. session->refCount--;
  17075. #ifndef SINGLE_THREADED
  17076. wc_UnLockMutex(&session->refMutex);
  17077. #endif
  17078. return;
  17079. }
  17080. #ifndef SINGLE_THREADED
  17081. wc_UnLockMutex(&session->refMutex);
  17082. wc_FreeMutex(&session->refMutex);
  17083. #endif
  17084. }
  17085. #if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA)
  17086. if (ctx != NULL && ctx->rem_sess_cb
  17087. #ifdef HAVE_EX_DATA
  17088. && session->ownExData /* This will be true if we are not using the
  17089. * internal cache so it will get called for
  17090. * externally cached sessions as well. */
  17091. #endif
  17092. ) {
  17093. ctx->rem_sess_cb(ctx, session);
  17094. }
  17095. #endif
  17096. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  17097. wolfSSL_CRYPTO_cleanup_ex_data(&session->ex_data);
  17098. #endif
  17099. #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
  17100. if (session->peer) {
  17101. wolfSSL_X509_free(session->peer);
  17102. session->peer = NULL;
  17103. }
  17104. #endif
  17105. #ifdef HAVE_SESSION_TICKET
  17106. if (session->ticketLenAlloc > 0) {
  17107. XFREE(session->ticket, session->heap, DYNAMIC_TYPE_SESSION_TICK);
  17108. }
  17109. #endif
  17110. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  17111. wolfSSL_CRYPTO_cleanup_ex_data(&session->ex_data);
  17112. #endif
  17113. /* Make sure masterSecret is zeroed. */
  17114. ForceZero(session->masterSecret, SECRET_LEN);
  17115. /* Session ID is sensitive information too. */
  17116. ForceZero(session->sessionID, ID_LEN);
  17117. if (session->type == WOLFSSL_SESSION_TYPE_HEAP) {
  17118. XFREE(session, session->heap, DYNAMIC_TYPE_SESSION);
  17119. }
  17120. }
  17121. void wolfSSL_SESSION_free(WOLFSSL_SESSION* session)
  17122. {
  17123. session = ClientSessionToSession(session);
  17124. wolfSSL_FreeSession(NULL, session);
  17125. }
  17126. #ifndef NO_SESSION_CACHE
  17127. int wolfSSL_CTX_add_session(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session)
  17128. {
  17129. int error = 0;
  17130. const byte* id = NULL;
  17131. byte idSz = 0;
  17132. WOLFSSL_ENTER("wolfSSL_CTX_add_session");
  17133. session = ClientSessionToSession(session);
  17134. if (session == NULL)
  17135. return WOLFSSL_FAILURE;
  17136. /* Session cache is global */
  17137. (void)ctx;
  17138. id = session->sessionID;
  17139. idSz = session->sessionIDSz;
  17140. if (session->haveAltSessionID) {
  17141. id = session->altSessionID;
  17142. idSz = ID_LEN;
  17143. }
  17144. error = AddSessionToCache(ctx, session, id, idSz,
  17145. NULL, session->side,
  17146. #ifdef HAVE_SESSION_TICKET
  17147. session->ticketLen > 0,
  17148. #else
  17149. 0,
  17150. #endif
  17151. NULL);
  17152. return error == 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
  17153. }
  17154. #endif
  17155. #if defined(OPENSSL_EXTRA) || defined(HAVE_EXT_CACHE)
  17156. /**
  17157. * set cipher to WOLFSSL_SESSION from WOLFSSL_CIPHER
  17158. * @param session a pointer to WOLFSSL_SESSION structure
  17159. * @param cipher a function pointer to WOLFSSL_CIPHER
  17160. * @return WOLFSSL_SUCCESS on success, otherwise WOLFSSL_FAILURE
  17161. */
  17162. int wolfSSL_SESSION_set_cipher(WOLFSSL_SESSION* session,
  17163. const WOLFSSL_CIPHER* cipher)
  17164. {
  17165. WOLFSSL_ENTER("wolfSSL_SESSION_set_cipher");
  17166. session = ClientSessionToSession(session);
  17167. /* sanity check */
  17168. if (session == NULL || cipher == NULL) {
  17169. WOLFSSL_MSG("bad argument");
  17170. return WOLFSSL_FAILURE;
  17171. }
  17172. session->cipherSuite0 = cipher->cipherSuite0;
  17173. session->cipherSuite = cipher->cipherSuite;
  17174. WOLFSSL_LEAVE("wolfSSL_SESSION_set_cipher", WOLFSSL_SUCCESS);
  17175. return WOLFSSL_SUCCESS;
  17176. }
  17177. #endif /* OPENSSL_EXTRA || HAVE_EXT_CACHE */
  17178. /* helper function that takes in a protocol version struct and returns string */
  17179. static const char* wolfSSL_internal_get_version(const ProtocolVersion* version)
  17180. {
  17181. WOLFSSL_ENTER("wolfSSL_get_version");
  17182. if (version == NULL) {
  17183. return "Bad arg";
  17184. }
  17185. if (version->major == SSLv3_MAJOR) {
  17186. switch (version->minor) {
  17187. case SSLv3_MINOR :
  17188. return "SSLv3";
  17189. case TLSv1_MINOR :
  17190. return "TLSv1";
  17191. case TLSv1_1_MINOR :
  17192. return "TLSv1.1";
  17193. case TLSv1_2_MINOR :
  17194. return "TLSv1.2";
  17195. case TLSv1_3_MINOR :
  17196. return "TLSv1.3";
  17197. default:
  17198. return "unknown";
  17199. }
  17200. }
  17201. #ifdef WOLFSSL_DTLS
  17202. else if (version->major == DTLS_MAJOR) {
  17203. switch (version->minor) {
  17204. case DTLS_MINOR :
  17205. return "DTLS";
  17206. case DTLSv1_2_MINOR :
  17207. return "DTLSv1.2";
  17208. case DTLSv1_3_MINOR :
  17209. return "DTLSv1.3";
  17210. default:
  17211. return "unknown";
  17212. }
  17213. }
  17214. #endif /* WOLFSSL_DTLS */
  17215. return "unknown";
  17216. }
  17217. const char* wolfSSL_get_version(const WOLFSSL* ssl)
  17218. {
  17219. if (ssl == NULL) {
  17220. WOLFSSL_MSG("Bad argument");
  17221. return "unknown";
  17222. }
  17223. return wolfSSL_internal_get_version(&ssl->version);
  17224. }
  17225. /* current library version */
  17226. const char* wolfSSL_lib_version(void)
  17227. {
  17228. return LIBWOLFSSL_VERSION_STRING;
  17229. }
  17230. #ifdef OPENSSL_EXTRA
  17231. #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
  17232. const char* wolfSSL_OpenSSL_version(int a)
  17233. {
  17234. (void)a;
  17235. return "wolfSSL " LIBWOLFSSL_VERSION_STRING;
  17236. }
  17237. #else
  17238. const char* wolfSSL_OpenSSL_version(void)
  17239. {
  17240. return "wolfSSL " LIBWOLFSSL_VERSION_STRING;
  17241. }
  17242. #endif /* WOLFSSL_QT */
  17243. #endif
  17244. /* current library version in hex */
  17245. word32 wolfSSL_lib_version_hex(void)
  17246. {
  17247. return LIBWOLFSSL_VERSION_HEX;
  17248. }
  17249. int wolfSSL_get_current_cipher_suite(WOLFSSL* ssl)
  17250. {
  17251. WOLFSSL_ENTER("SSL_get_current_cipher_suite");
  17252. if (ssl)
  17253. return (ssl->options.cipherSuite0 << 8) | ssl->options.cipherSuite;
  17254. return 0;
  17255. }
  17256. WOLFSSL_CIPHER* wolfSSL_get_current_cipher(WOLFSSL* ssl)
  17257. {
  17258. WOLFSSL_ENTER("SSL_get_current_cipher");
  17259. if (ssl) {
  17260. ssl->cipher.cipherSuite0 = ssl->options.cipherSuite0;
  17261. ssl->cipher.cipherSuite = ssl->options.cipherSuite;
  17262. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  17263. ssl->cipher.bits = ssl->specs.key_size * 8;
  17264. #endif
  17265. return &ssl->cipher;
  17266. }
  17267. else
  17268. return NULL;
  17269. }
  17270. const char* wolfSSL_CIPHER_get_name(const WOLFSSL_CIPHER* cipher)
  17271. {
  17272. WOLFSSL_ENTER("wolfSSL_CIPHER_get_name");
  17273. if (cipher == NULL) {
  17274. return NULL;
  17275. }
  17276. #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && !defined(NO_ERROR_STRINGS) && \
  17277. !defined(WOLFSSL_QT)
  17278. return GetCipherNameIana(cipher->cipherSuite0, cipher->cipherSuite);
  17279. #else
  17280. return wolfSSL_get_cipher_name_from_suite(cipher->cipherSuite0,
  17281. cipher->cipherSuite);
  17282. #endif
  17283. }
  17284. const char* wolfSSL_CIPHER_get_version(const WOLFSSL_CIPHER* cipher)
  17285. {
  17286. WOLFSSL_ENTER("SSL_CIPHER_get_version");
  17287. if (cipher == NULL || cipher->ssl == NULL) {
  17288. return NULL;
  17289. }
  17290. return wolfSSL_get_version(cipher->ssl);
  17291. }
  17292. const char* wolfSSL_SESSION_CIPHER_get_name(const WOLFSSL_SESSION* session)
  17293. {
  17294. session = ClientSessionToSession(session);
  17295. if (session == NULL) {
  17296. return NULL;
  17297. }
  17298. #if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \
  17299. (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
  17300. #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && !defined(NO_ERROR_STRINGS)
  17301. return GetCipherNameIana(session->cipherSuite0, session->cipherSuite);
  17302. #else
  17303. return GetCipherNameInternal(session->cipherSuite0, session->cipherSuite);
  17304. #endif
  17305. #else
  17306. return NULL;
  17307. #endif
  17308. }
  17309. const char* wolfSSL_get_cipher(WOLFSSL* ssl)
  17310. {
  17311. WOLFSSL_ENTER("wolfSSL_get_cipher");
  17312. return wolfSSL_CIPHER_get_name(wolfSSL_get_current_cipher(ssl));
  17313. }
  17314. /* gets cipher name in the format DHE-RSA-... rather then TLS_DHE... */
  17315. const char* wolfSSL_get_cipher_name(WOLFSSL* ssl)
  17316. {
  17317. /* get access to cipher_name_idx in internal.c */
  17318. return wolfSSL_get_cipher_name_internal(ssl);
  17319. }
  17320. const char* wolfSSL_get_cipher_name_from_suite(const byte cipherSuite0,
  17321. const byte cipherSuite)
  17322. {
  17323. return GetCipherNameInternal(cipherSuite0, cipherSuite);
  17324. }
  17325. const char* wolfSSL_get_cipher_name_iana_from_suite(const byte cipherSuite0,
  17326. const byte cipherSuite)
  17327. {
  17328. return GetCipherNameIana(cipherSuite0, cipherSuite);
  17329. }
  17330. int wolfSSL_get_cipher_suite_from_name(const char* name, byte* cipherSuite0,
  17331. byte* cipherSuite, int *flags) {
  17332. if ((name == NULL) ||
  17333. (cipherSuite0 == NULL) ||
  17334. (cipherSuite == NULL) ||
  17335. (flags == NULL))
  17336. return BAD_FUNC_ARG;
  17337. return GetCipherSuiteFromName(name, cipherSuite0, cipherSuite, flags);
  17338. }
  17339. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
  17340. /* Creates and returns a new WOLFSSL_CIPHER stack. */
  17341. WOLFSSL_STACK* wolfSSL_sk_new_cipher(void)
  17342. {
  17343. WOLFSSL_STACK* sk;
  17344. WOLFSSL_ENTER("wolfSSL_sk_new_cipher");
  17345. sk = wolfSSL_sk_new_null();
  17346. if (sk == NULL)
  17347. return NULL;
  17348. sk->type = STACK_TYPE_CIPHER;
  17349. return sk;
  17350. }
  17351. /* return 1 on success 0 on fail */
  17352. int wolfSSL_sk_CIPHER_push(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk,
  17353. WOLFSSL_CIPHER* cipher)
  17354. {
  17355. return wolfSSL_sk_push(sk, cipher);
  17356. }
  17357. #ifndef NO_WOLFSSL_STUB
  17358. WOLFSSL_CIPHER* wolfSSL_sk_CIPHER_pop(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk)
  17359. {
  17360. WOLFSSL_STUB("wolfSSL_sk_CIPHER_pop");
  17361. (void)sk;
  17362. return NULL;
  17363. }
  17364. #endif /* NO_WOLFSSL_STUB */
  17365. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  17366. word32 wolfSSL_CIPHER_get_id(const WOLFSSL_CIPHER* cipher)
  17367. {
  17368. word16 cipher_id = 0;
  17369. WOLFSSL_ENTER("SSL_CIPHER_get_id");
  17370. if (cipher && cipher->ssl) {
  17371. cipher_id = (cipher->ssl->options.cipherSuite0 << 8) |
  17372. cipher->ssl->options.cipherSuite;
  17373. }
  17374. return cipher_id;
  17375. }
  17376. const WOLFSSL_CIPHER* wolfSSL_get_cipher_by_value(word16 value)
  17377. {
  17378. const WOLFSSL_CIPHER* cipher = NULL;
  17379. byte cipherSuite0, cipherSuite;
  17380. WOLFSSL_ENTER("SSL_get_cipher_by_value");
  17381. /* extract cipher id information */
  17382. cipherSuite = (value & 0xFF);
  17383. cipherSuite0 = ((value >> 8) & 0xFF);
  17384. /* TODO: lookup by cipherSuite0 / cipherSuite */
  17385. (void)cipherSuite0;
  17386. (void)cipherSuite;
  17387. return cipher;
  17388. }
  17389. #if defined(OPENSSL_EXTRA)
  17390. /* Free the structure for WOLFSSL_CIPHER stack
  17391. *
  17392. * sk stack to free nodes in
  17393. */
  17394. void wolfSSL_sk_CIPHER_free(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk)
  17395. {
  17396. WOLFSSL_ENTER("wolfSSL_sk_CIPHER_free");
  17397. wolfSSL_sk_free(sk);
  17398. }
  17399. #endif /* OPENSSL_ALL */
  17400. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) || \
  17401. !defined(NO_DH)
  17402. #ifdef HAVE_FFDHE
  17403. static const char* wolfssl_ffdhe_name(word16 group)
  17404. {
  17405. const char* str = NULL;
  17406. switch (group) {
  17407. case WOLFSSL_FFDHE_2048:
  17408. str = "FFDHE_2048";
  17409. break;
  17410. case WOLFSSL_FFDHE_3072:
  17411. str = "FFDHE_3072";
  17412. break;
  17413. case WOLFSSL_FFDHE_4096:
  17414. str = "FFDHE_4096";
  17415. break;
  17416. case WOLFSSL_FFDHE_6144:
  17417. str = "FFDHE_6144";
  17418. break;
  17419. case WOLFSSL_FFDHE_8192:
  17420. str = "FFDHE_8192";
  17421. break;
  17422. default:
  17423. break;
  17424. }
  17425. return str;
  17426. }
  17427. #endif
  17428. /* Return the name of the curve used for key exchange as a printable string.
  17429. *
  17430. * ssl The SSL/TLS object.
  17431. * returns NULL if ECDH was not used, otherwise the name as a string.
  17432. */
  17433. const char* wolfSSL_get_curve_name(WOLFSSL* ssl)
  17434. {
  17435. const char* cName = NULL;
  17436. if (ssl == NULL)
  17437. return NULL;
  17438. #if defined(WOLFSSL_TLS13) && defined(HAVE_PQC)
  17439. /* Check for post-quantum groups. Return now because we do not want the ECC
  17440. * check to override this result in the case of a hybrid. */
  17441. if (IsAtLeastTLSv1_3(ssl->version)) {
  17442. switch (ssl->namedGroup) {
  17443. #ifdef HAVE_LIBOQS
  17444. case WOLFSSL_KYBER_LEVEL1:
  17445. return "KYBER_LEVEL1";
  17446. case WOLFSSL_KYBER_LEVEL3:
  17447. return "KYBER_LEVEL3";
  17448. case WOLFSSL_KYBER_LEVEL5:
  17449. return "KYBER_LEVEL5";
  17450. case WOLFSSL_NTRU_HPS_LEVEL1:
  17451. return "NTRU_HPS_LEVEL1";
  17452. case WOLFSSL_NTRU_HPS_LEVEL3:
  17453. return "NTRU_HPS_LEVEL3";
  17454. case WOLFSSL_NTRU_HPS_LEVEL5:
  17455. return "NTRU_HPS_LEVEL5";
  17456. case WOLFSSL_NTRU_HRSS_LEVEL3:
  17457. return "NTRU_HRSS_LEVEL3";
  17458. case WOLFSSL_SABER_LEVEL1:
  17459. return "SABER_LEVEL1";
  17460. case WOLFSSL_SABER_LEVEL3:
  17461. return "SABER_LEVEL3";
  17462. case WOLFSSL_SABER_LEVEL5:
  17463. return "SABER_LEVEL5";
  17464. case WOLFSSL_KYBER_90S_LEVEL1:
  17465. return "KYBER_90S_LEVEL1";
  17466. case WOLFSSL_KYBER_90S_LEVEL3:
  17467. return "KYBER_90S_LEVEL3";
  17468. case WOLFSSL_KYBER_90S_LEVEL5:
  17469. return "KYBER_90S_LEVEL5";
  17470. case WOLFSSL_P256_NTRU_HPS_LEVEL1:
  17471. return "P256_NTRU_HPS_LEVEL1";
  17472. case WOLFSSL_P384_NTRU_HPS_LEVEL3:
  17473. return "P384_NTRU_HPS_LEVEL3";
  17474. case WOLFSSL_P521_NTRU_HPS_LEVEL5:
  17475. return "P521_NTRU_HPS_LEVEL5";
  17476. case WOLFSSL_P384_NTRU_HRSS_LEVEL3:
  17477. return "P384_NTRU_HRSS_LEVEL3";
  17478. case WOLFSSL_P256_SABER_LEVEL1:
  17479. return "P256_SABER_LEVEL1";
  17480. case WOLFSSL_P384_SABER_LEVEL3:
  17481. return "P384_SABER_LEVEL3";
  17482. case WOLFSSL_P521_SABER_LEVEL5:
  17483. return "P521_SABER_LEVEL5";
  17484. case WOLFSSL_P256_KYBER_LEVEL1:
  17485. return "P256_KYBER_LEVEL1";
  17486. case WOLFSSL_P384_KYBER_LEVEL3:
  17487. return "P384_KYBER_LEVEL3";
  17488. case WOLFSSL_P521_KYBER_LEVEL5:
  17489. return "P521_KYBER_LEVEL5";
  17490. case WOLFSSL_P256_KYBER_90S_LEVEL1:
  17491. return "P256_KYBER_90S_LEVEL1";
  17492. case WOLFSSL_P384_KYBER_90S_LEVEL3:
  17493. return "P384_KYBER_90S_LEVEL3";
  17494. case WOLFSSL_P521_KYBER_90S_LEVEL5:
  17495. return "P521_KYBER_90S_LEVEL5";
  17496. #elif defined(HAVE_PQM4)
  17497. case WOLFSSL_KYBER_LEVEL1:
  17498. return "KYBER_LEVEL1";
  17499. #endif
  17500. }
  17501. }
  17502. #endif /* WOLFSSL_TLS13 && HAVE_PQC */
  17503. #ifdef HAVE_FFDHE
  17504. if (ssl->namedGroup != 0) {
  17505. cName = wolfssl_ffdhe_name(ssl->namedGroup);
  17506. }
  17507. #endif
  17508. #ifdef HAVE_CURVE25519
  17509. if (ssl->ecdhCurveOID == ECC_X25519_OID && cName == NULL) {
  17510. cName = "X25519";
  17511. }
  17512. #endif
  17513. #ifdef HAVE_CURVE448
  17514. if (ssl->ecdhCurveOID == ECC_X448_OID && cName == NULL) {
  17515. cName = "X448";
  17516. }
  17517. #endif
  17518. #ifdef HAVE_ECC
  17519. if (ssl->ecdhCurveOID != 0 && cName == NULL) {
  17520. cName = wc_ecc_get_name(wc_ecc_get_oid(ssl->ecdhCurveOID, NULL,
  17521. NULL));
  17522. }
  17523. #endif
  17524. return cName;
  17525. }
  17526. #endif
  17527. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
  17528. defined(OPENSSL_EXTRA_X509_SMALL)
  17529. /* Creates a new WOLFSSL_ASN1_STRING structure.
  17530. *
  17531. * returns a pointer to the new structure created on success or NULL if fail
  17532. */
  17533. WOLFSSL_ASN1_STRING* wolfSSL_ASN1_STRING_new(void)
  17534. {
  17535. WOLFSSL_ASN1_STRING* asn1;
  17536. #ifdef WOLFSSL_DEBUG_OPENSSL
  17537. WOLFSSL_ENTER("wolfSSL_ASN1_STRING_new");
  17538. #endif
  17539. asn1 = (WOLFSSL_ASN1_STRING*)XMALLOC(sizeof(WOLFSSL_ASN1_STRING), NULL,
  17540. DYNAMIC_TYPE_OPENSSL);
  17541. if (asn1 != NULL) {
  17542. XMEMSET(asn1, 0, sizeof(WOLFSSL_ASN1_STRING));
  17543. }
  17544. return asn1; /* no check for null because error case is returning null*/
  17545. }
  17546. /**
  17547. * Used to duplicate a passed in WOLFSSL_ASN1_STRING*
  17548. * @param asn1 WOLFSSL_ASN1_STRING* to be duplicated
  17549. * @return WOLFSSL_ASN1_STRING* the duplicate struct or NULL on error
  17550. */
  17551. WOLFSSL_ASN1_STRING* wolfSSL_ASN1_STRING_dup(WOLFSSL_ASN1_STRING* asn1)
  17552. {
  17553. WOLFSSL_ASN1_STRING* dupl = NULL;
  17554. WOLFSSL_ENTER("wolfSSL_ASN1_STRING_dup");
  17555. if (!asn1) {
  17556. WOLFSSL_MSG("Bad parameter");
  17557. return NULL;
  17558. }
  17559. dupl = wolfSSL_ASN1_STRING_new();
  17560. if (!dupl) {
  17561. WOLFSSL_MSG("wolfSSL_ASN1_STRING_new error");
  17562. return NULL;
  17563. }
  17564. dupl->type = asn1->type;
  17565. dupl->flags = asn1->flags;
  17566. if (wolfSSL_ASN1_STRING_set(dupl, asn1->data, asn1->length)
  17567. != WOLFSSL_SUCCESS) {
  17568. WOLFSSL_MSG("wolfSSL_ASN1_STRING_set error");
  17569. wolfSSL_ASN1_STRING_free(dupl);
  17570. return NULL;
  17571. }
  17572. return dupl;
  17573. }
  17574. /* used to free a WOLFSSL_ASN1_STRING structure */
  17575. void wolfSSL_ASN1_STRING_free(WOLFSSL_ASN1_STRING* asn1)
  17576. {
  17577. #ifdef WOLFSSL_DEBUG_OPENSSL
  17578. WOLFSSL_ENTER("wolfSSL_ASN1_STRING_free");
  17579. #endif
  17580. if (asn1 != NULL) {
  17581. if (asn1->length > 0 && asn1->data != NULL && asn1->isDynamic) {
  17582. XFREE(asn1->data, NULL, DYNAMIC_TYPE_OPENSSL);
  17583. }
  17584. XFREE(asn1, NULL, DYNAMIC_TYPE_OPENSSL);
  17585. }
  17586. }
  17587. int wolfSSL_ASN1_STRING_cmp(const WOLFSSL_ASN1_STRING *a, const WOLFSSL_ASN1_STRING *b)
  17588. {
  17589. int i;
  17590. WOLFSSL_ENTER("wolfSSL_ASN1_STRING_cmp");
  17591. if (!a || !b) {
  17592. return WOLFSSL_FATAL_ERROR;
  17593. }
  17594. if (a->length != b->length) {
  17595. return a->length - b->length;
  17596. }
  17597. if ((i = XMEMCMP(a->data, b->data, a->length)) != 0) {
  17598. return i;
  17599. }
  17600. return a->type - b->type;
  17601. }
  17602. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  17603. #if !defined(NO_CERTS) && (defined(OPENSSL_EXTRA) || \
  17604. defined(OPENSSL_EXTRA_X509_SMALL))
  17605. int wolfSSL_ASN1_STRING_copy(WOLFSSL_ASN1_STRING* dest,
  17606. const WOLFSSL_ASN1_STRING* src)
  17607. {
  17608. if (src == NULL || dest == NULL) {
  17609. return WOLFSSL_FAILURE;
  17610. }
  17611. dest->type = src->type;
  17612. if(wolfSSL_ASN1_STRING_set(dest, src->data, src->length)
  17613. != WOLFSSL_SUCCESS) {
  17614. return WOLFSSL_FAILURE;
  17615. }
  17616. dest->flags = src->flags;
  17617. return WOLFSSL_SUCCESS;
  17618. }
  17619. /* Creates a new WOLFSSL_ASN1_STRING structure given the input type.
  17620. *
  17621. * type is the type of set when WOLFSSL_ASN1_STRING is created
  17622. *
  17623. * returns a pointer to the new structure created on success or NULL if fail
  17624. */
  17625. WOLFSSL_ASN1_STRING* wolfSSL_ASN1_STRING_type_new(int type)
  17626. {
  17627. WOLFSSL_ASN1_STRING* asn1;
  17628. #ifdef WOLFSSL_DEBUG_OPENSSL
  17629. WOLFSSL_ENTER("wolfSSL_ASN1_STRING_type_new");
  17630. #endif
  17631. asn1 = wolfSSL_ASN1_STRING_new();
  17632. if (asn1 == NULL) {
  17633. return NULL;
  17634. }
  17635. asn1->type = type;
  17636. return asn1;
  17637. }
  17638. /******************************************************************************
  17639. * wolfSSL_ASN1_STRING_type - returns the type of <asn1>
  17640. *
  17641. * RETURNS:
  17642. * returns the type set for <asn1>. Otherwise, returns WOLFSSL_FAILURE.
  17643. */
  17644. int wolfSSL_ASN1_STRING_type(const WOLFSSL_ASN1_STRING* asn1)
  17645. {
  17646. #ifdef WOLFSSL_DEBUG_OPENSSL
  17647. WOLFSSL_ENTER("wolfSSL_ASN1_STRING_type");
  17648. #endif
  17649. if (asn1 == NULL) {
  17650. return WOLFSSL_FAILURE;
  17651. }
  17652. return asn1->type;
  17653. }
  17654. #endif /* !NO_CERTS && OPENSSL_EXTRA */
  17655. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
  17656. defined(OPENSSL_EXTRA_X509_SMALL)
  17657. /* if dataSz is negative then use XSTRLEN to find length of data
  17658. * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure */
  17659. /* `data` can be NULL and only buffer will be allocated */
  17660. int wolfSSL_ASN1_STRING_set(WOLFSSL_ASN1_STRING* asn1, const void* data,
  17661. int dataSz)
  17662. {
  17663. int sz;
  17664. #ifdef WOLFSSL_DEBUG_OPENSSL
  17665. WOLFSSL_ENTER("wolfSSL_ASN1_STRING_set");
  17666. #endif
  17667. if (asn1 == NULL || (data == NULL && dataSz < 0)) {
  17668. return WOLFSSL_FAILURE;
  17669. }
  17670. if (dataSz < 0) {
  17671. sz = (int)XSTRLEN((const char*)data);
  17672. }
  17673. else {
  17674. sz = dataSz;
  17675. }
  17676. if (sz < 0) {
  17677. return WOLFSSL_FAILURE;
  17678. }
  17679. /* free any existing data before copying */
  17680. if (asn1->data != NULL && asn1->isDynamic) {
  17681. XFREE(asn1->data, NULL, DYNAMIC_TYPE_OPENSSL);
  17682. asn1->data = NULL;
  17683. }
  17684. if (sz + 1 > CTC_NAME_SIZE) { /* account for null char */
  17685. /* create new data buffer and copy over */
  17686. asn1->data = (char*)XMALLOC(sz + 1, NULL, DYNAMIC_TYPE_OPENSSL);
  17687. if (asn1->data == NULL) {
  17688. return WOLFSSL_FAILURE;
  17689. }
  17690. asn1->isDynamic = 1;
  17691. }
  17692. else {
  17693. XMEMSET(asn1->strData, 0, CTC_NAME_SIZE);
  17694. asn1->data = asn1->strData;
  17695. asn1->isDynamic = 0;
  17696. }
  17697. if (data != NULL) {
  17698. XMEMCPY(asn1->data, data, sz);
  17699. asn1->data[sz] = '\0';
  17700. }
  17701. asn1->length = sz;
  17702. return WOLFSSL_SUCCESS;
  17703. }
  17704. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  17705. #ifndef NO_CERTS
  17706. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17707. const unsigned char* wolfSSL_ASN1_STRING_get0_data(
  17708. const WOLFSSL_ASN1_STRING* asn)
  17709. {
  17710. WOLFSSL_ENTER("wolfSSL_ASN1_STRING_get0_data");
  17711. if (asn) {
  17712. return (const unsigned char*)asn->data;
  17713. } else {
  17714. return NULL;
  17715. }
  17716. }
  17717. unsigned char* wolfSSL_ASN1_STRING_data(WOLFSSL_ASN1_STRING* asn)
  17718. {
  17719. #ifdef WOLFSSL_DEBUG_OPENSSL
  17720. WOLFSSL_ENTER("wolfSSL_ASN1_STRING_data");
  17721. #endif
  17722. if (asn) {
  17723. return (unsigned char*)asn->data;
  17724. }
  17725. else {
  17726. return NULL;
  17727. }
  17728. }
  17729. int wolfSSL_ASN1_STRING_length(WOLFSSL_ASN1_STRING* asn)
  17730. {
  17731. #ifdef WOLFSSL_DEBUG_OPENSSL
  17732. WOLFSSL_ENTER("wolfSSL_ASN1_STRING_length");
  17733. #endif
  17734. if (asn) {
  17735. return asn->length;
  17736. }
  17737. else {
  17738. return 0;
  17739. }
  17740. }
  17741. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  17742. #ifdef OPENSSL_EXTRA
  17743. #ifndef NO_WOLFSSL_STUB
  17744. WOLFSSL_ASN1_STRING* wolfSSL_d2i_DISPLAYTEXT(WOLFSSL_ASN1_STRING **asn,
  17745. const unsigned char **in, long len)
  17746. {
  17747. WOLFSSL_STUB("d2i_DISPLAYTEXT");
  17748. (void)asn;
  17749. (void)in;
  17750. (void)len;
  17751. return NULL;
  17752. }
  17753. #endif
  17754. #endif /* OPENSSL_EXTRA */
  17755. #endif /* !NO_CERTS */
  17756. #ifdef OPENSSL_EXTRA
  17757. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  17758. /* return authentication NID corresponding to cipher suite
  17759. * @param cipher a pointer to WOLFSSL_CIPHER
  17760. * return NID if found, NID_undef if not found
  17761. */
  17762. int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher)
  17763. {
  17764. static const struct authnid {
  17765. const char* alg_name;
  17766. const int nid;
  17767. } authnid_tbl[] = {
  17768. {"RSA", NID_auth_rsa},
  17769. {"PSK", NID_auth_psk},
  17770. {"SRP", NID_auth_srp},
  17771. {"ECDSA", NID_auth_ecdsa},
  17772. {"None", NID_auth_null},
  17773. {NULL, NID_undef}
  17774. };
  17775. const struct authnid* sa;
  17776. const char* authStr;
  17777. char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
  17778. if (GetCipherSegment(cipher, n) == NULL) {
  17779. WOLFSSL_MSG("no suitable cipher name found");
  17780. return NID_undef;
  17781. }
  17782. authStr = GetCipherAuthStr(n);
  17783. if (authStr != NULL) {
  17784. for(sa = authnid_tbl; sa->alg_name != NULL; sa++) {
  17785. if (XSTRCMP(sa->alg_name, authStr) == 0) {
  17786. return sa->nid;
  17787. }
  17788. }
  17789. }
  17790. return NID_undef;
  17791. }
  17792. /* return cipher NID corresponding to cipher suite
  17793. * @param cipher a pointer to WOLFSSL_CIPHER
  17794. * return NID if found, NID_undef if not found
  17795. */
  17796. int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher)
  17797. {
  17798. static const struct ciphernid {
  17799. const char* alg_name;
  17800. const int nid;
  17801. } ciphernid_tbl[] = {
  17802. {"AESGCM(256)", NID_aes_256_gcm},
  17803. {"AESGCM(128)", NID_aes_128_gcm},
  17804. {"AESCCM(128)", NID_aes_128_ccm},
  17805. {"AES(128)", NID_aes_128_cbc},
  17806. {"AES(256)", NID_aes_256_cbc},
  17807. {"CAMELLIA(256)", NID_camellia_256_cbc},
  17808. {"CAMELLIA(128)", NID_camellia_128_cbc},
  17809. {"RC4", NID_rc4},
  17810. {"3DES", NID_des_ede3_cbc},
  17811. {"CHACHA20/POLY1305(256)", NID_chacha20_poly1305},
  17812. {"None", NID_undef},
  17813. {NULL, NID_undef}
  17814. };
  17815. const struct ciphernid* c;
  17816. const char* encStr;
  17817. char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
  17818. WOLFSSL_ENTER("wolfSSL_CIPHER_get_cipher_nid");
  17819. if (GetCipherSegment(cipher, n) == NULL) {
  17820. WOLFSSL_MSG("no suitable cipher name found");
  17821. return NID_undef;
  17822. }
  17823. encStr = GetCipherEncStr(n);
  17824. if (encStr != NULL) {
  17825. for(c = ciphernid_tbl; c->alg_name != NULL; c++) {
  17826. if (XSTRCMP(c->alg_name, encStr) == 0) {
  17827. return c->nid;
  17828. }
  17829. }
  17830. }
  17831. return NID_undef;
  17832. }
  17833. /* return digest NID corresponding to cipher suite
  17834. * @param cipher a pointer to WOLFSSL_CIPHER
  17835. * return NID if found, NID_undef if not found
  17836. */
  17837. int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher)
  17838. {
  17839. static const struct macnid {
  17840. const char* alg_name;
  17841. const int nid;
  17842. } macnid_tbl[] = {
  17843. {"SHA1", NID_sha1},
  17844. {"SHA256", NID_sha256},
  17845. {"SHA384", NID_sha384},
  17846. {NULL, NID_undef}
  17847. };
  17848. const struct macnid* mc;
  17849. const char* name;
  17850. const char* macStr;
  17851. char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
  17852. (void)name;
  17853. WOLFSSL_ENTER("wolfSSL_CIPHER_get_digest_nid");
  17854. if ((name = GetCipherSegment(cipher, n)) == NULL) {
  17855. WOLFSSL_MSG("no suitable cipher name found");
  17856. return NID_undef;
  17857. }
  17858. /* in MD5 case, NID will be NID_md5 */
  17859. if (XSTRSTR(name, "MD5") != NULL) {
  17860. return NID_md5;
  17861. }
  17862. macStr = GetCipherMacStr(n);
  17863. if (macStr != NULL) {
  17864. for(mc = macnid_tbl; mc->alg_name != NULL; mc++) {
  17865. if (XSTRCMP(mc->alg_name, macStr) == 0) {
  17866. return mc->nid;
  17867. }
  17868. }
  17869. }
  17870. return NID_undef;
  17871. }
  17872. /* return key exchange NID corresponding to cipher suite
  17873. * @param cipher a pointer to WOLFSSL_CIPHER
  17874. * return NID if found, NID_undef if not found
  17875. */
  17876. int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher)
  17877. {
  17878. static const struct kxnid {
  17879. const char* name;
  17880. const int nid;
  17881. } kxnid_table[] = {
  17882. {"ECDHEPSK", NID_kx_ecdhe_psk},
  17883. {"ECDH", NID_kx_ecdhe},
  17884. {"DHEPSK", NID_kx_dhe_psk},
  17885. {"DH", NID_kx_dhe},
  17886. {"RSAPSK", NID_kx_rsa_psk},
  17887. {"SRP", NID_kx_srp},
  17888. {"EDH", NID_kx_dhe},
  17889. {"RSA", NID_kx_rsa},
  17890. {NULL, NID_undef}
  17891. };
  17892. const struct kxnid* k;
  17893. const char* keaStr;
  17894. char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
  17895. WOLFSSL_ENTER("wolfSSL_CIPHER_get_kx_nid");
  17896. if (GetCipherSegment(cipher, n) == NULL) {
  17897. WOLFSSL_MSG("no suitable cipher name found");
  17898. return NID_undef;
  17899. }
  17900. /* in TLS 1.3 case, NID will be NID_kx_any */
  17901. if (XSTRCMP(n[0], "TLS13") == 0) {
  17902. return NID_kx_any;
  17903. }
  17904. keaStr = GetCipherKeaStr(n);
  17905. if (keaStr != NULL) {
  17906. for(k = kxnid_table; k->name != NULL; k++) {
  17907. if (XSTRCMP(k->name, keaStr) == 0) {
  17908. return k->nid;
  17909. }
  17910. }
  17911. }
  17912. return NID_undef;
  17913. }
  17914. /* check if cipher suite is AEAD
  17915. * @param cipher a pointer to WOLFSSL_CIPHER
  17916. * return 1 if cipher is AEAD, 0 otherwise
  17917. */
  17918. int wolfSSL_CIPHER_is_aead(const WOLFSSL_CIPHER* cipher)
  17919. {
  17920. char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
  17921. WOLFSSL_ENTER("wolfSSL_CIPHER_is_aead");
  17922. if (GetCipherSegment(cipher, n) == NULL) {
  17923. WOLFSSL_MSG("no suitable cipher name found");
  17924. return NID_undef;
  17925. }
  17926. return IsCipherAEAD(n);
  17927. }
  17928. /* Creates cipher->description based on cipher->offset
  17929. * cipher->offset is set in wolfSSL_get_ciphers_compat when it is added
  17930. * to a stack of ciphers.
  17931. * @param [in] cipher: A cipher from a stack of ciphers.
  17932. * return WOLFSSL_SUCCESS if cipher->description is set, else WOLFSSL_FAILURE
  17933. */
  17934. int wolfSSL_sk_CIPHER_description(WOLFSSL_CIPHER* cipher)
  17935. {
  17936. int strLen;
  17937. unsigned long offset;
  17938. char* dp;
  17939. const char* name;
  17940. const char *keaStr, *authStr, *encStr, *macStr, *protocol;
  17941. char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
  17942. int len = MAX_DESCRIPTION_SZ-1;
  17943. const CipherSuiteInfo* cipher_names;
  17944. ProtocolVersion pv;
  17945. WOLFSSL_ENTER("wolfSSL_sk_CIPHER_description");
  17946. if (cipher == NULL)
  17947. return WOLFSSL_FAILURE;
  17948. dp = cipher->description;
  17949. if (dp == NULL)
  17950. return WOLFSSL_FAILURE;
  17951. cipher_names = GetCipherNames();
  17952. offset = cipher->offset;
  17953. if (offset >= (unsigned long)GetCipherNamesSize())
  17954. return WOLFSSL_FAILURE;
  17955. pv.major = cipher_names[offset].major;
  17956. pv.minor = cipher_names[offset].minor;
  17957. protocol = wolfSSL_internal_get_version(&pv);
  17958. if ((name = GetCipherSegment(cipher, n)) == NULL) {
  17959. WOLFSSL_MSG("no suitable cipher name found");
  17960. return WOLFSSL_FAILURE;
  17961. }
  17962. /* keaStr */
  17963. keaStr = GetCipherKeaStr(n);
  17964. /* authStr */
  17965. authStr = GetCipherAuthStr(n);
  17966. /* encStr */
  17967. encStr = GetCipherEncStr(n);
  17968. if ((cipher->bits = SetCipherBits(encStr)) == WOLFSSL_FAILURE) {
  17969. WOLFSSL_MSG("Cipher Bits Not Set.");
  17970. }
  17971. /* macStr */
  17972. macStr = GetCipherMacStr(n);
  17973. /* Build up the string by copying onto the end. */
  17974. XSTRNCPY(dp, name, len);
  17975. dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
  17976. len -= strLen; dp += strLen;
  17977. XSTRNCPY(dp, " ", len);
  17978. dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
  17979. len -= strLen; dp += strLen;
  17980. XSTRNCPY(dp, protocol, len);
  17981. dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
  17982. len -= strLen; dp += strLen;
  17983. XSTRNCPY(dp, " Kx=", len);
  17984. dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
  17985. len -= strLen; dp += strLen;
  17986. XSTRNCPY(dp, keaStr, len);
  17987. dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
  17988. len -= strLen; dp += strLen;
  17989. XSTRNCPY(dp, " Au=", len);
  17990. dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
  17991. len -= strLen; dp += strLen;
  17992. XSTRNCPY(dp, authStr, len);
  17993. dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
  17994. len -= strLen; dp += strLen;
  17995. XSTRNCPY(dp, " Enc=", len);
  17996. dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
  17997. len -= strLen; dp += strLen;
  17998. XSTRNCPY(dp, encStr, len);
  17999. dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
  18000. len -= strLen; dp += strLen;
  18001. XSTRNCPY(dp, " Mac=", len);
  18002. dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
  18003. len -= strLen; dp += strLen;
  18004. XSTRNCPY(dp, macStr, len);
  18005. dp[len-1] = '\0';
  18006. return WOLFSSL_SUCCESS;
  18007. }
  18008. #endif /* OPENSSL_ALL || WOLFSSL_QT */
  18009. static WC_INLINE const char* wolfssl_kea_to_string(int kea)
  18010. {
  18011. const char* keaStr;
  18012. switch (kea) {
  18013. case no_kea:
  18014. keaStr = "None";
  18015. break;
  18016. #ifndef NO_RSA
  18017. case rsa_kea:
  18018. keaStr = "RSA";
  18019. break;
  18020. #endif
  18021. #ifndef NO_DH
  18022. case diffie_hellman_kea:
  18023. keaStr = "DHE";
  18024. break;
  18025. #endif
  18026. case fortezza_kea:
  18027. keaStr = "FZ";
  18028. break;
  18029. #ifndef NO_PSK
  18030. case psk_kea:
  18031. keaStr = "PSK";
  18032. break;
  18033. #ifndef NO_DH
  18034. case dhe_psk_kea:
  18035. keaStr = "DHEPSK";
  18036. break;
  18037. #endif
  18038. #ifdef HAVE_ECC
  18039. case ecdhe_psk_kea:
  18040. keaStr = "ECDHEPSK";
  18041. break;
  18042. #endif
  18043. #endif
  18044. #ifdef HAVE_ECC
  18045. case ecc_diffie_hellman_kea:
  18046. keaStr = "ECDHE";
  18047. break;
  18048. case ecc_static_diffie_hellman_kea:
  18049. keaStr = "ECDH";
  18050. break;
  18051. #endif
  18052. default:
  18053. keaStr = "unknown";
  18054. break;
  18055. }
  18056. return keaStr;
  18057. }
  18058. static WC_INLINE const char* wolfssl_sigalg_to_string(int sig_algo)
  18059. {
  18060. const char* authStr;
  18061. switch (sig_algo) {
  18062. case anonymous_sa_algo:
  18063. authStr = "None";
  18064. break;
  18065. #ifndef NO_RSA
  18066. case rsa_sa_algo:
  18067. authStr = "RSA";
  18068. break;
  18069. #ifdef WC_RSA_PSS
  18070. case rsa_pss_sa_algo:
  18071. authStr = "RSA-PSS";
  18072. break;
  18073. #endif
  18074. #endif
  18075. #ifndef NO_DSA
  18076. case dsa_sa_algo:
  18077. authStr = "DSA";
  18078. break;
  18079. #endif
  18080. #ifdef HAVE_ECC
  18081. case ecc_dsa_sa_algo:
  18082. authStr = "ECDSA";
  18083. break;
  18084. #endif
  18085. #ifdef HAVE_ED25519
  18086. case ed25519_sa_algo:
  18087. authStr = "Ed25519";
  18088. break;
  18089. #endif
  18090. #ifdef HAVE_ED448
  18091. case ed448_sa_algo:
  18092. authStr = "Ed448";
  18093. break;
  18094. #endif
  18095. default:
  18096. authStr = "unknown";
  18097. break;
  18098. }
  18099. return authStr;
  18100. }
  18101. static WC_INLINE const char* wolfssl_cipher_to_string(int cipher, int key_size)
  18102. {
  18103. const char* encStr;
  18104. (void)key_size;
  18105. switch (cipher) {
  18106. case wolfssl_cipher_null:
  18107. encStr = "None";
  18108. break;
  18109. #ifndef NO_RC4
  18110. case wolfssl_rc4:
  18111. encStr = "RC4(128)";
  18112. break;
  18113. #endif
  18114. #ifndef NO_DES3
  18115. case wolfssl_triple_des:
  18116. encStr = "3DES(168)";
  18117. break;
  18118. #endif
  18119. #ifndef NO_AES
  18120. case wolfssl_aes:
  18121. if (key_size == 128)
  18122. encStr = "AES(128)";
  18123. else if (key_size == 256)
  18124. encStr = "AES(256)";
  18125. else
  18126. encStr = "AES(?)";
  18127. break;
  18128. #ifdef HAVE_AESGCM
  18129. case wolfssl_aes_gcm:
  18130. if (key_size == 128)
  18131. encStr = "AESGCM(128)";
  18132. else if (key_size == 256)
  18133. encStr = "AESGCM(256)";
  18134. else
  18135. encStr = "AESGCM(?)";
  18136. break;
  18137. #endif
  18138. #ifdef HAVE_AESCCM
  18139. case wolfssl_aes_ccm:
  18140. if (key_size == 128)
  18141. encStr = "AESCCM(128)";
  18142. else if (key_size == 256)
  18143. encStr = "AESCCM(256)";
  18144. else
  18145. encStr = "AESCCM(?)";
  18146. break;
  18147. #endif
  18148. #endif
  18149. #ifdef HAVE_CHACHA
  18150. case wolfssl_chacha:
  18151. encStr = "CHACHA20/POLY1305(256)";
  18152. break;
  18153. #endif
  18154. #ifdef HAVE_CAMELLIA
  18155. case wolfssl_camellia:
  18156. if (key_size == 128)
  18157. encStr = "Camellia(128)";
  18158. else if (key_size == 256)
  18159. encStr = "Camellia(256)";
  18160. else
  18161. encStr = "Camellia(?)";
  18162. break;
  18163. #endif
  18164. default:
  18165. encStr = "unknown";
  18166. break;
  18167. }
  18168. return encStr;
  18169. }
  18170. static WC_INLINE const char* wolfssl_mac_to_string(int mac)
  18171. {
  18172. const char* macStr;
  18173. switch (mac) {
  18174. case no_mac:
  18175. macStr = "None";
  18176. break;
  18177. #ifndef NO_MD5
  18178. case md5_mac:
  18179. macStr = "MD5";
  18180. break;
  18181. #endif
  18182. #ifndef NO_SHA
  18183. case sha_mac:
  18184. macStr = "SHA1";
  18185. break;
  18186. #endif
  18187. #ifdef HAVE_SHA224
  18188. case sha224_mac:
  18189. macStr = "SHA224";
  18190. break;
  18191. #endif
  18192. #ifndef NO_SHA256
  18193. case sha256_mac:
  18194. macStr = "SHA256";
  18195. break;
  18196. #endif
  18197. #ifdef HAVE_SHA384
  18198. case sha384_mac:
  18199. macStr = "SHA384";
  18200. break;
  18201. #endif
  18202. #ifdef HAVE_SHA512
  18203. case sha512_mac:
  18204. macStr = "SHA512";
  18205. break;
  18206. #endif
  18207. default:
  18208. macStr = "unknown";
  18209. break;
  18210. }
  18211. return macStr;
  18212. }
  18213. char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in,
  18214. int len)
  18215. {
  18216. char *ret = in;
  18217. const char *keaStr, *authStr, *encStr, *macStr;
  18218. size_t strLen;
  18219. WOLFSSL_ENTER("wolfSSL_CIPHER_description");
  18220. if (cipher == NULL || in == NULL)
  18221. return NULL;
  18222. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
  18223. /* if cipher is in the stack from wolfSSL_get_ciphers_compat then
  18224. * Return the description based on cipher_names[cipher->offset]
  18225. */
  18226. if (cipher->in_stack == TRUE) {
  18227. wolfSSL_sk_CIPHER_description((WOLFSSL_CIPHER*)cipher);
  18228. XSTRNCPY(in,cipher->description,len);
  18229. return ret;
  18230. }
  18231. #endif
  18232. /* Get the cipher description based on the SSL session cipher */
  18233. keaStr = wolfssl_kea_to_string(cipher->ssl->specs.kea);
  18234. authStr = wolfssl_sigalg_to_string(cipher->ssl->specs.sig_algo);
  18235. encStr = wolfssl_cipher_to_string(cipher->ssl->specs.bulk_cipher_algorithm,
  18236. cipher->ssl->specs.key_size);
  18237. macStr = wolfssl_mac_to_string(cipher->ssl->specs.mac_algorithm);
  18238. /* Build up the string by copying onto the end. */
  18239. XSTRNCPY(in, wolfSSL_CIPHER_get_name(cipher), len);
  18240. in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
  18241. XSTRNCPY(in, " ", len);
  18242. in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
  18243. XSTRNCPY(in, wolfSSL_get_version(cipher->ssl), len);
  18244. in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
  18245. XSTRNCPY(in, " Kx=", len);
  18246. in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
  18247. XSTRNCPY(in, keaStr, len);
  18248. in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
  18249. XSTRNCPY(in, " Au=", len);
  18250. in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
  18251. XSTRNCPY(in, authStr, len);
  18252. in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
  18253. XSTRNCPY(in, " Enc=", len);
  18254. in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
  18255. XSTRNCPY(in, encStr, len);
  18256. in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
  18257. XSTRNCPY(in, " Mac=", len);
  18258. in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
  18259. XSTRNCPY(in, macStr, len);
  18260. in[len-1] = '\0';
  18261. return ret;
  18262. }
  18263. #ifndef NO_WOLFSSL_STUB
  18264. int wolfSSL_OCSP_parse_url(char* url, char** host, char** port, char** path,
  18265. int* ssl)
  18266. {
  18267. (void)url;
  18268. (void)host;
  18269. (void)port;
  18270. (void)path;
  18271. (void)ssl;
  18272. WOLFSSL_STUB("OCSP_parse_url");
  18273. return 0;
  18274. }
  18275. #endif
  18276. #ifndef NO_MD4
  18277. void wolfSSL_MD4_Init(WOLFSSL_MD4_CTX* md4)
  18278. {
  18279. /* make sure we have a big enough buffer */
  18280. typedef char ok[sizeof(md4->buffer) >= sizeof(Md4) ? 1 : -1];
  18281. (void) sizeof(ok);
  18282. WOLFSSL_ENTER("MD4_Init");
  18283. wc_InitMd4((Md4*)md4);
  18284. }
  18285. void wolfSSL_MD4_Update(WOLFSSL_MD4_CTX* md4, const void* data,
  18286. unsigned long len)
  18287. {
  18288. WOLFSSL_ENTER("MD4_Update");
  18289. wc_Md4Update((Md4*)md4, (const byte*)data, (word32)len);
  18290. }
  18291. void wolfSSL_MD4_Final(unsigned char* digest, WOLFSSL_MD4_CTX* md4)
  18292. {
  18293. WOLFSSL_ENTER("MD4_Final");
  18294. wc_Md4Final((Md4*)md4, digest);
  18295. }
  18296. #endif /* NO_MD4 */
  18297. #ifndef NO_WOLFSSL_STUB
  18298. void wolfSSL_RAND_screen(void)
  18299. {
  18300. WOLFSSL_STUB("RAND_screen");
  18301. }
  18302. #endif
  18303. int wolfSSL_RAND_load_file(const char* fname, long len)
  18304. {
  18305. (void)fname;
  18306. /* wolfCrypt provides enough entropy internally or will report error */
  18307. if (len == -1)
  18308. return 1024;
  18309. else
  18310. return (int)len;
  18311. }
  18312. #ifndef NO_WOLFSSL_STUB
  18313. WOLFSSL_COMP_METHOD* wolfSSL_COMP_zlib(void)
  18314. {
  18315. WOLFSSL_STUB("COMP_zlib");
  18316. return 0;
  18317. }
  18318. #endif
  18319. #ifndef NO_WOLFSSL_STUB
  18320. WOLFSSL_COMP_METHOD* wolfSSL_COMP_rle(void)
  18321. {
  18322. WOLFSSL_STUB("COMP_rle");
  18323. return 0;
  18324. }
  18325. #endif
  18326. #ifndef NO_WOLFSSL_STUB
  18327. int wolfSSL_COMP_add_compression_method(int method, void* data)
  18328. {
  18329. (void)method;
  18330. (void)data;
  18331. WOLFSSL_STUB("COMP_add_compression_method");
  18332. return 0;
  18333. }
  18334. #endif
  18335. /* wolfSSL_set_dynlock_create_callback
  18336. * CRYPTO_set_dynlock_create_callback has been deprecated since openSSL 1.0.1.
  18337. * This function exists for compatibility purposes because wolfSSL satisfies
  18338. * thread safety without relying on the callback.
  18339. */
  18340. void wolfSSL_set_dynlock_create_callback(WOLFSSL_dynlock_value* (*f)(
  18341. const char*, int))
  18342. {
  18343. WOLFSSL_STUB("CRYPTO_set_dynlock_create_callback");
  18344. (void)f;
  18345. }
  18346. /* wolfSSL_set_dynlock_lock_callback
  18347. * CRYPTO_set_dynlock_lock_callback has been deprecated since openSSL 1.0.1.
  18348. * This function exists for compatibility purposes because wolfSSL satisfies
  18349. * thread safety without relying on the callback.
  18350. */
  18351. void wolfSSL_set_dynlock_lock_callback(
  18352. void (*f)(int, WOLFSSL_dynlock_value*, const char*, int))
  18353. {
  18354. WOLFSSL_STUB("CRYPTO_set_set_dynlock_lock_callback");
  18355. (void)f;
  18356. }
  18357. /* wolfSSL_set_dynlock_destroy_callback
  18358. * CRYPTO_set_dynlock_destroy_callback has been deprecated since openSSL 1.0.1.
  18359. * This function exists for compatibility purposes because wolfSSL satisfies
  18360. * thread safety without relying on the callback.
  18361. */
  18362. void wolfSSL_set_dynlock_destroy_callback(
  18363. void (*f)(WOLFSSL_dynlock_value*, const char*, int))
  18364. {
  18365. WOLFSSL_STUB("CRYPTO_set_set_dynlock_destroy_callback");
  18366. (void)f;
  18367. }
  18368. #endif /* OPENSSL_EXTRA */
  18369. #ifdef OPENSSL_EXTRA
  18370. #ifndef NO_CERTS
  18371. #if !defined(NO_ASN) && !defined(NO_PWDBASED)
  18372. /* Copies unencrypted DER key buffer into "der". If "der" is null then the size
  18373. * of buffer needed is returned. If *der == NULL then it allocates a buffer.
  18374. * NOTE: This also advances the "der" pointer to be at the end of buffer.
  18375. *
  18376. * Returns size of key buffer on success
  18377. */
  18378. int wolfSSL_i2d_PrivateKey(const WOLFSSL_EVP_PKEY* key, unsigned char** der)
  18379. {
  18380. return wolfSSL_EVP_PKEY_get_der(key, der);
  18381. }
  18382. int wolfSSL_i2d_PublicKey(const WOLFSSL_EVP_PKEY *key, unsigned char **der)
  18383. {
  18384. return wolfSSL_EVP_PKEY_get_der(key, der);
  18385. }
  18386. #endif /* !NO_ASN && !NO_PWDBASED */
  18387. #endif /* !NO_CERTS */
  18388. #endif /* OPENSSL_EXTRA */
  18389. #ifdef OPENSSL_EXTRA
  18390. /******************************************************************************
  18391. * wolfSSL_CTX_set1_param - set a pointer to the SSL verification parameters
  18392. *
  18393. * RETURNS:
  18394. * WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE
  18395. * Note: Returns WOLFSSL_SUCCESS, in case either parameter is NULL,
  18396. * same as openssl.
  18397. */
  18398. int wolfSSL_CTX_set1_param(WOLFSSL_CTX* ctx, WOLFSSL_X509_VERIFY_PARAM *vpm)
  18399. {
  18400. if (ctx == NULL || vpm == NULL)
  18401. return WOLFSSL_SUCCESS;
  18402. return wolfSSL_X509_VERIFY_PARAM_set1(ctx->param, vpm);
  18403. }
  18404. /******************************************************************************
  18405. * wolfSSL_CTX/_get0_param - return a pointer to the SSL verification parameters
  18406. *
  18407. * RETURNS:
  18408. * returns pointer to the SSL verification parameters on success,
  18409. * otherwise returns NULL
  18410. */
  18411. WOLFSSL_X509_VERIFY_PARAM* wolfSSL_CTX_get0_param(WOLFSSL_CTX* ctx)
  18412. {
  18413. if (ctx == NULL) {
  18414. return NULL;
  18415. }
  18416. return ctx->param;
  18417. }
  18418. WOLFSSL_X509_VERIFY_PARAM* wolfSSL_get0_param(WOLFSSL* ssl)
  18419. {
  18420. if (ssl == NULL) {
  18421. return NULL;
  18422. }
  18423. return ssl->param;
  18424. }
  18425. #endif /* OPENSSL_EXTRA */
  18426. #if defined(OPENSSL_EXTRA)
  18427. int wolfSSL_i2d_ASN1_INTEGER(WOLFSSL_ASN1_INTEGER* a, unsigned char** out)
  18428. {
  18429. int ret = 0;
  18430. word32 idx = 0;
  18431. int len;
  18432. int preAlloc = 1;
  18433. WOLFSSL_ENTER("wolfSSL_i2d_ASN1_INTEGER");
  18434. if (a == NULL || a->data == NULL || a->length <= 0 || out == NULL) {
  18435. WOLFSSL_MSG("Bad parameter.");
  18436. ret = WOLFSSL_FATAL_ERROR;
  18437. }
  18438. if (ret == 0 && *out == NULL) {
  18439. preAlloc = 0;
  18440. *out = (unsigned char*)XMALLOC(a->length, NULL, DYNAMIC_TYPE_ASN1);
  18441. if (*out == NULL) {
  18442. WOLFSSL_MSG("Failed to allocate output buffer.");
  18443. ret = WOLFSSL_FATAL_ERROR;
  18444. }
  18445. }
  18446. if (ret == 0) {
  18447. /*
  18448. * A WOLFSSL_ASN1_INTEGER stores the DER buffer of the integer in its
  18449. * "data" field, but it's only the magnitude of the number (i.e. the
  18450. * sign isn't encoded). The "negative" field is 1 if the value should
  18451. * be interpreted as negative and 0 otherwise. If the value is negative,
  18452. * we need to output the 2's complement of the value in the DER output.
  18453. */
  18454. XMEMCPY(*out, a->data, a->length);
  18455. if (a->negative) {
  18456. if (GetLength(a->data, &idx, &len, a->length) < 0) {
  18457. ret = WOLFSSL_FATAL_ERROR;
  18458. }
  18459. else {
  18460. ++idx;
  18461. for (; (int)idx < a->length; ++idx) {
  18462. (*out)[idx] = ~(*out)[idx];
  18463. }
  18464. do {
  18465. --idx;
  18466. ++(*out)[idx];
  18467. } while ((*out)[idx] == 0);
  18468. }
  18469. }
  18470. }
  18471. if (ret == 0) {
  18472. ret = a->length;
  18473. if (preAlloc) {
  18474. *out += a->length;
  18475. }
  18476. }
  18477. WOLFSSL_LEAVE("wolfSSL_i2d_ASN1_INTEGER", ret);
  18478. return ret;
  18479. }
  18480. WOLFSSL_ASN1_INTEGER* wolfSSL_d2i_ASN1_INTEGER(WOLFSSL_ASN1_INTEGER** a,
  18481. const unsigned char** in,
  18482. long inSz)
  18483. {
  18484. WOLFSSL_ASN1_INTEGER* ret = NULL;
  18485. int err = 0;
  18486. word32 idx = 0;
  18487. int len;
  18488. WOLFSSL_ENTER("wolfSSL_d2i_ASN1_INTEGER");
  18489. if (in == NULL || *in == NULL || inSz <= 0) {
  18490. WOLFSSL_MSG("Bad parameter");
  18491. err = 1;
  18492. }
  18493. if (err == 0 && (*in)[0] != ASN_INTEGER) {
  18494. WOLFSSL_MSG("Tag doesn't indicate integer type.");
  18495. err = 1;
  18496. }
  18497. if (err == 0) {
  18498. ret = wolfSSL_ASN1_INTEGER_new();
  18499. if (ret == NULL) {
  18500. err = 1;
  18501. }
  18502. else {
  18503. ret->type = V_ASN1_INTEGER;
  18504. }
  18505. }
  18506. if (err == 0 && inSz > (long)sizeof(ret->intData)) {
  18507. ret->data = (unsigned char*)XMALLOC(inSz, NULL, DYNAMIC_TYPE_ASN1);
  18508. if (ret->data == NULL) {
  18509. err = 1;
  18510. }
  18511. else {
  18512. ret->isDynamic = 1;
  18513. ret->dataMax = (word32)inSz;
  18514. }
  18515. }
  18516. if (err == 0) {
  18517. XMEMCPY(ret->data, *in, inSz);
  18518. ret->length = (word32)inSz;
  18519. /* Advance to the end of the length field.*/
  18520. if (GetLength(*in, &idx, &len, (word32)inSz) < 0) {
  18521. err = 1;
  18522. }
  18523. else {
  18524. /* See 2's complement comment in wolfSSL_d2i_ASN1_INTEGER. */
  18525. ret->negative = (*in)[idx+1] & 0x80;
  18526. if (ret->negative) {
  18527. ++idx;
  18528. for (; (int)idx < inSz; ++idx) {
  18529. ret->data[idx] = ~ret->data[idx];
  18530. }
  18531. do {
  18532. --idx;
  18533. ++ret->data[idx];
  18534. } while (ret->data[idx] == 0);
  18535. ret->type |= V_ASN1_NEG_INTEGER;
  18536. }
  18537. if (a != NULL) {
  18538. *a = ret;
  18539. }
  18540. }
  18541. }
  18542. if (err != 0) {
  18543. wolfSSL_ASN1_INTEGER_free(ret);
  18544. ret = NULL;
  18545. }
  18546. return ret;
  18547. }
  18548. #endif /* OPENSSL_EXTRA */
  18549. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  18550. /* Used to create a new WOLFSSL_ASN1_INTEGER structure.
  18551. * returns a pointer to new structure on success and NULL on failure
  18552. */
  18553. WOLFSSL_ASN1_INTEGER* wolfSSL_ASN1_INTEGER_new(void)
  18554. {
  18555. WOLFSSL_ASN1_INTEGER* a;
  18556. a = (WOLFSSL_ASN1_INTEGER*)XMALLOC(sizeof(WOLFSSL_ASN1_INTEGER), NULL,
  18557. DYNAMIC_TYPE_OPENSSL);
  18558. if (a == NULL) {
  18559. return NULL;
  18560. }
  18561. XMEMSET(a, 0, sizeof(WOLFSSL_ASN1_INTEGER));
  18562. a->data = a->intData;
  18563. a->isDynamic = 0;
  18564. a->dataMax = WOLFSSL_ASN1_INTEGER_MAX;
  18565. a->length = 0;
  18566. return a;
  18567. }
  18568. /* free's internal elements of WOLFSSL_ASN1_INTEGER and free's "in" itself */
  18569. void wolfSSL_ASN1_INTEGER_free(WOLFSSL_ASN1_INTEGER* in)
  18570. {
  18571. if (in != NULL) {
  18572. if (in->isDynamic) {
  18573. XFREE(in->data, NULL, DYNAMIC_TYPE_OPENSSL);
  18574. }
  18575. XFREE(in, NULL, DYNAMIC_TYPE_OPENSSL);
  18576. }
  18577. }
  18578. /* Duplicate all WOLFSSL_ASN1_INTEGER members from src to dup
  18579. * src : WOLFSSL_ASN1_INTEGER to duplicate
  18580. * Returns pointer to duplicate WOLFSSL_ASN1_INTEGER
  18581. */
  18582. WOLFSSL_ASN1_INTEGER* wolfSSL_ASN1_INTEGER_dup(const WOLFSSL_ASN1_INTEGER* src)
  18583. {
  18584. WOLFSSL_ASN1_INTEGER* copy;
  18585. WOLFSSL_ENTER("wolfSSL_ASN1_INTEGER_dup");
  18586. if (!src)
  18587. return NULL;
  18588. copy = wolfSSL_ASN1_INTEGER_new();
  18589. if (copy == NULL)
  18590. return NULL;
  18591. copy->negative = src->negative;
  18592. copy->dataMax = src->dataMax;
  18593. copy->isDynamic = src->isDynamic;
  18594. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  18595. copy->length = src->length;
  18596. #endif
  18597. XSTRNCPY((char*)copy->intData,(const char*)src->intData,WOLFSSL_ASN1_INTEGER_MAX);
  18598. if (copy->isDynamic && src->data && copy->dataMax) {
  18599. copy->data = (unsigned char*)
  18600. XMALLOC(src->dataMax,NULL,DYNAMIC_TYPE_OPENSSL);
  18601. if (copy->data == NULL) {
  18602. wolfSSL_ASN1_INTEGER_free(copy);
  18603. return NULL;
  18604. }
  18605. XMEMCPY(copy->data, src->data, copy->dataMax);
  18606. }
  18607. return copy;
  18608. }
  18609. /* sets the value of WOLFSSL_ASN1_INTEGER a to the long value v. */
  18610. int wolfSSL_ASN1_INTEGER_set(WOLFSSL_ASN1_INTEGER *a, long v)
  18611. {
  18612. int ret = WOLFSSL_SUCCESS; /* return 1 for success and 0 for failure */
  18613. int j;
  18614. unsigned int i = 0;
  18615. unsigned char tmp[sizeof(long)+1] = {0};
  18616. int pad = 0;
  18617. if (a != NULL) {
  18618. /* dynamically create data buffer, +2 for type and length */
  18619. a->data = (unsigned char*)XMALLOC((sizeof(long)+1) + 2, NULL,
  18620. DYNAMIC_TYPE_OPENSSL);
  18621. if (a->data == NULL) {
  18622. wolfSSL_ASN1_INTEGER_free(a);
  18623. ret = WOLFSSL_FAILURE;
  18624. }
  18625. else {
  18626. a->dataMax = (int)(sizeof(long)+1) + 2;
  18627. a->isDynamic = 1;
  18628. }
  18629. }
  18630. else {
  18631. /* Invalid parameter */
  18632. ret = WOLFSSL_FAILURE;
  18633. }
  18634. if (ret != WOLFSSL_FAILURE) {
  18635. /* Set type */
  18636. a->data[i++] = ASN_INTEGER;
  18637. /* Check for negative */
  18638. if (v < 0) {
  18639. a->negative = 1;
  18640. v *= -1;
  18641. }
  18642. /* Create char buffer */
  18643. for (j = 0; j < (int)sizeof(long); j++) {
  18644. if (v == 0) {
  18645. break;
  18646. }
  18647. tmp[j] = (unsigned char)(v & 0xff);
  18648. v >>= 8;
  18649. }
  18650. /* 0 pad to indicate positive number when top bit set. */
  18651. if ((!a->negative) && (j > 0) && (tmp[j-1] & 0x80)) {
  18652. pad = 1;
  18653. }
  18654. /* Set length */
  18655. a->data[i++] = (unsigned char)(((j == 0) ? ++j : j) + pad);
  18656. /* +2 for type and length */
  18657. a->length = j + pad + 2;
  18658. /* Add padding if required. */
  18659. if (pad) {
  18660. a->data[i++] = 0;
  18661. }
  18662. /* Copy to data */
  18663. for (; j > 0; j--) {
  18664. a->data[i++] = tmp[j-1];
  18665. }
  18666. }
  18667. return ret;
  18668. }
  18669. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  18670. #if defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(WOLFSSL_NGINX) || \
  18671. defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
  18672. #ifndef NO_ASN_TIME
  18673. #ifndef NO_BIO
  18674. int wolfSSL_ASN1_TIME_print(WOLFSSL_BIO* bio, const WOLFSSL_ASN1_TIME* asnTime)
  18675. {
  18676. char buf[MAX_TIME_STRING_SZ];
  18677. int ret = WOLFSSL_SUCCESS;
  18678. WOLFSSL_ENTER("wolfSSL_ASN1_TIME_print");
  18679. if (bio == NULL || asnTime == NULL) {
  18680. WOLFSSL_MSG("NULL function argument");
  18681. return WOLFSSL_FAILURE;
  18682. }
  18683. if (wolfSSL_ASN1_TIME_to_string((WOLFSSL_ASN1_TIME*)asnTime, buf,
  18684. sizeof(buf)) == NULL) {
  18685. XMEMSET(buf, 0, MAX_TIME_STRING_SZ);
  18686. XSTRNCPY(buf, "Bad time value", sizeof(buf)-1);
  18687. ret = WOLFSSL_FAILURE;
  18688. }
  18689. if (wolfSSL_BIO_write(bio, buf, (int)XSTRLEN(buf)) <= 0) {
  18690. WOLFSSL_MSG("Unable to write to bio");
  18691. return WOLFSSL_FAILURE;
  18692. }
  18693. return ret;
  18694. }
  18695. #endif /* !NO_BIO */
  18696. char* wolfSSL_ASN1_TIME_to_string(WOLFSSL_ASN1_TIME* t, char* buf, int len)
  18697. {
  18698. WOLFSSL_ENTER("wolfSSL_ASN1_TIME_to_string");
  18699. if (t == NULL || buf == NULL || len < 5) {
  18700. WOLFSSL_MSG("Bad argument");
  18701. return NULL;
  18702. }
  18703. if (t->length > len) {
  18704. WOLFSSL_MSG("Length of date is longer then buffer");
  18705. return NULL;
  18706. }
  18707. if (!GetTimeString(t->data, t->type, buf, len)) {
  18708. return NULL;
  18709. }
  18710. return buf;
  18711. }
  18712. /* Converts a WOLFSSL_ASN1_TIME to a struct tm. Returns WOLFSSL_SUCCESS on
  18713. * success and WOLFSSL_FAILURE on failure. */
  18714. static int Asn1TimeToTm(WOLFSSL_ASN1_TIME* asnTime, struct tm* tm)
  18715. {
  18716. unsigned char* asn1TimeBuf;
  18717. int asn1TimeBufLen;
  18718. int i = 0;
  18719. int bytesNeeded = 11;
  18720. if (asnTime == NULL) {
  18721. WOLFSSL_MSG("asnTime is NULL");
  18722. return WOLFSSL_FAILURE;
  18723. }
  18724. if (tm == NULL) {
  18725. WOLFSSL_MSG("tm is NULL");
  18726. return WOLFSSL_FAILURE;
  18727. }
  18728. asn1TimeBuf = wolfSSL_ASN1_TIME_get_data(asnTime);
  18729. if (asn1TimeBuf == NULL) {
  18730. WOLFSSL_MSG("Failed to get WOLFSSL_ASN1_TIME buffer.");
  18731. return WOLFSSL_FAILURE;
  18732. }
  18733. asn1TimeBufLen = wolfSSL_ASN1_TIME_get_length(asnTime);
  18734. if (asn1TimeBufLen <= 0) {
  18735. WOLFSSL_MSG("Failed to get WOLFSSL_ASN1_TIME buffer length.");
  18736. return WOLFSSL_FAILURE;
  18737. }
  18738. XMEMSET(tm, 0, sizeof(struct tm));
  18739. /* Convert ASN1_time to struct tm */
  18740. /* Check type */
  18741. if (asnTime->type == ASN_UTC_TIME) {
  18742. /* 2-digit year */
  18743. bytesNeeded += 2;
  18744. if (bytesNeeded > asn1TimeBufLen) {
  18745. WOLFSSL_MSG("WOLFSSL_ASN1_TIME buffer length is invalid.");
  18746. return WOLFSSL_FAILURE;
  18747. }
  18748. if (asn1TimeBuf[bytesNeeded-1] != 'Z') {
  18749. WOLFSSL_MSG("Expecting UTC time.");
  18750. return WOLFSSL_FAILURE;
  18751. }
  18752. tm->tm_year = (asn1TimeBuf[i] - '0') * 10; i++;
  18753. tm->tm_year += asn1TimeBuf[i] - '0'; i++;
  18754. if (tm->tm_year < 70) {
  18755. tm->tm_year += 100;
  18756. }
  18757. }
  18758. else if (asnTime->type == ASN_GENERALIZED_TIME) {
  18759. /* 4-digit year */
  18760. bytesNeeded += 4;
  18761. if (bytesNeeded > asn1TimeBufLen) {
  18762. WOLFSSL_MSG("WOLFSSL_ASN1_TIME buffer length is invalid.");
  18763. return WOLFSSL_FAILURE;
  18764. }
  18765. if (asn1TimeBuf[bytesNeeded-1] != 'Z') {
  18766. WOLFSSL_MSG("Expecting UTC time.");
  18767. return WOLFSSL_FAILURE;
  18768. }
  18769. tm->tm_year = (asn1TimeBuf[i] - '0') * 1000; i++;
  18770. tm->tm_year += (asn1TimeBuf[i] - '0') * 100; i++;
  18771. tm->tm_year += (asn1TimeBuf[i] - '0') * 10; i++;
  18772. tm->tm_year += asn1TimeBuf[i] - '0'; i++;
  18773. tm->tm_year -= 1900;
  18774. }
  18775. else {
  18776. WOLFSSL_MSG("asnTime->type is invalid.");
  18777. return WOLFSSL_FAILURE;
  18778. }
  18779. tm->tm_mon = (asn1TimeBuf[i] - '0') * 10; i++;
  18780. tm->tm_mon += (asn1TimeBuf[i] - '0') - 1; i++; /* January is 0 not 1 */
  18781. tm->tm_mday = (asn1TimeBuf[i] - '0') * 10; i++;
  18782. tm->tm_mday += (asn1TimeBuf[i] - '0'); i++;
  18783. tm->tm_hour = (asn1TimeBuf[i] - '0') * 10; i++;
  18784. tm->tm_hour += (asn1TimeBuf[i] - '0'); i++;
  18785. tm->tm_min = (asn1TimeBuf[i] - '0') * 10; i++;
  18786. tm->tm_min += (asn1TimeBuf[i] - '0'); i++;
  18787. tm->tm_sec = (asn1TimeBuf[i] - '0') * 10; i++;
  18788. tm->tm_sec += (asn1TimeBuf[i] - '0');
  18789. #ifdef XMKTIME
  18790. /* Call XMKTIME on tm to get the tm_wday and tm_yday fields populated. */
  18791. XMKTIME(tm);
  18792. #endif
  18793. return WOLFSSL_SUCCESS;
  18794. }
  18795. int wolfSSL_ASN1_TIME_to_tm(const WOLFSSL_ASN1_TIME* asnTime, struct tm* tm)
  18796. {
  18797. time_t currentTime;
  18798. struct tm *tmpTs;
  18799. #if defined(NEED_TMP_TIME)
  18800. /* for use with gmtime_r */
  18801. struct tm tmpTimeStorage;
  18802. tmpTs = &tmpTimeStorage;
  18803. #else
  18804. tmpTs = NULL;
  18805. #endif
  18806. (void)tmpTs;
  18807. WOLFSSL_ENTER("wolfSSL_ASN1_TIME_to_tm");
  18808. /* If asnTime is NULL, then the current time is converted. */
  18809. if (asnTime == NULL) {
  18810. if (tm == NULL) {
  18811. WOLFSSL_MSG("asnTime and tm are both NULL");
  18812. return WOLFSSL_FAILURE;
  18813. }
  18814. currentTime = wc_Time(0);
  18815. if (currentTime <= 0) {
  18816. WOLFSSL_MSG("Failed to get current time.");
  18817. return WOLFSSL_FAILURE;
  18818. }
  18819. tm = XGMTIME(&currentTime, tmpTs);
  18820. if (tm == NULL) {
  18821. WOLFSSL_MSG("Failed to convert current time to UTC.");
  18822. return WOLFSSL_FAILURE;
  18823. }
  18824. return WOLFSSL_SUCCESS;
  18825. }
  18826. /* If tm is NULL this function performs a format check on asnTime only. */
  18827. if (tm == NULL) {
  18828. return wolfSSL_ASN1_TIME_check(asnTime);
  18829. }
  18830. return Asn1TimeToTm((WOLFSSL_ASN1_TIME*)asnTime, tm);
  18831. }
  18832. #endif /* !NO_ASN_TIME */
  18833. #endif /* WOLFSSL_MYSQL_COMPATIBLE || WOLFSSL_NGINX || WOLFSSL_HAPROXY ||
  18834. OPENSSL_EXTRA*/
  18835. #ifdef OPENSSL_EXTRA
  18836. int wolfSSL_ASN1_INTEGER_cmp(const WOLFSSL_ASN1_INTEGER* a,
  18837. const WOLFSSL_ASN1_INTEGER* b)
  18838. {
  18839. int ret = 0;
  18840. WOLFSSL_ENTER("wolfSSL_ASN1_INTEGER_cmp");
  18841. if (a == NULL || b == NULL) {
  18842. WOLFSSL_MSG("Bad parameter.");
  18843. ret = WOLFSSL_FATAL_ERROR;
  18844. }
  18845. if (ret == 0 && ((a->length != b->length) ||
  18846. ((a->negative == 0) != (b->negative == 0)))) {
  18847. ret = WOLFSSL_FATAL_ERROR;
  18848. }
  18849. if (ret == 0) {
  18850. ret = XMEMCMP(a->data, b->data, a->length);
  18851. }
  18852. WOLFSSL_LEAVE("wolfSSL_ASN1_INTEGER_cmp", ret);
  18853. return ret;
  18854. }
  18855. long wolfSSL_ASN1_INTEGER_get(const WOLFSSL_ASN1_INTEGER* a)
  18856. {
  18857. long ret = 1;
  18858. WOLFSSL_BIGNUM* bn = NULL;
  18859. WOLFSSL_ENTER("ASN1_INTEGER_get");
  18860. if (a == NULL) {
  18861. /* OpenSSL returns 0 when a is NULL and -1 if there is an error. Quoting
  18862. * the documentation:
  18863. *
  18864. * "ASN1_INTEGER_get() also returns the value of a but it returns 0 if a
  18865. * is NULL and -1 on error (which is ambiguous because -1 is a
  18866. * legitimate value for an ASN1_INTEGER). New applications should use
  18867. * ASN1_INTEGER_get_int64() instead."
  18868. * */
  18869. ret = 0;
  18870. }
  18871. if (ret > 0) {
  18872. bn = wolfSSL_ASN1_INTEGER_to_BN(a, NULL);
  18873. if (bn == NULL) {
  18874. ret = -1;
  18875. }
  18876. }
  18877. if (ret > 0) {
  18878. ret = wolfSSL_BN_get_word(bn);
  18879. if (a->negative == 1) {
  18880. ret = -ret;
  18881. }
  18882. }
  18883. if (bn != NULL) {
  18884. wolfSSL_BN_free(bn);
  18885. }
  18886. WOLFSSL_LEAVE("ASN1_INTEGER_get", (int)ret);
  18887. return ret;
  18888. }
  18889. #endif /* OPENSSL_EXTRA */
  18890. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  18891. /* Gets an index to store SSL structure at.
  18892. *
  18893. * Returns positive index on success and negative values on failure
  18894. */
  18895. int wolfSSL_get_ex_data_X509_STORE_CTX_idx(void)
  18896. {
  18897. WOLFSSL_ENTER("wolfSSL_get_ex_data_X509_STORE_CTX_idx");
  18898. /* store SSL at index 0 */
  18899. return 0;
  18900. }
  18901. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  18902. #ifdef OPENSSL_EXTRA
  18903. /* Sets a function callback that will send information about the state of all
  18904. * WOLFSSL objects that have been created by the WOLFSSL_CTX structure passed
  18905. * in.
  18906. *
  18907. * ctx WOLFSSL_CTX structure to set callback function in
  18908. * f callback function to use
  18909. */
  18910. void wolfSSL_CTX_set_info_callback(WOLFSSL_CTX* ctx,
  18911. void (*f)(const WOLFSSL* ssl, int type, int val))
  18912. {
  18913. WOLFSSL_ENTER("wolfSSL_CTX_set_info_callback");
  18914. if (ctx == NULL) {
  18915. WOLFSSL_MSG("Bad function argument");
  18916. }
  18917. else {
  18918. ctx->CBIS = f;
  18919. }
  18920. }
  18921. unsigned long wolfSSL_ERR_peek_error(void)
  18922. {
  18923. WOLFSSL_ENTER("wolfSSL_ERR_peek_error");
  18924. return wolfSSL_ERR_peek_error_line_data(NULL, NULL, NULL, NULL);
  18925. }
  18926. int wolfSSL_ERR_GET_LIB(unsigned long err)
  18927. {
  18928. unsigned long value;
  18929. value = (err & 0xFFFFFFL);
  18930. switch (value) {
  18931. case -SSL_R_HTTP_REQUEST:
  18932. return ERR_LIB_SSL;
  18933. case PEM_R_NO_START_LINE:
  18934. case PEM_R_PROBLEMS_GETTING_PASSWORD:
  18935. case PEM_R_BAD_PASSWORD_READ:
  18936. case PEM_R_BAD_DECRYPT:
  18937. return ERR_LIB_PEM;
  18938. case EVP_R_BAD_DECRYPT:
  18939. case EVP_R_BN_DECODE_ERROR:
  18940. case EVP_R_DECODE_ERROR:
  18941. case EVP_R_PRIVATE_KEY_DECODE_ERROR:
  18942. return ERR_LIB_EVP;
  18943. case ASN1_R_HEADER_TOO_LONG:
  18944. return ERR_LIB_ASN1;
  18945. default:
  18946. return 0;
  18947. }
  18948. }
  18949. /* This function is to find global error values that are the same through out
  18950. * all library version. With wolfSSL having only one set of error codes the
  18951. * return value is pretty straight forward. The only thing needed is all wolfSSL
  18952. * error values are typically negative.
  18953. *
  18954. * Returns the error reason
  18955. */
  18956. int wolfSSL_ERR_GET_REASON(unsigned long err)
  18957. {
  18958. int ret = (int)err;
  18959. WOLFSSL_ENTER("wolfSSL_ERR_GET_REASON");
  18960. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  18961. /* Nginx looks for this error to know to stop parsing certificates. */
  18962. if (err == ((ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE))
  18963. return PEM_R_NO_START_LINE;
  18964. if (err == ((ERR_LIB_SSL << 24) | -SSL_R_HTTP_REQUEST))
  18965. return SSL_R_HTTP_REQUEST;
  18966. #endif
  18967. #if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
  18968. if (err == ((ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG))
  18969. return ASN1_R_HEADER_TOO_LONG;
  18970. #endif
  18971. /* check if error value is in range of wolfSSL errors */
  18972. ret = 0 - ret; /* setting as negative value */
  18973. /* wolfCrypt range is less than MAX (-100)
  18974. wolfSSL range is MIN (-300) and lower */
  18975. if (ret < MAX_CODE_E && ret > MIN_CODE_E) {
  18976. return ret;
  18977. }
  18978. else {
  18979. WOLFSSL_MSG("Not in range of typical error values");
  18980. ret = (int)err;
  18981. }
  18982. return ret;
  18983. }
  18984. /* returns a string that describes the alert
  18985. *
  18986. * alertID the alert value to look up
  18987. */
  18988. const char* wolfSSL_alert_type_string_long(int alertID)
  18989. {
  18990. WOLFSSL_ENTER("wolfSSL_alert_type_string_long");
  18991. return AlertTypeToString(alertID);
  18992. }
  18993. const char* wolfSSL_alert_desc_string_long(int alertID)
  18994. {
  18995. WOLFSSL_ENTER("wolfSSL_alert_desc_string_long");
  18996. return AlertTypeToString(alertID);
  18997. }
  18998. #define STATE_STRINGS_PROTO(s) \
  18999. { \
  19000. {"SSLv3 " s, \
  19001. "SSLv3 " s, \
  19002. "SSLv3 " s}, \
  19003. {"TLSv1 " s, \
  19004. "TLSv1 " s, \
  19005. "TLSv1 " s}, \
  19006. {"TLSv1_1 " s, \
  19007. "TLSv1_1 " s, \
  19008. "TLSv1_1 " s}, \
  19009. {"TLSv1_2 " s, \
  19010. "TLSv1_2 " s, \
  19011. "TLSv1_2 " s}, \
  19012. {"TLSv1_3 " s, \
  19013. "TLSv1_3 " s, \
  19014. "TLSv1_3 " s}, \
  19015. {"DTLSv1 " s, \
  19016. "DTLSv1 " s, \
  19017. "DTLSv1 " s}, \
  19018. {"DTLSv1_2 " s, \
  19019. "DTLSv1_2 " s, \
  19020. "DTLSv1_2 " s}, \
  19021. {"DTLSv1_3 " s, \
  19022. "DTLSv1_3 " s, \
  19023. "DTLSv1_3 " s}, \
  19024. }
  19025. #define STATE_STRINGS_PROTO_RW(s) \
  19026. { \
  19027. {"SSLv3 read " s, \
  19028. "SSLv3 write " s, \
  19029. "SSLv3 " s}, \
  19030. {"TLSv1 read " s, \
  19031. "TLSv1 write " s, \
  19032. "TLSv1 " s}, \
  19033. {"TLSv1_1 read " s, \
  19034. "TLSv1_1 write " s, \
  19035. "TLSv1_1 " s}, \
  19036. {"TLSv1_2 read " s, \
  19037. "TLSv1_2 write " s, \
  19038. "TLSv1_2 " s}, \
  19039. {"TLSv1_3 read " s, \
  19040. "TLSv1_3 write " s, \
  19041. "TLSv1_3 " s}, \
  19042. {"DTLSv1 read " s, \
  19043. "DTLSv1 write " s, \
  19044. "DTLSv1 " s}, \
  19045. {"DTLSv1_2 read " s, \
  19046. "DTLSv1_2 write " s, \
  19047. "DTLSv1_2 " s}, \
  19048. {"DTLSv1_3 read " s, \
  19049. "DTLSv1_3 write " s, \
  19050. "DTLSv1_3 " s}, \
  19051. }
  19052. /* Gets the current state of the WOLFSSL structure
  19053. *
  19054. * ssl WOLFSSL structure to get state of
  19055. *
  19056. * Returns a human readable string of the WOLFSSL structure state
  19057. */
  19058. const char* wolfSSL_state_string_long(const WOLFSSL* ssl)
  19059. {
  19060. static const char* OUTPUT_STR[24][8][3] = {
  19061. STATE_STRINGS_PROTO("Initialization"),
  19062. STATE_STRINGS_PROTO_RW("Server Hello Request"),
  19063. STATE_STRINGS_PROTO_RW("Server Hello Verify Request"),
  19064. STATE_STRINGS_PROTO_RW("Server Hello Retry Request"),
  19065. STATE_STRINGS_PROTO_RW("Server Hello"),
  19066. STATE_STRINGS_PROTO_RW("Server Certificate Status"),
  19067. STATE_STRINGS_PROTO_RW("Server Encrypted Extensions"),
  19068. STATE_STRINGS_PROTO_RW("Server Session Ticket"),
  19069. STATE_STRINGS_PROTO_RW("Server Certificate Request"),
  19070. STATE_STRINGS_PROTO_RW("Server Cert"),
  19071. STATE_STRINGS_PROTO_RW("Server Key Exchange"),
  19072. STATE_STRINGS_PROTO_RW("Server Hello Done"),
  19073. STATE_STRINGS_PROTO_RW("Server Change CipherSpec"),
  19074. STATE_STRINGS_PROTO_RW("Server Finished"),
  19075. STATE_STRINGS_PROTO_RW("server Key Update"),
  19076. STATE_STRINGS_PROTO_RW("Client Hello"),
  19077. STATE_STRINGS_PROTO_RW("Client Key Exchange"),
  19078. STATE_STRINGS_PROTO_RW("Client Cert"),
  19079. STATE_STRINGS_PROTO_RW("Client Change CipherSpec"),
  19080. STATE_STRINGS_PROTO_RW("Client Certificate Verify"),
  19081. STATE_STRINGS_PROTO_RW("Client End Of Early Data"),
  19082. STATE_STRINGS_PROTO_RW("Client Finished"),
  19083. STATE_STRINGS_PROTO_RW("Client Key Update"),
  19084. STATE_STRINGS_PROTO("Handshake Done"),
  19085. };
  19086. enum ProtocolVer {
  19087. SSL_V3 = 0,
  19088. TLS_V1,
  19089. TLS_V1_1,
  19090. TLS_V1_2,
  19091. TLS_V1_3,
  19092. DTLS_V1,
  19093. DTLS_V1_2,
  19094. DTLS_V1_3,
  19095. UNKNOWN = 100
  19096. };
  19097. enum IOMode {
  19098. SS_READ = 0,
  19099. SS_WRITE,
  19100. SS_NEITHER
  19101. };
  19102. enum SslState {
  19103. ss_null_state = 0,
  19104. ss_server_hellorequest,
  19105. ss_server_helloverify,
  19106. ss_server_helloretryrequest,
  19107. ss_server_hello,
  19108. ss_server_certificatestatus,
  19109. ss_server_encryptedextensions,
  19110. ss_server_sessionticket,
  19111. ss_server_certrequest,
  19112. ss_server_cert,
  19113. ss_server_keyexchange,
  19114. ss_server_hellodone,
  19115. ss_server_changecipherspec,
  19116. ss_server_finished,
  19117. ss_server_keyupdate,
  19118. ss_client_hello,
  19119. ss_client_keyexchange,
  19120. ss_client_cert,
  19121. ss_client_changecipherspec,
  19122. ss_client_certverify,
  19123. ss_client_endofearlydata,
  19124. ss_client_finished,
  19125. ss_client_keyupdate,
  19126. ss_handshake_done
  19127. };
  19128. int protocol = 0;
  19129. int cbmode = 0;
  19130. int state = 0;
  19131. WOLFSSL_ENTER("wolfSSL_state_string_long");
  19132. if (ssl == NULL) {
  19133. WOLFSSL_MSG("Null argument passed in");
  19134. return NULL;
  19135. }
  19136. /* Get state of callback */
  19137. if (ssl->cbmode == SSL_CB_MODE_WRITE) {
  19138. cbmode = SS_WRITE;
  19139. }
  19140. else if (ssl->cbmode == SSL_CB_MODE_READ) {
  19141. cbmode = SS_READ;
  19142. }
  19143. else {
  19144. cbmode = SS_NEITHER;
  19145. }
  19146. /* Get protocol version */
  19147. switch (ssl->version.major) {
  19148. case SSLv3_MAJOR:
  19149. switch (ssl->version.minor) {
  19150. case SSLv3_MINOR:
  19151. protocol = SSL_V3;
  19152. break;
  19153. case TLSv1_MINOR:
  19154. protocol = TLS_V1;
  19155. break;
  19156. case TLSv1_1_MINOR:
  19157. protocol = TLS_V1_1;
  19158. break;
  19159. case TLSv1_2_MINOR:
  19160. protocol = TLS_V1_2;
  19161. break;
  19162. case TLSv1_3_MINOR:
  19163. protocol = TLS_V1_3;
  19164. break;
  19165. default:
  19166. protocol = UNKNOWN;
  19167. }
  19168. break;
  19169. case DTLS_MAJOR:
  19170. switch (ssl->version.minor) {
  19171. case DTLS_MINOR:
  19172. protocol = DTLS_V1;
  19173. break;
  19174. case DTLSv1_2_MINOR:
  19175. protocol = DTLS_V1_2;
  19176. break;
  19177. case DTLSv1_3_MINOR:
  19178. protocol = DTLS_V1_3;
  19179. break;
  19180. default:
  19181. protocol = UNKNOWN;
  19182. }
  19183. break;
  19184. default:
  19185. protocol = UNKNOWN;
  19186. }
  19187. /* accept process */
  19188. if (ssl->cbmode == SSL_CB_MODE_READ) {
  19189. state = ssl->cbtype;
  19190. switch (state) {
  19191. case hello_request:
  19192. state = ss_server_hellorequest;
  19193. break;
  19194. case client_hello:
  19195. state = ss_client_hello;
  19196. break;
  19197. case server_hello:
  19198. state = ss_server_hello;
  19199. break;
  19200. case hello_verify_request:
  19201. state = ss_server_helloverify;
  19202. break;
  19203. case session_ticket:
  19204. state = ss_server_sessionticket;
  19205. break;
  19206. case end_of_early_data:
  19207. state = ss_client_endofearlydata;
  19208. break;
  19209. case hello_retry_request:
  19210. state = ss_server_helloretryrequest;
  19211. break;
  19212. case encrypted_extensions:
  19213. state = ss_server_encryptedextensions;
  19214. break;
  19215. case certificate:
  19216. if (ssl->options.side == WOLFSSL_SERVER_END)
  19217. state = ss_client_cert;
  19218. else if (ssl->options.side == WOLFSSL_CLIENT_END)
  19219. state = ss_server_cert;
  19220. else {
  19221. WOLFSSL_MSG("Unknown State");
  19222. state = ss_null_state;
  19223. }
  19224. break;
  19225. case server_key_exchange:
  19226. state = ss_server_keyexchange;
  19227. break;
  19228. case certificate_request:
  19229. state = ss_server_certrequest;
  19230. break;
  19231. case server_hello_done:
  19232. state = ss_server_hellodone;
  19233. break;
  19234. case certificate_verify:
  19235. state = ss_client_certverify;
  19236. break;
  19237. case client_key_exchange:
  19238. state = ss_client_keyexchange;
  19239. break;
  19240. case finished:
  19241. if (ssl->options.side == WOLFSSL_SERVER_END)
  19242. state = ss_client_finished;
  19243. else if (ssl->options.side == WOLFSSL_CLIENT_END)
  19244. state = ss_server_finished;
  19245. else {
  19246. WOLFSSL_MSG("Unknown State");
  19247. state = ss_null_state;
  19248. }
  19249. break;
  19250. case certificate_status:
  19251. state = ss_server_certificatestatus;
  19252. break;
  19253. case key_update:
  19254. if (ssl->options.side == WOLFSSL_SERVER_END)
  19255. state = ss_client_keyupdate;
  19256. else if (ssl->options.side == WOLFSSL_CLIENT_END)
  19257. state = ss_server_keyupdate;
  19258. else {
  19259. WOLFSSL_MSG("Unknown State");
  19260. state = ss_null_state;
  19261. }
  19262. break;
  19263. case change_cipher_hs:
  19264. if (ssl->options.side == WOLFSSL_SERVER_END)
  19265. state = ss_client_changecipherspec;
  19266. else if (ssl->options.side == WOLFSSL_CLIENT_END)
  19267. state = ss_server_changecipherspec;
  19268. else {
  19269. WOLFSSL_MSG("Unknown State");
  19270. state = ss_null_state;
  19271. }
  19272. break;
  19273. default:
  19274. WOLFSSL_MSG("Unknown State");
  19275. state = ss_null_state;
  19276. }
  19277. }
  19278. else {
  19279. /* Send process */
  19280. if (ssl->options.side == WOLFSSL_SERVER_END)
  19281. state = ssl->options.serverState;
  19282. else
  19283. state = ssl->options.clientState;
  19284. switch (state) {
  19285. case SERVER_HELLOVERIFYREQUEST_COMPLETE:
  19286. state = ss_server_helloverify;
  19287. break;
  19288. case SERVER_HELLO_RETRY_REQUEST_COMPLETE:
  19289. state = ss_server_helloretryrequest;
  19290. break;
  19291. case SERVER_HELLO_COMPLETE:
  19292. state = ss_server_hello;
  19293. break;
  19294. case SERVER_ENCRYPTED_EXTENSIONS_COMPLETE:
  19295. state = ss_server_encryptedextensions;
  19296. break;
  19297. case SERVER_CERT_COMPLETE:
  19298. state = ss_server_cert;
  19299. break;
  19300. case SERVER_KEYEXCHANGE_COMPLETE:
  19301. state = ss_server_keyexchange;
  19302. break;
  19303. case SERVER_HELLODONE_COMPLETE:
  19304. state = ss_server_hellodone;
  19305. break;
  19306. case SERVER_CHANGECIPHERSPEC_COMPLETE:
  19307. state = ss_server_changecipherspec;
  19308. break;
  19309. case SERVER_FINISHED_COMPLETE:
  19310. state = ss_server_finished;
  19311. break;
  19312. case CLIENT_HELLO_RETRY:
  19313. case CLIENT_HELLO_COMPLETE:
  19314. state = ss_client_hello;
  19315. break;
  19316. case CLIENT_KEYEXCHANGE_COMPLETE:
  19317. state = ss_client_keyexchange;
  19318. break;
  19319. case CLIENT_CHANGECIPHERSPEC_COMPLETE:
  19320. state = ss_client_changecipherspec;
  19321. break;
  19322. case CLIENT_FINISHED_COMPLETE:
  19323. state = ss_client_finished;
  19324. break;
  19325. case HANDSHAKE_DONE:
  19326. state = ss_handshake_done;
  19327. break;
  19328. default:
  19329. WOLFSSL_MSG("Unknown State");
  19330. state = ss_null_state;
  19331. }
  19332. }
  19333. if (protocol == UNKNOWN) {
  19334. WOLFSSL_MSG("Unknown protocol");
  19335. return "";
  19336. }
  19337. else {
  19338. return OUTPUT_STR[state][protocol][cbmode];
  19339. }
  19340. }
  19341. /*
  19342. * Sets default PEM callback password if null is passed into
  19343. * the callback parameter of a PEM_read_bio_* function.
  19344. *
  19345. * Returns callback phrase size on success or WOLFSSL_FAILURE otherwise.
  19346. */
  19347. int wolfSSL_PEM_def_callback(char* name, int num, int w, void* key)
  19348. {
  19349. int sz;
  19350. (void)w;
  19351. WOLFSSL_ENTER("wolfSSL_PEM_def_callback");
  19352. /* We assume that the user passes a default password as userdata */
  19353. if (key) {
  19354. sz = (int)XSTRLEN((const char*)key);
  19355. sz = (sz > num) ? num : sz;
  19356. XMEMCPY(name, key, sz);
  19357. return sz;
  19358. } else {
  19359. WOLFSSL_MSG("Error, default password cannot be created.");
  19360. return WOLFSSL_FAILURE;
  19361. }
  19362. }
  19363. #endif /* OPENSSL_EXTRA */
  19364. static long wolf_set_options(long old_op, long op)
  19365. {
  19366. /* if SSL_OP_ALL then turn all bug workarounds on */
  19367. if ((op & WOLFSSL_OP_ALL) == WOLFSSL_OP_ALL) {
  19368. WOLFSSL_MSG("\tSSL_OP_ALL");
  19369. }
  19370. /* by default cookie exchange is on with DTLS */
  19371. if ((op & WOLFSSL_OP_COOKIE_EXCHANGE) == WOLFSSL_OP_COOKIE_EXCHANGE) {
  19372. WOLFSSL_MSG("\tSSL_OP_COOKIE_EXCHANGE : on by default");
  19373. }
  19374. if ((op & WOLFSSL_OP_NO_SSLv2) == WOLFSSL_OP_NO_SSLv2) {
  19375. WOLFSSL_MSG("\tWOLFSSL_OP_NO_SSLv2 : wolfSSL does not support SSLv2");
  19376. }
  19377. #ifdef SSL_OP_NO_TLSv1_3
  19378. if ((op & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
  19379. WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_3");
  19380. }
  19381. #endif
  19382. if ((op & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
  19383. WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_2");
  19384. }
  19385. if ((op & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
  19386. WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_1");
  19387. }
  19388. if ((op & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
  19389. WOLFSSL_MSG("\tSSL_OP_NO_TLSv1");
  19390. }
  19391. if ((op & WOLFSSL_OP_NO_SSLv3) == WOLFSSL_OP_NO_SSLv3) {
  19392. WOLFSSL_MSG("\tSSL_OP_NO_SSLv3");
  19393. }
  19394. if ((op & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) ==
  19395. WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
  19396. WOLFSSL_MSG("\tWOLFSSL_OP_CIPHER_SERVER_PREFERENCE");
  19397. }
  19398. if ((op & WOLFSSL_OP_NO_COMPRESSION) == WOLFSSL_OP_NO_COMPRESSION) {
  19399. #ifdef HAVE_LIBZ
  19400. WOLFSSL_MSG("SSL_OP_NO_COMPRESSION");
  19401. #else
  19402. WOLFSSL_MSG("SSL_OP_NO_COMPRESSION: compression not compiled in");
  19403. #endif
  19404. }
  19405. return old_op | op;
  19406. }
  19407. long wolfSSL_set_options(WOLFSSL* ssl, long op)
  19408. {
  19409. word16 haveRSA = 1;
  19410. word16 havePSK = 0;
  19411. int keySz = 0;
  19412. WOLFSSL_ENTER("wolfSSL_set_options");
  19413. if (ssl == NULL) {
  19414. return 0;
  19415. }
  19416. ssl->options.mask = wolf_set_options(ssl->options.mask, op);
  19417. if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
  19418. if (ssl->version.minor == TLSv1_3_MINOR)
  19419. ssl->version.minor = TLSv1_2_MINOR;
  19420. }
  19421. if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
  19422. if (ssl->version.minor == TLSv1_2_MINOR)
  19423. ssl->version.minor = TLSv1_1_MINOR;
  19424. }
  19425. if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
  19426. if (ssl->version.minor == TLSv1_1_MINOR)
  19427. ssl->version.minor = TLSv1_MINOR;
  19428. }
  19429. if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
  19430. if (ssl->version.minor == TLSv1_MINOR)
  19431. ssl->version.minor = SSLv3_MINOR;
  19432. }
  19433. if ((ssl->options.mask & WOLFSSL_OP_NO_COMPRESSION)
  19434. == WOLFSSL_OP_NO_COMPRESSION) {
  19435. #ifdef HAVE_LIBZ
  19436. ssl->options.usingCompression = 0;
  19437. #endif
  19438. }
  19439. /* in the case of a version change the cipher suites should be reset */
  19440. #ifndef NO_PSK
  19441. havePSK = ssl->options.havePSK;
  19442. #endif
  19443. #ifdef NO_RSA
  19444. haveRSA = 0;
  19445. #endif
  19446. #ifndef NO_CERTS
  19447. keySz = ssl->buffers.keySz;
  19448. #endif
  19449. if (ssl->suites != NULL && ssl->options.side != WOLFSSL_NEITHER_END)
  19450. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
  19451. ssl->options.haveDH, ssl->options.haveECDSAsig,
  19452. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  19453. ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
  19454. ssl->options.haveAnon, TRUE, ssl->options.side);
  19455. return ssl->options.mask;
  19456. }
  19457. long wolfSSL_get_options(const WOLFSSL* ssl)
  19458. {
  19459. WOLFSSL_ENTER("wolfSSL_get_options");
  19460. if(ssl == NULL)
  19461. return WOLFSSL_FAILURE;
  19462. return ssl->options.mask;
  19463. }
  19464. #if defined(HAVE_SECURE_RENEGOTIATION) \
  19465. || defined(HAVE_SERVER_RENEGOTIATION_INFO)
  19466. /* clears the counter for number of renegotiations done
  19467. * returns the current count before it is cleared */
  19468. long wolfSSL_clear_num_renegotiations(WOLFSSL *s)
  19469. {
  19470. long total;
  19471. WOLFSSL_ENTER("wolfSSL_clear_num_renegotiations");
  19472. if (s == NULL)
  19473. return 0;
  19474. total = s->secure_rene_count;
  19475. s->secure_rene_count = 0;
  19476. return total;
  19477. }
  19478. /* return the number of renegotiations since wolfSSL_new */
  19479. long wolfSSL_total_renegotiations(WOLFSSL *s)
  19480. {
  19481. WOLFSSL_ENTER("wolfSSL_total_renegotiations");
  19482. return wolfSSL_num_renegotiations(s);
  19483. }
  19484. /* return the number of renegotiations since wolfSSL_new */
  19485. long wolfSSL_num_renegotiations(WOLFSSL* s)
  19486. {
  19487. if (s == NULL) {
  19488. return 0;
  19489. }
  19490. return s->secure_rene_count;
  19491. }
  19492. /* Is there a renegotiation currently in progress? */
  19493. int wolfSSL_SSL_renegotiate_pending(WOLFSSL *s)
  19494. {
  19495. return s && s->options.handShakeDone &&
  19496. s->options.handShakeState != HANDSHAKE_DONE ? 1 : 0;
  19497. }
  19498. #endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */
  19499. #ifdef OPENSSL_EXTRA
  19500. long wolfSSL_clear_options(WOLFSSL* ssl, long opt)
  19501. {
  19502. WOLFSSL_ENTER("SSL_clear_options");
  19503. if(ssl == NULL)
  19504. return WOLFSSL_FAILURE;
  19505. ssl->options.mask &= ~opt;
  19506. return ssl->options.mask;
  19507. }
  19508. #ifdef HAVE_PK_CALLBACKS
  19509. long wolfSSL_set_tlsext_debug_arg(WOLFSSL* ssl, void *arg)
  19510. {
  19511. if (ssl == NULL) {
  19512. return WOLFSSL_FAILURE;
  19513. }
  19514. ssl->loggingCtx = arg;
  19515. return WOLFSSL_SUCCESS;
  19516. }
  19517. #endif /* HAVE_PK_CALLBACKS */
  19518. #if defined(OPENSSL_ALL) || defined(WOLFSSL_HAPROXY)
  19519. const unsigned char *SSL_SESSION_get0_id_context(const WOLFSSL_SESSION *sess, unsigned int *sid_ctx_length)
  19520. {
  19521. sess = ClientSessionToSession(sess);
  19522. return wolfSSL_SESSION_get_id((WOLFSSL_SESSION *)sess, sid_ctx_length);
  19523. }
  19524. #endif
  19525. /*** TBD ***/
  19526. #ifndef NO_WOLFSSL_STUB
  19527. WOLFSSL_API int wolfSSL_sk_SSL_COMP_zero(WOLFSSL_STACK* st)
  19528. {
  19529. (void)st;
  19530. WOLFSSL_STUB("wolfSSL_sk_SSL_COMP_zero");
  19531. /* wolfSSL_set_options(ssl, SSL_OP_NO_COMPRESSION); */
  19532. return WOLFSSL_FAILURE;
  19533. }
  19534. #endif
  19535. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  19536. long wolfSSL_set_tlsext_status_type(WOLFSSL *s, int type)
  19537. {
  19538. WOLFSSL_ENTER("wolfSSL_set_tlsext_status_type");
  19539. if (s == NULL){
  19540. return BAD_FUNC_ARG;
  19541. }
  19542. if (type == TLSEXT_STATUSTYPE_ocsp){
  19543. int r = TLSX_UseCertificateStatusRequest(&s->extensions, (byte)type, 0, s,
  19544. s->heap, s->devId);
  19545. return (long)r;
  19546. } else {
  19547. WOLFSSL_MSG(
  19548. "SSL_set_tlsext_status_type only supports TLSEXT_STATUSTYPE_ocsp type.");
  19549. return SSL_FAILURE;
  19550. }
  19551. }
  19552. long wolfSSL_get_tlsext_status_type(WOLFSSL *s)
  19553. {
  19554. TLSX* extension;
  19555. if (s == NULL)
  19556. return WOLFSSL_FATAL_ERROR;
  19557. extension = TLSX_Find(s->extensions, TLSX_STATUS_REQUEST);
  19558. return extension != NULL ? TLSEXT_STATUSTYPE_ocsp : WOLFSSL_FATAL_ERROR;
  19559. }
  19560. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
  19561. #ifndef NO_WOLFSSL_STUB
  19562. WOLFSSL_API long wolfSSL_get_tlsext_status_exts(WOLFSSL *s, void *arg)
  19563. {
  19564. (void)s;
  19565. (void)arg;
  19566. WOLFSSL_STUB("wolfSSL_get_tlsext_status_exts");
  19567. return WOLFSSL_FAILURE;
  19568. }
  19569. #endif
  19570. /*** TBD ***/
  19571. #ifndef NO_WOLFSSL_STUB
  19572. WOLFSSL_API long wolfSSL_set_tlsext_status_exts(WOLFSSL *s, void *arg)
  19573. {
  19574. (void)s;
  19575. (void)arg;
  19576. WOLFSSL_STUB("wolfSSL_set_tlsext_status_exts");
  19577. return WOLFSSL_FAILURE;
  19578. }
  19579. #endif
  19580. /*** TBD ***/
  19581. #ifndef NO_WOLFSSL_STUB
  19582. WOLFSSL_API long wolfSSL_get_tlsext_status_ids(WOLFSSL *s, void *arg)
  19583. {
  19584. (void)s;
  19585. (void)arg;
  19586. WOLFSSL_STUB("wolfSSL_get_tlsext_status_ids");
  19587. return WOLFSSL_FAILURE;
  19588. }
  19589. #endif
  19590. /*** TBD ***/
  19591. #ifndef NO_WOLFSSL_STUB
  19592. WOLFSSL_API long wolfSSL_set_tlsext_status_ids(WOLFSSL *s, void *arg)
  19593. {
  19594. (void)s;
  19595. (void)arg;
  19596. WOLFSSL_STUB("wolfSSL_set_tlsext_status_ids");
  19597. return WOLFSSL_FAILURE;
  19598. }
  19599. #endif
  19600. /*** TBD ***/
  19601. #ifndef NO_WOLFSSL_STUB
  19602. WOLFSSL_API int SSL_SESSION_set1_id(WOLFSSL_SESSION *s, const unsigned char *sid, unsigned int sid_len)
  19603. {
  19604. (void)s;
  19605. (void)sid;
  19606. (void)sid_len;
  19607. WOLFSSL_STUB("SSL_SESSION_set1_id");
  19608. return WOLFSSL_FAILURE;
  19609. }
  19610. #endif
  19611. #ifndef NO_WOLFSSL_STUB
  19612. /*** TBD ***/
  19613. WOLFSSL_API int SSL_SESSION_set1_id_context(WOLFSSL_SESSION *s, const unsigned char *sid_ctx, unsigned int sid_ctx_len)
  19614. {
  19615. (void)s;
  19616. (void)sid_ctx;
  19617. (void)sid_ctx_len;
  19618. WOLFSSL_STUB("SSL_SESSION_set1_id_context");
  19619. return WOLFSSL_FAILURE;
  19620. }
  19621. #endif
  19622. #if defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD) \
  19623. || defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_WPAS)
  19624. /**
  19625. * Set `a` in a smart way.
  19626. *
  19627. * @param a Object to set
  19628. * @param type The type of object in value
  19629. * @param value Object to set
  19630. */
  19631. void wolfSSL_ASN1_TYPE_set(WOLFSSL_ASN1_TYPE *a, int type, void *value)
  19632. {
  19633. if (!a) {
  19634. return;
  19635. }
  19636. switch (type) {
  19637. case V_ASN1_NULL:
  19638. a->value.ptr = (char *)value;
  19639. break;
  19640. case V_ASN1_SEQUENCE:
  19641. a->value.asn1_string = (WOLFSSL_ASN1_STRING*)value;
  19642. break;
  19643. case V_ASN1_OBJECT:
  19644. a->value.object = (WOLFSSL_ASN1_OBJECT*)value;
  19645. break;
  19646. case V_ASN1_UTCTIME:
  19647. a->value.utctime = (WOLFSSL_ASN1_TIME*)value;
  19648. break;
  19649. case V_ASN1_GENERALIZEDTIME:
  19650. a->value.generalizedtime = (WOLFSSL_ASN1_TIME*)value;
  19651. break;
  19652. default:
  19653. WOLFSSL_MSG("Unknown or unsupported ASN1_TYPE");
  19654. return;
  19655. }
  19656. a->type = type;
  19657. }
  19658. #endif /* OPENSSL_ALL || WOLFSSL_APACHE_HTTPD || WOLFSSL_HAPROXY || WOLFSSL_WPAS */
  19659. #if defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD) \
  19660. || defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_WPAS) \
  19661. || defined(OPENSSL_EXTRA)
  19662. /**
  19663. * Allocate a new WOLFSSL_ASN1_TYPE object.
  19664. *
  19665. * @return New zero'ed WOLFSSL_ASN1_TYPE object
  19666. */
  19667. WOLFSSL_ASN1_TYPE* wolfSSL_ASN1_TYPE_new(void)
  19668. {
  19669. WOLFSSL_ASN1_TYPE* ret = (WOLFSSL_ASN1_TYPE*)XMALLOC(sizeof(WOLFSSL_ASN1_TYPE),
  19670. NULL, DYNAMIC_TYPE_OPENSSL);
  19671. if (!ret)
  19672. return NULL;
  19673. XMEMSET(ret, 0, sizeof(WOLFSSL_ASN1_TYPE));
  19674. return ret;
  19675. }
  19676. /**
  19677. * Free WOLFSSL_ASN1_TYPE and all its members.
  19678. *
  19679. * @param at Object to free
  19680. */
  19681. void wolfSSL_ASN1_TYPE_free(WOLFSSL_ASN1_TYPE* at)
  19682. {
  19683. if (at) {
  19684. switch (at->type) {
  19685. case V_ASN1_OBJECT:
  19686. wolfSSL_ASN1_OBJECT_free(at->value.object);
  19687. break;
  19688. case V_ASN1_UTCTIME:
  19689. #ifndef NO_ASN_TIME
  19690. wolfSSL_ASN1_TIME_free(at->value.utctime);
  19691. #endif
  19692. break;
  19693. case V_ASN1_GENERALIZEDTIME:
  19694. #ifndef NO_ASN_TIME
  19695. wolfSSL_ASN1_TIME_free(at->value.generalizedtime);
  19696. #endif
  19697. break;
  19698. case V_ASN1_UTF8STRING:
  19699. case V_ASN1_PRINTABLESTRING:
  19700. case V_ASN1_T61STRING:
  19701. case V_ASN1_IA5STRING:
  19702. case V_ASN1_UNIVERSALSTRING:
  19703. case V_ASN1_SEQUENCE:
  19704. wolfSSL_ASN1_STRING_free(at->value.asn1_string);
  19705. break;
  19706. default:
  19707. WOLFSSL_MSG("Unknown or unsupported ASN1_TYPE");
  19708. break;
  19709. }
  19710. XFREE(at, NULL, DYNAMIC_TYPE_OPENSSL);
  19711. }
  19712. }
  19713. #endif /* OPENSSL_ALL || WOLFSSL_APACHE_HTTPD || WOLFSSL_HAPROXY || WOLFSSL_WPAS
  19714. || OPENSSL_EXTRA */
  19715. #ifndef NO_WOLFSSL_STUB
  19716. /*** TBD ***/
  19717. WOLFSSL_API WOLFSSL_EVP_PKEY *wolfSSL_get_privatekey(const WOLFSSL *ssl)
  19718. {
  19719. (void)ssl;
  19720. WOLFSSL_STUB("SSL_get_privatekey");
  19721. return NULL;
  19722. }
  19723. #endif
  19724. /**
  19725. * Get a textual representation of given WOLFSSL_ASN1_OBJECT then write it to
  19726. * buf at most buf_len bytes.
  19727. *
  19728. * params
  19729. * - buf: buffer where the textual representation is to be written to
  19730. * - buf_len: buffer size in bytes
  19731. * - a: WOLFSSL_ASN1_OBJECT
  19732. *
  19733. * return the string length written on success, WOLFSSL_FAILURE on failure.
  19734. */
  19735. WOLFSSL_API int wolfSSL_i2t_ASN1_OBJECT(char *buf, int buf_len,
  19736. WOLFSSL_ASN1_OBJECT *a)
  19737. {
  19738. WOLFSSL_ENTER("wolfSSL_i2t_ASN1_OBJECT");
  19739. return wolfSSL_OBJ_obj2txt(buf, buf_len, a, 0);
  19740. }
  19741. WOLFSSL_ASN1_OBJECT *wolfSSL_d2i_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT **a,
  19742. const unsigned char **der,
  19743. long length)
  19744. {
  19745. const unsigned char *d;
  19746. long len;
  19747. int tag, cls;
  19748. WOLFSSL_ASN1_OBJECT* ret = NULL;
  19749. WOLFSSL_ENTER("wolfSSL_d2i_ASN1_OBJECT");
  19750. if (!der || !*der || length <= 0) {
  19751. WOLFSSL_MSG("Bad parameter");
  19752. return NULL;
  19753. }
  19754. d = *der;
  19755. if (wolfSSL_ASN1_get_object(&d, &len, &tag, &cls, length) & 0x80) {
  19756. WOLFSSL_MSG("wolfSSL_ASN1_get_object error");
  19757. return NULL;
  19758. }
  19759. /* d now points to value */
  19760. if (tag != ASN_OBJECT_ID) {
  19761. WOLFSSL_MSG("Not an ASN object");
  19762. return NULL;
  19763. }
  19764. ret = wolfSSL_c2i_ASN1_OBJECT(a, &d, len);
  19765. if (ret)
  19766. *der = d;
  19767. return ret;
  19768. }
  19769. /**
  19770. * Parse an ASN1 encoded input and output information about the parsed object
  19771. * @param in ASN1 encoded data. *in is moved to the value of the ASN1 object
  19772. * @param len Length of parsed ASN1 object
  19773. * @param tag Tag value of parsed ASN1 object
  19774. * @param cls Class of parsed ASN1 object
  19775. * @param inLen Length of *in buffer
  19776. * @return int Depends on which bits are set in the returned int:
  19777. * 0x80 an error occurred during parsing
  19778. * 0x20 parsed object is constructed
  19779. * 0x01 the parsed object length is infinite
  19780. */
  19781. int wolfSSL_ASN1_get_object(const unsigned char **in, long *len, int *tag,
  19782. int *cls, long inLen)
  19783. {
  19784. word32 inOutIdx = 0;
  19785. int l;
  19786. byte t;
  19787. int ret = 0x80;
  19788. WOLFSSL_ENTER("wolfSSL_ASN1_get_object");
  19789. if (!in || !*in || !len || !tag || !cls || inLen == 0) {
  19790. WOLFSSL_MSG("Bad parameter");
  19791. return ret;
  19792. }
  19793. if (GetASNTag(*in, &inOutIdx, &t, (word32)inLen) != 0) {
  19794. WOLFSSL_MSG("GetASNTag error");
  19795. return ret;
  19796. }
  19797. if (GetLength(*in, &inOutIdx, &l, (word32)inLen) < 0) {
  19798. WOLFSSL_MSG("GetLength error");
  19799. return ret;
  19800. }
  19801. *tag = t & 0x1F; /* Tag number is 5 lsb */
  19802. *cls = t & 0xC0; /* Class is 2 msb */
  19803. *len = l;
  19804. ret = t & ASN_CONSTRUCTED;
  19805. if (l > (int)(inLen - inOutIdx)) {
  19806. /* Still return other values but indicate error in msb */
  19807. ret |= 0x80;
  19808. }
  19809. *in += inOutIdx;
  19810. return ret;
  19811. }
  19812. WOLFSSL_ASN1_OBJECT *wolfSSL_c2i_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT **a,
  19813. const unsigned char **pp, long len)
  19814. {
  19815. WOLFSSL_ASN1_OBJECT* ret = NULL;
  19816. WOLFSSL_ENTER("wolfSSL_c2i_ASN1_OBJECT");
  19817. if (!pp || !*pp || len <= 0) {
  19818. WOLFSSL_MSG("Bad parameter");
  19819. return NULL;
  19820. }
  19821. if (!(ret = wolfSSL_ASN1_OBJECT_new())) {
  19822. WOLFSSL_MSG("wolfSSL_ASN1_OBJECT_new error");
  19823. return NULL;
  19824. }
  19825. ret->obj = (const unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_ASN1);
  19826. if (!ret->obj) {
  19827. WOLFSSL_MSG("error allocating asn data memory");
  19828. wolfSSL_ASN1_OBJECT_free(ret);
  19829. return NULL;
  19830. }
  19831. XMEMCPY((byte*)ret->obj, *pp, len);
  19832. ret->objSz = (unsigned int)len;
  19833. ret->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA;
  19834. *pp += len;
  19835. if (a)
  19836. *a = ret;
  19837. return ret;
  19838. }
  19839. #ifndef NO_BIO
  19840. /* Return number of bytes written to BIO on success. 0 on failure. */
  19841. WOLFSSL_API int wolfSSL_i2a_ASN1_OBJECT(WOLFSSL_BIO *bp,
  19842. WOLFSSL_ASN1_OBJECT *a)
  19843. {
  19844. int length = 0;
  19845. word32 idx = 0;
  19846. const char null_str[] = "NULL";
  19847. WOLFSSL_ENTER("wolfSSL_i2a_ASN1_OBJECT");
  19848. if (bp == NULL)
  19849. return WOLFSSL_FAILURE;
  19850. if (a == NULL) {
  19851. /* Write "NULL" */
  19852. if (wolfSSL_BIO_write(bp, null_str, (int)XSTRLEN(null_str)) ==
  19853. (int)XSTRLEN(null_str)) {
  19854. return (int)XSTRLEN(null_str);
  19855. }
  19856. else {
  19857. return WOLFSSL_FAILURE;
  19858. }
  19859. }
  19860. if ((a->obj == NULL) || (a->obj[idx++] != ASN_OBJECT_ID)) {
  19861. WOLFSSL_MSG("Bad ASN1 Object");
  19862. return WOLFSSL_FAILURE;
  19863. }
  19864. if (GetLength((const byte*)a->obj, &idx, &length,
  19865. a->objSz) < 0 || length < 0) {
  19866. return WOLFSSL_FAILURE;
  19867. }
  19868. if (wolfSSL_BIO_write(bp, a->obj + idx, length) == (int)length) {
  19869. return length;
  19870. }
  19871. return WOLFSSL_FAILURE;
  19872. }
  19873. #endif /* !NO_BIO */
  19874. /* Returns object data for an ASN1_OBJECT */
  19875. /* If pp is NULL then only the size is returned */
  19876. /* If pp has pointer to pointer then its used directly */
  19877. /* If pp has pointer to pointer that is NULL then new variable is allocated */
  19878. /* Failure returns WOLFSSL_FAILURE (0) */
  19879. int wolfSSL_i2d_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT *a, unsigned char **pp)
  19880. {
  19881. byte *p;
  19882. WOLFSSL_ENTER("wolfSSL_i2d_ASN1_OBJECT");
  19883. if (!a || !a->obj) {
  19884. WOLFSSL_MSG("Bad parameters");
  19885. return WOLFSSL_FAILURE;
  19886. }
  19887. if (!pp)
  19888. return a->objSz;
  19889. if (*pp)
  19890. p = *pp;
  19891. else {
  19892. p = (byte*)XMALLOC(a->objSz, NULL, DYNAMIC_TYPE_OPENSSL);
  19893. if (!p) {
  19894. WOLFSSL_MSG("Bad malloc");
  19895. return WOLFSSL_FAILURE;
  19896. }
  19897. }
  19898. XMEMCPY(p, a->obj, a->objSz);
  19899. *pp = p + a->objSz;
  19900. return a->objSz;
  19901. }
  19902. #ifndef NO_WOLFSSL_STUB
  19903. /*** TBD ***/
  19904. WOLFSSL_API void SSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx, WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength))
  19905. {
  19906. (void)ctx;
  19907. (void)dh;
  19908. WOLFSSL_STUB("SSL_CTX_set_tmp_dh_callback");
  19909. }
  19910. #endif
  19911. #ifndef NO_WOLFSSL_STUB
  19912. /*** TBD ***/
  19913. WOLFSSL_API WOLF_STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void)
  19914. {
  19915. WOLFSSL_STUB("SSL_COMP_get_compression_methods");
  19916. return NULL;
  19917. }
  19918. #endif
  19919. int wolfSSL_sk_SSL_CIPHER_num(const WOLF_STACK_OF(WOLFSSL_CIPHER)* p)
  19920. {
  19921. WOLFSSL_ENTER("wolfSSL_sk_SSL_CIPHER_num");
  19922. if (p == NULL) {
  19923. return WOLFSSL_FATAL_ERROR;
  19924. }
  19925. return (int)p->num;
  19926. }
  19927. WOLFSSL_API WOLFSSL_CIPHER* wolfSSL_sk_SSL_CIPHER_value(WOLFSSL_STACK* sk, int i)
  19928. {
  19929. WOLFSSL_ENTER("wolfSSL_sk_SSL_CIPHER_value");
  19930. return (WOLFSSL_CIPHER*)wolfSSL_sk_value(sk, i);
  19931. }
  19932. #if !defined(NETOS)
  19933. WOLFSSL_API void ERR_load_SSL_strings(void)
  19934. {
  19935. }
  19936. #endif
  19937. #ifdef HAVE_OCSP
  19938. WOLFSSL_API long wolfSSL_get_tlsext_status_ocsp_resp(WOLFSSL *s, unsigned char **resp)
  19939. {
  19940. if (s == NULL || resp == NULL)
  19941. return 0;
  19942. *resp = s->ocspResp;
  19943. return s->ocspRespSz;
  19944. }
  19945. WOLFSSL_API long wolfSSL_set_tlsext_status_ocsp_resp(WOLFSSL *s, unsigned char *resp, int len)
  19946. {
  19947. if (s == NULL)
  19948. return WOLFSSL_FAILURE;
  19949. s->ocspResp = resp;
  19950. s->ocspRespSz = len;
  19951. return WOLFSSL_SUCCESS;
  19952. }
  19953. #endif /* HAVE_OCSP */
  19954. #ifdef HAVE_MAX_FRAGMENT
  19955. #ifndef NO_WOLFSSL_CLIENT
  19956. /**
  19957. * Set max fragment tls extension
  19958. * @param c a pointer to WOLFSSL_CTX object
  19959. * @param mode maximum fragment length mode
  19960. * @return 1 on success, otherwise 0 or negative error code
  19961. */
  19962. WOLFSSL_API int wolfSSL_CTX_set_tlsext_max_fragment_length(WOLFSSL_CTX *c,
  19963. unsigned char mode)
  19964. {
  19965. if (c == NULL || (mode < WOLFSSL_MFL_2_9 || mode > WOLFSSL_MFL_2_12 ))
  19966. return BAD_FUNC_ARG;
  19967. return wolfSSL_CTX_UseMaxFragment(c, mode);
  19968. }
  19969. /**
  19970. * Set max fragment tls extension
  19971. * @param c a pointer to WOLFSSL object
  19972. * @param mode maximum fragment length mode
  19973. * @return 1 on success, otherwise 0 or negative error code
  19974. */
  19975. WOLFSSL_API int wolfSSL_set_tlsext_max_fragment_length(WOLFSSL *s,
  19976. unsigned char mode)
  19977. {
  19978. if (s == NULL || (mode < WOLFSSL_MFL_2_9 || mode > WOLFSSL_MFL_2_12 ))
  19979. return BAD_FUNC_ARG;
  19980. return wolfSSL_UseMaxFragment(s, mode);
  19981. }
  19982. #endif /* NO_WOLFSSL_CLIENT */
  19983. #endif /* HAVE_MAX_FRAGMENT */
  19984. #endif /* OPENSSL_EXTRA */
  19985. #ifdef WOLFSSL_HAVE_TLS_UNIQUE
  19986. WOLFSSL_API size_t wolfSSL_get_finished(const WOLFSSL *ssl, void *buf, size_t count)
  19987. {
  19988. byte len = 0;
  19989. WOLFSSL_ENTER("SSL_get_finished");
  19990. if (!ssl || !buf || count < TLS_FINISHED_SZ) {
  19991. WOLFSSL_MSG("Bad parameter");
  19992. return WOLFSSL_FAILURE;
  19993. }
  19994. if (ssl->options.side == WOLFSSL_SERVER_END) {
  19995. len = ssl->serverFinished_len;
  19996. XMEMCPY(buf, ssl->serverFinished, len);
  19997. }
  19998. else {
  19999. len = ssl->clientFinished_len;
  20000. XMEMCPY(buf, ssl->clientFinished, len);
  20001. }
  20002. return len;
  20003. }
  20004. WOLFSSL_API size_t wolfSSL_get_peer_finished(const WOLFSSL *ssl, void *buf, size_t count)
  20005. {
  20006. byte len = 0;
  20007. WOLFSSL_ENTER("SSL_get_peer_finished");
  20008. if (!ssl || !buf || count < TLS_FINISHED_SZ) {
  20009. WOLFSSL_MSG("Bad parameter");
  20010. return WOLFSSL_FAILURE;
  20011. }
  20012. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  20013. len = ssl->serverFinished_len;
  20014. XMEMCPY(buf, ssl->serverFinished, len);
  20015. }
  20016. else {
  20017. len = ssl->clientFinished_len;
  20018. XMEMCPY(buf, ssl->clientFinished, len);
  20019. }
  20020. return len;
  20021. }
  20022. #endif /* WOLFSSL_HAVE_TLS_UNIQUE */
  20023. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  20024. long wolfSSL_get_verify_result(const WOLFSSL *ssl)
  20025. {
  20026. if (ssl == NULL) {
  20027. return WOLFSSL_FAILURE;
  20028. }
  20029. return ssl->peerVerifyRet;
  20030. }
  20031. #endif
  20032. #ifdef OPENSSL_EXTRA
  20033. #ifndef NO_WOLFSSL_STUB
  20034. /* shows the number of accepts attempted by CTX in it's lifetime */
  20035. long wolfSSL_CTX_sess_accept(WOLFSSL_CTX* ctx)
  20036. {
  20037. WOLFSSL_STUB("wolfSSL_CTX_sess_accept");
  20038. (void)ctx;
  20039. return 0;
  20040. }
  20041. #endif
  20042. #ifndef NO_WOLFSSL_STUB
  20043. /* shows the number of connects attempted CTX in it's lifetime */
  20044. long wolfSSL_CTX_sess_connect(WOLFSSL_CTX* ctx)
  20045. {
  20046. WOLFSSL_STUB("wolfSSL_CTX_sess_connect");
  20047. (void)ctx;
  20048. return 0;
  20049. }
  20050. #endif
  20051. #ifndef NO_WOLFSSL_STUB
  20052. /* shows the number of accepts completed by CTX in it's lifetime */
  20053. long wolfSSL_CTX_sess_accept_good(WOLFSSL_CTX* ctx)
  20054. {
  20055. WOLFSSL_STUB("wolfSSL_CTX_sess_accept_good");
  20056. (void)ctx;
  20057. return 0;
  20058. }
  20059. #endif
  20060. #ifndef NO_WOLFSSL_STUB
  20061. /* shows the number of connects completed by CTX in it's lifetime */
  20062. long wolfSSL_CTX_sess_connect_good(WOLFSSL_CTX* ctx)
  20063. {
  20064. WOLFSSL_STUB("wolfSSL_CTX_sess_connect_good");
  20065. (void)ctx;
  20066. return 0;
  20067. }
  20068. #endif
  20069. #ifndef NO_WOLFSSL_STUB
  20070. /* shows the number of renegotiation accepts attempted by CTX */
  20071. long wolfSSL_CTX_sess_accept_renegotiate(WOLFSSL_CTX* ctx)
  20072. {
  20073. WOLFSSL_STUB("wolfSSL_CTX_sess_accept_renegotiate");
  20074. (void)ctx;
  20075. return 0;
  20076. }
  20077. #endif
  20078. #ifndef NO_WOLFSSL_STUB
  20079. /* shows the number of renegotiation accepts attempted by CTX */
  20080. long wolfSSL_CTX_sess_connect_renegotiate(WOLFSSL_CTX* ctx)
  20081. {
  20082. WOLFSSL_STUB("wolfSSL_CTX_sess_connect_renegotiate");
  20083. (void)ctx;
  20084. return 0;
  20085. }
  20086. #endif
  20087. #ifndef NO_WOLFSSL_STUB
  20088. long wolfSSL_CTX_sess_hits(WOLFSSL_CTX* ctx)
  20089. {
  20090. WOLFSSL_STUB("wolfSSL_CTX_sess_hits");
  20091. (void)ctx;
  20092. return 0;
  20093. }
  20094. #endif
  20095. #ifndef NO_WOLFSSL_STUB
  20096. long wolfSSL_CTX_sess_cb_hits(WOLFSSL_CTX* ctx)
  20097. {
  20098. WOLFSSL_STUB("wolfSSL_CTX_sess_cb_hits");
  20099. (void)ctx;
  20100. return 0;
  20101. }
  20102. #endif
  20103. #ifndef NO_WOLFSSL_STUB
  20104. long wolfSSL_CTX_sess_cache_full(WOLFSSL_CTX* ctx)
  20105. {
  20106. WOLFSSL_STUB("wolfSSL_CTX_sess_cache_full");
  20107. (void)ctx;
  20108. return 0;
  20109. }
  20110. #endif
  20111. #ifndef NO_WOLFSSL_STUB
  20112. long wolfSSL_CTX_sess_misses(WOLFSSL_CTX* ctx)
  20113. {
  20114. WOLFSSL_STUB("wolfSSL_CTX_sess_misses");
  20115. (void)ctx;
  20116. return 0;
  20117. }
  20118. #endif
  20119. #ifndef NO_WOLFSSL_STUB
  20120. long wolfSSL_CTX_sess_timeouts(WOLFSSL_CTX* ctx)
  20121. {
  20122. WOLFSSL_STUB("wolfSSL_CTX_sess_timeouts");
  20123. (void)ctx;
  20124. return 0;
  20125. }
  20126. #endif
  20127. /* Return the total number of sessions */
  20128. long wolfSSL_CTX_sess_number(WOLFSSL_CTX* ctx)
  20129. {
  20130. word32 total = 0;
  20131. WOLFSSL_ENTER("wolfSSL_CTX_sess_number");
  20132. (void)ctx;
  20133. #if defined(WOLFSSL_SESSION_STATS) && !defined(NO_SESSION_CACHE)
  20134. if (wolfSSL_get_session_stats(NULL, &total, NULL, NULL) != WOLFSSL_SUCCESS) {
  20135. WOLFSSL_MSG("Error getting session stats");
  20136. }
  20137. #else
  20138. WOLFSSL_MSG("Please use macro WOLFSSL_SESSION_STATS for session stats");
  20139. #endif
  20140. return (long)total;
  20141. }
  20142. #ifndef NO_CERTS
  20143. long wolfSSL_CTX_add_extra_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509)
  20144. {
  20145. byte* chain = NULL;
  20146. long chainSz = 0;
  20147. int derSz;
  20148. const byte* der;
  20149. int ret;
  20150. int idx = 0;
  20151. DerBuffer *derBuffer = NULL;
  20152. WOLFSSL_ENTER("wolfSSL_CTX_add_extra_chain_cert");
  20153. if (ctx == NULL || x509 == NULL) {
  20154. WOLFSSL_MSG("Bad Argument");
  20155. return WOLFSSL_FAILURE;
  20156. }
  20157. der = wolfSSL_X509_get_der(x509, &derSz);
  20158. if (der == NULL || derSz <= 0) {
  20159. WOLFSSL_MSG("Error getting X509 DER");
  20160. return WOLFSSL_FAILURE;
  20161. }
  20162. if (ctx->certificate == NULL) {
  20163. WOLFSSL_ENTER("wolfSSL_use_certificate_chain_buffer_format");
  20164. /* Process buffer makes first certificate the leaf. */
  20165. ret = ProcessBuffer(ctx, der, derSz, WOLFSSL_FILETYPE_ASN1, CERT_TYPE,
  20166. NULL, NULL, 1, GET_VERIFY_SETTING_CTX(ctx));
  20167. if (ret != WOLFSSL_SUCCESS) {
  20168. WOLFSSL_LEAVE("wolfSSL_CTX_add_extra_chain_cert", ret);
  20169. return WOLFSSL_FAILURE;
  20170. }
  20171. }
  20172. else {
  20173. /* TODO: Do this elsewhere. */
  20174. ret = AllocDer(&derBuffer, derSz, CERT_TYPE, ctx->heap);
  20175. if (ret != 0) {
  20176. WOLFSSL_MSG("Memory Error");
  20177. return WOLFSSL_FAILURE;
  20178. }
  20179. XMEMCPY(derBuffer->buffer, der, derSz);
  20180. ret = AddCA(ctx->cm, &derBuffer, WOLFSSL_USER_CA,
  20181. GET_VERIFY_SETTING_CTX(ctx));
  20182. if (ret != WOLFSSL_SUCCESS) {
  20183. WOLFSSL_LEAVE("wolfSSL_CTX_add_extra_chain_cert", ret);
  20184. return WOLFSSL_FAILURE;
  20185. }
  20186. /* adding cert to existing chain */
  20187. if (ctx->certChain != NULL && ctx->certChain->length > 0) {
  20188. chainSz += ctx->certChain->length;
  20189. }
  20190. chainSz += OPAQUE24_LEN + derSz;
  20191. chain = (byte*)XMALLOC(chainSz, ctx->heap, DYNAMIC_TYPE_DER);
  20192. if (chain == NULL) {
  20193. WOLFSSL_MSG("Memory Error");
  20194. return WOLFSSL_FAILURE;
  20195. }
  20196. if (ctx->certChain != NULL && ctx->certChain->length > 0) {
  20197. XMEMCPY(chain, ctx->certChain->buffer, ctx->certChain->length);
  20198. idx = ctx->certChain->length;
  20199. }
  20200. c32to24(derSz, chain + idx);
  20201. idx += OPAQUE24_LEN;
  20202. XMEMCPY(chain + idx, der, derSz);
  20203. idx += derSz;
  20204. #ifdef WOLFSSL_TLS13
  20205. ctx->certChainCnt++;
  20206. #endif
  20207. FreeDer(&ctx->certChain);
  20208. ret = AllocDer(&ctx->certChain, idx, CERT_TYPE, ctx->heap);
  20209. if (ret == 0) {
  20210. XMEMCPY(ctx->certChain->buffer, chain, idx);
  20211. }
  20212. }
  20213. /* on success WOLFSSL_X509 memory is responsibility of ctx */
  20214. wolfSSL_X509_free(x509);
  20215. if (chain != NULL)
  20216. XFREE(chain, ctx->heap, DYNAMIC_TYPE_DER);
  20217. return WOLFSSL_SUCCESS;
  20218. }
  20219. long wolfSSL_CTX_set_tlsext_status_arg(WOLFSSL_CTX* ctx, void* arg)
  20220. {
  20221. if (ctx == NULL || ctx->cm == NULL) {
  20222. return WOLFSSL_FAILURE;
  20223. }
  20224. ctx->cm->ocspIOCtx = arg;
  20225. return WOLFSSL_SUCCESS;
  20226. }
  20227. #endif /* NO_CERTS */
  20228. /* Get the session cache mode for CTX
  20229. *
  20230. * ctx WOLFSSL_CTX struct to get cache mode from
  20231. *
  20232. * Returns a bit mask that has the session cache mode */
  20233. WOLFSSL_API long wolfSSL_CTX_get_session_cache_mode(WOLFSSL_CTX* ctx)
  20234. {
  20235. long m = 0;
  20236. WOLFSSL_ENTER("SSL_CTX_set_session_cache_mode");
  20237. if (ctx == NULL) {
  20238. return m;
  20239. }
  20240. if (ctx->sessionCacheOff != 1) {
  20241. m |= SSL_SESS_CACHE_SERVER;
  20242. }
  20243. if (ctx->sessionCacheFlushOff == 1) {
  20244. m |= SSL_SESS_CACHE_NO_AUTO_CLEAR;
  20245. }
  20246. #ifdef HAVE_EXT_CACHE
  20247. if (ctx->internalCacheOff == 1) {
  20248. m |= SSL_SESS_CACHE_NO_INTERNAL_STORE;
  20249. }
  20250. if (ctx->internalCacheLookupOff == 1) {
  20251. m |= SSL_SESS_CACHE_NO_INTERNAL_LOOKUP;
  20252. }
  20253. #endif
  20254. return m;
  20255. }
  20256. int wolfSSL_get_read_ahead(const WOLFSSL* ssl)
  20257. {
  20258. if (ssl == NULL) {
  20259. return WOLFSSL_FAILURE;
  20260. }
  20261. return ssl->readAhead;
  20262. }
  20263. int wolfSSL_set_read_ahead(WOLFSSL* ssl, int v)
  20264. {
  20265. if (ssl == NULL) {
  20266. return WOLFSSL_FAILURE;
  20267. }
  20268. ssl->readAhead = (byte)v;
  20269. return WOLFSSL_SUCCESS;
  20270. }
  20271. int wolfSSL_CTX_get_read_ahead(WOLFSSL_CTX* ctx)
  20272. {
  20273. if (ctx == NULL) {
  20274. return WOLFSSL_FAILURE;
  20275. }
  20276. return ctx->readAhead;
  20277. }
  20278. int wolfSSL_CTX_set_read_ahead(WOLFSSL_CTX* ctx, int v)
  20279. {
  20280. if (ctx == NULL) {
  20281. return WOLFSSL_FAILURE;
  20282. }
  20283. ctx->readAhead = (byte)v;
  20284. return WOLFSSL_SUCCESS;
  20285. }
  20286. long wolfSSL_CTX_set_tlsext_opaque_prf_input_callback_arg(WOLFSSL_CTX* ctx,
  20287. void* arg)
  20288. {
  20289. if (ctx == NULL) {
  20290. return WOLFSSL_FAILURE;
  20291. }
  20292. ctx->userPRFArg = arg;
  20293. return WOLFSSL_SUCCESS;
  20294. }
  20295. #ifndef NO_DES3
  20296. /* 0 on success */
  20297. int wolfSSL_DES_set_key(WOLFSSL_const_DES_cblock* myDes,
  20298. WOLFSSL_DES_key_schedule* key)
  20299. {
  20300. #ifdef WOLFSSL_CHECK_DESKEY
  20301. return wolfSSL_DES_set_key_checked(myDes, key);
  20302. #else
  20303. wolfSSL_DES_set_key_unchecked(myDes, key);
  20304. return 0;
  20305. #endif
  20306. }
  20307. /* return true in fail case (1) */
  20308. static int DES_check(word32 mask, word32 mask2, unsigned char* key)
  20309. {
  20310. word32 value[2];
  20311. /* sanity check on length made in wolfSSL_DES_set_key_checked */
  20312. value[0] = mask;
  20313. value[1] = mask2;
  20314. return (XMEMCMP(value, key, sizeof(value)) == 0)? 1: 0;
  20315. }
  20316. /* check that the key is odd parity and is not a weak key
  20317. * returns -1 if parity is wrong, -2 if weak/null key and 0 on success */
  20318. int wolfSSL_DES_set_key_checked(WOLFSSL_const_DES_cblock* myDes,
  20319. WOLFSSL_DES_key_schedule* key)
  20320. {
  20321. if (myDes == NULL || key == NULL) {
  20322. WOLFSSL_MSG("Bad argument passed to wolfSSL_DES_set_key_checked");
  20323. return -2;
  20324. }
  20325. else {
  20326. word32 sz = sizeof(WOLFSSL_DES_key_schedule);
  20327. /* sanity check before call to DES_check */
  20328. if (sz != (sizeof(word32) * 2)) {
  20329. WOLFSSL_MSG("Unexpected WOLFSSL_DES_key_schedule size");
  20330. return -2;
  20331. }
  20332. /* check odd parity */
  20333. if (wolfSSL_DES_check_key_parity(myDes) != 1) {
  20334. WOLFSSL_MSG("Odd parity test fail");
  20335. return -1;
  20336. }
  20337. if (wolfSSL_DES_is_weak_key(myDes) == 1) {
  20338. WOLFSSL_MSG("Weak key found");
  20339. return -2;
  20340. }
  20341. /* passed tests, now copy over key */
  20342. XMEMCPY(key, myDes, sizeof(WOLFSSL_const_DES_cblock));
  20343. return 0;
  20344. }
  20345. }
  20346. /* check is not weak. Weak key list from Nist "Recommendation for the Triple
  20347. * Data Encryption Algorithm (TDEA) Block Cipher"
  20348. *
  20349. * returns 1 if is weak 0 if not
  20350. */
  20351. int wolfSSL_DES_is_weak_key(WOLFSSL_const_DES_cblock* key)
  20352. {
  20353. word32 mask, mask2;
  20354. WOLFSSL_ENTER("wolfSSL_DES_is_weak_key");
  20355. if (key == NULL) {
  20356. WOLFSSL_MSG("NULL key passed in");
  20357. return 1;
  20358. }
  20359. mask = 0x01010101; mask2 = 0x01010101;
  20360. if (DES_check(mask, mask2, *key)) {
  20361. WOLFSSL_MSG("Weak key found");
  20362. return 1;
  20363. }
  20364. mask = 0xFEFEFEFE; mask2 = 0xFEFEFEFE;
  20365. if (DES_check(mask, mask2, *key)) {
  20366. WOLFSSL_MSG("Weak key found");
  20367. return 1;
  20368. }
  20369. mask = 0xE0E0E0E0; mask2 = 0xF1F1F1F1;
  20370. if (DES_check(mask, mask2, *key)) {
  20371. WOLFSSL_MSG("Weak key found");
  20372. return 1;
  20373. }
  20374. mask = 0x1F1F1F1F; mask2 = 0x0E0E0E0E;
  20375. if (DES_check(mask, mask2, *key)) {
  20376. WOLFSSL_MSG("Weak key found");
  20377. return 1;
  20378. }
  20379. /* semi-weak *key check (list from same Nist paper) */
  20380. mask = 0x011F011F; mask2 = 0x010E010E;
  20381. if (DES_check(mask, mask2, *key) ||
  20382. DES_check(ByteReverseWord32(mask), ByteReverseWord32(mask2), *key)) {
  20383. WOLFSSL_MSG("Weak key found");
  20384. return 1;
  20385. }
  20386. mask = 0x01E001E0; mask2 = 0x01F101F1;
  20387. if (DES_check(mask, mask2, *key) ||
  20388. DES_check(ByteReverseWord32(mask), ByteReverseWord32(mask2), *key)) {
  20389. WOLFSSL_MSG("Weak key found");
  20390. return 1;
  20391. }
  20392. mask = 0x01FE01FE; mask2 = 0x01FE01FE;
  20393. if (DES_check(mask, mask2, *key) ||
  20394. DES_check(ByteReverseWord32(mask), ByteReverseWord32(mask2), *key)) {
  20395. WOLFSSL_MSG("Weak key found");
  20396. return 1;
  20397. }
  20398. mask = 0x1FE01FE0; mask2 = 0x0EF10EF1;
  20399. if (DES_check(mask, mask2, *key) ||
  20400. DES_check(ByteReverseWord32(mask), ByteReverseWord32(mask2), *key)) {
  20401. WOLFSSL_MSG("Weak key found");
  20402. return 1;
  20403. }
  20404. mask = 0x1FFE1FFE; mask2 = 0x0EFE0EFE;
  20405. if (DES_check(mask, mask2, *key) ||
  20406. DES_check(ByteReverseWord32(mask), ByteReverseWord32(mask2), *key)) {
  20407. WOLFSSL_MSG("Weak key found");
  20408. return 1;
  20409. }
  20410. return 0;
  20411. }
  20412. void wolfSSL_DES_set_key_unchecked(WOLFSSL_const_DES_cblock* myDes,
  20413. WOLFSSL_DES_key_schedule* key)
  20414. {
  20415. if (myDes != NULL && key != NULL) {
  20416. XMEMCPY(key, myDes, sizeof(WOLFSSL_const_DES_cblock));
  20417. }
  20418. }
  20419. /* Sets the parity of the DES key for use */
  20420. void wolfSSL_DES_set_odd_parity(WOLFSSL_DES_cblock* myDes)
  20421. {
  20422. word32 i;
  20423. word32 sz = sizeof(WOLFSSL_DES_cblock);
  20424. WOLFSSL_ENTER("wolfSSL_DES_set_odd_parity");
  20425. for (i = 0; i < sz; i++) {
  20426. unsigned char c = (*myDes)[i];
  20427. if ((
  20428. ((c >> 1) & 0x01) ^
  20429. ((c >> 2) & 0x01) ^
  20430. ((c >> 3) & 0x01) ^
  20431. ((c >> 4) & 0x01) ^
  20432. ((c >> 5) & 0x01) ^
  20433. ((c >> 6) & 0x01) ^
  20434. ((c >> 7) & 0x01)) == (c & 0x01)) {
  20435. WOLFSSL_MSG("Flipping parity bit");
  20436. (*myDes)[i] = c ^ 0x01;
  20437. }
  20438. }
  20439. }
  20440. int wolfSSL_DES_check_key_parity(WOLFSSL_DES_cblock *myDes)
  20441. {
  20442. word32 i;
  20443. word32 sz = sizeof(WOLFSSL_DES_cblock);
  20444. WOLFSSL_ENTER("wolfSSL_DES_check_key_parity");
  20445. for (i = 0; i < sz; i++) {
  20446. unsigned char c = (*myDes)[i];
  20447. if ((
  20448. ((c >> 1) & 0x01) ^
  20449. ((c >> 2) & 0x01) ^
  20450. ((c >> 3) & 0x01) ^
  20451. ((c >> 4) & 0x01) ^
  20452. ((c >> 5) & 0x01) ^
  20453. ((c >> 6) & 0x01) ^
  20454. ((c >> 7) & 0x01)) == (c & 0x01)) {
  20455. return 0;
  20456. }
  20457. }
  20458. return 1;
  20459. }
  20460. #ifdef WOLFSSL_DES_ECB
  20461. /* Encrypt or decrypt input message desa with key and get output in desb.
  20462. * if enc is DES_ENCRYPT,input message is encrypted or
  20463. * if enc is DES_DECRYPT,input message is decrypted.
  20464. * */
  20465. void wolfSSL_DES_ecb_encrypt(WOLFSSL_DES_cblock* desa,
  20466. WOLFSSL_DES_cblock* desb, WOLFSSL_DES_key_schedule* key, int enc)
  20467. {
  20468. Des myDes;
  20469. WOLFSSL_ENTER("wolfSSL_DES_ecb_encrypt");
  20470. if (desa == NULL || key == NULL || desb == NULL ||
  20471. (enc != DES_ENCRYPT && enc != DES_DECRYPT)) {
  20472. WOLFSSL_MSG("Bad argument passed to wolfSSL_DES_ecb_encrypt");
  20473. } else {
  20474. if (wc_Des_SetKey(&myDes, (const byte*) key,
  20475. (const byte*) NULL, !enc) != 0) {
  20476. WOLFSSL_MSG("wc_Des_SetKey return error.");
  20477. return;
  20478. }
  20479. if (enc == DES_ENCRYPT){
  20480. if (wc_Des_EcbEncrypt(&myDes, (byte*) desb, (const byte*) desa,
  20481. sizeof(WOLFSSL_DES_cblock)) != 0){
  20482. WOLFSSL_MSG("wc_Des_EcbEncrypt return error.");
  20483. }
  20484. } else {
  20485. if (wc_Des_EcbDecrypt(&myDes, (byte*) desb, (const byte*) desa,
  20486. sizeof(WOLFSSL_DES_cblock)) != 0){
  20487. WOLFSSL_MSG("wc_Des_EcbDecrpyt return error.");
  20488. }
  20489. }
  20490. }
  20491. }
  20492. #endif
  20493. #endif /* NO_DES3 */
  20494. #ifndef NO_RC4
  20495. /* Set the key state for Arc4 structure.
  20496. *
  20497. * key Arc4 structure to use
  20498. * len length of data buffer
  20499. * data initial state to set Arc4 structure
  20500. */
  20501. void wolfSSL_RC4_set_key(WOLFSSL_RC4_KEY* key, int len,
  20502. const unsigned char* data)
  20503. {
  20504. typedef char rc4_test[sizeof(WOLFSSL_RC4_KEY) >= sizeof(Arc4) ? 1 : -1];
  20505. (void)sizeof(rc4_test);
  20506. WOLFSSL_ENTER("wolfSSL_RC4_set_key");
  20507. if (key == NULL || len < 0) {
  20508. WOLFSSL_MSG("bad argument passed in");
  20509. return;
  20510. }
  20511. XMEMSET(key, 0, sizeof(WOLFSSL_RC4_KEY));
  20512. wc_Arc4SetKey((Arc4*)key, data, (word32)len);
  20513. }
  20514. /* Encrypt/decrypt with Arc4 structure.
  20515. *
  20516. * len length of buffer to encrypt/decrypt (in/out)
  20517. * in buffer to encrypt/decrypt
  20518. * out results of encryption/decryption
  20519. */
  20520. void wolfSSL_RC4(WOLFSSL_RC4_KEY* key, size_t len,
  20521. const unsigned char* in, unsigned char* out)
  20522. {
  20523. WOLFSSL_ENTER("wolfSSL_RC4");
  20524. if (key == NULL || in == NULL || out == NULL) {
  20525. WOLFSSL_MSG("Bad argument passed in");
  20526. return;
  20527. }
  20528. wc_Arc4Process((Arc4*)key, out, in, (word32)len);
  20529. }
  20530. #endif /* NO_RC4 */
  20531. #ifndef NO_AES
  20532. #ifdef WOLFSSL_AES_DIRECT
  20533. /* AES encrypt direct, it is expected to be blocks of AES_BLOCK_SIZE for input.
  20534. *
  20535. * input Data to encrypt
  20536. * output Encrypted data after done
  20537. * key AES key to use for encryption
  20538. */
  20539. void wolfSSL_AES_encrypt(const unsigned char* input, unsigned char* output,
  20540. AES_KEY *key)
  20541. {
  20542. WOLFSSL_ENTER("wolfSSL_AES_encrypt");
  20543. if (input == NULL || output == NULL || key == NULL) {
  20544. WOLFSSL_MSG("Null argument passed in");
  20545. return;
  20546. }
  20547. #if !defined(HAVE_SELFTEST) && \
  20548. (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
  20549. if (wc_AesEncryptDirect((Aes*)key, output, input) != 0) {
  20550. WOLFSSL_MSG("wc_AesEncryptDirect failed");
  20551. return;
  20552. }
  20553. #else
  20554. wc_AesEncryptDirect((Aes*)key, output, input);
  20555. #endif
  20556. }
  20557. /* AES decrypt direct, it is expected to be blocks of AES_BLOCK_SIZE for input.
  20558. *
  20559. * input Data to decrypt
  20560. * output Decrypted data after done
  20561. * key AES key to use for encryption
  20562. */
  20563. void wolfSSL_AES_decrypt(const unsigned char* input, unsigned char* output,
  20564. AES_KEY *key)
  20565. {
  20566. WOLFSSL_ENTER("wolfSSL_AES_decrypt");
  20567. if (input == NULL || output == NULL || key == NULL) {
  20568. WOLFSSL_MSG("Null argument passed in");
  20569. return;
  20570. }
  20571. #if !defined(HAVE_SELFTEST) && \
  20572. (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
  20573. if (wc_AesDecryptDirect((Aes*)key, output, input) != 0) {
  20574. WOLFSSL_MSG("wc_AesDecryptDirect failed");
  20575. return;
  20576. }
  20577. #else
  20578. wc_AesDecryptDirect((Aes*)key, output, input);
  20579. #endif
  20580. }
  20581. #endif /* WOLFSSL_AES_DIRECT */
  20582. /* Setup of an AES key to use for encryption.
  20583. *
  20584. * key key in bytes to use for encryption
  20585. * bits size of key in bits
  20586. * aes AES structure to initialize
  20587. */
  20588. int wolfSSL_AES_set_encrypt_key(const unsigned char *key, const int bits,
  20589. AES_KEY *aes)
  20590. {
  20591. typedef char aes_test[sizeof(AES_KEY) >= sizeof(Aes) ? 1 : -1];
  20592. (void)sizeof(aes_test);
  20593. WOLFSSL_ENTER("wolfSSL_AES_set_encrypt_key");
  20594. if (key == NULL || aes == NULL) {
  20595. WOLFSSL_MSG("Null argument passed in");
  20596. return -1;
  20597. }
  20598. XMEMSET(aes, 0, sizeof(AES_KEY));
  20599. if (wc_AesSetKey((Aes*)aes, key, ((bits)/8), NULL, AES_ENCRYPT) != 0) {
  20600. WOLFSSL_MSG("Error in setting AES key");
  20601. return -1;
  20602. }
  20603. return 0;
  20604. }
  20605. /* Setup of an AES key to use for decryption.
  20606. *
  20607. * key key in bytes to use for decryption
  20608. * bits size of key in bits
  20609. * aes AES structure to initialize
  20610. */
  20611. int wolfSSL_AES_set_decrypt_key(const unsigned char *key, const int bits,
  20612. AES_KEY *aes)
  20613. {
  20614. typedef char aes_test[sizeof(AES_KEY) >= sizeof(Aes) ? 1 : -1];
  20615. (void)sizeof(aes_test);
  20616. WOLFSSL_ENTER("wolfSSL_AES_set_decrypt_key");
  20617. if (key == NULL || aes == NULL) {
  20618. WOLFSSL_MSG("Null argument passed in");
  20619. return -1;
  20620. }
  20621. XMEMSET(aes, 0, sizeof(AES_KEY));
  20622. if (wc_AesSetKey((Aes*)aes, key, ((bits)/8), NULL, AES_DECRYPT) != 0) {
  20623. WOLFSSL_MSG("Error in setting AES key");
  20624. return -1;
  20625. }
  20626. return 0;
  20627. }
  20628. #ifdef HAVE_AES_ECB
  20629. /* Encrypt/decrypt a 16 byte block of data using the key passed in.
  20630. *
  20631. * in buffer to encrypt/decrypt
  20632. * out buffer to hold result of encryption/decryption
  20633. * key AES structure to use with encryption/decryption
  20634. * enc AES_ENCRPT for encryption and AES_DECRYPT for decryption
  20635. */
  20636. void wolfSSL_AES_ecb_encrypt(const unsigned char *in, unsigned char* out,
  20637. AES_KEY *key, const int enc)
  20638. {
  20639. Aes* aes;
  20640. WOLFSSL_ENTER("wolfSSL_AES_ecb_encrypt");
  20641. if (key == NULL || in == NULL || out == NULL) {
  20642. WOLFSSL_MSG("Error, Null argument passed in");
  20643. return;
  20644. }
  20645. aes = (Aes*)key;
  20646. if (enc == AES_ENCRYPT) {
  20647. if (wc_AesEcbEncrypt(aes, out, in, AES_BLOCK_SIZE) != 0) {
  20648. WOLFSSL_MSG("Error with AES CBC encrypt");
  20649. }
  20650. }
  20651. else {
  20652. #ifdef HAVE_AES_DECRYPT
  20653. if (wc_AesEcbDecrypt(aes, out, in, AES_BLOCK_SIZE) != 0) {
  20654. WOLFSSL_MSG("Error with AES CBC decrypt");
  20655. }
  20656. #else
  20657. WOLFSSL_MSG("AES decryption not compiled in");
  20658. #endif
  20659. }
  20660. }
  20661. #endif /* HAVE_AES_ECB */
  20662. #ifdef HAVE_AES_CBC
  20663. /* Encrypt data using key and iv passed in. iv gets updated to most recent iv
  20664. * state after encryption/decryption.
  20665. *
  20666. * in buffer to encrypt/decrypt
  20667. * out buffer to hold result of encryption/decryption
  20668. * len length of input buffer
  20669. * key AES structure to use with encryption/decryption
  20670. * iv iv to use with operation
  20671. * enc 1 for encryption and 0 for decryption
  20672. */
  20673. void wolfSSL_AES_cbc_encrypt(const unsigned char *in, unsigned char* out,
  20674. size_t len, AES_KEY *key, unsigned char* iv, const int enc)
  20675. {
  20676. Aes* aes;
  20677. WOLFSSL_ENTER("wolfSSL_AES_cbc_encrypt");
  20678. if (key == NULL || in == NULL || out == NULL || iv == NULL || len == 0) {
  20679. WOLFSSL_MSG("Error, Null argument passed in");
  20680. return;
  20681. }
  20682. aes = (Aes*)key;
  20683. if (wc_AesSetIV(aes, (const byte*)iv) != 0) {
  20684. WOLFSSL_MSG("Error with setting iv");
  20685. return;
  20686. }
  20687. if (enc == AES_ENCRYPT) {
  20688. if (wc_AesCbcEncrypt(aes, out, in, (word32)len) != 0) {
  20689. WOLFSSL_MSG("Error with AES CBC encrypt");
  20690. return;
  20691. }
  20692. }
  20693. else {
  20694. if (wc_AesCbcDecrypt(aes, out, in, (word32)len) != 0) {
  20695. WOLFSSL_MSG("Error with AES CBC decrypt");
  20696. return;
  20697. }
  20698. }
  20699. /* to be compatible copy iv to iv buffer after completing operation */
  20700. XMEMCPY(iv, (byte*)(aes->reg), AES_BLOCK_SIZE);
  20701. }
  20702. #endif /* HAVE_AES_CBC */
  20703. /* Encrypt data using CFB mode with key and iv passed in. iv gets updated to
  20704. * most recent iv state after encryption/decryption.
  20705. *
  20706. * in buffer to encrypt/decrypt
  20707. * out buffer to hold result of encryption/decryption
  20708. * len length of input buffer
  20709. * key AES structure to use with encryption/decryption
  20710. * iv iv to use with operation
  20711. * num contains the amount of block used
  20712. * enc AES_ENCRYPT for encryption and AES_DECRYPT for decryption
  20713. */
  20714. void wolfSSL_AES_cfb128_encrypt(const unsigned char *in, unsigned char* out,
  20715. size_t len, AES_KEY *key, unsigned char* iv, int* num,
  20716. const int enc)
  20717. {
  20718. #ifndef WOLFSSL_AES_CFB
  20719. WOLFSSL_MSG("CFB mode not enabled please use macro WOLFSSL_AES_CFB");
  20720. (void)in;
  20721. (void)out;
  20722. (void)len;
  20723. (void)key;
  20724. (void)iv;
  20725. (void)num;
  20726. (void)enc;
  20727. return;
  20728. #else
  20729. Aes* aes;
  20730. WOLFSSL_ENTER("wolfSSL_AES_cbc_encrypt");
  20731. if (key == NULL || in == NULL || out == NULL || iv == NULL) {
  20732. WOLFSSL_MSG("Error, Null argument passed in");
  20733. return;
  20734. }
  20735. aes = (Aes*)key;
  20736. /*
  20737. * We copy the IV directly into reg here because using wc_AesSetIV will
  20738. * clear the leftover bytes field "left", and this function relies on the
  20739. * leftover bytes being preserved between calls.
  20740. */
  20741. XMEMCPY(aes->reg, iv, AES_BLOCK_SIZE);
  20742. if (enc == AES_ENCRYPT) {
  20743. if (wc_AesCfbEncrypt(aes, out, in, (word32)len) != 0) {
  20744. WOLFSSL_MSG("Error with AES CBC encrypt");
  20745. return;
  20746. }
  20747. }
  20748. else {
  20749. if (wc_AesCfbDecrypt(aes, out, in, (word32)len) != 0) {
  20750. WOLFSSL_MSG("Error with AES CBC decrypt");
  20751. return;
  20752. }
  20753. }
  20754. /* to be compatible copy iv to iv buffer after completing operation */
  20755. XMEMCPY(iv, (byte*)(aes->reg), AES_BLOCK_SIZE);
  20756. /* store number of left over bytes to num */
  20757. *num = (aes->left)? AES_BLOCK_SIZE - aes->left : 0;
  20758. #endif /* WOLFSSL_AES_CFB */
  20759. }
  20760. /* wc_AesKey*Wrap_ex API not available in FIPS and SELFTEST */
  20761. #if defined(HAVE_AES_KEYWRAP) && !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  20762. int wolfSSL_AES_wrap_key(AES_KEY *key, const unsigned char *iv,
  20763. unsigned char *out,
  20764. const unsigned char *in, unsigned int inlen)
  20765. {
  20766. int ret;
  20767. WOLFSSL_ENTER("wolfSSL_AES_wrap_key");
  20768. if (out == NULL || in == NULL) {
  20769. WOLFSSL_MSG("Error, Null argument passed in");
  20770. return WOLFSSL_FAILURE;
  20771. }
  20772. ret = wc_AesKeyWrap_ex((Aes*)key, in, inlen, out, inlen + KEYWRAP_BLOCK_SIZE, iv);
  20773. return ret < 0 ? WOLFSSL_FAILURE : ret;
  20774. }
  20775. int wolfSSL_AES_unwrap_key(AES_KEY *key, const unsigned char *iv,
  20776. unsigned char *out,
  20777. const unsigned char *in, unsigned int inlen)
  20778. {
  20779. int ret;
  20780. WOLFSSL_ENTER("wolfSSL_AES_wrap_key");
  20781. if (out == NULL || in == NULL) {
  20782. WOLFSSL_MSG("Error, Null argument passed in");
  20783. return WOLFSSL_FAILURE;
  20784. }
  20785. ret = wc_AesKeyUnWrap_ex((Aes*)key, in, inlen, out, inlen + KEYWRAP_BLOCK_SIZE, iv);
  20786. return ret < 0 ? WOLFSSL_FAILURE : ret;
  20787. }
  20788. #endif /* HAVE_AES_KEYWRAP && !HAVE_FIPS && !HAVE_SELFTEST */
  20789. #ifdef HAVE_CTS
  20790. /*
  20791. * Ciphertext stealing interface compatible with RFC2040 and RFC3962.
  20792. */
  20793. size_t wolfSSL_CRYPTO_cts128_encrypt(const unsigned char *in,
  20794. unsigned char *out, size_t len, const void *key,
  20795. unsigned char *iv, WOLFSSL_CBC128_CB cbc)
  20796. {
  20797. byte lastBlk[WOLFSSL_CTS128_BLOCK_SZ];
  20798. int lastBlkLen = len % WOLFSSL_CTS128_BLOCK_SZ;
  20799. WOLFSSL_ENTER("wolfSSL_CRYPTO_cts128_encrypt");
  20800. if (in == NULL || out == NULL || len < WOLFSSL_CTS128_BLOCK_SZ ||
  20801. cbc == NULL) {
  20802. WOLFSSL_MSG("Bad parameter");
  20803. return WOLFSSL_FAILURE;
  20804. }
  20805. if (lastBlkLen == 0)
  20806. lastBlkLen = WOLFSSL_CTS128_BLOCK_SZ;
  20807. /* Encrypt data up to last block */
  20808. (*cbc)(in, out, len - lastBlkLen, key, iv, AES_ENCRYPT);
  20809. /* Move to last block */
  20810. in += len - lastBlkLen;
  20811. out += len - lastBlkLen;
  20812. /* RFC2040: Pad Pn with zeros at the end to create P of length BB. */
  20813. XMEMCPY(lastBlk, in, lastBlkLen);
  20814. XMEMSET(lastBlk + lastBlkLen, 0, WOLFSSL_CTS128_BLOCK_SZ - lastBlkLen);
  20815. /* RFC2040: Select the first Ln bytes of En-1 to create Cn */
  20816. XMEMCPY(out, out - WOLFSSL_CTS128_BLOCK_SZ, lastBlkLen);
  20817. (*cbc)(lastBlk, out - WOLFSSL_CTS128_BLOCK_SZ, WOLFSSL_CTS128_BLOCK_SZ,
  20818. key, iv, AES_ENCRYPT);
  20819. return len;
  20820. }
  20821. size_t wolfSSL_CRYPTO_cts128_decrypt(const unsigned char *in,
  20822. unsigned char *out, size_t len, const void *key,
  20823. unsigned char *iv, WOLFSSL_CBC128_CB cbc)
  20824. {
  20825. byte lastBlk[WOLFSSL_CTS128_BLOCK_SZ];
  20826. byte prevBlk[WOLFSSL_CTS128_BLOCK_SZ];
  20827. int lastBlkLen = len % WOLFSSL_CTS128_BLOCK_SZ;
  20828. WOLFSSL_ENTER("wolfSSL_CRYPTO_cts128_decrypt");
  20829. if (in == NULL || out == NULL || len <= WOLFSSL_CTS128_BLOCK_SZ ||
  20830. cbc == NULL) {
  20831. WOLFSSL_MSG("Bad parameter");
  20832. return WOLFSSL_FAILURE;
  20833. }
  20834. if (lastBlkLen == 0)
  20835. lastBlkLen = WOLFSSL_CTS128_BLOCK_SZ;
  20836. /* Decrypt up to last two blocks */
  20837. (*cbc)(in, out, len - lastBlkLen - WOLFSSL_CTS128_BLOCK_SZ, key, iv,
  20838. AES_DECRYPTION);
  20839. /* Move to last two blocks */
  20840. in += len - lastBlkLen - WOLFSSL_CTS128_BLOCK_SZ;
  20841. out += len - lastBlkLen - WOLFSSL_CTS128_BLOCK_SZ;
  20842. /* RFC2040: Decrypt Cn-1 to create Dn.
  20843. * Use 0 buffer as IV to do straight decryption.
  20844. * This places the Cn-1 block at lastBlk */
  20845. XMEMSET(lastBlk, 0, WOLFSSL_CTS128_BLOCK_SZ);
  20846. (*cbc)(in, prevBlk, WOLFSSL_CTS128_BLOCK_SZ, key, lastBlk, AES_DECRYPT);
  20847. /* RFC2040: Append the tail (BB minus Ln) bytes of Xn to Cn
  20848. * to create En. */
  20849. XMEMCPY(prevBlk, in + WOLFSSL_CTS128_BLOCK_SZ, lastBlkLen);
  20850. /* Cn and Cn-1 can now be decrypted */
  20851. (*cbc)(prevBlk, out, WOLFSSL_CTS128_BLOCK_SZ, key, iv, AES_DECRYPT);
  20852. (*cbc)(lastBlk, lastBlk, WOLFSSL_CTS128_BLOCK_SZ, key, iv, AES_DECRYPT);
  20853. XMEMCPY(out + WOLFSSL_CTS128_BLOCK_SZ, lastBlk, lastBlkLen);
  20854. return len;
  20855. }
  20856. #endif /* HAVE_CTS */
  20857. #endif /* NO_AES */
  20858. #ifndef NO_ASN_TIME
  20859. #ifndef NO_BIO
  20860. int wolfSSL_ASN1_UTCTIME_print(WOLFSSL_BIO* bio, const WOLFSSL_ASN1_UTCTIME* a)
  20861. {
  20862. WOLFSSL_ENTER("ASN1_UTCTIME_print");
  20863. if (bio == NULL || a == NULL) {
  20864. return WOLFSSL_FAILURE;
  20865. }
  20866. if (a->type != ASN_UTC_TIME) {
  20867. WOLFSSL_MSG("Error, not UTC_TIME");
  20868. return WOLFSSL_FAILURE;
  20869. }
  20870. return wolfSSL_ASN1_TIME_print(bio, a);
  20871. }
  20872. #endif /* !NO_BIO */
  20873. /* Checks the ASN1 syntax of "a"
  20874. * returns WOLFSSL_SUCCESS (1) if correct otherwise WOLFSSL_FAILURE (0) */
  20875. int wolfSSL_ASN1_TIME_check(const WOLFSSL_ASN1_TIME* a)
  20876. {
  20877. char buf[MAX_TIME_STRING_SZ];
  20878. WOLFSSL_ENTER("wolfSSL_ASN1_TIME_check");
  20879. /* if can parse the WOLFSSL_ASN1_TIME passed in then consider syntax good */
  20880. if (wolfSSL_ASN1_TIME_to_string((WOLFSSL_ASN1_TIME*)a, buf,
  20881. MAX_TIME_STRING_SZ) == NULL) {
  20882. return WOLFSSL_FAILURE;
  20883. }
  20884. return WOLFSSL_SUCCESS;
  20885. }
  20886. /*
  20887. * Convert time to Unix time (GMT).
  20888. */
  20889. static long long TimeToUnixTime(int sec, int min, int hour, int mday, int mon,
  20890. int year)
  20891. {
  20892. /* Number of cumulative days from the previous months, starting from
  20893. * beginning of January. */
  20894. static const int monthDaysCumulative [12] = {
  20895. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  20896. };
  20897. int leapDays = year;
  20898. if (mon <= 1) {
  20899. --leapDays;
  20900. }
  20901. leapDays = leapDays / 4 - leapDays / 100 + leapDays / 400 - 1969 / 4 +
  20902. 1969 / 100 - 1969 / 400;
  20903. return ((((long long) (year - 1970) * 365 + leapDays +
  20904. monthDaysCumulative[mon] + mday - 1) * 24 + hour) * 60 + min) * 60 +
  20905. sec;
  20906. }
  20907. int wolfSSL_ASN1_TIME_diff(int *days, int *secs, const WOLFSSL_ASN1_TIME *from,
  20908. const WOLFSSL_ASN1_TIME *to)
  20909. {
  20910. const int SECS_PER_DAY = 24 * 60 * 60;
  20911. struct tm fromTm_s, *fromTmGmt = &fromTm_s;
  20912. struct tm toTm_s, *toTmGmt = &toTm_s;
  20913. time_t currTime;
  20914. long long fromSecs;
  20915. long long toSecs;
  20916. double diffSecs;
  20917. struct tm *tmpTs;
  20918. #if defined(NEED_TMP_TIME)
  20919. /* for use with gmtime_r */
  20920. struct tm tmpTimeStorage;
  20921. tmpTs = &tmpTimeStorage;
  20922. #else
  20923. tmpTs = NULL;
  20924. #endif
  20925. (void)tmpTs;
  20926. WOLFSSL_ENTER("wolfSSL_ASN1_TIME_diff");
  20927. if (days == NULL) {
  20928. WOLFSSL_MSG("days is NULL");
  20929. return WOLFSSL_FAILURE;
  20930. }
  20931. if (secs == NULL) {
  20932. WOLFSSL_MSG("secs is NULL");
  20933. return WOLFSSL_FAILURE;
  20934. }
  20935. if (from == NULL && to == NULL) {
  20936. *days = 0;
  20937. *secs = 0;
  20938. return WOLFSSL_SUCCESS;
  20939. }
  20940. if (from == NULL) {
  20941. currTime = wc_Time(0);
  20942. fromTmGmt = XGMTIME(&currTime, tmpTs);
  20943. if (fromTmGmt == NULL) {
  20944. WOLFSSL_MSG("XGMTIME for from time failed.");
  20945. return WOLFSSL_FAILURE;
  20946. }
  20947. }
  20948. else if (wolfSSL_ASN1_TIME_to_tm(from, fromTmGmt) != WOLFSSL_SUCCESS) {
  20949. WOLFSSL_MSG("Failed to convert from time to struct tm.");
  20950. return WOLFSSL_FAILURE;
  20951. }
  20952. /* We use TimeToUnixTime here instead of XMKTIME to avoid the Year 2038
  20953. * Problem on platforms where time_t is 32 bits. struct tm stores the year
  20954. * as years since 1900, so we add 1900 to the year. */
  20955. fromSecs = TimeToUnixTime(fromTmGmt->tm_sec, fromTmGmt->tm_min,
  20956. fromTmGmt->tm_hour, fromTmGmt->tm_mday,
  20957. fromTmGmt->tm_mon, fromTmGmt->tm_year + 1900);
  20958. if (to == NULL) {
  20959. currTime = wc_Time(0);
  20960. toTmGmt = XGMTIME(&currTime, tmpTs);
  20961. if (toTmGmt == NULL) {
  20962. WOLFSSL_MSG("XGMTIME for to time failed.");
  20963. return WOLFSSL_FAILURE;
  20964. }
  20965. }
  20966. else if (wolfSSL_ASN1_TIME_to_tm(to, toTmGmt) != WOLFSSL_SUCCESS) {
  20967. WOLFSSL_MSG("Failed to convert to time to struct tm.");
  20968. return WOLFSSL_FAILURE;
  20969. }
  20970. toSecs = TimeToUnixTime(toTmGmt->tm_sec, toTmGmt->tm_min, toTmGmt->tm_hour,
  20971. toTmGmt->tm_mday, toTmGmt->tm_mon,
  20972. toTmGmt->tm_year + 1900);
  20973. diffSecs = (double)(toSecs - fromSecs);
  20974. *days = (int) (diffSecs / SECS_PER_DAY);
  20975. *secs = (int) (diffSecs - (((double)*days) * SECS_PER_DAY));
  20976. return WOLFSSL_SUCCESS;
  20977. }
  20978. int wolfSSL_ASN1_TIME_compare(const WOLFSSL_ASN1_TIME *a,
  20979. const WOLFSSL_ASN1_TIME *b)
  20980. {
  20981. int ret;
  20982. int days;
  20983. int secs;
  20984. WOLFSSL_ENTER("wolfSSL_ASN1_TIME_compare");
  20985. if (wolfSSL_ASN1_TIME_diff(&days, &secs, a, b) != WOLFSSL_SUCCESS) {
  20986. WOLFSSL_MSG("Failed to get time difference.");
  20987. ret = -2;
  20988. }
  20989. else {
  20990. if (days == 0 && secs == 0) {
  20991. /* a and b are the same time. */
  20992. ret = 0;
  20993. }
  20994. else if (days >= 0 && secs >= 0) {
  20995. /* a is before b. */
  20996. ret = -1;
  20997. }
  20998. else if (days <= 0 && secs <= 0) {
  20999. /* a is after b. */
  21000. ret = 1;
  21001. }
  21002. else {
  21003. WOLFSSL_MSG("Incoherent time difference.");
  21004. ret = -2;
  21005. }
  21006. }
  21007. WOLFSSL_LEAVE("wolfSSL_ASN1_TIME_compare", ret);
  21008. return ret;
  21009. }
  21010. #endif /* !NO_ASN_TIME */
  21011. #ifndef NO_WOLFSSL_STUB
  21012. WOLFSSL_ASN1_TIME *wolfSSL_ASN1_TIME_set(WOLFSSL_ASN1_TIME *s, time_t t)
  21013. {
  21014. WOLFSSL_STUB("wolfSSL_ASN1_TIME_set");
  21015. (void)s;
  21016. (void)t;
  21017. return s;
  21018. }
  21019. #endif /* !NO_WOLFSSL_STUB */
  21020. int wolfSSL_ASN1_TIME_set_string(WOLFSSL_ASN1_TIME *s, const char *str)
  21021. {
  21022. int slen;
  21023. WOLFSSL_ENTER("wolfSSL_ASN1_TIME_set_string");
  21024. if (!str) {
  21025. WOLFSSL_MSG("Bad parameter");
  21026. return WOLFSSL_FAILURE;
  21027. }
  21028. slen = (int)XSTRLEN(str)+1;
  21029. if (slen > CTC_DATE_SIZE) {
  21030. WOLFSSL_MSG("Date string too long");
  21031. return WOLFSSL_FAILURE;
  21032. }
  21033. if (s) {
  21034. XMEMCPY(s->data, str, slen);
  21035. s->length = slen - 1; /* do not include null terminator in length */
  21036. s->type = slen == ASN_UTC_TIME_SIZE ? V_ASN1_UTCTIME :
  21037. V_ASN1_GENERALIZEDTIME;
  21038. }
  21039. return WOLFSSL_SUCCESS;
  21040. }
  21041. #ifndef NO_BIO
  21042. /* Return the month as a string.
  21043. *
  21044. * n The number of the month as a two characters (1 based).
  21045. * returns the month as a string.
  21046. */
  21047. static WC_INLINE const char* MonthStr(const char* n)
  21048. {
  21049. static const char monthStr[12][4] = {
  21050. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  21051. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  21052. return monthStr[(n[0] - '0') * 10 + (n[1] - '0') - 1];
  21053. }
  21054. int wolfSSL_ASN1_GENERALIZEDTIME_print(WOLFSSL_BIO* bio,
  21055. const WOLFSSL_ASN1_GENERALIZEDTIME* asnTime)
  21056. {
  21057. const char* p;
  21058. WOLFSSL_ENTER("wolfSSL_ASN1_GENERALIZEDTIME_print");
  21059. if (bio == NULL || asnTime == NULL)
  21060. return BAD_FUNC_ARG;
  21061. if (asnTime->type != ASN_GENERALIZED_TIME) {
  21062. WOLFSSL_MSG("Error, not GENERALIZED_TIME");
  21063. return WOLFSSL_FAILURE;
  21064. }
  21065. p = (const char *)(asnTime->data);
  21066. /* GetTimeString not always available. */
  21067. if (wolfSSL_BIO_write(bio, MonthStr(p + 4), 3) <= 0)
  21068. return WOLFSSL_FAILURE;
  21069. if (wolfSSL_BIO_write(bio, " ", 1) <= 0)
  21070. return WOLFSSL_FAILURE;
  21071. /* Day */
  21072. if (wolfSSL_BIO_write(bio, p + 6, 2) <= 0)
  21073. return WOLFSSL_FAILURE;
  21074. if (wolfSSL_BIO_write(bio, " ", 1) <= 0)
  21075. return WOLFSSL_FAILURE;
  21076. /* Hour */
  21077. if (wolfSSL_BIO_write(bio, p + 8, 2) <= 0)
  21078. return WOLFSSL_FAILURE;
  21079. if (wolfSSL_BIO_write(bio, ":", 1) <= 0)
  21080. return WOLFSSL_FAILURE;
  21081. /* Min */
  21082. if (wolfSSL_BIO_write(bio, p + 10, 2) <= 0)
  21083. return WOLFSSL_FAILURE;
  21084. if (wolfSSL_BIO_write(bio, ":", 1) <= 0)
  21085. return WOLFSSL_FAILURE;
  21086. /* Secs */
  21087. if (wolfSSL_BIO_write(bio, p + 12, 2) <= 0)
  21088. return WOLFSSL_FAILURE;
  21089. if (wolfSSL_BIO_write(bio, " ", 1) <= 0)
  21090. return WOLFSSL_FAILURE;
  21091. if (wolfSSL_BIO_write(bio, p, 4) <= 0)
  21092. return WOLFSSL_FAILURE;
  21093. return 0;
  21094. }
  21095. #endif /* !NO_BIO */
  21096. void wolfSSL_ASN1_GENERALIZEDTIME_free(WOLFSSL_ASN1_TIME* asn1Time)
  21097. {
  21098. WOLFSSL_ENTER("wolfSSL_ASN1_GENERALIZEDTIME_free");
  21099. if (asn1Time == NULL)
  21100. return;
  21101. XMEMSET(asn1Time->data, 0, sizeof(asn1Time->data));
  21102. }
  21103. #endif /* OPENSSL_EXTRA */
  21104. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  21105. int wolfSSL_sk_num(const WOLFSSL_STACK* sk)
  21106. {
  21107. WOLFSSL_ENTER("wolfSSL_sk_num");
  21108. if (sk == NULL)
  21109. return 0;
  21110. return (int)sk->num;
  21111. }
  21112. void* wolfSSL_sk_value(const WOLFSSL_STACK* sk, int i)
  21113. {
  21114. WOLFSSL_ENTER("wolfSSL_sk_value");
  21115. for (; sk != NULL && i > 0; i--)
  21116. sk = sk->next;
  21117. if (sk == NULL)
  21118. return NULL;
  21119. switch (sk->type) {
  21120. case STACK_TYPE_X509:
  21121. return (void*)sk->data.x509;
  21122. case STACK_TYPE_GEN_NAME:
  21123. return (void*)sk->data.gn;
  21124. case STACK_TYPE_BIO:
  21125. return (void*)sk->data.bio;
  21126. case STACK_TYPE_OBJ:
  21127. return (void*)sk->data.obj;
  21128. case STACK_TYPE_STRING:
  21129. return (void*)sk->data.string;
  21130. case STACK_TYPE_CIPHER:
  21131. return (void*)&sk->data.cipher;
  21132. case STACK_TYPE_ACCESS_DESCRIPTION:
  21133. return (void*)sk->data.access;
  21134. case STACK_TYPE_X509_EXT:
  21135. return (void*)sk->data.ext;
  21136. case STACK_TYPE_X509_REQ_ATTR:
  21137. return (void*)sk->data.generic;
  21138. case STACK_TYPE_NULL:
  21139. return (void*)sk->data.generic;
  21140. case STACK_TYPE_X509_NAME:
  21141. return (void*)sk->data.name;
  21142. case STACK_TYPE_X509_NAME_ENTRY:
  21143. return (void*)sk->data.name_entry;
  21144. case STACK_TYPE_CONF_VALUE:
  21145. #ifdef OPENSSL_EXTRA
  21146. return (void*)sk->data.conf;
  21147. #else
  21148. return NULL;
  21149. #endif
  21150. case STACK_TYPE_X509_INFO:
  21151. return (void*)sk->data.info;
  21152. case STACK_TYPE_BY_DIR_entry:
  21153. return (void*)sk->data.dir_entry;
  21154. case STACK_TYPE_BY_DIR_hash:
  21155. return (void*)sk->data.dir_hash;
  21156. case STACK_TYPE_X509_OBJ:
  21157. return (void*)sk->data.x509_obj;
  21158. case STACK_TYPE_DIST_POINT:
  21159. return (void*)sk->data.dp;
  21160. case STACK_TYPE_X509_CRL:
  21161. return (void*)sk->data.crl;
  21162. default:
  21163. return (void*)sk->data.generic;
  21164. }
  21165. }
  21166. /* copies over data of "in" to "out" */
  21167. static void wolfSSL_CIPHER_copy(WOLFSSL_CIPHER* in, WOLFSSL_CIPHER* out)
  21168. {
  21169. if (in == NULL || out == NULL)
  21170. return;
  21171. *out = *in;
  21172. }
  21173. WOLFSSL_STACK* wolfSSL_sk_dup(WOLFSSL_STACK* sk)
  21174. {
  21175. WOLFSSL_STACK* ret = NULL;
  21176. WOLFSSL_STACK* last = NULL;
  21177. WOLFSSL_ENTER("wolfSSL_sk_dup");
  21178. while (sk) {
  21179. WOLFSSL_STACK* cur = wolfSSL_sk_new_node(sk->heap);
  21180. if (!cur) {
  21181. WOLFSSL_MSG("wolfSSL_sk_new_node error");
  21182. goto error;
  21183. }
  21184. if (!ret) {
  21185. /* Set first node */
  21186. ret = cur;
  21187. }
  21188. if (last) {
  21189. last->next = cur;
  21190. }
  21191. XMEMCPY(cur, sk, sizeof(WOLFSSL_STACK));
  21192. /* We will allocate new memory for this */
  21193. XMEMSET(&cur->data, 0, sizeof(cur->data));
  21194. cur->next = NULL;
  21195. switch (sk->type) {
  21196. case STACK_TYPE_X509:
  21197. if (!sk->data.x509)
  21198. break;
  21199. cur->data.x509 = wolfSSL_X509_dup(sk->data.x509);
  21200. if (!cur->data.x509) {
  21201. WOLFSSL_MSG("wolfSSL_X509_dup error");
  21202. goto error;
  21203. }
  21204. break;
  21205. case STACK_TYPE_CIPHER:
  21206. wolfSSL_CIPHER_copy(&sk->data.cipher, &cur->data.cipher);
  21207. break;
  21208. case STACK_TYPE_GEN_NAME:
  21209. if (!sk->data.gn)
  21210. break;
  21211. cur->data.gn = wolfSSL_GENERAL_NAME_dup(sk->data.gn);
  21212. if (!cur->data.gn) {
  21213. WOLFSSL_MSG("wolfSSL_GENERAL_NAME_new error");
  21214. goto error;
  21215. }
  21216. break;
  21217. case STACK_TYPE_OBJ:
  21218. if (!sk->data.obj)
  21219. break;
  21220. cur->data.obj = wolfSSL_ASN1_OBJECT_dup(sk->data.obj);
  21221. if (!cur->data.obj) {
  21222. WOLFSSL_MSG("wolfSSL_ASN1_OBJECT_dup error");
  21223. goto error;
  21224. }
  21225. break;
  21226. case STACK_TYPE_BIO:
  21227. case STACK_TYPE_STRING:
  21228. case STACK_TYPE_ACCESS_DESCRIPTION:
  21229. case STACK_TYPE_X509_EXT:
  21230. case STACK_TYPE_X509_REQ_ATTR:
  21231. case STACK_TYPE_NULL:
  21232. case STACK_TYPE_X509_NAME:
  21233. case STACK_TYPE_X509_NAME_ENTRY:
  21234. case STACK_TYPE_CONF_VALUE:
  21235. case STACK_TYPE_X509_INFO:
  21236. case STACK_TYPE_BY_DIR_entry:
  21237. case STACK_TYPE_BY_DIR_hash:
  21238. case STACK_TYPE_X509_OBJ:
  21239. case STACK_TYPE_DIST_POINT:
  21240. case STACK_TYPE_X509_CRL:
  21241. default:
  21242. WOLFSSL_MSG("Unsupported stack type");
  21243. goto error;
  21244. }
  21245. sk = sk->next;
  21246. last = cur;
  21247. }
  21248. return ret;
  21249. error:
  21250. if (ret) {
  21251. wolfSSL_sk_GENERAL_NAME_free(ret);
  21252. }
  21253. return NULL;
  21254. }
  21255. /* Free the just the stack structure */
  21256. void wolfSSL_sk_free(WOLFSSL_STACK* sk)
  21257. {
  21258. WOLFSSL_ENTER("wolfSSL_sk_free");
  21259. while (sk != NULL) {
  21260. WOLFSSL_STACK* next = sk->next;
  21261. XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL);
  21262. sk = next;
  21263. }
  21264. }
  21265. /* Frees each node in the stack and frees the stack.
  21266. */
  21267. void wolfSSL_sk_GENERIC_pop_free(WOLFSSL_STACK* sk,
  21268. void (*f) (void*))
  21269. {
  21270. WOLFSSL_ENTER("wolfSSL_sk_GENERIC_pop_free");
  21271. wolfSSL_sk_pop_free(sk, (wolfSSL_sk_freefunc)f);
  21272. }
  21273. /* return 1 on success 0 on fail */
  21274. int wolfSSL_sk_GENERIC_push(WOLFSSL_STACK* sk, void* generic)
  21275. {
  21276. WOLFSSL_ENTER("wolfSSL_sk_GENERIC_push");
  21277. return wolfSSL_sk_push(sk, generic);
  21278. }
  21279. void wolfSSL_sk_GENERIC_free(WOLFSSL_STACK* sk)
  21280. {
  21281. wolfSSL_sk_free(sk);
  21282. }
  21283. /* Free all nodes in a stack including the pushed objects */
  21284. void wolfSSL_sk_pop_free(WOLF_STACK_OF(WOLFSSL_ASN1_OBJECT)* sk,
  21285. wolfSSL_sk_freefunc func)
  21286. {
  21287. WOLFSSL_ENTER("wolfSSL_sk_pop_free");
  21288. if (sk == NULL) {
  21289. /* pop_free can be called with NULL, do not print bad argument */
  21290. return;
  21291. }
  21292. #if defined(WOLFSSL_QT)
  21293. /* In Qt v15.5, it calls OPENSSL_sk_free(xxx, OPENSSL_sk_free).
  21294. * By using OPENSSL_sk_free for free causes access violation.
  21295. * Therefore, switching free func to wolfSSL_ACCESS_DESCRIPTION_free
  21296. * is needed even the func isn't NULL.
  21297. */
  21298. if (sk->type == STACK_TYPE_ACCESS_DESCRIPTION) {
  21299. func = (wolfSSL_sk_freefunc)wolfSSL_ACCESS_DESCRIPTION_free;
  21300. }
  21301. #endif
  21302. if (func == NULL) {
  21303. switch(sk->type) {
  21304. case STACK_TYPE_ACCESS_DESCRIPTION:
  21305. #if defined(OPENSSL_ALL)
  21306. func = (wolfSSL_sk_freefunc)wolfSSL_ACCESS_DESCRIPTION_free;
  21307. #endif
  21308. break;
  21309. case STACK_TYPE_X509:
  21310. func = (wolfSSL_sk_freefunc)wolfSSL_X509_free;
  21311. break;
  21312. case STACK_TYPE_X509_OBJ:
  21313. #ifdef OPENSSL_ALL
  21314. func = (wolfSSL_sk_freefunc)wolfSSL_X509_OBJECT_free;
  21315. #endif
  21316. break;
  21317. case STACK_TYPE_OBJ:
  21318. func = (wolfSSL_sk_freefunc)wolfSSL_ASN1_OBJECT_free;
  21319. break;
  21320. case STACK_TYPE_DIST_POINT:
  21321. #ifdef OPENSSL_EXTRA
  21322. func = (wolfSSL_sk_freefunc)wolfSSL_DIST_POINT_free;
  21323. #endif
  21324. break;
  21325. case STACK_TYPE_GEN_NAME:
  21326. func = (wolfSSL_sk_freefunc)wolfSSL_GENERAL_NAME_free;
  21327. break;
  21328. case STACK_TYPE_STRING:
  21329. #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \
  21330. defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
  21331. func = (wolfSSL_sk_freefunc)wolfSSL_WOLFSSL_STRING_free;
  21332. #endif
  21333. break;
  21334. case STACK_TYPE_X509_NAME:
  21335. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  21336. && !defined(WOLFCRYPT_ONLY)
  21337. func = (wolfSSL_sk_freefunc)wolfSSL_X509_NAME_free;
  21338. #endif
  21339. break;
  21340. case STACK_TYPE_X509_NAME_ENTRY:
  21341. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  21342. && !defined(WOLFCRYPT_ONLY)
  21343. func = (wolfSSL_sk_freefunc)wolfSSL_X509_NAME_ENTRY_free;
  21344. #endif
  21345. break;
  21346. case STACK_TYPE_X509_EXT:
  21347. #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)
  21348. func = (wolfSSL_sk_freefunc)wolfSSL_X509_EXTENSION_free;
  21349. #endif
  21350. break;
  21351. case STACK_TYPE_X509_REQ_ATTR:
  21352. #if defined(OPENSSL_ALL) && \
  21353. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_REQ))
  21354. func = (wolfSSL_sk_freefunc)wolfSSL_X509_ATTRIBUTE_free;
  21355. #endif
  21356. break;
  21357. case STACK_TYPE_CONF_VALUE:
  21358. #if defined(OPENSSL_ALL)
  21359. func = (wolfSSL_sk_freefunc)wolfSSL_X509V3_conf_free;
  21360. #endif
  21361. break;
  21362. case STACK_TYPE_X509_INFO:
  21363. #if defined(OPENSSL_ALL)
  21364. func = (wolfSSL_sk_freefunc)wolfSSL_X509_INFO_free;
  21365. #endif
  21366. break;
  21367. case STACK_TYPE_BIO:
  21368. #if !defined(NO_BIO) && defined(OPENSSL_EXTRA)
  21369. func = (wolfSSL_sk_freefunc)wolfSSL_BIO_vfree;
  21370. #endif
  21371. break;
  21372. case STACK_TYPE_BY_DIR_entry:
  21373. #if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR)
  21374. func = (wolfSSL_sk_freefunc)wolfSSL_BY_DIR_entry_free;
  21375. #endif
  21376. break;
  21377. case STACK_TYPE_BY_DIR_hash:
  21378. #if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR)
  21379. func = (wolfSSL_sk_freefunc)wolfSSL_BY_DIR_HASH_free;
  21380. #endif
  21381. break;
  21382. case STACK_TYPE_X509_CRL:
  21383. #if defined(HAVE_CRL) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL))
  21384. func = (wolfSSL_sk_freefunc)wolfSSL_X509_CRL_free;
  21385. #endif
  21386. break;
  21387. case STACK_TYPE_CIPHER:
  21388. case STACK_TYPE_NULL:
  21389. default:
  21390. break;
  21391. }
  21392. }
  21393. while (sk != NULL) {
  21394. WOLFSSL_STACK* next = sk->next;
  21395. if (func != NULL) {
  21396. if (sk->type != STACK_TYPE_CIPHER)
  21397. func(sk->data.generic);
  21398. }
  21399. XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL);
  21400. sk = next;
  21401. }
  21402. }
  21403. /* Creates and returns a new null stack. */
  21404. WOLFSSL_STACK* wolfSSL_sk_new_null(void)
  21405. {
  21406. WOLFSSL_STACK* sk;
  21407. WOLFSSL_ENTER("wolfSSL_sk_new_null");
  21408. sk = (WOLFSSL_STACK*)XMALLOC(sizeof(WOLFSSL_STACK), NULL,
  21409. DYNAMIC_TYPE_OPENSSL);
  21410. if (sk == NULL) {
  21411. WOLFSSL_MSG("WOLFSSL_STACK memory error");
  21412. return NULL;
  21413. }
  21414. XMEMSET(sk, 0, sizeof(WOLFSSL_STACK));
  21415. sk->type = STACK_TYPE_NULL;
  21416. return sk;
  21417. }
  21418. int wolfSSL_sk_SSL_COMP_num(WOLF_STACK_OF(WOLFSSL_COMP)* sk)
  21419. {
  21420. if (sk == NULL)
  21421. return 0;
  21422. return (int)sk->num;
  21423. }
  21424. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  21425. #if !defined(NO_SESSION_CACHE) && (defined(OPENSSL_EXTRA) || \
  21426. defined(HAVE_EXT_CACHE))
  21427. /* stunnel 4.28 needs
  21428. *
  21429. * Callback that is called if a session tries to resume but could not find
  21430. * the session to resume it.
  21431. */
  21432. void wolfSSL_CTX_sess_set_get_cb(WOLFSSL_CTX* ctx,
  21433. WOLFSSL_SESSION*(*f)(WOLFSSL*, const unsigned char*, int, int*))
  21434. {
  21435. if (ctx == NULL)
  21436. return;
  21437. #ifdef HAVE_EXT_CACHE
  21438. ctx->get_sess_cb = f;
  21439. #else
  21440. (void)f;
  21441. #endif
  21442. }
  21443. void wolfSSL_CTX_sess_set_new_cb(WOLFSSL_CTX* ctx,
  21444. int (*f)(WOLFSSL*, WOLFSSL_SESSION*))
  21445. {
  21446. if (ctx == NULL)
  21447. return;
  21448. #ifdef HAVE_EXT_CACHE
  21449. ctx->new_sess_cb = f;
  21450. #else
  21451. (void)f;
  21452. #endif
  21453. }
  21454. void wolfSSL_CTX_sess_set_remove_cb(WOLFSSL_CTX* ctx, void (*f)(WOLFSSL_CTX*,
  21455. WOLFSSL_SESSION*))
  21456. {
  21457. if (ctx == NULL)
  21458. return;
  21459. #if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA)
  21460. ctx->rem_sess_cb = f;
  21461. #else
  21462. (void)f;
  21463. #endif
  21464. }
  21465. /*
  21466. *
  21467. * Note: It is expected that the importing and exporting function have been
  21468. * built with the same settings. For example if session tickets was
  21469. * enabled with the wolfSSL library exporting a session then it is
  21470. * expected to be turned on with the wolfSSL library importing the session.
  21471. */
  21472. int wolfSSL_i2d_SSL_SESSION(WOLFSSL_SESSION* sess, unsigned char** p)
  21473. {
  21474. int size = 0;
  21475. #ifdef HAVE_EXT_CACHE
  21476. int idx = 0;
  21477. #ifdef SESSION_CERTS
  21478. int i;
  21479. #endif
  21480. unsigned char *data;
  21481. WOLFSSL_ENTER("wolfSSL_i2d_SSL_SESSION");
  21482. sess = ClientSessionToSession(sess);
  21483. if (sess == NULL) {
  21484. return BAD_FUNC_ARG;
  21485. }
  21486. /* side | bornOn | timeout | sessionID len | sessionID | masterSecret |
  21487. * haveEMS */
  21488. size += OPAQUE8_LEN + OPAQUE32_LEN + OPAQUE32_LEN + OPAQUE8_LEN +
  21489. sess->sessionIDSz + SECRET_LEN + OPAQUE8_LEN;
  21490. /* altSessionID */
  21491. size += OPAQUE8_LEN + (sess->haveAltSessionID ? ID_LEN : 0);
  21492. #ifdef SESSION_CERTS
  21493. /* Peer chain */
  21494. size += OPAQUE8_LEN;
  21495. for (i = 0; i < sess->chain.count; i++)
  21496. size += OPAQUE16_LEN + sess->chain.certs[i].length;
  21497. #endif
  21498. #if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \
  21499. defined(HAVE_SESSION_TICKET))
  21500. /* Protocol version */
  21501. size += OPAQUE16_LEN;
  21502. #endif
  21503. #if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \
  21504. (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
  21505. /* cipher suite */
  21506. size += OPAQUE16_LEN;
  21507. #endif
  21508. #ifndef NO_CLIENT_CACHE
  21509. /* ServerID len | ServerID */
  21510. size += OPAQUE16_LEN + sess->idLen;
  21511. #endif
  21512. #ifdef OPENSSL_EXTRA
  21513. /* session context ID len | session context ID */
  21514. size += OPAQUE8_LEN + sess->sessionCtxSz;
  21515. #endif
  21516. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  21517. /* peerVerifyRet */
  21518. size += OPAQUE8_LEN;
  21519. #endif
  21520. #ifdef WOLFSSL_TLS13
  21521. /* namedGroup */
  21522. size += OPAQUE16_LEN;
  21523. #endif
  21524. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  21525. #ifdef WOLFSSL_TLS13
  21526. /* ticketSeen | ticketAdd */
  21527. size += OPAQUE32_LEN + OPAQUE32_LEN;
  21528. /* ticketNonce */
  21529. size += OPAQUE8_LEN + sess->ticketNonce.len;
  21530. #endif
  21531. #ifdef WOLFSSL_EARLY_DATA
  21532. size += OPAQUE32_LEN;
  21533. #endif
  21534. #endif
  21535. #ifdef HAVE_SESSION_TICKET
  21536. /* ticket len | ticket */
  21537. size += OPAQUE16_LEN + sess->ticketLen;
  21538. #endif
  21539. if (p != NULL) {
  21540. if (*p == NULL)
  21541. *p = (unsigned char*)XMALLOC(size, NULL, DYNAMIC_TYPE_OPENSSL);
  21542. if (*p == NULL)
  21543. return 0;
  21544. data = *p;
  21545. data[idx++] = sess->side;
  21546. c32toa(sess->bornOn, data + idx); idx += OPAQUE32_LEN;
  21547. c32toa(sess->timeout, data + idx); idx += OPAQUE32_LEN;
  21548. data[idx++] = sess->sessionIDSz;
  21549. XMEMCPY(data + idx, sess->sessionID, sess->sessionIDSz);
  21550. idx += sess->sessionIDSz;
  21551. XMEMCPY(data + idx, sess->masterSecret, SECRET_LEN); idx += SECRET_LEN;
  21552. data[idx++] = (byte)sess->haveEMS;
  21553. data[idx++] = sess->haveAltSessionID ? ID_LEN : 0;
  21554. if (sess->haveAltSessionID) {
  21555. XMEMCPY(data + idx, sess->altSessionID, ID_LEN);
  21556. idx += ID_LEN;
  21557. }
  21558. #ifdef SESSION_CERTS
  21559. data[idx++] = (byte)sess->chain.count;
  21560. for (i = 0; i < sess->chain.count; i++) {
  21561. c16toa((word16)sess->chain.certs[i].length, data + idx);
  21562. idx += OPAQUE16_LEN;
  21563. XMEMCPY(data + idx, sess->chain.certs[i].buffer,
  21564. sess->chain.certs[i].length);
  21565. idx += sess->chain.certs[i].length;
  21566. }
  21567. #endif
  21568. #if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \
  21569. defined(HAVE_SESSION_TICKET))
  21570. data[idx++] = sess->version.major;
  21571. data[idx++] = sess->version.minor;
  21572. #endif
  21573. #if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \
  21574. (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
  21575. data[idx++] = sess->cipherSuite0;
  21576. data[idx++] = sess->cipherSuite;
  21577. #endif
  21578. #ifndef NO_CLIENT_CACHE
  21579. c16toa(sess->idLen, data + idx); idx += OPAQUE16_LEN;
  21580. XMEMCPY(data + idx, sess->serverID, sess->idLen);
  21581. idx += sess->idLen;
  21582. #endif
  21583. #ifdef OPENSSL_EXTRA
  21584. data[idx++] = sess->sessionCtxSz;
  21585. XMEMCPY(data + idx, sess->sessionCtx, sess->sessionCtxSz);
  21586. idx += sess->sessionCtxSz;
  21587. #endif
  21588. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  21589. data[idx++] = sess->peerVerifyRet;
  21590. #endif
  21591. #ifdef WOLFSSL_TLS13
  21592. c16toa(sess->namedGroup, data + idx);
  21593. idx += OPAQUE16_LEN;
  21594. #endif
  21595. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  21596. #ifdef WOLFSSL_TLS13
  21597. c32toa(sess->ticketSeen, data + idx);
  21598. idx += OPAQUE32_LEN;
  21599. c32toa(sess->ticketAdd, data + idx);
  21600. idx += OPAQUE32_LEN;
  21601. data[idx++] = sess->ticketNonce.len;
  21602. XMEMCPY(data + idx, sess->ticketNonce.data, sess->ticketNonce.len);
  21603. idx += sess->ticketNonce.len;
  21604. #endif
  21605. #ifdef WOLFSSL_EARLY_DATA
  21606. c32toa(sess->maxEarlyDataSz, data + idx);
  21607. idx += OPAQUE32_LEN;
  21608. #endif
  21609. #endif
  21610. #ifdef HAVE_SESSION_TICKET
  21611. c16toa(sess->ticketLen, data + idx); idx += OPAQUE16_LEN;
  21612. XMEMCPY(data + idx, sess->ticket, sess->ticketLen);
  21613. idx += sess->ticketLen;
  21614. #endif
  21615. }
  21616. #endif
  21617. (void)sess;
  21618. (void)p;
  21619. #ifdef HAVE_EXT_CACHE
  21620. (void)idx;
  21621. #endif
  21622. return size;
  21623. }
  21624. /* TODO: no function to free new session.
  21625. *
  21626. * Note: It is expected that the importing and exporting function have been
  21627. * built with the same settings. For example if session tickets was
  21628. * enabled with the wolfSSL library exporting a session then it is
  21629. * expected to be turned on with the wolfSSL library importing the session.
  21630. */
  21631. WOLFSSL_SESSION* wolfSSL_d2i_SSL_SESSION(WOLFSSL_SESSION** sess,
  21632. const unsigned char** p, long i)
  21633. {
  21634. WOLFSSL_SESSION* s = NULL;
  21635. int ret = 0;
  21636. #if defined(HAVE_EXT_CACHE)
  21637. int idx;
  21638. byte* data;
  21639. #ifdef SESSION_CERTS
  21640. int j;
  21641. word16 length;
  21642. #endif
  21643. #endif /* HAVE_EXT_CACHE */
  21644. (void)p;
  21645. (void)i;
  21646. (void)ret;
  21647. (void)sess;
  21648. #ifdef HAVE_EXT_CACHE
  21649. if (p == NULL || *p == NULL)
  21650. return NULL;
  21651. s = wolfSSL_SESSION_new();
  21652. if (s == NULL)
  21653. return NULL;
  21654. idx = 0;
  21655. data = (byte*)*p;
  21656. /* side | bornOn | timeout | sessionID len */
  21657. if (i < OPAQUE8_LEN + OPAQUE32_LEN + OPAQUE32_LEN + OPAQUE8_LEN) {
  21658. ret = BUFFER_ERROR;
  21659. goto end;
  21660. }
  21661. s->side = data[idx++];
  21662. ato32(data + idx, &s->bornOn); idx += OPAQUE32_LEN;
  21663. ato32(data + idx, &s->timeout); idx += OPAQUE32_LEN;
  21664. s->sessionIDSz = data[idx++];
  21665. /* sessionID | secret | haveEMS | haveAltSessionID */
  21666. if (i - idx < s->sessionIDSz + SECRET_LEN + OPAQUE8_LEN + OPAQUE8_LEN) {
  21667. ret = BUFFER_ERROR;
  21668. goto end;
  21669. }
  21670. XMEMCPY(s->sessionID, data + idx, s->sessionIDSz);
  21671. idx += s->sessionIDSz;
  21672. XMEMCPY(s->masterSecret, data + idx, SECRET_LEN); idx += SECRET_LEN;
  21673. s->haveEMS = data[idx++];
  21674. if (data[idx] != ID_LEN && data[idx] != 0) {
  21675. ret = BUFFER_ERROR;
  21676. goto end;
  21677. }
  21678. s->haveAltSessionID = data[idx++] == ID_LEN;
  21679. /* altSessionID */
  21680. if (s->haveAltSessionID) {
  21681. if (i - idx < ID_LEN) {
  21682. ret = BUFFER_ERROR;
  21683. goto end;
  21684. }
  21685. XMEMCPY(s->altSessionID, data + idx, ID_LEN); idx += ID_LEN;
  21686. }
  21687. #ifdef SESSION_CERTS
  21688. /* Certificate chain */
  21689. if (i - idx == 0) {
  21690. ret = BUFFER_ERROR;
  21691. goto end;
  21692. }
  21693. s->chain.count = data[idx++];
  21694. for (j = 0; j < s->chain.count; j++) {
  21695. if (i - idx < OPAQUE16_LEN) {
  21696. ret = BUFFER_ERROR;
  21697. goto end;
  21698. }
  21699. ato16(data + idx, &length); idx += OPAQUE16_LEN;
  21700. s->chain.certs[j].length = length;
  21701. if (i - idx < length) {
  21702. ret = BUFFER_ERROR;
  21703. goto end;
  21704. }
  21705. XMEMCPY(s->chain.certs[j].buffer, data + idx, length);
  21706. idx += length;
  21707. }
  21708. #endif
  21709. #if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \
  21710. defined(HAVE_SESSION_TICKET))
  21711. /* Protocol Version */
  21712. if (i - idx < OPAQUE16_LEN) {
  21713. ret = BUFFER_ERROR;
  21714. goto end;
  21715. }
  21716. s->version.major = data[idx++];
  21717. s->version.minor = data[idx++];
  21718. #endif
  21719. #if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \
  21720. (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
  21721. /* Cipher suite */
  21722. if (i - idx < OPAQUE16_LEN) {
  21723. ret = BUFFER_ERROR;
  21724. goto end;
  21725. }
  21726. s->cipherSuite0 = data[idx++];
  21727. s->cipherSuite = data[idx++];
  21728. #endif
  21729. #ifndef NO_CLIENT_CACHE
  21730. /* ServerID len */
  21731. if (i - idx < OPAQUE16_LEN) {
  21732. ret = BUFFER_ERROR;
  21733. goto end;
  21734. }
  21735. ato16(data + idx, &s->idLen); idx += OPAQUE16_LEN;
  21736. /* ServerID */
  21737. if (i - idx < s->idLen) {
  21738. ret = BUFFER_ERROR;
  21739. goto end;
  21740. }
  21741. XMEMCPY(s->serverID, data + idx, s->idLen); idx += s->idLen;
  21742. #endif
  21743. #ifdef OPENSSL_EXTRA
  21744. /* byte for length of session context ID */
  21745. if (i - idx < OPAQUE8_LEN) {
  21746. ret = BUFFER_ERROR;
  21747. goto end;
  21748. }
  21749. s->sessionCtxSz = data[idx++];
  21750. /* app session context ID */
  21751. if (i - idx < s->sessionCtxSz) {
  21752. ret = BUFFER_ERROR;
  21753. goto end;
  21754. }
  21755. XMEMCPY(s->sessionCtx, data + idx, s->sessionCtxSz); idx += s->sessionCtxSz;
  21756. #endif
  21757. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  21758. /* byte for peerVerifyRet */
  21759. if (i - idx < OPAQUE8_LEN) {
  21760. ret = BUFFER_ERROR;
  21761. goto end;
  21762. }
  21763. s->peerVerifyRet = data[idx++];
  21764. #endif
  21765. #ifdef WOLFSSL_TLS13
  21766. if (i - idx < OPAQUE16_LEN) {
  21767. ret = BUFFER_ERROR;
  21768. goto end;
  21769. }
  21770. ato16(data + idx, &s->namedGroup);
  21771. idx += OPAQUE16_LEN;
  21772. #endif
  21773. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  21774. #ifdef WOLFSSL_TLS13
  21775. if (i - idx < (OPAQUE32_LEN * 2)) {
  21776. ret = BUFFER_ERROR;
  21777. goto end;
  21778. }
  21779. ato32(data + idx, &s->ticketSeen);
  21780. idx += OPAQUE32_LEN;
  21781. ato32(data + idx, &s->ticketAdd);
  21782. idx += OPAQUE32_LEN;
  21783. if (i - idx < OPAQUE8_LEN) {
  21784. ret = BUFFER_ERROR;
  21785. goto end;
  21786. }
  21787. s->ticketNonce.len = data[idx++];
  21788. if (i - idx < s->ticketNonce.len) {
  21789. ret = BUFFER_ERROR;
  21790. goto end;
  21791. }
  21792. XMEMCPY(s->ticketNonce.data, data + idx, s->ticketNonce.len);
  21793. idx += s->ticketNonce.len;
  21794. #endif
  21795. #ifdef WOLFSSL_EARLY_DATA
  21796. if (i - idx < OPAQUE32_LEN) {
  21797. ret = BUFFER_ERROR;
  21798. goto end;
  21799. }
  21800. ato32(data + idx, &s->maxEarlyDataSz);
  21801. idx += OPAQUE32_LEN;
  21802. #endif
  21803. #endif
  21804. #ifdef HAVE_SESSION_TICKET
  21805. /* ticket len */
  21806. if (i - idx < OPAQUE16_LEN) {
  21807. ret = BUFFER_ERROR;
  21808. goto end;
  21809. }
  21810. ato16(data + idx, &s->ticketLen); idx += OPAQUE16_LEN;
  21811. /* Dispose of ol dynamic ticket and ensure space for new ticket. */
  21812. if (s->ticketLenAlloc > 0) {
  21813. XFREE(s->ticket, NULL, DYNAMIC_TYPE_SESSION_TICK);
  21814. }
  21815. if (s->ticketLen <= SESSION_TICKET_LEN)
  21816. s->ticket = s->staticTicket;
  21817. else {
  21818. s->ticket = (byte*)XMALLOC(s->ticketLen, NULL,
  21819. DYNAMIC_TYPE_SESSION_TICK);
  21820. if (s->ticket == NULL) {
  21821. ret = MEMORY_ERROR;
  21822. goto end;
  21823. }
  21824. s->ticketLenAlloc = (word16)s->ticketLen;
  21825. }
  21826. /* ticket */
  21827. if (i - idx < s->ticketLen) {
  21828. ret = BUFFER_ERROR;
  21829. goto end;
  21830. }
  21831. XMEMCPY(s->ticket, data + idx, s->ticketLen); idx += s->ticketLen;
  21832. #endif
  21833. (void)idx;
  21834. if (sess != NULL) {
  21835. *sess = s;
  21836. }
  21837. *p += idx;
  21838. end:
  21839. if (ret != 0 && (sess == NULL || *sess != s)) {
  21840. wolfSSL_SESSION_free(s);
  21841. s = NULL;
  21842. }
  21843. #endif /* HAVE_EXT_CACHE */
  21844. return s;
  21845. }
  21846. /* Check if there is a session ticket associated with this WOLFSSL_SESSION.
  21847. *
  21848. * sess - pointer to WOLFSSL_SESSION struct
  21849. *
  21850. * Returns 1 if has session ticket, otherwise 0 */
  21851. int wolfSSL_SESSION_has_ticket(const WOLFSSL_SESSION* sess)
  21852. {
  21853. WOLFSSL_ENTER("wolfSSL_SESSION_has_ticket");
  21854. #ifdef HAVE_SESSION_TICKET
  21855. sess = ClientSessionToSession(sess);
  21856. if (sess) {
  21857. if ((sess->ticketLen > 0) && (sess->ticket != NULL)) {
  21858. return WOLFSSL_SUCCESS;
  21859. }
  21860. }
  21861. #else
  21862. (void)sess;
  21863. #endif
  21864. return WOLFSSL_FAILURE;
  21865. }
  21866. unsigned long wolfSSL_SESSION_get_ticket_lifetime_hint(
  21867. const WOLFSSL_SESSION* sess)
  21868. {
  21869. WOLFSSL_ENTER("wolfSSL_SESSION_get_ticket_lifetime_hint");
  21870. sess = ClientSessionToSession(sess);
  21871. if (sess) {
  21872. return sess->timeout;
  21873. }
  21874. return 0;
  21875. }
  21876. long wolfSSL_SESSION_get_timeout(const WOLFSSL_SESSION* sess)
  21877. {
  21878. long timeout = 0;
  21879. WOLFSSL_ENTER("wolfSSL_SESSION_get_timeout");
  21880. sess = ClientSessionToSession(sess);
  21881. if (sess)
  21882. timeout = sess->timeout;
  21883. return timeout;
  21884. }
  21885. long wolfSSL_SESSION_get_time(const WOLFSSL_SESSION* sess)
  21886. {
  21887. long bornOn = 0;
  21888. WOLFSSL_ENTER("wolfSSL_SESSION_get_time");
  21889. sess = ClientSessionToSession(sess);
  21890. if (sess)
  21891. bornOn = sess->bornOn;
  21892. return bornOn;
  21893. }
  21894. long wolfSSL_SSL_SESSION_set_timeout(WOLFSSL_SESSION* ses, long t)
  21895. {
  21896. word32 tmptime;
  21897. ses = ClientSessionToSession(ses);
  21898. if (ses == NULL || t < 0) {
  21899. return BAD_FUNC_ARG;
  21900. }
  21901. tmptime = t & 0xFFFFFFFF;
  21902. ses->timeout = tmptime;
  21903. return WOLFSSL_SUCCESS;
  21904. }
  21905. #endif /* !NO_SESSION_CACHE && OPENSSL_EXTRA || HAVE_EXT_CACHE */
  21906. #ifdef OPENSSL_EXTRA
  21907. #if defined(HAVE_EX_DATA) && !defined(NO_FILESYSTEM)
  21908. int wolfSSL_cmp_peer_cert_to_file(WOLFSSL* ssl, const char *fname)
  21909. {
  21910. int ret = WOLFSSL_FATAL_ERROR;
  21911. WOLFSSL_ENTER("wolfSSL_cmp_peer_cert_to_file");
  21912. if (ssl != NULL && fname != NULL)
  21913. {
  21914. #ifdef WOLFSSL_SMALL_STACK
  21915. byte staticBuffer[1]; /* force heap usage */
  21916. #else
  21917. byte staticBuffer[FILE_BUFFER_SIZE];
  21918. #endif
  21919. byte* myBuffer = staticBuffer;
  21920. int dynamic = 0;
  21921. XFILE file;
  21922. long sz = 0;
  21923. WOLFSSL_CTX* ctx = ssl->ctx;
  21924. WOLFSSL_X509* peer_cert = &ssl->peerCert;
  21925. DerBuffer* fileDer = NULL;
  21926. file = XFOPEN(fname, "rb");
  21927. if (file == XBADFILE)
  21928. return WOLFSSL_BAD_FILE;
  21929. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  21930. XFCLOSE(file);
  21931. return WOLFSSL_BAD_FILE;
  21932. }
  21933. sz = XFTELL(file);
  21934. XREWIND(file);
  21935. if (sz > MAX_WOLFSSL_FILE_SIZE || sz < 0) {
  21936. WOLFSSL_MSG("cmp_peer_cert_to_file size error");
  21937. XFCLOSE(file);
  21938. return WOLFSSL_BAD_FILE;
  21939. }
  21940. if (sz > (long)sizeof(staticBuffer)) {
  21941. WOLFSSL_MSG("Getting dynamic buffer");
  21942. myBuffer = (byte*)XMALLOC(sz, ctx->heap, DYNAMIC_TYPE_FILE);
  21943. dynamic = 1;
  21944. }
  21945. if ((myBuffer != NULL) &&
  21946. (sz > 0) &&
  21947. (XFREAD(myBuffer, 1, sz, file) == (size_t)sz) &&
  21948. (PemToDer(myBuffer, (long)sz, CERT_TYPE,
  21949. &fileDer, ctx->heap, NULL, NULL) == 0) &&
  21950. (fileDer->length != 0) &&
  21951. (fileDer->length == peer_cert->derCert->length) &&
  21952. (XMEMCMP(peer_cert->derCert->buffer, fileDer->buffer,
  21953. fileDer->length) == 0))
  21954. {
  21955. ret = 0;
  21956. }
  21957. FreeDer(&fileDer);
  21958. if (dynamic)
  21959. XFREE(myBuffer, ctx->heap, DYNAMIC_TYPE_FILE);
  21960. XFCLOSE(file);
  21961. }
  21962. return ret;
  21963. }
  21964. #endif
  21965. #endif /* OPENSSL_EXTRA */
  21966. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  21967. const WOLFSSL_ObjectInfo wolfssl_object_info[] = {
  21968. #ifndef NO_CERTS
  21969. /* oidCertExtType */
  21970. { NID_basic_constraints, BASIC_CA_OID, oidCertExtType, "basicConstraints",
  21971. "X509v3 Basic Constraints"},
  21972. { NID_subject_alt_name, ALT_NAMES_OID, oidCertExtType, "subjectAltName",
  21973. "X509v3 Subject Alternative Name"},
  21974. { NID_crl_distribution_points, CRL_DIST_OID, oidCertExtType, "crlDistributionPoints",
  21975. "X509v3 CRL Distribution Points"},
  21976. { NID_info_access, AUTH_INFO_OID, oidCertExtType, "authorityInfoAccess",
  21977. "Authority Information Access"},
  21978. { NID_authority_key_identifier, AUTH_KEY_OID, oidCertExtType,
  21979. "authorityKeyIdentifier", "X509v3 Authority Key Identifier"},
  21980. { NID_subject_key_identifier, SUBJ_KEY_OID, oidCertExtType,
  21981. "subjectKeyIdentifier", "X509v3 Subject Key Identifier"},
  21982. { NID_key_usage, KEY_USAGE_OID, oidCertExtType, "keyUsage",
  21983. "X509v3 Key Usage"},
  21984. { NID_inhibit_any_policy, INHIBIT_ANY_OID, oidCertExtType,
  21985. "inhibitAnyPolicy", "X509v3 Inhibit Any Policy"},
  21986. { NID_ext_key_usage, EXT_KEY_USAGE_OID, oidCertExtType,
  21987. "extendedKeyUsage", "X509v3 Extended Key Usage"},
  21988. { NID_name_constraints, NAME_CONS_OID, oidCertExtType,
  21989. "nameConstraints", "X509v3 Name Constraints"},
  21990. { NID_certificate_policies, CERT_POLICY_OID, oidCertExtType,
  21991. "certificatePolicies", "X509v3 Certificate Policies"},
  21992. /* oidCertAuthInfoType */
  21993. { NID_ad_OCSP, AIA_OCSP_OID, oidCertAuthInfoType, "OCSP",
  21994. "OCSP"},
  21995. { NID_ad_ca_issuers, AIA_CA_ISSUER_OID, oidCertAuthInfoType,
  21996. "caIssuers", "CA Issuers"},
  21997. /* oidCertPolicyType */
  21998. { NID_any_policy, CP_ANY_OID, oidCertPolicyType, "anyPolicy",
  21999. "X509v3 Any Policy"},
  22000. /* oidCertAltNameType */
  22001. { NID_hw_name_oid, HW_NAME_OID, oidCertAltNameType, "Hardware name",""},
  22002. /* oidCertKeyUseType */
  22003. { NID_anyExtendedKeyUsage, EKU_ANY_OID, oidCertKeyUseType,
  22004. "anyExtendedKeyUsage", "Any Extended Key Usage"},
  22005. { EKU_SERVER_AUTH_OID, EKU_SERVER_AUTH_OID, oidCertKeyUseType,
  22006. "serverAuth", "TLS Web Server Authentication"},
  22007. { EKU_CLIENT_AUTH_OID, EKU_CLIENT_AUTH_OID, oidCertKeyUseType,
  22008. "clientAuth", "TLS Web Client Authentication"},
  22009. { EKU_OCSP_SIGN_OID, EKU_OCSP_SIGN_OID, oidCertKeyUseType,
  22010. "OCSPSigning", "OCSP Signing"},
  22011. /* oidCertNameType */
  22012. { NID_commonName, NID_commonName, oidCertNameType, "CN", "commonName"},
  22013. { NID_surname, NID_surname, oidCertNameType, "SN", "surname"},
  22014. { NID_serialNumber, NID_serialNumber, oidCertNameType, "serialNumber",
  22015. "serialNumber"},
  22016. { NID_userId, NID_userId, oidCertNameType, "UID", "userid"},
  22017. { NID_countryName, NID_countryName, oidCertNameType, "C", "countryName"},
  22018. { NID_localityName, NID_localityName, oidCertNameType, "L", "localityName"},
  22019. { NID_stateOrProvinceName, NID_stateOrProvinceName, oidCertNameType, "ST",
  22020. "stateOrProvinceName"},
  22021. { NID_streetAddress, NID_streetAddress, oidCertNameType, "street",
  22022. "streetAddress"},
  22023. { NID_organizationName, NID_organizationName, oidCertNameType, "O",
  22024. "organizationName"},
  22025. { NID_organizationalUnitName, NID_organizationalUnitName, oidCertNameType,
  22026. "OU", "organizationalUnitName"},
  22027. { NID_emailAddress, NID_emailAddress, oidCertNameType, "emailAddress",
  22028. "emailAddress"},
  22029. { NID_domainComponent, NID_domainComponent, oidCertNameType, "DC",
  22030. "domainComponent"},
  22031. { NID_favouriteDrink, NID_favouriteDrink, oidCertNameType, "favouriteDrink",
  22032. "favouriteDrink"},
  22033. { NID_businessCategory, NID_businessCategory, oidCertNameType, "businessCategory",
  22034. "businessCategory"},
  22035. { NID_jurisdictionCountryName, NID_jurisdictionCountryName, oidCertNameType, "jurisdictionC",
  22036. "jurisdictionCountryName"},
  22037. { NID_jurisdictionStateOrProvinceName, NID_jurisdictionStateOrProvinceName,
  22038. oidCertNameType, "jurisdictionST", "jurisdictionStateOrProvinceName"},
  22039. { NID_postalCode, NID_postalCode, oidCertNameType, "postalCode", "postalCode"},
  22040. { NID_userId, NID_userId, oidCertNameType, "UID", "userId"},
  22041. #ifdef WOLFSSL_CERT_REQ
  22042. { NID_pkcs9_challengePassword, CHALLENGE_PASSWORD_OID,
  22043. oidCsrAttrType, "challengePassword", "challengePassword"},
  22044. { NID_pkcs9_contentType, PKCS9_CONTENT_TYPE_OID,
  22045. oidCsrAttrType, "contentType", "contentType" },
  22046. { NID_pkcs9_unstructuredName, UNSTRUCTURED_NAME_OID,
  22047. oidCsrAttrType, "unstructuredName", "unstructuredName" },
  22048. { NID_name, NAME_OID, oidCsrAttrType, "name", "name" },
  22049. { NID_surname, SURNAME_OID,
  22050. oidCsrAttrType, "surname", "surname" },
  22051. { NID_givenName, GIVEN_NAME_OID,
  22052. oidCsrAttrType, "givenName", "givenName" },
  22053. { NID_initials, INITIALS_OID,
  22054. oidCsrAttrType, "initials", "initials" },
  22055. { NID_dnQualifier, DNQUALIFIER_OID,
  22056. oidCsrAttrType, "dnQualifer", "dnQualifier" },
  22057. #endif
  22058. #endif
  22059. #ifdef OPENSSL_EXTRA /* OPENSSL_EXTRA_X509_SMALL only needs the above */
  22060. /* oidHashType */
  22061. #ifdef WOLFSSL_MD2
  22062. { NID_md2, MD2h, oidHashType, "MD2", "md2"},
  22063. #endif
  22064. #ifdef WOLFSSL_MD5
  22065. { NID_md5, MD5h, oidHashType, "MD5", "md5"},
  22066. #endif
  22067. #ifndef NO_SHA
  22068. { NID_sha1, SHAh, oidHashType, "SHA1", "sha1"},
  22069. #endif
  22070. #ifdef WOLFSSL_SHA224
  22071. { NID_sha224, SHA224h, oidHashType, "SHA224", "sha224"},
  22072. #endif
  22073. #ifndef NO_SHA256
  22074. { NID_sha256, SHA256h, oidHashType, "SHA256", "sha256"},
  22075. #endif
  22076. #ifdef WOLFSSL_SHA384
  22077. { NID_sha384, SHA384h, oidHashType, "SHA384", "sha384"},
  22078. #endif
  22079. #ifdef WOLFSSL_SHA512
  22080. { NID_sha512, SHA512h, oidHashType, "SHA512", "sha512"},
  22081. #endif
  22082. #ifdef WOLFSSL_SHA3
  22083. #ifndef WOLFSSL_NOSHA3_224
  22084. { NID_sha3_224, SHA3_224h, oidHashType, "SHA3-224", "sha3-224"},
  22085. #endif
  22086. #ifndef WOLFSSL_NOSHA3_256
  22087. { NID_sha3_256, SHA3_256h, oidHashType, "SHA3-256", "sha3-256"},
  22088. #endif
  22089. #ifndef WOLFSSL_NOSHA3_384
  22090. { NID_sha3_384, SHA3_384h, oidHashType, "SHA3-384", "sha3-384"},
  22091. #endif
  22092. #ifndef WOLFSSL_NOSHA3_512
  22093. { NID_sha3_512, SHA3_512h, oidHashType, "SHA3-512", "sha3-512"},
  22094. #endif
  22095. #endif /* WOLFSSL_SHA3 */
  22096. /* oidSigType */
  22097. #ifndef NO_DSA
  22098. #ifndef NO_SHA
  22099. { NID_dsaWithSHA1, CTC_SHAwDSA, oidSigType, "DSA-SHA1", "dsaWithSHA1"},
  22100. { NID_dsa_with_SHA256, CTC_SHA256wDSA, oidSigType, "dsa_with_SHA256",
  22101. "dsa_with_SHA256"},
  22102. #endif
  22103. #endif /* NO_DSA */
  22104. #ifndef NO_RSA
  22105. #ifdef WOLFSSL_MD2
  22106. { NID_md2WithRSAEncryption, CTC_MD2wRSA, oidSigType, "RSA-MD2",
  22107. "md2WithRSAEncryption"},
  22108. #endif
  22109. #ifndef NO_MD5
  22110. { NID_md5WithRSAEncryption, CTC_MD5wRSA, oidSigType, "RSA-MD5",
  22111. "md5WithRSAEncryption"},
  22112. #endif
  22113. #ifndef NO_SHA
  22114. { NID_sha1WithRSAEncryption, CTC_SHAwRSA, oidSigType, "RSA-SHA1",
  22115. "sha1WithRSAEncryption"},
  22116. #endif
  22117. #ifdef WOLFSSL_SHA224
  22118. { NID_sha224WithRSAEncryption, CTC_SHA224wRSA, oidSigType, "RSA-SHA224",
  22119. "sha224WithRSAEncryption"},
  22120. #endif
  22121. #ifndef NO_SHA256
  22122. { NID_sha256WithRSAEncryption, CTC_SHA256wRSA, oidSigType, "RSA-SHA256",
  22123. "sha256WithRSAEncryption"},
  22124. #endif
  22125. #ifdef WOLFSSL_SHA384
  22126. { NID_sha384WithRSAEncryption, CTC_SHA384wRSA, oidSigType, "RSA-SHA384",
  22127. "sha384WithRSAEncryption"},
  22128. #endif
  22129. #ifdef WOLFSSL_SHA512
  22130. { NID_sha512WithRSAEncryption, CTC_SHA512wRSA, oidSigType, "RSA-SHA512",
  22131. "sha512WithRSAEncryption"},
  22132. #endif
  22133. #ifdef WOLFSSL_SHA3
  22134. #ifndef WOLFSSL_NOSHA3_224
  22135. { NID_RSA_SHA3_224, CTC_SHA3_224wRSA, oidSigType, "RSA-SHA3-224",
  22136. "sha3-224WithRSAEncryption"},
  22137. #endif
  22138. #ifndef WOLFSSL_NOSHA3_256
  22139. { NID_RSA_SHA3_256, CTC_SHA3_256wRSA, oidSigType, "RSA-SHA3-256",
  22140. "sha3-256WithRSAEncryption"},
  22141. #endif
  22142. #ifndef WOLFSSL_NOSHA3_384
  22143. { NID_RSA_SHA3_384, CTC_SHA3_384wRSA, oidSigType, "RSA-SHA3-384",
  22144. "sha3-384WithRSAEncryption"},
  22145. #endif
  22146. #ifndef WOLFSSL_NOSHA3_512
  22147. { NID_RSA_SHA3_512, CTC_SHA3_512wRSA, oidSigType, "RSA-SHA3-512",
  22148. "sha3-512WithRSAEncryption"},
  22149. #endif
  22150. #endif
  22151. #endif /* NO_RSA */
  22152. #ifdef HAVE_ECC
  22153. #ifndef NO_SHA
  22154. { NID_ecdsa_with_SHA1, CTC_SHAwECDSA, oidSigType, "ecdsa-with-SHA1", "shaWithECDSA"},
  22155. #endif
  22156. #ifdef WOLFSSL_SHA224
  22157. { NID_ecdsa_with_SHA224, CTC_SHA224wECDSA, oidSigType, "ecdsa-with-SHA224","sha224WithECDSA"},
  22158. #endif
  22159. #ifndef NO_SHA256
  22160. { NID_ecdsa_with_SHA256, CTC_SHA256wECDSA, oidSigType, "ecdsa-with-SHA256","sha256WithECDSA"},
  22161. #endif
  22162. #ifdef WOLFSSL_SHA384
  22163. { NID_ecdsa_with_SHA384, CTC_SHA384wECDSA, oidSigType, "ecdsa-with-SHA384","sha384WithECDSA"},
  22164. #endif
  22165. #ifdef WOLFSSL_SHA512
  22166. { NID_ecdsa_with_SHA512, CTC_SHA512wECDSA, oidSigType, "ecdsa-with-SHA512","sha512WithECDSA"},
  22167. #endif
  22168. #ifdef WOLFSSL_SHA3
  22169. #ifndef WOLFSSL_NOSHA3_224
  22170. { NID_ecdsa_with_SHA3_224, CTC_SHA3_224wECDSA, oidSigType, "id-ecdsa-with-SHA3-224",
  22171. "ecdsa_with_SHA3-224"},
  22172. #endif
  22173. #ifndef WOLFSSL_NOSHA3_256
  22174. { NID_ecdsa_with_SHA3_256, CTC_SHA3_256wECDSA, oidSigType, "id-ecdsa-with-SHA3-256",
  22175. "ecdsa_with_SHA3-256"},
  22176. #endif
  22177. #ifndef WOLFSSL_NOSHA3_384
  22178. { NID_ecdsa_with_SHA3_384, CTC_SHA3_384wECDSA, oidSigType, "id-ecdsa-with-SHA3-384",
  22179. "ecdsa_with_SHA3-384"},
  22180. #endif
  22181. #ifndef WOLFSSL_NOSHA3_512
  22182. { NID_ecdsa_with_SHA3_512, CTC_SHA3_512wECDSA, oidSigType, "id-ecdsa-with-SHA3-512",
  22183. "ecdsa_with_SHA3-512"},
  22184. #endif
  22185. #endif
  22186. #endif /* HAVE_ECC */
  22187. /* oidKeyType */
  22188. #ifndef NO_DSA
  22189. { NID_dsa, DSAk, oidKeyType, "DSA", "dsaEncryption"},
  22190. #endif /* NO_DSA */
  22191. #ifndef NO_RSA
  22192. { NID_rsaEncryption, RSAk, oidKeyType, "rsaEncryption", "rsaEncryption"},
  22193. #endif /* NO_RSA */
  22194. #ifdef HAVE_ECC
  22195. { NID_X9_62_id_ecPublicKey, ECDSAk, oidKeyType, "id-ecPublicKey",
  22196. "id-ecPublicKey"},
  22197. #endif /* HAVE_ECC */
  22198. #ifndef NO_DH
  22199. { NID_dhKeyAgreement, DHk, oidKeyType, "dhKeyAgreement", "dhKeyAgreement"},
  22200. #endif
  22201. #ifdef HAVE_ED448
  22202. { NID_ED448, ED448k, oidKeyType, "ED448", "ED448"},
  22203. #endif
  22204. #ifdef HAVE_ED25519
  22205. { NID_ED25519, ED25519k, oidKeyType, "ED25519", "ED25519"},
  22206. #endif
  22207. #ifdef HAVE_PQC
  22208. #ifdef HAVE_FALCON
  22209. { CTC_FALCON_LEVEL1, FALCON_LEVEL1k, oidKeyType, "Falcon Level 1",
  22210. "Falcon Level 1"},
  22211. { CTC_FALCON_LEVEL5, FALCON_LEVEL5k, oidKeyType, "Falcon Level 5",
  22212. "Falcon Level 5"},
  22213. #endif /* HAVE_FALCON */
  22214. #ifdef HAVE_DILITHIUM
  22215. { CTC_DILITHIUM_LEVEL2, DILITHIUM_LEVEL2k, oidKeyType,
  22216. "Dilithium Level 2", "Dilithium Level 2"},
  22217. { CTC_DILITHIUM_LEVEL3, DILITHIUM_LEVEL3k, oidKeyType,
  22218. "Dilithium Level 3", "Dilithium Level 3"},
  22219. { CTC_DILITHIUM_LEVEL5, DILITHIUM_LEVEL5k, oidKeyType,
  22220. "Dilithium Level 5", "Dilithium Level 5"},
  22221. { CTC_DILITHIUM_AES_LEVEL2, DILITHIUM_AES_LEVEL2k, oidKeyType,
  22222. "Dilithium AES Level 2", "Dilithium AES Level 2"},
  22223. { CTC_DILITHIUM_AES_LEVEL3, DILITHIUM_AES_LEVEL3k, oidKeyType,
  22224. "Dilithium AES Level 3", "Dilithium AES Level 3"},
  22225. { CTC_DILITHIUM_AES_LEVEL5, DILITHIUM_AES_LEVEL5k, oidKeyType,
  22226. "Dilithium AES Level 5", "Dilithium AES Level 5"},
  22227. #endif /* HAVE_DILITHIUM */
  22228. #endif /* HAVE_PQC */
  22229. /* oidCurveType */
  22230. #ifdef HAVE_ECC
  22231. { NID_X9_62_prime192v1, ECC_SECP192R1_OID, oidCurveType, "prime192v1", "prime192v1"},
  22232. { NID_X9_62_prime192v2, ECC_PRIME192V2_OID, oidCurveType, "prime192v2", "prime192v2"},
  22233. { NID_X9_62_prime192v3, ECC_PRIME192V3_OID, oidCurveType, "prime192v3", "prime192v3"},
  22234. { NID_X9_62_prime239v1, ECC_PRIME239V1_OID, oidCurveType, "prime239v1", "prime239v1"},
  22235. { NID_X9_62_prime239v2, ECC_PRIME239V2_OID, oidCurveType, "prime239v2", "prime239v2"},
  22236. { NID_X9_62_prime239v3, ECC_PRIME239V3_OID, oidCurveType, "prime239v3", "prime239v3"},
  22237. { NID_X9_62_prime256v1, ECC_SECP256R1_OID, oidCurveType, "prime256v1", "prime256v1"},
  22238. { NID_secp112r1, ECC_SECP112R1_OID, oidCurveType, "secp112r1", "secp112r1"},
  22239. { NID_secp112r2, ECC_SECP112R2_OID, oidCurveType, "secp112r2", "secp112r2"},
  22240. { NID_secp128r1, ECC_SECP128R1_OID, oidCurveType, "secp128r1", "secp128r1"},
  22241. { NID_secp128r2, ECC_SECP128R2_OID, oidCurveType, "secp128r2", "secp128r2"},
  22242. { NID_secp160r1, ECC_SECP160R1_OID, oidCurveType, "secp160r1", "secp160r1"},
  22243. { NID_secp160r2, ECC_SECP160R2_OID, oidCurveType, "secp160r2", "secp160r2"},
  22244. { NID_secp224r1, ECC_SECP224R1_OID, oidCurveType, "secp224r1", "secp224r1"},
  22245. { NID_secp384r1, ECC_SECP384R1_OID, oidCurveType, "secp384r1", "secp384r1"},
  22246. { NID_secp521r1, ECC_SECP521R1_OID, oidCurveType, "secp521r1", "secp521r1"},
  22247. { NID_secp160k1, ECC_SECP160K1_OID, oidCurveType, "secp160k1", "secp160k1"},
  22248. { NID_secp192k1, ECC_SECP192K1_OID, oidCurveType, "secp192k1", "secp192k1"},
  22249. { NID_secp224k1, ECC_SECP224K1_OID, oidCurveType, "secp224k1", "secp224k1"},
  22250. { NID_secp256k1, ECC_SECP256K1_OID, oidCurveType, "secp256k1", "secp256k1"},
  22251. { NID_brainpoolP160r1, ECC_BRAINPOOLP160R1_OID, oidCurveType, "brainpoolP160r1", "brainpoolP160r1"},
  22252. { NID_brainpoolP192r1, ECC_BRAINPOOLP192R1_OID, oidCurveType, "brainpoolP192r1", "brainpoolP192r1"},
  22253. { NID_brainpoolP224r1, ECC_BRAINPOOLP224R1_OID, oidCurveType, "brainpoolP224r1", "brainpoolP224r1"},
  22254. { NID_brainpoolP256r1, ECC_BRAINPOOLP256R1_OID, oidCurveType, "brainpoolP256r1", "brainpoolP256r1"},
  22255. { NID_brainpoolP320r1, ECC_BRAINPOOLP320R1_OID, oidCurveType, "brainpoolP320r1", "brainpoolP320r1"},
  22256. { NID_brainpoolP384r1, ECC_BRAINPOOLP384R1_OID, oidCurveType, "brainpoolP384r1", "brainpoolP384r1"},
  22257. { NID_brainpoolP512r1, ECC_BRAINPOOLP512R1_OID, oidCurveType, "brainpoolP512r1", "brainpoolP512r1"},
  22258. #endif /* HAVE_ECC */
  22259. /* oidBlkType */
  22260. #ifdef WOLFSSL_AES_128
  22261. { AES128CBCb, AES128CBCb, oidBlkType, "AES-128-CBC", "aes-128-cbc"},
  22262. #endif
  22263. #ifdef WOLFSSL_AES_192
  22264. { AES192CBCb, AES192CBCb, oidBlkType, "AES-192-CBC", "aes-192-cbc"},
  22265. #endif
  22266. #ifdef WOLFSSL_AES_256
  22267. { AES256CBCb, AES256CBCb, oidBlkType, "AES-256-CBC", "aes-256-cbc"},
  22268. #endif
  22269. #ifndef NO_DES3
  22270. { NID_des, DESb, oidBlkType, "DES-CBC", "des-cbc"},
  22271. { NID_des3, DES3b, oidBlkType, "DES-EDE3-CBC", "des-ede3-cbc"},
  22272. #endif /* !NO_DES3 */
  22273. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  22274. { NID_chacha20_poly1305, NID_chacha20_poly1305, oidBlkType, "ChaCha20-Poly1305", "chacha20-poly1305"},
  22275. #endif
  22276. /* oidOcspType */
  22277. #ifdef HAVE_OCSP
  22278. { NID_id_pkix_OCSP_basic, OCSP_BASIC_OID, oidOcspType, "basicOCSPResponse",
  22279. "Basic OCSP Response"},
  22280. { OCSP_NONCE_OID, OCSP_NONCE_OID, oidOcspType, "Nonce",
  22281. "OCSP Nonce"},
  22282. #endif /* HAVE_OCSP */
  22283. #ifndef NO_PWDBASED
  22284. /* oidKdfType */
  22285. { PBKDF2_OID, PBKDF2_OID, oidKdfType, "PBKDFv2", "PBKDF2"},
  22286. /* oidPBEType */
  22287. { PBE_SHA1_RC4_128, PBE_SHA1_RC4_128, oidPBEType,
  22288. "PBE-SHA1-RC4-128", "pbeWithSHA1And128BitRC4"},
  22289. { PBE_SHA1_DES, PBE_SHA1_DES, oidPBEType, "PBE-SHA1-DES",
  22290. "pbeWithSHA1AndDES-CBC"},
  22291. { PBE_SHA1_DES3, PBE_SHA1_DES3, oidPBEType, "PBE-SHA1-3DES",
  22292. "pbeWithSHA1And3-KeyTripleDES-CBC"},
  22293. #endif
  22294. /* oidKeyWrapType */
  22295. #ifdef WOLFSSL_AES_128
  22296. { AES128_WRAP, AES128_WRAP, oidKeyWrapType, "AES-128 wrap", "aes128-wrap"},
  22297. #endif
  22298. #ifdef WOLFSSL_AES_192
  22299. { AES192_WRAP, AES192_WRAP, oidKeyWrapType, "AES-192 wrap", "aes192-wrap"},
  22300. #endif
  22301. #ifdef WOLFSSL_AES_256
  22302. { AES256_WRAP, AES256_WRAP, oidKeyWrapType, "AES-256 wrap", "aes256-wrap"},
  22303. #endif
  22304. #ifndef NO_PKCS7
  22305. #ifndef NO_DH
  22306. /* oidCmsKeyAgreeType */
  22307. #ifndef NO_SHA
  22308. { dhSinglePass_stdDH_sha1kdf_scheme, dhSinglePass_stdDH_sha1kdf_scheme,
  22309. oidCmsKeyAgreeType, "dhSinglePass-stdDH-sha1kdf-scheme", "dhSinglePass-stdDH-sha1kdf-scheme"},
  22310. #endif
  22311. #ifdef WOLFSSL_SHA224
  22312. { dhSinglePass_stdDH_sha224kdf_scheme,
  22313. dhSinglePass_stdDH_sha224kdf_scheme, oidCmsKeyAgreeType,
  22314. "dhSinglePass-stdDH-sha224kdf-scheme", "dhSinglePass-stdDH-sha224kdf-scheme"},
  22315. #endif
  22316. #ifndef NO_SHA256
  22317. { dhSinglePass_stdDH_sha256kdf_scheme,
  22318. dhSinglePass_stdDH_sha256kdf_scheme, oidCmsKeyAgreeType,
  22319. "dhSinglePass-stdDH-sha256kdf-scheme", "dhSinglePass-stdDH-sha256kdf-scheme"},
  22320. #endif
  22321. #ifdef WOLFSSL_SHA384
  22322. { dhSinglePass_stdDH_sha384kdf_scheme,
  22323. dhSinglePass_stdDH_sha384kdf_scheme, oidCmsKeyAgreeType,
  22324. "dhSinglePass-stdDH-sha384kdf-scheme", "dhSinglePass-stdDH-sha384kdf-scheme"},
  22325. #endif
  22326. #ifdef WOLFSSL_SHA512
  22327. { dhSinglePass_stdDH_sha512kdf_scheme,
  22328. dhSinglePass_stdDH_sha512kdf_scheme, oidCmsKeyAgreeType,
  22329. "dhSinglePass-stdDH-sha512kdf-scheme", "dhSinglePass-stdDH-sha512kdf-scheme"},
  22330. #endif
  22331. #endif
  22332. #endif
  22333. #if defined(WOLFSSL_APACHE_HTTPD)
  22334. /* "1.3.6.1.5.5.7.8.7" */
  22335. { NID_id_on_dnsSRV, NID_id_on_dnsSRV, oidCertNameType,
  22336. WOLFSSL_SN_DNS_SRV, WOLFSSL_LN_DNS_SRV },
  22337. /* "1.3.6.1.4.1.311.20.2.3" */
  22338. { NID_ms_upn, WOLFSSL_MS_UPN_SUM, oidCertExtType, WOLFSSL_SN_MS_UPN,
  22339. WOLFSSL_LN_MS_UPN },
  22340. /* "1.3.6.1.5.5.7.1.24" */
  22341. { NID_tlsfeature, WOLFSSL_TLS_FEATURE_SUM, oidTlsExtType,
  22342. WOLFSSL_SN_TLS_FEATURE, WOLFSSL_LN_TLS_FEATURE },
  22343. #endif
  22344. #endif /* OPENSSL_EXTRA */
  22345. };
  22346. #define WOLFSSL_OBJECT_INFO_SZ \
  22347. (sizeof(wolfssl_object_info) / sizeof(*wolfssl_object_info))
  22348. const size_t wolfssl_object_info_sz = WOLFSSL_OBJECT_INFO_SZ;
  22349. #endif
  22350. #ifdef OPENSSL_EXTRA
  22351. WOLFSSL_ASN1_INTEGER* wolfSSL_BN_to_ASN1_INTEGER(const WOLFSSL_BIGNUM *bn, WOLFSSL_ASN1_INTEGER *ai)
  22352. {
  22353. WOLFSSL_ASN1_INTEGER* a;
  22354. int len;
  22355. const int extraTagSz = MAX_LENGTH_SZ + 1;
  22356. byte intTag[MAX_LENGTH_SZ + 1];
  22357. int idx = 0;
  22358. WOLFSSL_ENTER("wolfSSL_BN_to_ASN1_INTEGER");
  22359. if (ai == NULL) {
  22360. a = wolfSSL_ASN1_INTEGER_new();
  22361. if (a == NULL)
  22362. return NULL;
  22363. a->type = V_ASN1_INTEGER;
  22364. }
  22365. else {
  22366. a = ai;
  22367. }
  22368. if (a) {
  22369. if (wolfSSL_BN_is_negative(bn) && !wolfSSL_BN_is_zero(bn)) {
  22370. a->type |= V_ASN1_NEG_INTEGER;
  22371. a->negative = 1;
  22372. }
  22373. len = wolfSSL_BN_num_bytes(bn);
  22374. if (len == 0)
  22375. len = 1;
  22376. /* allocate buffer */
  22377. if (len + extraTagSz > (int)sizeof(a->intData)) {
  22378. /* create new data buffer and copy over */
  22379. a->data = (byte*)XMALLOC(len + extraTagSz, NULL,
  22380. DYNAMIC_TYPE_OPENSSL);
  22381. if (a->data == NULL) {
  22382. if (a != ai)
  22383. wolfSSL_ASN1_INTEGER_free(a);
  22384. return NULL;
  22385. }
  22386. a->isDynamic = 1;
  22387. }
  22388. else {
  22389. XMEMSET(a->intData, 0, sizeof(a->intData));
  22390. a->data = a->intData;
  22391. a->isDynamic = 0;
  22392. }
  22393. /* populate data */
  22394. if (wolfSSL_BN_is_zero(bn)) {
  22395. a->data[0] = 0;
  22396. }
  22397. else {
  22398. len = wolfSSL_BN_bn2bin(bn, a->data);
  22399. if (len < 0) {
  22400. wolfSSL_ASN1_INTEGER_free(a);
  22401. return NULL;
  22402. }
  22403. }
  22404. a->length = len;
  22405. /* Write ASN tag */
  22406. idx = SetASNInt(a->length, a->data[0], intTag);
  22407. XMEMMOVE(a->data + idx, a->data, a->length);
  22408. XMEMCPY(a->data, intTag, idx);
  22409. a->dataMax = a->length += idx;
  22410. }
  22411. return a;
  22412. }
  22413. #ifdef OPENSSL_ALL
  22414. void *wolfSSL_ASN1_item_new(const WOLFSSL_ASN1_ITEM *tpl)
  22415. {
  22416. void *ret = NULL;
  22417. const WOLFSSL_ASN1_TEMPLATE *member = NULL;
  22418. size_t i;
  22419. WOLFSSL_ENTER("wolfSSL_ASN1_item_new");
  22420. if (!tpl) {
  22421. return NULL;
  22422. }
  22423. if (!(ret = (void *)XMALLOC(tpl->size, NULL, DYNAMIC_TYPE_OPENSSL))) {
  22424. return NULL;
  22425. }
  22426. XMEMSET(ret, 0, tpl->size);
  22427. for (member = tpl->members, i = 0; i < tpl->mcount;
  22428. member++, i++) {
  22429. switch (member->type) {
  22430. case WOLFSSL_X509_ALGOR_ASN1:
  22431. {
  22432. WOLFSSL_X509_ALGOR* algor = wolfSSL_X509_ALGOR_new();
  22433. if (!algor) {
  22434. goto error;
  22435. }
  22436. *(WOLFSSL_X509_ALGOR**)(((byte*)ret) + member->offset) = algor;
  22437. break;
  22438. }
  22439. case WOLFSSL_ASN1_BIT_STRING_ASN1:
  22440. {
  22441. WOLFSSL_ASN1_BIT_STRING* bit_str = wolfSSL_ASN1_BIT_STRING_new();
  22442. if (!bit_str) {
  22443. goto error;
  22444. }
  22445. *(WOLFSSL_ASN1_BIT_STRING**)(((byte*)ret) + member->offset) = bit_str;
  22446. break;
  22447. }
  22448. default:
  22449. WOLFSSL_MSG("Type not supported in wolfSSL_ASN1_item_new");
  22450. goto error;
  22451. }
  22452. }
  22453. return ret;
  22454. error:
  22455. wolfSSL_ASN1_item_free(ret, tpl);
  22456. return NULL;
  22457. }
  22458. void wolfSSL_ASN1_item_free(void *val, const WOLFSSL_ASN1_ITEM *tpl)
  22459. {
  22460. const WOLFSSL_ASN1_TEMPLATE *member = NULL;
  22461. size_t i;
  22462. WOLFSSL_ENTER("wolfSSL_ASN1_item_free");
  22463. if (val) {
  22464. for (member = tpl->members, i = 0; i < tpl->mcount;
  22465. member++, i++) {
  22466. switch (member->type) {
  22467. case WOLFSSL_X509_ALGOR_ASN1:
  22468. {
  22469. WOLFSSL_X509_ALGOR* algor = *(WOLFSSL_X509_ALGOR**)
  22470. (((byte*)val) + member->offset);
  22471. if (algor) {
  22472. wolfSSL_X509_ALGOR_free(algor);
  22473. }
  22474. break;
  22475. }
  22476. case WOLFSSL_ASN1_BIT_STRING_ASN1:
  22477. {
  22478. WOLFSSL_ASN1_BIT_STRING* bit_str = *(WOLFSSL_ASN1_BIT_STRING**)
  22479. (((byte*)val) + member->offset);
  22480. if (bit_str) {
  22481. wolfSSL_ASN1_BIT_STRING_free(bit_str);
  22482. }
  22483. break;
  22484. }
  22485. default:
  22486. WOLFSSL_MSG("Type not supported in wolfSSL_ASN1_item_free");
  22487. }
  22488. }
  22489. XFREE(val, NULL, DYNAMIC_TYPE_OPENSSL);
  22490. }
  22491. }
  22492. #define bufLenOrNull(buf, len) ((buf) ? (buf) + (len) : NULL)
  22493. static int i2dProcessMembers(const void *src, byte *buf,
  22494. const WOLFSSL_ASN1_TEMPLATE *members, size_t mcount)
  22495. {
  22496. const WOLFSSL_ASN1_TEMPLATE *member = NULL;
  22497. int len = 0, ret;
  22498. size_t i;
  22499. WOLFSSL_ENTER("processMembers");
  22500. for (member = members, i = 0; i < mcount; member++, i++) {
  22501. switch (member->type) {
  22502. case WOLFSSL_X509_ALGOR_ASN1:
  22503. {
  22504. word32 oid = 0;
  22505. word32 idx = 0;
  22506. const WOLFSSL_X509_ALGOR* algor = *(const WOLFSSL_X509_ALGOR**)
  22507. (((byte*)src) + member->offset);
  22508. if (!algor->algorithm) {
  22509. WOLFSSL_LEAVE("processMembers", WOLFSSL_FAILURE);
  22510. return WOLFSSL_FAILURE;
  22511. }
  22512. if (GetObjectId(algor->algorithm->obj, &idx, &oid,
  22513. algor->algorithm->grp, algor->algorithm->objSz) < 0) {
  22514. WOLFSSL_MSG("Issue getting OID of object");
  22515. return -1;
  22516. }
  22517. ret = SetAlgoID(oid, bufLenOrNull(buf, len),
  22518. algor->algorithm->grp, 0);
  22519. if (!ret) {
  22520. return WOLFSSL_FAILURE;
  22521. }
  22522. len += ret;
  22523. break;
  22524. }
  22525. case WOLFSSL_ASN1_BIT_STRING_ASN1:
  22526. {
  22527. const WOLFSSL_ASN1_BIT_STRING* bit_str;
  22528. bit_str = *(const WOLFSSL_ASN1_BIT_STRING**)
  22529. (((byte*)src) + member->offset);
  22530. len += SetBitString(bit_str->length, 0, bufLenOrNull(buf, len));
  22531. if (buf && bit_str->data) {
  22532. XMEMCPY(buf + len, bit_str->data, bit_str->length);
  22533. }
  22534. len += bit_str->length;
  22535. break;
  22536. }
  22537. default:
  22538. WOLFSSL_MSG("Type not support in processMembers");
  22539. WOLFSSL_LEAVE("processMembers", WOLFSSL_FAILURE);
  22540. return WOLFSSL_FAILURE;
  22541. }
  22542. }
  22543. WOLFSSL_LEAVE("processMembers", len);
  22544. return len;
  22545. }
  22546. static int wolfSSL_ASN1_item_i2d_1(const void *src, byte *buf,
  22547. const WOLFSSL_ASN1_ITEM *tpl, int *len)
  22548. {
  22549. *len = 0;
  22550. switch (tpl->type) {
  22551. case ASN_SEQUENCE:
  22552. {
  22553. int seq_len = i2dProcessMembers(src, NULL, tpl->members,
  22554. tpl->mcount);
  22555. if (seq_len == WOLFSSL_FAILURE)
  22556. return WOLFSSL_FAILURE;
  22557. *len += SetSequence(seq_len, bufLenOrNull(buf, *len));
  22558. if (buf) {
  22559. if (i2dProcessMembers(src, bufLenOrNull(buf, *len), tpl->members,
  22560. tpl->mcount) != seq_len) {
  22561. WOLFSSL_MSG("Inconsistent sequence length");
  22562. return WOLFSSL_FAILURE;
  22563. }
  22564. }
  22565. *len += seq_len;
  22566. break;
  22567. }
  22568. default:
  22569. WOLFSSL_MSG("Type not supported in wolfSSL_ASN1_item_i2d");
  22570. return WOLFSSL_FAILURE;
  22571. }
  22572. return WOLFSSL_SUCCESS;
  22573. }
  22574. int wolfSSL_ASN1_item_i2d(const void *src, byte **dest,
  22575. const WOLFSSL_ASN1_ITEM *tpl)
  22576. {
  22577. int len;
  22578. byte *buf = NULL;
  22579. WOLFSSL_ENTER("wolfSSL_ASN1_item_i2d");
  22580. if ((src == NULL) || (tpl == NULL))
  22581. goto error;
  22582. if (wolfSSL_ASN1_item_i2d_1(src, NULL, tpl, &len) != WOLFSSL_SUCCESS)
  22583. goto error;
  22584. if (dest == NULL) {
  22585. WOLFSSL_LEAVE("wolfSSL_ASN1_item_i2d", WOLFSSL_SUCCESS);
  22586. return len;
  22587. }
  22588. if (*dest == NULL) {
  22589. buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_ASN1);
  22590. if (buf == NULL)
  22591. goto error;
  22592. } else
  22593. buf = *dest;
  22594. if (wolfSSL_ASN1_item_i2d_1(src, buf, tpl, &len) != WOLFSSL_SUCCESS)
  22595. goto error;
  22596. if (*dest == NULL)
  22597. *dest = buf;
  22598. else {
  22599. /* XXX *dest length is not checked because the user is responsible
  22600. * for providing a long enough buffer
  22601. */
  22602. XMEMCPY(*dest, buf, len);
  22603. }
  22604. WOLFSSL_LEAVE("wolfSSL_ASN1_item_i2d", len);
  22605. return len;
  22606. error:
  22607. if (buf) {
  22608. XFREE(buf, NULL, DYNAMIC_TYPE_ASN1);
  22609. }
  22610. WOLFSSL_LEAVE("wolfSSL_ASN1_item_i2d", WOLFSSL_FAILURE);
  22611. return WOLFSSL_FAILURE;
  22612. }
  22613. #endif /* OPENSSL_ALL */
  22614. #endif /* OPENSSL_EXTRA */
  22615. #ifdef OPENSSL_EXTRA
  22616. WOLFSSL_HMAC_CTX* wolfSSL_HMAC_CTX_new(void)
  22617. {
  22618. WOLFSSL_HMAC_CTX* hmac_ctx = (WOLFSSL_HMAC_CTX*)XMALLOC(
  22619. sizeof(WOLFSSL_HMAC_CTX), NULL, DYNAMIC_TYPE_OPENSSL);
  22620. if (hmac_ctx != NULL) {
  22621. XMEMSET(hmac_ctx, 0, sizeof(WOLFSSL_HMAC_CTX));
  22622. }
  22623. return hmac_ctx;
  22624. }
  22625. int wolfSSL_HMAC_CTX_Init(WOLFSSL_HMAC_CTX* ctx)
  22626. {
  22627. WOLFSSL_MSG("wolfSSL_HMAC_CTX_Init");
  22628. if (ctx != NULL) {
  22629. /* wc_HmacSetKey sets up ctx->hmac */
  22630. XMEMSET(ctx, 0, sizeof(WOLFSSL_HMAC_CTX));
  22631. }
  22632. return WOLFSSL_SUCCESS;
  22633. }
  22634. int wolfSSL_HMAC_Init_ex(WOLFSSL_HMAC_CTX* ctx, const void* key,
  22635. int keylen, const EVP_MD* type, WOLFSSL_ENGINE* e)
  22636. {
  22637. WOLFSSL_ENTER("wolfSSL_HMAC_Init_ex");
  22638. /* WOLFSSL_ENGINE not used, call wolfSSL_HMAC_Init */
  22639. (void)e;
  22640. return wolfSSL_HMAC_Init(ctx, key, keylen, type);
  22641. }
  22642. /* helper function for Deep copy of internal wolfSSL hmac structure
  22643. * returns WOLFSSL_SUCCESS on success */
  22644. int wolfSSL_HmacCopy(Hmac* des, Hmac* src)
  22645. {
  22646. void* heap;
  22647. int ret;
  22648. #ifndef HAVE_FIPS
  22649. heap = src->heap;
  22650. #else
  22651. heap = NULL;
  22652. #endif
  22653. if (wc_HmacInit(des, heap, 0) != 0) {
  22654. return WOLFSSL_FAILURE;
  22655. }
  22656. /* requires that hash structures have no dynamic parts to them */
  22657. switch (src->macType) {
  22658. #ifndef NO_MD5
  22659. case WC_MD5:
  22660. ret = wc_Md5Copy(&src->hash.md5, &des->hash.md5);
  22661. break;
  22662. #endif /* !NO_MD5 */
  22663. #ifndef NO_SHA
  22664. case WC_SHA:
  22665. ret = wc_ShaCopy(&src->hash.sha, &des->hash.sha);
  22666. break;
  22667. #endif /* !NO_SHA */
  22668. #ifdef WOLFSSL_SHA224
  22669. case WC_SHA224:
  22670. ret = wc_Sha224Copy(&src->hash.sha224, &des->hash.sha224);
  22671. break;
  22672. #endif /* WOLFSSL_SHA224 */
  22673. #ifndef NO_SHA256
  22674. case WC_SHA256:
  22675. ret = wc_Sha256Copy(&src->hash.sha256, &des->hash.sha256);
  22676. break;
  22677. #endif /* !NO_SHA256 */
  22678. #ifdef WOLFSSL_SHA384
  22679. case WC_SHA384:
  22680. ret = wc_Sha384Copy(&src->hash.sha384, &des->hash.sha384);
  22681. break;
  22682. #endif /* WOLFSSL_SHA384 */
  22683. #ifdef WOLFSSL_SHA512
  22684. case WC_SHA512:
  22685. ret = wc_Sha512Copy(&src->hash.sha512, &des->hash.sha512);
  22686. break;
  22687. #endif /* WOLFSSL_SHA512 */
  22688. #ifdef WOLFSSL_SHA3
  22689. #ifndef WOLFSSL_NOSHA3_224
  22690. case WC_SHA3_224:
  22691. ret = wc_Sha3_224_Copy(&src->hash.sha3, &des->hash.sha3);
  22692. break;
  22693. #endif /* WOLFSSL_NO_SHA3_224 */
  22694. #ifndef WOLFSSL_NOSHA3_256
  22695. case WC_SHA3_256:
  22696. ret = wc_Sha3_256_Copy(&src->hash.sha3, &des->hash.sha3);
  22697. break;
  22698. #endif /* WOLFSSL_NO_SHA3_256 */
  22699. #ifndef WOLFSSL_NOSHA3_384
  22700. case WC_SHA3_384:
  22701. ret = wc_Sha3_384_Copy(&src->hash.sha3, &des->hash.sha3);
  22702. break;
  22703. #endif /* WOLFSSL_NO_SHA3_384 */
  22704. #ifndef WOLFSSL_NOSHA3_512
  22705. case WC_SHA3_512:
  22706. ret = wc_Sha3_512_Copy(&src->hash.sha3, &des->hash.sha3);
  22707. break;
  22708. #endif /* WOLFSSL_NO_SHA3_512 */
  22709. #endif /* WOLFSSL_SHA3 */
  22710. default:
  22711. return WOLFSSL_FAILURE;
  22712. }
  22713. if (ret != 0)
  22714. return WOLFSSL_FAILURE;
  22715. XMEMCPY((byte*)des->ipad, (byte*)src->ipad, WC_HMAC_BLOCK_SIZE);
  22716. XMEMCPY((byte*)des->opad, (byte*)src->opad, WC_HMAC_BLOCK_SIZE);
  22717. XMEMCPY((byte*)des->innerHash, (byte*)src->innerHash, WC_MAX_DIGEST_SIZE);
  22718. #ifndef HAVE_FIPS
  22719. des->heap = heap;
  22720. #endif
  22721. des->macType = src->macType;
  22722. des->innerHashKeyed = src->innerHashKeyed;
  22723. #ifdef WOLFSSL_ASYNC_CRYPT
  22724. XMEMCPY(&des->asyncDev, &src->asyncDev, sizeof(WC_ASYNC_DEV));
  22725. des->keyLen = src->keyLen;
  22726. #ifdef HAVE_CAVIUM
  22727. des->data = (byte*)XMALLOC(src->dataLen, des->heap,
  22728. DYNAMIC_TYPE_HMAC);
  22729. if (des->data == NULL) {
  22730. return BUFFER_E;
  22731. }
  22732. XMEMCPY(des->data, src->data, src->dataLen);
  22733. des->dataLen = src->dataLen;
  22734. #endif /* HAVE_CAVIUM */
  22735. #endif /* WOLFSSL_ASYNC_CRYPT */
  22736. return WOLFSSL_SUCCESS;
  22737. }
  22738. /* Deep copy of information from src to des structure
  22739. *
  22740. * des destination to copy information to
  22741. * src structure to get information from
  22742. *
  22743. * Returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error
  22744. */
  22745. int wolfSSL_HMAC_CTX_copy(WOLFSSL_HMAC_CTX* des, WOLFSSL_HMAC_CTX* src)
  22746. {
  22747. WOLFSSL_ENTER("wolfSSL_HMAC_CTX_copy");
  22748. if (des == NULL || src == NULL) {
  22749. return WOLFSSL_FAILURE;
  22750. }
  22751. des->type = src->type;
  22752. XMEMCPY((byte *)&des->save_ipad, (byte *)&src->hmac.ipad,
  22753. WC_HMAC_BLOCK_SIZE);
  22754. XMEMCPY((byte *)&des->save_opad, (byte *)&src->hmac.opad,
  22755. WC_HMAC_BLOCK_SIZE);
  22756. return wolfSSL_HmacCopy(&des->hmac, &src->hmac);
  22757. }
  22758. #if defined(HAVE_FIPS) && \
  22759. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2))
  22760. static int _HMAC_Init(Hmac* hmac, int type, void* heap)
  22761. {
  22762. int ret = 0;
  22763. switch (type) {
  22764. #ifndef NO_MD5
  22765. case WC_MD5:
  22766. ret = wc_InitMd5(&hmac->hash.md5);
  22767. break;
  22768. #endif /* !NO_MD5 */
  22769. #ifndef NO_SHA
  22770. case WC_SHA:
  22771. ret = wc_InitSha(&hmac->hash.sha);
  22772. break;
  22773. #endif /* !NO_SHA */
  22774. #ifdef WOLFSSL_SHA224
  22775. case WC_SHA224:
  22776. ret = wc_InitSha224(&hmac->hash.sha224);
  22777. break;
  22778. #endif /* WOLFSSL_SHA224 */
  22779. #ifndef NO_SHA256
  22780. case WC_SHA256:
  22781. ret = wc_InitSha256(&hmac->hash.sha256);
  22782. break;
  22783. #endif /* !NO_SHA256 */
  22784. #ifdef WOLFSSL_SHA384
  22785. case WC_SHA384:
  22786. ret = wc_InitSha384(&hmac->hash.sha384);
  22787. break;
  22788. #endif /* WOLFSSL_SHA384 */
  22789. #ifdef WOLFSSL_SHA512
  22790. case WC_SHA512:
  22791. ret = wc_InitSha512(&hmac->hash.sha512);
  22792. break;
  22793. #endif /* WOLFSSL_SHA512 */
  22794. #ifdef WOLFSSL_SHA3
  22795. case WC_SHA3_224:
  22796. ret = wc_InitSha3_224(&hmac->hash.sha3, heap, INVALID_DEVID);
  22797. break;
  22798. case WC_SHA3_256:
  22799. ret = wc_InitSha3_256(&hmac->hash.sha3, heap, INVALID_DEVID);
  22800. break;
  22801. case WC_SHA3_384:
  22802. ret = wc_InitSha3_384(&hmac->hash.sha3, heap, INVALID_DEVID);
  22803. break;
  22804. case WC_SHA3_512:
  22805. ret = wc_InitSha3_512(&hmac->hash.sha3, heap, INVALID_DEVID);
  22806. break;
  22807. #endif
  22808. default:
  22809. ret = BAD_FUNC_ARG;
  22810. break;
  22811. }
  22812. (void)heap;
  22813. return ret;
  22814. }
  22815. #else
  22816. #define _HMAC_Init _InitHmac
  22817. #endif
  22818. int wolfSSL_HMAC_Init(WOLFSSL_HMAC_CTX* ctx, const void* key, int keylen,
  22819. const EVP_MD* type)
  22820. {
  22821. int hmac_error = 0;
  22822. void* heap = NULL;
  22823. int inited;
  22824. WOLFSSL_MSG("wolfSSL_HMAC_Init");
  22825. if (ctx == NULL) {
  22826. WOLFSSL_MSG("no ctx on init");
  22827. return WOLFSSL_FAILURE;
  22828. }
  22829. #ifndef HAVE_FIPS
  22830. heap = ctx->hmac.heap;
  22831. #endif
  22832. if (type) {
  22833. WOLFSSL_MSG("init has type");
  22834. #ifndef NO_MD5
  22835. if (XSTRNCMP(type, "MD5", 3) == 0) {
  22836. WOLFSSL_MSG("md5 hmac");
  22837. ctx->type = WC_MD5;
  22838. }
  22839. else
  22840. #endif
  22841. #ifdef WOLFSSL_SHA224
  22842. if (XSTRNCMP(type, "SHA224", 6) == 0) {
  22843. WOLFSSL_MSG("sha224 hmac");
  22844. ctx->type = WC_SHA224;
  22845. }
  22846. else
  22847. #endif
  22848. #ifndef NO_SHA256
  22849. if (XSTRNCMP(type, "SHA256", 6) == 0) {
  22850. WOLFSSL_MSG("sha256 hmac");
  22851. ctx->type = WC_SHA256;
  22852. }
  22853. else
  22854. #endif
  22855. #ifdef WOLFSSL_SHA384
  22856. if (XSTRNCMP(type, "SHA384", 6) == 0) {
  22857. WOLFSSL_MSG("sha384 hmac");
  22858. ctx->type = WC_SHA384;
  22859. }
  22860. else
  22861. #endif
  22862. #ifdef WOLFSSL_SHA512
  22863. if (XSTRNCMP(type, "SHA512", 6) == 0) {
  22864. WOLFSSL_MSG("sha512 hmac");
  22865. ctx->type = WC_SHA512;
  22866. }
  22867. else
  22868. #endif
  22869. #ifdef WOLFSSL_SHA3
  22870. #ifndef WOLFSSL_NOSHA3_224
  22871. if (XSTRNCMP(type, "SHA3_224", 8) == 0) {
  22872. WOLFSSL_MSG("sha3_224 hmac");
  22873. ctx->type = WC_SHA3_224;
  22874. }
  22875. else
  22876. #endif
  22877. #ifndef WOLFSSL_NOSHA3_256
  22878. if (XSTRNCMP(type, "SHA3_256", 8) == 0) {
  22879. WOLFSSL_MSG("sha3_256 hmac");
  22880. ctx->type = WC_SHA3_256;
  22881. }
  22882. else
  22883. #endif
  22884. if (XSTRNCMP(type, "SHA3_384", 8) == 0) {
  22885. WOLFSSL_MSG("sha3_384 hmac");
  22886. ctx->type = WC_SHA3_384;
  22887. }
  22888. else
  22889. #ifndef WOLFSSL_NOSHA3_512
  22890. if (XSTRNCMP(type, "SHA3_512", 8) == 0) {
  22891. WOLFSSL_MSG("sha3_512 hmac");
  22892. ctx->type = WC_SHA3_512;
  22893. }
  22894. else
  22895. #endif
  22896. #endif
  22897. #ifndef NO_SHA
  22898. /* has to be last since would pick or 256, 384, or 512 too */
  22899. if (XSTRNCMP(type, "SHA", 3) == 0) {
  22900. WOLFSSL_MSG("sha hmac");
  22901. ctx->type = WC_SHA;
  22902. }
  22903. else
  22904. #endif
  22905. {
  22906. WOLFSSL_MSG("bad init type");
  22907. return WOLFSSL_FAILURE;
  22908. }
  22909. }
  22910. /* Check if init has been called before */
  22911. inited = (ctx->hmac.macType != WC_HASH_TYPE_NONE);
  22912. /* Free if needed */
  22913. if (inited) {
  22914. wc_HmacFree(&ctx->hmac);
  22915. }
  22916. if (key != NULL) {
  22917. WOLFSSL_MSG("keying hmac");
  22918. if (wc_HmacInit(&ctx->hmac, NULL, INVALID_DEVID) == 0) {
  22919. hmac_error = wc_HmacSetKey(&ctx->hmac, ctx->type, (const byte*)key,
  22920. (word32)keylen);
  22921. if (hmac_error < 0){
  22922. /* in FIPS mode a key < 14 characters will fail here */
  22923. WOLFSSL_MSG("hmac set key error");
  22924. WOLFSSL_ERROR(hmac_error);
  22925. wc_HmacFree(&ctx->hmac);
  22926. return WOLFSSL_FAILURE;
  22927. }
  22928. XMEMCPY((byte *)&ctx->save_ipad, (byte *)&ctx->hmac.ipad,
  22929. WC_HMAC_BLOCK_SIZE);
  22930. XMEMCPY((byte *)&ctx->save_opad, (byte *)&ctx->hmac.opad,
  22931. WC_HMAC_BLOCK_SIZE);
  22932. }
  22933. /* OpenSSL compat, no error */
  22934. }
  22935. else if (!inited) {
  22936. return WOLFSSL_FAILURE;
  22937. }
  22938. else if (ctx->type >= 0) { /* MD5 == 0 */
  22939. WOLFSSL_MSG("recover hmac");
  22940. if (wc_HmacInit(&ctx->hmac, NULL, INVALID_DEVID) == 0) {
  22941. ctx->hmac.macType = (byte)ctx->type;
  22942. ctx->hmac.innerHashKeyed = 0;
  22943. XMEMCPY((byte *)&ctx->hmac.ipad, (byte *)&ctx->save_ipad,
  22944. WC_HMAC_BLOCK_SIZE);
  22945. XMEMCPY((byte *)&ctx->hmac.opad, (byte *)&ctx->save_opad,
  22946. WC_HMAC_BLOCK_SIZE);
  22947. if ((hmac_error = _HMAC_Init(&ctx->hmac, ctx->hmac.macType, heap))
  22948. !=0) {
  22949. WOLFSSL_MSG("hmac init error");
  22950. WOLFSSL_ERROR(hmac_error);
  22951. return WOLFSSL_FAILURE;
  22952. }
  22953. }
  22954. }
  22955. (void)hmac_error;
  22956. return WOLFSSL_SUCCESS;
  22957. }
  22958. int wolfSSL_HMAC_Update(WOLFSSL_HMAC_CTX* ctx, const unsigned char* data,
  22959. int len)
  22960. {
  22961. int hmac_error = 0;
  22962. WOLFSSL_MSG("wolfSSL_HMAC_Update");
  22963. if (ctx == NULL) {
  22964. WOLFSSL_MSG("no ctx");
  22965. return WOLFSSL_FAILURE;
  22966. }
  22967. if (data) {
  22968. WOLFSSL_MSG("updating hmac");
  22969. hmac_error = wc_HmacUpdate(&ctx->hmac, data, (word32)len);
  22970. if (hmac_error < 0){
  22971. WOLFSSL_MSG("hmac update error");
  22972. return WOLFSSL_FAILURE;
  22973. }
  22974. }
  22975. return WOLFSSL_SUCCESS;
  22976. }
  22977. int wolfSSL_HMAC_Final(WOLFSSL_HMAC_CTX* ctx, unsigned char* hash,
  22978. unsigned int* len)
  22979. {
  22980. int hmac_error;
  22981. WOLFSSL_MSG("wolfSSL_HMAC_Final");
  22982. /* "len" parameter is optional. */
  22983. if (ctx == NULL || hash == NULL) {
  22984. WOLFSSL_MSG("invalid parameter");
  22985. return WOLFSSL_FAILURE;
  22986. }
  22987. WOLFSSL_MSG("final hmac");
  22988. hmac_error = wc_HmacFinal(&ctx->hmac, hash);
  22989. if (hmac_error < 0){
  22990. WOLFSSL_MSG("final hmac error");
  22991. return WOLFSSL_FAILURE;
  22992. }
  22993. if (len) {
  22994. WOLFSSL_MSG("setting output len");
  22995. switch (ctx->type) {
  22996. #ifndef NO_MD5
  22997. case WC_MD5:
  22998. *len = WC_MD5_DIGEST_SIZE;
  22999. break;
  23000. #endif
  23001. #ifndef NO_SHA
  23002. case WC_SHA:
  23003. *len = WC_SHA_DIGEST_SIZE;
  23004. break;
  23005. #endif
  23006. #ifdef WOLFSSL_SHA224
  23007. case WC_SHA224:
  23008. *len = WC_SHA224_DIGEST_SIZE;
  23009. break;
  23010. #endif
  23011. #ifndef NO_SHA256
  23012. case WC_SHA256:
  23013. *len = WC_SHA256_DIGEST_SIZE;
  23014. break;
  23015. #endif
  23016. #ifdef WOLFSSL_SHA384
  23017. case WC_SHA384:
  23018. *len = WC_SHA384_DIGEST_SIZE;
  23019. break;
  23020. #endif
  23021. #ifdef WOLFSSL_SHA512
  23022. case WC_SHA512:
  23023. *len = WC_SHA512_DIGEST_SIZE;
  23024. break;
  23025. #endif
  23026. #ifdef WOLFSSL_SHA3
  23027. #ifndef WOLFSSL_NOSHA3_224
  23028. case WC_SHA3_224:
  23029. *len = WC_SHA3_224_DIGEST_SIZE;
  23030. break;
  23031. #endif
  23032. #ifndef WOLFSSL_NOSHA3_256
  23033. case WC_SHA3_256:
  23034. *len = WC_SHA3_256_DIGEST_SIZE;
  23035. break;
  23036. #endif
  23037. #ifndef WOLFSSL_NOSHA3_384
  23038. case WC_SHA3_384:
  23039. *len = WC_SHA3_384_DIGEST_SIZE;
  23040. break;
  23041. #endif
  23042. #ifndef WOLFSSL_NOSHA3_512
  23043. case WC_SHA3_512:
  23044. *len = WC_SHA3_512_DIGEST_SIZE;
  23045. break;
  23046. #endif
  23047. #endif
  23048. default:
  23049. WOLFSSL_MSG("bad hmac type");
  23050. return WOLFSSL_FAILURE;
  23051. }
  23052. }
  23053. return WOLFSSL_SUCCESS;
  23054. }
  23055. int wolfSSL_HMAC_cleanup(WOLFSSL_HMAC_CTX* ctx)
  23056. {
  23057. WOLFSSL_MSG("wolfSSL_HMAC_cleanup");
  23058. if (ctx) {
  23059. wc_HmacFree(&ctx->hmac);
  23060. }
  23061. return WOLFSSL_SUCCESS;
  23062. }
  23063. void wolfSSL_HMAC_CTX_cleanup(WOLFSSL_HMAC_CTX* ctx)
  23064. {
  23065. if (ctx) {
  23066. wolfSSL_HMAC_cleanup(ctx);
  23067. }
  23068. }
  23069. void wolfSSL_HMAC_CTX_free(WOLFSSL_HMAC_CTX* ctx)
  23070. {
  23071. if (ctx) {
  23072. wolfSSL_HMAC_CTX_cleanup(ctx);
  23073. XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
  23074. }
  23075. }
  23076. size_t wolfSSL_HMAC_size(const WOLFSSL_HMAC_CTX *ctx)
  23077. {
  23078. if (!ctx) {
  23079. return 0;
  23080. }
  23081. return (size_t)wc_HashGetDigestSize((enum wc_HashType)ctx->hmac.macType);
  23082. }
  23083. const WOLFSSL_EVP_MD *wolfSSL_HMAC_CTX_get_md(const WOLFSSL_HMAC_CTX *ctx)
  23084. {
  23085. if (!ctx) {
  23086. return NULL;
  23087. }
  23088. return wolfSSL_macType2EVP_md((enum wc_HashType)ctx->type);
  23089. }
  23090. #if defined(WOLFSSL_CMAC) && defined(OPENSSL_EXTRA) && \
  23091. defined(WOLFSSL_AES_DIRECT)
  23092. WOLFSSL_CMAC_CTX* wolfSSL_CMAC_CTX_new(void)
  23093. {
  23094. WOLFSSL_CMAC_CTX* ctx = NULL;
  23095. ctx = (WOLFSSL_CMAC_CTX*)XMALLOC(sizeof(WOLFSSL_CMAC_CTX), NULL,
  23096. DYNAMIC_TYPE_OPENSSL);
  23097. if (ctx != NULL) {
  23098. ctx->internal = (Cmac*)XMALLOC(sizeof(Cmac), NULL, DYNAMIC_TYPE_CMAC);
  23099. if (ctx->internal == NULL) {
  23100. XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
  23101. ctx = NULL;
  23102. }
  23103. }
  23104. if (ctx != NULL) {
  23105. ctx->cctx = wolfSSL_EVP_CIPHER_CTX_new();
  23106. if (ctx->cctx == NULL) {
  23107. XFREE(ctx->internal, NULL, DYNAMIC_TYPE_CMAC);
  23108. XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
  23109. ctx = NULL;
  23110. }
  23111. }
  23112. return ctx;
  23113. }
  23114. void wolfSSL_CMAC_CTX_free(WOLFSSL_CMAC_CTX *ctx)
  23115. {
  23116. if (ctx != NULL) {
  23117. if (ctx->internal != NULL) {
  23118. XFREE(ctx->internal, NULL, DYNAMIC_TYPE_CMAC);
  23119. }
  23120. if (ctx->cctx != NULL) {
  23121. wolfSSL_EVP_CIPHER_CTX_free(ctx->cctx);
  23122. }
  23123. XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
  23124. }
  23125. }
  23126. WOLFSSL_EVP_CIPHER_CTX* wolfSSL_CMAC_CTX_get0_cipher_ctx(WOLFSSL_CMAC_CTX* ctx)
  23127. {
  23128. WOLFSSL_EVP_CIPHER_CTX* cctx = NULL;
  23129. if (ctx != NULL) {
  23130. cctx = ctx->cctx;
  23131. }
  23132. return cctx;
  23133. }
  23134. int wolfSSL_CMAC_Init(WOLFSSL_CMAC_CTX* ctx, const void *key, size_t keyLen,
  23135. const WOLFSSL_EVP_CIPHER* cipher, WOLFSSL_ENGINE* engine)
  23136. {
  23137. int ret = WOLFSSL_SUCCESS;
  23138. (void)engine;
  23139. WOLFSSL_ENTER("wolfSSL_CMAC_Init");
  23140. if (ctx == NULL || cipher == NULL || (
  23141. cipher != EVP_AES_128_CBC &&
  23142. cipher != EVP_AES_192_CBC &&
  23143. cipher != EVP_AES_256_CBC)) {
  23144. ret = WOLFSSL_FAILURE;
  23145. }
  23146. if (ret == WOLFSSL_SUCCESS) {
  23147. ret = wc_InitCmac((Cmac*)ctx->internal, (const byte*)key,
  23148. (word32)keyLen, WC_CMAC_AES, NULL);
  23149. if (ret != 0) {
  23150. ret = WOLFSSL_FAILURE;
  23151. }
  23152. else {
  23153. ret = WOLFSSL_SUCCESS;
  23154. }
  23155. }
  23156. if (ret == WOLFSSL_SUCCESS) {
  23157. ret = wolfSSL_EVP_CipherInit(ctx->cctx, cipher, (const byte*)key, NULL,
  23158. 1);
  23159. }
  23160. WOLFSSL_LEAVE("wolfSSL_CMAC_Init", ret);
  23161. return ret;
  23162. }
  23163. int wolfSSL_CMAC_Update(WOLFSSL_CMAC_CTX* ctx, const void* data, size_t len)
  23164. {
  23165. int ret = WOLFSSL_SUCCESS;
  23166. WOLFSSL_ENTER("wolfSSL_CMAC_Update");
  23167. if (ctx == NULL || ctx->internal == NULL) {
  23168. ret = WOLFSSL_FAILURE;
  23169. }
  23170. if (ret == WOLFSSL_SUCCESS) {
  23171. if (data) {
  23172. ret = wc_CmacUpdate((Cmac*)ctx->internal, (const byte*)data,
  23173. (word32)len);
  23174. if (ret != 0){
  23175. ret = WOLFSSL_FAILURE;
  23176. }
  23177. else {
  23178. ret = WOLFSSL_SUCCESS;
  23179. }
  23180. }
  23181. }
  23182. WOLFSSL_LEAVE("wolfSSL_CMAC_Update", ret);
  23183. return ret;
  23184. }
  23185. int wolfSSL_CMAC_Final(WOLFSSL_CMAC_CTX* ctx, unsigned char* out,
  23186. size_t* len)
  23187. {
  23188. int ret = WOLFSSL_SUCCESS;
  23189. int blockSize;
  23190. WOLFSSL_ENTER("wolfSSL_CMAC_Final");
  23191. if (ctx == NULL || ctx->cctx == NULL || ctx->internal == NULL ||
  23192. len == NULL) {
  23193. ret = WOLFSSL_FAILURE;
  23194. }
  23195. if (ret == WOLFSSL_SUCCESS) {
  23196. blockSize = EVP_CIPHER_CTX_block_size(ctx->cctx);
  23197. if (blockSize <= 0) {
  23198. ret = WOLFSSL_FAILURE;
  23199. }
  23200. else {
  23201. *len = blockSize;
  23202. }
  23203. }
  23204. if (ret == WOLFSSL_SUCCESS) {
  23205. word32 len32 = (word32)*len;
  23206. ret = wc_CmacFinal((Cmac*)ctx->internal, out, &len32);
  23207. *len = (size_t)len32;
  23208. if (ret != 0) {
  23209. ret = WOLFSSL_FAILURE;
  23210. }
  23211. else {
  23212. ret = WOLFSSL_SUCCESS;
  23213. }
  23214. }
  23215. WOLFSSL_LEAVE("wolfSSL_CMAC_Final", ret);
  23216. return ret;
  23217. }
  23218. #endif /* WOLFSSL_CMAC && OPENSSL_EXTRA && WOLFSSL_AES_DIRECT */
  23219. #endif /* OPENSSL_EXTRA */
  23220. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  23221. /* Free the dynamically allocated data.
  23222. *
  23223. * p Pointer to dynamically allocated memory.
  23224. */
  23225. void wolfSSL_OPENSSL_free(void* p)
  23226. {
  23227. WOLFSSL_MSG("wolfSSL_OPENSSL_free");
  23228. XFREE(p, NULL, DYNAMIC_TYPE_OPENSSL);
  23229. }
  23230. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  23231. #ifdef OPENSSL_EXTRA
  23232. void *wolfSSL_OPENSSL_malloc(size_t a)
  23233. {
  23234. return (void *)XMALLOC(a, NULL, DYNAMIC_TYPE_OPENSSL);
  23235. }
  23236. int wolfSSL_OPENSSL_hexchar2int(unsigned char c)
  23237. {
  23238. /* 'char' is unsigned on some platforms. */
  23239. return (int)(signed char)HexCharToByte((char)c);
  23240. }
  23241. unsigned char *wolfSSL_OPENSSL_hexstr2buf(const char *str, long *len)
  23242. {
  23243. unsigned char* targetBuf;
  23244. int srcDigitHigh = 0;
  23245. int srcDigitLow = 0;
  23246. size_t srcLen;
  23247. size_t srcIdx = 0;
  23248. long targetIdx = 0;
  23249. srcLen = XSTRLEN(str);
  23250. targetBuf = (unsigned char*)XMALLOC(srcLen / 2, NULL, DYNAMIC_TYPE_OPENSSL);
  23251. if (targetBuf == NULL) {
  23252. return NULL;
  23253. }
  23254. while (srcIdx < srcLen) {
  23255. if (str[srcIdx] == ':') {
  23256. srcIdx++;
  23257. continue;
  23258. }
  23259. srcDigitHigh = wolfSSL_OPENSSL_hexchar2int(str[srcIdx++]);
  23260. srcDigitLow = wolfSSL_OPENSSL_hexchar2int(str[srcIdx++]);
  23261. if (srcDigitHigh < 0 || srcDigitLow < 0) {
  23262. WOLFSSL_MSG("Invalid hex character.");
  23263. XFREE(targetBuf, NULL, DYNAMIC_TYPE_OPENSSL);
  23264. return NULL;
  23265. }
  23266. targetBuf[targetIdx++] = (unsigned char)((srcDigitHigh << 4) | srcDigitLow);
  23267. }
  23268. if (len != NULL)
  23269. *len = targetIdx;
  23270. return targetBuf;
  23271. }
  23272. int wolfSSL_OPENSSL_init_ssl(word64 opts, const OPENSSL_INIT_SETTINGS *settings)
  23273. {
  23274. (void)opts;
  23275. (void)settings;
  23276. return wolfSSL_library_init();
  23277. }
  23278. int wolfSSL_OPENSSL_init_crypto(word64 opts, const OPENSSL_INIT_SETTINGS* settings)
  23279. {
  23280. (void)opts;
  23281. (void)settings;
  23282. return wolfSSL_library_init();
  23283. }
  23284. #if defined(WOLFSSL_KEY_GEN) && defined(WOLFSSL_PEM_TO_DER)
  23285. int EncryptDerKey(byte *der, int *derSz, const EVP_CIPHER* cipher,
  23286. unsigned char* passwd, int passwdSz, byte **cipherInfo,
  23287. int maxDerSz)
  23288. {
  23289. int ret, paddingSz;
  23290. word32 idx, cipherInfoSz;
  23291. #ifdef WOLFSSL_SMALL_STACK
  23292. EncryptedInfo* info = NULL;
  23293. #else
  23294. EncryptedInfo info[1];
  23295. #endif
  23296. WOLFSSL_ENTER("EncryptDerKey");
  23297. if (der == NULL || derSz == NULL || cipher == NULL ||
  23298. passwd == NULL || cipherInfo == NULL)
  23299. return BAD_FUNC_ARG;
  23300. #ifdef WOLFSSL_SMALL_STACK
  23301. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  23302. DYNAMIC_TYPE_ENCRYPTEDINFO);
  23303. if (info == NULL) {
  23304. WOLFSSL_MSG("malloc failed");
  23305. return WOLFSSL_FAILURE;
  23306. }
  23307. #endif
  23308. XMEMSET(info, 0, sizeof(EncryptedInfo));
  23309. /* set the cipher name on info */
  23310. XSTRNCPY(info->name, cipher, NAME_SZ-1);
  23311. info->name[NAME_SZ-1] = '\0'; /* null term */
  23312. ret = wc_EncryptedInfoGet(info, info->name);
  23313. if (ret != 0) {
  23314. WOLFSSL_MSG("unsupported cipher");
  23315. #ifdef WOLFSSL_SMALL_STACK
  23316. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  23317. #endif
  23318. return WOLFSSL_FAILURE;
  23319. }
  23320. /* Generate a random salt */
  23321. if (wolfSSL_RAND_bytes(info->iv, info->ivSz) != WOLFSSL_SUCCESS) {
  23322. WOLFSSL_MSG("generate iv failed");
  23323. #ifdef WOLFSSL_SMALL_STACK
  23324. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  23325. #endif
  23326. return WOLFSSL_FAILURE;
  23327. }
  23328. /* add the padding before encryption */
  23329. paddingSz = ((*derSz)/info->ivSz + 1) * info->ivSz - (*derSz);
  23330. if (paddingSz == 0)
  23331. paddingSz = info->ivSz;
  23332. if (maxDerSz < *derSz + paddingSz) {
  23333. WOLFSSL_MSG("not enough DER buffer allocated");
  23334. #ifdef WOLFSSL_SMALL_STACK
  23335. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  23336. #endif
  23337. return WOLFSSL_FAILURE;
  23338. }
  23339. XMEMSET(der+(*derSz), (byte)paddingSz, paddingSz);
  23340. (*derSz) += paddingSz;
  23341. /* encrypt buffer */
  23342. if (wc_BufferKeyEncrypt(info, der, *derSz, passwd, passwdSz, WC_MD5) != 0) {
  23343. WOLFSSL_MSG("encrypt key failed");
  23344. #ifdef WOLFSSL_SMALL_STACK
  23345. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  23346. #endif
  23347. return WOLFSSL_FAILURE;
  23348. }
  23349. /* create cipher info : 'cipher_name,Salt(hex)' */
  23350. cipherInfoSz = (word32)(2*info->ivSz + XSTRLEN(info->name) + 2);
  23351. *cipherInfo = (byte*)XMALLOC(cipherInfoSz, NULL,
  23352. DYNAMIC_TYPE_STRING);
  23353. if (*cipherInfo == NULL) {
  23354. WOLFSSL_MSG("malloc failed");
  23355. #ifdef WOLFSSL_SMALL_STACK
  23356. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  23357. #endif
  23358. return WOLFSSL_FAILURE;
  23359. }
  23360. XSTRLCPY((char*)*cipherInfo, info->name, cipherInfoSz);
  23361. XSTRLCAT((char*)*cipherInfo, ",", cipherInfoSz);
  23362. idx = (word32)XSTRLEN((char*)*cipherInfo);
  23363. cipherInfoSz -= idx;
  23364. ret = Base16_Encode(info->iv, info->ivSz, *cipherInfo+idx, &cipherInfoSz);
  23365. #ifdef WOLFSSL_SMALL_STACK
  23366. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  23367. #endif
  23368. if (ret != 0) {
  23369. WOLFSSL_MSG("Base16_Encode failed");
  23370. XFREE(*cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  23371. return WOLFSSL_FAILURE;
  23372. }
  23373. return WOLFSSL_SUCCESS;
  23374. }
  23375. #endif /* WOLFSSL_KEY_GEN || WOLFSSL_PEM_TO_DER */
  23376. #ifndef NO_BIO
  23377. static int pem_write_bio_pubkey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key)
  23378. {
  23379. int ret;
  23380. int pemSz;
  23381. byte* pemBuf;
  23382. int derSz = 0;
  23383. byte* derBuf = NULL;
  23384. if (bio == NULL || key == NULL) {
  23385. WOLFSSL_MSG("Bad parameters");
  23386. return WOLFSSL_FAILURE;
  23387. }
  23388. switch (key->type) {
  23389. #if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) && !defined(HAVE_USER_RSA)
  23390. case EVP_PKEY_RSA:
  23391. if ((derSz = wolfSSL_RSA_To_Der(key->rsa, &derBuf, 1, bio->heap))
  23392. < 0) {
  23393. WOLFSSL_MSG("wolfSSL_RSA_To_Der failed");
  23394. break;
  23395. }
  23396. break;
  23397. #endif /* WOLFSSL_KEY_GEN && !NO_RSA && !HAVE_USER_RSA */
  23398. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
  23399. defined(WOLFSSL_CERT_GEN))
  23400. case EVP_PKEY_DSA:
  23401. if (key->dsa == NULL) {
  23402. WOLFSSL_MSG("key->dsa is null");
  23403. break;
  23404. }
  23405. derSz = MAX_DSA_PUBKEY_SZ;
  23406. derBuf = (byte*)XMALLOC(derSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23407. if (derBuf == NULL) {
  23408. WOLFSSL_MSG("malloc failed");
  23409. break;
  23410. }
  23411. /* Key to DER */
  23412. derSz = wc_DsaKeyToPublicDer((DsaKey*)key->dsa->internal, derBuf,
  23413. derSz);
  23414. if (derSz < 0) {
  23415. WOLFSSL_MSG("wc_DsaKeyToDer failed");
  23416. break;
  23417. }
  23418. break;
  23419. #endif /* !NO_DSA && !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
  23420. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  23421. case EVP_PKEY_EC:
  23422. {
  23423. if (key->ecc == NULL) {
  23424. WOLFSSL_MSG("key->ecc is null");
  23425. break;
  23426. }
  23427. derSz = wc_EccPublicKeyDerSize((ecc_key*)key->ecc->internal, 1);
  23428. if (derSz <= 0) {
  23429. WOLFSSL_MSG("wc_EccPublicKeyDerSize failed");
  23430. break;
  23431. }
  23432. derBuf = (byte*)XMALLOC(derSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23433. if (derBuf == NULL) {
  23434. WOLFSSL_MSG("malloc failed");
  23435. break;
  23436. }
  23437. derSz = wc_EccPublicKeyToDer((ecc_key*)key->ecc->internal, derBuf,
  23438. derSz, 1);
  23439. if (derSz < 0) {
  23440. WOLFSSL_MSG("wc_EccPublicKeyToDer failed");
  23441. break;
  23442. }
  23443. break;
  23444. }
  23445. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  23446. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  23447. case EVP_PKEY_DH:
  23448. WOLFSSL_MSG("Writing DH PUBKEY not supported!");
  23449. break;
  23450. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  23451. default:
  23452. WOLFSSL_MSG("Unknown Key type!");
  23453. break;
  23454. }
  23455. if (derBuf == NULL || derSz <= 0) {
  23456. if (derBuf != NULL)
  23457. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_DER);
  23458. return WOLFSSL_FAILURE;
  23459. }
  23460. pemSz = wc_DerToPem(derBuf, derSz, NULL, 0, PUBLICKEY_TYPE);
  23461. if (pemSz < 0) {
  23462. WOLFSSL_LEAVE("pem_write_bio_pubkey", pemSz);
  23463. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_DER);
  23464. return WOLFSSL_FAILURE;
  23465. }
  23466. pemBuf = (byte*)XMALLOC(pemSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23467. if (pemBuf == NULL) {
  23468. WOLFSSL_LEAVE("pem_write_bio_pubkey", pemSz);
  23469. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_DER);
  23470. return WOLFSSL_FAILURE;
  23471. }
  23472. ret = wc_DerToPem(derBuf, derSz, pemBuf, pemSz, PUBLICKEY_TYPE);
  23473. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_DER);
  23474. if (ret < 0) {
  23475. WOLFSSL_LEAVE("pem_write_bio_pubkey", ret);
  23476. XFREE(pemBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23477. return WOLFSSL_FAILURE;
  23478. }
  23479. ret = wolfSSL_BIO_write(bio, pemBuf, pemSz);
  23480. XFREE(pemBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23481. if (ret != pemSz) {
  23482. WOLFSSL_MSG("Unable to write full PEM to BIO");
  23483. return WOLFSSL_FAILURE;
  23484. }
  23485. return WOLFSSL_SUCCESS;
  23486. }
  23487. /* Takes a public key and writes it out to a WOLFSSL_BIO
  23488. * Returns WOLFSSL_SUCCESS or WOLFSSL_FAILURE
  23489. */
  23490. int wolfSSL_PEM_write_bio_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key)
  23491. {
  23492. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PUBKEY");
  23493. return pem_write_bio_pubkey(bio, key);
  23494. }
  23495. /* Takes a private key and writes it out to a WOLFSSL_BIO
  23496. * Returns WOLFSSL_SUCCESS or WOLFSSL_FAILURE
  23497. */
  23498. int wolfSSL_PEM_write_bio_PrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key,
  23499. const WOLFSSL_EVP_CIPHER* cipher,
  23500. unsigned char* passwd, int len,
  23501. wc_pem_password_cb* cb, void* arg)
  23502. {
  23503. byte* keyDer;
  23504. int pemSz;
  23505. int type;
  23506. int ret;
  23507. byte* tmp;
  23508. (void)cipher;
  23509. (void)passwd;
  23510. (void)len;
  23511. (void)cb;
  23512. (void)arg;
  23513. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PrivateKey");
  23514. if (bio == NULL || key == NULL) {
  23515. WOLFSSL_MSG("Bad Function Arguments");
  23516. return WOLFSSL_FAILURE;
  23517. }
  23518. keyDer = (byte*)key->pkey.ptr;
  23519. switch (key->type) {
  23520. #ifndef NO_RSA
  23521. case EVP_PKEY_RSA:
  23522. type = PRIVATEKEY_TYPE;
  23523. break;
  23524. #endif
  23525. #ifndef NO_DSA
  23526. case EVP_PKEY_DSA:
  23527. type = DSA_PRIVATEKEY_TYPE;
  23528. break;
  23529. #endif
  23530. #ifdef HAVE_ECC
  23531. case EVP_PKEY_EC:
  23532. type = ECC_PRIVATEKEY_TYPE;
  23533. break;
  23534. #endif
  23535. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  23536. case EVP_PKEY_DH:
  23537. type = DH_PRIVATEKEY_TYPE;
  23538. break;
  23539. #endif
  23540. default:
  23541. WOLFSSL_MSG("Unknown Key type!");
  23542. type = PRIVATEKEY_TYPE;
  23543. }
  23544. pemSz = wc_DerToPem(keyDer, key->pkey_sz, NULL, 0, type);
  23545. if (pemSz < 0) {
  23546. WOLFSSL_LEAVE("wolfSSL_PEM_write_bio_PrivateKey", pemSz);
  23547. return WOLFSSL_FAILURE;
  23548. }
  23549. tmp = (byte*)XMALLOC(pemSz, bio->heap, DYNAMIC_TYPE_OPENSSL);
  23550. if (tmp == NULL) {
  23551. return MEMORY_E;
  23552. }
  23553. ret = wc_DerToPem(keyDer, key->pkey_sz, tmp, pemSz, type);
  23554. if (ret < 0) {
  23555. WOLFSSL_LEAVE("wolfSSL_PEM_write_bio_PrivateKey", ret);
  23556. XFREE(tmp, bio->heap, DYNAMIC_TYPE_OPENSSL);
  23557. return WOLFSSL_FAILURE;
  23558. }
  23559. ret = wolfSSL_BIO_write(bio, tmp, pemSz);
  23560. XFREE(tmp, bio->heap, DYNAMIC_TYPE_OPENSSL);
  23561. if (ret != pemSz) {
  23562. WOLFSSL_MSG("Unable to write full PEM to BIO");
  23563. return WOLFSSL_FAILURE;
  23564. }
  23565. return WOLFSSL_SUCCESS;
  23566. }
  23567. #endif /* !NO_BIO */
  23568. /* Colon separated list of <public key>+<digest> algorithms.
  23569. * Replaces list in context.
  23570. */
  23571. int wolfSSL_CTX_set1_sigalgs_list(WOLFSSL_CTX* ctx, const char* list)
  23572. {
  23573. WOLFSSL_MSG("wolfSSL_CTX_set1_sigalg_list");
  23574. if (ctx == NULL || list == NULL) {
  23575. WOLFSSL_MSG("Bad function arguments");
  23576. return WOLFSSL_FAILURE;
  23577. }
  23578. /* alloc/init on demand only */
  23579. if (ctx->suites == NULL) {
  23580. ctx->suites = (Suites*)XMALLOC(sizeof(Suites), ctx->heap,
  23581. DYNAMIC_TYPE_SUITES);
  23582. if (ctx->suites == NULL) {
  23583. WOLFSSL_MSG("Memory alloc for Suites failed");
  23584. return WOLFSSL_FAILURE;
  23585. }
  23586. XMEMSET(ctx->suites, 0, sizeof(Suites));
  23587. }
  23588. return SetSuitesHashSigAlgo(ctx->suites, list);
  23589. }
  23590. /* Colon separated list of <public key>+<digest> algorithms.
  23591. * Replaces list in SSL.
  23592. */
  23593. int wolfSSL_set1_sigalgs_list(WOLFSSL* ssl, const char* list)
  23594. {
  23595. WOLFSSL_MSG("wolfSSL_set1_sigalg_list");
  23596. if (ssl == NULL) {
  23597. WOLFSSL_MSG("Bad function arguments");
  23598. return WOLFSSL_FAILURE;
  23599. }
  23600. #ifdef SINGLE_THREADED
  23601. if (ssl->ctx->suites == ssl->suites) {
  23602. ssl->suites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap,
  23603. DYNAMIC_TYPE_SUITES);
  23604. if (ssl->suites == NULL) {
  23605. WOLFSSL_MSG("Suites Memory error");
  23606. return MEMORY_E;
  23607. }
  23608. *ssl->suites = *ssl->ctx->suites;
  23609. ssl->options.ownSuites = 1;
  23610. }
  23611. #endif
  23612. if (ssl == NULL || list == NULL) {
  23613. WOLFSSL_MSG("Bad function arguments");
  23614. return WOLFSSL_FAILURE;
  23615. }
  23616. return SetSuitesHashSigAlgo(ssl->suites, list);
  23617. }
  23618. struct WOLFSSL_HashSigInfo {
  23619. int hashAlgo;
  23620. int sigAlgo;
  23621. int nid;
  23622. } wolfssl_hash_sig_info[] =
  23623. {
  23624. #ifndef NO_RSA
  23625. #ifndef NO_SHA256
  23626. { sha256_mac, rsa_sa_algo, CTC_SHA256wRSA },
  23627. #endif
  23628. #ifdef WOLFSSL_SHA384
  23629. { sha384_mac, rsa_sa_algo, CTC_SHA384wRSA },
  23630. #endif
  23631. #ifdef WOLFSSL_SHA512
  23632. { sha512_mac, rsa_sa_algo, CTC_SHA512wRSA },
  23633. #endif
  23634. #ifdef WOLFSSL_SHA224
  23635. { sha224_mac, rsa_sa_algo, CTC_SHA224wRSA },
  23636. #endif
  23637. #ifndef NO_SHA
  23638. { sha_mac, rsa_sa_algo, CTC_SHAwRSA },
  23639. #endif
  23640. #ifdef WC_RSA_PSS
  23641. #ifndef NO_SHA256
  23642. { sha256_mac, rsa_pss_sa_algo, CTC_SHA256wRSA },
  23643. #endif
  23644. #ifdef WOLFSSL_SHA384
  23645. { sha384_mac, rsa_pss_sa_algo, CTC_SHA384wRSA },
  23646. #endif
  23647. #ifdef WOLFSSL_SHA512
  23648. { sha512_mac, rsa_pss_sa_algo, CTC_SHA512wRSA },
  23649. #endif
  23650. #ifdef WOLFSSL_SHA224
  23651. { sha224_mac, rsa_pss_sa_algo, CTC_SHA224wRSA },
  23652. #endif
  23653. #endif
  23654. #endif
  23655. #ifdef HAVE_ECC
  23656. #ifndef NO_SHA256
  23657. { sha256_mac, ecc_dsa_sa_algo, CTC_SHA256wECDSA },
  23658. #endif
  23659. #ifdef WOLFSSL_SHA384
  23660. { sha384_mac, ecc_dsa_sa_algo, CTC_SHA384wECDSA },
  23661. #endif
  23662. #ifdef WOLFSSL_SHA512
  23663. { sha512_mac, ecc_dsa_sa_algo, CTC_SHA512wECDSA },
  23664. #endif
  23665. #ifdef WOLFSSL_SHA224
  23666. { sha224_mac, ecc_dsa_sa_algo, CTC_SHA224wECDSA },
  23667. #endif
  23668. #ifndef NO_SHA
  23669. { sha_mac, ecc_dsa_sa_algo, CTC_SHAwECDSA },
  23670. #endif
  23671. #endif
  23672. #ifdef HAVE_ED25519
  23673. { no_mac, ed25519_sa_algo, CTC_ED25519 },
  23674. #endif
  23675. #ifdef HAVE_ED448
  23676. { no_mac, ed448_sa_algo, CTC_ED448 },
  23677. #endif
  23678. #ifdef HAVE_PQC
  23679. #ifdef HAVE_FALCON
  23680. { no_mac, falcon_level1_sa_algo, CTC_FALCON_LEVEL1 },
  23681. { no_mac, falcon_level5_sa_algo, CTC_FALCON_LEVEL5 },
  23682. #endif /* HAVE_FALCON */
  23683. #ifdef HAVE_DILITHIUM
  23684. { no_mac, dilithium_level2_sa_algo, CTC_DILITHIUM_LEVEL2 },
  23685. { no_mac, dilithium_level3_sa_algo, CTC_DILITHIUM_LEVEL3 },
  23686. { no_mac, dilithium_level5_sa_algo, CTC_DILITHIUM_LEVEL5 },
  23687. { no_mac, dilithium_aes_level2_sa_algo, CTC_DILITHIUM_AES_LEVEL2 },
  23688. { no_mac, dilithium_aes_level3_sa_algo, CTC_DILITHIUM_AES_LEVEL3 },
  23689. { no_mac, dilithium_aes_level5_sa_algo, CTC_DILITHIUM_AES_LEVEL5 },
  23690. #endif /* HAVE_DILITHIUM */
  23691. #endif /* HAVE_PQC */
  23692. #ifndef NO_DSA
  23693. #ifndef NO_SHA
  23694. { sha_mac, dsa_sa_algo, CTC_SHAwDSA },
  23695. #endif
  23696. #endif
  23697. };
  23698. #define WOLFSSL_HASH_SIG_INFO_SZ \
  23699. (int)(sizeof(wolfssl_hash_sig_info)/sizeof(*wolfssl_hash_sig_info))
  23700. int wolfSSL_get_signature_nid(WOLFSSL *ssl, int* nid)
  23701. {
  23702. int i;
  23703. int ret = WOLFSSL_FAILURE;
  23704. WOLFSSL_MSG("wolfSSL_get_signature_nid");
  23705. if (ssl == NULL) {
  23706. WOLFSSL_MSG("Bad function arguments");
  23707. return WOLFSSL_FAILURE;
  23708. }
  23709. for (i = 0; i < WOLFSSL_HASH_SIG_INFO_SZ; i++) {
  23710. if (ssl->suites->hashAlgo == wolfssl_hash_sig_info[i].hashAlgo &&
  23711. ssl->suites->sigAlgo == wolfssl_hash_sig_info[i].sigAlgo) {
  23712. *nid = wolfssl_hash_sig_info[i].nid;
  23713. ret = WOLFSSL_SUCCESS;
  23714. break;
  23715. }
  23716. }
  23717. return ret;
  23718. }
  23719. #ifdef HAVE_ECC
  23720. #if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
  23721. static int populate_groups(int* groups, int max_count, char *list)
  23722. {
  23723. char *end;
  23724. int len;
  23725. int count = 0;
  23726. const WOLF_EC_NIST_NAME* nist_name;
  23727. if (!groups || !list) {
  23728. return -1;
  23729. }
  23730. for (end = list; ; list = ++end) {
  23731. if (count > max_count) {
  23732. WOLFSSL_MSG("Too many curves in list");
  23733. return -1;
  23734. }
  23735. while (*end != ':' && *end != '\0') end++;
  23736. len = (int)(end - list); /* end points to char after end
  23737. * of curve name so no need for -1 */
  23738. if ((len < kNistCurves_MIN_NAME_LEN) ||
  23739. (len > kNistCurves_MAX_NAME_LEN)) {
  23740. WOLFSSL_MSG("Unrecognized curve name in list");
  23741. return -1;
  23742. }
  23743. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  23744. if (len == nist_name->name_len &&
  23745. XSTRNCMP(list, nist_name->name, nist_name->name_len) == 0) {
  23746. break;
  23747. }
  23748. }
  23749. if (!nist_name->name) {
  23750. WOLFSSL_MSG("Unrecognized curve name in list");
  23751. return -1;
  23752. }
  23753. groups[count++] = nist_name->nid;
  23754. if (*end == '\0') break;
  23755. }
  23756. return count;
  23757. }
  23758. int wolfSSL_CTX_set1_groups_list(WOLFSSL_CTX *ctx, char *list)
  23759. {
  23760. int groups[WOLFSSL_MAX_GROUP_COUNT];
  23761. int count;
  23762. if (!ctx || !list) {
  23763. return WOLFSSL_FAILURE;
  23764. }
  23765. if ((count = populate_groups(groups,
  23766. WOLFSSL_MAX_GROUP_COUNT, list)) == -1) {
  23767. return WOLFSSL_FAILURE;
  23768. }
  23769. return wolfSSL_CTX_set1_groups(ctx, groups, count);
  23770. }
  23771. int wolfSSL_set1_groups_list(WOLFSSL *ssl, char *list)
  23772. {
  23773. int groups[WOLFSSL_MAX_GROUP_COUNT];
  23774. int count;
  23775. if (!ssl || !list) {
  23776. return WOLFSSL_FAILURE;
  23777. }
  23778. if ((count = populate_groups(groups,
  23779. WOLFSSL_MAX_GROUP_COUNT, list)) == -1) {
  23780. return WOLFSSL_FAILURE;
  23781. }
  23782. return wolfSSL_set1_groups(ssl, groups, count);
  23783. }
  23784. #endif /* WOLFSSL_TLS13 */
  23785. #endif /* HAVE_ECC */
  23786. #ifndef NO_BIO
  23787. /* Number of bytes to read from a file at a time. */
  23788. #define PEM_READ_FILE_CHUNK_SZ 100
  23789. static int pem_read_bio_file(WOLFSSL_BIO* bio, char** pem)
  23790. {
  23791. int ret = 0;
  23792. int idx = 0;
  23793. int sz = PEM_READ_FILE_CHUNK_SZ; /* read from file by chunks */
  23794. int memSz = 0;
  23795. char* mem = NULL;
  23796. char* tmp;
  23797. /* Allocate a chunk to read into. */
  23798. tmp = (char*)XMALLOC(sz, bio->heap, DYNAMIC_TYPE_OPENSSL);
  23799. if (tmp == NULL) {
  23800. WOLFSSL_MSG("Memory error");
  23801. ret = MEMORY_E;
  23802. }
  23803. while (ret == 0 && (sz = wolfSSL_BIO_read(bio, tmp, sz)) > 0) {
  23804. char* newMem;
  23805. /* sanity check for signed overflow */
  23806. if (memSz + sz < 0) {
  23807. break;
  23808. }
  23809. /* Reallocate to make space for read data. */
  23810. newMem = (char*)XREALLOC(mem, memSz + sz, bio->heap,
  23811. DYNAMIC_TYPE_OPENSSL);
  23812. if (newMem == NULL) {
  23813. WOLFSSL_MSG("Memory error");
  23814. ret = MEMORY_E;
  23815. break;
  23816. }
  23817. mem = newMem;
  23818. /* Copy in new data. */
  23819. XMEMCPY(mem + idx, tmp, sz);
  23820. memSz += sz;
  23821. idx += sz;
  23822. sz = PEM_READ_FILE_CHUNK_SZ; /* read another chunk from file */
  23823. }
  23824. XFREE(tmp, bio->heap, DYNAMIC_TYPE_OPENSSL);
  23825. tmp = NULL;
  23826. if (ret == 0) {
  23827. /* Check data was read. */
  23828. if (memSz <= 0) {
  23829. WOLFSSL_MSG("No data to read from bio");
  23830. ret = BUFFER_E;
  23831. }
  23832. else {
  23833. /* Return size of data read. */
  23834. ret = memSz;
  23835. }
  23836. }
  23837. /* Dispose of any allocated memory on error. */
  23838. if (ret < 0) {
  23839. XFREE(mem, bio->heap, DYNAMIC_TYPE_OPENSSL);
  23840. mem = NULL;
  23841. }
  23842. *pem = mem;
  23843. return ret;
  23844. }
  23845. static int pem_read_bio_pending(WOLFSSL_BIO* bio, int pendingSz, char** pem)
  23846. {
  23847. int ret = 0;
  23848. char* mem;
  23849. /* Allocate buffer to hold pending data. */
  23850. mem = (char*)XMALLOC(pendingSz, bio->heap, DYNAMIC_TYPE_OPENSSL);
  23851. if (mem == NULL) {
  23852. WOLFSSL_MSG("Memory error");
  23853. ret = MEMORY_E;
  23854. }
  23855. else if ((ret = wolfSSL_BIO_read(bio, mem, pendingSz)) <= 0) {
  23856. /* Pending data not read. */
  23857. XFREE(mem, bio->heap, DYNAMIC_TYPE_OPENSSL);
  23858. mem = NULL;
  23859. ret = MEMORY_E;
  23860. }
  23861. *pem = mem;
  23862. return ret;
  23863. }
  23864. static int pem_read_bio_key(WOLFSSL_BIO* bio, wc_pem_password_cb* cb,
  23865. void* pass, int keyType, int* eccFlag,
  23866. DerBuffer** der)
  23867. {
  23868. #ifdef WOLFSSL_SMALL_STACK
  23869. EncryptedInfo* info = NULL;
  23870. #else
  23871. EncryptedInfo info[1];
  23872. #endif /* WOLFSSL_SMALL_STACK */
  23873. wc_pem_password_cb* localCb = NULL;
  23874. char* mem = NULL;
  23875. int ret;
  23876. if (cb != NULL) {
  23877. localCb = cb;
  23878. }
  23879. else if (pass != NULL) {
  23880. localCb = wolfSSL_PEM_def_callback;
  23881. }
  23882. if ((ret = wolfSSL_BIO_pending(bio)) > 0) {
  23883. ret = pem_read_bio_pending(bio, ret, &mem);
  23884. }
  23885. else if (bio->type == WOLFSSL_BIO_FILE) {
  23886. ret = pem_read_bio_file(bio, &mem);
  23887. }
  23888. else {
  23889. WOLFSSL_MSG("No data to read from bio");
  23890. ret = NOT_COMPILED_IN;
  23891. }
  23892. #ifdef WOLFSSL_SMALL_STACK
  23893. if (ret >= 0) {
  23894. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  23895. DYNAMIC_TYPE_TMP_BUFFER);
  23896. if (info == NULL) {
  23897. WOLFSSL_MSG("Error getting memory for EncryptedInfo structure");
  23898. XFREE(mem, bio->heap, DYNAMIC_TYPE_OPENSSL);
  23899. mem = NULL;
  23900. ret = MEMORY_E;
  23901. }
  23902. }
  23903. #endif /* WOLFSSL_SMALL_STACK */
  23904. if (ret >= 0) {
  23905. int memSz = ret;
  23906. XMEMSET(info, 0, sizeof(EncryptedInfo));
  23907. info->passwd_cb = localCb;
  23908. info->passwd_userdata = pass;
  23909. /* Do not strip PKCS8 header */
  23910. ret = PemToDer((const unsigned char*)mem, memSz, keyType, der, NULL,
  23911. info, eccFlag);
  23912. if (ret < 0) {
  23913. WOLFSSL_MSG("Bad PEM To DER");
  23914. }
  23915. /* Write left over data back to BIO if not a file BIO */
  23916. else if ((memSz - (int)info->consumed) > 0 &&
  23917. bio->type != WOLFSSL_BIO_FILE) {
  23918. if (wolfSSL_BIO_write(bio, mem + (int)info->consumed,
  23919. memSz - (int)info->consumed) <= 0) {
  23920. WOLFSSL_MSG("Unable to advance bio read pointer");
  23921. }
  23922. }
  23923. }
  23924. #ifdef WOLFSSL_SMALL_STACK
  23925. XFREE(info, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  23926. #endif
  23927. XFREE(mem, bio->heap, DYNAMIC_TYPE_OPENSSL);
  23928. return ret;
  23929. }
  23930. WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio,
  23931. WOLFSSL_EVP_PKEY** key,
  23932. wc_pem_password_cb* cb,
  23933. void* pass)
  23934. {
  23935. WOLFSSL_EVP_PKEY* pkey = NULL;
  23936. DerBuffer* der = NULL;
  23937. int keyFormat = 0;
  23938. int type = -1;
  23939. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_PrivateKey");
  23940. if (bio == NULL)
  23941. return pkey;
  23942. if (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE, &keyFormat,
  23943. &der) >= 0) {
  23944. const unsigned char* ptr = der->buffer;
  23945. if (keyFormat) {
  23946. /* keyFormat is Key_Sum enum */
  23947. if (keyFormat == RSAk)
  23948. type = EVP_PKEY_RSA;
  23949. else if (keyFormat == ECDSAk)
  23950. type = EVP_PKEY_EC;
  23951. else if (keyFormat == DSAk)
  23952. type = EVP_PKEY_DSA;
  23953. else if (keyFormat == DHk)
  23954. type = EVP_PKEY_DH;
  23955. }
  23956. else {
  23957. /* Default to RSA if format is not set */
  23958. type = EVP_PKEY_RSA;
  23959. }
  23960. /* handle case where reuse is attempted */
  23961. if (key != NULL && *key != NULL)
  23962. pkey = *key;
  23963. wolfSSL_d2i_PrivateKey(type, &pkey, &ptr, der->length);
  23964. if (pkey == NULL) {
  23965. WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY");
  23966. }
  23967. }
  23968. FreeDer(&der);
  23969. if (key != NULL && pkey != NULL)
  23970. *key = pkey;
  23971. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_PrivateKey", 0);
  23972. return pkey;
  23973. }
  23974. WOLFSSL_EVP_PKEY *wolfSSL_PEM_read_bio_PUBKEY(WOLFSSL_BIO* bio,
  23975. WOLFSSL_EVP_PKEY **key,
  23976. wc_pem_password_cb *cb,
  23977. void *pass)
  23978. {
  23979. WOLFSSL_EVP_PKEY* pkey = NULL;
  23980. DerBuffer* der = NULL;
  23981. int keyFormat = 0;
  23982. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_PUBKEY");
  23983. if (bio == NULL)
  23984. return pkey;
  23985. if (pem_read_bio_key(bio, cb, pass, PUBLICKEY_TYPE, &keyFormat, &der) >= 0) {
  23986. const unsigned char* ptr = der->buffer;
  23987. /* handle case where reuse is attempted */
  23988. if (key != NULL && *key != NULL)
  23989. pkey = *key;
  23990. wolfSSL_d2i_PUBKEY(&pkey, &ptr, der->length);
  23991. if (pkey == NULL) {
  23992. WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY");
  23993. }
  23994. }
  23995. FreeDer(&der);
  23996. if (key != NULL && pkey != NULL)
  23997. *key = pkey;
  23998. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_PUBKEY", 0);
  23999. return pkey;
  24000. }
  24001. #if !defined(NO_FILESYSTEM)
  24002. WOLFSSL_EVP_PKEY *wolfSSL_PEM_read_PUBKEY(XFILE fp, WOLFSSL_EVP_PKEY **x,
  24003. wc_pem_password_cb *cb, void *u)
  24004. {
  24005. int err = 0;
  24006. WOLFSSL_EVP_PKEY* ret = NULL;
  24007. WOLFSSL_BIO* bio = NULL;
  24008. WOLFSSL_ENTER("wolfSSL_PEM_read_PUBKEY");
  24009. if (fp == XBADFILE) {
  24010. err = 1;
  24011. }
  24012. if (err == 0) {
  24013. bio = wolfSSL_BIO_new(wolfSSL_BIO_s_file());
  24014. err = bio == NULL;
  24015. }
  24016. if (err == 0) {
  24017. err = wolfSSL_BIO_set_fp(bio, fp, BIO_NOCLOSE) != WOLFSSL_SUCCESS;
  24018. }
  24019. if (err == 0) {
  24020. ret = wolfSSL_PEM_read_bio_PUBKEY(bio, x, cb, u);
  24021. }
  24022. if (bio != NULL) {
  24023. wolfSSL_BIO_free(bio);
  24024. }
  24025. WOLFSSL_LEAVE("wolfSSL_PEM_read_PUBKEY", 0);
  24026. return ret;
  24027. }
  24028. #endif /* NO_FILESYSTEM */
  24029. #endif /* !NO_BIO */
  24030. #endif /* OPENSSL_EXTRA */
  24031. #ifdef WOLFSSL_ALT_CERT_CHAINS
  24032. int wolfSSL_is_peer_alt_cert_chain(const WOLFSSL* ssl)
  24033. {
  24034. int isUsing = 0;
  24035. if (ssl)
  24036. isUsing = ssl->options.usingAltCertChain;
  24037. return isUsing;
  24038. }
  24039. #endif /* WOLFSSL_ALT_CERT_CHAINS */
  24040. #ifdef SESSION_CERTS
  24041. #ifdef WOLFSSL_ALT_CERT_CHAINS
  24042. /* Get peer's alternate certificate chain */
  24043. WOLFSSL_X509_CHAIN* wolfSSL_get_peer_alt_chain(WOLFSSL* ssl)
  24044. {
  24045. WOLFSSL_ENTER("wolfSSL_get_peer_alt_chain");
  24046. if (ssl)
  24047. return &ssl->session->altChain;
  24048. return 0;
  24049. }
  24050. #endif /* WOLFSSL_ALT_CERT_CHAINS */
  24051. /* Get peer's certificate chain */
  24052. WOLFSSL_X509_CHAIN* wolfSSL_get_peer_chain(WOLFSSL* ssl)
  24053. {
  24054. WOLFSSL_ENTER("wolfSSL_get_peer_chain");
  24055. if (ssl)
  24056. return &ssl->session->chain;
  24057. return 0;
  24058. }
  24059. /* Get peer's certificate chain total count */
  24060. int wolfSSL_get_chain_count(WOLFSSL_X509_CHAIN* chain)
  24061. {
  24062. WOLFSSL_ENTER("wolfSSL_get_chain_count");
  24063. if (chain)
  24064. return chain->count;
  24065. return 0;
  24066. }
  24067. /* Get peer's ASN.1 DER certificate at index (idx) length in bytes */
  24068. int wolfSSL_get_chain_length(WOLFSSL_X509_CHAIN* chain, int idx)
  24069. {
  24070. WOLFSSL_ENTER("wolfSSL_get_chain_length");
  24071. if (chain)
  24072. return chain->certs[idx].length;
  24073. return 0;
  24074. }
  24075. /* Get peer's ASN.1 DER certificate at index (idx) */
  24076. byte* wolfSSL_get_chain_cert(WOLFSSL_X509_CHAIN* chain, int idx)
  24077. {
  24078. WOLFSSL_ENTER("wolfSSL_get_chain_cert");
  24079. if (chain)
  24080. return chain->certs[idx].buffer;
  24081. return 0;
  24082. }
  24083. /* Get peer's wolfSSL X509 certificate at index (idx) */
  24084. WOLFSSL_X509* wolfSSL_get_chain_X509(WOLFSSL_X509_CHAIN* chain, int idx)
  24085. {
  24086. int ret;
  24087. WOLFSSL_X509* x509 = NULL;
  24088. #ifdef WOLFSSL_SMALL_STACK
  24089. DecodedCert* cert = NULL;
  24090. #else
  24091. DecodedCert cert[1];
  24092. #endif
  24093. WOLFSSL_ENTER("wolfSSL_get_chain_X509");
  24094. if (chain != NULL) {
  24095. #ifdef WOLFSSL_SMALL_STACK
  24096. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  24097. DYNAMIC_TYPE_DCERT);
  24098. if (cert != NULL)
  24099. #endif
  24100. {
  24101. InitDecodedCert(cert, chain->certs[idx].buffer,
  24102. chain->certs[idx].length, NULL);
  24103. if ((ret = ParseCertRelative(cert, CERT_TYPE, 0, NULL)) != 0) {
  24104. WOLFSSL_MSG("Failed to parse cert");
  24105. }
  24106. else {
  24107. x509 = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), NULL,
  24108. DYNAMIC_TYPE_X509);
  24109. if (x509 == NULL) {
  24110. WOLFSSL_MSG("Failed alloc X509");
  24111. }
  24112. else {
  24113. InitX509(x509, 1, NULL);
  24114. if ((ret = CopyDecodedToX509(x509, cert)) != 0) {
  24115. WOLFSSL_MSG("Failed to copy decoded");
  24116. wolfSSL_X509_free(x509);
  24117. x509 = NULL;
  24118. }
  24119. }
  24120. }
  24121. FreeDecodedCert(cert);
  24122. #ifdef WOLFSSL_SMALL_STACK
  24123. XFREE(cert, NULL, DYNAMIC_TYPE_DCERT);
  24124. #endif
  24125. }
  24126. }
  24127. (void)ret;
  24128. return x509;
  24129. }
  24130. /* Get peer's PEM certificate at index (idx), output to buffer if inLen big
  24131. enough else return error (-1). If buffer is NULL only calculate
  24132. outLen. Output length is in *outLen WOLFSSL_SUCCESS on ok */
  24133. int wolfSSL_get_chain_cert_pem(WOLFSSL_X509_CHAIN* chain, int idx,
  24134. unsigned char* buf, int inLen, int* outLen)
  24135. {
  24136. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  24137. const char* header = NULL;
  24138. const char* footer = NULL;
  24139. int headerLen;
  24140. int footerLen;
  24141. int i;
  24142. int err;
  24143. word32 szNeeded = 0;
  24144. WOLFSSL_ENTER("wolfSSL_get_chain_cert_pem");
  24145. if (!chain || !outLen || idx < 0 || idx >= wolfSSL_get_chain_count(chain))
  24146. return BAD_FUNC_ARG;
  24147. err = wc_PemGetHeaderFooter(CERT_TYPE, &header, &footer);
  24148. if (err != 0)
  24149. return err;
  24150. headerLen = (int)XSTRLEN(header);
  24151. footerLen = (int)XSTRLEN(footer);
  24152. /* Null output buffer return size needed in outLen */
  24153. if(!buf) {
  24154. if(Base64_Encode(chain->certs[idx].buffer, chain->certs[idx].length,
  24155. NULL, &szNeeded) != LENGTH_ONLY_E)
  24156. return WOLFSSL_FAILURE;
  24157. *outLen = szNeeded + headerLen + footerLen;
  24158. return LENGTH_ONLY_E;
  24159. }
  24160. /* don't even try if inLen too short */
  24161. if (inLen < headerLen + footerLen + chain->certs[idx].length)
  24162. return BAD_FUNC_ARG;
  24163. /* header */
  24164. if (XMEMCPY(buf, header, headerLen) == NULL)
  24165. return WOLFSSL_FATAL_ERROR;
  24166. i = headerLen;
  24167. /* body */
  24168. *outLen = inLen; /* input to Base64_Encode */
  24169. if ( (err = Base64_Encode(chain->certs[idx].buffer,
  24170. chain->certs[idx].length, buf + i, (word32*)outLen)) < 0)
  24171. return err;
  24172. i += *outLen;
  24173. /* footer */
  24174. if ( (i + footerLen) > inLen)
  24175. return BAD_FUNC_ARG;
  24176. if (XMEMCPY(buf + i, footer, footerLen) == NULL)
  24177. return WOLFSSL_FATAL_ERROR;
  24178. *outLen += headerLen + footerLen;
  24179. return WOLFSSL_SUCCESS;
  24180. #else
  24181. (void)chain;
  24182. (void)idx;
  24183. (void)buf;
  24184. (void)inLen;
  24185. (void)outLen;
  24186. return WOLFSSL_FAILURE;
  24187. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  24188. }
  24189. /* get session ID */
  24190. WOLFSSL_ABI
  24191. const byte* wolfSSL_get_sessionID(const WOLFSSL_SESSION* session)
  24192. {
  24193. WOLFSSL_ENTER("wolfSSL_get_sessionID");
  24194. session = ClientSessionToSession(session);
  24195. if (session)
  24196. return session->sessionID;
  24197. return NULL;
  24198. }
  24199. #endif /* SESSION_CERTS */
  24200. #ifdef HAVE_FUZZER
  24201. void wolfSSL_SetFuzzerCb(WOLFSSL* ssl, CallbackFuzzer cbf, void* fCtx)
  24202. {
  24203. if (ssl) {
  24204. ssl->fuzzerCb = cbf;
  24205. ssl->fuzzerCtx = fCtx;
  24206. }
  24207. }
  24208. #endif
  24209. #ifndef NO_CERTS
  24210. #ifdef HAVE_PK_CALLBACKS
  24211. #ifdef HAVE_ECC
  24212. void wolfSSL_CTX_SetEccKeyGenCb(WOLFSSL_CTX* ctx, CallbackEccKeyGen cb)
  24213. {
  24214. if (ctx)
  24215. ctx->EccKeyGenCb = cb;
  24216. }
  24217. void wolfSSL_SetEccKeyGenCtx(WOLFSSL* ssl, void *ctx)
  24218. {
  24219. if (ssl)
  24220. ssl->EccKeyGenCtx = ctx;
  24221. }
  24222. void* wolfSSL_GetEccKeyGenCtx(WOLFSSL* ssl)
  24223. {
  24224. if (ssl)
  24225. return ssl->EccKeyGenCtx;
  24226. return NULL;
  24227. }
  24228. void wolfSSL_CTX_SetEccSignCtx(WOLFSSL_CTX* ctx, void *userCtx)
  24229. {
  24230. if (ctx)
  24231. ctx->EccSignCtx = userCtx;
  24232. }
  24233. void* wolfSSL_CTX_GetEccSignCtx(WOLFSSL_CTX* ctx)
  24234. {
  24235. if (ctx)
  24236. return ctx->EccSignCtx;
  24237. return NULL;
  24238. }
  24239. WOLFSSL_ABI
  24240. void wolfSSL_CTX_SetEccSignCb(WOLFSSL_CTX* ctx, CallbackEccSign cb)
  24241. {
  24242. if (ctx)
  24243. ctx->EccSignCb = cb;
  24244. }
  24245. void wolfSSL_SetEccSignCtx(WOLFSSL* ssl, void *ctx)
  24246. {
  24247. if (ssl)
  24248. ssl->EccSignCtx = ctx;
  24249. }
  24250. void* wolfSSL_GetEccSignCtx(WOLFSSL* ssl)
  24251. {
  24252. if (ssl)
  24253. return ssl->EccSignCtx;
  24254. return NULL;
  24255. }
  24256. void wolfSSL_CTX_SetEccVerifyCb(WOLFSSL_CTX* ctx, CallbackEccVerify cb)
  24257. {
  24258. if (ctx)
  24259. ctx->EccVerifyCb = cb;
  24260. }
  24261. void wolfSSL_SetEccVerifyCtx(WOLFSSL* ssl, void *ctx)
  24262. {
  24263. if (ssl)
  24264. ssl->EccVerifyCtx = ctx;
  24265. }
  24266. void* wolfSSL_GetEccVerifyCtx(WOLFSSL* ssl)
  24267. {
  24268. if (ssl)
  24269. return ssl->EccVerifyCtx;
  24270. return NULL;
  24271. }
  24272. void wolfSSL_CTX_SetEccSharedSecretCb(WOLFSSL_CTX* ctx, CallbackEccSharedSecret cb)
  24273. {
  24274. if (ctx)
  24275. ctx->EccSharedSecretCb = cb;
  24276. }
  24277. void wolfSSL_SetEccSharedSecretCtx(WOLFSSL* ssl, void *ctx)
  24278. {
  24279. if (ssl)
  24280. ssl->EccSharedSecretCtx = ctx;
  24281. }
  24282. void* wolfSSL_GetEccSharedSecretCtx(WOLFSSL* ssl)
  24283. {
  24284. if (ssl)
  24285. return ssl->EccSharedSecretCtx;
  24286. return NULL;
  24287. }
  24288. #endif /* HAVE_ECC */
  24289. #ifdef HAVE_ED25519
  24290. void wolfSSL_CTX_SetEd25519SignCb(WOLFSSL_CTX* ctx, CallbackEd25519Sign cb)
  24291. {
  24292. if (ctx)
  24293. ctx->Ed25519SignCb = cb;
  24294. }
  24295. void wolfSSL_SetEd25519SignCtx(WOLFSSL* ssl, void *ctx)
  24296. {
  24297. if (ssl)
  24298. ssl->Ed25519SignCtx = ctx;
  24299. }
  24300. void* wolfSSL_GetEd25519SignCtx(WOLFSSL* ssl)
  24301. {
  24302. if (ssl)
  24303. return ssl->Ed25519SignCtx;
  24304. return NULL;
  24305. }
  24306. void wolfSSL_CTX_SetEd25519VerifyCb(WOLFSSL_CTX* ctx, CallbackEd25519Verify cb)
  24307. {
  24308. if (ctx)
  24309. ctx->Ed25519VerifyCb = cb;
  24310. }
  24311. void wolfSSL_SetEd25519VerifyCtx(WOLFSSL* ssl, void *ctx)
  24312. {
  24313. if (ssl)
  24314. ssl->Ed25519VerifyCtx = ctx;
  24315. }
  24316. void* wolfSSL_GetEd25519VerifyCtx(WOLFSSL* ssl)
  24317. {
  24318. if (ssl)
  24319. return ssl->Ed25519VerifyCtx;
  24320. return NULL;
  24321. }
  24322. #endif /* HAVE_ED25519 */
  24323. #ifdef HAVE_CURVE25519
  24324. void wolfSSL_CTX_SetX25519KeyGenCb(WOLFSSL_CTX* ctx,
  24325. CallbackX25519KeyGen cb)
  24326. {
  24327. if (ctx)
  24328. ctx->X25519KeyGenCb = cb;
  24329. }
  24330. void wolfSSL_SetX25519KeyGenCtx(WOLFSSL* ssl, void *ctx)
  24331. {
  24332. if (ssl)
  24333. ssl->X25519KeyGenCtx = ctx;
  24334. }
  24335. void* wolfSSL_GetX25519KeyGenCtx(WOLFSSL* ssl)
  24336. {
  24337. if (ssl)
  24338. return ssl->X25519KeyGenCtx;
  24339. return NULL;
  24340. }
  24341. void wolfSSL_CTX_SetX25519SharedSecretCb(WOLFSSL_CTX* ctx,
  24342. CallbackX25519SharedSecret cb)
  24343. {
  24344. if (ctx)
  24345. ctx->X25519SharedSecretCb = cb;
  24346. }
  24347. void wolfSSL_SetX25519SharedSecretCtx(WOLFSSL* ssl, void *ctx)
  24348. {
  24349. if (ssl)
  24350. ssl->X25519SharedSecretCtx = ctx;
  24351. }
  24352. void* wolfSSL_GetX25519SharedSecretCtx(WOLFSSL* ssl)
  24353. {
  24354. if (ssl)
  24355. return ssl->X25519SharedSecretCtx;
  24356. return NULL;
  24357. }
  24358. #endif /* HAVE_CURVE25519 */
  24359. #ifdef HAVE_ED448
  24360. void wolfSSL_CTX_SetEd448SignCb(WOLFSSL_CTX* ctx, CallbackEd448Sign cb)
  24361. {
  24362. if (ctx)
  24363. ctx->Ed448SignCb = cb;
  24364. }
  24365. void wolfSSL_SetEd448SignCtx(WOLFSSL* ssl, void *ctx)
  24366. {
  24367. if (ssl)
  24368. ssl->Ed448SignCtx = ctx;
  24369. }
  24370. void* wolfSSL_GetEd448SignCtx(WOLFSSL* ssl)
  24371. {
  24372. if (ssl)
  24373. return ssl->Ed448SignCtx;
  24374. return NULL;
  24375. }
  24376. void wolfSSL_CTX_SetEd448VerifyCb(WOLFSSL_CTX* ctx, CallbackEd448Verify cb)
  24377. {
  24378. if (ctx)
  24379. ctx->Ed448VerifyCb = cb;
  24380. }
  24381. void wolfSSL_SetEd448VerifyCtx(WOLFSSL* ssl, void *ctx)
  24382. {
  24383. if (ssl)
  24384. ssl->Ed448VerifyCtx = ctx;
  24385. }
  24386. void* wolfSSL_GetEd448VerifyCtx(WOLFSSL* ssl)
  24387. {
  24388. if (ssl)
  24389. return ssl->Ed448VerifyCtx;
  24390. return NULL;
  24391. }
  24392. #endif /* HAVE_ED448 */
  24393. #ifdef HAVE_CURVE448
  24394. void wolfSSL_CTX_SetX448KeyGenCb(WOLFSSL_CTX* ctx,
  24395. CallbackX448KeyGen cb)
  24396. {
  24397. if (ctx)
  24398. ctx->X448KeyGenCb = cb;
  24399. }
  24400. void wolfSSL_SetX448KeyGenCtx(WOLFSSL* ssl, void *ctx)
  24401. {
  24402. if (ssl)
  24403. ssl->X448KeyGenCtx = ctx;
  24404. }
  24405. void* wolfSSL_GetX448KeyGenCtx(WOLFSSL* ssl)
  24406. {
  24407. if (ssl)
  24408. return ssl->X448KeyGenCtx;
  24409. return NULL;
  24410. }
  24411. void wolfSSL_CTX_SetX448SharedSecretCb(WOLFSSL_CTX* ctx,
  24412. CallbackX448SharedSecret cb)
  24413. {
  24414. if (ctx)
  24415. ctx->X448SharedSecretCb = cb;
  24416. }
  24417. void wolfSSL_SetX448SharedSecretCtx(WOLFSSL* ssl, void *ctx)
  24418. {
  24419. if (ssl)
  24420. ssl->X448SharedSecretCtx = ctx;
  24421. }
  24422. void* wolfSSL_GetX448SharedSecretCtx(WOLFSSL* ssl)
  24423. {
  24424. if (ssl)
  24425. return ssl->X448SharedSecretCtx;
  24426. return NULL;
  24427. }
  24428. #endif /* HAVE_CURVE448 */
  24429. #ifndef NO_RSA
  24430. void wolfSSL_CTX_SetRsaSignCb(WOLFSSL_CTX* ctx, CallbackRsaSign cb)
  24431. {
  24432. if (ctx)
  24433. ctx->RsaSignCb = cb;
  24434. }
  24435. void wolfSSL_CTX_SetRsaSignCheckCb(WOLFSSL_CTX* ctx, CallbackRsaVerify cb)
  24436. {
  24437. if (ctx)
  24438. ctx->RsaSignCheckCb = cb;
  24439. }
  24440. void wolfSSL_SetRsaSignCtx(WOLFSSL* ssl, void *ctx)
  24441. {
  24442. if (ssl)
  24443. ssl->RsaSignCtx = ctx;
  24444. }
  24445. void* wolfSSL_GetRsaSignCtx(WOLFSSL* ssl)
  24446. {
  24447. if (ssl)
  24448. return ssl->RsaSignCtx;
  24449. return NULL;
  24450. }
  24451. void wolfSSL_CTX_SetRsaVerifyCb(WOLFSSL_CTX* ctx, CallbackRsaVerify cb)
  24452. {
  24453. if (ctx)
  24454. ctx->RsaVerifyCb = cb;
  24455. }
  24456. void wolfSSL_SetRsaVerifyCtx(WOLFSSL* ssl, void *ctx)
  24457. {
  24458. if (ssl)
  24459. ssl->RsaVerifyCtx = ctx;
  24460. }
  24461. void* wolfSSL_GetRsaVerifyCtx(WOLFSSL* ssl)
  24462. {
  24463. if (ssl)
  24464. return ssl->RsaVerifyCtx;
  24465. return NULL;
  24466. }
  24467. #ifdef WC_RSA_PSS
  24468. void wolfSSL_CTX_SetRsaPssSignCb(WOLFSSL_CTX* ctx, CallbackRsaPssSign cb)
  24469. {
  24470. if (ctx)
  24471. ctx->RsaPssSignCb = cb;
  24472. }
  24473. void wolfSSL_CTX_SetRsaPssSignCheckCb(WOLFSSL_CTX* ctx, CallbackRsaPssVerify cb)
  24474. {
  24475. if (ctx)
  24476. ctx->RsaPssSignCheckCb = cb;
  24477. }
  24478. void wolfSSL_SetRsaPssSignCtx(WOLFSSL* ssl, void *ctx)
  24479. {
  24480. if (ssl)
  24481. ssl->RsaPssSignCtx = ctx;
  24482. }
  24483. void* wolfSSL_GetRsaPssSignCtx(WOLFSSL* ssl)
  24484. {
  24485. if (ssl)
  24486. return ssl->RsaPssSignCtx;
  24487. return NULL;
  24488. }
  24489. void wolfSSL_CTX_SetRsaPssVerifyCb(WOLFSSL_CTX* ctx, CallbackRsaPssVerify cb)
  24490. {
  24491. if (ctx)
  24492. ctx->RsaPssVerifyCb = cb;
  24493. }
  24494. void wolfSSL_SetRsaPssVerifyCtx(WOLFSSL* ssl, void *ctx)
  24495. {
  24496. if (ssl)
  24497. ssl->RsaPssVerifyCtx = ctx;
  24498. }
  24499. void* wolfSSL_GetRsaPssVerifyCtx(WOLFSSL* ssl)
  24500. {
  24501. if (ssl)
  24502. return ssl->RsaPssVerifyCtx;
  24503. return NULL;
  24504. }
  24505. #endif /* WC_RSA_PSS */
  24506. void wolfSSL_CTX_SetRsaEncCb(WOLFSSL_CTX* ctx, CallbackRsaEnc cb)
  24507. {
  24508. if (ctx)
  24509. ctx->RsaEncCb = cb;
  24510. }
  24511. void wolfSSL_SetRsaEncCtx(WOLFSSL* ssl, void *ctx)
  24512. {
  24513. if (ssl)
  24514. ssl->RsaEncCtx = ctx;
  24515. }
  24516. void* wolfSSL_GetRsaEncCtx(WOLFSSL* ssl)
  24517. {
  24518. if (ssl)
  24519. return ssl->RsaEncCtx;
  24520. return NULL;
  24521. }
  24522. void wolfSSL_CTX_SetRsaDecCb(WOLFSSL_CTX* ctx, CallbackRsaDec cb)
  24523. {
  24524. if (ctx)
  24525. ctx->RsaDecCb = cb;
  24526. }
  24527. void wolfSSL_SetRsaDecCtx(WOLFSSL* ssl, void *ctx)
  24528. {
  24529. if (ssl)
  24530. ssl->RsaDecCtx = ctx;
  24531. }
  24532. void* wolfSSL_GetRsaDecCtx(WOLFSSL* ssl)
  24533. {
  24534. if (ssl)
  24535. return ssl->RsaDecCtx;
  24536. return NULL;
  24537. }
  24538. #endif /* NO_RSA */
  24539. /* callback for premaster secret generation */
  24540. void wolfSSL_CTX_SetGenPreMasterCb(WOLFSSL_CTX* ctx, CallbackGenPreMaster cb)
  24541. {
  24542. if (ctx)
  24543. ctx->GenPreMasterCb = cb;
  24544. }
  24545. /* Set premaster secret generation callback context */
  24546. void wolfSSL_SetGenPreMasterCtx(WOLFSSL* ssl, void *ctx)
  24547. {
  24548. if (ssl)
  24549. ssl->GenPreMasterCtx = ctx;
  24550. }
  24551. /* Get premaster secret generation callback context */
  24552. void* wolfSSL_GetGenPreMasterCtx(WOLFSSL* ssl)
  24553. {
  24554. if (ssl)
  24555. return ssl->GenPreMasterCtx;
  24556. return NULL;
  24557. }
  24558. /* callback for master secret generation */
  24559. void wolfSSL_CTX_SetGenMasterSecretCb(WOLFSSL_CTX* ctx, CallbackGenMasterSecret cb)
  24560. {
  24561. if (ctx)
  24562. ctx->GenMasterCb = cb;
  24563. }
  24564. /* Set master secret generation callback context */
  24565. void wolfSSL_SetGenMasterSecretCtx(WOLFSSL* ssl, void *ctx)
  24566. {
  24567. if (ssl)
  24568. ssl->GenMasterCtx = ctx;
  24569. }
  24570. /* Get master secret generation callback context */
  24571. void* wolfSSL_GetGenMasterSecretCtx(WOLFSSL* ssl)
  24572. {
  24573. if (ssl)
  24574. return ssl->GenMasterCtx;
  24575. return NULL;
  24576. }
  24577. /* callback for session key generation */
  24578. void wolfSSL_CTX_SetGenSessionKeyCb(WOLFSSL_CTX* ctx, CallbackGenSessionKey cb)
  24579. {
  24580. if (ctx)
  24581. ctx->GenSessionKeyCb = cb;
  24582. }
  24583. /* Set session key generation callback context */
  24584. void wolfSSL_SetGenSessionKeyCtx(WOLFSSL* ssl, void *ctx)
  24585. {
  24586. if (ssl)
  24587. ssl->GenSessionKeyCtx = ctx;
  24588. }
  24589. /* Get session key generation callback context */
  24590. void* wolfSSL_GetGenSessionKeyCtx(WOLFSSL* ssl)
  24591. {
  24592. if (ssl)
  24593. return ssl->GenSessionKeyCtx;
  24594. return NULL;
  24595. }
  24596. /* callback for setting encryption keys */
  24597. void wolfSSL_CTX_SetEncryptKeysCb(WOLFSSL_CTX* ctx, CallbackEncryptKeys cb)
  24598. {
  24599. if (ctx)
  24600. ctx->EncryptKeysCb = cb;
  24601. }
  24602. /* Set encryption keys callback context */
  24603. void wolfSSL_SetEncryptKeysCtx(WOLFSSL* ssl, void *ctx)
  24604. {
  24605. if (ssl)
  24606. ssl->EncryptKeysCtx = ctx;
  24607. }
  24608. /* Get encryption keys callback context */
  24609. void* wolfSSL_GetEncryptKeysCtx(WOLFSSL* ssl)
  24610. {
  24611. if (ssl)
  24612. return ssl->EncryptKeysCtx;
  24613. return NULL;
  24614. }
  24615. /* callback for Tls finished */
  24616. /* the callback can be used to build TLS Finished message if enabled */
  24617. void wolfSSL_CTX_SetTlsFinishedCb(WOLFSSL_CTX* ctx, CallbackTlsFinished cb)
  24618. {
  24619. if (ctx)
  24620. ctx->TlsFinishedCb = cb;
  24621. }
  24622. /* Set Tls finished callback context */
  24623. void wolfSSL_SetTlsFinishedCtx(WOLFSSL* ssl, void *ctx)
  24624. {
  24625. if (ssl)
  24626. ssl->TlsFinishedCtx = ctx;
  24627. }
  24628. /* Get Tls finished callback context */
  24629. void* wolfSSL_GetTlsFinishedCtx(WOLFSSL* ssl)
  24630. {
  24631. if (ssl)
  24632. return ssl->TlsFinishedCtx;
  24633. return NULL;
  24634. }
  24635. #if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
  24636. /* callback for verify data */
  24637. void wolfSSL_CTX_SetVerifyMacCb(WOLFSSL_CTX* ctx, CallbackVerifyMac cb)
  24638. {
  24639. if (ctx)
  24640. ctx->VerifyMacCb = cb;
  24641. }
  24642. /* Set set keys callback context */
  24643. void wolfSSL_SetVerifyMacCtx(WOLFSSL* ssl, void *ctx)
  24644. {
  24645. if (ssl)
  24646. ssl->VerifyMacCtx = ctx;
  24647. }
  24648. /* Get set keys callback context */
  24649. void* wolfSSL_GetVerifyMacCtx(WOLFSSL* ssl)
  24650. {
  24651. if (ssl)
  24652. return ssl->VerifyMacCtx;
  24653. return NULL;
  24654. }
  24655. #endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
  24656. #endif /* HAVE_PK_CALLBACKS */
  24657. #endif /* NO_CERTS */
  24658. #if defined(HAVE_PK_CALLBACKS) && !defined(NO_DH)
  24659. void wolfSSL_CTX_SetDhAgreeCb(WOLFSSL_CTX* ctx, CallbackDhAgree cb)
  24660. {
  24661. if (ctx)
  24662. ctx->DhAgreeCb = cb;
  24663. }
  24664. void wolfSSL_SetDhAgreeCtx(WOLFSSL* ssl, void *ctx)
  24665. {
  24666. if (ssl)
  24667. ssl->DhAgreeCtx = ctx;
  24668. }
  24669. void* wolfSSL_GetDhAgreeCtx(WOLFSSL* ssl)
  24670. {
  24671. if (ssl)
  24672. return ssl->DhAgreeCtx;
  24673. return NULL;
  24674. }
  24675. #endif /* HAVE_PK_CALLBACKS && !NO_DH */
  24676. #if defined(HAVE_PK_CALLBACKS) && defined(HAVE_HKDF)
  24677. void wolfSSL_CTX_SetHKDFExtractCb(WOLFSSL_CTX* ctx, CallbackHKDFExtract cb)
  24678. {
  24679. if (ctx)
  24680. ctx->HkdfExtractCb = cb;
  24681. }
  24682. void wolfSSL_SetHKDFExtractCtx(WOLFSSL* ssl, void *ctx)
  24683. {
  24684. if (ssl)
  24685. ssl->HkdfExtractCtx = ctx;
  24686. }
  24687. void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl)
  24688. {
  24689. if (ssl)
  24690. return ssl->HkdfExtractCtx;
  24691. return NULL;
  24692. }
  24693. #endif /* HAVE_PK_CALLBACKS && HAVE_HKDF */
  24694. #ifdef WOLFSSL_HAVE_WOLFSCEP
  24695. /* Used by autoconf to see if wolfSCEP is available */
  24696. void wolfSSL_wolfSCEP(void) {}
  24697. #endif
  24698. #ifdef WOLFSSL_HAVE_CERT_SERVICE
  24699. /* Used by autoconf to see if cert service is available */
  24700. void wolfSSL_cert_service(void) {}
  24701. #endif
  24702. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  24703. !defined(WOLFCRYPT_ONLY)
  24704. #ifndef NO_CERTS
  24705. #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  24706. /* Convert ASN1 input string into canonical ASN1 string */
  24707. /* , which has the following rules: */
  24708. /* convert to UTF8 */
  24709. /* convert to lower case */
  24710. /* multi-spaces collapsed */
  24711. /* @param asn_out a pointer to ASN1_STRING to be converted */
  24712. /* @param asn_in a pointer to input ASN1_STRING */
  24713. /* @return WOLFSSL_SUCCESS on successful converted, otherwise <=0 error code*/
  24714. int wolfSSL_ASN1_STRING_canon(WOLFSSL_ASN1_STRING* asn_out,
  24715. const WOLFSSL_ASN1_STRING* asn_in)
  24716. {
  24717. char* dst;
  24718. char* src;
  24719. int i, len;
  24720. WOLFSSL_ENTER("wolfSSL_ASN1_STRING_canon");
  24721. /* sanity check */
  24722. if (asn_out == NULL || asn_in == NULL) {
  24723. WOLFSSL_MSG("invalid function arguments");
  24724. return BAD_FUNC_ARG;
  24725. }
  24726. switch (asn_in->type) {
  24727. case MBSTRING_UTF8:
  24728. case V_ASN1_PRINTABLESTRING:
  24729. break;
  24730. default:
  24731. WOLFSSL_MSG("just copy string");
  24732. return wolfSSL_ASN1_STRING_copy(asn_out, asn_in);
  24733. }
  24734. /* type is set as UTF8 */
  24735. asn_out->type = MBSTRING_UTF8;
  24736. asn_out->length = wolfSSL_ASN1_STRING_to_UTF8(
  24737. (unsigned char**)&asn_out->data, (WOLFSSL_ASN1_STRING*)asn_in);
  24738. if (asn_out->length < 0) {
  24739. return WOLFSSL_FAILURE;
  24740. }
  24741. /* point to the last */
  24742. dst = asn_out->data + asn_out->length;
  24743. /* point to the start */
  24744. src = asn_out->data;
  24745. len = asn_out->length;
  24746. /* trimming spaces at the head and tail */
  24747. dst--;
  24748. for (; (len > 0 && XISSPACE(*dst)); len--) {
  24749. dst--;
  24750. }
  24751. for (; (len > 0 && XISSPACE(*src)); len--) {
  24752. src++;
  24753. }
  24754. /* point to the start */
  24755. dst = asn_out->data;
  24756. for (i = 0; i < len; dst++, i++) {
  24757. if (!XISASCII(*src)) {
  24758. /* keep non-ascii code */
  24759. *dst = *src++;
  24760. } else if (XISSPACE(*src)) {
  24761. *dst = 0x20; /* space */
  24762. /* remove the rest of spaces */
  24763. while (XISSPACE(*++src) && i++ < len);
  24764. } else {
  24765. *dst = (char)XTOLOWER((unsigned char)*src++);
  24766. }
  24767. }
  24768. /* put actual length */
  24769. asn_out->length = (int)(dst - asn_out->data);
  24770. return WOLFSSL_SUCCESS;
  24771. }
  24772. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
  24773. #if !defined(NO_FILESYSTEM)
  24774. #ifndef NO_BIO
  24775. WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_PrivateKey(XFILE fp,
  24776. WOLFSSL_EVP_PKEY **x, wc_pem_password_cb *cb, void *u)
  24777. {
  24778. int err = 0;
  24779. WOLFSSL_EVP_PKEY* ret = NULL;
  24780. WOLFSSL_BIO* bio = NULL;
  24781. WOLFSSL_ENTER("wolfSSL_PEM_read_PrivateKey");
  24782. if (fp == XBADFILE) {
  24783. err = 1;
  24784. }
  24785. if (err == 0) {
  24786. bio = wolfSSL_BIO_new(wolfSSL_BIO_s_file());
  24787. err = bio == NULL;
  24788. }
  24789. if (err == 0) {
  24790. err = wolfSSL_BIO_set_fp(bio, fp, BIO_NOCLOSE) != WOLFSSL_SUCCESS;
  24791. }
  24792. if (err == 0) {
  24793. ret = wolfSSL_PEM_read_bio_PrivateKey(bio, x, cb, u);
  24794. }
  24795. if (bio != NULL) {
  24796. wolfSSL_BIO_free(bio);
  24797. }
  24798. return ret;
  24799. }
  24800. #endif
  24801. #endif
  24802. #endif
  24803. #endif /* OPENSSL_ALL || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL*/
  24804. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
  24805. #define PEM_BEGIN "-----BEGIN "
  24806. #define PEM_BEGIN_SZ 11
  24807. #define PEM_END "-----END "
  24808. #define PEM_END_SZ 9
  24809. #define PEM_HDR_FIN "-----"
  24810. #define PEM_HDR_FIN_SZ 5
  24811. #define PEM_HDR_FIN_EOL_NEWLINE "-----\n"
  24812. #define PEM_HDR_FIN_EOL_NULL_TERM "-----\0"
  24813. #define PEM_HDR_FIN_EOL_SZ 6
  24814. #ifndef NO_BIO
  24815. int wolfSSL_PEM_read_bio(WOLFSSL_BIO* bio, char **name, char **header,
  24816. unsigned char **data, long *len)
  24817. {
  24818. int ret = WOLFSSL_SUCCESS;
  24819. char pem[256];
  24820. int pemLen;
  24821. char* p;
  24822. char* nameStr = NULL;
  24823. int nameLen = 0;
  24824. char* headerStr = NULL;
  24825. int headerLen;
  24826. int headerFound = 0;
  24827. unsigned char* der = NULL;
  24828. word32 derLen = 0;
  24829. if (bio == NULL || name == NULL || header == NULL || data == NULL ||
  24830. len == NULL) {
  24831. return WOLFSSL_FAILURE;
  24832. }
  24833. /* Find header line. */
  24834. pem[sizeof(pem) - 1] = '\0';
  24835. while ((pemLen = wolfSSL_BIO_gets(bio, pem, sizeof(pem) - 1)) > 0) {
  24836. if (XSTRNCMP(pem, PEM_BEGIN, PEM_BEGIN_SZ) == 0)
  24837. break;
  24838. }
  24839. if (pemLen <= 0)
  24840. ret = WOLFSSL_FAILURE;
  24841. /* Have a header line. */
  24842. if (ret == WOLFSSL_SUCCESS) {
  24843. while (pem[pemLen - 1] == '\r' || pem[pemLen - 1] == '\n')
  24844. pemLen--;
  24845. pem[pemLen] = '\0';
  24846. if (XSTRNCMP(pem + pemLen - PEM_HDR_FIN_SZ, PEM_HDR_FIN,
  24847. PEM_HDR_FIN_SZ) != 0) {
  24848. ret = WOLFSSL_FAILURE;
  24849. }
  24850. }
  24851. /* Get out name. */
  24852. if (ret == WOLFSSL_SUCCESS) {
  24853. nameLen = pemLen - PEM_BEGIN_SZ - PEM_HDR_FIN_SZ;
  24854. nameStr = (char*)XMALLOC(nameLen + 1, NULL,
  24855. DYNAMIC_TYPE_TMP_BUFFER);
  24856. if (nameStr == NULL)
  24857. ret = WOLFSSL_FAILURE;
  24858. }
  24859. if (ret == WOLFSSL_SUCCESS) {
  24860. XSTRNCPY(nameStr, pem + PEM_BEGIN_SZ, nameLen);
  24861. nameStr[nameLen] = '\0';
  24862. /* Get header of PEM - encryption header. */
  24863. headerLen = 0;
  24864. while ((pemLen = wolfSSL_BIO_gets(bio, pem, sizeof(pem) - 1)) > 0) {
  24865. while (pemLen > 0 && (pem[pemLen - 1] == '\r' ||
  24866. pem[pemLen - 1] == '\n')) {
  24867. pemLen--;
  24868. }
  24869. pem[pemLen++] = '\n';
  24870. pem[pemLen] = '\0';
  24871. /* Header separator is a blank line. */
  24872. if (pem[0] == '\n') {
  24873. headerFound = 1;
  24874. break;
  24875. }
  24876. /* Didn't find a blank line - no header. */
  24877. if (XSTRNCMP(pem, PEM_END, PEM_END_SZ) == 0) {
  24878. der = (unsigned char*)headerStr;
  24879. derLen = headerLen;
  24880. /* Empty header - empty string. */
  24881. headerStr = (char*)XMALLOC(1, NULL,
  24882. DYNAMIC_TYPE_TMP_BUFFER);
  24883. if (headerStr == NULL)
  24884. ret = WOLFSSL_FAILURE;
  24885. else
  24886. headerStr[0] = '\0';
  24887. break;
  24888. }
  24889. p = (char*)XREALLOC(headerStr, headerLen + pemLen + 1, NULL,
  24890. DYNAMIC_TYPE_TMP_BUFFER);
  24891. if (p == NULL) {
  24892. ret = WOLFSSL_FAILURE;
  24893. break;
  24894. }
  24895. headerStr = p;
  24896. XMEMCPY(headerStr + headerLen, pem, pemLen + 1);
  24897. headerLen += pemLen;
  24898. }
  24899. if (pemLen <= 0)
  24900. ret = WOLFSSL_FAILURE;
  24901. }
  24902. /* Get body of PEM - if there was a header */
  24903. if (ret == WOLFSSL_SUCCESS && headerFound) {
  24904. derLen = 0;
  24905. while ((pemLen = wolfSSL_BIO_gets(bio, pem, sizeof(pem) - 1)) > 0) {
  24906. while (pemLen > 0 && (pem[pemLen - 1] == '\r' ||
  24907. pem[pemLen - 1] == '\n')) {
  24908. pemLen--;
  24909. }
  24910. pem[pemLen++] = '\n';
  24911. pem[pemLen] = '\0';
  24912. if (XSTRNCMP(pem, PEM_END, PEM_END_SZ) == 0)
  24913. break;
  24914. p = (char*)XREALLOC(der, derLen + pemLen + 1, NULL,
  24915. DYNAMIC_TYPE_TMP_BUFFER);
  24916. if (p == NULL) {
  24917. ret = WOLFSSL_FAILURE;
  24918. break;
  24919. }
  24920. der = (unsigned char*)p;
  24921. XMEMCPY(der + derLen, pem, pemLen + 1);
  24922. derLen += pemLen;
  24923. }
  24924. if (pemLen <= 0)
  24925. ret = WOLFSSL_FAILURE;
  24926. }
  24927. /* Check trailer. */
  24928. if (ret == WOLFSSL_SUCCESS) {
  24929. if (XSTRNCMP(pem + PEM_END_SZ, nameStr, nameLen) != 0)
  24930. ret = WOLFSSL_FAILURE;
  24931. }
  24932. if (ret == WOLFSSL_SUCCESS) {
  24933. if (XSTRNCMP(pem + PEM_END_SZ + nameLen,
  24934. PEM_HDR_FIN_EOL_NEWLINE,
  24935. PEM_HDR_FIN_EOL_SZ) != 0 &&
  24936. XSTRNCMP(pem + PEM_END_SZ + nameLen,
  24937. PEM_HDR_FIN_EOL_NULL_TERM,
  24938. PEM_HDR_FIN_EOL_SZ) != 0) {
  24939. ret = WOLFSSL_FAILURE;
  24940. }
  24941. }
  24942. /* Base64 decode body. */
  24943. if (ret == WOLFSSL_SUCCESS) {
  24944. if (Base64_Decode(der, derLen, der, &derLen) != 0)
  24945. ret = WOLFSSL_FAILURE;
  24946. }
  24947. if (ret == WOLFSSL_SUCCESS) {
  24948. *name = nameStr;
  24949. *header = headerStr;
  24950. *data = der;
  24951. *len = derLen;
  24952. nameStr = NULL;
  24953. headerStr = NULL;
  24954. der = NULL;
  24955. }
  24956. if (nameStr != NULL)
  24957. XFREE(nameStr, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24958. if (headerStr != NULL)
  24959. XFREE(headerStr, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24960. if (der != NULL)
  24961. XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24962. return ret;
  24963. }
  24964. int wolfSSL_PEM_write_bio(WOLFSSL_BIO* bio, const char *name,
  24965. const char *header, const unsigned char *data,
  24966. long len)
  24967. {
  24968. int err = 0;
  24969. int outSz = 0;
  24970. int nameLen;
  24971. int headerLen;
  24972. byte* pem = NULL;
  24973. word32 pemLen;
  24974. word32 derLen = (word32)len;
  24975. if (bio == NULL || name == NULL || header == NULL || data == NULL)
  24976. return 0;
  24977. nameLen = (int)XSTRLEN(name);
  24978. headerLen = (int)XSTRLEN(header);
  24979. pemLen = (derLen + 2) / 3 * 4;
  24980. pemLen += (pemLen + 63) / 64;
  24981. pem = (byte*)XMALLOC(pemLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24982. err = pem == NULL;
  24983. if (!err)
  24984. err = Base64_Encode(data, derLen, pem, &pemLen) != 0;
  24985. if (!err) {
  24986. err = wolfSSL_BIO_write(bio, PEM_BEGIN, PEM_BEGIN_SZ) !=
  24987. (int)PEM_BEGIN_SZ;
  24988. }
  24989. if (!err)
  24990. err = wolfSSL_BIO_write(bio, name, nameLen) != nameLen;
  24991. if (!err) {
  24992. err = wolfSSL_BIO_write(bio, PEM_HDR_FIN_EOL_NEWLINE,
  24993. PEM_HDR_FIN_EOL_SZ) != (int)PEM_HDR_FIN_EOL_SZ;
  24994. }
  24995. if (!err && headerLen > 0) {
  24996. err = wolfSSL_BIO_write(bio, header, headerLen) != headerLen;
  24997. /* Blank line after a header and before body. */
  24998. if (!err)
  24999. err = wolfSSL_BIO_write(bio, "\n", 1) != 1;
  25000. headerLen++;
  25001. }
  25002. if (!err)
  25003. err = wolfSSL_BIO_write(bio, pem, pemLen) != (int)pemLen;
  25004. if (!err)
  25005. err = wolfSSL_BIO_write(bio, PEM_END, PEM_END_SZ) !=
  25006. (int)PEM_END_SZ;
  25007. if (!err)
  25008. err = wolfSSL_BIO_write(bio, name, nameLen) != nameLen;
  25009. if (!err) {
  25010. err = wolfSSL_BIO_write(bio, PEM_HDR_FIN_EOL_NEWLINE,
  25011. PEM_HDR_FIN_EOL_SZ) != (int)PEM_HDR_FIN_EOL_SZ;
  25012. }
  25013. if (!err) {
  25014. outSz = PEM_BEGIN_SZ + nameLen + PEM_HDR_FIN_EOL_SZ + headerLen +
  25015. pemLen + PEM_END_SZ + nameLen + PEM_HDR_FIN_EOL_SZ;
  25016. }
  25017. if (pem != NULL)
  25018. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  25019. return outSz;
  25020. }
  25021. #if !defined(NO_FILESYSTEM)
  25022. int wolfSSL_PEM_read(XFILE fp, char **name, char **header,
  25023. unsigned char **data, long *len)
  25024. {
  25025. int ret;
  25026. WOLFSSL_BIO* bio;
  25027. if (name == NULL || header == NULL || data == NULL || len == NULL)
  25028. return WOLFSSL_FAILURE;
  25029. bio = wolfSSL_BIO_new(wolfSSL_BIO_s_file());
  25030. if (bio == NULL)
  25031. return 0;
  25032. if (wolfSSL_BIO_set_fp(bio, fp, BIO_NOCLOSE) != WOLFSSL_SUCCESS) {
  25033. wolfSSL_BIO_free(bio);
  25034. bio = NULL;
  25035. }
  25036. ret = wolfSSL_PEM_read_bio(bio, name, header, data, len);
  25037. if (bio != NULL)
  25038. wolfSSL_BIO_free(bio);
  25039. return ret;
  25040. }
  25041. int wolfSSL_PEM_write(XFILE fp, const char *name, const char *header,
  25042. const unsigned char *data, long len)
  25043. {
  25044. int ret;
  25045. WOLFSSL_BIO* bio;
  25046. if (name == NULL || header == NULL || data == NULL)
  25047. return 0;
  25048. bio = wolfSSL_BIO_new(wolfSSL_BIO_s_file());
  25049. if (bio == NULL)
  25050. return 0;
  25051. if (wolfSSL_BIO_set_fp(bio, fp, BIO_NOCLOSE) != WOLFSSL_SUCCESS) {
  25052. wolfSSL_BIO_free(bio);
  25053. bio = NULL;
  25054. }
  25055. ret = wolfSSL_PEM_write_bio(bio, name, header, data, len);
  25056. if (bio != NULL)
  25057. wolfSSL_BIO_free(bio);
  25058. return ret;
  25059. }
  25060. #endif
  25061. #endif /* !NO_BIO */
  25062. int wolfSSL_PEM_get_EVP_CIPHER_INFO(const char* header,
  25063. EncryptedInfo* cipher)
  25064. {
  25065. if (header == NULL || cipher == NULL)
  25066. return WOLFSSL_FAILURE;
  25067. XMEMSET(cipher, 0, sizeof(*cipher));
  25068. if (wc_EncryptedInfoParse(cipher, &header, XSTRLEN(header)) != 0)
  25069. return WOLFSSL_FAILURE;
  25070. return WOLFSSL_SUCCESS;
  25071. }
  25072. int wolfSSL_PEM_do_header(EncryptedInfo* cipher, unsigned char* data,
  25073. long* len, wc_pem_password_cb* callback,
  25074. void* ctx)
  25075. {
  25076. int ret = WOLFSSL_SUCCESS;
  25077. char password[NAME_SZ];
  25078. int passwordSz;
  25079. if (cipher == NULL || data == NULL || len == NULL || callback == NULL)
  25080. return WOLFSSL_FAILURE;
  25081. passwordSz = callback(password, sizeof(password), PEM_PASS_READ, ctx);
  25082. if (passwordSz < 0)
  25083. ret = WOLFSSL_FAILURE;
  25084. if (ret == WOLFSSL_SUCCESS) {
  25085. if (wc_BufferKeyDecrypt(cipher, data, (word32)*len, (byte*)password,
  25086. passwordSz, WC_MD5) != 0) {
  25087. ret = WOLFSSL_FAILURE;
  25088. }
  25089. }
  25090. if (passwordSz > 0)
  25091. XMEMSET(password, 0, passwordSz);
  25092. return ret;
  25093. }
  25094. #ifndef NO_BIO
  25095. /*
  25096. * bp : bio to read X509 from
  25097. * x : x509 to write to
  25098. * cb : password call back for reading PEM
  25099. * u : password
  25100. * _AUX is for working with a trusted X509 certificate
  25101. */
  25102. WOLFSSL_X509 *wolfSSL_PEM_read_bio_X509_AUX(WOLFSSL_BIO *bp,
  25103. WOLFSSL_X509 **x, wc_pem_password_cb *cb,
  25104. void *u)
  25105. {
  25106. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_X509");
  25107. /* AUX info is; trusted/rejected uses, friendly name, private key id,
  25108. * and potentially a stack of "other" info. wolfSSL does not store
  25109. * friendly name or private key id yet in WOLFSSL_X509 for human
  25110. * readability and does not support extra trusted/rejected uses for
  25111. * root CA. */
  25112. return wolfSSL_PEM_read_bio_X509(bp, x, cb, u);
  25113. }
  25114. #endif /* !NO_BIO */
  25115. #endif /* OPENSSL_EXTRA || OPENSSL_ALL */
  25116. #endif /* !NO_CERTS */
  25117. /* NID variables are dependent on compatibility header files currently
  25118. *
  25119. * returns a pointer to a new WOLFSSL_ASN1_OBJECT struct on success and NULL
  25120. * on fail
  25121. */
  25122. WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_nid2obj(int id)
  25123. {
  25124. return wolfSSL_OBJ_nid2obj_ex(id, NULL);
  25125. }
  25126. WOLFSSL_LOCAL WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_nid2obj_ex(int id,
  25127. WOLFSSL_ASN1_OBJECT* arg_obj)
  25128. {
  25129. word32 oidSz = 0;
  25130. int nid = 0;
  25131. const byte* oid;
  25132. word32 type = 0;
  25133. WOLFSSL_ASN1_OBJECT* obj = arg_obj;
  25134. byte objBuf[MAX_OID_SZ + MAX_LENGTH_SZ + 1]; /* +1 for object tag */
  25135. word32 objSz = 0;
  25136. const char* sName = NULL;
  25137. int i;
  25138. #ifdef WOLFSSL_DEBUG_OPENSSL
  25139. WOLFSSL_ENTER("wolfSSL_OBJ_nid2obj()");
  25140. #endif
  25141. for (i = 0; i < (int)WOLFSSL_OBJECT_INFO_SZ; i++) {
  25142. if (wolfssl_object_info[i].nid == id) {
  25143. nid = id;
  25144. id = wolfssl_object_info[i].id;
  25145. sName = wolfssl_object_info[i].sName;
  25146. type = wolfssl_object_info[i].type;
  25147. break;
  25148. }
  25149. }
  25150. if (i == (int)WOLFSSL_OBJECT_INFO_SZ) {
  25151. WOLFSSL_MSG("NID not in table");
  25152. #ifdef WOLFSSL_QT
  25153. sName = NULL;
  25154. type = id;
  25155. #else
  25156. return NULL;
  25157. #endif
  25158. }
  25159. #ifdef HAVE_ECC
  25160. if (type == 0 && wc_ecc_get_oid(id, &oid, &oidSz) > 0) {
  25161. type = oidCurveType;
  25162. }
  25163. #endif /* HAVE_ECC */
  25164. if (sName != NULL) {
  25165. if (XSTRLEN(sName) > WOLFSSL_MAX_SNAME - 1) {
  25166. WOLFSSL_MSG("Attempted short name is too large");
  25167. return NULL;
  25168. }
  25169. }
  25170. oid = OidFromId(id, type, &oidSz);
  25171. /* set object ID to buffer */
  25172. if (obj == NULL){
  25173. obj = wolfSSL_ASN1_OBJECT_new();
  25174. if (obj == NULL) {
  25175. WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct");
  25176. return NULL;
  25177. }
  25178. }
  25179. obj->nid = nid;
  25180. obj->type = id;
  25181. obj->grp = type;
  25182. obj->sName[0] = '\0';
  25183. if (sName != NULL) {
  25184. XMEMCPY(obj->sName, (char*)sName, XSTRLEN((char*)sName));
  25185. }
  25186. objBuf[0] = ASN_OBJECT_ID; objSz++;
  25187. objSz += SetLength(oidSz, objBuf + 1);
  25188. if (oidSz) {
  25189. XMEMCPY(objBuf + objSz, oid, oidSz);
  25190. objSz += oidSz;
  25191. }
  25192. if (obj->objSz == 0 || objSz != obj->objSz) {
  25193. obj->objSz = objSz;
  25194. if(((obj->dynamic & WOLFSSL_ASN1_DYNAMIC_DATA) != 0) ||
  25195. (obj->obj == NULL)) {
  25196. if (obj->obj != NULL)
  25197. XFREE((byte*)obj->obj, NULL, DYNAMIC_TYPE_ASN1);
  25198. obj->obj = (byte*)XMALLOC(obj->objSz, NULL, DYNAMIC_TYPE_ASN1);
  25199. if (obj->obj == NULL) {
  25200. wolfSSL_ASN1_OBJECT_free(obj);
  25201. return NULL;
  25202. }
  25203. obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA ;
  25204. }
  25205. else {
  25206. obj->dynamic &= ~WOLFSSL_ASN1_DYNAMIC_DATA ;
  25207. }
  25208. }
  25209. XMEMCPY((byte*)obj->obj, objBuf, obj->objSz);
  25210. (void)type;
  25211. return obj;
  25212. }
  25213. static const char* oid_translate_num_to_str(const char* oid)
  25214. {
  25215. const struct oid_dict {
  25216. const char* num;
  25217. const char* desc;
  25218. } oid_dict[] = {
  25219. { "2.5.29.37.0", "Any Extended Key Usage" },
  25220. { "1.3.6.1.5.5.7.3.1", "TLS Web Server Authentication" },
  25221. { "1.3.6.1.5.5.7.3.2", "TLS Web Client Authentication" },
  25222. { "1.3.6.1.5.5.7.3.3", "Code Signing" },
  25223. { "1.3.6.1.5.5.7.3.4", "E-mail Protection" },
  25224. { "1.3.6.1.5.5.7.3.8", "Time Stamping" },
  25225. { "1.3.6.1.5.5.7.3.9", "OCSP Signing" },
  25226. { NULL, NULL }
  25227. };
  25228. const struct oid_dict* idx;
  25229. for (idx = oid_dict; idx->num != NULL; idx++) {
  25230. if (!XSTRCMP(oid, idx->num)) {
  25231. return idx->desc;
  25232. }
  25233. }
  25234. return NULL;
  25235. }
  25236. static int wolfssl_obj2txt_numeric(char *buf, int bufLen,
  25237. const WOLFSSL_ASN1_OBJECT *a)
  25238. {
  25239. int bufSz;
  25240. int length;
  25241. word32 idx = 0;
  25242. byte tag;
  25243. if (GetASNTag(a->obj, &idx, &tag, a->objSz) != 0) {
  25244. return WOLFSSL_FAILURE;
  25245. }
  25246. if (tag != ASN_OBJECT_ID) {
  25247. WOLFSSL_MSG("Bad ASN1 Object");
  25248. return WOLFSSL_FAILURE;
  25249. }
  25250. if (GetLength((const byte*)a->obj, &idx, &length,
  25251. a->objSz) < 0 || length < 0) {
  25252. return ASN_PARSE_E;
  25253. }
  25254. if (bufLen < MAX_OID_STRING_SZ) {
  25255. bufSz = bufLen - 1;
  25256. }
  25257. else {
  25258. bufSz = MAX_OID_STRING_SZ;
  25259. }
  25260. if ((bufSz = DecodePolicyOID(buf, (word32)bufSz, a->obj + idx,
  25261. (word32)length)) <= 0) {
  25262. WOLFSSL_MSG("Error decoding OID");
  25263. return WOLFSSL_FAILURE;
  25264. }
  25265. buf[bufSz] = '\0';
  25266. return bufSz;
  25267. }
  25268. /* If no_name is one then use numerical form, otherwise short name.
  25269. *
  25270. * Returns the buffer size on success, WOLFSSL_FAILURE on error
  25271. */
  25272. int wolfSSL_OBJ_obj2txt(char *buf, int bufLen, const WOLFSSL_ASN1_OBJECT *a,
  25273. int no_name)
  25274. {
  25275. int bufSz;
  25276. const char* desc;
  25277. const char* name;
  25278. WOLFSSL_ENTER("wolfSSL_OBJ_obj2txt()");
  25279. if (buf == NULL || bufLen <= 1 || a == NULL) {
  25280. WOLFSSL_MSG("Bad input argument");
  25281. return WOLFSSL_FAILURE;
  25282. }
  25283. if (no_name == 1) {
  25284. return wolfssl_obj2txt_numeric(buf, bufLen, a);
  25285. }
  25286. /* return long name unless using x509small, then return short name */
  25287. #if defined(OPENSSL_EXTRA_X509_SMALL) && !defined(OPENSSL_EXTRA)
  25288. name = a->sName;
  25289. #else
  25290. name = wolfSSL_OBJ_nid2ln(wolfSSL_OBJ_obj2nid(a));
  25291. #endif
  25292. if (name == NULL) {
  25293. WOLFSSL_MSG("Name not found");
  25294. bufSz = 0;
  25295. }
  25296. else if (XSTRLEN(name) + 1 < (word32)bufLen - 1) {
  25297. bufSz = (int)XSTRLEN(name);
  25298. }
  25299. else {
  25300. bufSz = bufLen - 1;
  25301. }
  25302. if (bufSz) {
  25303. XMEMCPY(buf, name, bufSz);
  25304. }
  25305. else if (a->type == GEN_DNS || a->type == GEN_EMAIL ||
  25306. a->type == GEN_URI) {
  25307. bufSz = (int)XSTRLEN((const char*)a->obj);
  25308. XMEMCPY(buf, a->obj, min(bufSz, bufLen));
  25309. }
  25310. else if ((bufSz = wolfssl_obj2txt_numeric(buf, bufLen, a)) > 0) {
  25311. if ((desc = oid_translate_num_to_str(buf))) {
  25312. bufSz = (int)XSTRLEN(desc);
  25313. bufSz = min(bufSz, bufLen - 1);
  25314. XMEMCPY(buf, desc, bufSz);
  25315. }
  25316. }
  25317. buf[bufSz] = '\0';
  25318. return bufSz;
  25319. }
  25320. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  25321. #if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
  25322. defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
  25323. defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
  25324. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_WPAS_SMALL)
  25325. /* Returns the long name that corresponds with an ASN1_OBJECT nid value.
  25326. * n : NID value of ASN1_OBJECT to search */
  25327. const char* wolfSSL_OBJ_nid2ln(int n)
  25328. {
  25329. const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
  25330. size_t i;
  25331. WOLFSSL_ENTER("wolfSSL_OBJ_nid2ln");
  25332. for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
  25333. if (obj_info->nid == n) {
  25334. return obj_info->lName;
  25335. }
  25336. }
  25337. WOLFSSL_MSG("NID not found in table");
  25338. return NULL;
  25339. }
  25340. #endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL,
  25341. WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY, WOLFSSL_WPAS_SMALL */
  25342. #if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
  25343. defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
  25344. defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
  25345. defined(WOLFSSL_HAPROXY)
  25346. char wolfSSL_CTX_use_certificate(WOLFSSL_CTX *ctx, WOLFSSL_X509 *x)
  25347. {
  25348. int ret;
  25349. WOLFSSL_ENTER("wolfSSL_CTX_use_certificate");
  25350. if (!ctx || !x || !x->derCert) {
  25351. WOLFSSL_MSG("Bad parameter");
  25352. return WOLFSSL_FAILURE;
  25353. }
  25354. FreeDer(&ctx->certificate); /* Make sure previous is free'd */
  25355. ret = AllocDer(&ctx->certificate, x->derCert->length, CERT_TYPE,
  25356. ctx->heap);
  25357. if (ret != 0)
  25358. return WOLFSSL_FAILURE;
  25359. XMEMCPY(ctx->certificate->buffer, x->derCert->buffer,
  25360. x->derCert->length);
  25361. #ifdef KEEP_OUR_CERT
  25362. if (ctx->ourCert != NULL && ctx->ownOurCert) {
  25363. wolfSSL_X509_free(ctx->ourCert);
  25364. }
  25365. #ifndef WOLFSSL_X509_STORE_CERTS
  25366. ctx->ourCert = x;
  25367. if (wolfSSL_X509_up_ref(x) != 1) {
  25368. return WOLFSSL_FAILURE;
  25369. }
  25370. #else
  25371. ctx->ourCert = wolfSSL_X509_d2i(NULL, x->derCert->buffer,x->derCert->length);
  25372. if(ctx->ourCert == NULL){
  25373. return WOLFSSL_FAILURE;
  25374. }
  25375. #endif
  25376. /* We own the cert because either we up its reference counter
  25377. * or we create our own copy of the cert object. */
  25378. ctx->ownOurCert = 1;
  25379. #endif
  25380. /* Update the available options with public keys. */
  25381. switch (x->pubKeyOID) {
  25382. #ifndef NO_RSA
  25383. #ifdef WC_RSA_PSS
  25384. case RSAPSSk:
  25385. #endif
  25386. case RSAk:
  25387. ctx->haveRSA = 1;
  25388. break;
  25389. #endif
  25390. #ifdef HAVE_ED25519
  25391. case ED25519k:
  25392. #endif
  25393. #ifdef HAVE_ED448
  25394. case ED448k:
  25395. #endif
  25396. case ECDSAk:
  25397. ctx->haveECC = 1;
  25398. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  25399. ctx->pkCurveOID = x->pkCurveOID;
  25400. #endif
  25401. break;
  25402. }
  25403. return WOLFSSL_SUCCESS;
  25404. }
  25405. static int PushCertToDerBuffer(DerBuffer** inOutDer, int weOwn,
  25406. byte* cert, word32 certSz, void* heap)
  25407. {
  25408. int ret;
  25409. DerBuffer* inChain = NULL;
  25410. DerBuffer* der = NULL;
  25411. word32 len = 0;
  25412. if (inOutDer == NULL)
  25413. return BAD_FUNC_ARG;
  25414. inChain = *inOutDer;
  25415. if (inChain != NULL)
  25416. len = inChain->length;
  25417. ret = AllocDer(&der, len + CERT_HEADER_SZ + certSz, CERT_TYPE,
  25418. heap);
  25419. if (ret != 0) {
  25420. WOLFSSL_MSG("AllocDer error");
  25421. return ret;
  25422. }
  25423. if (inChain != NULL)
  25424. XMEMCPY(der->buffer, inChain->buffer, len);
  25425. c32to24(certSz, der->buffer + len);
  25426. XMEMCPY(der->buffer + len + CERT_HEADER_SZ, cert, certSz);
  25427. if (weOwn)
  25428. FreeDer(inOutDer);
  25429. *inOutDer = der;
  25430. return WOLFSSL_SUCCESS;
  25431. }
  25432. /**
  25433. * wolfSSL_CTX_add1_chain_cert makes a copy of the cert so we free it
  25434. * on success
  25435. */
  25436. int wolfSSL_CTX_add0_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509)
  25437. {
  25438. WOLFSSL_ENTER("wolfSSL_CTX_add0_chain_cert");
  25439. if (wolfSSL_CTX_add1_chain_cert(ctx, x509) != WOLFSSL_SUCCESS) {
  25440. return WOLFSSL_FAILURE;
  25441. }
  25442. wolfSSL_X509_free(x509);
  25443. return WOLFSSL_SUCCESS;
  25444. }
  25445. int wolfSSL_CTX_add1_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509)
  25446. {
  25447. int ret;
  25448. WOLFSSL_ENTER("wolfSSL_CTX_add1_chain_cert");
  25449. if (ctx == NULL || x509 == NULL || x509->derCert == NULL) {
  25450. return WOLFSSL_FAILURE;
  25451. }
  25452. if (ctx->certificate == NULL)
  25453. ret = (int)wolfSSL_CTX_use_certificate(ctx, x509);
  25454. else {
  25455. if (wolfSSL_X509_up_ref(x509) != WOLFSSL_SUCCESS) {
  25456. WOLFSSL_MSG("wolfSSL_X509_up_ref error");
  25457. return WOLFSSL_FAILURE;
  25458. }
  25459. ret = wolfSSL_CTX_load_verify_buffer(ctx, x509->derCert->buffer,
  25460. x509->derCert->length, WOLFSSL_FILETYPE_ASN1);
  25461. if (ret == WOLFSSL_SUCCESS) {
  25462. /* push to ctx->certChain */
  25463. ret = PushCertToDerBuffer(&ctx->certChain, 1,
  25464. x509->derCert->buffer, x509->derCert->length, ctx->heap);
  25465. }
  25466. /* Store cert to free it later */
  25467. if (ret == WOLFSSL_SUCCESS && ctx->x509Chain == NULL) {
  25468. ctx->x509Chain = wolfSSL_sk_X509_new();
  25469. if (ctx->x509Chain == NULL) {
  25470. WOLFSSL_MSG("wolfSSL_sk_X509_new error");
  25471. ret = WOLFSSL_FAILURE;
  25472. }
  25473. }
  25474. if (ret == WOLFSSL_SUCCESS &&
  25475. wolfSSL_sk_X509_push(ctx->x509Chain, x509)
  25476. != WOLFSSL_SUCCESS) {
  25477. WOLFSSL_MSG("wolfSSL_sk_X509_push error");
  25478. ret = WOLFSSL_FAILURE;
  25479. }
  25480. if (ret != WOLFSSL_SUCCESS)
  25481. wolfSSL_X509_free(x509); /* Decrease ref counter */
  25482. }
  25483. return (ret == WOLFSSL_SUCCESS) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
  25484. }
  25485. #ifdef KEEP_OUR_CERT
  25486. int wolfSSL_add0_chain_cert(WOLFSSL* ssl, WOLFSSL_X509* x509)
  25487. {
  25488. int ret;
  25489. WOLFSSL_ENTER("wolfSSL_add0_chain_cert");
  25490. if (ssl == NULL || ssl->ctx == NULL || x509 == NULL ||
  25491. x509->derCert == NULL)
  25492. return WOLFSSL_FAILURE;
  25493. if (ssl->buffers.certificate == NULL) {
  25494. ret = wolfSSL_use_certificate(ssl, x509);
  25495. /* Store cert to free it later */
  25496. if (ret == WOLFSSL_SUCCESS) {
  25497. if (ssl->buffers.weOwnCert)
  25498. wolfSSL_X509_free(ssl->ourCert);
  25499. ssl->ourCert = x509;
  25500. ssl->buffers.weOwnCert = 1;
  25501. }
  25502. }
  25503. else {
  25504. ret = PushCertToDerBuffer(&ssl->buffers.certChain,
  25505. ssl->buffers.weOwnCertChain, x509->derCert->buffer,
  25506. x509->derCert->length, ssl->heap);
  25507. if (ret == WOLFSSL_SUCCESS) {
  25508. ssl->buffers.weOwnCertChain = 1;
  25509. /* Store cert to free it later */
  25510. if (ssl->ourCertChain == NULL) {
  25511. ssl->ourCertChain = wolfSSL_sk_X509_new();
  25512. if (ssl->ourCertChain == NULL) {
  25513. WOLFSSL_MSG("wolfSSL_sk_X509_new error");
  25514. return WOLFSSL_FAILURE;
  25515. }
  25516. }
  25517. if (wolfSSL_sk_X509_push(ssl->ourCertChain, x509)
  25518. != WOLFSSL_SUCCESS) {
  25519. WOLFSSL_MSG("wolfSSL_sk_X509_push error");
  25520. return WOLFSSL_FAILURE;
  25521. }
  25522. }
  25523. }
  25524. return ret == WOLFSSL_SUCCESS ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
  25525. }
  25526. int wolfSSL_add1_chain_cert(WOLFSSL* ssl, WOLFSSL_X509* x509)
  25527. {
  25528. int ret;
  25529. WOLFSSL_ENTER("wolfSSL_add1_chain_cert");
  25530. if (ssl == NULL || ssl->ctx == NULL || x509 == NULL ||
  25531. x509->derCert == NULL)
  25532. return WOLFSSL_FAILURE;
  25533. if (wolfSSL_X509_up_ref(x509) != WOLFSSL_SUCCESS) {
  25534. WOLFSSL_MSG("wolfSSL_X509_up_ref error");
  25535. return WOLFSSL_FAILURE;
  25536. }
  25537. ret = wolfSSL_add0_chain_cert(ssl, x509);
  25538. /* Decrease ref counter on error */
  25539. if (ret != WOLFSSL_SUCCESS)
  25540. wolfSSL_X509_free(x509);
  25541. return ret;
  25542. }
  25543. #endif
  25544. /* Return the corresponding short name for the nid <n>.
  25545. * or NULL if short name can't be found.
  25546. */
  25547. const char * wolfSSL_OBJ_nid2sn(int n) {
  25548. const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
  25549. size_t i;
  25550. WOLFSSL_ENTER("wolfSSL_OBJ_nid2sn");
  25551. if (n == NID_md5) {
  25552. /* NID_surname == NID_md5 and NID_surname comes before NID_md5 in
  25553. * wolfssl_object_info. As a result, the loop below will incorrectly
  25554. * return "SN" instead of "MD5." NID_surname isn't the true OpenSSL
  25555. * NID, but other functions rely on this table and modifying it to
  25556. * conform with OpenSSL's NIDs isn't trivial. */
  25557. return "MD5";
  25558. }
  25559. for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
  25560. if (obj_info->nid == n) {
  25561. return obj_info->sName;
  25562. }
  25563. }
  25564. WOLFSSL_MSG("SN not found");
  25565. return NULL;
  25566. }
  25567. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  25568. int wolfSSL_OBJ_sn2nid(const char *sn) {
  25569. WOLFSSL_ENTER("wolfSSL_OBJ_sn2nid");
  25570. if (sn == NULL)
  25571. return NID_undef;
  25572. return wc_OBJ_sn2nid(sn);
  25573. }
  25574. #endif
  25575. size_t wolfSSL_OBJ_length(const WOLFSSL_ASN1_OBJECT* o)
  25576. {
  25577. size_t ret = 0;
  25578. int err = 0;
  25579. word32 idx = 0;
  25580. int len = 0;
  25581. WOLFSSL_ENTER("wolfSSL_OBJ_length");
  25582. if (o == NULL || o->obj == NULL) {
  25583. WOLFSSL_MSG("Bad argument.");
  25584. err = 1;
  25585. }
  25586. if (err == 0 && GetASNObjectId(o->obj, &idx, &len, o->objSz)) {
  25587. WOLFSSL_MSG("Error parsing ASN.1 header.");
  25588. err = 1;
  25589. }
  25590. if (err == 0) {
  25591. ret = len;
  25592. }
  25593. WOLFSSL_LEAVE("wolfSSL_OBJ_length", (int)ret);
  25594. return ret;
  25595. }
  25596. const unsigned char* wolfSSL_OBJ_get0_data(const WOLFSSL_ASN1_OBJECT* o)
  25597. {
  25598. const unsigned char* ret = NULL;
  25599. int err = 0;
  25600. word32 idx = 0;
  25601. int len = 0;
  25602. WOLFSSL_ENTER("wolfSSL_OBJ_get0_data");
  25603. if (o == NULL || o->obj == NULL) {
  25604. WOLFSSL_MSG("Bad argument.");
  25605. err = 1;
  25606. }
  25607. if (err == 0 && GetASNObjectId(o->obj, &idx, &len, o->objSz)) {
  25608. WOLFSSL_MSG("Error parsing ASN.1 header.");
  25609. err = 1;
  25610. }
  25611. if (err == 0) {
  25612. ret = o->obj + idx;
  25613. }
  25614. return ret;
  25615. }
  25616. /* Gets the NID value that corresponds with the ASN1 object.
  25617. *
  25618. * o ASN1 object to get NID of
  25619. *
  25620. * Return NID on success and a negative value on failure
  25621. */
  25622. int wolfSSL_OBJ_obj2nid(const WOLFSSL_ASN1_OBJECT *o)
  25623. {
  25624. word32 oid = 0;
  25625. word32 idx = 0;
  25626. int ret;
  25627. #ifdef WOLFSSL_DEBUG_OPENSSL
  25628. WOLFSSL_ENTER("wolfSSL_OBJ_obj2nid");
  25629. #endif
  25630. if (o == NULL) {
  25631. return -1;
  25632. }
  25633. #ifdef WOLFSSL_QT
  25634. if (o->grp == oidCertExtType) {
  25635. /* If nid is an unknown extension, return NID_undef */
  25636. if (wolfSSL_OBJ_nid2sn(o->nid) == NULL)
  25637. return NID_undef;
  25638. }
  25639. #endif
  25640. if (o->nid > 0)
  25641. return o->nid;
  25642. if ((ret = GetObjectId(o->obj, &idx, &oid, o->grp, o->objSz)) < 0) {
  25643. if (ret == ASN_OBJECT_ID_E) {
  25644. /* Put ASN object tag in front and try again */
  25645. int len = SetObjectId(o->objSz, NULL) + o->objSz;
  25646. byte* buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  25647. if (!buf) {
  25648. WOLFSSL_MSG("malloc error");
  25649. return -1;
  25650. }
  25651. idx = SetObjectId(o->objSz, buf);
  25652. XMEMCPY(buf + idx, o->obj, o->objSz);
  25653. idx = 0;
  25654. ret = GetObjectId(buf, &idx, &oid, o->grp, len);
  25655. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  25656. if (ret < 0) {
  25657. WOLFSSL_MSG("Issue getting OID of object");
  25658. return -1;
  25659. }
  25660. }
  25661. else {
  25662. WOLFSSL_MSG("Issue getting OID of object");
  25663. return -1;
  25664. }
  25665. }
  25666. return oid2nid(oid, o->grp);
  25667. }
  25668. /* Return the corresponding NID for the long name <ln>
  25669. * or NID_undef if NID can't be found.
  25670. */
  25671. int wolfSSL_OBJ_ln2nid(const char *ln)
  25672. {
  25673. const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
  25674. size_t i, lnlen;
  25675. WOLFSSL_ENTER("wolfSSL_OBJ_ln2nid");
  25676. if (ln && (lnlen = XSTRLEN(ln)) > 0) {
  25677. /* Accept input like "/commonName=" */
  25678. if (ln[0] == '/') {
  25679. ln++;
  25680. lnlen--;
  25681. }
  25682. if (lnlen) {
  25683. if (ln[lnlen-1] == '=') {
  25684. lnlen--;
  25685. }
  25686. for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
  25687. if (lnlen == XSTRLEN(obj_info->lName) &&
  25688. XSTRNCMP(ln, obj_info->lName, lnlen) == 0) {
  25689. return obj_info->nid;
  25690. }
  25691. }
  25692. }
  25693. }
  25694. return NID_undef;
  25695. }
  25696. /* compares two objects, return 0 if equal */
  25697. int wolfSSL_OBJ_cmp(const WOLFSSL_ASN1_OBJECT* a,
  25698. const WOLFSSL_ASN1_OBJECT* b)
  25699. {
  25700. WOLFSSL_ENTER("wolfSSL_OBJ_cmp");
  25701. if (a && b && a->obj && b->obj) {
  25702. if (a->objSz == b->objSz) {
  25703. return XMEMCMP(a->obj, b->obj, a->objSz);
  25704. }
  25705. else if (a->type == EXT_KEY_USAGE_OID ||
  25706. b->type == EXT_KEY_USAGE_OID) {
  25707. /* Special case for EXT_KEY_USAGE_OID so that
  25708. * cmp will be treated as a substring search */
  25709. /* Used in libest to check for id-kp-cmcRA in
  25710. * EXT_KEY_USAGE extension */
  25711. unsigned int idx;
  25712. const byte* s; /* shorter */
  25713. unsigned int sLen;
  25714. const byte* l; /* longer */
  25715. unsigned int lLen;
  25716. if (a->objSz > b->objSz) {
  25717. s = b->obj; sLen = b->objSz;
  25718. l = a->obj; lLen = a->objSz;
  25719. }
  25720. else {
  25721. s = a->obj; sLen = a->objSz;
  25722. l = b->obj; lLen = b->objSz;
  25723. }
  25724. for (idx = 0; idx <= lLen - sLen; idx++) {
  25725. if (XMEMCMP(l + idx, s, sLen) == 0) {
  25726. /* Found substring */
  25727. return 0;
  25728. }
  25729. }
  25730. }
  25731. }
  25732. return WOLFSSL_FATAL_ERROR;
  25733. }
  25734. #endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL,
  25735. WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY */
  25736. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  25737. defined(HAVE_LIGHTY) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
  25738. defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
  25739. defined(HAVE_POCO_LIB) || defined(WOLFSSL_HAPROXY)
  25740. /* Gets the NID value that is related to the OID string passed in. Example
  25741. * string would be "2.5.29.14" for subject key ID.
  25742. *
  25743. * returns NID value on success and NID_undef on error
  25744. */
  25745. int wolfSSL_OBJ_txt2nid(const char* s)
  25746. {
  25747. unsigned int i;
  25748. #ifdef WOLFSSL_CERT_EXT
  25749. int ret;
  25750. unsigned int sum = 0;
  25751. unsigned int outSz = MAX_OID_SZ;
  25752. unsigned char out[MAX_OID_SZ];
  25753. #endif
  25754. WOLFSSL_ENTER("OBJ_txt2nid");
  25755. if (s == NULL) {
  25756. return NID_undef;
  25757. }
  25758. #ifdef WOLFSSL_CERT_EXT
  25759. ret = EncodePolicyOID(out, &outSz, s, NULL);
  25760. if (ret == 0) {
  25761. /* sum OID */
  25762. for (i = 0; i < outSz; i++) {
  25763. sum += out[i];
  25764. }
  25765. }
  25766. #endif /* WOLFSSL_CERT_EXT */
  25767. /* get the group that the OID's sum is in
  25768. * @TODO possible conflict with multiples */
  25769. for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++) {
  25770. int len;
  25771. #ifdef WOLFSSL_CERT_EXT
  25772. if (ret == 0) {
  25773. if (wolfssl_object_info[i].id == (int)sum) {
  25774. return wolfssl_object_info[i].nid;
  25775. }
  25776. }
  25777. #endif
  25778. /* try as a short name */
  25779. len = (int)XSTRLEN(s);
  25780. if ((int)XSTRLEN(wolfssl_object_info[i].sName) == len &&
  25781. XSTRNCMP(wolfssl_object_info[i].sName, s, len) == 0) {
  25782. return wolfssl_object_info[i].nid;
  25783. }
  25784. /* try as a long name */
  25785. if ((int)XSTRLEN(wolfssl_object_info[i].lName) == len &&
  25786. XSTRNCMP(wolfssl_object_info[i].lName, s, len) == 0) {
  25787. return wolfssl_object_info[i].nid;
  25788. }
  25789. }
  25790. return NID_undef;
  25791. }
  25792. #endif
  25793. #if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
  25794. defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
  25795. defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
  25796. defined(WOLFSSL_HAPROXY)
  25797. /* Creates new ASN1_OBJECT from short name, long name, or text
  25798. * representation of oid. If no_name is 0, then short name, long name, and
  25799. * numerical value of oid are interpreted. If no_name is 1, then only the
  25800. * numerical value of the oid is interpreted.
  25801. *
  25802. * Returns pointer to ASN1_OBJECT on success, or NULL on error.
  25803. */
  25804. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
  25805. WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_txt2obj(const char* s, int no_name)
  25806. {
  25807. int i, ret;
  25808. int nid = NID_undef;
  25809. unsigned int outSz = MAX_OID_SZ;
  25810. unsigned char out[MAX_OID_SZ];
  25811. WOLFSSL_ASN1_OBJECT* obj;
  25812. WOLFSSL_ENTER("wolfSSL_OBJ_txt2obj");
  25813. if (s == NULL)
  25814. return NULL;
  25815. /* If s is numerical value, try to sum oid */
  25816. ret = EncodePolicyOID(out, &outSz, s, NULL);
  25817. if (ret == 0 && outSz > 0) {
  25818. /* If numerical encode succeeded then just
  25819. * create object from that because sums are
  25820. * not unique and can cause confusion. */
  25821. obj = wolfSSL_ASN1_OBJECT_new();
  25822. if (obj == NULL) {
  25823. WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct");
  25824. return NULL;
  25825. }
  25826. obj->dynamic |= WOLFSSL_ASN1_DYNAMIC;
  25827. obj->obj = (byte*)XMALLOC(1 + MAX_LENGTH_SZ + outSz, NULL,
  25828. DYNAMIC_TYPE_ASN1);
  25829. if (obj->obj == NULL) {
  25830. wolfSSL_ASN1_OBJECT_free(obj);
  25831. return NULL;
  25832. }
  25833. obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA ;
  25834. i = SetObjectId(outSz, (byte*)obj->obj);
  25835. XMEMCPY((byte*)obj->obj + i, out, outSz);
  25836. obj->objSz = i + outSz;
  25837. return obj;
  25838. }
  25839. /* TODO: update short names in wolfssl_object_info and check OID sums
  25840. are correct */
  25841. for (i = 0; i < (int)WOLFSSL_OBJECT_INFO_SZ; i++) {
  25842. /* Short name, long name, and numerical value are interpreted */
  25843. if (no_name == 0 &&
  25844. ((XSTRCMP(s, wolfssl_object_info[i].sName) == 0) ||
  25845. (XSTRCMP(s, wolfssl_object_info[i].lName) == 0)))
  25846. {
  25847. nid = wolfssl_object_info[i].nid;
  25848. }
  25849. }
  25850. if (nid != NID_undef)
  25851. return wolfSSL_OBJ_nid2obj(nid);
  25852. return NULL;
  25853. }
  25854. #endif
  25855. /* compatibility function. Its intended use is to remove OID's from an
  25856. * internal table that have been added with OBJ_create. wolfSSL manages its
  25857. * own internal OID values and does not currently support OBJ_create. */
  25858. void wolfSSL_OBJ_cleanup(void)
  25859. {
  25860. WOLFSSL_ENTER("wolfSSL_OBJ_cleanup()");
  25861. }
  25862. #ifndef NO_WOLFSSL_STUB
  25863. int wolfSSL_OBJ_create(const char *oid, const char *sn, const char *ln)
  25864. {
  25865. (void)oid;
  25866. (void)sn;
  25867. (void)ln;
  25868. WOLFSSL_STUB("wolfSSL_OBJ_create");
  25869. return WOLFSSL_FAILURE;
  25870. }
  25871. #endif
  25872. void wolfSSL_set_verify_depth(WOLFSSL *ssl, int depth)
  25873. {
  25874. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  25875. WOLFSSL_ENTER("wolfSSL_set_verify_depth");
  25876. ssl->options.verifyDepth = (byte)depth;
  25877. #endif
  25878. }
  25879. #endif /* OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE ||
  25880. HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */
  25881. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  25882. defined(HAVE_LIGHTY) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
  25883. defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
  25884. defined(HAVE_POCO_LIB) || defined(WOLFSSL_HAPROXY)
  25885. WOLFSSL_ASN1_OBJECT * wolfSSL_X509_NAME_ENTRY_get_object(WOLFSSL_X509_NAME_ENTRY *ne)
  25886. {
  25887. WOLFSSL_ASN1_OBJECT* obj = NULL;
  25888. #ifdef WOLFSSL_DEBUG_OPENSSL
  25889. WOLFSSL_ENTER("wolfSSL_X509_NAME_ENTRY_get_object");
  25890. #endif
  25891. if (ne == NULL) return NULL;
  25892. obj = wolfSSL_OBJ_nid2obj_ex(ne->nid, ne->object);
  25893. if (obj != NULL) {
  25894. obj->nid = ne->nid;
  25895. return obj;
  25896. }
  25897. return NULL;
  25898. }
  25899. #endif /* OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE ||
  25900. HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */
  25901. #ifdef OPENSSL_EXTRA
  25902. /* wolfSSL uses negative values for error states. This function returns an
  25903. * unsigned type so the value returned is the absolute value of the error.
  25904. */
  25905. unsigned long wolfSSL_ERR_peek_last_error_line(const char **file, int *line)
  25906. {
  25907. WOLFSSL_ENTER("wolfSSL_ERR_peek_last_error");
  25908. (void)line;
  25909. (void)file;
  25910. #ifdef WOLFSSL_HAVE_ERROR_QUEUE
  25911. {
  25912. int ret;
  25913. if ((ret = wc_PeekErrorNode(-1, file, NULL, line)) < 0) {
  25914. WOLFSSL_MSG("Issue peeking at error node in queue");
  25915. return 0;
  25916. }
  25917. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  25918. if (ret == -ASN_NO_PEM_HEADER)
  25919. return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE;
  25920. #endif
  25921. #if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
  25922. if (ret == ASN1_R_HEADER_TOO_LONG) {
  25923. return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG;
  25924. }
  25925. #endif
  25926. return (unsigned long)ret;
  25927. }
  25928. #else
  25929. return (unsigned long)(0 - NOT_COMPILED_IN);
  25930. #endif
  25931. }
  25932. #ifndef NO_CERTS
  25933. int wolfSSL_CTX_use_PrivateKey(WOLFSSL_CTX *ctx, WOLFSSL_EVP_PKEY *pkey)
  25934. {
  25935. WOLFSSL_ENTER("wolfSSL_CTX_use_PrivateKey");
  25936. if (ctx == NULL || pkey == NULL) {
  25937. return WOLFSSL_FAILURE;
  25938. }
  25939. switch (pkey->type) {
  25940. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) && !defined(NO_RSA)
  25941. case EVP_PKEY_RSA:
  25942. WOLFSSL_MSG("populating RSA key");
  25943. if (PopulateRSAEvpPkeyDer(pkey) != WOLFSSL_SUCCESS)
  25944. return WOLFSSL_FAILURE;
  25945. break;
  25946. #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA */
  25947. #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
  25948. defined(WOLFSSL_CERT_GEN)) && !defined(NO_DSA)
  25949. case EVP_PKEY_DSA:
  25950. break;
  25951. #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) && !NO_DSA */
  25952. #ifdef HAVE_ECC
  25953. case EVP_PKEY_EC:
  25954. WOLFSSL_MSG("populating ECC key");
  25955. if (ECC_populate_EVP_PKEY(pkey, pkey->ecc)
  25956. != WOLFSSL_SUCCESS)
  25957. return WOLFSSL_FAILURE;
  25958. break;
  25959. #endif
  25960. default:
  25961. return WOLFSSL_FAILURE;
  25962. }
  25963. if (pkey->pkey.ptr != NULL) {
  25964. /* ptr for WOLFSSL_EVP_PKEY struct is expected to be DER format */
  25965. return wolfSSL_CTX_use_PrivateKey_buffer(ctx,
  25966. (const unsigned char*)pkey->pkey.ptr,
  25967. pkey->pkey_sz, SSL_FILETYPE_ASN1);
  25968. }
  25969. WOLFSSL_MSG("wolfSSL private key not set");
  25970. return BAD_FUNC_ARG;
  25971. }
  25972. #endif /* !NO_CERTS */
  25973. #endif /* OPENSSL_EXTRA */
  25974. #if defined(HAVE_EX_DATA) && \
  25975. (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  25976. defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || \
  25977. defined(HAVE_LIGHTY)) || defined(HAVE_EX_DATA) || \
  25978. defined(WOLFSSL_WPAS_SMALL)
  25979. /**
  25980. * get_ex_new_index is a helper function for the following
  25981. * xx_get_ex_new_index functions:
  25982. * - wolfSSL_CRYPTO_get_ex_new_index
  25983. * - wolfSSL_CTX_get_ex_new_index
  25984. * - wolfSSL_get_ex_new_index
  25985. * Issues a unique index number for the specified class-index.
  25986. * Returns an index number greater or equal to zero on success,
  25987. * -1 on failure.
  25988. */
  25989. int wolfssl_get_ex_new_index(int class_index)
  25990. {
  25991. /* index counter for each class index*/
  25992. static int ctx_idx = 0;
  25993. static int ssl_idx = 0;
  25994. static int ssl_session_idx = 0;
  25995. static int x509_idx = 0;
  25996. int idx = -1;
  25997. switch(class_index) {
  25998. case WOLF_CRYPTO_EX_INDEX_SSL:
  25999. idx = ssl_idx++;
  26000. break;
  26001. case WOLF_CRYPTO_EX_INDEX_SSL_CTX:
  26002. idx = ctx_idx++;
  26003. break;
  26004. case WOLF_CRYPTO_EX_INDEX_X509:
  26005. idx = x509_idx++;
  26006. break;
  26007. case WOLF_CRYPTO_EX_INDEX_SSL_SESSION:
  26008. idx = ssl_session_idx++;
  26009. break;
  26010. /* following class indexes are not supoprted */
  26011. case WOLF_CRYPTO_EX_INDEX_X509_STORE:
  26012. case WOLF_CRYPTO_EX_INDEX_X509_STORE_CTX:
  26013. case WOLF_CRYPTO_EX_INDEX_DH:
  26014. case WOLF_CRYPTO_EX_INDEX_DSA:
  26015. case WOLF_CRYPTO_EX_INDEX_EC_KEY:
  26016. case WOLF_CRYPTO_EX_INDEX_RSA:
  26017. case WOLF_CRYPTO_EX_INDEX_ENGINE:
  26018. case WOLF_CRYPTO_EX_INDEX_UI:
  26019. case WOLF_CRYPTO_EX_INDEX_BIO:
  26020. case WOLF_CRYPTO_EX_INDEX_APP:
  26021. case WOLF_CRYPTO_EX_INDEX_UI_METHOD:
  26022. case WOLF_CRYPTO_EX_INDEX_DRBG:
  26023. default:
  26024. break;
  26025. }
  26026. return idx;
  26027. }
  26028. #endif /* HAVE_EX_DATA || WOLFSSL_WPAS_SMALL */
  26029. #if defined(HAVE_EX_DATA) || defined(WOLFSSL_WPAS_SMALL)
  26030. void* wolfSSL_CTX_get_ex_data(const WOLFSSL_CTX* ctx, int idx)
  26031. {
  26032. WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data");
  26033. #ifdef HAVE_EX_DATA
  26034. if(ctx != NULL) {
  26035. return wolfSSL_CRYPTO_get_ex_data(&ctx->ex_data, idx);
  26036. }
  26037. #else
  26038. (void)ctx;
  26039. (void)idx;
  26040. #endif
  26041. return NULL;
  26042. }
  26043. int wolfSSL_CTX_get_ex_new_index(long idx, void* arg, void* a, void* b,
  26044. void* c)
  26045. {
  26046. WOLFSSL_ENTER("wolfSSL_CTX_get_ex_new_index");
  26047. WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(idx, arg, a, b, c);
  26048. return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_CTX);
  26049. }
  26050. /* Return the index that can be used for the WOLFSSL structure to store
  26051. * application data.
  26052. *
  26053. */
  26054. int wolfSSL_get_ex_new_index(long argValue, void* arg,
  26055. WOLFSSL_CRYPTO_EX_new* cb1, WOLFSSL_CRYPTO_EX_dup* cb2,
  26056. WOLFSSL_CRYPTO_EX_free* cb3)
  26057. {
  26058. WOLFSSL_ENTER("wolfSSL_get_ex_new_index");
  26059. WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(argValue, arg, cb1, cb2, cb3);
  26060. return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL);
  26061. }
  26062. int wolfSSL_CTX_set_ex_data(WOLFSSL_CTX* ctx, int idx, void* data)
  26063. {
  26064. WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data");
  26065. #ifdef HAVE_EX_DATA
  26066. if (ctx != NULL)
  26067. {
  26068. return wolfSSL_CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
  26069. }
  26070. #else
  26071. (void)ctx;
  26072. (void)idx;
  26073. (void)data;
  26074. #endif
  26075. return WOLFSSL_FAILURE;
  26076. }
  26077. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  26078. int wolfSSL_CTX_set_ex_data_with_cleanup(
  26079. WOLFSSL_CTX* ctx,
  26080. int idx,
  26081. void* data,
  26082. wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
  26083. {
  26084. WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data_with_cleanup");
  26085. if (ctx != NULL)
  26086. {
  26087. return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ctx->ex_data, idx, data,
  26088. cleanup_routine);
  26089. }
  26090. return WOLFSSL_FAILURE;
  26091. }
  26092. #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
  26093. #endif /* defined(HAVE_EX_DATA) || defined(WOLFSSL_WPAS_SMALL) */
  26094. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  26095. /* Returns char* to app data stored in ex[0].
  26096. *
  26097. * ssl WOLFSSL structure to get app data from
  26098. */
  26099. void* wolfSSL_get_app_data(const WOLFSSL *ssl)
  26100. {
  26101. /* checkout exdata stuff... */
  26102. WOLFSSL_ENTER("wolfSSL_get_app_data");
  26103. return wolfSSL_get_ex_data(ssl, 0);
  26104. }
  26105. /* Set ex array 0 to have app data
  26106. *
  26107. * ssl WOLFSSL struct to set app data in
  26108. * arg data to be stored
  26109. *
  26110. * Returns WOLFSSL_SUCCESS on success and SSL_FAILURE on failure
  26111. */
  26112. int wolfSSL_set_app_data(WOLFSSL *ssl, void* arg) {
  26113. WOLFSSL_ENTER("wolfSSL_set_app_data");
  26114. return wolfSSL_set_ex_data(ssl, 0, arg);
  26115. }
  26116. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  26117. #if defined(HAVE_EX_DATA) || defined(OPENSSL_EXTRA) || \
  26118. defined(OPENSSL_EXTRA_X509_SMALL) || defined(WOLFSSL_WPAS_SMALL)
  26119. int wolfSSL_set_ex_data(WOLFSSL* ssl, int idx, void* data)
  26120. {
  26121. WOLFSSL_ENTER("wolfSSL_set_ex_data");
  26122. #ifdef HAVE_EX_DATA
  26123. if (ssl != NULL)
  26124. {
  26125. return wolfSSL_CRYPTO_set_ex_data(&ssl->ex_data, idx, data);
  26126. }
  26127. #else
  26128. WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
  26129. (void)ssl;
  26130. (void)idx;
  26131. (void)data;
  26132. #endif
  26133. return WOLFSSL_FAILURE;
  26134. }
  26135. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  26136. int wolfSSL_set_ex_data_with_cleanup(
  26137. WOLFSSL* ssl,
  26138. int idx,
  26139. void* data,
  26140. wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
  26141. {
  26142. WOLFSSL_ENTER("wolfSSL_set_ex_data_with_cleanup");
  26143. if (ssl != NULL)
  26144. {
  26145. return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ssl->ex_data, idx, data,
  26146. cleanup_routine);
  26147. }
  26148. return WOLFSSL_FAILURE;
  26149. }
  26150. #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
  26151. void* wolfSSL_get_ex_data(const WOLFSSL* ssl, int idx)
  26152. {
  26153. WOLFSSL_ENTER("wolfSSL_get_ex_data");
  26154. #ifdef HAVE_EX_DATA
  26155. if (ssl != NULL) {
  26156. return wolfSSL_CRYPTO_get_ex_data(&ssl->ex_data, idx);
  26157. }
  26158. #else
  26159. WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
  26160. (void)ssl;
  26161. (void)idx;
  26162. #endif
  26163. return 0;
  26164. }
  26165. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || WOLFSSL_WPAS_SMALL */
  26166. #if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
  26167. || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
  26168. #if defined(OPENSSL_EXTRA) && !defined(NO_DH)
  26169. /* Initialize ctx->dh with dh's params. Return WOLFSSL_SUCCESS on ok */
  26170. long wolfSSL_CTX_set_tmp_dh(WOLFSSL_CTX* ctx, WOLFSSL_DH* dh)
  26171. {
  26172. int pSz, gSz;
  26173. byte *p, *g;
  26174. int ret=0;
  26175. WOLFSSL_ENTER("wolfSSL_CTX_set_tmp_dh");
  26176. if(!ctx || !dh)
  26177. return BAD_FUNC_ARG;
  26178. /* Get needed size for p and g */
  26179. pSz = wolfSSL_BN_bn2bin(dh->p, NULL);
  26180. gSz = wolfSSL_BN_bn2bin(dh->g, NULL);
  26181. if(pSz <= 0 || gSz <= 0)
  26182. return WOLFSSL_FATAL_ERROR;
  26183. p = (byte*)XMALLOC(pSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  26184. if(!p)
  26185. return MEMORY_E;
  26186. g = (byte*)XMALLOC(gSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  26187. if(!g) {
  26188. XFREE(p, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  26189. return MEMORY_E;
  26190. }
  26191. pSz = wolfSSL_BN_bn2bin(dh->p, p);
  26192. gSz = wolfSSL_BN_bn2bin(dh->g, g);
  26193. if(pSz >= 0 && gSz >= 0) /* Conversion successful */
  26194. ret = wolfSSL_CTX_SetTmpDH(ctx, p, pSz, g, gSz);
  26195. XFREE(p, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  26196. XFREE(g, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  26197. return pSz > 0 && gSz > 0 ? ret : WOLFSSL_FATAL_ERROR;
  26198. }
  26199. #endif /* OPENSSL_EXTRA && !NO_DH */
  26200. /* returns the enum value associated with handshake state
  26201. *
  26202. * ssl the WOLFSSL structure to get state of
  26203. */
  26204. int wolfSSL_get_state(const WOLFSSL* ssl)
  26205. {
  26206. WOLFSSL_ENTER("wolfSSL_get_state");
  26207. if (ssl == NULL) {
  26208. WOLFSSL_MSG("Null argument passed in");
  26209. return SSL_FAILURE;
  26210. }
  26211. return ssl->options.handShakeState;
  26212. }
  26213. #endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE */
  26214. #ifdef OPENSSL_EXTRA
  26215. void wolfSSL_certs_clear(WOLFSSL* ssl)
  26216. {
  26217. WOLFSSL_ENTER("wolfSSL_certs_clear()");
  26218. if (ssl == NULL)
  26219. return;
  26220. /* ctx still owns certificate, certChain, key, dh, and cm */
  26221. if (ssl->buffers.weOwnCert)
  26222. FreeDer(&ssl->buffers.certificate);
  26223. ssl->buffers.certificate = NULL;
  26224. if (ssl->buffers.weOwnCertChain)
  26225. FreeDer(&ssl->buffers.certChain);
  26226. ssl->buffers.certChain = NULL;
  26227. #ifdef WOLFSSL_TLS13
  26228. ssl->buffers.certChainCnt = 0;
  26229. #endif
  26230. if (ssl->buffers.weOwnKey)
  26231. FreeDer(&ssl->buffers.key);
  26232. ssl->buffers.key = NULL;
  26233. ssl->buffers.keyType = 0;
  26234. ssl->buffers.keyId = 0;
  26235. ssl->buffers.keyLabel = 0;
  26236. ssl->buffers.keySz = 0;
  26237. ssl->buffers.keyDevId = 0;
  26238. }
  26239. #endif
  26240. #if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
  26241. || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
  26242. long wolfSSL_ctrl(WOLFSSL* ssl, int cmd, long opt, void* pt)
  26243. {
  26244. WOLFSSL_ENTER("wolfSSL_ctrl");
  26245. if (ssl == NULL)
  26246. return BAD_FUNC_ARG;
  26247. switch (cmd) {
  26248. #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
  26249. #ifdef HAVE_SNI
  26250. case SSL_CTRL_SET_TLSEXT_HOSTNAME:
  26251. WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TLSEXT_HOSTNAME.");
  26252. if (pt == NULL) {
  26253. WOLFSSL_MSG("Passed in NULL Host Name.");
  26254. break;
  26255. }
  26256. return wolfSSL_set_tlsext_host_name(ssl, (const char*) pt);
  26257. #endif /* HAVE_SNI */
  26258. #endif /* WOLFSSL_NGINX || WOLFSSL_QT || OPENSSL_ALL */
  26259. default:
  26260. WOLFSSL_MSG("Case not implemented.");
  26261. }
  26262. (void)opt;
  26263. (void)pt;
  26264. return WOLFSSL_FAILURE;
  26265. }
  26266. long wolfSSL_CTX_ctrl(WOLFSSL_CTX* ctx, int cmd, long opt, void* pt)
  26267. {
  26268. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
  26269. long ctrl_opt;
  26270. #endif
  26271. long ret = WOLFSSL_SUCCESS;
  26272. WOLFSSL_ENTER("wolfSSL_CTX_ctrl");
  26273. if (ctx == NULL)
  26274. return WOLFSSL_FAILURE;
  26275. switch (cmd) {
  26276. case SSL_CTRL_CHAIN:
  26277. #ifdef SESSION_CERTS
  26278. {
  26279. /*
  26280. * We don't care about opt here because a copy of the certificate is
  26281. * stored anyway so increasing the reference counter is not necessary.
  26282. * Just check to make sure that it is set to one of the correct values.
  26283. */
  26284. WOLF_STACK_OF(WOLFSSL_X509)* sk = (WOLF_STACK_OF(WOLFSSL_X509)*) pt;
  26285. WOLFSSL_X509* x509;
  26286. int i;
  26287. if (opt != 0 && opt != 1) {
  26288. ret = WOLFSSL_FAILURE;
  26289. break;
  26290. }
  26291. /* Clear certificate chain */
  26292. FreeDer(&ctx->certChain);
  26293. if (sk) {
  26294. for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
  26295. x509 = wolfSSL_sk_X509_value(sk, i);
  26296. /* Prevent wolfSSL_CTX_add_extra_chain_cert from freeing cert */
  26297. if (wolfSSL_X509_up_ref(x509) != 1) {
  26298. WOLFSSL_MSG("Error increasing reference count");
  26299. continue;
  26300. }
  26301. if (wolfSSL_CTX_add_extra_chain_cert(ctx, x509) !=
  26302. WOLFSSL_SUCCESS) {
  26303. WOLFSSL_MSG("Error adding certificate to context");
  26304. /* Decrease reference count on failure */
  26305. wolfSSL_X509_free(x509);
  26306. }
  26307. }
  26308. }
  26309. /* Free previous chain */
  26310. wolfSSL_sk_X509_pop_free(ctx->x509Chain, NULL);
  26311. ctx->x509Chain = sk;
  26312. if (sk && opt == 1) {
  26313. /* up all refs when opt == 1 */
  26314. for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
  26315. x509 = wolfSSL_sk_X509_value(sk, i);
  26316. if (wolfSSL_X509_up_ref(x509) != 1) {
  26317. WOLFSSL_MSG("Error increasing reference count");
  26318. continue;
  26319. }
  26320. }
  26321. }
  26322. }
  26323. #else
  26324. WOLFSSL_MSG("Session certificates not compiled in");
  26325. ret = WOLFSSL_FAILURE;
  26326. #endif
  26327. break;
  26328. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
  26329. case SSL_CTRL_OPTIONS:
  26330. WOLFSSL_MSG("Entering Case: SSL_CTRL_OPTIONS.");
  26331. ctrl_opt = wolfSSL_CTX_set_options(ctx, opt);
  26332. #ifdef WOLFSSL_QT
  26333. /* Set whether to use client or server cipher preference */
  26334. if ((ctrl_opt & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE)
  26335. == WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
  26336. WOLFSSL_MSG("Using Server's Cipher Preference.");
  26337. ctx->useClientOrder = FALSE;
  26338. } else {
  26339. WOLFSSL_MSG("Using Client's Cipher Preference.");
  26340. ctx->useClientOrder = TRUE;
  26341. }
  26342. #endif /* WOLFSSL_QT */
  26343. return ctrl_opt;
  26344. #endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
  26345. case SSL_CTRL_EXTRA_CHAIN_CERT:
  26346. WOLFSSL_MSG("Entering Case: SSL_CTRL_EXTRA_CHAIN_CERT.");
  26347. if (pt == NULL) {
  26348. WOLFSSL_MSG("Passed in x509 pointer NULL.");
  26349. ret = WOLFSSL_FAILURE;
  26350. break;
  26351. }
  26352. return wolfSSL_CTX_add_extra_chain_cert(ctx, (WOLFSSL_X509*)pt);
  26353. #ifndef NO_DH
  26354. case SSL_CTRL_SET_TMP_DH:
  26355. WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_DH.");
  26356. if (pt == NULL) {
  26357. WOLFSSL_MSG("Passed in DH pointer NULL.");
  26358. ret = WOLFSSL_FAILURE;
  26359. break;
  26360. }
  26361. return wolfSSL_CTX_set_tmp_dh(ctx, (WOLFSSL_DH*)pt);
  26362. #endif
  26363. #ifdef HAVE_ECC
  26364. case SSL_CTRL_SET_TMP_ECDH:
  26365. WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_ECDH.");
  26366. if (pt == NULL) {
  26367. WOLFSSL_MSG("Passed in ECDH pointer NULL.");
  26368. ret = WOLFSSL_FAILURE;
  26369. break;
  26370. }
  26371. return wolfSSL_SSL_CTX_set_tmp_ecdh(ctx, (WOLFSSL_EC_KEY*)pt);
  26372. #endif
  26373. case SSL_CTRL_MODE:
  26374. wolfSSL_CTX_set_mode(ctx,opt);
  26375. break;
  26376. case SSL_CTRL_SET_MIN_PROTO_VERSION:
  26377. WOLFSSL_MSG("set min proto version");
  26378. return wolfSSL_CTX_set_min_proto_version(ctx, (int)opt);
  26379. case SSL_CTRL_SET_MAX_PROTO_VERSION:
  26380. WOLFSSL_MSG("set max proto version");
  26381. return wolfSSL_CTX_set_max_proto_version(ctx, (int)opt);
  26382. case SSL_CTRL_GET_MIN_PROTO_VERSION:
  26383. WOLFSSL_MSG("get min proto version");
  26384. return wolfSSL_CTX_get_min_proto_version(ctx);
  26385. case SSL_CTRL_GET_MAX_PROTO_VERSION:
  26386. WOLFSSL_MSG("get max proto version");
  26387. return wolfSSL_CTX_get_max_proto_version(ctx);
  26388. default:
  26389. WOLFSSL_MSG("CTX_ctrl cmd not implemented");
  26390. ret = WOLFSSL_FAILURE;
  26391. break;
  26392. }
  26393. (void)ctx;
  26394. (void)cmd;
  26395. (void)opt;
  26396. (void)pt;
  26397. WOLFSSL_LEAVE("wolfSSL_CTX_ctrl", (int)ret);
  26398. return ret;
  26399. }
  26400. #ifndef WOLFSSL_NO_STUB
  26401. long wolfSSL_CTX_callback_ctrl(WOLFSSL_CTX* ctx, int cmd, void (*fp)(void))
  26402. {
  26403. (void) ctx;
  26404. (void) cmd;
  26405. (void) fp;
  26406. WOLFSSL_STUB("wolfSSL_CTX_callback_ctrl");
  26407. return WOLFSSL_FAILURE;
  26408. }
  26409. #endif /* WOLFSSL_NO_STUB */
  26410. #ifndef NO_WOLFSSL_STUB
  26411. long wolfSSL_CTX_clear_extra_chain_certs(WOLFSSL_CTX* ctx)
  26412. {
  26413. return wolfSSL_CTX_ctrl(ctx, SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS, 0L, NULL);
  26414. }
  26415. #endif
  26416. /* Returns the verifyCallback from the ssl structure if successful.
  26417. Returns NULL otherwise. */
  26418. VerifyCallback wolfSSL_get_verify_callback(WOLFSSL* ssl)
  26419. {
  26420. WOLFSSL_ENTER("wolfSSL_get_verify_callback()");
  26421. if (ssl) {
  26422. return ssl->verifyCallback;
  26423. }
  26424. return NULL;
  26425. }
  26426. /* Adds the ASN1 certificate to the user ctx.
  26427. Returns WOLFSSL_SUCCESS if no error, returns WOLFSSL_FAILURE otherwise.*/
  26428. int wolfSSL_CTX_use_certificate_ASN1(WOLFSSL_CTX *ctx, int derSz,
  26429. const unsigned char *der)
  26430. {
  26431. WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_ASN1()");
  26432. if (der != NULL && ctx != NULL) {
  26433. if (wolfSSL_CTX_use_certificate_buffer(ctx, der, derSz,
  26434. WOLFSSL_FILETYPE_ASN1) == WOLFSSL_SUCCESS) {
  26435. return WOLFSSL_SUCCESS;
  26436. }
  26437. }
  26438. return WOLFSSL_FAILURE;
  26439. }
  26440. #if !defined(HAVE_FAST_RSA) && defined(WOLFSSL_KEY_GEN) && \
  26441. !defined(NO_RSA) && !defined(HAVE_USER_RSA)
  26442. /* Adds the rsa private key to the user ctx.
  26443. Returns WOLFSSL_SUCCESS if no error, returns WOLFSSL_FAILURE otherwise.*/
  26444. int wolfSSL_CTX_use_RSAPrivateKey(WOLFSSL_CTX* ctx, WOLFSSL_RSA* rsa)
  26445. {
  26446. int ret;
  26447. int derSize;
  26448. unsigned char *maxDerBuf;
  26449. unsigned char* key = NULL;
  26450. WOLFSSL_ENTER("wolfSSL_CTX_use_RSAPrivateKey()");
  26451. if (ctx == NULL || rsa == NULL) {
  26452. WOLFSSL_MSG("one or more inputs were NULL");
  26453. return BAD_FUNC_ARG;
  26454. }
  26455. maxDerBuf = (unsigned char*)XMALLOC(4096, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  26456. if (maxDerBuf == NULL) {
  26457. WOLFSSL_MSG("Malloc failure");
  26458. return MEMORY_E;
  26459. }
  26460. key = maxDerBuf;
  26461. /* convert RSA struct to der encoded buffer and get the size */
  26462. if ((derSize = wolfSSL_i2d_RSAPrivateKey(rsa, &key)) <= 0) {
  26463. WOLFSSL_MSG("wolfSSL_i2d_RSAPrivateKey() failure");
  26464. XFREE(maxDerBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  26465. return WOLFSSL_FAILURE;
  26466. }
  26467. ret = wolfSSL_CTX_use_PrivateKey_buffer(ctx, (const unsigned char*)maxDerBuf,
  26468. derSize, SSL_FILETYPE_ASN1);
  26469. if (ret != WOLFSSL_SUCCESS) {
  26470. WOLFSSL_MSG("wolfSSL_CTX_USE_PrivateKey_buffer() failure");
  26471. XFREE(maxDerBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  26472. return WOLFSSL_FAILURE;
  26473. }
  26474. XFREE(maxDerBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  26475. return ret;
  26476. }
  26477. #endif /* NO_RSA && !HAVE_FAST_RSA */
  26478. #ifndef NO_BIO
  26479. /* Converts EVP_PKEY data from a bio buffer to a WOLFSSL_EVP_PKEY structure.
  26480. Returns pointer to private EVP_PKEY struct upon success, NULL if there
  26481. is a failure.*/
  26482. WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_bio(WOLFSSL_BIO* bio,
  26483. WOLFSSL_EVP_PKEY** out)
  26484. {
  26485. unsigned char* mem = NULL;
  26486. int memSz = 0;
  26487. WOLFSSL_EVP_PKEY* key = NULL;
  26488. int i = 0, j = 0;
  26489. unsigned char* extraBioMem = NULL;
  26490. int extraBioMemSz = 0;
  26491. int derLength = 0;
  26492. WOLFSSL_ENTER("wolfSSL_d2i_PrivateKey_bio()");
  26493. if (bio == NULL) {
  26494. return NULL;
  26495. }
  26496. (void)out;
  26497. memSz = wolfSSL_BIO_get_len(bio);
  26498. if (memSz <= 0) {
  26499. WOLFSSL_MSG("wolfSSL_BIO_get_len() failure");
  26500. return NULL;
  26501. }
  26502. mem = (unsigned char*)XMALLOC(memSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26503. if (mem == NULL) {
  26504. WOLFSSL_MSG("Malloc failure");
  26505. return NULL;
  26506. }
  26507. if (wolfSSL_BIO_read(bio, (unsigned char*)mem, memSz) == memSz) {
  26508. /* Determines key type and returns the new private EVP_PKEY object */
  26509. if ((key = wolfSSL_d2i_PrivateKey_EVP(NULL, &mem, (long)memSz)) == NULL) {
  26510. WOLFSSL_MSG("wolfSSL_d2i_PrivateKey_EVP() failure");
  26511. XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26512. return NULL;
  26513. }
  26514. /* Write extra data back into bio object if necessary. */
  26515. derLength = key->pkey_sz;
  26516. extraBioMemSz = (memSz - derLength);
  26517. if (extraBioMemSz > 0) {
  26518. extraBioMem = (unsigned char *)XMALLOC(extraBioMemSz, NULL,
  26519. DYNAMIC_TYPE_TMP_BUFFER);
  26520. if (extraBioMem == NULL) {
  26521. WOLFSSL_MSG("Malloc failure");
  26522. XFREE((unsigned char*)extraBioMem, bio->heap,
  26523. DYNAMIC_TYPE_TMP_BUFFER);
  26524. XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26525. return NULL;
  26526. }
  26527. for (i = derLength; i < memSz; i++) {
  26528. *(extraBioMem + j) = *(mem + i);
  26529. j++;
  26530. }
  26531. wolfSSL_BIO_write(bio, extraBioMem, extraBioMemSz);
  26532. if (wolfSSL_BIO_get_len(bio) <= 0) {
  26533. WOLFSSL_MSG("Failed to write memory to bio");
  26534. XFREE((unsigned char*)extraBioMem, bio->heap,
  26535. DYNAMIC_TYPE_TMP_BUFFER);
  26536. XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26537. return NULL;
  26538. }
  26539. XFREE((unsigned char*)extraBioMem, bio->heap,
  26540. DYNAMIC_TYPE_TMP_BUFFER);
  26541. }
  26542. if (out != NULL) {
  26543. *out = key;
  26544. }
  26545. }
  26546. XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26547. return key;
  26548. }
  26549. #endif /* !NO_BIO */
  26550. #endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
  26551. #if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) || \
  26552. defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) || defined(WOLFSSL_WPAS_SMALL)
  26553. /* Converts a DER encoded private key to a WOLFSSL_EVP_PKEY structure.
  26554. * returns a pointer to a new WOLFSSL_EVP_PKEY structure on success and NULL
  26555. * on fail */
  26556. WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_EVP(WOLFSSL_EVP_PKEY** out,
  26557. unsigned char** in, long inSz)
  26558. {
  26559. WOLFSSL_ENTER("wolfSSL_d2i_PrivateKey_EVP");
  26560. return d2iGenericKey(out, (const unsigned char**)in, inSz, 1);
  26561. }
  26562. #endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT || WOLFSSL_WPAS_SMALL*/
  26563. /* stunnel compatibility functions*/
  26564. #if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && (defined(HAVE_STUNNEL) || \
  26565. defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY) || \
  26566. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_OPENSSH)))
  26567. void wolfSSL_ERR_remove_thread_state(void* pid)
  26568. {
  26569. (void) pid;
  26570. return;
  26571. }
  26572. #ifndef NO_FILESYSTEM
  26573. /***TBD ***/
  26574. void wolfSSL_print_all_errors_fp(XFILE fp)
  26575. {
  26576. (void)fp;
  26577. }
  26578. #endif /* !NO_FILESYSTEM */
  26579. #endif /* OPENSSL_ALL || OPENSSL_EXTRA || HAVE_STUNNEL || WOLFSSL_NGINX ||
  26580. HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH */
  26581. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
  26582. defined(HAVE_EX_DATA)
  26583. #if defined(HAVE_EX_DATA) && !defined(NO_SESSION_CACHE)
  26584. static void SESSION_ex_data_cache_update(WOLFSSL_SESSION* session, int idx,
  26585. void* data, byte get, void** getRet, int* setRet)
  26586. {
  26587. int row;
  26588. int i;
  26589. int error = 0;
  26590. SessionRow* sessRow = NULL;
  26591. const byte* id;
  26592. byte foundCache = 0;
  26593. if (getRet != NULL)
  26594. *getRet = NULL;
  26595. if (setRet != NULL)
  26596. *setRet = WOLFSSL_FAILURE;
  26597. id = session->sessionID;
  26598. if (session->haveAltSessionID)
  26599. id = session->altSessionID;
  26600. row = (int)(HashObject(id, ID_LEN, &error) % SESSION_ROWS);
  26601. if (error != 0) {
  26602. WOLFSSL_MSG("Hash session failed");
  26603. return;
  26604. }
  26605. sessRow = &SessionCache[row];
  26606. if (SESSION_ROW_LOCK(sessRow) != 0) {
  26607. WOLFSSL_MSG("Session row lock failed");
  26608. return;
  26609. }
  26610. for (i = 0; i < SESSIONS_PER_ROW && i < sessRow->totalCount; i++) {
  26611. if (XMEMCMP(id, sessRow->Sessions[i].sessionID, ID_LEN) == 0
  26612. && session->side == sessRow->Sessions[i].side) {
  26613. if (get) {
  26614. *getRet = wolfSSL_CRYPTO_get_ex_data(
  26615. &sessRow->Sessions[i].ex_data, idx);
  26616. }
  26617. else {
  26618. *setRet = wolfSSL_CRYPTO_set_ex_data(
  26619. &sessRow->Sessions[i].ex_data, idx, data);
  26620. }
  26621. foundCache = 1;
  26622. break;
  26623. }
  26624. }
  26625. SESSION_ROW_UNLOCK(sessRow);
  26626. /* If we don't have a session in cache then clear the ex_data and
  26627. * own it */
  26628. if (!foundCache) {
  26629. XMEMSET(&session->ex_data, 0, sizeof(WOLFSSL_CRYPTO_EX_DATA));
  26630. session->ownExData = 1;
  26631. if (!get) {
  26632. *setRet = wolfSSL_CRYPTO_set_ex_data(&session->ex_data, idx,
  26633. data);
  26634. }
  26635. }
  26636. }
  26637. #endif
  26638. int wolfSSL_SESSION_set_ex_data(WOLFSSL_SESSION* session, int idx, void* data)
  26639. {
  26640. int ret = WOLFSSL_FAILURE;
  26641. WOLFSSL_ENTER("wolfSSL_SESSION_set_ex_data");
  26642. #ifdef HAVE_EX_DATA
  26643. session = ClientSessionToSession(session);
  26644. if (session != NULL) {
  26645. #ifndef NO_SESSION_CACHE
  26646. if (!session->ownExData) {
  26647. /* Need to update in cache */
  26648. SESSION_ex_data_cache_update(session, idx, data, 0, NULL, &ret);
  26649. }
  26650. else
  26651. #endif
  26652. {
  26653. ret = wolfSSL_CRYPTO_set_ex_data(&session->ex_data, idx, data);
  26654. }
  26655. }
  26656. #else
  26657. (void)session;
  26658. (void)idx;
  26659. (void)data;
  26660. #endif
  26661. return ret;
  26662. }
  26663. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  26664. int wolfSSL_SESSION_set_ex_data_with_cleanup(
  26665. WOLFSSL_SESSION* session,
  26666. int idx,
  26667. void* data,
  26668. wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
  26669. {
  26670. WOLFSSL_ENTER("wolfSSL_SESSION_set_ex_data_with_cleanup");
  26671. session = ClientSessionToSession(session);
  26672. if(session != NULL) {
  26673. return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&session->ex_data, idx,
  26674. data, cleanup_routine);
  26675. }
  26676. return WOLFSSL_FAILURE;
  26677. }
  26678. #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
  26679. void* wolfSSL_SESSION_get_ex_data(const WOLFSSL_SESSION* session, int idx)
  26680. {
  26681. void* ret = NULL;
  26682. WOLFSSL_ENTER("wolfSSL_SESSION_get_ex_data");
  26683. #ifdef HAVE_EX_DATA
  26684. session = ClientSessionToSession(session);
  26685. if (session != NULL) {
  26686. #ifndef NO_SESSION_CACHE
  26687. if (!session->ownExData) {
  26688. /* Need to retrieve the data from the session cache */
  26689. SESSION_ex_data_cache_update((WOLFSSL_SESSION*)session, idx, NULL,
  26690. 1, &ret, NULL);
  26691. }
  26692. else
  26693. #endif
  26694. {
  26695. ret = wolfSSL_CRYPTO_get_ex_data(&session->ex_data, idx);
  26696. }
  26697. }
  26698. #else
  26699. (void)session;
  26700. (void)idx;
  26701. #endif
  26702. return ret;
  26703. }
  26704. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_EX_DATA */
  26705. /* Note: This is a huge section of API's - through
  26706. * wolfSSL_X509_OBJECT_get0_X509_CRL */
  26707. #if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
  26708. (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
  26709. defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
  26710. defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB)))
  26711. #ifdef HAVE_EX_DATA
  26712. int wolfSSL_SESSION_get_ex_new_index(long idx, void* data, void* cb1,
  26713. void* cb2, CRYPTO_free_func* cb3)
  26714. {
  26715. WOLFSSL_ENTER("wolfSSL_SESSION_get_ex_new_index");
  26716. WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(idx, data, cb1, cb2, cb3);
  26717. return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_SESSION);
  26718. }
  26719. #endif
  26720. #if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY)
  26721. static wolfSSL_OSSL_Malloc_cb ossl_malloc = NULL;
  26722. static wolfSSL_OSSL_Free_cb ossl_free = NULL;
  26723. static wolfSSL_OSSL_Realloc_cb ossl_realloc = NULL;
  26724. static void* OSSL_Malloc(size_t size)
  26725. {
  26726. if (ossl_malloc != NULL)
  26727. return ossl_malloc(size, NULL, 0);
  26728. else
  26729. return NULL;
  26730. }
  26731. static void OSSL_Free(void *ptr)
  26732. {
  26733. if (ossl_free != NULL)
  26734. ossl_free(ptr, NULL, 0);
  26735. }
  26736. static void* OSSL_Realloc(void *ptr, size_t size)
  26737. {
  26738. if (ossl_realloc != NULL)
  26739. return ossl_realloc(ptr, size, NULL, 0);
  26740. else
  26741. return NULL;
  26742. }
  26743. #endif /* USE_WOLFSSL_MEMORY && !WOLFSSL_DEBUG_MEMORY */
  26744. int wolfSSL_CRYPTO_set_mem_functions(
  26745. wolfSSL_OSSL_Malloc_cb m,
  26746. wolfSSL_OSSL_Realloc_cb r,
  26747. wolfSSL_OSSL_Free_cb f)
  26748. {
  26749. #ifdef USE_WOLFSSL_MEMORY
  26750. #ifdef WOLFSSL_DEBUG_MEMORY
  26751. WOLFSSL_MSG("mem functions will receive function name instead of "
  26752. "file name");
  26753. if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)m, (wolfSSL_Free_cb)f,
  26754. (wolfSSL_Realloc_cb)r) == 0)
  26755. return WOLFSSL_SUCCESS;
  26756. #else
  26757. WOLFSSL_MSG("wolfSSL was compiled without WOLFSSL_DEBUG_MEMORY. mem "
  26758. "functions will receive a NULL file name and 0 for the "
  26759. "line number.");
  26760. if (wolfSSL_SetAllocators(OSSL_Malloc, OSSL_Free, OSSL_Realloc) == 0) {
  26761. ossl_malloc = m;
  26762. ossl_free = f;
  26763. ossl_realloc = r;
  26764. return WOLFSSL_SUCCESS;
  26765. }
  26766. #endif
  26767. else
  26768. return WOLFSSL_FAILURE;
  26769. #else
  26770. (void)m;
  26771. (void)r;
  26772. (void)f;
  26773. WOLFSSL_MSG("wolfSSL allocator callback functions not compiled in");
  26774. return WOLFSSL_FAILURE;
  26775. #endif
  26776. }
  26777. int wolfSSL_ERR_load_ERR_strings(void)
  26778. {
  26779. return WOLFSSL_SUCCESS;
  26780. }
  26781. void wolfSSL_ERR_load_crypto_strings(void)
  26782. {
  26783. WOLFSSL_ENTER("wolfSSL_ERR_load_crypto_strings");
  26784. /* Do nothing */
  26785. return;
  26786. }
  26787. int wolfSSL_FIPS_mode(void)
  26788. {
  26789. #ifdef HAVE_FIPS
  26790. return 1;
  26791. #else
  26792. return 0;
  26793. #endif
  26794. }
  26795. int wolfSSL_FIPS_mode_set(int r)
  26796. {
  26797. #ifdef HAVE_FIPS
  26798. if (r == 0) {
  26799. WOLFSSL_MSG("Cannot disable FIPS at runtime.");
  26800. return WOLFSSL_FAILURE;
  26801. }
  26802. return WOLFSSL_SUCCESS;
  26803. #else
  26804. if (r == 0) {
  26805. return WOLFSSL_SUCCESS;
  26806. }
  26807. WOLFSSL_MSG("Cannot enable FIPS. This isn't the wolfSSL FIPS code.");
  26808. return WOLFSSL_FAILURE;
  26809. #endif
  26810. }
  26811. int wolfSSL_CIPHER_get_bits(const WOLFSSL_CIPHER *c, int *alg_bits)
  26812. {
  26813. int ret = WOLFSSL_FAILURE;
  26814. WOLFSSL_ENTER("wolfSSL_CIPHER_get_bits");
  26815. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
  26816. (void)alg_bits;
  26817. if (c!= NULL)
  26818. ret = c->bits;
  26819. #else
  26820. if (c != NULL && c->ssl != NULL) {
  26821. ret = 8 * c->ssl->specs.key_size;
  26822. if (alg_bits != NULL) {
  26823. *alg_bits = ret;
  26824. }
  26825. }
  26826. #endif
  26827. return ret;
  26828. }
  26829. /* returns value less than 0 on fail to match
  26830. * On a successful match the priority level found is returned
  26831. */
  26832. int wolfSSL_sk_SSL_CIPHER_find(
  26833. WOLF_STACK_OF(WOLFSSL_CIPHER)* sk, const WOLFSSL_CIPHER* toFind)
  26834. {
  26835. WOLFSSL_STACK* next;
  26836. int i, sz;
  26837. if (sk == NULL || toFind == NULL) {
  26838. return WOLFSSL_FATAL_ERROR;
  26839. }
  26840. sz = wolfSSL_sk_SSL_CIPHER_num(sk);
  26841. next = sk;
  26842. for (i = 0; i < sz && next != NULL; i++) {
  26843. if (next->data.cipher.cipherSuite0 == toFind->cipherSuite0 &&
  26844. next->data.cipher.cipherSuite == toFind->cipherSuite) {
  26845. return sz - i; /* reverse because stack pushed highest on first */
  26846. }
  26847. next = next->next;
  26848. }
  26849. return WOLFSSL_FATAL_ERROR;
  26850. }
  26851. /* free's all nodes in the stack and there data */
  26852. void wolfSSL_sk_SSL_CIPHER_free(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk)
  26853. {
  26854. WOLFSSL_ENTER("wolfSSL_sk_SSL_CIPHER_free");
  26855. wolfSSL_sk_free(sk);
  26856. }
  26857. #ifdef HAVE_SNI
  26858. int wolfSSL_set_tlsext_host_name(WOLFSSL* ssl, const char* host_name)
  26859. {
  26860. int ret;
  26861. WOLFSSL_ENTER("wolfSSL_set_tlsext_host_name");
  26862. ret = wolfSSL_UseSNI(ssl, WOLFSSL_SNI_HOST_NAME,
  26863. host_name, (word16)XSTRLEN(host_name));
  26864. WOLFSSL_LEAVE("wolfSSL_set_tlsext_host_name", ret);
  26865. return ret;
  26866. }
  26867. #ifndef NO_WOLFSSL_SERVER
  26868. const char * wolfSSL_get_servername(WOLFSSL* ssl, byte type)
  26869. {
  26870. void * serverName = NULL;
  26871. if (ssl == NULL)
  26872. return NULL;
  26873. TLSX_SNI_GetRequest(ssl->extensions, type, &serverName);
  26874. return (const char *)serverName;
  26875. }
  26876. #endif /* NO_WOLFSSL_SERVER */
  26877. #endif /* HAVE_SNI */
  26878. WOLFSSL_CTX* wolfSSL_set_SSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx)
  26879. {
  26880. if (ssl && ctx && SetSSL_CTX(ssl, ctx, 0) == WOLFSSL_SUCCESS)
  26881. return ssl->ctx;
  26882. return NULL;
  26883. }
  26884. VerifyCallback wolfSSL_CTX_get_verify_callback(WOLFSSL_CTX* ctx)
  26885. {
  26886. WOLFSSL_ENTER("wolfSSL_CTX_get_verify_callback");
  26887. if(ctx)
  26888. return ctx->verifyCallback;
  26889. return NULL;
  26890. }
  26891. #ifdef HAVE_SNI
  26892. void wolfSSL_CTX_set_servername_callback(WOLFSSL_CTX* ctx, CallbackSniRecv cb)
  26893. {
  26894. WOLFSSL_ENTER("wolfSSL_CTX_set_servername_callback");
  26895. if (ctx)
  26896. ctx->sniRecvCb = cb;
  26897. }
  26898. int wolfSSL_CTX_set_tlsext_servername_callback(WOLFSSL_CTX* ctx,
  26899. CallbackSniRecv cb)
  26900. {
  26901. WOLFSSL_ENTER("wolfSSL_CTX_set_tlsext_servername_callback");
  26902. if (ctx) {
  26903. ctx->sniRecvCb = cb;
  26904. return WOLFSSL_SUCCESS;
  26905. }
  26906. return WOLFSSL_FAILURE;
  26907. }
  26908. int wolfSSL_CTX_set_servername_arg(WOLFSSL_CTX* ctx, void* arg)
  26909. {
  26910. WOLFSSL_ENTER("wolfSSL_CTX_set_servername_arg");
  26911. if (ctx) {
  26912. ctx->sniRecvCbArg = arg;
  26913. return WOLFSSL_SUCCESS;
  26914. }
  26915. return WOLFSSL_FAILURE;
  26916. }
  26917. #endif /* HAVE_SNI */
  26918. #ifndef NO_BIO
  26919. void wolfSSL_ERR_load_BIO_strings(void) {
  26920. WOLFSSL_ENTER("ERR_load_BIO_strings");
  26921. /* do nothing */
  26922. }
  26923. #endif
  26924. #ifndef NO_WOLFSSL_STUB
  26925. /* Set THREADID callback, return 1 on success, 0 on error */
  26926. int wolfSSL_THREADID_set_callback(
  26927. void(*threadid_func)(WOLFSSL_CRYPTO_THREADID*))
  26928. {
  26929. WOLFSSL_ENTER("wolfSSL_THREADID_set_callback");
  26930. WOLFSSL_STUB("CRYPTO_THREADID_set_callback");
  26931. (void)threadid_func;
  26932. return 1;
  26933. }
  26934. #endif
  26935. #ifndef NO_WOLFSSL_STUB
  26936. void wolfSSL_THREADID_set_numeric(void* id, unsigned long val)
  26937. {
  26938. WOLFSSL_ENTER("wolfSSL_THREADID_set_numeric");
  26939. WOLFSSL_STUB("CRYPTO_THREADID_set_numeric");
  26940. (void)id;
  26941. (void)val;
  26942. return;
  26943. }
  26944. #endif
  26945. #endif /* OPENSSL_ALL || (OPENSSL_EXTRA && (HAVE_STUNNEL || WOLFSSL_NGINX ||
  26946. * HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH ||
  26947. * HAVE_SBLIM_SFCB)) */
  26948. #if defined(OPENSSL_EXTRA)
  26949. int wolfSSL_CRYPTO_memcmp(const void *a, const void *b, size_t size)
  26950. {
  26951. if (!a || !b)
  26952. return 0;
  26953. return ConstantCompare((const byte*)a, (const byte*)b, (int)size);
  26954. }
  26955. unsigned long wolfSSL_ERR_peek_last_error(void)
  26956. {
  26957. WOLFSSL_ENTER("wolfSSL_ERR_peek_last_error");
  26958. #ifdef WOLFSSL_HAVE_ERROR_QUEUE
  26959. {
  26960. int ret;
  26961. if ((ret = wc_PeekErrorNode(-1, NULL, NULL, NULL)) < 0) {
  26962. WOLFSSL_MSG("Issue peeking at error node in queue");
  26963. return 0;
  26964. }
  26965. if (ret == -ASN_NO_PEM_HEADER)
  26966. return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE;
  26967. #if defined(WOLFSSL_PYTHON)
  26968. if (ret == ASN1_R_HEADER_TOO_LONG)
  26969. return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG;
  26970. #endif
  26971. return (unsigned long)ret;
  26972. }
  26973. #else
  26974. return (unsigned long)(0 - NOT_COMPILED_IN);
  26975. #endif
  26976. }
  26977. #endif /* OPENSSL_EXTRA */
  26978. int wolfSSL_version(WOLFSSL* ssl)
  26979. {
  26980. WOLFSSL_ENTER("wolfSSL_version");
  26981. if (ssl->version.major == SSLv3_MAJOR) {
  26982. switch (ssl->version.minor) {
  26983. case SSLv3_MINOR :
  26984. return SSL3_VERSION;
  26985. case TLSv1_MINOR :
  26986. return TLS1_VERSION;
  26987. case TLSv1_1_MINOR :
  26988. return TLS1_1_VERSION;
  26989. case TLSv1_2_MINOR :
  26990. return TLS1_2_VERSION;
  26991. case TLSv1_3_MINOR :
  26992. return TLS1_3_VERSION;
  26993. default:
  26994. return WOLFSSL_FAILURE;
  26995. }
  26996. }
  26997. else if (ssl->version.major == DTLS_MAJOR) {
  26998. switch (ssl->version.minor) {
  26999. case DTLS_MINOR :
  27000. return DTLS1_VERSION;
  27001. case DTLSv1_2_MINOR :
  27002. return DTLS1_2_VERSION;
  27003. default:
  27004. return WOLFSSL_FAILURE;
  27005. }
  27006. }
  27007. return WOLFSSL_FAILURE;
  27008. }
  27009. WOLFSSL_CTX* wolfSSL_get_SSL_CTX(WOLFSSL* ssl)
  27010. {
  27011. WOLFSSL_ENTER("wolfSSL_get_SSL_CTX");
  27012. return ssl->ctx;
  27013. }
  27014. #if defined(OPENSSL_ALL) || \
  27015. defined(OPENSSL_EXTRA) || defined(HAVE_STUNNEL) || \
  27016. defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  27017. const byte* wolfSSL_SESSION_get_id(const WOLFSSL_SESSION* sess,
  27018. unsigned int* idLen)
  27019. {
  27020. WOLFSSL_ENTER("wolfSSL_SESSION_get_id");
  27021. sess = ClientSessionToSession(sess);
  27022. if (sess == NULL || idLen == NULL) {
  27023. WOLFSSL_MSG("Bad func args. Please provide idLen");
  27024. return NULL;
  27025. }
  27026. *idLen = sess->sessionIDSz;
  27027. return sess->sessionID;
  27028. }
  27029. #if (defined(HAVE_SESSION_TICKET) || defined(SESSION_CERTS)) && \
  27030. !defined(NO_FILESYSTEM)
  27031. #ifndef NO_BIO
  27032. #if defined(SESSION_CERTS) || \
  27033. (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
  27034. /* returns a pointer to the protocol used by the session */
  27035. static const char* wolfSSL_SESSION_get_protocol(const WOLFSSL_SESSION* in)
  27036. {
  27037. in = ClientSessionToSession(in);
  27038. return wolfSSL_internal_get_version((ProtocolVersion*)&in->version);
  27039. }
  27040. #endif
  27041. /* returns true (non 0) if the session has EMS (extended master secret) */
  27042. static int wolfSSL_SESSION_haveEMS(const WOLFSSL_SESSION* in)
  27043. {
  27044. in = ClientSessionToSession(in);
  27045. if (in == NULL)
  27046. return 0;
  27047. return in->haveEMS;
  27048. }
  27049. #if defined(HAVE_SESSION_TICKET)
  27050. /* prints out the ticket to bio passed in
  27051. * return WOLFSSL_SUCCESS on success
  27052. */
  27053. static int wolfSSL_SESSION_print_ticket(WOLFSSL_BIO* bio,
  27054. const WOLFSSL_SESSION* in, const char* tab)
  27055. {
  27056. unsigned short i, j, z, sz;
  27057. short tag = 0;
  27058. byte* pt;
  27059. in = ClientSessionToSession(in);
  27060. if (in == NULL || bio == NULL) {
  27061. return BAD_FUNC_ARG;
  27062. }
  27063. sz = in->ticketLen;
  27064. pt = in->ticket;
  27065. if (wolfSSL_BIO_printf(bio, "%s\n", (sz == 0)? " NONE": "") <= 0)
  27066. return WOLFSSL_FAILURE;
  27067. for (i = 0; i < sz;) {
  27068. char asc[16];
  27069. if (sz - i < 16) {
  27070. if (wolfSSL_BIO_printf(bio, "%s%04X -", tab, tag + (sz - i)) <= 0)
  27071. return WOLFSSL_FAILURE;
  27072. }
  27073. else {
  27074. if (wolfSSL_BIO_printf(bio, "%s%04X -", tab, tag) <= 0)
  27075. return WOLFSSL_FAILURE;
  27076. }
  27077. for (j = 0; i < sz && j < 8; j++,i++) {
  27078. asc[j] = ((pt[i])&0x6f)>='A'?((pt[i])&0x6f):'.';
  27079. if (wolfSSL_BIO_printf(bio, " %02X", pt[i]) <= 0)
  27080. return WOLFSSL_FAILURE;
  27081. }
  27082. if (i < sz) {
  27083. asc[j] = ((pt[i])&0x6f)>='A'?((pt[i])&0x6f):'.';
  27084. if (wolfSSL_BIO_printf(bio, "-%02X", pt[i]) <= 0)
  27085. return WOLFSSL_FAILURE;
  27086. j++;
  27087. i++;
  27088. }
  27089. for (; i < sz && j < 16; j++,i++) {
  27090. asc[j] = ((pt[i])&0x6f)>='A'?((pt[i])&0x6f):'.';
  27091. if (wolfSSL_BIO_printf(bio, " %02X", pt[i]) <= 0)
  27092. return WOLFSSL_FAILURE;
  27093. }
  27094. /* pad out spacing */
  27095. for (z = j; z < 17; z++) {
  27096. if (wolfSSL_BIO_printf(bio, " ") <= 0)
  27097. return WOLFSSL_FAILURE;
  27098. }
  27099. for (z = 0; z < j; z++) {
  27100. if (wolfSSL_BIO_printf(bio, "%c", asc[z]) <= 0)
  27101. return WOLFSSL_FAILURE;
  27102. }
  27103. if (wolfSSL_BIO_printf(bio, "\n") <= 0)
  27104. return WOLFSSL_FAILURE;
  27105. tag += 16;
  27106. }
  27107. return WOLFSSL_SUCCESS;
  27108. }
  27109. #endif /* HAVE_SESSION_TICKET */
  27110. /* prints out the session information in human readable form
  27111. * return WOLFSSL_SUCCESS on success
  27112. */
  27113. int wolfSSL_SESSION_print(WOLFSSL_BIO *bp, const WOLFSSL_SESSION *session)
  27114. {
  27115. const unsigned char* pt;
  27116. unsigned char buf[SECRET_LEN];
  27117. unsigned int sz = 0, i;
  27118. int ret;
  27119. session = ClientSessionToSession(session);
  27120. if (session == NULL) {
  27121. return WOLFSSL_FAILURE;
  27122. }
  27123. if (wolfSSL_BIO_printf(bp, "%s\n", "SSL-Session:") <= 0)
  27124. return WOLFSSL_FAILURE;
  27125. #if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \
  27126. defined(HAVE_SESSION_TICKET))
  27127. if (wolfSSL_BIO_printf(bp, " Protocol : %s\n",
  27128. wolfSSL_SESSION_get_protocol(session)) <= 0)
  27129. return WOLFSSL_FAILURE;
  27130. #endif
  27131. if (wolfSSL_BIO_printf(bp, " Cipher : %s\n",
  27132. wolfSSL_SESSION_CIPHER_get_name(session)) <= 0)
  27133. return WOLFSSL_FAILURE;
  27134. pt = wolfSSL_SESSION_get_id(session, &sz);
  27135. if (wolfSSL_BIO_printf(bp, " Session-ID: ") <= 0)
  27136. return WOLFSSL_FAILURE;
  27137. for (i = 0; i < sz; i++) {
  27138. if (wolfSSL_BIO_printf(bp, "%02X", pt[i]) <= 0)
  27139. return WOLFSSL_FAILURE;
  27140. }
  27141. if (wolfSSL_BIO_printf(bp, "\n") <= 0)
  27142. return WOLFSSL_FAILURE;
  27143. if (wolfSSL_BIO_printf(bp, " Session-ID-ctx: \n") <= 0)
  27144. return WOLFSSL_FAILURE;
  27145. ret = wolfSSL_SESSION_get_master_key(session, buf, sizeof(buf));
  27146. if (wolfSSL_BIO_printf(bp, " Master-Key: ") <= 0)
  27147. return WOLFSSL_FAILURE;
  27148. if (ret > 0) {
  27149. sz = (unsigned int)ret;
  27150. for (i = 0; i < sz; i++) {
  27151. if (wolfSSL_BIO_printf(bp, "%02X", buf[i]) <= 0)
  27152. return WOLFSSL_FAILURE;
  27153. }
  27154. }
  27155. if (wolfSSL_BIO_printf(bp, "\n") <= 0)
  27156. return WOLFSSL_FAILURE;
  27157. /* @TODO PSK identity hint and SRP */
  27158. if (wolfSSL_BIO_printf(bp, " TLS session ticket:") <= 0)
  27159. return WOLFSSL_FAILURE;
  27160. #ifdef HAVE_SESSION_TICKET
  27161. if (wolfSSL_SESSION_print_ticket(bp, session, " ") != WOLFSSL_SUCCESS)
  27162. return WOLFSSL_FAILURE;
  27163. #endif
  27164. #if !defined(NO_SESSION_CACHE) && (defined(OPENSSL_EXTRA) || \
  27165. defined(HAVE_EXT_CACHE))
  27166. if (wolfSSL_BIO_printf(bp, " Start Time: %ld\n",
  27167. wolfSSL_SESSION_get_time(session)) <= 0)
  27168. return WOLFSSL_FAILURE;
  27169. if (wolfSSL_BIO_printf(bp, " Timeout : %ld (sec)\n",
  27170. wolfSSL_SESSION_get_timeout(session)) <= 0)
  27171. return WOLFSSL_FAILURE;
  27172. #endif /* !NO_SESSION_CACHE && OPENSSL_EXTRA || HAVE_EXT_CACHE */
  27173. /* @TODO verify return code print */
  27174. if (wolfSSL_BIO_printf(bp, " Extended master secret: %s\n",
  27175. (wolfSSL_SESSION_haveEMS(session) == 0)? "no" : "yes") <= 0)
  27176. return WOLFSSL_FAILURE;
  27177. return WOLFSSL_SUCCESS;
  27178. }
  27179. #endif /* !NO_BIO */
  27180. #endif /* (HAVE_SESSION_TICKET || SESSION_CERTS) && !NO_FILESYSTEM */
  27181. #endif /* OPENSSL_ALL || OPENSSL_EXTRA || HAVE_STUNNEL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
  27182. #if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && defined(HAVE_STUNNEL)) \
  27183. || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(WOLFSSL_NGINX)
  27184. /* TODO: Doesn't currently track SSL_VERIFY_CLIENT_ONCE */
  27185. int wolfSSL_get_verify_mode(const WOLFSSL* ssl) {
  27186. int mode = 0;
  27187. WOLFSSL_ENTER("wolfSSL_get_verify_mode");
  27188. if (!ssl) {
  27189. return WOLFSSL_FAILURE;
  27190. }
  27191. if (ssl->options.verifyNone) {
  27192. mode = WOLFSSL_VERIFY_NONE;
  27193. }
  27194. else {
  27195. if (ssl->options.verifyPeer) {
  27196. mode |= WOLFSSL_VERIFY_PEER;
  27197. }
  27198. if (ssl->options.failNoCert) {
  27199. mode |= WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT;
  27200. }
  27201. if (ssl->options.failNoCertxPSK) {
  27202. mode |= WOLFSSL_VERIFY_FAIL_EXCEPT_PSK;
  27203. }
  27204. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  27205. if (ssl->options.verifyPostHandshake) {
  27206. mode |= WOLFSSL_VERIFY_POST_HANDSHAKE;
  27207. }
  27208. #endif
  27209. }
  27210. WOLFSSL_LEAVE("wolfSSL_get_verify_mode", mode);
  27211. return mode;
  27212. }
  27213. int wolfSSL_CTX_get_verify_mode(const WOLFSSL_CTX* ctx)
  27214. {
  27215. int mode = 0;
  27216. WOLFSSL_ENTER("wolfSSL_CTX_get_verify_mode");
  27217. if (!ctx) {
  27218. return WOLFSSL_FAILURE;
  27219. }
  27220. if (ctx->verifyNone) {
  27221. mode = WOLFSSL_VERIFY_NONE;
  27222. }
  27223. else {
  27224. if (ctx->verifyPeer) {
  27225. mode |= WOLFSSL_VERIFY_PEER;
  27226. }
  27227. if (ctx->failNoCert) {
  27228. mode |= WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT;
  27229. }
  27230. if (ctx->failNoCertxPSK) {
  27231. mode |= WOLFSSL_VERIFY_FAIL_EXCEPT_PSK;
  27232. }
  27233. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  27234. if (ctx->verifyPostHandshake) {
  27235. mode |= WOLFSSL_VERIFY_POST_HANDSHAKE;
  27236. }
  27237. #endif
  27238. }
  27239. WOLFSSL_LEAVE("wolfSSL_CTX_get_verify_mode", mode);
  27240. return mode;
  27241. }
  27242. #endif
  27243. #if defined(OPENSSL_EXTRA) && defined(HAVE_CURVE25519)
  27244. /* return 1 if success, 0 if error
  27245. * output keys are little endian format
  27246. */
  27247. int wolfSSL_EC25519_generate_key(unsigned char *priv, unsigned int *privSz,
  27248. unsigned char *pub, unsigned int *pubSz)
  27249. {
  27250. #ifndef WOLFSSL_KEY_GEN
  27251. WOLFSSL_MSG("No Key Gen built in");
  27252. (void) priv;
  27253. (void) privSz;
  27254. (void) pub;
  27255. (void) pubSz;
  27256. return WOLFSSL_FAILURE;
  27257. #else /* WOLFSSL_KEY_GEN */
  27258. int ret = WOLFSSL_FAILURE;
  27259. int initTmpRng = 0;
  27260. WC_RNG *rng = NULL;
  27261. #ifdef WOLFSSL_SMALL_STACK
  27262. WC_RNG *tmpRNG = NULL;
  27263. #else
  27264. WC_RNG tmpRNG[1];
  27265. #endif
  27266. WOLFSSL_ENTER("wolfSSL_EC25519_generate_key");
  27267. if (priv == NULL || privSz == NULL || *privSz < CURVE25519_KEYSIZE ||
  27268. pub == NULL || pubSz == NULL || *pubSz < CURVE25519_KEYSIZE) {
  27269. WOLFSSL_MSG("Bad arguments");
  27270. return WOLFSSL_FAILURE;
  27271. }
  27272. #ifdef WOLFSSL_SMALL_STACK
  27273. tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  27274. if (tmpRNG == NULL)
  27275. return WOLFSSL_FAILURE;
  27276. #endif
  27277. if (wc_InitRng(tmpRNG) == 0) {
  27278. rng = tmpRNG;
  27279. initTmpRng = 1;
  27280. }
  27281. else {
  27282. WOLFSSL_MSG("Bad RNG Init, trying global");
  27283. if (initGlobalRNG == 0)
  27284. WOLFSSL_MSG("Global RNG no Init");
  27285. else
  27286. rng = &globalRNG;
  27287. }
  27288. if (rng) {
  27289. curve25519_key key;
  27290. if (wc_curve25519_init(&key) != MP_OKAY)
  27291. WOLFSSL_MSG("wc_curve25519_init failed");
  27292. else if (wc_curve25519_make_key(rng, CURVE25519_KEYSIZE, &key)!=MP_OKAY)
  27293. WOLFSSL_MSG("wc_curve25519_make_key failed");
  27294. /* export key pair */
  27295. else if (wc_curve25519_export_key_raw_ex(&key, priv, privSz, pub,
  27296. pubSz, EC25519_LITTLE_ENDIAN)
  27297. != MP_OKAY)
  27298. WOLFSSL_MSG("wc_curve25519_export_key_raw_ex failed");
  27299. else
  27300. ret = WOLFSSL_SUCCESS;
  27301. wc_curve25519_free(&key);
  27302. }
  27303. if (initTmpRng)
  27304. wc_FreeRng(tmpRNG);
  27305. #ifdef WOLFSSL_SMALL_STACK
  27306. XFREE(tmpRNG, NULL, DYNAMIC_TYPE_RNG);
  27307. #endif
  27308. return ret;
  27309. #endif /* WOLFSSL_KEY_GEN */
  27310. }
  27311. /* return 1 if success, 0 if error
  27312. * input and output keys are little endian format
  27313. */
  27314. int wolfSSL_EC25519_shared_key(unsigned char *shared, unsigned int *sharedSz,
  27315. const unsigned char *priv, unsigned int privSz,
  27316. const unsigned char *pub, unsigned int pubSz)
  27317. {
  27318. #ifndef WOLFSSL_KEY_GEN
  27319. WOLFSSL_MSG("No Key Gen built in");
  27320. (void) shared;
  27321. (void) sharedSz;
  27322. (void) priv;
  27323. (void) privSz;
  27324. (void) pub;
  27325. (void) pubSz;
  27326. return WOLFSSL_FAILURE;
  27327. #else /* WOLFSSL_KEY_GEN */
  27328. int ret = WOLFSSL_FAILURE;
  27329. curve25519_key privkey, pubkey;
  27330. WOLFSSL_ENTER("wolfSSL_EC25519_shared_key");
  27331. if (shared == NULL || sharedSz == NULL || *sharedSz < CURVE25519_KEYSIZE ||
  27332. priv == NULL || privSz < CURVE25519_KEYSIZE ||
  27333. pub == NULL || pubSz < CURVE25519_KEYSIZE) {
  27334. WOLFSSL_MSG("Bad arguments");
  27335. return WOLFSSL_FAILURE;
  27336. }
  27337. /* import private key */
  27338. if (wc_curve25519_init(&privkey) != MP_OKAY) {
  27339. WOLFSSL_MSG("wc_curve25519_init privkey failed");
  27340. return ret;
  27341. }
  27342. if (wc_curve25519_import_private_ex(priv, privSz, &privkey,
  27343. EC25519_LITTLE_ENDIAN) != MP_OKAY) {
  27344. WOLFSSL_MSG("wc_curve25519_import_private_ex failed");
  27345. wc_curve25519_free(&privkey);
  27346. return ret;
  27347. }
  27348. /* import public key */
  27349. if (wc_curve25519_init(&pubkey) != MP_OKAY) {
  27350. WOLFSSL_MSG("wc_curve25519_init pubkey failed");
  27351. wc_curve25519_free(&privkey);
  27352. return ret;
  27353. }
  27354. if (wc_curve25519_import_public_ex(pub, pubSz, &pubkey,
  27355. EC25519_LITTLE_ENDIAN) != MP_OKAY) {
  27356. WOLFSSL_MSG("wc_curve25519_import_public_ex failed");
  27357. wc_curve25519_free(&privkey);
  27358. wc_curve25519_free(&pubkey);
  27359. return ret;
  27360. }
  27361. if (wc_curve25519_shared_secret_ex(&privkey, &pubkey,
  27362. shared, sharedSz,
  27363. EC25519_LITTLE_ENDIAN) != MP_OKAY)
  27364. WOLFSSL_MSG("wc_curve25519_shared_secret_ex failed");
  27365. else
  27366. ret = WOLFSSL_SUCCESS;
  27367. wc_curve25519_free(&privkey);
  27368. wc_curve25519_free(&pubkey);
  27369. return ret;
  27370. #endif /* WOLFSSL_KEY_GEN */
  27371. }
  27372. #endif /* OPENSSL_EXTRA && HAVE_CURVE25519 */
  27373. #if defined(OPENSSL_EXTRA) && defined(HAVE_ED25519)
  27374. /* return 1 if success, 0 if error
  27375. * output keys are little endian format
  27376. */
  27377. int wolfSSL_ED25519_generate_key(unsigned char *priv, unsigned int *privSz,
  27378. unsigned char *pub, unsigned int *pubSz)
  27379. {
  27380. #ifndef WOLFSSL_KEY_GEN
  27381. WOLFSSL_MSG("No Key Gen built in");
  27382. (void) priv;
  27383. (void) privSz;
  27384. (void) pub;
  27385. (void) pubSz;
  27386. return WOLFSSL_FAILURE;
  27387. #elif !defined(HAVE_ED25519_KEY_EXPORT)
  27388. WOLFSSL_MSG("No ED25519 key export built in");
  27389. (void) priv;
  27390. (void) privSz;
  27391. (void) pub;
  27392. (void) pubSz;
  27393. return WOLFSSL_FAILURE;
  27394. #else /* WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_EXPORT */
  27395. int ret = WOLFSSL_FAILURE;
  27396. int initTmpRng = 0;
  27397. WC_RNG *rng = NULL;
  27398. #ifdef WOLFSSL_SMALL_STACK
  27399. WC_RNG *tmpRNG = NULL;
  27400. #else
  27401. WC_RNG tmpRNG[1];
  27402. #endif
  27403. WOLFSSL_ENTER("wolfSSL_ED25519_generate_key");
  27404. if (priv == NULL || privSz == NULL || *privSz < ED25519_PRV_KEY_SIZE ||
  27405. pub == NULL || pubSz == NULL || *pubSz < ED25519_PUB_KEY_SIZE) {
  27406. WOLFSSL_MSG("Bad arguments");
  27407. return WOLFSSL_FAILURE;
  27408. }
  27409. #ifdef WOLFSSL_SMALL_STACK
  27410. tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  27411. if (tmpRNG == NULL)
  27412. return WOLFSSL_FATAL_ERROR;
  27413. #endif
  27414. if (wc_InitRng(tmpRNG) == 0) {
  27415. rng = tmpRNG;
  27416. initTmpRng = 1;
  27417. }
  27418. else {
  27419. WOLFSSL_MSG("Bad RNG Init, trying global");
  27420. if (initGlobalRNG == 0)
  27421. WOLFSSL_MSG("Global RNG no Init");
  27422. else
  27423. rng = &globalRNG;
  27424. }
  27425. if (rng) {
  27426. ed25519_key key;
  27427. if (wc_ed25519_init(&key) != MP_OKAY)
  27428. WOLFSSL_MSG("wc_ed25519_init failed");
  27429. else if (wc_ed25519_make_key(rng, ED25519_KEY_SIZE, &key)!=MP_OKAY)
  27430. WOLFSSL_MSG("wc_ed25519_make_key failed");
  27431. /* export private key */
  27432. else if (wc_ed25519_export_key(&key, priv, privSz, pub, pubSz)!=MP_OKAY)
  27433. WOLFSSL_MSG("wc_ed25519_export_key failed");
  27434. else
  27435. ret = WOLFSSL_SUCCESS;
  27436. wc_ed25519_free(&key);
  27437. }
  27438. if (initTmpRng)
  27439. wc_FreeRng(tmpRNG);
  27440. #ifdef WOLFSSL_SMALL_STACK
  27441. XFREE(tmpRNG, NULL, DYNAMIC_TYPE_RNG);
  27442. #endif
  27443. return ret;
  27444. #endif /* WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_EXPORT */
  27445. }
  27446. /* return 1 if success, 0 if error
  27447. * input and output keys are little endian format
  27448. * priv is a buffer containing private and public part of key
  27449. */
  27450. int wolfSSL_ED25519_sign(const unsigned char *msg, unsigned int msgSz,
  27451. const unsigned char *priv, unsigned int privSz,
  27452. unsigned char *sig, unsigned int *sigSz)
  27453. {
  27454. #if !defined(HAVE_ED25519_SIGN) || !defined(WOLFSSL_KEY_GEN) || !defined(HAVE_ED25519_KEY_IMPORT)
  27455. #if !defined(HAVE_ED25519_SIGN)
  27456. WOLFSSL_MSG("No ED25519 sign built in");
  27457. #elif !defined(WOLFSSL_KEY_GEN)
  27458. WOLFSSL_MSG("No Key Gen built in");
  27459. #elif !defined(HAVE_ED25519_KEY_IMPORT)
  27460. WOLFSSL_MSG("No ED25519 Key import built in");
  27461. #endif
  27462. (void) msg;
  27463. (void) msgSz;
  27464. (void) priv;
  27465. (void) privSz;
  27466. (void) sig;
  27467. (void) sigSz;
  27468. return WOLFSSL_FAILURE;
  27469. #else /* HAVE_ED25519_SIGN && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */
  27470. ed25519_key key;
  27471. int ret = WOLFSSL_FAILURE;
  27472. WOLFSSL_ENTER("wolfSSL_ED25519_sign");
  27473. if (priv == NULL || privSz != ED25519_PRV_KEY_SIZE ||
  27474. msg == NULL || sig == NULL || *sigSz < ED25519_SIG_SIZE) {
  27475. WOLFSSL_MSG("Bad arguments");
  27476. return WOLFSSL_FAILURE;
  27477. }
  27478. /* import key */
  27479. if (wc_ed25519_init(&key) != MP_OKAY) {
  27480. WOLFSSL_MSG("wc_curve25519_init failed");
  27481. return ret;
  27482. }
  27483. if (wc_ed25519_import_private_key(priv, privSz/2,
  27484. priv+(privSz/2), ED25519_PUB_KEY_SIZE,
  27485. &key) != MP_OKAY){
  27486. WOLFSSL_MSG("wc_ed25519_import_private failed");
  27487. wc_ed25519_free(&key);
  27488. return ret;
  27489. }
  27490. if (wc_ed25519_sign_msg(msg, msgSz, sig, sigSz, &key) != MP_OKAY)
  27491. WOLFSSL_MSG("wc_curve25519_shared_secret_ex failed");
  27492. else
  27493. ret = WOLFSSL_SUCCESS;
  27494. wc_ed25519_free(&key);
  27495. return ret;
  27496. #endif /* HAVE_ED25519_SIGN && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */
  27497. }
  27498. /* return 1 if success, 0 if error
  27499. * input and output keys are little endian format
  27500. * pub is a buffer containing public part of key
  27501. */
  27502. int wolfSSL_ED25519_verify(const unsigned char *msg, unsigned int msgSz,
  27503. const unsigned char *pub, unsigned int pubSz,
  27504. const unsigned char *sig, unsigned int sigSz)
  27505. {
  27506. #if !defined(HAVE_ED25519_VERIFY) || !defined(WOLFSSL_KEY_GEN) || !defined(HAVE_ED25519_KEY_IMPORT)
  27507. #if !defined(HAVE_ED25519_VERIFY)
  27508. WOLFSSL_MSG("No ED25519 verify built in");
  27509. #elif !defined(WOLFSSL_KEY_GEN)
  27510. WOLFSSL_MSG("No Key Gen built in");
  27511. #elif !defined(HAVE_ED25519_KEY_IMPORT)
  27512. WOLFSSL_MSG("No ED25519 Key import built in");
  27513. #endif
  27514. (void) msg;
  27515. (void) msgSz;
  27516. (void) pub;
  27517. (void) pubSz;
  27518. (void) sig;
  27519. (void) sigSz;
  27520. return WOLFSSL_FAILURE;
  27521. #else /* HAVE_ED25519_VERIFY && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */
  27522. ed25519_key key;
  27523. int ret = WOLFSSL_FAILURE, check = 0;
  27524. WOLFSSL_ENTER("wolfSSL_ED25519_verify");
  27525. if (pub == NULL || pubSz != ED25519_PUB_KEY_SIZE ||
  27526. msg == NULL || sig == NULL || sigSz != ED25519_SIG_SIZE) {
  27527. WOLFSSL_MSG("Bad arguments");
  27528. return WOLFSSL_FAILURE;
  27529. }
  27530. /* import key */
  27531. if (wc_ed25519_init(&key) != MP_OKAY) {
  27532. WOLFSSL_MSG("wc_curve25519_init failed");
  27533. return ret;
  27534. }
  27535. if (wc_ed25519_import_public(pub, pubSz, &key) != MP_OKAY){
  27536. WOLFSSL_MSG("wc_ed25519_import_public failed");
  27537. wc_ed25519_free(&key);
  27538. return ret;
  27539. }
  27540. if ((ret = wc_ed25519_verify_msg((byte*)sig, sigSz, msg, msgSz,
  27541. &check, &key)) != MP_OKAY) {
  27542. WOLFSSL_MSG("wc_ed25519_verify_msg failed");
  27543. }
  27544. else if (!check)
  27545. WOLFSSL_MSG("wc_ed25519_verify_msg failed (signature invalid)");
  27546. else
  27547. ret = WOLFSSL_SUCCESS;
  27548. wc_ed25519_free(&key);
  27549. return ret;
  27550. #endif /* HAVE_ED25519_VERIFY && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */
  27551. }
  27552. #endif /* OPENSSL_EXTRA && HAVE_ED25519 */
  27553. #if defined(OPENSSL_EXTRA) && defined(HAVE_CURVE448)
  27554. /* return 1 if success, 0 if error
  27555. * output keys are little endian format
  27556. */
  27557. int wolfSSL_EC448_generate_key(unsigned char *priv, unsigned int *privSz,
  27558. unsigned char *pub, unsigned int *pubSz)
  27559. {
  27560. #ifndef WOLFSSL_KEY_GEN
  27561. WOLFSSL_MSG("No Key Gen built in");
  27562. (void) priv;
  27563. (void) privSz;
  27564. (void) pub;
  27565. (void) pubSz;
  27566. return WOLFSSL_FAILURE;
  27567. #else /* WOLFSSL_KEY_GEN */
  27568. int ret = WOLFSSL_FAILURE;
  27569. int initTmpRng = 0;
  27570. WC_RNG *rng = NULL;
  27571. #ifdef WOLFSSL_SMALL_STACK
  27572. WC_RNG *tmpRNG = NULL;
  27573. #else
  27574. WC_RNG tmpRNG[1];
  27575. #endif
  27576. WOLFSSL_ENTER("wolfSSL_EC448_generate_key");
  27577. if (priv == NULL || privSz == NULL || *privSz < CURVE448_KEY_SIZE ||
  27578. pub == NULL || pubSz == NULL || *pubSz < CURVE448_KEY_SIZE) {
  27579. WOLFSSL_MSG("Bad arguments");
  27580. return WOLFSSL_FAILURE;
  27581. }
  27582. #ifdef WOLFSSL_SMALL_STACK
  27583. tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  27584. if (tmpRNG == NULL)
  27585. return WOLFSSL_FAILURE;
  27586. #endif
  27587. if (wc_InitRng(tmpRNG) == 0) {
  27588. rng = tmpRNG;
  27589. initTmpRng = 1;
  27590. }
  27591. else {
  27592. WOLFSSL_MSG("Bad RNG Init, trying global");
  27593. if (initGlobalRNG == 0)
  27594. WOLFSSL_MSG("Global RNG no Init");
  27595. else
  27596. rng = &globalRNG;
  27597. }
  27598. if (rng) {
  27599. curve448_key key;
  27600. if (wc_curve448_init(&key) != MP_OKAY)
  27601. WOLFSSL_MSG("wc_curve448_init failed");
  27602. else if (wc_curve448_make_key(rng, CURVE448_KEY_SIZE, &key)!=MP_OKAY)
  27603. WOLFSSL_MSG("wc_curve448_make_key failed");
  27604. /* export key pair */
  27605. else if (wc_curve448_export_key_raw_ex(&key, priv, privSz, pub, pubSz,
  27606. EC448_LITTLE_ENDIAN)
  27607. != MP_OKAY)
  27608. WOLFSSL_MSG("wc_curve448_export_key_raw_ex failed");
  27609. else
  27610. ret = WOLFSSL_SUCCESS;
  27611. wc_curve448_free(&key);
  27612. }
  27613. if (initTmpRng)
  27614. wc_FreeRng(tmpRNG);
  27615. #ifdef WOLFSSL_SMALL_STACK
  27616. XFREE(tmpRNG, NULL, DYNAMIC_TYPE_RNG);
  27617. #endif
  27618. return ret;
  27619. #endif /* WOLFSSL_KEY_GEN */
  27620. }
  27621. /* return 1 if success, 0 if error
  27622. * input and output keys are little endian format
  27623. */
  27624. int wolfSSL_EC448_shared_key(unsigned char *shared, unsigned int *sharedSz,
  27625. const unsigned char *priv, unsigned int privSz,
  27626. const unsigned char *pub, unsigned int pubSz)
  27627. {
  27628. #ifndef WOLFSSL_KEY_GEN
  27629. WOLFSSL_MSG("No Key Gen built in");
  27630. (void) shared;
  27631. (void) sharedSz;
  27632. (void) priv;
  27633. (void) privSz;
  27634. (void) pub;
  27635. (void) pubSz;
  27636. return WOLFSSL_FAILURE;
  27637. #else /* WOLFSSL_KEY_GEN */
  27638. int ret = WOLFSSL_FAILURE;
  27639. curve448_key privkey, pubkey;
  27640. WOLFSSL_ENTER("wolfSSL_EC448_shared_key");
  27641. if (shared == NULL || sharedSz == NULL || *sharedSz < CURVE448_KEY_SIZE ||
  27642. priv == NULL || privSz < CURVE448_KEY_SIZE ||
  27643. pub == NULL || pubSz < CURVE448_KEY_SIZE) {
  27644. WOLFSSL_MSG("Bad arguments");
  27645. return WOLFSSL_FAILURE;
  27646. }
  27647. /* import private key */
  27648. if (wc_curve448_init(&privkey) != MP_OKAY) {
  27649. WOLFSSL_MSG("wc_curve448_init privkey failed");
  27650. return ret;
  27651. }
  27652. if (wc_curve448_import_private_ex(priv, privSz, &privkey,
  27653. EC448_LITTLE_ENDIAN) != MP_OKAY) {
  27654. WOLFSSL_MSG("wc_curve448_import_private_ex failed");
  27655. wc_curve448_free(&privkey);
  27656. return ret;
  27657. }
  27658. /* import public key */
  27659. if (wc_curve448_init(&pubkey) != MP_OKAY) {
  27660. WOLFSSL_MSG("wc_curve448_init pubkey failed");
  27661. wc_curve448_free(&privkey);
  27662. return ret;
  27663. }
  27664. if (wc_curve448_import_public_ex(pub, pubSz, &pubkey,
  27665. EC448_LITTLE_ENDIAN) != MP_OKAY) {
  27666. WOLFSSL_MSG("wc_curve448_import_public_ex failed");
  27667. wc_curve448_free(&privkey);
  27668. wc_curve448_free(&pubkey);
  27669. return ret;
  27670. }
  27671. if (wc_curve448_shared_secret_ex(&privkey, &pubkey, shared, sharedSz,
  27672. EC448_LITTLE_ENDIAN) != MP_OKAY)
  27673. WOLFSSL_MSG("wc_curve448_shared_secret_ex failed");
  27674. else
  27675. ret = WOLFSSL_SUCCESS;
  27676. wc_curve448_free(&privkey);
  27677. wc_curve448_free(&pubkey);
  27678. return ret;
  27679. #endif /* WOLFSSL_KEY_GEN */
  27680. }
  27681. #endif /* OPENSSL_EXTRA && HAVE_CURVE448 */
  27682. #if defined(OPENSSL_EXTRA) && defined(HAVE_ED448)
  27683. /* return 1 if success, 0 if error
  27684. * output keys are little endian format
  27685. */
  27686. int wolfSSL_ED448_generate_key(unsigned char *priv, unsigned int *privSz,
  27687. unsigned char *pub, unsigned int *pubSz)
  27688. {
  27689. #ifndef WOLFSSL_KEY_GEN
  27690. WOLFSSL_MSG("No Key Gen built in");
  27691. (void) priv;
  27692. (void) privSz;
  27693. (void) pub;
  27694. (void) pubSz;
  27695. return WOLFSSL_FAILURE;
  27696. #elif !defined(HAVE_ED448_KEY_EXPORT)
  27697. WOLFSSL_MSG("No ED448 key export built in");
  27698. (void) priv;
  27699. (void) privSz;
  27700. (void) pub;
  27701. (void) pubSz;
  27702. return WOLFSSL_FAILURE;
  27703. #else /* WOLFSSL_KEY_GEN && HAVE_ED448_KEY_EXPORT */
  27704. int ret = WOLFSSL_FAILURE;
  27705. int initTmpRng = 0;
  27706. WC_RNG *rng = NULL;
  27707. #ifdef WOLFSSL_SMALL_STACK
  27708. WC_RNG *tmpRNG = NULL;
  27709. #else
  27710. WC_RNG tmpRNG[1];
  27711. #endif
  27712. WOLFSSL_ENTER("wolfSSL_ED448_generate_key");
  27713. if (priv == NULL || privSz == NULL || *privSz < ED448_PRV_KEY_SIZE ||
  27714. pub == NULL || pubSz == NULL || *pubSz < ED448_PUB_KEY_SIZE) {
  27715. WOLFSSL_MSG("Bad arguments");
  27716. return WOLFSSL_FAILURE;
  27717. }
  27718. #ifdef WOLFSSL_SMALL_STACK
  27719. tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  27720. if (tmpRNG == NULL)
  27721. return WOLFSSL_FATAL_ERROR;
  27722. #endif
  27723. if (wc_InitRng(tmpRNG) == 0) {
  27724. rng = tmpRNG;
  27725. initTmpRng = 1;
  27726. }
  27727. else {
  27728. WOLFSSL_MSG("Bad RNG Init, trying global");
  27729. if (initGlobalRNG == 0)
  27730. WOLFSSL_MSG("Global RNG no Init");
  27731. else
  27732. rng = &globalRNG;
  27733. }
  27734. if (rng) {
  27735. ed448_key key;
  27736. if (wc_ed448_init(&key) != MP_OKAY)
  27737. WOLFSSL_MSG("wc_ed448_init failed");
  27738. else if (wc_ed448_make_key(rng, ED448_KEY_SIZE, &key) != MP_OKAY)
  27739. WOLFSSL_MSG("wc_ed448_make_key failed");
  27740. /* export private key */
  27741. else if (wc_ed448_export_key(&key, priv, privSz, pub, pubSz) != MP_OKAY)
  27742. WOLFSSL_MSG("wc_ed448_export_key failed");
  27743. else
  27744. ret = WOLFSSL_SUCCESS;
  27745. wc_ed448_free(&key);
  27746. }
  27747. if (initTmpRng)
  27748. wc_FreeRng(tmpRNG);
  27749. #ifdef WOLFSSL_SMALL_STACK
  27750. XFREE(tmpRNG, NULL, DYNAMIC_TYPE_RNG);
  27751. #endif
  27752. return ret;
  27753. #endif /* WOLFSSL_KEY_GEN && HAVE_ED448_KEY_EXPORT */
  27754. }
  27755. /* return 1 if success, 0 if error
  27756. * input and output keys are little endian format
  27757. * priv is a buffer containing private and public part of key
  27758. */
  27759. int wolfSSL_ED448_sign(const unsigned char *msg, unsigned int msgSz,
  27760. const unsigned char *priv, unsigned int privSz,
  27761. unsigned char *sig, unsigned int *sigSz)
  27762. {
  27763. #if !defined(HAVE_ED448_SIGN) || !defined(WOLFSSL_KEY_GEN) || !defined(HAVE_ED448_KEY_IMPORT)
  27764. #if !defined(HAVE_ED448_SIGN)
  27765. WOLFSSL_MSG("No ED448 sign built in");
  27766. #elif !defined(WOLFSSL_KEY_GEN)
  27767. WOLFSSL_MSG("No Key Gen built in");
  27768. #elif !defined(HAVE_ED448_KEY_IMPORT)
  27769. WOLFSSL_MSG("No ED448 Key import built in");
  27770. #endif
  27771. (void) msg;
  27772. (void) msgSz;
  27773. (void) priv;
  27774. (void) privSz;
  27775. (void) sig;
  27776. (void) sigSz;
  27777. return WOLFSSL_FAILURE;
  27778. #else /* HAVE_ED448_SIGN && WOLFSSL_KEY_GEN && HAVE_ED448_KEY_IMPORT */
  27779. ed448_key key;
  27780. int ret = WOLFSSL_FAILURE;
  27781. WOLFSSL_ENTER("wolfSSL_ED448_sign");
  27782. if (priv == NULL || privSz != ED448_PRV_KEY_SIZE || msg == NULL ||
  27783. sig == NULL || *sigSz < ED448_SIG_SIZE) {
  27784. WOLFSSL_MSG("Bad arguments");
  27785. return WOLFSSL_FAILURE;
  27786. }
  27787. /* import key */
  27788. if (wc_ed448_init(&key) != MP_OKAY) {
  27789. WOLFSSL_MSG("wc_curve448_init failed");
  27790. return ret;
  27791. }
  27792. if (wc_ed448_import_private_key(priv, privSz/2, priv+(privSz/2),
  27793. ED448_PUB_KEY_SIZE, &key) != MP_OKAY){
  27794. WOLFSSL_MSG("wc_ed448_import_private failed");
  27795. wc_ed448_free(&key);
  27796. return ret;
  27797. }
  27798. if (wc_ed448_sign_msg(msg, msgSz, sig, sigSz, &key, NULL, 0) != MP_OKAY)
  27799. WOLFSSL_MSG("wc_curve448_shared_secret_ex failed");
  27800. else
  27801. ret = WOLFSSL_SUCCESS;
  27802. wc_ed448_free(&key);
  27803. return ret;
  27804. #endif /* HAVE_ED448_SIGN && WOLFSSL_KEY_GEN && HAVE_ED448_KEY_IMPORT */
  27805. }
  27806. /* return 1 if success, 0 if error
  27807. * input and output keys are little endian format
  27808. * pub is a buffer containing public part of key
  27809. */
  27810. int wolfSSL_ED448_verify(const unsigned char *msg, unsigned int msgSz,
  27811. const unsigned char *pub, unsigned int pubSz,
  27812. const unsigned char *sig, unsigned int sigSz)
  27813. {
  27814. #if !defined(HAVE_ED448_VERIFY) || !defined(WOLFSSL_KEY_GEN) || !defined(HAVE_ED448_KEY_IMPORT)
  27815. #if !defined(HAVE_ED448_VERIFY)
  27816. WOLFSSL_MSG("No ED448 verify built in");
  27817. #elif !defined(WOLFSSL_KEY_GEN)
  27818. WOLFSSL_MSG("No Key Gen built in");
  27819. #elif !defined(HAVE_ED448_KEY_IMPORT)
  27820. WOLFSSL_MSG("No ED448 Key import built in");
  27821. #endif
  27822. (void) msg;
  27823. (void) msgSz;
  27824. (void) pub;
  27825. (void) pubSz;
  27826. (void) sig;
  27827. (void) sigSz;
  27828. return WOLFSSL_FAILURE;
  27829. #else /* HAVE_ED448_VERIFY && WOLFSSL_KEY_GEN && HAVE_ED448_KEY_IMPORT */
  27830. ed448_key key;
  27831. int ret = WOLFSSL_FAILURE, check = 0;
  27832. WOLFSSL_ENTER("wolfSSL_ED448_verify");
  27833. if (pub == NULL || pubSz != ED448_PUB_KEY_SIZE || msg == NULL ||
  27834. sig == NULL || sigSz != ED448_SIG_SIZE) {
  27835. WOLFSSL_MSG("Bad arguments");
  27836. return WOLFSSL_FAILURE;
  27837. }
  27838. /* import key */
  27839. if (wc_ed448_init(&key) != MP_OKAY) {
  27840. WOLFSSL_MSG("wc_curve448_init failed");
  27841. return ret;
  27842. }
  27843. if (wc_ed448_import_public(pub, pubSz, &key) != MP_OKAY){
  27844. WOLFSSL_MSG("wc_ed448_import_public failed");
  27845. wc_ed448_free(&key);
  27846. return ret;
  27847. }
  27848. if ((ret = wc_ed448_verify_msg((byte*)sig, sigSz, msg, msgSz, &check,
  27849. &key, NULL, 0)) != MP_OKAY) {
  27850. WOLFSSL_MSG("wc_ed448_verify_msg failed");
  27851. }
  27852. else if (!check)
  27853. WOLFSSL_MSG("wc_ed448_verify_msg failed (signature invalid)");
  27854. else
  27855. ret = WOLFSSL_SUCCESS;
  27856. wc_ed448_free(&key);
  27857. return ret;
  27858. #endif /* HAVE_ED448_VERIFY && WOLFSSL_KEY_GEN */
  27859. }
  27860. #endif /* OPENSSL_EXTRA && HAVE_ED448 */
  27861. #ifdef WOLFSSL_JNI
  27862. int wolfSSL_set_jobject(WOLFSSL* ssl, void* objPtr)
  27863. {
  27864. WOLFSSL_ENTER("wolfSSL_set_jobject");
  27865. if (ssl != NULL)
  27866. {
  27867. ssl->jObjectRef = objPtr;
  27868. return WOLFSSL_SUCCESS;
  27869. }
  27870. return WOLFSSL_FAILURE;
  27871. }
  27872. void* wolfSSL_get_jobject(WOLFSSL* ssl)
  27873. {
  27874. WOLFSSL_ENTER("wolfSSL_get_jobject");
  27875. if (ssl != NULL)
  27876. return ssl->jObjectRef;
  27877. return NULL;
  27878. }
  27879. #endif /* WOLFSSL_JNI */
  27880. #ifdef WOLFSSL_ASYNC_CRYPT
  27881. int wolfSSL_CTX_AsyncPoll(WOLFSSL_CTX* ctx, WOLF_EVENT** events, int maxEvents,
  27882. WOLF_EVENT_FLAG flags, int* eventCount)
  27883. {
  27884. if (ctx == NULL) {
  27885. return BAD_FUNC_ARG;
  27886. }
  27887. return wolfAsync_EventQueuePoll(&ctx->event_queue, NULL,
  27888. events, maxEvents, flags, eventCount);
  27889. }
  27890. int wolfSSL_AsyncPoll(WOLFSSL* ssl, WOLF_EVENT_FLAG flags)
  27891. {
  27892. int ret, eventCount = 0;
  27893. WOLF_EVENT* events[1];
  27894. if (ssl == NULL) {
  27895. return BAD_FUNC_ARG;
  27896. }
  27897. ret = wolfAsync_EventQueuePoll(&ssl->ctx->event_queue, ssl,
  27898. events, sizeof(events)/sizeof(events[0]), flags, &eventCount);
  27899. if (ret == 0) {
  27900. ret = eventCount;
  27901. }
  27902. return ret;
  27903. }
  27904. #endif /* WOLFSSL_ASYNC_CRYPT */
  27905. #ifdef OPENSSL_EXTRA
  27906. unsigned long wolfSSL_ERR_peek_error_line_data(const char **file, int *line,
  27907. const char **data, int *flags)
  27908. {
  27909. WOLFSSL_ENTER("wolfSSL_ERR_peek_error_line_data");
  27910. (void)line;
  27911. (void)file;
  27912. /* No data or flags stored - error display only in Nginx. */
  27913. if (data != NULL) {
  27914. *data = "";
  27915. }
  27916. if (flags != NULL) {
  27917. *flags = 0;
  27918. }
  27919. #ifdef WOLFSSL_HAVE_ERROR_QUEUE
  27920. {
  27921. int ret = 0;
  27922. while (1) {
  27923. ret = wc_PeekErrorNode(0, file, NULL, line);
  27924. if (ret == BAD_MUTEX_E || ret == BAD_FUNC_ARG || ret == BAD_STATE_E) {
  27925. WOLFSSL_MSG("Issue peeking at error node in queue");
  27926. return 0;
  27927. }
  27928. /* OpenSSL uses positive error codes */
  27929. if (ret < 0) {
  27930. ret = -ret;
  27931. }
  27932. if (ret == -ASN_NO_PEM_HEADER)
  27933. return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE;
  27934. #ifdef OPENSSL_ALL
  27935. /* PARSE_ERROR is returned if an HTTP request is detected. */
  27936. if (ret == -SSL_R_HTTP_REQUEST)
  27937. return (ERR_LIB_SSL << 24) | -SSL_R_HTTP_REQUEST;
  27938. #endif
  27939. #if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
  27940. if (ret == ASN1_R_HEADER_TOO_LONG) {
  27941. return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG;
  27942. }
  27943. #endif
  27944. if (ret != -WANT_READ && ret != -WANT_WRITE &&
  27945. ret != -ZERO_RETURN && ret != -WOLFSSL_ERROR_ZERO_RETURN &&
  27946. ret != -SOCKET_PEER_CLOSED_E && ret != -SOCKET_ERROR_E)
  27947. break;
  27948. wc_RemoveErrorNode(0);
  27949. }
  27950. return (unsigned long)ret;
  27951. }
  27952. #else
  27953. return (unsigned long)(0 - NOT_COMPILED_IN);
  27954. #endif
  27955. }
  27956. #endif
  27957. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  27958. #if !defined(WOLFSSL_USER_IO)
  27959. /* converts an IPv6 or IPv4 address into an octet string for use with rfc3280
  27960. * example input would be "127.0.0.1" and the returned value would be 7F000001
  27961. */
  27962. WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa)
  27963. {
  27964. int ipaSz = WOLFSSL_IP4_ADDR_LEN;
  27965. char buf[WOLFSSL_IP6_ADDR_LEN + 1]; /* plus 1 for terminator */
  27966. int af = WOLFSSL_IP4;
  27967. WOLFSSL_ASN1_STRING *ret = NULL;
  27968. if (ipa == NULL)
  27969. return NULL;
  27970. if (XSTRSTR(ipa, ":") != NULL) {
  27971. af = WOLFSSL_IP6;
  27972. ipaSz = WOLFSSL_IP6_ADDR_LEN;
  27973. }
  27974. buf[WOLFSSL_IP6_ADDR_LEN] = '\0';
  27975. if (XINET_PTON(af, ipa, (void*)buf) != 1) {
  27976. WOLFSSL_MSG("Error parsing IP address");
  27977. return NULL;
  27978. }
  27979. ret = wolfSSL_ASN1_STRING_new();
  27980. if (ret != NULL) {
  27981. if (wolfSSL_ASN1_STRING_set(ret, buf, ipaSz) != WOLFSSL_SUCCESS) {
  27982. WOLFSSL_MSG("Error setting the string");
  27983. wolfSSL_ASN1_STRING_free(ret);
  27984. ret = NULL;
  27985. }
  27986. }
  27987. return ret;
  27988. }
  27989. #endif /* !WOLFSSL_USER_IO */
  27990. /* Is the specified cipher suite a fake one used an an extension proxy? */
  27991. static WC_INLINE int SCSV_Check(byte suite0, byte suite)
  27992. {
  27993. (void)suite0;
  27994. (void)suite;
  27995. #ifdef HAVE_RENEGOTIATION_INDICATION
  27996. if (suite0 == CIPHER_BYTE && suite == TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
  27997. return 1;
  27998. #endif
  27999. return 0;
  28000. }
  28001. static WC_INLINE int sslCipherMinMaxCheck(const WOLFSSL *ssl, byte suite0,
  28002. byte suite)
  28003. {
  28004. const CipherSuiteInfo* cipher_names = GetCipherNames();
  28005. int cipherSz = GetCipherNamesSize();
  28006. int i;
  28007. for (i = 0; i < cipherSz; i++)
  28008. if (cipher_names[i].cipherSuite0 == suite0 &&
  28009. cipher_names[i].cipherSuite == suite)
  28010. break;
  28011. if (i == cipherSz)
  28012. return 1;
  28013. /* Check min version */
  28014. if (cipher_names[i].minor < ssl->options.minDowngrade) {
  28015. if (ssl->options.minDowngrade <= TLSv1_2_MINOR &&
  28016. cipher_names[i].minor >= TLSv1_MINOR)
  28017. /* 1.0 ciphersuites are in general available in 1.1 and
  28018. * 1.1 ciphersuites are in general available in 1.2 */
  28019. return 0;
  28020. return 1;
  28021. }
  28022. /* Check max version */
  28023. switch (cipher_names[i].minor) {
  28024. case SSLv3_MINOR :
  28025. return ssl->options.mask & WOLFSSL_OP_NO_SSLv3;
  28026. case TLSv1_MINOR :
  28027. return ssl->options.mask & WOLFSSL_OP_NO_TLSv1;
  28028. case TLSv1_1_MINOR :
  28029. return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1;
  28030. case TLSv1_2_MINOR :
  28031. return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2;
  28032. case TLSv1_3_MINOR :
  28033. return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3;
  28034. default:
  28035. WOLFSSL_MSG("Unrecognized minor version");
  28036. return 1;
  28037. }
  28038. }
  28039. /* returns a pointer to internal cipher suite list. Should not be free'd by
  28040. * caller.
  28041. */
  28042. WOLF_STACK_OF(WOLFSSL_CIPHER) *wolfSSL_get_ciphers_compat(const WOLFSSL *ssl)
  28043. {
  28044. WOLF_STACK_OF(WOLFSSL_CIPHER)* ret = NULL;
  28045. Suites* suites;
  28046. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  28047. const CipherSuiteInfo* cipher_names = GetCipherNames();
  28048. int cipherSz = GetCipherNamesSize();
  28049. #endif
  28050. WOLFSSL_ENTER("wolfSSL_get_ciphers_compat");
  28051. if (ssl == NULL || (ssl->suites == NULL && ssl->ctx->suites == NULL)) {
  28052. return NULL;
  28053. }
  28054. if (ssl->suites != NULL) {
  28055. if (ssl->suites->suiteSz == 0 &&
  28056. InitSSL_Suites((WOLFSSL*)ssl) != WOLFSSL_SUCCESS) {
  28057. WOLFSSL_MSG("Suite initialization failure");
  28058. return NULL;
  28059. }
  28060. suites = ssl->suites;
  28061. }
  28062. else {
  28063. suites = ssl->ctx->suites;
  28064. }
  28065. /* check if stack needs populated */
  28066. if (suites->stack == NULL) {
  28067. int i;
  28068. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  28069. int j;
  28070. /* higher priority of cipher suite will be on top of stack */
  28071. for (i = suites->suiteSz - 2; i >=0; i-=2) {
  28072. #else
  28073. for (i = 0; i < suites->suiteSz; i+=2) {
  28074. #endif
  28075. WOLFSSL_STACK* add;
  28076. /* A couple of suites are placeholders for special options,
  28077. * skip those. */
  28078. if (SCSV_Check(suites->suites[i], suites->suites[i+1])
  28079. || sslCipherMinMaxCheck(ssl, suites->suites[i],
  28080. suites->suites[i+1])) {
  28081. continue;
  28082. }
  28083. add = wolfSSL_sk_new_node(ssl->heap);
  28084. if (add != NULL) {
  28085. add->type = STACK_TYPE_CIPHER;
  28086. add->data.cipher.cipherSuite0 = suites->suites[i];
  28087. add->data.cipher.cipherSuite = suites->suites[i+1];
  28088. add->data.cipher.ssl = ssl;
  28089. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  28090. for (j = 0; j < cipherSz; j++) {
  28091. if (cipher_names[j].cipherSuite0 ==
  28092. add->data.cipher.cipherSuite0 &&
  28093. cipher_names[j].cipherSuite ==
  28094. add->data.cipher.cipherSuite) {
  28095. add->data.cipher.offset = j;
  28096. break;
  28097. }
  28098. }
  28099. #endif
  28100. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
  28101. /* in_stack is checked in wolfSSL_CIPHER_description */
  28102. add->data.cipher.in_stack = 1;
  28103. #endif
  28104. add->next = ret;
  28105. if (ret != NULL) {
  28106. add->num = ret->num + 1;
  28107. }
  28108. else {
  28109. add->num = 1;
  28110. }
  28111. ret = add;
  28112. }
  28113. }
  28114. suites->stack = ret;
  28115. }
  28116. return suites->stack;
  28117. }
  28118. #endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
  28119. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
  28120. || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || defined(HAVE_SECRET_CALLBACK)
  28121. long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx)
  28122. {
  28123. WOLFSSL_ENTER("wolfSSL_SSL_CTX_get_timeout");
  28124. if (ctx == NULL)
  28125. return 0;
  28126. return ctx->timeout;
  28127. }
  28128. /* returns the time in seconds of the current timeout */
  28129. long wolfSSL_get_timeout(WOLFSSL* ssl)
  28130. {
  28131. WOLFSSL_ENTER("wolfSSL_get_timeout");
  28132. if (ssl == NULL)
  28133. return 0;
  28134. return ssl->timeout;
  28135. }
  28136. #endif
  28137. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
  28138. || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY)
  28139. #ifdef HAVE_ECC
  28140. int wolfSSL_SSL_CTX_set_tmp_ecdh(WOLFSSL_CTX *ctx, WOLFSSL_EC_KEY *ecdh)
  28141. {
  28142. WOLFSSL_ENTER("wolfSSL_SSL_CTX_set_tmp_ecdh");
  28143. if (ctx == NULL || ecdh == NULL)
  28144. return BAD_FUNC_ARG;
  28145. ctx->ecdhCurveOID = ecdh->group->curve_oid;
  28146. return WOLFSSL_SUCCESS;
  28147. }
  28148. #endif
  28149. /* Assumes that the session passed in is from the cache. */
  28150. int wolfSSL_SSL_CTX_remove_session(WOLFSSL_CTX *ctx, WOLFSSL_SESSION *s)
  28151. {
  28152. WOLFSSL_ENTER("wolfSSL_SSL_CTX_remove_session");
  28153. s = ClientSessionToSession(s);
  28154. if (ctx == NULL || s == NULL)
  28155. return BAD_FUNC_ARG;
  28156. #ifdef HAVE_EXT_CACHE
  28157. if (!ctx->internalCacheOff)
  28158. #endif
  28159. {
  28160. /* Don't remove session just timeout session. */
  28161. s->timeout = 0;
  28162. #ifndef NO_SESSION_CACHE
  28163. /* Clear the timeout in the cache */
  28164. {
  28165. int row;
  28166. int i;
  28167. SessionRow* sessRow = NULL;
  28168. WOLFSSL_SESSION *cacheSession;
  28169. const byte* id;
  28170. int ret = 0;
  28171. id = s->sessionID;
  28172. if (s->haveAltSessionID)
  28173. id = s->altSessionID;
  28174. row = (int)(HashObject(id, ID_LEN, &ret) % SESSION_ROWS);
  28175. if (ret != 0) {
  28176. WOLFSSL_MSG("Hash session failed");
  28177. return ret;
  28178. }
  28179. sessRow = &SessionCache[row];
  28180. if (SESSION_ROW_LOCK(sessRow) != 0) {
  28181. WOLFSSL_MSG("Session row lock failed");
  28182. return BAD_MUTEX_E;
  28183. }
  28184. for (i = 0; i < SESSIONS_PER_ROW && i < sessRow->totalCount; i++) {
  28185. cacheSession = &sessRow->Sessions[i];
  28186. if (XMEMCMP(id, cacheSession->sessionID, ID_LEN) == 0) {
  28187. if (ctx->method->side != cacheSession->side)
  28188. continue;
  28189. cacheSession->timeout = 0;
  28190. #ifdef HAVE_EX_DATA
  28191. if (cacheSession->ownExData) {
  28192. /* Most recent version of ex data is in cache. Copy it
  28193. * over so the user can free it. */
  28194. XMEMCPY(&s->ex_data, &cacheSession->ex_data,
  28195. sizeof(WOLFSSL_CRYPTO_EX_DATA));
  28196. }
  28197. cacheSession->ownExData = 0; /* We clear below */
  28198. s->ownExData = 1;
  28199. #endif
  28200. break;
  28201. }
  28202. }
  28203. SESSION_ROW_UNLOCK(sessRow);
  28204. }
  28205. #endif
  28206. }
  28207. #if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA)
  28208. if (ctx->rem_sess_cb != NULL) {
  28209. ctx->rem_sess_cb(ctx, s);
  28210. }
  28211. #endif
  28212. return 0;
  28213. }
  28214. #ifndef NO_BIO
  28215. BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s)
  28216. {
  28217. WOLFSSL_ENTER("wolfSSL_SSL_get_rbio");
  28218. /* Nginx sets the buffer size if the read BIO is different to write BIO.
  28219. * The setting buffer size doesn't do anything so return NULL for both.
  28220. */
  28221. if (s == NULL)
  28222. return NULL;
  28223. return s->biord;
  28224. }
  28225. BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s)
  28226. {
  28227. WOLFSSL_ENTER("wolfSSL_SSL_get_wbio");
  28228. (void)s;
  28229. /* Nginx sets the buffer size if the read BIO is different to write BIO.
  28230. * The setting buffer size doesn't do anything so return NULL for both.
  28231. */
  28232. if (s == NULL)
  28233. return NULL;
  28234. return s->biowr;
  28235. }
  28236. #endif /* !NO_BIO */
  28237. int wolfSSL_SSL_do_handshake(WOLFSSL *s)
  28238. {
  28239. WOLFSSL_ENTER("wolfSSL_SSL_do_handshake");
  28240. if (s == NULL)
  28241. return WOLFSSL_FAILURE;
  28242. if (s->options.side == WOLFSSL_CLIENT_END) {
  28243. #ifndef NO_WOLFSSL_CLIENT
  28244. return wolfSSL_connect(s);
  28245. #else
  28246. WOLFSSL_MSG("Client not compiled in");
  28247. return WOLFSSL_FAILURE;
  28248. #endif
  28249. }
  28250. #ifndef NO_WOLFSSL_SERVER
  28251. return wolfSSL_accept(s);
  28252. #else
  28253. WOLFSSL_MSG("Server not compiled in");
  28254. return WOLFSSL_FAILURE;
  28255. #endif
  28256. }
  28257. #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
  28258. int wolfSSL_SSL_in_init(const WOLFSSL *ssl)
  28259. #else
  28260. int wolfSSL_SSL_in_init(WOLFSSL *ssl)
  28261. #endif
  28262. {
  28263. WOLFSSL_ENTER("SSL_in_init");
  28264. if (ssl == NULL)
  28265. return WOLFSSL_FAILURE;
  28266. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  28267. return ssl->options.connectState < SECOND_REPLY_DONE;
  28268. }
  28269. return ssl->options.acceptState < ACCEPT_THIRD_REPLY_DONE;
  28270. }
  28271. int wolfSSL_SSL_in_connect_init(WOLFSSL* ssl)
  28272. {
  28273. WOLFSSL_ENTER("SSL_connect_init");
  28274. if (ssl == NULL)
  28275. return WOLFSSL_FAILURE;
  28276. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  28277. return ssl->options.connectState > CONNECT_BEGIN &&
  28278. ssl->options.connectState < SECOND_REPLY_DONE;
  28279. }
  28280. return ssl->options.acceptState > ACCEPT_BEGIN &&
  28281. ssl->options.acceptState < ACCEPT_THIRD_REPLY_DONE;
  28282. }
  28283. #ifndef NO_SESSION_CACHE
  28284. WOLFSSL_SESSION *wolfSSL_SSL_get0_session(const WOLFSSL *ssl)
  28285. {
  28286. WOLFSSL_ENTER("wolfSSL_SSL_get0_session");
  28287. return ssl->session;
  28288. }
  28289. #endif /* NO_SESSION_CACHE */
  28290. #ifndef NO_BIO
  28291. int wolfSSL_a2i_ASN1_INTEGER(WOLFSSL_BIO *bio, WOLFSSL_ASN1_INTEGER *asn1,
  28292. char *buf, int size)
  28293. {
  28294. int readNextLine;
  28295. int lineLen;
  28296. int len;
  28297. byte isNumCheck;
  28298. word32 outLen;
  28299. const int extraTagSz = MAX_LENGTH_SZ + 1;
  28300. byte intTag[MAX_LENGTH_SZ + 1];
  28301. int idx = 0;
  28302. WOLFSSL_ENTER("wolfSSL_a2i_ASN1_INTEGER");
  28303. if (!bio || !asn1 || !buf || size <= 0) {
  28304. WOLFSSL_MSG("Bad parameter");
  28305. return WOLFSSL_FAILURE;
  28306. }
  28307. /* Reset asn1 */
  28308. if (asn1->isDynamic && asn1->data) {
  28309. XFREE(asn1->data, NULL, DYNAMIC_TYPE_OPENSSL);
  28310. }
  28311. XMEMSET(asn1->intData, 0, WOLFSSL_ASN1_INTEGER_MAX);
  28312. asn1->data = asn1->intData;
  28313. asn1->isDynamic = 0;
  28314. asn1->length = 0;
  28315. asn1->negative = 0;
  28316. asn1->type = V_ASN1_INTEGER;
  28317. lineLen = wolfSSL_BIO_gets(bio, buf, size);
  28318. do {
  28319. readNextLine = 0;
  28320. if (lineLen <= 0) {
  28321. WOLFSSL_MSG("wolfSSL_BIO_gets error");
  28322. return WOLFSSL_FAILURE;
  28323. }
  28324. while (lineLen && (buf[lineLen-1] == '\n' || buf[lineLen-1] == '\r'))
  28325. lineLen--;
  28326. if (buf[lineLen-1] == '\\')
  28327. readNextLine = 1;
  28328. /* Ignore none-hex chars at the end of the line */
  28329. outLen = 1;
  28330. while (lineLen && Base16_Decode((byte*)buf + lineLen - 1, 1,
  28331. &isNumCheck, &outLen) == ASN_INPUT_E)
  28332. lineLen--;
  28333. if (!lineLen || lineLen % 2) {
  28334. WOLFSSL_MSG("Invalid line length");
  28335. return WOLFSSL_FAILURE;
  28336. }
  28337. len = asn1->length + (lineLen/2);
  28338. /* Check if it will fit in static memory and
  28339. * save space for the ASN tag in front */
  28340. if (len > (int)(WOLFSSL_ASN1_INTEGER_MAX - extraTagSz)) {
  28341. /* Allocate mem for data */
  28342. if (asn1->isDynamic) {
  28343. byte* tmp = (byte*)XREALLOC(asn1->data, len + extraTagSz, NULL,
  28344. DYNAMIC_TYPE_OPENSSL);
  28345. if (!tmp) {
  28346. WOLFSSL_MSG("realloc error");
  28347. return WOLFSSL_FAILURE;
  28348. }
  28349. asn1->data = tmp;
  28350. }
  28351. else {
  28352. /* Up to this point asn1->data pointed to asn1->intData.
  28353. * Now that the size has grown larger than intData can handle
  28354. * the asn1 structure moves to a dynamic type with isDynamic
  28355. * flag being set and asn1->data being malloc'd. */
  28356. asn1->data = (byte*)XMALLOC(len + extraTagSz, NULL,
  28357. DYNAMIC_TYPE_OPENSSL);
  28358. if (!asn1->data) {
  28359. WOLFSSL_MSG("malloc error");
  28360. return WOLFSSL_FAILURE;
  28361. }
  28362. asn1->isDynamic = 1;
  28363. XMEMCPY(asn1->data, asn1->intData, asn1->length);
  28364. }
  28365. }
  28366. len = lineLen/2;
  28367. if (Base16_Decode((byte*)buf, lineLen, asn1->data + asn1->length,
  28368. (word32*)&len) != 0) {
  28369. WOLFSSL_MSG("Base16_Decode error");
  28370. return WOLFSSL_FAILURE;
  28371. }
  28372. asn1->length += len;
  28373. } while (readNextLine);
  28374. /* Write ASN tag */
  28375. idx = SetASNInt(asn1->length, asn1->data[0], intTag);
  28376. XMEMMOVE(asn1->data + idx, asn1->data, asn1->length);
  28377. XMEMCPY(asn1->data, intTag, idx);
  28378. asn1->dataMax = asn1->length += idx;
  28379. return WOLFSSL_SUCCESS;
  28380. }
  28381. int wolfSSL_i2a_ASN1_INTEGER(BIO *bp, const WOLFSSL_ASN1_INTEGER *a)
  28382. {
  28383. word32 idx = 1;
  28384. int len = 0;
  28385. byte buf[512];
  28386. word32 bufLen = 512;
  28387. WOLFSSL_ENTER("wolfSSL_i2a_ASN1_INTEGER");
  28388. if (bp == NULL || a == NULL)
  28389. return WOLFSSL_FAILURE;
  28390. /* Skip ASN.1 INTEGER (type) byte. */
  28391. if (a->data[idx] == 0x80 || /* Indefinite length, can't determine length */
  28392. GetLength(a->data, &idx, &len, a->length) < 0) {
  28393. return 0;
  28394. }
  28395. /* Zero length integer is the value zero. */
  28396. if (len == 0) {
  28397. return wolfSSL_BIO_write(bp, "00", 2);
  28398. }
  28399. if (Base16_Encode(a->data + idx, len, buf, &bufLen) != 0 ||
  28400. bufLen == 0) {
  28401. return 0;
  28402. }
  28403. return wolfSSL_BIO_write(bp, buf, bufLen - 1); /* Don't write out NULL char */
  28404. }
  28405. #endif /* !NO_BIO */
  28406. #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER)
  28407. /* Expected return values from implementations of OpenSSL ticket key callback.
  28408. */
  28409. #define TICKET_KEY_CB_RET_FAILURE (-1)
  28410. #define TICKET_KEY_CB_RET_NOT_FOUND 0
  28411. #define TICKET_KEY_CB_RET_OK 1
  28412. #define TICKET_KEY_CB_RET_RENEW 2
  28413. /* Implementation of session ticket encryption/decryption using OpenSSL
  28414. * callback to initialize the cipher and HMAC.
  28415. *
  28416. * ssl The SSL/TLS object.
  28417. * keyName The key name - used to identify the key to be used.
  28418. * iv The IV to use.
  28419. * mac The MAC of the encrypted data.
  28420. * enc Encrypt ticket.
  28421. * encTicket The ticket data.
  28422. * encTicketLen The length of the ticket data.
  28423. * encLen The encrypted/decrypted ticket length - output length.
  28424. * ctx Ignored. Application specific data.
  28425. * returns WOLFSSL_TICKET_RET_OK to indicate success,
  28426. * WOLFSSL_TICKET_RET_CREATE if a new ticket is required and
  28427. * WOLFSSL_TICKET_RET_FATAL on error.
  28428. */
  28429. static int wolfSSL_TicketKeyCb(WOLFSSL* ssl,
  28430. unsigned char keyName[WOLFSSL_TICKET_NAME_SZ],
  28431. unsigned char iv[WOLFSSL_TICKET_IV_SZ],
  28432. unsigned char mac[WOLFSSL_TICKET_MAC_SZ],
  28433. int enc, unsigned char* encTicket,
  28434. int encTicketLen, int* encLen, void* ctx)
  28435. {
  28436. byte digest[WC_MAX_DIGEST_SIZE];
  28437. #ifdef WOLFSSL_SMALL_STACK
  28438. WOLFSSL_EVP_CIPHER_CTX *evpCtx;
  28439. #else
  28440. WOLFSSL_EVP_CIPHER_CTX evpCtx[1];
  28441. #endif
  28442. WOLFSSL_HMAC_CTX hmacCtx;
  28443. unsigned int mdSz = 0;
  28444. int len = 0;
  28445. int ret = WOLFSSL_TICKET_RET_FATAL;
  28446. int res;
  28447. int totalSz = 0;
  28448. (void)ctx;
  28449. WOLFSSL_ENTER("wolfSSL_TicketKeyCb");
  28450. if (ssl == NULL || ssl->ctx == NULL || ssl->ctx->ticketEncWrapCb == NULL) {
  28451. WOLFSSL_MSG("Bad parameter");
  28452. return WOLFSSL_TICKET_RET_FATAL;
  28453. }
  28454. #ifdef WOLFSSL_SMALL_STACK
  28455. evpCtx = (WOLFSSL_EVP_CIPHER_CTX *)XMALLOC(sizeof(*evpCtx), ssl->heap,
  28456. DYNAMIC_TYPE_TMP_BUFFER);
  28457. if (evpCtx == NULL) {
  28458. WOLFSSL_MSG("out of memory");
  28459. return WOLFSSL_TICKET_RET_FATAL;
  28460. }
  28461. #endif
  28462. /* Initialize the cipher and HMAC. */
  28463. wolfSSL_EVP_CIPHER_CTX_init(evpCtx);
  28464. if (wolfSSL_HMAC_CTX_Init(&hmacCtx) != WOLFSSL_SUCCESS) {
  28465. WOLFSSL_MSG("wolfSSL_HMAC_CTX_Init error");
  28466. #ifdef WOLFSSL_SMALL_STACK
  28467. XFREE(evpCtx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28468. #endif
  28469. return WOLFSSL_TICKET_RET_FATAL;
  28470. }
  28471. res = ssl->ctx->ticketEncWrapCb(ssl, keyName,
  28472. iv, evpCtx, &hmacCtx, enc);
  28473. if (res != TICKET_KEY_CB_RET_OK && res != TICKET_KEY_CB_RET_RENEW) {
  28474. WOLFSSL_MSG("Ticket callback error");
  28475. ret = WOLFSSL_TICKET_RET_FATAL;
  28476. goto end;
  28477. }
  28478. if (wolfSSL_HMAC_size(&hmacCtx) > WOLFSSL_TICKET_MAC_SZ) {
  28479. WOLFSSL_MSG("Ticket cipher MAC size error");
  28480. goto end;
  28481. }
  28482. if (enc)
  28483. {
  28484. /* Encrypt in place. */
  28485. if (!wolfSSL_EVP_CipherUpdate(evpCtx, encTicket, &len,
  28486. encTicket, encTicketLen))
  28487. goto end;
  28488. totalSz = len;
  28489. if (totalSz > *encLen)
  28490. goto end;
  28491. if (!wolfSSL_EVP_EncryptFinal(evpCtx, &encTicket[len], &len))
  28492. goto end;
  28493. /* Total length of encrypted data. */
  28494. totalSz += len;
  28495. if (totalSz > *encLen)
  28496. goto end;
  28497. /* HMAC the encrypted data into the parameter 'mac'. */
  28498. if (!wolfSSL_HMAC_Update(&hmacCtx, encTicket, totalSz))
  28499. goto end;
  28500. if (!wolfSSL_HMAC_Final(&hmacCtx, mac, &mdSz))
  28501. goto end;
  28502. }
  28503. else
  28504. {
  28505. /* HMAC the encrypted data and compare it to the passed in data. */
  28506. if (!wolfSSL_HMAC_Update(&hmacCtx, encTicket, encTicketLen))
  28507. goto end;
  28508. if (!wolfSSL_HMAC_Final(&hmacCtx, digest, &mdSz))
  28509. goto end;
  28510. if (XMEMCMP(mac, digest, mdSz) != 0)
  28511. goto end;
  28512. /* Decrypt the ticket data in place. */
  28513. if (!wolfSSL_EVP_CipherUpdate(evpCtx, encTicket, &len,
  28514. encTicket, encTicketLen))
  28515. goto end;
  28516. totalSz = len;
  28517. if (totalSz > encTicketLen)
  28518. goto end;
  28519. if (!wolfSSL_EVP_DecryptFinal(evpCtx, &encTicket[len], &len))
  28520. goto end;
  28521. /* Total length of decrypted data. */
  28522. totalSz += len;
  28523. if (totalSz > encTicketLen)
  28524. goto end;
  28525. }
  28526. *encLen = totalSz;
  28527. if (res == TICKET_KEY_CB_RET_RENEW && !IsAtLeastTLSv1_3(ssl->version)
  28528. && !enc)
  28529. ret = WOLFSSL_TICKET_RET_CREATE;
  28530. else
  28531. ret = WOLFSSL_TICKET_RET_OK;
  28532. end:
  28533. (void)wc_HmacFree(&hmacCtx.hmac);
  28534. #ifdef WOLFSSL_SMALL_STACK
  28535. XFREE(evpCtx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28536. #endif
  28537. return ret;
  28538. }
  28539. /* Set the callback to use when encrypting/decrypting tickets.
  28540. *
  28541. * ctx The SSL/TLS context object.
  28542. * cb The OpenSSL session ticket callback.
  28543. * returns WOLFSSL_SUCCESS to indicate success.
  28544. */
  28545. int wolfSSL_CTX_set_tlsext_ticket_key_cb(WOLFSSL_CTX *ctx, ticketCompatCb cb)
  28546. {
  28547. /* Set the ticket encryption callback to be a wrapper around OpenSSL
  28548. * callback.
  28549. */
  28550. ctx->ticketEncCb = wolfSSL_TicketKeyCb;
  28551. ctx->ticketEncWrapCb = cb;
  28552. return WOLFSSL_SUCCESS;
  28553. }
  28554. #endif /* HAVE_SESSION_TICKET */
  28555. #endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY ||
  28556. OPENSSL_EXTRA || HAVE_LIGHTY */
  28557. #if defined(HAVE_SESSION_TICKET) && !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && \
  28558. !defined(NO_WOLFSSL_SERVER)
  28559. /* Serialize the session ticket encryption keys.
  28560. *
  28561. * @param [in] ctx SSL/TLS context object.
  28562. * @param [in] keys Buffer to hold session ticket keys.
  28563. * @param [in] keylen Length of buffer.
  28564. * @return WOLFSSL_SUCCESS on success.
  28565. * @return WOLFSSL_FAILURE when ctx is NULL, keys is NULL or keylen is not the
  28566. * correct length.
  28567. */
  28568. long wolfSSL_CTX_get_tlsext_ticket_keys(WOLFSSL_CTX *ctx,
  28569. unsigned char *keys, int keylen)
  28570. {
  28571. if (ctx == NULL || keys == NULL) {
  28572. return WOLFSSL_FAILURE;
  28573. }
  28574. if (keylen != WOLFSSL_TICKET_KEYS_SZ) {
  28575. return WOLFSSL_FAILURE;
  28576. }
  28577. XMEMCPY(keys, ctx->ticketKeyCtx.name, WOLFSSL_TICKET_NAME_SZ);
  28578. keys += WOLFSSL_TICKET_NAME_SZ;
  28579. XMEMCPY(keys, ctx->ticketKeyCtx.key[0], WOLFSSL_TICKET_KEY_SZ);
  28580. keys += WOLFSSL_TICKET_KEY_SZ;
  28581. XMEMCPY(keys, ctx->ticketKeyCtx.key[1], WOLFSSL_TICKET_KEY_SZ);
  28582. keys += WOLFSSL_TICKET_KEY_SZ;
  28583. c32toa(ctx->ticketKeyCtx.expirary[0], keys);
  28584. keys += OPAQUE32_LEN;
  28585. c32toa(ctx->ticketKeyCtx.expirary[1], keys);
  28586. return WOLFSSL_SUCCESS;
  28587. }
  28588. /* Deserialize the session ticket encryption keys.
  28589. *
  28590. * @param [in] ctx SSL/TLS context object.
  28591. * @param [in] keys Session ticket keys.
  28592. * @param [in] keylen Length of data.
  28593. * @return WOLFSSL_SUCCESS on success.
  28594. * @return WOLFSSL_FAILURE when ctx is NULL, keys is NULL or keylen is not the
  28595. * correct length.
  28596. */
  28597. long wolfSSL_CTX_set_tlsext_ticket_keys(WOLFSSL_CTX *ctx,
  28598. unsigned char *keys, int keylen)
  28599. {
  28600. if (ctx == NULL || keys == NULL) {
  28601. return WOLFSSL_FAILURE;
  28602. }
  28603. if (keylen != WOLFSSL_TICKET_KEYS_SZ) {
  28604. return WOLFSSL_FAILURE;
  28605. }
  28606. XMEMCPY(ctx->ticketKeyCtx.name, keys, WOLFSSL_TICKET_NAME_SZ);
  28607. keys += WOLFSSL_TICKET_NAME_SZ;
  28608. XMEMCPY(ctx->ticketKeyCtx.key[0], keys, WOLFSSL_TICKET_KEY_SZ);
  28609. keys += WOLFSSL_TICKET_KEY_SZ;
  28610. XMEMCPY(ctx->ticketKeyCtx.key[1], keys, WOLFSSL_TICKET_KEY_SZ);
  28611. keys += WOLFSSL_TICKET_KEY_SZ;
  28612. ato32(keys, &ctx->ticketKeyCtx.expirary[0]);
  28613. keys += OPAQUE32_LEN;
  28614. ato32(keys, &ctx->ticketKeyCtx.expirary[1]);
  28615. return WOLFSSL_SUCCESS;
  28616. }
  28617. #endif
  28618. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  28619. #ifdef HAVE_OCSP
  28620. /* Not an OpenSSL API. */
  28621. int wolfSSL_get_ocsp_response(WOLFSSL* ssl, byte** response)
  28622. {
  28623. *response = ssl->ocspResp;
  28624. return ssl->ocspRespSz;
  28625. }
  28626. /* Not an OpenSSL API. */
  28627. char* wolfSSL_get_ocsp_url(WOLFSSL* ssl)
  28628. {
  28629. return ssl->url;
  28630. }
  28631. /* Not an OpenSSL API. */
  28632. int wolfSSL_set_ocsp_url(WOLFSSL* ssl, char* url)
  28633. {
  28634. if (ssl == NULL)
  28635. return WOLFSSL_FAILURE;
  28636. ssl->url = url;
  28637. return WOLFSSL_SUCCESS;
  28638. }
  28639. #endif /* OCSP */
  28640. #endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
  28641. #if defined(HAVE_OCSP) && !defined(NO_ASN_TIME)
  28642. int wolfSSL_get_ocsp_producedDate(
  28643. WOLFSSL *ssl,
  28644. byte *producedDate,
  28645. size_t producedDate_space,
  28646. int *producedDateFormat)
  28647. {
  28648. if ((ssl->ocspProducedDateFormat != ASN_UTC_TIME) &&
  28649. (ssl->ocspProducedDateFormat != ASN_GENERALIZED_TIME))
  28650. return BAD_FUNC_ARG;
  28651. if ((producedDate == NULL) || (producedDateFormat == NULL))
  28652. return BAD_FUNC_ARG;
  28653. if (XSTRLEN((char *)ssl->ocspProducedDate) >= producedDate_space)
  28654. return BUFFER_E;
  28655. XSTRNCPY((char *)producedDate, (const char *)ssl->ocspProducedDate, producedDate_space);
  28656. *producedDateFormat = ssl->ocspProducedDateFormat;
  28657. return 0;
  28658. }
  28659. int wolfSSL_get_ocsp_producedDate_tm(WOLFSSL *ssl, struct tm *produced_tm) {
  28660. int idx = 0;
  28661. if ((ssl->ocspProducedDateFormat != ASN_UTC_TIME) &&
  28662. (ssl->ocspProducedDateFormat != ASN_GENERALIZED_TIME))
  28663. return BAD_FUNC_ARG;
  28664. if (produced_tm == NULL)
  28665. return BAD_FUNC_ARG;
  28666. if (ExtractDate(ssl->ocspProducedDate,
  28667. (unsigned char)ssl->ocspProducedDateFormat, produced_tm, &idx))
  28668. return 0;
  28669. else
  28670. return ASN_PARSE_E;
  28671. }
  28672. #endif
  28673. #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \
  28674. defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
  28675. int wolfSSL_CTX_get_extra_chain_certs(WOLFSSL_CTX* ctx, WOLF_STACK_OF(X509)** chain)
  28676. {
  28677. word32 idx;
  28678. word32 length;
  28679. WOLFSSL_STACK* node;
  28680. WOLFSSL_STACK* last = NULL;
  28681. if (ctx == NULL || chain == NULL) {
  28682. chain = NULL;
  28683. return WOLFSSL_FAILURE;
  28684. }
  28685. if (ctx->x509Chain != NULL) {
  28686. *chain = ctx->x509Chain;
  28687. return WOLFSSL_SUCCESS;
  28688. }
  28689. /* If there are no chains then success! */
  28690. *chain = NULL;
  28691. if (ctx->certChain == NULL || ctx->certChain->length == 0) {
  28692. return WOLFSSL_SUCCESS;
  28693. }
  28694. /* Create a new stack of WOLFSSL_X509 object from chain buffer. */
  28695. for (idx = 0; idx < ctx->certChain->length; ) {
  28696. node = (WOLFSSL_STACK*)XMALLOC(sizeof(WOLFSSL_STACK), NULL,
  28697. DYNAMIC_TYPE_OPENSSL);
  28698. if (node == NULL)
  28699. return WOLFSSL_FAILURE;
  28700. node->next = NULL;
  28701. /* 3 byte length | X509 DER data */
  28702. ato24(ctx->certChain->buffer + idx, &length);
  28703. idx += 3;
  28704. /* Create a new X509 from DER encoded data. */
  28705. node->data.x509 = wolfSSL_X509_d2i(NULL, ctx->certChain->buffer + idx,
  28706. length);
  28707. if (node->data.x509 == NULL) {
  28708. XFREE(node, NULL, DYNAMIC_TYPE_OPENSSL);
  28709. /* Return as much of the chain as we created. */
  28710. ctx->x509Chain = *chain;
  28711. return WOLFSSL_FAILURE;
  28712. }
  28713. idx += length;
  28714. /* Add object to the end of the stack. */
  28715. if (last == NULL) {
  28716. node->num = 1;
  28717. *chain = node;
  28718. }
  28719. else {
  28720. (*chain)->num++;
  28721. last->next = node;
  28722. }
  28723. last = node;
  28724. }
  28725. ctx->x509Chain = *chain;
  28726. return WOLFSSL_SUCCESS;
  28727. }
  28728. int wolfSSL_CTX_get_tlsext_status_cb(WOLFSSL_CTX* ctx, tlsextStatusCb* cb)
  28729. {
  28730. if (ctx == NULL || ctx->cm == NULL || cb == NULL)
  28731. return WOLFSSL_FAILURE;
  28732. #if !defined(NO_WOLFSSL_SERVER) && (defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  28733. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))
  28734. if (ctx->cm->ocsp_stapling == NULL)
  28735. return WOLFSSL_FAILURE;
  28736. *cb = ctx->cm->ocsp_stapling->statusCb;
  28737. #else
  28738. (void)cb;
  28739. *cb = NULL;
  28740. #endif
  28741. return WOLFSSL_SUCCESS;
  28742. }
  28743. int wolfSSL_CTX_set_tlsext_status_cb(WOLFSSL_CTX* ctx, tlsextStatusCb cb)
  28744. {
  28745. if (ctx == NULL || ctx->cm == NULL)
  28746. return WOLFSSL_FAILURE;
  28747. #if !defined(NO_WOLFSSL_SERVER) && (defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  28748. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))
  28749. /* Ensure stapling is on for callback to be used. */
  28750. wolfSSL_CTX_EnableOCSPStapling(ctx);
  28751. if (ctx->cm->ocsp_stapling == NULL)
  28752. return WOLFSSL_FAILURE;
  28753. ctx->cm->ocsp_stapling->statusCb = cb;
  28754. #else
  28755. (void)cb;
  28756. #endif
  28757. return WOLFSSL_SUCCESS;
  28758. }
  28759. int wolfSSL_CTX_get0_chain_certs(WOLFSSL_CTX *ctx,
  28760. WOLF_STACK_OF(WOLFSSL_X509) **sk)
  28761. {
  28762. WOLFSSL_ENTER("wolfSSL_CTX_get0_chain_certs");
  28763. if (ctx == NULL || sk == NULL) {
  28764. WOLFSSL_MSG("Bad parameter");
  28765. return WOLFSSL_FAILURE;
  28766. }
  28767. *sk = ctx->x509Chain;
  28768. return WOLFSSL_SUCCESS;
  28769. }
  28770. #ifdef KEEP_OUR_CERT
  28771. int wolfSSL_get0_chain_certs(WOLFSSL *ssl,
  28772. WOLF_STACK_OF(WOLFSSL_X509) **sk)
  28773. {
  28774. WOLFSSL_ENTER("wolfSSL_get0_chain_certs");
  28775. if (ssl == NULL || sk == NULL) {
  28776. WOLFSSL_MSG("Bad parameter");
  28777. return WOLFSSL_FAILURE;
  28778. }
  28779. *sk = ssl->ourCertChain;
  28780. return WOLFSSL_SUCCESS;
  28781. }
  28782. #endif
  28783. WOLF_STACK_OF(WOLFSSL_STRING)* wolfSSL_sk_WOLFSSL_STRING_new(void)
  28784. {
  28785. WOLF_STACK_OF(WOLFSSL_STRING)* ret = wolfSSL_sk_new_node(NULL);
  28786. if (ret) {
  28787. ret->type = STACK_TYPE_STRING;
  28788. }
  28789. return ret;
  28790. }
  28791. void wolfSSL_WOLFSSL_STRING_free(WOLFSSL_STRING s)
  28792. {
  28793. WOLFSSL_ENTER("wolfSSL_WOLFSSL_STRING_free");
  28794. if (s != NULL)
  28795. XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL);
  28796. }
  28797. void wolfSSL_sk_WOLFSSL_STRING_free(WOLF_STACK_OF(WOLFSSL_STRING)* sk)
  28798. {
  28799. WOLFSSL_STACK* tmp;
  28800. WOLFSSL_ENTER("wolfSSL_sk_WOLFSSL_STRING_free");
  28801. if (sk == NULL)
  28802. return;
  28803. /* parse through stack freeing each node */
  28804. while (sk) {
  28805. tmp = sk->next;
  28806. XFREE(sk->data.string, NULL, DYNAMIC_TYPE_OPENSSL);
  28807. XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL);
  28808. sk = tmp;
  28809. }
  28810. }
  28811. WOLFSSL_STRING wolfSSL_sk_WOLFSSL_STRING_value(WOLF_STACK_OF(WOLFSSL_STRING)* strings,
  28812. int idx)
  28813. {
  28814. for (; idx > 0 && strings != NULL; idx--)
  28815. strings = strings->next;
  28816. if (strings == NULL)
  28817. return NULL;
  28818. return strings->data.string;
  28819. }
  28820. int wolfSSL_sk_WOLFSSL_STRING_num(WOLF_STACK_OF(WOLFSSL_STRING)* strings)
  28821. {
  28822. if (strings)
  28823. return (int)strings->num;
  28824. return 0;
  28825. }
  28826. #endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || OPENSSL_EXTRA || OPENSSL_ALL */
  28827. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  28828. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY) || \
  28829. defined(WOLFSSL_QUIC)
  28830. #ifdef HAVE_ALPN
  28831. void wolfSSL_get0_alpn_selected(const WOLFSSL *ssl, const unsigned char **data,
  28832. unsigned int *len)
  28833. {
  28834. word16 nameLen;
  28835. if (ssl != NULL && data != NULL && len != NULL) {
  28836. TLSX_ALPN_GetRequest(ssl->extensions, (void **)data, &nameLen);
  28837. *len = nameLen;
  28838. }
  28839. }
  28840. int wolfSSL_select_next_proto(unsigned char **out, unsigned char *outLen,
  28841. const unsigned char *in, unsigned int inLen,
  28842. const unsigned char *clientNames,
  28843. unsigned int clientLen)
  28844. {
  28845. unsigned int i, j;
  28846. byte lenIn, lenClient;
  28847. if (out == NULL || outLen == NULL || in == NULL || clientNames == NULL)
  28848. return OPENSSL_NPN_UNSUPPORTED;
  28849. for (i = 0; i < inLen; i += lenIn) {
  28850. lenIn = in[i++];
  28851. for (j = 0; j < clientLen; j += lenClient) {
  28852. lenClient = clientNames[j++];
  28853. if (lenIn != lenClient)
  28854. continue;
  28855. if (XMEMCMP(in + i, clientNames + j, lenIn) == 0) {
  28856. *out = (unsigned char *)(in + i);
  28857. *outLen = lenIn;
  28858. return OPENSSL_NPN_NEGOTIATED;
  28859. }
  28860. }
  28861. }
  28862. *out = (unsigned char *)clientNames + 1;
  28863. *outLen = clientNames[0];
  28864. return OPENSSL_NPN_NO_OVERLAP;
  28865. }
  28866. void wolfSSL_CTX_set_alpn_select_cb(WOLFSSL_CTX *ctx,
  28867. int (*cb) (WOLFSSL *ssl,
  28868. const unsigned char **out,
  28869. unsigned char *outlen,
  28870. const unsigned char *in,
  28871. unsigned int inlen,
  28872. void *arg), void *arg)
  28873. {
  28874. if (ctx != NULL) {
  28875. ctx->alpnSelect = cb;
  28876. ctx->alpnSelectArg = arg;
  28877. }
  28878. }
  28879. void wolfSSL_CTX_set_next_protos_advertised_cb(WOLFSSL_CTX *s,
  28880. int (*cb) (WOLFSSL *ssl,
  28881. const unsigned char
  28882. **out,
  28883. unsigned int *outlen,
  28884. void *arg), void *arg)
  28885. {
  28886. (void)s;
  28887. (void)cb;
  28888. (void)arg;
  28889. WOLFSSL_STUB("wolfSSL_CTX_set_next_protos_advertised_cb");
  28890. }
  28891. void wolfSSL_CTX_set_next_proto_select_cb(WOLFSSL_CTX *s,
  28892. int (*cb) (WOLFSSL *ssl,
  28893. unsigned char **out,
  28894. unsigned char *outlen,
  28895. const unsigned char *in,
  28896. unsigned int inlen,
  28897. void *arg), void *arg)
  28898. {
  28899. (void)s;
  28900. (void)cb;
  28901. (void)arg;
  28902. WOLFSSL_STUB("wolfSSL_CTX_set_next_proto_select_cb");
  28903. }
  28904. void wolfSSL_get0_next_proto_negotiated(const WOLFSSL *s, const unsigned char **data,
  28905. unsigned *len)
  28906. {
  28907. (void)s;
  28908. (void)data;
  28909. (void)len;
  28910. WOLFSSL_STUB("wolfSSL_get0_next_proto_negotiated");
  28911. }
  28912. #endif /* HAVE_ALPN */
  28913. #endif /* WOLFSSL_NGINX / WOLFSSL_HAPROXY */
  28914. #ifdef OPENSSL_EXTRA
  28915. int wolfSSL_curve_is_disabled(WOLFSSL* ssl, word16 curve_id)
  28916. {
  28917. return (curve_id <= WOLFSSL_ECC_MAX &&
  28918. ssl->disabledCurves &&
  28919. ssl->disabledCurves & (1 << curve_id));
  28920. }
  28921. #endif
  28922. #if defined(OPENSSL_EXTRA) && (defined(HAVE_ECC) || \
  28923. defined(HAVE_CURVE25519) || defined(HAVE_CURVE448))
  28924. static int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names)
  28925. {
  28926. int idx, start = 0, len;
  28927. word16 curve;
  28928. word32 disabled;
  28929. char name[MAX_CURVE_NAME_SZ];
  28930. /* Disable all curves so that only the ones the user wants are enabled. */
  28931. disabled = 0xFFFFFFFFUL;
  28932. for (idx = 1; names[idx-1] != '\0'; idx++) {
  28933. if (names[idx] != ':' && names[idx] != '\0')
  28934. continue;
  28935. len = idx - start;
  28936. if (len > MAX_CURVE_NAME_SZ - 1)
  28937. return WOLFSSL_FAILURE;
  28938. XMEMCPY(name, names + start, len);
  28939. name[len] = 0;
  28940. if ((XSTRCMP(name, "prime256v1") == 0) ||
  28941. (XSTRCMP(name, "secp256r1") == 0) ||
  28942. (XSTRCMP(name, "P-256") == 0))
  28943. {
  28944. curve = WOLFSSL_ECC_SECP256R1;
  28945. }
  28946. else if ((XSTRCMP(name, "secp384r1") == 0) ||
  28947. (XSTRCMP(name, "P-384") == 0))
  28948. {
  28949. curve = WOLFSSL_ECC_SECP384R1;
  28950. }
  28951. else if ((XSTRCMP(name, "secp521r1") == 0) ||
  28952. (XSTRCMP(name, "P-521") == 0))
  28953. {
  28954. curve = WOLFSSL_ECC_SECP521R1;
  28955. }
  28956. #ifdef HAVE_CURVE25519
  28957. else if (XSTRCMP(name, "X25519") == 0)
  28958. {
  28959. curve = WOLFSSL_ECC_X25519;
  28960. }
  28961. #endif
  28962. #ifdef HAVE_CURVE448
  28963. else if (XSTRCMP(name, "X448") == 0)
  28964. {
  28965. curve = WOLFSSL_ECC_X448;
  28966. }
  28967. #endif
  28968. else {
  28969. #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  28970. int ret;
  28971. const ecc_set_type *eccSet;
  28972. ret = wc_ecc_get_curve_idx_from_name(name);
  28973. if (ret < 0) {
  28974. WOLFSSL_MSG("Could not find name in set");
  28975. return WOLFSSL_FAILURE;
  28976. }
  28977. eccSet = wc_ecc_get_curve_params(ret);
  28978. if (eccSet == NULL) {
  28979. WOLFSSL_MSG("NULL set returned");
  28980. return WOLFSSL_FAILURE;
  28981. }
  28982. curve = GetCurveByOID(eccSet->oidSum);
  28983. #else
  28984. WOLFSSL_MSG("API not present to search farther using name");
  28985. return WOLFSSL_FAILURE;
  28986. #endif
  28987. }
  28988. if (curve >= (sizeof(word32) * WOLFSSL_BIT_SIZE)) {
  28989. /* shift left more than size of ctx->disabledCurves causes static
  28990. * analysis report */
  28991. WOLFSSL_MSG("curve value is too large for upcoming shift");
  28992. return WOLFSSL_FAILURE;
  28993. }
  28994. #if defined(HAVE_SUPPORTED_CURVES) && !defined(NO_WOLFSSL_CLIENT)
  28995. /* set the supported curve so client TLS extension contains only the
  28996. * desired curves */
  28997. if ((ssl
  28998. && wolfSSL_UseSupportedCurve(ssl, curve) != WOLFSSL_SUCCESS)
  28999. || (ctx
  29000. && wolfSSL_CTX_UseSupportedCurve(ctx, curve) != WOLFSSL_SUCCESS)) {
  29001. WOLFSSL_MSG("Unable to set supported curve");
  29002. return WOLFSSL_FAILURE;
  29003. }
  29004. #endif
  29005. /* Switch the bit to off and therefore is enabled. */
  29006. disabled &= ~(1U << curve);
  29007. start = idx + 1;
  29008. }
  29009. if (ssl)
  29010. ssl->disabledCurves = disabled;
  29011. else
  29012. ctx->disabledCurves = disabled;
  29013. return WOLFSSL_SUCCESS;
  29014. }
  29015. int wolfSSL_CTX_set1_curves_list(WOLFSSL_CTX* ctx, const char* names)
  29016. {
  29017. if (ctx == NULL || names == NULL) {
  29018. WOLFSSL_MSG("ctx or names was NULL");
  29019. return WOLFSSL_FAILURE;
  29020. }
  29021. return set_curves_list(NULL, ctx, names);
  29022. }
  29023. int wolfSSL_set1_curves_list(WOLFSSL* ssl, const char* names)
  29024. {
  29025. if (ssl == NULL || names == NULL) {
  29026. WOLFSSL_MSG("ssl or names was NULL");
  29027. return WOLFSSL_FAILURE;
  29028. }
  29029. return set_curves_list(ssl, NULL, names);
  29030. }
  29031. #endif /* OPENSSL_EXTRA && (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) */
  29032. #ifdef OPENSSL_EXTRA
  29033. /* Sets a callback for when sending and receiving protocol messages.
  29034. * This callback is copied to all WOLFSSL objects created from the ctx.
  29035. *
  29036. * ctx WOLFSSL_CTX structure to set callback in
  29037. * cb callback to use
  29038. *
  29039. * return WOLFSSL_SUCCESS on success and SSL_FAILURE with error case
  29040. */
  29041. int wolfSSL_CTX_set_msg_callback(WOLFSSL_CTX *ctx, SSL_Msg_Cb cb)
  29042. {
  29043. WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback");
  29044. if (ctx == NULL) {
  29045. WOLFSSL_MSG("Null ctx passed in");
  29046. return WOLFSSL_FAILURE;
  29047. }
  29048. ctx->protoMsgCb = cb;
  29049. return WOLFSSL_SUCCESS;
  29050. }
  29051. /* Sets a callback for when sending and receiving protocol messages.
  29052. *
  29053. * ssl WOLFSSL structure to set callback in
  29054. * cb callback to use
  29055. *
  29056. * return WOLFSSL_SUCCESS on success and SSL_FAILURE with error case
  29057. */
  29058. int wolfSSL_set_msg_callback(WOLFSSL *ssl, SSL_Msg_Cb cb)
  29059. {
  29060. WOLFSSL_ENTER("wolfSSL_set_msg_callback");
  29061. if (ssl == NULL) {
  29062. return SSL_FAILURE;
  29063. }
  29064. if (cb != NULL) {
  29065. ssl->toInfoOn = 1;
  29066. }
  29067. ssl->protoMsgCb = cb;
  29068. return WOLFSSL_SUCCESS;
  29069. }
  29070. /* set the user argument to pass to the msg callback when called
  29071. * return WOLFSSL_SUCCESS on success */
  29072. int wolfSSL_CTX_set_msg_callback_arg(WOLFSSL_CTX *ctx, void* arg)
  29073. {
  29074. WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback_arg");
  29075. if (ctx == NULL) {
  29076. WOLFSSL_MSG("Null WOLFSSL_CTX passed in");
  29077. return WOLFSSL_FAILURE;
  29078. }
  29079. ctx->protoMsgCtx = arg;
  29080. return WOLFSSL_SUCCESS;
  29081. }
  29082. int wolfSSL_set_msg_callback_arg(WOLFSSL *ssl, void* arg)
  29083. {
  29084. WOLFSSL_ENTER("wolfSSL_set_msg_callback_arg");
  29085. if (ssl == NULL)
  29086. return WOLFSSL_FAILURE;
  29087. ssl->protoMsgCtx = arg;
  29088. return WOLFSSL_SUCCESS;
  29089. }
  29090. void *wolfSSL_OPENSSL_memdup(const void *data, size_t siz, const char* file, int line)
  29091. {
  29092. void *ret;
  29093. (void)file;
  29094. (void)line;
  29095. if (data == NULL || siz >= INT_MAX)
  29096. return NULL;
  29097. ret = OPENSSL_malloc(siz);
  29098. if (ret == NULL) {
  29099. return NULL;
  29100. }
  29101. return XMEMCPY(ret, data, siz);
  29102. }
  29103. void wolfSSL_OPENSSL_cleanse(void *ptr, size_t len)
  29104. {
  29105. if (ptr)
  29106. ForceZero(ptr, (word32)len);
  29107. }
  29108. int wolfSSL_CTX_set_alpn_protos(WOLFSSL_CTX *ctx, const unsigned char *p,
  29109. unsigned int p_len)
  29110. {
  29111. WOLFSSL_ENTER("wolfSSL_CTX_set_alpn_protos");
  29112. if (ctx == NULL)
  29113. return BAD_FUNC_ARG;
  29114. if (ctx->alpn_cli_protos != NULL) {
  29115. XFREE((void*)ctx->alpn_cli_protos, ctx->heap, DYNAMIC_TYPE_OPENSSL);
  29116. }
  29117. ctx->alpn_cli_protos = (const unsigned char*)XMALLOC(p_len,
  29118. ctx->heap, DYNAMIC_TYPE_OPENSSL);
  29119. if (ctx->alpn_cli_protos == NULL) {
  29120. #if defined(WOLFSSL_ERROR_CODE_OPENSSL)
  29121. /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
  29122. * the function reverses the return value convention.
  29123. */
  29124. return 1;
  29125. #else
  29126. return WOLFSSL_FAILURE;
  29127. #endif
  29128. }
  29129. XMEMCPY((void*)ctx->alpn_cli_protos, p, p_len);
  29130. ctx->alpn_cli_protos_len = p_len;
  29131. #if defined(WOLFSSL_ERROR_CODE_OPENSSL)
  29132. /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
  29133. * the function reverses the return value convention.
  29134. */
  29135. return 0;
  29136. #else
  29137. return WOLFSSL_SUCCESS;
  29138. #endif
  29139. }
  29140. #ifdef HAVE_ALPN
  29141. #ifndef NO_BIO
  29142. /* Sets the ALPN extension protos
  29143. *
  29144. * example format is
  29145. * unsigned char p[] = {
  29146. * 8, 'h', 't', 't', 'p', '/', '1', '.', '1'
  29147. * };
  29148. *
  29149. * returns WOLFSSL_SUCCESS on success */
  29150. int wolfSSL_set_alpn_protos(WOLFSSL* ssl,
  29151. const unsigned char* p, unsigned int p_len)
  29152. {
  29153. WOLFSSL_BIO* bio;
  29154. char* pt;
  29155. unsigned int sz;
  29156. unsigned int idx = 0;
  29157. int alpn_opt = WOLFSSL_ALPN_CONTINUE_ON_MISMATCH;
  29158. WOLFSSL_ENTER("wolfSSL_set_alpn_protos");
  29159. if (ssl == NULL || p_len <= 1) {
  29160. #if defined(WOLFSSL_ERROR_CODE_OPENSSL)
  29161. /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
  29162. * the function reverses the return value convention.
  29163. */
  29164. return 1;
  29165. #else
  29166. return WOLFSSL_FAILURE;
  29167. #endif
  29168. }
  29169. bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem());
  29170. if (bio == NULL) {
  29171. #if defined(WOLFSSL_ERROR_CODE_OPENSSL)
  29172. /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
  29173. * the function reverses the return value convention.
  29174. */
  29175. return 1;
  29176. #else
  29177. return WOLFSSL_FAILURE;
  29178. #endif
  29179. }
  29180. /* convert into comma separated list */
  29181. while (idx < p_len - 1) {
  29182. unsigned int i;
  29183. sz = p[idx++];
  29184. if (idx + sz > p_len) {
  29185. WOLFSSL_MSG("Bad list format");
  29186. wolfSSL_BIO_free(bio);
  29187. #if defined(WOLFSSL_ERROR_CODE_OPENSSL)
  29188. /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
  29189. * the function reverses the return value convention.
  29190. */
  29191. return 1;
  29192. #else
  29193. return WOLFSSL_FAILURE;
  29194. #endif
  29195. }
  29196. if (sz > 0) {
  29197. for (i = 0; i < sz; i++) {
  29198. wolfSSL_BIO_write(bio, &p[idx++], 1);
  29199. }
  29200. if (idx < p_len - 1)
  29201. wolfSSL_BIO_write(bio, ",", 1);
  29202. }
  29203. }
  29204. wolfSSL_BIO_write(bio, "\0", 1);
  29205. /* clears out all current ALPN extensions set */
  29206. TLSX_Remove(&ssl->extensions, TLSX_APPLICATION_LAYER_PROTOCOL, ssl->heap);
  29207. if ((sz = wolfSSL_BIO_get_mem_data(bio, &pt)) > 0) {
  29208. wolfSSL_UseALPN(ssl, pt, sz, (byte) alpn_opt);
  29209. }
  29210. wolfSSL_BIO_free(bio);
  29211. #if defined(WOLFSSL_ERROR_CODE_OPENSSL)
  29212. /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
  29213. * the function reverses the return value convention.
  29214. */
  29215. return 0;
  29216. #else
  29217. return WOLFSSL_SUCCESS;
  29218. #endif
  29219. }
  29220. #endif /* !NO_BIO */
  29221. #endif /* HAVE_ALPN */
  29222. #endif /* OPENSSL_EXTRA */
  29223. #if defined(OPENSSL_EXTRA)
  29224. #ifndef NO_BIO
  29225. #define WOLFSSL_BIO_INCLUDED
  29226. #include "src/bio.c"
  29227. #endif
  29228. word32 nid2oid(int nid, int grp)
  29229. {
  29230. /* get OID type */
  29231. switch (grp) {
  29232. /* oidHashType */
  29233. case oidHashType:
  29234. switch (nid) {
  29235. #ifdef WOLFSSL_MD2
  29236. case NID_md2:
  29237. return MD2h;
  29238. #endif
  29239. #ifndef NO_MD5
  29240. case NID_md5:
  29241. return MD5h;
  29242. #endif
  29243. #ifndef NO_SHA
  29244. case NID_sha1:
  29245. return SHAh;
  29246. #endif
  29247. case NID_sha224:
  29248. return SHA224h;
  29249. #ifndef NO_SHA256
  29250. case NID_sha256:
  29251. return SHA256h;
  29252. #endif
  29253. #ifdef WOLFSSL_SHA384
  29254. case NID_sha384:
  29255. return SHA384h;
  29256. #endif
  29257. #ifdef WOLFSSL_SHA512
  29258. case NID_sha512:
  29259. return SHA512h;
  29260. #endif
  29261. #ifndef WOLFSSL_NOSHA3_224
  29262. case NID_sha3_224:
  29263. return SHA3_224h;
  29264. #endif
  29265. #ifndef WOLFSSL_NOSHA3_256
  29266. case NID_sha3_256:
  29267. return SHA3_256h;
  29268. #endif
  29269. #ifndef WOLFSSL_NOSHA3_384
  29270. case NID_sha3_384:
  29271. return SHA3_384h;
  29272. #endif
  29273. #ifndef WOLFSSL_NOSHA3_512
  29274. case NID_sha3_512:
  29275. return SHA3_512h;
  29276. #endif
  29277. }
  29278. break;
  29279. /* oidSigType */
  29280. case oidSigType:
  29281. switch (nid) {
  29282. #ifndef NO_DSA
  29283. case NID_dsaWithSHA1:
  29284. return CTC_SHAwDSA;
  29285. case NID_dsa_with_SHA256:
  29286. return CTC_SHA256wDSA;
  29287. #endif /* NO_DSA */
  29288. #ifndef NO_RSA
  29289. case NID_md2WithRSAEncryption:
  29290. return CTC_MD2wRSA;
  29291. case NID_md5WithRSAEncryption:
  29292. return CTC_MD5wRSA;
  29293. case NID_sha1WithRSAEncryption:
  29294. return CTC_SHAwRSA;
  29295. case NID_sha224WithRSAEncryption:
  29296. return CTC_SHA224wRSA;
  29297. case NID_sha256WithRSAEncryption:
  29298. return CTC_SHA256wRSA;
  29299. case NID_sha384WithRSAEncryption:
  29300. return CTC_SHA384wRSA;
  29301. case NID_sha512WithRSAEncryption:
  29302. return CTC_SHA512wRSA;
  29303. #ifdef WOLFSSL_SHA3
  29304. case NID_RSA_SHA3_224:
  29305. return CTC_SHA3_224wRSA;
  29306. case NID_RSA_SHA3_256:
  29307. return CTC_SHA3_256wRSA;
  29308. case NID_RSA_SHA3_384:
  29309. return CTC_SHA3_384wRSA;
  29310. case NID_RSA_SHA3_512:
  29311. return CTC_SHA3_512wRSA;
  29312. #endif
  29313. #endif /* NO_RSA */
  29314. #ifdef HAVE_ECC
  29315. case NID_ecdsa_with_SHA1:
  29316. return CTC_SHAwECDSA;
  29317. case NID_ecdsa_with_SHA224:
  29318. return CTC_SHA224wECDSA;
  29319. case NID_ecdsa_with_SHA256:
  29320. return CTC_SHA256wECDSA;
  29321. case NID_ecdsa_with_SHA384:
  29322. return CTC_SHA384wECDSA;
  29323. case NID_ecdsa_with_SHA512:
  29324. return CTC_SHA512wECDSA;
  29325. #ifdef WOLFSSL_SHA3
  29326. case NID_ecdsa_with_SHA3_224:
  29327. return CTC_SHA3_224wECDSA;
  29328. case NID_ecdsa_with_SHA3_256:
  29329. return CTC_SHA3_256wECDSA;
  29330. case NID_ecdsa_with_SHA3_384:
  29331. return CTC_SHA3_384wECDSA;
  29332. case NID_ecdsa_with_SHA3_512:
  29333. return CTC_SHA3_512wECDSA;
  29334. #endif
  29335. #endif /* HAVE_ECC */
  29336. }
  29337. break;
  29338. /* oidKeyType */
  29339. case oidKeyType:
  29340. switch (nid) {
  29341. #ifndef NO_DSA
  29342. case NID_dsa:
  29343. return DSAk;
  29344. #endif /* NO_DSA */
  29345. #ifndef NO_RSA
  29346. case NID_rsaEncryption:
  29347. return RSAk;
  29348. #endif /* NO_RSA */
  29349. #ifdef HAVE_ECC
  29350. case NID_X9_62_id_ecPublicKey:
  29351. return ECDSAk;
  29352. #endif /* HAVE_ECC */
  29353. }
  29354. break;
  29355. #ifdef HAVE_ECC
  29356. case oidCurveType:
  29357. switch (nid) {
  29358. case NID_X9_62_prime192v1:
  29359. return ECC_SECP192R1_OID;
  29360. case NID_X9_62_prime192v2:
  29361. return ECC_PRIME192V2_OID;
  29362. case NID_X9_62_prime192v3:
  29363. return ECC_PRIME192V3_OID;
  29364. case NID_X9_62_prime239v1:
  29365. return ECC_PRIME239V1_OID;
  29366. case NID_X9_62_prime239v2:
  29367. return ECC_PRIME239V2_OID;
  29368. case NID_X9_62_prime239v3:
  29369. return ECC_PRIME239V3_OID;
  29370. case NID_X9_62_prime256v1:
  29371. return ECC_SECP256R1_OID;
  29372. case NID_secp112r1:
  29373. return ECC_SECP112R1_OID;
  29374. case NID_secp112r2:
  29375. return ECC_SECP112R2_OID;
  29376. case NID_secp128r1:
  29377. return ECC_SECP128R1_OID;
  29378. case NID_secp128r2:
  29379. return ECC_SECP128R2_OID;
  29380. case NID_secp160r1:
  29381. return ECC_SECP160R1_OID;
  29382. case NID_secp160r2:
  29383. return ECC_SECP160R2_OID;
  29384. case NID_secp224r1:
  29385. return ECC_SECP224R1_OID;
  29386. case NID_secp384r1:
  29387. return ECC_SECP384R1_OID;
  29388. case NID_secp521r1:
  29389. return ECC_SECP521R1_OID;
  29390. case NID_secp160k1:
  29391. return ECC_SECP160K1_OID;
  29392. case NID_secp192k1:
  29393. return ECC_SECP192K1_OID;
  29394. case NID_secp224k1:
  29395. return ECC_SECP224K1_OID;
  29396. case NID_secp256k1:
  29397. return ECC_SECP256K1_OID;
  29398. case NID_brainpoolP160r1:
  29399. return ECC_BRAINPOOLP160R1_OID;
  29400. case NID_brainpoolP192r1:
  29401. return ECC_BRAINPOOLP192R1_OID;
  29402. case NID_brainpoolP224r1:
  29403. return ECC_BRAINPOOLP224R1_OID;
  29404. case NID_brainpoolP256r1:
  29405. return ECC_BRAINPOOLP256R1_OID;
  29406. case NID_brainpoolP320r1:
  29407. return ECC_BRAINPOOLP320R1_OID;
  29408. case NID_brainpoolP384r1:
  29409. return ECC_BRAINPOOLP384R1_OID;
  29410. case NID_brainpoolP512r1:
  29411. return ECC_BRAINPOOLP512R1_OID;
  29412. }
  29413. break;
  29414. #endif /* HAVE_ECC */
  29415. /* oidBlkType */
  29416. case oidBlkType:
  29417. switch (nid) {
  29418. #ifdef WOLFSSL_AES_128
  29419. case AES128CBCb:
  29420. return AES128CBCb;
  29421. #endif
  29422. #ifdef WOLFSSL_AES_192
  29423. case AES192CBCb:
  29424. return AES192CBCb;
  29425. #endif
  29426. #ifdef WOLFSSL_AES_256
  29427. case AES256CBCb:
  29428. return AES256CBCb;
  29429. #endif
  29430. #ifndef NO_DES3
  29431. case NID_des:
  29432. return DESb;
  29433. case NID_des3:
  29434. return DES3b;
  29435. #endif
  29436. }
  29437. break;
  29438. #ifdef HAVE_OCSP
  29439. case oidOcspType:
  29440. switch (nid) {
  29441. case NID_id_pkix_OCSP_basic:
  29442. return OCSP_BASIC_OID;
  29443. case OCSP_NONCE_OID:
  29444. return OCSP_NONCE_OID;
  29445. }
  29446. break;
  29447. #endif /* HAVE_OCSP */
  29448. /* oidCertExtType */
  29449. case oidCertExtType:
  29450. switch (nid) {
  29451. case NID_basic_constraints:
  29452. return BASIC_CA_OID;
  29453. case NID_subject_alt_name:
  29454. return ALT_NAMES_OID;
  29455. case NID_crl_distribution_points:
  29456. return CRL_DIST_OID;
  29457. case NID_info_access:
  29458. return AUTH_INFO_OID;
  29459. case NID_authority_key_identifier:
  29460. return AUTH_KEY_OID;
  29461. case NID_subject_key_identifier:
  29462. return SUBJ_KEY_OID;
  29463. case NID_inhibit_any_policy:
  29464. return INHIBIT_ANY_OID;
  29465. case NID_key_usage:
  29466. return KEY_USAGE_OID;
  29467. case NID_name_constraints:
  29468. return NAME_CONS_OID;
  29469. case NID_certificate_policies:
  29470. return CERT_POLICY_OID;
  29471. case NID_ext_key_usage:
  29472. return EXT_KEY_USAGE_OID;
  29473. }
  29474. break;
  29475. /* oidCertAuthInfoType */
  29476. case oidCertAuthInfoType:
  29477. switch (nid) {
  29478. case NID_ad_OCSP:
  29479. return AIA_OCSP_OID;
  29480. case NID_ad_ca_issuers:
  29481. return AIA_CA_ISSUER_OID;
  29482. }
  29483. break;
  29484. /* oidCertPolicyType */
  29485. case oidCertPolicyType:
  29486. switch (nid) {
  29487. case NID_any_policy:
  29488. return CP_ANY_OID;
  29489. }
  29490. break;
  29491. /* oidCertAltNameType */
  29492. case oidCertAltNameType:
  29493. switch (nid) {
  29494. case NID_hw_name_oid:
  29495. return HW_NAME_OID;
  29496. }
  29497. break;
  29498. /* oidCertKeyUseType */
  29499. case oidCertKeyUseType:
  29500. switch (nid) {
  29501. case NID_anyExtendedKeyUsage:
  29502. return EKU_ANY_OID;
  29503. case EKU_SERVER_AUTH_OID:
  29504. return EKU_SERVER_AUTH_OID;
  29505. case EKU_CLIENT_AUTH_OID:
  29506. return EKU_CLIENT_AUTH_OID;
  29507. case EKU_OCSP_SIGN_OID:
  29508. return EKU_OCSP_SIGN_OID;
  29509. }
  29510. break;
  29511. /* oidKdfType */
  29512. case oidKdfType:
  29513. switch (nid) {
  29514. case PBKDF2_OID:
  29515. return PBKDF2_OID;
  29516. }
  29517. break;
  29518. /* oidPBEType */
  29519. case oidPBEType:
  29520. switch (nid) {
  29521. case PBE_SHA1_RC4_128:
  29522. return PBE_SHA1_RC4_128;
  29523. case PBE_SHA1_DES:
  29524. return PBE_SHA1_DES;
  29525. case PBE_SHA1_DES3:
  29526. return PBE_SHA1_DES3;
  29527. }
  29528. break;
  29529. /* oidKeyWrapType */
  29530. case oidKeyWrapType:
  29531. switch (nid) {
  29532. #ifdef WOLFSSL_AES_128
  29533. case AES128_WRAP:
  29534. return AES128_WRAP;
  29535. #endif
  29536. #ifdef WOLFSSL_AES_192
  29537. case AES192_WRAP:
  29538. return AES192_WRAP;
  29539. #endif
  29540. #ifdef WOLFSSL_AES_256
  29541. case AES256_WRAP:
  29542. return AES256_WRAP;
  29543. #endif
  29544. }
  29545. break;
  29546. /* oidCmsKeyAgreeType */
  29547. case oidCmsKeyAgreeType:
  29548. switch (nid) {
  29549. #ifndef NO_SHA
  29550. case dhSinglePass_stdDH_sha1kdf_scheme:
  29551. return dhSinglePass_stdDH_sha1kdf_scheme;
  29552. #endif
  29553. #ifdef WOLFSSL_SHA224
  29554. case dhSinglePass_stdDH_sha224kdf_scheme:
  29555. return dhSinglePass_stdDH_sha224kdf_scheme;
  29556. #endif
  29557. #ifndef NO_SHA256
  29558. case dhSinglePass_stdDH_sha256kdf_scheme:
  29559. return dhSinglePass_stdDH_sha256kdf_scheme;
  29560. #endif
  29561. #ifdef WOLFSSL_SHA384
  29562. case dhSinglePass_stdDH_sha384kdf_scheme:
  29563. return dhSinglePass_stdDH_sha384kdf_scheme;
  29564. #endif
  29565. #ifdef WOLFSSL_SHA512
  29566. case dhSinglePass_stdDH_sha512kdf_scheme:
  29567. return dhSinglePass_stdDH_sha512kdf_scheme;
  29568. #endif
  29569. }
  29570. break;
  29571. default:
  29572. WOLFSSL_MSG("NID not in table");
  29573. /* MSVC warns without the cast */
  29574. return (word32)-1;
  29575. }
  29576. /* MSVC warns without the cast */
  29577. return (word32)-1;
  29578. }
  29579. int oid2nid(word32 oid, int grp)
  29580. {
  29581. size_t i;
  29582. /* get OID type */
  29583. switch (grp) {
  29584. /* oidHashType */
  29585. case oidHashType:
  29586. switch (oid) {
  29587. #ifdef WOLFSSL_MD2
  29588. case MD2h:
  29589. return NID_md2;
  29590. #endif
  29591. #ifndef NO_MD5
  29592. case MD5h:
  29593. return NID_md5;
  29594. #endif
  29595. #ifndef NO_SHA
  29596. case SHAh:
  29597. return NID_sha1;
  29598. #endif
  29599. case SHA224h:
  29600. return NID_sha224;
  29601. #ifndef NO_SHA256
  29602. case SHA256h:
  29603. return NID_sha256;
  29604. #endif
  29605. #ifdef WOLFSSL_SHA384
  29606. case SHA384h:
  29607. return NID_sha384;
  29608. #endif
  29609. #ifdef WOLFSSL_SHA512
  29610. case SHA512h:
  29611. return NID_sha512;
  29612. #endif
  29613. }
  29614. break;
  29615. /* oidSigType */
  29616. case oidSigType:
  29617. switch (oid) {
  29618. #ifndef NO_DSA
  29619. case CTC_SHAwDSA:
  29620. return NID_dsaWithSHA1;
  29621. case CTC_SHA256wDSA:
  29622. return NID_dsa_with_SHA256;
  29623. #endif /* NO_DSA */
  29624. #ifndef NO_RSA
  29625. case CTC_MD2wRSA:
  29626. return NID_md2WithRSAEncryption;
  29627. case CTC_MD5wRSA:
  29628. return NID_md5WithRSAEncryption;
  29629. case CTC_SHAwRSA:
  29630. return NID_sha1WithRSAEncryption;
  29631. case CTC_SHA224wRSA:
  29632. return NID_sha224WithRSAEncryption;
  29633. case CTC_SHA256wRSA:
  29634. return NID_sha256WithRSAEncryption;
  29635. case CTC_SHA384wRSA:
  29636. return NID_sha384WithRSAEncryption;
  29637. case CTC_SHA512wRSA:
  29638. return NID_sha512WithRSAEncryption;
  29639. #ifdef WOLFSSL_SHA3
  29640. case CTC_SHA3_224wRSA:
  29641. return NID_RSA_SHA3_224;
  29642. case CTC_SHA3_256wRSA:
  29643. return NID_RSA_SHA3_256;
  29644. case CTC_SHA3_384wRSA:
  29645. return NID_RSA_SHA3_384;
  29646. case CTC_SHA3_512wRSA:
  29647. return NID_RSA_SHA3_512;
  29648. #endif
  29649. #endif /* NO_RSA */
  29650. #ifdef HAVE_ECC
  29651. case CTC_SHAwECDSA:
  29652. return NID_ecdsa_with_SHA1;
  29653. case CTC_SHA224wECDSA:
  29654. return NID_ecdsa_with_SHA224;
  29655. case CTC_SHA256wECDSA:
  29656. return NID_ecdsa_with_SHA256;
  29657. case CTC_SHA384wECDSA:
  29658. return NID_ecdsa_with_SHA384;
  29659. case CTC_SHA512wECDSA:
  29660. return NID_ecdsa_with_SHA512;
  29661. #ifdef WOLFSSL_SHA3
  29662. case CTC_SHA3_224wECDSA:
  29663. return NID_ecdsa_with_SHA3_224;
  29664. case CTC_SHA3_256wECDSA:
  29665. return NID_ecdsa_with_SHA3_256;
  29666. case CTC_SHA3_384wECDSA:
  29667. return NID_ecdsa_with_SHA3_384;
  29668. case CTC_SHA3_512wECDSA:
  29669. return NID_ecdsa_with_SHA3_512;
  29670. #endif
  29671. #endif /* HAVE_ECC */
  29672. }
  29673. break;
  29674. /* oidKeyType */
  29675. case oidKeyType:
  29676. switch (oid) {
  29677. #ifndef NO_DSA
  29678. case DSAk:
  29679. return NID_dsa;
  29680. #endif /* NO_DSA */
  29681. #ifndef NO_RSA
  29682. case RSAk:
  29683. return NID_rsaEncryption;
  29684. #endif /* NO_RSA */
  29685. #ifdef HAVE_ECC
  29686. case ECDSAk:
  29687. return NID_X9_62_id_ecPublicKey;
  29688. #endif /* HAVE_ECC */
  29689. }
  29690. break;
  29691. #ifdef HAVE_ECC
  29692. case oidCurveType:
  29693. switch (oid) {
  29694. case ECC_SECP192R1_OID:
  29695. return NID_X9_62_prime192v1;
  29696. case ECC_PRIME192V2_OID:
  29697. return NID_X9_62_prime192v2;
  29698. case ECC_PRIME192V3_OID:
  29699. return NID_X9_62_prime192v3;
  29700. case ECC_PRIME239V1_OID:
  29701. return NID_X9_62_prime239v1;
  29702. case ECC_PRIME239V2_OID:
  29703. return NID_X9_62_prime239v2;
  29704. case ECC_PRIME239V3_OID:
  29705. return NID_X9_62_prime239v3;
  29706. case ECC_SECP256R1_OID:
  29707. return NID_X9_62_prime256v1;
  29708. case ECC_SECP112R1_OID:
  29709. return NID_secp112r1;
  29710. case ECC_SECP112R2_OID:
  29711. return NID_secp112r2;
  29712. case ECC_SECP128R1_OID:
  29713. return NID_secp128r1;
  29714. case ECC_SECP128R2_OID:
  29715. return NID_secp128r2;
  29716. case ECC_SECP160R1_OID:
  29717. return NID_secp160r1;
  29718. case ECC_SECP160R2_OID:
  29719. return NID_secp160r2;
  29720. case ECC_SECP224R1_OID:
  29721. return NID_secp224r1;
  29722. case ECC_SECP384R1_OID:
  29723. return NID_secp384r1;
  29724. case ECC_SECP521R1_OID:
  29725. return NID_secp521r1;
  29726. case ECC_SECP160K1_OID:
  29727. return NID_secp160k1;
  29728. case ECC_SECP192K1_OID:
  29729. return NID_secp192k1;
  29730. case ECC_SECP224K1_OID:
  29731. return NID_secp224k1;
  29732. case ECC_SECP256K1_OID:
  29733. return NID_secp256k1;
  29734. case ECC_BRAINPOOLP160R1_OID:
  29735. return NID_brainpoolP160r1;
  29736. case ECC_BRAINPOOLP192R1_OID:
  29737. return NID_brainpoolP192r1;
  29738. case ECC_BRAINPOOLP224R1_OID:
  29739. return NID_brainpoolP224r1;
  29740. case ECC_BRAINPOOLP256R1_OID:
  29741. return NID_brainpoolP256r1;
  29742. case ECC_BRAINPOOLP320R1_OID:
  29743. return NID_brainpoolP320r1;
  29744. case ECC_BRAINPOOLP384R1_OID:
  29745. return NID_brainpoolP384r1;
  29746. case ECC_BRAINPOOLP512R1_OID:
  29747. return NID_brainpoolP512r1;
  29748. }
  29749. break;
  29750. #endif /* HAVE_ECC */
  29751. /* oidBlkType */
  29752. case oidBlkType:
  29753. switch (oid) {
  29754. #ifdef WOLFSSL_AES_128
  29755. case AES128CBCb:
  29756. return AES128CBCb;
  29757. #endif
  29758. #ifdef WOLFSSL_AES_192
  29759. case AES192CBCb:
  29760. return AES192CBCb;
  29761. #endif
  29762. #ifdef WOLFSSL_AES_256
  29763. case AES256CBCb:
  29764. return AES256CBCb;
  29765. #endif
  29766. #ifndef NO_DES3
  29767. case DESb:
  29768. return NID_des;
  29769. case DES3b:
  29770. return NID_des3;
  29771. #endif
  29772. }
  29773. break;
  29774. #ifdef HAVE_OCSP
  29775. case oidOcspType:
  29776. switch (oid) {
  29777. case OCSP_BASIC_OID:
  29778. return NID_id_pkix_OCSP_basic;
  29779. case OCSP_NONCE_OID:
  29780. return OCSP_NONCE_OID;
  29781. }
  29782. break;
  29783. #endif /* HAVE_OCSP */
  29784. /* oidCertExtType */
  29785. case oidCertExtType:
  29786. switch (oid) {
  29787. case BASIC_CA_OID:
  29788. return NID_basic_constraints;
  29789. case ALT_NAMES_OID:
  29790. return NID_subject_alt_name;
  29791. case CRL_DIST_OID:
  29792. return NID_crl_distribution_points;
  29793. case AUTH_INFO_OID:
  29794. return NID_info_access;
  29795. case AUTH_KEY_OID:
  29796. return NID_authority_key_identifier;
  29797. case SUBJ_KEY_OID:
  29798. return NID_subject_key_identifier;
  29799. case INHIBIT_ANY_OID:
  29800. return NID_inhibit_any_policy;
  29801. case KEY_USAGE_OID:
  29802. return NID_key_usage;
  29803. case NAME_CONS_OID:
  29804. return NID_name_constraints;
  29805. case CERT_POLICY_OID:
  29806. return NID_certificate_policies;
  29807. case EXT_KEY_USAGE_OID:
  29808. return NID_ext_key_usage;
  29809. }
  29810. break;
  29811. /* oidCertAuthInfoType */
  29812. case oidCertAuthInfoType:
  29813. switch (oid) {
  29814. case AIA_OCSP_OID:
  29815. return NID_ad_OCSP;
  29816. case AIA_CA_ISSUER_OID:
  29817. return NID_ad_ca_issuers;
  29818. }
  29819. break;
  29820. /* oidCertPolicyType */
  29821. case oidCertPolicyType:
  29822. switch (oid) {
  29823. case CP_ANY_OID:
  29824. return NID_any_policy;
  29825. }
  29826. break;
  29827. /* oidCertAltNameType */
  29828. case oidCertAltNameType:
  29829. switch (oid) {
  29830. case HW_NAME_OID:
  29831. return NID_hw_name_oid;
  29832. }
  29833. break;
  29834. /* oidCertKeyUseType */
  29835. case oidCertKeyUseType:
  29836. switch (oid) {
  29837. case EKU_ANY_OID:
  29838. return NID_anyExtendedKeyUsage;
  29839. case EKU_SERVER_AUTH_OID:
  29840. return EKU_SERVER_AUTH_OID;
  29841. case EKU_CLIENT_AUTH_OID:
  29842. return EKU_CLIENT_AUTH_OID;
  29843. case EKU_OCSP_SIGN_OID:
  29844. return EKU_OCSP_SIGN_OID;
  29845. }
  29846. break;
  29847. /* oidKdfType */
  29848. case oidKdfType:
  29849. switch (oid) {
  29850. case PBKDF2_OID:
  29851. return PBKDF2_OID;
  29852. }
  29853. break;
  29854. /* oidPBEType */
  29855. case oidPBEType:
  29856. switch (oid) {
  29857. case PBE_SHA1_RC4_128:
  29858. return PBE_SHA1_RC4_128;
  29859. case PBE_SHA1_DES:
  29860. return PBE_SHA1_DES;
  29861. case PBE_SHA1_DES3:
  29862. return PBE_SHA1_DES3;
  29863. }
  29864. break;
  29865. /* oidKeyWrapType */
  29866. case oidKeyWrapType:
  29867. switch (oid) {
  29868. #ifdef WOLFSSL_AES_128
  29869. case AES128_WRAP:
  29870. return AES128_WRAP;
  29871. #endif
  29872. #ifdef WOLFSSL_AES_192
  29873. case AES192_WRAP:
  29874. return AES192_WRAP;
  29875. #endif
  29876. #ifdef WOLFSSL_AES_256
  29877. case AES256_WRAP:
  29878. return AES256_WRAP;
  29879. #endif
  29880. }
  29881. break;
  29882. /* oidCmsKeyAgreeType */
  29883. case oidCmsKeyAgreeType:
  29884. switch (oid) {
  29885. #ifndef NO_SHA
  29886. case dhSinglePass_stdDH_sha1kdf_scheme:
  29887. return dhSinglePass_stdDH_sha1kdf_scheme;
  29888. #endif
  29889. #ifdef WOLFSSL_SHA224
  29890. case dhSinglePass_stdDH_sha224kdf_scheme:
  29891. return dhSinglePass_stdDH_sha224kdf_scheme;
  29892. #endif
  29893. #ifndef NO_SHA256
  29894. case dhSinglePass_stdDH_sha256kdf_scheme:
  29895. return dhSinglePass_stdDH_sha256kdf_scheme;
  29896. #endif
  29897. #ifdef WOLFSSL_SHA384
  29898. case dhSinglePass_stdDH_sha384kdf_scheme:
  29899. return dhSinglePass_stdDH_sha384kdf_scheme;
  29900. #endif
  29901. #ifdef WOLFSSL_SHA512
  29902. case dhSinglePass_stdDH_sha512kdf_scheme:
  29903. return dhSinglePass_stdDH_sha512kdf_scheme;
  29904. #endif
  29905. }
  29906. break;
  29907. #ifdef WOLFSSL_CERT_REQ
  29908. case oidCsrAttrType:
  29909. switch (oid) {
  29910. case PKCS9_CONTENT_TYPE_OID:
  29911. return NID_pkcs9_contentType;
  29912. case CHALLENGE_PASSWORD_OID:
  29913. return NID_pkcs9_challengePassword;
  29914. case SERIAL_NUMBER_OID:
  29915. return NID_serialNumber;
  29916. case USER_ID_OID:
  29917. return NID_userId;
  29918. }
  29919. break;
  29920. #endif
  29921. default:
  29922. WOLFSSL_MSG("NID not in table");
  29923. }
  29924. /* If not found in above switch then try the table */
  29925. for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++) {
  29926. if (wolfssl_object_info[i].id == (int)oid) {
  29927. return wolfssl_object_info[i].nid;
  29928. }
  29929. }
  29930. return -1;
  29931. }
  29932. /* when calling SetIndividualInternal, mpi should be cleared by caller if no
  29933. * longer used. ie mp_free(mpi). This is to free data when fastmath is
  29934. * disabled since a copy of mpi is made by this function and placed into bn.
  29935. */
  29936. int SetIndividualInternal(WOLFSSL_BIGNUM* bn, mp_int* mpi)
  29937. {
  29938. WOLFSSL_MSG("Entering SetIndividualInternal");
  29939. if (bn == NULL || bn->internal == NULL) {
  29940. WOLFSSL_MSG("bn NULL error");
  29941. return WOLFSSL_FATAL_ERROR;
  29942. }
  29943. if (mpi == NULL) {
  29944. WOLFSSL_MSG("mpi NULL error");
  29945. return WOLFSSL_FATAL_ERROR;
  29946. }
  29947. if (mp_copy((mp_int*)bn->internal, mpi) != MP_OKAY) {
  29948. WOLFSSL_MSG("mp_copy error");
  29949. return WOLFSSL_FATAL_ERROR;
  29950. }
  29951. return WOLFSSL_SUCCESS;
  29952. }
  29953. #ifndef NO_ASN
  29954. WOLFSSL_BIGNUM *wolfSSL_ASN1_INTEGER_to_BN(const WOLFSSL_ASN1_INTEGER *ai,
  29955. WOLFSSL_BIGNUM *bn)
  29956. {
  29957. #ifdef WOLFSSL_SMALL_STACK
  29958. mp_int* mpi = NULL;
  29959. #else
  29960. mp_int mpi[1];
  29961. #endif
  29962. word32 idx = 0;
  29963. int ret;
  29964. WOLFSSL_ENTER("wolfSSL_ASN1_INTEGER_to_BN");
  29965. if (ai == NULL) {
  29966. return NULL;
  29967. }
  29968. #ifdef WOLFSSL_SMALL_STACK
  29969. mpi = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  29970. if (mpi == NULL) {
  29971. return NULL;
  29972. }
  29973. #endif
  29974. ret = GetInt(mpi, ai->data, &idx, ai->dataMax);
  29975. if (ret != 0) {
  29976. #if defined(WOLFSSL_QT) || defined(WOLFSSL_HAPROXY)
  29977. ret = mp_init(mpi); /* must init mpi */
  29978. if (ret != MP_OKAY) {
  29979. #ifdef WOLFSSL_SMALL_STACK
  29980. XFREE(mpi, NULL, DYNAMIC_TYPE_BIGINT);
  29981. #endif
  29982. return NULL;
  29983. }
  29984. /* Serial number in QT starts at index 0 of data */
  29985. if (mp_read_unsigned_bin(mpi, (byte*)ai->data, ai->length) != 0) {
  29986. mp_clear(mpi);
  29987. #ifdef WOLFSSL_SMALL_STACK
  29988. XFREE(mpi, NULL, DYNAMIC_TYPE_BIGINT);
  29989. #endif
  29990. return NULL;
  29991. }
  29992. #else
  29993. /* expecting ASN1 format for INTEGER */
  29994. WOLFSSL_LEAVE("wolfSSL_ASN1_INTEGER_to_BN", ret);
  29995. #ifdef WOLFSSL_SMALL_STACK
  29996. XFREE(mpi, NULL, DYNAMIC_TYPE_BIGINT);
  29997. #endif
  29998. return NULL;
  29999. #endif
  30000. }
  30001. /* mp_clear needs called because mpi is copied and causes memory leak with
  30002. * --disable-fastmath */
  30003. ret = SetIndividualExternal(&bn, mpi);
  30004. mp_clear(mpi);
  30005. #ifdef WOLFSSL_SMALL_STACK
  30006. XFREE(mpi, NULL, DYNAMIC_TYPE_BIGINT);
  30007. #endif
  30008. if (ret != WOLFSSL_SUCCESS) {
  30009. return NULL;
  30010. }
  30011. return bn;
  30012. }
  30013. #endif /* !NO_ASN */
  30014. /* frees all nodes in the current threads error queue
  30015. *
  30016. * id thread id. ERR_remove_state is depreciated and id is ignored. The
  30017. * current threads queue will be free'd.
  30018. */
  30019. void wolfSSL_ERR_remove_state(unsigned long id)
  30020. {
  30021. WOLFSSL_ENTER("wolfSSL_ERR_remove_state");
  30022. (void)id;
  30023. if (wc_ERR_remove_state() != 0) {
  30024. WOLFSSL_MSG("Error with removing the state");
  30025. }
  30026. }
  30027. WOLFSSL_BN_CTX* wolfSSL_BN_CTX_new(void)
  30028. {
  30029. static int ctx; /* wolfcrypt doesn't now need ctx */
  30030. WOLFSSL_MSG("wolfSSL_BN_CTX_new");
  30031. return (WOLFSSL_BN_CTX*)&ctx;
  30032. }
  30033. void wolfSSL_BN_CTX_init(WOLFSSL_BN_CTX* ctx)
  30034. {
  30035. (void)ctx;
  30036. WOLFSSL_MSG("wolfSSL_BN_CTX_init");
  30037. }
  30038. void wolfSSL_BN_CTX_free(WOLFSSL_BN_CTX* ctx)
  30039. {
  30040. (void)ctx;
  30041. WOLFSSL_MSG("wolfSSL_BN_CTX_free");
  30042. /* do free since static ctx that does nothing */
  30043. }
  30044. /* WOLFSSL_SUCCESS on ok */
  30045. int wolfSSL_BN_sub(WOLFSSL_BIGNUM* r, const WOLFSSL_BIGNUM* a,
  30046. const WOLFSSL_BIGNUM* b)
  30047. {
  30048. WOLFSSL_MSG("wolfSSL_BN_sub");
  30049. if (r == NULL || a == NULL || b == NULL)
  30050. return 0;
  30051. if (mp_sub((mp_int*)a->internal,(mp_int*)b->internal,
  30052. (mp_int*)r->internal) == MP_OKAY)
  30053. return WOLFSSL_SUCCESS;
  30054. WOLFSSL_MSG("wolfSSL_BN_sub mp_sub failed");
  30055. return 0;
  30056. }
  30057. WOLFSSL_API int wolfSSL_BN_mul(WOLFSSL_BIGNUM *r, WOLFSSL_BIGNUM *a, WOLFSSL_BIGNUM *b,
  30058. WOLFSSL_BN_CTX *ctx)
  30059. {
  30060. int ret = WOLFSSL_SUCCESS;
  30061. (void)ctx;
  30062. WOLFSSL_ENTER("wolfSSL_BN_mul");
  30063. if (r == NULL || a == NULL || b == NULL || r->internal == NULL ||
  30064. a->internal == NULL || b->internal == NULL) {
  30065. ret = WOLFSSL_FAILURE;
  30066. }
  30067. if (ret == WOLFSSL_SUCCESS) {
  30068. ret = mp_mul((mp_int*)a->internal, (mp_int*)b->internal,
  30069. (mp_int*)r->internal);
  30070. if (ret == MP_OKAY) {
  30071. ret = WOLFSSL_SUCCESS;
  30072. }
  30073. else {
  30074. ret = WOLFSSL_FAILURE;
  30075. }
  30076. }
  30077. WOLFSSL_LEAVE("wolfSSL_BN_mul", ret);
  30078. return ret;
  30079. }
  30080. #ifndef WOLFSSL_SP_MATH
  30081. int wolfSSL_BN_div(WOLFSSL_BIGNUM* dv, WOLFSSL_BIGNUM* rem,
  30082. const WOLFSSL_BIGNUM* a, const WOLFSSL_BIGNUM* d,
  30083. WOLFSSL_BN_CTX* ctx)
  30084. {
  30085. int ret = WOLFSSL_SUCCESS;
  30086. (void)ctx;
  30087. WOLFSSL_ENTER("wolfSSL_BN_div");
  30088. if (dv == NULL || rem == NULL || a == NULL || d == NULL ||
  30089. dv->internal == NULL || rem->internal == NULL || a->internal == NULL ||
  30090. d->internal == NULL) {
  30091. ret = WOLFSSL_FAILURE;
  30092. }
  30093. if (ret == WOLFSSL_SUCCESS) {
  30094. ret = mp_div((mp_int*)a->internal, (mp_int*)d->internal,
  30095. (mp_int*)dv->internal, (mp_int*)rem->internal);
  30096. if (ret == MP_OKAY) {
  30097. ret = WOLFSSL_SUCCESS;
  30098. }
  30099. else {
  30100. ret = WOLFSSL_FAILURE;
  30101. }
  30102. }
  30103. WOLFSSL_LEAVE("wolfSSL_BN_div", ret);
  30104. return ret;
  30105. }
  30106. #endif
  30107. #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) /* Needed to get mp_gcd. */
  30108. int wolfSSL_BN_gcd(WOLFSSL_BIGNUM* r, WOLFSSL_BIGNUM* a, WOLFSSL_BIGNUM* b,
  30109. WOLFSSL_BN_CTX* ctx)
  30110. {
  30111. int ret = WOLFSSL_SUCCESS;
  30112. (void)ctx;
  30113. WOLFSSL_ENTER("wolfSSL_BN_gcd");
  30114. if (r == NULL || a == NULL || b == NULL || r->internal == NULL ||
  30115. a->internal == NULL || b->internal == NULL) {
  30116. ret = WOLFSSL_FAILURE;
  30117. }
  30118. if (ret == WOLFSSL_SUCCESS) {
  30119. ret = mp_gcd((mp_int*)a->internal, (mp_int*)b->internal,
  30120. (mp_int*)r->internal);
  30121. if (ret == MP_OKAY) {
  30122. ret = WOLFSSL_SUCCESS;
  30123. }
  30124. else {
  30125. ret = WOLFSSL_FAILURE;
  30126. }
  30127. }
  30128. WOLFSSL_LEAVE("wolfSSL_BN_gcd", ret);
  30129. return ret;
  30130. }
  30131. #endif /* !NO_RSA && WOLFSSL_KEY_GEN */
  30132. /* WOLFSSL_SUCCESS on ok */
  30133. int wolfSSL_BN_mod(WOLFSSL_BIGNUM* r, const WOLFSSL_BIGNUM* a,
  30134. const WOLFSSL_BIGNUM* b, const WOLFSSL_BN_CTX* c)
  30135. {
  30136. (void)c;
  30137. WOLFSSL_MSG("wolfSSL_BN_mod");
  30138. if (r == NULL || a == NULL || b == NULL)
  30139. return 0;
  30140. if (mp_mod((mp_int*)a->internal,(mp_int*)b->internal,
  30141. (mp_int*)r->internal) == MP_OKAY)
  30142. return WOLFSSL_SUCCESS;
  30143. WOLFSSL_MSG("wolfSSL_BN_mod mp_mod failed");
  30144. return 0;
  30145. }
  30146. /* r = (a^p) % m */
  30147. int wolfSSL_BN_mod_exp(WOLFSSL_BIGNUM *r, const WOLFSSL_BIGNUM *a,
  30148. const WOLFSSL_BIGNUM *p, const WOLFSSL_BIGNUM *m, WOLFSSL_BN_CTX *ctx)
  30149. {
  30150. int ret;
  30151. WOLFSSL_ENTER("wolfSSL_BN_mod_exp");
  30152. (void) ctx;
  30153. if (r == NULL || a == NULL || p == NULL || m == NULL) {
  30154. WOLFSSL_MSG("Bad Argument");
  30155. return WOLFSSL_FAILURE;
  30156. }
  30157. if ((ret = mp_exptmod((mp_int*)a->internal,(mp_int*)p->internal,
  30158. (mp_int*)m->internal, (mp_int*)r->internal)) == MP_OKAY) {
  30159. return WOLFSSL_SUCCESS;
  30160. }
  30161. WOLFSSL_LEAVE("wolfSSL_BN_mod_exp", ret);
  30162. (void)ret;
  30163. return WOLFSSL_FAILURE;
  30164. }
  30165. /* r = (a * p) % m */
  30166. int wolfSSL_BN_mod_mul(WOLFSSL_BIGNUM *r, const WOLFSSL_BIGNUM *a,
  30167. const WOLFSSL_BIGNUM *p, const WOLFSSL_BIGNUM *m, WOLFSSL_BN_CTX *ctx)
  30168. {
  30169. int ret;
  30170. WOLFSSL_ENTER("wolfSSL_BN_mod_mul");
  30171. (void) ctx;
  30172. if (r == NULL || a == NULL || p == NULL || m == NULL) {
  30173. WOLFSSL_MSG("Bad Argument");
  30174. return SSL_FAILURE;
  30175. }
  30176. if ((ret = mp_mulmod((mp_int*)a->internal,(mp_int*)p->internal,
  30177. (mp_int*)m->internal, (mp_int*)r->internal)) == MP_OKAY) {
  30178. return WOLFSSL_SUCCESS;
  30179. }
  30180. WOLFSSL_LEAVE("wolfSSL_BN_mod_mul", ret);
  30181. (void)ret;
  30182. return SSL_FAILURE;
  30183. }
  30184. const WOLFSSL_BIGNUM* wolfSSL_BN_value_one(void)
  30185. {
  30186. WOLFSSL_MSG("wolfSSL_BN_value_one");
  30187. if (bn_one == NULL) {
  30188. bn_one = wolfSSL_BN_new();
  30189. if (bn_one) {
  30190. if (mp_set_int((mp_int*)bn_one->internal, 1) != MP_OKAY) {
  30191. /* handle error by freeing BN and returning NULL */
  30192. wolfSSL_BN_free(bn_one);
  30193. bn_one = NULL;
  30194. }
  30195. }
  30196. }
  30197. return bn_one;
  30198. }
  30199. /* return compliant with OpenSSL
  30200. * size of BIGNUM in bytes, 0 if error */
  30201. int wolfSSL_BN_num_bytes(const WOLFSSL_BIGNUM* bn)
  30202. {
  30203. WOLFSSL_ENTER("wolfSSL_BN_num_bytes");
  30204. if (bn == NULL || bn->internal == NULL)
  30205. return WOLFSSL_FAILURE;
  30206. return mp_unsigned_bin_size((mp_int*)bn->internal);
  30207. }
  30208. /* return compliant with OpenSSL
  30209. * size of BIGNUM in bits, 0 if error */
  30210. int wolfSSL_BN_num_bits(const WOLFSSL_BIGNUM* bn)
  30211. {
  30212. WOLFSSL_ENTER("wolfSSL_BN_num_bits");
  30213. if (bn == NULL || bn->internal == NULL)
  30214. return WOLFSSL_FAILURE;
  30215. return mp_count_bits((mp_int*)bn->internal);
  30216. }
  30217. int wolfSSL_BN_is_negative(const WOLFSSL_BIGNUM* bn)
  30218. {
  30219. if (bn == NULL)
  30220. return WOLFSSL_FAILURE;
  30221. return mp_isneg((mp_int*)bn->internal);
  30222. }
  30223. WOLFSSL_API void wolfSSL_BN_zero(WOLFSSL_BIGNUM* bn)
  30224. {
  30225. if (bn == NULL || bn->internal == NULL) {
  30226. return;
  30227. }
  30228. mp_zero((mp_int*)bn->internal);
  30229. }
  30230. WOLFSSL_API int wolfSSL_BN_one(WOLFSSL_BIGNUM* bn)
  30231. {
  30232. int ret = WOLFSSL_SUCCESS;
  30233. if (bn == NULL || bn->internal == NULL) {
  30234. return WOLFSSL_FAILURE;
  30235. }
  30236. if (ret == WOLFSSL_SUCCESS) {
  30237. ret = wolfSSL_BN_set_word(bn, 1);
  30238. }
  30239. return ret;
  30240. }
  30241. /* return compliant with OpenSSL
  30242. * 1 if BIGNUM is zero, 0 else */
  30243. int wolfSSL_BN_is_zero(const WOLFSSL_BIGNUM* bn)
  30244. {
  30245. WOLFSSL_MSG("wolfSSL_BN_is_zero");
  30246. if (bn == NULL || bn->internal == NULL)
  30247. return WOLFSSL_FAILURE;
  30248. if (mp_iszero((mp_int*)bn->internal) == MP_YES)
  30249. return WOLFSSL_SUCCESS;
  30250. return WOLFSSL_FAILURE;
  30251. }
  30252. /* return compliant with OpenSSL
  30253. * 1 if BIGNUM is one, 0 else */
  30254. int wolfSSL_BN_is_one(const WOLFSSL_BIGNUM* bn)
  30255. {
  30256. WOLFSSL_MSG("wolfSSL_BN_is_one");
  30257. if (bn == NULL || bn->internal == NULL)
  30258. return WOLFSSL_FAILURE;
  30259. if (mp_cmp_d((mp_int*)bn->internal, 1) == MP_EQ)
  30260. return WOLFSSL_SUCCESS;
  30261. return WOLFSSL_FAILURE;
  30262. }
  30263. /* return compliant with OpenSSL
  30264. * 1 if BIGNUM is odd, 0 else */
  30265. int wolfSSL_BN_is_odd(const WOLFSSL_BIGNUM* bn)
  30266. {
  30267. WOLFSSL_MSG("wolfSSL_BN_is_odd");
  30268. if (bn == NULL || bn->internal == NULL)
  30269. return WOLFSSL_FAILURE;
  30270. if (mp_isodd((mp_int*)bn->internal) == MP_YES)
  30271. return WOLFSSL_SUCCESS;
  30272. return WOLFSSL_FAILURE;
  30273. }
  30274. /* return compliant with OpenSSL
  30275. * 1 if BIGNUM is word, 0 else */
  30276. int wolfSSL_BN_is_word(const WOLFSSL_BIGNUM* bn, WOLFSSL_BN_ULONG w)
  30277. {
  30278. WOLFSSL_MSG("wolfSSL_BN_is_word");
  30279. if (bn == NULL || bn->internal == NULL) {
  30280. WOLFSSL_MSG("bn NULL error");
  30281. return WOLFSSL_FAILURE;
  30282. }
  30283. if (w <= (WOLFSSL_BN_ULONG)MP_MASK) {
  30284. if (mp_isword((mp_int*)bn->internal, (mp_digit)w) == MP_YES) {
  30285. return WOLFSSL_SUCCESS;
  30286. }
  30287. } else {
  30288. int ret;
  30289. mp_int w_mp;
  30290. if (mp_init(&w_mp) != MP_OKAY)
  30291. return WOLFSSL_FAILURE;
  30292. if (mp_set_int(&w_mp, w) != MP_OKAY)
  30293. return WOLFSSL_FAILURE;
  30294. ret = mp_cmp((mp_int *)bn->internal, &w_mp);
  30295. mp_free(&w_mp);
  30296. if (ret == MP_EQ)
  30297. return WOLFSSL_SUCCESS;
  30298. }
  30299. return WOLFSSL_FAILURE;
  30300. }
  30301. /* return compliant with OpenSSL
  30302. * -1 if a < b, 0 if a == b and 1 if a > b
  30303. */
  30304. int wolfSSL_BN_cmp(const WOLFSSL_BIGNUM* a, const WOLFSSL_BIGNUM* b)
  30305. {
  30306. int ret;
  30307. WOLFSSL_MSG("wolfSSL_BN_cmp");
  30308. if (a == NULL || a->internal == NULL || b == NULL || b->internal == NULL)
  30309. return WOLFSSL_FATAL_ERROR;
  30310. ret = mp_cmp((mp_int*)a->internal, (mp_int*)b->internal);
  30311. return (ret == MP_EQ ? 0 : (ret == MP_GT ? 1 : -1));
  30312. }
  30313. /* return compliant with OpenSSL
  30314. * length of BIGNUM in bytes, -1 if error */
  30315. int wolfSSL_BN_bn2bin(const WOLFSSL_BIGNUM* bn, unsigned char* r)
  30316. {
  30317. WOLFSSL_MSG("wolfSSL_BN_bn2bin");
  30318. if (bn == NULL || bn->internal == NULL) {
  30319. WOLFSSL_MSG("NULL bn error");
  30320. return WOLFSSL_FATAL_ERROR;
  30321. }
  30322. if (r == NULL)
  30323. return mp_unsigned_bin_size((mp_int*)bn->internal);
  30324. if (mp_to_unsigned_bin((mp_int*)bn->internal, r) != MP_OKAY) {
  30325. WOLFSSL_MSG("mp_to_unsigned_bin error");
  30326. return WOLFSSL_FATAL_ERROR;
  30327. }
  30328. return mp_unsigned_bin_size((mp_int*)bn->internal);
  30329. }
  30330. WOLFSSL_BIGNUM* wolfSSL_BN_bin2bn(const unsigned char* str, int len,
  30331. WOLFSSL_BIGNUM* ret)
  30332. {
  30333. int weOwn = 0;
  30334. WOLFSSL_MSG("wolfSSL_BN_bin2bn");
  30335. /* if ret is null create a BN */
  30336. if (ret == NULL) {
  30337. ret = wolfSSL_BN_new();
  30338. weOwn = 1;
  30339. if (ret == NULL)
  30340. return NULL;
  30341. }
  30342. /* check ret and ret->internal then read in value */
  30343. if (ret && ret->internal) {
  30344. if (mp_read_unsigned_bin((mp_int*)ret->internal, str, len) != 0) {
  30345. WOLFSSL_MSG("mp_read_unsigned_bin failure");
  30346. if (weOwn)
  30347. wolfSSL_BN_free(ret);
  30348. return NULL;
  30349. }
  30350. } else {
  30351. /* This may be overly defensive */
  30352. if (weOwn)
  30353. wolfSSL_BN_free(ret);
  30354. return NULL;
  30355. }
  30356. return ret;
  30357. }
  30358. /* return compliant with OpenSSL
  30359. * 1 if success, 0 if error */
  30360. #ifndef NO_WOLFSSL_STUB
  30361. int wolfSSL_mask_bits(WOLFSSL_BIGNUM* bn, int n)
  30362. {
  30363. (void)bn;
  30364. (void)n;
  30365. WOLFSSL_ENTER("wolfSSL_BN_mask_bits");
  30366. WOLFSSL_STUB("BN_mask_bits");
  30367. return SSL_FAILURE;
  30368. }
  30369. #endif
  30370. /* WOLFSSL_SUCCESS on ok */
  30371. int wolfSSL_BN_rand(WOLFSSL_BIGNUM* bn, int bits, int top, int bottom)
  30372. {
  30373. int ret = WOLFSSL_SUCCESS;
  30374. int len = (bits + 7) / 8;
  30375. WC_RNG* rng = &globalRNG;
  30376. byte* buff = NULL;
  30377. WOLFSSL_ENTER("wolfSSL_BN_rand");
  30378. if ((bn == NULL || bn->internal == NULL) || bits < 0 ||
  30379. (bits == 0 && (bottom != 0 || top != -1)) || (bits == 1 && top > 0)) {
  30380. WOLFSSL_MSG("Bad argument");
  30381. ret = WOLFSSL_FAILURE;
  30382. }
  30383. if (ret == WOLFSSL_SUCCESS) {
  30384. if (len == 0) {
  30385. mp_zero((mp_int*)bn->internal);
  30386. }
  30387. else {
  30388. buff = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  30389. if (buff == NULL) {
  30390. WOLFSSL_MSG("Failed to allocate buffer.");
  30391. XFREE(buff, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  30392. ret = WOLFSSL_FAILURE;
  30393. }
  30394. if (ret == WOLFSSL_SUCCESS && initGlobalRNG == 0 &&
  30395. wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
  30396. WOLFSSL_MSG("Failed to use global RNG.");
  30397. ret = WOLFSSL_FAILURE;
  30398. }
  30399. if (ret == WOLFSSL_SUCCESS &&
  30400. wc_RNG_GenerateBlock(rng, buff, len) != 0) {
  30401. WOLFSSL_MSG("wc_RNG_GenerateBlock failed");
  30402. ret = WOLFSSL_FAILURE;
  30403. }
  30404. if (ret == WOLFSSL_SUCCESS &&
  30405. mp_read_unsigned_bin((mp_int*)bn->internal,buff,len)
  30406. != MP_OKAY) {
  30407. WOLFSSL_MSG("mp_read_unsigned_bin failed");
  30408. ret = WOLFSSL_FAILURE;
  30409. }
  30410. if (ret == WOLFSSL_SUCCESS) {
  30411. /* Truncate to requested bit length. */
  30412. mp_rshb((mp_int*)bn->internal, 8 - (bits % 8));
  30413. if (top == 0) {
  30414. if (mp_set_bit((mp_int*)bn->internal, bits - 1)
  30415. != MP_OKAY) {
  30416. WOLFSSL_MSG("Failed to set top bit");
  30417. ret = WOLFSSL_FAILURE;
  30418. }
  30419. }
  30420. else if (top > 0) {
  30421. if (mp_set_bit((mp_int*)bn->internal, bits - 1)
  30422. != MP_OKAY ||
  30423. mp_set_bit((mp_int*)bn->internal, bits - 2)
  30424. != MP_OKAY) {
  30425. WOLFSSL_MSG("Failed to set top 2 bits");
  30426. ret = WOLFSSL_FAILURE;
  30427. }
  30428. }
  30429. }
  30430. if (ret == WOLFSSL_SUCCESS && bottom &&
  30431. mp_set_bit((mp_int*)bn->internal, 0) != MP_OKAY) {
  30432. WOLFSSL_MSG("Failed to set 0th bit");
  30433. ret = WOLFSSL_FAILURE;
  30434. }
  30435. if (buff != NULL) {
  30436. XFREE(buff, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  30437. }
  30438. }
  30439. }
  30440. WOLFSSL_LEAVE("wolfSSL_BN_rand", ret);
  30441. return ret;
  30442. }
  30443. /**
  30444. * N = length of range input var
  30445. * Generate N-bit length numbers until generated number is less than range
  30446. * @param r Output number
  30447. * @param range The upper limit of generated output
  30448. * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure
  30449. */
  30450. int wolfSSL_BN_rand_range(WOLFSSL_BIGNUM *r, const WOLFSSL_BIGNUM *range)
  30451. {
  30452. int n;
  30453. int iter = 0;
  30454. WOLFSSL_MSG("wolfSSL_BN_rand_range");
  30455. if (r == NULL || range == NULL) {
  30456. WOLFSSL_MSG("Bad parameter");
  30457. return WOLFSSL_FAILURE;
  30458. }
  30459. n = wolfSSL_BN_num_bits(range);
  30460. if (n <= 1) {
  30461. wolfSSL_BN_zero(r);
  30462. }
  30463. else {
  30464. do {
  30465. if (iter >= 100) {
  30466. WOLFSSL_MSG("wolfSSL_BN_rand_range too many iterations");
  30467. return WOLFSSL_FAILURE;
  30468. }
  30469. iter++;
  30470. if (wolfSSL_BN_pseudo_rand(r, n, -1, 0) == WOLFSSL_FAILURE) {
  30471. WOLFSSL_MSG("wolfSSL_BN_rand error");
  30472. return WOLFSSL_FAILURE;
  30473. }
  30474. } while(wolfSSL_BN_cmp(r, range) >= 0);
  30475. }
  30476. return WOLFSSL_SUCCESS;
  30477. }
  30478. /* WOLFSSL_SUCCESS on ok
  30479. * code is same as wolfSSL_BN_rand except for how top and bottom is handled.
  30480. * top -1 then leave most sig bit alone
  30481. * top 0 then most sig is set to 1
  30482. * top is 1 then first two most sig bits are 1
  30483. *
  30484. * bottom is hot then odd number */
  30485. int wolfSSL_BN_pseudo_rand(WOLFSSL_BIGNUM* bn, int bits, int top, int bottom)
  30486. {
  30487. int ret = 0;
  30488. int len;
  30489. int initTmpRng = 0;
  30490. WC_RNG* rng = NULL;
  30491. #ifdef WOLFSSL_SMALL_STACK
  30492. WC_RNG* tmpRNG = NULL;
  30493. byte* buff = NULL;
  30494. #else
  30495. WC_RNG tmpRNG[1];
  30496. byte buff[1024];
  30497. #endif
  30498. WOLFSSL_ENTER("wolfSSL_BN_pseudo_rand");
  30499. if (bits <= 0) {
  30500. return WOLFSSL_FAILURE;
  30501. }
  30502. len = bits / 8;
  30503. if (bits % 8)
  30504. len++;
  30505. /* has to be a length of at least 1 since we set buf[0] and buf[len-1] */
  30506. if (top == 1 || top == 0 || bottom == 1) {
  30507. if (len < 1) {
  30508. return WOLFSSL_FAILURE;
  30509. }
  30510. }
  30511. #ifdef WOLFSSL_SMALL_STACK
  30512. buff = (byte*)XMALLOC(1024, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  30513. tmpRNG = (WC_RNG*) XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_TMP_BUFFER);
  30514. if (buff == NULL || tmpRNG == NULL) {
  30515. XFREE(buff, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  30516. XFREE(tmpRNG, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  30517. return ret;
  30518. }
  30519. #endif
  30520. if (bn == NULL || bn->internal == NULL)
  30521. WOLFSSL_MSG("Bad function arguments");
  30522. else if (wc_InitRng(tmpRNG) == 0) {
  30523. rng = tmpRNG;
  30524. initTmpRng = 1;
  30525. }
  30526. else if (initGlobalRNG)
  30527. rng = &globalRNG;
  30528. if (rng) {
  30529. if (wc_RNG_GenerateBlock(rng, buff, len) != 0)
  30530. WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
  30531. else {
  30532. switch (top) {
  30533. case -1:
  30534. break;
  30535. case 0:
  30536. buff[0] |= 0x80;
  30537. break;
  30538. case 1:
  30539. buff[0] |= 0x80 | 0x40;
  30540. break;
  30541. }
  30542. if (bottom == 1) {
  30543. buff[len-1] |= 0x01;
  30544. }
  30545. if (mp_read_unsigned_bin((mp_int*)bn->internal,buff,len) != MP_OKAY)
  30546. WOLFSSL_MSG("mp read bin failed");
  30547. else
  30548. ret = WOLFSSL_SUCCESS;
  30549. }
  30550. }
  30551. if (initTmpRng)
  30552. wc_FreeRng(tmpRNG);
  30553. #ifdef WOLFSSL_SMALL_STACK
  30554. XFREE(buff, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  30555. XFREE(tmpRNG, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  30556. #endif
  30557. return ret;
  30558. }
  30559. /* return code compliant with OpenSSL :
  30560. * 1 if bit set, 0 else
  30561. */
  30562. int wolfSSL_BN_is_bit_set(const WOLFSSL_BIGNUM* bn, int n)
  30563. {
  30564. if (bn == NULL || bn->internal == NULL) {
  30565. WOLFSSL_MSG("bn NULL error");
  30566. return WOLFSSL_FAILURE;
  30567. }
  30568. return mp_is_bit_set((mp_int*)bn->internal, (mp_digit)n);
  30569. }
  30570. /* return code compliant with OpenSSL :
  30571. * 1 if success, 0 else
  30572. */
  30573. int wolfSSL_BN_set_bit(WOLFSSL_BIGNUM* bn, int n)
  30574. {
  30575. if (bn == NULL || bn->internal == NULL) {
  30576. WOLFSSL_MSG("bn NULL error");
  30577. return WOLFSSL_FAILURE;
  30578. }
  30579. if (mp_set_bit((mp_int*)bn->internal, n) != MP_OKAY) {
  30580. WOLFSSL_MSG("mp_set_bit error");
  30581. return WOLFSSL_FAILURE;
  30582. }
  30583. return WOLFSSL_SUCCESS;
  30584. }
  30585. int wolfSSL_BN_clear_bit(WOLFSSL_BIGNUM* bn, int n)
  30586. {
  30587. int ret = WOLFSSL_FAILURE;
  30588. #ifndef WOLFSSL_SMALL_STACK
  30589. mp_int tmp[1];
  30590. #else
  30591. mp_int* tmp = NULL;
  30592. #endif
  30593. if (bn == NULL || bn->internal == NULL) {
  30594. WOLFSSL_MSG("bn NULL error");
  30595. goto end;
  30596. }
  30597. if (mp_is_bit_set((mp_int*)bn->internal, n)) {
  30598. #ifdef WOLFSSL_SMALL_STACK
  30599. tmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  30600. if (tmp == NULL) {
  30601. goto end;
  30602. }
  30603. #endif
  30604. if (mp_init(tmp) != MP_OKAY) {
  30605. goto end;
  30606. }
  30607. if (mp_set_bit(tmp, n) != MP_OKAY) {
  30608. goto cleanup;
  30609. }
  30610. if (mp_sub((mp_int*)bn->internal, tmp, (mp_int*)bn->internal) != MP_OKAY) {
  30611. goto cleanup;
  30612. }
  30613. } else {
  30614. goto end;
  30615. }
  30616. ret = WOLFSSL_SUCCESS;
  30617. cleanup:
  30618. mp_clear(tmp);
  30619. end:
  30620. #ifdef WOLFSSL_SMALL_STACK
  30621. if (tmp)
  30622. XFREE(tmp, NULL, DYNAMIC_TYPE_BIGINT);
  30623. #endif
  30624. return ret;
  30625. }
  30626. /* WOLFSSL_SUCCESS on ok */
  30627. /* Note on use: this function expects str to be an even length. It is
  30628. * converting pairs of bytes into 8-bit values. As an example, the RSA
  30629. * public exponent is commonly 0x010001. To get it to convert, you need
  30630. * to pass in the string "010001", it will fail if you use "10001". This
  30631. * is an affect of how Base16_Decode() works.
  30632. */
  30633. int wolfSSL_BN_hex2bn(WOLFSSL_BIGNUM** bn, const char* str)
  30634. {
  30635. int ret = 0;
  30636. word32 decSz = 1024;
  30637. #ifdef WOLFSSL_SMALL_STACK
  30638. byte* decoded;
  30639. #else
  30640. byte decoded[1024];
  30641. #endif
  30642. int weOwn = 0;
  30643. int strLen;
  30644. WOLFSSL_MSG("wolfSSL_BN_hex2bn");
  30645. #ifdef WOLFSSL_SMALL_STACK
  30646. decoded = (byte*)XMALLOC(decSz, NULL, DYNAMIC_TYPE_DER);
  30647. if (decoded == NULL)
  30648. return ret;
  30649. #endif
  30650. if (str == NULL || str[0] == '\0') {
  30651. WOLFSSL_MSG("Bad function argument");
  30652. ret = WOLFSSL_FAILURE;
  30653. } else {
  30654. strLen = (int)XSTRLEN(str);
  30655. /* ignore trailing new lines */
  30656. while (str[strLen-1] == '\n' && strLen > 0) strLen--;
  30657. if (Base16_Decode((byte*)str, strLen, decoded, &decSz) < 0)
  30658. WOLFSSL_MSG("Bad Base16_Decode error");
  30659. else if (bn == NULL)
  30660. ret = decSz;
  30661. else {
  30662. if (*bn == NULL) {
  30663. *bn = wolfSSL_BN_new();
  30664. if (*bn != NULL) {
  30665. weOwn = 1;
  30666. }
  30667. }
  30668. if (*bn == NULL)
  30669. WOLFSSL_MSG("BN new failed");
  30670. else if (wolfSSL_BN_bin2bn(decoded, decSz, *bn) == NULL) {
  30671. WOLFSSL_MSG("Bad bin2bn error");
  30672. if (weOwn == 1) {
  30673. wolfSSL_BN_free(*bn); /* Free new BN */
  30674. }
  30675. }
  30676. else
  30677. ret = WOLFSSL_SUCCESS;
  30678. }
  30679. }
  30680. #ifdef WOLFSSL_SMALL_STACK
  30681. XFREE(decoded, NULL, DYNAMIC_TYPE_DER);
  30682. #endif
  30683. return ret;
  30684. }
  30685. WOLFSSL_BIGNUM* wolfSSL_BN_dup(const WOLFSSL_BIGNUM* bn)
  30686. {
  30687. WOLFSSL_BIGNUM* ret;
  30688. WOLFSSL_MSG("wolfSSL_BN_dup");
  30689. if (bn == NULL || bn->internal == NULL) {
  30690. WOLFSSL_MSG("bn NULL error");
  30691. return NULL;
  30692. }
  30693. ret = wolfSSL_BN_new();
  30694. if (ret == NULL) {
  30695. WOLFSSL_MSG("bn new error");
  30696. return NULL;
  30697. }
  30698. if (mp_copy((mp_int*)bn->internal, (mp_int*)ret->internal) != MP_OKAY) {
  30699. WOLFSSL_MSG("mp_copy error");
  30700. wolfSSL_BN_free(ret);
  30701. return NULL;
  30702. }
  30703. ret->neg = bn->neg;
  30704. return ret;
  30705. }
  30706. WOLFSSL_BIGNUM* wolfSSL_BN_copy(WOLFSSL_BIGNUM* r, const WOLFSSL_BIGNUM* bn)
  30707. {
  30708. WOLFSSL_MSG("wolfSSL_BN_copy");
  30709. if (r == NULL || bn == NULL) {
  30710. WOLFSSL_MSG("r or bn NULL error");
  30711. return NULL;
  30712. }
  30713. if (mp_copy((mp_int*)bn->internal, (mp_int*)r->internal) != MP_OKAY) {
  30714. WOLFSSL_MSG("mp_copy error");
  30715. return NULL;
  30716. }
  30717. r->neg = bn->neg;
  30718. return r;
  30719. }
  30720. /* return code compliant with OpenSSL :
  30721. * 1 if success, 0 else
  30722. */
  30723. int wolfSSL_BN_set_word(WOLFSSL_BIGNUM* bn, unsigned long w)
  30724. {
  30725. WOLFSSL_MSG("wolfSSL_BN_set_word");
  30726. if (bn == NULL) {
  30727. WOLFSSL_MSG("bn NULL error");
  30728. return WOLFSSL_FAILURE;
  30729. }
  30730. if (mp_set_int((mp_int*)bn->internal, w) != MP_OKAY) {
  30731. WOLFSSL_MSG("mp_init_set_int error");
  30732. return WOLFSSL_FAILURE;
  30733. }
  30734. return WOLFSSL_SUCCESS;
  30735. }
  30736. static WOLFSSL_BN_ULONG wolfSSL_BN_get_word_1(mp_int *mp) {
  30737. #if DIGIT_BIT >= (SIZEOF_LONG * CHAR_BIT)
  30738. return (WOLFSSL_BN_ULONG)mp->dp[0];
  30739. #else
  30740. WOLFSSL_BN_ULONG ret = 0UL;
  30741. int digit_i;
  30742. for (digit_i = 0; digit_i < mp->used; ++digit_i)
  30743. ret |= ((WOLFSSL_BN_ULONG)mp->dp[digit_i]) << (DIGIT_BIT * digit_i);
  30744. return ret;
  30745. #endif
  30746. }
  30747. /* Returns the big number as an unsigned long if possible.
  30748. *
  30749. * bn big number structure to get value from
  30750. *
  30751. * Returns value or 0xFFFFFFFFL if bigger than unsigned long.
  30752. */
  30753. WOLFSSL_BN_ULONG wolfSSL_BN_get_word(const WOLFSSL_BIGNUM* bn)
  30754. {
  30755. WOLFSSL_MSG("wolfSSL_BN_get_word");
  30756. if (bn == NULL) {
  30757. WOLFSSL_MSG("Invalid argument");
  30758. return 0;
  30759. }
  30760. if (wolfSSL_BN_num_bytes(bn) > (int)sizeof(unsigned long)) {
  30761. WOLFSSL_MSG("bignum is larger than unsigned long");
  30762. return 0xFFFFFFFFL;
  30763. }
  30764. return wolfSSL_BN_get_word_1((mp_int*)bn->internal);
  30765. }
  30766. /* return code compliant with OpenSSL :
  30767. * number length in decimal if success, 0 if error
  30768. */
  30769. #ifndef NO_WOLFSSL_STUB
  30770. int wolfSSL_BN_dec2bn(WOLFSSL_BIGNUM** bn, const char* str)
  30771. {
  30772. (void)bn;
  30773. (void)str;
  30774. WOLFSSL_MSG("wolfSSL_BN_dec2bn");
  30775. WOLFSSL_STUB("BN_dec2bn");
  30776. return SSL_FAILURE;
  30777. }
  30778. #endif
  30779. #if defined(WOLFSSL_KEY_GEN) || defined(HAVE_COMP_KEY)
  30780. char *wolfSSL_BN_bn2dec(const WOLFSSL_BIGNUM *bn)
  30781. {
  30782. int len = 0;
  30783. char *buf;
  30784. WOLFSSL_MSG("wolfSSL_BN_bn2dec");
  30785. if (bn == NULL || bn->internal == NULL) {
  30786. WOLFSSL_MSG("bn NULL error");
  30787. return NULL;
  30788. }
  30789. if (mp_radix_size((mp_int*)bn->internal, MP_RADIX_DEC, &len) != MP_OKAY) {
  30790. WOLFSSL_MSG("mp_radix_size failure");
  30791. return NULL;
  30792. }
  30793. buf = (char*) XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL);
  30794. if (buf == NULL) {
  30795. WOLFSSL_MSG("BN_bn2dec malloc buffer failure");
  30796. return NULL;
  30797. }
  30798. if (mp_todecimal((mp_int*)bn->internal, buf) != MP_OKAY) {
  30799. XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
  30800. return NULL;
  30801. }
  30802. return buf;
  30803. }
  30804. #else
  30805. char* wolfSSL_BN_bn2dec(const WOLFSSL_BIGNUM* bn)
  30806. {
  30807. (void)bn;
  30808. WOLFSSL_MSG("wolfSSL_BN_bn2dec");
  30809. return NULL;
  30810. }
  30811. #endif /* defined(WOLFSSL_KEY_GEN) || defined(HAVE_COMP_KEY) */
  30812. /* Internal function for adding/subtracting an unsigned long from a
  30813. * WOLFSSL_BIGNUM. To add, pass "sub" as 0. To subtract, pass it as 1.
  30814. * Returns 1 (WOLFSSL_SUCCESS) on success and 0 (WOLFSSL_FAILURE) on failure.
  30815. */
  30816. static int wolfSSL_BN_add_word_int(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w,
  30817. int sub)
  30818. {
  30819. int ret = WOLFSSL_SUCCESS;
  30820. int rc = 0;
  30821. #ifdef WOLFSSL_SMALL_STACK
  30822. mp_int *w_mp = (mp_int *)XMALLOC(sizeof(*w_mp), NULL,
  30823. DYNAMIC_TYPE_TMP_BUFFER);
  30824. if (w_mp == NULL)
  30825. return WOLFSSL_FAILURE;
  30826. #else
  30827. mp_int w_mp[1];
  30828. #endif
  30829. XMEMSET(w_mp, 0, sizeof(*w_mp));
  30830. if (bn == NULL || bn->internal == NULL) {
  30831. WOLFSSL_MSG("bn NULL error");
  30832. ret = WOLFSSL_FAILURE;
  30833. }
  30834. if (ret == WOLFSSL_SUCCESS) {
  30835. if (w <= (WOLFSSL_BN_ULONG)MP_MASK) {
  30836. if (sub == 1) {
  30837. rc = mp_sub_d((mp_int*)bn->internal, (mp_digit)w,
  30838. (mp_int*)bn->internal);
  30839. }
  30840. else {
  30841. rc = mp_add_d((mp_int*)bn->internal, (mp_digit)w,
  30842. (mp_int*)bn->internal);
  30843. }
  30844. if (rc != MP_OKAY) {
  30845. WOLFSSL_MSG("mp_add/sub_d error");
  30846. ret = WOLFSSL_FAILURE;
  30847. }
  30848. }
  30849. else {
  30850. if (mp_init(w_mp) != MP_OKAY) {
  30851. ret = WOLFSSL_FAILURE;
  30852. }
  30853. if (ret == WOLFSSL_SUCCESS) {
  30854. if (mp_set_int(w_mp, w) != MP_OKAY) {
  30855. ret = WOLFSSL_FAILURE;
  30856. }
  30857. }
  30858. if (ret == WOLFSSL_SUCCESS) {
  30859. if (sub == 1) {
  30860. rc = mp_sub((mp_int *)bn->internal, w_mp,
  30861. (mp_int *)bn->internal);
  30862. }
  30863. else {
  30864. rc = mp_add((mp_int *)bn->internal, w_mp,
  30865. (mp_int *)bn->internal);
  30866. }
  30867. if (rc != MP_OKAY) {
  30868. WOLFSSL_MSG("mp_add/sub error");
  30869. ret = WOLFSSL_FAILURE;
  30870. }
  30871. }
  30872. }
  30873. }
  30874. mp_free(w_mp);
  30875. #ifdef WOLFSSL_SMALL_STACK
  30876. XFREE(w_mp, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  30877. #endif
  30878. return ret;
  30879. }
  30880. /* return code compliant with OpenSSL :
  30881. * 1 if success, 0 else
  30882. */
  30883. int wolfSSL_BN_add_word(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w)
  30884. {
  30885. int ret;
  30886. WOLFSSL_ENTER("wolfSSL_BN_add_word");
  30887. ret = wolfSSL_BN_add_word_int(bn, w, 0);
  30888. WOLFSSL_LEAVE("wolfSSL_BN_add_word", ret);
  30889. return ret;
  30890. }
  30891. /* return code compliant with OpenSSL :
  30892. * 1 if success, 0 else
  30893. */
  30894. WOLFSSL_API int wolfSSL_BN_sub_word(WOLFSSL_BIGNUM* bn, WOLFSSL_BN_ULONG w)
  30895. {
  30896. int ret;
  30897. WOLFSSL_ENTER("wolfSSL_BN_sub_word");
  30898. ret = wolfSSL_BN_add_word_int(bn, w, 1);
  30899. WOLFSSL_LEAVE("wolfSSL_BN_sub_word", ret);
  30900. return ret;
  30901. }
  30902. #ifndef WOLFSSL_SP_MATH
  30903. /* return code compliant with OpenSSL :
  30904. * 1 if success, 0 else
  30905. */
  30906. int wolfSSL_BN_lshift(WOLFSSL_BIGNUM *r, const WOLFSSL_BIGNUM *bn, int n)
  30907. {
  30908. WOLFSSL_MSG("wolfSSL_BN_lshift");
  30909. if (r == NULL || r->internal == NULL || bn == NULL || bn->internal == NULL){
  30910. WOLFSSL_MSG("bn NULL error");
  30911. return WOLFSSL_FAILURE;
  30912. }
  30913. if (mp_mul_2d((mp_int*)bn->internal, n, (mp_int*)r->internal) != MP_OKAY) {
  30914. WOLFSSL_MSG("mp_mul_2d error");
  30915. return WOLFSSL_FAILURE;
  30916. }
  30917. return WOLFSSL_SUCCESS;
  30918. }
  30919. /* return code compliant with OpenSSL :
  30920. * 1 if success, 0 else
  30921. */
  30922. int wolfSSL_BN_rshift(WOLFSSL_BIGNUM *r, const WOLFSSL_BIGNUM *bn, int n)
  30923. {
  30924. WOLFSSL_MSG("wolfSSL_BN_rshift");
  30925. if (r == NULL || r->internal == NULL || bn == NULL || bn->internal == NULL){
  30926. WOLFSSL_MSG("bn NULL error");
  30927. return WOLFSSL_FAILURE;
  30928. }
  30929. if (mp_div_2d((mp_int*)bn->internal, n,
  30930. (mp_int*)r->internal, NULL) != MP_OKAY) {
  30931. WOLFSSL_MSG("mp_mul_2d error");
  30932. return WOLFSSL_FAILURE;
  30933. }
  30934. return WOLFSSL_SUCCESS;
  30935. }
  30936. #endif
  30937. /* return code compliant with OpenSSL :
  30938. * 1 if success, 0 else
  30939. */
  30940. int wolfSSL_BN_add(WOLFSSL_BIGNUM *r, WOLFSSL_BIGNUM *a, WOLFSSL_BIGNUM *b)
  30941. {
  30942. WOLFSSL_MSG("wolfSSL_BN_add");
  30943. if (r == NULL || r->internal == NULL || a == NULL || a->internal == NULL ||
  30944. b == NULL || b->internal == NULL) {
  30945. WOLFSSL_MSG("bn NULL error");
  30946. return WOLFSSL_FAILURE;
  30947. }
  30948. if (mp_add((mp_int*)a->internal, (mp_int*)b->internal,
  30949. (mp_int*)r->internal) != MP_OKAY) {
  30950. WOLFSSL_MSG("mp_add_d error");
  30951. return WOLFSSL_FAILURE;
  30952. }
  30953. return WOLFSSL_SUCCESS;
  30954. }
  30955. #ifndef WOLFSSL_SP_MATH
  30956. /* r = a + b (mod m) */
  30957. int wolfSSL_BN_mod_add(WOLFSSL_BIGNUM *r, const WOLFSSL_BIGNUM *a,
  30958. const WOLFSSL_BIGNUM *b, const WOLFSSL_BIGNUM *m,
  30959. WOLFSSL_BN_CTX *ctx)
  30960. {
  30961. (void)ctx;
  30962. WOLFSSL_MSG("wolfSSL_BN_add");
  30963. if (r == NULL || r->internal == NULL ||
  30964. a == NULL || a->internal == NULL ||
  30965. b == NULL || b->internal == NULL ||
  30966. m == NULL || m->internal == NULL) {
  30967. WOLFSSL_MSG("bn NULL error");
  30968. return WOLFSSL_FAILURE;
  30969. }
  30970. if (mp_addmod((mp_int*)a->internal, (mp_int*)b->internal,
  30971. (mp_int*)m->internal, (mp_int*)r->internal) != MP_OKAY) {
  30972. WOLFSSL_MSG("mp_add_d error");
  30973. return WOLFSSL_FAILURE;
  30974. }
  30975. return WOLFSSL_SUCCESS;
  30976. }
  30977. #endif
  30978. #if defined(WOLFSSL_KEY_GEN) && (!defined(NO_RSA) || !defined(NO_DH) || !defined(NO_DSA))
  30979. int wolfSSL_BN_generate_prime_ex(WOLFSSL_BIGNUM* prime, int bits,
  30980. int safe, const WOLFSSL_BIGNUM* add, const WOLFSSL_BIGNUM* rem,
  30981. WOLFSSL_BN_GENCB* cb)
  30982. {
  30983. int ret = WOLFSSL_SUCCESS;
  30984. #ifdef WOLFSSL_SMALL_STACK
  30985. WC_RNG* rng = NULL;
  30986. #else
  30987. WC_RNG rng[1];
  30988. #endif
  30989. (void)cb;
  30990. WOLFSSL_ENTER("wolfSSL_BN_generate_prime_ex");
  30991. if (safe == 1 || add != NULL || rem != NULL) {
  30992. /* These parameters aren't supported, yet. */
  30993. ret = WOLFSSL_FAILURE;
  30994. }
  30995. if (prime == NULL || prime->internal == NULL) {
  30996. ret = WOLFSSL_FAILURE;
  30997. }
  30998. #ifdef WOLFSSL_SMALL_STACK
  30999. if (ret == WOLFSSL_SUCCESS) {
  31000. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  31001. if (rng == NULL) {
  31002. ret = WOLFSSL_FAILURE;
  31003. }
  31004. }
  31005. #endif
  31006. if (ret == WOLFSSL_SUCCESS) {
  31007. XMEMSET(rng, 0, sizeof(WC_RNG));
  31008. if (wc_InitRng(rng) != 0) {
  31009. ret = WOLFSSL_FAILURE;
  31010. }
  31011. }
  31012. if (ret == WOLFSSL_SUCCESS) {
  31013. if (mp_rand_prime((mp_int*)prime->internal, (bits + 7) / 8, rng, NULL)
  31014. != MP_OKAY) {
  31015. ret = WOLFSSL_FAILURE;
  31016. }
  31017. }
  31018. wc_FreeRng(rng);
  31019. #ifdef WOLFSSL_SMALL_STACK
  31020. if (rng != NULL)
  31021. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  31022. #endif
  31023. WOLFSSL_LEAVE("wolfSSL_BN_generate_prime_ex", ret);
  31024. return ret;
  31025. }
  31026. /* return code compliant with OpenSSL :
  31027. * 1 if prime, 0 if not, -1 if error
  31028. */
  31029. int wolfSSL_BN_is_prime_ex(const WOLFSSL_BIGNUM *bn, int nbchecks,
  31030. WOLFSSL_BN_CTX *ctx, WOLFSSL_BN_GENCB *cb)
  31031. {
  31032. WC_RNG* rng = NULL;
  31033. #ifdef WOLFSSL_SMALL_STACK
  31034. WC_RNG* tmpRNG = NULL;
  31035. #else
  31036. WC_RNG tmpRNG[1];
  31037. #endif
  31038. int initTmpRng = 0;
  31039. int res = MP_NO;
  31040. (void)ctx;
  31041. (void)cb;
  31042. WOLFSSL_MSG("wolfSSL_BN_is_prime_ex");
  31043. if (bn == NULL || bn->internal == NULL) {
  31044. WOLFSSL_MSG("bn NULL error");
  31045. return WOLFSSL_FATAL_ERROR;
  31046. }
  31047. #ifdef WOLFSSL_SMALL_STACK
  31048. tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  31049. if (tmpRNG == NULL)
  31050. return WOLFSSL_FAILURE;
  31051. #endif
  31052. if (wc_InitRng(tmpRNG) == 0) {
  31053. rng = tmpRNG;
  31054. initTmpRng = 1;
  31055. }
  31056. else {
  31057. WOLFSSL_MSG("Bad RNG Init, trying global");
  31058. if (initGlobalRNG == 0) {
  31059. WOLFSSL_MSG("Global RNG no Init");
  31060. }
  31061. else
  31062. rng = &globalRNG;
  31063. }
  31064. if (rng) {
  31065. if (mp_prime_is_prime_ex((mp_int*)bn->internal,
  31066. nbchecks, &res, rng) != MP_OKAY) {
  31067. WOLFSSL_MSG("mp_prime_is_prime_ex error");
  31068. res = MP_NO;
  31069. }
  31070. }
  31071. if (initTmpRng)
  31072. wc_FreeRng(tmpRNG);
  31073. #ifdef WOLFSSL_SMALL_STACK
  31074. XFREE(tmpRNG, NULL, DYNAMIC_TYPE_RNG);
  31075. #endif
  31076. if (res != MP_YES) {
  31077. WOLFSSL_MSG("mp_prime_is_prime_ex not prime");
  31078. return WOLFSSL_FAILURE;
  31079. }
  31080. return WOLFSSL_SUCCESS;
  31081. }
  31082. /* return code compliant with OpenSSL :
  31083. * (bn mod w) if success, -1 if error
  31084. */
  31085. WOLFSSL_BN_ULONG wolfSSL_BN_mod_word(const WOLFSSL_BIGNUM *bn,
  31086. WOLFSSL_BN_ULONG w)
  31087. {
  31088. WOLFSSL_BN_ULONG ret = 0;
  31089. WOLFSSL_MSG("wolfSSL_BN_mod_word");
  31090. if (bn == NULL || bn->internal == NULL) {
  31091. WOLFSSL_MSG("bn NULL error");
  31092. return (WOLFSSL_BN_ULONG)WOLFSSL_FATAL_ERROR;
  31093. }
  31094. if (w <= (WOLFSSL_BN_ULONG)MP_MASK) {
  31095. mp_digit bn_ret;
  31096. if (mp_mod_d((mp_int*)bn->internal, (mp_digit)w, &bn_ret) != MP_OKAY) {
  31097. WOLFSSL_MSG("mp_add_d error");
  31098. return (WOLFSSL_BN_ULONG)WOLFSSL_FATAL_ERROR;
  31099. }
  31100. ret = (WOLFSSL_BN_ULONG)bn_ret;
  31101. } else {
  31102. int mp_ret;
  31103. mp_int w_mp, r_mp;
  31104. if (mp_init(&w_mp) != MP_OKAY)
  31105. return (unsigned long)WOLFSSL_FAILURE;
  31106. if (mp_init(&r_mp) != MP_OKAY)
  31107. return (unsigned long)WOLFSSL_FAILURE;
  31108. if (mp_set_int(&w_mp, w) != MP_OKAY)
  31109. return (unsigned long)WOLFSSL_FAILURE;
  31110. mp_ret = mp_mod((mp_int *)bn->internal, &w_mp, &r_mp);
  31111. ret = wolfSSL_BN_get_word_1(&r_mp);
  31112. mp_free(&r_mp);
  31113. mp_free(&w_mp);
  31114. if (mp_ret != MP_OKAY) {
  31115. WOLFSSL_MSG("mp_mod error");
  31116. return (WOLFSSL_BN_ULONG)WOLFSSL_FAILURE;
  31117. }
  31118. }
  31119. return ret;
  31120. }
  31121. #endif /* WOLFSSL_KEY_GEN && (!NO_RSA || !NO_DH || !NO_DSA) */
  31122. char *wolfSSL_BN_bn2hex(const WOLFSSL_BIGNUM *bn)
  31123. {
  31124. int len = 0;
  31125. char *buf;
  31126. WOLFSSL_ENTER("wolfSSL_BN_bn2hex");
  31127. if (bn == NULL || bn->internal == NULL) {
  31128. WOLFSSL_MSG("bn NULL error");
  31129. return NULL;
  31130. }
  31131. if (mp_radix_size((mp_int*)bn->internal, MP_RADIX_HEX, &len) != MP_OKAY) {
  31132. WOLFSSL_MSG("mp_radix_size failure");
  31133. return NULL;
  31134. }
  31135. buf = (char*)XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL);
  31136. if (buf == NULL) {
  31137. WOLFSSL_MSG("BN_bn2hex malloc buffer failure");
  31138. return NULL;
  31139. }
  31140. if (mp_tohex((mp_int*)bn->internal, buf) != MP_OKAY) {
  31141. XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
  31142. return NULL;
  31143. }
  31144. return buf;
  31145. }
  31146. #ifndef NO_FILESYSTEM
  31147. /* return code compliant with OpenSSL :
  31148. * 1 if success, 0 if error
  31149. */
  31150. int wolfSSL_BN_print_fp(XFILE fp, const WOLFSSL_BIGNUM *bn)
  31151. {
  31152. char *buf;
  31153. int ret;
  31154. WOLFSSL_ENTER("wolfSSL_BN_print_fp");
  31155. if (fp == XBADFILE || bn == NULL || bn->internal == NULL) {
  31156. WOLFSSL_MSG("bn NULL error");
  31157. return WOLFSSL_FAILURE;
  31158. }
  31159. buf = wolfSSL_BN_bn2hex(bn);
  31160. if (buf == NULL) {
  31161. WOLFSSL_MSG("wolfSSL_BN_bn2hex failure");
  31162. return WOLFSSL_FAILURE;
  31163. }
  31164. if (XFPRINTF(fp, "%s", buf) < 0)
  31165. ret = WOLFSSL_FAILURE;
  31166. else
  31167. ret = WOLFSSL_SUCCESS;
  31168. XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
  31169. return ret;
  31170. }
  31171. #endif /* !NO_FILESYSTEM */
  31172. WOLFSSL_BIGNUM *wolfSSL_BN_CTX_get(WOLFSSL_BN_CTX *ctx)
  31173. {
  31174. /* ctx is not used, return new Bignum */
  31175. (void)ctx;
  31176. WOLFSSL_ENTER("wolfSSL_BN_CTX_get");
  31177. return wolfSSL_BN_new();
  31178. }
  31179. #ifndef NO_WOLFSSL_STUB
  31180. void wolfSSL_BN_CTX_start(WOLFSSL_BN_CTX *ctx)
  31181. {
  31182. (void)ctx;
  31183. WOLFSSL_ENTER("wolfSSL_BN_CTX_start");
  31184. WOLFSSL_STUB("BN_CTX_start");
  31185. WOLFSSL_MSG("wolfSSL_BN_CTX_start TBD");
  31186. }
  31187. #endif
  31188. WOLFSSL_BIGNUM *wolfSSL_BN_mod_inverse(WOLFSSL_BIGNUM *r,
  31189. WOLFSSL_BIGNUM *a,
  31190. const WOLFSSL_BIGNUM *n,
  31191. WOLFSSL_BN_CTX *ctx)
  31192. {
  31193. int dynamic = 0;
  31194. /* ctx is not used */
  31195. (void)ctx;
  31196. WOLFSSL_ENTER("wolfSSL_BN_mod_inverse");
  31197. /* check parameter */
  31198. if (r == NULL) {
  31199. r = wolfSSL_BN_new();
  31200. if (r == NULL){
  31201. WOLFSSL_MSG("WolfSSL_BN_new() failed");
  31202. return NULL;
  31203. }
  31204. dynamic = 1;
  31205. }
  31206. if (a == NULL) {
  31207. WOLFSSL_MSG("a NULL error");
  31208. if (dynamic == 1) {
  31209. wolfSSL_BN_free(r);
  31210. }
  31211. return NULL;
  31212. }
  31213. if (n == NULL) {
  31214. WOLFSSL_MSG("n NULL error");
  31215. if (dynamic == 1) {
  31216. wolfSSL_BN_free(r);
  31217. }
  31218. return NULL;
  31219. }
  31220. /* Compute inverse of a modulo n and return r */
  31221. if (mp_invmod((mp_int *)a->internal,(mp_int *)n->internal,
  31222. (mp_int*)r->internal) == MP_VAL){
  31223. WOLFSSL_MSG("mp_invmod() error");
  31224. if (dynamic == 1) {
  31225. wolfSSL_BN_free(r);
  31226. }
  31227. return NULL;
  31228. }
  31229. return r;
  31230. }
  31231. #endif /* OPENSSL_EXTRA */
  31232. #if (defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)) && \
  31233. !defined(NO_ASN)
  31234. #ifndef NO_BIO
  31235. static int unprintable_char(char c)
  31236. {
  31237. const unsigned char last_unprintable = 31;
  31238. const unsigned char LF = 10;
  31239. const unsigned char CR = 13;
  31240. if (c <= last_unprintable && c != LF && c != CR) {
  31241. return 1;
  31242. }
  31243. return 0;
  31244. }
  31245. int wolfSSL_ASN1_STRING_print(WOLFSSL_BIO *out, WOLFSSL_ASN1_STRING *str)
  31246. {
  31247. int i;
  31248. WOLFSSL_ENTER("wolfSSL_ASN1_STRING_print");
  31249. if (out == NULL || str == NULL)
  31250. return WOLFSSL_FAILURE;
  31251. for (i=0; i < str->length; i++) {
  31252. if (unprintable_char(str->data[i])) {
  31253. str->data[i] = '.';
  31254. }
  31255. }
  31256. if (wolfSSL_BIO_write(out, str->data, str->length) != str->length){
  31257. return WOLFSSL_FAILURE;
  31258. }
  31259. return str->length;
  31260. }
  31261. #endif /* !NO_BIO */
  31262. #endif /* (WOLFSSL_QT || OPENSSL_ALL || OPENSSL_EXTRA) && !NO_ASN */
  31263. #if defined(OPENSSL_EXTRA)
  31264. const char *wolfSSL_ASN1_tag2str(int tag)
  31265. {
  31266. static const char *const tag_label[31] = {
  31267. "EOC", "BOOLEAN", "INTEGER", "BIT STRING", "OCTET STRING", "NULL",
  31268. "OBJECT", "OBJECT DESCRIPTOR", "EXTERNAL", "REAL", "ENUMERATED",
  31269. "<ASN1 11>", "UTF8STRING", "<ASN1 13>", "<ASN1 14>", "<ASN1 15>",
  31270. "SEQUENCE", "SET", "NUMERICSTRING", "PRINTABLESTRING", "T61STRING",
  31271. "VIDEOTEXTSTRING", "IA5STRING", "UTCTIME", "GENERALIZEDTIME",
  31272. "GRAPHICSTRING", "VISIBLESTRING", "GENERALSTRING", "UNIVERSALSTRING",
  31273. "<ASN1 29>", "BMPSTRING"
  31274. };
  31275. if ((tag == V_ASN1_NEG_INTEGER) || (tag == V_ASN1_NEG_ENUMERATED))
  31276. tag &= ~0x100;
  31277. if (tag < 0 || tag > 30)
  31278. return "(unknown)";
  31279. return tag_label[tag];
  31280. }
  31281. #ifndef NO_BIO
  31282. static int check_esc_char(char c, char *esc)
  31283. {
  31284. char *ptr;
  31285. ptr = esc;
  31286. while(*ptr != 0){
  31287. if (c == *ptr)
  31288. return 1;
  31289. ptr++;
  31290. }
  31291. return 0;
  31292. }
  31293. int wolfSSL_ASN1_STRING_print_ex(WOLFSSL_BIO *out, WOLFSSL_ASN1_STRING *str,
  31294. unsigned long flags)
  31295. {
  31296. size_t str_len = 0, type_len = 0;
  31297. unsigned char *typebuf = NULL;
  31298. const char *hash="#";
  31299. WOLFSSL_ENTER("wolfSSL_ASN1_STRING_PRINT_ex");
  31300. if (out == NULL || str == NULL)
  31301. return WOLFSSL_FAILURE;
  31302. /* add ASN1 type tag */
  31303. if (flags & ASN1_STRFLGS_SHOW_TYPE){
  31304. const char *tag = wolfSSL_ASN1_tag2str(str->type);
  31305. /* colon len + tag len + null*/
  31306. type_len = XSTRLEN(tag) + 2;
  31307. typebuf = (unsigned char *)XMALLOC(type_len , NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31308. if (typebuf == NULL){
  31309. WOLFSSL_MSG("memory alloc failed.");
  31310. return WOLFSSL_FAILURE;
  31311. }
  31312. XMEMSET(typebuf, 0, type_len);
  31313. if (XSNPRINTF((char*)typebuf, (size_t)type_len , "%s:", tag)
  31314. >= (int)type_len)
  31315. {
  31316. WOLFSSL_MSG("Buffer overrun.");
  31317. return WOLFSSL_FAILURE;
  31318. }
  31319. type_len--;
  31320. }
  31321. /* dump hex */
  31322. if (flags & ASN1_STRFLGS_DUMP_ALL){
  31323. char hex_tmp[4];
  31324. char *str_ptr, *str_end;
  31325. if (type_len > 0){
  31326. if (wolfSSL_BIO_write(out, typebuf, (int)type_len) != (int)type_len){
  31327. XFREE(typebuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31328. return WOLFSSL_FAILURE;
  31329. }
  31330. str_len += type_len;
  31331. }
  31332. if (wolfSSL_BIO_write(out, hash, 1) != 1){
  31333. goto err_exit;
  31334. }
  31335. str_len++;
  31336. if (flags & ASN1_STRFLGS_DUMP_DER){
  31337. ByteToHexStr((byte)str->type, &hex_tmp[0]);
  31338. ByteToHexStr((byte)str->length, &hex_tmp[2]);
  31339. if (wolfSSL_BIO_write(out, hex_tmp, 4) != 4){
  31340. goto err_exit;
  31341. }
  31342. str_len += 4;
  31343. XMEMSET(hex_tmp, 0, 4);
  31344. }
  31345. str_ptr = str->data;
  31346. str_end = str->data + str->length;
  31347. while (str_ptr < str_end){
  31348. ByteToHexStr((byte)*str_ptr, &hex_tmp[0]);
  31349. if (wolfSSL_BIO_write(out, hex_tmp, 2) != 2){
  31350. goto err_exit;
  31351. }
  31352. str_ptr++;
  31353. str_len += 2;
  31354. }
  31355. if (type_len > 0)
  31356. XFREE(typebuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31357. return (int)str_len;
  31358. }
  31359. if (type_len > 0){
  31360. if (wolfSSL_BIO_write(out, typebuf, (int)type_len) != (int)type_len){
  31361. XFREE(typebuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31362. return WOLFSSL_FAILURE;
  31363. }
  31364. str_len += type_len;
  31365. }
  31366. if (flags & ASN1_STRFLGS_ESC_2253){
  31367. char esc_ch[] = "+;<>\\";
  31368. char* esc_ptr;
  31369. esc_ptr = str->data;
  31370. while (*esc_ptr != 0){
  31371. if (check_esc_char(*esc_ptr, esc_ch)){
  31372. if (wolfSSL_BIO_write(out,"\\", 1) != 1)
  31373. goto err_exit;
  31374. str_len++;
  31375. }
  31376. if (wolfSSL_BIO_write(out, esc_ptr, 1) != 1)
  31377. goto err_exit;
  31378. str_len++;
  31379. esc_ptr++;
  31380. }
  31381. if (type_len > 0)
  31382. XFREE(typebuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31383. return (int)str_len;
  31384. }
  31385. if (wolfSSL_BIO_write(out, str->data, str->length) != str->length){
  31386. goto err_exit;
  31387. }
  31388. str_len += str->length;
  31389. if (type_len > 0)
  31390. XFREE(typebuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31391. return (int)str_len;
  31392. err_exit:
  31393. if (type_len > 0)
  31394. XFREE(typebuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31395. return WOLFSSL_FAILURE;
  31396. }
  31397. #endif /* !NO_BIO */
  31398. #if !defined(NO_ASN_TIME) && !defined(USER_TIME) && !defined(TIME_OVERRIDES)
  31399. WOLFSSL_ASN1_TIME* wolfSSL_ASN1_TIME_adj(WOLFSSL_ASN1_TIME *s, time_t t,
  31400. int offset_day, long offset_sec)
  31401. {
  31402. const time_t sec_per_day = 24*60*60;
  31403. time_t t_adj = 0;
  31404. time_t offset_day_sec = 0;
  31405. char time_str[MAX_TIME_STRING_SZ];
  31406. int time_get;
  31407. WOLFSSL_ENTER("wolfSSL_ASN1_TIME_adj");
  31408. if (s == NULL) {
  31409. s = wolfSSL_ASN1_TIME_new();
  31410. if (s == NULL) {
  31411. return NULL;
  31412. }
  31413. }
  31414. /* compute GMT time with offset */
  31415. offset_day_sec = offset_day * sec_per_day;
  31416. t_adj = t + offset_day_sec + offset_sec;
  31417. /* Get time string as either UTC or GeneralizedTime */
  31418. time_get = GetFormattedTime(&t_adj, (byte*)time_str,
  31419. (word32)sizeof(time_str));
  31420. if (time_get <= 0) {
  31421. wolfSSL_ASN1_TIME_free(s);
  31422. return NULL;
  31423. }
  31424. if (wolfSSL_ASN1_TIME_set_string(s, time_str) != WOLFSSL_SUCCESS) {
  31425. wolfSSL_ASN1_TIME_free(s);
  31426. return NULL;
  31427. }
  31428. return s;
  31429. }
  31430. #endif /* !NO_ASN_TIME && !USER_TIME && !TIME_OVERRIDES */
  31431. #ifndef NO_ASN_TIME
  31432. WOLFSSL_ASN1_TIME* wolfSSL_ASN1_TIME_new(void)
  31433. {
  31434. WOLFSSL_ASN1_TIME* ret = (WOLFSSL_ASN1_TIME*)
  31435. XMALLOC(sizeof(WOLFSSL_ASN1_TIME), NULL, DYNAMIC_TYPE_OPENSSL);
  31436. if (!ret)
  31437. return NULL;
  31438. XMEMSET(ret, 0, sizeof(WOLFSSL_ASN1_TIME));
  31439. return ret;
  31440. }
  31441. void wolfSSL_ASN1_TIME_free(WOLFSSL_ASN1_TIME* t)
  31442. {
  31443. if (t) {
  31444. XFREE(t, NULL, DYNAMIC_TYPE_OPENSSL);
  31445. }
  31446. }
  31447. /* not a compatibility function - length getter for opaque type */
  31448. int wolfSSL_ASN1_TIME_get_length(WOLFSSL_ASN1_TIME *t)
  31449. {
  31450. WOLFSSL_ENTER("wolfSSL_ASN1_TIME_get_length");
  31451. if (t == NULL)
  31452. return WOLFSSL_FAILURE;
  31453. return t->length;
  31454. }
  31455. /* not a compatibility function - data getter for opaque type */
  31456. unsigned char* wolfSSL_ASN1_TIME_get_data(WOLFSSL_ASN1_TIME *t)
  31457. {
  31458. WOLFSSL_ENTER("wolfSSL_ASN1_TIME_get_data");
  31459. if (t == NULL)
  31460. return NULL;
  31461. return t->data;
  31462. }
  31463. WOLFSSL_ASN1_TIME* wolfSSL_ASN1_TIME_to_generalizedtime(WOLFSSL_ASN1_TIME *t,
  31464. WOLFSSL_ASN1_TIME **out)
  31465. {
  31466. int time_type = 0;
  31467. WOLFSSL_ASN1_TIME *ret = NULL;
  31468. WOLFSSL_ENTER("wolfSSL_ASN1_TIME_to_generalizedtime");
  31469. if (t == NULL) {
  31470. WOLFSSL_MSG("Invalid ASN_TIME value");
  31471. } else {
  31472. time_type = t->type;
  31473. if (time_type != ASN_UTC_TIME && time_type != ASN_GENERALIZED_TIME){
  31474. WOLFSSL_MSG("Invalid ASN_TIME type.");
  31475. } else {
  31476. if (out == NULL || *out == NULL) {
  31477. ret = wolfSSL_ASN1_TIME_new();
  31478. if (ret == NULL){
  31479. WOLFSSL_MSG("memory alloc failed.");
  31480. }
  31481. } else {
  31482. ret = *out;
  31483. }
  31484. }
  31485. }
  31486. if (ret != NULL) {
  31487. if (time_type == ASN_GENERALIZED_TIME){
  31488. XMEMCPY(ret->data, t->data, ASN_GENERALIZED_TIME_SIZE);
  31489. } else { /* ASN_UTC_TIME */
  31490. /* convert UTC to generalized time */
  31491. ret->type = ASN_GENERALIZED_TIME;
  31492. ret->length = ASN_GENERALIZED_TIME_SIZE;
  31493. if (t->data[0] >= '5') {
  31494. ret->data[0] = '1'; ret->data[1] = '9';
  31495. } else {
  31496. ret->data[0] = '2'; ret->data[1] = '0';
  31497. }
  31498. XMEMCPY(&ret->data[2], t->data, ASN_UTC_TIME_SIZE);
  31499. }
  31500. }
  31501. return ret;
  31502. }
  31503. #endif /* !NO_ASN_TIME */
  31504. #ifndef NO_ASN
  31505. int wolfSSL_i2c_ASN1_INTEGER(WOLFSSL_ASN1_INTEGER *a, unsigned char **pp)
  31506. {
  31507. unsigned char *pptr = NULL;
  31508. char pad = 0 ;
  31509. unsigned char pad_val = 0;
  31510. int ret_size = 0;
  31511. unsigned char data1 = 0;
  31512. unsigned char neg = 0;
  31513. int i = 0;
  31514. WOLFSSL_ENTER("wolfSSL_i2c_ASN1_INTEGER");
  31515. if (a == NULL)
  31516. return WOLFSSL_FAILURE;
  31517. ret_size = a->intData[1];
  31518. if (ret_size == 0)
  31519. ret_size = 1;
  31520. else{
  31521. ret_size = (int)a->intData[1];
  31522. neg = a->negative;
  31523. data1 = a->intData[2];
  31524. if (ret_size == 1 && data1 == 0)
  31525. neg = 0;
  31526. /* 0x80 or greater positive number in first byte */
  31527. if (!neg && (data1 > 127)){
  31528. pad = 1;
  31529. pad_val = 0;
  31530. } else if (neg){
  31531. /* negative number */
  31532. if (data1 > 128){
  31533. pad = 1;
  31534. pad_val = 0xff;
  31535. } else if (data1 == 128){
  31536. for (i = 3; i < a->intData[1] + 2; i++){
  31537. if (a->intData[i]){
  31538. pad = 1;
  31539. pad_val = 0xff;
  31540. break;
  31541. }
  31542. }
  31543. }
  31544. }
  31545. ret_size += (int)pad;
  31546. }
  31547. if (pp == NULL)
  31548. return ret_size;
  31549. pptr = *pp;
  31550. if (pad)
  31551. *(pptr++) = pad_val;
  31552. if (a->intData[1] == 0)
  31553. *(pptr++) = 0;
  31554. else if (!neg){
  31555. /* positive number */
  31556. for (i=0; i < a->intData[1]; i++){
  31557. *pptr = a->intData[i+2];
  31558. pptr++;
  31559. }
  31560. } else {
  31561. /* negative number */
  31562. int str_len = 0;
  31563. /* 0 padding from end of buffer */
  31564. str_len = (int)a->intData[1];
  31565. pptr += a->intData[1] - 1;
  31566. while (!a->intData[str_len + 2] && str_len > 1){
  31567. *(pptr--) = 0;
  31568. str_len--;
  31569. }
  31570. /* 2's complement next octet */
  31571. *(pptr--) = ((a->intData[str_len + 1]) ^ 0xff) + 1;
  31572. str_len--;
  31573. /* Complement any octets left */
  31574. while (str_len > 0){
  31575. *(pptr--) = a->intData[str_len + 1] ^ 0xff;
  31576. str_len--;
  31577. }
  31578. }
  31579. *pp += ret_size;
  31580. return ret_size;
  31581. }
  31582. #endif /* !NO_ASN */
  31583. #endif /* OPENSSL_EXTRA */
  31584. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  31585. /* when calling SetIndividualExternal, mpi should be cleared by caller if no
  31586. * longer used. ie mp_free(mpi). This is to free data when fastmath is
  31587. * disabled since a copy of mpi is made by this function and placed into bn.
  31588. */
  31589. int SetIndividualExternal(WOLFSSL_BIGNUM** bn, mp_int* mpi)
  31590. {
  31591. byte dynamic = 0;
  31592. #ifdef WOLFSSL_DEBUG_OPENSSL
  31593. WOLFSSL_MSG("Entering SetIndividualExternal");
  31594. #endif
  31595. if (mpi == NULL || bn == NULL) {
  31596. WOLFSSL_MSG("mpi NULL error");
  31597. return WOLFSSL_FATAL_ERROR;
  31598. }
  31599. if (*bn == NULL) {
  31600. *bn = wolfSSL_BN_new();
  31601. if (*bn == NULL) {
  31602. WOLFSSL_MSG("SetIndividualExternal alloc failed");
  31603. return WOLFSSL_FATAL_ERROR;
  31604. }
  31605. dynamic = 1;
  31606. }
  31607. if (mp_copy(mpi, (mp_int*)((*bn)->internal)) != MP_OKAY) {
  31608. WOLFSSL_MSG("mp_copy error");
  31609. if (dynamic == 1) {
  31610. wolfSSL_BN_free(*bn);
  31611. }
  31612. return WOLFSSL_FATAL_ERROR;
  31613. }
  31614. return WOLFSSL_SUCCESS;
  31615. }
  31616. static void InitwolfSSL_BigNum(WOLFSSL_BIGNUM* bn)
  31617. {
  31618. if (bn)
  31619. XMEMSET(bn, 0, sizeof(WOLFSSL_BIGNUM));
  31620. }
  31621. WOLFSSL_BIGNUM* wolfSSL_BN_new(void)
  31622. {
  31623. WOLFSSL_BIGNUM* external;
  31624. mp_int* mpi;
  31625. #ifdef WOLFSSL_DEBUG_OPENSSL
  31626. WOLFSSL_MSG("wolfSSL_BN_new");
  31627. #endif
  31628. #if !defined(USE_FAST_MATH) || defined(HAVE_WOLF_BIGINT)
  31629. mpi = (mp_int*) XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  31630. if (mpi == NULL) {
  31631. WOLFSSL_MSG("wolfSSL_BN_new malloc mpi failure");
  31632. return NULL;
  31633. }
  31634. #endif
  31635. external = (WOLFSSL_BIGNUM*) XMALLOC(sizeof(WOLFSSL_BIGNUM), NULL,
  31636. DYNAMIC_TYPE_BIGINT);
  31637. if (external == NULL) {
  31638. WOLFSSL_MSG("wolfSSL_BN_new malloc WOLFSSL_BIGNUM failure");
  31639. #if !defined(USE_FAST_MATH) || defined(HAVE_WOLF_BIGINT)
  31640. XFREE(mpi, NULL, DYNAMIC_TYPE_BIGINT);
  31641. #endif
  31642. return NULL;
  31643. }
  31644. #if defined(USE_FAST_MATH) && !defined(HAVE_WOLF_BIGINT)
  31645. mpi = &external->fp;
  31646. #endif
  31647. InitwolfSSL_BigNum(external);
  31648. if (mp_init(mpi) != MP_OKAY) {
  31649. wolfSSL_BN_free(external);
  31650. return NULL;
  31651. }
  31652. external->internal = mpi;
  31653. return external;
  31654. }
  31655. #if defined(USE_FAST_MATH) && !defined(HAVE_WOLF_BIGINT)
  31656. /* This function works without BN_free only with TFM */
  31657. void wolfSSL_BN_init(WOLFSSL_BIGNUM* bn)
  31658. {
  31659. if(bn == NULL)return;
  31660. #ifdef WOLFSSL_DEBUG_OPENSSL
  31661. WOLFSSL_MSG("wolfSSL_BN_init");
  31662. #endif
  31663. InitwolfSSL_BigNum(bn);
  31664. if (mp_init(&bn->fp) != MP_OKAY)
  31665. return;
  31666. bn->internal = (void *)&bn->fp;
  31667. }
  31668. #endif
  31669. void wolfSSL_BN_free(WOLFSSL_BIGNUM* bn)
  31670. {
  31671. #ifdef WOLFSSL_DEBUG_OPENSSL
  31672. WOLFSSL_MSG("wolfSSL_BN_free");
  31673. #endif
  31674. if (bn) {
  31675. if (bn->internal) {
  31676. mp_int* bni = (mp_int*)bn->internal;
  31677. mp_free(bni);
  31678. #if !defined(USE_FAST_MATH) || defined(HAVE_WOLF_BIGINT)
  31679. XFREE(bn->internal, NULL, DYNAMIC_TYPE_BIGINT);
  31680. #endif
  31681. bn->internal = NULL;
  31682. }
  31683. XFREE(bn, NULL, DYNAMIC_TYPE_BIGINT);
  31684. /* bn = NULL, don't try to access or double free it */
  31685. }
  31686. }
  31687. void wolfSSL_BN_clear_free(WOLFSSL_BIGNUM* bn)
  31688. {
  31689. #ifdef WOLFSSL_DEBUG_OPENSSL
  31690. WOLFSSL_MSG("wolfSSL_BN_clear_free");
  31691. #endif
  31692. if (bn) {
  31693. if (bn->internal) {
  31694. mp_int* bni = (mp_int*)bn->internal;
  31695. mp_forcezero(bni);
  31696. }
  31697. wolfSSL_BN_free(bn);
  31698. }
  31699. }
  31700. void wolfSSL_BN_clear(WOLFSSL_BIGNUM* bn)
  31701. {
  31702. #ifdef WOLFSSL_DEBUG_OPENSSL
  31703. WOLFSSL_MSG("wolfSSL_BN_clear");
  31704. #endif
  31705. if (bn && bn->internal) {
  31706. mp_forcezero((mp_int*)bn->internal);
  31707. }
  31708. }
  31709. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  31710. #ifdef OPENSSL_ALL
  31711. #if !defined(NO_BIO) && !defined(NO_PWDBASED) && defined(HAVE_PKCS8)
  31712. int wolfSSL_PEM_write_bio_PKCS8PrivateKey(WOLFSSL_BIO* bio,
  31713. WOLFSSL_EVP_PKEY* pkey,
  31714. const WOLFSSL_EVP_CIPHER* enc,
  31715. char* passwd, int passwdSz,
  31716. wc_pem_password_cb* cb, void* ctx)
  31717. {
  31718. int ret = 0;
  31719. char password[NAME_SZ];
  31720. byte* key = NULL;
  31721. word32 keySz;
  31722. byte* pem = NULL;
  31723. int pemSz;
  31724. int type = PKCS8_PRIVATEKEY_TYPE;
  31725. int algId;
  31726. const byte* curveOid;
  31727. word32 oidSz;
  31728. int encAlgId = 0;
  31729. if (bio == NULL || pkey == NULL)
  31730. return -1;
  31731. keySz = pkey->pkey_sz + 128;
  31732. key = (byte*)XMALLOC(keySz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31733. if (key == NULL)
  31734. ret = MEMORY_E;
  31735. if (ret == 0 && enc != NULL && passwd == NULL) {
  31736. passwdSz = cb(password, sizeof(password), 1, ctx);
  31737. if (passwdSz < 0)
  31738. ret = WOLFSSL_FAILURE;
  31739. passwd = password;
  31740. }
  31741. if (ret == 0 && enc != NULL) {
  31742. WC_RNG rng;
  31743. ret = wc_InitRng(&rng);
  31744. if (ret == 0) {
  31745. #ifndef NO_DES3
  31746. if (enc == EVP_DES_CBC)
  31747. encAlgId = DESb;
  31748. else if (enc == EVP_DES_EDE3_CBC)
  31749. encAlgId = DES3b;
  31750. else
  31751. #endif
  31752. #if !defined(NO_AES) && defined(HAVE_AES_CBC)
  31753. #ifdef WOLFSSL_AES_256
  31754. if (enc == EVP_AES_256_CBC)
  31755. encAlgId = AES256CBCb;
  31756. else
  31757. #endif
  31758. #endif
  31759. ret = -1;
  31760. if (ret == 0) {
  31761. ret = TraditionalEnc((byte*)pkey->pkey.ptr, pkey->pkey_sz, key,
  31762. &keySz, passwd, passwdSz, PKCS5, PBES2,
  31763. encAlgId, NULL, 0, WC_PKCS12_ITT_DEFAULT,
  31764. &rng, NULL);
  31765. if (ret > 0) {
  31766. keySz = ret;
  31767. ret = 0;
  31768. }
  31769. }
  31770. wc_FreeRng(&rng);
  31771. }
  31772. type = PKCS8_ENC_PRIVATEKEY_TYPE;
  31773. }
  31774. if (ret == 0 && enc == NULL) {
  31775. type = PKCS8_PRIVATEKEY_TYPE;
  31776. #ifdef HAVE_ECC
  31777. if (pkey->type == EVP_PKEY_EC) {
  31778. algId = ECDSAk;
  31779. ret = wc_ecc_get_oid(pkey->ecc->group->curve_oid, &curveOid,
  31780. &oidSz);
  31781. }
  31782. else
  31783. #endif
  31784. {
  31785. algId = RSAk;
  31786. curveOid = NULL;
  31787. oidSz = 0;
  31788. }
  31789. #ifdef HAVE_ECC
  31790. if (ret >= 0)
  31791. #endif
  31792. {
  31793. ret = wc_CreatePKCS8Key(key, &keySz, (byte*)pkey->pkey.ptr,
  31794. pkey->pkey_sz, algId, curveOid, oidSz);
  31795. keySz = ret;
  31796. }
  31797. }
  31798. if (password == passwd)
  31799. XMEMSET(password, 0, passwdSz);
  31800. if (ret >= 0) {
  31801. pemSz = 2 * keySz + 2 * 64;
  31802. pem = (byte*)XMALLOC(pemSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31803. if (pem == NULL)
  31804. ret = MEMORY_E;
  31805. }
  31806. if (ret >= 0)
  31807. ret = wc_DerToPemEx(key, keySz, pem, pemSz, NULL, type);
  31808. if (key != NULL)
  31809. XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31810. if (ret >= 0) {
  31811. if (wolfSSL_BIO_write(bio, pem, ret) != ret)
  31812. ret = -1;
  31813. }
  31814. if (pem != NULL)
  31815. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31816. return ret < 0 ? 0 : ret;
  31817. }
  31818. #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM)
  31819. int wolfSSL_PEM_write_PKCS8PrivateKey(XFILE f, WOLFSSL_EVP_PKEY* pkey,
  31820. const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz,
  31821. wc_pem_password_cb* cb, void* ctx)
  31822. {
  31823. int ret = WOLFSSL_SUCCESS;
  31824. BIO *b;
  31825. WOLFSSL_ENTER("wolfSSL_PEM_write_PKCS8PrivateKey");
  31826. b = wolfSSL_BIO_new_fp(f, BIO_NOCLOSE);
  31827. if (b == NULL) {
  31828. ret = WOLFSSL_FAILURE;
  31829. }
  31830. if (ret == WOLFSSL_SUCCESS) {
  31831. ret = wolfSSL_PEM_write_bio_PKCS8PrivateKey(b, pkey, enc, passwd,
  31832. passwdSz, cb, ctx);
  31833. }
  31834. wolfSSL_BIO_free(b);
  31835. return ret;
  31836. }
  31837. #endif /* !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  31838. static int bio_get_data(WOLFSSL_BIO* bio, byte** data)
  31839. {
  31840. int ret = 0;
  31841. byte* mem = NULL;
  31842. #ifndef NO_FILESYSTEM
  31843. long memSz;
  31844. XFILE file;
  31845. long curr;
  31846. #endif
  31847. if ((ret = wolfSSL_BIO_pending(bio)) > 0) {
  31848. }
  31849. #ifndef NO_FILESYSTEM
  31850. else if (bio->type == WOLFSSL_BIO_FILE) {
  31851. if (wolfSSL_BIO_get_fp(bio, &file) != WOLFSSL_SUCCESS)
  31852. ret = BAD_FUNC_ARG;
  31853. if (ret == 0) {
  31854. curr = XFTELL(file);
  31855. if (curr < 0) {
  31856. ret = WOLFSSL_BAD_FILE;
  31857. }
  31858. if (XFSEEK(file, 0, XSEEK_END) != 0)
  31859. ret = WOLFSSL_BAD_FILE;
  31860. }
  31861. if (ret == 0) {
  31862. memSz = XFTELL(file);
  31863. if (memSz > MAX_WOLFSSL_FILE_SIZE || memSz < 0) {
  31864. ret = WOLFSSL_BAD_FILE;
  31865. }
  31866. }
  31867. if (ret == 0) {
  31868. memSz -= curr;
  31869. ret = (int)memSz;
  31870. if (XFSEEK(file, curr, SEEK_SET) != 0)
  31871. ret = WOLFSSL_BAD_FILE;
  31872. }
  31873. }
  31874. #endif
  31875. if (ret > 0) {
  31876. mem = (byte*)XMALLOC(ret, bio->heap, DYNAMIC_TYPE_OPENSSL);
  31877. if (mem == NULL) {
  31878. WOLFSSL_MSG("Memory error");
  31879. ret = MEMORY_E;
  31880. }
  31881. if (ret >= 0) {
  31882. if ((ret = wolfSSL_BIO_read(bio, mem, ret)) <= 0) {
  31883. XFREE(mem, bio->heap, DYNAMIC_TYPE_OPENSSL);
  31884. ret = MEMORY_E;
  31885. mem = NULL;
  31886. }
  31887. }
  31888. }
  31889. *data = mem;
  31890. return ret;
  31891. }
  31892. /* DER data is PKCS#8 encrypted. */
  31893. WOLFSSL_EVP_PKEY* wolfSSL_d2i_PKCS8PrivateKey_bio(WOLFSSL_BIO* bio,
  31894. WOLFSSL_EVP_PKEY** pkey,
  31895. wc_pem_password_cb* cb,
  31896. void* ctx)
  31897. {
  31898. int ret;
  31899. byte* der;
  31900. int len;
  31901. byte* p;
  31902. word32 algId;
  31903. WOLFSSL_EVP_PKEY* key;
  31904. if ((len = bio_get_data(bio, &der)) < 0)
  31905. return NULL;
  31906. if (cb != NULL) {
  31907. char password[NAME_SZ];
  31908. int passwordSz = cb(password, sizeof(password), PEM_PASS_READ, ctx);
  31909. if (passwordSz < 0) {
  31910. XFREE(der, bio->heap, DYNAMIC_TYPE_OPENSSL);
  31911. return NULL;
  31912. }
  31913. #ifdef WOLFSSL_CHECK_MEM_ZERO
  31914. wc_MemZero_Add("wolfSSL_d2i_PKCS8PrivateKey_bio password", password,
  31915. passwordSz);
  31916. #endif
  31917. ret = ToTraditionalEnc(der, len, password, passwordSz, &algId);
  31918. if (ret < 0) {
  31919. XFREE(der, bio->heap, DYNAMIC_TYPE_OPENSSL);
  31920. return NULL;
  31921. }
  31922. ForceZero(password, passwordSz);
  31923. #ifdef WOLFSSL_CHECK_MEM_ZERO
  31924. wc_MemZero_Check(password, passwordSz);
  31925. #endif
  31926. }
  31927. p = der;
  31928. key = wolfSSL_d2i_PrivateKey_EVP(pkey, &p, len);
  31929. XFREE(der, bio->heap, DYNAMIC_TYPE_OPENSSL);
  31930. return key;
  31931. }
  31932. #endif /* !NO_BIO && !NO_PWDBASED && HAVE_PKCS8 */
  31933. /* Detect which type of key it is before decoding. */
  31934. WOLFSSL_EVP_PKEY* wolfSSL_d2i_AutoPrivateKey(WOLFSSL_EVP_PKEY** pkey,
  31935. const unsigned char** pp,
  31936. long length)
  31937. {
  31938. int ret;
  31939. WOLFSSL_EVP_PKEY* key = NULL;
  31940. const byte* der = *pp;
  31941. word32 idx = 0;
  31942. int len = 0;
  31943. word32 end = 0;
  31944. int cnt = 0;
  31945. int type;
  31946. word32 algId;
  31947. word32 keyLen = (word32)length;
  31948. /* Take off PKCS#8 wrapper if found. */
  31949. if ((len = ToTraditionalInline_ex(der, &idx, keyLen, &algId)) >= 0) {
  31950. der += idx;
  31951. keyLen = len;
  31952. }
  31953. idx = 0;
  31954. len = 0;
  31955. /* Use the number of elements in the outer sequence to determine key type.
  31956. */
  31957. ret = GetSequence(der, &idx, &len, keyLen);
  31958. if (ret >= 0) {
  31959. end = idx + len;
  31960. while (ret >= 0 && idx < end) {
  31961. /* Skip type */
  31962. idx++;
  31963. /* Get length and skip over - keeping count */
  31964. len = 0;
  31965. ret = GetLength(der, &idx, &len, keyLen);
  31966. if (ret >= 0) {
  31967. if (idx + len > end)
  31968. ret = ASN_PARSE_E;
  31969. else {
  31970. idx += len;
  31971. cnt++;
  31972. }
  31973. }
  31974. }
  31975. }
  31976. if (ret >= 0) {
  31977. /* ECC includes version, private[, curve][, public key] */
  31978. if (cnt >= 2 && cnt <= 4)
  31979. type = EVP_PKEY_EC;
  31980. else
  31981. type = EVP_PKEY_RSA;
  31982. key = wolfSSL_d2i_PrivateKey(type, pkey, &der, keyLen);
  31983. *pp = der;
  31984. }
  31985. return key;
  31986. }
  31987. #endif /* OPENSSL_ALL */
  31988. #ifdef WOLFSSL_STATIC_EPHEMERAL
  31989. int wolfSSL_StaticEphemeralKeyLoad(WOLFSSL* ssl, int keyAlgo, void* keyPtr)
  31990. {
  31991. int ret;
  31992. word32 idx = 0;
  31993. DerBuffer* der = NULL;
  31994. if (ssl == NULL || ssl->ctx == NULL || keyPtr == NULL) {
  31995. return BAD_FUNC_ARG;
  31996. }
  31997. #ifndef SINGLE_THREADED
  31998. if (!ssl->ctx->staticKELockInit) {
  31999. return BUFFER_E; /* no keys set */
  32000. }
  32001. ret = wc_LockMutex(&ssl->ctx->staticKELock);
  32002. if (ret != 0) {
  32003. return ret;
  32004. }
  32005. #endif
  32006. ret = BUFFER_E; /* set default error */
  32007. switch (keyAlgo) {
  32008. #ifndef NO_DH
  32009. case WC_PK_TYPE_DH:
  32010. if (ssl != NULL)
  32011. der = ssl->staticKE.dhKey;
  32012. if (der == NULL)
  32013. der = ssl->ctx->staticKE.dhKey;
  32014. if (der != NULL) {
  32015. DhKey* key = (DhKey*)keyPtr;
  32016. WOLFSSL_MSG("Using static DH key");
  32017. ret = wc_DhKeyDecode(der->buffer, &idx, key, der->length);
  32018. }
  32019. break;
  32020. #endif
  32021. #ifdef HAVE_ECC
  32022. case WC_PK_TYPE_ECDH:
  32023. if (ssl != NULL)
  32024. der = ssl->staticKE.ecKey;
  32025. if (der == NULL)
  32026. der = ssl->ctx->staticKE.ecKey;
  32027. if (der != NULL) {
  32028. ecc_key* key = (ecc_key*)keyPtr;
  32029. WOLFSSL_MSG("Using static ECDH key");
  32030. ret = wc_EccPrivateKeyDecode(der->buffer, &idx, key, der->length);
  32031. }
  32032. break;
  32033. #endif
  32034. #ifdef HAVE_CURVE25519
  32035. case WC_PK_TYPE_CURVE25519:
  32036. if (ssl != NULL)
  32037. der = ssl->staticKE.x25519Key;
  32038. if (der == NULL)
  32039. der = ssl->ctx->staticKE.x25519Key;
  32040. if (der != NULL) {
  32041. curve25519_key* key = (curve25519_key*)keyPtr;
  32042. WOLFSSL_MSG("Using static X25519 key");
  32043. ret = wc_Curve25519PrivateKeyDecode(der->buffer, &idx, key,
  32044. der->length);
  32045. }
  32046. break;
  32047. #endif
  32048. #ifdef HAVE_CURVE448
  32049. case WC_PK_TYPE_CURVE448:
  32050. if (ssl != NULL)
  32051. der = ssl->staticKE.x448Key;
  32052. if (der == NULL)
  32053. der = ssl->ctx->staticKE.x448Key;
  32054. if (der != NULL) {
  32055. curve448_key* key = (curve448_key*)keyPtr;
  32056. WOLFSSL_MSG("Using static X448 key");
  32057. ret = wc_Curve448PrivateKeyDecode(der->buffer, &idx, key,
  32058. der->length);
  32059. }
  32060. break;
  32061. #endif
  32062. default:
  32063. /* not supported */
  32064. ret = NOT_COMPILED_IN;
  32065. break;
  32066. }
  32067. #ifndef SINGLE_THREADED
  32068. wc_UnLockMutex(&ssl->ctx->staticKELock);
  32069. #endif
  32070. return ret;
  32071. }
  32072. static int SetStaticEphemeralKey(WOLFSSL_CTX* ctx,
  32073. StaticKeyExchangeInfo_t* staticKE, int keyAlgo, const char* key,
  32074. unsigned int keySz, int format, void* heap)
  32075. {
  32076. int ret = 0;
  32077. DerBuffer* der = NULL;
  32078. byte* keyBuf = NULL;
  32079. #ifndef NO_FILESYSTEM
  32080. const char* keyFile = NULL;
  32081. #endif
  32082. /* allow empty key to free buffer */
  32083. if (staticKE == NULL || (key == NULL && keySz > 0)) {
  32084. return BAD_FUNC_ARG;
  32085. }
  32086. WOLFSSL_ENTER("SetStaticEphemeralKey");
  32087. /* if just free'ing key then skip loading */
  32088. if (key != NULL) {
  32089. #ifndef NO_FILESYSTEM
  32090. /* load file from filesystem */
  32091. if (key != NULL && keySz == 0) {
  32092. size_t keyBufSz = 0;
  32093. keyFile = (const char*)key;
  32094. ret = wc_FileLoad(keyFile, &keyBuf, &keyBufSz, heap);
  32095. if (ret != 0) {
  32096. return ret;
  32097. }
  32098. keySz = (unsigned int)keyBufSz;
  32099. }
  32100. else
  32101. #endif
  32102. {
  32103. /* use as key buffer directly */
  32104. keyBuf = (byte*)key;
  32105. }
  32106. if (format == WOLFSSL_FILETYPE_PEM) {
  32107. #ifdef WOLFSSL_PEM_TO_DER
  32108. int keyFormat = 0;
  32109. ret = PemToDer(keyBuf, keySz, PRIVATEKEY_TYPE, &der,
  32110. heap, NULL, &keyFormat);
  32111. /* auto detect key type */
  32112. if (ret == 0 && keyAlgo == WC_PK_TYPE_NONE) {
  32113. if (keyFormat == ECDSAk)
  32114. keyAlgo = WC_PK_TYPE_ECDH;
  32115. else if (keyFormat == X25519k)
  32116. keyAlgo = WC_PK_TYPE_CURVE25519;
  32117. else
  32118. keyAlgo = WC_PK_TYPE_DH;
  32119. }
  32120. #else
  32121. ret = NOT_COMPILED_IN;
  32122. #endif
  32123. }
  32124. else {
  32125. /* Detect PK type (if required) */
  32126. #ifdef HAVE_ECC
  32127. if (keyAlgo == WC_PK_TYPE_NONE) {
  32128. word32 idx = 0;
  32129. ecc_key eccKey;
  32130. ret = wc_ecc_init_ex(&eccKey, heap, INVALID_DEVID);
  32131. if (ret == 0) {
  32132. ret = wc_EccPrivateKeyDecode(keyBuf, &idx, &eccKey, keySz);
  32133. if (ret == 0)
  32134. keyAlgo = WC_PK_TYPE_ECDH;
  32135. wc_ecc_free(&eccKey);
  32136. }
  32137. }
  32138. #endif
  32139. #if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)
  32140. if (keyAlgo == WC_PK_TYPE_NONE) {
  32141. word32 idx = 0;
  32142. DhKey dhKey;
  32143. ret = wc_InitDhKey_ex(&dhKey, heap, INVALID_DEVID);
  32144. if (ret == 0) {
  32145. ret = wc_DhKeyDecode(keyBuf, &idx, &dhKey, keySz);
  32146. if (ret == 0)
  32147. keyAlgo = WC_PK_TYPE_DH;
  32148. wc_FreeDhKey(&dhKey);
  32149. }
  32150. }
  32151. #endif
  32152. #ifdef HAVE_CURVE25519
  32153. if (keyAlgo == WC_PK_TYPE_NONE) {
  32154. word32 idx = 0;
  32155. curve25519_key x25519Key;
  32156. ret = wc_curve25519_init_ex(&x25519Key, heap, INVALID_DEVID);
  32157. if (ret == 0) {
  32158. ret = wc_Curve25519PrivateKeyDecode(keyBuf, &idx, &x25519Key,
  32159. keySz);
  32160. if (ret == 0)
  32161. keyAlgo = WC_PK_TYPE_CURVE25519;
  32162. wc_curve25519_free(&x25519Key);
  32163. }
  32164. }
  32165. #endif
  32166. #ifdef HAVE_CURVE448
  32167. if (keyAlgo == WC_PK_TYPE_NONE) {
  32168. word32 idx = 0;
  32169. curve448_key x448Key;
  32170. ret = wc_curve448_init(&x448Key);
  32171. if (ret == 0) {
  32172. ret = wc_Curve448PrivateKeyDecode(keyBuf, &idx, &x448Key,
  32173. keySz);
  32174. if (ret == 0)
  32175. keyAlgo = WC_PK_TYPE_CURVE448;
  32176. wc_curve448_free(&x448Key);
  32177. }
  32178. }
  32179. #endif
  32180. if (keyAlgo != WC_PK_TYPE_NONE) {
  32181. ret = AllocDer(&der, keySz, PRIVATEKEY_TYPE, heap);
  32182. if (ret == 0) {
  32183. XMEMCPY(der->buffer, keyBuf, keySz);
  32184. }
  32185. }
  32186. }
  32187. }
  32188. #ifndef NO_FILESYSTEM
  32189. /* done with keyFile buffer */
  32190. if (keyFile && keyBuf) {
  32191. XFREE(keyBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  32192. }
  32193. #endif
  32194. #ifndef SINGLE_THREADED
  32195. if (ret == 0 && !ctx->staticKELockInit) {
  32196. ret = wc_InitMutex(&ctx->staticKELock);
  32197. if (ret == 0) {
  32198. ctx->staticKELockInit = 1;
  32199. }
  32200. }
  32201. #endif
  32202. if (ret == 0
  32203. #ifndef SINGLE_THREADED
  32204. && (ret = wc_LockMutex(&ctx->staticKELock)) == 0
  32205. #endif
  32206. ) {
  32207. switch (keyAlgo) {
  32208. #ifndef NO_DH
  32209. case WC_PK_TYPE_DH:
  32210. FreeDer(&staticKE->dhKey);
  32211. staticKE->dhKey = der; der = NULL;
  32212. break;
  32213. #endif
  32214. #ifdef HAVE_ECC
  32215. case WC_PK_TYPE_ECDH:
  32216. FreeDer(&staticKE->ecKey);
  32217. staticKE->ecKey = der; der = NULL;
  32218. break;
  32219. #endif
  32220. #ifdef HAVE_CURVE25519
  32221. case WC_PK_TYPE_CURVE25519:
  32222. FreeDer(&staticKE->x25519Key);
  32223. staticKE->x25519Key = der; der = NULL;
  32224. break;
  32225. #endif
  32226. #ifdef HAVE_CURVE448
  32227. case WC_PK_TYPE_CURVE448:
  32228. FreeDer(&staticKE->x448Key);
  32229. staticKE->x448Key = der; der = NULL;
  32230. break;
  32231. #endif
  32232. default:
  32233. /* not supported */
  32234. ret = NOT_COMPILED_IN;
  32235. break;
  32236. }
  32237. #ifndef SINGLE_THREADED
  32238. wc_UnLockMutex(&ctx->staticKELock);
  32239. #endif
  32240. }
  32241. if (ret != 0) {
  32242. FreeDer(&der);
  32243. }
  32244. (void)ctx; /* not used for single threaded */
  32245. WOLFSSL_LEAVE("SetStaticEphemeralKey", ret);
  32246. return ret;
  32247. }
  32248. int wolfSSL_CTX_set_ephemeral_key(WOLFSSL_CTX* ctx, int keyAlgo,
  32249. const char* key, unsigned int keySz, int format)
  32250. {
  32251. if (ctx == NULL) {
  32252. return BAD_FUNC_ARG;
  32253. }
  32254. return SetStaticEphemeralKey(ctx, &ctx->staticKE, keyAlgo,
  32255. key, keySz, format, ctx->heap);
  32256. }
  32257. int wolfSSL_set_ephemeral_key(WOLFSSL* ssl, int keyAlgo,
  32258. const char* key, unsigned int keySz, int format)
  32259. {
  32260. if (ssl == NULL || ssl->ctx == NULL) {
  32261. return BAD_FUNC_ARG;
  32262. }
  32263. return SetStaticEphemeralKey(ssl->ctx, &ssl->staticKE, keyAlgo,
  32264. key, keySz, format, ssl->heap);
  32265. }
  32266. static int GetStaticEphemeralKey(WOLFSSL_CTX* ctx, WOLFSSL* ssl,
  32267. int keyAlgo, const unsigned char** key, unsigned int* keySz)
  32268. {
  32269. int ret = 0;
  32270. DerBuffer* der = NULL;
  32271. if (key) *key = NULL;
  32272. if (keySz) *keySz = 0;
  32273. #ifndef SINGLE_THREADED
  32274. if (ctx->staticKELockInit &&
  32275. (ret = wc_LockMutex(&ctx->staticKELock)) != 0) {
  32276. return ret;
  32277. }
  32278. #endif
  32279. switch (keyAlgo) {
  32280. #ifndef NO_DH
  32281. case WC_PK_TYPE_DH:
  32282. if (ssl != NULL)
  32283. der = ssl->staticKE.dhKey;
  32284. if (der == NULL)
  32285. der = ctx->staticKE.dhKey;
  32286. break;
  32287. #endif
  32288. #ifdef HAVE_ECC
  32289. case WC_PK_TYPE_ECDH:
  32290. if (ssl != NULL)
  32291. der = ssl->staticKE.ecKey;
  32292. if (der == NULL)
  32293. der = ctx->staticKE.ecKey;
  32294. break;
  32295. #endif
  32296. #ifdef HAVE_CURVE25519
  32297. case WC_PK_TYPE_CURVE25519:
  32298. if (ssl != NULL)
  32299. der = ssl->staticKE.x25519Key;
  32300. if (der == NULL)
  32301. der = ctx->staticKE.x25519Key;
  32302. break;
  32303. #endif
  32304. #ifdef HAVE_CURVE448
  32305. case WC_PK_TYPE_CURVE448:
  32306. if (ssl != NULL)
  32307. der = ssl->staticKE.x448Key;
  32308. if (der == NULL)
  32309. der = ctx->staticKE.x448Key;
  32310. break;
  32311. #endif
  32312. default:
  32313. /* not supported */
  32314. ret = NOT_COMPILED_IN;
  32315. break;
  32316. }
  32317. if (der) {
  32318. if (key)
  32319. *key = der->buffer;
  32320. if (keySz)
  32321. *keySz = der->length;
  32322. }
  32323. #ifndef SINGLE_THREADED
  32324. wc_UnLockMutex(&ctx->staticKELock);
  32325. #endif
  32326. return ret;
  32327. }
  32328. /* returns pointer to currently loaded static ephemeral as ASN.1 */
  32329. /* this can be converted to PEM using wc_DerToPem */
  32330. int wolfSSL_CTX_get_ephemeral_key(WOLFSSL_CTX* ctx, int keyAlgo,
  32331. const unsigned char** key, unsigned int* keySz)
  32332. {
  32333. if (ctx == NULL) {
  32334. return BAD_FUNC_ARG;
  32335. }
  32336. return GetStaticEphemeralKey(ctx, NULL, keyAlgo, key, keySz);
  32337. }
  32338. int wolfSSL_get_ephemeral_key(WOLFSSL* ssl, int keyAlgo,
  32339. const unsigned char** key, unsigned int* keySz)
  32340. {
  32341. if (ssl == NULL || ssl->ctx == NULL) {
  32342. return BAD_FUNC_ARG;
  32343. }
  32344. return GetStaticEphemeralKey(ssl->ctx, ssl, keyAlgo, key, keySz);
  32345. }
  32346. #endif /* WOLFSSL_STATIC_EPHEMERAL */
  32347. #if defined(OPENSSL_EXTRA)
  32348. /* wolfSSL_THREADID_current is provided as a compat API with
  32349. * CRYPTO_THREADID_current to register current thread id into given id object.
  32350. * However, CRYPTO_THREADID_current API has been deprecated and no longer
  32351. * exists in the OpenSSL 1.0.0 or later.This API only works as a stub
  32352. * like as existing wolfSSL_THREADID_set_numeric.
  32353. */
  32354. void wolfSSL_THREADID_current(WOLFSSL_CRYPTO_THREADID* id)
  32355. {
  32356. (void)id;
  32357. return;
  32358. }
  32359. /* wolfSSL_THREADID_hash is provided as a compatible API with
  32360. * CRYPTO_THREADID_hash which returns a hash value calcurated from the
  32361. * specified thread id. However, CRYPTO_THREADID_hash API has been
  32362. * deprecated and no longer exists in the OpenSSL 1.0.0 or later.
  32363. * This API only works as a stub to returns 0. This behavior is
  32364. * equivalent to the latest OpenSSL CRYPTO_THREADID_hash.
  32365. */
  32366. unsigned long wolfSSL_THREADID_hash(const WOLFSSL_CRYPTO_THREADID* id)
  32367. {
  32368. (void)id;
  32369. return 0UL;
  32370. }
  32371. /* wolfSSL_CTX_set_ecdh_auto is provided as compatible API with
  32372. * SSL_CTX_set_ecdh_auto to enable auto ecdh curve selection functionality.
  32373. * Since this functionality is enabled by default in wolfSSL,
  32374. * this API exists as a stub.
  32375. */
  32376. int wolfSSL_CTX_set_ecdh_auto(WOLFSSL_CTX* ctx, int onoff)
  32377. {
  32378. (void)ctx;
  32379. (void)onoff;
  32380. return WOLFSSL_SUCCESS;
  32381. }
  32382. /**
  32383. * set security level (wolfSSL doesn't support security level)
  32384. * @param ctx a pointer to WOLFSSL_EVP_PKEY_CTX structure
  32385. * @param level security level
  32386. */
  32387. void wolfSSL_CTX_set_security_level(WOLFSSL_CTX* ctx, int level)
  32388. {
  32389. WOLFSSL_ENTER("wolfSSL_CTX_set_security_level");
  32390. (void)ctx;
  32391. (void)level;
  32392. }
  32393. /**
  32394. * get security level (wolfSSL doesn't support security level)
  32395. * @param ctx a pointer to WOLFSSL_EVP_PKEY_CTX structure
  32396. * @return always 0(level 0)
  32397. */
  32398. int wolfSSL_CTX_get_security_level(const WOLFSSL_CTX* ctx)
  32399. {
  32400. WOLFSSL_ENTER("wolfSSL_CTX_get_security_level");
  32401. (void)ctx;
  32402. return 0;
  32403. }
  32404. /**
  32405. * Determine whether a WOLFSSL_SESSION object can be used for resumption
  32406. * @param s a pointer to WOLFSSL_SESSION structure
  32407. * @return return 1 if session is resumable, otherwise 0.
  32408. */
  32409. int wolfSSL_SESSION_is_resumable(const WOLFSSL_SESSION *s)
  32410. {
  32411. s = ClientSessionToSession(s);
  32412. if (s == NULL)
  32413. return 0;
  32414. #ifdef HAVE_SESSION_TICKET
  32415. if (s->ticketLen > 0)
  32416. return 1;
  32417. #endif
  32418. if (s->sessionIDSz > 0)
  32419. return 1;
  32420. return 0;
  32421. }
  32422. #if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK)
  32423. /*
  32424. * This API accepts a user callback which puts key-log records into
  32425. * a KEY LOGFILE. The callback is stored into a CTX and propagated to
  32426. * each SSL object on its creation timing.
  32427. */
  32428. void wolfSSL_CTX_set_keylog_callback(WOLFSSL_CTX* ctx, wolfSSL_CTX_keylog_cb_func cb)
  32429. {
  32430. WOLFSSL_ENTER("wolfSSL_CTX_set_keylog_callback");
  32431. /* stores the callback into WOLFSSL_CTX */
  32432. if (ctx != NULL) {
  32433. ctx->keyLogCb = cb;
  32434. }
  32435. }
  32436. wolfSSL_CTX_keylog_cb_func wolfSSL_CTX_get_keylog_callback(
  32437. const WOLFSSL_CTX* ctx)
  32438. {
  32439. WOLFSSL_ENTER("wolfSSL_CTX_get_keylog_callback");
  32440. if (ctx != NULL)
  32441. return ctx->keyLogCb;
  32442. else
  32443. return NULL;
  32444. }
  32445. #endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */
  32446. #endif /* OPENSSL_EXTRA */
  32447. #ifndef NO_CERT
  32448. #define WOLFSSL_X509_INCLUDED
  32449. #include "src/x509.c"
  32450. #endif
  32451. /*******************************************************************************
  32452. * START OF standard C library wrapping APIs
  32453. ******************************************************************************/
  32454. #if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && (defined(HAVE_STUNNEL) || \
  32455. defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY) || \
  32456. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_OPENSSH)))
  32457. #ifndef NO_WOLFSSL_STUB
  32458. int wolfSSL_CRYPTO_set_mem_ex_functions(void *(*m) (size_t, const char *, int),
  32459. void *(*r) (void *, size_t, const char *,
  32460. int), void (*f) (void *))
  32461. {
  32462. (void) m;
  32463. (void) r;
  32464. (void) f;
  32465. WOLFSSL_ENTER("wolfSSL_CRYPTO_set_mem_ex_functions");
  32466. WOLFSSL_STUB("CRYPTO_set_mem_ex_functions");
  32467. return WOLFSSL_FAILURE;
  32468. }
  32469. #endif
  32470. #endif
  32471. #if defined(OPENSSL_EXTRA)
  32472. /**
  32473. * free allocated memory resouce
  32474. * @param str a pointer to resource to be freed
  32475. * @param file dummy argument
  32476. * @param line dummy argument
  32477. */
  32478. void wolfSSL_CRYPTO_free(void *str, const char *file, int line)
  32479. {
  32480. (void)file;
  32481. (void)line;
  32482. XFREE(str, 0, DYNAMIC_TYPE_TMP_BUFFER);
  32483. }
  32484. /**
  32485. * allocate memory with size of num
  32486. * @param num size of memory allocation to be malloced
  32487. * @param file dummy argument
  32488. * @param line dummy argument
  32489. * @return a pointer to allocated memory on succssesful, otherwise NULL
  32490. */
  32491. void *wolfSSL_CRYPTO_malloc(size_t num, const char *file, int line)
  32492. {
  32493. (void)file;
  32494. (void)line;
  32495. return XMALLOC(num, 0, DYNAMIC_TYPE_TMP_BUFFER);
  32496. }
  32497. #endif
  32498. /*******************************************************************************
  32499. * END OF standard C library wrapping APIs
  32500. ******************************************************************************/
  32501. /*******************************************************************************
  32502. * START OF EX_DATA APIs
  32503. ******************************************************************************/
  32504. #if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && (defined(HAVE_STUNNEL) || \
  32505. defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY) || \
  32506. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_OPENSSH)))
  32507. void wolfSSL_CRYPTO_cleanup_all_ex_data(void){
  32508. WOLFSSL_ENTER("CRYPTO_cleanup_all_ex_data");
  32509. }
  32510. #endif
  32511. #ifdef HAVE_EX_DATA
  32512. void* wolfSSL_CRYPTO_get_ex_data(const WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx)
  32513. {
  32514. WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data");
  32515. #ifdef MAX_EX_DATA
  32516. if(ex_data && idx < MAX_EX_DATA && idx >= 0) {
  32517. return ex_data->ex_data[idx];
  32518. }
  32519. #else
  32520. (void)ex_data;
  32521. (void)idx;
  32522. #endif
  32523. return NULL;
  32524. }
  32525. int wolfSSL_CRYPTO_set_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx, void *data)
  32526. {
  32527. WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data");
  32528. #ifdef MAX_EX_DATA
  32529. if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
  32530. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  32531. if (ex_data->ex_data_cleanup_routines[idx]) {
  32532. if (ex_data->ex_data[idx])
  32533. ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
  32534. ex_data->ex_data_cleanup_routines[idx] = NULL;
  32535. }
  32536. #endif
  32537. ex_data->ex_data[idx] = data;
  32538. return WOLFSSL_SUCCESS;
  32539. }
  32540. #else
  32541. (void)ex_data;
  32542. (void)idx;
  32543. (void)data;
  32544. #endif
  32545. return WOLFSSL_FAILURE;
  32546. }
  32547. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  32548. int wolfSSL_CRYPTO_set_ex_data_with_cleanup(
  32549. WOLFSSL_CRYPTO_EX_DATA* ex_data,
  32550. int idx,
  32551. void *data,
  32552. wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
  32553. {
  32554. WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data_with_cleanup");
  32555. if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
  32556. if (ex_data->ex_data_cleanup_routines[idx] && ex_data->ex_data[idx])
  32557. ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
  32558. ex_data->ex_data[idx] = data;
  32559. ex_data->ex_data_cleanup_routines[idx] = cleanup_routine;
  32560. return WOLFSSL_SUCCESS;
  32561. }
  32562. return WOLFSSL_FAILURE;
  32563. }
  32564. #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
  32565. /**
  32566. * Issues unique index for the class specified by class_index.
  32567. * Other parameter except class_index are ignored.
  32568. * Currently, following class_index are accepted:
  32569. * - WOLF_CRYPTO_EX_INDEX_SSL
  32570. * - WOLF_CRYPTO_EX_INDEX_SSL_CTX
  32571. * - WOLF_CRYPTO_EX_INDEX_X509
  32572. * @param class_index index one of CRYPTO_EX_INDEX_xxx
  32573. * @param argp parameters to be saved
  32574. * @param argl parameters to be saved
  32575. * @param new_func a pointer to WOLFSSL_CRYPTO_EX_new
  32576. * @param dup_func a pointer to WOLFSSL_CRYPTO_EX_dup
  32577. * @param free_func a pointer to WOLFSSL_CRYPTO_EX_free
  32578. * @return index value grater or equal to zero on success, -1 on failure.
  32579. */
  32580. int wolfSSL_CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
  32581. WOLFSSL_CRYPTO_EX_new* new_func,
  32582. WOLFSSL_CRYPTO_EX_dup* dup_func,
  32583. WOLFSSL_CRYPTO_EX_free* free_func)
  32584. {
  32585. WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_new_index");
  32586. WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(argl, argp, new_func, dup_func,
  32587. free_func);
  32588. return wolfssl_get_ex_new_index(class_index);
  32589. }
  32590. #endif /* HAVE_EX_DATA */
  32591. /*******************************************************************************
  32592. * END OF EX_DATA APIs
  32593. ******************************************************************************/
  32594. /*******************************************************************************
  32595. * START OF BUF_MEM API
  32596. ******************************************************************************/
  32597. #if defined(OPENSSL_EXTRA)
  32598. /* Begin functions for openssl/buffer.h */
  32599. WOLFSSL_BUF_MEM* wolfSSL_BUF_MEM_new(void)
  32600. {
  32601. WOLFSSL_BUF_MEM* buf;
  32602. buf = (WOLFSSL_BUF_MEM*)XMALLOC(sizeof(WOLFSSL_BUF_MEM), NULL,
  32603. DYNAMIC_TYPE_OPENSSL);
  32604. if (buf) {
  32605. XMEMSET(buf, 0, sizeof(WOLFSSL_BUF_MEM));
  32606. }
  32607. return buf;
  32608. }
  32609. /* non-compat API returns length of buffer on success */
  32610. int wolfSSL_BUF_MEM_grow_ex(WOLFSSL_BUF_MEM* buf, size_t len,
  32611. char zeroFill)
  32612. {
  32613. int len_int = (int)len;
  32614. int mx;
  32615. char* tmp;
  32616. /* verify provided arguments */
  32617. if (buf == NULL || len_int < 0) {
  32618. return 0; /* BAD_FUNC_ARG; */
  32619. }
  32620. /* check to see if fits in existing length */
  32621. if (buf->length > len) {
  32622. buf->length = len;
  32623. return len_int;
  32624. }
  32625. /* check to see if fits in max buffer */
  32626. if (buf->max >= len) {
  32627. if (buf->data != NULL && zeroFill) {
  32628. XMEMSET(&buf->data[buf->length], 0, len - buf->length);
  32629. }
  32630. buf->length = len;
  32631. return len_int;
  32632. }
  32633. /* expand size, to handle growth */
  32634. mx = (len_int + 3) / 3 * 4;
  32635. /* use realloc */
  32636. tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
  32637. if (tmp == NULL) {
  32638. return 0; /* ERR_R_MALLOC_FAILURE; */
  32639. }
  32640. buf->data = tmp;
  32641. buf->max = mx;
  32642. if (zeroFill)
  32643. XMEMSET(&buf->data[buf->length], 0, len - buf->length);
  32644. buf->length = len;
  32645. return len_int;
  32646. }
  32647. /* returns length of buffer on success */
  32648. int wolfSSL_BUF_MEM_grow(WOLFSSL_BUF_MEM* buf, size_t len)
  32649. {
  32650. return wolfSSL_BUF_MEM_grow_ex(buf, len, 1);
  32651. }
  32652. /* non-compat API returns length of buffer on success */
  32653. int wolfSSL_BUF_MEM_resize(WOLFSSL_BUF_MEM* buf, size_t len)
  32654. {
  32655. char* tmp;
  32656. int mx;
  32657. /* verify provided arguments */
  32658. if (buf == NULL || len == 0 || (int)len <= 0) {
  32659. return 0; /* BAD_FUNC_ARG; */
  32660. }
  32661. if (len == buf->length)
  32662. return (int)len;
  32663. if (len > buf->length)
  32664. return wolfSSL_BUF_MEM_grow_ex(buf, len, 0);
  32665. /* expand size, to handle growth */
  32666. mx = ((int)len + 3) / 3 * 4;
  32667. /* We want to shrink the internal buffer */
  32668. tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
  32669. if (tmp == NULL)
  32670. return 0;
  32671. buf->data = tmp;
  32672. buf->length = len;
  32673. buf->max = mx;
  32674. return (int)len;
  32675. }
  32676. void wolfSSL_BUF_MEM_free(WOLFSSL_BUF_MEM* buf)
  32677. {
  32678. if (buf) {
  32679. if (buf->data) {
  32680. XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
  32681. buf->data = NULL;
  32682. }
  32683. buf->max = 0;
  32684. buf->length = 0;
  32685. XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
  32686. }
  32687. }
  32688. /* End Functions for openssl/buffer.h */
  32689. #endif /* OPENSSL_EXTRA */
  32690. /*******************************************************************************
  32691. * END OF BUF_MEM API
  32692. ******************************************************************************/
  32693. #define WOLFSSL_CONF_INCLUDED
  32694. #include <src/conf.c>
  32695. /*******************************************************************************
  32696. * START OF RAND API
  32697. ******************************************************************************/
  32698. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB)
  32699. static int wolfSSL_RAND_InitMutex(void)
  32700. {
  32701. if (gRandMethodsInit == 0) {
  32702. if (wc_InitMutex(&gRandMethodMutex) != 0) {
  32703. WOLFSSL_MSG("Bad Init Mutex rand methods");
  32704. return BAD_MUTEX_E;
  32705. }
  32706. gRandMethodsInit = 1;
  32707. }
  32708. return 0;
  32709. }
  32710. #endif
  32711. #ifdef OPENSSL_EXTRA
  32712. /* Checks if the global RNG has been created. If not then one is created.
  32713. *
  32714. * Returns WOLFSSL_SUCCESS when no error is encountered.
  32715. */
  32716. int wolfSSL_RAND_Init(void)
  32717. {
  32718. int ret = WOLFSSL_FAILURE;
  32719. #ifdef HAVE_GLOBAL_RNG
  32720. if (wc_LockMutex(&globalRNGMutex) == 0) {
  32721. if (initGlobalRNG == 0) {
  32722. ret = wc_InitRng(&globalRNG);
  32723. if (ret == 0) {
  32724. initGlobalRNG = 1;
  32725. ret = WOLFSSL_SUCCESS;
  32726. }
  32727. }
  32728. wc_UnLockMutex(&globalRNGMutex);
  32729. }
  32730. #endif
  32731. return ret;
  32732. }
  32733. /* WOLFSSL_SUCCESS on ok */
  32734. int wolfSSL_RAND_seed(const void* seed, int len)
  32735. {
  32736. #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
  32737. if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
  32738. if (gRandMethods && gRandMethods->seed) {
  32739. int ret = gRandMethods->seed(seed, len);
  32740. wc_UnLockMutex(&gRandMethodMutex);
  32741. return ret;
  32742. }
  32743. wc_UnLockMutex(&gRandMethodMutex);
  32744. }
  32745. #else
  32746. (void)seed;
  32747. (void)len;
  32748. #endif
  32749. /* Make sure global shared RNG (globalRNG) is initialized */
  32750. return wolfSSL_RAND_Init();
  32751. }
  32752. /* Returns the path for reading seed data from.
  32753. * Uses the env variable $RANDFILE first if set, if not then used $HOME/.rnd
  32754. *
  32755. * Note uses stdlib by default unless XGETENV macro is overwritten
  32756. *
  32757. * fname buffer to hold path
  32758. * len length of fname buffer
  32759. *
  32760. * Returns a pointer to fname on success and NULL on failure
  32761. */
  32762. const char* wolfSSL_RAND_file_name(char* fname, unsigned long len)
  32763. {
  32764. #ifndef NO_FILESYSTEM
  32765. char* rt;
  32766. char ap[] = "/.rnd";
  32767. WOLFSSL_ENTER("wolfSSL_RAND_file_name");
  32768. if (fname == NULL) {
  32769. return NULL;
  32770. }
  32771. XMEMSET(fname, 0, len);
  32772. /* if access to stdlib.h */
  32773. if ((rt = XGETENV("RANDFILE")) != NULL) {
  32774. if (len > XSTRLEN(rt)) {
  32775. XMEMCPY(fname, rt, XSTRLEN(rt));
  32776. }
  32777. else {
  32778. WOLFSSL_MSG("RANDFILE too large for buffer");
  32779. rt = NULL;
  32780. }
  32781. }
  32782. /* $RANDFILE was not set or is too large, check $HOME */
  32783. if (rt == NULL) {
  32784. WOLFSSL_MSG("Environment variable RANDFILE not set");
  32785. if ((rt = XGETENV("HOME")) == NULL) {
  32786. WOLFSSL_MSG("Environment variable HOME not set");
  32787. return NULL;
  32788. }
  32789. if (len > XSTRLEN(rt) + XSTRLEN(ap)) {
  32790. fname[0] = '\0';
  32791. XSTRNCAT(fname, rt, len);
  32792. XSTRNCAT(fname, ap, len - XSTRLEN(rt));
  32793. return fname;
  32794. }
  32795. else {
  32796. WOLFSSL_MSG("HOME too large for buffer");
  32797. return NULL;
  32798. }
  32799. }
  32800. return fname;
  32801. #else
  32802. /* no filesystem defined */
  32803. WOLFSSL_ENTER("wolfSSL_RAND_file_name");
  32804. WOLFSSL_MSG("No filesystem feature enabled, not compiled in");
  32805. (void)fname;
  32806. (void)len;
  32807. return NULL;
  32808. #endif
  32809. }
  32810. /* Writes 1024 bytes from the RNG to the given file name.
  32811. *
  32812. * fname name of file to write to
  32813. *
  32814. * Returns the number of bytes written
  32815. */
  32816. int wolfSSL_RAND_write_file(const char* fname)
  32817. {
  32818. int bytes = 0;
  32819. WOLFSSL_ENTER("RAND_write_file");
  32820. if (fname == NULL) {
  32821. return SSL_FAILURE;
  32822. }
  32823. #ifndef NO_FILESYSTEM
  32824. {
  32825. #ifndef WOLFSSL_SMALL_STACK
  32826. unsigned char buf[1024];
  32827. #else
  32828. unsigned char* buf = (unsigned char *)XMALLOC(1024, NULL,
  32829. DYNAMIC_TYPE_TMP_BUFFER);
  32830. if (buf == NULL) {
  32831. WOLFSSL_MSG("malloc failed");
  32832. return SSL_FAILURE;
  32833. }
  32834. #endif
  32835. bytes = 1024; /* default size of buf */
  32836. if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
  32837. WOLFSSL_MSG("No RNG to use");
  32838. #ifdef WOLFSSL_SMALL_STACK
  32839. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  32840. #endif
  32841. return 0;
  32842. }
  32843. if (wc_RNG_GenerateBlock(&globalRNG, buf, bytes) != 0) {
  32844. WOLFSSL_MSG("Error generating random buffer");
  32845. bytes = 0;
  32846. }
  32847. else {
  32848. XFILE f;
  32849. #ifdef WOLFSSL_CHECK_MEM_ZERO
  32850. wc_MemZero_Add("wolfSSL_RAND_write_file buf", buf, bytes);
  32851. #endif
  32852. f = XFOPEN(fname, "wb");
  32853. if (f == XBADFILE) {
  32854. WOLFSSL_MSG("Error opening the file");
  32855. bytes = 0;
  32856. }
  32857. else {
  32858. size_t bytes_written = XFWRITE(buf, 1, bytes, f);
  32859. bytes = (int)bytes_written;
  32860. XFCLOSE(f);
  32861. }
  32862. }
  32863. ForceZero(buf, bytes);
  32864. #ifdef WOLFSSL_SMALL_STACK
  32865. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  32866. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  32867. wc_MemZero_Check(buf, sizeof(buf));
  32868. #endif
  32869. }
  32870. #endif
  32871. return bytes;
  32872. }
  32873. #ifndef FREERTOS_TCP
  32874. /* These constant values are protocol values made by egd */
  32875. #if defined(USE_WOLFSSL_IO) && !defined(USE_WINDOWS_API) && !defined(HAVE_FIPS) && \
  32876. defined(HAVE_HASHDRBG) && !defined(NETOS) && defined(HAVE_SYS_UN_H)
  32877. #define WOLFSSL_EGD_NBLOCK 0x01
  32878. #include <sys/un.h>
  32879. #endif
  32880. /* This collects entropy from the path nm and seeds the global PRNG with it.
  32881. *
  32882. * nm is the file path to the egd server
  32883. *
  32884. * Returns the number of bytes read.
  32885. */
  32886. int wolfSSL_RAND_egd(const char* nm)
  32887. {
  32888. #ifdef WOLFSSL_EGD_NBLOCK
  32889. struct sockaddr_un rem;
  32890. int fd;
  32891. int ret = WOLFSSL_SUCCESS;
  32892. word32 bytes = 0;
  32893. word32 idx = 0;
  32894. #ifndef WOLFSSL_SMALL_STACK
  32895. unsigned char buf[256];
  32896. #else
  32897. unsigned char* buf;
  32898. buf = (unsigned char*)XMALLOC(256, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  32899. if (buf == NULL) {
  32900. WOLFSSL_MSG("Not enough memory");
  32901. return WOLFSSL_FATAL_ERROR;
  32902. }
  32903. #endif
  32904. XMEMSET(&rem, 0, sizeof(struct sockaddr_un));
  32905. if (nm == NULL) {
  32906. #ifdef WOLFSSL_SMALL_STACK
  32907. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  32908. #endif
  32909. return WOLFSSL_FATAL_ERROR;
  32910. }
  32911. fd = socket(AF_UNIX, SOCK_STREAM, 0);
  32912. if (fd < 0) {
  32913. WOLFSSL_MSG("Error creating socket");
  32914. #ifdef WOLFSSL_SMALL_STACK
  32915. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  32916. #endif
  32917. return WOLFSSL_FATAL_ERROR;
  32918. }
  32919. rem.sun_family = AF_UNIX;
  32920. XSTRNCPY(rem.sun_path, nm, sizeof(rem.sun_path) - 1);
  32921. rem.sun_path[sizeof(rem.sun_path)-1] = '\0';
  32922. /* connect to egd server */
  32923. if (connect(fd, (struct sockaddr*)&rem, sizeof(struct sockaddr_un)) == -1) {
  32924. WOLFSSL_MSG("error connecting to egd server");
  32925. ret = WOLFSSL_FATAL_ERROR;
  32926. }
  32927. #ifdef WOLFSSL_CHECK_MEM_ZERO
  32928. if (ret == WOLFSSL_SUCCESS) {
  32929. wc_MemZero_Add("wolfSSL_RAND_egd buf", buf, 256);
  32930. }
  32931. #endif
  32932. while (ret == WOLFSSL_SUCCESS && bytes < 255 && idx + 2 < 256) {
  32933. buf[idx] = WOLFSSL_EGD_NBLOCK;
  32934. buf[idx + 1] = 255 - bytes; /* request 255 bytes from server */
  32935. ret = (int)write(fd, buf + idx, 2);
  32936. if (ret != 2) {
  32937. if (errno == EAGAIN) {
  32938. ret = WOLFSSL_SUCCESS;
  32939. continue;
  32940. }
  32941. WOLFSSL_MSG("error requesting entropy from egd server");
  32942. ret = WOLFSSL_FATAL_ERROR;
  32943. break;
  32944. }
  32945. /* attempting to read */
  32946. buf[idx] = 0;
  32947. ret = (int)read(fd, buf + idx, 256 - bytes);
  32948. if (ret == 0) {
  32949. WOLFSSL_MSG("error reading entropy from egd server");
  32950. ret = WOLFSSL_FATAL_ERROR;
  32951. break;
  32952. }
  32953. if (ret > 0 && buf[idx] > 0) {
  32954. bytes += buf[idx]; /* egd stores amount sent in first byte */
  32955. if (bytes + idx > 255 || buf[idx] > ret) {
  32956. WOLFSSL_MSG("Buffer error");
  32957. ret = WOLFSSL_FATAL_ERROR;
  32958. break;
  32959. }
  32960. XMEMMOVE(buf + idx, buf + idx + 1, buf[idx]);
  32961. idx = bytes;
  32962. ret = WOLFSSL_SUCCESS;
  32963. if (bytes >= 255) {
  32964. break;
  32965. }
  32966. }
  32967. else {
  32968. if (errno == EAGAIN || errno == EINTR) {
  32969. WOLFSSL_MSG("EGD would read");
  32970. ret = WOLFSSL_SUCCESS; /* try again */
  32971. }
  32972. else if (buf[idx] == 0) {
  32973. /* if egd returned 0 then there is no more entropy to be had.
  32974. Do not try more reads. */
  32975. ret = WOLFSSL_SUCCESS;
  32976. break;
  32977. }
  32978. else {
  32979. WOLFSSL_MSG("Error with read");
  32980. ret = WOLFSSL_FATAL_ERROR;
  32981. }
  32982. }
  32983. }
  32984. if (bytes > 0 && ret == WOLFSSL_SUCCESS) {
  32985. /* call to check global RNG is created */
  32986. if (wolfSSL_RAND_Init() != SSL_SUCCESS) {
  32987. WOLFSSL_MSG("Error with initializing global RNG structure");
  32988. ret = WOLFSSL_FATAL_ERROR;
  32989. }
  32990. else if (wc_RNG_DRBG_Reseed(&globalRNG, (const byte*) buf, bytes)
  32991. != 0) {
  32992. WOLFSSL_MSG("Error with reseeding DRBG structure");
  32993. ret = WOLFSSL_FATAL_ERROR;
  32994. }
  32995. #ifdef SHOW_SECRETS
  32996. else { /* print out entropy found only when no error occured */
  32997. word32 i;
  32998. printf("EGD Entropy = ");
  32999. for (i = 0; i < bytes; i++) {
  33000. printf("%02X", buf[i]);
  33001. }
  33002. printf("\n");
  33003. }
  33004. #endif
  33005. }
  33006. ForceZero(buf, bytes);
  33007. #ifdef WOLFSSL_SMALL_STACK
  33008. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  33009. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  33010. wc_MemZero_Check(buf, 256);
  33011. #endif
  33012. close(fd);
  33013. if (ret == WOLFSSL_SUCCESS) {
  33014. return bytes;
  33015. }
  33016. else {
  33017. return ret;
  33018. }
  33019. #else
  33020. WOLFSSL_MSG("Type of socket needed is not available");
  33021. WOLFSSL_MSG("\tor using mode where DRBG API is not available");
  33022. (void)nm;
  33023. return WOLFSSL_FATAL_ERROR;
  33024. #endif /* WOLFSSL_EGD_NBLOCK */
  33025. }
  33026. #endif /* !FREERTOS_TCP */
  33027. void wolfSSL_RAND_Cleanup(void)
  33028. {
  33029. #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
  33030. if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
  33031. if (gRandMethods && gRandMethods->cleanup)
  33032. gRandMethods->cleanup();
  33033. wc_UnLockMutex(&gRandMethodMutex);
  33034. }
  33035. if (wc_FreeMutex(&gRandMethodMutex) == 0)
  33036. gRandMethodsInit = 0;
  33037. #endif
  33038. #ifdef HAVE_GLOBAL_RNG
  33039. if (wc_LockMutex(&globalRNGMutex) == 0) {
  33040. if (initGlobalRNG) {
  33041. wc_FreeRng(&globalRNG);
  33042. initGlobalRNG = 0;
  33043. }
  33044. wc_UnLockMutex(&globalRNGMutex);
  33045. }
  33046. #endif
  33047. }
  33048. /* returns WOLFSSL_SUCCESS if the bytes generated are valid otherwise WOLFSSL_FAILURE */
  33049. int wolfSSL_RAND_pseudo_bytes(unsigned char* buf, int num)
  33050. {
  33051. int ret;
  33052. int hash;
  33053. byte secret[DRBG_SEED_LEN]; /* secret length arbitraily choosen */
  33054. #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
  33055. if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
  33056. if (gRandMethods && gRandMethods->pseudorand) {
  33057. ret = gRandMethods->pseudorand(buf, num);
  33058. wc_UnLockMutex(&gRandMethodMutex);
  33059. return ret;
  33060. }
  33061. wc_UnLockMutex(&gRandMethodMutex);
  33062. }
  33063. #endif
  33064. #ifdef WOLFSSL_HAVE_PRF
  33065. #ifndef NO_SHA256
  33066. hash = WC_SHA256;
  33067. #elif defined(WOLFSSL_SHA384)
  33068. hash = WC_SHA384;
  33069. #elif !defined(NO_SHA)
  33070. hash = WC_SHA;
  33071. #elif !defined(NO_MD5)
  33072. hash = WC_MD5;
  33073. #endif
  33074. /* get secret value from source of entropy */
  33075. ret = wolfSSL_RAND_bytes(secret, DRBG_SEED_LEN);
  33076. /* uses input buffer to seed for pseudo random number generation, each
  33077. * thread will potentially have different results this way */
  33078. if (ret == WOLFSSL_SUCCESS) {
  33079. PRIVATE_KEY_UNLOCK();
  33080. ret = wc_PRF(buf, num, secret, DRBG_SEED_LEN, (const byte*)buf, num,
  33081. hash, NULL, INVALID_DEVID);
  33082. PRIVATE_KEY_LOCK();
  33083. ret = (ret == 0) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE;
  33084. }
  33085. #else
  33086. /* fall back to just doing wolfSSL_RAND_bytes if PRF not avialbale */
  33087. ret = wolfSSL_RAND_bytes(buf, num);
  33088. (void)hash;
  33089. (void)secret;
  33090. #endif
  33091. return ret;
  33092. }
  33093. /* returns WOLFSSL_SUCCESS if the bytes generated are valid otherwise WOLFSSL_FAILURE */
  33094. int wolfSSL_RAND_bytes(unsigned char* buf, int num)
  33095. {
  33096. int ret = 0;
  33097. WC_RNG* rng = NULL;
  33098. #ifdef WOLFSSL_SMALL_STACK
  33099. WC_RNG* tmpRNG = NULL;
  33100. #else
  33101. WC_RNG tmpRNG[1];
  33102. #endif
  33103. int initTmpRng = 0;
  33104. int blockCount = 0;
  33105. #ifdef HAVE_GLOBAL_RNG
  33106. int used_global = 0;
  33107. #endif
  33108. WOLFSSL_ENTER("wolfSSL_RAND_bytes");
  33109. /* sanity check */
  33110. if (buf == NULL || num < 0)
  33111. /* return code compliant with OpenSSL */
  33112. return 0;
  33113. /* if a RAND callback has been set try and use it */
  33114. #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
  33115. if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
  33116. if (gRandMethods && gRandMethods->bytes) {
  33117. ret = gRandMethods->bytes(buf, num);
  33118. wc_UnLockMutex(&gRandMethodMutex);
  33119. return ret;
  33120. }
  33121. wc_UnLockMutex(&gRandMethodMutex);
  33122. }
  33123. #endif
  33124. #ifdef HAVE_GLOBAL_RNG
  33125. if (initGlobalRNG) {
  33126. if (wc_LockMutex(&globalRNGMutex) != 0) {
  33127. WOLFSSL_MSG("Bad Lock Mutex rng");
  33128. return ret;
  33129. }
  33130. rng = &globalRNG;
  33131. used_global = 1;
  33132. }
  33133. else
  33134. #endif
  33135. {
  33136. #ifdef WOLFSSL_SMALL_STACK
  33137. tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  33138. if (tmpRNG == NULL)
  33139. return ret;
  33140. #endif
  33141. if (wc_InitRng(tmpRNG) == 0) {
  33142. rng = tmpRNG;
  33143. initTmpRng = 1;
  33144. }
  33145. }
  33146. if (rng) {
  33147. /* handles size greater than RNG_MAX_BLOCK_LEN */
  33148. blockCount = num / RNG_MAX_BLOCK_LEN;
  33149. while (blockCount--) {
  33150. ret = wc_RNG_GenerateBlock(rng, buf, RNG_MAX_BLOCK_LEN);
  33151. if (ret != 0) {
  33152. WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
  33153. break;
  33154. }
  33155. num -= RNG_MAX_BLOCK_LEN;
  33156. buf += RNG_MAX_BLOCK_LEN;
  33157. }
  33158. if (ret == 0 && num)
  33159. ret = wc_RNG_GenerateBlock(rng, buf, num);
  33160. if (ret != 0)
  33161. WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
  33162. else
  33163. ret = WOLFSSL_SUCCESS;
  33164. }
  33165. #ifdef HAVE_GLOBAL_RNG
  33166. if (used_global == 1)
  33167. wc_UnLockMutex(&globalRNGMutex);
  33168. #endif
  33169. if (initTmpRng)
  33170. wc_FreeRng(tmpRNG);
  33171. #ifdef WOLFSSL_SMALL_STACK
  33172. if (tmpRNG)
  33173. XFREE(tmpRNG, NULL, DYNAMIC_TYPE_RNG);
  33174. #endif
  33175. return ret;
  33176. }
  33177. int wolfSSL_RAND_poll(void)
  33178. {
  33179. byte entropy[16];
  33180. int ret = 0;
  33181. word32 entropy_sz = 16;
  33182. WOLFSSL_ENTER("wolfSSL_RAND_poll");
  33183. if (initGlobalRNG == 0){
  33184. WOLFSSL_MSG("Global RNG no Init");
  33185. return WOLFSSL_FAILURE;
  33186. }
  33187. ret = wc_GenerateSeed(&globalRNG.seed, entropy, entropy_sz);
  33188. if (ret != 0){
  33189. WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
  33190. ret = WOLFSSL_FAILURE;
  33191. }else
  33192. ret = WOLFSSL_SUCCESS;
  33193. return ret;
  33194. }
  33195. /* If a valid struct is provided with function pointers, will override
  33196. RAND_seed, bytes, cleanup, add, pseudo_bytes and status. If a NULL
  33197. pointer is passed in, it will cancel any previous function overrides.
  33198. Returns WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE on failure. */
  33199. int wolfSSL_RAND_set_rand_method(const WOLFSSL_RAND_METHOD *methods)
  33200. {
  33201. #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
  33202. if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
  33203. gRandMethods = methods;
  33204. wc_UnLockMutex(&gRandMethodMutex);
  33205. return WOLFSSL_SUCCESS;
  33206. }
  33207. #else
  33208. (void)methods;
  33209. #endif
  33210. return WOLFSSL_FAILURE;
  33211. }
  33212. /* Returns WOLFSSL_SUCCESS if the RNG has been seeded with enough data */
  33213. int wolfSSL_RAND_status(void)
  33214. {
  33215. int ret = WOLFSSL_SUCCESS;
  33216. #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
  33217. if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
  33218. if (gRandMethods && gRandMethods->status)
  33219. ret = gRandMethods->status();
  33220. wc_UnLockMutex(&gRandMethodMutex);
  33221. }
  33222. else {
  33223. ret = WOLFSSL_FAILURE;
  33224. }
  33225. #else
  33226. /* wolfCrypt provides enough seed internally, so return success */
  33227. #endif
  33228. return ret;
  33229. }
  33230. void wolfSSL_RAND_add(const void* add, int len, double entropy)
  33231. {
  33232. #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
  33233. if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
  33234. if (gRandMethods && gRandMethods->add) {
  33235. /* callback has return code, but RAND_add does not */
  33236. (void)gRandMethods->add(add, len, entropy);
  33237. }
  33238. wc_UnLockMutex(&gRandMethodMutex);
  33239. }
  33240. #else
  33241. /* wolfSSL seeds/adds internally, use explicit RNG if you want
  33242. to take control */
  33243. (void)add;
  33244. (void)len;
  33245. (void)entropy;
  33246. #endif
  33247. }
  33248. #endif /* OPENSSL_EXTRA */
  33249. /*******************************************************************************
  33250. * END OF RAND API
  33251. ******************************************************************************/
  33252. /*******************************************************************************
  33253. * START OF EVP_CIPHER API
  33254. ******************************************************************************/
  33255. #ifdef OPENSSL_EXTRA
  33256. /* store for external read of iv, WOLFSSL_SUCCESS on success */
  33257. int wolfSSL_StoreExternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
  33258. {
  33259. WOLFSSL_ENTER("wolfSSL_StoreExternalIV");
  33260. if (ctx == NULL) {
  33261. WOLFSSL_MSG("Bad function argument");
  33262. return WOLFSSL_FATAL_ERROR;
  33263. }
  33264. switch (ctx->cipherType) {
  33265. #ifndef NO_AES
  33266. #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
  33267. case AES_128_CBC_TYPE :
  33268. case AES_192_CBC_TYPE :
  33269. case AES_256_CBC_TYPE :
  33270. WOLFSSL_MSG("AES CBC");
  33271. XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, AES_BLOCK_SIZE);
  33272. break;
  33273. #endif
  33274. #ifdef HAVE_AESGCM
  33275. case AES_128_GCM_TYPE :
  33276. case AES_192_GCM_TYPE :
  33277. case AES_256_GCM_TYPE :
  33278. WOLFSSL_MSG("AES GCM");
  33279. XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, AES_BLOCK_SIZE);
  33280. break;
  33281. #endif /* HAVE_AESGCM */
  33282. #ifdef HAVE_AES_ECB
  33283. case AES_128_ECB_TYPE :
  33284. case AES_192_ECB_TYPE :
  33285. case AES_256_ECB_TYPE :
  33286. WOLFSSL_MSG("AES ECB");
  33287. break;
  33288. #endif
  33289. #ifdef WOLFSSL_AES_COUNTER
  33290. case AES_128_CTR_TYPE :
  33291. case AES_192_CTR_TYPE :
  33292. case AES_256_CTR_TYPE :
  33293. WOLFSSL_MSG("AES CTR");
  33294. XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, AES_BLOCK_SIZE);
  33295. break;
  33296. #endif /* WOLFSSL_AES_COUNTER */
  33297. #ifdef WOLFSSL_AES_CFB
  33298. #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS)
  33299. case AES_128_CFB1_TYPE:
  33300. case AES_192_CFB1_TYPE:
  33301. case AES_256_CFB1_TYPE:
  33302. WOLFSSL_MSG("AES CFB1");
  33303. break;
  33304. case AES_128_CFB8_TYPE:
  33305. case AES_192_CFB8_TYPE:
  33306. case AES_256_CFB8_TYPE:
  33307. WOLFSSL_MSG("AES CFB8");
  33308. break;
  33309. #endif /* !HAVE_SELFTEST && !HAVE_FIPS */
  33310. case AES_128_CFB128_TYPE:
  33311. case AES_192_CFB128_TYPE:
  33312. case AES_256_CFB128_TYPE:
  33313. WOLFSSL_MSG("AES CFB128");
  33314. break;
  33315. #endif /* WOLFSSL_AES_CFB */
  33316. #if defined(WOLFSSL_AES_OFB)
  33317. case AES_128_OFB_TYPE:
  33318. case AES_192_OFB_TYPE:
  33319. case AES_256_OFB_TYPE:
  33320. WOLFSSL_MSG("AES OFB");
  33321. break;
  33322. #endif /* WOLFSSL_AES_OFB */
  33323. #ifdef WOLFSSL_AES_XTS
  33324. case AES_128_XTS_TYPE:
  33325. case AES_256_XTS_TYPE:
  33326. WOLFSSL_MSG("AES XTS");
  33327. break;
  33328. #endif /* WOLFSSL_AES_XTS */
  33329. #endif /* NO_AES */
  33330. #ifndef NO_DES3
  33331. case DES_CBC_TYPE :
  33332. WOLFSSL_MSG("DES CBC");
  33333. XMEMCPY(ctx->iv, &ctx->cipher.des.reg, DES_BLOCK_SIZE);
  33334. break;
  33335. case DES_EDE3_CBC_TYPE :
  33336. WOLFSSL_MSG("DES EDE3 CBC");
  33337. XMEMCPY(ctx->iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
  33338. break;
  33339. #endif
  33340. #ifdef WOLFSSL_DES_ECB
  33341. case DES_ECB_TYPE :
  33342. WOLFSSL_MSG("DES ECB");
  33343. break;
  33344. case DES_EDE3_ECB_TYPE :
  33345. WOLFSSL_MSG("DES3 ECB");
  33346. break;
  33347. #endif
  33348. case ARC4_TYPE :
  33349. WOLFSSL_MSG("ARC4");
  33350. break;
  33351. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  33352. case CHACHA20_POLY1305_TYPE:
  33353. break;
  33354. #endif
  33355. case NULL_CIPHER_TYPE :
  33356. WOLFSSL_MSG("NULL");
  33357. break;
  33358. default: {
  33359. WOLFSSL_MSG("bad type");
  33360. return WOLFSSL_FATAL_ERROR;
  33361. }
  33362. }
  33363. return WOLFSSL_SUCCESS;
  33364. }
  33365. /* set internal IV from external, WOLFSSL_SUCCESS on success */
  33366. int wolfSSL_SetInternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
  33367. {
  33368. WOLFSSL_ENTER("wolfSSL_SetInternalIV");
  33369. if (ctx == NULL) {
  33370. WOLFSSL_MSG("Bad function argument");
  33371. return WOLFSSL_FATAL_ERROR;
  33372. }
  33373. switch (ctx->cipherType) {
  33374. #ifndef NO_AES
  33375. #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
  33376. case AES_128_CBC_TYPE :
  33377. case AES_192_CBC_TYPE :
  33378. case AES_256_CBC_TYPE :
  33379. WOLFSSL_MSG("AES CBC");
  33380. XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, AES_BLOCK_SIZE);
  33381. break;
  33382. #endif
  33383. #ifdef HAVE_AESGCM
  33384. case AES_128_GCM_TYPE :
  33385. case AES_192_GCM_TYPE :
  33386. case AES_256_GCM_TYPE :
  33387. WOLFSSL_MSG("AES GCM");
  33388. XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, AES_BLOCK_SIZE);
  33389. break;
  33390. #endif
  33391. #ifdef HAVE_AES_ECB
  33392. case AES_128_ECB_TYPE :
  33393. case AES_192_ECB_TYPE :
  33394. case AES_256_ECB_TYPE :
  33395. WOLFSSL_MSG("AES ECB");
  33396. break;
  33397. #endif
  33398. #ifdef WOLFSSL_AES_COUNTER
  33399. case AES_128_CTR_TYPE :
  33400. case AES_192_CTR_TYPE :
  33401. case AES_256_CTR_TYPE :
  33402. WOLFSSL_MSG("AES CTR");
  33403. XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, AES_BLOCK_SIZE);
  33404. break;
  33405. #endif
  33406. #endif /* NO_AES */
  33407. #ifndef NO_DES3
  33408. case DES_CBC_TYPE :
  33409. WOLFSSL_MSG("DES CBC");
  33410. XMEMCPY(&ctx->cipher.des.reg, ctx->iv, DES_BLOCK_SIZE);
  33411. break;
  33412. case DES_EDE3_CBC_TYPE :
  33413. WOLFSSL_MSG("DES EDE3 CBC");
  33414. XMEMCPY(&ctx->cipher.des3.reg, ctx->iv, DES_BLOCK_SIZE);
  33415. break;
  33416. #endif
  33417. #ifdef WOLFSSL_DES_ECB
  33418. case DES_ECB_TYPE :
  33419. WOLFSSL_MSG("DES ECB");
  33420. break;
  33421. case DES_EDE3_ECB_TYPE :
  33422. WOLFSSL_MSG("DES3 ECB");
  33423. break;
  33424. #endif
  33425. case ARC4_TYPE :
  33426. WOLFSSL_MSG("ARC4");
  33427. break;
  33428. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  33429. case CHACHA20_POLY1305_TYPE:
  33430. break;
  33431. #endif
  33432. case NULL_CIPHER_TYPE :
  33433. WOLFSSL_MSG("NULL");
  33434. break;
  33435. default: {
  33436. WOLFSSL_MSG("bad type");
  33437. return WOLFSSL_FATAL_ERROR;
  33438. }
  33439. }
  33440. return WOLFSSL_SUCCESS;
  33441. }
  33442. #ifndef NO_DES3
  33443. void wolfSSL_3des_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
  33444. unsigned char* iv, int len)
  33445. {
  33446. (void)len;
  33447. WOLFSSL_MSG("wolfSSL_3des_iv");
  33448. if (ctx == NULL || iv == NULL) {
  33449. WOLFSSL_MSG("Bad function argument");
  33450. return;
  33451. }
  33452. if (doset)
  33453. wc_Des3_SetIV(&ctx->cipher.des3, iv); /* OpenSSL compat, no ret */
  33454. else
  33455. XMEMCPY(iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
  33456. }
  33457. #endif /* NO_DES3 */
  33458. #ifndef NO_AES
  33459. void wolfSSL_aes_ctr_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
  33460. unsigned char* iv, int len)
  33461. {
  33462. (void)len;
  33463. WOLFSSL_MSG("wolfSSL_aes_ctr_iv");
  33464. if (ctx == NULL || iv == NULL) {
  33465. WOLFSSL_MSG("Bad function argument");
  33466. return;
  33467. }
  33468. if (doset)
  33469. (void)wc_AesSetIV(&ctx->cipher.aes, iv); /* OpenSSL compat, no ret */
  33470. else
  33471. XMEMCPY(iv, &ctx->cipher.aes.reg, AES_BLOCK_SIZE);
  33472. }
  33473. #endif /* NO_AES */
  33474. #endif /* OPENSSL_EXTRA */
  33475. /*******************************************************************************
  33476. * END OF EVP_CIPHER API
  33477. ******************************************************************************/
  33478. #ifndef NO_CERTS
  33479. #define WOLFSSL_X509_STORE_INCLUDED
  33480. #include <src/x509_str.c>
  33481. /*******************************************************************************
  33482. * START OF PKCS7 APIs
  33483. ******************************************************************************/
  33484. #ifdef HAVE_PKCS7
  33485. #ifdef OPENSSL_ALL
  33486. PKCS7* wolfSSL_PKCS7_new(void)
  33487. {
  33488. WOLFSSL_PKCS7* pkcs7;
  33489. int ret = 0;
  33490. pkcs7 = (WOLFSSL_PKCS7*)XMALLOC(sizeof(WOLFSSL_PKCS7), NULL,
  33491. DYNAMIC_TYPE_PKCS7);
  33492. if (pkcs7 != NULL) {
  33493. XMEMSET(pkcs7, 0, sizeof(WOLFSSL_PKCS7));
  33494. ret = wc_PKCS7_Init(&pkcs7->pkcs7, NULL, INVALID_DEVID);
  33495. }
  33496. if (ret != 0 && pkcs7 != NULL) {
  33497. XFREE(pkcs7, NULL, DYNAMIC_TYPE_PKCS7);
  33498. pkcs7 = NULL;
  33499. }
  33500. return (PKCS7*)pkcs7;
  33501. }
  33502. /******************************************************************************
  33503. * wolfSSL_PKCS7_SIGNED_new - allocates PKCS7 and initialize it for a signed data
  33504. *
  33505. * RETURNS:
  33506. * returns pointer to the PKCS7 structure on success, otherwise returns NULL
  33507. */
  33508. PKCS7_SIGNED* wolfSSL_PKCS7_SIGNED_new(void)
  33509. {
  33510. byte signedData[]= { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02};
  33511. PKCS7* pkcs7 = NULL;
  33512. if ((pkcs7 = wolfSSL_PKCS7_new()) == NULL)
  33513. return NULL;
  33514. pkcs7->contentOID = SIGNED_DATA;
  33515. if ((wc_PKCS7_SetContentType(pkcs7, signedData, sizeof(signedData))) < 0) {
  33516. if (pkcs7) {
  33517. wolfSSL_PKCS7_free(pkcs7);
  33518. return NULL;
  33519. }
  33520. }
  33521. return pkcs7;
  33522. }
  33523. void wolfSSL_PKCS7_free(PKCS7* pkcs7)
  33524. {
  33525. WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7;
  33526. if (p7 != NULL) {
  33527. if (p7->data != NULL)
  33528. XFREE(p7->data, NULL, DYNAMIC_TYPE_PKCS7);
  33529. wc_PKCS7_Free(&p7->pkcs7);
  33530. if (p7->certs)
  33531. wolfSSL_sk_pop_free(p7->certs, NULL);
  33532. XFREE(p7, NULL, DYNAMIC_TYPE_PKCS7);
  33533. }
  33534. }
  33535. void wolfSSL_PKCS7_SIGNED_free(PKCS7_SIGNED* p7)
  33536. {
  33537. wolfSSL_PKCS7_free(p7);
  33538. return;
  33539. }
  33540. /**
  33541. * Convert DER/ASN.1 encoded signedData structure to internal PKCS7
  33542. * structure. Note, does not support detached content.
  33543. *
  33544. * p7 - pointer to set to address of newly created PKCS7 structure on return
  33545. * in - pointer to pointer of DER/ASN.1 data
  33546. * len - length of input data, bytes
  33547. *
  33548. * Returns newly allocated and populated PKCS7 structure or NULL on error.
  33549. */
  33550. PKCS7* wolfSSL_d2i_PKCS7(PKCS7** p7, const unsigned char** in, int len)
  33551. {
  33552. return wolfSSL_d2i_PKCS7_ex(p7, in, len, NULL, 0);
  33553. }
  33554. /*****************************************************************************
  33555. * wolfSSL_d2i_PKCS7_ex - Converts the given unsigned char buffer of size len
  33556. * into a PKCS7 object. Optionally, accepts a byte buffer of content which
  33557. * is stored as the PKCS7 object's content, to support detached signatures.
  33558. * @param content The content which is signed, in case the signature is
  33559. * detached. Ignored if NULL.
  33560. * @param contentSz The size of the passed in content.
  33561. *
  33562. * RETURNS:
  33563. * returns pointer to a PKCS7 structure on success, otherwise returns NULL
  33564. */
  33565. PKCS7* wolfSSL_d2i_PKCS7_ex(PKCS7** p7, const unsigned char** in, int len,
  33566. byte* content, word32 contentSz)
  33567. {
  33568. WOLFSSL_PKCS7* pkcs7 = NULL;
  33569. WOLFSSL_ENTER("wolfSSL_d2i_PKCS7_ex");
  33570. if (in == NULL || *in == NULL || len < 0)
  33571. return NULL;
  33572. if ((pkcs7 = (WOLFSSL_PKCS7*)wolfSSL_PKCS7_new()) == NULL)
  33573. return NULL;
  33574. pkcs7->len = len;
  33575. pkcs7->data = (byte*)XMALLOC(pkcs7->len, NULL, DYNAMIC_TYPE_PKCS7);
  33576. if (pkcs7->data == NULL) {
  33577. wolfSSL_PKCS7_free((PKCS7*)pkcs7);
  33578. return NULL;
  33579. }
  33580. XMEMCPY(pkcs7->data, *in, pkcs7->len);
  33581. if (content != NULL) {
  33582. pkcs7->pkcs7.content = content;
  33583. pkcs7->pkcs7.contentSz = contentSz;
  33584. }
  33585. if (wc_PKCS7_VerifySignedData(&pkcs7->pkcs7, pkcs7->data, pkcs7->len)
  33586. != 0) {
  33587. WOLFSSL_MSG("wc_PKCS7_VerifySignedData failed");
  33588. wolfSSL_PKCS7_free((PKCS7*)pkcs7);
  33589. return NULL;
  33590. }
  33591. if (p7 != NULL)
  33592. *p7 = (PKCS7*)pkcs7;
  33593. *in += pkcs7->len;
  33594. return (PKCS7*)pkcs7;
  33595. }
  33596. /**
  33597. * This API was added as a helper function for libest. It
  33598. * extracts a stack of certificates from the pkcs7 object.
  33599. * @param pkcs7 PKCS7 parameter object
  33600. * @return WOLFSSL_STACK_OF(WOLFSSL_X509)*
  33601. */
  33602. WOLFSSL_STACK* wolfSSL_PKCS7_to_stack(PKCS7* pkcs7)
  33603. {
  33604. int i;
  33605. WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7;
  33606. WOLF_STACK_OF(WOLFSSL_X509)* ret = NULL;
  33607. WOLFSSL_ENTER("wolfSSL_PKCS7_to_stack");
  33608. if (!p7) {
  33609. WOLFSSL_MSG("Bad parameter");
  33610. return NULL;
  33611. }
  33612. if (p7->certs)
  33613. return p7->certs;
  33614. for (i = 0; i < MAX_PKCS7_CERTS && p7->pkcs7.cert[i]; i++) {
  33615. WOLFSSL_X509* x509 = wolfSSL_X509_d2i(NULL, p7->pkcs7.cert[i],
  33616. p7->pkcs7.certSz[i]);
  33617. if (!ret)
  33618. ret = wolfSSL_sk_X509_new();
  33619. if (x509) {
  33620. if (wolfSSL_sk_X509_push(ret, x509) != WOLFSSL_SUCCESS) {
  33621. wolfSSL_X509_free(x509);
  33622. WOLFSSL_MSG("wolfSSL_sk_X509_push error");
  33623. goto error;
  33624. }
  33625. }
  33626. else {
  33627. WOLFSSL_MSG("wolfSSL_X509_d2i error");
  33628. goto error;
  33629. }
  33630. }
  33631. /* Save stack to free later */
  33632. if (p7->certs)
  33633. wolfSSL_sk_pop_free(p7->certs, NULL);
  33634. p7->certs = ret;
  33635. return ret;
  33636. error:
  33637. if (ret) {
  33638. wolfSSL_sk_pop_free(ret, NULL);
  33639. }
  33640. return NULL;
  33641. }
  33642. /**
  33643. * Return stack of signers contained in PKCS7 cert.
  33644. * Notes:
  33645. * - Currently only PKCS#7 messages with a single signer cert is supported.
  33646. * - Returned WOLFSSL_STACK must be freed by caller.
  33647. *
  33648. * pkcs7 - PKCS7 struct to retrieve signer certs from.
  33649. * certs - currently unused
  33650. * flags - flags to control function behavior.
  33651. *
  33652. * Return WOLFSSL_STACK of signers on success, NULL on error.
  33653. */
  33654. WOLFSSL_STACK* wolfSSL_PKCS7_get0_signers(PKCS7* pkcs7, WOLFSSL_STACK* certs,
  33655. int flags)
  33656. {
  33657. WOLFSSL_X509* x509 = NULL;
  33658. WOLFSSL_STACK* signers = NULL;
  33659. WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7;
  33660. if (p7 == NULL)
  33661. return NULL;
  33662. /* Only PKCS#7 messages with a single cert that is the verifying certificate
  33663. * is supported.
  33664. */
  33665. if (flags & PKCS7_NOINTERN) {
  33666. WOLFSSL_MSG("PKCS7_NOINTERN flag not supported");
  33667. return NULL;
  33668. }
  33669. signers = wolfSSL_sk_X509_new();
  33670. if (signers == NULL)
  33671. return NULL;
  33672. if (wolfSSL_d2i_X509(&x509, (const byte**)&p7->pkcs7.singleCert,
  33673. p7->pkcs7.singleCertSz) == NULL) {
  33674. wolfSSL_sk_X509_pop_free(signers, NULL);
  33675. return NULL;
  33676. }
  33677. if (wolfSSL_sk_X509_push(signers, x509) != WOLFSSL_SUCCESS) {
  33678. wolfSSL_sk_X509_pop_free(signers, NULL);
  33679. return NULL;
  33680. }
  33681. (void)certs;
  33682. return signers;
  33683. }
  33684. #ifndef NO_BIO
  33685. PKCS7* wolfSSL_d2i_PKCS7_bio(WOLFSSL_BIO* bio, PKCS7** p7)
  33686. {
  33687. WOLFSSL_PKCS7* pkcs7;
  33688. int ret;
  33689. WOLFSSL_ENTER("wolfSSL_d2i_PKCS7_bio");
  33690. if (bio == NULL)
  33691. return NULL;
  33692. if ((pkcs7 = (WOLFSSL_PKCS7*)wolfSSL_PKCS7_new()) == NULL)
  33693. return NULL;
  33694. pkcs7->len = wolfSSL_BIO_get_len(bio);
  33695. pkcs7->data = (byte*)XMALLOC(pkcs7->len, NULL, DYNAMIC_TYPE_PKCS7);
  33696. if (pkcs7->data == NULL) {
  33697. wolfSSL_PKCS7_free((PKCS7*)pkcs7);
  33698. return NULL;
  33699. }
  33700. if ((ret = wolfSSL_BIO_read(bio, pkcs7->data, pkcs7->len)) <= 0) {
  33701. wolfSSL_PKCS7_free((PKCS7*)pkcs7);
  33702. return NULL;
  33703. }
  33704. /* pkcs7->len may change if using b64 for example */
  33705. pkcs7->len = ret;
  33706. if (wc_PKCS7_VerifySignedData(&pkcs7->pkcs7, pkcs7->data, pkcs7->len)
  33707. != 0) {
  33708. WOLFSSL_MSG("wc_PKCS7_VerifySignedData failed");
  33709. wolfSSL_PKCS7_free((PKCS7*)pkcs7);
  33710. return NULL;
  33711. }
  33712. if (p7 != NULL)
  33713. *p7 = (PKCS7*)pkcs7;
  33714. return (PKCS7*)pkcs7;
  33715. }
  33716. int wolfSSL_i2d_PKCS7(PKCS7 *p7, unsigned char **out)
  33717. {
  33718. byte* output = NULL;
  33719. int localBuf = 0;
  33720. int len;
  33721. WC_RNG rng;
  33722. int ret = WOLFSSL_FAILURE;
  33723. WOLFSSL_ENTER("wolfSSL_i2d_PKCS7");
  33724. if (!out || !p7) {
  33725. WOLFSSL_MSG("Bad parameter");
  33726. return WOLFSSL_FAILURE;
  33727. }
  33728. if (!p7->rng) {
  33729. if (wc_InitRng(&rng) != 0) {
  33730. WOLFSSL_MSG("wc_InitRng error");
  33731. return WOLFSSL_FAILURE;
  33732. }
  33733. p7->rng = &rng; // cppcheck-suppress autoVariables
  33734. }
  33735. if ((len = wc_PKCS7_EncodeSignedData(p7, NULL, 0)) < 0) {
  33736. WOLFSSL_MSG("wc_PKCS7_EncodeSignedData error");
  33737. goto cleanup;
  33738. }
  33739. if (*out == NULL) {
  33740. output = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  33741. if (!output) {
  33742. WOLFSSL_MSG("malloc error");
  33743. goto cleanup;
  33744. }
  33745. localBuf = 1;
  33746. }
  33747. else {
  33748. output = *out;
  33749. }
  33750. if ((len = wc_PKCS7_EncodeSignedData(p7, output, len)) < 0) {
  33751. WOLFSSL_MSG("wc_PKCS7_EncodeSignedData error");
  33752. goto cleanup;
  33753. }
  33754. ret = len;
  33755. cleanup:
  33756. if (p7->rng == &rng) {
  33757. wc_FreeRng(&rng);
  33758. p7->rng = NULL;
  33759. }
  33760. if (ret == WOLFSSL_FAILURE && localBuf && output)
  33761. XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  33762. if (ret != WOLFSSL_FAILURE)
  33763. *out = output;
  33764. return ret;
  33765. }
  33766. int wolfSSL_i2d_PKCS7_bio(WOLFSSL_BIO *bio, PKCS7 *p7)
  33767. {
  33768. byte* output = NULL;
  33769. int len;
  33770. int ret = WOLFSSL_FAILURE;
  33771. WOLFSSL_ENTER("wolfSSL_i2d_PKCS7_bio");
  33772. if (!bio || !p7) {
  33773. WOLFSSL_MSG("Bad parameter");
  33774. return WOLFSSL_FAILURE;
  33775. }
  33776. if ((len = wolfSSL_i2d_PKCS7(p7, &output)) == WOLFSSL_FAILURE) {
  33777. WOLFSSL_MSG("wolfSSL_i2d_PKCS7 error");
  33778. goto cleanup;
  33779. }
  33780. if (wolfSSL_BIO_write(bio, output, len) <= 0) {
  33781. WOLFSSL_MSG("wolfSSL_BIO_write error");
  33782. goto cleanup;
  33783. }
  33784. ret = WOLFSSL_SUCCESS;
  33785. cleanup:
  33786. if (output)
  33787. XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  33788. return ret;
  33789. }
  33790. /**
  33791. * Creates and returns a PKCS7 signedData structure.
  33792. *
  33793. * Inner content type is set to DATA to match OpenSSL behavior.
  33794. *
  33795. * signer - certificate to sign bundle with
  33796. * pkey - private key matching signer
  33797. * certs - optional additional set of certificates to include
  33798. * in - input data to be signed
  33799. * flags - optional set of flags to control sign behavior
  33800. *
  33801. * PKCS7_BINARY - Do not translate input data to MIME canonical
  33802. * format (\r\n line endings), thus preventing corruption of
  33803. * binary content.
  33804. * PKCS7_TEXT - Prepend MIME headers for text/plain to content.
  33805. * PKCS7_DETACHED - Set signature detached, omit content from output bundle.
  33806. * PKCS7_STREAM - initialize PKCS7 struct for signing, do not read data.
  33807. *
  33808. * Flags not currently supported:
  33809. * PKCS7_NOCERTS - Do not include the signer cert in the output bundle.
  33810. * PKCS7_PARTIAL - Allow for PKCS7_sign() to be only partially set up,
  33811. * then signers etc to be added separately before
  33812. * calling PKCS7_final().
  33813. *
  33814. * Returns valid PKCS7 structure pointer, or NULL if an error occurred.
  33815. */
  33816. PKCS7* wolfSSL_PKCS7_sign(WOLFSSL_X509* signer, WOLFSSL_EVP_PKEY* pkey,
  33817. WOLFSSL_STACK* certs, WOLFSSL_BIO* in, int flags)
  33818. {
  33819. int err = 0;
  33820. WOLFSSL_PKCS7* p7 = NULL;
  33821. WOLFSSL_STACK* cert = certs;
  33822. WOLFSSL_ENTER("wolfSSL_PKCS7_sign");
  33823. if (flags & PKCS7_NOCERTS) {
  33824. WOLFSSL_MSG("PKCS7_NOCERTS flag not yet supported");
  33825. err = 1;
  33826. }
  33827. if (flags & PKCS7_PARTIAL) {
  33828. WOLFSSL_MSG("PKCS7_PARTIAL flag not yet supported");
  33829. err = 1;
  33830. }
  33831. if ((err == 0) && (signer == NULL || signer->derCert == NULL ||
  33832. signer->derCert->length == 0)) {
  33833. WOLFSSL_MSG("Bad function arg, signer is NULL or incomplete");
  33834. err = 1;
  33835. }
  33836. if ((err == 0) && (pkey == NULL || pkey->pkey.ptr == NULL ||
  33837. pkey->pkey_sz <= 0)) {
  33838. WOLFSSL_MSG("Bad function arg, pkey is NULL or incomplete");
  33839. err = 1;
  33840. }
  33841. if ((err == 0) && (in == NULL) && !(flags & PKCS7_STREAM)) {
  33842. WOLFSSL_MSG("input data required unless PKCS7_STREAM used");
  33843. err = 1;
  33844. }
  33845. if ((err == 0) && ((p7 = (WOLFSSL_PKCS7*)wolfSSL_PKCS7_new()) == NULL)) {
  33846. WOLFSSL_MSG("Error allocating new WOLFSSL_PKCS7");
  33847. err = 1;
  33848. }
  33849. /* load signer certificate */
  33850. if (err == 0) {
  33851. if (wc_PKCS7_InitWithCert(&p7->pkcs7, signer->derCert->buffer,
  33852. signer->derCert->length) != 0) {
  33853. WOLFSSL_MSG("Failed to load signer certificate");
  33854. err = 1;
  33855. }
  33856. }
  33857. /* set signer private key, data types, defaults */
  33858. if (err == 0) {
  33859. p7->pkcs7.privateKey = (byte*)pkey->pkey.ptr;
  33860. p7->pkcs7.privateKeySz = pkey->pkey_sz;
  33861. p7->pkcs7.contentOID = DATA; /* inner content default is DATA */
  33862. p7->pkcs7.hashOID = SHA256h; /* default to SHA-256 hash type */
  33863. p7->type = SIGNED_DATA; /* PKCS7_final switches on type */
  33864. }
  33865. /* add additional chain certs if provided */
  33866. while (cert && (err == 0)) {
  33867. if (cert->data.x509 != NULL && cert->data.x509->derCert != NULL) {
  33868. if (wc_PKCS7_AddCertificate(&p7->pkcs7,
  33869. cert->data.x509->derCert->buffer,
  33870. cert->data.x509->derCert->length) != 0) {
  33871. WOLFSSL_MSG("Error in wc_PKCS7_AddCertificate");
  33872. err = 1;
  33873. }
  33874. }
  33875. cert = cert->next;
  33876. }
  33877. if ((err == 0) && (flags & PKCS7_DETACHED)) {
  33878. if (wc_PKCS7_SetDetached(&p7->pkcs7, 1) != 0) {
  33879. WOLFSSL_MSG("Failed to set signature detached");
  33880. err = 1;
  33881. }
  33882. }
  33883. if ((err == 0) && (flags & PKCS7_STREAM)) {
  33884. /* if streaming, return before finalizing */
  33885. return (PKCS7*)p7;
  33886. }
  33887. if ((err == 0) && (wolfSSL_PKCS7_final((PKCS7*)p7, in, flags) != 1)) {
  33888. WOLFSSL_MSG("Error calling wolfSSL_PKCS7_final");
  33889. err = 1;
  33890. }
  33891. if ((err != 0) && (p7 != NULL)) {
  33892. wolfSSL_PKCS7_free((PKCS7*)p7);
  33893. p7 = NULL;
  33894. }
  33895. return (PKCS7*)p7;
  33896. }
  33897. #ifdef HAVE_SMIME
  33898. #ifndef MAX_MIME_LINE_LEN
  33899. #define MAX_MIME_LINE_LEN 1024
  33900. #endif
  33901. /**
  33902. * Copy input BIO to output BIO, but convert all line endings to CRLF (\r\n),
  33903. * used by PKCS7_final().
  33904. *
  33905. * in - input WOLFSSL_BIO to be converted
  33906. * out - output WOLFSSL_BIO to hold copy of in, with line endings adjusted
  33907. *
  33908. * Return 0 on success, negative on error
  33909. */
  33910. static int wolfSSL_BIO_to_MIME_crlf(WOLFSSL_BIO* in, WOLFSSL_BIO* out)
  33911. {
  33912. int ret = 0;
  33913. int lineLen = 0;
  33914. word32 canonLineLen = 0;
  33915. char* canonLine = NULL;
  33916. #ifdef WOLFSSL_SMALL_STACK
  33917. char* line = NULL;
  33918. #else
  33919. char line[MAX_MIME_LINE_LEN];
  33920. #endif
  33921. if (in == NULL || out == NULL) {
  33922. return BAD_FUNC_ARG;
  33923. }
  33924. #ifdef WOLFSSL_SMALL_STACK
  33925. line = (char*)XMALLOC(MAX_MIME_LINE_LEN, in->heap,
  33926. DYNAMIC_TYPE_TMP_BUFFER);
  33927. if (line == NULL) {
  33928. return MEMORY_E;
  33929. }
  33930. #endif
  33931. XMEMSET(line, 0, MAX_MIME_LINE_LEN);
  33932. while ((lineLen = wolfSSL_BIO_gets(in, line, (int)sizeof(line))) > 0) {
  33933. if (line[lineLen - 1] == '\r' || line[lineLen - 1] == '\n') {
  33934. canonLineLen = (word32)lineLen;
  33935. if ((canonLine = wc_MIME_single_canonicalize(
  33936. line, &canonLineLen)) == NULL) {
  33937. ret = -1;
  33938. break;
  33939. }
  33940. /* remove trailing null */
  33941. if (canonLine[canonLineLen] == '\0') {
  33942. canonLineLen--;
  33943. }
  33944. if (wolfSSL_BIO_write(out, canonLine, (int)canonLineLen) < 0) {
  33945. ret = -1;
  33946. break;
  33947. }
  33948. XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7);
  33949. canonLine = NULL;
  33950. }
  33951. else {
  33952. /* no line ending in current line, write direct to out */
  33953. if (wolfSSL_BIO_write(out, line, lineLen) < 0) {
  33954. ret = -1;
  33955. break;
  33956. }
  33957. }
  33958. }
  33959. if (canonLine != NULL) {
  33960. XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7);
  33961. }
  33962. #ifdef WOLFSSL_SMALL_STACK
  33963. XFREE(line, in->heap, DYNAMIC_TYPE_TMP_BUFFER);
  33964. #endif
  33965. return ret;
  33966. }
  33967. #endif /* HAVE_SMIME */
  33968. /* Used by both PKCS7_final() and PKCS7_verify() */
  33969. static const char contTypeText[] = "Content-Type: text/plain\r\n\r\n";
  33970. /**
  33971. * Finalize PKCS7 structure, currently supports signedData only.
  33972. *
  33973. * Does not generate final bundle (ie: signedData), but finalizes
  33974. * the PKCS7 structure in preparation for a output function to be called next.
  33975. *
  33976. * pkcs7 - initialized PKCS7 structure, populated with signer, etc
  33977. * in - input data
  33978. * flags - flags to control PKCS7 behavior. Other flags except those noted
  33979. * below are ignored:
  33980. *
  33981. * PKCS7_BINARY - Do not translate input data to MIME canonical
  33982. * format (\r\n line endings), thus preventing corruption of
  33983. * binary content.
  33984. * PKCS7_TEXT - Prepend MIME headers for text/plain to content.
  33985. *
  33986. * Returns 1 on success, 0 on error
  33987. */
  33988. int wolfSSL_PKCS7_final(PKCS7* pkcs7, WOLFSSL_BIO* in, int flags)
  33989. {
  33990. int ret = 1;
  33991. int memSz = 0;
  33992. unsigned char* mem = NULL;
  33993. WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7;
  33994. WOLFSSL_BIO* data = NULL;
  33995. WOLFSSL_ENTER("wolfSSL_PKCS7_final");
  33996. if (p7 == NULL || in == NULL) {
  33997. WOLFSSL_MSG("Bad input args to PKCS7_final");
  33998. ret = 0;
  33999. }
  34000. if (ret == 1) {
  34001. if ((data = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())) == NULL) {
  34002. WOLFSSL_MSG("Error in wolfSSL_BIO_new");
  34003. ret = 0;
  34004. }
  34005. }
  34006. /* prepend Content-Type header if PKCS7_TEXT */
  34007. if ((ret == 1) && (flags & PKCS7_TEXT)) {
  34008. if (wolfSSL_BIO_write(data, contTypeText,
  34009. (int)XSTR_SIZEOF(contTypeText)) < 0) {
  34010. WOLFSSL_MSG("Error prepending Content-Type header");
  34011. ret = 0;
  34012. }
  34013. }
  34014. /* convert line endings to CRLF if !PKCS7_BINARY */
  34015. if (ret == 1) {
  34016. if (flags & PKCS7_BINARY) {
  34017. /* no CRLF conversion, direct copy content */
  34018. if ((memSz = wolfSSL_BIO_get_len(in)) <= 0) {
  34019. ret = 0;
  34020. }
  34021. if (ret == 1) {
  34022. mem = (unsigned char*)XMALLOC(memSz, in->heap,
  34023. DYNAMIC_TYPE_TMP_BUFFER);
  34024. if (mem == NULL) {
  34025. WOLFSSL_MSG("Failed to allocate memory for input data");
  34026. ret = 0;
  34027. }
  34028. }
  34029. if (ret == 1) {
  34030. if (wolfSSL_BIO_read(in, mem, memSz) != memSz) {
  34031. WOLFSSL_MSG("Error reading from input BIO");
  34032. ret = 0;
  34033. }
  34034. else if (wolfSSL_BIO_write(data, mem, memSz) < 0) {
  34035. ret = 0;
  34036. }
  34037. }
  34038. if (mem != NULL) {
  34039. XFREE(mem, in->heap, DYNAMIC_TYPE_TMP_BUFFER);
  34040. }
  34041. }
  34042. else {
  34043. #ifdef HAVE_SMIME
  34044. /* convert content line endings to CRLF */
  34045. if (wolfSSL_BIO_to_MIME_crlf(in, data) != 0) {
  34046. WOLFSSL_MSG("Error converting line endings to CRLF");
  34047. ret = 0;
  34048. }
  34049. else {
  34050. p7->pkcs7.contentCRLF = 1;
  34051. }
  34052. #else
  34053. WOLFSSL_MSG("Without PKCS7_BINARY requires wolfSSL to be built "
  34054. "with HAVE_SMIME");
  34055. ret = 0;
  34056. #endif
  34057. }
  34058. }
  34059. if ((ret == 1) && ((memSz = wolfSSL_BIO_get_mem_data(data, &mem)) < 0)) {
  34060. WOLFSSL_MSG("Error in wolfSSL_BIO_get_mem_data");
  34061. ret = 0;
  34062. }
  34063. if (ret == 1) {
  34064. if (p7->data != NULL) {
  34065. XFREE(p7->data, NULL, DYNAMIC_TYPE_PKCS7);
  34066. }
  34067. p7->data = (byte*)XMALLOC(memSz, NULL, DYNAMIC_TYPE_PKCS7);
  34068. if (p7->data == NULL) {
  34069. ret = 0;
  34070. }
  34071. else {
  34072. XMEMCPY(p7->data, mem, memSz);
  34073. p7->len = memSz;
  34074. }
  34075. }
  34076. if (ret == 1) {
  34077. p7->pkcs7.content = p7->data;
  34078. p7->pkcs7.contentSz = p7->len;
  34079. }
  34080. if (data != NULL) {
  34081. wolfSSL_BIO_free(data);
  34082. }
  34083. return ret;
  34084. }
  34085. int wolfSSL_PKCS7_verify(PKCS7* pkcs7, WOLFSSL_STACK* certs,
  34086. WOLFSSL_X509_STORE* store, WOLFSSL_BIO* in, WOLFSSL_BIO* out, int flags)
  34087. {
  34088. int i, ret = 0;
  34089. unsigned char* mem = NULL;
  34090. int memSz = 0;
  34091. WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7;
  34092. int contTypeLen;
  34093. WOLFSSL_X509* signer = NULL;
  34094. WOLFSSL_STACK* signers = NULL;
  34095. WOLFSSL_ENTER("wolfSSL_PKCS7_verify");
  34096. if (pkcs7 == NULL)
  34097. return WOLFSSL_FAILURE;
  34098. if (in != NULL) {
  34099. if ((memSz = wolfSSL_BIO_get_mem_data(in, &mem)) < 0)
  34100. return WOLFSSL_FAILURE;
  34101. p7->pkcs7.content = mem;
  34102. p7->pkcs7.contentSz = memSz;
  34103. }
  34104. /* certs is the list of certificates to find the cert with issuer/serial. */
  34105. (void)certs;
  34106. /* store is the certificate store to use to verify signer certificate
  34107. * associated with the signers.
  34108. */
  34109. (void)store;
  34110. ret = wc_PKCS7_VerifySignedData(&p7->pkcs7, p7->data, p7->len);
  34111. if (ret != 0)
  34112. return WOLFSSL_FAILURE;
  34113. if ((flags & PKCS7_NOVERIFY) != PKCS7_NOVERIFY) {
  34114. /* Verify signer certificates */
  34115. if (store == NULL || store->cm == NULL) {
  34116. WOLFSSL_MSG("No store or store certs, but PKCS7_NOVERIFY not set");
  34117. return WOLFSSL_FAILURE;
  34118. }
  34119. signers = wolfSSL_PKCS7_get0_signers(pkcs7, certs, flags);
  34120. if (signers == NULL) {
  34121. WOLFSSL_MSG("No signers found to verify");
  34122. return WOLFSSL_FAILURE;
  34123. }
  34124. for (i = 0; i < wolfSSL_sk_X509_num(signers); i++) {
  34125. signer = wolfSSL_sk_X509_value(signers, i);
  34126. if (wolfSSL_CertManagerVerifyBuffer(store->cm,
  34127. signer->derCert->buffer,
  34128. signer->derCert->length,
  34129. WOLFSSL_FILETYPE_ASN1) != WOLFSSL_SUCCESS) {
  34130. WOLFSSL_MSG("Failed to verify signer certificate");
  34131. wolfSSL_sk_X509_pop_free(signers, NULL);
  34132. return WOLFSSL_FAILURE;
  34133. }
  34134. }
  34135. wolfSSL_sk_X509_pop_free(signers, NULL);
  34136. }
  34137. if (flags & PKCS7_TEXT) {
  34138. /* strip MIME header for text/plain, otherwise error */
  34139. contTypeLen = XSTR_SIZEOF(contTypeText);
  34140. if ((p7->pkcs7.contentSz < (word32)contTypeLen) ||
  34141. (XMEMCMP(p7->pkcs7.content, contTypeText, contTypeLen) != 0)) {
  34142. WOLFSSL_MSG("Error PKCS7 Content-Type not found with PKCS7_TEXT");
  34143. return WOLFSSL_FAILURE;
  34144. }
  34145. p7->pkcs7.content += contTypeLen;
  34146. p7->pkcs7.contentSz -= contTypeLen;
  34147. }
  34148. if (out != NULL) {
  34149. wolfSSL_BIO_write(out, p7->pkcs7.content, p7->pkcs7.contentSz);
  34150. }
  34151. WOLFSSL_LEAVE("wolfSSL_PKCS7_verify", WOLFSSL_SUCCESS);
  34152. return WOLFSSL_SUCCESS;
  34153. }
  34154. /**
  34155. * This API was added as a helper function for libest. It
  34156. * encodes a stack of certificates to pkcs7 format.
  34157. * @param pkcs7 PKCS7 parameter object
  34158. * @param certs WOLFSSL_STACK_OF(WOLFSSL_X509)*
  34159. * @param out Output bio
  34160. * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure
  34161. */
  34162. int wolfSSL_PKCS7_encode_certs(PKCS7* pkcs7, WOLFSSL_STACK* certs,
  34163. WOLFSSL_BIO* out)
  34164. {
  34165. int ret;
  34166. WOLFSSL_PKCS7* p7;
  34167. WOLFSSL_ENTER("wolfSSL_PKCS7_encode_certs");
  34168. if (!pkcs7 || !certs || !out) {
  34169. WOLFSSL_MSG("Bad parameter");
  34170. return WOLFSSL_FAILURE;
  34171. }
  34172. p7 = (WOLFSSL_PKCS7*)pkcs7;
  34173. /* take ownership of certs */
  34174. p7->certs = certs;
  34175. if (pkcs7->certList) {
  34176. WOLFSSL_MSG("wolfSSL_PKCS7_encode_certs called multiple times on same "
  34177. "struct");
  34178. return WOLFSSL_FAILURE;
  34179. }
  34180. if (certs) {
  34181. /* Save some of the values */
  34182. int hashOID = pkcs7->hashOID;
  34183. byte version = pkcs7->version;
  34184. if (!certs->data.x509 || !certs->data.x509->derCert) {
  34185. WOLFSSL_MSG("Missing cert");
  34186. return WOLFSSL_FAILURE;
  34187. }
  34188. if (wc_PKCS7_InitWithCert(pkcs7, certs->data.x509->derCert->buffer,
  34189. certs->data.x509->derCert->length) != 0) {
  34190. WOLFSSL_MSG("wc_PKCS7_InitWithCert error");
  34191. return WOLFSSL_FAILURE;
  34192. }
  34193. certs = certs->next;
  34194. pkcs7->hashOID = hashOID;
  34195. pkcs7->version = version;
  34196. }
  34197. /* Add the certs to the PKCS7 struct */
  34198. while (certs) {
  34199. if (!certs->data.x509 || !certs->data.x509->derCert) {
  34200. WOLFSSL_MSG("Missing cert");
  34201. return WOLFSSL_FAILURE;
  34202. }
  34203. if (wc_PKCS7_AddCertificate(pkcs7, certs->data.x509->derCert->buffer,
  34204. certs->data.x509->derCert->length) != 0) {
  34205. WOLFSSL_MSG("wc_PKCS7_AddCertificate error");
  34206. return WOLFSSL_FAILURE;
  34207. }
  34208. certs = certs->next;
  34209. }
  34210. if (wc_PKCS7_SetSignerIdentifierType(pkcs7, DEGENERATE_SID) != 0) {
  34211. WOLFSSL_MSG("wc_PKCS7_SetSignerIdentifierType error");
  34212. return WOLFSSL_FAILURE;
  34213. }
  34214. ret = wolfSSL_i2d_PKCS7_bio(out, pkcs7);
  34215. return ret;
  34216. }
  34217. /******************************************************************************
  34218. * wolfSSL_PEM_write_bio_PKCS7 - writes the PKCS7 data to BIO
  34219. *
  34220. * RETURNS:
  34221. * returns WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE
  34222. */
  34223. int wolfSSL_PEM_write_bio_PKCS7(WOLFSSL_BIO* bio, PKCS7* p7)
  34224. {
  34225. #ifdef WOLFSSL_SMALL_STACK
  34226. byte* outputHead;
  34227. byte* outputFoot;
  34228. #else
  34229. byte outputHead[2048];
  34230. byte outputFoot[2048];
  34231. #endif
  34232. word32 outputHeadSz = 2048;
  34233. word32 outputFootSz = 2048;
  34234. word32 outputSz = 0;
  34235. byte* output = NULL;
  34236. byte* pem = NULL;
  34237. int pemSz = -1;
  34238. enum wc_HashType hashType;
  34239. byte hashBuf[WC_MAX_DIGEST_SIZE];
  34240. word32 hashSz = -1;
  34241. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PKCS7()");
  34242. if (bio == NULL || p7 == NULL)
  34243. return WOLFSSL_FAILURE;
  34244. #ifdef WOLFSSL_SMALL_STACK
  34245. outputHead = (byte*)XMALLOC(outputHeadSz, bio->heap,
  34246. DYNAMIC_TYPE_TMP_BUFFER);
  34247. if (outputHead == NULL)
  34248. return MEMORY_E;
  34249. outputFoot = (byte*)XMALLOC(outputFootSz, bio->heap,
  34250. DYNAMIC_TYPE_TMP_BUFFER);
  34251. if (outputFoot == NULL)
  34252. goto error;
  34253. #endif
  34254. XMEMSET(hashBuf, 0, WC_MAX_DIGEST_SIZE);
  34255. XMEMSET(outputHead, 0, outputHeadSz);
  34256. XMEMSET(outputFoot, 0, outputFootSz);
  34257. hashType = wc_OidGetHash(p7->hashOID);
  34258. hashSz = wc_HashGetDigestSize(hashType);
  34259. if (hashSz > WC_MAX_DIGEST_SIZE)
  34260. return WOLFSSL_FAILURE;
  34261. /* only SIGNED_DATA is supported */
  34262. switch (p7->contentOID) {
  34263. case SIGNED_DATA:
  34264. break;
  34265. default:
  34266. WOLFSSL_MSG("Unknown PKCS#7 Type");
  34267. return WOLFSSL_FAILURE;
  34268. };
  34269. if ((wc_PKCS7_EncodeSignedData_ex(p7, hashBuf, hashSz,
  34270. outputHead, &outputHeadSz, outputFoot, &outputFootSz)) != 0)
  34271. return WOLFSSL_FAILURE;
  34272. outputSz = outputHeadSz + p7->contentSz + outputFootSz;
  34273. output = (byte*)XMALLOC(outputSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  34274. if (!output)
  34275. return WOLFSSL_FAILURE;
  34276. XMEMSET(output, 0, outputSz);
  34277. outputSz = 0;
  34278. XMEMCPY(&output[outputSz], outputHead, outputHeadSz);
  34279. outputSz += outputHeadSz;
  34280. XMEMCPY(&output[outputSz], p7->content, p7->contentSz);
  34281. outputSz += p7->contentSz;
  34282. XMEMCPY(&output[outputSz], outputFoot, outputFootSz);
  34283. outputSz += outputFootSz;
  34284. /* get PEM size */
  34285. pemSz = wc_DerToPemEx(output, outputSz, NULL, 0, NULL, CERT_TYPE);
  34286. if (pemSz < 0)
  34287. goto error;
  34288. pemSz++; /* for '\0'*/
  34289. /* create PEM buffer and convert from DER to PEM*/
  34290. if ((pem = (byte*)XMALLOC(pemSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER))
  34291. == NULL)
  34292. goto error;
  34293. XMEMSET(pem, 0, pemSz);
  34294. if (wc_DerToPemEx(output, outputSz, pem, pemSz, NULL, CERT_TYPE) < 0) {
  34295. goto error;
  34296. }
  34297. if ((wolfSSL_BIO_write(bio, pem, pemSz) == pemSz)) {
  34298. XFREE(output, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  34299. XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  34300. #ifdef WOLFSSL_SMALL_STACK
  34301. XFREE(outputHead, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  34302. XFREE(outputFoot, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  34303. #endif
  34304. return WOLFSSL_SUCCESS;
  34305. }
  34306. error:
  34307. #ifdef WOLFSSL_SMALL_STACK
  34308. if (outputHead) {
  34309. XFREE(outputHead, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  34310. }
  34311. if (outputFoot) {
  34312. XFREE(outputFoot, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  34313. }
  34314. #endif
  34315. if (output) {
  34316. XFREE(output, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  34317. }
  34318. if (pem) {
  34319. XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  34320. }
  34321. return WOLFSSL_FAILURE;
  34322. }
  34323. #ifdef HAVE_SMIME
  34324. /*****************************************************************************
  34325. * wolfSSL_SMIME_read_PKCS7 - Reads the given S/MIME message and parses it into
  34326. * a PKCS7 object. In case of a multipart message, stores the signed data in
  34327. * bcont.
  34328. *
  34329. * RETURNS:
  34330. * returns pointer to a PKCS7 structure on success, otherwise returns NULL
  34331. */
  34332. WOLFSSL_API PKCS7* wolfSSL_SMIME_read_PKCS7(WOLFSSL_BIO* in,
  34333. WOLFSSL_BIO** bcont)
  34334. {
  34335. MimeHdr* allHdrs = NULL;
  34336. MimeHdr* curHdr = NULL;
  34337. MimeParam* curParam = NULL;
  34338. int inLen = 0;
  34339. byte* bcontMem = NULL;
  34340. int bcontMemSz = 0;
  34341. int sectionLen = 0;
  34342. int ret = -1;
  34343. char* section = NULL;
  34344. char* canonLine = NULL;
  34345. char* canonSection = NULL;
  34346. PKCS7* pkcs7 = NULL;
  34347. word32 outLen = 0;
  34348. word32 canonLineLen = 0;
  34349. byte* out = NULL;
  34350. byte* outHead = NULL;
  34351. int canonPos = 0;
  34352. int lineLen = 0;
  34353. int remainLen = 0;
  34354. byte isEnd = 0;
  34355. size_t canonSize = 0;
  34356. size_t boundLen = 0;
  34357. char* boundary = NULL;
  34358. static const char kContType[] = "Content-Type";
  34359. static const char kCTE[] = "Content-Transfer-Encoding";
  34360. static const char kMultSigned[] = "multipart/signed";
  34361. static const char kAppPkcsSign[] = "application/pkcs7-signature";
  34362. static const char kAppXPkcsSign[] = "application/x-pkcs7-signature";
  34363. static const char kAppPkcs7Mime[] = "application/pkcs7-mime";
  34364. static const char kAppXPkcs7Mime[] = "application/x-pkcs7-mime";
  34365. WOLFSSL_ENTER("wolfSSL_SMIME_read_PKCS7");
  34366. if (in == NULL || bcont == NULL) {
  34367. goto error;
  34368. }
  34369. inLen = wolfSSL_BIO_get_len(in);
  34370. if (inLen <= 0) {
  34371. goto error;
  34372. }
  34373. remainLen = wolfSSL_BIO_get_len(in);
  34374. if (remainLen <= 0) {
  34375. goto error;
  34376. }
  34377. section = (char*)XMALLOC(remainLen+1, NULL, DYNAMIC_TYPE_PKCS7);
  34378. if (section == NULL) {
  34379. goto error;
  34380. }
  34381. lineLen = wolfSSL_BIO_gets(in, section, remainLen);
  34382. if (lineLen <= 0) {
  34383. goto error;
  34384. }
  34385. while (isEnd == 0 && remainLen > 0) {
  34386. sectionLen += lineLen;
  34387. remainLen -= lineLen;
  34388. lineLen = wolfSSL_BIO_gets(in, &section[sectionLen], remainLen);
  34389. if (lineLen <= 0) {
  34390. goto error;
  34391. }
  34392. /* Line with just newline signals end of headers. */
  34393. if ((lineLen==2 && !XSTRNCMP(&section[sectionLen],
  34394. "\r\n", 2)) ||
  34395. (lineLen==1 && (section[sectionLen] == '\r' ||
  34396. section[sectionLen] == '\n'))) {
  34397. isEnd = 1;
  34398. }
  34399. }
  34400. section[sectionLen] = '\0';
  34401. ret = wc_MIME_parse_headers(section, sectionLen, &allHdrs);
  34402. if (ret < 0) {
  34403. WOLFSSL_MSG("Parsing MIME headers failed.");
  34404. goto error;
  34405. }
  34406. isEnd = 0;
  34407. section[0] = '\0';
  34408. sectionLen = 0;
  34409. curHdr = wc_MIME_find_header_name(kContType, allHdrs);
  34410. if (curHdr && !XSTRNCMP(curHdr->body, kMultSigned,
  34411. XSTR_SIZEOF(kMultSigned))) {
  34412. curParam = wc_MIME_find_param_attr("protocol", curHdr->params);
  34413. if (curParam && (!XSTRNCMP(curParam->value, kAppPkcsSign,
  34414. XSTR_SIZEOF(kAppPkcsSign)) ||
  34415. !XSTRNCMP(curParam->value, kAppXPkcsSign,
  34416. XSTR_SIZEOF(kAppXPkcsSign)))) {
  34417. curParam = wc_MIME_find_param_attr("boundary", curHdr->params);
  34418. if (curParam == NULL) {
  34419. goto error;
  34420. }
  34421. boundLen = XSTRLEN(curParam->value) + 2;
  34422. boundary = (char*)XMALLOC(boundLen+1, NULL, DYNAMIC_TYPE_PKCS7);
  34423. if (boundary == NULL) {
  34424. goto error;
  34425. }
  34426. XMEMSET(boundary, 0, (word32)(boundLen+1));
  34427. boundary[0] = boundary[1] = '-';
  34428. XSTRNCPY(&boundary[2], curParam->value, boundLen-2);
  34429. /* Parse up to first boundary, ignore everything here. */
  34430. lineLen = wolfSSL_BIO_gets(in, section, remainLen);
  34431. if (lineLen <= 0) {
  34432. goto error;
  34433. }
  34434. while (XSTRNCMP(&section[sectionLen], boundary, boundLen) &&
  34435. remainLen > 0) {
  34436. sectionLen += lineLen;
  34437. remainLen -= lineLen;
  34438. lineLen = wolfSSL_BIO_gets(in, &section[sectionLen],
  34439. remainLen);
  34440. if (lineLen <= 0) {
  34441. goto error;
  34442. }
  34443. }
  34444. section[0] = '\0';
  34445. sectionLen = 0;
  34446. canonSize = remainLen + 1;
  34447. canonSection = (char*)XMALLOC(canonSize, NULL,
  34448. DYNAMIC_TYPE_PKCS7);
  34449. if (canonSection == NULL) {
  34450. goto error;
  34451. }
  34452. lineLen = wolfSSL_BIO_gets(in, section, remainLen);
  34453. while (XSTRNCMP(&section[sectionLen], boundary, boundLen) &&
  34454. remainLen > 0) {
  34455. canonLineLen = lineLen;
  34456. canonLine = wc_MIME_single_canonicalize(&section[sectionLen],
  34457. &canonLineLen);
  34458. if (canonLine == NULL) {
  34459. goto error;
  34460. }
  34461. /* If line endings were added, the initial length may be
  34462. * exceeded. */
  34463. if ((canonPos + canonLineLen) >= canonSize) {
  34464. canonSize = canonPos + canonLineLen;
  34465. canonSection = (char*)XREALLOC(canonSection, canonSize,
  34466. NULL, DYNAMIC_TYPE_PKCS7);
  34467. if (canonSection == NULL) {
  34468. goto error;
  34469. }
  34470. }
  34471. XMEMCPY(&canonSection[canonPos], canonLine,
  34472. (int)canonLineLen - 1);
  34473. canonPos += canonLineLen - 1;
  34474. XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7);
  34475. canonLine = NULL;
  34476. sectionLen += lineLen;
  34477. remainLen -= lineLen;
  34478. lineLen = wolfSSL_BIO_gets(in, &section[sectionLen],
  34479. remainLen);
  34480. if (lineLen <= 0) {
  34481. goto error;
  34482. }
  34483. }
  34484. if (canonPos > 0) {
  34485. canonPos--;
  34486. }
  34487. /* Strip the final trailing newline. Support \r, \n or \r\n. */
  34488. if (canonSection[canonPos] == '\n') {
  34489. if (canonPos > 0) {
  34490. canonPos--;
  34491. }
  34492. }
  34493. if (canonSection[canonPos] == '\r') {
  34494. if (canonPos > 0) {
  34495. canonPos--;
  34496. }
  34497. }
  34498. canonSection[canonPos+1] = '\0';
  34499. *bcont = wolfSSL_BIO_new(wolfSSL_BIO_s_mem());
  34500. ret = wolfSSL_BIO_write(*bcont, canonSection,
  34501. canonPos + 1);
  34502. if (ret != (canonPos+1)) {
  34503. goto error;
  34504. }
  34505. if ((bcontMemSz = wolfSSL_BIO_get_mem_data(*bcont, &bcontMem))
  34506. < 0) {
  34507. goto error;
  34508. }
  34509. XFREE(canonSection, NULL, DYNAMIC_TYPE_PKCS7);
  34510. canonSection = NULL;
  34511. wc_MIME_free_hdrs(allHdrs);
  34512. allHdrs = NULL;
  34513. section[0] = '\0';
  34514. sectionLen = 0;
  34515. lineLen = wolfSSL_BIO_gets(in, section, remainLen);
  34516. if (lineLen <= 0) {
  34517. goto error;
  34518. }
  34519. while (isEnd == 0 && remainLen > 0) {
  34520. sectionLen += lineLen;
  34521. remainLen -= lineLen;
  34522. lineLen = wolfSSL_BIO_gets(in, &section[sectionLen],
  34523. remainLen);
  34524. if (lineLen <= 0) {
  34525. goto error;
  34526. }
  34527. /* Line with just newline signals end of headers. */
  34528. if ((lineLen==2 && !XSTRNCMP(&section[sectionLen],
  34529. "\r\n", 2)) ||
  34530. (lineLen==1 && (section[sectionLen] == '\r' ||
  34531. section[sectionLen] == '\n'))) {
  34532. isEnd = 1;
  34533. }
  34534. }
  34535. section[sectionLen] = '\0';
  34536. ret = wc_MIME_parse_headers(section, sectionLen, &allHdrs);
  34537. if (ret < 0) {
  34538. WOLFSSL_MSG("Parsing MIME headers failed.");
  34539. goto error;
  34540. }
  34541. curHdr = wc_MIME_find_header_name(kContType, allHdrs);
  34542. if (curHdr == NULL || (XSTRNCMP(curHdr->body, kAppPkcsSign,
  34543. XSTR_SIZEOF(kAppPkcsSign)) &&
  34544. XSTRNCMP(curHdr->body, kAppXPkcsSign,
  34545. XSTR_SIZEOF(kAppXPkcsSign)))) {
  34546. WOLFSSL_MSG("S/MIME headers not found inside "
  34547. "multipart message.\n");
  34548. goto error;
  34549. }
  34550. section[0] = '\0';
  34551. sectionLen = 0;
  34552. lineLen = wolfSSL_BIO_gets(in, section, remainLen);
  34553. while (XSTRNCMP(&section[sectionLen], boundary, boundLen) &&
  34554. remainLen > 0) {
  34555. sectionLen += lineLen;
  34556. remainLen -= lineLen;
  34557. lineLen = wolfSSL_BIO_gets(in, &section[sectionLen],
  34558. remainLen);
  34559. if (lineLen <= 0) {
  34560. goto error;
  34561. }
  34562. }
  34563. XFREE(boundary, NULL, DYNAMIC_TYPE_PKCS7);
  34564. boundary = NULL;
  34565. }
  34566. }
  34567. else if (curHdr && (!XSTRNCMP(curHdr->body, kAppPkcs7Mime,
  34568. XSTR_SIZEOF(kAppPkcs7Mime)) ||
  34569. !XSTRNCMP(curHdr->body, kAppXPkcs7Mime,
  34570. XSTR_SIZEOF(kAppXPkcs7Mime)))) {
  34571. sectionLen = wolfSSL_BIO_get_len(in);
  34572. if (sectionLen <= 0) {
  34573. goto error;
  34574. }
  34575. ret = wolfSSL_BIO_read(in, section, sectionLen);
  34576. if (ret < 0 || ret != sectionLen) {
  34577. WOLFSSL_MSG("Error reading input BIO.");
  34578. goto error;
  34579. }
  34580. }
  34581. else {
  34582. WOLFSSL_MSG("S/MIME headers not found.");
  34583. goto error;
  34584. }
  34585. curHdr = wc_MIME_find_header_name(kCTE, allHdrs);
  34586. if (curHdr == NULL) {
  34587. WOLFSSL_MSG("Content-Transfer-Encoding header not found, "
  34588. "assuming base64 encoding.");
  34589. }
  34590. else if (XSTRNCMP(curHdr->body, "base64", XSTRLEN("base64"))) {
  34591. WOLFSSL_MSG("S/MIME encodings other than base64 are not "
  34592. "currently supported.\n");
  34593. goto error;
  34594. }
  34595. if (section == NULL || sectionLen <= 0) {
  34596. goto error;
  34597. }
  34598. outLen = ((sectionLen*3+3)/4)+1;
  34599. out = (byte*)XMALLOC(outLen*sizeof(byte), NULL, DYNAMIC_TYPE_PKCS7);
  34600. outHead = out;
  34601. if (outHead == NULL) {
  34602. goto error;
  34603. }
  34604. /* Strip trailing newlines. */
  34605. while ((sectionLen > 0) &&
  34606. (section[sectionLen-1] == '\r' || section[sectionLen-1] == '\n')) {
  34607. sectionLen--;
  34608. }
  34609. section[sectionLen] = '\0';
  34610. ret = Base64_Decode((const byte*)section, sectionLen, out, &outLen);
  34611. if (ret < 0) {
  34612. WOLFSSL_MSG("Error base64 decoding S/MIME message.");
  34613. goto error;
  34614. }
  34615. pkcs7 = wolfSSL_d2i_PKCS7_ex(NULL, (const unsigned char**)&out, outLen,
  34616. bcontMem, bcontMemSz);
  34617. wc_MIME_free_hdrs(allHdrs);
  34618. XFREE(outHead, NULL, DYNAMIC_TYPE_PKCS7);
  34619. XFREE(section, NULL, DYNAMIC_TYPE_PKCS7);
  34620. return pkcs7;
  34621. error:
  34622. wc_MIME_free_hdrs(allHdrs);
  34623. XFREE(boundary, NULL, DYNAMIC_TYPE_PKCS7);
  34624. XFREE(outHead, NULL, DYNAMIC_TYPE_PKCS7);
  34625. XFREE(section, NULL, DYNAMIC_TYPE_PKCS7);
  34626. if (canonSection != NULL)
  34627. XFREE(canonSection, NULL, DYNAMIC_TYPE_PKCS7);
  34628. if (bcont) {
  34629. wolfSSL_BIO_free(*bcont);
  34630. *bcont = NULL; /* reset 'bcount' pointer to NULL on failure */
  34631. }
  34632. return NULL;
  34633. }
  34634. /* Convert hash algo OID (from Hash_Sum in asn.h) to SMIME string equivalent.
  34635. * Returns hash algorithm string or "unknown" if not found */
  34636. static const char* wolfSSL_SMIME_HashOIDToString(int hashOID)
  34637. {
  34638. switch (hashOID) {
  34639. case MD5h:
  34640. return "md5";
  34641. case SHAh:
  34642. return "sha1";
  34643. case SHA224h:
  34644. return "sha-224";
  34645. case SHA256h:
  34646. return "sha-256";
  34647. case SHA384h:
  34648. return "sha-384";
  34649. case SHA512h:
  34650. return "sha-512";
  34651. case SHA3_224h:
  34652. return "sha3-224";
  34653. case SHA3_384h:
  34654. return "sha3-384";
  34655. case SHA3_512h:
  34656. return "sha3-512";
  34657. default:
  34658. break;
  34659. }
  34660. return "unknown";
  34661. }
  34662. /* Convert PKCS#7 type (from PKCS7_TYPES in pkcs7.h) to SMIME string.
  34663. * RFC2633 only defines signed-data, enveloped-data, certs-only.
  34664. * Returns string on success, NULL on unknown type. */
  34665. static const char* wolfSSL_SMIME_PKCS7TypeToString(int type)
  34666. {
  34667. switch (type) {
  34668. case SIGNED_DATA:
  34669. return "signed-data";
  34670. case ENVELOPED_DATA:
  34671. return "enveloped-data";
  34672. default:
  34673. break;
  34674. }
  34675. return NULL;
  34676. }
  34677. /**
  34678. * Convert PKCS7 structure to SMIME format, adding necessary headers.
  34679. *
  34680. * Handles generation of PKCS7 bundle (ie: signedData). PKCS7 structure
  34681. * should be set up beforehand with PKCS7_sign/final/etc. Output is always
  34682. * Base64 encoded.
  34683. *
  34684. * out - output BIO for SMIME formatted data to be placed
  34685. * pkcs7 - input PKCS7 structure, initialized and set up
  34686. * in - input content to be encoded into PKCS7
  34687. * flags - flags to control behavior of PKCS7 generation
  34688. *
  34689. * Returns 1 on success, 0 or negative on failure
  34690. */
  34691. int wolfSSL_SMIME_write_PKCS7(WOLFSSL_BIO* out, PKCS7* pkcs7, WOLFSSL_BIO* in,
  34692. int flags)
  34693. {
  34694. int i;
  34695. int ret = 1;
  34696. WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7;
  34697. byte* p7out = NULL;
  34698. int len = 0;
  34699. char boundary[33]; /* 32 chars + \0 */
  34700. byte* sigBase64 = NULL;
  34701. word32 sigBase64Len = 0;
  34702. const char* p7TypeString = NULL;
  34703. static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  34704. if (out == NULL || p7 == NULL) {
  34705. WOLFSSL_MSG("Bad function arguments");
  34706. return 0;
  34707. }
  34708. if (in != NULL && (p7->pkcs7.content == NULL || p7->pkcs7.contentSz == 0 ||
  34709. p7->pkcs7.contentCRLF == 0)) {
  34710. /* store and adjust content line endings for CRLF if needed */
  34711. if (wolfSSL_PKCS7_final((PKCS7*)p7, in, flags) != 1) {
  34712. ret = 0;
  34713. }
  34714. }
  34715. if (ret > 0) {
  34716. /* Generate signedData bundle, DER in output (dynamic) */
  34717. if ((len = wolfSSL_i2d_PKCS7((PKCS7*)p7, &p7out)) == WOLFSSL_FAILURE) {
  34718. WOLFSSL_MSG("Error in wolfSSL_i2d_PKCS7");
  34719. ret = 0;
  34720. }
  34721. }
  34722. /* Base64 encode signedData bundle */
  34723. if (ret > 0) {
  34724. if (Base64_Encode(p7out, len, NULL, &sigBase64Len) != LENGTH_ONLY_E) {
  34725. ret = 0;
  34726. }
  34727. else {
  34728. sigBase64 = (byte*)XMALLOC(sigBase64Len, NULL,
  34729. DYNAMIC_TYPE_TMP_BUFFER);
  34730. if (sigBase64 == NULL) {
  34731. ret = 0;
  34732. }
  34733. }
  34734. }
  34735. if (ret > 0) {
  34736. XMEMSET(sigBase64, 0, sigBase64Len);
  34737. if (Base64_Encode(p7out, len, sigBase64, &sigBase64Len) < 0) {
  34738. WOLFSSL_MSG("Error in Base64_Encode of signature");
  34739. ret = 0;
  34740. }
  34741. }
  34742. /* build up SMIME message */
  34743. if (ret > 0) {
  34744. if (flags & PKCS7_DETACHED) {
  34745. /* generate random boundary */
  34746. if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
  34747. WOLFSSL_MSG("No RNG to use");
  34748. ret = 0;
  34749. }
  34750. /* no need to generate random byte for null terminator (size-1) */
  34751. if ((ret > 0) && (wc_RNG_GenerateBlock(&globalRNG, (byte*)boundary,
  34752. sizeof(boundary) - 1 ) != 0)) {
  34753. WOLFSSL_MSG("Error in wc_RNG_GenerateBlock");
  34754. ret = 0;
  34755. }
  34756. if (ret > 0) {
  34757. for (i = 0; i < (int)sizeof(boundary) - 1; i++) {
  34758. boundary[i] =
  34759. alphanum[boundary[i] % XSTR_SIZEOF(alphanum)];
  34760. }
  34761. boundary[sizeof(boundary)-1] = 0;
  34762. }
  34763. if (ret > 0) {
  34764. /* S/MIME header beginning */
  34765. ret = wolfSSL_BIO_printf(out,
  34766. "MIME-Version: 1.0\n"
  34767. "Content-Type: multipart/signed; "
  34768. "protocol=\"application/x-pkcs7-signature\"; "
  34769. "micalg=\"%s\"; "
  34770. "boundary=\"----%s\"\n\n"
  34771. "This is an S/MIME signed message\n\n"
  34772. "------%s\n",
  34773. wolfSSL_SMIME_HashOIDToString(p7->pkcs7.hashOID),
  34774. boundary, boundary);
  34775. }
  34776. if (ret > 0) {
  34777. /* S/MIME content */
  34778. ret = wolfSSL_BIO_write(out,
  34779. p7->pkcs7.content, p7->pkcs7.contentSz);
  34780. }
  34781. if (ret > 0) {
  34782. /* S/SMIME header end boundary */
  34783. ret = wolfSSL_BIO_printf(out,
  34784. "\n------%s\n", boundary);
  34785. }
  34786. if (ret > 0) {
  34787. /* Signature and header */
  34788. ret = wolfSSL_BIO_printf(out,
  34789. "Content-Type: application/x-pkcs7-signature; "
  34790. "name=\"smime.p7s\"\n"
  34791. "Content-Transfer-Encoding: base64\n"
  34792. "Content-Disposition: attachment; "
  34793. "filename=\"smime.p7s\"\n\n"
  34794. "%.*s\n" /* Base64 encoded signature */
  34795. "------%s--\n\n",
  34796. sigBase64Len, sigBase64,
  34797. boundary);
  34798. }
  34799. }
  34800. else {
  34801. p7TypeString = wolfSSL_SMIME_PKCS7TypeToString(p7->type);
  34802. if (p7TypeString == NULL) {
  34803. WOLFSSL_MSG("Unsupported PKCS7 SMIME type");
  34804. ret = 0;
  34805. }
  34806. if (ret > 0) {
  34807. /* not detached */
  34808. ret = wolfSSL_BIO_printf(out,
  34809. "MIME-Version: 1.0\n"
  34810. "Content-Disposition: attachment; "
  34811. "filename=\"smime.p7m\"\n"
  34812. "Content-Type: application/x-pkcs7-mime; "
  34813. "smime-type=%s; name=\"smime.p7m\"\n"
  34814. "Content-Transfer-Encoding: base64\n\n"
  34815. "%.*s\n" /* signature */,
  34816. p7TypeString, sigBase64Len, sigBase64);
  34817. }
  34818. }
  34819. }
  34820. if (p7out != NULL) {
  34821. XFREE(p7out, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  34822. }
  34823. if (sigBase64 != NULL) {
  34824. XFREE(sigBase64, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  34825. }
  34826. if (ret > 0) {
  34827. return WOLFSSL_SUCCESS;
  34828. }
  34829. return WOLFSSL_FAILURE;
  34830. }
  34831. #endif /* HAVE_SMIME */
  34832. #endif /* !NO_BIO */
  34833. #endif /* OPENSSL_ALL */
  34834. #endif /* HAVE_PKCS7 */
  34835. /*******************************************************************************
  34836. * END OF PKCS7 APIs
  34837. ******************************************************************************/
  34838. /*******************************************************************************
  34839. * START OF PKCS12 APIs
  34840. ******************************************************************************/
  34841. #ifdef OPENSSL_EXTRA
  34842. /* no-op function. Was initially used for adding encryption algorithms available
  34843. * for PKCS12 */
  34844. void wolfSSL_PKCS12_PBE_add(void)
  34845. {
  34846. WOLFSSL_ENTER("wolfSSL_PKCS12_PBE_add");
  34847. }
  34848. #if !defined(NO_FILESYSTEM)
  34849. WOLFSSL_X509_PKCS12 *wolfSSL_d2i_PKCS12_fp(XFILE fp,
  34850. WOLFSSL_X509_PKCS12 **pkcs12)
  34851. {
  34852. WOLFSSL_ENTER("wolfSSL_d2i_PKCS12_fp");
  34853. return (WOLFSSL_X509_PKCS12 *)wolfSSL_d2i_X509_fp_ex(fp, (void **)pkcs12,
  34854. PKCS12_TYPE);
  34855. }
  34856. #endif /* !NO_FILESYSTEM */
  34857. #endif /* OPENSSL_EXTRA */
  34858. #if defined(HAVE_PKCS12)
  34859. #ifdef OPENSSL_EXTRA
  34860. #if !defined(NO_ASN) && !defined(NO_PWDBASED)
  34861. #ifndef NO_BIO
  34862. WC_PKCS12* wolfSSL_d2i_PKCS12_bio(WOLFSSL_BIO* bio, WC_PKCS12** pkcs12)
  34863. {
  34864. WC_PKCS12* localPkcs12 = NULL;
  34865. unsigned char* mem = NULL;
  34866. long memSz;
  34867. int ret = -1;
  34868. WOLFSSL_ENTER("wolfSSL_d2i_PKCS12_bio");
  34869. if (bio == NULL) {
  34870. WOLFSSL_MSG("Bad Function Argument bio is NULL");
  34871. return NULL;
  34872. }
  34873. memSz = wolfSSL_BIO_get_len(bio);
  34874. if (memSz <= 0) {
  34875. return NULL;
  34876. }
  34877. mem = (unsigned char*)XMALLOC(memSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  34878. if (mem == NULL) {
  34879. return NULL;
  34880. }
  34881. if (mem != NULL) {
  34882. localPkcs12 = wc_PKCS12_new();
  34883. if (localPkcs12 == NULL) {
  34884. WOLFSSL_MSG("Memory error");
  34885. }
  34886. }
  34887. if (mem != NULL && localPkcs12 != NULL) {
  34888. if (wolfSSL_BIO_read(bio, mem, (int)memSz) == memSz) {
  34889. ret = wc_d2i_PKCS12(mem, (word32)memSz, localPkcs12);
  34890. if (ret < 0) {
  34891. WOLFSSL_MSG("Failed to get PKCS12 sequence");
  34892. }
  34893. }
  34894. else {
  34895. WOLFSSL_MSG("Failed to get data from bio struct");
  34896. }
  34897. }
  34898. /* cleanup */
  34899. if (mem != NULL)
  34900. XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  34901. if (ret < 0 && localPkcs12 != NULL) {
  34902. wc_PKCS12_free(localPkcs12);
  34903. localPkcs12 = NULL;
  34904. }
  34905. if (pkcs12 != NULL)
  34906. *pkcs12 = localPkcs12;
  34907. return localPkcs12;
  34908. }
  34909. /* Converts the PKCS12 to DER format and outputs it into bio.
  34910. *
  34911. * bio is the structure to hold output DER
  34912. * pkcs12 structure to create DER from
  34913. *
  34914. * return 1 for success or 0 if an error occurs
  34915. */
  34916. int wolfSSL_i2d_PKCS12_bio(WOLFSSL_BIO *bio, WC_PKCS12 *pkcs12)
  34917. {
  34918. int ret = WOLFSSL_FAILURE;
  34919. WOLFSSL_ENTER("wolfSSL_i2d_PKCS12_bio");
  34920. if ((bio != NULL) && (pkcs12 != NULL)) {
  34921. word32 certSz = 0;
  34922. byte *certDer = NULL;
  34923. certSz = wc_i2d_PKCS12(pkcs12, &certDer, NULL);
  34924. if ((certSz > 0) && (certDer != NULL)) {
  34925. if (wolfSSL_BIO_write(bio, certDer, certSz) == (int)certSz) {
  34926. ret = WOLFSSL_SUCCESS;
  34927. }
  34928. }
  34929. if (certDer != NULL) {
  34930. XFREE(certDer, NULL, DYNAMIC_TYPE_PKCS);
  34931. }
  34932. }
  34933. return ret;
  34934. }
  34935. #endif /* !NO_BIO */
  34936. /* Creates a new WC_PKCS12 structure
  34937. *
  34938. * pass password to use
  34939. * name friendlyName to use
  34940. * pkey private key to go into PKCS12 bundle
  34941. * cert certificate to go into PKCS12 bundle
  34942. * ca extra certificates that can be added to bundle. Can be NULL
  34943. * keyNID type of encryption to use on the key (-1 means no encryption)
  34944. * certNID type of encryption to use on the certificate
  34945. * itt number of iterations with encryption
  34946. * macItt number of iterations with mac creation
  34947. * keyType flag for signature and/or encryption key
  34948. *
  34949. * returns a pointer to a new WC_PKCS12 structure on success and NULL on fail
  34950. */
  34951. WC_PKCS12* wolfSSL_PKCS12_create(char* pass, char* name, WOLFSSL_EVP_PKEY* pkey,
  34952. WOLFSSL_X509* cert, WOLF_STACK_OF(WOLFSSL_X509)* ca, int keyNID,
  34953. int certNID, int itt, int macItt, int keyType)
  34954. {
  34955. WC_PKCS12* pkcs12;
  34956. WC_DerCertList* list = NULL;
  34957. word32 passSz;
  34958. byte* keyDer = NULL;
  34959. word32 keyDerSz;
  34960. byte* certDer;
  34961. int certDerSz;
  34962. WOLFSSL_ENTER("wolfSSL_PKCS12_create()");
  34963. if (pass == NULL || pkey == NULL || cert == NULL) {
  34964. WOLFSSL_LEAVE("wolfSSL_PKCS12_create()", BAD_FUNC_ARG);
  34965. return NULL;
  34966. }
  34967. passSz = (word32)XSTRLEN(pass);
  34968. keyDer = (byte*)pkey->pkey.ptr;
  34969. keyDerSz = pkey->pkey_sz;
  34970. certDer = (byte*)wolfSSL_X509_get_der(cert, &certDerSz);
  34971. if (certDer == NULL) {
  34972. return NULL;
  34973. }
  34974. if (ca != NULL) {
  34975. WC_DerCertList* cur;
  34976. unsigned long numCerts = ca->num;
  34977. byte* curDer;
  34978. int curDerSz = 0;
  34979. WOLFSSL_STACK* sk = ca;
  34980. while (numCerts > 0 && sk != NULL) {
  34981. cur = (WC_DerCertList*)XMALLOC(sizeof(WC_DerCertList), NULL,
  34982. DYNAMIC_TYPE_PKCS);
  34983. if (cur == NULL) {
  34984. wc_FreeCertList(list, NULL);
  34985. return NULL;
  34986. }
  34987. curDer = (byte*)wolfSSL_X509_get_der(sk->data.x509, &curDerSz);
  34988. if (curDer == NULL || curDerSz < 0) {
  34989. XFREE(cur, NULL, DYNAMIC_TYPE_PKCS);
  34990. wc_FreeCertList(list, NULL);
  34991. return NULL;
  34992. }
  34993. cur->buffer = (byte*)XMALLOC(curDerSz, NULL, DYNAMIC_TYPE_PKCS);
  34994. if (cur->buffer == NULL) {
  34995. XFREE(cur, NULL, DYNAMIC_TYPE_PKCS);
  34996. wc_FreeCertList(list, NULL);
  34997. return NULL;
  34998. }
  34999. XMEMCPY(cur->buffer, curDer, curDerSz);
  35000. cur->bufferSz = curDerSz;
  35001. cur->next = list;
  35002. list = cur;
  35003. sk = sk->next;
  35004. numCerts--;
  35005. }
  35006. }
  35007. pkcs12 = wc_PKCS12_create(pass, passSz, name, keyDer, keyDerSz,
  35008. certDer, certDerSz, list, keyNID, certNID, itt, macItt,
  35009. keyType, NULL);
  35010. if (ca != NULL) {
  35011. wc_FreeCertList(list, NULL);
  35012. }
  35013. return pkcs12;
  35014. }
  35015. /* return WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE on failure */
  35016. int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw,
  35017. WOLFSSL_EVP_PKEY** pkey, WOLFSSL_X509** cert,
  35018. WOLF_STACK_OF(WOLFSSL_X509)** ca)
  35019. {
  35020. void* heap = NULL;
  35021. int ret;
  35022. byte* certData = NULL;
  35023. word32 certDataSz;
  35024. byte* pk = NULL;
  35025. word32 pkSz;
  35026. WC_DerCertList* certList = NULL;
  35027. #ifdef WOLFSSL_SMALL_STACK
  35028. DecodedCert *DeCert;
  35029. #else
  35030. DecodedCert DeCert[1];
  35031. #endif
  35032. WOLFSSL_ENTER("wolfSSL_PKCS12_parse");
  35033. /* make sure we init return args */
  35034. if (pkey) *pkey = NULL;
  35035. if (cert) *cert = NULL;
  35036. if (ca) *ca = NULL;
  35037. if (pkcs12 == NULL || psw == NULL || pkey == NULL || cert == NULL) {
  35038. WOLFSSL_MSG("Bad argument value");
  35039. return WOLFSSL_FAILURE;
  35040. }
  35041. heap = wc_PKCS12_GetHeap(pkcs12);
  35042. if (ca == NULL) {
  35043. ret = wc_PKCS12_parse(pkcs12, psw, &pk, &pkSz, &certData, &certDataSz,
  35044. NULL);
  35045. }
  35046. else {
  35047. ret = wc_PKCS12_parse(pkcs12, psw, &pk, &pkSz, &certData, &certDataSz,
  35048. &certList);
  35049. }
  35050. if (ret < 0) {
  35051. WOLFSSL_LEAVE("wolfSSL_PKCS12_parse", ret);
  35052. return WOLFSSL_FAILURE;
  35053. }
  35054. #ifdef WOLFSSL_SMALL_STACK
  35055. DeCert = (DecodedCert *)XMALLOC(sizeof(*DeCert), heap,
  35056. DYNAMIC_TYPE_DCERT);
  35057. if (DeCert == NULL) {
  35058. WOLFSSL_MSG("out of memory");
  35059. return WOLFSSL_FAILURE;
  35060. }
  35061. #endif
  35062. /* Decode cert and place in X509 stack struct */
  35063. if (certList != NULL) {
  35064. WC_DerCertList* current = certList;
  35065. *ca = (WOLF_STACK_OF(WOLFSSL_X509)*)XMALLOC(
  35066. sizeof(WOLF_STACK_OF(WOLFSSL_X509)), heap, DYNAMIC_TYPE_X509);
  35067. if (*ca == NULL) {
  35068. if (pk != NULL) {
  35069. XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  35070. }
  35071. if (certData != NULL) {
  35072. XFREE(*cert, heap, DYNAMIC_TYPE_PKCS); *cert = NULL;
  35073. }
  35074. /* Free up WC_DerCertList and move on */
  35075. while (current != NULL) {
  35076. WC_DerCertList* next = current->next;
  35077. XFREE(current->buffer, heap, DYNAMIC_TYPE_PKCS);
  35078. XFREE(current, heap, DYNAMIC_TYPE_PKCS);
  35079. current = next;
  35080. }
  35081. ret = WOLFSSL_FAILURE;
  35082. goto out;
  35083. }
  35084. XMEMSET(*ca, 0, sizeof(WOLF_STACK_OF(WOLFSSL_X509)));
  35085. /* add list of DER certs as X509's to stack */
  35086. while (current != NULL) {
  35087. WC_DerCertList* toFree = current;
  35088. WOLFSSL_X509* x509;
  35089. x509 = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), heap,
  35090. DYNAMIC_TYPE_X509);
  35091. InitX509(x509, 1, heap);
  35092. InitDecodedCert(DeCert, current->buffer, current->bufferSz, heap);
  35093. if (ParseCertRelative(DeCert, CERT_TYPE, NO_VERIFY, NULL) != 0) {
  35094. WOLFSSL_MSG("Issue with parsing certificate");
  35095. FreeDecodedCert(DeCert);
  35096. wolfSSL_X509_free(x509);
  35097. }
  35098. else {
  35099. if (CopyDecodedToX509(x509, DeCert) != 0) {
  35100. WOLFSSL_MSG("Failed to copy decoded cert");
  35101. FreeDecodedCert(DeCert);
  35102. wolfSSL_X509_free(x509);
  35103. wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL;
  35104. if (pk != NULL) {
  35105. XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  35106. }
  35107. if (certData != NULL) {
  35108. XFREE(certData, heap, DYNAMIC_TYPE_PKCS);
  35109. }
  35110. /* Free up WC_DerCertList */
  35111. while (current != NULL) {
  35112. WC_DerCertList* next = current->next;
  35113. XFREE(current->buffer, heap, DYNAMIC_TYPE_PKCS);
  35114. XFREE(current, heap, DYNAMIC_TYPE_PKCS);
  35115. current = next;
  35116. }
  35117. ret = WOLFSSL_FAILURE;
  35118. goto out;
  35119. }
  35120. FreeDecodedCert(DeCert);
  35121. if (wolfSSL_sk_X509_push(*ca, x509) != 1) {
  35122. WOLFSSL_MSG("Failed to push x509 onto stack");
  35123. wolfSSL_X509_free(x509);
  35124. wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL;
  35125. if (pk != NULL) {
  35126. XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  35127. }
  35128. if (certData != NULL) {
  35129. XFREE(certData, heap, DYNAMIC_TYPE_PKCS);
  35130. }
  35131. /* Free up WC_DerCertList */
  35132. while (current != NULL) {
  35133. WC_DerCertList* next = current->next;
  35134. XFREE(current->buffer, heap, DYNAMIC_TYPE_PKCS);
  35135. XFREE(current, heap, DYNAMIC_TYPE_PKCS);
  35136. current = next;
  35137. }
  35138. ret = WOLFSSL_FAILURE;
  35139. goto out;
  35140. }
  35141. }
  35142. current = current->next;
  35143. XFREE(toFree->buffer, heap, DYNAMIC_TYPE_PKCS);
  35144. XFREE(toFree, heap, DYNAMIC_TYPE_PKCS);
  35145. }
  35146. }
  35147. /* Decode cert and place in X509 struct */
  35148. if (certData != NULL) {
  35149. *cert = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), heap,
  35150. DYNAMIC_TYPE_X509);
  35151. if (*cert == NULL) {
  35152. if (pk != NULL) {
  35153. XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  35154. }
  35155. if (ca != NULL) {
  35156. wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL;
  35157. }
  35158. XFREE(certData, heap, DYNAMIC_TYPE_PKCS);
  35159. ret = WOLFSSL_FAILURE;
  35160. goto out;
  35161. }
  35162. InitX509(*cert, 1, heap);
  35163. InitDecodedCert(DeCert, certData, certDataSz, heap);
  35164. if (ParseCertRelative(DeCert, CERT_TYPE, NO_VERIFY, NULL) != 0) {
  35165. WOLFSSL_MSG("Issue with parsing certificate");
  35166. }
  35167. if (CopyDecodedToX509(*cert, DeCert) != 0) {
  35168. WOLFSSL_MSG("Failed to copy decoded cert");
  35169. FreeDecodedCert(DeCert);
  35170. if (pk != NULL) {
  35171. XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  35172. }
  35173. if (ca != NULL) {
  35174. wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL;
  35175. }
  35176. wolfSSL_X509_free(*cert); *cert = NULL;
  35177. ret = WOLFSSL_FAILURE;
  35178. goto out;
  35179. }
  35180. FreeDecodedCert(DeCert);
  35181. XFREE(certData, heap, DYNAMIC_TYPE_PKCS);
  35182. }
  35183. /* get key type */
  35184. ret = BAD_STATE_E;
  35185. if (pk != NULL) { /* decode key if present */
  35186. *pkey = wolfSSL_EVP_PKEY_new_ex(heap);
  35187. if (*pkey == NULL) {
  35188. wolfSSL_X509_free(*cert); *cert = NULL;
  35189. if (ca != NULL) {
  35190. wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL;
  35191. }
  35192. XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  35193. ret = WOLFSSL_FAILURE;
  35194. goto out;
  35195. }
  35196. #ifndef NO_RSA
  35197. {
  35198. const unsigned char* pt = pk;
  35199. if (wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, pkey, &pt, pkSz) !=
  35200. NULL) {
  35201. ret = 0;
  35202. }
  35203. }
  35204. #endif /* NO_RSA */
  35205. #ifdef HAVE_ECC
  35206. if (ret != 0) { /* if is in fail state check if ECC key */
  35207. const unsigned char* pt = pk;
  35208. if (wolfSSL_d2i_PrivateKey(EVP_PKEY_EC, pkey, &pt, pkSz) !=
  35209. NULL) {
  35210. ret = 0;
  35211. }
  35212. }
  35213. #endif /* HAVE_ECC */
  35214. if (pk != NULL)
  35215. XFREE(pk, heap, DYNAMIC_TYPE_PKCS);
  35216. if (ret != 0) { /* if is in fail state and no PKEY then fail */
  35217. wolfSSL_X509_free(*cert); *cert = NULL;
  35218. if (ca != NULL) {
  35219. wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL;
  35220. }
  35221. wolfSSL_EVP_PKEY_free(*pkey); *pkey = NULL;
  35222. WOLFSSL_MSG("Bad PKCS12 key format");
  35223. ret = WOLFSSL_FAILURE;
  35224. goto out;
  35225. }
  35226. if (pkey != NULL && *pkey != NULL) {
  35227. (*pkey)->save_type = 0;
  35228. }
  35229. }
  35230. (void)ret;
  35231. (void)ca;
  35232. ret = WOLFSSL_SUCCESS;
  35233. out:
  35234. #ifdef WOLFSSL_SMALL_STACK
  35235. XFREE(DeCert, heap, DYNAMIC_TYPE_DCERT);
  35236. #endif
  35237. return ret;
  35238. }
  35239. int wolfSSL_PKCS12_verify_mac(WC_PKCS12 *pkcs12, const char *psw,
  35240. int pswLen)
  35241. {
  35242. WOLFSSL_ENTER("wolfSSL_PKCS12_verify_mac");
  35243. if (!pkcs12) {
  35244. return WOLFSSL_FAILURE;
  35245. }
  35246. return wc_PKCS12_verify_ex(pkcs12, (const byte*)psw, pswLen) == 0 ?
  35247. WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
  35248. }
  35249. #endif /* !NO_ASN && !NO_PWDBASED */
  35250. #endif /* OPENSSL_EXTRA */
  35251. #endif /* HAVE_PKCS12 */
  35252. /*******************************************************************************
  35253. * END OF PKCS12 APIs
  35254. ******************************************************************************/
  35255. #endif /* !NO_CERTS */
  35256. /*******************************************************************************
  35257. * BEGIN OPENSSL FIPS DRBG APIs
  35258. ******************************************************************************/
  35259. #if defined(OPENSSL_EXTRA) && !defined(WC_NO_RNG) && defined(HAVE_HASHDRBG)
  35260. int wolfSSL_FIPS_drbg_init(WOLFSSL_DRBG_CTX *ctx, int type, unsigned int flags)
  35261. {
  35262. int ret = WOLFSSL_FAILURE;
  35263. if (ctx != NULL) {
  35264. XMEMSET(ctx, 0, sizeof(WOLFSSL_DRBG_CTX));
  35265. ctx->type = type;
  35266. ctx->xflags = flags;
  35267. ctx->status = DRBG_STATUS_UNINITIALISED;
  35268. ret = WOLFSSL_SUCCESS;
  35269. }
  35270. return ret;
  35271. }
  35272. WOLFSSL_DRBG_CTX* wolfSSL_FIPS_drbg_new(int type, unsigned int flags)
  35273. {
  35274. int ret = WOLFSSL_FAILURE;
  35275. WOLFSSL_DRBG_CTX* ctx = (WOLFSSL_DRBG_CTX*)XMALLOC(sizeof(WOLFSSL_DRBG_CTX),
  35276. NULL, DYNAMIC_TYPE_OPENSSL);
  35277. ret = wolfSSL_FIPS_drbg_init(ctx, type, flags);
  35278. if (ret == WOLFSSL_SUCCESS && type != 0) {
  35279. ret = wolfSSL_FIPS_drbg_instantiate(ctx, NULL, 0);
  35280. }
  35281. if (ret != WOLFSSL_SUCCESS) {
  35282. WOLFSSL_ERROR(ret);
  35283. wolfSSL_FIPS_drbg_free(ctx);
  35284. ctx = NULL;
  35285. }
  35286. return ctx;
  35287. }
  35288. int wolfSSL_FIPS_drbg_instantiate(WOLFSSL_DRBG_CTX* ctx,
  35289. const unsigned char* pers, size_t perslen)
  35290. {
  35291. int ret = WOLFSSL_FAILURE;
  35292. if (ctx != NULL && ctx->rng == NULL) {
  35293. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
  35294. (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
  35295. ctx->rng = wc_rng_new((byte*)pers, (word32)perslen, NULL);
  35296. #else
  35297. ctx->rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  35298. if (ctx->rng != NULL) {
  35299. #if defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)
  35300. ret = wc_InitRngNonce(ctx->rng, (byte*)pers, (word32)perslen);
  35301. #else
  35302. ret = wc_InitRng(ctx->rng);
  35303. (void)pers;
  35304. (void)perslen;
  35305. #endif
  35306. if (ret != 0) {
  35307. WOLFSSL_ERROR(ret);
  35308. XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
  35309. ctx->rng = NULL;
  35310. }
  35311. }
  35312. #endif
  35313. }
  35314. if (ctx != NULL && ctx->rng != NULL) {
  35315. ctx->status = DRBG_STATUS_READY;
  35316. ret = WOLFSSL_SUCCESS;
  35317. }
  35318. return ret;
  35319. }
  35320. int wolfSSL_FIPS_drbg_set_callbacks(WOLFSSL_DRBG_CTX* ctx,
  35321. drbg_entropy_get entropy_get, drbg_entropy_clean entropy_clean,
  35322. size_t entropy_blocklen,
  35323. drbg_nonce_get none_get, drbg_nonce_clean nonce_clean)
  35324. {
  35325. int ret = WOLFSSL_FAILURE;
  35326. if (ctx != NULL) {
  35327. ctx->entropy_get = entropy_get;
  35328. ctx->entropy_clean = entropy_clean;
  35329. ctx->entropy_blocklen = entropy_blocklen;
  35330. ctx->none_get = none_get;
  35331. ctx->nonce_clean = nonce_clean;
  35332. ret = WOLFSSL_SUCCESS;
  35333. }
  35334. return ret;
  35335. }
  35336. void wolfSSL_FIPS_rand_add(const void* buf, int num, double entropy)
  35337. {
  35338. /* not implemented */
  35339. (void)buf;
  35340. (void)num;
  35341. (void)entropy;
  35342. }
  35343. int wolfSSL_FIPS_drbg_reseed(WOLFSSL_DRBG_CTX* ctx, const unsigned char* adin,
  35344. size_t adinlen)
  35345. {
  35346. int ret = WOLFSSL_FAILURE;
  35347. if (ctx != NULL && ctx->rng != NULL) {
  35348. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
  35349. (defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)))
  35350. if (wc_RNG_DRBG_Reseed(ctx->rng, adin, (word32)adinlen) == 0) {
  35351. ret = WOLFSSL_SUCCESS;
  35352. }
  35353. #else
  35354. ret = WOLFSSL_SUCCESS;
  35355. (void)adin;
  35356. (void)adinlen;
  35357. #endif
  35358. }
  35359. return ret;
  35360. }
  35361. int wolfSSL_FIPS_drbg_generate(WOLFSSL_DRBG_CTX* ctx, unsigned char* out,
  35362. size_t outlen, int prediction_resistance, const unsigned char* adin,
  35363. size_t adinlen)
  35364. {
  35365. int ret = WOLFSSL_FAILURE;
  35366. if (ctx != NULL && ctx->rng != NULL) {
  35367. ret = wc_RNG_GenerateBlock(ctx->rng, out, (word32)outlen);
  35368. if (ret == 0) {
  35369. ret = WOLFSSL_SUCCESS;
  35370. }
  35371. }
  35372. (void)prediction_resistance;
  35373. (void)adin;
  35374. (void)adinlen;
  35375. return ret;
  35376. }
  35377. int wolfSSL_FIPS_drbg_uninstantiate(WOLFSSL_DRBG_CTX *ctx)
  35378. {
  35379. if (ctx != NULL && ctx->rng != NULL) {
  35380. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
  35381. (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
  35382. wc_rng_free(ctx->rng);
  35383. #else
  35384. wc_FreeRng(ctx->rng);
  35385. XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
  35386. #endif
  35387. ctx->rng = NULL;
  35388. ctx->status = DRBG_STATUS_UNINITIALISED;
  35389. }
  35390. return WOLFSSL_SUCCESS;
  35391. }
  35392. void wolfSSL_FIPS_drbg_free(WOLFSSL_DRBG_CTX *ctx)
  35393. {
  35394. if (ctx != NULL) {
  35395. /* As saftey check if free'ing the default drbg, then mark global NULL.
  35396. * Technically the user should not call free on the default drbg. */
  35397. if (ctx == gDrbgDefCtx) {
  35398. gDrbgDefCtx = NULL;
  35399. }
  35400. wolfSSL_FIPS_drbg_uninstantiate(ctx);
  35401. XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
  35402. }
  35403. }
  35404. WOLFSSL_DRBG_CTX* wolfSSL_FIPS_get_default_drbg(void)
  35405. {
  35406. if (gDrbgDefCtx == NULL) {
  35407. gDrbgDefCtx = wolfSSL_FIPS_drbg_new(0, 0);
  35408. }
  35409. return gDrbgDefCtx;
  35410. }
  35411. void wolfSSL_FIPS_get_timevec(unsigned char* buf, unsigned long* pctr)
  35412. {
  35413. /* not implemented */
  35414. (void)buf;
  35415. (void)pctr;
  35416. }
  35417. void* wolfSSL_FIPS_drbg_get_app_data(WOLFSSL_DRBG_CTX *ctx)
  35418. {
  35419. if (ctx != NULL) {
  35420. return ctx->app_data;
  35421. }
  35422. return NULL;
  35423. }
  35424. void wolfSSL_FIPS_drbg_set_app_data(WOLFSSL_DRBG_CTX *ctx, void *app_data)
  35425. {
  35426. if (ctx != NULL) {
  35427. ctx->app_data = app_data;
  35428. }
  35429. }
  35430. #endif
  35431. /*******************************************************************************
  35432. * END OF OPENSSL FIPS DRBG APIs
  35433. ******************************************************************************/
  35434. #endif /* !WOLFCRYPT_ONLY */
  35435. /*******************************************************************************
  35436. * START OF CRYPTO-ONLY APIs
  35437. ******************************************************************************/
  35438. #if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
  35439. defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
  35440. defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
  35441. defined(WOLFSSL_HAPROXY)
  35442. #ifndef NO_SHA
  35443. /* One shot SHA1 hash of message.
  35444. *
  35445. * d message to hash
  35446. * n size of d buffer
  35447. * md buffer to hold digest. Should be SHA_DIGEST_SIZE.
  35448. *
  35449. * Note: if md is null then a static buffer of SHA_DIGEST_SIZE is used.
  35450. * When the static buffer is used this function is not thread safe.
  35451. *
  35452. * Returns a pointer to the message digest on success and NULL on failure.
  35453. */
  35454. unsigned char *wolfSSL_SHA1(const unsigned char *d, size_t n,
  35455. unsigned char *md)
  35456. {
  35457. static byte dig[WC_SHA_DIGEST_SIZE];
  35458. byte* ret = md;
  35459. wc_Sha sha;
  35460. WOLFSSL_ENTER("wolfSSL_SHA1");
  35461. if (wc_InitSha_ex(&sha, NULL, INVALID_DEVID) != 0) {
  35462. WOLFSSL_MSG("SHA1 Init failed");
  35463. return NULL;
  35464. }
  35465. if (wc_ShaUpdate(&sha, (const byte*)d, (word32)n) != 0) {
  35466. WOLFSSL_MSG("SHA1 Update failed");
  35467. return NULL;
  35468. }
  35469. if (md == NULL) {
  35470. WOLFSSL_MSG("STATIC BUFFER BEING USED. wolfSSL_SHA1 IS NOT "
  35471. "THREAD SAFE WHEN md == NULL");
  35472. ret = dig;
  35473. }
  35474. if (wc_ShaFinal(&sha, ret) != 0) {
  35475. WOLFSSL_MSG("SHA1 Final failed");
  35476. wc_ShaFree(&sha);
  35477. return NULL;
  35478. }
  35479. wc_ShaFree(&sha);
  35480. return ret;
  35481. }
  35482. #endif /* ! NO_SHA */
  35483. #ifdef WOLFSSL_SHA224
  35484. /* One shot SHA224 hash of message.
  35485. *
  35486. * d message to hash
  35487. * n size of d buffer
  35488. * md buffer to hold digest. Should be WC_SHA224_DIGEST_SIZE.
  35489. *
  35490. * Note: if md is null then a static buffer of WC_SHA256_DIGEST_SIZE is used.
  35491. * When the static buffer is used this function is not thread safe.
  35492. *
  35493. * Returns a pointer to the message digest on success and NULL on failure.
  35494. */
  35495. unsigned char *wolfSSL_SHA224(const unsigned char *d, size_t n,
  35496. unsigned char *md)
  35497. {
  35498. static byte dig[WC_SHA224_DIGEST_SIZE];
  35499. byte* ret = md;
  35500. wc_Sha256 sha;
  35501. WOLFSSL_ENTER("wolfSSL_SHA224");
  35502. if (wc_InitSha224_ex(&sha, NULL, INVALID_DEVID) != 0) {
  35503. WOLFSSL_MSG("SHA224 Init failed");
  35504. return NULL;
  35505. }
  35506. if (wc_Sha224Update(&sha, (const byte*)d, (word32)n) != 0) {
  35507. WOLFSSL_MSG("SHA224 Update failed");
  35508. return NULL;
  35509. }
  35510. if (md == NULL) {
  35511. WOLFSSL_MSG("STATIC BUFFER BEING USED. wolfSSL_SHA224 IS NOT "
  35512. "THREAD SAFE WHEN md == NULL");
  35513. ret = dig;
  35514. }
  35515. if (wc_Sha224Final(&sha, ret) != 0) {
  35516. WOLFSSL_MSG("SHA224 Final failed");
  35517. wc_Sha224Free(&sha);
  35518. return NULL;
  35519. }
  35520. wc_Sha224Free(&sha);
  35521. return ret;
  35522. }
  35523. #endif
  35524. #ifndef NO_SHA256
  35525. /* One shot SHA256 hash of message.
  35526. *
  35527. * d message to hash
  35528. * n size of d buffer
  35529. * md buffer to hold digest. Should be WC_SHA256_DIGEST_SIZE.
  35530. *
  35531. * Note: if md is null then a static buffer of WC_SHA256_DIGEST_SIZE is used.
  35532. * When the static buffer is used this function is not thread safe.
  35533. *
  35534. * Returns a pointer to the message digest on success and NULL on failure.
  35535. */
  35536. unsigned char *wolfSSL_SHA256(const unsigned char *d, size_t n,
  35537. unsigned char *md)
  35538. {
  35539. static byte dig[WC_SHA256_DIGEST_SIZE];
  35540. byte* ret = md;
  35541. wc_Sha256 sha;
  35542. WOLFSSL_ENTER("wolfSSL_SHA256");
  35543. if (wc_InitSha256_ex(&sha, NULL, INVALID_DEVID) != 0) {
  35544. WOLFSSL_MSG("SHA256 Init failed");
  35545. return NULL;
  35546. }
  35547. if (wc_Sha256Update(&sha, (const byte*)d, (word32)n) != 0) {
  35548. WOLFSSL_MSG("SHA256 Update failed");
  35549. return NULL;
  35550. }
  35551. if (md == NULL) {
  35552. WOLFSSL_MSG("STATIC BUFFER BEING USED. wolfSSL_SHA256 IS NOT "
  35553. "THREAD SAFE WHEN md == NULL");
  35554. ret = dig;
  35555. }
  35556. if (wc_Sha256Final(&sha, ret) != 0) {
  35557. WOLFSSL_MSG("SHA256 Final failed");
  35558. wc_Sha256Free(&sha);
  35559. return NULL;
  35560. }
  35561. wc_Sha256Free(&sha);
  35562. return ret;
  35563. }
  35564. #endif /* ! NO_SHA256 */
  35565. #ifdef WOLFSSL_SHA384
  35566. /* One shot SHA384 hash of message.
  35567. *
  35568. * d message to hash
  35569. * n size of d buffer
  35570. * md buffer to hold digest. Should be WC_SHA256_DIGEST_SIZE.
  35571. *
  35572. * Note: if md is null then a static buffer of WC_SHA256_DIGEST_SIZE is used.
  35573. * When the static buffer is used this function is not thread safe.
  35574. *
  35575. * Returns a pointer to the message digest on success and NULL on failure.
  35576. */
  35577. unsigned char *wolfSSL_SHA384(const unsigned char *d, size_t n,
  35578. unsigned char *md)
  35579. {
  35580. static byte dig[WC_SHA384_DIGEST_SIZE];
  35581. byte* ret = md;
  35582. wc_Sha384 sha;
  35583. WOLFSSL_ENTER("wolfSSL_SHA384");
  35584. if (wc_InitSha384_ex(&sha, NULL, INVALID_DEVID) != 0) {
  35585. WOLFSSL_MSG("SHA384 Init failed");
  35586. return NULL;
  35587. }
  35588. if (wc_Sha384Update(&sha, (const byte*)d, (word32)n) != 0) {
  35589. WOLFSSL_MSG("SHA384 Update failed");
  35590. return NULL;
  35591. }
  35592. if (md == NULL) {
  35593. WOLFSSL_MSG("STATIC BUFFER BEING USED. wolfSSL_SHA384 IS NOT "
  35594. "THREAD SAFE WHEN md == NULL");
  35595. ret = dig;
  35596. }
  35597. if (wc_Sha384Final(&sha, ret) != 0) {
  35598. WOLFSSL_MSG("SHA384 Final failed");
  35599. wc_Sha384Free(&sha);
  35600. return NULL;
  35601. }
  35602. wc_Sha384Free(&sha);
  35603. return ret;
  35604. }
  35605. #endif /* WOLFSSL_SHA384 */
  35606. #if defined(WOLFSSL_SHA512)
  35607. /* One shot SHA512 hash of message.
  35608. *
  35609. * d message to hash
  35610. * n size of d buffer
  35611. * md buffer to hold digest. Should be WC_SHA256_DIGEST_SIZE.
  35612. *
  35613. * Note: if md is null then a static buffer of WC_SHA256_DIGEST_SIZE is used.
  35614. * When the static buffer is used this function is not thread safe.
  35615. *
  35616. * Returns a pointer to the message digest on success and NULL on failure.
  35617. */
  35618. unsigned char *wolfSSL_SHA512(const unsigned char *d, size_t n,
  35619. unsigned char *md)
  35620. {
  35621. static byte dig[WC_SHA512_DIGEST_SIZE];
  35622. byte* ret = md;
  35623. wc_Sha512 sha;
  35624. WOLFSSL_ENTER("wolfSSL_SHA512");
  35625. if (wc_InitSha512_ex(&sha, NULL, INVALID_DEVID) != 0) {
  35626. WOLFSSL_MSG("SHA512 Init failed");
  35627. return NULL;
  35628. }
  35629. if (wc_Sha512Update(&sha, (const byte*)d, (word32)n) != 0) {
  35630. WOLFSSL_MSG("SHA512 Update failed");
  35631. return NULL;
  35632. }
  35633. if (md == NULL) {
  35634. WOLFSSL_MSG("STATIC BUFFER BEING USED. wolfSSL_SHA512 IS NOT "
  35635. "THREAD SAFE WHEN md == NULL");
  35636. ret = dig;
  35637. }
  35638. if (wc_Sha512Final(&sha, ret) != 0) {
  35639. WOLFSSL_MSG("SHA512 Final failed");
  35640. wc_Sha512Free(&sha);
  35641. return NULL;
  35642. }
  35643. wc_Sha512Free(&sha);
  35644. return ret;
  35645. }
  35646. #endif /* WOLFSSL_SHA512 */
  35647. #endif /* OPENSSL_EXTRA || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE ||
  35648. * HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */
  35649. /*******************************************************************************
  35650. * END OF CRYPTO-ONLY APIs
  35651. ******************************************************************************/