ssl_msg.c 229 KB

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