ssl_msg.c 200 KB

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