ssl_tls.c 312 KB

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