ssl_msg.c 203 KB

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