ssl_tls.c 315 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920
  1. /*
  2. * SSLv3/TLSv1 shared functions
  3. *
  4. * Copyright The Mbed TLS Contributors
  5. * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  6. *
  7. * This file is provided under the Apache License 2.0, or the
  8. * GNU General Public License v2.0 or later.
  9. *
  10. * **********
  11. * Apache License 2.0:
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  14. * not use this file except in compliance with the License.
  15. * You may obtain a copy of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. * See the License for the specific language governing permissions and
  23. * limitations under the License.
  24. *
  25. * **********
  26. *
  27. * **********
  28. * GNU General Public License v2.0 or later:
  29. *
  30. * This program is free software; you can redistribute it and/or modify
  31. * it under the terms of the GNU General Public License as published by
  32. * the Free Software Foundation; either version 2 of the License, or
  33. * (at your option) any later version.
  34. *
  35. * This program is distributed in the hope that it will be useful,
  36. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  37. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  38. * GNU General Public License for more details.
  39. *
  40. * You should have received a copy of the GNU General Public License along
  41. * with this program; if not, write to the Free Software Foundation, Inc.,
  42. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  43. *
  44. * **********
  45. */
  46. /*
  47. * The SSL 3.0 specification was drafted by Netscape in 1996,
  48. * and became an IETF standard in 1999.
  49. *
  50. * http://wp.netscape.com/eng/ssl3/
  51. * http://www.ietf.org/rfc/rfc2246.txt
  52. * http://www.ietf.org/rfc/rfc4346.txt
  53. */
  54. #if !defined(MBEDTLS_CONFIG_FILE)
  55. #include "mbedtls/config.h"
  56. #else
  57. #include MBEDTLS_CONFIG_FILE
  58. #endif
  59. #if defined(MBEDTLS_SSL_TLS_C)
  60. #if defined(MBEDTLS_PLATFORM_C)
  61. #include "mbedtls/platform.h"
  62. #else
  63. #include <stdlib.h>
  64. #define mbedtls_calloc calloc
  65. #define mbedtls_free free
  66. #endif
  67. #include "mbedtls/debug.h"
  68. #include "mbedtls/ssl.h"
  69. #include "mbedtls/ssl_internal.h"
  70. #include "mbedtls/platform_util.h"
  71. #include <string.h>
  72. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  73. #include "mbedtls/oid.h"
  74. #endif
  75. static void ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl );
  76. static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl );
  77. /* Length of the "epoch" field in the record header */
  78. static inline size_t ssl_ep_len( const mbedtls_ssl_context *ssl )
  79. {
  80. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  81. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  82. return( 2 );
  83. #else
  84. ((void) ssl);
  85. #endif
  86. return( 0 );
  87. }
  88. /*
  89. * Start a timer.
  90. * Passing millisecs = 0 cancels a running timer.
  91. */
  92. static void ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs )
  93. {
  94. if( ssl->f_set_timer == NULL )
  95. return;
  96. MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) );
  97. ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs );
  98. }
  99. /*
  100. * Return -1 is timer is expired, 0 if it isn't.
  101. */
  102. static int ssl_check_timer( mbedtls_ssl_context *ssl )
  103. {
  104. if( ssl->f_get_timer == NULL )
  105. return( 0 );
  106. if( ssl->f_get_timer( ssl->p_timer ) == 2 )
  107. {
  108. MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) );
  109. return( -1 );
  110. }
  111. return( 0 );
  112. }
  113. static void ssl_update_out_pointers( mbedtls_ssl_context *ssl,
  114. mbedtls_ssl_transform *transform );
  115. static void ssl_update_in_pointers( mbedtls_ssl_context *ssl,
  116. mbedtls_ssl_transform *transform );
  117. #define SSL_DONT_FORCE_FLUSH 0
  118. #define SSL_FORCE_FLUSH 1
  119. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  120. /* Forward declarations for functions related to message buffering. */
  121. static void ssl_buffering_free( mbedtls_ssl_context *ssl );
  122. static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
  123. uint8_t slot );
  124. static void ssl_free_buffered_record( mbedtls_ssl_context *ssl );
  125. static int ssl_load_buffered_message( mbedtls_ssl_context *ssl );
  126. static int ssl_load_buffered_record( mbedtls_ssl_context *ssl );
  127. static int ssl_buffer_message( mbedtls_ssl_context *ssl );
  128. static int ssl_buffer_future_record( mbedtls_ssl_context *ssl );
  129. static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl );
  130. static size_t ssl_get_current_mtu( const mbedtls_ssl_context *ssl );
  131. static size_t ssl_get_maximum_datagram_size( mbedtls_ssl_context const *ssl )
  132. {
  133. size_t mtu = ssl_get_current_mtu( ssl );
  134. if( mtu != 0 && mtu < MBEDTLS_SSL_OUT_BUFFER_LEN )
  135. return( mtu );
  136. return( MBEDTLS_SSL_OUT_BUFFER_LEN );
  137. }
  138. static int ssl_get_remaining_space_in_datagram( mbedtls_ssl_context const *ssl )
  139. {
  140. size_t const bytes_written = ssl->out_left;
  141. size_t const mtu = ssl_get_maximum_datagram_size( ssl );
  142. /* Double-check that the write-index hasn't gone
  143. * past what we can transmit in a single datagram. */
  144. if( bytes_written > mtu )
  145. {
  146. /* Should never happen... */
  147. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  148. }
  149. return( (int) ( mtu - bytes_written ) );
  150. }
  151. static int ssl_get_remaining_payload_in_datagram( mbedtls_ssl_context const *ssl )
  152. {
  153. int ret;
  154. size_t remaining, expansion;
  155. size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
  156. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  157. const size_t mfl = mbedtls_ssl_get_max_frag_len( ssl );
  158. if( max_len > mfl )
  159. max_len = mfl;
  160. /* By the standard (RFC 6066 Sect. 4), the MFL extension
  161. * only limits the maximum record payload size, so in theory
  162. * we would be allowed to pack multiple records of payload size
  163. * MFL into a single datagram. However, this would mean that there's
  164. * no way to explicitly communicate MTU restrictions to the peer.
  165. *
  166. * The following reduction of max_len makes sure that we never
  167. * write datagrams larger than MFL + Record Expansion Overhead.
  168. */
  169. if( max_len <= ssl->out_left )
  170. return( 0 );
  171. max_len -= ssl->out_left;
  172. #endif
  173. ret = ssl_get_remaining_space_in_datagram( ssl );
  174. if( ret < 0 )
  175. return( ret );
  176. remaining = (size_t) ret;
  177. ret = mbedtls_ssl_get_record_expansion( ssl );
  178. if( ret < 0 )
  179. return( ret );
  180. expansion = (size_t) ret;
  181. if( remaining <= expansion )
  182. return( 0 );
  183. remaining -= expansion;
  184. if( remaining >= max_len )
  185. remaining = max_len;
  186. return( (int) remaining );
  187. }
  188. /*
  189. * Double the retransmit timeout value, within the allowed range,
  190. * returning -1 if the maximum value has already been reached.
  191. */
  192. static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl )
  193. {
  194. uint32_t new_timeout;
  195. if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max )
  196. return( -1 );
  197. /* Implement the final paragraph of RFC 6347 section 4.1.1.1
  198. * in the following way: after the initial transmission and a first
  199. * retransmission, back off to a temporary estimated MTU of 508 bytes.
  200. * This value is guaranteed to be deliverable (if not guaranteed to be
  201. * delivered) of any compliant IPv4 (and IPv6) network, and should work
  202. * on most non-IP stacks too. */
  203. if( ssl->handshake->retransmit_timeout != ssl->conf->hs_timeout_min )
  204. {
  205. ssl->handshake->mtu = 508;
  206. MBEDTLS_SSL_DEBUG_MSG( 2, ( "mtu autoreduction to %d bytes", ssl->handshake->mtu ) );
  207. }
  208. new_timeout = 2 * ssl->handshake->retransmit_timeout;
  209. /* Avoid arithmetic overflow and range overflow */
  210. if( new_timeout < ssl->handshake->retransmit_timeout ||
  211. new_timeout > ssl->conf->hs_timeout_max )
  212. {
  213. new_timeout = ssl->conf->hs_timeout_max;
  214. }
  215. ssl->handshake->retransmit_timeout = new_timeout;
  216. MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
  217. ssl->handshake->retransmit_timeout ) );
  218. return( 0 );
  219. }
  220. static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl )
  221. {
  222. ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min;
  223. MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
  224. ssl->handshake->retransmit_timeout ) );
  225. }
  226. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  227. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  228. /*
  229. * Convert max_fragment_length codes to length.
  230. * RFC 6066 says:
  231. * enum{
  232. * 2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)
  233. * } MaxFragmentLength;
  234. * and we add 0 -> extension unused
  235. */
  236. static unsigned int ssl_mfl_code_to_length( int mfl )
  237. {
  238. switch( mfl )
  239. {
  240. case MBEDTLS_SSL_MAX_FRAG_LEN_NONE:
  241. return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );
  242. case MBEDTLS_SSL_MAX_FRAG_LEN_512:
  243. return 512;
  244. case MBEDTLS_SSL_MAX_FRAG_LEN_1024:
  245. return 1024;
  246. case MBEDTLS_SSL_MAX_FRAG_LEN_2048:
  247. return 2048;
  248. case MBEDTLS_SSL_MAX_FRAG_LEN_4096:
  249. return 4096;
  250. default:
  251. return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );
  252. }
  253. }
  254. #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
  255. #if defined(MBEDTLS_SSL_CLI_C)
  256. static int ssl_session_copy( mbedtls_ssl_session *dst, const mbedtls_ssl_session *src )
  257. {
  258. mbedtls_ssl_session_free( dst );
  259. memcpy( dst, src, sizeof( mbedtls_ssl_session ) );
  260. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  261. if( src->peer_cert != NULL )
  262. {
  263. int ret;
  264. dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) );
  265. if( dst->peer_cert == NULL )
  266. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  267. mbedtls_x509_crt_init( dst->peer_cert );
  268. if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p,
  269. src->peer_cert->raw.len ) ) != 0 )
  270. {
  271. mbedtls_free( dst->peer_cert );
  272. dst->peer_cert = NULL;
  273. return( ret );
  274. }
  275. }
  276. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  277. #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
  278. if( src->ticket != NULL )
  279. {
  280. dst->ticket = mbedtls_calloc( 1, src->ticket_len );
  281. if( dst->ticket == NULL )
  282. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  283. memcpy( dst->ticket, src->ticket, src->ticket_len );
  284. }
  285. #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
  286. return( 0 );
  287. }
  288. #endif /* MBEDTLS_SSL_CLI_C */
  289. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  290. int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl,
  291. const unsigned char *key_enc, const unsigned char *key_dec,
  292. size_t keylen,
  293. const unsigned char *iv_enc, const unsigned char *iv_dec,
  294. size_t ivlen,
  295. const unsigned char *mac_enc, const unsigned char *mac_dec,
  296. size_t maclen ) = NULL;
  297. int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL;
  298. int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL;
  299. int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL;
  300. int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL;
  301. int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL;
  302. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  303. /*
  304. * Key material generation
  305. */
  306. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  307. static int ssl3_prf( const unsigned char *secret, size_t slen,
  308. const char *label,
  309. const unsigned char *random, size_t rlen,
  310. unsigned char *dstbuf, size_t dlen )
  311. {
  312. int ret = 0;
  313. size_t i;
  314. mbedtls_md5_context md5;
  315. mbedtls_sha1_context sha1;
  316. unsigned char padding[16];
  317. unsigned char sha1sum[20];
  318. ((void)label);
  319. mbedtls_md5_init( &md5 );
  320. mbedtls_sha1_init( &sha1 );
  321. /*
  322. * SSLv3:
  323. * block =
  324. * MD5( secret + SHA1( 'A' + secret + random ) ) +
  325. * MD5( secret + SHA1( 'BB' + secret + random ) ) +
  326. * MD5( secret + SHA1( 'CCC' + secret + random ) ) +
  327. * ...
  328. */
  329. for( i = 0; i < dlen / 16; i++ )
  330. {
  331. memset( padding, (unsigned char) ('A' + i), 1 + i );
  332. if( ( ret = mbedtls_sha1_starts_ret( &sha1 ) ) != 0 )
  333. goto exit;
  334. if( ( ret = mbedtls_sha1_update_ret( &sha1, padding, 1 + i ) ) != 0 )
  335. goto exit;
  336. if( ( ret = mbedtls_sha1_update_ret( &sha1, secret, slen ) ) != 0 )
  337. goto exit;
  338. if( ( ret = mbedtls_sha1_update_ret( &sha1, random, rlen ) ) != 0 )
  339. goto exit;
  340. if( ( ret = mbedtls_sha1_finish_ret( &sha1, sha1sum ) ) != 0 )
  341. goto exit;
  342. if( ( ret = mbedtls_md5_starts_ret( &md5 ) ) != 0 )
  343. goto exit;
  344. if( ( ret = mbedtls_md5_update_ret( &md5, secret, slen ) ) != 0 )
  345. goto exit;
  346. if( ( ret = mbedtls_md5_update_ret( &md5, sha1sum, 20 ) ) != 0 )
  347. goto exit;
  348. if( ( ret = mbedtls_md5_finish_ret( &md5, dstbuf + i * 16 ) ) != 0 )
  349. goto exit;
  350. }
  351. exit:
  352. mbedtls_md5_free( &md5 );
  353. mbedtls_sha1_free( &sha1 );
  354. mbedtls_platform_zeroize( padding, sizeof( padding ) );
  355. mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );
  356. return( ret );
  357. }
  358. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  359. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  360. static int tls1_prf( const unsigned char *secret, size_t slen,
  361. const char *label,
  362. const unsigned char *random, size_t rlen,
  363. unsigned char *dstbuf, size_t dlen )
  364. {
  365. size_t nb, hs;
  366. size_t i, j, k;
  367. const unsigned char *S1, *S2;
  368. unsigned char tmp[128];
  369. unsigned char h_i[20];
  370. const mbedtls_md_info_t *md_info;
  371. mbedtls_md_context_t md_ctx;
  372. int ret;
  373. mbedtls_md_init( &md_ctx );
  374. if( sizeof( tmp ) < 20 + strlen( label ) + rlen )
  375. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  376. hs = ( slen + 1 ) / 2;
  377. S1 = secret;
  378. S2 = secret + slen - hs;
  379. nb = strlen( label );
  380. memcpy( tmp + 20, label, nb );
  381. memcpy( tmp + 20 + nb, random, rlen );
  382. nb += rlen;
  383. /*
  384. * First compute P_md5(secret,label+random)[0..dlen]
  385. */
  386. if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL )
  387. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  388. if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
  389. return( ret );
  390. mbedtls_md_hmac_starts( &md_ctx, S1, hs );
  391. mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
  392. mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
  393. for( i = 0; i < dlen; i += 16 )
  394. {
  395. mbedtls_md_hmac_reset ( &md_ctx );
  396. mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb );
  397. mbedtls_md_hmac_finish( &md_ctx, h_i );
  398. mbedtls_md_hmac_reset ( &md_ctx );
  399. mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 );
  400. mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
  401. k = ( i + 16 > dlen ) ? dlen % 16 : 16;
  402. for( j = 0; j < k; j++ )
  403. dstbuf[i + j] = h_i[j];
  404. }
  405. mbedtls_md_free( &md_ctx );
  406. /*
  407. * XOR out with P_sha1(secret,label+random)[0..dlen]
  408. */
  409. if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL )
  410. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  411. if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
  412. return( ret );
  413. mbedtls_md_hmac_starts( &md_ctx, S2, hs );
  414. mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
  415. mbedtls_md_hmac_finish( &md_ctx, tmp );
  416. for( i = 0; i < dlen; i += 20 )
  417. {
  418. mbedtls_md_hmac_reset ( &md_ctx );
  419. mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb );
  420. mbedtls_md_hmac_finish( &md_ctx, h_i );
  421. mbedtls_md_hmac_reset ( &md_ctx );
  422. mbedtls_md_hmac_update( &md_ctx, tmp, 20 );
  423. mbedtls_md_hmac_finish( &md_ctx, tmp );
  424. k = ( i + 20 > dlen ) ? dlen % 20 : 20;
  425. for( j = 0; j < k; j++ )
  426. dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] );
  427. }
  428. mbedtls_md_free( &md_ctx );
  429. mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
  430. mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
  431. return( 0 );
  432. }
  433. #endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */
  434. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  435. static int tls_prf_generic( mbedtls_md_type_t md_type,
  436. const unsigned char *secret, size_t slen,
  437. const char *label,
  438. const unsigned char *random, size_t rlen,
  439. unsigned char *dstbuf, size_t dlen )
  440. {
  441. size_t nb;
  442. size_t i, j, k, md_len;
  443. unsigned char tmp[128];
  444. unsigned char h_i[MBEDTLS_MD_MAX_SIZE];
  445. const mbedtls_md_info_t *md_info;
  446. mbedtls_md_context_t md_ctx;
  447. int ret;
  448. mbedtls_md_init( &md_ctx );
  449. if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL )
  450. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  451. md_len = mbedtls_md_get_size( md_info );
  452. if( sizeof( tmp ) < md_len + strlen( label ) + rlen )
  453. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  454. nb = strlen( label );
  455. memcpy( tmp + md_len, label, nb );
  456. memcpy( tmp + md_len + nb, random, rlen );
  457. nb += rlen;
  458. /*
  459. * Compute P_<hash>(secret, label + random)[0..dlen]
  460. */
  461. if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
  462. return( ret );
  463. mbedtls_md_hmac_starts( &md_ctx, secret, slen );
  464. mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb );
  465. mbedtls_md_hmac_finish( &md_ctx, tmp );
  466. for( i = 0; i < dlen; i += md_len )
  467. {
  468. mbedtls_md_hmac_reset ( &md_ctx );
  469. mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb );
  470. mbedtls_md_hmac_finish( &md_ctx, h_i );
  471. mbedtls_md_hmac_reset ( &md_ctx );
  472. mbedtls_md_hmac_update( &md_ctx, tmp, md_len );
  473. mbedtls_md_hmac_finish( &md_ctx, tmp );
  474. k = ( i + md_len > dlen ) ? dlen % md_len : md_len;
  475. for( j = 0; j < k; j++ )
  476. dstbuf[i + j] = h_i[j];
  477. }
  478. mbedtls_md_free( &md_ctx );
  479. mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
  480. mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
  481. return( 0 );
  482. }
  483. #if defined(MBEDTLS_SHA256_C)
  484. static int tls_prf_sha256( const unsigned char *secret, size_t slen,
  485. const char *label,
  486. const unsigned char *random, size_t rlen,
  487. unsigned char *dstbuf, size_t dlen )
  488. {
  489. return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen,
  490. label, random, rlen, dstbuf, dlen ) );
  491. }
  492. #endif /* MBEDTLS_SHA256_C */
  493. #if defined(MBEDTLS_SHA512_C)
  494. static int tls_prf_sha384( const unsigned char *secret, size_t slen,
  495. const char *label,
  496. const unsigned char *random, size_t rlen,
  497. unsigned char *dstbuf, size_t dlen )
  498. {
  499. return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen,
  500. label, random, rlen, dstbuf, dlen ) );
  501. }
  502. #endif /* MBEDTLS_SHA512_C */
  503. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  504. static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t );
  505. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  506. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  507. static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t );
  508. #endif
  509. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  510. static void ssl_calc_verify_ssl( mbedtls_ssl_context *, unsigned char * );
  511. static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int );
  512. #endif
  513. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  514. static void ssl_calc_verify_tls( mbedtls_ssl_context *, unsigned char * );
  515. static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int );
  516. #endif
  517. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  518. #if defined(MBEDTLS_SHA256_C)
  519. static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t );
  520. static void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *, unsigned char * );
  521. static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int );
  522. #endif
  523. #if defined(MBEDTLS_SHA512_C)
  524. static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t );
  525. static void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *, unsigned char * );
  526. static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int );
  527. #endif
  528. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  529. int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
  530. {
  531. int ret = 0;
  532. unsigned char tmp[64];
  533. unsigned char keyblk[256];
  534. unsigned char *key1;
  535. unsigned char *key2;
  536. unsigned char *mac_enc;
  537. unsigned char *mac_dec;
  538. size_t mac_key_len;
  539. size_t iv_copy_len;
  540. const mbedtls_cipher_info_t *cipher_info;
  541. const mbedtls_md_info_t *md_info;
  542. mbedtls_ssl_session *session = ssl->session_negotiate;
  543. mbedtls_ssl_transform *transform = ssl->transform_negotiate;
  544. mbedtls_ssl_handshake_params *handshake = ssl->handshake;
  545. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
  546. cipher_info = mbedtls_cipher_info_from_type( transform->ciphersuite_info->cipher );
  547. if( cipher_info == NULL )
  548. {
  549. MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %d not found",
  550. transform->ciphersuite_info->cipher ) );
  551. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  552. }
  553. md_info = mbedtls_md_info_from_type( transform->ciphersuite_info->mac );
  554. if( md_info == NULL )
  555. {
  556. MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %d not found",
  557. transform->ciphersuite_info->mac ) );
  558. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  559. }
  560. /*
  561. * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions
  562. */
  563. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  564. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  565. {
  566. handshake->tls_prf = ssl3_prf;
  567. handshake->calc_verify = ssl_calc_verify_ssl;
  568. handshake->calc_finished = ssl_calc_finished_ssl;
  569. }
  570. else
  571. #endif
  572. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  573. if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
  574. {
  575. handshake->tls_prf = tls1_prf;
  576. handshake->calc_verify = ssl_calc_verify_tls;
  577. handshake->calc_finished = ssl_calc_finished_tls;
  578. }
  579. else
  580. #endif
  581. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  582. #if defined(MBEDTLS_SHA512_C)
  583. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
  584. transform->ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
  585. {
  586. handshake->tls_prf = tls_prf_sha384;
  587. handshake->calc_verify = ssl_calc_verify_tls_sha384;
  588. handshake->calc_finished = ssl_calc_finished_tls_sha384;
  589. }
  590. else
  591. #endif
  592. #if defined(MBEDTLS_SHA256_C)
  593. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  594. {
  595. handshake->tls_prf = tls_prf_sha256;
  596. handshake->calc_verify = ssl_calc_verify_tls_sha256;
  597. handshake->calc_finished = ssl_calc_finished_tls_sha256;
  598. }
  599. else
  600. #endif
  601. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  602. {
  603. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  604. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  605. }
  606. /*
  607. * SSLv3:
  608. * master =
  609. * MD5( premaster + SHA1( 'A' + premaster + randbytes ) ) +
  610. * MD5( premaster + SHA1( 'BB' + premaster + randbytes ) ) +
  611. * MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )
  612. *
  613. * TLSv1+:
  614. * master = PRF( premaster, "master secret", randbytes )[0..47]
  615. */
  616. if( handshake->resume == 0 )
  617. {
  618. MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster,
  619. handshake->pmslen );
  620. #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
  621. if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED )
  622. {
  623. unsigned char session_hash[48];
  624. size_t hash_len;
  625. MBEDTLS_SSL_DEBUG_MSG( 3, ( "using extended master secret" ) );
  626. ssl->handshake->calc_verify( ssl, session_hash );
  627. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  628. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  629. {
  630. #if defined(MBEDTLS_SHA512_C)
  631. if( ssl->transform_negotiate->ciphersuite_info->mac ==
  632. MBEDTLS_MD_SHA384 )
  633. {
  634. hash_len = 48;
  635. }
  636. else
  637. #endif
  638. hash_len = 32;
  639. }
  640. else
  641. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  642. hash_len = 36;
  643. MBEDTLS_SSL_DEBUG_BUF( 3, "session hash", session_hash, hash_len );
  644. ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
  645. "extended master secret",
  646. session_hash, hash_len,
  647. session->master, 48 );
  648. if( ret != 0 )
  649. {
  650. MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
  651. return( ret );
  652. }
  653. }
  654. else
  655. #endif
  656. ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
  657. "master secret",
  658. handshake->randbytes, 64,
  659. session->master, 48 );
  660. if( ret != 0 )
  661. {
  662. MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
  663. return( ret );
  664. }
  665. mbedtls_platform_zeroize( handshake->premaster,
  666. sizeof(handshake->premaster) );
  667. }
  668. else
  669. MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );
  670. /*
  671. * Swap the client and server random values.
  672. */
  673. memcpy( tmp, handshake->randbytes, 64 );
  674. memcpy( handshake->randbytes, tmp + 32, 32 );
  675. memcpy( handshake->randbytes + 32, tmp, 32 );
  676. mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
  677. /*
  678. * SSLv3:
  679. * key block =
  680. * MD5( master + SHA1( 'A' + master + randbytes ) ) +
  681. * MD5( master + SHA1( 'BB' + master + randbytes ) ) +
  682. * MD5( master + SHA1( 'CCC' + master + randbytes ) ) +
  683. * MD5( master + SHA1( 'DDDD' + master + randbytes ) ) +
  684. * ...
  685. *
  686. * TLSv1:
  687. * key block = PRF( master, "key expansion", randbytes )
  688. */
  689. ret = handshake->tls_prf( session->master, 48, "key expansion",
  690. handshake->randbytes, 64, keyblk, 256 );
  691. if( ret != 0 )
  692. {
  693. MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
  694. return( ret );
  695. }
  696. MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s",
  697. mbedtls_ssl_get_ciphersuite_name( session->ciphersuite ) ) );
  698. MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", session->master, 48 );
  699. MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 );
  700. MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );
  701. mbedtls_platform_zeroize( handshake->randbytes,
  702. sizeof( handshake->randbytes ) );
  703. /*
  704. * Determine the appropriate key, IV and MAC length.
  705. */
  706. transform->keylen = cipher_info->key_bitlen / 8;
  707. if( cipher_info->mode == MBEDTLS_MODE_GCM ||
  708. cipher_info->mode == MBEDTLS_MODE_CCM ||
  709. cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
  710. {
  711. size_t taglen, explicit_ivlen;
  712. transform->maclen = 0;
  713. mac_key_len = 0;
  714. /* All modes haves 96-bit IVs;
  715. * GCM and CCM has 4 implicit and 8 explicit bytes
  716. * ChachaPoly has all 12 bytes implicit
  717. */
  718. transform->ivlen = 12;
  719. if( cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
  720. transform->fixed_ivlen = 12;
  721. else
  722. transform->fixed_ivlen = 4;
  723. /* All modes have 128-bit tags, except CCM_8 (ciphersuite flag) */
  724. taglen = transform->ciphersuite_info->flags &
  725. MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
  726. /* Minimum length of encrypted record */
  727. explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
  728. transform->minlen = explicit_ivlen + taglen;
  729. }
  730. else
  731. {
  732. /* Initialize HMAC contexts */
  733. if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 ||
  734. ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 )
  735. {
  736. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
  737. return( ret );
  738. }
  739. /* Get MAC length */
  740. mac_key_len = mbedtls_md_get_size( md_info );
  741. transform->maclen = mac_key_len;
  742. #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
  743. /*
  744. * If HMAC is to be truncated, we shall keep the leftmost bytes,
  745. * (rfc 6066 page 13 or rfc 2104 section 4),
  746. * so we only need to adjust the length here.
  747. */
  748. if( session->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
  749. {
  750. transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN;
  751. #if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT)
  752. /* Fall back to old, non-compliant version of the truncated
  753. * HMAC implementation which also truncates the key
  754. * (Mbed TLS versions from 1.3 to 2.6.0) */
  755. mac_key_len = transform->maclen;
  756. #endif
  757. }
  758. #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
  759. /* IV length */
  760. transform->ivlen = cipher_info->iv_size;
  761. /* Minimum length */
  762. if( cipher_info->mode == MBEDTLS_MODE_STREAM )
  763. transform->minlen = transform->maclen;
  764. else
  765. {
  766. /*
  767. * GenericBlockCipher:
  768. * 1. if EtM is in use: one block plus MAC
  769. * otherwise: * first multiple of blocklen greater than maclen
  770. * 2. IV except for SSL3 and TLS 1.0
  771. */
  772. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  773. if( session->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
  774. {
  775. transform->minlen = transform->maclen
  776. + cipher_info->block_size;
  777. }
  778. else
  779. #endif
  780. {
  781. transform->minlen = transform->maclen
  782. + cipher_info->block_size
  783. - transform->maclen % cipher_info->block_size;
  784. }
  785. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
  786. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
  787. ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_1 )
  788. ; /* No need to adjust minlen */
  789. else
  790. #endif
  791. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  792. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 ||
  793. ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  794. {
  795. transform->minlen += transform->ivlen;
  796. }
  797. else
  798. #endif
  799. {
  800. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  801. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  802. }
  803. }
  804. }
  805. MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
  806. transform->keylen, transform->minlen, transform->ivlen,
  807. transform->maclen ) );
  808. /*
  809. * Finally setup the cipher contexts, IVs and MAC secrets.
  810. */
  811. #if defined(MBEDTLS_SSL_CLI_C)
  812. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  813. {
  814. key1 = keyblk + mac_key_len * 2;
  815. key2 = keyblk + mac_key_len * 2 + transform->keylen;
  816. mac_enc = keyblk;
  817. mac_dec = keyblk + mac_key_len;
  818. /*
  819. * This is not used in TLS v1.1.
  820. */
  821. iv_copy_len = ( transform->fixed_ivlen ) ?
  822. transform->fixed_ivlen : transform->ivlen;
  823. memcpy( transform->iv_enc, key2 + transform->keylen, iv_copy_len );
  824. memcpy( transform->iv_dec, key2 + transform->keylen + iv_copy_len,
  825. iv_copy_len );
  826. }
  827. else
  828. #endif /* MBEDTLS_SSL_CLI_C */
  829. #if defined(MBEDTLS_SSL_SRV_C)
  830. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  831. {
  832. key1 = keyblk + mac_key_len * 2 + transform->keylen;
  833. key2 = keyblk + mac_key_len * 2;
  834. mac_enc = keyblk + mac_key_len;
  835. mac_dec = keyblk;
  836. /*
  837. * This is not used in TLS v1.1.
  838. */
  839. iv_copy_len = ( transform->fixed_ivlen ) ?
  840. transform->fixed_ivlen : transform->ivlen;
  841. memcpy( transform->iv_dec, key1 + transform->keylen, iv_copy_len );
  842. memcpy( transform->iv_enc, key1 + transform->keylen + iv_copy_len,
  843. iv_copy_len );
  844. }
  845. else
  846. #endif /* MBEDTLS_SSL_SRV_C */
  847. {
  848. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  849. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  850. }
  851. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  852. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  853. {
  854. if( mac_key_len > sizeof transform->mac_enc )
  855. {
  856. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  857. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  858. }
  859. memcpy( transform->mac_enc, mac_enc, mac_key_len );
  860. memcpy( transform->mac_dec, mac_dec, mac_key_len );
  861. }
  862. else
  863. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  864. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  865. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  866. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
  867. {
  868. /* For HMAC-based ciphersuites, initialize the HMAC transforms.
  869. For AEAD-based ciphersuites, there is nothing to do here. */
  870. if( mac_key_len != 0 )
  871. {
  872. mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, mac_key_len );
  873. mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, mac_key_len );
  874. }
  875. }
  876. else
  877. #endif
  878. {
  879. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  880. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  881. }
  882. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  883. if( mbedtls_ssl_hw_record_init != NULL )
  884. {
  885. MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) );
  886. if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, transform->keylen,
  887. transform->iv_enc, transform->iv_dec,
  888. iv_copy_len,
  889. mac_enc, mac_dec,
  890. mac_key_len ) ) != 0 )
  891. {
  892. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret );
  893. return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  894. }
  895. }
  896. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  897. #if defined(MBEDTLS_SSL_EXPORT_KEYS)
  898. if( ssl->conf->f_export_keys != NULL )
  899. {
  900. ssl->conf->f_export_keys( ssl->conf->p_export_keys,
  901. session->master, keyblk,
  902. mac_key_len, transform->keylen,
  903. iv_copy_len );
  904. }
  905. #endif
  906. if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,
  907. cipher_info ) ) != 0 )
  908. {
  909. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
  910. return( ret );
  911. }
  912. if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,
  913. cipher_info ) ) != 0 )
  914. {
  915. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
  916. return( ret );
  917. }
  918. if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1,
  919. cipher_info->key_bitlen,
  920. MBEDTLS_ENCRYPT ) ) != 0 )
  921. {
  922. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
  923. return( ret );
  924. }
  925. if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2,
  926. cipher_info->key_bitlen,
  927. MBEDTLS_DECRYPT ) ) != 0 )
  928. {
  929. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
  930. return( ret );
  931. }
  932. #if defined(MBEDTLS_CIPHER_MODE_CBC)
  933. if( cipher_info->mode == MBEDTLS_MODE_CBC )
  934. {
  935. if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc,
  936. MBEDTLS_PADDING_NONE ) ) != 0 )
  937. {
  938. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
  939. return( ret );
  940. }
  941. if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec,
  942. MBEDTLS_PADDING_NONE ) ) != 0 )
  943. {
  944. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
  945. return( ret );
  946. }
  947. }
  948. #endif /* MBEDTLS_CIPHER_MODE_CBC */
  949. mbedtls_platform_zeroize( keyblk, sizeof( keyblk ) );
  950. #if defined(MBEDTLS_ZLIB_SUPPORT)
  951. // Initialize compression
  952. //
  953. if( session->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
  954. {
  955. if( ssl->compress_buf == NULL )
  956. {
  957. MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) );
  958. ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );
  959. if( ssl->compress_buf == NULL )
  960. {
  961. MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
  962. MBEDTLS_SSL_COMPRESS_BUFFER_LEN ) );
  963. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  964. }
  965. }
  966. MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );
  967. memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
  968. memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
  969. if( deflateInit( &transform->ctx_deflate,
  970. Z_DEFAULT_COMPRESSION ) != Z_OK ||
  971. inflateInit( &transform->ctx_inflate ) != Z_OK )
  972. {
  973. MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
  974. return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
  975. }
  976. }
  977. #endif /* MBEDTLS_ZLIB_SUPPORT */
  978. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
  979. return( 0 );
  980. }
  981. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  982. void ssl_calc_verify_ssl( mbedtls_ssl_context *ssl, unsigned char *hash )
  983. {
  984. mbedtls_md5_context md5;
  985. mbedtls_sha1_context sha1;
  986. unsigned char pad_1[48];
  987. unsigned char pad_2[48];
  988. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
  989. mbedtls_md5_init( &md5 );
  990. mbedtls_sha1_init( &sha1 );
  991. mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
  992. mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
  993. memset( pad_1, 0x36, 48 );
  994. memset( pad_2, 0x5C, 48 );
  995. mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 );
  996. mbedtls_md5_update_ret( &md5, pad_1, 48 );
  997. mbedtls_md5_finish_ret( &md5, hash );
  998. mbedtls_md5_starts_ret( &md5 );
  999. mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 );
  1000. mbedtls_md5_update_ret( &md5, pad_2, 48 );
  1001. mbedtls_md5_update_ret( &md5, hash, 16 );
  1002. mbedtls_md5_finish_ret( &md5, hash );
  1003. mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 );
  1004. mbedtls_sha1_update_ret( &sha1, pad_1, 40 );
  1005. mbedtls_sha1_finish_ret( &sha1, hash + 16 );
  1006. mbedtls_sha1_starts_ret( &sha1 );
  1007. mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 );
  1008. mbedtls_sha1_update_ret( &sha1, pad_2, 40 );
  1009. mbedtls_sha1_update_ret( &sha1, hash + 16, 20 );
  1010. mbedtls_sha1_finish_ret( &sha1, hash + 16 );
  1011. MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
  1012. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
  1013. mbedtls_md5_free( &md5 );
  1014. mbedtls_sha1_free( &sha1 );
  1015. return;
  1016. }
  1017. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  1018. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  1019. void ssl_calc_verify_tls( mbedtls_ssl_context *ssl, unsigned char *hash )
  1020. {
  1021. mbedtls_md5_context md5;
  1022. mbedtls_sha1_context sha1;
  1023. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );
  1024. mbedtls_md5_init( &md5 );
  1025. mbedtls_sha1_init( &sha1 );
  1026. mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
  1027. mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
  1028. mbedtls_md5_finish_ret( &md5, hash );
  1029. mbedtls_sha1_finish_ret( &sha1, hash + 16 );
  1030. MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
  1031. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
  1032. mbedtls_md5_free( &md5 );
  1033. mbedtls_sha1_free( &sha1 );
  1034. return;
  1035. }
  1036. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
  1037. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1038. #if defined(MBEDTLS_SHA256_C)
  1039. void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *ssl, unsigned char *hash )
  1040. {
  1041. mbedtls_sha256_context sha256;
  1042. mbedtls_sha256_init( &sha256 );
  1043. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
  1044. mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
  1045. mbedtls_sha256_finish_ret( &sha256, hash );
  1046. MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 );
  1047. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
  1048. mbedtls_sha256_free( &sha256 );
  1049. return;
  1050. }
  1051. #endif /* MBEDTLS_SHA256_C */
  1052. #if defined(MBEDTLS_SHA512_C)
  1053. void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *ssl, unsigned char *hash )
  1054. {
  1055. mbedtls_sha512_context sha512;
  1056. mbedtls_sha512_init( &sha512 );
  1057. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );
  1058. mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
  1059. mbedtls_sha512_finish_ret( &sha512, hash );
  1060. MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 );
  1061. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
  1062. mbedtls_sha512_free( &sha512 );
  1063. return;
  1064. }
  1065. #endif /* MBEDTLS_SHA512_C */
  1066. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  1067. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
  1068. int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex )
  1069. {
  1070. unsigned char *p = ssl->handshake->premaster;
  1071. unsigned char *end = p + sizeof( ssl->handshake->premaster );
  1072. const unsigned char *psk = ssl->conf->psk;
  1073. size_t psk_len = ssl->conf->psk_len;
  1074. /* If the psk callback was called, use its result */
  1075. if( ssl->handshake->psk != NULL )
  1076. {
  1077. psk = ssl->handshake->psk;
  1078. psk_len = ssl->handshake->psk_len;
  1079. }
  1080. /*
  1081. * PMS = struct {
  1082. * opaque other_secret<0..2^16-1>;
  1083. * opaque psk<0..2^16-1>;
  1084. * };
  1085. * with "other_secret" depending on the particular key exchange
  1086. */
  1087. #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
  1088. if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK )
  1089. {
  1090. if( end - p < 2 )
  1091. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1092. *(p++) = (unsigned char)( psk_len >> 8 );
  1093. *(p++) = (unsigned char)( psk_len );
  1094. if( end < p || (size_t)( end - p ) < psk_len )
  1095. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1096. memset( p, 0, psk_len );
  1097. p += psk_len;
  1098. }
  1099. else
  1100. #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
  1101. #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
  1102. if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
  1103. {
  1104. /*
  1105. * other_secret already set by the ClientKeyExchange message,
  1106. * and is 48 bytes long
  1107. */
  1108. if( end - p < 2 )
  1109. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1110. *p++ = 0;
  1111. *p++ = 48;
  1112. p += 48;
  1113. }
  1114. else
  1115. #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
  1116. #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
  1117. if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
  1118. {
  1119. int ret;
  1120. size_t len;
  1121. /* Write length only when we know the actual value */
  1122. if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
  1123. p + 2, end - ( p + 2 ), &len,
  1124. ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
  1125. {
  1126. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
  1127. return( ret );
  1128. }
  1129. *(p++) = (unsigned char)( len >> 8 );
  1130. *(p++) = (unsigned char)( len );
  1131. p += len;
  1132. MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K );
  1133. }
  1134. else
  1135. #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
  1136. #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
  1137. if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
  1138. {
  1139. int ret;
  1140. size_t zlen;
  1141. if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen,
  1142. p + 2, end - ( p + 2 ),
  1143. ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
  1144. {
  1145. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
  1146. return( ret );
  1147. }
  1148. *(p++) = (unsigned char)( zlen >> 8 );
  1149. *(p++) = (unsigned char)( zlen );
  1150. p += zlen;
  1151. MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
  1152. MBEDTLS_DEBUG_ECDH_Z );
  1153. }
  1154. else
  1155. #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
  1156. {
  1157. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1158. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1159. }
  1160. /* opaque psk<0..2^16-1>; */
  1161. if( end - p < 2 )
  1162. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1163. *(p++) = (unsigned char)( psk_len >> 8 );
  1164. *(p++) = (unsigned char)( psk_len );
  1165. if( end < p || (size_t)( end - p ) < psk_len )
  1166. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1167. memcpy( p, psk, psk_len );
  1168. p += psk_len;
  1169. ssl->handshake->pmslen = p - ssl->handshake->premaster;
  1170. return( 0 );
  1171. }
  1172. #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
  1173. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  1174. /*
  1175. * SSLv3.0 MAC functions
  1176. */
  1177. #define SSL_MAC_MAX_BYTES 20 /* MD-5 or SHA-1 */
  1178. static void ssl_mac( mbedtls_md_context_t *md_ctx,
  1179. const unsigned char *secret,
  1180. const unsigned char *buf, size_t len,
  1181. const unsigned char *ctr, int type,
  1182. unsigned char out[SSL_MAC_MAX_BYTES] )
  1183. {
  1184. unsigned char header[11];
  1185. unsigned char padding[48];
  1186. int padlen;
  1187. int md_size = mbedtls_md_get_size( md_ctx->md_info );
  1188. int md_type = mbedtls_md_get_type( md_ctx->md_info );
  1189. /* Only MD5 and SHA-1 supported */
  1190. if( md_type == MBEDTLS_MD_MD5 )
  1191. padlen = 48;
  1192. else
  1193. padlen = 40;
  1194. memcpy( header, ctr, 8 );
  1195. header[ 8] = (unsigned char) type;
  1196. header[ 9] = (unsigned char)( len >> 8 );
  1197. header[10] = (unsigned char)( len );
  1198. memset( padding, 0x36, padlen );
  1199. mbedtls_md_starts( md_ctx );
  1200. mbedtls_md_update( md_ctx, secret, md_size );
  1201. mbedtls_md_update( md_ctx, padding, padlen );
  1202. mbedtls_md_update( md_ctx, header, 11 );
  1203. mbedtls_md_update( md_ctx, buf, len );
  1204. mbedtls_md_finish( md_ctx, out );
  1205. memset( padding, 0x5C, padlen );
  1206. mbedtls_md_starts( md_ctx );
  1207. mbedtls_md_update( md_ctx, secret, md_size );
  1208. mbedtls_md_update( md_ctx, padding, padlen );
  1209. mbedtls_md_update( md_ctx, out, md_size );
  1210. mbedtls_md_finish( md_ctx, out );
  1211. }
  1212. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  1213. #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \
  1214. defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
  1215. #define SSL_SOME_MODES_USE_MAC
  1216. #endif
  1217. /*
  1218. * Encryption/decryption functions
  1219. */
  1220. static int ssl_encrypt_buf( mbedtls_ssl_context *ssl )
  1221. {
  1222. mbedtls_cipher_mode_t mode;
  1223. int auth_done = 0;
  1224. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );
  1225. if( ssl->session_out == NULL || ssl->transform_out == NULL )
  1226. {
  1227. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1228. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1229. }
  1230. mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc );
  1231. MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload",
  1232. ssl->out_msg, ssl->out_msglen );
  1233. /*
  1234. * Add MAC before if needed
  1235. */
  1236. #if defined(SSL_SOME_MODES_USE_MAC)
  1237. if( mode == MBEDTLS_MODE_STREAM ||
  1238. ( mode == MBEDTLS_MODE_CBC
  1239. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  1240. && ssl->session_out->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED
  1241. #endif
  1242. ) )
  1243. {
  1244. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  1245. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  1246. {
  1247. unsigned char mac[SSL_MAC_MAX_BYTES];
  1248. ssl_mac( &ssl->transform_out->md_ctx_enc,
  1249. ssl->transform_out->mac_enc,
  1250. ssl->out_msg, ssl->out_msglen,
  1251. ssl->out_ctr, ssl->out_msgtype,
  1252. mac );
  1253. memcpy( ssl->out_msg + ssl->out_msglen, mac, ssl->transform_out->maclen );
  1254. }
  1255. else
  1256. #endif
  1257. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  1258. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1259. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
  1260. {
  1261. unsigned char mac[MBEDTLS_SSL_MAC_ADD];
  1262. mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_ctr, 8 );
  1263. mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_hdr, 3 );
  1264. mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_len, 2 );
  1265. mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
  1266. ssl->out_msg, ssl->out_msglen );
  1267. mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, mac );
  1268. mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
  1269. memcpy( ssl->out_msg + ssl->out_msglen, mac, ssl->transform_out->maclen );
  1270. }
  1271. else
  1272. #endif
  1273. {
  1274. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1275. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1276. }
  1277. MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac",
  1278. ssl->out_msg + ssl->out_msglen,
  1279. ssl->transform_out->maclen );
  1280. ssl->out_msglen += ssl->transform_out->maclen;
  1281. auth_done++;
  1282. }
  1283. #endif /* AEAD not the only option */
  1284. /*
  1285. * Encrypt
  1286. */
  1287. #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
  1288. if( mode == MBEDTLS_MODE_STREAM )
  1289. {
  1290. int ret;
  1291. size_t olen = 0;
  1292. MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
  1293. "including %d bytes of padding",
  1294. ssl->out_msglen, 0 ) );
  1295. if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
  1296. ssl->transform_out->iv_enc,
  1297. ssl->transform_out->ivlen,
  1298. ssl->out_msg, ssl->out_msglen,
  1299. ssl->out_msg, &olen ) ) != 0 )
  1300. {
  1301. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
  1302. return( ret );
  1303. }
  1304. if( ssl->out_msglen != olen )
  1305. {
  1306. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1307. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1308. }
  1309. }
  1310. else
  1311. #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
  1312. #if defined(MBEDTLS_GCM_C) || \
  1313. defined(MBEDTLS_CCM_C) || \
  1314. defined(MBEDTLS_CHACHAPOLY_C)
  1315. if( mode == MBEDTLS_MODE_GCM ||
  1316. mode == MBEDTLS_MODE_CCM ||
  1317. mode == MBEDTLS_MODE_CHACHAPOLY )
  1318. {
  1319. int ret;
  1320. size_t enc_msglen, olen;
  1321. unsigned char *enc_msg;
  1322. unsigned char add_data[13];
  1323. unsigned char iv[12];
  1324. mbedtls_ssl_transform *transform = ssl->transform_out;
  1325. unsigned char taglen = transform->ciphersuite_info->flags &
  1326. MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
  1327. size_t explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
  1328. /*
  1329. * Prepare additional authenticated data
  1330. */
  1331. memcpy( add_data, ssl->out_ctr, 8 );
  1332. add_data[8] = ssl->out_msgtype;
  1333. mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
  1334. ssl->conf->transport, add_data + 9 );
  1335. add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF;
  1336. add_data[12] = ssl->out_msglen & 0xFF;
  1337. MBEDTLS_SSL_DEBUG_BUF( 4, "additional data for AEAD", add_data, 13 );
  1338. /*
  1339. * Generate IV
  1340. */
  1341. if( transform->ivlen == 12 && transform->fixed_ivlen == 4 )
  1342. {
  1343. /* GCM and CCM: fixed || explicit (=seqnum) */
  1344. memcpy( iv, transform->iv_enc, transform->fixed_ivlen );
  1345. memcpy( iv + transform->fixed_ivlen, ssl->out_ctr, 8 );
  1346. memcpy( ssl->out_iv, ssl->out_ctr, 8 );
  1347. }
  1348. else if( transform->ivlen == 12 && transform->fixed_ivlen == 12 )
  1349. {
  1350. /* ChachaPoly: fixed XOR sequence number */
  1351. unsigned char i;
  1352. memcpy( iv, transform->iv_enc, transform->fixed_ivlen );
  1353. for( i = 0; i < 8; i++ )
  1354. iv[i+4] ^= ssl->out_ctr[i];
  1355. }
  1356. else
  1357. {
  1358. /* Reminder if we ever add an AEAD mode with a different size */
  1359. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1360. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1361. }
  1362. MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (internal)",
  1363. iv, transform->ivlen );
  1364. MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (transmitted)",
  1365. ssl->out_iv, explicit_ivlen );
  1366. /*
  1367. * Fix message length with added IV
  1368. */
  1369. enc_msg = ssl->out_msg;
  1370. enc_msglen = ssl->out_msglen;
  1371. ssl->out_msglen += explicit_ivlen;
  1372. MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
  1373. "including 0 bytes of padding",
  1374. ssl->out_msglen ) );
  1375. /*
  1376. * Encrypt and authenticate
  1377. */
  1378. if( ( ret = mbedtls_cipher_auth_encrypt( &transform->cipher_ctx_enc,
  1379. iv, transform->ivlen,
  1380. add_data, 13,
  1381. enc_msg, enc_msglen,
  1382. enc_msg, &olen,
  1383. enc_msg + enc_msglen, taglen ) ) != 0 )
  1384. {
  1385. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret );
  1386. return( ret );
  1387. }
  1388. if( olen != enc_msglen )
  1389. {
  1390. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1391. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1392. }
  1393. ssl->out_msglen += taglen;
  1394. auth_done++;
  1395. MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", enc_msg + enc_msglen, taglen );
  1396. }
  1397. else
  1398. #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
  1399. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
  1400. if( mode == MBEDTLS_MODE_CBC )
  1401. {
  1402. int ret;
  1403. unsigned char *enc_msg;
  1404. size_t enc_msglen, padlen, olen = 0, i;
  1405. padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) %
  1406. ssl->transform_out->ivlen;
  1407. if( padlen == ssl->transform_out->ivlen )
  1408. padlen = 0;
  1409. for( i = 0; i <= padlen; i++ )
  1410. ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen;
  1411. ssl->out_msglen += padlen + 1;
  1412. enc_msglen = ssl->out_msglen;
  1413. enc_msg = ssl->out_msg;
  1414. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1415. /*
  1416. * Prepend per-record IV for block cipher in TLS v1.1 and up as per
  1417. * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
  1418. */
  1419. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  1420. {
  1421. /*
  1422. * Generate IV
  1423. */
  1424. ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->transform_out->iv_enc,
  1425. ssl->transform_out->ivlen );
  1426. if( ret != 0 )
  1427. return( ret );
  1428. memcpy( ssl->out_iv, ssl->transform_out->iv_enc,
  1429. ssl->transform_out->ivlen );
  1430. /*
  1431. * Fix pointer positions and message length with added IV
  1432. */
  1433. enc_msg = ssl->out_msg;
  1434. enc_msglen = ssl->out_msglen;
  1435. ssl->out_msglen += ssl->transform_out->ivlen;
  1436. }
  1437. #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
  1438. MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
  1439. "including %d bytes of IV and %d bytes of padding",
  1440. ssl->out_msglen, ssl->transform_out->ivlen,
  1441. padlen + 1 ) );
  1442. if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
  1443. ssl->transform_out->iv_enc,
  1444. ssl->transform_out->ivlen,
  1445. enc_msg, enc_msglen,
  1446. enc_msg, &olen ) ) != 0 )
  1447. {
  1448. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
  1449. return( ret );
  1450. }
  1451. if( enc_msglen != olen )
  1452. {
  1453. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1454. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1455. }
  1456. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
  1457. if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
  1458. {
  1459. /*
  1460. * Save IV in SSL3 and TLS1
  1461. */
  1462. memcpy( ssl->transform_out->iv_enc,
  1463. ssl->transform_out->cipher_ctx_enc.iv,
  1464. ssl->transform_out->ivlen );
  1465. }
  1466. #endif
  1467. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  1468. if( auth_done == 0 )
  1469. {
  1470. unsigned char mac[MBEDTLS_SSL_MAC_ADD];
  1471. /*
  1472. * MAC(MAC_write_key, seq_num +
  1473. * TLSCipherText.type +
  1474. * TLSCipherText.version +
  1475. * length_of( (IV +) ENC(...) ) +
  1476. * IV + // except for TLS 1.0
  1477. * ENC(content + padding + padding_length));
  1478. */
  1479. unsigned char pseudo_hdr[13];
  1480. MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
  1481. memcpy( pseudo_hdr + 0, ssl->out_ctr, 8 );
  1482. memcpy( pseudo_hdr + 8, ssl->out_hdr, 3 );
  1483. pseudo_hdr[11] = (unsigned char)( ( ssl->out_msglen >> 8 ) & 0xFF );
  1484. pseudo_hdr[12] = (unsigned char)( ( ssl->out_msglen ) & 0xFF );
  1485. MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
  1486. mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, pseudo_hdr, 13 );
  1487. mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
  1488. ssl->out_iv, ssl->out_msglen );
  1489. mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, mac );
  1490. mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
  1491. memcpy( ssl->out_iv + ssl->out_msglen, mac,
  1492. ssl->transform_out->maclen );
  1493. ssl->out_msglen += ssl->transform_out->maclen;
  1494. auth_done++;
  1495. }
  1496. #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
  1497. }
  1498. else
  1499. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC */
  1500. {
  1501. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1502. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1503. }
  1504. /* Make extra sure authentication was performed, exactly once */
  1505. if( auth_done != 1 )
  1506. {
  1507. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1508. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1509. }
  1510. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );
  1511. return( 0 );
  1512. }
  1513. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
  1514. /*
  1515. * Constant-flow conditional memcpy:
  1516. * - if c1 == c2, equivalent to memcpy(dst, src, len),
  1517. * - otherwise, a no-op,
  1518. * but with execution flow independent of the values of c1 and c2.
  1519. *
  1520. * Use only bit operations to avoid branches that could be used by some
  1521. * compilers on some platforms to translate comparison operators.
  1522. */
  1523. static void mbedtls_ssl_cf_memcpy_if_eq( unsigned char *dst,
  1524. const unsigned char *src,
  1525. size_t len,
  1526. size_t c1, size_t c2 )
  1527. {
  1528. /* diff = 0 if c1 == c2, non-zero otherwise */
  1529. const size_t diff = c1 ^ c2;
  1530. /* MSVC has a warning about unary minus on unsigned integer types,
  1531. * but this is well-defined and precisely what we want to do here. */
  1532. #if defined(_MSC_VER)
  1533. #pragma warning( push )
  1534. #pragma warning( disable : 4146 )
  1535. #endif
  1536. /* diff_msb's most significant bit is equal to c1 != c2 */
  1537. const size_t diff_msb = ( diff | -diff );
  1538. /* diff1 = c1 != c2 */
  1539. const size_t diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 );
  1540. /* mask = c1 != c2 ? 0xff : 0x00 */
  1541. const unsigned char mask = (unsigned char) -diff1;
  1542. #if defined(_MSC_VER)
  1543. #pragma warning( pop )
  1544. #endif
  1545. /* dst[i] = c1 != c2 ? dst[i] : src[i] */
  1546. size_t i;
  1547. for( i = 0; i < len; i++ )
  1548. dst[i] = ( dst[i] & mask ) | ( src[i] & ~mask );
  1549. }
  1550. /*
  1551. * Compute HMAC of variable-length data with constant flow.
  1552. *
  1553. * Only works with MD-5, SHA-1, SHA-256 and SHA-384.
  1554. * (Otherwise, computation of block_size needs to be adapted.)
  1555. */
  1556. int mbedtls_ssl_cf_hmac(
  1557. mbedtls_md_context_t *ctx,
  1558. const unsigned char *add_data, size_t add_data_len,
  1559. const unsigned char *data, size_t data_len_secret,
  1560. size_t min_data_len, size_t max_data_len,
  1561. unsigned char *output )
  1562. {
  1563. /*
  1564. * This function breaks the HMAC abstraction and uses the md_clone()
  1565. * extension to the MD API in order to get constant-flow behaviour.
  1566. *
  1567. * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
  1568. * concatenation, and okey/ikey are the XOR of the key with some fixed bit
  1569. * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx.
  1570. *
  1571. * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to
  1572. * minlen, then cloning the context, and for each byte up to maxlen
  1573. * finishing up the hash computation, keeping only the correct result.
  1574. *
  1575. * Then we only need to compute HASH(okey + inner_hash) and we're done.
  1576. */
  1577. const mbedtls_md_type_t md_alg = mbedtls_md_get_type( ctx->md_info );
  1578. /* TLS 1.0-1.2 only support SHA-384, SHA-256, SHA-1, MD-5,
  1579. * all of which have the same block size except SHA-384. */
  1580. const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64;
  1581. const unsigned char * const ikey = ctx->hmac_ctx;
  1582. const unsigned char * const okey = ikey + block_size;
  1583. const size_t hash_size = mbedtls_md_get_size( ctx->md_info );
  1584. unsigned char aux_out[MBEDTLS_MD_MAX_SIZE];
  1585. mbedtls_md_context_t aux;
  1586. size_t offset;
  1587. int ret;
  1588. mbedtls_md_init( &aux );
  1589. #define MD_CHK( func_call ) \
  1590. do { \
  1591. ret = (func_call); \
  1592. if( ret != 0 ) \
  1593. goto cleanup; \
  1594. } while( 0 )
  1595. MD_CHK( mbedtls_md_setup( &aux, ctx->md_info, 0 ) );
  1596. /* After hmac_start() of hmac_reset(), ikey has already been hashed,
  1597. * so we can start directly with the message */
  1598. MD_CHK( mbedtls_md_update( ctx, add_data, add_data_len ) );
  1599. MD_CHK( mbedtls_md_update( ctx, data, min_data_len ) );
  1600. /* For each possible length, compute the hash up to that point */
  1601. for( offset = min_data_len; offset <= max_data_len; offset++ )
  1602. {
  1603. MD_CHK( mbedtls_md_clone( &aux, ctx ) );
  1604. MD_CHK( mbedtls_md_finish( &aux, aux_out ) );
  1605. /* Keep only the correct inner_hash in the output buffer */
  1606. mbedtls_ssl_cf_memcpy_if_eq( output, aux_out, hash_size,
  1607. offset, data_len_secret );
  1608. if( offset < max_data_len )
  1609. MD_CHK( mbedtls_md_update( ctx, data + offset, 1 ) );
  1610. }
  1611. /* The context needs to finish() before it starts() again */
  1612. MD_CHK( mbedtls_md_finish( ctx, aux_out ) );
  1613. /* Now compute HASH(okey + inner_hash) */
  1614. MD_CHK( mbedtls_md_starts( ctx ) );
  1615. MD_CHK( mbedtls_md_update( ctx, okey, block_size ) );
  1616. MD_CHK( mbedtls_md_update( ctx, output, hash_size ) );
  1617. MD_CHK( mbedtls_md_finish( ctx, output ) );
  1618. /* Done, get ready for next time */
  1619. MD_CHK( mbedtls_md_hmac_reset( ctx ) );
  1620. #undef MD_CHK
  1621. cleanup:
  1622. mbedtls_md_free( &aux );
  1623. return( ret );
  1624. }
  1625. /*
  1626. * Constant-flow memcpy from variable position in buffer.
  1627. * - functionally equivalent to memcpy(dst, src + offset_secret, len)
  1628. * - but with execution flow independent from the value of offset_secret.
  1629. */
  1630. void mbedtls_ssl_cf_memcpy_offset( unsigned char *dst,
  1631. const unsigned char *src_base,
  1632. size_t offset_secret,
  1633. size_t offset_min, size_t offset_max,
  1634. size_t len )
  1635. {
  1636. size_t offset;
  1637. for( offset = offset_min; offset <= offset_max; offset++ )
  1638. {
  1639. mbedtls_ssl_cf_memcpy_if_eq( dst, src_base + offset, len,
  1640. offset, offset_secret );
  1641. }
  1642. }
  1643. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
  1644. static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
  1645. {
  1646. mbedtls_cipher_mode_t mode;
  1647. int auth_done = 0;
  1648. #if defined(SSL_SOME_MODES_USE_MAC)
  1649. size_t padlen = 0, correct = 1;
  1650. #endif
  1651. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) );
  1652. if( ssl->session_in == NULL || ssl->transform_in == NULL )
  1653. {
  1654. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1655. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1656. }
  1657. mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_in->cipher_ctx_dec );
  1658. if( ssl->in_msglen < ssl->transform_in->minlen )
  1659. {
  1660. MBEDTLS_SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)",
  1661. ssl->in_msglen, ssl->transform_in->minlen ) );
  1662. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1663. }
  1664. #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
  1665. if( mode == MBEDTLS_MODE_STREAM )
  1666. {
  1667. int ret;
  1668. size_t olen = 0;
  1669. padlen = 0;
  1670. if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
  1671. ssl->transform_in->iv_dec,
  1672. ssl->transform_in->ivlen,
  1673. ssl->in_msg, ssl->in_msglen,
  1674. ssl->in_msg, &olen ) ) != 0 )
  1675. {
  1676. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
  1677. return( ret );
  1678. }
  1679. if( ssl->in_msglen != olen )
  1680. {
  1681. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1682. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1683. }
  1684. }
  1685. else
  1686. #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
  1687. #if defined(MBEDTLS_GCM_C) || \
  1688. defined(MBEDTLS_CCM_C) || \
  1689. defined(MBEDTLS_CHACHAPOLY_C)
  1690. if( mode == MBEDTLS_MODE_GCM ||
  1691. mode == MBEDTLS_MODE_CCM ||
  1692. mode == MBEDTLS_MODE_CHACHAPOLY )
  1693. {
  1694. int ret;
  1695. size_t dec_msglen, olen;
  1696. unsigned char *dec_msg;
  1697. unsigned char *dec_msg_result;
  1698. unsigned char add_data[13];
  1699. unsigned char iv[12];
  1700. mbedtls_ssl_transform *transform = ssl->transform_in;
  1701. unsigned char taglen = transform->ciphersuite_info->flags &
  1702. MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
  1703. size_t explicit_iv_len = transform->ivlen - transform->fixed_ivlen;
  1704. /*
  1705. * Compute and update sizes
  1706. */
  1707. if( ssl->in_msglen < explicit_iv_len + taglen )
  1708. {
  1709. MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) "
  1710. "+ taglen (%d)", ssl->in_msglen,
  1711. explicit_iv_len, taglen ) );
  1712. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1713. }
  1714. dec_msglen = ssl->in_msglen - explicit_iv_len - taglen;
  1715. dec_msg = ssl->in_msg;
  1716. dec_msg_result = ssl->in_msg;
  1717. ssl->in_msglen = dec_msglen;
  1718. /*
  1719. * Prepare additional authenticated data
  1720. */
  1721. memcpy( add_data, ssl->in_ctr, 8 );
  1722. add_data[8] = ssl->in_msgtype;
  1723. mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
  1724. ssl->conf->transport, add_data + 9 );
  1725. add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF;
  1726. add_data[12] = ssl->in_msglen & 0xFF;
  1727. MBEDTLS_SSL_DEBUG_BUF( 4, "additional data for AEAD", add_data, 13 );
  1728. /*
  1729. * Prepare IV
  1730. */
  1731. if( transform->ivlen == 12 && transform->fixed_ivlen == 4 )
  1732. {
  1733. /* GCM and CCM: fixed || explicit (transmitted) */
  1734. memcpy( iv, transform->iv_dec, transform->fixed_ivlen );
  1735. memcpy( iv + transform->fixed_ivlen, ssl->in_iv, 8 );
  1736. }
  1737. else if( transform->ivlen == 12 && transform->fixed_ivlen == 12 )
  1738. {
  1739. /* ChachaPoly: fixed XOR sequence number */
  1740. unsigned char i;
  1741. memcpy( iv, transform->iv_dec, transform->fixed_ivlen );
  1742. for( i = 0; i < 8; i++ )
  1743. iv[i+4] ^= ssl->in_ctr[i];
  1744. }
  1745. else
  1746. {
  1747. /* Reminder if we ever add an AEAD mode with a different size */
  1748. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1749. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1750. }
  1751. MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", iv, transform->ivlen );
  1752. MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, taglen );
  1753. /*
  1754. * Decrypt and authenticate
  1755. */
  1756. if( ( ret = mbedtls_cipher_auth_decrypt( &ssl->transform_in->cipher_ctx_dec,
  1757. iv, transform->ivlen,
  1758. add_data, 13,
  1759. dec_msg, dec_msglen,
  1760. dec_msg_result, &olen,
  1761. dec_msg + dec_msglen, taglen ) ) != 0 )
  1762. {
  1763. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret );
  1764. if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED )
  1765. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1766. return( ret );
  1767. }
  1768. auth_done++;
  1769. if( olen != dec_msglen )
  1770. {
  1771. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1772. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1773. }
  1774. }
  1775. else
  1776. #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
  1777. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
  1778. if( mode == MBEDTLS_MODE_CBC )
  1779. {
  1780. /*
  1781. * Decrypt and check the padding
  1782. */
  1783. int ret;
  1784. unsigned char *dec_msg;
  1785. unsigned char *dec_msg_result;
  1786. size_t dec_msglen;
  1787. size_t minlen = 0;
  1788. size_t olen = 0;
  1789. /*
  1790. * Check immediate ciphertext sanity
  1791. */
  1792. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1793. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  1794. minlen += ssl->transform_in->ivlen;
  1795. #endif
  1796. if( ssl->in_msglen < minlen + ssl->transform_in->ivlen ||
  1797. ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 )
  1798. {
  1799. MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) "
  1800. "+ 1 ) ( + expl IV )", ssl->in_msglen,
  1801. ssl->transform_in->ivlen,
  1802. ssl->transform_in->maclen ) );
  1803. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1804. }
  1805. dec_msglen = ssl->in_msglen;
  1806. dec_msg = ssl->in_msg;
  1807. dec_msg_result = ssl->in_msg;
  1808. /*
  1809. * Authenticate before decrypt if enabled
  1810. */
  1811. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  1812. if( ssl->session_in->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
  1813. {
  1814. unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
  1815. unsigned char pseudo_hdr[13];
  1816. MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
  1817. dec_msglen -= ssl->transform_in->maclen;
  1818. ssl->in_msglen -= ssl->transform_in->maclen;
  1819. memcpy( pseudo_hdr + 0, ssl->in_ctr, 8 );
  1820. memcpy( pseudo_hdr + 8, ssl->in_hdr, 3 );
  1821. pseudo_hdr[11] = (unsigned char)( ( ssl->in_msglen >> 8 ) & 0xFF );
  1822. pseudo_hdr[12] = (unsigned char)( ( ssl->in_msglen ) & 0xFF );
  1823. MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
  1824. mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, pseudo_hdr, 13 );
  1825. mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec,
  1826. ssl->in_iv, ssl->in_msglen );
  1827. mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, mac_expect );
  1828. mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
  1829. MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", ssl->in_iv + ssl->in_msglen,
  1830. ssl->transform_in->maclen );
  1831. MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect,
  1832. ssl->transform_in->maclen );
  1833. if( mbedtls_ssl_safer_memcmp( ssl->in_iv + ssl->in_msglen, mac_expect,
  1834. ssl->transform_in->maclen ) != 0 )
  1835. {
  1836. MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
  1837. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1838. }
  1839. auth_done++;
  1840. }
  1841. #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
  1842. /*
  1843. * Check length sanity
  1844. */
  1845. if( ssl->in_msglen % ssl->transform_in->ivlen != 0 )
  1846. {
  1847. MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0",
  1848. ssl->in_msglen, ssl->transform_in->ivlen ) );
  1849. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1850. }
  1851. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1852. /*
  1853. * Initialize for prepended IV for block cipher in TLS v1.1 and up
  1854. */
  1855. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  1856. {
  1857. unsigned char i;
  1858. dec_msglen -= ssl->transform_in->ivlen;
  1859. ssl->in_msglen -= ssl->transform_in->ivlen;
  1860. for( i = 0; i < ssl->transform_in->ivlen; i++ )
  1861. ssl->transform_in->iv_dec[i] = ssl->in_iv[i];
  1862. }
  1863. #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
  1864. if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
  1865. ssl->transform_in->iv_dec,
  1866. ssl->transform_in->ivlen,
  1867. dec_msg, dec_msglen,
  1868. dec_msg_result, &olen ) ) != 0 )
  1869. {
  1870. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
  1871. return( ret );
  1872. }
  1873. if( dec_msglen != olen )
  1874. {
  1875. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1876. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1877. }
  1878. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
  1879. if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
  1880. {
  1881. /*
  1882. * Save IV in SSL3 and TLS1
  1883. */
  1884. memcpy( ssl->transform_in->iv_dec,
  1885. ssl->transform_in->cipher_ctx_dec.iv,
  1886. ssl->transform_in->ivlen );
  1887. }
  1888. #endif
  1889. padlen = 1 + ssl->in_msg[ssl->in_msglen - 1];
  1890. if( ssl->in_msglen < ssl->transform_in->maclen + padlen &&
  1891. auth_done == 0 )
  1892. {
  1893. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1894. MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)",
  1895. ssl->in_msglen, ssl->transform_in->maclen, padlen ) );
  1896. #endif
  1897. padlen = 0;
  1898. correct = 0;
  1899. }
  1900. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  1901. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  1902. {
  1903. if( padlen > ssl->transform_in->ivlen )
  1904. {
  1905. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1906. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, "
  1907. "should be no more than %d",
  1908. padlen, ssl->transform_in->ivlen ) );
  1909. #endif
  1910. correct = 0;
  1911. }
  1912. }
  1913. else
  1914. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  1915. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  1916. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1917. if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
  1918. {
  1919. /*
  1920. * TLSv1+: always check the padding up to the first failure
  1921. * and fake check up to 256 bytes of padding
  1922. */
  1923. size_t pad_count = 0, real_count = 1;
  1924. size_t padding_idx = ssl->in_msglen - padlen;
  1925. size_t i;
  1926. /*
  1927. * Padding is guaranteed to be incorrect if:
  1928. * 1. padlen > ssl->in_msglen
  1929. *
  1930. * 2. padding_idx > MBEDTLS_SSL_IN_CONTENT_LEN +
  1931. * ssl->transform_in->maclen
  1932. *
  1933. * In both cases we reset padding_idx to a safe value (0) to
  1934. * prevent out-of-buffer reads.
  1935. */
  1936. correct &= ( padlen <= ssl->in_msglen );
  1937. correct &= ( padding_idx <= MBEDTLS_SSL_IN_CONTENT_LEN +
  1938. ssl->transform_in->maclen );
  1939. padding_idx *= correct;
  1940. for( i = 0; i < 256; i++ )
  1941. {
  1942. real_count &= ( i < padlen );
  1943. pad_count += real_count *
  1944. ( ssl->in_msg[padding_idx + i] == padlen - 1 );
  1945. }
  1946. correct &= ( pad_count == padlen ); /* Only 1 on correct padding */
  1947. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1948. if( padlen > 0 && correct == 0 )
  1949. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) );
  1950. #endif
  1951. padlen &= correct * 0x1FF;
  1952. }
  1953. else
  1954. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
  1955. MBEDTLS_SSL_PROTO_TLS1_2 */
  1956. {
  1957. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1958. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1959. }
  1960. ssl->in_msglen -= padlen;
  1961. }
  1962. else
  1963. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC) */
  1964. {
  1965. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1966. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1967. }
  1968. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1969. MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption",
  1970. ssl->in_msg, ssl->in_msglen );
  1971. #endif
  1972. /*
  1973. * Authenticate if not done yet.
  1974. * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
  1975. */
  1976. #if defined(SSL_SOME_MODES_USE_MAC)
  1977. if( auth_done == 0 )
  1978. {
  1979. unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
  1980. unsigned char mac_peer[MBEDTLS_SSL_MAC_ADD];
  1981. ssl->in_msglen -= ssl->transform_in->maclen;
  1982. ssl->in_len[0] = (unsigned char)( ssl->in_msglen >> 8 );
  1983. ssl->in_len[1] = (unsigned char)( ssl->in_msglen );
  1984. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  1985. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  1986. {
  1987. ssl_mac( &ssl->transform_in->md_ctx_dec,
  1988. ssl->transform_in->mac_dec,
  1989. ssl->in_msg, ssl->in_msglen,
  1990. ssl->in_ctr, ssl->in_msgtype,
  1991. mac_expect );
  1992. memcpy( mac_peer, ssl->in_msg + ssl->in_msglen,
  1993. ssl->transform_in->maclen );
  1994. }
  1995. else
  1996. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  1997. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  1998. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1999. if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
  2000. {
  2001. int ret;
  2002. unsigned char add_data[13];
  2003. /*
  2004. * The next two sizes are the minimum and maximum values of
  2005. * in_msglen over all padlen values.
  2006. *
  2007. * They're independent of padlen, since we previously did
  2008. * in_msglen -= padlen.
  2009. *
  2010. * Note that max_len + maclen is never more than the buffer
  2011. * length, as we previously did in_msglen -= maclen too.
  2012. */
  2013. const size_t max_len = ssl->in_msglen + padlen;
  2014. const size_t min_len = ( max_len > 256 ) ? max_len - 256 : 0;
  2015. memcpy( add_data + 0, ssl->in_ctr, 8 );
  2016. memcpy( add_data + 8, ssl->in_hdr, 3 );
  2017. memcpy( add_data + 11, ssl->in_len, 2 );
  2018. ret = mbedtls_ssl_cf_hmac( &ssl->transform_in->md_ctx_dec,
  2019. add_data, sizeof( add_data ),
  2020. ssl->in_msg, ssl->in_msglen,
  2021. min_len, max_len,
  2022. mac_expect );
  2023. if( ret != 0 )
  2024. {
  2025. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_cf_hmac", ret );
  2026. return( ret );
  2027. }
  2028. mbedtls_ssl_cf_memcpy_offset( mac_peer, ssl->in_msg,
  2029. ssl->in_msglen,
  2030. min_len, max_len,
  2031. ssl->transform_in->maclen );
  2032. }
  2033. else
  2034. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
  2035. MBEDTLS_SSL_PROTO_TLS1_2 */
  2036. {
  2037. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2038. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2039. }
  2040. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  2041. MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, ssl->transform_in->maclen );
  2042. MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", mac_peer, ssl->transform_in->maclen );
  2043. #endif
  2044. if( mbedtls_ssl_safer_memcmp( mac_peer, mac_expect,
  2045. ssl->transform_in->maclen ) != 0 )
  2046. {
  2047. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  2048. MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
  2049. #endif
  2050. correct = 0;
  2051. }
  2052. auth_done++;
  2053. }
  2054. /*
  2055. * Finally check the correct flag
  2056. */
  2057. if( correct == 0 )
  2058. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  2059. #endif /* SSL_SOME_MODES_USE_MAC */
  2060. /* Make extra sure authentication was performed, exactly once */
  2061. if( auth_done != 1 )
  2062. {
  2063. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2064. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2065. }
  2066. if( ssl->in_msglen == 0 )
  2067. {
  2068. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  2069. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3
  2070. && ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
  2071. {
  2072. /* TLS v1.2 explicitly disallows zero-length messages which are not application data */
  2073. MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid zero-length message type: %d", ssl->in_msgtype ) );
  2074. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  2075. }
  2076. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  2077. ssl->nb_zero++;
  2078. /*
  2079. * Three or more empty messages may be a DoS attack
  2080. * (excessive CPU consumption).
  2081. */
  2082. if( ssl->nb_zero > 3 )
  2083. {
  2084. MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty "
  2085. "messages, possible DoS attack" ) );
  2086. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  2087. }
  2088. }
  2089. else
  2090. ssl->nb_zero = 0;
  2091. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2092. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  2093. {
  2094. ; /* in_ctr read from peer, not maintained internally */
  2095. }
  2096. else
  2097. #endif
  2098. {
  2099. unsigned char i;
  2100. for( i = 8; i > ssl_ep_len( ssl ); i-- )
  2101. if( ++ssl->in_ctr[i - 1] != 0 )
  2102. break;
  2103. /* The loop goes to its end iff the counter is wrapping */
  2104. if( i == ssl_ep_len( ssl ) )
  2105. {
  2106. MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) );
  2107. return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
  2108. }
  2109. }
  2110. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
  2111. return( 0 );
  2112. }
  2113. #undef MAC_NONE
  2114. #undef MAC_PLAINTEXT
  2115. #undef MAC_CIPHERTEXT
  2116. #if defined(MBEDTLS_ZLIB_SUPPORT)
  2117. /*
  2118. * Compression/decompression functions
  2119. */
  2120. static int ssl_compress_buf( mbedtls_ssl_context *ssl )
  2121. {
  2122. int ret;
  2123. unsigned char *msg_post = ssl->out_msg;
  2124. ptrdiff_t bytes_written = ssl->out_msg - ssl->out_buf;
  2125. size_t len_pre = ssl->out_msglen;
  2126. unsigned char *msg_pre = ssl->compress_buf;
  2127. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) );
  2128. if( len_pre == 0 )
  2129. return( 0 );
  2130. memcpy( msg_pre, ssl->out_msg, len_pre );
  2131. MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ",
  2132. ssl->out_msglen ) );
  2133. MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload",
  2134. ssl->out_msg, ssl->out_msglen );
  2135. ssl->transform_out->ctx_deflate.next_in = msg_pre;
  2136. ssl->transform_out->ctx_deflate.avail_in = len_pre;
  2137. ssl->transform_out->ctx_deflate.next_out = msg_post;
  2138. ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_OUT_BUFFER_LEN - bytes_written;
  2139. ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );
  2140. if( ret != Z_OK )
  2141. {
  2142. MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) );
  2143. return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
  2144. }
  2145. ssl->out_msglen = MBEDTLS_SSL_OUT_BUFFER_LEN -
  2146. ssl->transform_out->ctx_deflate.avail_out - bytes_written;
  2147. MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ",
  2148. ssl->out_msglen ) );
  2149. MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload",
  2150. ssl->out_msg, ssl->out_msglen );
  2151. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) );
  2152. return( 0 );
  2153. }
  2154. static int ssl_decompress_buf( mbedtls_ssl_context *ssl )
  2155. {
  2156. int ret;
  2157. unsigned char *msg_post = ssl->in_msg;
  2158. ptrdiff_t header_bytes = ssl->in_msg - ssl->in_buf;
  2159. size_t len_pre = ssl->in_msglen;
  2160. unsigned char *msg_pre = ssl->compress_buf;
  2161. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) );
  2162. if( len_pre == 0 )
  2163. return( 0 );
  2164. memcpy( msg_pre, ssl->in_msg, len_pre );
  2165. MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ",
  2166. ssl->in_msglen ) );
  2167. MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload",
  2168. ssl->in_msg, ssl->in_msglen );
  2169. ssl->transform_in->ctx_inflate.next_in = msg_pre;
  2170. ssl->transform_in->ctx_inflate.avail_in = len_pre;
  2171. ssl->transform_in->ctx_inflate.next_out = msg_post;
  2172. ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_IN_BUFFER_LEN -
  2173. header_bytes;
  2174. ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );
  2175. if( ret != Z_OK )
  2176. {
  2177. MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) );
  2178. return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
  2179. }
  2180. ssl->in_msglen = MBEDTLS_SSL_IN_BUFFER_LEN -
  2181. ssl->transform_in->ctx_inflate.avail_out - header_bytes;
  2182. MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ",
  2183. ssl->in_msglen ) );
  2184. MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload",
  2185. ssl->in_msg, ssl->in_msglen );
  2186. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) );
  2187. return( 0 );
  2188. }
  2189. #endif /* MBEDTLS_ZLIB_SUPPORT */
  2190. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
  2191. static int ssl_write_hello_request( mbedtls_ssl_context *ssl );
  2192. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2193. static int ssl_resend_hello_request( mbedtls_ssl_context *ssl )
  2194. {
  2195. /* If renegotiation is not enforced, retransmit until we would reach max
  2196. * timeout if we were using the usual handshake doubling scheme */
  2197. if( ssl->conf->renego_max_records < 0 )
  2198. {
  2199. uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;
  2200. unsigned char doublings = 1;
  2201. while( ratio != 0 )
  2202. {
  2203. ++doublings;
  2204. ratio >>= 1;
  2205. }
  2206. if( ++ssl->renego_records_seen > doublings )
  2207. {
  2208. MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) );
  2209. return( 0 );
  2210. }
  2211. }
  2212. return( ssl_write_hello_request( ssl ) );
  2213. }
  2214. #endif
  2215. #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
  2216. /*
  2217. * Fill the input message buffer by appending data to it.
  2218. * The amount of data already fetched is in ssl->in_left.
  2219. *
  2220. * If we return 0, is it guaranteed that (at least) nb_want bytes are
  2221. * available (from this read and/or a previous one). Otherwise, an error code
  2222. * is returned (possibly EOF or WANT_READ).
  2223. *
  2224. * With stream transport (TLS) on success ssl->in_left == nb_want, but
  2225. * with datagram transport (DTLS) on success ssl->in_left >= nb_want,
  2226. * since we always read a whole datagram at once.
  2227. *
  2228. * For DTLS, it is up to the caller to set ssl->next_record_offset when
  2229. * they're done reading a record.
  2230. */
  2231. int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want )
  2232. {
  2233. int ret;
  2234. size_t len;
  2235. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) );
  2236. if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL )
  2237. {
  2238. MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
  2239. "or mbedtls_ssl_set_bio()" ) );
  2240. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2241. }
  2242. if( nb_want > MBEDTLS_SSL_IN_BUFFER_LEN - (size_t)( ssl->in_hdr - ssl->in_buf ) )
  2243. {
  2244. MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) );
  2245. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2246. }
  2247. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2248. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  2249. {
  2250. uint32_t timeout;
  2251. /* Just to be sure */
  2252. if( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL )
  2253. {
  2254. MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use "
  2255. "mbedtls_ssl_set_timer_cb() for DTLS" ) );
  2256. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2257. }
  2258. /*
  2259. * The point is, we need to always read a full datagram at once, so we
  2260. * sometimes read more then requested, and handle the additional data.
  2261. * It could be the rest of the current record (while fetching the
  2262. * header) and/or some other records in the same datagram.
  2263. */
  2264. /*
  2265. * Move to the next record in the already read datagram if applicable
  2266. */
  2267. if( ssl->next_record_offset != 0 )
  2268. {
  2269. if( ssl->in_left < ssl->next_record_offset )
  2270. {
  2271. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2272. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2273. }
  2274. ssl->in_left -= ssl->next_record_offset;
  2275. if( ssl->in_left != 0 )
  2276. {
  2277. MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %d",
  2278. ssl->next_record_offset ) );
  2279. memmove( ssl->in_hdr,
  2280. ssl->in_hdr + ssl->next_record_offset,
  2281. ssl->in_left );
  2282. }
  2283. ssl->next_record_offset = 0;
  2284. }
  2285. MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
  2286. ssl->in_left, nb_want ) );
  2287. /*
  2288. * Done if we already have enough data.
  2289. */
  2290. if( nb_want <= ssl->in_left)
  2291. {
  2292. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
  2293. return( 0 );
  2294. }
  2295. /*
  2296. * A record can't be split across datagrams. If we need to read but
  2297. * are not at the beginning of a new record, the caller did something
  2298. * wrong.
  2299. */
  2300. if( ssl->in_left != 0 )
  2301. {
  2302. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2303. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2304. }
  2305. /*
  2306. * Don't even try to read if time's out already.
  2307. * This avoids by-passing the timer when repeatedly receiving messages
  2308. * that will end up being dropped.
  2309. */
  2310. if( ssl_check_timer( ssl ) != 0 )
  2311. {
  2312. MBEDTLS_SSL_DEBUG_MSG( 2, ( "timer has expired" ) );
  2313. ret = MBEDTLS_ERR_SSL_TIMEOUT;
  2314. }
  2315. else
  2316. {
  2317. len = MBEDTLS_SSL_IN_BUFFER_LEN - ( ssl->in_hdr - ssl->in_buf );
  2318. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  2319. timeout = ssl->handshake->retransmit_timeout;
  2320. else
  2321. timeout = ssl->conf->read_timeout;
  2322. MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %u ms", timeout ) );
  2323. if( ssl->f_recv_timeout != NULL )
  2324. ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len,
  2325. timeout );
  2326. else
  2327. ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len );
  2328. MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
  2329. if( ret == 0 )
  2330. return( MBEDTLS_ERR_SSL_CONN_EOF );
  2331. }
  2332. if( ret == MBEDTLS_ERR_SSL_TIMEOUT )
  2333. {
  2334. MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) );
  2335. ssl_set_timer( ssl, 0 );
  2336. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  2337. {
  2338. if( ssl_double_retransmit_timeout( ssl ) != 0 )
  2339. {
  2340. MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) );
  2341. return( MBEDTLS_ERR_SSL_TIMEOUT );
  2342. }
  2343. if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
  2344. {
  2345. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
  2346. return( ret );
  2347. }
  2348. return( MBEDTLS_ERR_SSL_WANT_READ );
  2349. }
  2350. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
  2351. else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  2352. ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
  2353. {
  2354. if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
  2355. {
  2356. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
  2357. return( ret );
  2358. }
  2359. return( MBEDTLS_ERR_SSL_WANT_READ );
  2360. }
  2361. #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
  2362. }
  2363. if( ret < 0 )
  2364. return( ret );
  2365. ssl->in_left = ret;
  2366. }
  2367. else
  2368. #endif
  2369. {
  2370. MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
  2371. ssl->in_left, nb_want ) );
  2372. while( ssl->in_left < nb_want )
  2373. {
  2374. len = nb_want - ssl->in_left;
  2375. if( ssl_check_timer( ssl ) != 0 )
  2376. ret = MBEDTLS_ERR_SSL_TIMEOUT;
  2377. else
  2378. {
  2379. if( ssl->f_recv_timeout != NULL )
  2380. {
  2381. ret = ssl->f_recv_timeout( ssl->p_bio,
  2382. ssl->in_hdr + ssl->in_left, len,
  2383. ssl->conf->read_timeout );
  2384. }
  2385. else
  2386. {
  2387. ret = ssl->f_recv( ssl->p_bio,
  2388. ssl->in_hdr + ssl->in_left, len );
  2389. }
  2390. }
  2391. MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
  2392. ssl->in_left, nb_want ) );
  2393. MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
  2394. if( ret == 0 )
  2395. return( MBEDTLS_ERR_SSL_CONN_EOF );
  2396. if( ret < 0 )
  2397. return( ret );
  2398. if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > (int)SIZE_MAX ) )
  2399. {
  2400. MBEDTLS_SSL_DEBUG_MSG( 1,
  2401. ( "f_recv returned %d bytes but only %lu were requested",
  2402. ret, (unsigned long)len ) );
  2403. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2404. }
  2405. ssl->in_left += ret;
  2406. }
  2407. }
  2408. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
  2409. return( 0 );
  2410. }
  2411. /*
  2412. * Flush any data not yet written
  2413. */
  2414. int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl )
  2415. {
  2416. int ret;
  2417. unsigned char *buf;
  2418. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) );
  2419. if( ssl->f_send == NULL )
  2420. {
  2421. MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
  2422. "or mbedtls_ssl_set_bio()" ) );
  2423. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2424. }
  2425. /* Avoid incrementing counter if data is flushed */
  2426. if( ssl->out_left == 0 )
  2427. {
  2428. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
  2429. return( 0 );
  2430. }
  2431. while( ssl->out_left > 0 )
  2432. {
  2433. MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d",
  2434. mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) );
  2435. buf = ssl->out_hdr - ssl->out_left;
  2436. ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left );
  2437. MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret );
  2438. if( ret <= 0 )
  2439. return( ret );
  2440. if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > (int)SIZE_MAX ) )
  2441. {
  2442. MBEDTLS_SSL_DEBUG_MSG( 1,
  2443. ( "f_send returned %d bytes but only %lu bytes were sent",
  2444. ret, (unsigned long)ssl->out_left ) );
  2445. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2446. }
  2447. ssl->out_left -= ret;
  2448. }
  2449. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2450. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  2451. {
  2452. ssl->out_hdr = ssl->out_buf;
  2453. }
  2454. else
  2455. #endif
  2456. {
  2457. ssl->out_hdr = ssl->out_buf + 8;
  2458. }
  2459. ssl_update_out_pointers( ssl, ssl->transform_out );
  2460. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
  2461. return( 0 );
  2462. }
  2463. /*
  2464. * Functions to handle the DTLS retransmission state machine
  2465. */
  2466. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2467. /*
  2468. * Append current handshake message to current outgoing flight
  2469. */
  2470. static int ssl_flight_append( mbedtls_ssl_context *ssl )
  2471. {
  2472. mbedtls_ssl_flight_item *msg;
  2473. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_flight_append" ) );
  2474. MBEDTLS_SSL_DEBUG_BUF( 4, "message appended to flight",
  2475. ssl->out_msg, ssl->out_msglen );
  2476. /* Allocate space for current message */
  2477. if( ( msg = mbedtls_calloc( 1, sizeof( mbedtls_ssl_flight_item ) ) ) == NULL )
  2478. {
  2479. MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed",
  2480. sizeof( mbedtls_ssl_flight_item ) ) );
  2481. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  2482. }
  2483. if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL )
  2484. {
  2485. MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", ssl->out_msglen ) );
  2486. mbedtls_free( msg );
  2487. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  2488. }
  2489. /* Copy current handshake message with headers */
  2490. memcpy( msg->p, ssl->out_msg, ssl->out_msglen );
  2491. msg->len = ssl->out_msglen;
  2492. msg->type = ssl->out_msgtype;
  2493. msg->next = NULL;
  2494. /* Append to the current flight */
  2495. if( ssl->handshake->flight == NULL )
  2496. ssl->handshake->flight = msg;
  2497. else
  2498. {
  2499. mbedtls_ssl_flight_item *cur = ssl->handshake->flight;
  2500. while( cur->next != NULL )
  2501. cur = cur->next;
  2502. cur->next = msg;
  2503. }
  2504. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_flight_append" ) );
  2505. return( 0 );
  2506. }
  2507. /*
  2508. * Free the current flight of handshake messages
  2509. */
  2510. static void ssl_flight_free( mbedtls_ssl_flight_item *flight )
  2511. {
  2512. mbedtls_ssl_flight_item *cur = flight;
  2513. mbedtls_ssl_flight_item *next;
  2514. while( cur != NULL )
  2515. {
  2516. next = cur->next;
  2517. mbedtls_free( cur->p );
  2518. mbedtls_free( cur );
  2519. cur = next;
  2520. }
  2521. }
  2522. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  2523. static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl );
  2524. #endif
  2525. /*
  2526. * Swap transform_out and out_ctr with the alternative ones
  2527. */
  2528. static int ssl_swap_epochs( mbedtls_ssl_context *ssl )
  2529. {
  2530. mbedtls_ssl_transform *tmp_transform;
  2531. unsigned char tmp_out_ctr[8];
  2532. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  2533. int ret;
  2534. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  2535. if( ssl->transform_out == ssl->handshake->alt_transform_out )
  2536. {
  2537. MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) );
  2538. return( 0 );
  2539. }
  2540. MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) );
  2541. /* Swap transforms */
  2542. tmp_transform = ssl->transform_out;
  2543. ssl->transform_out = ssl->handshake->alt_transform_out;
  2544. ssl->handshake->alt_transform_out = tmp_transform;
  2545. /* Swap epoch + sequence_number */
  2546. memcpy( tmp_out_ctr, ssl->cur_out_ctr, 8 );
  2547. memcpy( ssl->cur_out_ctr, ssl->handshake->alt_out_ctr, 8 );
  2548. memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr, 8 );
  2549. /* Adjust to the newly activated transform */
  2550. ssl_update_out_pointers( ssl, ssl->transform_out );
  2551. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  2552. if( mbedtls_ssl_hw_record_activate != NULL )
  2553. {
  2554. if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
  2555. {
  2556. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
  2557. return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  2558. }
  2559. }
  2560. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  2561. return( 0 );
  2562. }
  2563. /*
  2564. * Retransmit the current flight of messages.
  2565. */
  2566. int mbedtls_ssl_resend( mbedtls_ssl_context *ssl )
  2567. {
  2568. int ret = 0;
  2569. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) );
  2570. ret = mbedtls_ssl_flight_transmit( ssl );
  2571. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) );
  2572. return( ret );
  2573. }
  2574. /*
  2575. * Transmit or retransmit the current flight of messages.
  2576. *
  2577. * Need to remember the current message in case flush_output returns
  2578. * WANT_WRITE, causing us to exit this function and come back later.
  2579. * This function must be called until state is no longer SENDING.
  2580. */
  2581. int mbedtls_ssl_flight_transmit( mbedtls_ssl_context *ssl )
  2582. {
  2583. int ret;
  2584. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_flight_transmit" ) );
  2585. if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING )
  2586. {
  2587. MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise flight transmission" ) );
  2588. ssl->handshake->cur_msg = ssl->handshake->flight;
  2589. ssl->handshake->cur_msg_p = ssl->handshake->flight->p + 12;
  2590. if( ( ret = ssl_swap_epochs( ssl ) ) != 0 )
  2591. return( ret );
  2592. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;
  2593. }
  2594. while( ssl->handshake->cur_msg != NULL )
  2595. {
  2596. size_t max_frag_len;
  2597. const mbedtls_ssl_flight_item * const cur = ssl->handshake->cur_msg;
  2598. int const is_finished =
  2599. ( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2600. cur->p[0] == MBEDTLS_SSL_HS_FINISHED );
  2601. uint8_t const force_flush = ssl->disable_datagram_packing == 1 ?
  2602. SSL_FORCE_FLUSH : SSL_DONT_FORCE_FLUSH;
  2603. /* Swap epochs before sending Finished: we can't do it after
  2604. * sending ChangeCipherSpec, in case write returns WANT_READ.
  2605. * Must be done before copying, may change out_msg pointer */
  2606. if( is_finished && ssl->handshake->cur_msg_p == ( cur->p + 12 ) )
  2607. {
  2608. MBEDTLS_SSL_DEBUG_MSG( 2, ( "swap epochs to send finished message" ) );
  2609. if( ( ret = ssl_swap_epochs( ssl ) ) != 0 )
  2610. return( ret );
  2611. }
  2612. ret = ssl_get_remaining_payload_in_datagram( ssl );
  2613. if( ret < 0 )
  2614. return( ret );
  2615. max_frag_len = (size_t) ret;
  2616. /* CCS is copied as is, while HS messages may need fragmentation */
  2617. if( cur->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
  2618. {
  2619. if( max_frag_len == 0 )
  2620. {
  2621. if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  2622. return( ret );
  2623. continue;
  2624. }
  2625. memcpy( ssl->out_msg, cur->p, cur->len );
  2626. ssl->out_msglen = cur->len;
  2627. ssl->out_msgtype = cur->type;
  2628. /* Update position inside current message */
  2629. ssl->handshake->cur_msg_p += cur->len;
  2630. }
  2631. else
  2632. {
  2633. const unsigned char * const p = ssl->handshake->cur_msg_p;
  2634. const size_t hs_len = cur->len - 12;
  2635. const size_t frag_off = p - ( cur->p + 12 );
  2636. const size_t rem_len = hs_len - frag_off;
  2637. size_t cur_hs_frag_len, max_hs_frag_len;
  2638. if( ( max_frag_len < 12 ) || ( max_frag_len == 12 && hs_len != 0 ) )
  2639. {
  2640. if( is_finished )
  2641. {
  2642. if( ( ret = ssl_swap_epochs( ssl ) ) != 0 )
  2643. return( ret );
  2644. }
  2645. if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  2646. return( ret );
  2647. continue;
  2648. }
  2649. max_hs_frag_len = max_frag_len - 12;
  2650. cur_hs_frag_len = rem_len > max_hs_frag_len ?
  2651. max_hs_frag_len : rem_len;
  2652. if( frag_off == 0 && cur_hs_frag_len != hs_len )
  2653. {
  2654. MBEDTLS_SSL_DEBUG_MSG( 2, ( "fragmenting handshake message (%u > %u)",
  2655. (unsigned) cur_hs_frag_len,
  2656. (unsigned) max_hs_frag_len ) );
  2657. }
  2658. /* Messages are stored with handshake headers as if not fragmented,
  2659. * copy beginning of headers then fill fragmentation fields.
  2660. * Handshake headers: type(1) len(3) seq(2) f_off(3) f_len(3) */
  2661. memcpy( ssl->out_msg, cur->p, 6 );
  2662. ssl->out_msg[6] = ( ( frag_off >> 16 ) & 0xff );
  2663. ssl->out_msg[7] = ( ( frag_off >> 8 ) & 0xff );
  2664. ssl->out_msg[8] = ( ( frag_off ) & 0xff );
  2665. ssl->out_msg[ 9] = ( ( cur_hs_frag_len >> 16 ) & 0xff );
  2666. ssl->out_msg[10] = ( ( cur_hs_frag_len >> 8 ) & 0xff );
  2667. ssl->out_msg[11] = ( ( cur_hs_frag_len ) & 0xff );
  2668. MBEDTLS_SSL_DEBUG_BUF( 3, "handshake header", ssl->out_msg, 12 );
  2669. /* Copy the handshake message content and set records fields */
  2670. memcpy( ssl->out_msg + 12, p, cur_hs_frag_len );
  2671. ssl->out_msglen = cur_hs_frag_len + 12;
  2672. ssl->out_msgtype = cur->type;
  2673. /* Update position inside current message */
  2674. ssl->handshake->cur_msg_p += cur_hs_frag_len;
  2675. }
  2676. /* If done with the current message move to the next one if any */
  2677. if( ssl->handshake->cur_msg_p >= cur->p + cur->len )
  2678. {
  2679. if( cur->next != NULL )
  2680. {
  2681. ssl->handshake->cur_msg = cur->next;
  2682. ssl->handshake->cur_msg_p = cur->next->p + 12;
  2683. }
  2684. else
  2685. {
  2686. ssl->handshake->cur_msg = NULL;
  2687. ssl->handshake->cur_msg_p = NULL;
  2688. }
  2689. }
  2690. /* Actually send the message out */
  2691. if( ( ret = mbedtls_ssl_write_record( ssl, force_flush ) ) != 0 )
  2692. {
  2693. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
  2694. return( ret );
  2695. }
  2696. }
  2697. if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  2698. return( ret );
  2699. /* Update state and set timer */
  2700. if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
  2701. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
  2702. else
  2703. {
  2704. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
  2705. ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
  2706. }
  2707. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_flight_transmit" ) );
  2708. return( 0 );
  2709. }
  2710. /*
  2711. * To be called when the last message of an incoming flight is received.
  2712. */
  2713. void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl )
  2714. {
  2715. /* We won't need to resend that one any more */
  2716. ssl_flight_free( ssl->handshake->flight );
  2717. ssl->handshake->flight = NULL;
  2718. ssl->handshake->cur_msg = NULL;
  2719. /* The next incoming flight will start with this msg_seq */
  2720. ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;
  2721. /* We don't want to remember CCS's across flight boundaries. */
  2722. ssl->handshake->buffering.seen_ccs = 0;
  2723. /* Clear future message buffering structure. */
  2724. ssl_buffering_free( ssl );
  2725. /* Cancel timer */
  2726. ssl_set_timer( ssl, 0 );
  2727. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2728. ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
  2729. {
  2730. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
  2731. }
  2732. else
  2733. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
  2734. }
  2735. /*
  2736. * To be called when the last message of an outgoing flight is send.
  2737. */
  2738. void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl )
  2739. {
  2740. ssl_reset_retransmit_timeout( ssl );
  2741. ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
  2742. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2743. ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
  2744. {
  2745. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
  2746. }
  2747. else
  2748. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
  2749. }
  2750. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  2751. /*
  2752. * Handshake layer functions
  2753. */
  2754. /*
  2755. * Write (DTLS: or queue) current handshake (including CCS) message.
  2756. *
  2757. * - fill in handshake headers
  2758. * - update handshake checksum
  2759. * - DTLS: save message for resending
  2760. * - then pass to the record layer
  2761. *
  2762. * DTLS: except for HelloRequest, messages are only queued, and will only be
  2763. * actually sent when calling flight_transmit() or resend().
  2764. *
  2765. * Inputs:
  2766. * - ssl->out_msglen: 4 + actual handshake message len
  2767. * (4 is the size of handshake headers for TLS)
  2768. * - ssl->out_msg[0]: the handshake type (ClientHello, ServerHello, etc)
  2769. * - ssl->out_msg + 4: the handshake message body
  2770. *
  2771. * Outputs, ie state before passing to flight_append() or write_record():
  2772. * - ssl->out_msglen: the length of the record contents
  2773. * (including handshake headers but excluding record headers)
  2774. * - ssl->out_msg: the record contents (handshake headers + content)
  2775. */
  2776. int mbedtls_ssl_write_handshake_msg( mbedtls_ssl_context *ssl )
  2777. {
  2778. int ret;
  2779. const size_t hs_len = ssl->out_msglen - 4;
  2780. const unsigned char hs_type = ssl->out_msg[0];
  2781. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write handshake message" ) );
  2782. /*
  2783. * Sanity checks
  2784. */
  2785. if( ssl->out_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE &&
  2786. ssl->out_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
  2787. {
  2788. /* In SSLv3, the client might send a NoCertificate alert. */
  2789. #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
  2790. if( ! ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
  2791. ssl->out_msgtype == MBEDTLS_SSL_MSG_ALERT &&
  2792. ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) )
  2793. #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
  2794. {
  2795. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2796. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2797. }
  2798. }
  2799. /* Whenever we send anything different from a
  2800. * HelloRequest we should be in a handshake - double check. */
  2801. if( ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2802. hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST ) &&
  2803. ssl->handshake == NULL )
  2804. {
  2805. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2806. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2807. }
  2808. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2809. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  2810. ssl->handshake != NULL &&
  2811. ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
  2812. {
  2813. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2814. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2815. }
  2816. #endif
  2817. /* Double-check that we did not exceed the bounds
  2818. * of the outgoing record buffer.
  2819. * This should never fail as the various message
  2820. * writing functions must obey the bounds of the
  2821. * outgoing record buffer, but better be safe.
  2822. *
  2823. * Note: We deliberately do not check for the MTU or MFL here.
  2824. */
  2825. if( ssl->out_msglen > MBEDTLS_SSL_OUT_CONTENT_LEN )
  2826. {
  2827. MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record too large: "
  2828. "size %u, maximum %u",
  2829. (unsigned) ssl->out_msglen,
  2830. (unsigned) MBEDTLS_SSL_OUT_CONTENT_LEN ) );
  2831. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2832. }
  2833. /*
  2834. * Fill handshake headers
  2835. */
  2836. if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
  2837. {
  2838. ssl->out_msg[1] = (unsigned char)( hs_len >> 16 );
  2839. ssl->out_msg[2] = (unsigned char)( hs_len >> 8 );
  2840. ssl->out_msg[3] = (unsigned char)( hs_len );
  2841. /*
  2842. * DTLS has additional fields in the Handshake layer,
  2843. * between the length field and the actual payload:
  2844. * uint16 message_seq;
  2845. * uint24 fragment_offset;
  2846. * uint24 fragment_length;
  2847. */
  2848. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2849. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  2850. {
  2851. /* Make room for the additional DTLS fields */
  2852. if( MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen < 8 )
  2853. {
  2854. MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS handshake message too large: "
  2855. "size %u, maximum %u",
  2856. (unsigned) ( hs_len ),
  2857. (unsigned) ( MBEDTLS_SSL_OUT_CONTENT_LEN - 12 ) ) );
  2858. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2859. }
  2860. memmove( ssl->out_msg + 12, ssl->out_msg + 4, hs_len );
  2861. ssl->out_msglen += 8;
  2862. /* Write message_seq and update it, except for HelloRequest */
  2863. if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
  2864. {
  2865. ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF;
  2866. ssl->out_msg[5] = ( ssl->handshake->out_msg_seq ) & 0xFF;
  2867. ++( ssl->handshake->out_msg_seq );
  2868. }
  2869. else
  2870. {
  2871. ssl->out_msg[4] = 0;
  2872. ssl->out_msg[5] = 0;
  2873. }
  2874. /* Handshake hashes are computed without fragmentation,
  2875. * so set frag_offset = 0 and frag_len = hs_len for now */
  2876. memset( ssl->out_msg + 6, 0x00, 3 );
  2877. memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 );
  2878. }
  2879. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  2880. /* Update running hashes of handshake messages seen */
  2881. if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
  2882. ssl->handshake->update_checksum( ssl, ssl->out_msg, ssl->out_msglen );
  2883. }
  2884. /* Either send now, or just save to be sent (and resent) later */
  2885. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2886. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  2887. ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2888. hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST ) )
  2889. {
  2890. if( ( ret = ssl_flight_append( ssl ) ) != 0 )
  2891. {
  2892. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret );
  2893. return( ret );
  2894. }
  2895. }
  2896. else
  2897. #endif
  2898. {
  2899. if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
  2900. {
  2901. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_record", ret );
  2902. return( ret );
  2903. }
  2904. }
  2905. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write handshake message" ) );
  2906. return( 0 );
  2907. }
  2908. /*
  2909. * Record layer functions
  2910. */
  2911. /*
  2912. * Write current record.
  2913. *
  2914. * Uses:
  2915. * - ssl->out_msgtype: type of the message (AppData, Handshake, Alert, CCS)
  2916. * - ssl->out_msglen: length of the record content (excl headers)
  2917. * - ssl->out_msg: record content
  2918. */
  2919. int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl, uint8_t force_flush )
  2920. {
  2921. int ret, done = 0;
  2922. size_t len = ssl->out_msglen;
  2923. uint8_t flush = force_flush;
  2924. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) );
  2925. #if defined(MBEDTLS_ZLIB_SUPPORT)
  2926. if( ssl->transform_out != NULL &&
  2927. ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
  2928. {
  2929. if( ( ret = ssl_compress_buf( ssl ) ) != 0 )
  2930. {
  2931. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret );
  2932. return( ret );
  2933. }
  2934. len = ssl->out_msglen;
  2935. }
  2936. #endif /*MBEDTLS_ZLIB_SUPPORT */
  2937. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  2938. if( mbedtls_ssl_hw_record_write != NULL )
  2939. {
  2940. MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) );
  2941. ret = mbedtls_ssl_hw_record_write( ssl );
  2942. if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
  2943. {
  2944. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret );
  2945. return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  2946. }
  2947. if( ret == 0 )
  2948. done = 1;
  2949. }
  2950. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  2951. if( !done )
  2952. {
  2953. unsigned i;
  2954. size_t protected_record_size;
  2955. ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
  2956. mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
  2957. ssl->conf->transport, ssl->out_hdr + 1 );
  2958. memcpy( ssl->out_ctr, ssl->cur_out_ctr, 8 );
  2959. ssl->out_len[0] = (unsigned char)( len >> 8 );
  2960. ssl->out_len[1] = (unsigned char)( len );
  2961. if( ssl->transform_out != NULL )
  2962. {
  2963. if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 )
  2964. {
  2965. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret );
  2966. return( ret );
  2967. }
  2968. len = ssl->out_msglen;
  2969. ssl->out_len[0] = (unsigned char)( len >> 8 );
  2970. ssl->out_len[1] = (unsigned char)( len );
  2971. }
  2972. protected_record_size = len + mbedtls_ssl_hdr_len( ssl );
  2973. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2974. /* In case of DTLS, double-check that we don't exceed
  2975. * the remaining space in the datagram. */
  2976. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  2977. {
  2978. ret = ssl_get_remaining_space_in_datagram( ssl );
  2979. if( ret < 0 )
  2980. return( ret );
  2981. if( protected_record_size > (size_t) ret )
  2982. {
  2983. /* Should never happen */
  2984. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2985. }
  2986. }
  2987. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  2988. MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, "
  2989. "version = [%d:%d], msglen = %d",
  2990. ssl->out_hdr[0], ssl->out_hdr[1],
  2991. ssl->out_hdr[2], len ) );
  2992. MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
  2993. ssl->out_hdr, protected_record_size );
  2994. ssl->out_left += protected_record_size;
  2995. ssl->out_hdr += protected_record_size;
  2996. ssl_update_out_pointers( ssl, ssl->transform_out );
  2997. for( i = 8; i > ssl_ep_len( ssl ); i-- )
  2998. if( ++ssl->cur_out_ctr[i - 1] != 0 )
  2999. break;
  3000. /* The loop goes to its end iff the counter is wrapping */
  3001. if( i == ssl_ep_len( ssl ) )
  3002. {
  3003. MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) );
  3004. return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
  3005. }
  3006. }
  3007. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3008. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  3009. flush == SSL_DONT_FORCE_FLUSH )
  3010. {
  3011. size_t remaining;
  3012. ret = ssl_get_remaining_payload_in_datagram( ssl );
  3013. if( ret < 0 )
  3014. {
  3015. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_remaining_payload_in_datagram",
  3016. ret );
  3017. return( ret );
  3018. }
  3019. remaining = (size_t) ret;
  3020. if( remaining == 0 )
  3021. {
  3022. flush = SSL_FORCE_FLUSH;
  3023. }
  3024. else
  3025. {
  3026. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Still %u bytes available in current datagram", (unsigned) remaining ) );
  3027. }
  3028. }
  3029. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3030. if( ( flush == SSL_FORCE_FLUSH ) &&
  3031. ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  3032. {
  3033. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
  3034. return( ret );
  3035. }
  3036. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) );
  3037. return( 0 );
  3038. }
  3039. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3040. static int ssl_hs_is_proper_fragment( mbedtls_ssl_context *ssl )
  3041. {
  3042. if( ssl->in_msglen < ssl->in_hslen ||
  3043. memcmp( ssl->in_msg + 6, "\0\0\0", 3 ) != 0 ||
  3044. memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 )
  3045. {
  3046. return( 1 );
  3047. }
  3048. return( 0 );
  3049. }
  3050. static uint32_t ssl_get_hs_frag_len( mbedtls_ssl_context const *ssl )
  3051. {
  3052. return( ( ssl->in_msg[9] << 16 ) |
  3053. ( ssl->in_msg[10] << 8 ) |
  3054. ssl->in_msg[11] );
  3055. }
  3056. static uint32_t ssl_get_hs_frag_off( mbedtls_ssl_context const *ssl )
  3057. {
  3058. return( ( ssl->in_msg[6] << 16 ) |
  3059. ( ssl->in_msg[7] << 8 ) |
  3060. ssl->in_msg[8] );
  3061. }
  3062. static int ssl_check_hs_header( mbedtls_ssl_context const *ssl )
  3063. {
  3064. uint32_t msg_len, frag_off, frag_len;
  3065. msg_len = ssl_get_hs_total_len( ssl );
  3066. frag_off = ssl_get_hs_frag_off( ssl );
  3067. frag_len = ssl_get_hs_frag_len( ssl );
  3068. if( frag_off > msg_len )
  3069. return( -1 );
  3070. if( frag_len > msg_len - frag_off )
  3071. return( -1 );
  3072. if( frag_len + 12 > ssl->in_msglen )
  3073. return( -1 );
  3074. return( 0 );
  3075. }
  3076. /*
  3077. * Mark bits in bitmask (used for DTLS HS reassembly)
  3078. */
  3079. static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len )
  3080. {
  3081. unsigned int start_bits, end_bits;
  3082. start_bits = 8 - ( offset % 8 );
  3083. if( start_bits != 8 )
  3084. {
  3085. size_t first_byte_idx = offset / 8;
  3086. /* Special case */
  3087. if( len <= start_bits )
  3088. {
  3089. for( ; len != 0; len-- )
  3090. mask[first_byte_idx] |= 1 << ( start_bits - len );
  3091. /* Avoid potential issues with offset or len becoming invalid */
  3092. return;
  3093. }
  3094. offset += start_bits; /* Now offset % 8 == 0 */
  3095. len -= start_bits;
  3096. for( ; start_bits != 0; start_bits-- )
  3097. mask[first_byte_idx] |= 1 << ( start_bits - 1 );
  3098. }
  3099. end_bits = len % 8;
  3100. if( end_bits != 0 )
  3101. {
  3102. size_t last_byte_idx = ( offset + len ) / 8;
  3103. len -= end_bits; /* Now len % 8 == 0 */
  3104. for( ; end_bits != 0; end_bits-- )
  3105. mask[last_byte_idx] |= 1 << ( 8 - end_bits );
  3106. }
  3107. memset( mask + offset / 8, 0xFF, len / 8 );
  3108. }
  3109. /*
  3110. * Check that bitmask is full
  3111. */
  3112. static int ssl_bitmask_check( unsigned char *mask, size_t len )
  3113. {
  3114. size_t i;
  3115. for( i = 0; i < len / 8; i++ )
  3116. if( mask[i] != 0xFF )
  3117. return( -1 );
  3118. for( i = 0; i < len % 8; i++ )
  3119. if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 )
  3120. return( -1 );
  3121. return( 0 );
  3122. }
  3123. /* msg_len does not include the handshake header */
  3124. static size_t ssl_get_reassembly_buffer_size( size_t msg_len,
  3125. unsigned add_bitmap )
  3126. {
  3127. size_t alloc_len;
  3128. alloc_len = 12; /* Handshake header */
  3129. alloc_len += msg_len; /* Content buffer */
  3130. if( add_bitmap )
  3131. alloc_len += msg_len / 8 + ( msg_len % 8 != 0 ); /* Bitmap */
  3132. return( alloc_len );
  3133. }
  3134. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3135. static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl )
  3136. {
  3137. return( ( ssl->in_msg[1] << 16 ) |
  3138. ( ssl->in_msg[2] << 8 ) |
  3139. ssl->in_msg[3] );
  3140. }
  3141. int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl )
  3142. {
  3143. if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) )
  3144. {
  3145. MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %d",
  3146. ssl->in_msglen ) );
  3147. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3148. }
  3149. ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + ssl_get_hs_total_len( ssl );
  3150. MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen ="
  3151. " %d, type = %d, hslen = %d",
  3152. ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );
  3153. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3154. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  3155. {
  3156. int ret;
  3157. unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
  3158. if( ssl_check_hs_header( ssl ) != 0 )
  3159. {
  3160. MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid handshake header" ) );
  3161. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3162. }
  3163. if( ssl->handshake != NULL &&
  3164. ( ( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER &&
  3165. recv_msg_seq != ssl->handshake->in_msg_seq ) ||
  3166. ( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER &&
  3167. ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) ) )
  3168. {
  3169. if( recv_msg_seq > ssl->handshake->in_msg_seq )
  3170. {
  3171. MBEDTLS_SSL_DEBUG_MSG( 2, ( "received future handshake message of sequence number %u (next %u)",
  3172. recv_msg_seq,
  3173. ssl->handshake->in_msg_seq ) );
  3174. return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
  3175. }
  3176. /* Retransmit only on last message from previous flight, to avoid
  3177. * too many retransmissions.
  3178. * Besides, No sane server ever retransmits HelloVerifyRequest */
  3179. if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 &&
  3180. ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
  3181. {
  3182. MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, "
  3183. "message_seq = %d, start_of_flight = %d",
  3184. recv_msg_seq,
  3185. ssl->handshake->in_flight_start_seq ) );
  3186. if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
  3187. {
  3188. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
  3189. return( ret );
  3190. }
  3191. }
  3192. else
  3193. {
  3194. MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: "
  3195. "message_seq = %d, expected = %d",
  3196. recv_msg_seq,
  3197. ssl->handshake->in_msg_seq ) );
  3198. }
  3199. return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
  3200. }
  3201. /* Wait until message completion to increment in_msg_seq */
  3202. /* Message reassembly is handled alongside buffering of future
  3203. * messages; the commonality is that both handshake fragments and
  3204. * future messages cannot be forwarded immediately to the
  3205. * handshake logic layer. */
  3206. if( ssl_hs_is_proper_fragment( ssl ) == 1 )
  3207. {
  3208. MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) );
  3209. return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
  3210. }
  3211. }
  3212. else
  3213. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3214. /* With TLS we don't handle fragmentation (for now) */
  3215. if( ssl->in_msglen < ssl->in_hslen )
  3216. {
  3217. MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) );
  3218. return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  3219. }
  3220. return( 0 );
  3221. }
  3222. void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl )
  3223. {
  3224. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  3225. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && hs != NULL )
  3226. {
  3227. ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );
  3228. }
  3229. /* Handshake message is complete, increment counter */
  3230. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3231. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  3232. ssl->handshake != NULL )
  3233. {
  3234. unsigned offset;
  3235. mbedtls_ssl_hs_buffer *hs_buf;
  3236. /* Increment handshake sequence number */
  3237. hs->in_msg_seq++;
  3238. /*
  3239. * Clear up handshake buffering and reassembly structure.
  3240. */
  3241. /* Free first entry */
  3242. ssl_buffering_free_slot( ssl, 0 );
  3243. /* Shift all other entries */
  3244. for( offset = 0, hs_buf = &hs->buffering.hs[0];
  3245. offset + 1 < MBEDTLS_SSL_MAX_BUFFERED_HS;
  3246. offset++, hs_buf++ )
  3247. {
  3248. *hs_buf = *(hs_buf + 1);
  3249. }
  3250. /* Create a fresh last entry */
  3251. memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) );
  3252. }
  3253. #endif
  3254. }
  3255. /*
  3256. * DTLS anti-replay: RFC 6347 4.1.2.6
  3257. *
  3258. * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).
  3259. * Bit n is set iff record number in_window_top - n has been seen.
  3260. *
  3261. * Usually, in_window_top is the last record number seen and the lsb of
  3262. * in_window is set. The only exception is the initial state (record number 0
  3263. * not seen yet).
  3264. */
  3265. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  3266. static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl )
  3267. {
  3268. ssl->in_window_top = 0;
  3269. ssl->in_window = 0;
  3270. }
  3271. static inline uint64_t ssl_load_six_bytes( unsigned char *buf )
  3272. {
  3273. return( ( (uint64_t) buf[0] << 40 ) |
  3274. ( (uint64_t) buf[1] << 32 ) |
  3275. ( (uint64_t) buf[2] << 24 ) |
  3276. ( (uint64_t) buf[3] << 16 ) |
  3277. ( (uint64_t) buf[4] << 8 ) |
  3278. ( (uint64_t) buf[5] ) );
  3279. }
  3280. /*
  3281. * Return 0 if sequence number is acceptable, -1 otherwise
  3282. */
  3283. int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context *ssl )
  3284. {
  3285. uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
  3286. uint64_t bit;
  3287. if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
  3288. return( 0 );
  3289. if( rec_seqnum > ssl->in_window_top )
  3290. return( 0 );
  3291. bit = ssl->in_window_top - rec_seqnum;
  3292. if( bit >= 64 )
  3293. return( -1 );
  3294. if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 )
  3295. return( -1 );
  3296. return( 0 );
  3297. }
  3298. /*
  3299. * Update replay window on new validated record
  3300. */
  3301. void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl )
  3302. {
  3303. uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
  3304. if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
  3305. return;
  3306. if( rec_seqnum > ssl->in_window_top )
  3307. {
  3308. /* Update window_top and the contents of the window */
  3309. uint64_t shift = rec_seqnum - ssl->in_window_top;
  3310. if( shift >= 64 )
  3311. ssl->in_window = 1;
  3312. else
  3313. {
  3314. ssl->in_window <<= shift;
  3315. ssl->in_window |= 1;
  3316. }
  3317. ssl->in_window_top = rec_seqnum;
  3318. }
  3319. else
  3320. {
  3321. /* Mark that number as seen in the current window */
  3322. uint64_t bit = ssl->in_window_top - rec_seqnum;
  3323. if( bit < 64 ) /* Always true, but be extra sure */
  3324. ssl->in_window |= (uint64_t) 1 << bit;
  3325. }
  3326. }
  3327. #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
  3328. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
  3329. /* Forward declaration */
  3330. static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial );
  3331. /*
  3332. * Without any SSL context, check if a datagram looks like a ClientHello with
  3333. * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message.
  3334. * Both input and output include full DTLS headers.
  3335. *
  3336. * - if cookie is valid, return 0
  3337. * - if ClientHello looks superficially valid but cookie is not,
  3338. * fill obuf and set olen, then
  3339. * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
  3340. * - otherwise return a specific error code
  3341. */
  3342. static int ssl_check_dtls_clihlo_cookie(
  3343. mbedtls_ssl_cookie_write_t *f_cookie_write,
  3344. mbedtls_ssl_cookie_check_t *f_cookie_check,
  3345. void *p_cookie,
  3346. const unsigned char *cli_id, size_t cli_id_len,
  3347. const unsigned char *in, size_t in_len,
  3348. unsigned char *obuf, size_t buf_len, size_t *olen )
  3349. {
  3350. size_t sid_len, cookie_len;
  3351. unsigned char *p;
  3352. if( f_cookie_write == NULL || f_cookie_check == NULL )
  3353. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  3354. /*
  3355. * Structure of ClientHello with record and handshake headers,
  3356. * and expected values. We don't need to check a lot, more checks will be
  3357. * done when actually parsing the ClientHello - skipping those checks
  3358. * avoids code duplication and does not make cookie forging any easier.
  3359. *
  3360. * 0-0 ContentType type; copied, must be handshake
  3361. * 1-2 ProtocolVersion version; copied
  3362. * 3-4 uint16 epoch; copied, must be 0
  3363. * 5-10 uint48 sequence_number; copied
  3364. * 11-12 uint16 length; (ignored)
  3365. *
  3366. * 13-13 HandshakeType msg_type; (ignored)
  3367. * 14-16 uint24 length; (ignored)
  3368. * 17-18 uint16 message_seq; copied
  3369. * 19-21 uint24 fragment_offset; copied, must be 0
  3370. * 22-24 uint24 fragment_length; (ignored)
  3371. *
  3372. * 25-26 ProtocolVersion client_version; (ignored)
  3373. * 27-58 Random random; (ignored)
  3374. * 59-xx SessionID session_id; 1 byte len + sid_len content
  3375. * 60+ opaque cookie<0..2^8-1>; 1 byte len + content
  3376. * ...
  3377. *
  3378. * Minimum length is 61 bytes.
  3379. */
  3380. if( in_len < 61 ||
  3381. in[0] != MBEDTLS_SSL_MSG_HANDSHAKE ||
  3382. in[3] != 0 || in[4] != 0 ||
  3383. in[19] != 0 || in[20] != 0 || in[21] != 0 )
  3384. {
  3385. return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  3386. }
  3387. sid_len = in[59];
  3388. if( sid_len > in_len - 61 )
  3389. return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  3390. cookie_len = in[60 + sid_len];
  3391. if( cookie_len > in_len - 60 )
  3392. return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  3393. if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len,
  3394. cli_id, cli_id_len ) == 0 )
  3395. {
  3396. /* Valid cookie */
  3397. return( 0 );
  3398. }
  3399. /*
  3400. * If we get here, we've got an invalid cookie, let's prepare HVR.
  3401. *
  3402. * 0-0 ContentType type; copied
  3403. * 1-2 ProtocolVersion version; copied
  3404. * 3-4 uint16 epoch; copied
  3405. * 5-10 uint48 sequence_number; copied
  3406. * 11-12 uint16 length; olen - 13
  3407. *
  3408. * 13-13 HandshakeType msg_type; hello_verify_request
  3409. * 14-16 uint24 length; olen - 25
  3410. * 17-18 uint16 message_seq; copied
  3411. * 19-21 uint24 fragment_offset; copied
  3412. * 22-24 uint24 fragment_length; olen - 25
  3413. *
  3414. * 25-26 ProtocolVersion server_version; 0xfe 0xff
  3415. * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie
  3416. *
  3417. * Minimum length is 28.
  3418. */
  3419. if( buf_len < 28 )
  3420. return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
  3421. /* Copy most fields and adapt others */
  3422. memcpy( obuf, in, 25 );
  3423. obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
  3424. obuf[25] = 0xfe;
  3425. obuf[26] = 0xff;
  3426. /* Generate and write actual cookie */
  3427. p = obuf + 28;
  3428. if( f_cookie_write( p_cookie,
  3429. &p, obuf + buf_len, cli_id, cli_id_len ) != 0 )
  3430. {
  3431. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3432. }
  3433. *olen = p - obuf;
  3434. /* Go back and fill length fields */
  3435. obuf[27] = (unsigned char)( *olen - 28 );
  3436. obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 );
  3437. obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >> 8 );
  3438. obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 ) );
  3439. obuf[11] = (unsigned char)( ( *olen - 13 ) >> 8 );
  3440. obuf[12] = (unsigned char)( ( *olen - 13 ) );
  3441. return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
  3442. }
  3443. /*
  3444. * Handle possible client reconnect with the same UDP quadruplet
  3445. * (RFC 6347 Section 4.2.8).
  3446. *
  3447. * Called by ssl_parse_record_header() in case we receive an epoch 0 record
  3448. * that looks like a ClientHello.
  3449. *
  3450. * - if the input looks like a ClientHello without cookies,
  3451. * send back HelloVerifyRequest, then
  3452. * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
  3453. * - if the input looks like a ClientHello with a valid cookie,
  3454. * reset the session of the current context, and
  3455. * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT
  3456. * - if anything goes wrong, return a specific error code
  3457. *
  3458. * mbedtls_ssl_read_record() will ignore the record if anything else than
  3459. * MBEDTLS_ERR_SSL_CLIENT_RECONNECT or 0 is returned, although this function
  3460. * cannot not return 0.
  3461. */
  3462. static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl )
  3463. {
  3464. int ret;
  3465. size_t len;
  3466. ret = ssl_check_dtls_clihlo_cookie(
  3467. ssl->conf->f_cookie_write,
  3468. ssl->conf->f_cookie_check,
  3469. ssl->conf->p_cookie,
  3470. ssl->cli_id, ssl->cli_id_len,
  3471. ssl->in_buf, ssl->in_left,
  3472. ssl->out_buf, MBEDTLS_SSL_OUT_CONTENT_LEN, &len );
  3473. MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_dtls_clihlo_cookie", ret );
  3474. if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED )
  3475. {
  3476. int send_ret;
  3477. MBEDTLS_SSL_DEBUG_MSG( 1, ( "sending HelloVerifyRequest" ) );
  3478. MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
  3479. ssl->out_buf, len );
  3480. /* Don't check write errors as we can't do anything here.
  3481. * If the error is permanent we'll catch it later,
  3482. * if it's not, then hopefully it'll work next time. */
  3483. send_ret = ssl->f_send( ssl->p_bio, ssl->out_buf, len );
  3484. MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", send_ret );
  3485. (void) send_ret;
  3486. return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
  3487. }
  3488. if( ret == 0 )
  3489. {
  3490. MBEDTLS_SSL_DEBUG_MSG( 1, ( "cookie is valid, resetting context" ) );
  3491. if( ( ret = ssl_session_reset_int( ssl, 1 ) ) != 0 )
  3492. {
  3493. MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret );
  3494. return( ret );
  3495. }
  3496. return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT );
  3497. }
  3498. return( ret );
  3499. }
  3500. #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
  3501. /*
  3502. * ContentType type;
  3503. * ProtocolVersion version;
  3504. * uint16 epoch; // DTLS only
  3505. * uint48 sequence_number; // DTLS only
  3506. * uint16 length;
  3507. *
  3508. * Return 0 if header looks sane (and, for DTLS, the record is expected)
  3509. * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad,
  3510. * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected.
  3511. *
  3512. * With DTLS, mbedtls_ssl_read_record() will:
  3513. * 1. proceed with the record if this function returns 0
  3514. * 2. drop only the current record if this function returns UNEXPECTED_RECORD
  3515. * 3. return CLIENT_RECONNECT if this function return that value
  3516. * 4. drop the whole datagram if this function returns anything else.
  3517. * Point 2 is needed when the peer is resending, and we have already received
  3518. * the first record from a datagram but are still waiting for the others.
  3519. */
  3520. static int ssl_parse_record_header( mbedtls_ssl_context *ssl )
  3521. {
  3522. int major_ver, minor_ver;
  3523. MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) );
  3524. ssl->in_msgtype = ssl->in_hdr[0];
  3525. ssl->in_msglen = ( ssl->in_len[0] << 8 ) | ssl->in_len[1];
  3526. mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, ssl->in_hdr + 1 );
  3527. MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, "
  3528. "version = [%d:%d], msglen = %d",
  3529. ssl->in_msgtype,
  3530. major_ver, minor_ver, ssl->in_msglen ) );
  3531. /* Check record type */
  3532. if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE &&
  3533. ssl->in_msgtype != MBEDTLS_SSL_MSG_ALERT &&
  3534. ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
  3535. ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
  3536. {
  3537. MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) );
  3538. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3539. /* Silently ignore invalid DTLS records as recommended by RFC 6347
  3540. * Section 4.1.2.7 */
  3541. if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  3542. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3543. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  3544. MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  3545. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3546. }
  3547. /* Check version */
  3548. if( major_ver != ssl->major_ver )
  3549. {
  3550. MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch" ) );
  3551. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3552. }
  3553. if( minor_ver > ssl->conf->max_minor_ver )
  3554. {
  3555. MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) );
  3556. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3557. }
  3558. /* Check length against the size of our buffer */
  3559. if( ssl->in_msglen > MBEDTLS_SSL_IN_BUFFER_LEN
  3560. - (size_t)( ssl->in_msg - ssl->in_buf ) )
  3561. {
  3562. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  3563. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3564. }
  3565. /*
  3566. * DTLS-related tests.
  3567. * Check epoch before checking length constraint because
  3568. * the latter varies with the epoch. E.g., if a ChangeCipherSpec
  3569. * message gets duplicated before the corresponding Finished message,
  3570. * the second ChangeCipherSpec should be discarded because it belongs
  3571. * to an old epoch, but not because its length is shorter than
  3572. * the minimum record length for packets using the new record transform.
  3573. * Note that these two kinds of failures are handled differently,
  3574. * as an unexpected record is silently skipped but an invalid
  3575. * record leads to the entire datagram being dropped.
  3576. */
  3577. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3578. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  3579. {
  3580. unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1];
  3581. /* Check epoch (and sequence number) with DTLS */
  3582. if( rec_epoch != ssl->in_epoch )
  3583. {
  3584. MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: "
  3585. "expected %d, received %d",
  3586. ssl->in_epoch, rec_epoch ) );
  3587. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
  3588. /*
  3589. * Check for an epoch 0 ClientHello. We can't use in_msg here to
  3590. * access the first byte of record content (handshake type), as we
  3591. * have an active transform (possibly iv_len != 0), so use the
  3592. * fact that the record header len is 13 instead.
  3593. */
  3594. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  3595. ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER &&
  3596. rec_epoch == 0 &&
  3597. ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  3598. ssl->in_left > 13 &&
  3599. ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO )
  3600. {
  3601. MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect "
  3602. "from the same port" ) );
  3603. return( ssl_handle_possible_reconnect( ssl ) );
  3604. }
  3605. else
  3606. #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
  3607. {
  3608. /* Consider buffering the record. */
  3609. if( rec_epoch == (unsigned int) ssl->in_epoch + 1 )
  3610. {
  3611. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Consider record for buffering" ) );
  3612. return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
  3613. }
  3614. return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
  3615. }
  3616. }
  3617. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  3618. /* Replay detection only works for the current epoch */
  3619. if( rec_epoch == ssl->in_epoch &&
  3620. mbedtls_ssl_dtls_replay_check( ssl ) != 0 )
  3621. {
  3622. MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) );
  3623. return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
  3624. }
  3625. #endif
  3626. /* Drop unexpected ApplicationData records,
  3627. * except at the beginning of renegotiations */
  3628. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA &&
  3629. ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER
  3630. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  3631. && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
  3632. ssl->state == MBEDTLS_SSL_SERVER_HELLO )
  3633. #endif
  3634. )
  3635. {
  3636. MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) );
  3637. return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
  3638. }
  3639. }
  3640. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3641. /* Check length against bounds of the current transform and version */
  3642. if( ssl->transform_in == NULL )
  3643. {
  3644. if( ssl->in_msglen < 1 ||
  3645. ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN )
  3646. {
  3647. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  3648. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3649. }
  3650. }
  3651. else
  3652. {
  3653. if( ssl->in_msglen < ssl->transform_in->minlen )
  3654. {
  3655. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  3656. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3657. }
  3658. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  3659. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
  3660. ssl->in_msglen > ssl->transform_in->minlen + MBEDTLS_SSL_IN_CONTENT_LEN )
  3661. {
  3662. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  3663. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3664. }
  3665. #endif
  3666. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  3667. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  3668. /*
  3669. * TLS encrypted messages can have up to 256 bytes of padding
  3670. */
  3671. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 &&
  3672. ssl->in_msglen > ssl->transform_in->minlen +
  3673. MBEDTLS_SSL_IN_CONTENT_LEN + 256 )
  3674. {
  3675. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  3676. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3677. }
  3678. #endif
  3679. }
  3680. return( 0 );
  3681. }
  3682. /*
  3683. * If applicable, decrypt (and decompress) record content
  3684. */
  3685. static int ssl_prepare_record_content( mbedtls_ssl_context *ssl )
  3686. {
  3687. int ret, done = 0;
  3688. MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network",
  3689. ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen );
  3690. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  3691. if( mbedtls_ssl_hw_record_read != NULL )
  3692. {
  3693. MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) );
  3694. ret = mbedtls_ssl_hw_record_read( ssl );
  3695. if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
  3696. {
  3697. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret );
  3698. return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  3699. }
  3700. if( ret == 0 )
  3701. done = 1;
  3702. }
  3703. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  3704. if( !done && ssl->transform_in != NULL )
  3705. {
  3706. if( ( ret = ssl_decrypt_buf( ssl ) ) != 0 )
  3707. {
  3708. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret );
  3709. return( ret );
  3710. }
  3711. MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt",
  3712. ssl->in_msg, ssl->in_msglen );
  3713. if( ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN )
  3714. {
  3715. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  3716. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3717. }
  3718. }
  3719. #if defined(MBEDTLS_ZLIB_SUPPORT)
  3720. if( ssl->transform_in != NULL &&
  3721. ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
  3722. {
  3723. if( ( ret = ssl_decompress_buf( ssl ) ) != 0 )
  3724. {
  3725. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret );
  3726. return( ret );
  3727. }
  3728. }
  3729. #endif /* MBEDTLS_ZLIB_SUPPORT */
  3730. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  3731. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  3732. {
  3733. mbedtls_ssl_dtls_replay_update( ssl );
  3734. }
  3735. #endif
  3736. return( 0 );
  3737. }
  3738. static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl );
  3739. /*
  3740. * Read a record.
  3741. *
  3742. * Silently ignore non-fatal alert (and for DTLS, invalid records as well,
  3743. * RFC 6347 4.1.2.7) and continue reading until a valid record is found.
  3744. *
  3745. */
  3746. /* Helper functions for mbedtls_ssl_read_record(). */
  3747. static int ssl_consume_current_message( mbedtls_ssl_context *ssl );
  3748. static int ssl_get_next_record( mbedtls_ssl_context *ssl );
  3749. static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl );
  3750. int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl,
  3751. unsigned update_hs_digest )
  3752. {
  3753. int ret;
  3754. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) );
  3755. if( ssl->keep_current_message == 0 )
  3756. {
  3757. do {
  3758. ret = ssl_consume_current_message( ssl );
  3759. if( ret != 0 )
  3760. return( ret );
  3761. if( ssl_record_is_in_progress( ssl ) == 0 )
  3762. {
  3763. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3764. int have_buffered = 0;
  3765. /* We only check for buffered messages if the
  3766. * current datagram is fully consumed. */
  3767. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  3768. ssl_next_record_is_in_datagram( ssl ) == 0 )
  3769. {
  3770. if( ssl_load_buffered_message( ssl ) == 0 )
  3771. have_buffered = 1;
  3772. }
  3773. if( have_buffered == 0 )
  3774. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3775. {
  3776. ret = ssl_get_next_record( ssl );
  3777. if( ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING )
  3778. continue;
  3779. if( ret != 0 )
  3780. {
  3781. MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_get_next_record" ), ret );
  3782. return( ret );
  3783. }
  3784. }
  3785. }
  3786. ret = mbedtls_ssl_handle_message_type( ssl );
  3787. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3788. if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
  3789. {
  3790. /* Buffer future message */
  3791. ret = ssl_buffer_message( ssl );
  3792. if( ret != 0 )
  3793. return( ret );
  3794. ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
  3795. }
  3796. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3797. } while( MBEDTLS_ERR_SSL_NON_FATAL == ret ||
  3798. MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret );
  3799. if( 0 != ret )
  3800. {
  3801. MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_handle_message_type" ), ret );
  3802. return( ret );
  3803. }
  3804. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  3805. update_hs_digest == 1 )
  3806. {
  3807. mbedtls_ssl_update_handshake_status( ssl );
  3808. }
  3809. }
  3810. else
  3811. {
  3812. MBEDTLS_SSL_DEBUG_MSG( 2, ( "reuse previously read message" ) );
  3813. ssl->keep_current_message = 0;
  3814. }
  3815. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) );
  3816. return( 0 );
  3817. }
  3818. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3819. static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl )
  3820. {
  3821. if( ssl->in_left > ssl->next_record_offset )
  3822. return( 1 );
  3823. return( 0 );
  3824. }
  3825. static int ssl_load_buffered_message( mbedtls_ssl_context *ssl )
  3826. {
  3827. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  3828. mbedtls_ssl_hs_buffer * hs_buf;
  3829. int ret = 0;
  3830. if( hs == NULL )
  3831. return( -1 );
  3832. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_messsage" ) );
  3833. if( ssl->state == MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC ||
  3834. ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
  3835. {
  3836. /* Check if we have seen a ChangeCipherSpec before.
  3837. * If yes, synthesize a CCS record. */
  3838. if( !hs->buffering.seen_ccs )
  3839. {
  3840. MBEDTLS_SSL_DEBUG_MSG( 2, ( "CCS not seen in the current flight" ) );
  3841. ret = -1;
  3842. goto exit;
  3843. }
  3844. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Injecting buffered CCS message" ) );
  3845. ssl->in_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
  3846. ssl->in_msglen = 1;
  3847. ssl->in_msg[0] = 1;
  3848. /* As long as they are equal, the exact value doesn't matter. */
  3849. ssl->in_left = 0;
  3850. ssl->next_record_offset = 0;
  3851. hs->buffering.seen_ccs = 0;
  3852. goto exit;
  3853. }
  3854. #if defined(MBEDTLS_DEBUG_C)
  3855. /* Debug only */
  3856. {
  3857. unsigned offset;
  3858. for( offset = 1; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ )
  3859. {
  3860. hs_buf = &hs->buffering.hs[offset];
  3861. if( hs_buf->is_valid == 1 )
  3862. {
  3863. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Future message with sequence number %u %s buffered.",
  3864. hs->in_msg_seq + offset,
  3865. hs_buf->is_complete ? "fully" : "partially" ) );
  3866. }
  3867. }
  3868. }
  3869. #endif /* MBEDTLS_DEBUG_C */
  3870. /* Check if we have buffered and/or fully reassembled the
  3871. * next handshake message. */
  3872. hs_buf = &hs->buffering.hs[0];
  3873. if( ( hs_buf->is_valid == 1 ) && ( hs_buf->is_complete == 1 ) )
  3874. {
  3875. /* Synthesize a record containing the buffered HS message. */
  3876. size_t msg_len = ( hs_buf->data[1] << 16 ) |
  3877. ( hs_buf->data[2] << 8 ) |
  3878. hs_buf->data[3];
  3879. /* Double-check that we haven't accidentally buffered
  3880. * a message that doesn't fit into the input buffer. */
  3881. if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN )
  3882. {
  3883. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  3884. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3885. }
  3886. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message has been buffered - load" ) );
  3887. MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered handshake message (incl. header)",
  3888. hs_buf->data, msg_len + 12 );
  3889. ssl->in_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  3890. ssl->in_hslen = msg_len + 12;
  3891. ssl->in_msglen = msg_len + 12;
  3892. memcpy( ssl->in_msg, hs_buf->data, ssl->in_hslen );
  3893. ret = 0;
  3894. goto exit;
  3895. }
  3896. else
  3897. {
  3898. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message %u not or only partially bufffered",
  3899. hs->in_msg_seq ) );
  3900. }
  3901. ret = -1;
  3902. exit:
  3903. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_message" ) );
  3904. return( ret );
  3905. }
  3906. static int ssl_buffer_make_space( mbedtls_ssl_context *ssl,
  3907. size_t desired )
  3908. {
  3909. int offset;
  3910. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  3911. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Attempt to free buffered messages to have %u bytes available",
  3912. (unsigned) desired ) );
  3913. /* Get rid of future records epoch first, if such exist. */
  3914. ssl_free_buffered_record( ssl );
  3915. /* Check if we have enough space available now. */
  3916. if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  3917. hs->buffering.total_bytes_buffered ) )
  3918. {
  3919. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing future epoch record" ) );
  3920. return( 0 );
  3921. }
  3922. /* We don't have enough space to buffer the next expected handshake
  3923. * message. Remove buffers used for future messages to gain space,
  3924. * starting with the most distant one. */
  3925. for( offset = MBEDTLS_SSL_MAX_BUFFERED_HS - 1;
  3926. offset >= 0; offset-- )
  3927. {
  3928. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Free buffering slot %d to make space for reassembly of next handshake message",
  3929. offset ) );
  3930. ssl_buffering_free_slot( ssl, (uint8_t) offset );
  3931. /* Check if we have enough space available now. */
  3932. if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  3933. hs->buffering.total_bytes_buffered ) )
  3934. {
  3935. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing buffered HS messages" ) );
  3936. return( 0 );
  3937. }
  3938. }
  3939. return( -1 );
  3940. }
  3941. static int ssl_buffer_message( mbedtls_ssl_context *ssl )
  3942. {
  3943. int ret = 0;
  3944. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  3945. if( hs == NULL )
  3946. return( 0 );
  3947. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_buffer_message" ) );
  3948. switch( ssl->in_msgtype )
  3949. {
  3950. case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC:
  3951. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Remember CCS message" ) );
  3952. hs->buffering.seen_ccs = 1;
  3953. break;
  3954. case MBEDTLS_SSL_MSG_HANDSHAKE:
  3955. {
  3956. unsigned recv_msg_seq_offset;
  3957. unsigned recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
  3958. mbedtls_ssl_hs_buffer *hs_buf;
  3959. size_t msg_len = ssl->in_hslen - 12;
  3960. /* We should never receive an old handshake
  3961. * message - double-check nonetheless. */
  3962. if( recv_msg_seq < ssl->handshake->in_msg_seq )
  3963. {
  3964. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  3965. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3966. }
  3967. recv_msg_seq_offset = recv_msg_seq - ssl->handshake->in_msg_seq;
  3968. if( recv_msg_seq_offset >= MBEDTLS_SSL_MAX_BUFFERED_HS )
  3969. {
  3970. /* Silently ignore -- message too far in the future */
  3971. MBEDTLS_SSL_DEBUG_MSG( 2,
  3972. ( "Ignore future HS message with sequence number %u, "
  3973. "buffering window %u - %u",
  3974. recv_msg_seq, ssl->handshake->in_msg_seq,
  3975. ssl->handshake->in_msg_seq + MBEDTLS_SSL_MAX_BUFFERED_HS - 1 ) );
  3976. goto exit;
  3977. }
  3978. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering HS message with sequence number %u, offset %u ",
  3979. recv_msg_seq, recv_msg_seq_offset ) );
  3980. hs_buf = &hs->buffering.hs[ recv_msg_seq_offset ];
  3981. /* Check if the buffering for this seq nr has already commenced. */
  3982. if( !hs_buf->is_valid )
  3983. {
  3984. size_t reassembly_buf_sz;
  3985. hs_buf->is_fragmented =
  3986. ( ssl_hs_is_proper_fragment( ssl ) == 1 );
  3987. /* We copy the message back into the input buffer
  3988. * after reassembly, so check that it's not too large.
  3989. * This is an implementation-specific limitation
  3990. * and not one from the standard, hence it is not
  3991. * checked in ssl_check_hs_header(). */
  3992. if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN )
  3993. {
  3994. /* Ignore message */
  3995. goto exit;
  3996. }
  3997. /* Check if we have enough space to buffer the message. */
  3998. if( hs->buffering.total_bytes_buffered >
  3999. MBEDTLS_SSL_DTLS_MAX_BUFFERING )
  4000. {
  4001. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4002. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4003. }
  4004. reassembly_buf_sz = ssl_get_reassembly_buffer_size( msg_len,
  4005. hs_buf->is_fragmented );
  4006. if( reassembly_buf_sz > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  4007. hs->buffering.total_bytes_buffered ) )
  4008. {
  4009. if( recv_msg_seq_offset > 0 )
  4010. {
  4011. /* If we can't buffer a future message because
  4012. * of space limitations -- ignore. */
  4013. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future message of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- ignore\n",
  4014. (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  4015. (unsigned) hs->buffering.total_bytes_buffered ) );
  4016. goto exit;
  4017. }
  4018. else
  4019. {
  4020. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future message of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- attempt to make space by freeing buffered future messages\n",
  4021. (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  4022. (unsigned) hs->buffering.total_bytes_buffered ) );
  4023. }
  4024. if( ssl_buffer_make_space( ssl, reassembly_buf_sz ) != 0 )
  4025. {
  4026. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reassembly of next message of size %u (%u with bitmap) would exceed the compile-time limit %u (already %u bytes buffered) -- fail\n",
  4027. (unsigned) msg_len,
  4028. (unsigned) reassembly_buf_sz,
  4029. MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  4030. (unsigned) hs->buffering.total_bytes_buffered ) );
  4031. ret = MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
  4032. goto exit;
  4033. }
  4034. }
  4035. MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %d",
  4036. msg_len ) );
  4037. hs_buf->data = mbedtls_calloc( 1, reassembly_buf_sz );
  4038. if( hs_buf->data == NULL )
  4039. {
  4040. ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
  4041. goto exit;
  4042. }
  4043. hs_buf->data_len = reassembly_buf_sz;
  4044. /* Prepare final header: copy msg_type, length and message_seq,
  4045. * then add standardised fragment_offset and fragment_length */
  4046. memcpy( hs_buf->data, ssl->in_msg, 6 );
  4047. memset( hs_buf->data + 6, 0, 3 );
  4048. memcpy( hs_buf->data + 9, hs_buf->data + 1, 3 );
  4049. hs_buf->is_valid = 1;
  4050. hs->buffering.total_bytes_buffered += reassembly_buf_sz;
  4051. }
  4052. else
  4053. {
  4054. /* Make sure msg_type and length are consistent */
  4055. if( memcmp( hs_buf->data, ssl->in_msg, 4 ) != 0 )
  4056. {
  4057. MBEDTLS_SSL_DEBUG_MSG( 1, ( "Fragment header mismatch - ignore" ) );
  4058. /* Ignore */
  4059. goto exit;
  4060. }
  4061. }
  4062. if( !hs_buf->is_complete )
  4063. {
  4064. size_t frag_len, frag_off;
  4065. unsigned char * const msg = hs_buf->data + 12;
  4066. /*
  4067. * Check and copy current fragment
  4068. */
  4069. /* Validation of header fields already done in
  4070. * mbedtls_ssl_prepare_handshake_record(). */
  4071. frag_off = ssl_get_hs_frag_off( ssl );
  4072. frag_len = ssl_get_hs_frag_len( ssl );
  4073. MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %d, length = %d",
  4074. frag_off, frag_len ) );
  4075. memcpy( msg + frag_off, ssl->in_msg + 12, frag_len );
  4076. if( hs_buf->is_fragmented )
  4077. {
  4078. unsigned char * const bitmask = msg + msg_len;
  4079. ssl_bitmask_set( bitmask, frag_off, frag_len );
  4080. hs_buf->is_complete = ( ssl_bitmask_check( bitmask,
  4081. msg_len ) == 0 );
  4082. }
  4083. else
  4084. {
  4085. hs_buf->is_complete = 1;
  4086. }
  4087. MBEDTLS_SSL_DEBUG_MSG( 2, ( "message %scomplete",
  4088. hs_buf->is_complete ? "" : "not yet " ) );
  4089. }
  4090. break;
  4091. }
  4092. default:
  4093. /* We don't buffer other types of messages. */
  4094. break;
  4095. }
  4096. exit:
  4097. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_buffer_message" ) );
  4098. return( ret );
  4099. }
  4100. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4101. static int ssl_consume_current_message( mbedtls_ssl_context *ssl )
  4102. {
  4103. /*
  4104. * Consume last content-layer message and potentially
  4105. * update in_msglen which keeps track of the contents'
  4106. * consumption state.
  4107. *
  4108. * (1) Handshake messages:
  4109. * Remove last handshake message, move content
  4110. * and adapt in_msglen.
  4111. *
  4112. * (2) Alert messages:
  4113. * Consume whole record content, in_msglen = 0.
  4114. *
  4115. * (3) Change cipher spec:
  4116. * Consume whole record content, in_msglen = 0.
  4117. *
  4118. * (4) Application data:
  4119. * Don't do anything - the record layer provides
  4120. * the application data as a stream transport
  4121. * and consumes through mbedtls_ssl_read only.
  4122. *
  4123. */
  4124. /* Case (1): Handshake messages */
  4125. if( ssl->in_hslen != 0 )
  4126. {
  4127. /* Hard assertion to be sure that no application data
  4128. * is in flight, as corrupting ssl->in_msglen during
  4129. * ssl->in_offt != NULL is fatal. */
  4130. if( ssl->in_offt != NULL )
  4131. {
  4132. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4133. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4134. }
  4135. /*
  4136. * Get next Handshake message in the current record
  4137. */
  4138. /* Notes:
  4139. * (1) in_hslen is not necessarily the size of the
  4140. * current handshake content: If DTLS handshake
  4141. * fragmentation is used, that's the fragment
  4142. * size instead. Using the total handshake message
  4143. * size here is faulty and should be changed at
  4144. * some point.
  4145. * (2) While it doesn't seem to cause problems, one
  4146. * has to be very careful not to assume that in_hslen
  4147. * is always <= in_msglen in a sensible communication.
  4148. * Again, it's wrong for DTLS handshake fragmentation.
  4149. * The following check is therefore mandatory, and
  4150. * should not be treated as a silently corrected assertion.
  4151. * Additionally, ssl->in_hslen might be arbitrarily out of
  4152. * bounds after handling a DTLS message with an unexpected
  4153. * sequence number, see mbedtls_ssl_prepare_handshake_record.
  4154. */
  4155. if( ssl->in_hslen < ssl->in_msglen )
  4156. {
  4157. ssl->in_msglen -= ssl->in_hslen;
  4158. memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen,
  4159. ssl->in_msglen );
  4160. MBEDTLS_SSL_DEBUG_BUF( 4, "remaining content in record",
  4161. ssl->in_msg, ssl->in_msglen );
  4162. }
  4163. else
  4164. {
  4165. ssl->in_msglen = 0;
  4166. }
  4167. ssl->in_hslen = 0;
  4168. }
  4169. /* Case (4): Application data */
  4170. else if( ssl->in_offt != NULL )
  4171. {
  4172. return( 0 );
  4173. }
  4174. /* Everything else (CCS & Alerts) */
  4175. else
  4176. {
  4177. ssl->in_msglen = 0;
  4178. }
  4179. return( 0 );
  4180. }
  4181. static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl )
  4182. {
  4183. if( ssl->in_msglen > 0 )
  4184. return( 1 );
  4185. return( 0 );
  4186. }
  4187. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4188. static void ssl_free_buffered_record( mbedtls_ssl_context *ssl )
  4189. {
  4190. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4191. if( hs == NULL )
  4192. return;
  4193. if( hs->buffering.future_record.data != NULL )
  4194. {
  4195. hs->buffering.total_bytes_buffered -=
  4196. hs->buffering.future_record.len;
  4197. mbedtls_free( hs->buffering.future_record.data );
  4198. hs->buffering.future_record.data = NULL;
  4199. }
  4200. }
  4201. static int ssl_load_buffered_record( mbedtls_ssl_context *ssl )
  4202. {
  4203. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4204. unsigned char * rec;
  4205. size_t rec_len;
  4206. unsigned rec_epoch;
  4207. if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  4208. return( 0 );
  4209. if( hs == NULL )
  4210. return( 0 );
  4211. rec = hs->buffering.future_record.data;
  4212. rec_len = hs->buffering.future_record.len;
  4213. rec_epoch = hs->buffering.future_record.epoch;
  4214. if( rec == NULL )
  4215. return( 0 );
  4216. /* Only consider loading future records if the
  4217. * input buffer is empty. */
  4218. if( ssl_next_record_is_in_datagram( ssl ) == 1 )
  4219. return( 0 );
  4220. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_record" ) );
  4221. if( rec_epoch != ssl->in_epoch )
  4222. {
  4223. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffered record not from current epoch." ) );
  4224. goto exit;
  4225. }
  4226. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Found buffered record from current epoch - load" ) );
  4227. /* Double-check that the record is not too large */
  4228. if( rec_len > MBEDTLS_SSL_IN_BUFFER_LEN -
  4229. (size_t)( ssl->in_hdr - ssl->in_buf ) )
  4230. {
  4231. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4232. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4233. }
  4234. memcpy( ssl->in_hdr, rec, rec_len );
  4235. ssl->in_left = rec_len;
  4236. ssl->next_record_offset = 0;
  4237. ssl_free_buffered_record( ssl );
  4238. exit:
  4239. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_record" ) );
  4240. return( 0 );
  4241. }
  4242. static int ssl_buffer_future_record( mbedtls_ssl_context *ssl )
  4243. {
  4244. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4245. size_t const rec_hdr_len = 13;
  4246. size_t const total_buf_sz = rec_hdr_len + ssl->in_msglen;
  4247. /* Don't buffer future records outside handshakes. */
  4248. if( hs == NULL )
  4249. return( 0 );
  4250. /* Only buffer handshake records (we are only interested
  4251. * in Finished messages). */
  4252. if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
  4253. return( 0 );
  4254. /* Don't buffer more than one future epoch record. */
  4255. if( hs->buffering.future_record.data != NULL )
  4256. return( 0 );
  4257. /* Don't buffer record if there's not enough buffering space remaining. */
  4258. if( total_buf_sz > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  4259. hs->buffering.total_bytes_buffered ) )
  4260. {
  4261. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future epoch record of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- ignore\n",
  4262. (unsigned) total_buf_sz, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  4263. (unsigned) hs->buffering.total_bytes_buffered ) );
  4264. return( 0 );
  4265. }
  4266. /* Buffer record */
  4267. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffer record from epoch %u",
  4268. ssl->in_epoch + 1 ) );
  4269. MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered record", ssl->in_hdr,
  4270. rec_hdr_len + ssl->in_msglen );
  4271. /* ssl_parse_record_header() only considers records
  4272. * of the next epoch as candidates for buffering. */
  4273. hs->buffering.future_record.epoch = ssl->in_epoch + 1;
  4274. hs->buffering.future_record.len = total_buf_sz;
  4275. hs->buffering.future_record.data =
  4276. mbedtls_calloc( 1, hs->buffering.future_record.len );
  4277. if( hs->buffering.future_record.data == NULL )
  4278. {
  4279. /* If we run out of RAM trying to buffer a
  4280. * record from the next epoch, just ignore. */
  4281. return( 0 );
  4282. }
  4283. memcpy( hs->buffering.future_record.data, ssl->in_hdr, total_buf_sz );
  4284. hs->buffering.total_bytes_buffered += total_buf_sz;
  4285. return( 0 );
  4286. }
  4287. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4288. static int ssl_get_next_record( mbedtls_ssl_context *ssl )
  4289. {
  4290. int ret;
  4291. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4292. /* We might have buffered a future record; if so,
  4293. * and if the epoch matches now, load it.
  4294. * On success, this call will set ssl->in_left to
  4295. * the length of the buffered record, so that
  4296. * the calls to ssl_fetch_input() below will
  4297. * essentially be no-ops. */
  4298. ret = ssl_load_buffered_record( ssl );
  4299. if( ret != 0 )
  4300. return( ret );
  4301. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4302. if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_hdr_len( ssl ) ) ) != 0 )
  4303. {
  4304. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
  4305. return( ret );
  4306. }
  4307. if( ( ret = ssl_parse_record_header( ssl ) ) != 0 )
  4308. {
  4309. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4310. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  4311. ret != MBEDTLS_ERR_SSL_CLIENT_RECONNECT )
  4312. {
  4313. if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
  4314. {
  4315. ret = ssl_buffer_future_record( ssl );
  4316. if( ret != 0 )
  4317. return( ret );
  4318. /* Fall through to handling of unexpected records */
  4319. ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
  4320. }
  4321. if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD )
  4322. {
  4323. /* Skip unexpected record (but not whole datagram) */
  4324. ssl->next_record_offset = ssl->in_msglen
  4325. + mbedtls_ssl_hdr_len( ssl );
  4326. MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding unexpected record "
  4327. "(header)" ) );
  4328. }
  4329. else
  4330. {
  4331. /* Skip invalid record and the rest of the datagram */
  4332. ssl->next_record_offset = 0;
  4333. ssl->in_left = 0;
  4334. MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record "
  4335. "(header)" ) );
  4336. }
  4337. /* Get next record */
  4338. return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
  4339. }
  4340. #endif
  4341. return( ret );
  4342. }
  4343. /*
  4344. * Read and optionally decrypt the message contents
  4345. */
  4346. if( ( ret = mbedtls_ssl_fetch_input( ssl,
  4347. mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen ) ) != 0 )
  4348. {
  4349. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
  4350. return( ret );
  4351. }
  4352. /* Done reading this record, get ready for the next one */
  4353. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4354. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  4355. {
  4356. ssl->next_record_offset = ssl->in_msglen + mbedtls_ssl_hdr_len( ssl );
  4357. if( ssl->next_record_offset < ssl->in_left )
  4358. {
  4359. MBEDTLS_SSL_DEBUG_MSG( 3, ( "more than one record within datagram" ) );
  4360. }
  4361. }
  4362. else
  4363. #endif
  4364. ssl->in_left = 0;
  4365. if( ( ret = ssl_prepare_record_content( ssl ) ) != 0 )
  4366. {
  4367. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4368. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  4369. {
  4370. /* Silently discard invalid records */
  4371. if( ret == MBEDTLS_ERR_SSL_INVALID_RECORD ||
  4372. ret == MBEDTLS_ERR_SSL_INVALID_MAC )
  4373. {
  4374. /* Except when waiting for Finished as a bad mac here
  4375. * probably means something went wrong in the handshake
  4376. * (eg wrong psk used, mitm downgrade attempt, etc.) */
  4377. if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED ||
  4378. ssl->state == MBEDTLS_SSL_SERVER_FINISHED )
  4379. {
  4380. #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
  4381. if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
  4382. {
  4383. mbedtls_ssl_send_alert_message( ssl,
  4384. MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4385. MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
  4386. }
  4387. #endif
  4388. return( ret );
  4389. }
  4390. #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
  4391. if( ssl->conf->badmac_limit != 0 &&
  4392. ++ssl->badmac_seen >= ssl->conf->badmac_limit )
  4393. {
  4394. MBEDTLS_SSL_DEBUG_MSG( 1, ( "too many records with bad MAC" ) );
  4395. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  4396. }
  4397. #endif
  4398. /* As above, invalid records cause
  4399. * dismissal of the whole datagram. */
  4400. ssl->next_record_offset = 0;
  4401. ssl->in_left = 0;
  4402. MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) );
  4403. return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
  4404. }
  4405. return( ret );
  4406. }
  4407. else
  4408. #endif
  4409. {
  4410. /* Error out (and send alert) on invalid records */
  4411. #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
  4412. if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
  4413. {
  4414. mbedtls_ssl_send_alert_message( ssl,
  4415. MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4416. MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
  4417. }
  4418. #endif
  4419. return( ret );
  4420. }
  4421. }
  4422. return( 0 );
  4423. }
  4424. int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl )
  4425. {
  4426. int ret;
  4427. /*
  4428. * Handle particular types of records
  4429. */
  4430. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
  4431. {
  4432. if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 )
  4433. {
  4434. return( ret );
  4435. }
  4436. }
  4437. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
  4438. {
  4439. if( ssl->in_msglen != 1 )
  4440. {
  4441. MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, len: %d",
  4442. ssl->in_msglen ) );
  4443. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4444. }
  4445. if( ssl->in_msg[0] != 1 )
  4446. {
  4447. MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, content: %02x",
  4448. ssl->in_msg[0] ) );
  4449. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4450. }
  4451. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4452. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  4453. ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC &&
  4454. ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
  4455. {
  4456. if( ssl->handshake == NULL )
  4457. {
  4458. MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping ChangeCipherSpec outside handshake" ) );
  4459. return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
  4460. }
  4461. MBEDTLS_SSL_DEBUG_MSG( 1, ( "received out-of-order ChangeCipherSpec - remember" ) );
  4462. return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
  4463. }
  4464. #endif
  4465. }
  4466. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
  4467. {
  4468. if( ssl->in_msglen != 2 )
  4469. {
  4470. /* Note: Standard allows for more than one 2 byte alert
  4471. to be packed in a single message, but Mbed TLS doesn't
  4472. currently support this. */
  4473. MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid alert message, len: %d",
  4474. ssl->in_msglen ) );
  4475. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4476. }
  4477. MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]",
  4478. ssl->in_msg[0], ssl->in_msg[1] ) );
  4479. /*
  4480. * Ignore non-fatal alerts, except close_notify and no_renegotiation
  4481. */
  4482. if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL )
  4483. {
  4484. MBEDTLS_SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)",
  4485. ssl->in_msg[1] ) );
  4486. return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE );
  4487. }
  4488. if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
  4489. ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY )
  4490. {
  4491. MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a close notify message" ) );
  4492. return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY );
  4493. }
  4494. #if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED)
  4495. if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
  4496. ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION )
  4497. {
  4498. MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no renegotiation alert" ) );
  4499. /* Will be handled when trying to parse ServerHello */
  4500. return( 0 );
  4501. }
  4502. #endif
  4503. #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C)
  4504. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
  4505. ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  4506. ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
  4507. ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
  4508. {
  4509. MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) );
  4510. /* Will be handled in mbedtls_ssl_parse_certificate() */
  4511. return( 0 );
  4512. }
  4513. #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
  4514. /* Silently ignore: fetch new message */
  4515. return MBEDTLS_ERR_SSL_NON_FATAL;
  4516. }
  4517. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4518. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  4519. ssl->handshake != NULL &&
  4520. ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
  4521. {
  4522. ssl_handshake_wrapup_free_hs_transform( ssl );
  4523. }
  4524. #endif
  4525. return( 0 );
  4526. }
  4527. int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl )
  4528. {
  4529. int ret;
  4530. if( ( ret = mbedtls_ssl_send_alert_message( ssl,
  4531. MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4532. MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ) != 0 )
  4533. {
  4534. return( ret );
  4535. }
  4536. return( 0 );
  4537. }
  4538. int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl,
  4539. unsigned char level,
  4540. unsigned char message )
  4541. {
  4542. int ret;
  4543. if( ssl == NULL || ssl->conf == NULL )
  4544. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  4545. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) );
  4546. MBEDTLS_SSL_DEBUG_MSG( 3, ( "send alert level=%u message=%u", level, message ));
  4547. ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
  4548. ssl->out_msglen = 2;
  4549. ssl->out_msg[0] = level;
  4550. ssl->out_msg[1] = message;
  4551. if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
  4552. {
  4553. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
  4554. return( ret );
  4555. }
  4556. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= send alert message" ) );
  4557. return( 0 );
  4558. }
  4559. /*
  4560. * Handshake functions
  4561. */
  4562. #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \
  4563. !defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) && \
  4564. !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \
  4565. !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
  4566. !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \
  4567. !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \
  4568. !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
  4569. /* No certificate support -> dummy functions */
  4570. int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
  4571. {
  4572. const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
  4573. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
  4574. if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  4575. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  4576. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  4577. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  4578. {
  4579. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
  4580. ssl->state++;
  4581. return( 0 );
  4582. }
  4583. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4584. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4585. }
  4586. int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
  4587. {
  4588. const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
  4589. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
  4590. if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  4591. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  4592. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  4593. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  4594. {
  4595. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
  4596. ssl->state++;
  4597. return( 0 );
  4598. }
  4599. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4600. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4601. }
  4602. #else
  4603. /* Some certificate support -> implement write and parse */
  4604. int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
  4605. {
  4606. int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
  4607. size_t i, n;
  4608. const mbedtls_x509_crt *crt;
  4609. const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
  4610. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
  4611. if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  4612. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  4613. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  4614. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  4615. {
  4616. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
  4617. ssl->state++;
  4618. return( 0 );
  4619. }
  4620. #if defined(MBEDTLS_SSL_CLI_C)
  4621. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  4622. {
  4623. if( ssl->client_auth == 0 )
  4624. {
  4625. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
  4626. ssl->state++;
  4627. return( 0 );
  4628. }
  4629. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  4630. /*
  4631. * If using SSLv3 and got no cert, send an Alert message
  4632. * (otherwise an empty Certificate message will be sent).
  4633. */
  4634. if( mbedtls_ssl_own_cert( ssl ) == NULL &&
  4635. ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  4636. {
  4637. ssl->out_msglen = 2;
  4638. ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
  4639. ssl->out_msg[0] = MBEDTLS_SSL_ALERT_LEVEL_WARNING;
  4640. ssl->out_msg[1] = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
  4641. MBEDTLS_SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) );
  4642. goto write_msg;
  4643. }
  4644. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  4645. }
  4646. #endif /* MBEDTLS_SSL_CLI_C */
  4647. #if defined(MBEDTLS_SSL_SRV_C)
  4648. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  4649. {
  4650. if( mbedtls_ssl_own_cert( ssl ) == NULL )
  4651. {
  4652. MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) );
  4653. return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED );
  4654. }
  4655. }
  4656. #endif
  4657. MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) );
  4658. /*
  4659. * 0 . 0 handshake type
  4660. * 1 . 3 handshake length
  4661. * 4 . 6 length of all certs
  4662. * 7 . 9 length of cert. 1
  4663. * 10 . n-1 peer certificate
  4664. * n . n+2 length of cert. 2
  4665. * n+3 . ... upper level cert, etc.
  4666. */
  4667. i = 7;
  4668. crt = mbedtls_ssl_own_cert( ssl );
  4669. while( crt != NULL )
  4670. {
  4671. n = crt->raw.len;
  4672. if( n > MBEDTLS_SSL_OUT_CONTENT_LEN - 3 - i )
  4673. {
  4674. MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d",
  4675. i + 3 + n, MBEDTLS_SSL_OUT_CONTENT_LEN ) );
  4676. return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE );
  4677. }
  4678. ssl->out_msg[i ] = (unsigned char)( n >> 16 );
  4679. ssl->out_msg[i + 1] = (unsigned char)( n >> 8 );
  4680. ssl->out_msg[i + 2] = (unsigned char)( n );
  4681. i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n );
  4682. i += n; crt = crt->next;
  4683. }
  4684. ssl->out_msg[4] = (unsigned char)( ( i - 7 ) >> 16 );
  4685. ssl->out_msg[5] = (unsigned char)( ( i - 7 ) >> 8 );
  4686. ssl->out_msg[6] = (unsigned char)( ( i - 7 ) );
  4687. ssl->out_msglen = i;
  4688. ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  4689. ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE;
  4690. #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
  4691. write_msg:
  4692. #endif
  4693. ssl->state++;
  4694. if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  4695. {
  4696. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  4697. return( ret );
  4698. }
  4699. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) );
  4700. return( ret );
  4701. }
  4702. /*
  4703. * Once the certificate message is read, parse it into a cert chain and
  4704. * perform basic checks, but leave actual verification to the caller
  4705. */
  4706. static int ssl_parse_certificate_chain( mbedtls_ssl_context *ssl )
  4707. {
  4708. int ret;
  4709. size_t i, n;
  4710. uint8_t alert;
  4711. #if defined(MBEDTLS_SSL_SRV_C)
  4712. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  4713. /*
  4714. * Check if the client sent an empty certificate
  4715. */
  4716. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  4717. ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  4718. {
  4719. if( ssl->in_msglen == 2 &&
  4720. ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT &&
  4721. ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
  4722. ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
  4723. {
  4724. MBEDTLS_SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
  4725. /* The client was asked for a certificate but didn't send
  4726. one. The client should know what's going on, so we
  4727. don't send an alert. */
  4728. ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
  4729. return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
  4730. }
  4731. }
  4732. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  4733. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  4734. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  4735. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  4736. ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
  4737. {
  4738. if( ssl->in_hslen == 3 + mbedtls_ssl_hs_hdr_len( ssl ) &&
  4739. ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  4740. ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE &&
  4741. memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 )
  4742. {
  4743. MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
  4744. /* The client was asked for a certificate but didn't send
  4745. one. The client should know what's going on, so we
  4746. don't send an alert. */
  4747. ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
  4748. return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
  4749. }
  4750. }
  4751. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
  4752. MBEDTLS_SSL_PROTO_TLS1_2 */
  4753. #endif /* MBEDTLS_SSL_SRV_C */
  4754. if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
  4755. {
  4756. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  4757. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4758. MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  4759. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  4760. }
  4761. if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE ||
  4762. ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 )
  4763. {
  4764. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  4765. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4766. MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  4767. return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  4768. }
  4769. i = mbedtls_ssl_hs_hdr_len( ssl );
  4770. /*
  4771. * Same message structure as in mbedtls_ssl_write_certificate()
  4772. */
  4773. n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2];
  4774. if( ssl->in_msg[i] != 0 ||
  4775. ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) )
  4776. {
  4777. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  4778. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4779. MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  4780. return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  4781. }
  4782. /* In case we tried to reuse a session but it failed */
  4783. if( ssl->session_negotiate->peer_cert != NULL )
  4784. {
  4785. mbedtls_x509_crt_free( ssl->session_negotiate->peer_cert );
  4786. mbedtls_free( ssl->session_negotiate->peer_cert );
  4787. }
  4788. if( ( ssl->session_negotiate->peer_cert = mbedtls_calloc( 1,
  4789. sizeof( mbedtls_x509_crt ) ) ) == NULL )
  4790. {
  4791. MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
  4792. sizeof( mbedtls_x509_crt ) ) );
  4793. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4794. MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
  4795. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  4796. }
  4797. mbedtls_x509_crt_init( ssl->session_negotiate->peer_cert );
  4798. i += 3;
  4799. while( i < ssl->in_hslen )
  4800. {
  4801. if ( i + 3 > ssl->in_hslen ) {
  4802. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  4803. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4804. MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  4805. return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  4806. }
  4807. if( ssl->in_msg[i] != 0 )
  4808. {
  4809. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  4810. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4811. MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  4812. return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  4813. }
  4814. n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
  4815. | (unsigned int) ssl->in_msg[i + 2];
  4816. i += 3;
  4817. if( n < 128 || i + n > ssl->in_hslen )
  4818. {
  4819. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  4820. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4821. MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  4822. return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  4823. }
  4824. ret = mbedtls_x509_crt_parse_der( ssl->session_negotiate->peer_cert,
  4825. ssl->in_msg + i, n );
  4826. switch( ret )
  4827. {
  4828. case 0: /*ok*/
  4829. case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND:
  4830. /* Ignore certificate with an unknown algorithm: maybe a
  4831. prior certificate was already trusted. */
  4832. break;
  4833. case MBEDTLS_ERR_X509_ALLOC_FAILED:
  4834. alert = MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR;
  4835. goto crt_parse_der_failed;
  4836. case MBEDTLS_ERR_X509_UNKNOWN_VERSION:
  4837. alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  4838. goto crt_parse_der_failed;
  4839. default:
  4840. alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
  4841. crt_parse_der_failed:
  4842. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert );
  4843. MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret );
  4844. return( ret );
  4845. }
  4846. i += n;
  4847. }
  4848. MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert );
  4849. /*
  4850. * On client, make sure the server cert doesn't change during renego to
  4851. * avoid "triple handshake" attack: https://secure-resumption.com/
  4852. */
  4853. #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
  4854. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
  4855. ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
  4856. {
  4857. if( ssl->session->peer_cert == NULL )
  4858. {
  4859. MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) );
  4860. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4861. MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
  4862. return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  4863. }
  4864. if( ssl->session->peer_cert->raw.len !=
  4865. ssl->session_negotiate->peer_cert->raw.len ||
  4866. memcmp( ssl->session->peer_cert->raw.p,
  4867. ssl->session_negotiate->peer_cert->raw.p,
  4868. ssl->session->peer_cert->raw.len ) != 0 )
  4869. {
  4870. MBEDTLS_SSL_DEBUG_MSG( 1, ( "server cert changed during renegotiation" ) );
  4871. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4872. MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
  4873. return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  4874. }
  4875. }
  4876. #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
  4877. return( 0 );
  4878. }
  4879. int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
  4880. {
  4881. int ret;
  4882. const mbedtls_ssl_ciphersuite_t * const ciphersuite_info =
  4883. ssl->transform_negotiate->ciphersuite_info;
  4884. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  4885. const int authmode = ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET
  4886. ? ssl->handshake->sni_authmode
  4887. : ssl->conf->authmode;
  4888. #else
  4889. const int authmode = ssl->conf->authmode;
  4890. #endif
  4891. void *rs_ctx = NULL;
  4892. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
  4893. if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  4894. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  4895. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  4896. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  4897. {
  4898. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
  4899. ssl->state++;
  4900. return( 0 );
  4901. }
  4902. #if defined(MBEDTLS_SSL_SRV_C)
  4903. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  4904. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
  4905. {
  4906. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
  4907. ssl->state++;
  4908. return( 0 );
  4909. }
  4910. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  4911. authmode == MBEDTLS_SSL_VERIFY_NONE )
  4912. {
  4913. ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY;
  4914. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
  4915. ssl->state++;
  4916. return( 0 );
  4917. }
  4918. #endif
  4919. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  4920. if( ssl->handshake->ecrs_enabled &&
  4921. ssl->handshake->ecrs_state == ssl_ecrs_crt_verify )
  4922. {
  4923. goto crt_verify;
  4924. }
  4925. #endif
  4926. if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  4927. {
  4928. /* mbedtls_ssl_read_record may have sent an alert already. We
  4929. let it decide whether to alert. */
  4930. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  4931. return( ret );
  4932. }
  4933. if( ( ret = ssl_parse_certificate_chain( ssl ) ) != 0 )
  4934. {
  4935. #if defined(MBEDTLS_SSL_SRV_C)
  4936. if( ret == MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE &&
  4937. authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
  4938. {
  4939. ret = 0;
  4940. }
  4941. #endif
  4942. ssl->state++;
  4943. return( ret );
  4944. }
  4945. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  4946. if( ssl->handshake->ecrs_enabled)
  4947. ssl->handshake->ecrs_state = ssl_ecrs_crt_verify;
  4948. crt_verify:
  4949. if( ssl->handshake->ecrs_enabled)
  4950. rs_ctx = &ssl->handshake->ecrs_ctx;
  4951. #endif
  4952. if( authmode != MBEDTLS_SSL_VERIFY_NONE )
  4953. {
  4954. mbedtls_x509_crt *ca_chain;
  4955. mbedtls_x509_crl *ca_crl;
  4956. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  4957. if( ssl->handshake->sni_ca_chain != NULL )
  4958. {
  4959. ca_chain = ssl->handshake->sni_ca_chain;
  4960. ca_crl = ssl->handshake->sni_ca_crl;
  4961. }
  4962. else
  4963. #endif
  4964. {
  4965. ca_chain = ssl->conf->ca_chain;
  4966. ca_crl = ssl->conf->ca_crl;
  4967. }
  4968. /*
  4969. * Main check: verify certificate
  4970. */
  4971. ret = mbedtls_x509_crt_verify_restartable(
  4972. ssl->session_negotiate->peer_cert,
  4973. ca_chain, ca_crl,
  4974. ssl->conf->cert_profile,
  4975. ssl->hostname,
  4976. &ssl->session_negotiate->verify_result,
  4977. ssl->conf->f_vrfy, ssl->conf->p_vrfy, rs_ctx );
  4978. if( ret != 0 )
  4979. {
  4980. MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
  4981. }
  4982. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  4983. if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
  4984. return( MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS );
  4985. #endif
  4986. /*
  4987. * Secondary checks: always done, but change 'ret' only if it was 0
  4988. */
  4989. #if defined(MBEDTLS_ECP_C)
  4990. {
  4991. const mbedtls_pk_context *pk = &ssl->session_negotiate->peer_cert->pk;
  4992. /* If certificate uses an EC key, make sure the curve is OK */
  4993. if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) &&
  4994. mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp.id ) != 0 )
  4995. {
  4996. ssl->session_negotiate->verify_result |= MBEDTLS_X509_BADCERT_BAD_KEY;
  4997. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) );
  4998. if( ret == 0 )
  4999. ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
  5000. }
  5001. }
  5002. #endif /* MBEDTLS_ECP_C */
  5003. if( mbedtls_ssl_check_cert_usage( ssl->session_negotiate->peer_cert,
  5004. ciphersuite_info,
  5005. ! ssl->conf->endpoint,
  5006. &ssl->session_negotiate->verify_result ) != 0 )
  5007. {
  5008. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) );
  5009. if( ret == 0 )
  5010. ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
  5011. }
  5012. /* mbedtls_x509_crt_verify_with_profile is supposed to report a
  5013. * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED,
  5014. * with details encoded in the verification flags. All other kinds
  5015. * of error codes, including those from the user provided f_vrfy
  5016. * functions, are treated as fatal and lead to a failure of
  5017. * ssl_parse_certificate even if verification was optional. */
  5018. if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL &&
  5019. ( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ||
  5020. ret == MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ) )
  5021. {
  5022. ret = 0;
  5023. }
  5024. if( ca_chain == NULL && authmode == MBEDTLS_SSL_VERIFY_REQUIRED )
  5025. {
  5026. MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
  5027. ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED;
  5028. }
  5029. if( ret != 0 )
  5030. {
  5031. uint8_t alert;
  5032. /* The certificate may have been rejected for several reasons.
  5033. Pick one and send the corresponding alert. Which alert to send
  5034. may be a subject of debate in some cases. */
  5035. if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_OTHER )
  5036. alert = MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED;
  5037. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH )
  5038. alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
  5039. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_KEY_USAGE )
  5040. alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  5041. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXT_KEY_USAGE )
  5042. alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  5043. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NS_CERT_TYPE )
  5044. alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  5045. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_PK )
  5046. alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  5047. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_KEY )
  5048. alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  5049. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXPIRED )
  5050. alert = MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED;
  5051. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_REVOKED )
  5052. alert = MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED;
  5053. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED )
  5054. alert = MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA;
  5055. else
  5056. alert = MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN;
  5057. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5058. alert );
  5059. }
  5060. #if defined(MBEDTLS_DEBUG_C)
  5061. if( ssl->session_negotiate->verify_result != 0 )
  5062. {
  5063. MBEDTLS_SSL_DEBUG_MSG( 3, ( "! Certificate verification flags %x",
  5064. ssl->session_negotiate->verify_result ) );
  5065. }
  5066. else
  5067. {
  5068. MBEDTLS_SSL_DEBUG_MSG( 3, ( "Certificate verification flags clear" ) );
  5069. }
  5070. #endif /* MBEDTLS_DEBUG_C */
  5071. }
  5072. ssl->state++;
  5073. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
  5074. return( ret );
  5075. }
  5076. #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
  5077. !MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED
  5078. !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
  5079. !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
  5080. !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
  5081. !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED
  5082. !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
  5083. int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl )
  5084. {
  5085. int ret;
  5086. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) );
  5087. ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
  5088. ssl->out_msglen = 1;
  5089. ssl->out_msg[0] = 1;
  5090. ssl->state++;
  5091. if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  5092. {
  5093. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  5094. return( ret );
  5095. }
  5096. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) );
  5097. return( 0 );
  5098. }
  5099. int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl )
  5100. {
  5101. int ret;
  5102. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) );
  5103. if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  5104. {
  5105. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  5106. return( ret );
  5107. }
  5108. if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
  5109. {
  5110. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
  5111. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5112. MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  5113. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  5114. }
  5115. /* CCS records are only accepted if they have length 1 and content '1',
  5116. * so we don't need to check this here. */
  5117. /*
  5118. * Switch to our negotiated transform and session parameters for inbound
  5119. * data.
  5120. */
  5121. MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) );
  5122. ssl->transform_in = ssl->transform_negotiate;
  5123. ssl->session_in = ssl->session_negotiate;
  5124. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5125. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5126. {
  5127. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  5128. ssl_dtls_replay_reset( ssl );
  5129. #endif
  5130. /* Increment epoch */
  5131. if( ++ssl->in_epoch == 0 )
  5132. {
  5133. MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
  5134. /* This is highly unlikely to happen for legitimate reasons, so
  5135. treat it as an attack and don't send an alert. */
  5136. return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
  5137. }
  5138. }
  5139. else
  5140. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  5141. memset( ssl->in_ctr, 0, 8 );
  5142. ssl_update_in_pointers( ssl, ssl->transform_negotiate );
  5143. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  5144. if( mbedtls_ssl_hw_record_activate != NULL )
  5145. {
  5146. if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 )
  5147. {
  5148. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
  5149. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5150. MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
  5151. return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  5152. }
  5153. }
  5154. #endif
  5155. ssl->state++;
  5156. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) );
  5157. return( 0 );
  5158. }
  5159. void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,
  5160. const mbedtls_ssl_ciphersuite_t *ciphersuite_info )
  5161. {
  5162. ((void) ciphersuite_info);
  5163. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  5164. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  5165. if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
  5166. ssl->handshake->update_checksum = ssl_update_checksum_md5sha1;
  5167. else
  5168. #endif
  5169. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  5170. #if defined(MBEDTLS_SHA512_C)
  5171. if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
  5172. ssl->handshake->update_checksum = ssl_update_checksum_sha384;
  5173. else
  5174. #endif
  5175. #if defined(MBEDTLS_SHA256_C)
  5176. if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 )
  5177. ssl->handshake->update_checksum = ssl_update_checksum_sha256;
  5178. else
  5179. #endif
  5180. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  5181. {
  5182. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  5183. return;
  5184. }
  5185. }
  5186. void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl )
  5187. {
  5188. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  5189. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  5190. mbedtls_md5_starts_ret( &ssl->handshake->fin_md5 );
  5191. mbedtls_sha1_starts_ret( &ssl->handshake->fin_sha1 );
  5192. #endif
  5193. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  5194. #if defined(MBEDTLS_SHA256_C)
  5195. mbedtls_sha256_starts_ret( &ssl->handshake->fin_sha256, 0 );
  5196. #endif
  5197. #if defined(MBEDTLS_SHA512_C)
  5198. mbedtls_sha512_starts_ret( &ssl->handshake->fin_sha512, 1 );
  5199. #endif
  5200. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  5201. }
  5202. static void ssl_update_checksum_start( mbedtls_ssl_context *ssl,
  5203. const unsigned char *buf, size_t len )
  5204. {
  5205. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  5206. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  5207. mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );
  5208. mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );
  5209. #endif
  5210. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  5211. #if defined(MBEDTLS_SHA256_C)
  5212. mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );
  5213. #endif
  5214. #if defined(MBEDTLS_SHA512_C)
  5215. mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );
  5216. #endif
  5217. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  5218. }
  5219. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  5220. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  5221. static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl,
  5222. const unsigned char *buf, size_t len )
  5223. {
  5224. mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );
  5225. mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );
  5226. }
  5227. #endif
  5228. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  5229. #if defined(MBEDTLS_SHA256_C)
  5230. static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl,
  5231. const unsigned char *buf, size_t len )
  5232. {
  5233. mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );
  5234. }
  5235. #endif
  5236. #if defined(MBEDTLS_SHA512_C)
  5237. static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl,
  5238. const unsigned char *buf, size_t len )
  5239. {
  5240. mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );
  5241. }
  5242. #endif
  5243. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  5244. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  5245. static void ssl_calc_finished_ssl(
  5246. mbedtls_ssl_context *ssl, unsigned char *buf, int from )
  5247. {
  5248. const char *sender;
  5249. mbedtls_md5_context md5;
  5250. mbedtls_sha1_context sha1;
  5251. unsigned char padbuf[48];
  5252. unsigned char md5sum[16];
  5253. unsigned char sha1sum[20];
  5254. mbedtls_ssl_session *session = ssl->session_negotiate;
  5255. if( !session )
  5256. session = ssl->session;
  5257. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished ssl" ) );
  5258. mbedtls_md5_init( &md5 );
  5259. mbedtls_sha1_init( &sha1 );
  5260. mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
  5261. mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
  5262. /*
  5263. * SSLv3:
  5264. * hash =
  5265. * MD5( master + pad2 +
  5266. * MD5( handshake + sender + master + pad1 ) )
  5267. * + SHA1( master + pad2 +
  5268. * SHA1( handshake + sender + master + pad1 ) )
  5269. */
  5270. #if !defined(MBEDTLS_MD5_ALT)
  5271. MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *)
  5272. md5.state, sizeof( md5.state ) );
  5273. #endif
  5274. #if !defined(MBEDTLS_SHA1_ALT)
  5275. MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
  5276. sha1.state, sizeof( sha1.state ) );
  5277. #endif
  5278. sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "CLNT"
  5279. : "SRVR";
  5280. memset( padbuf, 0x36, 48 );
  5281. mbedtls_md5_update_ret( &md5, (const unsigned char *) sender, 4 );
  5282. mbedtls_md5_update_ret( &md5, session->master, 48 );
  5283. mbedtls_md5_update_ret( &md5, padbuf, 48 );
  5284. mbedtls_md5_finish_ret( &md5, md5sum );
  5285. mbedtls_sha1_update_ret( &sha1, (const unsigned char *) sender, 4 );
  5286. mbedtls_sha1_update_ret( &sha1, session->master, 48 );
  5287. mbedtls_sha1_update_ret( &sha1, padbuf, 40 );
  5288. mbedtls_sha1_finish_ret( &sha1, sha1sum );
  5289. memset( padbuf, 0x5C, 48 );
  5290. mbedtls_md5_starts_ret( &md5 );
  5291. mbedtls_md5_update_ret( &md5, session->master, 48 );
  5292. mbedtls_md5_update_ret( &md5, padbuf, 48 );
  5293. mbedtls_md5_update_ret( &md5, md5sum, 16 );
  5294. mbedtls_md5_finish_ret( &md5, buf );
  5295. mbedtls_sha1_starts_ret( &sha1 );
  5296. mbedtls_sha1_update_ret( &sha1, session->master, 48 );
  5297. mbedtls_sha1_update_ret( &sha1, padbuf , 40 );
  5298. mbedtls_sha1_update_ret( &sha1, sha1sum, 20 );
  5299. mbedtls_sha1_finish_ret( &sha1, buf + 16 );
  5300. MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 );
  5301. mbedtls_md5_free( &md5 );
  5302. mbedtls_sha1_free( &sha1 );
  5303. mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) );
  5304. mbedtls_platform_zeroize( md5sum, sizeof( md5sum ) );
  5305. mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );
  5306. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
  5307. }
  5308. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  5309. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  5310. static void ssl_calc_finished_tls(
  5311. mbedtls_ssl_context *ssl, unsigned char *buf, int from )
  5312. {
  5313. int len = 12;
  5314. const char *sender;
  5315. mbedtls_md5_context md5;
  5316. mbedtls_sha1_context sha1;
  5317. unsigned char padbuf[36];
  5318. mbedtls_ssl_session *session = ssl->session_negotiate;
  5319. if( !session )
  5320. session = ssl->session;
  5321. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls" ) );
  5322. mbedtls_md5_init( &md5 );
  5323. mbedtls_sha1_init( &sha1 );
  5324. mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
  5325. mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
  5326. /*
  5327. * TLSv1:
  5328. * hash = PRF( master, finished_label,
  5329. * MD5( handshake ) + SHA1( handshake ) )[0..11]
  5330. */
  5331. #if !defined(MBEDTLS_MD5_ALT)
  5332. MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *)
  5333. md5.state, sizeof( md5.state ) );
  5334. #endif
  5335. #if !defined(MBEDTLS_SHA1_ALT)
  5336. MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
  5337. sha1.state, sizeof( sha1.state ) );
  5338. #endif
  5339. sender = ( from == MBEDTLS_SSL_IS_CLIENT )
  5340. ? "client finished"
  5341. : "server finished";
  5342. mbedtls_md5_finish_ret( &md5, padbuf );
  5343. mbedtls_sha1_finish_ret( &sha1, padbuf + 16 );
  5344. ssl->handshake->tls_prf( session->master, 48, sender,
  5345. padbuf, 36, buf, len );
  5346. MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
  5347. mbedtls_md5_free( &md5 );
  5348. mbedtls_sha1_free( &sha1 );
  5349. mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) );
  5350. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
  5351. }
  5352. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
  5353. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  5354. #if defined(MBEDTLS_SHA256_C)
  5355. static void ssl_calc_finished_tls_sha256(
  5356. mbedtls_ssl_context *ssl, unsigned char *buf, int from )
  5357. {
  5358. int len = 12;
  5359. const char *sender;
  5360. mbedtls_sha256_context sha256;
  5361. unsigned char padbuf[32];
  5362. mbedtls_ssl_session *session = ssl->session_negotiate;
  5363. if( !session )
  5364. session = ssl->session;
  5365. mbedtls_sha256_init( &sha256 );
  5366. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha256" ) );
  5367. mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
  5368. /*
  5369. * TLSv1.2:
  5370. * hash = PRF( master, finished_label,
  5371. * Hash( handshake ) )[0.11]
  5372. */
  5373. #if !defined(MBEDTLS_SHA256_ALT)
  5374. MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *)
  5375. sha256.state, sizeof( sha256.state ) );
  5376. #endif
  5377. sender = ( from == MBEDTLS_SSL_IS_CLIENT )
  5378. ? "client finished"
  5379. : "server finished";
  5380. mbedtls_sha256_finish_ret( &sha256, padbuf );
  5381. ssl->handshake->tls_prf( session->master, 48, sender,
  5382. padbuf, 32, buf, len );
  5383. MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
  5384. mbedtls_sha256_free( &sha256 );
  5385. mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) );
  5386. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
  5387. }
  5388. #endif /* MBEDTLS_SHA256_C */
  5389. #if defined(MBEDTLS_SHA512_C)
  5390. static void ssl_calc_finished_tls_sha384(
  5391. mbedtls_ssl_context *ssl, unsigned char *buf, int from )
  5392. {
  5393. int len = 12;
  5394. const char *sender;
  5395. mbedtls_sha512_context sha512;
  5396. unsigned char padbuf[48];
  5397. mbedtls_ssl_session *session = ssl->session_negotiate;
  5398. if( !session )
  5399. session = ssl->session;
  5400. mbedtls_sha512_init( &sha512 );
  5401. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha384" ) );
  5402. mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
  5403. /*
  5404. * TLSv1.2:
  5405. * hash = PRF( master, finished_label,
  5406. * Hash( handshake ) )[0.11]
  5407. */
  5408. #if !defined(MBEDTLS_SHA512_ALT)
  5409. MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *)
  5410. sha512.state, sizeof( sha512.state ) );
  5411. #endif
  5412. sender = ( from == MBEDTLS_SSL_IS_CLIENT )
  5413. ? "client finished"
  5414. : "server finished";
  5415. /* mbedtls_sha512_finish_ret's output parameter is declared as a
  5416. * 64-byte buffer, but sice we're using SHA-384, we know that the
  5417. * output fits in 48 bytes. This is correct C, but GCC 11.1 warns
  5418. * about it.
  5419. */
  5420. #if defined(__GNUC__) && __GNUC__ >= 11
  5421. #pragma GCC diagnostic push
  5422. #pragma GCC diagnostic ignored "-Wstringop-overflow"
  5423. #endif
  5424. mbedtls_sha512_finish_ret( &sha512, padbuf );
  5425. #if defined(__GNUC__) && __GNUC__ >= 11
  5426. #pragma GCC diagnostic pop
  5427. #endif
  5428. ssl->handshake->tls_prf( session->master, 48, sender,
  5429. padbuf, 48, buf, len );
  5430. MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
  5431. mbedtls_sha512_free( &sha512 );
  5432. mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) );
  5433. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
  5434. }
  5435. #endif /* MBEDTLS_SHA512_C */
  5436. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  5437. static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl )
  5438. {
  5439. MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) );
  5440. /*
  5441. * Free our handshake params
  5442. */
  5443. mbedtls_ssl_handshake_free( ssl );
  5444. mbedtls_free( ssl->handshake );
  5445. ssl->handshake = NULL;
  5446. /*
  5447. * Free the previous transform and swith in the current one
  5448. */
  5449. if( ssl->transform )
  5450. {
  5451. mbedtls_ssl_transform_free( ssl->transform );
  5452. mbedtls_free( ssl->transform );
  5453. }
  5454. ssl->transform = ssl->transform_negotiate;
  5455. ssl->transform_negotiate = NULL;
  5456. MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) );
  5457. }
  5458. void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl )
  5459. {
  5460. int resume = ssl->handshake->resume;
  5461. MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) );
  5462. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  5463. if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
  5464. {
  5465. ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_DONE;
  5466. ssl->renego_records_seen = 0;
  5467. }
  5468. #endif
  5469. /*
  5470. * Free the previous session and switch in the current one
  5471. */
  5472. if( ssl->session )
  5473. {
  5474. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  5475. /* RFC 7366 3.1: keep the EtM state */
  5476. ssl->session_negotiate->encrypt_then_mac =
  5477. ssl->session->encrypt_then_mac;
  5478. #endif
  5479. mbedtls_ssl_session_free( ssl->session );
  5480. mbedtls_free( ssl->session );
  5481. }
  5482. ssl->session = ssl->session_negotiate;
  5483. ssl->session_negotiate = NULL;
  5484. /*
  5485. * Add cache entry
  5486. */
  5487. if( ssl->conf->f_set_cache != NULL &&
  5488. ssl->session->id_len != 0 &&
  5489. resume == 0 )
  5490. {
  5491. if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 )
  5492. MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) );
  5493. }
  5494. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5495. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  5496. ssl->handshake->flight != NULL )
  5497. {
  5498. /* Cancel handshake timer */
  5499. ssl_set_timer( ssl, 0 );
  5500. /* Keep last flight around in case we need to resend it:
  5501. * we need the handshake and transform structures for that */
  5502. MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) );
  5503. }
  5504. else
  5505. #endif
  5506. ssl_handshake_wrapup_free_hs_transform( ssl );
  5507. ssl->state++;
  5508. MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) );
  5509. }
  5510. int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl )
  5511. {
  5512. int ret, hash_len;
  5513. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) );
  5514. ssl_update_out_pointers( ssl, ssl->transform_negotiate );
  5515. ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint );
  5516. /*
  5517. * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites
  5518. * may define some other value. Currently (early 2016), no defined
  5519. * ciphersuite does this (and this is unlikely to change as activity has
  5520. * moved to TLS 1.3 now) so we can keep the hardcoded 12 here.
  5521. */
  5522. hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12;
  5523. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  5524. ssl->verify_data_len = hash_len;
  5525. memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len );
  5526. #endif
  5527. ssl->out_msglen = 4 + hash_len;
  5528. ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  5529. ssl->out_msg[0] = MBEDTLS_SSL_HS_FINISHED;
  5530. /*
  5531. * In case of session resuming, invert the client and server
  5532. * ChangeCipherSpec messages order.
  5533. */
  5534. if( ssl->handshake->resume != 0 )
  5535. {
  5536. #if defined(MBEDTLS_SSL_CLI_C)
  5537. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  5538. ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
  5539. #endif
  5540. #if defined(MBEDTLS_SSL_SRV_C)
  5541. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  5542. ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
  5543. #endif
  5544. }
  5545. else
  5546. ssl->state++;
  5547. /*
  5548. * Switch to our negotiated transform and session parameters for outbound
  5549. * data.
  5550. */
  5551. MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) );
  5552. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5553. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5554. {
  5555. unsigned char i;
  5556. /* Remember current epoch settings for resending */
  5557. ssl->handshake->alt_transform_out = ssl->transform_out;
  5558. memcpy( ssl->handshake->alt_out_ctr, ssl->cur_out_ctr, 8 );
  5559. /* Set sequence_number to zero */
  5560. memset( ssl->cur_out_ctr + 2, 0, 6 );
  5561. /* Increment epoch */
  5562. for( i = 2; i > 0; i-- )
  5563. if( ++ssl->cur_out_ctr[i - 1] != 0 )
  5564. break;
  5565. /* The loop goes to its end iff the counter is wrapping */
  5566. if( i == 0 )
  5567. {
  5568. MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
  5569. return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
  5570. }
  5571. }
  5572. else
  5573. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  5574. memset( ssl->cur_out_ctr, 0, 8 );
  5575. ssl->transform_out = ssl->transform_negotiate;
  5576. ssl->session_out = ssl->session_negotiate;
  5577. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  5578. if( mbedtls_ssl_hw_record_activate != NULL )
  5579. {
  5580. if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
  5581. {
  5582. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
  5583. return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  5584. }
  5585. }
  5586. #endif
  5587. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5588. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5589. mbedtls_ssl_send_flight_completed( ssl );
  5590. #endif
  5591. if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  5592. {
  5593. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  5594. return( ret );
  5595. }
  5596. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5597. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  5598. ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
  5599. {
  5600. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
  5601. return( ret );
  5602. }
  5603. #endif
  5604. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) );
  5605. return( 0 );
  5606. }
  5607. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  5608. #define SSL_MAX_HASH_LEN 36
  5609. #else
  5610. #define SSL_MAX_HASH_LEN 12
  5611. #endif
  5612. int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl )
  5613. {
  5614. int ret;
  5615. unsigned int hash_len;
  5616. unsigned char buf[SSL_MAX_HASH_LEN];
  5617. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) );
  5618. ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 );
  5619. if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  5620. {
  5621. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  5622. return( ret );
  5623. }
  5624. if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
  5625. {
  5626. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
  5627. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5628. MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  5629. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  5630. }
  5631. /* There is currently no ciphersuite using another length with TLS 1.2 */
  5632. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  5633. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  5634. hash_len = 36;
  5635. else
  5636. #endif
  5637. hash_len = 12;
  5638. if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED ||
  5639. ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len )
  5640. {
  5641. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
  5642. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5643. MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  5644. return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
  5645. }
  5646. if( mbedtls_ssl_safer_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ),
  5647. buf, hash_len ) != 0 )
  5648. {
  5649. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
  5650. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5651. MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
  5652. return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
  5653. }
  5654. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  5655. ssl->verify_data_len = hash_len;
  5656. memcpy( ssl->peer_verify_data, buf, hash_len );
  5657. #endif
  5658. if( ssl->handshake->resume != 0 )
  5659. {
  5660. #if defined(MBEDTLS_SSL_CLI_C)
  5661. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  5662. ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
  5663. #endif
  5664. #if defined(MBEDTLS_SSL_SRV_C)
  5665. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  5666. ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
  5667. #endif
  5668. }
  5669. else
  5670. ssl->state++;
  5671. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5672. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5673. mbedtls_ssl_recv_flight_completed( ssl );
  5674. #endif
  5675. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) );
  5676. return( 0 );
  5677. }
  5678. static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake )
  5679. {
  5680. memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) );
  5681. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  5682. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  5683. mbedtls_md5_init( &handshake->fin_md5 );
  5684. mbedtls_sha1_init( &handshake->fin_sha1 );
  5685. mbedtls_md5_starts_ret( &handshake->fin_md5 );
  5686. mbedtls_sha1_starts_ret( &handshake->fin_sha1 );
  5687. #endif
  5688. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  5689. #if defined(MBEDTLS_SHA256_C)
  5690. mbedtls_sha256_init( &handshake->fin_sha256 );
  5691. mbedtls_sha256_starts_ret( &handshake->fin_sha256, 0 );
  5692. #endif
  5693. #if defined(MBEDTLS_SHA512_C)
  5694. mbedtls_sha512_init( &handshake->fin_sha512 );
  5695. mbedtls_sha512_starts_ret( &handshake->fin_sha512, 1 );
  5696. #endif
  5697. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  5698. handshake->update_checksum = ssl_update_checksum_start;
  5699. #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
  5700. defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  5701. mbedtls_ssl_sig_hash_set_init( &handshake->hash_algs );
  5702. #endif
  5703. #if defined(MBEDTLS_DHM_C)
  5704. mbedtls_dhm_init( &handshake->dhm_ctx );
  5705. #endif
  5706. #if defined(MBEDTLS_ECDH_C)
  5707. mbedtls_ecdh_init( &handshake->ecdh_ctx );
  5708. #endif
  5709. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  5710. mbedtls_ecjpake_init( &handshake->ecjpake_ctx );
  5711. #if defined(MBEDTLS_SSL_CLI_C)
  5712. handshake->ecjpake_cache = NULL;
  5713. handshake->ecjpake_cache_len = 0;
  5714. #endif
  5715. #endif
  5716. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  5717. mbedtls_x509_crt_restart_init( &handshake->ecrs_ctx );
  5718. #endif
  5719. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  5720. handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET;
  5721. #endif
  5722. }
  5723. static void ssl_transform_init( mbedtls_ssl_transform *transform )
  5724. {
  5725. memset( transform, 0, sizeof(mbedtls_ssl_transform) );
  5726. mbedtls_cipher_init( &transform->cipher_ctx_enc );
  5727. mbedtls_cipher_init( &transform->cipher_ctx_dec );
  5728. mbedtls_md_init( &transform->md_ctx_enc );
  5729. mbedtls_md_init( &transform->md_ctx_dec );
  5730. }
  5731. void mbedtls_ssl_session_init( mbedtls_ssl_session *session )
  5732. {
  5733. memset( session, 0, sizeof(mbedtls_ssl_session) );
  5734. }
  5735. static int ssl_handshake_init( mbedtls_ssl_context *ssl )
  5736. {
  5737. /* Clear old handshake information if present */
  5738. if( ssl->transform_negotiate )
  5739. mbedtls_ssl_transform_free( ssl->transform_negotiate );
  5740. if( ssl->session_negotiate )
  5741. mbedtls_ssl_session_free( ssl->session_negotiate );
  5742. if( ssl->handshake )
  5743. mbedtls_ssl_handshake_free( ssl );
  5744. /*
  5745. * Either the pointers are now NULL or cleared properly and can be freed.
  5746. * Now allocate missing structures.
  5747. */
  5748. if( ssl->transform_negotiate == NULL )
  5749. {
  5750. ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) );
  5751. }
  5752. if( ssl->session_negotiate == NULL )
  5753. {
  5754. ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) );
  5755. }
  5756. if( ssl->handshake == NULL )
  5757. {
  5758. ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) );
  5759. }
  5760. /* All pointers should exist and can be directly freed without issue */
  5761. if( ssl->handshake == NULL ||
  5762. ssl->transform_negotiate == NULL ||
  5763. ssl->session_negotiate == NULL )
  5764. {
  5765. MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) );
  5766. mbedtls_free( ssl->handshake );
  5767. mbedtls_free( ssl->transform_negotiate );
  5768. mbedtls_free( ssl->session_negotiate );
  5769. ssl->handshake = NULL;
  5770. ssl->transform_negotiate = NULL;
  5771. ssl->session_negotiate = NULL;
  5772. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  5773. }
  5774. /* Initialize structures */
  5775. mbedtls_ssl_session_init( ssl->session_negotiate );
  5776. ssl_transform_init( ssl->transform_negotiate );
  5777. ssl_handshake_params_init( ssl->handshake );
  5778. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5779. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5780. {
  5781. ssl->handshake->alt_transform_out = ssl->transform_out;
  5782. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  5783. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
  5784. else
  5785. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
  5786. ssl_set_timer( ssl, 0 );
  5787. }
  5788. #endif
  5789. return( 0 );
  5790. }
  5791. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
  5792. /* Dummy cookie callbacks for defaults */
  5793. static int ssl_cookie_write_dummy( void *ctx,
  5794. unsigned char **p, unsigned char *end,
  5795. const unsigned char *cli_id, size_t cli_id_len )
  5796. {
  5797. ((void) ctx);
  5798. ((void) p);
  5799. ((void) end);
  5800. ((void) cli_id);
  5801. ((void) cli_id_len);
  5802. return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  5803. }
  5804. static int ssl_cookie_check_dummy( void *ctx,
  5805. const unsigned char *cookie, size_t cookie_len,
  5806. const unsigned char *cli_id, size_t cli_id_len )
  5807. {
  5808. ((void) ctx);
  5809. ((void) cookie);
  5810. ((void) cookie_len);
  5811. ((void) cli_id);
  5812. ((void) cli_id_len);
  5813. return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  5814. }
  5815. #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
  5816. /* Once ssl->out_hdr as the address of the beginning of the
  5817. * next outgoing record is set, deduce the other pointers.
  5818. *
  5819. * Note: For TLS, we save the implicit record sequence number
  5820. * (entering MAC computation) in the 8 bytes before ssl->out_hdr,
  5821. * and the caller has to make sure there's space for this.
  5822. */
  5823. static void ssl_update_out_pointers( mbedtls_ssl_context *ssl,
  5824. mbedtls_ssl_transform *transform )
  5825. {
  5826. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5827. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5828. {
  5829. ssl->out_ctr = ssl->out_hdr + 3;
  5830. ssl->out_len = ssl->out_hdr + 11;
  5831. ssl->out_iv = ssl->out_hdr + 13;
  5832. }
  5833. else
  5834. #endif
  5835. {
  5836. ssl->out_ctr = ssl->out_hdr - 8;
  5837. ssl->out_len = ssl->out_hdr + 3;
  5838. ssl->out_iv = ssl->out_hdr + 5;
  5839. }
  5840. /* Adjust out_msg to make space for explicit IV, if used. */
  5841. if( transform != NULL &&
  5842. ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  5843. {
  5844. ssl->out_msg = ssl->out_iv + transform->ivlen - transform->fixed_ivlen;
  5845. }
  5846. else
  5847. ssl->out_msg = ssl->out_iv;
  5848. }
  5849. /* Once ssl->in_hdr as the address of the beginning of the
  5850. * next incoming record is set, deduce the other pointers.
  5851. *
  5852. * Note: For TLS, we save the implicit record sequence number
  5853. * (entering MAC computation) in the 8 bytes before ssl->in_hdr,
  5854. * and the caller has to make sure there's space for this.
  5855. */
  5856. static void ssl_update_in_pointers( mbedtls_ssl_context *ssl,
  5857. mbedtls_ssl_transform *transform )
  5858. {
  5859. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5860. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5861. {
  5862. ssl->in_ctr = ssl->in_hdr + 3;
  5863. ssl->in_len = ssl->in_hdr + 11;
  5864. ssl->in_iv = ssl->in_hdr + 13;
  5865. }
  5866. else
  5867. #endif
  5868. {
  5869. ssl->in_ctr = ssl->in_hdr - 8;
  5870. ssl->in_len = ssl->in_hdr + 3;
  5871. ssl->in_iv = ssl->in_hdr + 5;
  5872. }
  5873. /* Offset in_msg from in_iv to allow space for explicit IV, if used. */
  5874. if( transform != NULL &&
  5875. ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  5876. {
  5877. ssl->in_msg = ssl->in_iv + transform->ivlen - transform->fixed_ivlen;
  5878. }
  5879. else
  5880. ssl->in_msg = ssl->in_iv;
  5881. }
  5882. /*
  5883. * Initialize an SSL context
  5884. */
  5885. void mbedtls_ssl_init( mbedtls_ssl_context *ssl )
  5886. {
  5887. memset( ssl, 0, sizeof( mbedtls_ssl_context ) );
  5888. }
  5889. /*
  5890. * Setup an SSL context
  5891. */
  5892. static void ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl )
  5893. {
  5894. /* Set the incoming and outgoing record pointers. */
  5895. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5896. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5897. {
  5898. ssl->out_hdr = ssl->out_buf;
  5899. ssl->in_hdr = ssl->in_buf;
  5900. }
  5901. else
  5902. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  5903. {
  5904. ssl->out_hdr = ssl->out_buf + 8;
  5905. ssl->in_hdr = ssl->in_buf + 8;
  5906. }
  5907. /* Derive other internal pointers. */
  5908. ssl_update_out_pointers( ssl, NULL /* no transform enabled */ );
  5909. ssl_update_in_pointers ( ssl, NULL /* no transform enabled */ );
  5910. }
  5911. int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
  5912. const mbedtls_ssl_config *conf )
  5913. {
  5914. int ret;
  5915. ssl->conf = conf;
  5916. /*
  5917. * Prepare base structures
  5918. */
  5919. /* Set to NULL in case of an error condition */
  5920. ssl->out_buf = NULL;
  5921. ssl->in_buf = mbedtls_calloc( 1, MBEDTLS_SSL_IN_BUFFER_LEN );
  5922. if( ssl->in_buf == NULL )
  5923. {
  5924. MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_IN_BUFFER_LEN) );
  5925. ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
  5926. goto error;
  5927. }
  5928. ssl->out_buf = mbedtls_calloc( 1, MBEDTLS_SSL_OUT_BUFFER_LEN );
  5929. if( ssl->out_buf == NULL )
  5930. {
  5931. MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_OUT_BUFFER_LEN) );
  5932. ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
  5933. goto error;
  5934. }
  5935. ssl_reset_in_out_pointers( ssl );
  5936. if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
  5937. goto error;
  5938. return( 0 );
  5939. error:
  5940. mbedtls_free( ssl->in_buf );
  5941. mbedtls_free( ssl->out_buf );
  5942. ssl->conf = NULL;
  5943. ssl->in_buf = NULL;
  5944. ssl->out_buf = NULL;
  5945. ssl->in_hdr = NULL;
  5946. ssl->in_ctr = NULL;
  5947. ssl->in_len = NULL;
  5948. ssl->in_iv = NULL;
  5949. ssl->in_msg = NULL;
  5950. ssl->out_hdr = NULL;
  5951. ssl->out_ctr = NULL;
  5952. ssl->out_len = NULL;
  5953. ssl->out_iv = NULL;
  5954. ssl->out_msg = NULL;
  5955. return( ret );
  5956. }
  5957. /*
  5958. * Reset an initialized and used SSL context for re-use while retaining
  5959. * all application-set variables, function pointers and data.
  5960. *
  5961. * If partial is non-zero, keep data in the input buffer and client ID.
  5962. * (Use when a DTLS client reconnects from the same port.)
  5963. */
  5964. static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial )
  5965. {
  5966. int ret;
  5967. #if !defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) || \
  5968. !defined(MBEDTLS_SSL_SRV_C)
  5969. ((void) partial);
  5970. #endif
  5971. ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
  5972. /* Cancel any possibly running timer */
  5973. ssl_set_timer( ssl, 0 );
  5974. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  5975. ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE;
  5976. ssl->renego_records_seen = 0;
  5977. ssl->verify_data_len = 0;
  5978. memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
  5979. memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
  5980. #endif
  5981. ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION;
  5982. ssl->in_offt = NULL;
  5983. ssl_reset_in_out_pointers( ssl );
  5984. ssl->in_msgtype = 0;
  5985. ssl->in_msglen = 0;
  5986. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5987. ssl->next_record_offset = 0;
  5988. ssl->in_epoch = 0;
  5989. #endif
  5990. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  5991. ssl_dtls_replay_reset( ssl );
  5992. #endif
  5993. ssl->in_hslen = 0;
  5994. ssl->nb_zero = 0;
  5995. ssl->keep_current_message = 0;
  5996. ssl->out_msgtype = 0;
  5997. ssl->out_msglen = 0;
  5998. ssl->out_left = 0;
  5999. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  6000. if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED )
  6001. ssl->split_done = 0;
  6002. #endif
  6003. memset( ssl->cur_out_ctr, 0, sizeof( ssl->cur_out_ctr ) );
  6004. ssl->transform_in = NULL;
  6005. ssl->transform_out = NULL;
  6006. ssl->session_in = NULL;
  6007. ssl->session_out = NULL;
  6008. memset( ssl->out_buf, 0, MBEDTLS_SSL_OUT_BUFFER_LEN );
  6009. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
  6010. if( partial == 0 )
  6011. #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
  6012. {
  6013. ssl->in_left = 0;
  6014. memset( ssl->in_buf, 0, MBEDTLS_SSL_IN_BUFFER_LEN );
  6015. }
  6016. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  6017. if( mbedtls_ssl_hw_record_reset != NULL )
  6018. {
  6019. MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_reset()" ) );
  6020. if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 )
  6021. {
  6022. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_reset", ret );
  6023. return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  6024. }
  6025. }
  6026. #endif
  6027. if( ssl->transform )
  6028. {
  6029. mbedtls_ssl_transform_free( ssl->transform );
  6030. mbedtls_free( ssl->transform );
  6031. ssl->transform = NULL;
  6032. }
  6033. if( ssl->session )
  6034. {
  6035. mbedtls_ssl_session_free( ssl->session );
  6036. mbedtls_free( ssl->session );
  6037. ssl->session = NULL;
  6038. }
  6039. #if defined(MBEDTLS_SSL_ALPN)
  6040. ssl->alpn_chosen = NULL;
  6041. #endif
  6042. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
  6043. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE)
  6044. if( partial == 0 )
  6045. #endif
  6046. {
  6047. mbedtls_free( ssl->cli_id );
  6048. ssl->cli_id = NULL;
  6049. ssl->cli_id_len = 0;
  6050. }
  6051. #endif
  6052. if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
  6053. return( ret );
  6054. return( 0 );
  6055. }
  6056. /*
  6057. * Reset an initialized and used SSL context for re-use while retaining
  6058. * all application-set variables, function pointers and data.
  6059. */
  6060. int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl )
  6061. {
  6062. return( ssl_session_reset_int( ssl, 0 ) );
  6063. }
  6064. /*
  6065. * SSL set accessors
  6066. */
  6067. void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint )
  6068. {
  6069. conf->endpoint = endpoint;
  6070. }
  6071. void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport )
  6072. {
  6073. conf->transport = transport;
  6074. }
  6075. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  6076. void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode )
  6077. {
  6078. conf->anti_replay = mode;
  6079. }
  6080. #endif
  6081. #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
  6082. void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit )
  6083. {
  6084. conf->badmac_limit = limit;
  6085. }
  6086. #endif
  6087. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6088. void mbedtls_ssl_set_datagram_packing( mbedtls_ssl_context *ssl,
  6089. unsigned allow_packing )
  6090. {
  6091. ssl->disable_datagram_packing = !allow_packing;
  6092. }
  6093. void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf,
  6094. uint32_t min, uint32_t max )
  6095. {
  6096. conf->hs_timeout_min = min;
  6097. conf->hs_timeout_max = max;
  6098. }
  6099. #endif
  6100. void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode )
  6101. {
  6102. conf->authmode = authmode;
  6103. }
  6104. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  6105. void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf,
  6106. int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  6107. void *p_vrfy )
  6108. {
  6109. conf->f_vrfy = f_vrfy;
  6110. conf->p_vrfy = p_vrfy;
  6111. }
  6112. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  6113. void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf,
  6114. int (*f_rng)(void *, unsigned char *, size_t),
  6115. void *p_rng )
  6116. {
  6117. conf->f_rng = f_rng;
  6118. conf->p_rng = p_rng;
  6119. }
  6120. void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,
  6121. void (*f_dbg)(void *, int, const char *, int, const char *),
  6122. void *p_dbg )
  6123. {
  6124. conf->f_dbg = f_dbg;
  6125. conf->p_dbg = p_dbg;
  6126. }
  6127. void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,
  6128. void *p_bio,
  6129. mbedtls_ssl_send_t *f_send,
  6130. mbedtls_ssl_recv_t *f_recv,
  6131. mbedtls_ssl_recv_timeout_t *f_recv_timeout )
  6132. {
  6133. ssl->p_bio = p_bio;
  6134. ssl->f_send = f_send;
  6135. ssl->f_recv = f_recv;
  6136. ssl->f_recv_timeout = f_recv_timeout;
  6137. }
  6138. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6139. void mbedtls_ssl_set_mtu( mbedtls_ssl_context *ssl, uint16_t mtu )
  6140. {
  6141. ssl->mtu = mtu;
  6142. }
  6143. #endif
  6144. void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout )
  6145. {
  6146. conf->read_timeout = timeout;
  6147. }
  6148. void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,
  6149. void *p_timer,
  6150. mbedtls_ssl_set_timer_t *f_set_timer,
  6151. mbedtls_ssl_get_timer_t *f_get_timer )
  6152. {
  6153. ssl->p_timer = p_timer;
  6154. ssl->f_set_timer = f_set_timer;
  6155. ssl->f_get_timer = f_get_timer;
  6156. /* Make sure we start with no timer running */
  6157. ssl_set_timer( ssl, 0 );
  6158. }
  6159. #if defined(MBEDTLS_SSL_SRV_C)
  6160. void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,
  6161. void *p_cache,
  6162. int (*f_get_cache)(void *, mbedtls_ssl_session *),
  6163. int (*f_set_cache)(void *, const mbedtls_ssl_session *) )
  6164. {
  6165. conf->p_cache = p_cache;
  6166. conf->f_get_cache = f_get_cache;
  6167. conf->f_set_cache = f_set_cache;
  6168. }
  6169. #endif /* MBEDTLS_SSL_SRV_C */
  6170. #if defined(MBEDTLS_SSL_CLI_C)
  6171. int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session )
  6172. {
  6173. int ret;
  6174. if( ssl == NULL ||
  6175. session == NULL ||
  6176. ssl->session_negotiate == NULL ||
  6177. ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
  6178. {
  6179. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6180. }
  6181. if( ( ret = ssl_session_copy( ssl->session_negotiate, session ) ) != 0 )
  6182. return( ret );
  6183. ssl->handshake->resume = 1;
  6184. return( 0 );
  6185. }
  6186. #endif /* MBEDTLS_SSL_CLI_C */
  6187. void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,
  6188. const int *ciphersuites )
  6189. {
  6190. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites;
  6191. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites;
  6192. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites;
  6193. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites;
  6194. }
  6195. void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,
  6196. const int *ciphersuites,
  6197. int major, int minor )
  6198. {
  6199. if( major != MBEDTLS_SSL_MAJOR_VERSION_3 )
  6200. return;
  6201. if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 )
  6202. return;
  6203. conf->ciphersuite_list[minor] = ciphersuites;
  6204. }
  6205. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  6206. void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,
  6207. const mbedtls_x509_crt_profile *profile )
  6208. {
  6209. conf->cert_profile = profile;
  6210. }
  6211. /* Append a new keycert entry to a (possibly empty) list */
  6212. static int ssl_append_key_cert( mbedtls_ssl_key_cert **head,
  6213. mbedtls_x509_crt *cert,
  6214. mbedtls_pk_context *key )
  6215. {
  6216. mbedtls_ssl_key_cert *new_cert;
  6217. new_cert = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) );
  6218. if( new_cert == NULL )
  6219. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  6220. new_cert->cert = cert;
  6221. new_cert->key = key;
  6222. new_cert->next = NULL;
  6223. /* Update head is the list was null, else add to the end */
  6224. if( *head == NULL )
  6225. {
  6226. *head = new_cert;
  6227. }
  6228. else
  6229. {
  6230. mbedtls_ssl_key_cert *cur = *head;
  6231. while( cur->next != NULL )
  6232. cur = cur->next;
  6233. cur->next = new_cert;
  6234. }
  6235. return( 0 );
  6236. }
  6237. int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
  6238. mbedtls_x509_crt *own_cert,
  6239. mbedtls_pk_context *pk_key )
  6240. {
  6241. return( ssl_append_key_cert( &conf->key_cert, own_cert, pk_key ) );
  6242. }
  6243. void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,
  6244. mbedtls_x509_crt *ca_chain,
  6245. mbedtls_x509_crl *ca_crl )
  6246. {
  6247. conf->ca_chain = ca_chain;
  6248. conf->ca_crl = ca_crl;
  6249. }
  6250. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  6251. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  6252. int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl,
  6253. mbedtls_x509_crt *own_cert,
  6254. mbedtls_pk_context *pk_key )
  6255. {
  6256. return( ssl_append_key_cert( &ssl->handshake->sni_key_cert,
  6257. own_cert, pk_key ) );
  6258. }
  6259. void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl,
  6260. mbedtls_x509_crt *ca_chain,
  6261. mbedtls_x509_crl *ca_crl )
  6262. {
  6263. ssl->handshake->sni_ca_chain = ca_chain;
  6264. ssl->handshake->sni_ca_crl = ca_crl;
  6265. }
  6266. void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl,
  6267. int authmode )
  6268. {
  6269. ssl->handshake->sni_authmode = authmode;
  6270. }
  6271. #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
  6272. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  6273. /*
  6274. * Set EC J-PAKE password for current handshake
  6275. */
  6276. int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
  6277. const unsigned char *pw,
  6278. size_t pw_len )
  6279. {
  6280. mbedtls_ecjpake_role role;
  6281. if( ssl->handshake == NULL || ssl->conf == NULL )
  6282. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6283. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  6284. role = MBEDTLS_ECJPAKE_SERVER;
  6285. else
  6286. role = MBEDTLS_ECJPAKE_CLIENT;
  6287. return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx,
  6288. role,
  6289. MBEDTLS_MD_SHA256,
  6290. MBEDTLS_ECP_DP_SECP256R1,
  6291. pw, pw_len ) );
  6292. }
  6293. #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
  6294. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
  6295. int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
  6296. const unsigned char *psk, size_t psk_len,
  6297. const unsigned char *psk_identity, size_t psk_identity_len )
  6298. {
  6299. if( psk == NULL || psk_identity == NULL )
  6300. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6301. if( psk_len > MBEDTLS_PSK_MAX_LEN )
  6302. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6303. /* Identity len will be encoded on two bytes */
  6304. if( ( psk_identity_len >> 16 ) != 0 ||
  6305. psk_identity_len > MBEDTLS_SSL_OUT_CONTENT_LEN )
  6306. {
  6307. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6308. }
  6309. if( conf->psk != NULL )
  6310. {
  6311. mbedtls_platform_zeroize( conf->psk, conf->psk_len );
  6312. mbedtls_free( conf->psk );
  6313. conf->psk = NULL;
  6314. conf->psk_len = 0;
  6315. }
  6316. if( conf->psk_identity != NULL )
  6317. {
  6318. mbedtls_free( conf->psk_identity );
  6319. conf->psk_identity = NULL;
  6320. conf->psk_identity_len = 0;
  6321. }
  6322. if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ||
  6323. ( conf->psk_identity = mbedtls_calloc( 1, psk_identity_len ) ) == NULL )
  6324. {
  6325. mbedtls_free( conf->psk );
  6326. mbedtls_free( conf->psk_identity );
  6327. conf->psk = NULL;
  6328. conf->psk_identity = NULL;
  6329. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  6330. }
  6331. conf->psk_len = psk_len;
  6332. conf->psk_identity_len = psk_identity_len;
  6333. memcpy( conf->psk, psk, conf->psk_len );
  6334. memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len );
  6335. return( 0 );
  6336. }
  6337. int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl,
  6338. const unsigned char *psk, size_t psk_len )
  6339. {
  6340. if( psk == NULL || ssl->handshake == NULL )
  6341. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6342. if( psk_len > MBEDTLS_PSK_MAX_LEN )
  6343. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6344. if( ssl->handshake->psk != NULL )
  6345. {
  6346. mbedtls_platform_zeroize( ssl->handshake->psk,
  6347. ssl->handshake->psk_len );
  6348. mbedtls_free( ssl->handshake->psk );
  6349. ssl->handshake->psk_len = 0;
  6350. }
  6351. if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL )
  6352. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  6353. ssl->handshake->psk_len = psk_len;
  6354. memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len );
  6355. return( 0 );
  6356. }
  6357. void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,
  6358. int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
  6359. size_t),
  6360. void *p_psk )
  6361. {
  6362. conf->f_psk = f_psk;
  6363. conf->p_psk = p_psk;
  6364. }
  6365. #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
  6366. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
  6367. #if !defined(MBEDTLS_DEPRECATED_REMOVED)
  6368. int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G )
  6369. {
  6370. int ret;
  6371. if( ( ret = mbedtls_mpi_read_string( &conf->dhm_P, 16, dhm_P ) ) != 0 ||
  6372. ( ret = mbedtls_mpi_read_string( &conf->dhm_G, 16, dhm_G ) ) != 0 )
  6373. {
  6374. mbedtls_mpi_free( &conf->dhm_P );
  6375. mbedtls_mpi_free( &conf->dhm_G );
  6376. return( ret );
  6377. }
  6378. return( 0 );
  6379. }
  6380. #endif /* MBEDTLS_DEPRECATED_REMOVED */
  6381. int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf,
  6382. const unsigned char *dhm_P, size_t P_len,
  6383. const unsigned char *dhm_G, size_t G_len )
  6384. {
  6385. int ret;
  6386. if( ( ret = mbedtls_mpi_read_binary( &conf->dhm_P, dhm_P, P_len ) ) != 0 ||
  6387. ( ret = mbedtls_mpi_read_binary( &conf->dhm_G, dhm_G, G_len ) ) != 0 )
  6388. {
  6389. mbedtls_mpi_free( &conf->dhm_P );
  6390. mbedtls_mpi_free( &conf->dhm_G );
  6391. return( ret );
  6392. }
  6393. return( 0 );
  6394. }
  6395. int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx )
  6396. {
  6397. int ret;
  6398. if( ( ret = mbedtls_mpi_copy( &conf->dhm_P, &dhm_ctx->P ) ) != 0 ||
  6399. ( ret = mbedtls_mpi_copy( &conf->dhm_G, &dhm_ctx->G ) ) != 0 )
  6400. {
  6401. mbedtls_mpi_free( &conf->dhm_P );
  6402. mbedtls_mpi_free( &conf->dhm_G );
  6403. return( ret );
  6404. }
  6405. return( 0 );
  6406. }
  6407. #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */
  6408. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
  6409. /*
  6410. * Set the minimum length for Diffie-Hellman parameters
  6411. */
  6412. void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf,
  6413. unsigned int bitlen )
  6414. {
  6415. conf->dhm_min_bitlen = bitlen;
  6416. }
  6417. #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
  6418. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  6419. /*
  6420. * Set allowed/preferred hashes for handshake signatures
  6421. */
  6422. void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
  6423. const int *hashes )
  6424. {
  6425. conf->sig_hashes = hashes;
  6426. }
  6427. #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
  6428. #if defined(MBEDTLS_ECP_C)
  6429. /*
  6430. * Set the allowed elliptic curves
  6431. */
  6432. void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,
  6433. const mbedtls_ecp_group_id *curve_list )
  6434. {
  6435. conf->curve_list = curve_list;
  6436. }
  6437. #endif /* MBEDTLS_ECP_C */
  6438. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  6439. int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname )
  6440. {
  6441. /* Initialize to suppress unnecessary compiler warning */
  6442. size_t hostname_len = 0;
  6443. /* Check if new hostname is valid before
  6444. * making any change to current one */
  6445. if( hostname != NULL )
  6446. {
  6447. hostname_len = strlen( hostname );
  6448. if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )
  6449. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6450. }
  6451. /* Now it's clear that we will overwrite the old hostname,
  6452. * so we can free it safely */
  6453. if( ssl->hostname != NULL )
  6454. {
  6455. mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );
  6456. mbedtls_free( ssl->hostname );
  6457. }
  6458. /* Passing NULL as hostname shall clear the old one */
  6459. if( hostname == NULL )
  6460. {
  6461. ssl->hostname = NULL;
  6462. }
  6463. else
  6464. {
  6465. ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 );
  6466. if( ssl->hostname == NULL )
  6467. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  6468. memcpy( ssl->hostname, hostname, hostname_len );
  6469. ssl->hostname[hostname_len] = '\0';
  6470. }
  6471. return( 0 );
  6472. }
  6473. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  6474. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  6475. void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,
  6476. int (*f_sni)(void *, mbedtls_ssl_context *,
  6477. const unsigned char *, size_t),
  6478. void *p_sni )
  6479. {
  6480. conf->f_sni = f_sni;
  6481. conf->p_sni = p_sni;
  6482. }
  6483. #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
  6484. #if defined(MBEDTLS_SSL_ALPN)
  6485. int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos )
  6486. {
  6487. size_t cur_len, tot_len;
  6488. const char **p;
  6489. /*
  6490. * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings
  6491. * MUST NOT be truncated."
  6492. * We check lengths now rather than later.
  6493. */
  6494. tot_len = 0;
  6495. for( p = protos; *p != NULL; p++ )
  6496. {
  6497. cur_len = strlen( *p );
  6498. tot_len += cur_len;
  6499. if( ( cur_len == 0 ) ||
  6500. ( cur_len > MBEDTLS_SSL_MAX_ALPN_NAME_LEN ) ||
  6501. ( tot_len > MBEDTLS_SSL_MAX_ALPN_LIST_LEN ) )
  6502. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6503. }
  6504. conf->alpn_list = protos;
  6505. return( 0 );
  6506. }
  6507. const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl )
  6508. {
  6509. return( ssl->alpn_chosen );
  6510. }
  6511. #endif /* MBEDTLS_SSL_ALPN */
  6512. void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor )
  6513. {
  6514. conf->max_major_ver = major;
  6515. conf->max_minor_ver = minor;
  6516. }
  6517. void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor )
  6518. {
  6519. conf->min_major_ver = major;
  6520. conf->min_minor_ver = minor;
  6521. }
  6522. #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
  6523. void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback )
  6524. {
  6525. conf->fallback = fallback;
  6526. }
  6527. #endif
  6528. #if defined(MBEDTLS_SSL_SRV_C)
  6529. void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf,
  6530. char cert_req_ca_list )
  6531. {
  6532. conf->cert_req_ca_list = cert_req_ca_list;
  6533. }
  6534. #endif
  6535. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  6536. void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm )
  6537. {
  6538. conf->encrypt_then_mac = etm;
  6539. }
  6540. #endif
  6541. #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
  6542. void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems )
  6543. {
  6544. conf->extended_ms = ems;
  6545. }
  6546. #endif
  6547. #if defined(MBEDTLS_ARC4_C)
  6548. void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 )
  6549. {
  6550. conf->arc4_disabled = arc4;
  6551. }
  6552. #endif
  6553. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  6554. int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code )
  6555. {
  6556. if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ||
  6557. ssl_mfl_code_to_length( mfl_code ) > MBEDTLS_TLS_EXT_ADV_CONTENT_LEN )
  6558. {
  6559. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6560. }
  6561. conf->mfl_code = mfl_code;
  6562. return( 0 );
  6563. }
  6564. #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
  6565. #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
  6566. void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate )
  6567. {
  6568. conf->trunc_hmac = truncate;
  6569. }
  6570. #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
  6571. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  6572. void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split )
  6573. {
  6574. conf->cbc_record_splitting = split;
  6575. }
  6576. #endif
  6577. void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy )
  6578. {
  6579. conf->allow_legacy_renegotiation = allow_legacy;
  6580. }
  6581. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  6582. void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation )
  6583. {
  6584. conf->disable_renegotiation = renegotiation;
  6585. }
  6586. void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records )
  6587. {
  6588. conf->renego_max_records = max_records;
  6589. }
  6590. void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,
  6591. const unsigned char period[8] )
  6592. {
  6593. memcpy( conf->renego_period, period, 8 );
  6594. }
  6595. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  6596. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  6597. #if defined(MBEDTLS_SSL_CLI_C)
  6598. void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets )
  6599. {
  6600. conf->session_tickets = use_tickets;
  6601. }
  6602. #endif
  6603. #if defined(MBEDTLS_SSL_SRV_C)
  6604. void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf,
  6605. mbedtls_ssl_ticket_write_t *f_ticket_write,
  6606. mbedtls_ssl_ticket_parse_t *f_ticket_parse,
  6607. void *p_ticket )
  6608. {
  6609. conf->f_ticket_write = f_ticket_write;
  6610. conf->f_ticket_parse = f_ticket_parse;
  6611. conf->p_ticket = p_ticket;
  6612. }
  6613. #endif
  6614. #endif /* MBEDTLS_SSL_SESSION_TICKETS */
  6615. #if defined(MBEDTLS_SSL_EXPORT_KEYS)
  6616. void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf,
  6617. mbedtls_ssl_export_keys_t *f_export_keys,
  6618. void *p_export_keys )
  6619. {
  6620. conf->f_export_keys = f_export_keys;
  6621. conf->p_export_keys = p_export_keys;
  6622. }
  6623. #endif
  6624. #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
  6625. void mbedtls_ssl_conf_async_private_cb(
  6626. mbedtls_ssl_config *conf,
  6627. mbedtls_ssl_async_sign_t *f_async_sign,
  6628. mbedtls_ssl_async_decrypt_t *f_async_decrypt,
  6629. mbedtls_ssl_async_resume_t *f_async_resume,
  6630. mbedtls_ssl_async_cancel_t *f_async_cancel,
  6631. void *async_config_data )
  6632. {
  6633. conf->f_async_sign_start = f_async_sign;
  6634. conf->f_async_decrypt_start = f_async_decrypt;
  6635. conf->f_async_resume = f_async_resume;
  6636. conf->f_async_cancel = f_async_cancel;
  6637. conf->p_async_config_data = async_config_data;
  6638. }
  6639. void *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf )
  6640. {
  6641. return( conf->p_async_config_data );
  6642. }
  6643. void *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl )
  6644. {
  6645. if( ssl->handshake == NULL )
  6646. return( NULL );
  6647. else
  6648. return( ssl->handshake->user_async_ctx );
  6649. }
  6650. void mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl,
  6651. void *ctx )
  6652. {
  6653. if( ssl->handshake != NULL )
  6654. ssl->handshake->user_async_ctx = ctx;
  6655. }
  6656. #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
  6657. /*
  6658. * SSL get accessors
  6659. */
  6660. size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl )
  6661. {
  6662. return( ssl->in_offt == NULL ? 0 : ssl->in_msglen );
  6663. }
  6664. int mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl )
  6665. {
  6666. /*
  6667. * Case A: We're currently holding back
  6668. * a message for further processing.
  6669. */
  6670. if( ssl->keep_current_message == 1 )
  6671. {
  6672. MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: record held back for processing" ) );
  6673. return( 1 );
  6674. }
  6675. /*
  6676. * Case B: Further records are pending in the current datagram.
  6677. */
  6678. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6679. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  6680. ssl->in_left > ssl->next_record_offset )
  6681. {
  6682. MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more records within current datagram" ) );
  6683. return( 1 );
  6684. }
  6685. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  6686. /*
  6687. * Case C: A handshake message is being processed.
  6688. */
  6689. if( ssl->in_hslen > 0 && ssl->in_hslen < ssl->in_msglen )
  6690. {
  6691. MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more handshake messages within current record" ) );
  6692. return( 1 );
  6693. }
  6694. /*
  6695. * Case D: An application data message is being processed
  6696. */
  6697. if( ssl->in_offt != NULL )
  6698. {
  6699. MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: application data record is being processed" ) );
  6700. return( 1 );
  6701. }
  6702. /*
  6703. * In all other cases, the rest of the message can be dropped.
  6704. * As in ssl_get_next_record, this needs to be adapted if
  6705. * we implement support for multiple alerts in single records.
  6706. */
  6707. MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: nothing pending" ) );
  6708. return( 0 );
  6709. }
  6710. uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl )
  6711. {
  6712. if( ssl->session != NULL )
  6713. return( ssl->session->verify_result );
  6714. if( ssl->session_negotiate != NULL )
  6715. return( ssl->session_negotiate->verify_result );
  6716. return( 0xFFFFFFFF );
  6717. }
  6718. const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl )
  6719. {
  6720. if( ssl == NULL || ssl->session == NULL )
  6721. return( NULL );
  6722. return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite );
  6723. }
  6724. const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl )
  6725. {
  6726. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6727. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  6728. {
  6729. switch( ssl->minor_ver )
  6730. {
  6731. case MBEDTLS_SSL_MINOR_VERSION_2:
  6732. return( "DTLSv1.0" );
  6733. case MBEDTLS_SSL_MINOR_VERSION_3:
  6734. return( "DTLSv1.2" );
  6735. default:
  6736. return( "unknown (DTLS)" );
  6737. }
  6738. }
  6739. #endif
  6740. switch( ssl->minor_ver )
  6741. {
  6742. case MBEDTLS_SSL_MINOR_VERSION_0:
  6743. return( "SSLv3.0" );
  6744. case MBEDTLS_SSL_MINOR_VERSION_1:
  6745. return( "TLSv1.0" );
  6746. case MBEDTLS_SSL_MINOR_VERSION_2:
  6747. return( "TLSv1.1" );
  6748. case MBEDTLS_SSL_MINOR_VERSION_3:
  6749. return( "TLSv1.2" );
  6750. default:
  6751. return( "unknown" );
  6752. }
  6753. }
  6754. int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl )
  6755. {
  6756. size_t transform_expansion = 0;
  6757. const mbedtls_ssl_transform *transform = ssl->transform_out;
  6758. unsigned block_size;
  6759. if( transform == NULL )
  6760. return( (int) mbedtls_ssl_hdr_len( ssl ) );
  6761. #if defined(MBEDTLS_ZLIB_SUPPORT)
  6762. if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL )
  6763. return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  6764. #endif
  6765. switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) )
  6766. {
  6767. case MBEDTLS_MODE_GCM:
  6768. case MBEDTLS_MODE_CCM:
  6769. case MBEDTLS_MODE_CHACHAPOLY:
  6770. case MBEDTLS_MODE_STREAM:
  6771. transform_expansion = transform->minlen;
  6772. break;
  6773. case MBEDTLS_MODE_CBC:
  6774. block_size = mbedtls_cipher_get_block_size(
  6775. &transform->cipher_ctx_enc );
  6776. /* Expansion due to the addition of the MAC. */
  6777. transform_expansion += transform->maclen;
  6778. /* Expansion due to the addition of CBC padding;
  6779. * Theoretically up to 256 bytes, but we never use
  6780. * more than the block size of the underlying cipher. */
  6781. transform_expansion += block_size;
  6782. /* For TLS 1.1 or higher, an explicit IV is added
  6783. * after the record header. */
  6784. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  6785. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  6786. transform_expansion += block_size;
  6787. #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
  6788. break;
  6789. default:
  6790. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  6791. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  6792. }
  6793. return( (int)( mbedtls_ssl_hdr_len( ssl ) + transform_expansion ) );
  6794. }
  6795. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  6796. size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl )
  6797. {
  6798. size_t max_len;
  6799. /*
  6800. * Assume mfl_code is correct since it was checked when set
  6801. */
  6802. max_len = ssl_mfl_code_to_length( ssl->conf->mfl_code );
  6803. /* Check if a smaller max length was negotiated */
  6804. if( ssl->session_out != NULL &&
  6805. ssl_mfl_code_to_length( ssl->session_out->mfl_code ) < max_len )
  6806. {
  6807. max_len = ssl_mfl_code_to_length( ssl->session_out->mfl_code );
  6808. }
  6809. /* During a handshake, use the value being negotiated */
  6810. if( ssl->session_negotiate != NULL &&
  6811. ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code ) < max_len )
  6812. {
  6813. max_len = ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code );
  6814. }
  6815. return( max_len );
  6816. }
  6817. #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
  6818. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6819. static size_t ssl_get_current_mtu( const mbedtls_ssl_context *ssl )
  6820. {
  6821. /* Return unlimited mtu for client hello messages to avoid fragmentation. */
  6822. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
  6823. ( ssl->state == MBEDTLS_SSL_CLIENT_HELLO ||
  6824. ssl->state == MBEDTLS_SSL_SERVER_HELLO ) )
  6825. return ( 0 );
  6826. if( ssl->handshake == NULL || ssl->handshake->mtu == 0 )
  6827. return( ssl->mtu );
  6828. if( ssl->mtu == 0 )
  6829. return( ssl->handshake->mtu );
  6830. return( ssl->mtu < ssl->handshake->mtu ?
  6831. ssl->mtu : ssl->handshake->mtu );
  6832. }
  6833. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  6834. int mbedtls_ssl_get_max_out_record_payload( const mbedtls_ssl_context *ssl )
  6835. {
  6836. size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
  6837. #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \
  6838. !defined(MBEDTLS_SSL_PROTO_DTLS)
  6839. (void) ssl;
  6840. #endif
  6841. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  6842. const size_t mfl = mbedtls_ssl_get_max_frag_len( ssl );
  6843. if( max_len > mfl )
  6844. max_len = mfl;
  6845. #endif
  6846. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6847. if( ssl_get_current_mtu( ssl ) != 0 )
  6848. {
  6849. const size_t mtu = ssl_get_current_mtu( ssl );
  6850. const int ret = mbedtls_ssl_get_record_expansion( ssl );
  6851. const size_t overhead = (size_t) ret;
  6852. if( ret < 0 )
  6853. return( ret );
  6854. if( mtu <= overhead )
  6855. {
  6856. MBEDTLS_SSL_DEBUG_MSG( 1, ( "MTU too low for record expansion" ) );
  6857. return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  6858. }
  6859. if( max_len > mtu - overhead )
  6860. max_len = mtu - overhead;
  6861. }
  6862. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  6863. #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \
  6864. !defined(MBEDTLS_SSL_PROTO_DTLS)
  6865. ((void) ssl);
  6866. #endif
  6867. return( (int) max_len );
  6868. }
  6869. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  6870. const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl )
  6871. {
  6872. if( ssl == NULL || ssl->session == NULL )
  6873. return( NULL );
  6874. return( ssl->session->peer_cert );
  6875. }
  6876. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  6877. #if defined(MBEDTLS_SSL_CLI_C)
  6878. int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *dst )
  6879. {
  6880. if( ssl == NULL ||
  6881. dst == NULL ||
  6882. ssl->session == NULL ||
  6883. ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
  6884. {
  6885. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6886. }
  6887. return( ssl_session_copy( dst, ssl->session ) );
  6888. }
  6889. #endif /* MBEDTLS_SSL_CLI_C */
  6890. /*
  6891. * Perform a single step of the SSL handshake
  6892. */
  6893. int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl )
  6894. {
  6895. int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
  6896. if( ssl == NULL || ssl->conf == NULL )
  6897. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6898. #if defined(MBEDTLS_SSL_CLI_C)
  6899. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  6900. ret = mbedtls_ssl_handshake_client_step( ssl );
  6901. #endif
  6902. #if defined(MBEDTLS_SSL_SRV_C)
  6903. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  6904. ret = mbedtls_ssl_handshake_server_step( ssl );
  6905. #endif
  6906. return( ret );
  6907. }
  6908. /*
  6909. * Perform the SSL handshake
  6910. */
  6911. int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl )
  6912. {
  6913. int ret = 0;
  6914. if( ssl == NULL || ssl->conf == NULL )
  6915. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6916. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) );
  6917. while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  6918. {
  6919. ret = mbedtls_ssl_handshake_step( ssl );
  6920. if( ret != 0 )
  6921. break;
  6922. }
  6923. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) );
  6924. return( ret );
  6925. }
  6926. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  6927. #if defined(MBEDTLS_SSL_SRV_C)
  6928. /*
  6929. * Write HelloRequest to request renegotiation on server
  6930. */
  6931. static int ssl_write_hello_request( mbedtls_ssl_context *ssl )
  6932. {
  6933. int ret;
  6934. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) );
  6935. ssl->out_msglen = 4;
  6936. ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  6937. ssl->out_msg[0] = MBEDTLS_SSL_HS_HELLO_REQUEST;
  6938. if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  6939. {
  6940. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  6941. return( ret );
  6942. }
  6943. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) );
  6944. return( 0 );
  6945. }
  6946. #endif /* MBEDTLS_SSL_SRV_C */
  6947. /*
  6948. * Actually renegotiate current connection, triggered by either:
  6949. * - any side: calling mbedtls_ssl_renegotiate(),
  6950. * - client: receiving a HelloRequest during mbedtls_ssl_read(),
  6951. * - server: receiving any handshake message on server during mbedtls_ssl_read() after
  6952. * the initial handshake is completed.
  6953. * If the handshake doesn't complete due to waiting for I/O, it will continue
  6954. * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively.
  6955. */
  6956. static int ssl_start_renegotiation( mbedtls_ssl_context *ssl )
  6957. {
  6958. int ret;
  6959. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) );
  6960. if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
  6961. return( ret );
  6962. /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and
  6963. * the ServerHello will have message_seq = 1" */
  6964. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6965. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  6966. ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
  6967. {
  6968. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  6969. ssl->handshake->out_msg_seq = 1;
  6970. else
  6971. ssl->handshake->in_msg_seq = 1;
  6972. }
  6973. #endif
  6974. ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
  6975. ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS;
  6976. if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
  6977. {
  6978. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
  6979. return( ret );
  6980. }
  6981. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) );
  6982. return( 0 );
  6983. }
  6984. /*
  6985. * Renegotiate current connection on client,
  6986. * or request renegotiation on server
  6987. */
  6988. int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl )
  6989. {
  6990. int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
  6991. if( ssl == NULL || ssl->conf == NULL )
  6992. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6993. #if defined(MBEDTLS_SSL_SRV_C)
  6994. /* On server, just send the request */
  6995. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  6996. {
  6997. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  6998. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6999. ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
  7000. /* Did we already try/start sending HelloRequest? */
  7001. if( ssl->out_left != 0 )
  7002. return( mbedtls_ssl_flush_output( ssl ) );
  7003. return( ssl_write_hello_request( ssl ) );
  7004. }
  7005. #endif /* MBEDTLS_SSL_SRV_C */
  7006. #if defined(MBEDTLS_SSL_CLI_C)
  7007. /*
  7008. * On client, either start the renegotiation process or,
  7009. * if already in progress, continue the handshake
  7010. */
  7011. if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
  7012. {
  7013. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  7014. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7015. if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 )
  7016. {
  7017. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
  7018. return( ret );
  7019. }
  7020. }
  7021. else
  7022. {
  7023. if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
  7024. {
  7025. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
  7026. return( ret );
  7027. }
  7028. }
  7029. #endif /* MBEDTLS_SSL_CLI_C */
  7030. return( ret );
  7031. }
  7032. /*
  7033. * Check record counters and renegotiate if they're above the limit.
  7034. */
  7035. static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl )
  7036. {
  7037. size_t ep_len = ssl_ep_len( ssl );
  7038. int in_ctr_cmp;
  7039. int out_ctr_cmp;
  7040. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ||
  7041. ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||
  7042. ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED )
  7043. {
  7044. return( 0 );
  7045. }
  7046. in_ctr_cmp = memcmp( ssl->in_ctr + ep_len,
  7047. ssl->conf->renego_period + ep_len, 8 - ep_len );
  7048. out_ctr_cmp = memcmp( ssl->cur_out_ctr + ep_len,
  7049. ssl->conf->renego_period + ep_len, 8 - ep_len );
  7050. if( in_ctr_cmp <= 0 && out_ctr_cmp <= 0 )
  7051. {
  7052. return( 0 );
  7053. }
  7054. MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) );
  7055. return( mbedtls_ssl_renegotiate( ssl ) );
  7056. }
  7057. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  7058. /*
  7059. * Receive application data decrypted from the SSL layer
  7060. */
  7061. int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
  7062. {
  7063. int ret;
  7064. size_t n;
  7065. if( ssl == NULL || ssl->conf == NULL )
  7066. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7067. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) );
  7068. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7069. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  7070. {
  7071. if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  7072. return( ret );
  7073. if( ssl->handshake != NULL &&
  7074. ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
  7075. {
  7076. if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
  7077. return( ret );
  7078. }
  7079. }
  7080. #endif
  7081. /*
  7082. * Check if renegotiation is necessary and/or handshake is
  7083. * in process. If yes, perform/continue, and fall through
  7084. * if an unexpected packet is received while the client
  7085. * is waiting for the ServerHello.
  7086. *
  7087. * (There is no equivalent to the last condition on
  7088. * the server-side as it is not treated as within
  7089. * a handshake while waiting for the ClientHello
  7090. * after a renegotiation request.)
  7091. */
  7092. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  7093. ret = ssl_check_ctr_renegotiate( ssl );
  7094. if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
  7095. ret != 0 )
  7096. {
  7097. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
  7098. return( ret );
  7099. }
  7100. #endif
  7101. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  7102. {
  7103. ret = mbedtls_ssl_handshake( ssl );
  7104. if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
  7105. ret != 0 )
  7106. {
  7107. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
  7108. return( ret );
  7109. }
  7110. }
  7111. /* Loop as long as no application data record is available */
  7112. while( ssl->in_offt == NULL )
  7113. {
  7114. /* Start timer if not already running */
  7115. if( ssl->f_get_timer != NULL &&
  7116. ssl->f_get_timer( ssl->p_timer ) == -1 )
  7117. {
  7118. ssl_set_timer( ssl, ssl->conf->read_timeout );
  7119. }
  7120. if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  7121. {
  7122. if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
  7123. return( 0 );
  7124. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  7125. return( ret );
  7126. }
  7127. if( ssl->in_msglen == 0 &&
  7128. ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA )
  7129. {
  7130. /*
  7131. * OpenSSL sends empty messages to randomize the IV
  7132. */
  7133. if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  7134. {
  7135. if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
  7136. return( 0 );
  7137. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  7138. return( ret );
  7139. }
  7140. }
  7141. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
  7142. {
  7143. MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) );
  7144. /*
  7145. * - For client-side, expect SERVER_HELLO_REQUEST.
  7146. * - For server-side, expect CLIENT_HELLO.
  7147. * - Fail (TLS) or silently drop record (DTLS) in other cases.
  7148. */
  7149. #if defined(MBEDTLS_SSL_CLI_C)
  7150. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
  7151. ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST ||
  7152. ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ) )
  7153. {
  7154. MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) );
  7155. /* With DTLS, drop the packet (probably from last handshake) */
  7156. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7157. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  7158. {
  7159. continue;
  7160. }
  7161. #endif
  7162. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  7163. }
  7164. #endif /* MBEDTLS_SSL_CLI_C */
  7165. #if defined(MBEDTLS_SSL_SRV_C)
  7166. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  7167. ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )
  7168. {
  7169. MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) );
  7170. /* With DTLS, drop the packet (probably from last handshake) */
  7171. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7172. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  7173. {
  7174. continue;
  7175. }
  7176. #endif
  7177. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  7178. }
  7179. #endif /* MBEDTLS_SSL_SRV_C */
  7180. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  7181. /* Determine whether renegotiation attempt should be accepted */
  7182. if( ! ( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
  7183. ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
  7184. ssl->conf->allow_legacy_renegotiation ==
  7185. MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) )
  7186. {
  7187. /*
  7188. * Accept renegotiation request
  7189. */
  7190. /* DTLS clients need to know renego is server-initiated */
  7191. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7192. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  7193. ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  7194. {
  7195. ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
  7196. }
  7197. #endif
  7198. ret = ssl_start_renegotiation( ssl );
  7199. if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
  7200. ret != 0 )
  7201. {
  7202. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
  7203. return( ret );
  7204. }
  7205. }
  7206. else
  7207. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  7208. {
  7209. /*
  7210. * Refuse renegotiation
  7211. */
  7212. MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) );
  7213. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  7214. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  7215. {
  7216. /* SSLv3 does not have a "no_renegotiation" warning, so
  7217. we send a fatal alert and abort the connection. */
  7218. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  7219. MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  7220. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  7221. }
  7222. else
  7223. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  7224. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  7225. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  7226. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
  7227. {
  7228. if( ( ret = mbedtls_ssl_send_alert_message( ssl,
  7229. MBEDTLS_SSL_ALERT_LEVEL_WARNING,
  7230. MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 )
  7231. {
  7232. return( ret );
  7233. }
  7234. }
  7235. else
  7236. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 ||
  7237. MBEDTLS_SSL_PROTO_TLS1_2 */
  7238. {
  7239. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  7240. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  7241. }
  7242. }
  7243. /* At this point, we don't know whether the renegotiation has been
  7244. * completed or not. The cases to consider are the following:
  7245. * 1) The renegotiation is complete. In this case, no new record
  7246. * has been read yet.
  7247. * 2) The renegotiation is incomplete because the client received
  7248. * an application data record while awaiting the ServerHello.
  7249. * 3) The renegotiation is incomplete because the client received
  7250. * a non-handshake, non-application data message while awaiting
  7251. * the ServerHello.
  7252. * In each of these case, looping will be the proper action:
  7253. * - For 1), the next iteration will read a new record and check
  7254. * if it's application data.
  7255. * - For 2), the loop condition isn't satisfied as application data
  7256. * is present, hence continue is the same as break
  7257. * - For 3), the loop condition is satisfied and read_record
  7258. * will re-deliver the message that was held back by the client
  7259. * when expecting the ServerHello.
  7260. */
  7261. continue;
  7262. }
  7263. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  7264. else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
  7265. {
  7266. if( ssl->conf->renego_max_records >= 0 )
  7267. {
  7268. if( ++ssl->renego_records_seen > ssl->conf->renego_max_records )
  7269. {
  7270. MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
  7271. "but not honored by client" ) );
  7272. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  7273. }
  7274. }
  7275. }
  7276. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  7277. /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */
  7278. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
  7279. {
  7280. MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) );
  7281. return( MBEDTLS_ERR_SSL_WANT_READ );
  7282. }
  7283. if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
  7284. {
  7285. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) );
  7286. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  7287. }
  7288. ssl->in_offt = ssl->in_msg;
  7289. /* We're going to return something now, cancel timer,
  7290. * except if handshake (renegotiation) is in progress */
  7291. if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
  7292. ssl_set_timer( ssl, 0 );
  7293. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7294. /* If we requested renego but received AppData, resend HelloRequest.
  7295. * Do it now, after setting in_offt, to avoid taking this branch
  7296. * again if ssl_write_hello_request() returns WANT_WRITE */
  7297. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
  7298. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  7299. ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
  7300. {
  7301. if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
  7302. {
  7303. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
  7304. return( ret );
  7305. }
  7306. }
  7307. #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
  7308. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  7309. }
  7310. n = ( len < ssl->in_msglen )
  7311. ? len : ssl->in_msglen;
  7312. memcpy( buf, ssl->in_offt, n );
  7313. ssl->in_msglen -= n;
  7314. /* Zeroising the plaintext buffer to erase unused application data
  7315. from the memory. */
  7316. mbedtls_platform_zeroize( ssl->in_offt, n );
  7317. if( ssl->in_msglen == 0 )
  7318. {
  7319. /* all bytes consumed */
  7320. ssl->in_offt = NULL;
  7321. ssl->keep_current_message = 0;
  7322. }
  7323. else
  7324. {
  7325. /* more data available */
  7326. ssl->in_offt += n;
  7327. }
  7328. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) );
  7329. return( (int) n );
  7330. }
  7331. /*
  7332. * Send application data to be encrypted by the SSL layer, taking care of max
  7333. * fragment length and buffer size.
  7334. *
  7335. * According to RFC 5246 Section 6.2.1:
  7336. *
  7337. * Zero-length fragments of Application data MAY be sent as they are
  7338. * potentially useful as a traffic analysis countermeasure.
  7339. *
  7340. * Therefore, it is possible that the input message length is 0 and the
  7341. * corresponding return code is 0 on success.
  7342. */
  7343. static int ssl_write_real( mbedtls_ssl_context *ssl,
  7344. const unsigned char *buf, size_t len )
  7345. {
  7346. int ret = mbedtls_ssl_get_max_out_record_payload( ssl );
  7347. const size_t max_len = (size_t) ret;
  7348. if( ret < 0 )
  7349. {
  7350. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_get_max_out_record_payload", ret );
  7351. return( ret );
  7352. }
  7353. if( len > max_len )
  7354. {
  7355. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7356. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  7357. {
  7358. MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) "
  7359. "maximum fragment length: %d > %d",
  7360. len, max_len ) );
  7361. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7362. }
  7363. else
  7364. #endif
  7365. len = max_len;
  7366. }
  7367. if( ssl->out_left != 0 )
  7368. {
  7369. /*
  7370. * The user has previously tried to send the data and
  7371. * MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially
  7372. * written. In this case, we expect the high-level write function
  7373. * (e.g. mbedtls_ssl_write()) to be called with the same parameters
  7374. */
  7375. if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  7376. {
  7377. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
  7378. return( ret );
  7379. }
  7380. }
  7381. else
  7382. {
  7383. /*
  7384. * The user is trying to send a message the first time, so we need to
  7385. * copy the data into the internal buffers and setup the data structure
  7386. * to keep track of partial writes
  7387. */
  7388. ssl->out_msglen = len;
  7389. ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
  7390. memcpy( ssl->out_msg, buf, len );
  7391. if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
  7392. {
  7393. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
  7394. return( ret );
  7395. }
  7396. }
  7397. return( (int) len );
  7398. }
  7399. /*
  7400. * Write application data, doing 1/n-1 splitting if necessary.
  7401. *
  7402. * With non-blocking I/O, ssl_write_real() may return WANT_WRITE,
  7403. * then the caller will call us again with the same arguments, so
  7404. * remember whether we already did the split or not.
  7405. */
  7406. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  7407. static int ssl_write_split( mbedtls_ssl_context *ssl,
  7408. const unsigned char *buf, size_t len )
  7409. {
  7410. int ret;
  7411. if( ssl->conf->cbc_record_splitting ==
  7412. MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ||
  7413. len <= 1 ||
  7414. ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 ||
  7415. mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc )
  7416. != MBEDTLS_MODE_CBC )
  7417. {
  7418. return( ssl_write_real( ssl, buf, len ) );
  7419. }
  7420. if( ssl->split_done == 0 )
  7421. {
  7422. if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 )
  7423. return( ret );
  7424. ssl->split_done = 1;
  7425. }
  7426. if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 )
  7427. return( ret );
  7428. ssl->split_done = 0;
  7429. return( ret + 1 );
  7430. }
  7431. #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
  7432. /*
  7433. * Write application data (public-facing wrapper)
  7434. */
  7435. int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len )
  7436. {
  7437. int ret;
  7438. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) );
  7439. if( ssl == NULL || ssl->conf == NULL )
  7440. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7441. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  7442. if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
  7443. {
  7444. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
  7445. return( ret );
  7446. }
  7447. #endif
  7448. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  7449. {
  7450. if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
  7451. {
  7452. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
  7453. return( ret );
  7454. }
  7455. }
  7456. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  7457. ret = ssl_write_split( ssl, buf, len );
  7458. #else
  7459. ret = ssl_write_real( ssl, buf, len );
  7460. #endif
  7461. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) );
  7462. return( ret );
  7463. }
  7464. /*
  7465. * Notify the peer that the connection is being closed
  7466. */
  7467. int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl )
  7468. {
  7469. int ret;
  7470. if( ssl == NULL || ssl->conf == NULL )
  7471. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7472. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
  7473. if( ssl->out_left != 0 )
  7474. return( mbedtls_ssl_flush_output( ssl ) );
  7475. if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
  7476. {
  7477. if( ( ret = mbedtls_ssl_send_alert_message( ssl,
  7478. MBEDTLS_SSL_ALERT_LEVEL_WARNING,
  7479. MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )
  7480. {
  7481. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret );
  7482. return( ret );
  7483. }
  7484. }
  7485. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) );
  7486. return( 0 );
  7487. }
  7488. void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform )
  7489. {
  7490. if( transform == NULL )
  7491. return;
  7492. #if defined(MBEDTLS_ZLIB_SUPPORT)
  7493. deflateEnd( &transform->ctx_deflate );
  7494. inflateEnd( &transform->ctx_inflate );
  7495. #endif
  7496. mbedtls_cipher_free( &transform->cipher_ctx_enc );
  7497. mbedtls_cipher_free( &transform->cipher_ctx_dec );
  7498. mbedtls_md_free( &transform->md_ctx_enc );
  7499. mbedtls_md_free( &transform->md_ctx_dec );
  7500. mbedtls_platform_zeroize( transform, sizeof( mbedtls_ssl_transform ) );
  7501. }
  7502. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7503. static void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert )
  7504. {
  7505. mbedtls_ssl_key_cert *cur = key_cert, *next;
  7506. while( cur != NULL )
  7507. {
  7508. next = cur->next;
  7509. mbedtls_free( cur );
  7510. cur = next;
  7511. }
  7512. }
  7513. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  7514. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7515. static void ssl_buffering_free( mbedtls_ssl_context *ssl )
  7516. {
  7517. unsigned offset;
  7518. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  7519. if( hs == NULL )
  7520. return;
  7521. ssl_free_buffered_record( ssl );
  7522. for( offset = 0; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ )
  7523. ssl_buffering_free_slot( ssl, offset );
  7524. }
  7525. static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
  7526. uint8_t slot )
  7527. {
  7528. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  7529. mbedtls_ssl_hs_buffer * const hs_buf = &hs->buffering.hs[slot];
  7530. if( slot >= MBEDTLS_SSL_MAX_BUFFERED_HS )
  7531. return;
  7532. if( hs_buf->is_valid == 1 )
  7533. {
  7534. hs->buffering.total_bytes_buffered -= hs_buf->data_len;
  7535. mbedtls_platform_zeroize( hs_buf->data, hs_buf->data_len );
  7536. mbedtls_free( hs_buf->data );
  7537. memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) );
  7538. }
  7539. }
  7540. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  7541. void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl )
  7542. {
  7543. mbedtls_ssl_handshake_params *handshake = ssl->handshake;
  7544. if( handshake == NULL )
  7545. return;
  7546. #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
  7547. if( ssl->conf->f_async_cancel != NULL && handshake->async_in_progress != 0 )
  7548. {
  7549. ssl->conf->f_async_cancel( ssl );
  7550. handshake->async_in_progress = 0;
  7551. }
  7552. #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
  7553. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  7554. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  7555. mbedtls_md5_free( &handshake->fin_md5 );
  7556. mbedtls_sha1_free( &handshake->fin_sha1 );
  7557. #endif
  7558. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  7559. #if defined(MBEDTLS_SHA256_C)
  7560. mbedtls_sha256_free( &handshake->fin_sha256 );
  7561. #endif
  7562. #if defined(MBEDTLS_SHA512_C)
  7563. mbedtls_sha512_free( &handshake->fin_sha512 );
  7564. #endif
  7565. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  7566. #if defined(MBEDTLS_DHM_C)
  7567. mbedtls_dhm_free( &handshake->dhm_ctx );
  7568. #endif
  7569. #if defined(MBEDTLS_ECDH_C)
  7570. mbedtls_ecdh_free( &handshake->ecdh_ctx );
  7571. #endif
  7572. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  7573. mbedtls_ecjpake_free( &handshake->ecjpake_ctx );
  7574. #if defined(MBEDTLS_SSL_CLI_C)
  7575. mbedtls_free( handshake->ecjpake_cache );
  7576. handshake->ecjpake_cache = NULL;
  7577. handshake->ecjpake_cache_len = 0;
  7578. #endif
  7579. #endif
  7580. #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
  7581. defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  7582. /* explicit void pointer cast for buggy MS compiler */
  7583. mbedtls_free( (void *) handshake->curves );
  7584. #endif
  7585. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
  7586. if( handshake->psk != NULL )
  7587. {
  7588. mbedtls_platform_zeroize( handshake->psk, handshake->psk_len );
  7589. mbedtls_free( handshake->psk );
  7590. }
  7591. #endif
  7592. #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
  7593. defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  7594. /*
  7595. * Free only the linked list wrapper, not the keys themselves
  7596. * since the belong to the SNI callback
  7597. */
  7598. if( handshake->sni_key_cert != NULL )
  7599. {
  7600. mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next;
  7601. while( cur != NULL )
  7602. {
  7603. next = cur->next;
  7604. mbedtls_free( cur );
  7605. cur = next;
  7606. }
  7607. }
  7608. #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */
  7609. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  7610. mbedtls_x509_crt_restart_free( &handshake->ecrs_ctx );
  7611. #endif
  7612. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7613. mbedtls_free( handshake->verify_cookie );
  7614. ssl_flight_free( handshake->flight );
  7615. ssl_buffering_free( ssl );
  7616. #endif
  7617. mbedtls_platform_zeroize( handshake,
  7618. sizeof( mbedtls_ssl_handshake_params ) );
  7619. }
  7620. void mbedtls_ssl_session_free( mbedtls_ssl_session *session )
  7621. {
  7622. if( session == NULL )
  7623. return;
  7624. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7625. if( session->peer_cert != NULL )
  7626. {
  7627. mbedtls_x509_crt_free( session->peer_cert );
  7628. mbedtls_free( session->peer_cert );
  7629. }
  7630. #endif
  7631. #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
  7632. mbedtls_free( session->ticket );
  7633. #endif
  7634. mbedtls_platform_zeroize( session, sizeof( mbedtls_ssl_session ) );
  7635. }
  7636. /*
  7637. * Free an SSL context
  7638. */
  7639. void mbedtls_ssl_free( mbedtls_ssl_context *ssl )
  7640. {
  7641. if( ssl == NULL )
  7642. return;
  7643. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) );
  7644. if( ssl->out_buf != NULL )
  7645. {
  7646. mbedtls_platform_zeroize( ssl->out_buf, MBEDTLS_SSL_OUT_BUFFER_LEN );
  7647. mbedtls_free( ssl->out_buf );
  7648. }
  7649. if( ssl->in_buf != NULL )
  7650. {
  7651. mbedtls_platform_zeroize( ssl->in_buf, MBEDTLS_SSL_IN_BUFFER_LEN );
  7652. mbedtls_free( ssl->in_buf );
  7653. }
  7654. #if defined(MBEDTLS_ZLIB_SUPPORT)
  7655. if( ssl->compress_buf != NULL )
  7656. {
  7657. mbedtls_platform_zeroize( ssl->compress_buf, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );
  7658. mbedtls_free( ssl->compress_buf );
  7659. }
  7660. #endif
  7661. if( ssl->transform )
  7662. {
  7663. mbedtls_ssl_transform_free( ssl->transform );
  7664. mbedtls_free( ssl->transform );
  7665. }
  7666. if( ssl->handshake )
  7667. {
  7668. mbedtls_ssl_handshake_free( ssl );
  7669. mbedtls_ssl_transform_free( ssl->transform_negotiate );
  7670. mbedtls_ssl_session_free( ssl->session_negotiate );
  7671. mbedtls_free( ssl->handshake );
  7672. mbedtls_free( ssl->transform_negotiate );
  7673. mbedtls_free( ssl->session_negotiate );
  7674. }
  7675. if( ssl->session )
  7676. {
  7677. mbedtls_ssl_session_free( ssl->session );
  7678. mbedtls_free( ssl->session );
  7679. }
  7680. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7681. if( ssl->hostname != NULL )
  7682. {
  7683. mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );
  7684. mbedtls_free( ssl->hostname );
  7685. }
  7686. #endif
  7687. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  7688. if( mbedtls_ssl_hw_record_finish != NULL )
  7689. {
  7690. MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_finish()" ) );
  7691. mbedtls_ssl_hw_record_finish( ssl );
  7692. }
  7693. #endif
  7694. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
  7695. mbedtls_free( ssl->cli_id );
  7696. #endif
  7697. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) );
  7698. /* Actually clear after last debug message */
  7699. mbedtls_platform_zeroize( ssl, sizeof( mbedtls_ssl_context ) );
  7700. }
  7701. /*
  7702. * Initialze mbedtls_ssl_config
  7703. */
  7704. void mbedtls_ssl_config_init( mbedtls_ssl_config *conf )
  7705. {
  7706. memset( conf, 0, sizeof( mbedtls_ssl_config ) );
  7707. }
  7708. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  7709. static int ssl_preset_default_hashes[] = {
  7710. #if defined(MBEDTLS_SHA512_C)
  7711. MBEDTLS_MD_SHA512,
  7712. MBEDTLS_MD_SHA384,
  7713. #endif
  7714. #if defined(MBEDTLS_SHA256_C)
  7715. MBEDTLS_MD_SHA256,
  7716. MBEDTLS_MD_SHA224,
  7717. #endif
  7718. #if defined(MBEDTLS_SHA1_C) && defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE)
  7719. MBEDTLS_MD_SHA1,
  7720. #endif
  7721. MBEDTLS_MD_NONE
  7722. };
  7723. #endif
  7724. static int ssl_preset_suiteb_ciphersuites[] = {
  7725. MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  7726. MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  7727. 0
  7728. };
  7729. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  7730. static int ssl_preset_suiteb_hashes[] = {
  7731. MBEDTLS_MD_SHA256,
  7732. MBEDTLS_MD_SHA384,
  7733. MBEDTLS_MD_NONE
  7734. };
  7735. #endif
  7736. #if defined(MBEDTLS_ECP_C)
  7737. static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = {
  7738. #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
  7739. MBEDTLS_ECP_DP_SECP256R1,
  7740. #endif
  7741. #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
  7742. MBEDTLS_ECP_DP_SECP384R1,
  7743. #endif
  7744. MBEDTLS_ECP_DP_NONE
  7745. };
  7746. #endif
  7747. /*
  7748. * Load default in mbedtls_ssl_config
  7749. */
  7750. int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
  7751. int endpoint, int transport, int preset )
  7752. {
  7753. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
  7754. int ret;
  7755. #endif
  7756. /* Use the functions here so that they are covered in tests,
  7757. * but otherwise access member directly for efficiency */
  7758. mbedtls_ssl_conf_endpoint( conf, endpoint );
  7759. mbedtls_ssl_conf_transport( conf, transport );
  7760. /*
  7761. * Things that are common to all presets
  7762. */
  7763. #if defined(MBEDTLS_SSL_CLI_C)
  7764. if( endpoint == MBEDTLS_SSL_IS_CLIENT )
  7765. {
  7766. conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
  7767. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  7768. conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED;
  7769. #endif
  7770. }
  7771. #endif
  7772. #if defined(MBEDTLS_ARC4_C)
  7773. conf->arc4_disabled = MBEDTLS_SSL_ARC4_DISABLED;
  7774. #endif
  7775. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  7776. conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
  7777. #endif
  7778. #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
  7779. conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
  7780. #endif
  7781. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  7782. conf->cbc_record_splitting = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED;
  7783. #endif
  7784. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
  7785. conf->f_cookie_write = ssl_cookie_write_dummy;
  7786. conf->f_cookie_check = ssl_cookie_check_dummy;
  7787. #endif
  7788. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  7789. conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED;
  7790. #endif
  7791. #if defined(MBEDTLS_SSL_SRV_C)
  7792. conf->cert_req_ca_list = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED;
  7793. #endif
  7794. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7795. conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN;
  7796. conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX;
  7797. #endif
  7798. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  7799. conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT;
  7800. memset( conf->renego_period, 0x00, 2 );
  7801. memset( conf->renego_period + 2, 0xFF, 6 );
  7802. #endif
  7803. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
  7804. if( endpoint == MBEDTLS_SSL_IS_SERVER )
  7805. {
  7806. const unsigned char dhm_p[] =
  7807. MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN;
  7808. const unsigned char dhm_g[] =
  7809. MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN;
  7810. if ( ( ret = mbedtls_ssl_conf_dh_param_bin( conf,
  7811. dhm_p, sizeof( dhm_p ),
  7812. dhm_g, sizeof( dhm_g ) ) ) != 0 )
  7813. {
  7814. return( ret );
  7815. }
  7816. }
  7817. #endif
  7818. /*
  7819. * Preset-specific defaults
  7820. */
  7821. switch( preset )
  7822. {
  7823. /*
  7824. * NSA Suite B
  7825. */
  7826. case MBEDTLS_SSL_PRESET_SUITEB:
  7827. conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
  7828. conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */
  7829. conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
  7830. conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
  7831. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
  7832. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
  7833. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
  7834. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
  7835. ssl_preset_suiteb_ciphersuites;
  7836. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7837. conf->cert_profile = &mbedtls_x509_crt_profile_suiteb;
  7838. #endif
  7839. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  7840. conf->sig_hashes = ssl_preset_suiteb_hashes;
  7841. #endif
  7842. #if defined(MBEDTLS_ECP_C)
  7843. conf->curve_list = ssl_preset_suiteb_curves;
  7844. #endif
  7845. break;
  7846. /*
  7847. * Default
  7848. */
  7849. default:
  7850. conf->min_major_ver = ( MBEDTLS_SSL_MIN_MAJOR_VERSION >
  7851. MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION ) ?
  7852. MBEDTLS_SSL_MIN_MAJOR_VERSION :
  7853. MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION;
  7854. conf->min_minor_ver = ( MBEDTLS_SSL_MIN_MINOR_VERSION >
  7855. MBEDTLS_SSL_MIN_VALID_MINOR_VERSION ) ?
  7856. MBEDTLS_SSL_MIN_MINOR_VERSION :
  7857. MBEDTLS_SSL_MIN_VALID_MINOR_VERSION;
  7858. conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
  7859. conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
  7860. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7861. if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  7862. conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_2;
  7863. #endif
  7864. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
  7865. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
  7866. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
  7867. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
  7868. mbedtls_ssl_list_ciphersuites();
  7869. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7870. conf->cert_profile = &mbedtls_x509_crt_profile_default;
  7871. #endif
  7872. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  7873. conf->sig_hashes = ssl_preset_default_hashes;
  7874. #endif
  7875. #if defined(MBEDTLS_ECP_C)
  7876. conf->curve_list = mbedtls_ecp_grp_id_list();
  7877. #endif
  7878. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
  7879. conf->dhm_min_bitlen = 1024;
  7880. #endif
  7881. }
  7882. return( 0 );
  7883. }
  7884. /*
  7885. * Free mbedtls_ssl_config
  7886. */
  7887. void mbedtls_ssl_config_free( mbedtls_ssl_config *conf )
  7888. {
  7889. #if defined(MBEDTLS_DHM_C)
  7890. mbedtls_mpi_free( &conf->dhm_P );
  7891. mbedtls_mpi_free( &conf->dhm_G );
  7892. #endif
  7893. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
  7894. if( conf->psk != NULL )
  7895. {
  7896. mbedtls_platform_zeroize( conf->psk, conf->psk_len );
  7897. mbedtls_free( conf->psk );
  7898. conf->psk = NULL;
  7899. conf->psk_len = 0;
  7900. }
  7901. if( conf->psk_identity != NULL )
  7902. {
  7903. mbedtls_platform_zeroize( conf->psk_identity, conf->psk_identity_len );
  7904. mbedtls_free( conf->psk_identity );
  7905. conf->psk_identity = NULL;
  7906. conf->psk_identity_len = 0;
  7907. }
  7908. #endif
  7909. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7910. ssl_key_cert_free( conf->key_cert );
  7911. #endif
  7912. mbedtls_platform_zeroize( conf, sizeof( mbedtls_ssl_config ) );
  7913. }
  7914. #if defined(MBEDTLS_PK_C) && \
  7915. ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) )
  7916. /*
  7917. * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX
  7918. */
  7919. unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk )
  7920. {
  7921. #if defined(MBEDTLS_RSA_C)
  7922. if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) )
  7923. return( MBEDTLS_SSL_SIG_RSA );
  7924. #endif
  7925. #if defined(MBEDTLS_ECDSA_C)
  7926. if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) )
  7927. return( MBEDTLS_SSL_SIG_ECDSA );
  7928. #endif
  7929. return( MBEDTLS_SSL_SIG_ANON );
  7930. }
  7931. unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type )
  7932. {
  7933. switch( type ) {
  7934. case MBEDTLS_PK_RSA:
  7935. return( MBEDTLS_SSL_SIG_RSA );
  7936. case MBEDTLS_PK_ECDSA:
  7937. case MBEDTLS_PK_ECKEY:
  7938. return( MBEDTLS_SSL_SIG_ECDSA );
  7939. default:
  7940. return( MBEDTLS_SSL_SIG_ANON );
  7941. }
  7942. }
  7943. mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig )
  7944. {
  7945. switch( sig )
  7946. {
  7947. #if defined(MBEDTLS_RSA_C)
  7948. case MBEDTLS_SSL_SIG_RSA:
  7949. return( MBEDTLS_PK_RSA );
  7950. #endif
  7951. #if defined(MBEDTLS_ECDSA_C)
  7952. case MBEDTLS_SSL_SIG_ECDSA:
  7953. return( MBEDTLS_PK_ECDSA );
  7954. #endif
  7955. default:
  7956. return( MBEDTLS_PK_NONE );
  7957. }
  7958. }
  7959. #endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */
  7960. #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
  7961. defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  7962. /* Find an entry in a signature-hash set matching a given hash algorithm. */
  7963. mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set,
  7964. mbedtls_pk_type_t sig_alg )
  7965. {
  7966. switch( sig_alg )
  7967. {
  7968. case MBEDTLS_PK_RSA:
  7969. return( set->rsa );
  7970. case MBEDTLS_PK_ECDSA:
  7971. return( set->ecdsa );
  7972. default:
  7973. return( MBEDTLS_MD_NONE );
  7974. }
  7975. }
  7976. /* Add a signature-hash-pair to a signature-hash set */
  7977. void mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set,
  7978. mbedtls_pk_type_t sig_alg,
  7979. mbedtls_md_type_t md_alg )
  7980. {
  7981. switch( sig_alg )
  7982. {
  7983. case MBEDTLS_PK_RSA:
  7984. if( set->rsa == MBEDTLS_MD_NONE )
  7985. set->rsa = md_alg;
  7986. break;
  7987. case MBEDTLS_PK_ECDSA:
  7988. if( set->ecdsa == MBEDTLS_MD_NONE )
  7989. set->ecdsa = md_alg;
  7990. break;
  7991. default:
  7992. break;
  7993. }
  7994. }
  7995. /* Allow exactly one hash algorithm for each signature. */
  7996. void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set,
  7997. mbedtls_md_type_t md_alg )
  7998. {
  7999. set->rsa = md_alg;
  8000. set->ecdsa = md_alg;
  8001. }
  8002. #endif /* MBEDTLS_SSL_PROTO_TLS1_2) &&
  8003. MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
  8004. /*
  8005. * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX
  8006. */
  8007. mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash )
  8008. {
  8009. switch( hash )
  8010. {
  8011. #if defined(MBEDTLS_MD5_C)
  8012. case MBEDTLS_SSL_HASH_MD5:
  8013. return( MBEDTLS_MD_MD5 );
  8014. #endif
  8015. #if defined(MBEDTLS_SHA1_C)
  8016. case MBEDTLS_SSL_HASH_SHA1:
  8017. return( MBEDTLS_MD_SHA1 );
  8018. #endif
  8019. #if defined(MBEDTLS_SHA256_C)
  8020. case MBEDTLS_SSL_HASH_SHA224:
  8021. return( MBEDTLS_MD_SHA224 );
  8022. case MBEDTLS_SSL_HASH_SHA256:
  8023. return( MBEDTLS_MD_SHA256 );
  8024. #endif
  8025. #if defined(MBEDTLS_SHA512_C)
  8026. case MBEDTLS_SSL_HASH_SHA384:
  8027. return( MBEDTLS_MD_SHA384 );
  8028. case MBEDTLS_SSL_HASH_SHA512:
  8029. return( MBEDTLS_MD_SHA512 );
  8030. #endif
  8031. default:
  8032. return( MBEDTLS_MD_NONE );
  8033. }
  8034. }
  8035. /*
  8036. * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX
  8037. */
  8038. unsigned char mbedtls_ssl_hash_from_md_alg( int md )
  8039. {
  8040. switch( md )
  8041. {
  8042. #if defined(MBEDTLS_MD5_C)
  8043. case MBEDTLS_MD_MD5:
  8044. return( MBEDTLS_SSL_HASH_MD5 );
  8045. #endif
  8046. #if defined(MBEDTLS_SHA1_C)
  8047. case MBEDTLS_MD_SHA1:
  8048. return( MBEDTLS_SSL_HASH_SHA1 );
  8049. #endif
  8050. #if defined(MBEDTLS_SHA256_C)
  8051. case MBEDTLS_MD_SHA224:
  8052. return( MBEDTLS_SSL_HASH_SHA224 );
  8053. case MBEDTLS_MD_SHA256:
  8054. return( MBEDTLS_SSL_HASH_SHA256 );
  8055. #endif
  8056. #if defined(MBEDTLS_SHA512_C)
  8057. case MBEDTLS_MD_SHA384:
  8058. return( MBEDTLS_SSL_HASH_SHA384 );
  8059. case MBEDTLS_MD_SHA512:
  8060. return( MBEDTLS_SSL_HASH_SHA512 );
  8061. #endif
  8062. default:
  8063. return( MBEDTLS_SSL_HASH_NONE );
  8064. }
  8065. }
  8066. #if defined(MBEDTLS_ECP_C)
  8067. /*
  8068. * Check if a curve proposed by the peer is in our list.
  8069. * Return 0 if we're willing to use it, -1 otherwise.
  8070. */
  8071. int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id )
  8072. {
  8073. const mbedtls_ecp_group_id *gid;
  8074. if( ssl->conf->curve_list == NULL )
  8075. return( -1 );
  8076. for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )
  8077. if( *gid == grp_id )
  8078. return( 0 );
  8079. return( -1 );
  8080. }
  8081. #endif /* MBEDTLS_ECP_C */
  8082. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  8083. /*
  8084. * Check if a hash proposed by the peer is in our list.
  8085. * Return 0 if we're willing to use it, -1 otherwise.
  8086. */
  8087. int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl,
  8088. mbedtls_md_type_t md )
  8089. {
  8090. const int *cur;
  8091. if( ssl->conf->sig_hashes == NULL )
  8092. return( -1 );
  8093. for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )
  8094. if( *cur == (int) md )
  8095. return( 0 );
  8096. return( -1 );
  8097. }
  8098. #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
  8099. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  8100. int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert,
  8101. const mbedtls_ssl_ciphersuite_t *ciphersuite,
  8102. int cert_endpoint,
  8103. uint32_t *flags )
  8104. {
  8105. int ret = 0;
  8106. #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
  8107. int usage = 0;
  8108. #endif
  8109. #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
  8110. const char *ext_oid;
  8111. size_t ext_len;
  8112. #endif
  8113. #if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) && \
  8114. !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
  8115. ((void) cert);
  8116. ((void) cert_endpoint);
  8117. ((void) flags);
  8118. #endif
  8119. #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
  8120. if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
  8121. {
  8122. /* Server part of the key exchange */
  8123. switch( ciphersuite->key_exchange )
  8124. {
  8125. case MBEDTLS_KEY_EXCHANGE_RSA:
  8126. case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
  8127. usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
  8128. break;
  8129. case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
  8130. case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
  8131. case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
  8132. usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
  8133. break;
  8134. case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
  8135. case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
  8136. usage = MBEDTLS_X509_KU_KEY_AGREEMENT;
  8137. break;
  8138. /* Don't use default: we want warnings when adding new values */
  8139. case MBEDTLS_KEY_EXCHANGE_NONE:
  8140. case MBEDTLS_KEY_EXCHANGE_PSK:
  8141. case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
  8142. case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
  8143. case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
  8144. usage = 0;
  8145. }
  8146. }
  8147. else
  8148. {
  8149. /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */
  8150. usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
  8151. }
  8152. if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 )
  8153. {
  8154. *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE;
  8155. ret = -1;
  8156. }
  8157. #else
  8158. ((void) ciphersuite);
  8159. #endif /* MBEDTLS_X509_CHECK_KEY_USAGE */
  8160. #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
  8161. if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
  8162. {
  8163. ext_oid = MBEDTLS_OID_SERVER_AUTH;
  8164. ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH );
  8165. }
  8166. else
  8167. {
  8168. ext_oid = MBEDTLS_OID_CLIENT_AUTH;
  8169. ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH );
  8170. }
  8171. if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 )
  8172. {
  8173. *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE;
  8174. ret = -1;
  8175. }
  8176. #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
  8177. return( ret );
  8178. }
  8179. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  8180. /*
  8181. * Convert version numbers to/from wire format
  8182. * and, for DTLS, to/from TLS equivalent.
  8183. *
  8184. * For TLS this is the identity.
  8185. * For DTLS, use 1's complement (v -> 255 - v, and then map as follows:
  8186. * 1.0 <-> 3.2 (DTLS 1.0 is based on TLS 1.1)
  8187. * 1.x <-> 3.x+1 for x != 0 (DTLS 1.2 based on TLS 1.2)
  8188. */
  8189. void mbedtls_ssl_write_version( int major, int minor, int transport,
  8190. unsigned char ver[2] )
  8191. {
  8192. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  8193. if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  8194. {
  8195. if( minor == MBEDTLS_SSL_MINOR_VERSION_2 )
  8196. --minor; /* DTLS 1.0 stored as TLS 1.1 internally */
  8197. ver[0] = (unsigned char)( 255 - ( major - 2 ) );
  8198. ver[1] = (unsigned char)( 255 - ( minor - 1 ) );
  8199. }
  8200. else
  8201. #else
  8202. ((void) transport);
  8203. #endif
  8204. {
  8205. ver[0] = (unsigned char) major;
  8206. ver[1] = (unsigned char) minor;
  8207. }
  8208. }
  8209. void mbedtls_ssl_read_version( int *major, int *minor, int transport,
  8210. const unsigned char ver[2] )
  8211. {
  8212. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  8213. if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  8214. {
  8215. *major = 255 - ver[0] + 2;
  8216. *minor = 255 - ver[1] + 1;
  8217. if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 )
  8218. ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */
  8219. }
  8220. else
  8221. #else
  8222. ((void) transport);
  8223. #endif
  8224. {
  8225. *major = ver[0];
  8226. *minor = ver[1];
  8227. }
  8228. }
  8229. int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md )
  8230. {
  8231. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  8232. if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
  8233. return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
  8234. switch( md )
  8235. {
  8236. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  8237. #if defined(MBEDTLS_MD5_C)
  8238. case MBEDTLS_SSL_HASH_MD5:
  8239. return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
  8240. #endif
  8241. #if defined(MBEDTLS_SHA1_C)
  8242. case MBEDTLS_SSL_HASH_SHA1:
  8243. ssl->handshake->calc_verify = ssl_calc_verify_tls;
  8244. break;
  8245. #endif
  8246. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
  8247. #if defined(MBEDTLS_SHA512_C)
  8248. case MBEDTLS_SSL_HASH_SHA384:
  8249. ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384;
  8250. break;
  8251. #endif
  8252. #if defined(MBEDTLS_SHA256_C)
  8253. case MBEDTLS_SSL_HASH_SHA256:
  8254. ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256;
  8255. break;
  8256. #endif
  8257. default:
  8258. return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
  8259. }
  8260. return 0;
  8261. #else /* !MBEDTLS_SSL_PROTO_TLS1_2 */
  8262. (void) ssl;
  8263. (void) md;
  8264. return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
  8265. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  8266. }
  8267. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  8268. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  8269. int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl,
  8270. unsigned char *output,
  8271. unsigned char *data, size_t data_len )
  8272. {
  8273. int ret = 0;
  8274. mbedtls_md5_context mbedtls_md5;
  8275. mbedtls_sha1_context mbedtls_sha1;
  8276. mbedtls_md5_init( &mbedtls_md5 );
  8277. mbedtls_sha1_init( &mbedtls_sha1 );
  8278. /*
  8279. * digitally-signed struct {
  8280. * opaque md5_hash[16];
  8281. * opaque sha_hash[20];
  8282. * };
  8283. *
  8284. * md5_hash
  8285. * MD5(ClientHello.random + ServerHello.random
  8286. * + ServerParams);
  8287. * sha_hash
  8288. * SHA(ClientHello.random + ServerHello.random
  8289. * + ServerParams);
  8290. */
  8291. if( ( ret = mbedtls_md5_starts_ret( &mbedtls_md5 ) ) != 0 )
  8292. {
  8293. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_starts_ret", ret );
  8294. goto exit;
  8295. }
  8296. if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5,
  8297. ssl->handshake->randbytes, 64 ) ) != 0 )
  8298. {
  8299. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret );
  8300. goto exit;
  8301. }
  8302. if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5, data, data_len ) ) != 0 )
  8303. {
  8304. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret );
  8305. goto exit;
  8306. }
  8307. if( ( ret = mbedtls_md5_finish_ret( &mbedtls_md5, output ) ) != 0 )
  8308. {
  8309. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_finish_ret", ret );
  8310. goto exit;
  8311. }
  8312. if( ( ret = mbedtls_sha1_starts_ret( &mbedtls_sha1 ) ) != 0 )
  8313. {
  8314. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_starts_ret", ret );
  8315. goto exit;
  8316. }
  8317. if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1,
  8318. ssl->handshake->randbytes, 64 ) ) != 0 )
  8319. {
  8320. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret );
  8321. goto exit;
  8322. }
  8323. if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1, data,
  8324. data_len ) ) != 0 )
  8325. {
  8326. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret );
  8327. goto exit;
  8328. }
  8329. if( ( ret = mbedtls_sha1_finish_ret( &mbedtls_sha1,
  8330. output + 16 ) ) != 0 )
  8331. {
  8332. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_finish_ret", ret );
  8333. goto exit;
  8334. }
  8335. exit:
  8336. mbedtls_md5_free( &mbedtls_md5 );
  8337. mbedtls_sha1_free( &mbedtls_sha1 );
  8338. if( ret != 0 )
  8339. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  8340. MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
  8341. return( ret );
  8342. }
  8343. #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
  8344. MBEDTLS_SSL_PROTO_TLS1_1 */
  8345. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  8346. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  8347. int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
  8348. unsigned char *hash, size_t *hashlen,
  8349. unsigned char *data, size_t data_len,
  8350. mbedtls_md_type_t md_alg )
  8351. {
  8352. int ret = 0;
  8353. mbedtls_md_context_t ctx;
  8354. const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
  8355. *hashlen = mbedtls_md_get_size( md_info );
  8356. mbedtls_md_init( &ctx );
  8357. /*
  8358. * digitally-signed struct {
  8359. * opaque client_random[32];
  8360. * opaque server_random[32];
  8361. * ServerDHParams params;
  8362. * };
  8363. */
  8364. if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 )
  8365. {
  8366. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
  8367. goto exit;
  8368. }
  8369. if( ( ret = mbedtls_md_starts( &ctx ) ) != 0 )
  8370. {
  8371. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_starts", ret );
  8372. goto exit;
  8373. }
  8374. if( ( ret = mbedtls_md_update( &ctx, ssl->handshake->randbytes, 64 ) ) != 0 )
  8375. {
  8376. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
  8377. goto exit;
  8378. }
  8379. if( ( ret = mbedtls_md_update( &ctx, data, data_len ) ) != 0 )
  8380. {
  8381. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
  8382. goto exit;
  8383. }
  8384. if( ( ret = mbedtls_md_finish( &ctx, hash ) ) != 0 )
  8385. {
  8386. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_finish", ret );
  8387. goto exit;
  8388. }
  8389. exit:
  8390. mbedtls_md_free( &ctx );
  8391. if( ret != 0 )
  8392. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  8393. MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
  8394. return( ret );
  8395. }
  8396. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
  8397. MBEDTLS_SSL_PROTO_TLS1_2 */
  8398. #endif /* MBEDTLS_SSL_TLS_C */