ssl_msg.c 204 KB

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