ssl_msg.c 200 KB

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