ssl_msg.c 222 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377
  1. /*
  2. * Generic SSL/TLS messaging layer functions
  3. * (record layer + retransmission state machine)
  4. *
  5. * Copyright The Mbed TLS Contributors
  6. * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  7. */
  8. /*
  9. * http://www.ietf.org/rfc/rfc2246.txt
  10. * http://www.ietf.org/rfc/rfc4346.txt
  11. */
  12. #include "common.h"
  13. #if defined(MBEDTLS_SSL_TLS_C)
  14. #include "mbedtls/platform.h"
  15. #include "mbedtls/ssl.h"
  16. #include "ssl_misc.h"
  17. #include "debug_internal.h"
  18. #include "mbedtls/error.h"
  19. #include "mbedtls/platform_util.h"
  20. #include "mbedtls/version.h"
  21. #include "constant_time_internal.h"
  22. #include "mbedtls/constant_time.h"
  23. #include <string.h>
  24. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  25. #include "psa_util_internal.h"
  26. #include "psa/crypto.h"
  27. #endif
  28. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  29. #include "mbedtls/oid.h"
  30. #endif
  31. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  32. /* Define a local translating function to save code size by not using too many
  33. * arguments in each translating place. */
  34. static int local_err_translation(psa_status_t status)
  35. {
  36. return psa_status_to_mbedtls(status, psa_to_ssl_errors,
  37. ARRAY_LENGTH(psa_to_ssl_errors),
  38. psa_generic_status_to_mbedtls);
  39. }
  40. #define PSA_TO_MBEDTLS_ERR(status) local_err_translation(status)
  41. #endif
  42. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
  43. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  44. #if defined(PSA_WANT_ALG_SHA_384)
  45. #define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_384)
  46. #elif defined(PSA_WANT_ALG_SHA_256)
  47. #define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_256)
  48. #else /* See check_config.h */
  49. #define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_1)
  50. #endif
  51. MBEDTLS_STATIC_TESTABLE
  52. int mbedtls_ct_hmac(mbedtls_svc_key_id_t key,
  53. psa_algorithm_t mac_alg,
  54. const unsigned char *add_data,
  55. size_t add_data_len,
  56. const unsigned char *data,
  57. size_t data_len_secret,
  58. size_t min_data_len,
  59. size_t max_data_len,
  60. unsigned char *output)
  61. {
  62. /*
  63. * This function breaks the HMAC abstraction and uses psa_hash_clone()
  64. * extension in order to get constant-flow behaviour.
  65. *
  66. * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
  67. * concatenation, and okey/ikey are the XOR of the key with some fixed bit
  68. * patterns (see RFC 2104, sec. 2).
  69. *
  70. * We'll first compute ikey/okey, then inner_hash = HASH(ikey + msg) by
  71. * hashing up to minlen, then cloning the context, and for each byte up
  72. * to maxlen finishing up the hash computation, keeping only the
  73. * correct result.
  74. *
  75. * Then we only need to compute HASH(okey + inner_hash) and we're done.
  76. */
  77. psa_algorithm_t hash_alg = PSA_ALG_HMAC_GET_HASH(mac_alg);
  78. const size_t block_size = PSA_HASH_BLOCK_LENGTH(hash_alg);
  79. unsigned char key_buf[MAX_HASH_BLOCK_LENGTH];
  80. const size_t hash_size = PSA_HASH_LENGTH(hash_alg);
  81. psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
  82. size_t hash_length;
  83. unsigned char aux_out[PSA_HASH_MAX_SIZE];
  84. psa_hash_operation_t aux_operation = PSA_HASH_OPERATION_INIT;
  85. size_t offset;
  86. psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
  87. size_t mac_key_length;
  88. size_t i;
  89. #define PSA_CHK(func_call) \
  90. do { \
  91. status = (func_call); \
  92. if (status != PSA_SUCCESS) \
  93. goto cleanup; \
  94. } while (0)
  95. /* Export MAC key
  96. * We assume key length is always exactly the output size
  97. * which is never more than the block size, thus we use block_size
  98. * as the key buffer size.
  99. */
  100. PSA_CHK(psa_export_key(key, key_buf, block_size, &mac_key_length));
  101. /* Calculate ikey */
  102. for (i = 0; i < mac_key_length; i++) {
  103. key_buf[i] = (unsigned char) (key_buf[i] ^ 0x36);
  104. }
  105. for (; i < block_size; ++i) {
  106. key_buf[i] = 0x36;
  107. }
  108. PSA_CHK(psa_hash_setup(&operation, hash_alg));
  109. /* Now compute inner_hash = HASH(ikey + msg) */
  110. PSA_CHK(psa_hash_update(&operation, key_buf, block_size));
  111. PSA_CHK(psa_hash_update(&operation, add_data, add_data_len));
  112. PSA_CHK(psa_hash_update(&operation, data, min_data_len));
  113. /* Fill the hash buffer in advance with something that is
  114. * not a valid hash (barring an attack on the hash and
  115. * deliberately-crafted input), in case the caller doesn't
  116. * check the return status properly. */
  117. memset(output, '!', hash_size);
  118. /* For each possible length, compute the hash up to that point */
  119. for (offset = min_data_len; offset <= max_data_len; offset++) {
  120. PSA_CHK(psa_hash_clone(&operation, &aux_operation));
  121. PSA_CHK(psa_hash_finish(&aux_operation, aux_out,
  122. PSA_HASH_MAX_SIZE, &hash_length));
  123. /* Keep only the correct inner_hash in the output buffer */
  124. mbedtls_ct_memcpy_if(mbedtls_ct_uint_eq(offset, data_len_secret),
  125. output, aux_out, NULL, hash_size);
  126. if (offset < max_data_len) {
  127. PSA_CHK(psa_hash_update(&operation, data + offset, 1));
  128. }
  129. }
  130. /* Abort current operation to prepare for final operation */
  131. PSA_CHK(psa_hash_abort(&operation));
  132. /* Calculate okey */
  133. for (i = 0; i < mac_key_length; i++) {
  134. key_buf[i] = (unsigned char) ((key_buf[i] ^ 0x36) ^ 0x5C);
  135. }
  136. for (; i < block_size; ++i) {
  137. key_buf[i] = 0x5C;
  138. }
  139. /* Now compute HASH(okey + inner_hash) */
  140. PSA_CHK(psa_hash_setup(&operation, hash_alg));
  141. PSA_CHK(psa_hash_update(&operation, key_buf, block_size));
  142. PSA_CHK(psa_hash_update(&operation, output, hash_size));
  143. PSA_CHK(psa_hash_finish(&operation, output, hash_size, &hash_length));
  144. #undef PSA_CHK
  145. cleanup:
  146. mbedtls_platform_zeroize(key_buf, MAX_HASH_BLOCK_LENGTH);
  147. mbedtls_platform_zeroize(aux_out, PSA_HASH_MAX_SIZE);
  148. psa_hash_abort(&operation);
  149. psa_hash_abort(&aux_operation);
  150. return PSA_TO_MBEDTLS_ERR(status);
  151. }
  152. #undef MAX_HASH_BLOCK_LENGTH
  153. #else
  154. MBEDTLS_STATIC_TESTABLE
  155. int mbedtls_ct_hmac(mbedtls_md_context_t *ctx,
  156. const unsigned char *add_data,
  157. size_t add_data_len,
  158. const unsigned char *data,
  159. size_t data_len_secret,
  160. size_t min_data_len,
  161. size_t max_data_len,
  162. unsigned char *output)
  163. {
  164. /*
  165. * This function breaks the HMAC abstraction and uses the md_clone()
  166. * extension to the MD API in order to get constant-flow behaviour.
  167. *
  168. * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
  169. * concatenation, and okey/ikey are the XOR of the key with some fixed bit
  170. * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx.
  171. *
  172. * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to
  173. * minlen, then cloning the context, and for each byte up to maxlen
  174. * finishing up the hash computation, keeping only the correct result.
  175. *
  176. * Then we only need to compute HASH(okey + inner_hash) and we're done.
  177. */
  178. const mbedtls_md_type_t md_alg = mbedtls_md_get_type(ctx->md_info);
  179. /* TLS 1.2 only supports SHA-384, SHA-256, SHA-1, MD-5,
  180. * all of which have the same block size except SHA-384. */
  181. const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64;
  182. const unsigned char * const ikey = ctx->hmac_ctx;
  183. const unsigned char * const okey = ikey + block_size;
  184. const size_t hash_size = mbedtls_md_get_size(ctx->md_info);
  185. unsigned char aux_out[MBEDTLS_MD_MAX_SIZE];
  186. mbedtls_md_context_t aux;
  187. size_t offset;
  188. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  189. mbedtls_md_init(&aux);
  190. #define MD_CHK(func_call) \
  191. do { \
  192. ret = (func_call); \
  193. if (ret != 0) \
  194. goto cleanup; \
  195. } while (0)
  196. MD_CHK(mbedtls_md_setup(&aux, ctx->md_info, 0));
  197. /* After hmac_start() of hmac_reset(), ikey has already been hashed,
  198. * so we can start directly with the message */
  199. MD_CHK(mbedtls_md_update(ctx, add_data, add_data_len));
  200. MD_CHK(mbedtls_md_update(ctx, data, min_data_len));
  201. /* Fill the hash buffer in advance with something that is
  202. * not a valid hash (barring an attack on the hash and
  203. * deliberately-crafted input), in case the caller doesn't
  204. * check the return status properly. */
  205. memset(output, '!', hash_size);
  206. /* For each possible length, compute the hash up to that point */
  207. for (offset = min_data_len; offset <= max_data_len; offset++) {
  208. MD_CHK(mbedtls_md_clone(&aux, ctx));
  209. MD_CHK(mbedtls_md_finish(&aux, aux_out));
  210. /* Keep only the correct inner_hash in the output buffer */
  211. mbedtls_ct_memcpy_if(mbedtls_ct_uint_eq(offset, data_len_secret),
  212. output, aux_out, NULL, hash_size);
  213. if (offset < max_data_len) {
  214. MD_CHK(mbedtls_md_update(ctx, data + offset, 1));
  215. }
  216. }
  217. /* The context needs to finish() before it starts() again */
  218. MD_CHK(mbedtls_md_finish(ctx, aux_out));
  219. /* Now compute HASH(okey + inner_hash) */
  220. MD_CHK(mbedtls_md_starts(ctx));
  221. MD_CHK(mbedtls_md_update(ctx, okey, block_size));
  222. MD_CHK(mbedtls_md_update(ctx, output, hash_size));
  223. MD_CHK(mbedtls_md_finish(ctx, output));
  224. /* Done, get ready for next time */
  225. MD_CHK(mbedtls_md_hmac_reset(ctx));
  226. #undef MD_CHK
  227. cleanup:
  228. mbedtls_md_free(&aux);
  229. return ret;
  230. }
  231. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  232. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
  233. static uint32_t ssl_get_hs_total_len(mbedtls_ssl_context const *ssl);
  234. /*
  235. * Start a timer.
  236. * Passing millisecs = 0 cancels a running timer.
  237. */
  238. void mbedtls_ssl_set_timer(mbedtls_ssl_context *ssl, uint32_t millisecs)
  239. {
  240. if (ssl->f_set_timer == NULL) {
  241. return;
  242. }
  243. MBEDTLS_SSL_DEBUG_MSG(3, ("set_timer to %d ms", (int) millisecs));
  244. ssl->f_set_timer(ssl->p_timer, millisecs / 4, millisecs);
  245. }
  246. /*
  247. * Return -1 is timer is expired, 0 if it isn't.
  248. */
  249. int mbedtls_ssl_check_timer(mbedtls_ssl_context *ssl)
  250. {
  251. if (ssl->f_get_timer == NULL) {
  252. return 0;
  253. }
  254. if (ssl->f_get_timer(ssl->p_timer) == 2) {
  255. MBEDTLS_SSL_DEBUG_MSG(3, ("timer expired"));
  256. return -1;
  257. }
  258. return 0;
  259. }
  260. MBEDTLS_CHECK_RETURN_CRITICAL
  261. static int ssl_parse_record_header(mbedtls_ssl_context const *ssl,
  262. unsigned char *buf,
  263. size_t len,
  264. mbedtls_record *rec);
  265. int mbedtls_ssl_check_record(mbedtls_ssl_context const *ssl,
  266. unsigned char *buf,
  267. size_t buflen)
  268. {
  269. int ret = 0;
  270. MBEDTLS_SSL_DEBUG_MSG(1, ("=> mbedtls_ssl_check_record"));
  271. MBEDTLS_SSL_DEBUG_BUF(3, "record buffer", buf, buflen);
  272. /* We don't support record checking in TLS because
  273. * there doesn't seem to be a usecase for it.
  274. */
  275. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM) {
  276. ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
  277. goto exit;
  278. }
  279. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  280. else {
  281. mbedtls_record rec;
  282. ret = ssl_parse_record_header(ssl, buf, buflen, &rec);
  283. if (ret != 0) {
  284. MBEDTLS_SSL_DEBUG_RET(3, "ssl_parse_record_header", ret);
  285. goto exit;
  286. }
  287. if (ssl->transform_in != NULL) {
  288. ret = mbedtls_ssl_decrypt_buf(ssl, ssl->transform_in, &rec);
  289. if (ret != 0) {
  290. MBEDTLS_SSL_DEBUG_RET(3, "mbedtls_ssl_decrypt_buf", ret);
  291. goto exit;
  292. }
  293. }
  294. }
  295. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  296. exit:
  297. /* On success, we have decrypted the buffer in-place, so make
  298. * sure we don't leak any plaintext data. */
  299. mbedtls_platform_zeroize(buf, buflen);
  300. /* For the purpose of this API, treat messages with unexpected CID
  301. * as well as such from future epochs as unexpected. */
  302. if (ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID ||
  303. ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE) {
  304. ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
  305. }
  306. MBEDTLS_SSL_DEBUG_MSG(1, ("<= mbedtls_ssl_check_record"));
  307. return ret;
  308. }
  309. #define SSL_DONT_FORCE_FLUSH 0
  310. #define SSL_FORCE_FLUSH 1
  311. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  312. /* Forward declarations for functions related to message buffering. */
  313. static void ssl_buffering_free_slot(mbedtls_ssl_context *ssl,
  314. uint8_t slot);
  315. static void ssl_free_buffered_record(mbedtls_ssl_context *ssl);
  316. MBEDTLS_CHECK_RETURN_CRITICAL
  317. static int ssl_load_buffered_message(mbedtls_ssl_context *ssl);
  318. MBEDTLS_CHECK_RETURN_CRITICAL
  319. static int ssl_load_buffered_record(mbedtls_ssl_context *ssl);
  320. MBEDTLS_CHECK_RETURN_CRITICAL
  321. static int ssl_buffer_message(mbedtls_ssl_context *ssl);
  322. MBEDTLS_CHECK_RETURN_CRITICAL
  323. static int ssl_buffer_future_record(mbedtls_ssl_context *ssl,
  324. mbedtls_record const *rec);
  325. MBEDTLS_CHECK_RETURN_CRITICAL
  326. static int ssl_next_record_is_in_datagram(mbedtls_ssl_context *ssl);
  327. static size_t ssl_get_maximum_datagram_size(mbedtls_ssl_context const *ssl)
  328. {
  329. size_t mtu = mbedtls_ssl_get_current_mtu(ssl);
  330. #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
  331. size_t out_buf_len = ssl->out_buf_len;
  332. #else
  333. size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
  334. #endif
  335. if (mtu != 0 && mtu < out_buf_len) {
  336. return mtu;
  337. }
  338. return out_buf_len;
  339. }
  340. MBEDTLS_CHECK_RETURN_CRITICAL
  341. static int ssl_get_remaining_space_in_datagram(mbedtls_ssl_context const *ssl)
  342. {
  343. size_t const bytes_written = ssl->out_left;
  344. size_t const mtu = ssl_get_maximum_datagram_size(ssl);
  345. /* Double-check that the write-index hasn't gone
  346. * past what we can transmit in a single datagram. */
  347. if (bytes_written > mtu) {
  348. /* Should never happen... */
  349. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  350. }
  351. return (int) (mtu - bytes_written);
  352. }
  353. MBEDTLS_CHECK_RETURN_CRITICAL
  354. static int ssl_get_remaining_payload_in_datagram(mbedtls_ssl_context const *ssl)
  355. {
  356. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  357. size_t remaining, expansion;
  358. size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
  359. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  360. const size_t mfl = mbedtls_ssl_get_output_max_frag_len(ssl);
  361. if (max_len > mfl) {
  362. max_len = mfl;
  363. }
  364. /* By the standard (RFC 6066 Sect. 4), the MFL extension
  365. * only limits the maximum record payload size, so in theory
  366. * we would be allowed to pack multiple records of payload size
  367. * MFL into a single datagram. However, this would mean that there's
  368. * no way to explicitly communicate MTU restrictions to the peer.
  369. *
  370. * The following reduction of max_len makes sure that we never
  371. * write datagrams larger than MFL + Record Expansion Overhead.
  372. */
  373. if (max_len <= ssl->out_left) {
  374. return 0;
  375. }
  376. max_len -= ssl->out_left;
  377. #endif
  378. ret = ssl_get_remaining_space_in_datagram(ssl);
  379. if (ret < 0) {
  380. return ret;
  381. }
  382. remaining = (size_t) ret;
  383. ret = mbedtls_ssl_get_record_expansion(ssl);
  384. if (ret < 0) {
  385. return ret;
  386. }
  387. expansion = (size_t) ret;
  388. if (remaining <= expansion) {
  389. return 0;
  390. }
  391. remaining -= expansion;
  392. if (remaining >= max_len) {
  393. remaining = max_len;
  394. }
  395. return (int) remaining;
  396. }
  397. /*
  398. * Double the retransmit timeout value, within the allowed range,
  399. * returning -1 if the maximum value has already been reached.
  400. */
  401. MBEDTLS_CHECK_RETURN_CRITICAL
  402. static int ssl_double_retransmit_timeout(mbedtls_ssl_context *ssl)
  403. {
  404. uint32_t new_timeout;
  405. if (ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max) {
  406. return -1;
  407. }
  408. /* Implement the final paragraph of RFC 6347 section 4.1.1.1
  409. * in the following way: after the initial transmission and a first
  410. * retransmission, back off to a temporary estimated MTU of 508 bytes.
  411. * This value is guaranteed to be deliverable (if not guaranteed to be
  412. * delivered) of any compliant IPv4 (and IPv6) network, and should work
  413. * on most non-IP stacks too. */
  414. if (ssl->handshake->retransmit_timeout != ssl->conf->hs_timeout_min) {
  415. ssl->handshake->mtu = 508;
  416. MBEDTLS_SSL_DEBUG_MSG(2, ("mtu autoreduction to %d bytes", ssl->handshake->mtu));
  417. }
  418. new_timeout = 2 * ssl->handshake->retransmit_timeout;
  419. /* Avoid arithmetic overflow and range overflow */
  420. if (new_timeout < ssl->handshake->retransmit_timeout ||
  421. new_timeout > ssl->conf->hs_timeout_max) {
  422. new_timeout = ssl->conf->hs_timeout_max;
  423. }
  424. ssl->handshake->retransmit_timeout = new_timeout;
  425. MBEDTLS_SSL_DEBUG_MSG(3, ("update timeout value to %lu millisecs",
  426. (unsigned long) ssl->handshake->retransmit_timeout));
  427. return 0;
  428. }
  429. static void ssl_reset_retransmit_timeout(mbedtls_ssl_context *ssl)
  430. {
  431. ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min;
  432. MBEDTLS_SSL_DEBUG_MSG(3, ("update timeout value to %lu millisecs",
  433. (unsigned long) ssl->handshake->retransmit_timeout));
  434. }
  435. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  436. /*
  437. * Encryption/decryption functions
  438. */
  439. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
  440. static size_t ssl_compute_padding_length(size_t len,
  441. size_t granularity)
  442. {
  443. return (granularity - (len + 1) % granularity) % granularity;
  444. }
  445. /* This functions transforms a (D)TLS plaintext fragment and a record content
  446. * type into an instance of the (D)TLSInnerPlaintext structure. This is used
  447. * in DTLS 1.2 + CID and within TLS 1.3 to allow flexible padding and to protect
  448. * a record's content type.
  449. *
  450. * struct {
  451. * opaque content[DTLSPlaintext.length];
  452. * ContentType real_type;
  453. * uint8 zeros[length_of_padding];
  454. * } (D)TLSInnerPlaintext;
  455. *
  456. * Input:
  457. * - `content`: The beginning of the buffer holding the
  458. * plaintext to be wrapped.
  459. * - `*content_size`: The length of the plaintext in Bytes.
  460. * - `max_len`: The number of Bytes available starting from
  461. * `content`. This must be `>= *content_size`.
  462. * - `rec_type`: The desired record content type.
  463. *
  464. * Output:
  465. * - `content`: The beginning of the resulting (D)TLSInnerPlaintext structure.
  466. * - `*content_size`: The length of the resulting (D)TLSInnerPlaintext structure.
  467. *
  468. * Returns:
  469. * - `0` on success.
  470. * - A negative error code if `max_len` didn't offer enough space
  471. * for the expansion.
  472. */
  473. MBEDTLS_CHECK_RETURN_CRITICAL
  474. static int ssl_build_inner_plaintext(unsigned char *content,
  475. size_t *content_size,
  476. size_t remaining,
  477. uint8_t rec_type,
  478. size_t pad)
  479. {
  480. size_t len = *content_size;
  481. /* Write real content type */
  482. if (remaining == 0) {
  483. return -1;
  484. }
  485. content[len] = rec_type;
  486. len++;
  487. remaining--;
  488. if (remaining < pad) {
  489. return -1;
  490. }
  491. memset(content + len, 0, pad);
  492. len += pad;
  493. remaining -= pad;
  494. *content_size = len;
  495. return 0;
  496. }
  497. /* This function parses a (D)TLSInnerPlaintext structure.
  498. * See ssl_build_inner_plaintext() for details. */
  499. MBEDTLS_CHECK_RETURN_CRITICAL
  500. static int ssl_parse_inner_plaintext(unsigned char const *content,
  501. size_t *content_size,
  502. uint8_t *rec_type)
  503. {
  504. size_t remaining = *content_size;
  505. /* Determine length of padding by skipping zeroes from the back. */
  506. do {
  507. if (remaining == 0) {
  508. return -1;
  509. }
  510. remaining--;
  511. } while (content[remaining] == 0);
  512. *content_size = remaining;
  513. *rec_type = content[remaining];
  514. return 0;
  515. }
  516. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID || MBEDTLS_SSL_PROTO_TLS1_3 */
  517. /* The size of the `add_data` structure depends on various
  518. * factors, namely
  519. *
  520. * 1) CID functionality disabled
  521. *
  522. * additional_data =
  523. * 8: seq_num +
  524. * 1: type +
  525. * 2: version +
  526. * 2: length of inner plaintext +
  527. *
  528. * size = 13 bytes
  529. *
  530. * 2) CID functionality based on RFC 9146 enabled
  531. *
  532. * size = 8 + 1 + 1 + 1 + 2 + 2 + 6 + 2 + CID-length
  533. * = 23 + CID-length
  534. *
  535. * 3) CID functionality based on legacy CID version
  536. according to draft-ietf-tls-dtls-connection-id-05
  537. * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05
  538. *
  539. * size = 13 + 1 + CID-length
  540. *
  541. * More information about the CID usage:
  542. *
  543. * Per Section 5.3 of draft-ietf-tls-dtls-connection-id-05 the
  544. * size of the additional data structure is calculated as:
  545. *
  546. * additional_data =
  547. * 8: seq_num +
  548. * 1: tls12_cid +
  549. * 2: DTLSCipherText.version +
  550. * n: cid +
  551. * 1: cid_length +
  552. * 2: length_of_DTLSInnerPlaintext
  553. *
  554. * Per RFC 9146 the size of the add_data structure is calculated as:
  555. *
  556. * additional_data =
  557. * 8: seq_num_placeholder +
  558. * 1: tls12_cid +
  559. * 1: cid_length +
  560. * 1: tls12_cid +
  561. * 2: DTLSCiphertext.version +
  562. * 2: epoch +
  563. * 6: sequence_number +
  564. * n: cid +
  565. * 2: length_of_DTLSInnerPlaintext
  566. *
  567. */
  568. static void ssl_extract_add_data_from_record(unsigned char *add_data,
  569. size_t *add_data_len,
  570. mbedtls_record *rec,
  571. mbedtls_ssl_protocol_version
  572. tls_version,
  573. size_t taglen)
  574. {
  575. /* Several types of ciphers have been defined for use with TLS and DTLS,
  576. * and the MAC calculations for those ciphers differ slightly. Further
  577. * variants were added when the CID functionality was added with RFC 9146.
  578. * This implementations also considers the use of a legacy version of the
  579. * CID specification published in draft-ietf-tls-dtls-connection-id-05,
  580. * which is used in deployments.
  581. *
  582. * We will distinguish between the non-CID and the CID cases below.
  583. *
  584. * --- Non-CID cases ---
  585. *
  586. * Quoting RFC 5246 (TLS 1.2):
  587. *
  588. * additional_data = seq_num + TLSCompressed.type +
  589. * TLSCompressed.version + TLSCompressed.length;
  590. *
  591. * For TLS 1.3, the record sequence number is dropped from the AAD
  592. * and encoded within the nonce of the AEAD operation instead.
  593. * Moreover, the additional data involves the length of the TLS
  594. * ciphertext, not the TLS plaintext as in earlier versions.
  595. * Quoting RFC 8446 (TLS 1.3):
  596. *
  597. * additional_data = TLSCiphertext.opaque_type ||
  598. * TLSCiphertext.legacy_record_version ||
  599. * TLSCiphertext.length
  600. *
  601. * We pass the tag length to this function in order to compute the
  602. * ciphertext length from the inner plaintext length rec->data_len via
  603. *
  604. * TLSCiphertext.length = TLSInnerPlaintext.length + taglen.
  605. *
  606. * --- CID cases ---
  607. *
  608. * RFC 9146 uses a common pattern when constructing the data
  609. * passed into a MAC / AEAD cipher.
  610. *
  611. * Data concatenation for MACs used with block ciphers with
  612. * Encrypt-then-MAC Processing (with CID):
  613. *
  614. * data = seq_num_placeholder +
  615. * tls12_cid +
  616. * cid_length +
  617. * tls12_cid +
  618. * DTLSCiphertext.version +
  619. * epoch +
  620. * sequence_number +
  621. * cid +
  622. * DTLSCiphertext.length +
  623. * IV +
  624. * ENC(content + padding + padding_length)
  625. *
  626. * Data concatenation for MACs used with block ciphers (with CID):
  627. *
  628. * data = seq_num_placeholder +
  629. * tls12_cid +
  630. * cid_length +
  631. * tls12_cid +
  632. * DTLSCiphertext.version +
  633. * epoch +
  634. * sequence_number +
  635. * cid +
  636. * length_of_DTLSInnerPlaintext +
  637. * DTLSInnerPlaintext.content +
  638. * DTLSInnerPlaintext.real_type +
  639. * DTLSInnerPlaintext.zeros
  640. *
  641. * AEAD ciphers use the following additional data calculation (with CIDs):
  642. *
  643. * additional_data = seq_num_placeholder +
  644. * tls12_cid +
  645. * cid_length +
  646. * tls12_cid +
  647. * DTLSCiphertext.version +
  648. * epoch +
  649. * sequence_number +
  650. * cid +
  651. * length_of_DTLSInnerPlaintext
  652. *
  653. * Section 5.3 of draft-ietf-tls-dtls-connection-id-05 (for legacy CID use)
  654. * defines the additional data calculation as follows:
  655. *
  656. * additional_data = seq_num +
  657. * tls12_cid +
  658. * DTLSCipherText.version +
  659. * cid +
  660. * cid_length +
  661. * length_of_DTLSInnerPlaintext
  662. */
  663. unsigned char *cur = add_data;
  664. size_t ad_len_field = rec->data_len;
  665. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
  666. MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT == 0
  667. const unsigned char seq_num_placeholder[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
  668. #endif
  669. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  670. if (tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
  671. /* In TLS 1.3, the AAD contains the length of the TLSCiphertext,
  672. * which differs from the length of the TLSInnerPlaintext
  673. * by the length of the authentication tag. */
  674. ad_len_field += taglen;
  675. } else
  676. #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
  677. {
  678. ((void) tls_version);
  679. ((void) taglen);
  680. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
  681. MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT == 0
  682. if (rec->cid_len != 0) {
  683. // seq_num_placeholder
  684. memcpy(cur, seq_num_placeholder, sizeof(seq_num_placeholder));
  685. cur += sizeof(seq_num_placeholder);
  686. // tls12_cid type
  687. *cur = rec->type;
  688. cur++;
  689. // cid_length
  690. *cur = rec->cid_len;
  691. cur++;
  692. } else
  693. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  694. {
  695. // epoch + sequence number
  696. memcpy(cur, rec->ctr, sizeof(rec->ctr));
  697. cur += sizeof(rec->ctr);
  698. }
  699. }
  700. // type
  701. *cur = rec->type;
  702. cur++;
  703. // version
  704. memcpy(cur, rec->ver, sizeof(rec->ver));
  705. cur += sizeof(rec->ver);
  706. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
  707. MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT == 1
  708. if (rec->cid_len != 0) {
  709. // CID
  710. memcpy(cur, rec->cid, rec->cid_len);
  711. cur += rec->cid_len;
  712. // cid_length
  713. *cur = rec->cid_len;
  714. cur++;
  715. // length of inner plaintext
  716. MBEDTLS_PUT_UINT16_BE(ad_len_field, cur, 0);
  717. cur += 2;
  718. } else
  719. #elif defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
  720. MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT == 0
  721. if (rec->cid_len != 0) {
  722. // epoch + sequence number
  723. memcpy(cur, rec->ctr, sizeof(rec->ctr));
  724. cur += sizeof(rec->ctr);
  725. // CID
  726. memcpy(cur, rec->cid, rec->cid_len);
  727. cur += rec->cid_len;
  728. // length of inner plaintext
  729. MBEDTLS_PUT_UINT16_BE(ad_len_field, cur, 0);
  730. cur += 2;
  731. } else
  732. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  733. {
  734. MBEDTLS_PUT_UINT16_BE(ad_len_field, cur, 0);
  735. cur += 2;
  736. }
  737. *add_data_len = (size_t) (cur - add_data);
  738. }
  739. #if defined(MBEDTLS_SSL_HAVE_AEAD)
  740. MBEDTLS_CHECK_RETURN_CRITICAL
  741. static int ssl_transform_aead_dynamic_iv_is_explicit(
  742. mbedtls_ssl_transform const *transform)
  743. {
  744. return transform->ivlen != transform->fixed_ivlen;
  745. }
  746. /* Compute IV := ( fixed_iv || 0 ) XOR ( 0 || dynamic_IV )
  747. *
  748. * Concretely, this occurs in two variants:
  749. *
  750. * a) Fixed and dynamic IV lengths add up to total IV length, giving
  751. * IV = fixed_iv || dynamic_iv
  752. *
  753. * This variant is used in TLS 1.2 when used with GCM or CCM.
  754. *
  755. * b) Fixed IV lengths matches total IV length, giving
  756. * IV = fixed_iv XOR ( 0 || dynamic_iv )
  757. *
  758. * This variant occurs in TLS 1.3 and for TLS 1.2 when using ChaChaPoly.
  759. *
  760. * See also the documentation of mbedtls_ssl_transform.
  761. *
  762. * This function has the precondition that
  763. *
  764. * dst_iv_len >= max( fixed_iv_len, dynamic_iv_len )
  765. *
  766. * which has to be ensured by the caller. If this precondition
  767. * violated, the behavior of this function is undefined.
  768. */
  769. static void ssl_build_record_nonce(unsigned char *dst_iv,
  770. size_t dst_iv_len,
  771. unsigned char const *fixed_iv,
  772. size_t fixed_iv_len,
  773. unsigned char const *dynamic_iv,
  774. size_t dynamic_iv_len)
  775. {
  776. /* Start with Fixed IV || 0 */
  777. memset(dst_iv, 0, dst_iv_len);
  778. memcpy(dst_iv, fixed_iv, fixed_iv_len);
  779. dst_iv += dst_iv_len - dynamic_iv_len;
  780. mbedtls_xor(dst_iv, dst_iv, dynamic_iv, dynamic_iv_len);
  781. }
  782. #endif /* MBEDTLS_SSL_HAVE_AEAD */
  783. int mbedtls_ssl_encrypt_buf(mbedtls_ssl_context *ssl,
  784. mbedtls_ssl_transform *transform,
  785. mbedtls_record *rec,
  786. int (*f_rng)(void *, unsigned char *, size_t),
  787. void *p_rng)
  788. {
  789. mbedtls_ssl_mode_t ssl_mode;
  790. int auth_done = 0;
  791. unsigned char *data;
  792. /* For an explanation of the additional data length see
  793. * the description of ssl_extract_add_data_from_record().
  794. */
  795. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  796. unsigned char add_data[23 + MBEDTLS_SSL_CID_OUT_LEN_MAX];
  797. #else
  798. unsigned char add_data[13];
  799. #endif
  800. size_t add_data_len;
  801. size_t post_avail;
  802. /* The SSL context is only used for debugging purposes! */
  803. #if !defined(MBEDTLS_DEBUG_C)
  804. ssl = NULL; /* make sure we don't use it except for debug */
  805. ((void) ssl);
  806. #endif
  807. /* The PRNG is used for dynamic IV generation that's used
  808. * for CBC transformations in TLS 1.2. */
  809. #if !(defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) && \
  810. defined(MBEDTLS_SSL_PROTO_TLS1_2))
  811. ((void) f_rng);
  812. ((void) p_rng);
  813. #endif
  814. MBEDTLS_SSL_DEBUG_MSG(2, ("=> encrypt buf"));
  815. if (transform == NULL) {
  816. MBEDTLS_SSL_DEBUG_MSG(1, ("no transform provided to encrypt_buf"));
  817. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  818. }
  819. if (rec == NULL
  820. || rec->buf == NULL
  821. || rec->buf_len < rec->data_offset
  822. || rec->buf_len - rec->data_offset < rec->data_len
  823. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  824. || rec->cid_len != 0
  825. #endif
  826. ) {
  827. MBEDTLS_SSL_DEBUG_MSG(1, ("bad record structure provided to encrypt_buf"));
  828. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  829. }
  830. ssl_mode = mbedtls_ssl_get_mode_from_transform(transform);
  831. data = rec->buf + rec->data_offset;
  832. post_avail = rec->buf_len - (rec->data_len + rec->data_offset);
  833. MBEDTLS_SSL_DEBUG_BUF(4, "before encrypt: output payload",
  834. data, rec->data_len);
  835. if (rec->data_len > MBEDTLS_SSL_OUT_CONTENT_LEN) {
  836. MBEDTLS_SSL_DEBUG_MSG(1, ("Record content %" MBEDTLS_PRINTF_SIZET
  837. " too large, maximum %" MBEDTLS_PRINTF_SIZET,
  838. rec->data_len,
  839. (size_t) MBEDTLS_SSL_OUT_CONTENT_LEN));
  840. return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
  841. }
  842. /* The following two code paths implement the (D)TLSInnerPlaintext
  843. * structure present in TLS 1.3 and DTLS 1.2 + CID.
  844. *
  845. * See ssl_build_inner_plaintext() for more information.
  846. *
  847. * Note that this changes `rec->data_len`, and hence
  848. * `post_avail` needs to be recalculated afterwards.
  849. *
  850. * Note also that the two code paths cannot occur simultaneously
  851. * since they apply to different versions of the protocol. There
  852. * is hence no risk of double-addition of the inner plaintext.
  853. */
  854. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  855. if (transform->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
  856. size_t padding =
  857. ssl_compute_padding_length(rec->data_len,
  858. MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY);
  859. if (ssl_build_inner_plaintext(data,
  860. &rec->data_len,
  861. post_avail,
  862. rec->type,
  863. padding) != 0) {
  864. return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
  865. }
  866. rec->type = MBEDTLS_SSL_MSG_APPLICATION_DATA;
  867. }
  868. #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
  869. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  870. /*
  871. * Add CID information
  872. */
  873. rec->cid_len = transform->out_cid_len;
  874. memcpy(rec->cid, transform->out_cid, transform->out_cid_len);
  875. MBEDTLS_SSL_DEBUG_BUF(3, "CID", rec->cid, rec->cid_len);
  876. if (rec->cid_len != 0) {
  877. size_t padding =
  878. ssl_compute_padding_length(rec->data_len,
  879. MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY);
  880. /*
  881. * Wrap plaintext into DTLSInnerPlaintext structure.
  882. * See ssl_build_inner_plaintext() for more information.
  883. *
  884. * Note that this changes `rec->data_len`, and hence
  885. * `post_avail` needs to be recalculated afterwards.
  886. */
  887. if (ssl_build_inner_plaintext(data,
  888. &rec->data_len,
  889. post_avail,
  890. rec->type,
  891. padding) != 0) {
  892. return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
  893. }
  894. rec->type = MBEDTLS_SSL_MSG_CID;
  895. }
  896. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  897. post_avail = rec->buf_len - (rec->data_len + rec->data_offset);
  898. /*
  899. * Add MAC before if needed
  900. */
  901. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
  902. if (ssl_mode == MBEDTLS_SSL_MODE_STREAM ||
  903. ssl_mode == MBEDTLS_SSL_MODE_CBC) {
  904. if (post_avail < transform->maclen) {
  905. MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
  906. return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
  907. }
  908. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  909. unsigned char mac[MBEDTLS_SSL_MAC_ADD];
  910. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  911. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  912. psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
  913. psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
  914. size_t sign_mac_length = 0;
  915. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  916. ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
  917. transform->tls_version,
  918. transform->taglen);
  919. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  920. status = psa_mac_sign_setup(&operation, transform->psa_mac_enc,
  921. transform->psa_mac_alg);
  922. if (status != PSA_SUCCESS) {
  923. goto hmac_failed_etm_disabled;
  924. }
  925. status = psa_mac_update(&operation, add_data, add_data_len);
  926. if (status != PSA_SUCCESS) {
  927. goto hmac_failed_etm_disabled;
  928. }
  929. status = psa_mac_update(&operation, data, rec->data_len);
  930. if (status != PSA_SUCCESS) {
  931. goto hmac_failed_etm_disabled;
  932. }
  933. status = psa_mac_sign_finish(&operation, mac, MBEDTLS_SSL_MAC_ADD,
  934. &sign_mac_length);
  935. if (status != PSA_SUCCESS) {
  936. goto hmac_failed_etm_disabled;
  937. }
  938. #else
  939. ret = mbedtls_md_hmac_update(&transform->md_ctx_enc, add_data,
  940. add_data_len);
  941. if (ret != 0) {
  942. goto hmac_failed_etm_disabled;
  943. }
  944. ret = mbedtls_md_hmac_update(&transform->md_ctx_enc, data, rec->data_len);
  945. if (ret != 0) {
  946. goto hmac_failed_etm_disabled;
  947. }
  948. ret = mbedtls_md_hmac_finish(&transform->md_ctx_enc, mac);
  949. if (ret != 0) {
  950. goto hmac_failed_etm_disabled;
  951. }
  952. ret = mbedtls_md_hmac_reset(&transform->md_ctx_enc);
  953. if (ret != 0) {
  954. goto hmac_failed_etm_disabled;
  955. }
  956. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  957. memcpy(data + rec->data_len, mac, transform->maclen);
  958. #endif
  959. MBEDTLS_SSL_DEBUG_BUF(4, "computed mac", data + rec->data_len,
  960. transform->maclen);
  961. rec->data_len += transform->maclen;
  962. post_avail -= transform->maclen;
  963. auth_done++;
  964. hmac_failed_etm_disabled:
  965. mbedtls_platform_zeroize(mac, transform->maclen);
  966. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  967. ret = PSA_TO_MBEDTLS_ERR(status);
  968. status = psa_mac_abort(&operation);
  969. if (ret == 0 && status != PSA_SUCCESS) {
  970. ret = PSA_TO_MBEDTLS_ERR(status);
  971. }
  972. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  973. if (ret != 0) {
  974. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_md_hmac_xxx", ret);
  975. return ret;
  976. }
  977. }
  978. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
  979. /*
  980. * Encrypt
  981. */
  982. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_STREAM)
  983. if (ssl_mode == MBEDTLS_SSL_MODE_STREAM) {
  984. MBEDTLS_SSL_DEBUG_MSG(3, ("before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", "
  985. "including %d bytes of padding",
  986. rec->data_len, 0));
  987. /* The only supported stream cipher is "NULL",
  988. * so there's nothing to do here.*/
  989. } else
  990. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_STREAM */
  991. #if defined(MBEDTLS_SSL_HAVE_AEAD)
  992. if (ssl_mode == MBEDTLS_SSL_MODE_AEAD) {
  993. unsigned char iv[12];
  994. unsigned char *dynamic_iv;
  995. size_t dynamic_iv_len;
  996. int dynamic_iv_is_explicit =
  997. ssl_transform_aead_dynamic_iv_is_explicit(transform);
  998. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  999. psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
  1000. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1001. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1002. /* Check that there's space for the authentication tag. */
  1003. if (post_avail < transform->taglen) {
  1004. MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
  1005. return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
  1006. }
  1007. /*
  1008. * Build nonce for AEAD encryption.
  1009. *
  1010. * Note: In the case of CCM and GCM in TLS 1.2, the dynamic
  1011. * part of the IV is prepended to the ciphertext and
  1012. * can be chosen freely - in particular, it need not
  1013. * agree with the record sequence number.
  1014. * However, since ChaChaPoly as well as all AEAD modes
  1015. * in TLS 1.3 use the record sequence number as the
  1016. * dynamic part of the nonce, we uniformly use the
  1017. * record sequence number here in all cases.
  1018. */
  1019. dynamic_iv = rec->ctr;
  1020. dynamic_iv_len = sizeof(rec->ctr);
  1021. ssl_build_record_nonce(iv, sizeof(iv),
  1022. transform->iv_enc,
  1023. transform->fixed_ivlen,
  1024. dynamic_iv,
  1025. dynamic_iv_len);
  1026. /*
  1027. * Build additional data for AEAD encryption.
  1028. * This depends on the TLS version.
  1029. */
  1030. ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
  1031. transform->tls_version,
  1032. transform->taglen);
  1033. MBEDTLS_SSL_DEBUG_BUF(4, "IV used (internal)",
  1034. iv, transform->ivlen);
  1035. MBEDTLS_SSL_DEBUG_BUF(4, "IV used (transmitted)",
  1036. dynamic_iv,
  1037. dynamic_iv_is_explicit ? dynamic_iv_len : 0);
  1038. MBEDTLS_SSL_DEBUG_BUF(4, "additional data used for AEAD",
  1039. add_data, add_data_len);
  1040. MBEDTLS_SSL_DEBUG_MSG(3, ("before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", "
  1041. "including 0 bytes of padding",
  1042. rec->data_len));
  1043. /*
  1044. * Encrypt and authenticate
  1045. */
  1046. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1047. status = psa_aead_encrypt(transform->psa_key_enc,
  1048. transform->psa_alg,
  1049. iv, transform->ivlen,
  1050. add_data, add_data_len,
  1051. data, rec->data_len,
  1052. data, rec->buf_len - (data - rec->buf),
  1053. &rec->data_len);
  1054. if (status != PSA_SUCCESS) {
  1055. ret = PSA_TO_MBEDTLS_ERR(status);
  1056. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_encrypt_buf", ret);
  1057. return ret;
  1058. }
  1059. #else
  1060. if ((ret = mbedtls_cipher_auth_encrypt_ext(&transform->cipher_ctx_enc,
  1061. iv, transform->ivlen,
  1062. add_data, add_data_len,
  1063. data, rec->data_len, /* src */
  1064. data, rec->buf_len - (size_t) (data - rec->buf), /* dst */
  1065. &rec->data_len,
  1066. transform->taglen)) != 0) {
  1067. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_auth_encrypt_ext", ret);
  1068. return ret;
  1069. }
  1070. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1071. MBEDTLS_SSL_DEBUG_BUF(4, "after encrypt: tag",
  1072. data + rec->data_len - transform->taglen,
  1073. transform->taglen);
  1074. /* Account for authentication tag. */
  1075. post_avail -= transform->taglen;
  1076. /*
  1077. * Prefix record content with dynamic IV in case it is explicit.
  1078. */
  1079. if (dynamic_iv_is_explicit != 0) {
  1080. if (rec->data_offset < dynamic_iv_len) {
  1081. MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
  1082. return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
  1083. }
  1084. memcpy(data - dynamic_iv_len, dynamic_iv, dynamic_iv_len);
  1085. rec->data_offset -= dynamic_iv_len;
  1086. rec->data_len += dynamic_iv_len;
  1087. }
  1088. auth_done++;
  1089. } else
  1090. #endif /* MBEDTLS_SSL_HAVE_AEAD */
  1091. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
  1092. if (ssl_mode == MBEDTLS_SSL_MODE_CBC ||
  1093. ssl_mode == MBEDTLS_SSL_MODE_CBC_ETM) {
  1094. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1095. size_t padlen, i;
  1096. size_t olen;
  1097. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1098. psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
  1099. size_t part_len;
  1100. psa_cipher_operation_t cipher_op = PSA_CIPHER_OPERATION_INIT;
  1101. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1102. /* Currently we're always using minimal padding
  1103. * (up to 255 bytes would be allowed). */
  1104. padlen = transform->ivlen - (rec->data_len + 1) % transform->ivlen;
  1105. if (padlen == transform->ivlen) {
  1106. padlen = 0;
  1107. }
  1108. /* Check there's enough space in the buffer for the padding. */
  1109. if (post_avail < padlen + 1) {
  1110. MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
  1111. return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
  1112. }
  1113. for (i = 0; i <= padlen; i++) {
  1114. data[rec->data_len + i] = (unsigned char) padlen;
  1115. }
  1116. rec->data_len += padlen + 1;
  1117. post_avail -= padlen + 1;
  1118. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1119. /*
  1120. * Prepend per-record IV for block cipher in TLS v1.2 as per
  1121. * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
  1122. */
  1123. if (f_rng == NULL) {
  1124. MBEDTLS_SSL_DEBUG_MSG(1, ("No PRNG provided to encrypt_record routine"));
  1125. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  1126. }
  1127. if (rec->data_offset < transform->ivlen) {
  1128. MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
  1129. return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
  1130. }
  1131. /*
  1132. * Generate IV
  1133. */
  1134. ret = f_rng(p_rng, transform->iv_enc, transform->ivlen);
  1135. if (ret != 0) {
  1136. return ret;
  1137. }
  1138. memcpy(data - transform->ivlen, transform->iv_enc, transform->ivlen);
  1139. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  1140. MBEDTLS_SSL_DEBUG_MSG(3, ("before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", "
  1141. "including %"
  1142. MBEDTLS_PRINTF_SIZET
  1143. " bytes of IV and %" MBEDTLS_PRINTF_SIZET " bytes of padding",
  1144. rec->data_len, transform->ivlen,
  1145. padlen + 1));
  1146. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1147. status = psa_cipher_encrypt_setup(&cipher_op,
  1148. transform->psa_key_enc, transform->psa_alg);
  1149. if (status != PSA_SUCCESS) {
  1150. ret = PSA_TO_MBEDTLS_ERR(status);
  1151. MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_encrypt_setup", ret);
  1152. return ret;
  1153. }
  1154. status = psa_cipher_set_iv(&cipher_op, transform->iv_enc, transform->ivlen);
  1155. if (status != PSA_SUCCESS) {
  1156. ret = PSA_TO_MBEDTLS_ERR(status);
  1157. MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_set_iv", ret);
  1158. return ret;
  1159. }
  1160. status = psa_cipher_update(&cipher_op,
  1161. data, rec->data_len,
  1162. data, rec->data_len, &olen);
  1163. if (status != PSA_SUCCESS) {
  1164. ret = PSA_TO_MBEDTLS_ERR(status);
  1165. MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_update", ret);
  1166. return ret;
  1167. }
  1168. status = psa_cipher_finish(&cipher_op,
  1169. data + olen, rec->data_len - olen,
  1170. &part_len);
  1171. if (status != PSA_SUCCESS) {
  1172. ret = PSA_TO_MBEDTLS_ERR(status);
  1173. MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_finish", ret);
  1174. return ret;
  1175. }
  1176. olen += part_len;
  1177. #else
  1178. if ((ret = mbedtls_cipher_crypt(&transform->cipher_ctx_enc,
  1179. transform->iv_enc,
  1180. transform->ivlen,
  1181. data, rec->data_len,
  1182. data, &olen)) != 0) {
  1183. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_crypt", ret);
  1184. return ret;
  1185. }
  1186. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1187. if (rec->data_len != olen) {
  1188. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  1189. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  1190. }
  1191. data -= transform->ivlen;
  1192. rec->data_offset -= transform->ivlen;
  1193. rec->data_len += transform->ivlen;
  1194. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  1195. if (auth_done == 0) {
  1196. unsigned char mac[MBEDTLS_SSL_MAC_ADD];
  1197. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1198. psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
  1199. size_t sign_mac_length = 0;
  1200. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1201. /* MAC(MAC_write_key, add_data, IV, ENC(content + padding + padding_length))
  1202. */
  1203. if (post_avail < transform->maclen) {
  1204. MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
  1205. return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
  1206. }
  1207. ssl_extract_add_data_from_record(add_data, &add_data_len,
  1208. rec, transform->tls_version,
  1209. transform->taglen);
  1210. MBEDTLS_SSL_DEBUG_MSG(3, ("using encrypt then mac"));
  1211. MBEDTLS_SSL_DEBUG_BUF(4, "MAC'd meta-data", add_data,
  1212. add_data_len);
  1213. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1214. status = psa_mac_sign_setup(&operation, transform->psa_mac_enc,
  1215. transform->psa_mac_alg);
  1216. if (status != PSA_SUCCESS) {
  1217. goto hmac_failed_etm_enabled;
  1218. }
  1219. status = psa_mac_update(&operation, add_data, add_data_len);
  1220. if (status != PSA_SUCCESS) {
  1221. goto hmac_failed_etm_enabled;
  1222. }
  1223. status = psa_mac_update(&operation, data, rec->data_len);
  1224. if (status != PSA_SUCCESS) {
  1225. goto hmac_failed_etm_enabled;
  1226. }
  1227. status = psa_mac_sign_finish(&operation, mac, MBEDTLS_SSL_MAC_ADD,
  1228. &sign_mac_length);
  1229. if (status != PSA_SUCCESS) {
  1230. goto hmac_failed_etm_enabled;
  1231. }
  1232. #else
  1233. ret = mbedtls_md_hmac_update(&transform->md_ctx_enc, add_data,
  1234. add_data_len);
  1235. if (ret != 0) {
  1236. goto hmac_failed_etm_enabled;
  1237. }
  1238. ret = mbedtls_md_hmac_update(&transform->md_ctx_enc,
  1239. data, rec->data_len);
  1240. if (ret != 0) {
  1241. goto hmac_failed_etm_enabled;
  1242. }
  1243. ret = mbedtls_md_hmac_finish(&transform->md_ctx_enc, mac);
  1244. if (ret != 0) {
  1245. goto hmac_failed_etm_enabled;
  1246. }
  1247. ret = mbedtls_md_hmac_reset(&transform->md_ctx_enc);
  1248. if (ret != 0) {
  1249. goto hmac_failed_etm_enabled;
  1250. }
  1251. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1252. memcpy(data + rec->data_len, mac, transform->maclen);
  1253. rec->data_len += transform->maclen;
  1254. post_avail -= transform->maclen;
  1255. auth_done++;
  1256. hmac_failed_etm_enabled:
  1257. mbedtls_platform_zeroize(mac, transform->maclen);
  1258. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1259. ret = PSA_TO_MBEDTLS_ERR(status);
  1260. status = psa_mac_abort(&operation);
  1261. if (ret == 0 && status != PSA_SUCCESS) {
  1262. ret = PSA_TO_MBEDTLS_ERR(status);
  1263. }
  1264. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1265. if (ret != 0) {
  1266. MBEDTLS_SSL_DEBUG_RET(1, "HMAC calculation failed", ret);
  1267. return ret;
  1268. }
  1269. }
  1270. #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
  1271. } else
  1272. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC) */
  1273. {
  1274. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  1275. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  1276. }
  1277. /* Make extra sure authentication was performed, exactly once */
  1278. if (auth_done != 1) {
  1279. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  1280. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  1281. }
  1282. MBEDTLS_SSL_DEBUG_MSG(2, ("<= encrypt buf"));
  1283. return 0;
  1284. }
  1285. int mbedtls_ssl_decrypt_buf(mbedtls_ssl_context const *ssl,
  1286. mbedtls_ssl_transform *transform,
  1287. mbedtls_record *rec)
  1288. {
  1289. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) || defined(MBEDTLS_SSL_HAVE_AEAD)
  1290. size_t olen;
  1291. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC || MBEDTLS_SSL_HAVE_AEAD */
  1292. mbedtls_ssl_mode_t ssl_mode;
  1293. int ret;
  1294. int auth_done = 0;
  1295. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
  1296. size_t padlen = 0;
  1297. mbedtls_ct_condition_t correct = MBEDTLS_CT_TRUE;
  1298. #endif
  1299. unsigned char *data;
  1300. /* For an explanation of the additional data length see
  1301. * the description of ssl_extract_add_data_from_record().
  1302. */
  1303. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  1304. unsigned char add_data[23 + MBEDTLS_SSL_CID_IN_LEN_MAX];
  1305. #else
  1306. unsigned char add_data[13];
  1307. #endif
  1308. size_t add_data_len;
  1309. #if !defined(MBEDTLS_DEBUG_C)
  1310. ssl = NULL; /* make sure we don't use it except for debug */
  1311. ((void) ssl);
  1312. #endif
  1313. MBEDTLS_SSL_DEBUG_MSG(2, ("=> decrypt buf"));
  1314. if (rec == NULL ||
  1315. rec->buf == NULL ||
  1316. rec->buf_len < rec->data_offset ||
  1317. rec->buf_len - rec->data_offset < rec->data_len) {
  1318. MBEDTLS_SSL_DEBUG_MSG(1, ("bad record structure provided to decrypt_buf"));
  1319. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  1320. }
  1321. data = rec->buf + rec->data_offset;
  1322. ssl_mode = mbedtls_ssl_get_mode_from_transform(transform);
  1323. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  1324. /*
  1325. * Match record's CID with incoming CID.
  1326. */
  1327. if (rec->cid_len != transform->in_cid_len ||
  1328. memcmp(rec->cid, transform->in_cid, rec->cid_len) != 0) {
  1329. return MBEDTLS_ERR_SSL_UNEXPECTED_CID;
  1330. }
  1331. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  1332. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_STREAM)
  1333. if (ssl_mode == MBEDTLS_SSL_MODE_STREAM) {
  1334. if (rec->data_len < transform->maclen) {
  1335. MBEDTLS_SSL_DEBUG_MSG(1,
  1336. ("Record too short for MAC:"
  1337. " %" MBEDTLS_PRINTF_SIZET " < %" MBEDTLS_PRINTF_SIZET,
  1338. rec->data_len, transform->maclen));
  1339. return MBEDTLS_ERR_SSL_INVALID_MAC;
  1340. }
  1341. /* The only supported stream cipher is "NULL",
  1342. * so there's no encryption to do here.*/
  1343. } else
  1344. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_STREAM */
  1345. #if defined(MBEDTLS_SSL_HAVE_AEAD)
  1346. if (ssl_mode == MBEDTLS_SSL_MODE_AEAD) {
  1347. unsigned char iv[12];
  1348. unsigned char *dynamic_iv;
  1349. size_t dynamic_iv_len;
  1350. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1351. psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
  1352. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1353. /*
  1354. * Extract dynamic part of nonce for AEAD decryption.
  1355. *
  1356. * Note: In the case of CCM and GCM in TLS 1.2, the dynamic
  1357. * part of the IV is prepended to the ciphertext and
  1358. * can be chosen freely - in particular, it need not
  1359. * agree with the record sequence number.
  1360. */
  1361. dynamic_iv_len = sizeof(rec->ctr);
  1362. if (ssl_transform_aead_dynamic_iv_is_explicit(transform) == 1) {
  1363. if (rec->data_len < dynamic_iv_len) {
  1364. MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
  1365. " ) < explicit_iv_len (%" MBEDTLS_PRINTF_SIZET ") ",
  1366. rec->data_len,
  1367. dynamic_iv_len));
  1368. return MBEDTLS_ERR_SSL_INVALID_MAC;
  1369. }
  1370. dynamic_iv = data;
  1371. data += dynamic_iv_len;
  1372. rec->data_offset += dynamic_iv_len;
  1373. rec->data_len -= dynamic_iv_len;
  1374. } else {
  1375. dynamic_iv = rec->ctr;
  1376. }
  1377. /* Check that there's space for the authentication tag. */
  1378. if (rec->data_len < transform->taglen) {
  1379. MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
  1380. ") < taglen (%" MBEDTLS_PRINTF_SIZET ") ",
  1381. rec->data_len,
  1382. transform->taglen));
  1383. return MBEDTLS_ERR_SSL_INVALID_MAC;
  1384. }
  1385. rec->data_len -= transform->taglen;
  1386. /*
  1387. * Prepare nonce from dynamic and static parts.
  1388. */
  1389. ssl_build_record_nonce(iv, sizeof(iv),
  1390. transform->iv_dec,
  1391. transform->fixed_ivlen,
  1392. dynamic_iv,
  1393. dynamic_iv_len);
  1394. /*
  1395. * Build additional data for AEAD encryption.
  1396. * This depends on the TLS version.
  1397. */
  1398. ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
  1399. transform->tls_version,
  1400. transform->taglen);
  1401. MBEDTLS_SSL_DEBUG_BUF(4, "additional data used for AEAD",
  1402. add_data, add_data_len);
  1403. /* Because of the check above, we know that there are
  1404. * explicit_iv_len Bytes preceding data, and taglen
  1405. * bytes following data + data_len. This justifies
  1406. * the debug message and the invocation of
  1407. * mbedtls_cipher_auth_decrypt_ext() below. */
  1408. MBEDTLS_SSL_DEBUG_BUF(4, "IV used", iv, transform->ivlen);
  1409. MBEDTLS_SSL_DEBUG_BUF(4, "TAG used", data + rec->data_len,
  1410. transform->taglen);
  1411. /*
  1412. * Decrypt and authenticate
  1413. */
  1414. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1415. status = psa_aead_decrypt(transform->psa_key_dec,
  1416. transform->psa_alg,
  1417. iv, transform->ivlen,
  1418. add_data, add_data_len,
  1419. data, rec->data_len + transform->taglen,
  1420. data, rec->buf_len - (data - rec->buf),
  1421. &olen);
  1422. if (status != PSA_SUCCESS) {
  1423. ret = PSA_TO_MBEDTLS_ERR(status);
  1424. MBEDTLS_SSL_DEBUG_RET(1, "psa_aead_decrypt", ret);
  1425. return ret;
  1426. }
  1427. #else
  1428. if ((ret = mbedtls_cipher_auth_decrypt_ext
  1429. (&transform->cipher_ctx_dec,
  1430. iv, transform->ivlen,
  1431. add_data, add_data_len,
  1432. data, rec->data_len + transform->taglen, /* src */
  1433. data, rec->buf_len - (size_t) (data - rec->buf), &olen, /* dst */
  1434. transform->taglen)) != 0) {
  1435. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_auth_decrypt_ext", ret);
  1436. if (ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED) {
  1437. return MBEDTLS_ERR_SSL_INVALID_MAC;
  1438. }
  1439. return ret;
  1440. }
  1441. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1442. auth_done++;
  1443. /* Double-check that AEAD decryption doesn't change content length. */
  1444. if (olen != rec->data_len) {
  1445. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  1446. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  1447. }
  1448. } else
  1449. #endif /* MBEDTLS_SSL_HAVE_AEAD */
  1450. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
  1451. if (ssl_mode == MBEDTLS_SSL_MODE_CBC ||
  1452. ssl_mode == MBEDTLS_SSL_MODE_CBC_ETM) {
  1453. size_t minlen = 0;
  1454. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1455. psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
  1456. size_t part_len;
  1457. psa_cipher_operation_t cipher_op = PSA_CIPHER_OPERATION_INIT;
  1458. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1459. /*
  1460. * Check immediate ciphertext sanity
  1461. */
  1462. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1463. /* The ciphertext is prefixed with the CBC IV. */
  1464. minlen += transform->ivlen;
  1465. #endif
  1466. /* Size considerations:
  1467. *
  1468. * - The CBC cipher text must not be empty and hence
  1469. * at least of size transform->ivlen.
  1470. *
  1471. * Together with the potential IV-prefix, this explains
  1472. * the first of the two checks below.
  1473. *
  1474. * - The record must contain a MAC, either in plain or
  1475. * encrypted, depending on whether Encrypt-then-MAC
  1476. * is used or not.
  1477. * - If it is, the message contains the IV-prefix,
  1478. * the CBC ciphertext, and the MAC.
  1479. * - If it is not, the padded plaintext, and hence
  1480. * the CBC ciphertext, has at least length maclen + 1
  1481. * because there is at least the padding length byte.
  1482. *
  1483. * As the CBC ciphertext is not empty, both cases give the
  1484. * lower bound minlen + maclen + 1 on the record size, which
  1485. * we test for in the second check below.
  1486. */
  1487. if (rec->data_len < minlen + transform->ivlen ||
  1488. rec->data_len < minlen + transform->maclen + 1) {
  1489. MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
  1490. ") < max( ivlen(%" MBEDTLS_PRINTF_SIZET
  1491. "), maclen (%" MBEDTLS_PRINTF_SIZET ") "
  1492. "+ 1 ) ( + expl IV )",
  1493. rec->data_len,
  1494. transform->ivlen,
  1495. transform->maclen));
  1496. return MBEDTLS_ERR_SSL_INVALID_MAC;
  1497. }
  1498. /*
  1499. * Authenticate before decrypt if enabled
  1500. */
  1501. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  1502. if (ssl_mode == MBEDTLS_SSL_MODE_CBC_ETM) {
  1503. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1504. psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
  1505. #else
  1506. unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
  1507. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1508. MBEDTLS_SSL_DEBUG_MSG(3, ("using encrypt then mac"));
  1509. /* Update data_len in tandem with add_data.
  1510. *
  1511. * The subtraction is safe because of the previous check
  1512. * data_len >= minlen + maclen + 1.
  1513. *
  1514. * Afterwards, we know that data + data_len is followed by at
  1515. * least maclen Bytes, which justifies the call to
  1516. * mbedtls_ct_memcmp() below.
  1517. *
  1518. * Further, we still know that data_len > minlen */
  1519. rec->data_len -= transform->maclen;
  1520. ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
  1521. transform->tls_version,
  1522. transform->taglen);
  1523. /* Calculate expected MAC. */
  1524. MBEDTLS_SSL_DEBUG_BUF(4, "MAC'd meta-data", add_data,
  1525. add_data_len);
  1526. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1527. status = psa_mac_verify_setup(&operation, transform->psa_mac_dec,
  1528. transform->psa_mac_alg);
  1529. if (status != PSA_SUCCESS) {
  1530. goto hmac_failed_etm_enabled;
  1531. }
  1532. status = psa_mac_update(&operation, add_data, add_data_len);
  1533. if (status != PSA_SUCCESS) {
  1534. goto hmac_failed_etm_enabled;
  1535. }
  1536. status = psa_mac_update(&operation, data, rec->data_len);
  1537. if (status != PSA_SUCCESS) {
  1538. goto hmac_failed_etm_enabled;
  1539. }
  1540. /* Compare expected MAC with MAC at the end of the record. */
  1541. status = psa_mac_verify_finish(&operation, data + rec->data_len,
  1542. transform->maclen);
  1543. if (status != PSA_SUCCESS) {
  1544. goto hmac_failed_etm_enabled;
  1545. }
  1546. #else
  1547. ret = mbedtls_md_hmac_update(&transform->md_ctx_dec, add_data,
  1548. add_data_len);
  1549. if (ret != 0) {
  1550. goto hmac_failed_etm_enabled;
  1551. }
  1552. ret = mbedtls_md_hmac_update(&transform->md_ctx_dec,
  1553. data, rec->data_len);
  1554. if (ret != 0) {
  1555. goto hmac_failed_etm_enabled;
  1556. }
  1557. ret = mbedtls_md_hmac_finish(&transform->md_ctx_dec, mac_expect);
  1558. if (ret != 0) {
  1559. goto hmac_failed_etm_enabled;
  1560. }
  1561. ret = mbedtls_md_hmac_reset(&transform->md_ctx_dec);
  1562. if (ret != 0) {
  1563. goto hmac_failed_etm_enabled;
  1564. }
  1565. MBEDTLS_SSL_DEBUG_BUF(4, "message mac", data + rec->data_len,
  1566. transform->maclen);
  1567. MBEDTLS_SSL_DEBUG_BUF(4, "expected mac", mac_expect,
  1568. transform->maclen);
  1569. /* Compare expected MAC with MAC at the end of the record. */
  1570. if (mbedtls_ct_memcmp(data + rec->data_len, mac_expect,
  1571. transform->maclen) != 0) {
  1572. MBEDTLS_SSL_DEBUG_MSG(1, ("message mac does not match"));
  1573. ret = MBEDTLS_ERR_SSL_INVALID_MAC;
  1574. goto hmac_failed_etm_enabled;
  1575. }
  1576. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1577. auth_done++;
  1578. hmac_failed_etm_enabled:
  1579. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1580. ret = PSA_TO_MBEDTLS_ERR(status);
  1581. status = psa_mac_abort(&operation);
  1582. if (ret == 0 && status != PSA_SUCCESS) {
  1583. ret = PSA_TO_MBEDTLS_ERR(status);
  1584. }
  1585. #else
  1586. mbedtls_platform_zeroize(mac_expect, transform->maclen);
  1587. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1588. if (ret != 0) {
  1589. if (ret != MBEDTLS_ERR_SSL_INVALID_MAC) {
  1590. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_hmac_xxx", ret);
  1591. }
  1592. return ret;
  1593. }
  1594. }
  1595. #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
  1596. /*
  1597. * Check length sanity
  1598. */
  1599. /* We know from above that data_len > minlen >= 0,
  1600. * so the following check in particular implies that
  1601. * data_len >= minlen + ivlen ( = minlen or 2 * minlen ). */
  1602. if (rec->data_len % transform->ivlen != 0) {
  1603. MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
  1604. ") %% ivlen (%" MBEDTLS_PRINTF_SIZET ") != 0",
  1605. rec->data_len, transform->ivlen));
  1606. return MBEDTLS_ERR_SSL_INVALID_MAC;
  1607. }
  1608. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1609. /*
  1610. * Initialize for prepended IV for block cipher in TLS v1.2
  1611. */
  1612. /* Safe because data_len >= minlen + ivlen = 2 * ivlen. */
  1613. memcpy(transform->iv_dec, data, transform->ivlen);
  1614. data += transform->ivlen;
  1615. rec->data_offset += transform->ivlen;
  1616. rec->data_len -= transform->ivlen;
  1617. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  1618. /* We still have data_len % ivlen == 0 and data_len >= ivlen here. */
  1619. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1620. status = psa_cipher_decrypt_setup(&cipher_op,
  1621. transform->psa_key_dec, transform->psa_alg);
  1622. if (status != PSA_SUCCESS) {
  1623. ret = PSA_TO_MBEDTLS_ERR(status);
  1624. MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_decrypt_setup", ret);
  1625. return ret;
  1626. }
  1627. status = psa_cipher_set_iv(&cipher_op, transform->iv_dec, transform->ivlen);
  1628. if (status != PSA_SUCCESS) {
  1629. ret = PSA_TO_MBEDTLS_ERR(status);
  1630. MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_set_iv", ret);
  1631. return ret;
  1632. }
  1633. status = psa_cipher_update(&cipher_op,
  1634. data, rec->data_len,
  1635. data, rec->data_len, &olen);
  1636. if (status != PSA_SUCCESS) {
  1637. ret = PSA_TO_MBEDTLS_ERR(status);
  1638. MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_update", ret);
  1639. return ret;
  1640. }
  1641. status = psa_cipher_finish(&cipher_op,
  1642. data + olen, rec->data_len - olen,
  1643. &part_len);
  1644. if (status != PSA_SUCCESS) {
  1645. ret = PSA_TO_MBEDTLS_ERR(status);
  1646. MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_finish", ret);
  1647. return ret;
  1648. }
  1649. olen += part_len;
  1650. #else
  1651. if ((ret = mbedtls_cipher_crypt(&transform->cipher_ctx_dec,
  1652. transform->iv_dec, transform->ivlen,
  1653. data, rec->data_len, data, &olen)) != 0) {
  1654. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_crypt", ret);
  1655. return ret;
  1656. }
  1657. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1658. /* Double-check that length hasn't changed during decryption. */
  1659. if (rec->data_len != olen) {
  1660. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  1661. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  1662. }
  1663. /* Safe since data_len >= minlen + maclen + 1, so after having
  1664. * subtracted at most minlen and maclen up to this point,
  1665. * data_len > 0 (because of data_len % ivlen == 0, it's actually
  1666. * >= ivlen ). */
  1667. padlen = data[rec->data_len - 1];
  1668. if (auth_done == 1) {
  1669. const mbedtls_ct_condition_t ge = mbedtls_ct_uint_ge(
  1670. rec->data_len,
  1671. padlen + 1);
  1672. correct = mbedtls_ct_bool_and(ge, correct);
  1673. padlen = mbedtls_ct_size_if_else_0(ge, padlen);
  1674. } else {
  1675. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1676. if (rec->data_len < transform->maclen + padlen + 1) {
  1677. MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
  1678. ") < maclen (%" MBEDTLS_PRINTF_SIZET
  1679. ") + padlen (%" MBEDTLS_PRINTF_SIZET ")",
  1680. rec->data_len,
  1681. transform->maclen,
  1682. padlen + 1));
  1683. }
  1684. #endif
  1685. const mbedtls_ct_condition_t ge = mbedtls_ct_uint_ge(
  1686. rec->data_len,
  1687. transform->maclen + padlen + 1);
  1688. correct = mbedtls_ct_bool_and(ge, correct);
  1689. padlen = mbedtls_ct_size_if_else_0(ge, padlen);
  1690. }
  1691. padlen++;
  1692. /* Regardless of the validity of the padding,
  1693. * we have data_len >= padlen here. */
  1694. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1695. /* The padding check involves a series of up to 256
  1696. * consecutive memory reads at the end of the record
  1697. * plaintext buffer. In order to hide the length and
  1698. * validity of the padding, always perform exactly
  1699. * `min(256,plaintext_len)` reads (but take into account
  1700. * only the last `padlen` bytes for the padding check). */
  1701. size_t pad_count = 0;
  1702. volatile unsigned char * const check = data;
  1703. /* Index of first padding byte; it has been ensured above
  1704. * that the subtraction is safe. */
  1705. size_t const padding_idx = rec->data_len - padlen;
  1706. size_t const num_checks = rec->data_len <= 256 ? rec->data_len : 256;
  1707. size_t const start_idx = rec->data_len - num_checks;
  1708. size_t idx;
  1709. for (idx = start_idx; idx < rec->data_len; idx++) {
  1710. /* pad_count += (idx >= padding_idx) &&
  1711. * (check[idx] == padlen - 1);
  1712. */
  1713. const mbedtls_ct_condition_t a = mbedtls_ct_uint_ge(idx, padding_idx);
  1714. size_t increment = mbedtls_ct_size_if_else_0(a, 1);
  1715. const mbedtls_ct_condition_t b = mbedtls_ct_uint_eq(check[idx], padlen - 1);
  1716. increment = mbedtls_ct_size_if_else_0(b, increment);
  1717. pad_count += increment;
  1718. }
  1719. correct = mbedtls_ct_bool_and(mbedtls_ct_uint_eq(pad_count, padlen), correct);
  1720. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1721. if (padlen > 0 && correct == MBEDTLS_CT_FALSE) {
  1722. MBEDTLS_SSL_DEBUG_MSG(1, ("bad padding byte detected"));
  1723. }
  1724. #endif
  1725. padlen = mbedtls_ct_size_if_else_0(correct, padlen);
  1726. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  1727. /* If the padding was found to be invalid, padlen == 0
  1728. * and the subtraction is safe. If the padding was found valid,
  1729. * padlen hasn't been changed and the previous assertion
  1730. * data_len >= padlen still holds. */
  1731. rec->data_len -= padlen;
  1732. } else
  1733. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC */
  1734. {
  1735. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  1736. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  1737. }
  1738. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1739. MBEDTLS_SSL_DEBUG_BUF(4, "raw buffer after decryption",
  1740. data, rec->data_len);
  1741. #endif
  1742. /*
  1743. * Authenticate if not done yet.
  1744. * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
  1745. */
  1746. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
  1747. if (auth_done == 0) {
  1748. unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD] = { 0 };
  1749. unsigned char mac_peer[MBEDTLS_SSL_MAC_ADD] = { 0 };
  1750. /* For CBC+MAC, If the initial value of padlen was such that
  1751. * data_len < maclen + padlen + 1, then padlen
  1752. * got reset to 1, and the initial check
  1753. * data_len >= minlen + maclen + 1
  1754. * guarantees that at this point we still
  1755. * have at least data_len >= maclen.
  1756. *
  1757. * If the initial value of padlen was such that
  1758. * data_len >= maclen + padlen + 1, then we have
  1759. * subtracted either padlen + 1 (if the padding was correct)
  1760. * or 0 (if the padding was incorrect) since then,
  1761. * hence data_len >= maclen in any case.
  1762. *
  1763. * For stream ciphers, we checked above that
  1764. * data_len >= maclen.
  1765. */
  1766. rec->data_len -= transform->maclen;
  1767. ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
  1768. transform->tls_version,
  1769. transform->taglen);
  1770. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1771. /*
  1772. * The next two sizes are the minimum and maximum values of
  1773. * data_len over all padlen values.
  1774. *
  1775. * They're independent of padlen, since we previously did
  1776. * data_len -= padlen.
  1777. *
  1778. * Note that max_len + maclen is never more than the buffer
  1779. * length, as we previously did in_msglen -= maclen too.
  1780. */
  1781. const size_t max_len = rec->data_len + padlen;
  1782. const size_t min_len = (max_len > 256) ? max_len - 256 : 0;
  1783. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1784. ret = mbedtls_ct_hmac(transform->psa_mac_dec,
  1785. transform->psa_mac_alg,
  1786. add_data, add_data_len,
  1787. data, rec->data_len, min_len, max_len,
  1788. mac_expect);
  1789. #else
  1790. ret = mbedtls_ct_hmac(&transform->md_ctx_dec,
  1791. add_data, add_data_len,
  1792. data, rec->data_len, min_len, max_len,
  1793. mac_expect);
  1794. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1795. if (ret != 0) {
  1796. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ct_hmac", ret);
  1797. goto hmac_failed_etm_disabled;
  1798. }
  1799. mbedtls_ct_memcpy_offset(mac_peer, data,
  1800. rec->data_len,
  1801. min_len, max_len,
  1802. transform->maclen);
  1803. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  1804. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1805. MBEDTLS_SSL_DEBUG_BUF(4, "expected mac", mac_expect, transform->maclen);
  1806. MBEDTLS_SSL_DEBUG_BUF(4, "message mac", mac_peer, transform->maclen);
  1807. #endif
  1808. if (mbedtls_ct_memcmp(mac_peer, mac_expect,
  1809. transform->maclen) != 0) {
  1810. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1811. MBEDTLS_SSL_DEBUG_MSG(1, ("message mac does not match"));
  1812. #endif
  1813. correct = MBEDTLS_CT_FALSE;
  1814. }
  1815. auth_done++;
  1816. hmac_failed_etm_disabled:
  1817. mbedtls_platform_zeroize(mac_peer, transform->maclen);
  1818. mbedtls_platform_zeroize(mac_expect, transform->maclen);
  1819. if (ret != 0) {
  1820. return ret;
  1821. }
  1822. }
  1823. /*
  1824. * Finally check the correct flag
  1825. */
  1826. if (correct == MBEDTLS_CT_FALSE) {
  1827. return MBEDTLS_ERR_SSL_INVALID_MAC;
  1828. }
  1829. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
  1830. /* Make extra sure authentication was performed, exactly once */
  1831. if (auth_done != 1) {
  1832. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  1833. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  1834. }
  1835. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  1836. if (transform->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
  1837. /* Remove inner padding and infer true content type. */
  1838. ret = ssl_parse_inner_plaintext(data, &rec->data_len,
  1839. &rec->type);
  1840. if (ret != 0) {
  1841. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  1842. }
  1843. }
  1844. #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
  1845. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  1846. if (rec->cid_len != 0) {
  1847. ret = ssl_parse_inner_plaintext(data, &rec->data_len,
  1848. &rec->type);
  1849. if (ret != 0) {
  1850. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  1851. }
  1852. }
  1853. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  1854. MBEDTLS_SSL_DEBUG_MSG(2, ("<= decrypt buf"));
  1855. return 0;
  1856. }
  1857. #undef MAC_NONE
  1858. #undef MAC_PLAINTEXT
  1859. #undef MAC_CIPHERTEXT
  1860. /*
  1861. * Fill the input message buffer by appending data to it.
  1862. * The amount of data already fetched is in ssl->in_left.
  1863. *
  1864. * If we return 0, is it guaranteed that (at least) nb_want bytes are
  1865. * available (from this read and/or a previous one). Otherwise, an error code
  1866. * is returned (possibly EOF or WANT_READ).
  1867. *
  1868. * With stream transport (TLS) on success ssl->in_left == nb_want, but
  1869. * with datagram transport (DTLS) on success ssl->in_left >= nb_want,
  1870. * since we always read a whole datagram at once.
  1871. *
  1872. * For DTLS, it is up to the caller to set ssl->next_record_offset when
  1873. * they're done reading a record.
  1874. */
  1875. int mbedtls_ssl_fetch_input(mbedtls_ssl_context *ssl, size_t nb_want)
  1876. {
  1877. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1878. size_t len;
  1879. #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
  1880. size_t in_buf_len = ssl->in_buf_len;
  1881. #else
  1882. size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
  1883. #endif
  1884. MBEDTLS_SSL_DEBUG_MSG(2, ("=> fetch input"));
  1885. if (ssl->f_recv == NULL && ssl->f_recv_timeout == NULL) {
  1886. MBEDTLS_SSL_DEBUG_MSG(1, ("Bad usage of mbedtls_ssl_set_bio() "));
  1887. return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
  1888. }
  1889. if (nb_want > in_buf_len - (size_t) (ssl->in_hdr - ssl->in_buf)) {
  1890. MBEDTLS_SSL_DEBUG_MSG(1, ("requesting more data than fits"));
  1891. return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
  1892. }
  1893. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  1894. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  1895. uint32_t timeout;
  1896. /*
  1897. * The point is, we need to always read a full datagram at once, so we
  1898. * sometimes read more then requested, and handle the additional data.
  1899. * It could be the rest of the current record (while fetching the
  1900. * header) and/or some other records in the same datagram.
  1901. */
  1902. /*
  1903. * Move to the next record in the already read datagram if applicable
  1904. */
  1905. if (ssl->next_record_offset != 0) {
  1906. if (ssl->in_left < ssl->next_record_offset) {
  1907. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  1908. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  1909. }
  1910. ssl->in_left -= ssl->next_record_offset;
  1911. if (ssl->in_left != 0) {
  1912. MBEDTLS_SSL_DEBUG_MSG(2, ("next record in same datagram, offset: %"
  1913. MBEDTLS_PRINTF_SIZET,
  1914. ssl->next_record_offset));
  1915. memmove(ssl->in_hdr,
  1916. ssl->in_hdr + ssl->next_record_offset,
  1917. ssl->in_left);
  1918. }
  1919. ssl->next_record_offset = 0;
  1920. }
  1921. MBEDTLS_SSL_DEBUG_MSG(2, ("in_left: %" MBEDTLS_PRINTF_SIZET
  1922. ", nb_want: %" MBEDTLS_PRINTF_SIZET,
  1923. ssl->in_left, nb_want));
  1924. /*
  1925. * Done if we already have enough data.
  1926. */
  1927. if (nb_want <= ssl->in_left) {
  1928. MBEDTLS_SSL_DEBUG_MSG(2, ("<= fetch input"));
  1929. return 0;
  1930. }
  1931. /*
  1932. * A record can't be split across datagrams. If we need to read but
  1933. * are not at the beginning of a new record, the caller did something
  1934. * wrong.
  1935. */
  1936. if (ssl->in_left != 0) {
  1937. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  1938. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  1939. }
  1940. /*
  1941. * Don't even try to read if time's out already.
  1942. * This avoids by-passing the timer when repeatedly receiving messages
  1943. * that will end up being dropped.
  1944. */
  1945. if (mbedtls_ssl_check_timer(ssl) != 0) {
  1946. MBEDTLS_SSL_DEBUG_MSG(2, ("timer has expired"));
  1947. ret = MBEDTLS_ERR_SSL_TIMEOUT;
  1948. } else {
  1949. len = in_buf_len - (size_t) (ssl->in_hdr - ssl->in_buf);
  1950. if (mbedtls_ssl_is_handshake_over(ssl) == 0) {
  1951. timeout = ssl->handshake->retransmit_timeout;
  1952. } else {
  1953. timeout = ssl->conf->read_timeout;
  1954. }
  1955. MBEDTLS_SSL_DEBUG_MSG(3, ("f_recv_timeout: %lu ms", (unsigned long) timeout));
  1956. if (ssl->f_recv_timeout != NULL) {
  1957. ret = ssl->f_recv_timeout(ssl->p_bio, ssl->in_hdr, len,
  1958. timeout);
  1959. } else {
  1960. ret = ssl->f_recv(ssl->p_bio, ssl->in_hdr, len);
  1961. }
  1962. MBEDTLS_SSL_DEBUG_RET(2, "ssl->f_recv(_timeout)", ret);
  1963. if (ret == 0) {
  1964. return MBEDTLS_ERR_SSL_CONN_EOF;
  1965. }
  1966. }
  1967. if (ret == MBEDTLS_ERR_SSL_TIMEOUT) {
  1968. MBEDTLS_SSL_DEBUG_MSG(2, ("timeout"));
  1969. mbedtls_ssl_set_timer(ssl, 0);
  1970. if (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
  1971. if (ssl_double_retransmit_timeout(ssl) != 0) {
  1972. MBEDTLS_SSL_DEBUG_MSG(1, ("handshake timeout"));
  1973. return MBEDTLS_ERR_SSL_TIMEOUT;
  1974. }
  1975. if ((ret = mbedtls_ssl_resend(ssl)) != 0) {
  1976. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_resend", ret);
  1977. return ret;
  1978. }
  1979. return MBEDTLS_ERR_SSL_WANT_READ;
  1980. }
  1981. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
  1982. else if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  1983. ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING) {
  1984. if ((ret = mbedtls_ssl_resend_hello_request(ssl)) != 0) {
  1985. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_resend_hello_request",
  1986. ret);
  1987. return ret;
  1988. }
  1989. return MBEDTLS_ERR_SSL_WANT_READ;
  1990. }
  1991. #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
  1992. }
  1993. if (ret < 0) {
  1994. return ret;
  1995. }
  1996. ssl->in_left = ret;
  1997. } else
  1998. #endif
  1999. {
  2000. MBEDTLS_SSL_DEBUG_MSG(2, ("in_left: %" MBEDTLS_PRINTF_SIZET
  2001. ", nb_want: %" MBEDTLS_PRINTF_SIZET,
  2002. ssl->in_left, nb_want));
  2003. while (ssl->in_left < nb_want) {
  2004. len = nb_want - ssl->in_left;
  2005. if (mbedtls_ssl_check_timer(ssl) != 0) {
  2006. ret = MBEDTLS_ERR_SSL_TIMEOUT;
  2007. } else {
  2008. if (ssl->f_recv_timeout != NULL) {
  2009. ret = ssl->f_recv_timeout(ssl->p_bio,
  2010. ssl->in_hdr + ssl->in_left, len,
  2011. ssl->conf->read_timeout);
  2012. } else {
  2013. ret = ssl->f_recv(ssl->p_bio,
  2014. ssl->in_hdr + ssl->in_left, len);
  2015. }
  2016. }
  2017. MBEDTLS_SSL_DEBUG_MSG(2, ("in_left: %" MBEDTLS_PRINTF_SIZET
  2018. ", nb_want: %" MBEDTLS_PRINTF_SIZET,
  2019. ssl->in_left, nb_want));
  2020. MBEDTLS_SSL_DEBUG_RET(2, "ssl->f_recv(_timeout)", ret);
  2021. if (ret == 0) {
  2022. return MBEDTLS_ERR_SSL_CONN_EOF;
  2023. }
  2024. if (ret < 0) {
  2025. return ret;
  2026. }
  2027. if ((size_t) ret > len) {
  2028. MBEDTLS_SSL_DEBUG_MSG(1,
  2029. ("f_recv returned %d bytes but only %" MBEDTLS_PRINTF_SIZET
  2030. " were requested",
  2031. ret, len));
  2032. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  2033. }
  2034. ssl->in_left += ret;
  2035. }
  2036. }
  2037. MBEDTLS_SSL_DEBUG_MSG(2, ("<= fetch input"));
  2038. return 0;
  2039. }
  2040. /*
  2041. * Flush any data not yet written
  2042. */
  2043. int mbedtls_ssl_flush_output(mbedtls_ssl_context *ssl)
  2044. {
  2045. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2046. unsigned char *buf;
  2047. MBEDTLS_SSL_DEBUG_MSG(2, ("=> flush output"));
  2048. if (ssl->f_send == NULL) {
  2049. MBEDTLS_SSL_DEBUG_MSG(1, ("Bad usage of mbedtls_ssl_set_bio() "));
  2050. return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
  2051. }
  2052. /* Avoid incrementing counter if data is flushed */
  2053. if (ssl->out_left == 0) {
  2054. MBEDTLS_SSL_DEBUG_MSG(2, ("<= flush output"));
  2055. return 0;
  2056. }
  2057. while (ssl->out_left > 0) {
  2058. MBEDTLS_SSL_DEBUG_MSG(2, ("message length: %" MBEDTLS_PRINTF_SIZET
  2059. ", out_left: %" MBEDTLS_PRINTF_SIZET,
  2060. mbedtls_ssl_out_hdr_len(ssl) + ssl->out_msglen, ssl->out_left));
  2061. buf = ssl->out_hdr - ssl->out_left;
  2062. ret = ssl->f_send(ssl->p_bio, buf, ssl->out_left);
  2063. MBEDTLS_SSL_DEBUG_RET(2, "ssl->f_send", ret);
  2064. if (ret <= 0) {
  2065. return ret;
  2066. }
  2067. if ((size_t) ret > ssl->out_left) {
  2068. MBEDTLS_SSL_DEBUG_MSG(1,
  2069. ("f_send returned %d bytes but only %" MBEDTLS_PRINTF_SIZET
  2070. " bytes were sent",
  2071. ret, ssl->out_left));
  2072. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  2073. }
  2074. ssl->out_left -= ret;
  2075. }
  2076. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2077. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  2078. ssl->out_hdr = ssl->out_buf;
  2079. } else
  2080. #endif
  2081. {
  2082. ssl->out_hdr = ssl->out_buf + 8;
  2083. }
  2084. mbedtls_ssl_update_out_pointers(ssl, ssl->transform_out);
  2085. MBEDTLS_SSL_DEBUG_MSG(2, ("<= flush output"));
  2086. return 0;
  2087. }
  2088. /*
  2089. * Functions to handle the DTLS retransmission state machine
  2090. */
  2091. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2092. /*
  2093. * Append current handshake message to current outgoing flight
  2094. */
  2095. MBEDTLS_CHECK_RETURN_CRITICAL
  2096. static int ssl_flight_append(mbedtls_ssl_context *ssl)
  2097. {
  2098. mbedtls_ssl_flight_item *msg;
  2099. MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_flight_append"));
  2100. MBEDTLS_SSL_DEBUG_BUF(4, "message appended to flight",
  2101. ssl->out_msg, ssl->out_msglen);
  2102. /* Allocate space for current message */
  2103. if ((msg = mbedtls_calloc(1, sizeof(mbedtls_ssl_flight_item))) == NULL) {
  2104. MBEDTLS_SSL_DEBUG_MSG(1, ("alloc %" MBEDTLS_PRINTF_SIZET " bytes failed",
  2105. sizeof(mbedtls_ssl_flight_item)));
  2106. return MBEDTLS_ERR_SSL_ALLOC_FAILED;
  2107. }
  2108. if ((msg->p = mbedtls_calloc(1, ssl->out_msglen)) == NULL) {
  2109. MBEDTLS_SSL_DEBUG_MSG(1, ("alloc %" MBEDTLS_PRINTF_SIZET " bytes failed",
  2110. ssl->out_msglen));
  2111. mbedtls_free(msg);
  2112. return MBEDTLS_ERR_SSL_ALLOC_FAILED;
  2113. }
  2114. /* Copy current handshake message with headers */
  2115. memcpy(msg->p, ssl->out_msg, ssl->out_msglen);
  2116. msg->len = ssl->out_msglen;
  2117. msg->type = ssl->out_msgtype;
  2118. msg->next = NULL;
  2119. /* Append to the current flight */
  2120. if (ssl->handshake->flight == NULL) {
  2121. ssl->handshake->flight = msg;
  2122. } else {
  2123. mbedtls_ssl_flight_item *cur = ssl->handshake->flight;
  2124. while (cur->next != NULL) {
  2125. cur = cur->next;
  2126. }
  2127. cur->next = msg;
  2128. }
  2129. MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_flight_append"));
  2130. return 0;
  2131. }
  2132. /*
  2133. * Free the current flight of handshake messages
  2134. */
  2135. void mbedtls_ssl_flight_free(mbedtls_ssl_flight_item *flight)
  2136. {
  2137. mbedtls_ssl_flight_item *cur = flight;
  2138. mbedtls_ssl_flight_item *next;
  2139. while (cur != NULL) {
  2140. next = cur->next;
  2141. mbedtls_free(cur->p);
  2142. mbedtls_free(cur);
  2143. cur = next;
  2144. }
  2145. }
  2146. /*
  2147. * Swap transform_out and out_ctr with the alternative ones
  2148. */
  2149. MBEDTLS_CHECK_RETURN_CRITICAL
  2150. static int ssl_swap_epochs(mbedtls_ssl_context *ssl)
  2151. {
  2152. mbedtls_ssl_transform *tmp_transform;
  2153. unsigned char tmp_out_ctr[MBEDTLS_SSL_SEQUENCE_NUMBER_LEN];
  2154. if (ssl->transform_out == ssl->handshake->alt_transform_out) {
  2155. MBEDTLS_SSL_DEBUG_MSG(3, ("skip swap epochs"));
  2156. return 0;
  2157. }
  2158. MBEDTLS_SSL_DEBUG_MSG(3, ("swap epochs"));
  2159. /* Swap transforms */
  2160. tmp_transform = ssl->transform_out;
  2161. ssl->transform_out = ssl->handshake->alt_transform_out;
  2162. ssl->handshake->alt_transform_out = tmp_transform;
  2163. /* Swap epoch + sequence_number */
  2164. memcpy(tmp_out_ctr, ssl->cur_out_ctr, sizeof(tmp_out_ctr));
  2165. memcpy(ssl->cur_out_ctr, ssl->handshake->alt_out_ctr,
  2166. sizeof(ssl->cur_out_ctr));
  2167. memcpy(ssl->handshake->alt_out_ctr, tmp_out_ctr,
  2168. sizeof(ssl->handshake->alt_out_ctr));
  2169. /* Adjust to the newly activated transform */
  2170. mbedtls_ssl_update_out_pointers(ssl, ssl->transform_out);
  2171. return 0;
  2172. }
  2173. /*
  2174. * Retransmit the current flight of messages.
  2175. */
  2176. int mbedtls_ssl_resend(mbedtls_ssl_context *ssl)
  2177. {
  2178. int ret = 0;
  2179. MBEDTLS_SSL_DEBUG_MSG(2, ("=> mbedtls_ssl_resend"));
  2180. ret = mbedtls_ssl_flight_transmit(ssl);
  2181. MBEDTLS_SSL_DEBUG_MSG(2, ("<= mbedtls_ssl_resend"));
  2182. return ret;
  2183. }
  2184. /*
  2185. * Transmit or retransmit the current flight of messages.
  2186. *
  2187. * Need to remember the current message in case flush_output returns
  2188. * WANT_WRITE, causing us to exit this function and come back later.
  2189. * This function must be called until state is no longer SENDING.
  2190. */
  2191. int mbedtls_ssl_flight_transmit(mbedtls_ssl_context *ssl)
  2192. {
  2193. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2194. MBEDTLS_SSL_DEBUG_MSG(2, ("=> mbedtls_ssl_flight_transmit"));
  2195. if (ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING) {
  2196. MBEDTLS_SSL_DEBUG_MSG(2, ("initialise flight transmission"));
  2197. ssl->handshake->cur_msg = ssl->handshake->flight;
  2198. ssl->handshake->cur_msg_p = ssl->handshake->flight->p + 12;
  2199. ret = ssl_swap_epochs(ssl);
  2200. if (ret != 0) {
  2201. return ret;
  2202. }
  2203. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;
  2204. }
  2205. while (ssl->handshake->cur_msg != NULL) {
  2206. size_t max_frag_len;
  2207. const mbedtls_ssl_flight_item * const cur = ssl->handshake->cur_msg;
  2208. int const is_finished =
  2209. (cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2210. cur->p[0] == MBEDTLS_SSL_HS_FINISHED);
  2211. int const force_flush = ssl->disable_datagram_packing == 1 ?
  2212. SSL_FORCE_FLUSH : SSL_DONT_FORCE_FLUSH;
  2213. /* Swap epochs before sending Finished: we can't do it after
  2214. * sending ChangeCipherSpec, in case write returns WANT_READ.
  2215. * Must be done before copying, may change out_msg pointer */
  2216. if (is_finished && ssl->handshake->cur_msg_p == (cur->p + 12)) {
  2217. MBEDTLS_SSL_DEBUG_MSG(2, ("swap epochs to send finished message"));
  2218. ret = ssl_swap_epochs(ssl);
  2219. if (ret != 0) {
  2220. return ret;
  2221. }
  2222. }
  2223. ret = ssl_get_remaining_payload_in_datagram(ssl);
  2224. if (ret < 0) {
  2225. return ret;
  2226. }
  2227. max_frag_len = (size_t) ret;
  2228. /* CCS is copied as is, while HS messages may need fragmentation */
  2229. if (cur->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
  2230. if (max_frag_len == 0) {
  2231. if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
  2232. return ret;
  2233. }
  2234. continue;
  2235. }
  2236. memcpy(ssl->out_msg, cur->p, cur->len);
  2237. ssl->out_msglen = cur->len;
  2238. ssl->out_msgtype = cur->type;
  2239. /* Update position inside current message */
  2240. ssl->handshake->cur_msg_p += cur->len;
  2241. } else {
  2242. const unsigned char * const p = ssl->handshake->cur_msg_p;
  2243. const size_t hs_len = cur->len - 12;
  2244. const size_t frag_off = (size_t) (p - (cur->p + 12));
  2245. const size_t rem_len = hs_len - frag_off;
  2246. size_t cur_hs_frag_len, max_hs_frag_len;
  2247. if ((max_frag_len < 12) || (max_frag_len == 12 && hs_len != 0)) {
  2248. if (is_finished) {
  2249. ret = ssl_swap_epochs(ssl);
  2250. if (ret != 0) {
  2251. return ret;
  2252. }
  2253. }
  2254. if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
  2255. return ret;
  2256. }
  2257. continue;
  2258. }
  2259. max_hs_frag_len = max_frag_len - 12;
  2260. cur_hs_frag_len = rem_len > max_hs_frag_len ?
  2261. max_hs_frag_len : rem_len;
  2262. if (frag_off == 0 && cur_hs_frag_len != hs_len) {
  2263. MBEDTLS_SSL_DEBUG_MSG(2, ("fragmenting handshake message (%u > %u)",
  2264. (unsigned) cur_hs_frag_len,
  2265. (unsigned) max_hs_frag_len));
  2266. }
  2267. /* Messages are stored with handshake headers as if not fragmented,
  2268. * copy beginning of headers then fill fragmentation fields.
  2269. * Handshake headers: type(1) len(3) seq(2) f_off(3) f_len(3) */
  2270. memcpy(ssl->out_msg, cur->p, 6);
  2271. ssl->out_msg[6] = MBEDTLS_BYTE_2(frag_off);
  2272. ssl->out_msg[7] = MBEDTLS_BYTE_1(frag_off);
  2273. ssl->out_msg[8] = MBEDTLS_BYTE_0(frag_off);
  2274. ssl->out_msg[9] = MBEDTLS_BYTE_2(cur_hs_frag_len);
  2275. ssl->out_msg[10] = MBEDTLS_BYTE_1(cur_hs_frag_len);
  2276. ssl->out_msg[11] = MBEDTLS_BYTE_0(cur_hs_frag_len);
  2277. MBEDTLS_SSL_DEBUG_BUF(3, "handshake header", ssl->out_msg, 12);
  2278. /* Copy the handshake message content and set records fields */
  2279. memcpy(ssl->out_msg + 12, p, cur_hs_frag_len);
  2280. ssl->out_msglen = cur_hs_frag_len + 12;
  2281. ssl->out_msgtype = cur->type;
  2282. /* Update position inside current message */
  2283. ssl->handshake->cur_msg_p += cur_hs_frag_len;
  2284. }
  2285. /* If done with the current message move to the next one if any */
  2286. if (ssl->handshake->cur_msg_p >= cur->p + cur->len) {
  2287. if (cur->next != NULL) {
  2288. ssl->handshake->cur_msg = cur->next;
  2289. ssl->handshake->cur_msg_p = cur->next->p + 12;
  2290. } else {
  2291. ssl->handshake->cur_msg = NULL;
  2292. ssl->handshake->cur_msg_p = NULL;
  2293. }
  2294. }
  2295. /* Actually send the message out */
  2296. if ((ret = mbedtls_ssl_write_record(ssl, force_flush)) != 0) {
  2297. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_record", ret);
  2298. return ret;
  2299. }
  2300. }
  2301. if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
  2302. return ret;
  2303. }
  2304. /* Update state and set timer */
  2305. if (mbedtls_ssl_is_handshake_over(ssl) == 1) {
  2306. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
  2307. } else {
  2308. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
  2309. mbedtls_ssl_set_timer(ssl, ssl->handshake->retransmit_timeout);
  2310. }
  2311. MBEDTLS_SSL_DEBUG_MSG(2, ("<= mbedtls_ssl_flight_transmit"));
  2312. return 0;
  2313. }
  2314. /*
  2315. * To be called when the last message of an incoming flight is received.
  2316. */
  2317. void mbedtls_ssl_recv_flight_completed(mbedtls_ssl_context *ssl)
  2318. {
  2319. /* We won't need to resend that one any more */
  2320. mbedtls_ssl_flight_free(ssl->handshake->flight);
  2321. ssl->handshake->flight = NULL;
  2322. ssl->handshake->cur_msg = NULL;
  2323. /* The next incoming flight will start with this msg_seq */
  2324. ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;
  2325. /* We don't want to remember CCS's across flight boundaries. */
  2326. ssl->handshake->buffering.seen_ccs = 0;
  2327. /* Clear future message buffering structure. */
  2328. mbedtls_ssl_buffering_free(ssl);
  2329. /* Cancel timer */
  2330. mbedtls_ssl_set_timer(ssl, 0);
  2331. if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2332. ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED) {
  2333. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
  2334. } else {
  2335. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
  2336. }
  2337. }
  2338. /*
  2339. * To be called when the last message of an outgoing flight is send.
  2340. */
  2341. void mbedtls_ssl_send_flight_completed(mbedtls_ssl_context *ssl)
  2342. {
  2343. ssl_reset_retransmit_timeout(ssl);
  2344. mbedtls_ssl_set_timer(ssl, ssl->handshake->retransmit_timeout);
  2345. if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2346. ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED) {
  2347. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
  2348. } else {
  2349. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
  2350. }
  2351. }
  2352. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  2353. /*
  2354. * Handshake layer functions
  2355. */
  2356. int mbedtls_ssl_start_handshake_msg(mbedtls_ssl_context *ssl, unsigned char hs_type,
  2357. unsigned char **buf, size_t *buf_len)
  2358. {
  2359. /*
  2360. * Reserve 4 bytes for handshake header. ( Section 4,RFC 8446 )
  2361. * ...
  2362. * HandshakeType msg_type;
  2363. * uint24 length;
  2364. * ...
  2365. */
  2366. *buf = ssl->out_msg + 4;
  2367. *buf_len = MBEDTLS_SSL_OUT_CONTENT_LEN - 4;
  2368. ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  2369. ssl->out_msg[0] = hs_type;
  2370. return 0;
  2371. }
  2372. /*
  2373. * Write (DTLS: or queue) current handshake (including CCS) message.
  2374. *
  2375. * - fill in handshake headers
  2376. * - update handshake checksum
  2377. * - DTLS: save message for resending
  2378. * - then pass to the record layer
  2379. *
  2380. * DTLS: except for HelloRequest, messages are only queued, and will only be
  2381. * actually sent when calling flight_transmit() or resend().
  2382. *
  2383. * Inputs:
  2384. * - ssl->out_msglen: 4 + actual handshake message len
  2385. * (4 is the size of handshake headers for TLS)
  2386. * - ssl->out_msg[0]: the handshake type (ClientHello, ServerHello, etc)
  2387. * - ssl->out_msg + 4: the handshake message body
  2388. *
  2389. * Outputs, ie state before passing to flight_append() or write_record():
  2390. * - ssl->out_msglen: the length of the record contents
  2391. * (including handshake headers but excluding record headers)
  2392. * - ssl->out_msg: the record contents (handshake headers + content)
  2393. */
  2394. int mbedtls_ssl_write_handshake_msg_ext(mbedtls_ssl_context *ssl,
  2395. int update_checksum,
  2396. int force_flush)
  2397. {
  2398. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2399. const size_t hs_len = ssl->out_msglen - 4;
  2400. const unsigned char hs_type = ssl->out_msg[0];
  2401. MBEDTLS_SSL_DEBUG_MSG(2, ("=> write handshake message"));
  2402. /*
  2403. * Sanity checks
  2404. */
  2405. if (ssl->out_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE &&
  2406. ssl->out_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
  2407. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  2408. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  2409. }
  2410. /* Whenever we send anything different from a
  2411. * HelloRequest we should be in a handshake - double check. */
  2412. if (!(ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2413. hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST) &&
  2414. ssl->handshake == NULL) {
  2415. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  2416. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  2417. }
  2418. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2419. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  2420. ssl->handshake != NULL &&
  2421. ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING) {
  2422. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  2423. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  2424. }
  2425. #endif
  2426. /* Double-check that we did not exceed the bounds
  2427. * of the outgoing record buffer.
  2428. * This should never fail as the various message
  2429. * writing functions must obey the bounds of the
  2430. * outgoing record buffer, but better be safe.
  2431. *
  2432. * Note: We deliberately do not check for the MTU or MFL here.
  2433. */
  2434. if (ssl->out_msglen > MBEDTLS_SSL_OUT_CONTENT_LEN) {
  2435. MBEDTLS_SSL_DEBUG_MSG(1, ("Record too large: "
  2436. "size %" MBEDTLS_PRINTF_SIZET
  2437. ", maximum %" MBEDTLS_PRINTF_SIZET,
  2438. ssl->out_msglen,
  2439. (size_t) MBEDTLS_SSL_OUT_CONTENT_LEN));
  2440. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  2441. }
  2442. /*
  2443. * Fill handshake headers
  2444. */
  2445. if (ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE) {
  2446. ssl->out_msg[1] = MBEDTLS_BYTE_2(hs_len);
  2447. ssl->out_msg[2] = MBEDTLS_BYTE_1(hs_len);
  2448. ssl->out_msg[3] = MBEDTLS_BYTE_0(hs_len);
  2449. /*
  2450. * DTLS has additional fields in the Handshake layer,
  2451. * between the length field and the actual payload:
  2452. * uint16 message_seq;
  2453. * uint24 fragment_offset;
  2454. * uint24 fragment_length;
  2455. */
  2456. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2457. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  2458. /* Make room for the additional DTLS fields */
  2459. if (MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen < 8) {
  2460. MBEDTLS_SSL_DEBUG_MSG(1, ("DTLS handshake message too large: "
  2461. "size %" MBEDTLS_PRINTF_SIZET ", maximum %"
  2462. MBEDTLS_PRINTF_SIZET,
  2463. hs_len,
  2464. (size_t) (MBEDTLS_SSL_OUT_CONTENT_LEN - 12)));
  2465. return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
  2466. }
  2467. memmove(ssl->out_msg + 12, ssl->out_msg + 4, hs_len);
  2468. ssl->out_msglen += 8;
  2469. /* Write message_seq and update it, except for HelloRequest */
  2470. if (hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST) {
  2471. MBEDTLS_PUT_UINT16_BE(ssl->handshake->out_msg_seq, ssl->out_msg, 4);
  2472. ++(ssl->handshake->out_msg_seq);
  2473. } else {
  2474. ssl->out_msg[4] = 0;
  2475. ssl->out_msg[5] = 0;
  2476. }
  2477. /* Handshake hashes are computed without fragmentation,
  2478. * so set frag_offset = 0 and frag_len = hs_len for now */
  2479. memset(ssl->out_msg + 6, 0x00, 3);
  2480. memcpy(ssl->out_msg + 9, ssl->out_msg + 1, 3);
  2481. }
  2482. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  2483. /* Update running hashes of handshake messages seen */
  2484. if (hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST && update_checksum != 0) {
  2485. ret = ssl->handshake->update_checksum(ssl, ssl->out_msg,
  2486. ssl->out_msglen);
  2487. if (ret != 0) {
  2488. MBEDTLS_SSL_DEBUG_RET(1, "update_checksum", ret);
  2489. return ret;
  2490. }
  2491. }
  2492. }
  2493. /* Either send now, or just save to be sent (and resent) later */
  2494. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2495. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  2496. !(ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2497. hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST)) {
  2498. if ((ret = ssl_flight_append(ssl)) != 0) {
  2499. MBEDTLS_SSL_DEBUG_RET(1, "ssl_flight_append", ret);
  2500. return ret;
  2501. }
  2502. } else
  2503. #endif
  2504. {
  2505. if ((ret = mbedtls_ssl_write_record(ssl, force_flush)) != 0) {
  2506. MBEDTLS_SSL_DEBUG_RET(1, "ssl_write_record", ret);
  2507. return ret;
  2508. }
  2509. }
  2510. MBEDTLS_SSL_DEBUG_MSG(2, ("<= write handshake message"));
  2511. return 0;
  2512. }
  2513. int mbedtls_ssl_finish_handshake_msg(mbedtls_ssl_context *ssl,
  2514. size_t buf_len, size_t msg_len)
  2515. {
  2516. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2517. size_t msg_with_header_len;
  2518. ((void) buf_len);
  2519. /* Add reserved 4 bytes for handshake header */
  2520. msg_with_header_len = msg_len + 4;
  2521. ssl->out_msglen = msg_with_header_len;
  2522. MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_write_handshake_msg_ext(ssl, 0, 0));
  2523. cleanup:
  2524. return ret;
  2525. }
  2526. /*
  2527. * Record layer functions
  2528. */
  2529. /*
  2530. * Write current record.
  2531. *
  2532. * Uses:
  2533. * - ssl->out_msgtype: type of the message (AppData, Handshake, Alert, CCS)
  2534. * - ssl->out_msglen: length of the record content (excl headers)
  2535. * - ssl->out_msg: record content
  2536. */
  2537. int mbedtls_ssl_write_record(mbedtls_ssl_context *ssl, int force_flush)
  2538. {
  2539. int ret, done = 0;
  2540. size_t len = ssl->out_msglen;
  2541. int flush = force_flush;
  2542. MBEDTLS_SSL_DEBUG_MSG(2, ("=> write record"));
  2543. if (!done) {
  2544. unsigned i;
  2545. size_t protected_record_size;
  2546. #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
  2547. size_t out_buf_len = ssl->out_buf_len;
  2548. #else
  2549. size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
  2550. #endif
  2551. /* Skip writing the record content type to after the encryption,
  2552. * as it may change when using the CID extension. */
  2553. mbedtls_ssl_protocol_version tls_ver = ssl->tls_version;
  2554. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  2555. /* TLS 1.3 still uses the TLS 1.2 version identifier
  2556. * for backwards compatibility. */
  2557. if (tls_ver == MBEDTLS_SSL_VERSION_TLS1_3) {
  2558. tls_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  2559. }
  2560. #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
  2561. mbedtls_ssl_write_version(ssl->out_hdr + 1, ssl->conf->transport,
  2562. tls_ver);
  2563. memcpy(ssl->out_ctr, ssl->cur_out_ctr, MBEDTLS_SSL_SEQUENCE_NUMBER_LEN);
  2564. MBEDTLS_PUT_UINT16_BE(len, ssl->out_len, 0);
  2565. if (ssl->transform_out != NULL) {
  2566. mbedtls_record rec;
  2567. rec.buf = ssl->out_iv;
  2568. rec.buf_len = out_buf_len - (size_t) (ssl->out_iv - ssl->out_buf);
  2569. rec.data_len = ssl->out_msglen;
  2570. rec.data_offset = (size_t) (ssl->out_msg - rec.buf);
  2571. memcpy(&rec.ctr[0], ssl->out_ctr, sizeof(rec.ctr));
  2572. mbedtls_ssl_write_version(rec.ver, ssl->conf->transport, tls_ver);
  2573. rec.type = ssl->out_msgtype;
  2574. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  2575. /* The CID is set by mbedtls_ssl_encrypt_buf(). */
  2576. rec.cid_len = 0;
  2577. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  2578. if ((ret = mbedtls_ssl_encrypt_buf(ssl, ssl->transform_out, &rec,
  2579. ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
  2580. MBEDTLS_SSL_DEBUG_RET(1, "ssl_encrypt_buf", ret);
  2581. return ret;
  2582. }
  2583. if (rec.data_offset != 0) {
  2584. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  2585. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  2586. }
  2587. /* Update the record content type and CID. */
  2588. ssl->out_msgtype = rec.type;
  2589. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  2590. memcpy(ssl->out_cid, rec.cid, rec.cid_len);
  2591. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  2592. ssl->out_msglen = len = rec.data_len;
  2593. MBEDTLS_PUT_UINT16_BE(rec.data_len, ssl->out_len, 0);
  2594. }
  2595. protected_record_size = len + mbedtls_ssl_out_hdr_len(ssl);
  2596. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2597. /* In case of DTLS, double-check that we don't exceed
  2598. * the remaining space in the datagram. */
  2599. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  2600. ret = ssl_get_remaining_space_in_datagram(ssl);
  2601. if (ret < 0) {
  2602. return ret;
  2603. }
  2604. if (protected_record_size > (size_t) ret) {
  2605. /* Should never happen */
  2606. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  2607. }
  2608. }
  2609. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  2610. /* Now write the potentially updated record content type. */
  2611. ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
  2612. MBEDTLS_SSL_DEBUG_MSG(3, ("output record: msgtype = %u, "
  2613. "version = [%u:%u], msglen = %" MBEDTLS_PRINTF_SIZET,
  2614. ssl->out_hdr[0], ssl->out_hdr[1],
  2615. ssl->out_hdr[2], len));
  2616. MBEDTLS_SSL_DEBUG_BUF(4, "output record sent to network",
  2617. ssl->out_hdr, protected_record_size);
  2618. ssl->out_left += protected_record_size;
  2619. ssl->out_hdr += protected_record_size;
  2620. mbedtls_ssl_update_out_pointers(ssl, ssl->transform_out);
  2621. for (i = 8; i > mbedtls_ssl_ep_len(ssl); i--) {
  2622. if (++ssl->cur_out_ctr[i - 1] != 0) {
  2623. break;
  2624. }
  2625. }
  2626. /* The loop goes to its end if the counter is wrapping */
  2627. if (i == mbedtls_ssl_ep_len(ssl)) {
  2628. MBEDTLS_SSL_DEBUG_MSG(1, ("outgoing message counter would wrap"));
  2629. return MBEDTLS_ERR_SSL_COUNTER_WRAPPING;
  2630. }
  2631. }
  2632. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2633. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  2634. flush == SSL_DONT_FORCE_FLUSH) {
  2635. size_t remaining;
  2636. ret = ssl_get_remaining_payload_in_datagram(ssl);
  2637. if (ret < 0) {
  2638. MBEDTLS_SSL_DEBUG_RET(1, "ssl_get_remaining_payload_in_datagram",
  2639. ret);
  2640. return ret;
  2641. }
  2642. remaining = (size_t) ret;
  2643. if (remaining == 0) {
  2644. flush = SSL_FORCE_FLUSH;
  2645. } else {
  2646. MBEDTLS_SSL_DEBUG_MSG(2,
  2647. ("Still %u bytes available in current datagram",
  2648. (unsigned) remaining));
  2649. }
  2650. }
  2651. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  2652. if ((flush == SSL_FORCE_FLUSH) &&
  2653. (ret = mbedtls_ssl_flush_output(ssl)) != 0) {
  2654. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flush_output", ret);
  2655. return ret;
  2656. }
  2657. MBEDTLS_SSL_DEBUG_MSG(2, ("<= write record"));
  2658. return 0;
  2659. }
  2660. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2661. MBEDTLS_CHECK_RETURN_CRITICAL
  2662. static int ssl_hs_is_proper_fragment(mbedtls_ssl_context *ssl)
  2663. {
  2664. if (ssl->in_msglen < ssl->in_hslen ||
  2665. memcmp(ssl->in_msg + 6, "\0\0\0", 3) != 0 ||
  2666. memcmp(ssl->in_msg + 9, ssl->in_msg + 1, 3) != 0) {
  2667. return 1;
  2668. }
  2669. return 0;
  2670. }
  2671. static uint32_t ssl_get_hs_frag_len(mbedtls_ssl_context const *ssl)
  2672. {
  2673. return MBEDTLS_GET_UINT24_BE(ssl->in_msg, 9);
  2674. }
  2675. static uint32_t ssl_get_hs_frag_off(mbedtls_ssl_context const *ssl)
  2676. {
  2677. return MBEDTLS_GET_UINT24_BE(ssl->in_msg, 6);
  2678. }
  2679. MBEDTLS_CHECK_RETURN_CRITICAL
  2680. static int ssl_check_hs_header(mbedtls_ssl_context const *ssl)
  2681. {
  2682. uint32_t msg_len, frag_off, frag_len;
  2683. msg_len = ssl_get_hs_total_len(ssl);
  2684. frag_off = ssl_get_hs_frag_off(ssl);
  2685. frag_len = ssl_get_hs_frag_len(ssl);
  2686. if (frag_off > msg_len) {
  2687. return -1;
  2688. }
  2689. if (frag_len > msg_len - frag_off) {
  2690. return -1;
  2691. }
  2692. if (frag_len + 12 > ssl->in_msglen) {
  2693. return -1;
  2694. }
  2695. return 0;
  2696. }
  2697. /*
  2698. * Mark bits in bitmask (used for DTLS HS reassembly)
  2699. */
  2700. static void ssl_bitmask_set(unsigned char *mask, size_t offset, size_t len)
  2701. {
  2702. unsigned int start_bits, end_bits;
  2703. start_bits = 8 - (offset % 8);
  2704. if (start_bits != 8) {
  2705. size_t first_byte_idx = offset / 8;
  2706. /* Special case */
  2707. if (len <= start_bits) {
  2708. for (; len != 0; len--) {
  2709. mask[first_byte_idx] |= 1 << (start_bits - len);
  2710. }
  2711. /* Avoid potential issues with offset or len becoming invalid */
  2712. return;
  2713. }
  2714. offset += start_bits; /* Now offset % 8 == 0 */
  2715. len -= start_bits;
  2716. for (; start_bits != 0; start_bits--) {
  2717. mask[first_byte_idx] |= 1 << (start_bits - 1);
  2718. }
  2719. }
  2720. end_bits = len % 8;
  2721. if (end_bits != 0) {
  2722. size_t last_byte_idx = (offset + len) / 8;
  2723. len -= end_bits; /* Now len % 8 == 0 */
  2724. for (; end_bits != 0; end_bits--) {
  2725. mask[last_byte_idx] |= 1 << (8 - end_bits);
  2726. }
  2727. }
  2728. memset(mask + offset / 8, 0xFF, len / 8);
  2729. }
  2730. /*
  2731. * Check that bitmask is full
  2732. */
  2733. MBEDTLS_CHECK_RETURN_CRITICAL
  2734. static int ssl_bitmask_check(unsigned char *mask, size_t len)
  2735. {
  2736. size_t i;
  2737. for (i = 0; i < len / 8; i++) {
  2738. if (mask[i] != 0xFF) {
  2739. return -1;
  2740. }
  2741. }
  2742. for (i = 0; i < len % 8; i++) {
  2743. if ((mask[len / 8] & (1 << (7 - i))) == 0) {
  2744. return -1;
  2745. }
  2746. }
  2747. return 0;
  2748. }
  2749. /* msg_len does not include the handshake header */
  2750. static size_t ssl_get_reassembly_buffer_size(size_t msg_len,
  2751. unsigned add_bitmap)
  2752. {
  2753. size_t alloc_len;
  2754. alloc_len = 12; /* Handshake header */
  2755. alloc_len += msg_len; /* Content buffer */
  2756. if (add_bitmap) {
  2757. alloc_len += msg_len / 8 + (msg_len % 8 != 0); /* Bitmap */
  2758. }
  2759. return alloc_len;
  2760. }
  2761. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  2762. static uint32_t ssl_get_hs_total_len(mbedtls_ssl_context const *ssl)
  2763. {
  2764. return MBEDTLS_GET_UINT24_BE(ssl->in_msg, 1);
  2765. }
  2766. int mbedtls_ssl_prepare_handshake_record(mbedtls_ssl_context *ssl)
  2767. {
  2768. if (ssl->in_msglen < mbedtls_ssl_hs_hdr_len(ssl)) {
  2769. MBEDTLS_SSL_DEBUG_MSG(1, ("handshake message too short: %" MBEDTLS_PRINTF_SIZET,
  2770. ssl->in_msglen));
  2771. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  2772. }
  2773. ssl->in_hslen = mbedtls_ssl_hs_hdr_len(ssl) + ssl_get_hs_total_len(ssl);
  2774. MBEDTLS_SSL_DEBUG_MSG(3, ("handshake message: msglen ="
  2775. " %" MBEDTLS_PRINTF_SIZET ", type = %u, hslen = %"
  2776. MBEDTLS_PRINTF_SIZET,
  2777. ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen));
  2778. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2779. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  2780. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2781. unsigned int recv_msg_seq = MBEDTLS_GET_UINT16_BE(ssl->in_msg, 4);
  2782. if (ssl_check_hs_header(ssl) != 0) {
  2783. MBEDTLS_SSL_DEBUG_MSG(1, ("invalid handshake header"));
  2784. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  2785. }
  2786. if (ssl->handshake != NULL &&
  2787. ((mbedtls_ssl_is_handshake_over(ssl) == 0 &&
  2788. recv_msg_seq != ssl->handshake->in_msg_seq) ||
  2789. (mbedtls_ssl_is_handshake_over(ssl) == 1 &&
  2790. ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO))) {
  2791. if (recv_msg_seq > ssl->handshake->in_msg_seq) {
  2792. MBEDTLS_SSL_DEBUG_MSG(2,
  2793. (
  2794. "received future handshake message of sequence number %u (next %u)",
  2795. recv_msg_seq,
  2796. ssl->handshake->in_msg_seq));
  2797. return MBEDTLS_ERR_SSL_EARLY_MESSAGE;
  2798. }
  2799. /* Retransmit only on last message from previous flight, to avoid
  2800. * too many retransmissions.
  2801. * Besides, No sane server ever retransmits HelloVerifyRequest */
  2802. if (recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 &&
  2803. ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST) {
  2804. MBEDTLS_SSL_DEBUG_MSG(2, ("received message from last flight, "
  2805. "message_seq = %u, start_of_flight = %u",
  2806. recv_msg_seq,
  2807. ssl->handshake->in_flight_start_seq));
  2808. if ((ret = mbedtls_ssl_resend(ssl)) != 0) {
  2809. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_resend", ret);
  2810. return ret;
  2811. }
  2812. } else {
  2813. MBEDTLS_SSL_DEBUG_MSG(2, ("dropping out-of-sequence message: "
  2814. "message_seq = %u, expected = %u",
  2815. recv_msg_seq,
  2816. ssl->handshake->in_msg_seq));
  2817. }
  2818. return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
  2819. }
  2820. /* Wait until message completion to increment in_msg_seq */
  2821. /* Message reassembly is handled alongside buffering of future
  2822. * messages; the commonality is that both handshake fragments and
  2823. * future messages cannot be forwarded immediately to the
  2824. * handshake logic layer. */
  2825. if (ssl_hs_is_proper_fragment(ssl) == 1) {
  2826. MBEDTLS_SSL_DEBUG_MSG(2, ("found fragmented DTLS handshake message"));
  2827. return MBEDTLS_ERR_SSL_EARLY_MESSAGE;
  2828. }
  2829. } else
  2830. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  2831. /* With TLS we don't handle fragmentation (for now) */
  2832. if (ssl->in_msglen < ssl->in_hslen) {
  2833. MBEDTLS_SSL_DEBUG_MSG(1, ("TLS handshake fragmentation not supported"));
  2834. return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
  2835. }
  2836. return 0;
  2837. }
  2838. int mbedtls_ssl_update_handshake_status(mbedtls_ssl_context *ssl)
  2839. {
  2840. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2841. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  2842. if (mbedtls_ssl_is_handshake_over(ssl) == 0 && hs != NULL) {
  2843. ret = ssl->handshake->update_checksum(ssl, ssl->in_msg, ssl->in_hslen);
  2844. if (ret != 0) {
  2845. MBEDTLS_SSL_DEBUG_RET(1, "update_checksum", ret);
  2846. return ret;
  2847. }
  2848. }
  2849. /* Handshake message is complete, increment counter */
  2850. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2851. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  2852. ssl->handshake != NULL) {
  2853. unsigned offset;
  2854. mbedtls_ssl_hs_buffer *hs_buf;
  2855. /* Increment handshake sequence number */
  2856. hs->in_msg_seq++;
  2857. /*
  2858. * Clear up handshake buffering and reassembly structure.
  2859. */
  2860. /* Free first entry */
  2861. ssl_buffering_free_slot(ssl, 0);
  2862. /* Shift all other entries */
  2863. for (offset = 0, hs_buf = &hs->buffering.hs[0];
  2864. offset + 1 < MBEDTLS_SSL_MAX_BUFFERED_HS;
  2865. offset++, hs_buf++) {
  2866. *hs_buf = *(hs_buf + 1);
  2867. }
  2868. /* Create a fresh last entry */
  2869. memset(hs_buf, 0, sizeof(mbedtls_ssl_hs_buffer));
  2870. }
  2871. #endif
  2872. return 0;
  2873. }
  2874. /*
  2875. * DTLS anti-replay: RFC 6347 4.1.2.6
  2876. *
  2877. * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).
  2878. * Bit n is set iff record number in_window_top - n has been seen.
  2879. *
  2880. * Usually, in_window_top is the last record number seen and the lsb of
  2881. * in_window is set. The only exception is the initial state (record number 0
  2882. * not seen yet).
  2883. */
  2884. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  2885. void mbedtls_ssl_dtls_replay_reset(mbedtls_ssl_context *ssl)
  2886. {
  2887. ssl->in_window_top = 0;
  2888. ssl->in_window = 0;
  2889. }
  2890. static inline uint64_t ssl_load_six_bytes(unsigned char *buf)
  2891. {
  2892. return ((uint64_t) buf[0] << 40) |
  2893. ((uint64_t) buf[1] << 32) |
  2894. ((uint64_t) buf[2] << 24) |
  2895. ((uint64_t) buf[3] << 16) |
  2896. ((uint64_t) buf[4] << 8) |
  2897. ((uint64_t) buf[5]);
  2898. }
  2899. MBEDTLS_CHECK_RETURN_CRITICAL
  2900. static int mbedtls_ssl_dtls_record_replay_check(mbedtls_ssl_context *ssl, uint8_t *record_in_ctr)
  2901. {
  2902. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2903. unsigned char *original_in_ctr;
  2904. // save original in_ctr
  2905. original_in_ctr = ssl->in_ctr;
  2906. // use counter from record
  2907. ssl->in_ctr = record_in_ctr;
  2908. ret = mbedtls_ssl_dtls_replay_check((mbedtls_ssl_context const *) ssl);
  2909. // restore the counter
  2910. ssl->in_ctr = original_in_ctr;
  2911. return ret;
  2912. }
  2913. /*
  2914. * Return 0 if sequence number is acceptable, -1 otherwise
  2915. */
  2916. int mbedtls_ssl_dtls_replay_check(mbedtls_ssl_context const *ssl)
  2917. {
  2918. uint64_t rec_seqnum = ssl_load_six_bytes(ssl->in_ctr + 2);
  2919. uint64_t bit;
  2920. if (ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED) {
  2921. return 0;
  2922. }
  2923. if (rec_seqnum > ssl->in_window_top) {
  2924. return 0;
  2925. }
  2926. bit = ssl->in_window_top - rec_seqnum;
  2927. if (bit >= 64) {
  2928. return -1;
  2929. }
  2930. if ((ssl->in_window & ((uint64_t) 1 << bit)) != 0) {
  2931. return -1;
  2932. }
  2933. return 0;
  2934. }
  2935. /*
  2936. * Update replay window on new validated record
  2937. */
  2938. void mbedtls_ssl_dtls_replay_update(mbedtls_ssl_context *ssl)
  2939. {
  2940. uint64_t rec_seqnum = ssl_load_six_bytes(ssl->in_ctr + 2);
  2941. if (ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED) {
  2942. return;
  2943. }
  2944. if (rec_seqnum > ssl->in_window_top) {
  2945. /* Update window_top and the contents of the window */
  2946. uint64_t shift = rec_seqnum - ssl->in_window_top;
  2947. if (shift >= 64) {
  2948. ssl->in_window = 1;
  2949. } else {
  2950. ssl->in_window <<= shift;
  2951. ssl->in_window |= 1;
  2952. }
  2953. ssl->in_window_top = rec_seqnum;
  2954. } else {
  2955. /* Mark that number as seen in the current window */
  2956. uint64_t bit = ssl->in_window_top - rec_seqnum;
  2957. if (bit < 64) { /* Always true, but be extra sure */
  2958. ssl->in_window |= (uint64_t) 1 << bit;
  2959. }
  2960. }
  2961. }
  2962. #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
  2963. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
  2964. /*
  2965. * Check if a datagram looks like a ClientHello with a valid cookie,
  2966. * and if it doesn't, generate a HelloVerifyRequest message.
  2967. * Both input and output include full DTLS headers.
  2968. *
  2969. * - if cookie is valid, return 0
  2970. * - if ClientHello looks superficially valid but cookie is not,
  2971. * fill obuf and set olen, then
  2972. * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
  2973. * - otherwise return a specific error code
  2974. */
  2975. MBEDTLS_CHECK_RETURN_CRITICAL
  2976. MBEDTLS_STATIC_TESTABLE
  2977. int mbedtls_ssl_check_dtls_clihlo_cookie(
  2978. mbedtls_ssl_context *ssl,
  2979. const unsigned char *cli_id, size_t cli_id_len,
  2980. const unsigned char *in, size_t in_len,
  2981. unsigned char *obuf, size_t buf_len, size_t *olen)
  2982. {
  2983. size_t sid_len, cookie_len, epoch, fragment_offset;
  2984. unsigned char *p;
  2985. /*
  2986. * Structure of ClientHello with record and handshake headers,
  2987. * and expected values. We don't need to check a lot, more checks will be
  2988. * done when actually parsing the ClientHello - skipping those checks
  2989. * avoids code duplication and does not make cookie forging any easier.
  2990. *
  2991. * 0-0 ContentType type; copied, must be handshake
  2992. * 1-2 ProtocolVersion version; copied
  2993. * 3-4 uint16 epoch; copied, must be 0
  2994. * 5-10 uint48 sequence_number; copied
  2995. * 11-12 uint16 length; (ignored)
  2996. *
  2997. * 13-13 HandshakeType msg_type; (ignored)
  2998. * 14-16 uint24 length; (ignored)
  2999. * 17-18 uint16 message_seq; copied
  3000. * 19-21 uint24 fragment_offset; copied, must be 0
  3001. * 22-24 uint24 fragment_length; (ignored)
  3002. *
  3003. * 25-26 ProtocolVersion client_version; (ignored)
  3004. * 27-58 Random random; (ignored)
  3005. * 59-xx SessionID session_id; 1 byte len + sid_len content
  3006. * 60+ opaque cookie<0..2^8-1>; 1 byte len + content
  3007. * ...
  3008. *
  3009. * Minimum length is 61 bytes.
  3010. */
  3011. MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: in_len=%u",
  3012. (unsigned) in_len));
  3013. MBEDTLS_SSL_DEBUG_BUF(4, "cli_id", cli_id, cli_id_len);
  3014. if (in_len < 61) {
  3015. MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: record too short"));
  3016. return MBEDTLS_ERR_SSL_DECODE_ERROR;
  3017. }
  3018. epoch = MBEDTLS_GET_UINT16_BE(in, 3);
  3019. fragment_offset = MBEDTLS_GET_UINT24_BE(in, 19);
  3020. if (in[0] != MBEDTLS_SSL_MSG_HANDSHAKE || epoch != 0 ||
  3021. fragment_offset != 0) {
  3022. MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: not a good ClientHello"));
  3023. MBEDTLS_SSL_DEBUG_MSG(4, (" type=%u epoch=%u fragment_offset=%u",
  3024. in[0], (unsigned) epoch,
  3025. (unsigned) fragment_offset));
  3026. return MBEDTLS_ERR_SSL_DECODE_ERROR;
  3027. }
  3028. sid_len = in[59];
  3029. if (59 + 1 + sid_len + 1 > in_len) {
  3030. MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: sid_len=%u > %u",
  3031. (unsigned) sid_len,
  3032. (unsigned) in_len - 61));
  3033. return MBEDTLS_ERR_SSL_DECODE_ERROR;
  3034. }
  3035. MBEDTLS_SSL_DEBUG_BUF(4, "sid received from network",
  3036. in + 60, sid_len);
  3037. cookie_len = in[60 + sid_len];
  3038. if (59 + 1 + sid_len + 1 + cookie_len > in_len) {
  3039. MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: cookie_len=%u > %u",
  3040. (unsigned) cookie_len,
  3041. (unsigned) (in_len - sid_len - 61)));
  3042. return MBEDTLS_ERR_SSL_DECODE_ERROR;
  3043. }
  3044. MBEDTLS_SSL_DEBUG_BUF(4, "cookie received from network",
  3045. in + sid_len + 61, cookie_len);
  3046. if (ssl->conf->f_cookie_check(ssl->conf->p_cookie,
  3047. in + sid_len + 61, cookie_len,
  3048. cli_id, cli_id_len) == 0) {
  3049. MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: valid"));
  3050. return 0;
  3051. }
  3052. /*
  3053. * If we get here, we've got an invalid cookie, let's prepare HVR.
  3054. *
  3055. * 0-0 ContentType type; copied
  3056. * 1-2 ProtocolVersion version; copied
  3057. * 3-4 uint16 epoch; copied
  3058. * 5-10 uint48 sequence_number; copied
  3059. * 11-12 uint16 length; olen - 13
  3060. *
  3061. * 13-13 HandshakeType msg_type; hello_verify_request
  3062. * 14-16 uint24 length; olen - 25
  3063. * 17-18 uint16 message_seq; copied
  3064. * 19-21 uint24 fragment_offset; copied
  3065. * 22-24 uint24 fragment_length; olen - 25
  3066. *
  3067. * 25-26 ProtocolVersion server_version; 0xfe 0xff
  3068. * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie
  3069. *
  3070. * Minimum length is 28.
  3071. */
  3072. if (buf_len < 28) {
  3073. return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
  3074. }
  3075. /* Copy most fields and adapt others */
  3076. memcpy(obuf, in, 25);
  3077. obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
  3078. obuf[25] = 0xfe;
  3079. obuf[26] = 0xff;
  3080. /* Generate and write actual cookie */
  3081. p = obuf + 28;
  3082. if (ssl->conf->f_cookie_write(ssl->conf->p_cookie,
  3083. &p, obuf + buf_len,
  3084. cli_id, cli_id_len) != 0) {
  3085. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  3086. }
  3087. *olen = (size_t) (p - obuf);
  3088. /* Go back and fill length fields */
  3089. obuf[27] = (unsigned char) (*olen - 28);
  3090. obuf[14] = obuf[22] = MBEDTLS_BYTE_2(*olen - 25);
  3091. obuf[15] = obuf[23] = MBEDTLS_BYTE_1(*olen - 25);
  3092. obuf[16] = obuf[24] = MBEDTLS_BYTE_0(*olen - 25);
  3093. MBEDTLS_PUT_UINT16_BE(*olen - 13, obuf, 11);
  3094. return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED;
  3095. }
  3096. /*
  3097. * Handle possible client reconnect with the same UDP quadruplet
  3098. * (RFC 6347 Section 4.2.8).
  3099. *
  3100. * Called by ssl_parse_record_header() in case we receive an epoch 0 record
  3101. * that looks like a ClientHello.
  3102. *
  3103. * - if the input looks like a ClientHello without cookies,
  3104. * send back HelloVerifyRequest, then return 0
  3105. * - if the input looks like a ClientHello with a valid cookie,
  3106. * reset the session of the current context, and
  3107. * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT
  3108. * - if anything goes wrong, return a specific error code
  3109. *
  3110. * This function is called (through ssl_check_client_reconnect()) when an
  3111. * unexpected record is found in ssl_get_next_record(), which will discard the
  3112. * record if we return 0, and bubble up the return value otherwise (this
  3113. * includes the case of MBEDTLS_ERR_SSL_CLIENT_RECONNECT and of unexpected
  3114. * errors, and is the right thing to do in both cases).
  3115. */
  3116. MBEDTLS_CHECK_RETURN_CRITICAL
  3117. static int ssl_handle_possible_reconnect(mbedtls_ssl_context *ssl)
  3118. {
  3119. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  3120. size_t len = 0;
  3121. if (ssl->conf->f_cookie_write == NULL ||
  3122. ssl->conf->f_cookie_check == NULL) {
  3123. /* If we can't use cookies to verify reachability of the peer,
  3124. * drop the record. */
  3125. MBEDTLS_SSL_DEBUG_MSG(1, ("no cookie callbacks, "
  3126. "can't check reconnect validity"));
  3127. return 0;
  3128. }
  3129. ret = mbedtls_ssl_check_dtls_clihlo_cookie(
  3130. ssl,
  3131. ssl->cli_id, ssl->cli_id_len,
  3132. ssl->in_buf, ssl->in_left,
  3133. ssl->out_buf, MBEDTLS_SSL_OUT_CONTENT_LEN, &len);
  3134. MBEDTLS_SSL_DEBUG_RET(2, "mbedtls_ssl_check_dtls_clihlo_cookie", ret);
  3135. if (ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) {
  3136. int send_ret;
  3137. MBEDTLS_SSL_DEBUG_MSG(1, ("sending HelloVerifyRequest"));
  3138. MBEDTLS_SSL_DEBUG_BUF(4, "output record sent to network",
  3139. ssl->out_buf, len);
  3140. /* Don't check write errors as we can't do anything here.
  3141. * If the error is permanent we'll catch it later,
  3142. * if it's not, then hopefully it'll work next time. */
  3143. send_ret = ssl->f_send(ssl->p_bio, ssl->out_buf, len);
  3144. MBEDTLS_SSL_DEBUG_RET(2, "ssl->f_send", send_ret);
  3145. (void) send_ret;
  3146. return 0;
  3147. }
  3148. if (ret == 0) {
  3149. MBEDTLS_SSL_DEBUG_MSG(1, ("cookie is valid, resetting context"));
  3150. if ((ret = mbedtls_ssl_session_reset_int(ssl, 1)) != 0) {
  3151. MBEDTLS_SSL_DEBUG_RET(1, "reset", ret);
  3152. return ret;
  3153. }
  3154. return MBEDTLS_ERR_SSL_CLIENT_RECONNECT;
  3155. }
  3156. return ret;
  3157. }
  3158. #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
  3159. MBEDTLS_CHECK_RETURN_CRITICAL
  3160. static int ssl_check_record_type(uint8_t record_type)
  3161. {
  3162. if (record_type != MBEDTLS_SSL_MSG_HANDSHAKE &&
  3163. record_type != MBEDTLS_SSL_MSG_ALERT &&
  3164. record_type != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
  3165. record_type != MBEDTLS_SSL_MSG_APPLICATION_DATA) {
  3166. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  3167. }
  3168. return 0;
  3169. }
  3170. /*
  3171. * ContentType type;
  3172. * ProtocolVersion version;
  3173. * uint16 epoch; // DTLS only
  3174. * uint48 sequence_number; // DTLS only
  3175. * uint16 length;
  3176. *
  3177. * Return 0 if header looks sane (and, for DTLS, the record is expected)
  3178. * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad,
  3179. * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected.
  3180. *
  3181. * With DTLS, mbedtls_ssl_read_record() will:
  3182. * 1. proceed with the record if this function returns 0
  3183. * 2. drop only the current record if this function returns UNEXPECTED_RECORD
  3184. * 3. return CLIENT_RECONNECT if this function return that value
  3185. * 4. drop the whole datagram if this function returns anything else.
  3186. * Point 2 is needed when the peer is resending, and we have already received
  3187. * the first record from a datagram but are still waiting for the others.
  3188. */
  3189. MBEDTLS_CHECK_RETURN_CRITICAL
  3190. static int ssl_parse_record_header(mbedtls_ssl_context const *ssl,
  3191. unsigned char *buf,
  3192. size_t len,
  3193. mbedtls_record *rec)
  3194. {
  3195. mbedtls_ssl_protocol_version tls_version;
  3196. size_t const rec_hdr_type_offset = 0;
  3197. size_t const rec_hdr_type_len = 1;
  3198. size_t const rec_hdr_version_offset = rec_hdr_type_offset +
  3199. rec_hdr_type_len;
  3200. size_t const rec_hdr_version_len = 2;
  3201. size_t const rec_hdr_ctr_len = 8;
  3202. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3203. uint32_t rec_epoch;
  3204. size_t const rec_hdr_ctr_offset = rec_hdr_version_offset +
  3205. rec_hdr_version_len;
  3206. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  3207. size_t const rec_hdr_cid_offset = rec_hdr_ctr_offset +
  3208. rec_hdr_ctr_len;
  3209. size_t rec_hdr_cid_len = 0;
  3210. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  3211. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3212. size_t rec_hdr_len_offset; /* To be determined */
  3213. size_t const rec_hdr_len_len = 2;
  3214. /*
  3215. * Check minimum lengths for record header.
  3216. */
  3217. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3218. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  3219. rec_hdr_len_offset = rec_hdr_ctr_offset + rec_hdr_ctr_len;
  3220. } else
  3221. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3222. {
  3223. rec_hdr_len_offset = rec_hdr_version_offset + rec_hdr_version_len;
  3224. }
  3225. if (len < rec_hdr_len_offset + rec_hdr_len_len) {
  3226. MBEDTLS_SSL_DEBUG_MSG(1,
  3227. (
  3228. "datagram of length %u too small to hold DTLS record header of length %u",
  3229. (unsigned) len,
  3230. (unsigned) (rec_hdr_len_len + rec_hdr_len_len)));
  3231. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  3232. }
  3233. /*
  3234. * Parse and validate record content type
  3235. */
  3236. rec->type = buf[rec_hdr_type_offset];
  3237. /* Check record content type */
  3238. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  3239. rec->cid_len = 0;
  3240. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  3241. ssl->conf->cid_len != 0 &&
  3242. rec->type == MBEDTLS_SSL_MSG_CID) {
  3243. /* Shift pointers to account for record header including CID
  3244. * struct {
  3245. * ContentType outer_type = tls12_cid;
  3246. * ProtocolVersion version;
  3247. * uint16 epoch;
  3248. * uint48 sequence_number;
  3249. * opaque cid[cid_length]; // Additional field compared to
  3250. * // default DTLS record format
  3251. * uint16 length;
  3252. * opaque enc_content[DTLSCiphertext.length];
  3253. * } DTLSCiphertext;
  3254. */
  3255. /* So far, we only support static CID lengths
  3256. * fixed in the configuration. */
  3257. rec_hdr_cid_len = ssl->conf->cid_len;
  3258. rec_hdr_len_offset += rec_hdr_cid_len;
  3259. if (len < rec_hdr_len_offset + rec_hdr_len_len) {
  3260. MBEDTLS_SSL_DEBUG_MSG(1,
  3261. (
  3262. "datagram of length %u too small to hold DTLS record header including CID, length %u",
  3263. (unsigned) len,
  3264. (unsigned) (rec_hdr_len_offset + rec_hdr_len_len)));
  3265. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  3266. }
  3267. /* configured CID len is guaranteed at most 255, see
  3268. * MBEDTLS_SSL_CID_OUT_LEN_MAX in check_config.h */
  3269. rec->cid_len = (uint8_t) rec_hdr_cid_len;
  3270. memcpy(rec->cid, buf + rec_hdr_cid_offset, rec_hdr_cid_len);
  3271. } else
  3272. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  3273. {
  3274. if (ssl_check_record_type(rec->type)) {
  3275. MBEDTLS_SSL_DEBUG_MSG(1, ("unknown record type %u",
  3276. (unsigned) rec->type));
  3277. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  3278. }
  3279. }
  3280. /*
  3281. * Parse and validate record version
  3282. */
  3283. rec->ver[0] = buf[rec_hdr_version_offset + 0];
  3284. rec->ver[1] = buf[rec_hdr_version_offset + 1];
  3285. tls_version = (mbedtls_ssl_protocol_version) mbedtls_ssl_read_version(
  3286. buf + rec_hdr_version_offset,
  3287. ssl->conf->transport);
  3288. if (tls_version > ssl->conf->max_tls_version) {
  3289. MBEDTLS_SSL_DEBUG_MSG(1, ("TLS version mismatch: got %u, expected max %u",
  3290. (unsigned) tls_version,
  3291. (unsigned) ssl->conf->max_tls_version));
  3292. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  3293. }
  3294. /*
  3295. * Parse/Copy record sequence number.
  3296. */
  3297. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3298. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  3299. /* Copy explicit record sequence number from input buffer. */
  3300. memcpy(&rec->ctr[0], buf + rec_hdr_ctr_offset,
  3301. rec_hdr_ctr_len);
  3302. } else
  3303. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3304. {
  3305. /* Copy implicit record sequence number from SSL context structure. */
  3306. memcpy(&rec->ctr[0], ssl->in_ctr, rec_hdr_ctr_len);
  3307. }
  3308. /*
  3309. * Parse record length.
  3310. */
  3311. rec->data_offset = rec_hdr_len_offset + rec_hdr_len_len;
  3312. rec->data_len = MBEDTLS_GET_UINT16_BE(buf, rec_hdr_len_offset);
  3313. MBEDTLS_SSL_DEBUG_BUF(4, "input record header", buf, rec->data_offset);
  3314. MBEDTLS_SSL_DEBUG_MSG(3, ("input record: msgtype = %u, "
  3315. "version = [0x%x], msglen = %" MBEDTLS_PRINTF_SIZET,
  3316. rec->type, (unsigned) tls_version, rec->data_len));
  3317. rec->buf = buf;
  3318. rec->buf_len = rec->data_offset + rec->data_len;
  3319. if (rec->data_len == 0) {
  3320. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  3321. }
  3322. /*
  3323. * DTLS-related tests.
  3324. * Check epoch before checking length constraint because
  3325. * the latter varies with the epoch. E.g., if a ChangeCipherSpec
  3326. * message gets duplicated before the corresponding Finished message,
  3327. * the second ChangeCipherSpec should be discarded because it belongs
  3328. * to an old epoch, but not because its length is shorter than
  3329. * the minimum record length for packets using the new record transform.
  3330. * Note that these two kinds of failures are handled differently,
  3331. * as an unexpected record is silently skipped but an invalid
  3332. * record leads to the entire datagram being dropped.
  3333. */
  3334. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3335. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  3336. rec_epoch = MBEDTLS_GET_UINT16_BE(rec->ctr, 0);
  3337. /* Check that the datagram is large enough to contain a record
  3338. * of the advertised length. */
  3339. if (len < rec->data_offset + rec->data_len) {
  3340. MBEDTLS_SSL_DEBUG_MSG(1,
  3341. (
  3342. "Datagram of length %u too small to contain record of advertised length %u.",
  3343. (unsigned) len,
  3344. (unsigned) (rec->data_offset + rec->data_len)));
  3345. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  3346. }
  3347. /* Records from other, non-matching epochs are silently discarded.
  3348. * (The case of same-port Client reconnects must be considered in
  3349. * the caller). */
  3350. if (rec_epoch != ssl->in_epoch) {
  3351. MBEDTLS_SSL_DEBUG_MSG(1, ("record from another epoch: "
  3352. "expected %u, received %lu",
  3353. ssl->in_epoch, (unsigned long) rec_epoch));
  3354. /* Records from the next epoch are considered for buffering
  3355. * (concretely: early Finished messages). */
  3356. if (rec_epoch == (unsigned) ssl->in_epoch + 1) {
  3357. MBEDTLS_SSL_DEBUG_MSG(2, ("Consider record for buffering"));
  3358. return MBEDTLS_ERR_SSL_EARLY_MESSAGE;
  3359. }
  3360. return MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
  3361. }
  3362. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  3363. /* For records from the correct epoch, check whether their
  3364. * sequence number has been seen before. */
  3365. else if (mbedtls_ssl_dtls_record_replay_check((mbedtls_ssl_context *) ssl,
  3366. &rec->ctr[0]) != 0) {
  3367. MBEDTLS_SSL_DEBUG_MSG(1, ("replayed record"));
  3368. return MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
  3369. }
  3370. #endif
  3371. }
  3372. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3373. return 0;
  3374. }
  3375. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
  3376. MBEDTLS_CHECK_RETURN_CRITICAL
  3377. static int ssl_check_client_reconnect(mbedtls_ssl_context *ssl)
  3378. {
  3379. unsigned int rec_epoch = MBEDTLS_GET_UINT16_BE(ssl->in_ctr, 0);
  3380. /*
  3381. * Check for an epoch 0 ClientHello. We can't use in_msg here to
  3382. * access the first byte of record content (handshake type), as we
  3383. * have an active transform (possibly iv_len != 0), so use the
  3384. * fact that the record header len is 13 instead.
  3385. */
  3386. if (rec_epoch == 0 &&
  3387. ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  3388. mbedtls_ssl_is_handshake_over(ssl) == 1 &&
  3389. ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  3390. ssl->in_left > 13 &&
  3391. ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO) {
  3392. MBEDTLS_SSL_DEBUG_MSG(1, ("possible client reconnect "
  3393. "from the same port"));
  3394. return ssl_handle_possible_reconnect(ssl);
  3395. }
  3396. return 0;
  3397. }
  3398. #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
  3399. /*
  3400. * If applicable, decrypt record content
  3401. */
  3402. MBEDTLS_CHECK_RETURN_CRITICAL
  3403. static int ssl_prepare_record_content(mbedtls_ssl_context *ssl,
  3404. mbedtls_record *rec)
  3405. {
  3406. int ret, done = 0;
  3407. MBEDTLS_SSL_DEBUG_BUF(4, "input record from network",
  3408. rec->buf, rec->buf_len);
  3409. /*
  3410. * In TLS 1.3, always treat ChangeCipherSpec records
  3411. * as unencrypted. The only thing we do with them is
  3412. * check the length and content and ignore them.
  3413. */
  3414. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  3415. if (ssl->transform_in != NULL &&
  3416. ssl->transform_in->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
  3417. if (rec->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
  3418. done = 1;
  3419. }
  3420. }
  3421. #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
  3422. if (!done && ssl->transform_in != NULL) {
  3423. unsigned char const old_msg_type = rec->type;
  3424. if ((ret = mbedtls_ssl_decrypt_buf(ssl, ssl->transform_in,
  3425. rec)) != 0) {
  3426. MBEDTLS_SSL_DEBUG_RET(1, "ssl_decrypt_buf", ret);
  3427. #if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_SRV_C)
  3428. /*
  3429. * Although the server rejected early data, it might receive early
  3430. * data as long as it has not received the client Finished message.
  3431. * It is encrypted with early keys and should be ignored as stated
  3432. * in section 4.2.10 of RFC 8446:
  3433. *
  3434. * "Ignore the extension and return a regular 1-RTT response. The
  3435. * server then skips past early data by attempting to deprotect
  3436. * received records using the handshake traffic key, discarding
  3437. * records which fail deprotection (up to the configured
  3438. * max_early_data_size). Once a record is deprotected successfully,
  3439. * it is treated as the start of the client's second flight and the
  3440. * server proceeds as with an ordinary 1-RTT handshake."
  3441. */
  3442. if ((old_msg_type == MBEDTLS_SSL_MSG_APPLICATION_DATA) &&
  3443. (ssl->discard_early_data_record ==
  3444. MBEDTLS_SSL_EARLY_DATA_TRY_TO_DEPROTECT_AND_DISCARD)) {
  3445. MBEDTLS_SSL_DEBUG_MSG(
  3446. 3, ("EarlyData: deprotect and discard app data records."));
  3447. ret = mbedtls_ssl_tls13_check_early_data_len(ssl, rec->data_len);
  3448. if (ret != 0) {
  3449. return ret;
  3450. }
  3451. ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
  3452. }
  3453. #endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_SRV_C */
  3454. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  3455. if (ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID &&
  3456. ssl->conf->ignore_unexpected_cid
  3457. == MBEDTLS_SSL_UNEXPECTED_CID_IGNORE) {
  3458. MBEDTLS_SSL_DEBUG_MSG(3, ("ignoring unexpected CID"));
  3459. ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
  3460. }
  3461. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  3462. /*
  3463. * The decryption of the record failed, no reason to ignore it,
  3464. * return in error with the decryption error code.
  3465. */
  3466. return ret;
  3467. }
  3468. #if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_SRV_C)
  3469. /*
  3470. * If the server were discarding protected records that it fails to
  3471. * deprotect because it has rejected early data, as we have just
  3472. * deprotected successfully a record, the server has to resume normal
  3473. * operation and fail the connection if the deprotection of a record
  3474. * fails.
  3475. */
  3476. if (ssl->discard_early_data_record ==
  3477. MBEDTLS_SSL_EARLY_DATA_TRY_TO_DEPROTECT_AND_DISCARD) {
  3478. ssl->discard_early_data_record = MBEDTLS_SSL_EARLY_DATA_NO_DISCARD;
  3479. }
  3480. #endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_SRV_C */
  3481. if (old_msg_type != rec->type) {
  3482. MBEDTLS_SSL_DEBUG_MSG(4, ("record type after decrypt (before %d): %d",
  3483. old_msg_type, rec->type));
  3484. }
  3485. MBEDTLS_SSL_DEBUG_BUF(4, "input payload after decrypt",
  3486. rec->buf + rec->data_offset, rec->data_len);
  3487. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  3488. /* We have already checked the record content type
  3489. * in ssl_parse_record_header(), failing or silently
  3490. * dropping the record in the case of an unknown type.
  3491. *
  3492. * Since with the use of CIDs, the record content type
  3493. * might change during decryption, re-check the record
  3494. * content type, but treat a failure as fatal this time. */
  3495. if (ssl_check_record_type(rec->type)) {
  3496. MBEDTLS_SSL_DEBUG_MSG(1, ("unknown record type"));
  3497. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  3498. }
  3499. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  3500. if (rec->data_len == 0) {
  3501. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  3502. if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_2
  3503. && rec->type != MBEDTLS_SSL_MSG_APPLICATION_DATA) {
  3504. /* TLS v1.2 explicitly disallows zero-length messages which are not application data */
  3505. MBEDTLS_SSL_DEBUG_MSG(1, ("invalid zero-length message type: %d", ssl->in_msgtype));
  3506. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  3507. }
  3508. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  3509. ssl->nb_zero++;
  3510. /*
  3511. * Three or more empty messages may be a DoS attack
  3512. * (excessive CPU consumption).
  3513. */
  3514. if (ssl->nb_zero > 3) {
  3515. MBEDTLS_SSL_DEBUG_MSG(1, ("received four consecutive empty "
  3516. "messages, possible DoS attack"));
  3517. /* Treat the records as if they were not properly authenticated,
  3518. * thereby failing the connection if we see more than allowed
  3519. * by the configured bad MAC threshold. */
  3520. return MBEDTLS_ERR_SSL_INVALID_MAC;
  3521. }
  3522. } else {
  3523. ssl->nb_zero = 0;
  3524. }
  3525. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3526. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  3527. ; /* in_ctr read from peer, not maintained internally */
  3528. } else
  3529. #endif
  3530. {
  3531. unsigned i;
  3532. for (i = MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
  3533. i > mbedtls_ssl_ep_len(ssl); i--) {
  3534. if (++ssl->in_ctr[i - 1] != 0) {
  3535. break;
  3536. }
  3537. }
  3538. /* The loop goes to its end iff the counter is wrapping */
  3539. if (i == mbedtls_ssl_ep_len(ssl)) {
  3540. MBEDTLS_SSL_DEBUG_MSG(1, ("incoming message counter would wrap"));
  3541. return MBEDTLS_ERR_SSL_COUNTER_WRAPPING;
  3542. }
  3543. }
  3544. }
  3545. #if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_SRV_C)
  3546. /*
  3547. * Although the server rejected early data because it needed to send an
  3548. * HelloRetryRequest message, it might receive early data as long as it has
  3549. * not received the client Finished message.
  3550. * The early data is encrypted with early keys and should be ignored as
  3551. * stated in section 4.2.10 of RFC 8446 (second case):
  3552. *
  3553. * "The server then ignores early data by skipping all records with an
  3554. * external content type of "application_data" (indicating that they are
  3555. * encrypted), up to the configured max_early_data_size. Ignore application
  3556. * data message before 2nd ClientHello when early_data was received in 1st
  3557. * ClientHello."
  3558. */
  3559. if (ssl->discard_early_data_record == MBEDTLS_SSL_EARLY_DATA_DISCARD) {
  3560. if (rec->type == MBEDTLS_SSL_MSG_APPLICATION_DATA) {
  3561. ret = mbedtls_ssl_tls13_check_early_data_len(ssl, rec->data_len);
  3562. if (ret != 0) {
  3563. return ret;
  3564. }
  3565. MBEDTLS_SSL_DEBUG_MSG(
  3566. 3, ("EarlyData: Ignore application message before 2nd ClientHello"));
  3567. return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
  3568. } else if (rec->type == MBEDTLS_SSL_MSG_HANDSHAKE) {
  3569. ssl->discard_early_data_record = MBEDTLS_SSL_EARLY_DATA_NO_DISCARD;
  3570. }
  3571. }
  3572. #endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_SRV_C */
  3573. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  3574. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  3575. mbedtls_ssl_dtls_replay_update(ssl);
  3576. }
  3577. #endif
  3578. /* Check actual (decrypted) record content length against
  3579. * configured maximum. */
  3580. if (rec->data_len > MBEDTLS_SSL_IN_CONTENT_LEN) {
  3581. MBEDTLS_SSL_DEBUG_MSG(1, ("bad message length"));
  3582. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  3583. }
  3584. return 0;
  3585. }
  3586. /*
  3587. * Read a record.
  3588. *
  3589. * Silently ignore non-fatal alert (and for DTLS, invalid records as well,
  3590. * RFC 6347 4.1.2.7) and continue reading until a valid record is found.
  3591. *
  3592. */
  3593. /* Helper functions for mbedtls_ssl_read_record(). */
  3594. MBEDTLS_CHECK_RETURN_CRITICAL
  3595. static int ssl_consume_current_message(mbedtls_ssl_context *ssl);
  3596. MBEDTLS_CHECK_RETURN_CRITICAL
  3597. static int ssl_get_next_record(mbedtls_ssl_context *ssl);
  3598. MBEDTLS_CHECK_RETURN_CRITICAL
  3599. static int ssl_record_is_in_progress(mbedtls_ssl_context *ssl);
  3600. int mbedtls_ssl_read_record(mbedtls_ssl_context *ssl,
  3601. unsigned update_hs_digest)
  3602. {
  3603. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  3604. MBEDTLS_SSL_DEBUG_MSG(2, ("=> read record"));
  3605. if (ssl->keep_current_message == 0) {
  3606. do {
  3607. ret = ssl_consume_current_message(ssl);
  3608. if (ret != 0) {
  3609. return ret;
  3610. }
  3611. if (ssl_record_is_in_progress(ssl) == 0) {
  3612. int dtls_have_buffered = 0;
  3613. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3614. /* We only check for buffered messages if the
  3615. * current datagram is fully consumed. */
  3616. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  3617. ssl_next_record_is_in_datagram(ssl) == 0) {
  3618. if (ssl_load_buffered_message(ssl) == 0) {
  3619. dtls_have_buffered = 1;
  3620. }
  3621. }
  3622. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3623. if (dtls_have_buffered == 0) {
  3624. ret = ssl_get_next_record(ssl);
  3625. if (ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING) {
  3626. continue;
  3627. }
  3628. if (ret != 0) {
  3629. MBEDTLS_SSL_DEBUG_RET(1, ("ssl_get_next_record"), ret);
  3630. return ret;
  3631. }
  3632. }
  3633. }
  3634. ret = mbedtls_ssl_handle_message_type(ssl);
  3635. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3636. if (ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE) {
  3637. /* Buffer future message */
  3638. ret = ssl_buffer_message(ssl);
  3639. if (ret != 0) {
  3640. return ret;
  3641. }
  3642. ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
  3643. }
  3644. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3645. } while (MBEDTLS_ERR_SSL_NON_FATAL == ret ||
  3646. MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret);
  3647. if (0 != ret) {
  3648. MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_handle_message_type"), ret);
  3649. return ret;
  3650. }
  3651. if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  3652. update_hs_digest == 1) {
  3653. ret = mbedtls_ssl_update_handshake_status(ssl);
  3654. if (0 != ret) {
  3655. MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_update_handshake_status"), ret);
  3656. return ret;
  3657. }
  3658. }
  3659. } else {
  3660. MBEDTLS_SSL_DEBUG_MSG(2, ("reuse previously read message"));
  3661. ssl->keep_current_message = 0;
  3662. }
  3663. MBEDTLS_SSL_DEBUG_MSG(2, ("<= read record"));
  3664. return 0;
  3665. }
  3666. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3667. MBEDTLS_CHECK_RETURN_CRITICAL
  3668. static int ssl_next_record_is_in_datagram(mbedtls_ssl_context *ssl)
  3669. {
  3670. if (ssl->in_left > ssl->next_record_offset) {
  3671. return 1;
  3672. }
  3673. return 0;
  3674. }
  3675. MBEDTLS_CHECK_RETURN_CRITICAL
  3676. static int ssl_load_buffered_message(mbedtls_ssl_context *ssl)
  3677. {
  3678. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  3679. mbedtls_ssl_hs_buffer *hs_buf;
  3680. int ret = 0;
  3681. if (hs == NULL) {
  3682. return -1;
  3683. }
  3684. MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_load_buffered_message"));
  3685. if (ssl->state == MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC ||
  3686. ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC) {
  3687. /* Check if we have seen a ChangeCipherSpec before.
  3688. * If yes, synthesize a CCS record. */
  3689. if (!hs->buffering.seen_ccs) {
  3690. MBEDTLS_SSL_DEBUG_MSG(2, ("CCS not seen in the current flight"));
  3691. ret = -1;
  3692. goto exit;
  3693. }
  3694. MBEDTLS_SSL_DEBUG_MSG(2, ("Injecting buffered CCS message"));
  3695. ssl->in_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
  3696. ssl->in_msglen = 1;
  3697. ssl->in_msg[0] = 1;
  3698. /* As long as they are equal, the exact value doesn't matter. */
  3699. ssl->in_left = 0;
  3700. ssl->next_record_offset = 0;
  3701. hs->buffering.seen_ccs = 0;
  3702. goto exit;
  3703. }
  3704. #if defined(MBEDTLS_DEBUG_C)
  3705. /* Debug only */
  3706. {
  3707. unsigned offset;
  3708. for (offset = 1; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++) {
  3709. hs_buf = &hs->buffering.hs[offset];
  3710. if (hs_buf->is_valid == 1) {
  3711. MBEDTLS_SSL_DEBUG_MSG(2, ("Future message with sequence number %u %s buffered.",
  3712. hs->in_msg_seq + offset,
  3713. hs_buf->is_complete ? "fully" : "partially"));
  3714. }
  3715. }
  3716. }
  3717. #endif /* MBEDTLS_DEBUG_C */
  3718. /* Check if we have buffered and/or fully reassembled the
  3719. * next handshake message. */
  3720. hs_buf = &hs->buffering.hs[0];
  3721. if ((hs_buf->is_valid == 1) && (hs_buf->is_complete == 1)) {
  3722. /* Synthesize a record containing the buffered HS message. */
  3723. size_t msg_len = MBEDTLS_GET_UINT24_BE(hs_buf->data, 1);
  3724. /* Double-check that we haven't accidentally buffered
  3725. * a message that doesn't fit into the input buffer. */
  3726. if (msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN) {
  3727. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  3728. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  3729. }
  3730. MBEDTLS_SSL_DEBUG_MSG(2, ("Next handshake message has been buffered - load"));
  3731. MBEDTLS_SSL_DEBUG_BUF(3, "Buffered handshake message (incl. header)",
  3732. hs_buf->data, msg_len + 12);
  3733. ssl->in_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  3734. ssl->in_hslen = msg_len + 12;
  3735. ssl->in_msglen = msg_len + 12;
  3736. memcpy(ssl->in_msg, hs_buf->data, ssl->in_hslen);
  3737. ret = 0;
  3738. goto exit;
  3739. } else {
  3740. MBEDTLS_SSL_DEBUG_MSG(2, ("Next handshake message %u not or only partially bufffered",
  3741. hs->in_msg_seq));
  3742. }
  3743. ret = -1;
  3744. exit:
  3745. MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_load_buffered_message"));
  3746. return ret;
  3747. }
  3748. MBEDTLS_CHECK_RETURN_CRITICAL
  3749. static int ssl_buffer_make_space(mbedtls_ssl_context *ssl,
  3750. size_t desired)
  3751. {
  3752. int offset;
  3753. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  3754. MBEDTLS_SSL_DEBUG_MSG(2, ("Attempt to free buffered messages to have %u bytes available",
  3755. (unsigned) desired));
  3756. /* Get rid of future records epoch first, if such exist. */
  3757. ssl_free_buffered_record(ssl);
  3758. /* Check if we have enough space available now. */
  3759. if (desired <= (MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  3760. hs->buffering.total_bytes_buffered)) {
  3761. MBEDTLS_SSL_DEBUG_MSG(2, ("Enough space available after freeing future epoch record"));
  3762. return 0;
  3763. }
  3764. /* We don't have enough space to buffer the next expected handshake
  3765. * message. Remove buffers used for future messages to gain space,
  3766. * starting with the most distant one. */
  3767. for (offset = MBEDTLS_SSL_MAX_BUFFERED_HS - 1;
  3768. offset >= 0; offset--) {
  3769. MBEDTLS_SSL_DEBUG_MSG(2,
  3770. (
  3771. "Free buffering slot %d to make space for reassembly of next handshake message",
  3772. offset));
  3773. ssl_buffering_free_slot(ssl, (uint8_t) offset);
  3774. /* Check if we have enough space available now. */
  3775. if (desired <= (MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  3776. hs->buffering.total_bytes_buffered)) {
  3777. MBEDTLS_SSL_DEBUG_MSG(2, ("Enough space available after freeing buffered HS messages"));
  3778. return 0;
  3779. }
  3780. }
  3781. return -1;
  3782. }
  3783. MBEDTLS_CHECK_RETURN_CRITICAL
  3784. static int ssl_buffer_message(mbedtls_ssl_context *ssl)
  3785. {
  3786. int ret = 0;
  3787. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  3788. if (hs == NULL) {
  3789. return 0;
  3790. }
  3791. MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_buffer_message"));
  3792. switch (ssl->in_msgtype) {
  3793. case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC:
  3794. MBEDTLS_SSL_DEBUG_MSG(2, ("Remember CCS message"));
  3795. hs->buffering.seen_ccs = 1;
  3796. break;
  3797. case MBEDTLS_SSL_MSG_HANDSHAKE:
  3798. {
  3799. unsigned recv_msg_seq_offset;
  3800. unsigned recv_msg_seq = MBEDTLS_GET_UINT16_BE(ssl->in_msg, 4);
  3801. mbedtls_ssl_hs_buffer *hs_buf;
  3802. size_t msg_len = ssl->in_hslen - 12;
  3803. /* We should never receive an old handshake
  3804. * message - double-check nonetheless. */
  3805. if (recv_msg_seq < ssl->handshake->in_msg_seq) {
  3806. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  3807. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  3808. }
  3809. recv_msg_seq_offset = recv_msg_seq - ssl->handshake->in_msg_seq;
  3810. if (recv_msg_seq_offset >= MBEDTLS_SSL_MAX_BUFFERED_HS) {
  3811. /* Silently ignore -- message too far in the future */
  3812. MBEDTLS_SSL_DEBUG_MSG(2,
  3813. ("Ignore future HS message with sequence number %u, "
  3814. "buffering window %u - %u",
  3815. recv_msg_seq, ssl->handshake->in_msg_seq,
  3816. ssl->handshake->in_msg_seq + MBEDTLS_SSL_MAX_BUFFERED_HS -
  3817. 1));
  3818. goto exit;
  3819. }
  3820. MBEDTLS_SSL_DEBUG_MSG(2, ("Buffering HS message with sequence number %u, offset %u ",
  3821. recv_msg_seq, recv_msg_seq_offset));
  3822. hs_buf = &hs->buffering.hs[recv_msg_seq_offset];
  3823. /* Check if the buffering for this seq nr has already commenced. */
  3824. if (!hs_buf->is_valid) {
  3825. size_t reassembly_buf_sz;
  3826. hs_buf->is_fragmented =
  3827. (ssl_hs_is_proper_fragment(ssl) == 1);
  3828. /* We copy the message back into the input buffer
  3829. * after reassembly, so check that it's not too large.
  3830. * This is an implementation-specific limitation
  3831. * and not one from the standard, hence it is not
  3832. * checked in ssl_check_hs_header(). */
  3833. if (msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN) {
  3834. /* Ignore message */
  3835. goto exit;
  3836. }
  3837. /* Check if we have enough space to buffer the message. */
  3838. if (hs->buffering.total_bytes_buffered >
  3839. MBEDTLS_SSL_DTLS_MAX_BUFFERING) {
  3840. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  3841. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  3842. }
  3843. reassembly_buf_sz = ssl_get_reassembly_buffer_size(msg_len,
  3844. hs_buf->is_fragmented);
  3845. if (reassembly_buf_sz > (MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  3846. hs->buffering.total_bytes_buffered)) {
  3847. if (recv_msg_seq_offset > 0) {
  3848. /* If we can't buffer a future message because
  3849. * of space limitations -- ignore. */
  3850. MBEDTLS_SSL_DEBUG_MSG(2,
  3851. ("Buffering of future message of size %"
  3852. MBEDTLS_PRINTF_SIZET
  3853. " would exceed the compile-time limit %"
  3854. MBEDTLS_PRINTF_SIZET
  3855. " (already %" MBEDTLS_PRINTF_SIZET
  3856. " bytes buffered) -- ignore\n",
  3857. msg_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  3858. hs->buffering.total_bytes_buffered));
  3859. goto exit;
  3860. } else {
  3861. MBEDTLS_SSL_DEBUG_MSG(2,
  3862. ("Buffering of future message of size %"
  3863. MBEDTLS_PRINTF_SIZET
  3864. " would exceed the compile-time limit %"
  3865. MBEDTLS_PRINTF_SIZET
  3866. " (already %" MBEDTLS_PRINTF_SIZET
  3867. " bytes buffered) -- attempt to make space by freeing buffered future messages\n",
  3868. msg_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  3869. hs->buffering.total_bytes_buffered));
  3870. }
  3871. if (ssl_buffer_make_space(ssl, reassembly_buf_sz) != 0) {
  3872. MBEDTLS_SSL_DEBUG_MSG(2,
  3873. ("Reassembly of next message of size %"
  3874. MBEDTLS_PRINTF_SIZET
  3875. " (%" MBEDTLS_PRINTF_SIZET
  3876. " with bitmap) would exceed"
  3877. " the compile-time limit %"
  3878. MBEDTLS_PRINTF_SIZET
  3879. " (already %" MBEDTLS_PRINTF_SIZET
  3880. " bytes buffered) -- fail\n",
  3881. msg_len,
  3882. reassembly_buf_sz,
  3883. (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  3884. hs->buffering.total_bytes_buffered));
  3885. ret = MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
  3886. goto exit;
  3887. }
  3888. }
  3889. MBEDTLS_SSL_DEBUG_MSG(2,
  3890. ("initialize reassembly, total length = %"
  3891. MBEDTLS_PRINTF_SIZET,
  3892. msg_len));
  3893. hs_buf->data = mbedtls_calloc(1, reassembly_buf_sz);
  3894. if (hs_buf->data == NULL) {
  3895. ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
  3896. goto exit;
  3897. }
  3898. hs_buf->data_len = reassembly_buf_sz;
  3899. /* Prepare final header: copy msg_type, length and message_seq,
  3900. * then add standardised fragment_offset and fragment_length */
  3901. memcpy(hs_buf->data, ssl->in_msg, 6);
  3902. memset(hs_buf->data + 6, 0, 3);
  3903. memcpy(hs_buf->data + 9, hs_buf->data + 1, 3);
  3904. hs_buf->is_valid = 1;
  3905. hs->buffering.total_bytes_buffered += reassembly_buf_sz;
  3906. } else {
  3907. /* Make sure msg_type and length are consistent */
  3908. if (memcmp(hs_buf->data, ssl->in_msg, 4) != 0) {
  3909. MBEDTLS_SSL_DEBUG_MSG(1, ("Fragment header mismatch - ignore"));
  3910. /* Ignore */
  3911. goto exit;
  3912. }
  3913. }
  3914. if (!hs_buf->is_complete) {
  3915. size_t frag_len, frag_off;
  3916. unsigned char * const msg = hs_buf->data + 12;
  3917. /*
  3918. * Check and copy current fragment
  3919. */
  3920. /* Validation of header fields already done in
  3921. * mbedtls_ssl_prepare_handshake_record(). */
  3922. frag_off = ssl_get_hs_frag_off(ssl);
  3923. frag_len = ssl_get_hs_frag_len(ssl);
  3924. MBEDTLS_SSL_DEBUG_MSG(2, ("adding fragment, offset = %" MBEDTLS_PRINTF_SIZET
  3925. ", length = %" MBEDTLS_PRINTF_SIZET,
  3926. frag_off, frag_len));
  3927. memcpy(msg + frag_off, ssl->in_msg + 12, frag_len);
  3928. if (hs_buf->is_fragmented) {
  3929. unsigned char * const bitmask = msg + msg_len;
  3930. ssl_bitmask_set(bitmask, frag_off, frag_len);
  3931. hs_buf->is_complete = (ssl_bitmask_check(bitmask,
  3932. msg_len) == 0);
  3933. } else {
  3934. hs_buf->is_complete = 1;
  3935. }
  3936. MBEDTLS_SSL_DEBUG_MSG(2, ("message %scomplete",
  3937. hs_buf->is_complete ? "" : "not yet "));
  3938. }
  3939. break;
  3940. }
  3941. default:
  3942. /* We don't buffer other types of messages. */
  3943. break;
  3944. }
  3945. exit:
  3946. MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_buffer_message"));
  3947. return ret;
  3948. }
  3949. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3950. MBEDTLS_CHECK_RETURN_CRITICAL
  3951. static int ssl_consume_current_message(mbedtls_ssl_context *ssl)
  3952. {
  3953. /*
  3954. * Consume last content-layer message and potentially
  3955. * update in_msglen which keeps track of the contents'
  3956. * consumption state.
  3957. *
  3958. * (1) Handshake messages:
  3959. * Remove last handshake message, move content
  3960. * and adapt in_msglen.
  3961. *
  3962. * (2) Alert messages:
  3963. * Consume whole record content, in_msglen = 0.
  3964. *
  3965. * (3) Change cipher spec:
  3966. * Consume whole record content, in_msglen = 0.
  3967. *
  3968. * (4) Application data:
  3969. * Don't do anything - the record layer provides
  3970. * the application data as a stream transport
  3971. * and consumes through mbedtls_ssl_read only.
  3972. *
  3973. */
  3974. /* Case (1): Handshake messages */
  3975. if (ssl->in_hslen != 0) {
  3976. /* Hard assertion to be sure that no application data
  3977. * is in flight, as corrupting ssl->in_msglen during
  3978. * ssl->in_offt != NULL is fatal. */
  3979. if (ssl->in_offt != NULL) {
  3980. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  3981. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  3982. }
  3983. /*
  3984. * Get next Handshake message in the current record
  3985. */
  3986. /* Notes:
  3987. * (1) in_hslen is not necessarily the size of the
  3988. * current handshake content: If DTLS handshake
  3989. * fragmentation is used, that's the fragment
  3990. * size instead. Using the total handshake message
  3991. * size here is faulty and should be changed at
  3992. * some point.
  3993. * (2) While it doesn't seem to cause problems, one
  3994. * has to be very careful not to assume that in_hslen
  3995. * is always <= in_msglen in a sensible communication.
  3996. * Again, it's wrong for DTLS handshake fragmentation.
  3997. * The following check is therefore mandatory, and
  3998. * should not be treated as a silently corrected assertion.
  3999. * Additionally, ssl->in_hslen might be arbitrarily out of
  4000. * bounds after handling a DTLS message with an unexpected
  4001. * sequence number, see mbedtls_ssl_prepare_handshake_record.
  4002. */
  4003. if (ssl->in_hslen < ssl->in_msglen) {
  4004. ssl->in_msglen -= ssl->in_hslen;
  4005. memmove(ssl->in_msg, ssl->in_msg + ssl->in_hslen,
  4006. ssl->in_msglen);
  4007. MBEDTLS_SSL_DEBUG_BUF(4, "remaining content in record",
  4008. ssl->in_msg, ssl->in_msglen);
  4009. } else {
  4010. ssl->in_msglen = 0;
  4011. }
  4012. ssl->in_hslen = 0;
  4013. }
  4014. /* Case (4): Application data */
  4015. else if (ssl->in_offt != NULL) {
  4016. return 0;
  4017. }
  4018. /* Everything else (CCS & Alerts) */
  4019. else {
  4020. ssl->in_msglen = 0;
  4021. }
  4022. return 0;
  4023. }
  4024. MBEDTLS_CHECK_RETURN_CRITICAL
  4025. static int ssl_record_is_in_progress(mbedtls_ssl_context *ssl)
  4026. {
  4027. if (ssl->in_msglen > 0) {
  4028. return 1;
  4029. }
  4030. return 0;
  4031. }
  4032. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4033. static void ssl_free_buffered_record(mbedtls_ssl_context *ssl)
  4034. {
  4035. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4036. if (hs == NULL) {
  4037. return;
  4038. }
  4039. if (hs->buffering.future_record.data != NULL) {
  4040. hs->buffering.total_bytes_buffered -=
  4041. hs->buffering.future_record.len;
  4042. mbedtls_free(hs->buffering.future_record.data);
  4043. hs->buffering.future_record.data = NULL;
  4044. }
  4045. }
  4046. MBEDTLS_CHECK_RETURN_CRITICAL
  4047. static int ssl_load_buffered_record(mbedtls_ssl_context *ssl)
  4048. {
  4049. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4050. unsigned char *rec;
  4051. size_t rec_len;
  4052. unsigned rec_epoch;
  4053. #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
  4054. size_t in_buf_len = ssl->in_buf_len;
  4055. #else
  4056. size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
  4057. #endif
  4058. if (ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  4059. return 0;
  4060. }
  4061. if (hs == NULL) {
  4062. return 0;
  4063. }
  4064. rec = hs->buffering.future_record.data;
  4065. rec_len = hs->buffering.future_record.len;
  4066. rec_epoch = hs->buffering.future_record.epoch;
  4067. if (rec == NULL) {
  4068. return 0;
  4069. }
  4070. /* Only consider loading future records if the
  4071. * input buffer is empty. */
  4072. if (ssl_next_record_is_in_datagram(ssl) == 1) {
  4073. return 0;
  4074. }
  4075. MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_load_buffered_record"));
  4076. if (rec_epoch != ssl->in_epoch) {
  4077. MBEDTLS_SSL_DEBUG_MSG(2, ("Buffered record not from current epoch."));
  4078. goto exit;
  4079. }
  4080. MBEDTLS_SSL_DEBUG_MSG(2, ("Found buffered record from current epoch - load"));
  4081. /* Double-check that the record is not too large */
  4082. if (rec_len > in_buf_len - (size_t) (ssl->in_hdr - ssl->in_buf)) {
  4083. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  4084. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  4085. }
  4086. memcpy(ssl->in_hdr, rec, rec_len);
  4087. ssl->in_left = rec_len;
  4088. ssl->next_record_offset = 0;
  4089. ssl_free_buffered_record(ssl);
  4090. exit:
  4091. MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_load_buffered_record"));
  4092. return 0;
  4093. }
  4094. MBEDTLS_CHECK_RETURN_CRITICAL
  4095. static int ssl_buffer_future_record(mbedtls_ssl_context *ssl,
  4096. mbedtls_record const *rec)
  4097. {
  4098. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4099. /* Don't buffer future records outside handshakes. */
  4100. if (hs == NULL) {
  4101. return 0;
  4102. }
  4103. /* Only buffer handshake records (we are only interested
  4104. * in Finished messages). */
  4105. if (rec->type != MBEDTLS_SSL_MSG_HANDSHAKE) {
  4106. return 0;
  4107. }
  4108. /* Don't buffer more than one future epoch record. */
  4109. if (hs->buffering.future_record.data != NULL) {
  4110. return 0;
  4111. }
  4112. /* Don't buffer record if there's not enough buffering space remaining. */
  4113. if (rec->buf_len > (MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  4114. hs->buffering.total_bytes_buffered)) {
  4115. MBEDTLS_SSL_DEBUG_MSG(2, ("Buffering of future epoch record of size %" MBEDTLS_PRINTF_SIZET
  4116. " would exceed the compile-time limit %" MBEDTLS_PRINTF_SIZET
  4117. " (already %" MBEDTLS_PRINTF_SIZET
  4118. " bytes buffered) -- ignore\n",
  4119. rec->buf_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  4120. hs->buffering.total_bytes_buffered));
  4121. return 0;
  4122. }
  4123. /* Buffer record */
  4124. MBEDTLS_SSL_DEBUG_MSG(2, ("Buffer record from epoch %u",
  4125. ssl->in_epoch + 1U));
  4126. MBEDTLS_SSL_DEBUG_BUF(3, "Buffered record", rec->buf, rec->buf_len);
  4127. /* ssl_parse_record_header() only considers records
  4128. * of the next epoch as candidates for buffering. */
  4129. hs->buffering.future_record.epoch = ssl->in_epoch + 1;
  4130. hs->buffering.future_record.len = rec->buf_len;
  4131. hs->buffering.future_record.data =
  4132. mbedtls_calloc(1, hs->buffering.future_record.len);
  4133. if (hs->buffering.future_record.data == NULL) {
  4134. /* If we run out of RAM trying to buffer a
  4135. * record from the next epoch, just ignore. */
  4136. return 0;
  4137. }
  4138. memcpy(hs->buffering.future_record.data, rec->buf, rec->buf_len);
  4139. hs->buffering.total_bytes_buffered += rec->buf_len;
  4140. return 0;
  4141. }
  4142. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4143. MBEDTLS_CHECK_RETURN_CRITICAL
  4144. static int ssl_get_next_record(mbedtls_ssl_context *ssl)
  4145. {
  4146. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  4147. mbedtls_record rec;
  4148. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4149. /* We might have buffered a future record; if so,
  4150. * and if the epoch matches now, load it.
  4151. * On success, this call will set ssl->in_left to
  4152. * the length of the buffered record, so that
  4153. * the calls to ssl_fetch_input() below will
  4154. * essentially be no-ops. */
  4155. ret = ssl_load_buffered_record(ssl);
  4156. if (ret != 0) {
  4157. return ret;
  4158. }
  4159. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4160. /* Ensure that we have enough space available for the default form
  4161. * of TLS / DTLS record headers (5 Bytes for TLS, 13 Bytes for DTLS,
  4162. * with no space for CIDs counted in). */
  4163. ret = mbedtls_ssl_fetch_input(ssl, mbedtls_ssl_in_hdr_len(ssl));
  4164. if (ret != 0) {
  4165. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_fetch_input", ret);
  4166. return ret;
  4167. }
  4168. ret = ssl_parse_record_header(ssl, ssl->in_hdr, ssl->in_left, &rec);
  4169. if (ret != 0) {
  4170. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4171. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  4172. if (ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE) {
  4173. ret = ssl_buffer_future_record(ssl, &rec);
  4174. if (ret != 0) {
  4175. return ret;
  4176. }
  4177. /* Fall through to handling of unexpected records */
  4178. ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
  4179. }
  4180. if (ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD) {
  4181. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
  4182. /* Reset in pointers to default state for TLS/DTLS records,
  4183. * assuming no CID and no offset between record content and
  4184. * record plaintext. */
  4185. mbedtls_ssl_update_in_pointers(ssl);
  4186. /* Setup internal message pointers from record structure. */
  4187. ssl->in_msgtype = rec.type;
  4188. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  4189. ssl->in_len = ssl->in_cid + rec.cid_len;
  4190. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  4191. ssl->in_iv = ssl->in_msg = ssl->in_len + 2;
  4192. ssl->in_msglen = rec.data_len;
  4193. ret = ssl_check_client_reconnect(ssl);
  4194. MBEDTLS_SSL_DEBUG_RET(2, "ssl_check_client_reconnect", ret);
  4195. if (ret != 0) {
  4196. return ret;
  4197. }
  4198. #endif
  4199. /* Skip unexpected record (but not whole datagram) */
  4200. ssl->next_record_offset = rec.buf_len;
  4201. MBEDTLS_SSL_DEBUG_MSG(1, ("discarding unexpected record "
  4202. "(header)"));
  4203. } else {
  4204. /* Skip invalid record and the rest of the datagram */
  4205. ssl->next_record_offset = 0;
  4206. ssl->in_left = 0;
  4207. MBEDTLS_SSL_DEBUG_MSG(1, ("discarding invalid record "
  4208. "(header)"));
  4209. }
  4210. /* Get next record */
  4211. return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
  4212. } else
  4213. #endif
  4214. {
  4215. return ret;
  4216. }
  4217. }
  4218. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4219. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  4220. /* Remember offset of next record within datagram. */
  4221. ssl->next_record_offset = rec.buf_len;
  4222. if (ssl->next_record_offset < ssl->in_left) {
  4223. MBEDTLS_SSL_DEBUG_MSG(3, ("more than one record within datagram"));
  4224. }
  4225. } else
  4226. #endif
  4227. {
  4228. /*
  4229. * Fetch record contents from underlying transport.
  4230. */
  4231. ret = mbedtls_ssl_fetch_input(ssl, rec.buf_len);
  4232. if (ret != 0) {
  4233. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_fetch_input", ret);
  4234. return ret;
  4235. }
  4236. ssl->in_left = 0;
  4237. }
  4238. /*
  4239. * Decrypt record contents.
  4240. */
  4241. if ((ret = ssl_prepare_record_content(ssl, &rec)) != 0) {
  4242. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4243. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  4244. /* Silently discard invalid records */
  4245. if (ret == MBEDTLS_ERR_SSL_INVALID_MAC) {
  4246. /* Except when waiting for Finished as a bad mac here
  4247. * probably means something went wrong in the handshake
  4248. * (eg wrong psk used, mitm downgrade attempt, etc.) */
  4249. if (ssl->state == MBEDTLS_SSL_CLIENT_FINISHED ||
  4250. ssl->state == MBEDTLS_SSL_SERVER_FINISHED) {
  4251. #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
  4252. if (ret == MBEDTLS_ERR_SSL_INVALID_MAC) {
  4253. mbedtls_ssl_send_alert_message(ssl,
  4254. MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4255. MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC);
  4256. }
  4257. #endif
  4258. return ret;
  4259. }
  4260. if (ssl->conf->badmac_limit != 0 &&
  4261. ++ssl->badmac_seen >= ssl->conf->badmac_limit) {
  4262. MBEDTLS_SSL_DEBUG_MSG(1, ("too many records with bad MAC"));
  4263. return MBEDTLS_ERR_SSL_INVALID_MAC;
  4264. }
  4265. /* As above, invalid records cause
  4266. * dismissal of the whole datagram. */
  4267. ssl->next_record_offset = 0;
  4268. ssl->in_left = 0;
  4269. MBEDTLS_SSL_DEBUG_MSG(1, ("discarding invalid record (mac)"));
  4270. return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
  4271. }
  4272. return ret;
  4273. } else
  4274. #endif
  4275. {
  4276. /* Error out (and send alert) on invalid records */
  4277. #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
  4278. if (ret == MBEDTLS_ERR_SSL_INVALID_MAC) {
  4279. mbedtls_ssl_send_alert_message(ssl,
  4280. MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4281. MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC);
  4282. }
  4283. #endif
  4284. return ret;
  4285. }
  4286. }
  4287. /* Reset in pointers to default state for TLS/DTLS records,
  4288. * assuming no CID and no offset between record content and
  4289. * record plaintext. */
  4290. mbedtls_ssl_update_in_pointers(ssl);
  4291. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  4292. ssl->in_len = ssl->in_cid + rec.cid_len;
  4293. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  4294. ssl->in_iv = ssl->in_len + 2;
  4295. /* The record content type may change during decryption,
  4296. * so re-read it. */
  4297. ssl->in_msgtype = rec.type;
  4298. /* Also update the input buffer, because unfortunately
  4299. * the server-side ssl_parse_client_hello() reparses the
  4300. * record header when receiving a ClientHello initiating
  4301. * a renegotiation. */
  4302. ssl->in_hdr[0] = rec.type;
  4303. ssl->in_msg = rec.buf + rec.data_offset;
  4304. ssl->in_msglen = rec.data_len;
  4305. MBEDTLS_PUT_UINT16_BE(rec.data_len, ssl->in_len, 0);
  4306. return 0;
  4307. }
  4308. int mbedtls_ssl_handle_message_type(mbedtls_ssl_context *ssl)
  4309. {
  4310. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  4311. /*
  4312. * Handle particular types of records
  4313. */
  4314. if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE) {
  4315. if ((ret = mbedtls_ssl_prepare_handshake_record(ssl)) != 0) {
  4316. return ret;
  4317. }
  4318. }
  4319. if (ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
  4320. if (ssl->in_msglen != 1) {
  4321. MBEDTLS_SSL_DEBUG_MSG(1, ("invalid CCS message, len: %" MBEDTLS_PRINTF_SIZET,
  4322. ssl->in_msglen));
  4323. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  4324. }
  4325. if (ssl->in_msg[0] != 1) {
  4326. MBEDTLS_SSL_DEBUG_MSG(1, ("invalid CCS message, content: %02x",
  4327. ssl->in_msg[0]));
  4328. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  4329. }
  4330. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4331. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  4332. ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC &&
  4333. ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC) {
  4334. if (ssl->handshake == NULL) {
  4335. MBEDTLS_SSL_DEBUG_MSG(1, ("dropping ChangeCipherSpec outside handshake"));
  4336. return MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
  4337. }
  4338. MBEDTLS_SSL_DEBUG_MSG(1, ("received out-of-order ChangeCipherSpec - remember"));
  4339. return MBEDTLS_ERR_SSL_EARLY_MESSAGE;
  4340. }
  4341. #endif
  4342. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  4343. if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
  4344. #if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
  4345. MBEDTLS_SSL_DEBUG_MSG(1,
  4346. ("Ignore ChangeCipherSpec in TLS 1.3 compatibility mode"));
  4347. return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
  4348. #else
  4349. MBEDTLS_SSL_DEBUG_MSG(1,
  4350. ("ChangeCipherSpec invalid in TLS 1.3 without compatibility mode"));
  4351. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  4352. #endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
  4353. }
  4354. #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
  4355. }
  4356. if (ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT) {
  4357. if (ssl->in_msglen != 2) {
  4358. /* Note: Standard allows for more than one 2 byte alert
  4359. to be packed in a single message, but Mbed TLS doesn't
  4360. currently support this. */
  4361. MBEDTLS_SSL_DEBUG_MSG(1, ("invalid alert message, len: %" MBEDTLS_PRINTF_SIZET,
  4362. ssl->in_msglen));
  4363. return MBEDTLS_ERR_SSL_INVALID_RECORD;
  4364. }
  4365. MBEDTLS_SSL_DEBUG_MSG(2, ("got an alert message, type: [%u:%u]",
  4366. ssl->in_msg[0], ssl->in_msg[1]));
  4367. /*
  4368. * Ignore non-fatal alerts, except close_notify and no_renegotiation
  4369. */
  4370. if (ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL) {
  4371. MBEDTLS_SSL_DEBUG_MSG(1, ("is a fatal alert message (msg %d)",
  4372. ssl->in_msg[1]));
  4373. return MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE;
  4374. }
  4375. if (ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
  4376. ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY) {
  4377. MBEDTLS_SSL_DEBUG_MSG(2, ("is a close notify message"));
  4378. return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY;
  4379. }
  4380. #if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED)
  4381. if (ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
  4382. ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION) {
  4383. MBEDTLS_SSL_DEBUG_MSG(2, ("is a no renegotiation alert"));
  4384. /* Will be handled when trying to parse ServerHello */
  4385. return 0;
  4386. }
  4387. #endif
  4388. /* Silently ignore: fetch new message */
  4389. return MBEDTLS_ERR_SSL_NON_FATAL;
  4390. }
  4391. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4392. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  4393. /* Drop unexpected ApplicationData records,
  4394. * except at the beginning of renegotiations */
  4395. if (ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA &&
  4396. mbedtls_ssl_is_handshake_over(ssl) == 0
  4397. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  4398. && !(ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
  4399. ssl->state == MBEDTLS_SSL_SERVER_HELLO)
  4400. #endif
  4401. ) {
  4402. MBEDTLS_SSL_DEBUG_MSG(1, ("dropping unexpected ApplicationData"));
  4403. return MBEDTLS_ERR_SSL_NON_FATAL;
  4404. }
  4405. if (ssl->handshake != NULL &&
  4406. mbedtls_ssl_is_handshake_over(ssl) == 1) {
  4407. mbedtls_ssl_handshake_wrapup_free_hs_transform(ssl);
  4408. }
  4409. }
  4410. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4411. return 0;
  4412. }
  4413. int mbedtls_ssl_send_fatal_handshake_failure(mbedtls_ssl_context *ssl)
  4414. {
  4415. return mbedtls_ssl_send_alert_message(ssl,
  4416. MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4417. MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
  4418. }
  4419. int mbedtls_ssl_send_alert_message(mbedtls_ssl_context *ssl,
  4420. unsigned char level,
  4421. unsigned char message)
  4422. {
  4423. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  4424. if (ssl == NULL || ssl->conf == NULL) {
  4425. return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
  4426. }
  4427. if (ssl->out_left != 0) {
  4428. return mbedtls_ssl_flush_output(ssl);
  4429. }
  4430. MBEDTLS_SSL_DEBUG_MSG(2, ("=> send alert message"));
  4431. MBEDTLS_SSL_DEBUG_MSG(3, ("send alert level=%u message=%u", level, message));
  4432. ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
  4433. ssl->out_msglen = 2;
  4434. ssl->out_msg[0] = level;
  4435. ssl->out_msg[1] = message;
  4436. if ((ret = mbedtls_ssl_write_record(ssl, SSL_FORCE_FLUSH)) != 0) {
  4437. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_record", ret);
  4438. return ret;
  4439. }
  4440. MBEDTLS_SSL_DEBUG_MSG(2, ("<= send alert message"));
  4441. return 0;
  4442. }
  4443. int mbedtls_ssl_write_change_cipher_spec(mbedtls_ssl_context *ssl)
  4444. {
  4445. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  4446. MBEDTLS_SSL_DEBUG_MSG(2, ("=> write change cipher spec"));
  4447. ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
  4448. ssl->out_msglen = 1;
  4449. ssl->out_msg[0] = 1;
  4450. ssl->state++;
  4451. if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
  4452. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
  4453. return ret;
  4454. }
  4455. MBEDTLS_SSL_DEBUG_MSG(2, ("<= write change cipher spec"));
  4456. return 0;
  4457. }
  4458. int mbedtls_ssl_parse_change_cipher_spec(mbedtls_ssl_context *ssl)
  4459. {
  4460. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  4461. MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse change cipher spec"));
  4462. if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
  4463. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
  4464. return ret;
  4465. }
  4466. if (ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
  4467. MBEDTLS_SSL_DEBUG_MSG(1, ("bad change cipher spec message"));
  4468. mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4469. MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE);
  4470. return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
  4471. }
  4472. /* CCS records are only accepted if they have length 1 and content '1',
  4473. * so we don't need to check this here. */
  4474. /*
  4475. * Switch to our negotiated transform and session parameters for inbound
  4476. * data.
  4477. */
  4478. MBEDTLS_SSL_DEBUG_MSG(3, ("switching to new transform spec for inbound data"));
  4479. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  4480. ssl->transform_in = ssl->transform_negotiate;
  4481. #endif
  4482. ssl->session_in = ssl->session_negotiate;
  4483. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4484. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  4485. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  4486. mbedtls_ssl_dtls_replay_reset(ssl);
  4487. #endif
  4488. /* Increment epoch */
  4489. if (++ssl->in_epoch == 0) {
  4490. MBEDTLS_SSL_DEBUG_MSG(1, ("DTLS epoch would wrap"));
  4491. /* This is highly unlikely to happen for legitimate reasons, so
  4492. treat it as an attack and don't send an alert. */
  4493. return MBEDTLS_ERR_SSL_COUNTER_WRAPPING;
  4494. }
  4495. } else
  4496. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4497. memset(ssl->in_ctr, 0, MBEDTLS_SSL_SEQUENCE_NUMBER_LEN);
  4498. mbedtls_ssl_update_in_pointers(ssl);
  4499. ssl->state++;
  4500. MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse change cipher spec"));
  4501. return 0;
  4502. }
  4503. /* Once ssl->out_hdr as the address of the beginning of the
  4504. * next outgoing record is set, deduce the other pointers.
  4505. *
  4506. * Note: For TLS, we save the implicit record sequence number
  4507. * (entering MAC computation) in the 8 bytes before ssl->out_hdr,
  4508. * and the caller has to make sure there's space for this.
  4509. */
  4510. static size_t ssl_transform_get_explicit_iv_len(
  4511. mbedtls_ssl_transform const *transform)
  4512. {
  4513. return transform->ivlen - transform->fixed_ivlen;
  4514. }
  4515. void mbedtls_ssl_update_out_pointers(mbedtls_ssl_context *ssl,
  4516. mbedtls_ssl_transform *transform)
  4517. {
  4518. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4519. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  4520. ssl->out_ctr = ssl->out_hdr + 3;
  4521. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  4522. ssl->out_cid = ssl->out_ctr + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
  4523. ssl->out_len = ssl->out_cid;
  4524. if (transform != NULL) {
  4525. ssl->out_len += transform->out_cid_len;
  4526. }
  4527. #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  4528. ssl->out_len = ssl->out_ctr + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
  4529. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  4530. ssl->out_iv = ssl->out_len + 2;
  4531. } else
  4532. #endif
  4533. {
  4534. ssl->out_len = ssl->out_hdr + 3;
  4535. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  4536. ssl->out_cid = ssl->out_len;
  4537. #endif
  4538. ssl->out_iv = ssl->out_hdr + 5;
  4539. }
  4540. ssl->out_msg = ssl->out_iv;
  4541. /* Adjust out_msg to make space for explicit IV, if used. */
  4542. if (transform != NULL) {
  4543. ssl->out_msg += ssl_transform_get_explicit_iv_len(transform);
  4544. }
  4545. }
  4546. /* Once ssl->in_hdr as the address of the beginning of the
  4547. * next incoming record is set, deduce the other pointers.
  4548. *
  4549. * Note: For TLS, we save the implicit record sequence number
  4550. * (entering MAC computation) in the 8 bytes before ssl->in_hdr,
  4551. * and the caller has to make sure there's space for this.
  4552. */
  4553. void mbedtls_ssl_update_in_pointers(mbedtls_ssl_context *ssl)
  4554. {
  4555. /* This function sets the pointers to match the case
  4556. * of unprotected TLS/DTLS records, with both ssl->in_iv
  4557. * and ssl->in_msg pointing to the beginning of the record
  4558. * content.
  4559. *
  4560. * When decrypting a protected record, ssl->in_msg
  4561. * will be shifted to point to the beginning of the
  4562. * record plaintext.
  4563. */
  4564. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4565. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  4566. /* This sets the header pointers to match records
  4567. * without CID. When we receive a record containing
  4568. * a CID, the fields are shifted accordingly in
  4569. * ssl_parse_record_header(). */
  4570. ssl->in_ctr = ssl->in_hdr + 3;
  4571. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  4572. ssl->in_cid = ssl->in_ctr + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
  4573. ssl->in_len = ssl->in_cid; /* Default: no CID */
  4574. #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  4575. ssl->in_len = ssl->in_ctr + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
  4576. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  4577. ssl->in_iv = ssl->in_len + 2;
  4578. } else
  4579. #endif
  4580. {
  4581. ssl->in_ctr = ssl->in_hdr - MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
  4582. ssl->in_len = ssl->in_hdr + 3;
  4583. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  4584. ssl->in_cid = ssl->in_len;
  4585. #endif
  4586. ssl->in_iv = ssl->in_hdr + 5;
  4587. }
  4588. /* This will be adjusted at record decryption time. */
  4589. ssl->in_msg = ssl->in_iv;
  4590. }
  4591. /*
  4592. * Setup an SSL context
  4593. */
  4594. void mbedtls_ssl_reset_in_out_pointers(mbedtls_ssl_context *ssl)
  4595. {
  4596. /* Set the incoming and outgoing record pointers. */
  4597. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4598. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  4599. ssl->out_hdr = ssl->out_buf;
  4600. ssl->in_hdr = ssl->in_buf;
  4601. } else
  4602. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4603. {
  4604. ssl->out_ctr = ssl->out_buf;
  4605. ssl->out_hdr = ssl->out_buf + 8;
  4606. ssl->in_hdr = ssl->in_buf + 8;
  4607. }
  4608. /* Derive other internal pointers. */
  4609. mbedtls_ssl_update_out_pointers(ssl, NULL /* no transform enabled */);
  4610. mbedtls_ssl_update_in_pointers(ssl);
  4611. }
  4612. /*
  4613. * SSL get accessors
  4614. */
  4615. size_t mbedtls_ssl_get_bytes_avail(const mbedtls_ssl_context *ssl)
  4616. {
  4617. return ssl->in_offt == NULL ? 0 : ssl->in_msglen;
  4618. }
  4619. int mbedtls_ssl_check_pending(const mbedtls_ssl_context *ssl)
  4620. {
  4621. /*
  4622. * Case A: We're currently holding back
  4623. * a message for further processing.
  4624. */
  4625. if (ssl->keep_current_message == 1) {
  4626. MBEDTLS_SSL_DEBUG_MSG(3, ("ssl_check_pending: record held back for processing"));
  4627. return 1;
  4628. }
  4629. /*
  4630. * Case B: Further records are pending in the current datagram.
  4631. */
  4632. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4633. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  4634. ssl->in_left > ssl->next_record_offset) {
  4635. MBEDTLS_SSL_DEBUG_MSG(3, ("ssl_check_pending: more records within current datagram"));
  4636. return 1;
  4637. }
  4638. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4639. /*
  4640. * Case C: A handshake message is being processed.
  4641. */
  4642. if (ssl->in_hslen > 0 && ssl->in_hslen < ssl->in_msglen) {
  4643. MBEDTLS_SSL_DEBUG_MSG(3,
  4644. ("ssl_check_pending: more handshake messages within current record"));
  4645. return 1;
  4646. }
  4647. /*
  4648. * Case D: An application data message is being processed
  4649. */
  4650. if (ssl->in_offt != NULL) {
  4651. MBEDTLS_SSL_DEBUG_MSG(3, ("ssl_check_pending: application data record is being processed"));
  4652. return 1;
  4653. }
  4654. /*
  4655. * In all other cases, the rest of the message can be dropped.
  4656. * As in ssl_get_next_record, this needs to be adapted if
  4657. * we implement support for multiple alerts in single records.
  4658. */
  4659. MBEDTLS_SSL_DEBUG_MSG(3, ("ssl_check_pending: nothing pending"));
  4660. return 0;
  4661. }
  4662. int mbedtls_ssl_get_record_expansion(const mbedtls_ssl_context *ssl)
  4663. {
  4664. size_t transform_expansion = 0;
  4665. const mbedtls_ssl_transform *transform = ssl->transform_out;
  4666. unsigned block_size;
  4667. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  4668. psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT;
  4669. psa_key_type_t key_type;
  4670. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  4671. size_t out_hdr_len = mbedtls_ssl_out_hdr_len(ssl);
  4672. if (transform == NULL) {
  4673. return (int) out_hdr_len;
  4674. }
  4675. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  4676. if (transform->psa_alg == PSA_ALG_GCM ||
  4677. transform->psa_alg == PSA_ALG_CCM ||
  4678. transform->psa_alg == PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, 8) ||
  4679. transform->psa_alg == PSA_ALG_CHACHA20_POLY1305 ||
  4680. transform->psa_alg == MBEDTLS_SSL_NULL_CIPHER) {
  4681. transform_expansion = transform->minlen;
  4682. } else if (transform->psa_alg == PSA_ALG_CBC_NO_PADDING) {
  4683. (void) psa_get_key_attributes(transform->psa_key_enc, &attr);
  4684. key_type = psa_get_key_type(&attr);
  4685. block_size = PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type);
  4686. /* Expansion due to the addition of the MAC. */
  4687. transform_expansion += transform->maclen;
  4688. /* Expansion due to the addition of CBC padding;
  4689. * Theoretically up to 256 bytes, but we never use
  4690. * more than the block size of the underlying cipher. */
  4691. transform_expansion += block_size;
  4692. /* For TLS 1.2 or higher, an explicit IV is added
  4693. * after the record header. */
  4694. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  4695. transform_expansion += block_size;
  4696. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  4697. } else {
  4698. MBEDTLS_SSL_DEBUG_MSG(1,
  4699. ("Unsupported psa_alg spotted in mbedtls_ssl_get_record_expansion()"));
  4700. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  4701. }
  4702. #else
  4703. switch (mbedtls_cipher_get_cipher_mode(&transform->cipher_ctx_enc)) {
  4704. case MBEDTLS_MODE_GCM:
  4705. case MBEDTLS_MODE_CCM:
  4706. case MBEDTLS_MODE_CHACHAPOLY:
  4707. case MBEDTLS_MODE_STREAM:
  4708. transform_expansion = transform->minlen;
  4709. break;
  4710. case MBEDTLS_MODE_CBC:
  4711. block_size = mbedtls_cipher_get_block_size(
  4712. &transform->cipher_ctx_enc);
  4713. /* Expansion due to the addition of the MAC. */
  4714. transform_expansion += transform->maclen;
  4715. /* Expansion due to the addition of CBC padding;
  4716. * Theoretically up to 256 bytes, but we never use
  4717. * more than the block size of the underlying cipher. */
  4718. transform_expansion += block_size;
  4719. /* For TLS 1.2 or higher, an explicit IV is added
  4720. * after the record header. */
  4721. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  4722. transform_expansion += block_size;
  4723. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  4724. break;
  4725. default:
  4726. MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
  4727. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  4728. }
  4729. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  4730. #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
  4731. if (transform->out_cid_len != 0) {
  4732. transform_expansion += MBEDTLS_SSL_MAX_CID_EXPANSION;
  4733. }
  4734. #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
  4735. return (int) (out_hdr_len + transform_expansion);
  4736. }
  4737. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  4738. /*
  4739. * Check record counters and renegotiate if they're above the limit.
  4740. */
  4741. MBEDTLS_CHECK_RETURN_CRITICAL
  4742. static int ssl_check_ctr_renegotiate(mbedtls_ssl_context *ssl)
  4743. {
  4744. size_t ep_len = mbedtls_ssl_ep_len(ssl);
  4745. int in_ctr_cmp;
  4746. int out_ctr_cmp;
  4747. if (mbedtls_ssl_is_handshake_over(ssl) == 0 ||
  4748. ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||
  4749. ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED) {
  4750. return 0;
  4751. }
  4752. in_ctr_cmp = memcmp(ssl->in_ctr + ep_len,
  4753. &ssl->conf->renego_period[ep_len],
  4754. MBEDTLS_SSL_SEQUENCE_NUMBER_LEN - ep_len);
  4755. out_ctr_cmp = memcmp(&ssl->cur_out_ctr[ep_len],
  4756. &ssl->conf->renego_period[ep_len],
  4757. sizeof(ssl->cur_out_ctr) - ep_len);
  4758. if (in_ctr_cmp <= 0 && out_ctr_cmp <= 0) {
  4759. return 0;
  4760. }
  4761. MBEDTLS_SSL_DEBUG_MSG(1, ("record counter limit reached: renegotiate"));
  4762. return mbedtls_ssl_renegotiate(ssl);
  4763. }
  4764. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  4765. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  4766. #if defined(MBEDTLS_SSL_CLI_C)
  4767. MBEDTLS_CHECK_RETURN_CRITICAL
  4768. static int ssl_tls13_is_new_session_ticket(mbedtls_ssl_context *ssl)
  4769. {
  4770. if ((ssl->in_hslen == mbedtls_ssl_hs_hdr_len(ssl)) ||
  4771. (ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET)) {
  4772. return 0;
  4773. }
  4774. return 1;
  4775. }
  4776. #endif /* MBEDTLS_SSL_CLI_C */
  4777. MBEDTLS_CHECK_RETURN_CRITICAL
  4778. static int ssl_tls13_handle_hs_message_post_handshake(mbedtls_ssl_context *ssl)
  4779. {
  4780. MBEDTLS_SSL_DEBUG_MSG(3, ("received post-handshake message"));
  4781. #if defined(MBEDTLS_SSL_CLI_C)
  4782. if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
  4783. if (ssl_tls13_is_new_session_ticket(ssl)) {
  4784. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  4785. MBEDTLS_SSL_DEBUG_MSG(3, ("NewSessionTicket received"));
  4786. if (mbedtls_ssl_conf_is_signal_new_session_tickets_enabled(ssl->conf) ==
  4787. MBEDTLS_SSL_TLS1_3_SIGNAL_NEW_SESSION_TICKETS_ENABLED) {
  4788. ssl->keep_current_message = 1;
  4789. mbedtls_ssl_handshake_set_state(ssl,
  4790. MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET);
  4791. return MBEDTLS_ERR_SSL_WANT_READ;
  4792. } else {
  4793. MBEDTLS_SSL_DEBUG_MSG(3, ("Ignoring NewSessionTicket, handling disabled."));
  4794. return 0;
  4795. }
  4796. #else
  4797. MBEDTLS_SSL_DEBUG_MSG(3, ("Ignoring NewSessionTicket, not supported."));
  4798. return 0;
  4799. #endif
  4800. }
  4801. }
  4802. #endif /* MBEDTLS_SSL_CLI_C */
  4803. /* Fail in all other cases. */
  4804. return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
  4805. }
  4806. #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
  4807. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  4808. /* This function is called from mbedtls_ssl_read() when a handshake message is
  4809. * received after the initial handshake. In this context, handshake messages
  4810. * may only be sent for the purpose of initiating renegotiations.
  4811. *
  4812. * This function is introduced as a separate helper since the handling
  4813. * of post-handshake handshake messages changes significantly in TLS 1.3,
  4814. * and having a helper function allows to distinguish between TLS <= 1.2 and
  4815. * TLS 1.3 in the future without bloating the logic of mbedtls_ssl_read().
  4816. */
  4817. MBEDTLS_CHECK_RETURN_CRITICAL
  4818. static int ssl_tls12_handle_hs_message_post_handshake(mbedtls_ssl_context *ssl)
  4819. {
  4820. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  4821. /*
  4822. * - For client-side, expect SERVER_HELLO_REQUEST.
  4823. * - For server-side, expect CLIENT_HELLO.
  4824. * - Fail (TLS) or silently drop record (DTLS) in other cases.
  4825. */
  4826. #if defined(MBEDTLS_SSL_CLI_C)
  4827. if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
  4828. (ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST ||
  4829. ssl->in_hslen != mbedtls_ssl_hs_hdr_len(ssl))) {
  4830. MBEDTLS_SSL_DEBUG_MSG(1, ("handshake received (not HelloRequest)"));
  4831. /* With DTLS, drop the packet (probably from last handshake) */
  4832. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4833. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  4834. return 0;
  4835. }
  4836. #endif
  4837. return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
  4838. }
  4839. #endif /* MBEDTLS_SSL_CLI_C */
  4840. #if defined(MBEDTLS_SSL_SRV_C)
  4841. if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  4842. ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO) {
  4843. MBEDTLS_SSL_DEBUG_MSG(1, ("handshake received (not ClientHello)"));
  4844. /* With DTLS, drop the packet (probably from last handshake) */
  4845. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4846. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  4847. return 0;
  4848. }
  4849. #endif
  4850. return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
  4851. }
  4852. #endif /* MBEDTLS_SSL_SRV_C */
  4853. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  4854. /* Determine whether renegotiation attempt should be accepted */
  4855. if (!(ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
  4856. (ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
  4857. ssl->conf->allow_legacy_renegotiation ==
  4858. MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION))) {
  4859. /*
  4860. * Accept renegotiation request
  4861. */
  4862. /* DTLS clients need to know renego is server-initiated */
  4863. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4864. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  4865. ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
  4866. ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
  4867. }
  4868. #endif
  4869. ret = mbedtls_ssl_start_renegotiation(ssl);
  4870. if (ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
  4871. ret != 0) {
  4872. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_start_renegotiation",
  4873. ret);
  4874. return ret;
  4875. }
  4876. } else
  4877. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  4878. {
  4879. /*
  4880. * Refuse renegotiation
  4881. */
  4882. MBEDTLS_SSL_DEBUG_MSG(3, ("refusing renegotiation, sending alert"));
  4883. if ((ret = mbedtls_ssl_send_alert_message(ssl,
  4884. MBEDTLS_SSL_ALERT_LEVEL_WARNING,
  4885. MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION)) != 0) {
  4886. return ret;
  4887. }
  4888. }
  4889. return 0;
  4890. }
  4891. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  4892. MBEDTLS_CHECK_RETURN_CRITICAL
  4893. static int ssl_handle_hs_message_post_handshake(mbedtls_ssl_context *ssl)
  4894. {
  4895. /* Check protocol version and dispatch accordingly. */
  4896. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  4897. if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
  4898. return ssl_tls13_handle_hs_message_post_handshake(ssl);
  4899. }
  4900. #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
  4901. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  4902. if (ssl->tls_version <= MBEDTLS_SSL_VERSION_TLS1_2) {
  4903. return ssl_tls12_handle_hs_message_post_handshake(ssl);
  4904. }
  4905. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  4906. /* Should never happen */
  4907. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  4908. }
  4909. /*
  4910. * brief Read at most 'len' application data bytes from the input
  4911. * buffer.
  4912. *
  4913. * param ssl SSL context:
  4914. * - First byte of application data not read yet in the input
  4915. * buffer located at address `in_offt`.
  4916. * - The number of bytes of data not read yet is `in_msglen`.
  4917. * param buf buffer that will hold the data
  4918. * param len maximum number of bytes to read
  4919. *
  4920. * note The function updates the fields `in_offt` and `in_msglen`
  4921. * according to the number of bytes read.
  4922. *
  4923. * return The number of bytes read.
  4924. */
  4925. static int ssl_read_application_data(
  4926. mbedtls_ssl_context *ssl, unsigned char *buf, size_t len)
  4927. {
  4928. size_t n = (len < ssl->in_msglen) ? len : ssl->in_msglen;
  4929. if (len != 0) {
  4930. memcpy(buf, ssl->in_offt, n);
  4931. ssl->in_msglen -= n;
  4932. }
  4933. /* Zeroising the plaintext buffer to erase unused application data
  4934. from the memory. */
  4935. mbedtls_platform_zeroize(ssl->in_offt, n);
  4936. if (ssl->in_msglen == 0) {
  4937. /* all bytes consumed */
  4938. ssl->in_offt = NULL;
  4939. ssl->keep_current_message = 0;
  4940. } else {
  4941. /* more data available */
  4942. ssl->in_offt += n;
  4943. }
  4944. return (int) n;
  4945. }
  4946. /*
  4947. * Receive application data decrypted from the SSL layer
  4948. */
  4949. int mbedtls_ssl_read(mbedtls_ssl_context *ssl, unsigned char *buf, size_t len)
  4950. {
  4951. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  4952. if (ssl == NULL || ssl->conf == NULL) {
  4953. return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
  4954. }
  4955. MBEDTLS_SSL_DEBUG_MSG(2, ("=> read"));
  4956. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4957. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  4958. if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
  4959. return ret;
  4960. }
  4961. if (ssl->handshake != NULL &&
  4962. ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING) {
  4963. if ((ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
  4964. return ret;
  4965. }
  4966. }
  4967. }
  4968. #endif
  4969. /*
  4970. * Check if renegotiation is necessary and/or handshake is
  4971. * in process. If yes, perform/continue, and fall through
  4972. * if an unexpected packet is received while the client
  4973. * is waiting for the ServerHello.
  4974. *
  4975. * (There is no equivalent to the last condition on
  4976. * the server-side as it is not treated as within
  4977. * a handshake while waiting for the ClientHello
  4978. * after a renegotiation request.)
  4979. */
  4980. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  4981. ret = ssl_check_ctr_renegotiate(ssl);
  4982. if (ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
  4983. ret != 0) {
  4984. MBEDTLS_SSL_DEBUG_RET(1, "ssl_check_ctr_renegotiate", ret);
  4985. return ret;
  4986. }
  4987. #endif
  4988. if (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
  4989. ret = mbedtls_ssl_handshake(ssl);
  4990. if (ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
  4991. ret != 0) {
  4992. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake", ret);
  4993. return ret;
  4994. }
  4995. }
  4996. /* Loop as long as no application data record is available */
  4997. while (ssl->in_offt == NULL) {
  4998. /* Start timer if not already running */
  4999. if (ssl->f_get_timer != NULL &&
  5000. ssl->f_get_timer(ssl->p_timer) == -1) {
  5001. mbedtls_ssl_set_timer(ssl, ssl->conf->read_timeout);
  5002. }
  5003. if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
  5004. if (ret == MBEDTLS_ERR_SSL_CONN_EOF) {
  5005. return 0;
  5006. }
  5007. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
  5008. return ret;
  5009. }
  5010. if (ssl->in_msglen == 0 &&
  5011. ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA) {
  5012. /*
  5013. * OpenSSL sends empty messages to randomize the IV
  5014. */
  5015. if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
  5016. if (ret == MBEDTLS_ERR_SSL_CONN_EOF) {
  5017. return 0;
  5018. }
  5019. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
  5020. return ret;
  5021. }
  5022. }
  5023. if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE) {
  5024. ret = ssl_handle_hs_message_post_handshake(ssl);
  5025. if (ret != 0) {
  5026. MBEDTLS_SSL_DEBUG_RET(1, "ssl_handle_hs_message_post_handshake",
  5027. ret);
  5028. return ret;
  5029. }
  5030. /* At this point, we don't know whether the renegotiation triggered
  5031. * by the post-handshake message has been completed or not. The cases
  5032. * to consider are the following:
  5033. * 1) The renegotiation is complete. In this case, no new record
  5034. * has been read yet.
  5035. * 2) The renegotiation is incomplete because the client received
  5036. * an application data record while awaiting the ServerHello.
  5037. * 3) The renegotiation is incomplete because the client received
  5038. * a non-handshake, non-application data message while awaiting
  5039. * the ServerHello.
  5040. *
  5041. * In each of these cases, looping will be the proper action:
  5042. * - For 1), the next iteration will read a new record and check
  5043. * if it's application data.
  5044. * - For 2), the loop condition isn't satisfied as application data
  5045. * is present, hence continue is the same as break
  5046. * - For 3), the loop condition is satisfied and read_record
  5047. * will re-deliver the message that was held back by the client
  5048. * when expecting the ServerHello.
  5049. */
  5050. continue;
  5051. }
  5052. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  5053. else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING) {
  5054. if (ssl->conf->renego_max_records >= 0) {
  5055. if (++ssl->renego_records_seen > ssl->conf->renego_max_records) {
  5056. MBEDTLS_SSL_DEBUG_MSG(1, ("renegotiation requested, "
  5057. "but not honored by client"));
  5058. return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
  5059. }
  5060. }
  5061. }
  5062. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  5063. /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */
  5064. if (ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT) {
  5065. MBEDTLS_SSL_DEBUG_MSG(2, ("ignoring non-fatal non-closure alert"));
  5066. return MBEDTLS_ERR_SSL_WANT_READ;
  5067. }
  5068. if (ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA) {
  5069. MBEDTLS_SSL_DEBUG_MSG(1, ("bad application data message"));
  5070. return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
  5071. }
  5072. ssl->in_offt = ssl->in_msg;
  5073. /* We're going to return something now, cancel timer,
  5074. * except if handshake (renegotiation) is in progress */
  5075. if (mbedtls_ssl_is_handshake_over(ssl) == 1) {
  5076. mbedtls_ssl_set_timer(ssl, 0);
  5077. }
  5078. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5079. /* If we requested renego but received AppData, resend HelloRequest.
  5080. * Do it now, after setting in_offt, to avoid taking this branch
  5081. * again if ssl_write_hello_request() returns WANT_WRITE */
  5082. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
  5083. if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  5084. ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING) {
  5085. if ((ret = mbedtls_ssl_resend_hello_request(ssl)) != 0) {
  5086. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_resend_hello_request",
  5087. ret);
  5088. return ret;
  5089. }
  5090. }
  5091. #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
  5092. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  5093. }
  5094. ret = ssl_read_application_data(ssl, buf, len);
  5095. MBEDTLS_SSL_DEBUG_MSG(2, ("<= read"));
  5096. return ret;
  5097. }
  5098. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_EARLY_DATA)
  5099. int mbedtls_ssl_read_early_data(mbedtls_ssl_context *ssl,
  5100. unsigned char *buf, size_t len)
  5101. {
  5102. if (ssl == NULL || (ssl->conf == NULL)) {
  5103. return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
  5104. }
  5105. /*
  5106. * The server may receive early data only while waiting for the End of
  5107. * Early Data handshake message.
  5108. */
  5109. if ((ssl->state != MBEDTLS_SSL_END_OF_EARLY_DATA) ||
  5110. (ssl->in_offt == NULL)) {
  5111. return MBEDTLS_ERR_SSL_CANNOT_READ_EARLY_DATA;
  5112. }
  5113. return ssl_read_application_data(ssl, buf, len);
  5114. }
  5115. #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_EARLY_DATA */
  5116. /*
  5117. * Send application data to be encrypted by the SSL layer, taking care of max
  5118. * fragment length and buffer size.
  5119. *
  5120. * According to RFC 5246 Section 6.2.1:
  5121. *
  5122. * Zero-length fragments of Application data MAY be sent as they are
  5123. * potentially useful as a traffic analysis countermeasure.
  5124. *
  5125. * Therefore, it is possible that the input message length is 0 and the
  5126. * corresponding return code is 0 on success.
  5127. */
  5128. MBEDTLS_CHECK_RETURN_CRITICAL
  5129. static int ssl_write_real(mbedtls_ssl_context *ssl,
  5130. const unsigned char *buf, size_t len)
  5131. {
  5132. int ret = mbedtls_ssl_get_max_out_record_payload(ssl);
  5133. const size_t max_len = (size_t) ret;
  5134. if (ret < 0) {
  5135. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_get_max_out_record_payload", ret);
  5136. return ret;
  5137. }
  5138. if (len > max_len) {
  5139. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5140. if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  5141. MBEDTLS_SSL_DEBUG_MSG(1, ("fragment larger than the (negotiated) "
  5142. "maximum fragment length: %" MBEDTLS_PRINTF_SIZET
  5143. " > %" MBEDTLS_PRINTF_SIZET,
  5144. len, max_len));
  5145. return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
  5146. } else
  5147. #endif
  5148. len = max_len;
  5149. }
  5150. if (ssl->out_left != 0) {
  5151. /*
  5152. * The user has previously tried to send the data and
  5153. * MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially
  5154. * written. In this case, we expect the high-level write function
  5155. * (e.g. mbedtls_ssl_write()) to be called with the same parameters
  5156. */
  5157. if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
  5158. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flush_output", ret);
  5159. return ret;
  5160. }
  5161. } else {
  5162. /*
  5163. * The user is trying to send a message the first time, so we need to
  5164. * copy the data into the internal buffers and setup the data structure
  5165. * to keep track of partial writes
  5166. */
  5167. ssl->out_msglen = len;
  5168. ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
  5169. if (len > 0) {
  5170. memcpy(ssl->out_msg, buf, len);
  5171. }
  5172. if ((ret = mbedtls_ssl_write_record(ssl, SSL_FORCE_FLUSH)) != 0) {
  5173. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_record", ret);
  5174. return ret;
  5175. }
  5176. }
  5177. return (int) len;
  5178. }
  5179. /*
  5180. * Write application data (public-facing wrapper)
  5181. */
  5182. int mbedtls_ssl_write(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len)
  5183. {
  5184. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  5185. MBEDTLS_SSL_DEBUG_MSG(2, ("=> write"));
  5186. if (ssl == NULL || ssl->conf == NULL) {
  5187. return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
  5188. }
  5189. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  5190. if ((ret = ssl_check_ctr_renegotiate(ssl)) != 0) {
  5191. MBEDTLS_SSL_DEBUG_RET(1, "ssl_check_ctr_renegotiate", ret);
  5192. return ret;
  5193. }
  5194. #endif
  5195. if (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
  5196. if ((ret = mbedtls_ssl_handshake(ssl)) != 0) {
  5197. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake", ret);
  5198. return ret;
  5199. }
  5200. }
  5201. ret = ssl_write_real(ssl, buf, len);
  5202. MBEDTLS_SSL_DEBUG_MSG(2, ("<= write"));
  5203. return ret;
  5204. }
  5205. #if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_CLI_C)
  5206. int mbedtls_ssl_write_early_data(mbedtls_ssl_context *ssl,
  5207. const unsigned char *buf, size_t len)
  5208. {
  5209. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  5210. const struct mbedtls_ssl_config *conf;
  5211. uint32_t remaining;
  5212. MBEDTLS_SSL_DEBUG_MSG(2, ("=> write early_data"));
  5213. if (ssl == NULL || (conf = ssl->conf) == NULL) {
  5214. return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
  5215. }
  5216. if (conf->endpoint != MBEDTLS_SSL_IS_CLIENT) {
  5217. return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
  5218. }
  5219. if ((!mbedtls_ssl_conf_is_tls13_enabled(conf)) ||
  5220. (conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) ||
  5221. (conf->early_data_enabled != MBEDTLS_SSL_EARLY_DATA_ENABLED)) {
  5222. return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
  5223. }
  5224. if (ssl->tls_version != MBEDTLS_SSL_VERSION_TLS1_3) {
  5225. return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
  5226. }
  5227. /*
  5228. * If we are at the beginning of the handshake, the early data state being
  5229. * equal to MBEDTLS_SSL_EARLY_DATA_STATE_IDLE or
  5230. * MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT advance the handshake just
  5231. * enough to be able to send early data if possible. That way, we can
  5232. * guarantee that when starting the handshake with this function we will
  5233. * send at least one record of early data. Note that when the state is
  5234. * MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT and not yet
  5235. * MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE, we cannot send early data
  5236. * as the early data outbound transform has not been set as we may have to
  5237. * first send a dummy CCS in clear.
  5238. */
  5239. if ((ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IDLE) ||
  5240. (ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT)) {
  5241. while ((ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IDLE) ||
  5242. (ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT)) {
  5243. ret = mbedtls_ssl_handshake_step(ssl);
  5244. if (ret != 0) {
  5245. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake_step", ret);
  5246. return ret;
  5247. }
  5248. ret = mbedtls_ssl_flush_output(ssl);
  5249. if (ret != 0) {
  5250. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flush_output", ret);
  5251. return ret;
  5252. }
  5253. }
  5254. remaining = ssl->session_negotiate->max_early_data_size;
  5255. } else {
  5256. /*
  5257. * If we are past the point where we can send early data or we have
  5258. * already reached the maximum early data size, return immediatly.
  5259. * Otherwise, progress the handshake as much as possible to not delay
  5260. * it too much. If we reach a point where we can still send early data,
  5261. * then we will send some.
  5262. */
  5263. if ((ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE) &&
  5264. (ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED)) {
  5265. return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
  5266. }
  5267. remaining = ssl->session_negotiate->max_early_data_size -
  5268. ssl->total_early_data_size;
  5269. if (remaining == 0) {
  5270. return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
  5271. }
  5272. ret = mbedtls_ssl_handshake(ssl);
  5273. if ((ret != 0) && (ret != MBEDTLS_ERR_SSL_WANT_READ)) {
  5274. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake", ret);
  5275. return ret;
  5276. }
  5277. }
  5278. if (((ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE) &&
  5279. (ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED))
  5280. || (remaining == 0)) {
  5281. return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
  5282. }
  5283. if (len > remaining) {
  5284. len = remaining;
  5285. }
  5286. ret = ssl_write_real(ssl, buf, len);
  5287. if (ret >= 0) {
  5288. ssl->total_early_data_size += ret;
  5289. }
  5290. MBEDTLS_SSL_DEBUG_MSG(2, ("<= write early_data, ret=%d", ret));
  5291. return ret;
  5292. }
  5293. #endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_CLI_C */
  5294. /*
  5295. * Notify the peer that the connection is being closed
  5296. */
  5297. int mbedtls_ssl_close_notify(mbedtls_ssl_context *ssl)
  5298. {
  5299. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  5300. if (ssl == NULL || ssl->conf == NULL) {
  5301. return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
  5302. }
  5303. MBEDTLS_SSL_DEBUG_MSG(2, ("=> write close notify"));
  5304. if (mbedtls_ssl_is_handshake_over(ssl) == 1) {
  5305. if ((ret = mbedtls_ssl_send_alert_message(ssl,
  5306. MBEDTLS_SSL_ALERT_LEVEL_WARNING,
  5307. MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY)) != 0) {
  5308. MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_send_alert_message", ret);
  5309. return ret;
  5310. }
  5311. }
  5312. MBEDTLS_SSL_DEBUG_MSG(2, ("<= write close notify"));
  5313. return 0;
  5314. }
  5315. void mbedtls_ssl_transform_free(mbedtls_ssl_transform *transform)
  5316. {
  5317. if (transform == NULL) {
  5318. return;
  5319. }
  5320. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  5321. psa_destroy_key(transform->psa_key_enc);
  5322. psa_destroy_key(transform->psa_key_dec);
  5323. #else
  5324. mbedtls_cipher_free(&transform->cipher_ctx_enc);
  5325. mbedtls_cipher_free(&transform->cipher_ctx_dec);
  5326. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  5327. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
  5328. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  5329. psa_destroy_key(transform->psa_mac_enc);
  5330. psa_destroy_key(transform->psa_mac_dec);
  5331. #else
  5332. mbedtls_md_free(&transform->md_ctx_enc);
  5333. mbedtls_md_free(&transform->md_ctx_dec);
  5334. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  5335. #endif
  5336. mbedtls_platform_zeroize(transform, sizeof(mbedtls_ssl_transform));
  5337. }
  5338. void mbedtls_ssl_set_inbound_transform(mbedtls_ssl_context *ssl,
  5339. mbedtls_ssl_transform *transform)
  5340. {
  5341. ssl->transform_in = transform;
  5342. memset(ssl->in_ctr, 0, MBEDTLS_SSL_SEQUENCE_NUMBER_LEN);
  5343. }
  5344. void mbedtls_ssl_set_outbound_transform(mbedtls_ssl_context *ssl,
  5345. mbedtls_ssl_transform *transform)
  5346. {
  5347. ssl->transform_out = transform;
  5348. memset(ssl->cur_out_ctr, 0, sizeof(ssl->cur_out_ctr));
  5349. }
  5350. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5351. void mbedtls_ssl_buffering_free(mbedtls_ssl_context *ssl)
  5352. {
  5353. unsigned offset;
  5354. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  5355. if (hs == NULL) {
  5356. return;
  5357. }
  5358. ssl_free_buffered_record(ssl);
  5359. for (offset = 0; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++) {
  5360. ssl_buffering_free_slot(ssl, offset);
  5361. }
  5362. }
  5363. static void ssl_buffering_free_slot(mbedtls_ssl_context *ssl,
  5364. uint8_t slot)
  5365. {
  5366. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  5367. mbedtls_ssl_hs_buffer * const hs_buf = &hs->buffering.hs[slot];
  5368. if (slot >= MBEDTLS_SSL_MAX_BUFFERED_HS) {
  5369. return;
  5370. }
  5371. if (hs_buf->is_valid == 1) {
  5372. hs->buffering.total_bytes_buffered -= hs_buf->data_len;
  5373. mbedtls_zeroize_and_free(hs_buf->data, hs_buf->data_len);
  5374. memset(hs_buf, 0, sizeof(mbedtls_ssl_hs_buffer));
  5375. }
  5376. }
  5377. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  5378. /*
  5379. * Convert version numbers to/from wire format
  5380. * and, for DTLS, to/from TLS equivalent.
  5381. *
  5382. * For TLS this is the identity.
  5383. * For DTLS, map as follows, then use 1's complement (v -> ~v):
  5384. * 1.x <-> 3.x+1 for x != 0 (DTLS 1.2 based on TLS 1.2)
  5385. * DTLS 1.0 is stored as TLS 1.1 internally
  5386. */
  5387. void mbedtls_ssl_write_version(unsigned char version[2], int transport,
  5388. mbedtls_ssl_protocol_version tls_version)
  5389. {
  5390. uint16_t tls_version_formatted;
  5391. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5392. if (transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  5393. tls_version_formatted =
  5394. ~(tls_version - (tls_version == 0x0302 ? 0x0202 : 0x0201));
  5395. } else
  5396. #else
  5397. ((void) transport);
  5398. #endif
  5399. {
  5400. tls_version_formatted = (uint16_t) tls_version;
  5401. }
  5402. MBEDTLS_PUT_UINT16_BE(tls_version_formatted, version, 0);
  5403. }
  5404. uint16_t mbedtls_ssl_read_version(const unsigned char version[2],
  5405. int transport)
  5406. {
  5407. uint16_t tls_version = MBEDTLS_GET_UINT16_BE(version, 0);
  5408. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5409. if (transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
  5410. tls_version =
  5411. ~(tls_version - (tls_version == 0xfeff ? 0x0202 : 0x0201));
  5412. }
  5413. #else
  5414. ((void) transport);
  5415. #endif
  5416. return tls_version;
  5417. }
  5418. /*
  5419. * Send pending fatal alert.
  5420. * 0, No alert message.
  5421. * !0, if mbedtls_ssl_send_alert_message() returned in error, the error code it
  5422. * returned, ssl->alert_reason otherwise.
  5423. */
  5424. int mbedtls_ssl_handle_pending_alert(mbedtls_ssl_context *ssl)
  5425. {
  5426. int ret;
  5427. /* No pending alert, return success*/
  5428. if (ssl->send_alert == 0) {
  5429. return 0;
  5430. }
  5431. ret = mbedtls_ssl_send_alert_message(ssl,
  5432. MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5433. ssl->alert_type);
  5434. /* If mbedtls_ssl_send_alert_message() returned with MBEDTLS_ERR_SSL_WANT_WRITE,
  5435. * do not clear the alert to be able to send it later.
  5436. */
  5437. if (ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  5438. ssl->send_alert = 0;
  5439. }
  5440. if (ret != 0) {
  5441. return ret;
  5442. }
  5443. return ssl->alert_reason;
  5444. }
  5445. /*
  5446. * Set pending fatal alert flag.
  5447. */
  5448. void mbedtls_ssl_pend_fatal_alert(mbedtls_ssl_context *ssl,
  5449. unsigned char alert_type,
  5450. int alert_reason)
  5451. {
  5452. ssl->send_alert = 1;
  5453. ssl->alert_type = alert_type;
  5454. ssl->alert_reason = alert_reason;
  5455. }
  5456. #endif /* MBEDTLS_SSL_TLS_C */