ssl_msg.c 200 KB

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