ssl_tls.c 312 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786
  1. /*
  2. * SSLv3/TLSv1 shared functions
  3. *
  4. * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  5. * SPDX-License-Identifier: Apache-2.0
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  8. * not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * This file is part of mbed TLS (https://tls.mbed.org)
  20. */
  21. /*
  22. * The SSL 3.0 specification was drafted by Netscape in 1996,
  23. * and became an IETF standard in 1999.
  24. *
  25. * http://wp.netscape.com/eng/ssl3/
  26. * http://www.ietf.org/rfc/rfc2246.txt
  27. * http://www.ietf.org/rfc/rfc4346.txt
  28. */
  29. #if !defined(MBEDTLS_CONFIG_FILE)
  30. #include "mbedtls/config.h"
  31. #else
  32. #include MBEDTLS_CONFIG_FILE
  33. #endif
  34. #if defined(MBEDTLS_SSL_TLS_C)
  35. #if defined(MBEDTLS_PLATFORM_C)
  36. #include "mbedtls/platform.h"
  37. #else
  38. #include <stdlib.h>
  39. #define mbedtls_calloc calloc
  40. #define mbedtls_free free
  41. #endif
  42. #include "mbedtls/debug.h"
  43. #include "mbedtls/ssl.h"
  44. #include "mbedtls/ssl_internal.h"
  45. #include "mbedtls/platform_util.h"
  46. #include <string.h>
  47. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  48. #include "mbedtls/oid.h"
  49. #endif
  50. static void ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl );
  51. static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl );
  52. /* Length of the "epoch" field in the record header */
  53. static inline size_t ssl_ep_len( const mbedtls_ssl_context *ssl )
  54. {
  55. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  56. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  57. return( 2 );
  58. #else
  59. ((void) ssl);
  60. #endif
  61. return( 0 );
  62. }
  63. /*
  64. * Start a timer.
  65. * Passing millisecs = 0 cancels a running timer.
  66. */
  67. static void ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs )
  68. {
  69. if( ssl->f_set_timer == NULL )
  70. return;
  71. MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) );
  72. ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs );
  73. }
  74. /*
  75. * Return -1 is timer is expired, 0 if it isn't.
  76. */
  77. static int ssl_check_timer( mbedtls_ssl_context *ssl )
  78. {
  79. if( ssl->f_get_timer == NULL )
  80. return( 0 );
  81. if( ssl->f_get_timer( ssl->p_timer ) == 2 )
  82. {
  83. MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) );
  84. return( -1 );
  85. }
  86. return( 0 );
  87. }
  88. static void ssl_update_out_pointers( mbedtls_ssl_context *ssl,
  89. mbedtls_ssl_transform *transform );
  90. static void ssl_update_in_pointers( mbedtls_ssl_context *ssl,
  91. mbedtls_ssl_transform *transform );
  92. #define SSL_DONT_FORCE_FLUSH 0
  93. #define SSL_FORCE_FLUSH 1
  94. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  95. /* Forward declarations for functions related to message buffering. */
  96. static void ssl_buffering_free( mbedtls_ssl_context *ssl );
  97. static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
  98. uint8_t slot );
  99. static void ssl_free_buffered_record( mbedtls_ssl_context *ssl );
  100. static int ssl_load_buffered_message( mbedtls_ssl_context *ssl );
  101. static int ssl_load_buffered_record( mbedtls_ssl_context *ssl );
  102. static int ssl_buffer_message( mbedtls_ssl_context *ssl );
  103. static int ssl_buffer_future_record( mbedtls_ssl_context *ssl );
  104. static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl );
  105. static size_t ssl_get_current_mtu( const mbedtls_ssl_context *ssl );
  106. static size_t ssl_get_maximum_datagram_size( mbedtls_ssl_context const *ssl )
  107. {
  108. size_t mtu = ssl_get_current_mtu( ssl );
  109. if( mtu != 0 && mtu < MBEDTLS_SSL_OUT_BUFFER_LEN )
  110. return( mtu );
  111. return( MBEDTLS_SSL_OUT_BUFFER_LEN );
  112. }
  113. static int ssl_get_remaining_space_in_datagram( mbedtls_ssl_context const *ssl )
  114. {
  115. size_t const bytes_written = ssl->out_left;
  116. size_t const mtu = ssl_get_maximum_datagram_size( ssl );
  117. /* Double-check that the write-index hasn't gone
  118. * past what we can transmit in a single datagram. */
  119. if( bytes_written > mtu )
  120. {
  121. /* Should never happen... */
  122. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  123. }
  124. return( (int) ( mtu - bytes_written ) );
  125. }
  126. static int ssl_get_remaining_payload_in_datagram( mbedtls_ssl_context const *ssl )
  127. {
  128. int ret;
  129. size_t remaining, expansion;
  130. size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
  131. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  132. const size_t mfl = mbedtls_ssl_get_max_frag_len( ssl );
  133. if( max_len > mfl )
  134. max_len = mfl;
  135. /* By the standard (RFC 6066 Sect. 4), the MFL extension
  136. * only limits the maximum record payload size, so in theory
  137. * we would be allowed to pack multiple records of payload size
  138. * MFL into a single datagram. However, this would mean that there's
  139. * no way to explicitly communicate MTU restrictions to the peer.
  140. *
  141. * The following reduction of max_len makes sure that we never
  142. * write datagrams larger than MFL + Record Expansion Overhead.
  143. */
  144. if( max_len <= ssl->out_left )
  145. return( 0 );
  146. max_len -= ssl->out_left;
  147. #endif
  148. ret = ssl_get_remaining_space_in_datagram( ssl );
  149. if( ret < 0 )
  150. return( ret );
  151. remaining = (size_t) ret;
  152. ret = mbedtls_ssl_get_record_expansion( ssl );
  153. if( ret < 0 )
  154. return( ret );
  155. expansion = (size_t) ret;
  156. if( remaining <= expansion )
  157. return( 0 );
  158. remaining -= expansion;
  159. if( remaining >= max_len )
  160. remaining = max_len;
  161. return( (int) remaining );
  162. }
  163. /*
  164. * Double the retransmit timeout value, within the allowed range,
  165. * returning -1 if the maximum value has already been reached.
  166. */
  167. static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl )
  168. {
  169. uint32_t new_timeout;
  170. if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max )
  171. return( -1 );
  172. /* Implement the final paragraph of RFC 6347 section 4.1.1.1
  173. * in the following way: after the initial transmission and a first
  174. * retransmission, back off to a temporary estimated MTU of 508 bytes.
  175. * This value is guaranteed to be deliverable (if not guaranteed to be
  176. * delivered) of any compliant IPv4 (and IPv6) network, and should work
  177. * on most non-IP stacks too. */
  178. if( ssl->handshake->retransmit_timeout != ssl->conf->hs_timeout_min )
  179. {
  180. ssl->handshake->mtu = 508;
  181. MBEDTLS_SSL_DEBUG_MSG( 2, ( "mtu autoreduction to %d bytes", ssl->handshake->mtu ) );
  182. }
  183. new_timeout = 2 * ssl->handshake->retransmit_timeout;
  184. /* Avoid arithmetic overflow and range overflow */
  185. if( new_timeout < ssl->handshake->retransmit_timeout ||
  186. new_timeout > ssl->conf->hs_timeout_max )
  187. {
  188. new_timeout = ssl->conf->hs_timeout_max;
  189. }
  190. ssl->handshake->retransmit_timeout = new_timeout;
  191. MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
  192. ssl->handshake->retransmit_timeout ) );
  193. return( 0 );
  194. }
  195. static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl )
  196. {
  197. ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min;
  198. MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
  199. ssl->handshake->retransmit_timeout ) );
  200. }
  201. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  202. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  203. /*
  204. * Convert max_fragment_length codes to length.
  205. * RFC 6066 says:
  206. * enum{
  207. * 2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)
  208. * } MaxFragmentLength;
  209. * and we add 0 -> extension unused
  210. */
  211. static unsigned int ssl_mfl_code_to_length( int mfl )
  212. {
  213. switch( mfl )
  214. {
  215. case MBEDTLS_SSL_MAX_FRAG_LEN_NONE:
  216. return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );
  217. case MBEDTLS_SSL_MAX_FRAG_LEN_512:
  218. return 512;
  219. case MBEDTLS_SSL_MAX_FRAG_LEN_1024:
  220. return 1024;
  221. case MBEDTLS_SSL_MAX_FRAG_LEN_2048:
  222. return 2048;
  223. case MBEDTLS_SSL_MAX_FRAG_LEN_4096:
  224. return 4096;
  225. default:
  226. return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );
  227. }
  228. }
  229. #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
  230. #if defined(MBEDTLS_SSL_CLI_C)
  231. static int ssl_session_copy( mbedtls_ssl_session *dst, const mbedtls_ssl_session *src )
  232. {
  233. mbedtls_ssl_session_free( dst );
  234. memcpy( dst, src, sizeof( mbedtls_ssl_session ) );
  235. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  236. if( src->peer_cert != NULL )
  237. {
  238. int ret;
  239. dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) );
  240. if( dst->peer_cert == NULL )
  241. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  242. mbedtls_x509_crt_init( dst->peer_cert );
  243. if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p,
  244. src->peer_cert->raw.len ) ) != 0 )
  245. {
  246. mbedtls_free( dst->peer_cert );
  247. dst->peer_cert = NULL;
  248. return( ret );
  249. }
  250. }
  251. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  252. #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
  253. if( src->ticket != NULL )
  254. {
  255. dst->ticket = mbedtls_calloc( 1, src->ticket_len );
  256. if( dst->ticket == NULL )
  257. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  258. memcpy( dst->ticket, src->ticket, src->ticket_len );
  259. }
  260. #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
  261. return( 0 );
  262. }
  263. #endif /* MBEDTLS_SSL_CLI_C */
  264. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  265. int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl,
  266. const unsigned char *key_enc, const unsigned char *key_dec,
  267. size_t keylen,
  268. const unsigned char *iv_enc, const unsigned char *iv_dec,
  269. size_t ivlen,
  270. const unsigned char *mac_enc, const unsigned char *mac_dec,
  271. size_t maclen ) = NULL;
  272. int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL;
  273. int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL;
  274. int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL;
  275. int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL;
  276. int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL;
  277. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  278. /*
  279. * Key material generation
  280. */
  281. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  282. static int ssl3_prf( const unsigned char *secret, size_t slen,
  283. const char *label,
  284. const unsigned char *random, size_t rlen,
  285. unsigned char *dstbuf, size_t dlen )
  286. {
  287. int ret = 0;
  288. size_t i;
  289. mbedtls_md5_context md5;
  290. mbedtls_sha1_context sha1;
  291. unsigned char padding[16];
  292. unsigned char sha1sum[20];
  293. ((void)label);
  294. mbedtls_md5_init( &md5 );
  295. mbedtls_sha1_init( &sha1 );
  296. /*
  297. * SSLv3:
  298. * block =
  299. * MD5( secret + SHA1( 'A' + secret + random ) ) +
  300. * MD5( secret + SHA1( 'BB' + secret + random ) ) +
  301. * MD5( secret + SHA1( 'CCC' + secret + random ) ) +
  302. * ...
  303. */
  304. for( i = 0; i < dlen / 16; i++ )
  305. {
  306. memset( padding, (unsigned char) ('A' + i), 1 + i );
  307. if( ( ret = mbedtls_sha1_starts_ret( &sha1 ) ) != 0 )
  308. goto exit;
  309. if( ( ret = mbedtls_sha1_update_ret( &sha1, padding, 1 + i ) ) != 0 )
  310. goto exit;
  311. if( ( ret = mbedtls_sha1_update_ret( &sha1, secret, slen ) ) != 0 )
  312. goto exit;
  313. if( ( ret = mbedtls_sha1_update_ret( &sha1, random, rlen ) ) != 0 )
  314. goto exit;
  315. if( ( ret = mbedtls_sha1_finish_ret( &sha1, sha1sum ) ) != 0 )
  316. goto exit;
  317. if( ( ret = mbedtls_md5_starts_ret( &md5 ) ) != 0 )
  318. goto exit;
  319. if( ( ret = mbedtls_md5_update_ret( &md5, secret, slen ) ) != 0 )
  320. goto exit;
  321. if( ( ret = mbedtls_md5_update_ret( &md5, sha1sum, 20 ) ) != 0 )
  322. goto exit;
  323. if( ( ret = mbedtls_md5_finish_ret( &md5, dstbuf + i * 16 ) ) != 0 )
  324. goto exit;
  325. }
  326. exit:
  327. mbedtls_md5_free( &md5 );
  328. mbedtls_sha1_free( &sha1 );
  329. mbedtls_platform_zeroize( padding, sizeof( padding ) );
  330. mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );
  331. return( ret );
  332. }
  333. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  334. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  335. static int tls1_prf( const unsigned char *secret, size_t slen,
  336. const char *label,
  337. const unsigned char *random, size_t rlen,
  338. unsigned char *dstbuf, size_t dlen )
  339. {
  340. size_t nb, hs;
  341. size_t i, j, k;
  342. const unsigned char *S1, *S2;
  343. unsigned char tmp[128];
  344. unsigned char h_i[20];
  345. const mbedtls_md_info_t *md_info;
  346. mbedtls_md_context_t md_ctx;
  347. int ret;
  348. mbedtls_md_init( &md_ctx );
  349. if( sizeof( tmp ) < 20 + strlen( label ) + rlen )
  350. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  351. hs = ( slen + 1 ) / 2;
  352. S1 = secret;
  353. S2 = secret + slen - hs;
  354. nb = strlen( label );
  355. memcpy( tmp + 20, label, nb );
  356. memcpy( tmp + 20 + nb, random, rlen );
  357. nb += rlen;
  358. /*
  359. * First compute P_md5(secret,label+random)[0..dlen]
  360. */
  361. if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL )
  362. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  363. if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
  364. return( ret );
  365. mbedtls_md_hmac_starts( &md_ctx, S1, hs );
  366. mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
  367. mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
  368. for( i = 0; i < dlen; i += 16 )
  369. {
  370. mbedtls_md_hmac_reset ( &md_ctx );
  371. mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb );
  372. mbedtls_md_hmac_finish( &md_ctx, h_i );
  373. mbedtls_md_hmac_reset ( &md_ctx );
  374. mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 );
  375. mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
  376. k = ( i + 16 > dlen ) ? dlen % 16 : 16;
  377. for( j = 0; j < k; j++ )
  378. dstbuf[i + j] = h_i[j];
  379. }
  380. mbedtls_md_free( &md_ctx );
  381. /*
  382. * XOR out with P_sha1(secret,label+random)[0..dlen]
  383. */
  384. if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL )
  385. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  386. if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
  387. return( ret );
  388. mbedtls_md_hmac_starts( &md_ctx, S2, hs );
  389. mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
  390. mbedtls_md_hmac_finish( &md_ctx, tmp );
  391. for( i = 0; i < dlen; i += 20 )
  392. {
  393. mbedtls_md_hmac_reset ( &md_ctx );
  394. mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb );
  395. mbedtls_md_hmac_finish( &md_ctx, h_i );
  396. mbedtls_md_hmac_reset ( &md_ctx );
  397. mbedtls_md_hmac_update( &md_ctx, tmp, 20 );
  398. mbedtls_md_hmac_finish( &md_ctx, tmp );
  399. k = ( i + 20 > dlen ) ? dlen % 20 : 20;
  400. for( j = 0; j < k; j++ )
  401. dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] );
  402. }
  403. mbedtls_md_free( &md_ctx );
  404. mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
  405. mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
  406. return( 0 );
  407. }
  408. #endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */
  409. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  410. static int tls_prf_generic( mbedtls_md_type_t md_type,
  411. const unsigned char *secret, size_t slen,
  412. const char *label,
  413. const unsigned char *random, size_t rlen,
  414. unsigned char *dstbuf, size_t dlen )
  415. {
  416. size_t nb;
  417. size_t i, j, k, md_len;
  418. unsigned char tmp[128];
  419. unsigned char h_i[MBEDTLS_MD_MAX_SIZE];
  420. const mbedtls_md_info_t *md_info;
  421. mbedtls_md_context_t md_ctx;
  422. int ret;
  423. mbedtls_md_init( &md_ctx );
  424. if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL )
  425. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  426. md_len = mbedtls_md_get_size( md_info );
  427. if( sizeof( tmp ) < md_len + strlen( label ) + rlen )
  428. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  429. nb = strlen( label );
  430. memcpy( tmp + md_len, label, nb );
  431. memcpy( tmp + md_len + nb, random, rlen );
  432. nb += rlen;
  433. /*
  434. * Compute P_<hash>(secret, label + random)[0..dlen]
  435. */
  436. if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
  437. return( ret );
  438. mbedtls_md_hmac_starts( &md_ctx, secret, slen );
  439. mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb );
  440. mbedtls_md_hmac_finish( &md_ctx, tmp );
  441. for( i = 0; i < dlen; i += md_len )
  442. {
  443. mbedtls_md_hmac_reset ( &md_ctx );
  444. mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb );
  445. mbedtls_md_hmac_finish( &md_ctx, h_i );
  446. mbedtls_md_hmac_reset ( &md_ctx );
  447. mbedtls_md_hmac_update( &md_ctx, tmp, md_len );
  448. mbedtls_md_hmac_finish( &md_ctx, tmp );
  449. k = ( i + md_len > dlen ) ? dlen % md_len : md_len;
  450. for( j = 0; j < k; j++ )
  451. dstbuf[i + j] = h_i[j];
  452. }
  453. mbedtls_md_free( &md_ctx );
  454. mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
  455. mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
  456. return( 0 );
  457. }
  458. #if defined(MBEDTLS_SHA256_C)
  459. static int tls_prf_sha256( const unsigned char *secret, size_t slen,
  460. const char *label,
  461. const unsigned char *random, size_t rlen,
  462. unsigned char *dstbuf, size_t dlen )
  463. {
  464. return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen,
  465. label, random, rlen, dstbuf, dlen ) );
  466. }
  467. #endif /* MBEDTLS_SHA256_C */
  468. #if defined(MBEDTLS_SHA512_C)
  469. static int tls_prf_sha384( const unsigned char *secret, size_t slen,
  470. const char *label,
  471. const unsigned char *random, size_t rlen,
  472. unsigned char *dstbuf, size_t dlen )
  473. {
  474. return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen,
  475. label, random, rlen, dstbuf, dlen ) );
  476. }
  477. #endif /* MBEDTLS_SHA512_C */
  478. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  479. static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t );
  480. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  481. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  482. static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t );
  483. #endif
  484. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  485. static void ssl_calc_verify_ssl( mbedtls_ssl_context *, unsigned char * );
  486. static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int );
  487. #endif
  488. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  489. static void ssl_calc_verify_tls( mbedtls_ssl_context *, unsigned char * );
  490. static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int );
  491. #endif
  492. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  493. #if defined(MBEDTLS_SHA256_C)
  494. static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t );
  495. static void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *,unsigned char * );
  496. static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int );
  497. #endif
  498. #if defined(MBEDTLS_SHA512_C)
  499. static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t );
  500. static void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *, unsigned char * );
  501. static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int );
  502. #endif
  503. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  504. int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
  505. {
  506. int ret = 0;
  507. unsigned char tmp[64];
  508. unsigned char keyblk[256];
  509. unsigned char *key1;
  510. unsigned char *key2;
  511. unsigned char *mac_enc;
  512. unsigned char *mac_dec;
  513. size_t mac_key_len;
  514. size_t iv_copy_len;
  515. const mbedtls_cipher_info_t *cipher_info;
  516. const mbedtls_md_info_t *md_info;
  517. mbedtls_ssl_session *session = ssl->session_negotiate;
  518. mbedtls_ssl_transform *transform = ssl->transform_negotiate;
  519. mbedtls_ssl_handshake_params *handshake = ssl->handshake;
  520. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
  521. cipher_info = mbedtls_cipher_info_from_type( transform->ciphersuite_info->cipher );
  522. if( cipher_info == NULL )
  523. {
  524. MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %d not found",
  525. transform->ciphersuite_info->cipher ) );
  526. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  527. }
  528. md_info = mbedtls_md_info_from_type( transform->ciphersuite_info->mac );
  529. if( md_info == NULL )
  530. {
  531. MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %d not found",
  532. transform->ciphersuite_info->mac ) );
  533. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  534. }
  535. /*
  536. * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions
  537. */
  538. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  539. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  540. {
  541. handshake->tls_prf = ssl3_prf;
  542. handshake->calc_verify = ssl_calc_verify_ssl;
  543. handshake->calc_finished = ssl_calc_finished_ssl;
  544. }
  545. else
  546. #endif
  547. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  548. if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
  549. {
  550. handshake->tls_prf = tls1_prf;
  551. handshake->calc_verify = ssl_calc_verify_tls;
  552. handshake->calc_finished = ssl_calc_finished_tls;
  553. }
  554. else
  555. #endif
  556. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  557. #if defined(MBEDTLS_SHA512_C)
  558. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
  559. transform->ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
  560. {
  561. handshake->tls_prf = tls_prf_sha384;
  562. handshake->calc_verify = ssl_calc_verify_tls_sha384;
  563. handshake->calc_finished = ssl_calc_finished_tls_sha384;
  564. }
  565. else
  566. #endif
  567. #if defined(MBEDTLS_SHA256_C)
  568. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  569. {
  570. handshake->tls_prf = tls_prf_sha256;
  571. handshake->calc_verify = ssl_calc_verify_tls_sha256;
  572. handshake->calc_finished = ssl_calc_finished_tls_sha256;
  573. }
  574. else
  575. #endif
  576. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  577. {
  578. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  579. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  580. }
  581. /*
  582. * SSLv3:
  583. * master =
  584. * MD5( premaster + SHA1( 'A' + premaster + randbytes ) ) +
  585. * MD5( premaster + SHA1( 'BB' + premaster + randbytes ) ) +
  586. * MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )
  587. *
  588. * TLSv1+:
  589. * master = PRF( premaster, "master secret", randbytes )[0..47]
  590. */
  591. if( handshake->resume == 0 )
  592. {
  593. MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster,
  594. handshake->pmslen );
  595. #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
  596. if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED )
  597. {
  598. unsigned char session_hash[48];
  599. size_t hash_len;
  600. MBEDTLS_SSL_DEBUG_MSG( 3, ( "using extended master secret" ) );
  601. ssl->handshake->calc_verify( ssl, session_hash );
  602. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  603. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  604. {
  605. #if defined(MBEDTLS_SHA512_C)
  606. if( ssl->transform_negotiate->ciphersuite_info->mac ==
  607. MBEDTLS_MD_SHA384 )
  608. {
  609. hash_len = 48;
  610. }
  611. else
  612. #endif
  613. hash_len = 32;
  614. }
  615. else
  616. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  617. hash_len = 36;
  618. MBEDTLS_SSL_DEBUG_BUF( 3, "session hash", session_hash, hash_len );
  619. ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
  620. "extended master secret",
  621. session_hash, hash_len,
  622. session->master, 48 );
  623. if( ret != 0 )
  624. {
  625. MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
  626. return( ret );
  627. }
  628. }
  629. else
  630. #endif
  631. ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
  632. "master secret",
  633. handshake->randbytes, 64,
  634. session->master, 48 );
  635. if( ret != 0 )
  636. {
  637. MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
  638. return( ret );
  639. }
  640. mbedtls_platform_zeroize( handshake->premaster,
  641. sizeof(handshake->premaster) );
  642. }
  643. else
  644. MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );
  645. /*
  646. * Swap the client and server random values.
  647. */
  648. memcpy( tmp, handshake->randbytes, 64 );
  649. memcpy( handshake->randbytes, tmp + 32, 32 );
  650. memcpy( handshake->randbytes + 32, tmp, 32 );
  651. mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
  652. /*
  653. * SSLv3:
  654. * key block =
  655. * MD5( master + SHA1( 'A' + master + randbytes ) ) +
  656. * MD5( master + SHA1( 'BB' + master + randbytes ) ) +
  657. * MD5( master + SHA1( 'CCC' + master + randbytes ) ) +
  658. * MD5( master + SHA1( 'DDDD' + master + randbytes ) ) +
  659. * ...
  660. *
  661. * TLSv1:
  662. * key block = PRF( master, "key expansion", randbytes )
  663. */
  664. ret = handshake->tls_prf( session->master, 48, "key expansion",
  665. handshake->randbytes, 64, keyblk, 256 );
  666. if( ret != 0 )
  667. {
  668. MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
  669. return( ret );
  670. }
  671. MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s",
  672. mbedtls_ssl_get_ciphersuite_name( session->ciphersuite ) ) );
  673. MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", session->master, 48 );
  674. MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 );
  675. MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );
  676. mbedtls_platform_zeroize( handshake->randbytes,
  677. sizeof( handshake->randbytes ) );
  678. /*
  679. * Determine the appropriate key, IV and MAC length.
  680. */
  681. transform->keylen = cipher_info->key_bitlen / 8;
  682. if( cipher_info->mode == MBEDTLS_MODE_GCM ||
  683. cipher_info->mode == MBEDTLS_MODE_CCM ||
  684. cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
  685. {
  686. size_t taglen, explicit_ivlen;
  687. transform->maclen = 0;
  688. mac_key_len = 0;
  689. /* All modes haves 96-bit IVs;
  690. * GCM and CCM has 4 implicit and 8 explicit bytes
  691. * ChachaPoly has all 12 bytes implicit
  692. */
  693. transform->ivlen = 12;
  694. if( cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
  695. transform->fixed_ivlen = 12;
  696. else
  697. transform->fixed_ivlen = 4;
  698. /* All modes have 128-bit tags, except CCM_8 (ciphersuite flag) */
  699. taglen = transform->ciphersuite_info->flags &
  700. MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
  701. /* Minimum length of encrypted record */
  702. explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
  703. transform->minlen = explicit_ivlen + taglen;
  704. }
  705. else
  706. {
  707. /* Initialize HMAC contexts */
  708. if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 ||
  709. ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 )
  710. {
  711. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
  712. return( ret );
  713. }
  714. /* Get MAC length */
  715. mac_key_len = mbedtls_md_get_size( md_info );
  716. transform->maclen = mac_key_len;
  717. #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
  718. /*
  719. * If HMAC is to be truncated, we shall keep the leftmost bytes,
  720. * (rfc 6066 page 13 or rfc 2104 section 4),
  721. * so we only need to adjust the length here.
  722. */
  723. if( session->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
  724. {
  725. transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN;
  726. #if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT)
  727. /* Fall back to old, non-compliant version of the truncated
  728. * HMAC implementation which also truncates the key
  729. * (Mbed TLS versions from 1.3 to 2.6.0) */
  730. mac_key_len = transform->maclen;
  731. #endif
  732. }
  733. #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
  734. /* IV length */
  735. transform->ivlen = cipher_info->iv_size;
  736. /* Minimum length */
  737. if( cipher_info->mode == MBEDTLS_MODE_STREAM )
  738. transform->minlen = transform->maclen;
  739. else
  740. {
  741. /*
  742. * GenericBlockCipher:
  743. * 1. if EtM is in use: one block plus MAC
  744. * otherwise: * first multiple of blocklen greater than maclen
  745. * 2. IV except for SSL3 and TLS 1.0
  746. */
  747. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  748. if( session->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
  749. {
  750. transform->minlen = transform->maclen
  751. + cipher_info->block_size;
  752. }
  753. else
  754. #endif
  755. {
  756. transform->minlen = transform->maclen
  757. + cipher_info->block_size
  758. - transform->maclen % cipher_info->block_size;
  759. }
  760. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
  761. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
  762. ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_1 )
  763. ; /* No need to adjust minlen */
  764. else
  765. #endif
  766. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  767. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 ||
  768. ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  769. {
  770. transform->minlen += transform->ivlen;
  771. }
  772. else
  773. #endif
  774. {
  775. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  776. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  777. }
  778. }
  779. }
  780. MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
  781. transform->keylen, transform->minlen, transform->ivlen,
  782. transform->maclen ) );
  783. /*
  784. * Finally setup the cipher contexts, IVs and MAC secrets.
  785. */
  786. #if defined(MBEDTLS_SSL_CLI_C)
  787. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  788. {
  789. key1 = keyblk + mac_key_len * 2;
  790. key2 = keyblk + mac_key_len * 2 + transform->keylen;
  791. mac_enc = keyblk;
  792. mac_dec = keyblk + mac_key_len;
  793. /*
  794. * This is not used in TLS v1.1.
  795. */
  796. iv_copy_len = ( transform->fixed_ivlen ) ?
  797. transform->fixed_ivlen : transform->ivlen;
  798. memcpy( transform->iv_enc, key2 + transform->keylen, iv_copy_len );
  799. memcpy( transform->iv_dec, key2 + transform->keylen + iv_copy_len,
  800. iv_copy_len );
  801. }
  802. else
  803. #endif /* MBEDTLS_SSL_CLI_C */
  804. #if defined(MBEDTLS_SSL_SRV_C)
  805. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  806. {
  807. key1 = keyblk + mac_key_len * 2 + transform->keylen;
  808. key2 = keyblk + mac_key_len * 2;
  809. mac_enc = keyblk + mac_key_len;
  810. mac_dec = keyblk;
  811. /*
  812. * This is not used in TLS v1.1.
  813. */
  814. iv_copy_len = ( transform->fixed_ivlen ) ?
  815. transform->fixed_ivlen : transform->ivlen;
  816. memcpy( transform->iv_dec, key1 + transform->keylen, iv_copy_len );
  817. memcpy( transform->iv_enc, key1 + transform->keylen + iv_copy_len,
  818. iv_copy_len );
  819. }
  820. else
  821. #endif /* MBEDTLS_SSL_SRV_C */
  822. {
  823. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  824. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  825. }
  826. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  827. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  828. {
  829. if( mac_key_len > sizeof transform->mac_enc )
  830. {
  831. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  832. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  833. }
  834. memcpy( transform->mac_enc, mac_enc, mac_key_len );
  835. memcpy( transform->mac_dec, mac_dec, mac_key_len );
  836. }
  837. else
  838. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  839. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  840. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  841. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
  842. {
  843. /* For HMAC-based ciphersuites, initialize the HMAC transforms.
  844. For AEAD-based ciphersuites, there is nothing to do here. */
  845. if( mac_key_len != 0 )
  846. {
  847. mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, mac_key_len );
  848. mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, mac_key_len );
  849. }
  850. }
  851. else
  852. #endif
  853. {
  854. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  855. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  856. }
  857. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  858. if( mbedtls_ssl_hw_record_init != NULL )
  859. {
  860. int ret = 0;
  861. MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) );
  862. if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, transform->keylen,
  863. transform->iv_enc, transform->iv_dec,
  864. iv_copy_len,
  865. mac_enc, mac_dec,
  866. mac_key_len ) ) != 0 )
  867. {
  868. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret );
  869. return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  870. }
  871. }
  872. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  873. #if defined(MBEDTLS_SSL_EXPORT_KEYS)
  874. if( ssl->conf->f_export_keys != NULL )
  875. {
  876. ssl->conf->f_export_keys( ssl->conf->p_export_keys,
  877. session->master, keyblk,
  878. mac_key_len, transform->keylen,
  879. iv_copy_len );
  880. }
  881. #endif
  882. if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,
  883. cipher_info ) ) != 0 )
  884. {
  885. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
  886. return( ret );
  887. }
  888. if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,
  889. cipher_info ) ) != 0 )
  890. {
  891. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
  892. return( ret );
  893. }
  894. if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1,
  895. cipher_info->key_bitlen,
  896. MBEDTLS_ENCRYPT ) ) != 0 )
  897. {
  898. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
  899. return( ret );
  900. }
  901. if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2,
  902. cipher_info->key_bitlen,
  903. MBEDTLS_DECRYPT ) ) != 0 )
  904. {
  905. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
  906. return( ret );
  907. }
  908. #if defined(MBEDTLS_CIPHER_MODE_CBC)
  909. if( cipher_info->mode == MBEDTLS_MODE_CBC )
  910. {
  911. if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc,
  912. MBEDTLS_PADDING_NONE ) ) != 0 )
  913. {
  914. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
  915. return( ret );
  916. }
  917. if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec,
  918. MBEDTLS_PADDING_NONE ) ) != 0 )
  919. {
  920. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
  921. return( ret );
  922. }
  923. }
  924. #endif /* MBEDTLS_CIPHER_MODE_CBC */
  925. mbedtls_platform_zeroize( keyblk, sizeof( keyblk ) );
  926. #if defined(MBEDTLS_ZLIB_SUPPORT)
  927. // Initialize compression
  928. //
  929. if( session->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
  930. {
  931. if( ssl->compress_buf == NULL )
  932. {
  933. MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) );
  934. ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );
  935. if( ssl->compress_buf == NULL )
  936. {
  937. MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
  938. MBEDTLS_SSL_COMPRESS_BUFFER_LEN ) );
  939. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  940. }
  941. }
  942. MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );
  943. memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
  944. memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
  945. if( deflateInit( &transform->ctx_deflate,
  946. Z_DEFAULT_COMPRESSION ) != Z_OK ||
  947. inflateInit( &transform->ctx_inflate ) != Z_OK )
  948. {
  949. MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
  950. return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
  951. }
  952. }
  953. #endif /* MBEDTLS_ZLIB_SUPPORT */
  954. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
  955. return( 0 );
  956. }
  957. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  958. void ssl_calc_verify_ssl( mbedtls_ssl_context *ssl, unsigned char hash[36] )
  959. {
  960. mbedtls_md5_context md5;
  961. mbedtls_sha1_context sha1;
  962. unsigned char pad_1[48];
  963. unsigned char pad_2[48];
  964. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
  965. mbedtls_md5_init( &md5 );
  966. mbedtls_sha1_init( &sha1 );
  967. mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
  968. mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
  969. memset( pad_1, 0x36, 48 );
  970. memset( pad_2, 0x5C, 48 );
  971. mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 );
  972. mbedtls_md5_update_ret( &md5, pad_1, 48 );
  973. mbedtls_md5_finish_ret( &md5, hash );
  974. mbedtls_md5_starts_ret( &md5 );
  975. mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 );
  976. mbedtls_md5_update_ret( &md5, pad_2, 48 );
  977. mbedtls_md5_update_ret( &md5, hash, 16 );
  978. mbedtls_md5_finish_ret( &md5, hash );
  979. mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 );
  980. mbedtls_sha1_update_ret( &sha1, pad_1, 40 );
  981. mbedtls_sha1_finish_ret( &sha1, hash + 16 );
  982. mbedtls_sha1_starts_ret( &sha1 );
  983. mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 );
  984. mbedtls_sha1_update_ret( &sha1, pad_2, 40 );
  985. mbedtls_sha1_update_ret( &sha1, hash + 16, 20 );
  986. mbedtls_sha1_finish_ret( &sha1, hash + 16 );
  987. MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
  988. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
  989. mbedtls_md5_free( &md5 );
  990. mbedtls_sha1_free( &sha1 );
  991. return;
  992. }
  993. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  994. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  995. void ssl_calc_verify_tls( mbedtls_ssl_context *ssl, unsigned char hash[36] )
  996. {
  997. mbedtls_md5_context md5;
  998. mbedtls_sha1_context sha1;
  999. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );
  1000. mbedtls_md5_init( &md5 );
  1001. mbedtls_sha1_init( &sha1 );
  1002. mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
  1003. mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
  1004. mbedtls_md5_finish_ret( &md5, hash );
  1005. mbedtls_sha1_finish_ret( &sha1, hash + 16 );
  1006. MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
  1007. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
  1008. mbedtls_md5_free( &md5 );
  1009. mbedtls_sha1_free( &sha1 );
  1010. return;
  1011. }
  1012. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
  1013. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1014. #if defined(MBEDTLS_SHA256_C)
  1015. void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *ssl, unsigned char hash[32] )
  1016. {
  1017. mbedtls_sha256_context sha256;
  1018. mbedtls_sha256_init( &sha256 );
  1019. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
  1020. mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
  1021. mbedtls_sha256_finish_ret( &sha256, hash );
  1022. MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 );
  1023. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
  1024. mbedtls_sha256_free( &sha256 );
  1025. return;
  1026. }
  1027. #endif /* MBEDTLS_SHA256_C */
  1028. #if defined(MBEDTLS_SHA512_C)
  1029. void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *ssl, unsigned char hash[48] )
  1030. {
  1031. mbedtls_sha512_context sha512;
  1032. mbedtls_sha512_init( &sha512 );
  1033. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );
  1034. mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
  1035. mbedtls_sha512_finish_ret( &sha512, hash );
  1036. MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 );
  1037. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
  1038. mbedtls_sha512_free( &sha512 );
  1039. return;
  1040. }
  1041. #endif /* MBEDTLS_SHA512_C */
  1042. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  1043. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
  1044. int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex )
  1045. {
  1046. unsigned char *p = ssl->handshake->premaster;
  1047. unsigned char *end = p + sizeof( ssl->handshake->premaster );
  1048. const unsigned char *psk = ssl->conf->psk;
  1049. size_t psk_len = ssl->conf->psk_len;
  1050. /* If the psk callback was called, use its result */
  1051. if( ssl->handshake->psk != NULL )
  1052. {
  1053. psk = ssl->handshake->psk;
  1054. psk_len = ssl->handshake->psk_len;
  1055. }
  1056. /*
  1057. * PMS = struct {
  1058. * opaque other_secret<0..2^16-1>;
  1059. * opaque psk<0..2^16-1>;
  1060. * };
  1061. * with "other_secret" depending on the particular key exchange
  1062. */
  1063. #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
  1064. if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK )
  1065. {
  1066. if( end - p < 2 )
  1067. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1068. *(p++) = (unsigned char)( psk_len >> 8 );
  1069. *(p++) = (unsigned char)( psk_len );
  1070. if( end < p || (size_t)( end - p ) < psk_len )
  1071. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1072. memset( p, 0, psk_len );
  1073. p += psk_len;
  1074. }
  1075. else
  1076. #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
  1077. #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
  1078. if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
  1079. {
  1080. /*
  1081. * other_secret already set by the ClientKeyExchange message,
  1082. * and is 48 bytes long
  1083. */
  1084. if( end - p < 2 )
  1085. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1086. *p++ = 0;
  1087. *p++ = 48;
  1088. p += 48;
  1089. }
  1090. else
  1091. #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
  1092. #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
  1093. if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
  1094. {
  1095. int ret;
  1096. size_t len;
  1097. /* Write length only when we know the actual value */
  1098. if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
  1099. p + 2, end - ( p + 2 ), &len,
  1100. ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
  1101. {
  1102. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
  1103. return( ret );
  1104. }
  1105. *(p++) = (unsigned char)( len >> 8 );
  1106. *(p++) = (unsigned char)( len );
  1107. p += len;
  1108. MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K );
  1109. }
  1110. else
  1111. #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
  1112. #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
  1113. if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
  1114. {
  1115. int ret;
  1116. size_t zlen;
  1117. if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen,
  1118. p + 2, end - ( p + 2 ),
  1119. ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
  1120. {
  1121. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
  1122. return( ret );
  1123. }
  1124. *(p++) = (unsigned char)( zlen >> 8 );
  1125. *(p++) = (unsigned char)( zlen );
  1126. p += zlen;
  1127. MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
  1128. MBEDTLS_DEBUG_ECDH_Z );
  1129. }
  1130. else
  1131. #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
  1132. {
  1133. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1134. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1135. }
  1136. /* opaque psk<0..2^16-1>; */
  1137. if( end - p < 2 )
  1138. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1139. *(p++) = (unsigned char)( psk_len >> 8 );
  1140. *(p++) = (unsigned char)( psk_len );
  1141. if( end < p || (size_t)( end - p ) < psk_len )
  1142. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1143. memcpy( p, psk, psk_len );
  1144. p += psk_len;
  1145. ssl->handshake->pmslen = p - ssl->handshake->premaster;
  1146. return( 0 );
  1147. }
  1148. #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
  1149. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  1150. /*
  1151. * SSLv3.0 MAC functions
  1152. */
  1153. #define SSL_MAC_MAX_BYTES 20 /* MD-5 or SHA-1 */
  1154. static void ssl_mac( mbedtls_md_context_t *md_ctx,
  1155. const unsigned char *secret,
  1156. const unsigned char *buf, size_t len,
  1157. const unsigned char *ctr, int type,
  1158. unsigned char out[SSL_MAC_MAX_BYTES] )
  1159. {
  1160. unsigned char header[11];
  1161. unsigned char padding[48];
  1162. int padlen;
  1163. int md_size = mbedtls_md_get_size( md_ctx->md_info );
  1164. int md_type = mbedtls_md_get_type( md_ctx->md_info );
  1165. /* Only MD5 and SHA-1 supported */
  1166. if( md_type == MBEDTLS_MD_MD5 )
  1167. padlen = 48;
  1168. else
  1169. padlen = 40;
  1170. memcpy( header, ctr, 8 );
  1171. header[ 8] = (unsigned char) type;
  1172. header[ 9] = (unsigned char)( len >> 8 );
  1173. header[10] = (unsigned char)( len );
  1174. memset( padding, 0x36, padlen );
  1175. mbedtls_md_starts( md_ctx );
  1176. mbedtls_md_update( md_ctx, secret, md_size );
  1177. mbedtls_md_update( md_ctx, padding, padlen );
  1178. mbedtls_md_update( md_ctx, header, 11 );
  1179. mbedtls_md_update( md_ctx, buf, len );
  1180. mbedtls_md_finish( md_ctx, out );
  1181. memset( padding, 0x5C, padlen );
  1182. mbedtls_md_starts( md_ctx );
  1183. mbedtls_md_update( md_ctx, secret, md_size );
  1184. mbedtls_md_update( md_ctx, padding, padlen );
  1185. mbedtls_md_update( md_ctx, out, md_size );
  1186. mbedtls_md_finish( md_ctx, out );
  1187. }
  1188. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  1189. #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \
  1190. ( defined(MBEDTLS_CIPHER_MODE_CBC) && \
  1191. ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C)) )
  1192. #define SSL_SOME_MODES_USE_MAC
  1193. #endif
  1194. /* The function below is only used in the Lucky 13 counter-measure in
  1195. * ssl_decrypt_buf(). These are the defines that guard the call site. */
  1196. #if defined(SSL_SOME_MODES_USE_MAC) && \
  1197. ( defined(MBEDTLS_SSL_PROTO_TLS1) || \
  1198. defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  1199. defined(MBEDTLS_SSL_PROTO_TLS1_2) )
  1200. /* This function makes sure every byte in the memory region is accessed
  1201. * (in ascending addresses order) */
  1202. static void ssl_read_memory( unsigned char *p, size_t len )
  1203. {
  1204. unsigned char acc = 0;
  1205. volatile unsigned char force;
  1206. for( ; len != 0; p++, len-- )
  1207. acc ^= *p;
  1208. force = acc;
  1209. (void) force;
  1210. }
  1211. #endif /* SSL_SOME_MODES_USE_MAC && ( TLS1 || TLS1_1 || TLS1_2 ) */
  1212. /*
  1213. * Encryption/decryption functions
  1214. */
  1215. static int ssl_encrypt_buf( mbedtls_ssl_context *ssl )
  1216. {
  1217. mbedtls_cipher_mode_t mode;
  1218. int auth_done = 0;
  1219. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );
  1220. if( ssl->session_out == NULL || ssl->transform_out == NULL )
  1221. {
  1222. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1223. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1224. }
  1225. mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc );
  1226. MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload",
  1227. ssl->out_msg, ssl->out_msglen );
  1228. /*
  1229. * Add MAC before if needed
  1230. */
  1231. #if defined(SSL_SOME_MODES_USE_MAC)
  1232. if( mode == MBEDTLS_MODE_STREAM ||
  1233. ( mode == MBEDTLS_MODE_CBC
  1234. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  1235. && ssl->session_out->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED
  1236. #endif
  1237. ) )
  1238. {
  1239. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  1240. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  1241. {
  1242. unsigned char mac[SSL_MAC_MAX_BYTES];
  1243. ssl_mac( &ssl->transform_out->md_ctx_enc,
  1244. ssl->transform_out->mac_enc,
  1245. ssl->out_msg, ssl->out_msglen,
  1246. ssl->out_ctr, ssl->out_msgtype,
  1247. mac );
  1248. memcpy( ssl->out_msg + ssl->out_msglen, mac, ssl->transform_out->maclen );
  1249. }
  1250. else
  1251. #endif
  1252. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  1253. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1254. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
  1255. {
  1256. unsigned char mac[MBEDTLS_SSL_MAC_ADD];
  1257. mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_ctr, 8 );
  1258. mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_hdr, 3 );
  1259. mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_len, 2 );
  1260. mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
  1261. ssl->out_msg, ssl->out_msglen );
  1262. mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, mac );
  1263. mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
  1264. memcpy( ssl->out_msg + ssl->out_msglen, mac, ssl->transform_out->maclen );
  1265. }
  1266. else
  1267. #endif
  1268. {
  1269. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1270. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1271. }
  1272. MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac",
  1273. ssl->out_msg + ssl->out_msglen,
  1274. ssl->transform_out->maclen );
  1275. ssl->out_msglen += ssl->transform_out->maclen;
  1276. auth_done++;
  1277. }
  1278. #endif /* AEAD not the only option */
  1279. /*
  1280. * Encrypt
  1281. */
  1282. #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
  1283. if( mode == MBEDTLS_MODE_STREAM )
  1284. {
  1285. int ret;
  1286. size_t olen = 0;
  1287. MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
  1288. "including %d bytes of padding",
  1289. ssl->out_msglen, 0 ) );
  1290. if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
  1291. ssl->transform_out->iv_enc,
  1292. ssl->transform_out->ivlen,
  1293. ssl->out_msg, ssl->out_msglen,
  1294. ssl->out_msg, &olen ) ) != 0 )
  1295. {
  1296. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
  1297. return( ret );
  1298. }
  1299. if( ssl->out_msglen != olen )
  1300. {
  1301. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1302. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1303. }
  1304. }
  1305. else
  1306. #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
  1307. #if defined(MBEDTLS_GCM_C) || \
  1308. defined(MBEDTLS_CCM_C) || \
  1309. defined(MBEDTLS_CHACHAPOLY_C)
  1310. if( mode == MBEDTLS_MODE_GCM ||
  1311. mode == MBEDTLS_MODE_CCM ||
  1312. mode == MBEDTLS_MODE_CHACHAPOLY )
  1313. {
  1314. int ret;
  1315. size_t enc_msglen, olen;
  1316. unsigned char *enc_msg;
  1317. unsigned char add_data[13];
  1318. unsigned char iv[12];
  1319. mbedtls_ssl_transform *transform = ssl->transform_out;
  1320. unsigned char taglen = transform->ciphersuite_info->flags &
  1321. MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
  1322. size_t explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
  1323. /*
  1324. * Prepare additional authenticated data
  1325. */
  1326. memcpy( add_data, ssl->out_ctr, 8 );
  1327. add_data[8] = ssl->out_msgtype;
  1328. mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
  1329. ssl->conf->transport, add_data + 9 );
  1330. add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF;
  1331. add_data[12] = ssl->out_msglen & 0xFF;
  1332. MBEDTLS_SSL_DEBUG_BUF( 4, "additional data for AEAD", add_data, 13 );
  1333. /*
  1334. * Generate IV
  1335. */
  1336. if( transform->ivlen == 12 && transform->fixed_ivlen == 4 )
  1337. {
  1338. /* GCM and CCM: fixed || explicit (=seqnum) */
  1339. memcpy( iv, transform->iv_enc, transform->fixed_ivlen );
  1340. memcpy( iv + transform->fixed_ivlen, ssl->out_ctr, 8 );
  1341. memcpy( ssl->out_iv, ssl->out_ctr, 8 );
  1342. }
  1343. else if( transform->ivlen == 12 && transform->fixed_ivlen == 12 )
  1344. {
  1345. /* ChachaPoly: fixed XOR sequence number */
  1346. unsigned char i;
  1347. memcpy( iv, transform->iv_enc, transform->fixed_ivlen );
  1348. for( i = 0; i < 8; i++ )
  1349. iv[i+4] ^= ssl->out_ctr[i];
  1350. }
  1351. else
  1352. {
  1353. /* Reminder if we ever add an AEAD mode with a different size */
  1354. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1355. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1356. }
  1357. MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (internal)",
  1358. iv, transform->ivlen );
  1359. MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (transmitted)",
  1360. ssl->out_iv, explicit_ivlen );
  1361. /*
  1362. * Fix message length with added IV
  1363. */
  1364. enc_msg = ssl->out_msg;
  1365. enc_msglen = ssl->out_msglen;
  1366. ssl->out_msglen += explicit_ivlen;
  1367. MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
  1368. "including 0 bytes of padding",
  1369. ssl->out_msglen ) );
  1370. /*
  1371. * Encrypt and authenticate
  1372. */
  1373. if( ( ret = mbedtls_cipher_auth_encrypt( &transform->cipher_ctx_enc,
  1374. iv, transform->ivlen,
  1375. add_data, 13,
  1376. enc_msg, enc_msglen,
  1377. enc_msg, &olen,
  1378. enc_msg + enc_msglen, taglen ) ) != 0 )
  1379. {
  1380. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret );
  1381. return( ret );
  1382. }
  1383. if( olen != enc_msglen )
  1384. {
  1385. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1386. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1387. }
  1388. ssl->out_msglen += taglen;
  1389. auth_done++;
  1390. MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", enc_msg + enc_msglen, taglen );
  1391. }
  1392. else
  1393. #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
  1394. #if defined(MBEDTLS_CIPHER_MODE_CBC) && \
  1395. ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C) )
  1396. if( mode == MBEDTLS_MODE_CBC )
  1397. {
  1398. int ret;
  1399. unsigned char *enc_msg;
  1400. size_t enc_msglen, padlen, olen = 0, i;
  1401. padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) %
  1402. ssl->transform_out->ivlen;
  1403. if( padlen == ssl->transform_out->ivlen )
  1404. padlen = 0;
  1405. for( i = 0; i <= padlen; i++ )
  1406. ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen;
  1407. ssl->out_msglen += padlen + 1;
  1408. enc_msglen = ssl->out_msglen;
  1409. enc_msg = ssl->out_msg;
  1410. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1411. /*
  1412. * Prepend per-record IV for block cipher in TLS v1.1 and up as per
  1413. * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
  1414. */
  1415. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  1416. {
  1417. /*
  1418. * Generate IV
  1419. */
  1420. ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->transform_out->iv_enc,
  1421. ssl->transform_out->ivlen );
  1422. if( ret != 0 )
  1423. return( ret );
  1424. memcpy( ssl->out_iv, ssl->transform_out->iv_enc,
  1425. ssl->transform_out->ivlen );
  1426. /*
  1427. * Fix pointer positions and message length with added IV
  1428. */
  1429. enc_msg = ssl->out_msg;
  1430. enc_msglen = ssl->out_msglen;
  1431. ssl->out_msglen += ssl->transform_out->ivlen;
  1432. }
  1433. #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
  1434. MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
  1435. "including %d bytes of IV and %d bytes of padding",
  1436. ssl->out_msglen, ssl->transform_out->ivlen,
  1437. padlen + 1 ) );
  1438. if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
  1439. ssl->transform_out->iv_enc,
  1440. ssl->transform_out->ivlen,
  1441. enc_msg, enc_msglen,
  1442. enc_msg, &olen ) ) != 0 )
  1443. {
  1444. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
  1445. return( ret );
  1446. }
  1447. if( enc_msglen != olen )
  1448. {
  1449. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1450. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1451. }
  1452. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
  1453. if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
  1454. {
  1455. /*
  1456. * Save IV in SSL3 and TLS1
  1457. */
  1458. memcpy( ssl->transform_out->iv_enc,
  1459. ssl->transform_out->cipher_ctx_enc.iv,
  1460. ssl->transform_out->ivlen );
  1461. }
  1462. #endif
  1463. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  1464. if( auth_done == 0 )
  1465. {
  1466. unsigned char mac[MBEDTLS_SSL_MAC_ADD];
  1467. /*
  1468. * MAC(MAC_write_key, seq_num +
  1469. * TLSCipherText.type +
  1470. * TLSCipherText.version +
  1471. * length_of( (IV +) ENC(...) ) +
  1472. * IV + // except for TLS 1.0
  1473. * ENC(content + padding + padding_length));
  1474. */
  1475. unsigned char pseudo_hdr[13];
  1476. MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
  1477. memcpy( pseudo_hdr + 0, ssl->out_ctr, 8 );
  1478. memcpy( pseudo_hdr + 8, ssl->out_hdr, 3 );
  1479. pseudo_hdr[11] = (unsigned char)( ( ssl->out_msglen >> 8 ) & 0xFF );
  1480. pseudo_hdr[12] = (unsigned char)( ( ssl->out_msglen ) & 0xFF );
  1481. MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
  1482. mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, pseudo_hdr, 13 );
  1483. mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
  1484. ssl->out_iv, ssl->out_msglen );
  1485. mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, mac );
  1486. mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
  1487. memcpy( ssl->out_iv + ssl->out_msglen, mac,
  1488. ssl->transform_out->maclen );
  1489. ssl->out_msglen += ssl->transform_out->maclen;
  1490. auth_done++;
  1491. }
  1492. #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
  1493. }
  1494. else
  1495. #endif /* MBEDTLS_CIPHER_MODE_CBC &&
  1496. ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C || MBEDTLS_ARIA_C ) */
  1497. {
  1498. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1499. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1500. }
  1501. /* Make extra sure authentication was performed, exactly once */
  1502. if( auth_done != 1 )
  1503. {
  1504. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1505. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1506. }
  1507. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );
  1508. return( 0 );
  1509. }
  1510. static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
  1511. {
  1512. mbedtls_cipher_mode_t mode;
  1513. int auth_done = 0;
  1514. #if defined(SSL_SOME_MODES_USE_MAC)
  1515. size_t padlen = 0, correct = 1;
  1516. #endif
  1517. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) );
  1518. if( ssl->session_in == NULL || ssl->transform_in == NULL )
  1519. {
  1520. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1521. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1522. }
  1523. mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_in->cipher_ctx_dec );
  1524. if( ssl->in_msglen < ssl->transform_in->minlen )
  1525. {
  1526. MBEDTLS_SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)",
  1527. ssl->in_msglen, ssl->transform_in->minlen ) );
  1528. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1529. }
  1530. #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
  1531. if( mode == MBEDTLS_MODE_STREAM )
  1532. {
  1533. int ret;
  1534. size_t olen = 0;
  1535. padlen = 0;
  1536. if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
  1537. ssl->transform_in->iv_dec,
  1538. ssl->transform_in->ivlen,
  1539. ssl->in_msg, ssl->in_msglen,
  1540. ssl->in_msg, &olen ) ) != 0 )
  1541. {
  1542. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
  1543. return( ret );
  1544. }
  1545. if( ssl->in_msglen != olen )
  1546. {
  1547. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1548. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1549. }
  1550. }
  1551. else
  1552. #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
  1553. #if defined(MBEDTLS_GCM_C) || \
  1554. defined(MBEDTLS_CCM_C) || \
  1555. defined(MBEDTLS_CHACHAPOLY_C)
  1556. if( mode == MBEDTLS_MODE_GCM ||
  1557. mode == MBEDTLS_MODE_CCM ||
  1558. mode == MBEDTLS_MODE_CHACHAPOLY )
  1559. {
  1560. int ret;
  1561. size_t dec_msglen, olen;
  1562. unsigned char *dec_msg;
  1563. unsigned char *dec_msg_result;
  1564. unsigned char add_data[13];
  1565. unsigned char iv[12];
  1566. mbedtls_ssl_transform *transform = ssl->transform_in;
  1567. unsigned char taglen = transform->ciphersuite_info->flags &
  1568. MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
  1569. size_t explicit_iv_len = transform->ivlen - transform->fixed_ivlen;
  1570. /*
  1571. * Compute and update sizes
  1572. */
  1573. if( ssl->in_msglen < explicit_iv_len + taglen )
  1574. {
  1575. MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) "
  1576. "+ taglen (%d)", ssl->in_msglen,
  1577. explicit_iv_len, taglen ) );
  1578. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1579. }
  1580. dec_msglen = ssl->in_msglen - explicit_iv_len - taglen;
  1581. dec_msg = ssl->in_msg;
  1582. dec_msg_result = ssl->in_msg;
  1583. ssl->in_msglen = dec_msglen;
  1584. /*
  1585. * Prepare additional authenticated data
  1586. */
  1587. memcpy( add_data, ssl->in_ctr, 8 );
  1588. add_data[8] = ssl->in_msgtype;
  1589. mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
  1590. ssl->conf->transport, add_data + 9 );
  1591. add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF;
  1592. add_data[12] = ssl->in_msglen & 0xFF;
  1593. MBEDTLS_SSL_DEBUG_BUF( 4, "additional data for AEAD", add_data, 13 );
  1594. /*
  1595. * Prepare IV
  1596. */
  1597. if( transform->ivlen == 12 && transform->fixed_ivlen == 4 )
  1598. {
  1599. /* GCM and CCM: fixed || explicit (transmitted) */
  1600. memcpy( iv, transform->iv_dec, transform->fixed_ivlen );
  1601. memcpy( iv + transform->fixed_ivlen, ssl->in_iv, 8 );
  1602. }
  1603. else if( transform->ivlen == 12 && transform->fixed_ivlen == 12 )
  1604. {
  1605. /* ChachaPoly: fixed XOR sequence number */
  1606. unsigned char i;
  1607. memcpy( iv, transform->iv_dec, transform->fixed_ivlen );
  1608. for( i = 0; i < 8; i++ )
  1609. iv[i+4] ^= ssl->in_ctr[i];
  1610. }
  1611. else
  1612. {
  1613. /* Reminder if we ever add an AEAD mode with a different size */
  1614. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1615. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1616. }
  1617. MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", iv, transform->ivlen );
  1618. MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, taglen );
  1619. /*
  1620. * Decrypt and authenticate
  1621. */
  1622. if( ( ret = mbedtls_cipher_auth_decrypt( &ssl->transform_in->cipher_ctx_dec,
  1623. iv, transform->ivlen,
  1624. add_data, 13,
  1625. dec_msg, dec_msglen,
  1626. dec_msg_result, &olen,
  1627. dec_msg + dec_msglen, taglen ) ) != 0 )
  1628. {
  1629. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret );
  1630. if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED )
  1631. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1632. return( ret );
  1633. }
  1634. auth_done++;
  1635. if( olen != dec_msglen )
  1636. {
  1637. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1638. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1639. }
  1640. }
  1641. else
  1642. #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
  1643. #if defined(MBEDTLS_CIPHER_MODE_CBC) && \
  1644. ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C) )
  1645. if( mode == MBEDTLS_MODE_CBC )
  1646. {
  1647. /*
  1648. * Decrypt and check the padding
  1649. */
  1650. int ret;
  1651. unsigned char *dec_msg;
  1652. unsigned char *dec_msg_result;
  1653. size_t dec_msglen;
  1654. size_t minlen = 0;
  1655. size_t olen = 0;
  1656. /*
  1657. * Check immediate ciphertext sanity
  1658. */
  1659. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1660. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  1661. minlen += ssl->transform_in->ivlen;
  1662. #endif
  1663. if( ssl->in_msglen < minlen + ssl->transform_in->ivlen ||
  1664. ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 )
  1665. {
  1666. MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) "
  1667. "+ 1 ) ( + expl IV )", ssl->in_msglen,
  1668. ssl->transform_in->ivlen,
  1669. ssl->transform_in->maclen ) );
  1670. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1671. }
  1672. dec_msglen = ssl->in_msglen;
  1673. dec_msg = ssl->in_msg;
  1674. dec_msg_result = ssl->in_msg;
  1675. /*
  1676. * Authenticate before decrypt if enabled
  1677. */
  1678. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  1679. if( ssl->session_in->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
  1680. {
  1681. unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
  1682. unsigned char pseudo_hdr[13];
  1683. MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
  1684. dec_msglen -= ssl->transform_in->maclen;
  1685. ssl->in_msglen -= ssl->transform_in->maclen;
  1686. memcpy( pseudo_hdr + 0, ssl->in_ctr, 8 );
  1687. memcpy( pseudo_hdr + 8, ssl->in_hdr, 3 );
  1688. pseudo_hdr[11] = (unsigned char)( ( ssl->in_msglen >> 8 ) & 0xFF );
  1689. pseudo_hdr[12] = (unsigned char)( ( ssl->in_msglen ) & 0xFF );
  1690. MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
  1691. mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, pseudo_hdr, 13 );
  1692. mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec,
  1693. ssl->in_iv, ssl->in_msglen );
  1694. mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, mac_expect );
  1695. mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
  1696. MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", ssl->in_iv + ssl->in_msglen,
  1697. ssl->transform_in->maclen );
  1698. MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect,
  1699. ssl->transform_in->maclen );
  1700. if( mbedtls_ssl_safer_memcmp( ssl->in_iv + ssl->in_msglen, mac_expect,
  1701. ssl->transform_in->maclen ) != 0 )
  1702. {
  1703. MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
  1704. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1705. }
  1706. auth_done++;
  1707. }
  1708. #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
  1709. /*
  1710. * Check length sanity
  1711. */
  1712. if( ssl->in_msglen % ssl->transform_in->ivlen != 0 )
  1713. {
  1714. MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0",
  1715. ssl->in_msglen, ssl->transform_in->ivlen ) );
  1716. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1717. }
  1718. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1719. /*
  1720. * Initialize for prepended IV for block cipher in TLS v1.1 and up
  1721. */
  1722. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  1723. {
  1724. unsigned char i;
  1725. dec_msglen -= ssl->transform_in->ivlen;
  1726. ssl->in_msglen -= ssl->transform_in->ivlen;
  1727. for( i = 0; i < ssl->transform_in->ivlen; i++ )
  1728. ssl->transform_in->iv_dec[i] = ssl->in_iv[i];
  1729. }
  1730. #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
  1731. if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
  1732. ssl->transform_in->iv_dec,
  1733. ssl->transform_in->ivlen,
  1734. dec_msg, dec_msglen,
  1735. dec_msg_result, &olen ) ) != 0 )
  1736. {
  1737. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
  1738. return( ret );
  1739. }
  1740. if( dec_msglen != olen )
  1741. {
  1742. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1743. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1744. }
  1745. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
  1746. if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
  1747. {
  1748. /*
  1749. * Save IV in SSL3 and TLS1
  1750. */
  1751. memcpy( ssl->transform_in->iv_dec,
  1752. ssl->transform_in->cipher_ctx_dec.iv,
  1753. ssl->transform_in->ivlen );
  1754. }
  1755. #endif
  1756. padlen = 1 + ssl->in_msg[ssl->in_msglen - 1];
  1757. if( ssl->in_msglen < ssl->transform_in->maclen + padlen &&
  1758. auth_done == 0 )
  1759. {
  1760. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1761. MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)",
  1762. ssl->in_msglen, ssl->transform_in->maclen, padlen ) );
  1763. #endif
  1764. padlen = 0;
  1765. correct = 0;
  1766. }
  1767. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  1768. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  1769. {
  1770. if( padlen > ssl->transform_in->ivlen )
  1771. {
  1772. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1773. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, "
  1774. "should be no more than %d",
  1775. padlen, ssl->transform_in->ivlen ) );
  1776. #endif
  1777. correct = 0;
  1778. }
  1779. }
  1780. else
  1781. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  1782. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  1783. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1784. if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
  1785. {
  1786. /*
  1787. * TLSv1+: always check the padding up to the first failure
  1788. * and fake check up to 256 bytes of padding
  1789. */
  1790. size_t pad_count = 0, real_count = 1;
  1791. size_t padding_idx = ssl->in_msglen - padlen;
  1792. size_t i;
  1793. /*
  1794. * Padding is guaranteed to be incorrect if:
  1795. * 1. padlen > ssl->in_msglen
  1796. *
  1797. * 2. padding_idx > MBEDTLS_SSL_IN_CONTENT_LEN +
  1798. * ssl->transform_in->maclen
  1799. *
  1800. * In both cases we reset padding_idx to a safe value (0) to
  1801. * prevent out-of-buffer reads.
  1802. */
  1803. correct &= ( padlen <= ssl->in_msglen );
  1804. correct &= ( padding_idx <= MBEDTLS_SSL_IN_CONTENT_LEN +
  1805. ssl->transform_in->maclen );
  1806. padding_idx *= correct;
  1807. for( i = 0; i < 256; i++ )
  1808. {
  1809. real_count &= ( i < padlen );
  1810. pad_count += real_count *
  1811. ( ssl->in_msg[padding_idx + i] == padlen - 1 );
  1812. }
  1813. correct &= ( pad_count == padlen ); /* Only 1 on correct padding */
  1814. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1815. if( padlen > 0 && correct == 0 )
  1816. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) );
  1817. #endif
  1818. padlen &= correct * 0x1FF;
  1819. }
  1820. else
  1821. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
  1822. MBEDTLS_SSL_PROTO_TLS1_2 */
  1823. {
  1824. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1825. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1826. }
  1827. ssl->in_msglen -= padlen;
  1828. }
  1829. else
  1830. #endif /* MBEDTLS_CIPHER_MODE_CBC &&
  1831. ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C || MBEDTLS_ARIA_C ) */
  1832. {
  1833. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1834. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1835. }
  1836. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1837. MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption",
  1838. ssl->in_msg, ssl->in_msglen );
  1839. #endif
  1840. /*
  1841. * Authenticate if not done yet.
  1842. * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
  1843. */
  1844. #if defined(SSL_SOME_MODES_USE_MAC)
  1845. if( auth_done == 0 )
  1846. {
  1847. unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
  1848. ssl->in_msglen -= ssl->transform_in->maclen;
  1849. ssl->in_len[0] = (unsigned char)( ssl->in_msglen >> 8 );
  1850. ssl->in_len[1] = (unsigned char)( ssl->in_msglen );
  1851. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  1852. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  1853. {
  1854. ssl_mac( &ssl->transform_in->md_ctx_dec,
  1855. ssl->transform_in->mac_dec,
  1856. ssl->in_msg, ssl->in_msglen,
  1857. ssl->in_ctr, ssl->in_msgtype,
  1858. mac_expect );
  1859. }
  1860. else
  1861. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  1862. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  1863. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1864. if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
  1865. {
  1866. /*
  1867. * Process MAC and always update for padlen afterwards to make
  1868. * total time independent of padlen.
  1869. *
  1870. * Known timing attacks:
  1871. * - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf)
  1872. *
  1873. * To compensate for different timings for the MAC calculation
  1874. * depending on how much padding was removed (which is determined
  1875. * by padlen), process extra_run more blocks through the hash
  1876. * function.
  1877. *
  1878. * The formula in the paper is
  1879. * extra_run = ceil( (L1-55) / 64 ) - ceil( (L2-55) / 64 )
  1880. * where L1 is the size of the header plus the decrypted message
  1881. * plus CBC padding and L2 is the size of the header plus the
  1882. * decrypted message. This is for an underlying hash function
  1883. * with 64-byte blocks.
  1884. * We use ( (Lx+8) / 64 ) to handle 'negative Lx' values
  1885. * correctly. We round down instead of up, so -56 is the correct
  1886. * value for our calculations instead of -55.
  1887. *
  1888. * Repeat the formula rather than defining a block_size variable.
  1889. * This avoids requiring division by a variable at runtime
  1890. * (which would be marginally less efficient and would require
  1891. * linking an extra division function in some builds).
  1892. */
  1893. size_t j, extra_run = 0;
  1894. /*
  1895. * The next two sizes are the minimum and maximum values of
  1896. * in_msglen over all padlen values.
  1897. *
  1898. * They're independent of padlen, since we previously did
  1899. * in_msglen -= padlen.
  1900. *
  1901. * Note that max_len + maclen is never more than the buffer
  1902. * length, as we previously did in_msglen -= maclen too.
  1903. */
  1904. const size_t max_len = ssl->in_msglen + padlen;
  1905. const size_t min_len = ( max_len > 256 ) ? max_len - 256 : 0;
  1906. switch( ssl->transform_in->ciphersuite_info->mac )
  1907. {
  1908. #if defined(MBEDTLS_MD5_C) || defined(MBEDTLS_SHA1_C) || \
  1909. defined(MBEDTLS_SHA256_C)
  1910. case MBEDTLS_MD_MD5:
  1911. case MBEDTLS_MD_SHA1:
  1912. case MBEDTLS_MD_SHA256:
  1913. /* 8 bytes of message size, 64-byte compression blocks */
  1914. extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 -
  1915. ( 13 + ssl->in_msglen + 8 ) / 64;
  1916. break;
  1917. #endif
  1918. #if defined(MBEDTLS_SHA512_C)
  1919. case MBEDTLS_MD_SHA384:
  1920. /* 16 bytes of message size, 128-byte compression blocks */
  1921. extra_run = ( 13 + ssl->in_msglen + padlen + 16 ) / 128 -
  1922. ( 13 + ssl->in_msglen + 16 ) / 128;
  1923. break;
  1924. #endif
  1925. default:
  1926. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1927. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1928. }
  1929. extra_run &= correct * 0xFF;
  1930. mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_ctr, 8 );
  1931. mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_hdr, 3 );
  1932. mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_len, 2 );
  1933. mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_msg,
  1934. ssl->in_msglen );
  1935. /* Make sure we access everything even when padlen > 0. This
  1936. * makes the synchronisation requirements for just-in-time
  1937. * Prime+Probe attacks much tighter and hopefully impractical. */
  1938. ssl_read_memory( ssl->in_msg + ssl->in_msglen, padlen );
  1939. mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, mac_expect );
  1940. /* Call mbedtls_md_process at least once due to cache attacks
  1941. * that observe whether md_process() was called of not */
  1942. for( j = 0; j < extra_run + 1; j++ )
  1943. mbedtls_md_process( &ssl->transform_in->md_ctx_dec, ssl->in_msg );
  1944. mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
  1945. /* Make sure we access all the memory that could contain the MAC,
  1946. * before we check it in the next code block. This makes the
  1947. * synchronisation requirements for just-in-time Prime+Probe
  1948. * attacks much tighter and hopefully impractical. */
  1949. ssl_read_memory( ssl->in_msg + min_len,
  1950. max_len - min_len + ssl->transform_in->maclen );
  1951. }
  1952. else
  1953. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
  1954. MBEDTLS_SSL_PROTO_TLS1_2 */
  1955. {
  1956. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1957. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1958. }
  1959. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1960. MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, ssl->transform_in->maclen );
  1961. MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", ssl->in_msg + ssl->in_msglen,
  1962. ssl->transform_in->maclen );
  1963. #endif
  1964. if( mbedtls_ssl_safer_memcmp( ssl->in_msg + ssl->in_msglen, mac_expect,
  1965. ssl->transform_in->maclen ) != 0 )
  1966. {
  1967. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  1968. MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
  1969. #endif
  1970. correct = 0;
  1971. }
  1972. auth_done++;
  1973. }
  1974. /*
  1975. * Finally check the correct flag
  1976. */
  1977. if( correct == 0 )
  1978. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1979. #endif /* SSL_SOME_MODES_USE_MAC */
  1980. /* Make extra sure authentication was performed, exactly once */
  1981. if( auth_done != 1 )
  1982. {
  1983. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1984. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1985. }
  1986. if( ssl->in_msglen == 0 )
  1987. {
  1988. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1989. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3
  1990. && ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
  1991. {
  1992. /* TLS v1.2 explicitly disallows zero-length messages which are not application data */
  1993. MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid zero-length message type: %d", ssl->in_msgtype ) );
  1994. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  1995. }
  1996. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  1997. ssl->nb_zero++;
  1998. /*
  1999. * Three or more empty messages may be a DoS attack
  2000. * (excessive CPU consumption).
  2001. */
  2002. if( ssl->nb_zero > 3 )
  2003. {
  2004. MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty "
  2005. "messages, possible DoS attack" ) );
  2006. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  2007. }
  2008. }
  2009. else
  2010. ssl->nb_zero = 0;
  2011. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2012. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  2013. {
  2014. ; /* in_ctr read from peer, not maintained internally */
  2015. }
  2016. else
  2017. #endif
  2018. {
  2019. unsigned char i;
  2020. for( i = 8; i > ssl_ep_len( ssl ); i-- )
  2021. if( ++ssl->in_ctr[i - 1] != 0 )
  2022. break;
  2023. /* The loop goes to its end iff the counter is wrapping */
  2024. if( i == ssl_ep_len( ssl ) )
  2025. {
  2026. MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) );
  2027. return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
  2028. }
  2029. }
  2030. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
  2031. return( 0 );
  2032. }
  2033. #undef MAC_NONE
  2034. #undef MAC_PLAINTEXT
  2035. #undef MAC_CIPHERTEXT
  2036. #if defined(MBEDTLS_ZLIB_SUPPORT)
  2037. /*
  2038. * Compression/decompression functions
  2039. */
  2040. static int ssl_compress_buf( mbedtls_ssl_context *ssl )
  2041. {
  2042. int ret;
  2043. unsigned char *msg_post = ssl->out_msg;
  2044. ptrdiff_t bytes_written = ssl->out_msg - ssl->out_buf;
  2045. size_t len_pre = ssl->out_msglen;
  2046. unsigned char *msg_pre = ssl->compress_buf;
  2047. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) );
  2048. if( len_pre == 0 )
  2049. return( 0 );
  2050. memcpy( msg_pre, ssl->out_msg, len_pre );
  2051. MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ",
  2052. ssl->out_msglen ) );
  2053. MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload",
  2054. ssl->out_msg, ssl->out_msglen );
  2055. ssl->transform_out->ctx_deflate.next_in = msg_pre;
  2056. ssl->transform_out->ctx_deflate.avail_in = len_pre;
  2057. ssl->transform_out->ctx_deflate.next_out = msg_post;
  2058. ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_OUT_BUFFER_LEN - bytes_written;
  2059. ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );
  2060. if( ret != Z_OK )
  2061. {
  2062. MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) );
  2063. return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
  2064. }
  2065. ssl->out_msglen = MBEDTLS_SSL_OUT_BUFFER_LEN -
  2066. ssl->transform_out->ctx_deflate.avail_out - bytes_written;
  2067. MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ",
  2068. ssl->out_msglen ) );
  2069. MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload",
  2070. ssl->out_msg, ssl->out_msglen );
  2071. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) );
  2072. return( 0 );
  2073. }
  2074. static int ssl_decompress_buf( mbedtls_ssl_context *ssl )
  2075. {
  2076. int ret;
  2077. unsigned char *msg_post = ssl->in_msg;
  2078. ptrdiff_t header_bytes = ssl->in_msg - ssl->in_buf;
  2079. size_t len_pre = ssl->in_msglen;
  2080. unsigned char *msg_pre = ssl->compress_buf;
  2081. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) );
  2082. if( len_pre == 0 )
  2083. return( 0 );
  2084. memcpy( msg_pre, ssl->in_msg, len_pre );
  2085. MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ",
  2086. ssl->in_msglen ) );
  2087. MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload",
  2088. ssl->in_msg, ssl->in_msglen );
  2089. ssl->transform_in->ctx_inflate.next_in = msg_pre;
  2090. ssl->transform_in->ctx_inflate.avail_in = len_pre;
  2091. ssl->transform_in->ctx_inflate.next_out = msg_post;
  2092. ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_IN_BUFFER_LEN -
  2093. header_bytes;
  2094. ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );
  2095. if( ret != Z_OK )
  2096. {
  2097. MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) );
  2098. return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
  2099. }
  2100. ssl->in_msglen = MBEDTLS_SSL_IN_BUFFER_LEN -
  2101. ssl->transform_in->ctx_inflate.avail_out - header_bytes;
  2102. MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ",
  2103. ssl->in_msglen ) );
  2104. MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload",
  2105. ssl->in_msg, ssl->in_msglen );
  2106. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) );
  2107. return( 0 );
  2108. }
  2109. #endif /* MBEDTLS_ZLIB_SUPPORT */
  2110. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
  2111. static int ssl_write_hello_request( mbedtls_ssl_context *ssl );
  2112. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2113. static int ssl_resend_hello_request( mbedtls_ssl_context *ssl )
  2114. {
  2115. /* If renegotiation is not enforced, retransmit until we would reach max
  2116. * timeout if we were using the usual handshake doubling scheme */
  2117. if( ssl->conf->renego_max_records < 0 )
  2118. {
  2119. uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;
  2120. unsigned char doublings = 1;
  2121. while( ratio != 0 )
  2122. {
  2123. ++doublings;
  2124. ratio >>= 1;
  2125. }
  2126. if( ++ssl->renego_records_seen > doublings )
  2127. {
  2128. MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) );
  2129. return( 0 );
  2130. }
  2131. }
  2132. return( ssl_write_hello_request( ssl ) );
  2133. }
  2134. #endif
  2135. #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
  2136. /*
  2137. * Fill the input message buffer by appending data to it.
  2138. * The amount of data already fetched is in ssl->in_left.
  2139. *
  2140. * If we return 0, is it guaranteed that (at least) nb_want bytes are
  2141. * available (from this read and/or a previous one). Otherwise, an error code
  2142. * is returned (possibly EOF or WANT_READ).
  2143. *
  2144. * With stream transport (TLS) on success ssl->in_left == nb_want, but
  2145. * with datagram transport (DTLS) on success ssl->in_left >= nb_want,
  2146. * since we always read a whole datagram at once.
  2147. *
  2148. * For DTLS, it is up to the caller to set ssl->next_record_offset when
  2149. * they're done reading a record.
  2150. */
  2151. int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want )
  2152. {
  2153. int ret;
  2154. size_t len;
  2155. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) );
  2156. if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL )
  2157. {
  2158. MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
  2159. "or mbedtls_ssl_set_bio()" ) );
  2160. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2161. }
  2162. if( nb_want > MBEDTLS_SSL_IN_BUFFER_LEN - (size_t)( ssl->in_hdr - ssl->in_buf ) )
  2163. {
  2164. MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) );
  2165. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2166. }
  2167. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2168. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  2169. {
  2170. uint32_t timeout;
  2171. /* Just to be sure */
  2172. if( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL )
  2173. {
  2174. MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use "
  2175. "mbedtls_ssl_set_timer_cb() for DTLS" ) );
  2176. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2177. }
  2178. /*
  2179. * The point is, we need to always read a full datagram at once, so we
  2180. * sometimes read more then requested, and handle the additional data.
  2181. * It could be the rest of the current record (while fetching the
  2182. * header) and/or some other records in the same datagram.
  2183. */
  2184. /*
  2185. * Move to the next record in the already read datagram if applicable
  2186. */
  2187. if( ssl->next_record_offset != 0 )
  2188. {
  2189. if( ssl->in_left < ssl->next_record_offset )
  2190. {
  2191. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2192. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2193. }
  2194. ssl->in_left -= ssl->next_record_offset;
  2195. if( ssl->in_left != 0 )
  2196. {
  2197. MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %d",
  2198. ssl->next_record_offset ) );
  2199. memmove( ssl->in_hdr,
  2200. ssl->in_hdr + ssl->next_record_offset,
  2201. ssl->in_left );
  2202. }
  2203. ssl->next_record_offset = 0;
  2204. }
  2205. MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
  2206. ssl->in_left, nb_want ) );
  2207. /*
  2208. * Done if we already have enough data.
  2209. */
  2210. if( nb_want <= ssl->in_left)
  2211. {
  2212. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
  2213. return( 0 );
  2214. }
  2215. /*
  2216. * A record can't be split accross datagrams. If we need to read but
  2217. * are not at the beginning of a new record, the caller did something
  2218. * wrong.
  2219. */
  2220. if( ssl->in_left != 0 )
  2221. {
  2222. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2223. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2224. }
  2225. /*
  2226. * Don't even try to read if time's out already.
  2227. * This avoids by-passing the timer when repeatedly receiving messages
  2228. * that will end up being dropped.
  2229. */
  2230. if( ssl_check_timer( ssl ) != 0 )
  2231. {
  2232. MBEDTLS_SSL_DEBUG_MSG( 2, ( "timer has expired" ) );
  2233. ret = MBEDTLS_ERR_SSL_TIMEOUT;
  2234. }
  2235. else
  2236. {
  2237. len = MBEDTLS_SSL_IN_BUFFER_LEN - ( ssl->in_hdr - ssl->in_buf );
  2238. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  2239. timeout = ssl->handshake->retransmit_timeout;
  2240. else
  2241. timeout = ssl->conf->read_timeout;
  2242. MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %u ms", timeout ) );
  2243. if( ssl->f_recv_timeout != NULL )
  2244. ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len,
  2245. timeout );
  2246. else
  2247. ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len );
  2248. MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
  2249. if( ret == 0 )
  2250. return( MBEDTLS_ERR_SSL_CONN_EOF );
  2251. }
  2252. if( ret == MBEDTLS_ERR_SSL_TIMEOUT )
  2253. {
  2254. MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) );
  2255. ssl_set_timer( ssl, 0 );
  2256. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  2257. {
  2258. if( ssl_double_retransmit_timeout( ssl ) != 0 )
  2259. {
  2260. MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) );
  2261. return( MBEDTLS_ERR_SSL_TIMEOUT );
  2262. }
  2263. if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
  2264. {
  2265. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
  2266. return( ret );
  2267. }
  2268. return( MBEDTLS_ERR_SSL_WANT_READ );
  2269. }
  2270. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
  2271. else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  2272. ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
  2273. {
  2274. if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
  2275. {
  2276. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
  2277. return( ret );
  2278. }
  2279. return( MBEDTLS_ERR_SSL_WANT_READ );
  2280. }
  2281. #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
  2282. }
  2283. if( ret < 0 )
  2284. return( ret );
  2285. ssl->in_left = ret;
  2286. }
  2287. else
  2288. #endif
  2289. {
  2290. MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
  2291. ssl->in_left, nb_want ) );
  2292. while( ssl->in_left < nb_want )
  2293. {
  2294. len = nb_want - ssl->in_left;
  2295. if( ssl_check_timer( ssl ) != 0 )
  2296. ret = MBEDTLS_ERR_SSL_TIMEOUT;
  2297. else
  2298. {
  2299. if( ssl->f_recv_timeout != NULL )
  2300. {
  2301. ret = ssl->f_recv_timeout( ssl->p_bio,
  2302. ssl->in_hdr + ssl->in_left, len,
  2303. ssl->conf->read_timeout );
  2304. }
  2305. else
  2306. {
  2307. ret = ssl->f_recv( ssl->p_bio,
  2308. ssl->in_hdr + ssl->in_left, len );
  2309. }
  2310. }
  2311. MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
  2312. ssl->in_left, nb_want ) );
  2313. MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
  2314. if( ret == 0 )
  2315. return( MBEDTLS_ERR_SSL_CONN_EOF );
  2316. if( ret < 0 )
  2317. return( ret );
  2318. if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) )
  2319. {
  2320. MBEDTLS_SSL_DEBUG_MSG( 1,
  2321. ( "f_recv returned %d bytes but only %lu were requested",
  2322. ret, (unsigned long)len ) );
  2323. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2324. }
  2325. ssl->in_left += ret;
  2326. }
  2327. }
  2328. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
  2329. return( 0 );
  2330. }
  2331. /*
  2332. * Flush any data not yet written
  2333. */
  2334. int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl )
  2335. {
  2336. int ret;
  2337. unsigned char *buf;
  2338. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) );
  2339. if( ssl->f_send == NULL )
  2340. {
  2341. MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
  2342. "or mbedtls_ssl_set_bio()" ) );
  2343. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2344. }
  2345. /* Avoid incrementing counter if data is flushed */
  2346. if( ssl->out_left == 0 )
  2347. {
  2348. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
  2349. return( 0 );
  2350. }
  2351. while( ssl->out_left > 0 )
  2352. {
  2353. MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d",
  2354. mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) );
  2355. buf = ssl->out_hdr - ssl->out_left;
  2356. ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left );
  2357. MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret );
  2358. if( ret <= 0 )
  2359. return( ret );
  2360. if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) )
  2361. {
  2362. MBEDTLS_SSL_DEBUG_MSG( 1,
  2363. ( "f_send returned %d bytes but only %lu bytes were sent",
  2364. ret, (unsigned long)ssl->out_left ) );
  2365. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2366. }
  2367. ssl->out_left -= ret;
  2368. }
  2369. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2370. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  2371. {
  2372. ssl->out_hdr = ssl->out_buf;
  2373. }
  2374. else
  2375. #endif
  2376. {
  2377. ssl->out_hdr = ssl->out_buf + 8;
  2378. }
  2379. ssl_update_out_pointers( ssl, ssl->transform_out );
  2380. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
  2381. return( 0 );
  2382. }
  2383. /*
  2384. * Functions to handle the DTLS retransmission state machine
  2385. */
  2386. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2387. /*
  2388. * Append current handshake message to current outgoing flight
  2389. */
  2390. static int ssl_flight_append( mbedtls_ssl_context *ssl )
  2391. {
  2392. mbedtls_ssl_flight_item *msg;
  2393. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_flight_append" ) );
  2394. MBEDTLS_SSL_DEBUG_BUF( 4, "message appended to flight",
  2395. ssl->out_msg, ssl->out_msglen );
  2396. /* Allocate space for current message */
  2397. if( ( msg = mbedtls_calloc( 1, sizeof( mbedtls_ssl_flight_item ) ) ) == NULL )
  2398. {
  2399. MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed",
  2400. sizeof( mbedtls_ssl_flight_item ) ) );
  2401. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  2402. }
  2403. if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL )
  2404. {
  2405. MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", ssl->out_msglen ) );
  2406. mbedtls_free( msg );
  2407. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  2408. }
  2409. /* Copy current handshake message with headers */
  2410. memcpy( msg->p, ssl->out_msg, ssl->out_msglen );
  2411. msg->len = ssl->out_msglen;
  2412. msg->type = ssl->out_msgtype;
  2413. msg->next = NULL;
  2414. /* Append to the current flight */
  2415. if( ssl->handshake->flight == NULL )
  2416. ssl->handshake->flight = msg;
  2417. else
  2418. {
  2419. mbedtls_ssl_flight_item *cur = ssl->handshake->flight;
  2420. while( cur->next != NULL )
  2421. cur = cur->next;
  2422. cur->next = msg;
  2423. }
  2424. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_flight_append" ) );
  2425. return( 0 );
  2426. }
  2427. /*
  2428. * Free the current flight of handshake messages
  2429. */
  2430. static void ssl_flight_free( mbedtls_ssl_flight_item *flight )
  2431. {
  2432. mbedtls_ssl_flight_item *cur = flight;
  2433. mbedtls_ssl_flight_item *next;
  2434. while( cur != NULL )
  2435. {
  2436. next = cur->next;
  2437. mbedtls_free( cur->p );
  2438. mbedtls_free( cur );
  2439. cur = next;
  2440. }
  2441. }
  2442. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  2443. static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl );
  2444. #endif
  2445. /*
  2446. * Swap transform_out and out_ctr with the alternative ones
  2447. */
  2448. static void ssl_swap_epochs( mbedtls_ssl_context *ssl )
  2449. {
  2450. mbedtls_ssl_transform *tmp_transform;
  2451. unsigned char tmp_out_ctr[8];
  2452. if( ssl->transform_out == ssl->handshake->alt_transform_out )
  2453. {
  2454. MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) );
  2455. return;
  2456. }
  2457. MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) );
  2458. /* Swap transforms */
  2459. tmp_transform = ssl->transform_out;
  2460. ssl->transform_out = ssl->handshake->alt_transform_out;
  2461. ssl->handshake->alt_transform_out = tmp_transform;
  2462. /* Swap epoch + sequence_number */
  2463. memcpy( tmp_out_ctr, ssl->cur_out_ctr, 8 );
  2464. memcpy( ssl->cur_out_ctr, ssl->handshake->alt_out_ctr, 8 );
  2465. memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr, 8 );
  2466. /* Adjust to the newly activated transform */
  2467. ssl_update_out_pointers( ssl, ssl->transform_out );
  2468. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  2469. if( mbedtls_ssl_hw_record_activate != NULL )
  2470. {
  2471. if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
  2472. {
  2473. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
  2474. return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  2475. }
  2476. }
  2477. #endif
  2478. }
  2479. /*
  2480. * Retransmit the current flight of messages.
  2481. */
  2482. int mbedtls_ssl_resend( mbedtls_ssl_context *ssl )
  2483. {
  2484. int ret = 0;
  2485. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) );
  2486. ret = mbedtls_ssl_flight_transmit( ssl );
  2487. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) );
  2488. return( ret );
  2489. }
  2490. /*
  2491. * Transmit or retransmit the current flight of messages.
  2492. *
  2493. * Need to remember the current message in case flush_output returns
  2494. * WANT_WRITE, causing us to exit this function and come back later.
  2495. * This function must be called until state is no longer SENDING.
  2496. */
  2497. int mbedtls_ssl_flight_transmit( mbedtls_ssl_context *ssl )
  2498. {
  2499. int ret;
  2500. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_flight_transmit" ) );
  2501. if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING )
  2502. {
  2503. MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise flight transmission" ) );
  2504. ssl->handshake->cur_msg = ssl->handshake->flight;
  2505. ssl->handshake->cur_msg_p = ssl->handshake->flight->p + 12;
  2506. ssl_swap_epochs( ssl );
  2507. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;
  2508. }
  2509. while( ssl->handshake->cur_msg != NULL )
  2510. {
  2511. size_t max_frag_len;
  2512. const mbedtls_ssl_flight_item * const cur = ssl->handshake->cur_msg;
  2513. int const is_finished =
  2514. ( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2515. cur->p[0] == MBEDTLS_SSL_HS_FINISHED );
  2516. uint8_t const force_flush = ssl->disable_datagram_packing == 1 ?
  2517. SSL_FORCE_FLUSH : SSL_DONT_FORCE_FLUSH;
  2518. /* Swap epochs before sending Finished: we can't do it after
  2519. * sending ChangeCipherSpec, in case write returns WANT_READ.
  2520. * Must be done before copying, may change out_msg pointer */
  2521. if( is_finished && ssl->handshake->cur_msg_p == ( cur->p + 12 ) )
  2522. {
  2523. MBEDTLS_SSL_DEBUG_MSG( 2, ( "swap epochs to send finished message" ) );
  2524. ssl_swap_epochs( ssl );
  2525. }
  2526. ret = ssl_get_remaining_payload_in_datagram( ssl );
  2527. if( ret < 0 )
  2528. return( ret );
  2529. max_frag_len = (size_t) ret;
  2530. /* CCS is copied as is, while HS messages may need fragmentation */
  2531. if( cur->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
  2532. {
  2533. if( max_frag_len == 0 )
  2534. {
  2535. if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  2536. return( ret );
  2537. continue;
  2538. }
  2539. memcpy( ssl->out_msg, cur->p, cur->len );
  2540. ssl->out_msglen = cur->len;
  2541. ssl->out_msgtype = cur->type;
  2542. /* Update position inside current message */
  2543. ssl->handshake->cur_msg_p += cur->len;
  2544. }
  2545. else
  2546. {
  2547. const unsigned char * const p = ssl->handshake->cur_msg_p;
  2548. const size_t hs_len = cur->len - 12;
  2549. const size_t frag_off = p - ( cur->p + 12 );
  2550. const size_t rem_len = hs_len - frag_off;
  2551. size_t cur_hs_frag_len, max_hs_frag_len;
  2552. if( ( max_frag_len < 12 ) || ( max_frag_len == 12 && hs_len != 0 ) )
  2553. {
  2554. if( is_finished )
  2555. ssl_swap_epochs( ssl );
  2556. if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  2557. return( ret );
  2558. continue;
  2559. }
  2560. max_hs_frag_len = max_frag_len - 12;
  2561. cur_hs_frag_len = rem_len > max_hs_frag_len ?
  2562. max_hs_frag_len : rem_len;
  2563. if( frag_off == 0 && cur_hs_frag_len != hs_len )
  2564. {
  2565. MBEDTLS_SSL_DEBUG_MSG( 2, ( "fragmenting handshake message (%u > %u)",
  2566. (unsigned) cur_hs_frag_len,
  2567. (unsigned) max_hs_frag_len ) );
  2568. }
  2569. /* Messages are stored with handshake headers as if not fragmented,
  2570. * copy beginning of headers then fill fragmentation fields.
  2571. * Handshake headers: type(1) len(3) seq(2) f_off(3) f_len(3) */
  2572. memcpy( ssl->out_msg, cur->p, 6 );
  2573. ssl->out_msg[6] = ( ( frag_off >> 16 ) & 0xff );
  2574. ssl->out_msg[7] = ( ( frag_off >> 8 ) & 0xff );
  2575. ssl->out_msg[8] = ( ( frag_off ) & 0xff );
  2576. ssl->out_msg[ 9] = ( ( cur_hs_frag_len >> 16 ) & 0xff );
  2577. ssl->out_msg[10] = ( ( cur_hs_frag_len >> 8 ) & 0xff );
  2578. ssl->out_msg[11] = ( ( cur_hs_frag_len ) & 0xff );
  2579. MBEDTLS_SSL_DEBUG_BUF( 3, "handshake header", ssl->out_msg, 12 );
  2580. /* Copy the handshake message content and set records fields */
  2581. memcpy( ssl->out_msg + 12, p, cur_hs_frag_len );
  2582. ssl->out_msglen = cur_hs_frag_len + 12;
  2583. ssl->out_msgtype = cur->type;
  2584. /* Update position inside current message */
  2585. ssl->handshake->cur_msg_p += cur_hs_frag_len;
  2586. }
  2587. /* If done with the current message move to the next one if any */
  2588. if( ssl->handshake->cur_msg_p >= cur->p + cur->len )
  2589. {
  2590. if( cur->next != NULL )
  2591. {
  2592. ssl->handshake->cur_msg = cur->next;
  2593. ssl->handshake->cur_msg_p = cur->next->p + 12;
  2594. }
  2595. else
  2596. {
  2597. ssl->handshake->cur_msg = NULL;
  2598. ssl->handshake->cur_msg_p = NULL;
  2599. }
  2600. }
  2601. /* Actually send the message out */
  2602. if( ( ret = mbedtls_ssl_write_record( ssl, force_flush ) ) != 0 )
  2603. {
  2604. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
  2605. return( ret );
  2606. }
  2607. }
  2608. if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  2609. return( ret );
  2610. /* Update state and set timer */
  2611. if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
  2612. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
  2613. else
  2614. {
  2615. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
  2616. ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
  2617. }
  2618. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_flight_transmit" ) );
  2619. return( 0 );
  2620. }
  2621. /*
  2622. * To be called when the last message of an incoming flight is received.
  2623. */
  2624. void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl )
  2625. {
  2626. /* We won't need to resend that one any more */
  2627. ssl_flight_free( ssl->handshake->flight );
  2628. ssl->handshake->flight = NULL;
  2629. ssl->handshake->cur_msg = NULL;
  2630. /* The next incoming flight will start with this msg_seq */
  2631. ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;
  2632. /* We don't want to remember CCS's across flight boundaries. */
  2633. ssl->handshake->buffering.seen_ccs = 0;
  2634. /* Clear future message buffering structure. */
  2635. ssl_buffering_free( ssl );
  2636. /* Cancel timer */
  2637. ssl_set_timer( ssl, 0 );
  2638. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2639. ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
  2640. {
  2641. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
  2642. }
  2643. else
  2644. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
  2645. }
  2646. /*
  2647. * To be called when the last message of an outgoing flight is send.
  2648. */
  2649. void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl )
  2650. {
  2651. ssl_reset_retransmit_timeout( ssl );
  2652. ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
  2653. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2654. ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
  2655. {
  2656. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
  2657. }
  2658. else
  2659. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
  2660. }
  2661. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  2662. /*
  2663. * Handshake layer functions
  2664. */
  2665. /*
  2666. * Write (DTLS: or queue) current handshake (including CCS) message.
  2667. *
  2668. * - fill in handshake headers
  2669. * - update handshake checksum
  2670. * - DTLS: save message for resending
  2671. * - then pass to the record layer
  2672. *
  2673. * DTLS: except for HelloRequest, messages are only queued, and will only be
  2674. * actually sent when calling flight_transmit() or resend().
  2675. *
  2676. * Inputs:
  2677. * - ssl->out_msglen: 4 + actual handshake message len
  2678. * (4 is the size of handshake headers for TLS)
  2679. * - ssl->out_msg[0]: the handshake type (ClientHello, ServerHello, etc)
  2680. * - ssl->out_msg + 4: the handshake message body
  2681. *
  2682. * Outputs, ie state before passing to flight_append() or write_record():
  2683. * - ssl->out_msglen: the length of the record contents
  2684. * (including handshake headers but excluding record headers)
  2685. * - ssl->out_msg: the record contents (handshake headers + content)
  2686. */
  2687. int mbedtls_ssl_write_handshake_msg( mbedtls_ssl_context *ssl )
  2688. {
  2689. int ret;
  2690. const size_t hs_len = ssl->out_msglen - 4;
  2691. const unsigned char hs_type = ssl->out_msg[0];
  2692. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write handshake message" ) );
  2693. /*
  2694. * Sanity checks
  2695. */
  2696. if( ssl->out_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE &&
  2697. ssl->out_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
  2698. {
  2699. /* In SSLv3, the client might send a NoCertificate alert. */
  2700. #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
  2701. if( ! ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
  2702. ssl->out_msgtype == MBEDTLS_SSL_MSG_ALERT &&
  2703. ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) )
  2704. #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
  2705. {
  2706. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2707. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2708. }
  2709. }
  2710. /* Whenever we send anything different from a
  2711. * HelloRequest we should be in a handshake - double check. */
  2712. if( ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2713. hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST ) &&
  2714. ssl->handshake == NULL )
  2715. {
  2716. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2717. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2718. }
  2719. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2720. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  2721. ssl->handshake != NULL &&
  2722. ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
  2723. {
  2724. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2725. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2726. }
  2727. #endif
  2728. /* Double-check that we did not exceed the bounds
  2729. * of the outgoing record buffer.
  2730. * This should never fail as the various message
  2731. * writing functions must obey the bounds of the
  2732. * outgoing record buffer, but better be safe.
  2733. *
  2734. * Note: We deliberately do not check for the MTU or MFL here.
  2735. */
  2736. if( ssl->out_msglen > MBEDTLS_SSL_OUT_CONTENT_LEN )
  2737. {
  2738. MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record too large: "
  2739. "size %u, maximum %u",
  2740. (unsigned) ssl->out_msglen,
  2741. (unsigned) MBEDTLS_SSL_OUT_CONTENT_LEN ) );
  2742. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2743. }
  2744. /*
  2745. * Fill handshake headers
  2746. */
  2747. if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
  2748. {
  2749. ssl->out_msg[1] = (unsigned char)( hs_len >> 16 );
  2750. ssl->out_msg[2] = (unsigned char)( hs_len >> 8 );
  2751. ssl->out_msg[3] = (unsigned char)( hs_len );
  2752. /*
  2753. * DTLS has additional fields in the Handshake layer,
  2754. * between the length field and the actual payload:
  2755. * uint16 message_seq;
  2756. * uint24 fragment_offset;
  2757. * uint24 fragment_length;
  2758. */
  2759. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2760. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  2761. {
  2762. /* Make room for the additional DTLS fields */
  2763. if( MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen < 8 )
  2764. {
  2765. MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS handshake message too large: "
  2766. "size %u, maximum %u",
  2767. (unsigned) ( hs_len ),
  2768. (unsigned) ( MBEDTLS_SSL_OUT_CONTENT_LEN - 12 ) ) );
  2769. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2770. }
  2771. memmove( ssl->out_msg + 12, ssl->out_msg + 4, hs_len );
  2772. ssl->out_msglen += 8;
  2773. /* Write message_seq and update it, except for HelloRequest */
  2774. if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
  2775. {
  2776. ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF;
  2777. ssl->out_msg[5] = ( ssl->handshake->out_msg_seq ) & 0xFF;
  2778. ++( ssl->handshake->out_msg_seq );
  2779. }
  2780. else
  2781. {
  2782. ssl->out_msg[4] = 0;
  2783. ssl->out_msg[5] = 0;
  2784. }
  2785. /* Handshake hashes are computed without fragmentation,
  2786. * so set frag_offset = 0 and frag_len = hs_len for now */
  2787. memset( ssl->out_msg + 6, 0x00, 3 );
  2788. memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 );
  2789. }
  2790. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  2791. /* Update running hashes of handshake messages seen */
  2792. if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
  2793. ssl->handshake->update_checksum( ssl, ssl->out_msg, ssl->out_msglen );
  2794. }
  2795. /* Either send now, or just save to be sent (and resent) later */
  2796. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2797. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  2798. ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2799. hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST ) )
  2800. {
  2801. if( ( ret = ssl_flight_append( ssl ) ) != 0 )
  2802. {
  2803. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret );
  2804. return( ret );
  2805. }
  2806. }
  2807. else
  2808. #endif
  2809. {
  2810. if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
  2811. {
  2812. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_record", ret );
  2813. return( ret );
  2814. }
  2815. }
  2816. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write handshake message" ) );
  2817. return( 0 );
  2818. }
  2819. /*
  2820. * Record layer functions
  2821. */
  2822. /*
  2823. * Write current record.
  2824. *
  2825. * Uses:
  2826. * - ssl->out_msgtype: type of the message (AppData, Handshake, Alert, CCS)
  2827. * - ssl->out_msglen: length of the record content (excl headers)
  2828. * - ssl->out_msg: record content
  2829. */
  2830. int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl, uint8_t force_flush )
  2831. {
  2832. int ret, done = 0;
  2833. size_t len = ssl->out_msglen;
  2834. uint8_t flush = force_flush;
  2835. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) );
  2836. #if defined(MBEDTLS_ZLIB_SUPPORT)
  2837. if( ssl->transform_out != NULL &&
  2838. ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
  2839. {
  2840. if( ( ret = ssl_compress_buf( ssl ) ) != 0 )
  2841. {
  2842. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret );
  2843. return( ret );
  2844. }
  2845. len = ssl->out_msglen;
  2846. }
  2847. #endif /*MBEDTLS_ZLIB_SUPPORT */
  2848. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  2849. if( mbedtls_ssl_hw_record_write != NULL )
  2850. {
  2851. MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) );
  2852. ret = mbedtls_ssl_hw_record_write( ssl );
  2853. if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
  2854. {
  2855. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret );
  2856. return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  2857. }
  2858. if( ret == 0 )
  2859. done = 1;
  2860. }
  2861. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  2862. if( !done )
  2863. {
  2864. unsigned i;
  2865. size_t protected_record_size;
  2866. ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
  2867. mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
  2868. ssl->conf->transport, ssl->out_hdr + 1 );
  2869. memcpy( ssl->out_ctr, ssl->cur_out_ctr, 8 );
  2870. ssl->out_len[0] = (unsigned char)( len >> 8 );
  2871. ssl->out_len[1] = (unsigned char)( len );
  2872. if( ssl->transform_out != NULL )
  2873. {
  2874. if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 )
  2875. {
  2876. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret );
  2877. return( ret );
  2878. }
  2879. len = ssl->out_msglen;
  2880. ssl->out_len[0] = (unsigned char)( len >> 8 );
  2881. ssl->out_len[1] = (unsigned char)( len );
  2882. }
  2883. protected_record_size = len + mbedtls_ssl_hdr_len( ssl );
  2884. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2885. /* In case of DTLS, double-check that we don't exceed
  2886. * the remaining space in the datagram. */
  2887. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  2888. {
  2889. ret = ssl_get_remaining_space_in_datagram( ssl );
  2890. if( ret < 0 )
  2891. return( ret );
  2892. if( protected_record_size > (size_t) ret )
  2893. {
  2894. /* Should never happen */
  2895. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2896. }
  2897. }
  2898. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  2899. MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, "
  2900. "version = [%d:%d], msglen = %d",
  2901. ssl->out_hdr[0], ssl->out_hdr[1],
  2902. ssl->out_hdr[2], len ) );
  2903. MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
  2904. ssl->out_hdr, protected_record_size );
  2905. ssl->out_left += protected_record_size;
  2906. ssl->out_hdr += protected_record_size;
  2907. ssl_update_out_pointers( ssl, ssl->transform_out );
  2908. for( i = 8; i > ssl_ep_len( ssl ); i-- )
  2909. if( ++ssl->cur_out_ctr[i - 1] != 0 )
  2910. break;
  2911. /* The loop goes to its end iff the counter is wrapping */
  2912. if( i == ssl_ep_len( ssl ) )
  2913. {
  2914. MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) );
  2915. return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
  2916. }
  2917. }
  2918. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2919. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  2920. flush == SSL_DONT_FORCE_FLUSH )
  2921. {
  2922. size_t remaining;
  2923. ret = ssl_get_remaining_payload_in_datagram( ssl );
  2924. if( ret < 0 )
  2925. {
  2926. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_remaining_payload_in_datagram",
  2927. ret );
  2928. return( ret );
  2929. }
  2930. remaining = (size_t) ret;
  2931. if( remaining == 0 )
  2932. {
  2933. flush = SSL_FORCE_FLUSH;
  2934. }
  2935. else
  2936. {
  2937. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Still %u bytes available in current datagram", (unsigned) remaining ) );
  2938. }
  2939. }
  2940. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  2941. if( ( flush == SSL_FORCE_FLUSH ) &&
  2942. ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  2943. {
  2944. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
  2945. return( ret );
  2946. }
  2947. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) );
  2948. return( 0 );
  2949. }
  2950. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2951. static int ssl_hs_is_proper_fragment( mbedtls_ssl_context *ssl )
  2952. {
  2953. if( ssl->in_msglen < ssl->in_hslen ||
  2954. memcmp( ssl->in_msg + 6, "\0\0\0", 3 ) != 0 ||
  2955. memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 )
  2956. {
  2957. return( 1 );
  2958. }
  2959. return( 0 );
  2960. }
  2961. static uint32_t ssl_get_hs_frag_len( mbedtls_ssl_context const *ssl )
  2962. {
  2963. return( ( ssl->in_msg[9] << 16 ) |
  2964. ( ssl->in_msg[10] << 8 ) |
  2965. ssl->in_msg[11] );
  2966. }
  2967. static uint32_t ssl_get_hs_frag_off( mbedtls_ssl_context const *ssl )
  2968. {
  2969. return( ( ssl->in_msg[6] << 16 ) |
  2970. ( ssl->in_msg[7] << 8 ) |
  2971. ssl->in_msg[8] );
  2972. }
  2973. static int ssl_check_hs_header( mbedtls_ssl_context const *ssl )
  2974. {
  2975. uint32_t msg_len, frag_off, frag_len;
  2976. msg_len = ssl_get_hs_total_len( ssl );
  2977. frag_off = ssl_get_hs_frag_off( ssl );
  2978. frag_len = ssl_get_hs_frag_len( ssl );
  2979. if( frag_off > msg_len )
  2980. return( -1 );
  2981. if( frag_len > msg_len - frag_off )
  2982. return( -1 );
  2983. if( frag_len + 12 > ssl->in_msglen )
  2984. return( -1 );
  2985. return( 0 );
  2986. }
  2987. /*
  2988. * Mark bits in bitmask (used for DTLS HS reassembly)
  2989. */
  2990. static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len )
  2991. {
  2992. unsigned int start_bits, end_bits;
  2993. start_bits = 8 - ( offset % 8 );
  2994. if( start_bits != 8 )
  2995. {
  2996. size_t first_byte_idx = offset / 8;
  2997. /* Special case */
  2998. if( len <= start_bits )
  2999. {
  3000. for( ; len != 0; len-- )
  3001. mask[first_byte_idx] |= 1 << ( start_bits - len );
  3002. /* Avoid potential issues with offset or len becoming invalid */
  3003. return;
  3004. }
  3005. offset += start_bits; /* Now offset % 8 == 0 */
  3006. len -= start_bits;
  3007. for( ; start_bits != 0; start_bits-- )
  3008. mask[first_byte_idx] |= 1 << ( start_bits - 1 );
  3009. }
  3010. end_bits = len % 8;
  3011. if( end_bits != 0 )
  3012. {
  3013. size_t last_byte_idx = ( offset + len ) / 8;
  3014. len -= end_bits; /* Now len % 8 == 0 */
  3015. for( ; end_bits != 0; end_bits-- )
  3016. mask[last_byte_idx] |= 1 << ( 8 - end_bits );
  3017. }
  3018. memset( mask + offset / 8, 0xFF, len / 8 );
  3019. }
  3020. /*
  3021. * Check that bitmask is full
  3022. */
  3023. static int ssl_bitmask_check( unsigned char *mask, size_t len )
  3024. {
  3025. size_t i;
  3026. for( i = 0; i < len / 8; i++ )
  3027. if( mask[i] != 0xFF )
  3028. return( -1 );
  3029. for( i = 0; i < len % 8; i++ )
  3030. if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 )
  3031. return( -1 );
  3032. return( 0 );
  3033. }
  3034. /* msg_len does not include the handshake header */
  3035. static size_t ssl_get_reassembly_buffer_size( size_t msg_len,
  3036. unsigned add_bitmap )
  3037. {
  3038. size_t alloc_len;
  3039. alloc_len = 12; /* Handshake header */
  3040. alloc_len += msg_len; /* Content buffer */
  3041. if( add_bitmap )
  3042. alloc_len += msg_len / 8 + ( msg_len % 8 != 0 ); /* Bitmap */
  3043. return( alloc_len );
  3044. }
  3045. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3046. static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl )
  3047. {
  3048. return( ( ssl->in_msg[1] << 16 ) |
  3049. ( ssl->in_msg[2] << 8 ) |
  3050. ssl->in_msg[3] );
  3051. }
  3052. int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl )
  3053. {
  3054. if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) )
  3055. {
  3056. MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %d",
  3057. ssl->in_msglen ) );
  3058. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3059. }
  3060. ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + ssl_get_hs_total_len( ssl );
  3061. MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen ="
  3062. " %d, type = %d, hslen = %d",
  3063. ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );
  3064. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3065. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  3066. {
  3067. int ret;
  3068. unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
  3069. if( ssl_check_hs_header( ssl ) != 0 )
  3070. {
  3071. MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid handshake header" ) );
  3072. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3073. }
  3074. if( ssl->handshake != NULL &&
  3075. ( ( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER &&
  3076. recv_msg_seq != ssl->handshake->in_msg_seq ) ||
  3077. ( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER &&
  3078. ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) ) )
  3079. {
  3080. if( recv_msg_seq > ssl->handshake->in_msg_seq )
  3081. {
  3082. MBEDTLS_SSL_DEBUG_MSG( 2, ( "received future handshake message of sequence number %u (next %u)",
  3083. recv_msg_seq,
  3084. ssl->handshake->in_msg_seq ) );
  3085. return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
  3086. }
  3087. /* Retransmit only on last message from previous flight, to avoid
  3088. * too many retransmissions.
  3089. * Besides, No sane server ever retransmits HelloVerifyRequest */
  3090. if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 &&
  3091. ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
  3092. {
  3093. MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, "
  3094. "message_seq = %d, start_of_flight = %d",
  3095. recv_msg_seq,
  3096. ssl->handshake->in_flight_start_seq ) );
  3097. if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
  3098. {
  3099. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
  3100. return( ret );
  3101. }
  3102. }
  3103. else
  3104. {
  3105. MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: "
  3106. "message_seq = %d, expected = %d",
  3107. recv_msg_seq,
  3108. ssl->handshake->in_msg_seq ) );
  3109. }
  3110. return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
  3111. }
  3112. /* Wait until message completion to increment in_msg_seq */
  3113. /* Message reassembly is handled alongside buffering of future
  3114. * messages; the commonality is that both handshake fragments and
  3115. * future messages cannot be forwarded immediately to the
  3116. * handshake logic layer. */
  3117. if( ssl_hs_is_proper_fragment( ssl ) == 1 )
  3118. {
  3119. MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) );
  3120. return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
  3121. }
  3122. }
  3123. else
  3124. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3125. /* With TLS we don't handle fragmentation (for now) */
  3126. if( ssl->in_msglen < ssl->in_hslen )
  3127. {
  3128. MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) );
  3129. return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  3130. }
  3131. return( 0 );
  3132. }
  3133. void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl )
  3134. {
  3135. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  3136. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && hs != NULL )
  3137. {
  3138. ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );
  3139. }
  3140. /* Handshake message is complete, increment counter */
  3141. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3142. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  3143. ssl->handshake != NULL )
  3144. {
  3145. unsigned offset;
  3146. mbedtls_ssl_hs_buffer *hs_buf;
  3147. /* Increment handshake sequence number */
  3148. hs->in_msg_seq++;
  3149. /*
  3150. * Clear up handshake buffering and reassembly structure.
  3151. */
  3152. /* Free first entry */
  3153. ssl_buffering_free_slot( ssl, 0 );
  3154. /* Shift all other entries */
  3155. for( offset = 0, hs_buf = &hs->buffering.hs[0];
  3156. offset + 1 < MBEDTLS_SSL_MAX_BUFFERED_HS;
  3157. offset++, hs_buf++ )
  3158. {
  3159. *hs_buf = *(hs_buf + 1);
  3160. }
  3161. /* Create a fresh last entry */
  3162. memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) );
  3163. }
  3164. #endif
  3165. }
  3166. /*
  3167. * DTLS anti-replay: RFC 6347 4.1.2.6
  3168. *
  3169. * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).
  3170. * Bit n is set iff record number in_window_top - n has been seen.
  3171. *
  3172. * Usually, in_window_top is the last record number seen and the lsb of
  3173. * in_window is set. The only exception is the initial state (record number 0
  3174. * not seen yet).
  3175. */
  3176. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  3177. static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl )
  3178. {
  3179. ssl->in_window_top = 0;
  3180. ssl->in_window = 0;
  3181. }
  3182. static inline uint64_t ssl_load_six_bytes( unsigned char *buf )
  3183. {
  3184. return( ( (uint64_t) buf[0] << 40 ) |
  3185. ( (uint64_t) buf[1] << 32 ) |
  3186. ( (uint64_t) buf[2] << 24 ) |
  3187. ( (uint64_t) buf[3] << 16 ) |
  3188. ( (uint64_t) buf[4] << 8 ) |
  3189. ( (uint64_t) buf[5] ) );
  3190. }
  3191. /*
  3192. * Return 0 if sequence number is acceptable, -1 otherwise
  3193. */
  3194. int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context *ssl )
  3195. {
  3196. uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
  3197. uint64_t bit;
  3198. if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
  3199. return( 0 );
  3200. if( rec_seqnum > ssl->in_window_top )
  3201. return( 0 );
  3202. bit = ssl->in_window_top - rec_seqnum;
  3203. if( bit >= 64 )
  3204. return( -1 );
  3205. if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 )
  3206. return( -1 );
  3207. return( 0 );
  3208. }
  3209. /*
  3210. * Update replay window on new validated record
  3211. */
  3212. void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl )
  3213. {
  3214. uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
  3215. if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
  3216. return;
  3217. if( rec_seqnum > ssl->in_window_top )
  3218. {
  3219. /* Update window_top and the contents of the window */
  3220. uint64_t shift = rec_seqnum - ssl->in_window_top;
  3221. if( shift >= 64 )
  3222. ssl->in_window = 1;
  3223. else
  3224. {
  3225. ssl->in_window <<= shift;
  3226. ssl->in_window |= 1;
  3227. }
  3228. ssl->in_window_top = rec_seqnum;
  3229. }
  3230. else
  3231. {
  3232. /* Mark that number as seen in the current window */
  3233. uint64_t bit = ssl->in_window_top - rec_seqnum;
  3234. if( bit < 64 ) /* Always true, but be extra sure */
  3235. ssl->in_window |= (uint64_t) 1 << bit;
  3236. }
  3237. }
  3238. #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
  3239. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
  3240. /* Forward declaration */
  3241. static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial );
  3242. /*
  3243. * Without any SSL context, check if a datagram looks like a ClientHello with
  3244. * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message.
  3245. * Both input and output include full DTLS headers.
  3246. *
  3247. * - if cookie is valid, return 0
  3248. * - if ClientHello looks superficially valid but cookie is not,
  3249. * fill obuf and set olen, then
  3250. * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
  3251. * - otherwise return a specific error code
  3252. */
  3253. static int ssl_check_dtls_clihlo_cookie(
  3254. mbedtls_ssl_cookie_write_t *f_cookie_write,
  3255. mbedtls_ssl_cookie_check_t *f_cookie_check,
  3256. void *p_cookie,
  3257. const unsigned char *cli_id, size_t cli_id_len,
  3258. const unsigned char *in, size_t in_len,
  3259. unsigned char *obuf, size_t buf_len, size_t *olen )
  3260. {
  3261. size_t sid_len, cookie_len;
  3262. unsigned char *p;
  3263. if( f_cookie_write == NULL || f_cookie_check == NULL )
  3264. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  3265. /*
  3266. * Structure of ClientHello with record and handshake headers,
  3267. * and expected values. We don't need to check a lot, more checks will be
  3268. * done when actually parsing the ClientHello - skipping those checks
  3269. * avoids code duplication and does not make cookie forging any easier.
  3270. *
  3271. * 0-0 ContentType type; copied, must be handshake
  3272. * 1-2 ProtocolVersion version; copied
  3273. * 3-4 uint16 epoch; copied, must be 0
  3274. * 5-10 uint48 sequence_number; copied
  3275. * 11-12 uint16 length; (ignored)
  3276. *
  3277. * 13-13 HandshakeType msg_type; (ignored)
  3278. * 14-16 uint24 length; (ignored)
  3279. * 17-18 uint16 message_seq; copied
  3280. * 19-21 uint24 fragment_offset; copied, must be 0
  3281. * 22-24 uint24 fragment_length; (ignored)
  3282. *
  3283. * 25-26 ProtocolVersion client_version; (ignored)
  3284. * 27-58 Random random; (ignored)
  3285. * 59-xx SessionID session_id; 1 byte len + sid_len content
  3286. * 60+ opaque cookie<0..2^8-1>; 1 byte len + content
  3287. * ...
  3288. *
  3289. * Minimum length is 61 bytes.
  3290. */
  3291. if( in_len < 61 ||
  3292. in[0] != MBEDTLS_SSL_MSG_HANDSHAKE ||
  3293. in[3] != 0 || in[4] != 0 ||
  3294. in[19] != 0 || in[20] != 0 || in[21] != 0 )
  3295. {
  3296. return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  3297. }
  3298. sid_len = in[59];
  3299. if( sid_len > in_len - 61 )
  3300. return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  3301. cookie_len = in[60 + sid_len];
  3302. if( cookie_len > in_len - 60 )
  3303. return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  3304. if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len,
  3305. cli_id, cli_id_len ) == 0 )
  3306. {
  3307. /* Valid cookie */
  3308. return( 0 );
  3309. }
  3310. /*
  3311. * If we get here, we've got an invalid cookie, let's prepare HVR.
  3312. *
  3313. * 0-0 ContentType type; copied
  3314. * 1-2 ProtocolVersion version; copied
  3315. * 3-4 uint16 epoch; copied
  3316. * 5-10 uint48 sequence_number; copied
  3317. * 11-12 uint16 length; olen - 13
  3318. *
  3319. * 13-13 HandshakeType msg_type; hello_verify_request
  3320. * 14-16 uint24 length; olen - 25
  3321. * 17-18 uint16 message_seq; copied
  3322. * 19-21 uint24 fragment_offset; copied
  3323. * 22-24 uint24 fragment_length; olen - 25
  3324. *
  3325. * 25-26 ProtocolVersion server_version; 0xfe 0xff
  3326. * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie
  3327. *
  3328. * Minimum length is 28.
  3329. */
  3330. if( buf_len < 28 )
  3331. return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
  3332. /* Copy most fields and adapt others */
  3333. memcpy( obuf, in, 25 );
  3334. obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
  3335. obuf[25] = 0xfe;
  3336. obuf[26] = 0xff;
  3337. /* Generate and write actual cookie */
  3338. p = obuf + 28;
  3339. if( f_cookie_write( p_cookie,
  3340. &p, obuf + buf_len, cli_id, cli_id_len ) != 0 )
  3341. {
  3342. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3343. }
  3344. *olen = p - obuf;
  3345. /* Go back and fill length fields */
  3346. obuf[27] = (unsigned char)( *olen - 28 );
  3347. obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 );
  3348. obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >> 8 );
  3349. obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 ) );
  3350. obuf[11] = (unsigned char)( ( *olen - 13 ) >> 8 );
  3351. obuf[12] = (unsigned char)( ( *olen - 13 ) );
  3352. return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
  3353. }
  3354. /*
  3355. * Handle possible client reconnect with the same UDP quadruplet
  3356. * (RFC 6347 Section 4.2.8).
  3357. *
  3358. * Called by ssl_parse_record_header() in case we receive an epoch 0 record
  3359. * that looks like a ClientHello.
  3360. *
  3361. * - if the input looks like a ClientHello without cookies,
  3362. * send back HelloVerifyRequest, then
  3363. * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
  3364. * - if the input looks like a ClientHello with a valid cookie,
  3365. * reset the session of the current context, and
  3366. * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT
  3367. * - if anything goes wrong, return a specific error code
  3368. *
  3369. * mbedtls_ssl_read_record() will ignore the record if anything else than
  3370. * MBEDTLS_ERR_SSL_CLIENT_RECONNECT or 0 is returned, although this function
  3371. * cannot not return 0.
  3372. */
  3373. static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl )
  3374. {
  3375. int ret;
  3376. size_t len;
  3377. ret = ssl_check_dtls_clihlo_cookie(
  3378. ssl->conf->f_cookie_write,
  3379. ssl->conf->f_cookie_check,
  3380. ssl->conf->p_cookie,
  3381. ssl->cli_id, ssl->cli_id_len,
  3382. ssl->in_buf, ssl->in_left,
  3383. ssl->out_buf, MBEDTLS_SSL_OUT_CONTENT_LEN, &len );
  3384. MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_dtls_clihlo_cookie", ret );
  3385. if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED )
  3386. {
  3387. /* Don't check write errors as we can't do anything here.
  3388. * If the error is permanent we'll catch it later,
  3389. * if it's not, then hopefully it'll work next time. */
  3390. (void) ssl->f_send( ssl->p_bio, ssl->out_buf, len );
  3391. return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
  3392. }
  3393. if( ret == 0 )
  3394. {
  3395. /* Got a valid cookie, partially reset context */
  3396. if( ( ret = ssl_session_reset_int( ssl, 1 ) ) != 0 )
  3397. {
  3398. MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret );
  3399. return( ret );
  3400. }
  3401. return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT );
  3402. }
  3403. return( ret );
  3404. }
  3405. #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
  3406. /*
  3407. * ContentType type;
  3408. * ProtocolVersion version;
  3409. * uint16 epoch; // DTLS only
  3410. * uint48 sequence_number; // DTLS only
  3411. * uint16 length;
  3412. *
  3413. * Return 0 if header looks sane (and, for DTLS, the record is expected)
  3414. * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad,
  3415. * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected.
  3416. *
  3417. * With DTLS, mbedtls_ssl_read_record() will:
  3418. * 1. proceed with the record if this function returns 0
  3419. * 2. drop only the current record if this function returns UNEXPECTED_RECORD
  3420. * 3. return CLIENT_RECONNECT if this function return that value
  3421. * 4. drop the whole datagram if this function returns anything else.
  3422. * Point 2 is needed when the peer is resending, and we have already received
  3423. * the first record from a datagram but are still waiting for the others.
  3424. */
  3425. static int ssl_parse_record_header( mbedtls_ssl_context *ssl )
  3426. {
  3427. int major_ver, minor_ver;
  3428. MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) );
  3429. ssl->in_msgtype = ssl->in_hdr[0];
  3430. ssl->in_msglen = ( ssl->in_len[0] << 8 ) | ssl->in_len[1];
  3431. mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, ssl->in_hdr + 1 );
  3432. MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, "
  3433. "version = [%d:%d], msglen = %d",
  3434. ssl->in_msgtype,
  3435. major_ver, minor_ver, ssl->in_msglen ) );
  3436. /* Check record type */
  3437. if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE &&
  3438. ssl->in_msgtype != MBEDTLS_SSL_MSG_ALERT &&
  3439. ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
  3440. ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
  3441. {
  3442. MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) );
  3443. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3444. /* Silently ignore invalid DTLS records as recommended by RFC 6347
  3445. * Section 4.1.2.7 */
  3446. if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  3447. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3448. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  3449. MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  3450. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3451. }
  3452. /* Check version */
  3453. if( major_ver != ssl->major_ver )
  3454. {
  3455. MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch" ) );
  3456. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3457. }
  3458. if( minor_ver > ssl->conf->max_minor_ver )
  3459. {
  3460. MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) );
  3461. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3462. }
  3463. /* Check length against the size of our buffer */
  3464. if( ssl->in_msglen > MBEDTLS_SSL_IN_BUFFER_LEN
  3465. - (size_t)( ssl->in_msg - ssl->in_buf ) )
  3466. {
  3467. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  3468. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3469. }
  3470. /*
  3471. * DTLS-related tests.
  3472. * Check epoch before checking length constraint because
  3473. * the latter varies with the epoch. E.g., if a ChangeCipherSpec
  3474. * message gets duplicated before the corresponding Finished message,
  3475. * the second ChangeCipherSpec should be discarded because it belongs
  3476. * to an old epoch, but not because its length is shorter than
  3477. * the minimum record length for packets using the new record transform.
  3478. * Note that these two kinds of failures are handled differently,
  3479. * as an unexpected record is silently skipped but an invalid
  3480. * record leads to the entire datagram being dropped.
  3481. */
  3482. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3483. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  3484. {
  3485. unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1];
  3486. /* Check epoch (and sequence number) with DTLS */
  3487. if( rec_epoch != ssl->in_epoch )
  3488. {
  3489. MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: "
  3490. "expected %d, received %d",
  3491. ssl->in_epoch, rec_epoch ) );
  3492. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
  3493. /*
  3494. * Check for an epoch 0 ClientHello. We can't use in_msg here to
  3495. * access the first byte of record content (handshake type), as we
  3496. * have an active transform (possibly iv_len != 0), so use the
  3497. * fact that the record header len is 13 instead.
  3498. */
  3499. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  3500. ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER &&
  3501. rec_epoch == 0 &&
  3502. ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  3503. ssl->in_left > 13 &&
  3504. ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO )
  3505. {
  3506. MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect "
  3507. "from the same port" ) );
  3508. return( ssl_handle_possible_reconnect( ssl ) );
  3509. }
  3510. else
  3511. #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
  3512. {
  3513. /* Consider buffering the record. */
  3514. if( rec_epoch == (unsigned int) ssl->in_epoch + 1 )
  3515. {
  3516. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Consider record for buffering" ) );
  3517. return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
  3518. }
  3519. return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
  3520. }
  3521. }
  3522. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  3523. /* Replay detection only works for the current epoch */
  3524. if( rec_epoch == ssl->in_epoch &&
  3525. mbedtls_ssl_dtls_replay_check( ssl ) != 0 )
  3526. {
  3527. MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) );
  3528. return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
  3529. }
  3530. #endif
  3531. /* Drop unexpected ApplicationData records,
  3532. * except at the beginning of renegotiations */
  3533. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA &&
  3534. ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER
  3535. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  3536. && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
  3537. ssl->state == MBEDTLS_SSL_SERVER_HELLO )
  3538. #endif
  3539. )
  3540. {
  3541. MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) );
  3542. return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
  3543. }
  3544. }
  3545. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3546. /* Check length against bounds of the current transform and version */
  3547. if( ssl->transform_in == NULL )
  3548. {
  3549. if( ssl->in_msglen < 1 ||
  3550. ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN )
  3551. {
  3552. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  3553. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3554. }
  3555. }
  3556. else
  3557. {
  3558. if( ssl->in_msglen < ssl->transform_in->minlen )
  3559. {
  3560. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  3561. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3562. }
  3563. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  3564. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
  3565. ssl->in_msglen > ssl->transform_in->minlen + MBEDTLS_SSL_IN_CONTENT_LEN )
  3566. {
  3567. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  3568. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3569. }
  3570. #endif
  3571. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  3572. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  3573. /*
  3574. * TLS encrypted messages can have up to 256 bytes of padding
  3575. */
  3576. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 &&
  3577. ssl->in_msglen > ssl->transform_in->minlen +
  3578. MBEDTLS_SSL_IN_CONTENT_LEN + 256 )
  3579. {
  3580. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  3581. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3582. }
  3583. #endif
  3584. }
  3585. return( 0 );
  3586. }
  3587. /*
  3588. * If applicable, decrypt (and decompress) record content
  3589. */
  3590. static int ssl_prepare_record_content( mbedtls_ssl_context *ssl )
  3591. {
  3592. int ret, done = 0;
  3593. MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network",
  3594. ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen );
  3595. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  3596. if( mbedtls_ssl_hw_record_read != NULL )
  3597. {
  3598. MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) );
  3599. ret = mbedtls_ssl_hw_record_read( ssl );
  3600. if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
  3601. {
  3602. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret );
  3603. return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  3604. }
  3605. if( ret == 0 )
  3606. done = 1;
  3607. }
  3608. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  3609. if( !done && ssl->transform_in != NULL )
  3610. {
  3611. if( ( ret = ssl_decrypt_buf( ssl ) ) != 0 )
  3612. {
  3613. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret );
  3614. return( ret );
  3615. }
  3616. MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt",
  3617. ssl->in_msg, ssl->in_msglen );
  3618. if( ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN )
  3619. {
  3620. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  3621. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3622. }
  3623. }
  3624. #if defined(MBEDTLS_ZLIB_SUPPORT)
  3625. if( ssl->transform_in != NULL &&
  3626. ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
  3627. {
  3628. if( ( ret = ssl_decompress_buf( ssl ) ) != 0 )
  3629. {
  3630. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret );
  3631. return( ret );
  3632. }
  3633. }
  3634. #endif /* MBEDTLS_ZLIB_SUPPORT */
  3635. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  3636. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  3637. {
  3638. mbedtls_ssl_dtls_replay_update( ssl );
  3639. }
  3640. #endif
  3641. return( 0 );
  3642. }
  3643. static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl );
  3644. /*
  3645. * Read a record.
  3646. *
  3647. * Silently ignore non-fatal alert (and for DTLS, invalid records as well,
  3648. * RFC 6347 4.1.2.7) and continue reading until a valid record is found.
  3649. *
  3650. */
  3651. /* Helper functions for mbedtls_ssl_read_record(). */
  3652. static int ssl_consume_current_message( mbedtls_ssl_context *ssl );
  3653. static int ssl_get_next_record( mbedtls_ssl_context *ssl );
  3654. static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl );
  3655. int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl,
  3656. unsigned update_hs_digest )
  3657. {
  3658. int ret;
  3659. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) );
  3660. if( ssl->keep_current_message == 0 )
  3661. {
  3662. do {
  3663. ret = ssl_consume_current_message( ssl );
  3664. if( ret != 0 )
  3665. return( ret );
  3666. if( ssl_record_is_in_progress( ssl ) == 0 )
  3667. {
  3668. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3669. int have_buffered = 0;
  3670. /* We only check for buffered messages if the
  3671. * current datagram is fully consumed. */
  3672. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  3673. ssl_next_record_is_in_datagram( ssl ) == 0 )
  3674. {
  3675. if( ssl_load_buffered_message( ssl ) == 0 )
  3676. have_buffered = 1;
  3677. }
  3678. if( have_buffered == 0 )
  3679. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3680. {
  3681. ret = ssl_get_next_record( ssl );
  3682. if( ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING )
  3683. continue;
  3684. if( ret != 0 )
  3685. {
  3686. MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_get_next_record" ), ret );
  3687. return( ret );
  3688. }
  3689. }
  3690. }
  3691. ret = mbedtls_ssl_handle_message_type( ssl );
  3692. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3693. if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
  3694. {
  3695. /* Buffer future message */
  3696. ret = ssl_buffer_message( ssl );
  3697. if( ret != 0 )
  3698. return( ret );
  3699. ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
  3700. }
  3701. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3702. } while( MBEDTLS_ERR_SSL_NON_FATAL == ret ||
  3703. MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret );
  3704. if( 0 != ret )
  3705. {
  3706. MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_handle_message_type" ), ret );
  3707. return( ret );
  3708. }
  3709. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  3710. update_hs_digest == 1 )
  3711. {
  3712. mbedtls_ssl_update_handshake_status( ssl );
  3713. }
  3714. }
  3715. else
  3716. {
  3717. MBEDTLS_SSL_DEBUG_MSG( 2, ( "reuse previously read message" ) );
  3718. ssl->keep_current_message = 0;
  3719. }
  3720. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) );
  3721. return( 0 );
  3722. }
  3723. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3724. static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl )
  3725. {
  3726. if( ssl->in_left > ssl->next_record_offset )
  3727. return( 1 );
  3728. return( 0 );
  3729. }
  3730. static int ssl_load_buffered_message( mbedtls_ssl_context *ssl )
  3731. {
  3732. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  3733. mbedtls_ssl_hs_buffer * hs_buf;
  3734. int ret = 0;
  3735. if( hs == NULL )
  3736. return( -1 );
  3737. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_messsage" ) );
  3738. if( ssl->state == MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC ||
  3739. ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
  3740. {
  3741. /* Check if we have seen a ChangeCipherSpec before.
  3742. * If yes, synthesize a CCS record. */
  3743. if( !hs->buffering.seen_ccs )
  3744. {
  3745. MBEDTLS_SSL_DEBUG_MSG( 2, ( "CCS not seen in the current flight" ) );
  3746. ret = -1;
  3747. goto exit;
  3748. }
  3749. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Injecting buffered CCS message" ) );
  3750. ssl->in_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
  3751. ssl->in_msglen = 1;
  3752. ssl->in_msg[0] = 1;
  3753. /* As long as they are equal, the exact value doesn't matter. */
  3754. ssl->in_left = 0;
  3755. ssl->next_record_offset = 0;
  3756. hs->buffering.seen_ccs = 0;
  3757. goto exit;
  3758. }
  3759. #if defined(MBEDTLS_DEBUG_C)
  3760. /* Debug only */
  3761. {
  3762. unsigned offset;
  3763. for( offset = 1; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ )
  3764. {
  3765. hs_buf = &hs->buffering.hs[offset];
  3766. if( hs_buf->is_valid == 1 )
  3767. {
  3768. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Future message with sequence number %u %s buffered.",
  3769. hs->in_msg_seq + offset,
  3770. hs_buf->is_complete ? "fully" : "partially" ) );
  3771. }
  3772. }
  3773. }
  3774. #endif /* MBEDTLS_DEBUG_C */
  3775. /* Check if we have buffered and/or fully reassembled the
  3776. * next handshake message. */
  3777. hs_buf = &hs->buffering.hs[0];
  3778. if( ( hs_buf->is_valid == 1 ) && ( hs_buf->is_complete == 1 ) )
  3779. {
  3780. /* Synthesize a record containing the buffered HS message. */
  3781. size_t msg_len = ( hs_buf->data[1] << 16 ) |
  3782. ( hs_buf->data[2] << 8 ) |
  3783. hs_buf->data[3];
  3784. /* Double-check that we haven't accidentally buffered
  3785. * a message that doesn't fit into the input buffer. */
  3786. if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN )
  3787. {
  3788. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  3789. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3790. }
  3791. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message has been buffered - load" ) );
  3792. MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered handshake message (incl. header)",
  3793. hs_buf->data, msg_len + 12 );
  3794. ssl->in_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  3795. ssl->in_hslen = msg_len + 12;
  3796. ssl->in_msglen = msg_len + 12;
  3797. memcpy( ssl->in_msg, hs_buf->data, ssl->in_hslen );
  3798. ret = 0;
  3799. goto exit;
  3800. }
  3801. else
  3802. {
  3803. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message %u not or only partially bufffered",
  3804. hs->in_msg_seq ) );
  3805. }
  3806. ret = -1;
  3807. exit:
  3808. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_message" ) );
  3809. return( ret );
  3810. }
  3811. static int ssl_buffer_make_space( mbedtls_ssl_context *ssl,
  3812. size_t desired )
  3813. {
  3814. int offset;
  3815. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  3816. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Attempt to free buffered messages to have %u bytes available",
  3817. (unsigned) desired ) );
  3818. /* Get rid of future records epoch first, if such exist. */
  3819. ssl_free_buffered_record( ssl );
  3820. /* Check if we have enough space available now. */
  3821. if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  3822. hs->buffering.total_bytes_buffered ) )
  3823. {
  3824. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing future epoch record" ) );
  3825. return( 0 );
  3826. }
  3827. /* We don't have enough space to buffer the next expected handshake
  3828. * message. Remove buffers used for future messages to gain space,
  3829. * starting with the most distant one. */
  3830. for( offset = MBEDTLS_SSL_MAX_BUFFERED_HS - 1;
  3831. offset >= 0; offset-- )
  3832. {
  3833. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Free buffering slot %d to make space for reassembly of next handshake message",
  3834. offset ) );
  3835. ssl_buffering_free_slot( ssl, (uint8_t) offset );
  3836. /* Check if we have enough space available now. */
  3837. if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  3838. hs->buffering.total_bytes_buffered ) )
  3839. {
  3840. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing buffered HS messages" ) );
  3841. return( 0 );
  3842. }
  3843. }
  3844. return( -1 );
  3845. }
  3846. static int ssl_buffer_message( mbedtls_ssl_context *ssl )
  3847. {
  3848. int ret = 0;
  3849. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  3850. if( hs == NULL )
  3851. return( 0 );
  3852. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_buffer_message" ) );
  3853. switch( ssl->in_msgtype )
  3854. {
  3855. case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC:
  3856. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Remember CCS message" ) );
  3857. hs->buffering.seen_ccs = 1;
  3858. break;
  3859. case MBEDTLS_SSL_MSG_HANDSHAKE:
  3860. {
  3861. unsigned recv_msg_seq_offset;
  3862. unsigned recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
  3863. mbedtls_ssl_hs_buffer *hs_buf;
  3864. size_t msg_len = ssl->in_hslen - 12;
  3865. /* We should never receive an old handshake
  3866. * message - double-check nonetheless. */
  3867. if( recv_msg_seq < ssl->handshake->in_msg_seq )
  3868. {
  3869. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  3870. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3871. }
  3872. recv_msg_seq_offset = recv_msg_seq - ssl->handshake->in_msg_seq;
  3873. if( recv_msg_seq_offset >= MBEDTLS_SSL_MAX_BUFFERED_HS )
  3874. {
  3875. /* Silently ignore -- message too far in the future */
  3876. MBEDTLS_SSL_DEBUG_MSG( 2,
  3877. ( "Ignore future HS message with sequence number %u, "
  3878. "buffering window %u - %u",
  3879. recv_msg_seq, ssl->handshake->in_msg_seq,
  3880. ssl->handshake->in_msg_seq + MBEDTLS_SSL_MAX_BUFFERED_HS - 1 ) );
  3881. goto exit;
  3882. }
  3883. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering HS message with sequence number %u, offset %u ",
  3884. recv_msg_seq, recv_msg_seq_offset ) );
  3885. hs_buf = &hs->buffering.hs[ recv_msg_seq_offset ];
  3886. /* Check if the buffering for this seq nr has already commenced. */
  3887. if( !hs_buf->is_valid )
  3888. {
  3889. size_t reassembly_buf_sz;
  3890. hs_buf->is_fragmented =
  3891. ( ssl_hs_is_proper_fragment( ssl ) == 1 );
  3892. /* We copy the message back into the input buffer
  3893. * after reassembly, so check that it's not too large.
  3894. * This is an implementation-specific limitation
  3895. * and not one from the standard, hence it is not
  3896. * checked in ssl_check_hs_header(). */
  3897. if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN )
  3898. {
  3899. /* Ignore message */
  3900. goto exit;
  3901. }
  3902. /* Check if we have enough space to buffer the message. */
  3903. if( hs->buffering.total_bytes_buffered >
  3904. MBEDTLS_SSL_DTLS_MAX_BUFFERING )
  3905. {
  3906. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  3907. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3908. }
  3909. reassembly_buf_sz = ssl_get_reassembly_buffer_size( msg_len,
  3910. hs_buf->is_fragmented );
  3911. if( reassembly_buf_sz > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  3912. hs->buffering.total_bytes_buffered ) )
  3913. {
  3914. if( recv_msg_seq_offset > 0 )
  3915. {
  3916. /* If we can't buffer a future message because
  3917. * of space limitations -- ignore. */
  3918. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future message of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- ignore\n",
  3919. (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  3920. (unsigned) hs->buffering.total_bytes_buffered ) );
  3921. goto exit;
  3922. }
  3923. else
  3924. {
  3925. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future message of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- attempt to make space by freeing buffered future messages\n",
  3926. (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  3927. (unsigned) hs->buffering.total_bytes_buffered ) );
  3928. }
  3929. if( ssl_buffer_make_space( ssl, reassembly_buf_sz ) != 0 )
  3930. {
  3931. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reassembly of next message of size %u (%u with bitmap) would exceed the compile-time limit %u (already %u bytes buffered) -- fail\n",
  3932. (unsigned) msg_len,
  3933. (unsigned) reassembly_buf_sz,
  3934. MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  3935. (unsigned) hs->buffering.total_bytes_buffered ) );
  3936. ret = MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
  3937. goto exit;
  3938. }
  3939. }
  3940. MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %d",
  3941. msg_len ) );
  3942. hs_buf->data = mbedtls_calloc( 1, reassembly_buf_sz );
  3943. if( hs_buf->data == NULL )
  3944. {
  3945. ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
  3946. goto exit;
  3947. }
  3948. hs_buf->data_len = reassembly_buf_sz;
  3949. /* Prepare final header: copy msg_type, length and message_seq,
  3950. * then add standardised fragment_offset and fragment_length */
  3951. memcpy( hs_buf->data, ssl->in_msg, 6 );
  3952. memset( hs_buf->data + 6, 0, 3 );
  3953. memcpy( hs_buf->data + 9, hs_buf->data + 1, 3 );
  3954. hs_buf->is_valid = 1;
  3955. hs->buffering.total_bytes_buffered += reassembly_buf_sz;
  3956. }
  3957. else
  3958. {
  3959. /* Make sure msg_type and length are consistent */
  3960. if( memcmp( hs_buf->data, ssl->in_msg, 4 ) != 0 )
  3961. {
  3962. MBEDTLS_SSL_DEBUG_MSG( 1, ( "Fragment header mismatch - ignore" ) );
  3963. /* Ignore */
  3964. goto exit;
  3965. }
  3966. }
  3967. if( !hs_buf->is_complete )
  3968. {
  3969. size_t frag_len, frag_off;
  3970. unsigned char * const msg = hs_buf->data + 12;
  3971. /*
  3972. * Check and copy current fragment
  3973. */
  3974. /* Validation of header fields already done in
  3975. * mbedtls_ssl_prepare_handshake_record(). */
  3976. frag_off = ssl_get_hs_frag_off( ssl );
  3977. frag_len = ssl_get_hs_frag_len( ssl );
  3978. MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %d, length = %d",
  3979. frag_off, frag_len ) );
  3980. memcpy( msg + frag_off, ssl->in_msg + 12, frag_len );
  3981. if( hs_buf->is_fragmented )
  3982. {
  3983. unsigned char * const bitmask = msg + msg_len;
  3984. ssl_bitmask_set( bitmask, frag_off, frag_len );
  3985. hs_buf->is_complete = ( ssl_bitmask_check( bitmask,
  3986. msg_len ) == 0 );
  3987. }
  3988. else
  3989. {
  3990. hs_buf->is_complete = 1;
  3991. }
  3992. MBEDTLS_SSL_DEBUG_MSG( 2, ( "message %scomplete",
  3993. hs_buf->is_complete ? "" : "not yet " ) );
  3994. }
  3995. break;
  3996. }
  3997. default:
  3998. /* We don't buffer other types of messages. */
  3999. break;
  4000. }
  4001. exit:
  4002. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_buffer_message" ) );
  4003. return( ret );
  4004. }
  4005. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4006. static int ssl_consume_current_message( mbedtls_ssl_context *ssl )
  4007. {
  4008. /*
  4009. * Consume last content-layer message and potentially
  4010. * update in_msglen which keeps track of the contents'
  4011. * consumption state.
  4012. *
  4013. * (1) Handshake messages:
  4014. * Remove last handshake message, move content
  4015. * and adapt in_msglen.
  4016. *
  4017. * (2) Alert messages:
  4018. * Consume whole record content, in_msglen = 0.
  4019. *
  4020. * (3) Change cipher spec:
  4021. * Consume whole record content, in_msglen = 0.
  4022. *
  4023. * (4) Application data:
  4024. * Don't do anything - the record layer provides
  4025. * the application data as a stream transport
  4026. * and consumes through mbedtls_ssl_read only.
  4027. *
  4028. */
  4029. /* Case (1): Handshake messages */
  4030. if( ssl->in_hslen != 0 )
  4031. {
  4032. /* Hard assertion to be sure that no application data
  4033. * is in flight, as corrupting ssl->in_msglen during
  4034. * ssl->in_offt != NULL is fatal. */
  4035. if( ssl->in_offt != NULL )
  4036. {
  4037. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4038. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4039. }
  4040. /*
  4041. * Get next Handshake message in the current record
  4042. */
  4043. /* Notes:
  4044. * (1) in_hslen is not necessarily the size of the
  4045. * current handshake content: If DTLS handshake
  4046. * fragmentation is used, that's the fragment
  4047. * size instead. Using the total handshake message
  4048. * size here is faulty and should be changed at
  4049. * some point.
  4050. * (2) While it doesn't seem to cause problems, one
  4051. * has to be very careful not to assume that in_hslen
  4052. * is always <= in_msglen in a sensible communication.
  4053. * Again, it's wrong for DTLS handshake fragmentation.
  4054. * The following check is therefore mandatory, and
  4055. * should not be treated as a silently corrected assertion.
  4056. * Additionally, ssl->in_hslen might be arbitrarily out of
  4057. * bounds after handling a DTLS message with an unexpected
  4058. * sequence number, see mbedtls_ssl_prepare_handshake_record.
  4059. */
  4060. if( ssl->in_hslen < ssl->in_msglen )
  4061. {
  4062. ssl->in_msglen -= ssl->in_hslen;
  4063. memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen,
  4064. ssl->in_msglen );
  4065. MBEDTLS_SSL_DEBUG_BUF( 4, "remaining content in record",
  4066. ssl->in_msg, ssl->in_msglen );
  4067. }
  4068. else
  4069. {
  4070. ssl->in_msglen = 0;
  4071. }
  4072. ssl->in_hslen = 0;
  4073. }
  4074. /* Case (4): Application data */
  4075. else if( ssl->in_offt != NULL )
  4076. {
  4077. return( 0 );
  4078. }
  4079. /* Everything else (CCS & Alerts) */
  4080. else
  4081. {
  4082. ssl->in_msglen = 0;
  4083. }
  4084. return( 0 );
  4085. }
  4086. static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl )
  4087. {
  4088. if( ssl->in_msglen > 0 )
  4089. return( 1 );
  4090. return( 0 );
  4091. }
  4092. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4093. static void ssl_free_buffered_record( mbedtls_ssl_context *ssl )
  4094. {
  4095. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4096. if( hs == NULL )
  4097. return;
  4098. if( hs->buffering.future_record.data != NULL )
  4099. {
  4100. hs->buffering.total_bytes_buffered -=
  4101. hs->buffering.future_record.len;
  4102. mbedtls_free( hs->buffering.future_record.data );
  4103. hs->buffering.future_record.data = NULL;
  4104. }
  4105. }
  4106. static int ssl_load_buffered_record( mbedtls_ssl_context *ssl )
  4107. {
  4108. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4109. unsigned char * rec;
  4110. size_t rec_len;
  4111. unsigned rec_epoch;
  4112. if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  4113. return( 0 );
  4114. if( hs == NULL )
  4115. return( 0 );
  4116. rec = hs->buffering.future_record.data;
  4117. rec_len = hs->buffering.future_record.len;
  4118. rec_epoch = hs->buffering.future_record.epoch;
  4119. if( rec == NULL )
  4120. return( 0 );
  4121. /* Only consider loading future records if the
  4122. * input buffer is empty. */
  4123. if( ssl_next_record_is_in_datagram( ssl ) == 1 )
  4124. return( 0 );
  4125. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_record" ) );
  4126. if( rec_epoch != ssl->in_epoch )
  4127. {
  4128. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffered record not from current epoch." ) );
  4129. goto exit;
  4130. }
  4131. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Found buffered record from current epoch - load" ) );
  4132. /* Double-check that the record is not too large */
  4133. if( rec_len > MBEDTLS_SSL_IN_BUFFER_LEN -
  4134. (size_t)( ssl->in_hdr - ssl->in_buf ) )
  4135. {
  4136. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4137. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4138. }
  4139. memcpy( ssl->in_hdr, rec, rec_len );
  4140. ssl->in_left = rec_len;
  4141. ssl->next_record_offset = 0;
  4142. ssl_free_buffered_record( ssl );
  4143. exit:
  4144. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_record" ) );
  4145. return( 0 );
  4146. }
  4147. static int ssl_buffer_future_record( mbedtls_ssl_context *ssl )
  4148. {
  4149. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4150. size_t const rec_hdr_len = 13;
  4151. size_t const total_buf_sz = rec_hdr_len + ssl->in_msglen;
  4152. /* Don't buffer future records outside handshakes. */
  4153. if( hs == NULL )
  4154. return( 0 );
  4155. /* Only buffer handshake records (we are only interested
  4156. * in Finished messages). */
  4157. if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
  4158. return( 0 );
  4159. /* Don't buffer more than one future epoch record. */
  4160. if( hs->buffering.future_record.data != NULL )
  4161. return( 0 );
  4162. /* Don't buffer record if there's not enough buffering space remaining. */
  4163. if( total_buf_sz > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  4164. hs->buffering.total_bytes_buffered ) )
  4165. {
  4166. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future epoch record of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- ignore\n",
  4167. (unsigned) total_buf_sz, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  4168. (unsigned) hs->buffering.total_bytes_buffered ) );
  4169. return( 0 );
  4170. }
  4171. /* Buffer record */
  4172. MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffer record from epoch %u",
  4173. ssl->in_epoch + 1 ) );
  4174. MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered record", ssl->in_hdr,
  4175. rec_hdr_len + ssl->in_msglen );
  4176. /* ssl_parse_record_header() only considers records
  4177. * of the next epoch as candidates for buffering. */
  4178. hs->buffering.future_record.epoch = ssl->in_epoch + 1;
  4179. hs->buffering.future_record.len = total_buf_sz;
  4180. hs->buffering.future_record.data =
  4181. mbedtls_calloc( 1, hs->buffering.future_record.len );
  4182. if( hs->buffering.future_record.data == NULL )
  4183. {
  4184. /* If we run out of RAM trying to buffer a
  4185. * record from the next epoch, just ignore. */
  4186. return( 0 );
  4187. }
  4188. memcpy( hs->buffering.future_record.data, ssl->in_hdr, total_buf_sz );
  4189. hs->buffering.total_bytes_buffered += total_buf_sz;
  4190. return( 0 );
  4191. }
  4192. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4193. static int ssl_get_next_record( mbedtls_ssl_context *ssl )
  4194. {
  4195. int ret;
  4196. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4197. /* We might have buffered a future record; if so,
  4198. * and if the epoch matches now, load it.
  4199. * On success, this call will set ssl->in_left to
  4200. * the length of the buffered record, so that
  4201. * the calls to ssl_fetch_input() below will
  4202. * essentially be no-ops. */
  4203. ret = ssl_load_buffered_record( ssl );
  4204. if( ret != 0 )
  4205. return( ret );
  4206. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4207. if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_hdr_len( ssl ) ) ) != 0 )
  4208. {
  4209. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
  4210. return( ret );
  4211. }
  4212. if( ( ret = ssl_parse_record_header( ssl ) ) != 0 )
  4213. {
  4214. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4215. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  4216. ret != MBEDTLS_ERR_SSL_CLIENT_RECONNECT )
  4217. {
  4218. if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
  4219. {
  4220. ret = ssl_buffer_future_record( ssl );
  4221. if( ret != 0 )
  4222. return( ret );
  4223. /* Fall through to handling of unexpected records */
  4224. ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
  4225. }
  4226. if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD )
  4227. {
  4228. /* Skip unexpected record (but not whole datagram) */
  4229. ssl->next_record_offset = ssl->in_msglen
  4230. + mbedtls_ssl_hdr_len( ssl );
  4231. MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding unexpected record "
  4232. "(header)" ) );
  4233. }
  4234. else
  4235. {
  4236. /* Skip invalid record and the rest of the datagram */
  4237. ssl->next_record_offset = 0;
  4238. ssl->in_left = 0;
  4239. MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record "
  4240. "(header)" ) );
  4241. }
  4242. /* Get next record */
  4243. return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
  4244. }
  4245. #endif
  4246. return( ret );
  4247. }
  4248. /*
  4249. * Read and optionally decrypt the message contents
  4250. */
  4251. if( ( ret = mbedtls_ssl_fetch_input( ssl,
  4252. mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen ) ) != 0 )
  4253. {
  4254. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
  4255. return( ret );
  4256. }
  4257. /* Done reading this record, get ready for the next one */
  4258. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4259. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  4260. {
  4261. ssl->next_record_offset = ssl->in_msglen + mbedtls_ssl_hdr_len( ssl );
  4262. if( ssl->next_record_offset < ssl->in_left )
  4263. {
  4264. MBEDTLS_SSL_DEBUG_MSG( 3, ( "more than one record within datagram" ) );
  4265. }
  4266. }
  4267. else
  4268. #endif
  4269. ssl->in_left = 0;
  4270. if( ( ret = ssl_prepare_record_content( ssl ) ) != 0 )
  4271. {
  4272. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4273. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  4274. {
  4275. /* Silently discard invalid records */
  4276. if( ret == MBEDTLS_ERR_SSL_INVALID_RECORD ||
  4277. ret == MBEDTLS_ERR_SSL_INVALID_MAC )
  4278. {
  4279. /* Except when waiting for Finished as a bad mac here
  4280. * probably means something went wrong in the handshake
  4281. * (eg wrong psk used, mitm downgrade attempt, etc.) */
  4282. if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED ||
  4283. ssl->state == MBEDTLS_SSL_SERVER_FINISHED )
  4284. {
  4285. #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
  4286. if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
  4287. {
  4288. mbedtls_ssl_send_alert_message( ssl,
  4289. MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4290. MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
  4291. }
  4292. #endif
  4293. return( ret );
  4294. }
  4295. #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
  4296. if( ssl->conf->badmac_limit != 0 &&
  4297. ++ssl->badmac_seen >= ssl->conf->badmac_limit )
  4298. {
  4299. MBEDTLS_SSL_DEBUG_MSG( 1, ( "too many records with bad MAC" ) );
  4300. return( MBEDTLS_ERR_SSL_INVALID_MAC );
  4301. }
  4302. #endif
  4303. /* As above, invalid records cause
  4304. * dismissal of the whole datagram. */
  4305. ssl->next_record_offset = 0;
  4306. ssl->in_left = 0;
  4307. MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) );
  4308. return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
  4309. }
  4310. return( ret );
  4311. }
  4312. else
  4313. #endif
  4314. {
  4315. /* Error out (and send alert) on invalid records */
  4316. #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
  4317. if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
  4318. {
  4319. mbedtls_ssl_send_alert_message( ssl,
  4320. MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4321. MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
  4322. }
  4323. #endif
  4324. return( ret );
  4325. }
  4326. }
  4327. return( 0 );
  4328. }
  4329. int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl )
  4330. {
  4331. int ret;
  4332. /*
  4333. * Handle particular types of records
  4334. */
  4335. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
  4336. {
  4337. if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 )
  4338. {
  4339. return( ret );
  4340. }
  4341. }
  4342. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
  4343. {
  4344. if( ssl->in_msglen != 1 )
  4345. {
  4346. MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, len: %d",
  4347. ssl->in_msglen ) );
  4348. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4349. }
  4350. if( ssl->in_msg[0] != 1 )
  4351. {
  4352. MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, content: %02x",
  4353. ssl->in_msg[0] ) );
  4354. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4355. }
  4356. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4357. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  4358. ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC &&
  4359. ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
  4360. {
  4361. if( ssl->handshake == NULL )
  4362. {
  4363. MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping ChangeCipherSpec outside handshake" ) );
  4364. return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
  4365. }
  4366. MBEDTLS_SSL_DEBUG_MSG( 1, ( "received out-of-order ChangeCipherSpec - remember" ) );
  4367. return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
  4368. }
  4369. #endif
  4370. }
  4371. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
  4372. {
  4373. if( ssl->in_msglen != 2 )
  4374. {
  4375. /* Note: Standard allows for more than one 2 byte alert
  4376. to be packed in a single message, but Mbed TLS doesn't
  4377. currently support this. */
  4378. MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid alert message, len: %d",
  4379. ssl->in_msglen ) );
  4380. return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4381. }
  4382. MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]",
  4383. ssl->in_msg[0], ssl->in_msg[1] ) );
  4384. /*
  4385. * Ignore non-fatal alerts, except close_notify and no_renegotiation
  4386. */
  4387. if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL )
  4388. {
  4389. MBEDTLS_SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)",
  4390. ssl->in_msg[1] ) );
  4391. return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE );
  4392. }
  4393. if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
  4394. ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY )
  4395. {
  4396. MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a close notify message" ) );
  4397. return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY );
  4398. }
  4399. #if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED)
  4400. if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
  4401. ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION )
  4402. {
  4403. MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no renegotiation alert" ) );
  4404. /* Will be handled when trying to parse ServerHello */
  4405. return( 0 );
  4406. }
  4407. #endif
  4408. #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C)
  4409. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
  4410. ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  4411. ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
  4412. ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
  4413. {
  4414. MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) );
  4415. /* Will be handled in mbedtls_ssl_parse_certificate() */
  4416. return( 0 );
  4417. }
  4418. #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
  4419. /* Silently ignore: fetch new message */
  4420. return MBEDTLS_ERR_SSL_NON_FATAL;
  4421. }
  4422. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4423. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  4424. ssl->handshake != NULL &&
  4425. ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
  4426. {
  4427. ssl_handshake_wrapup_free_hs_transform( ssl );
  4428. }
  4429. #endif
  4430. return( 0 );
  4431. }
  4432. int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl )
  4433. {
  4434. int ret;
  4435. if( ( ret = mbedtls_ssl_send_alert_message( ssl,
  4436. MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4437. MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ) != 0 )
  4438. {
  4439. return( ret );
  4440. }
  4441. return( 0 );
  4442. }
  4443. int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl,
  4444. unsigned char level,
  4445. unsigned char message )
  4446. {
  4447. int ret;
  4448. if( ssl == NULL || ssl->conf == NULL )
  4449. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  4450. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) );
  4451. MBEDTLS_SSL_DEBUG_MSG( 3, ( "send alert level=%u message=%u", level, message ));
  4452. ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
  4453. ssl->out_msglen = 2;
  4454. ssl->out_msg[0] = level;
  4455. ssl->out_msg[1] = message;
  4456. if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
  4457. {
  4458. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
  4459. return( ret );
  4460. }
  4461. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= send alert message" ) );
  4462. return( 0 );
  4463. }
  4464. /*
  4465. * Handshake functions
  4466. */
  4467. #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \
  4468. !defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) && \
  4469. !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \
  4470. !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
  4471. !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \
  4472. !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \
  4473. !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
  4474. /* No certificate support -> dummy functions */
  4475. int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
  4476. {
  4477. const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
  4478. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
  4479. if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  4480. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  4481. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  4482. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  4483. {
  4484. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
  4485. ssl->state++;
  4486. return( 0 );
  4487. }
  4488. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4489. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4490. }
  4491. int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
  4492. {
  4493. const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
  4494. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
  4495. if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  4496. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  4497. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  4498. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  4499. {
  4500. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
  4501. ssl->state++;
  4502. return( 0 );
  4503. }
  4504. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4505. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4506. }
  4507. #else
  4508. /* Some certificate support -> implement write and parse */
  4509. int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
  4510. {
  4511. int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
  4512. size_t i, n;
  4513. const mbedtls_x509_crt *crt;
  4514. const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
  4515. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
  4516. if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  4517. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  4518. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  4519. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  4520. {
  4521. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
  4522. ssl->state++;
  4523. return( 0 );
  4524. }
  4525. #if defined(MBEDTLS_SSL_CLI_C)
  4526. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  4527. {
  4528. if( ssl->client_auth == 0 )
  4529. {
  4530. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
  4531. ssl->state++;
  4532. return( 0 );
  4533. }
  4534. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  4535. /*
  4536. * If using SSLv3 and got no cert, send an Alert message
  4537. * (otherwise an empty Certificate message will be sent).
  4538. */
  4539. if( mbedtls_ssl_own_cert( ssl ) == NULL &&
  4540. ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  4541. {
  4542. ssl->out_msglen = 2;
  4543. ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
  4544. ssl->out_msg[0] = MBEDTLS_SSL_ALERT_LEVEL_WARNING;
  4545. ssl->out_msg[1] = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
  4546. MBEDTLS_SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) );
  4547. goto write_msg;
  4548. }
  4549. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  4550. }
  4551. #endif /* MBEDTLS_SSL_CLI_C */
  4552. #if defined(MBEDTLS_SSL_SRV_C)
  4553. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  4554. {
  4555. if( mbedtls_ssl_own_cert( ssl ) == NULL )
  4556. {
  4557. MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) );
  4558. return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED );
  4559. }
  4560. }
  4561. #endif
  4562. MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) );
  4563. /*
  4564. * 0 . 0 handshake type
  4565. * 1 . 3 handshake length
  4566. * 4 . 6 length of all certs
  4567. * 7 . 9 length of cert. 1
  4568. * 10 . n-1 peer certificate
  4569. * n . n+2 length of cert. 2
  4570. * n+3 . ... upper level cert, etc.
  4571. */
  4572. i = 7;
  4573. crt = mbedtls_ssl_own_cert( ssl );
  4574. while( crt != NULL )
  4575. {
  4576. n = crt->raw.len;
  4577. if( n > MBEDTLS_SSL_OUT_CONTENT_LEN - 3 - i )
  4578. {
  4579. MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d",
  4580. i + 3 + n, MBEDTLS_SSL_OUT_CONTENT_LEN ) );
  4581. return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE );
  4582. }
  4583. ssl->out_msg[i ] = (unsigned char)( n >> 16 );
  4584. ssl->out_msg[i + 1] = (unsigned char)( n >> 8 );
  4585. ssl->out_msg[i + 2] = (unsigned char)( n );
  4586. i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n );
  4587. i += n; crt = crt->next;
  4588. }
  4589. ssl->out_msg[4] = (unsigned char)( ( i - 7 ) >> 16 );
  4590. ssl->out_msg[5] = (unsigned char)( ( i - 7 ) >> 8 );
  4591. ssl->out_msg[6] = (unsigned char)( ( i - 7 ) );
  4592. ssl->out_msglen = i;
  4593. ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  4594. ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE;
  4595. #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
  4596. write_msg:
  4597. #endif
  4598. ssl->state++;
  4599. if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  4600. {
  4601. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  4602. return( ret );
  4603. }
  4604. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) );
  4605. return( ret );
  4606. }
  4607. /*
  4608. * Once the certificate message is read, parse it into a cert chain and
  4609. * perform basic checks, but leave actual verification to the caller
  4610. */
  4611. static int ssl_parse_certificate_chain( mbedtls_ssl_context *ssl )
  4612. {
  4613. int ret;
  4614. size_t i, n;
  4615. uint8_t alert;
  4616. #if defined(MBEDTLS_SSL_SRV_C)
  4617. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  4618. /*
  4619. * Check if the client sent an empty certificate
  4620. */
  4621. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  4622. ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  4623. {
  4624. if( ssl->in_msglen == 2 &&
  4625. ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT &&
  4626. ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
  4627. ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
  4628. {
  4629. MBEDTLS_SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
  4630. /* The client was asked for a certificate but didn't send
  4631. one. The client should know what's going on, so we
  4632. don't send an alert. */
  4633. ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
  4634. return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
  4635. }
  4636. }
  4637. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  4638. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  4639. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  4640. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  4641. ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
  4642. {
  4643. if( ssl->in_hslen == 3 + mbedtls_ssl_hs_hdr_len( ssl ) &&
  4644. ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  4645. ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE &&
  4646. memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 )
  4647. {
  4648. MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
  4649. /* The client was asked for a certificate but didn't send
  4650. one. The client should know what's going on, so we
  4651. don't send an alert. */
  4652. ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
  4653. return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
  4654. }
  4655. }
  4656. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
  4657. MBEDTLS_SSL_PROTO_TLS1_2 */
  4658. #endif /* MBEDTLS_SSL_SRV_C */
  4659. if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
  4660. {
  4661. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  4662. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4663. MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  4664. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  4665. }
  4666. if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE ||
  4667. ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 )
  4668. {
  4669. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  4670. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4671. MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  4672. return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  4673. }
  4674. i = mbedtls_ssl_hs_hdr_len( ssl );
  4675. /*
  4676. * Same message structure as in mbedtls_ssl_write_certificate()
  4677. */
  4678. n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2];
  4679. if( ssl->in_msg[i] != 0 ||
  4680. ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) )
  4681. {
  4682. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  4683. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4684. MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  4685. return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  4686. }
  4687. /* In case we tried to reuse a session but it failed */
  4688. if( ssl->session_negotiate->peer_cert != NULL )
  4689. {
  4690. mbedtls_x509_crt_free( ssl->session_negotiate->peer_cert );
  4691. mbedtls_free( ssl->session_negotiate->peer_cert );
  4692. }
  4693. if( ( ssl->session_negotiate->peer_cert = mbedtls_calloc( 1,
  4694. sizeof( mbedtls_x509_crt ) ) ) == NULL )
  4695. {
  4696. MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
  4697. sizeof( mbedtls_x509_crt ) ) );
  4698. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4699. MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
  4700. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  4701. }
  4702. mbedtls_x509_crt_init( ssl->session_negotiate->peer_cert );
  4703. i += 3;
  4704. while( i < ssl->in_hslen )
  4705. {
  4706. if ( i + 3 > ssl->in_hslen ) {
  4707. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  4708. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4709. MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  4710. return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  4711. }
  4712. if( ssl->in_msg[i] != 0 )
  4713. {
  4714. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  4715. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4716. MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  4717. return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  4718. }
  4719. n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
  4720. | (unsigned int) ssl->in_msg[i + 2];
  4721. i += 3;
  4722. if( n < 128 || i + n > ssl->in_hslen )
  4723. {
  4724. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  4725. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4726. MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  4727. return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  4728. }
  4729. ret = mbedtls_x509_crt_parse_der( ssl->session_negotiate->peer_cert,
  4730. ssl->in_msg + i, n );
  4731. switch( ret )
  4732. {
  4733. case 0: /*ok*/
  4734. case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND:
  4735. /* Ignore certificate with an unknown algorithm: maybe a
  4736. prior certificate was already trusted. */
  4737. break;
  4738. case MBEDTLS_ERR_X509_ALLOC_FAILED:
  4739. alert = MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR;
  4740. goto crt_parse_der_failed;
  4741. case MBEDTLS_ERR_X509_UNKNOWN_VERSION:
  4742. alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  4743. goto crt_parse_der_failed;
  4744. default:
  4745. alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
  4746. crt_parse_der_failed:
  4747. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert );
  4748. MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret );
  4749. return( ret );
  4750. }
  4751. i += n;
  4752. }
  4753. MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert );
  4754. /*
  4755. * On client, make sure the server cert doesn't change during renego to
  4756. * avoid "triple handshake" attack: https://secure-resumption.com/
  4757. */
  4758. #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
  4759. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
  4760. ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
  4761. {
  4762. if( ssl->session->peer_cert == NULL )
  4763. {
  4764. MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) );
  4765. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4766. MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
  4767. return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  4768. }
  4769. if( ssl->session->peer_cert->raw.len !=
  4770. ssl->session_negotiate->peer_cert->raw.len ||
  4771. memcmp( ssl->session->peer_cert->raw.p,
  4772. ssl->session_negotiate->peer_cert->raw.p,
  4773. ssl->session->peer_cert->raw.len ) != 0 )
  4774. {
  4775. MBEDTLS_SSL_DEBUG_MSG( 1, ( "server cert changed during renegotiation" ) );
  4776. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4777. MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
  4778. return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  4779. }
  4780. }
  4781. #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
  4782. return( 0 );
  4783. }
  4784. int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
  4785. {
  4786. int ret;
  4787. const mbedtls_ssl_ciphersuite_t * const ciphersuite_info =
  4788. ssl->transform_negotiate->ciphersuite_info;
  4789. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  4790. const int authmode = ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET
  4791. ? ssl->handshake->sni_authmode
  4792. : ssl->conf->authmode;
  4793. #else
  4794. const int authmode = ssl->conf->authmode;
  4795. #endif
  4796. void *rs_ctx = NULL;
  4797. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
  4798. if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  4799. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  4800. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  4801. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  4802. {
  4803. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
  4804. ssl->state++;
  4805. return( 0 );
  4806. }
  4807. #if defined(MBEDTLS_SSL_SRV_C)
  4808. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  4809. ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
  4810. {
  4811. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
  4812. ssl->state++;
  4813. return( 0 );
  4814. }
  4815. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  4816. authmode == MBEDTLS_SSL_VERIFY_NONE )
  4817. {
  4818. ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY;
  4819. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
  4820. ssl->state++;
  4821. return( 0 );
  4822. }
  4823. #endif
  4824. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  4825. if( ssl->handshake->ecrs_enabled &&
  4826. ssl->handshake->ecrs_state == ssl_ecrs_crt_verify )
  4827. {
  4828. goto crt_verify;
  4829. }
  4830. #endif
  4831. if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  4832. {
  4833. /* mbedtls_ssl_read_record may have sent an alert already. We
  4834. let it decide whether to alert. */
  4835. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  4836. return( ret );
  4837. }
  4838. if( ( ret = ssl_parse_certificate_chain( ssl ) ) != 0 )
  4839. {
  4840. #if defined(MBEDTLS_SSL_SRV_C)
  4841. if( ret == MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE &&
  4842. authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
  4843. {
  4844. ret = 0;
  4845. }
  4846. #endif
  4847. ssl->state++;
  4848. return( ret );
  4849. }
  4850. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  4851. if( ssl->handshake->ecrs_enabled)
  4852. ssl->handshake->ecrs_state = ssl_ecrs_crt_verify;
  4853. crt_verify:
  4854. if( ssl->handshake->ecrs_enabled)
  4855. rs_ctx = &ssl->handshake->ecrs_ctx;
  4856. #endif
  4857. if( authmode != MBEDTLS_SSL_VERIFY_NONE )
  4858. {
  4859. mbedtls_x509_crt *ca_chain;
  4860. mbedtls_x509_crl *ca_crl;
  4861. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  4862. if( ssl->handshake->sni_ca_chain != NULL )
  4863. {
  4864. ca_chain = ssl->handshake->sni_ca_chain;
  4865. ca_crl = ssl->handshake->sni_ca_crl;
  4866. }
  4867. else
  4868. #endif
  4869. {
  4870. ca_chain = ssl->conf->ca_chain;
  4871. ca_crl = ssl->conf->ca_crl;
  4872. }
  4873. /*
  4874. * Main check: verify certificate
  4875. */
  4876. ret = mbedtls_x509_crt_verify_restartable(
  4877. ssl->session_negotiate->peer_cert,
  4878. ca_chain, ca_crl,
  4879. ssl->conf->cert_profile,
  4880. ssl->hostname,
  4881. &ssl->session_negotiate->verify_result,
  4882. ssl->conf->f_vrfy, ssl->conf->p_vrfy, rs_ctx );
  4883. if( ret != 0 )
  4884. {
  4885. MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
  4886. }
  4887. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  4888. if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
  4889. return( MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS );
  4890. #endif
  4891. /*
  4892. * Secondary checks: always done, but change 'ret' only if it was 0
  4893. */
  4894. #if defined(MBEDTLS_ECP_C)
  4895. {
  4896. const mbedtls_pk_context *pk = &ssl->session_negotiate->peer_cert->pk;
  4897. /* If certificate uses an EC key, make sure the curve is OK */
  4898. if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) &&
  4899. mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp.id ) != 0 )
  4900. {
  4901. ssl->session_negotiate->verify_result |= MBEDTLS_X509_BADCERT_BAD_KEY;
  4902. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) );
  4903. if( ret == 0 )
  4904. ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
  4905. }
  4906. }
  4907. #endif /* MBEDTLS_ECP_C */
  4908. if( mbedtls_ssl_check_cert_usage( ssl->session_negotiate->peer_cert,
  4909. ciphersuite_info,
  4910. ! ssl->conf->endpoint,
  4911. &ssl->session_negotiate->verify_result ) != 0 )
  4912. {
  4913. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) );
  4914. if( ret == 0 )
  4915. ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
  4916. }
  4917. /* mbedtls_x509_crt_verify_with_profile is supposed to report a
  4918. * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED,
  4919. * with details encoded in the verification flags. All other kinds
  4920. * of error codes, including those from the user provided f_vrfy
  4921. * functions, are treated as fatal and lead to a failure of
  4922. * ssl_parse_certificate even if verification was optional. */
  4923. if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL &&
  4924. ( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ||
  4925. ret == MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ) )
  4926. {
  4927. ret = 0;
  4928. }
  4929. if( ca_chain == NULL && authmode == MBEDTLS_SSL_VERIFY_REQUIRED )
  4930. {
  4931. MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
  4932. ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED;
  4933. }
  4934. if( ret != 0 )
  4935. {
  4936. uint8_t alert;
  4937. /* The certificate may have been rejected for several reasons.
  4938. Pick one and send the corresponding alert. Which alert to send
  4939. may be a subject of debate in some cases. */
  4940. if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_OTHER )
  4941. alert = MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED;
  4942. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH )
  4943. alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
  4944. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_KEY_USAGE )
  4945. alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  4946. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXT_KEY_USAGE )
  4947. alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  4948. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NS_CERT_TYPE )
  4949. alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  4950. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_PK )
  4951. alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  4952. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_KEY )
  4953. alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  4954. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXPIRED )
  4955. alert = MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED;
  4956. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_REVOKED )
  4957. alert = MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED;
  4958. else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED )
  4959. alert = MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA;
  4960. else
  4961. alert = MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN;
  4962. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4963. alert );
  4964. }
  4965. #if defined(MBEDTLS_DEBUG_C)
  4966. if( ssl->session_negotiate->verify_result != 0 )
  4967. {
  4968. MBEDTLS_SSL_DEBUG_MSG( 3, ( "! Certificate verification flags %x",
  4969. ssl->session_negotiate->verify_result ) );
  4970. }
  4971. else
  4972. {
  4973. MBEDTLS_SSL_DEBUG_MSG( 3, ( "Certificate verification flags clear" ) );
  4974. }
  4975. #endif /* MBEDTLS_DEBUG_C */
  4976. }
  4977. ssl->state++;
  4978. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
  4979. return( ret );
  4980. }
  4981. #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
  4982. !MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED
  4983. !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
  4984. !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
  4985. !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
  4986. !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED
  4987. !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
  4988. int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl )
  4989. {
  4990. int ret;
  4991. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) );
  4992. ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
  4993. ssl->out_msglen = 1;
  4994. ssl->out_msg[0] = 1;
  4995. ssl->state++;
  4996. if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  4997. {
  4998. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  4999. return( ret );
  5000. }
  5001. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) );
  5002. return( 0 );
  5003. }
  5004. int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl )
  5005. {
  5006. int ret;
  5007. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) );
  5008. if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  5009. {
  5010. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  5011. return( ret );
  5012. }
  5013. if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
  5014. {
  5015. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
  5016. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5017. MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  5018. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  5019. }
  5020. /* CCS records are only accepted if they have length 1 and content '1',
  5021. * so we don't need to check this here. */
  5022. /*
  5023. * Switch to our negotiated transform and session parameters for inbound
  5024. * data.
  5025. */
  5026. MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) );
  5027. ssl->transform_in = ssl->transform_negotiate;
  5028. ssl->session_in = ssl->session_negotiate;
  5029. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5030. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5031. {
  5032. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  5033. ssl_dtls_replay_reset( ssl );
  5034. #endif
  5035. /* Increment epoch */
  5036. if( ++ssl->in_epoch == 0 )
  5037. {
  5038. MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
  5039. /* This is highly unlikely to happen for legitimate reasons, so
  5040. treat it as an attack and don't send an alert. */
  5041. return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
  5042. }
  5043. }
  5044. else
  5045. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  5046. memset( ssl->in_ctr, 0, 8 );
  5047. ssl_update_in_pointers( ssl, ssl->transform_negotiate );
  5048. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  5049. if( mbedtls_ssl_hw_record_activate != NULL )
  5050. {
  5051. if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 )
  5052. {
  5053. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
  5054. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5055. MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
  5056. return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  5057. }
  5058. }
  5059. #endif
  5060. ssl->state++;
  5061. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) );
  5062. return( 0 );
  5063. }
  5064. void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,
  5065. const mbedtls_ssl_ciphersuite_t *ciphersuite_info )
  5066. {
  5067. ((void) ciphersuite_info);
  5068. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  5069. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  5070. if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
  5071. ssl->handshake->update_checksum = ssl_update_checksum_md5sha1;
  5072. else
  5073. #endif
  5074. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  5075. #if defined(MBEDTLS_SHA512_C)
  5076. if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
  5077. ssl->handshake->update_checksum = ssl_update_checksum_sha384;
  5078. else
  5079. #endif
  5080. #if defined(MBEDTLS_SHA256_C)
  5081. if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 )
  5082. ssl->handshake->update_checksum = ssl_update_checksum_sha256;
  5083. else
  5084. #endif
  5085. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  5086. {
  5087. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  5088. return;
  5089. }
  5090. }
  5091. void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl )
  5092. {
  5093. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  5094. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  5095. mbedtls_md5_starts_ret( &ssl->handshake->fin_md5 );
  5096. mbedtls_sha1_starts_ret( &ssl->handshake->fin_sha1 );
  5097. #endif
  5098. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  5099. #if defined(MBEDTLS_SHA256_C)
  5100. mbedtls_sha256_starts_ret( &ssl->handshake->fin_sha256, 0 );
  5101. #endif
  5102. #if defined(MBEDTLS_SHA512_C)
  5103. mbedtls_sha512_starts_ret( &ssl->handshake->fin_sha512, 1 );
  5104. #endif
  5105. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  5106. }
  5107. static void ssl_update_checksum_start( mbedtls_ssl_context *ssl,
  5108. const unsigned char *buf, size_t len )
  5109. {
  5110. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  5111. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  5112. mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );
  5113. mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );
  5114. #endif
  5115. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  5116. #if defined(MBEDTLS_SHA256_C)
  5117. mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );
  5118. #endif
  5119. #if defined(MBEDTLS_SHA512_C)
  5120. mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );
  5121. #endif
  5122. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  5123. }
  5124. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  5125. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  5126. static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl,
  5127. const unsigned char *buf, size_t len )
  5128. {
  5129. mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );
  5130. mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );
  5131. }
  5132. #endif
  5133. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  5134. #if defined(MBEDTLS_SHA256_C)
  5135. static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl,
  5136. const unsigned char *buf, size_t len )
  5137. {
  5138. mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );
  5139. }
  5140. #endif
  5141. #if defined(MBEDTLS_SHA512_C)
  5142. static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl,
  5143. const unsigned char *buf, size_t len )
  5144. {
  5145. mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );
  5146. }
  5147. #endif
  5148. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  5149. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  5150. static void ssl_calc_finished_ssl(
  5151. mbedtls_ssl_context *ssl, unsigned char *buf, int from )
  5152. {
  5153. const char *sender;
  5154. mbedtls_md5_context md5;
  5155. mbedtls_sha1_context sha1;
  5156. unsigned char padbuf[48];
  5157. unsigned char md5sum[16];
  5158. unsigned char sha1sum[20];
  5159. mbedtls_ssl_session *session = ssl->session_negotiate;
  5160. if( !session )
  5161. session = ssl->session;
  5162. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished ssl" ) );
  5163. mbedtls_md5_init( &md5 );
  5164. mbedtls_sha1_init( &sha1 );
  5165. mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
  5166. mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
  5167. /*
  5168. * SSLv3:
  5169. * hash =
  5170. * MD5( master + pad2 +
  5171. * MD5( handshake + sender + master + pad1 ) )
  5172. * + SHA1( master + pad2 +
  5173. * SHA1( handshake + sender + master + pad1 ) )
  5174. */
  5175. #if !defined(MBEDTLS_MD5_ALT)
  5176. MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *)
  5177. md5.state, sizeof( md5.state ) );
  5178. #endif
  5179. #if !defined(MBEDTLS_SHA1_ALT)
  5180. MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
  5181. sha1.state, sizeof( sha1.state ) );
  5182. #endif
  5183. sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "CLNT"
  5184. : "SRVR";
  5185. memset( padbuf, 0x36, 48 );
  5186. mbedtls_md5_update_ret( &md5, (const unsigned char *) sender, 4 );
  5187. mbedtls_md5_update_ret( &md5, session->master, 48 );
  5188. mbedtls_md5_update_ret( &md5, padbuf, 48 );
  5189. mbedtls_md5_finish_ret( &md5, md5sum );
  5190. mbedtls_sha1_update_ret( &sha1, (const unsigned char *) sender, 4 );
  5191. mbedtls_sha1_update_ret( &sha1, session->master, 48 );
  5192. mbedtls_sha1_update_ret( &sha1, padbuf, 40 );
  5193. mbedtls_sha1_finish_ret( &sha1, sha1sum );
  5194. memset( padbuf, 0x5C, 48 );
  5195. mbedtls_md5_starts_ret( &md5 );
  5196. mbedtls_md5_update_ret( &md5, session->master, 48 );
  5197. mbedtls_md5_update_ret( &md5, padbuf, 48 );
  5198. mbedtls_md5_update_ret( &md5, md5sum, 16 );
  5199. mbedtls_md5_finish_ret( &md5, buf );
  5200. mbedtls_sha1_starts_ret( &sha1 );
  5201. mbedtls_sha1_update_ret( &sha1, session->master, 48 );
  5202. mbedtls_sha1_update_ret( &sha1, padbuf , 40 );
  5203. mbedtls_sha1_update_ret( &sha1, sha1sum, 20 );
  5204. mbedtls_sha1_finish_ret( &sha1, buf + 16 );
  5205. MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 );
  5206. mbedtls_md5_free( &md5 );
  5207. mbedtls_sha1_free( &sha1 );
  5208. mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) );
  5209. mbedtls_platform_zeroize( md5sum, sizeof( md5sum ) );
  5210. mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );
  5211. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
  5212. }
  5213. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  5214. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  5215. static void ssl_calc_finished_tls(
  5216. mbedtls_ssl_context *ssl, unsigned char *buf, int from )
  5217. {
  5218. int len = 12;
  5219. const char *sender;
  5220. mbedtls_md5_context md5;
  5221. mbedtls_sha1_context sha1;
  5222. unsigned char padbuf[36];
  5223. mbedtls_ssl_session *session = ssl->session_negotiate;
  5224. if( !session )
  5225. session = ssl->session;
  5226. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls" ) );
  5227. mbedtls_md5_init( &md5 );
  5228. mbedtls_sha1_init( &sha1 );
  5229. mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
  5230. mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
  5231. /*
  5232. * TLSv1:
  5233. * hash = PRF( master, finished_label,
  5234. * MD5( handshake ) + SHA1( handshake ) )[0..11]
  5235. */
  5236. #if !defined(MBEDTLS_MD5_ALT)
  5237. MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *)
  5238. md5.state, sizeof( md5.state ) );
  5239. #endif
  5240. #if !defined(MBEDTLS_SHA1_ALT)
  5241. MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
  5242. sha1.state, sizeof( sha1.state ) );
  5243. #endif
  5244. sender = ( from == MBEDTLS_SSL_IS_CLIENT )
  5245. ? "client finished"
  5246. : "server finished";
  5247. mbedtls_md5_finish_ret( &md5, padbuf );
  5248. mbedtls_sha1_finish_ret( &sha1, padbuf + 16 );
  5249. ssl->handshake->tls_prf( session->master, 48, sender,
  5250. padbuf, 36, buf, len );
  5251. MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
  5252. mbedtls_md5_free( &md5 );
  5253. mbedtls_sha1_free( &sha1 );
  5254. mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) );
  5255. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
  5256. }
  5257. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
  5258. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  5259. #if defined(MBEDTLS_SHA256_C)
  5260. static void ssl_calc_finished_tls_sha256(
  5261. mbedtls_ssl_context *ssl, unsigned char *buf, int from )
  5262. {
  5263. int len = 12;
  5264. const char *sender;
  5265. mbedtls_sha256_context sha256;
  5266. unsigned char padbuf[32];
  5267. mbedtls_ssl_session *session = ssl->session_negotiate;
  5268. if( !session )
  5269. session = ssl->session;
  5270. mbedtls_sha256_init( &sha256 );
  5271. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha256" ) );
  5272. mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
  5273. /*
  5274. * TLSv1.2:
  5275. * hash = PRF( master, finished_label,
  5276. * Hash( handshake ) )[0.11]
  5277. */
  5278. #if !defined(MBEDTLS_SHA256_ALT)
  5279. MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *)
  5280. sha256.state, sizeof( sha256.state ) );
  5281. #endif
  5282. sender = ( from == MBEDTLS_SSL_IS_CLIENT )
  5283. ? "client finished"
  5284. : "server finished";
  5285. mbedtls_sha256_finish_ret( &sha256, padbuf );
  5286. ssl->handshake->tls_prf( session->master, 48, sender,
  5287. padbuf, 32, buf, len );
  5288. MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
  5289. mbedtls_sha256_free( &sha256 );
  5290. mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) );
  5291. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
  5292. }
  5293. #endif /* MBEDTLS_SHA256_C */
  5294. #if defined(MBEDTLS_SHA512_C)
  5295. static void ssl_calc_finished_tls_sha384(
  5296. mbedtls_ssl_context *ssl, unsigned char *buf, int from )
  5297. {
  5298. int len = 12;
  5299. const char *sender;
  5300. mbedtls_sha512_context sha512;
  5301. unsigned char padbuf[48];
  5302. mbedtls_ssl_session *session = ssl->session_negotiate;
  5303. if( !session )
  5304. session = ssl->session;
  5305. mbedtls_sha512_init( &sha512 );
  5306. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha384" ) );
  5307. mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
  5308. /*
  5309. * TLSv1.2:
  5310. * hash = PRF( master, finished_label,
  5311. * Hash( handshake ) )[0.11]
  5312. */
  5313. #if !defined(MBEDTLS_SHA512_ALT)
  5314. MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *)
  5315. sha512.state, sizeof( sha512.state ) );
  5316. #endif
  5317. sender = ( from == MBEDTLS_SSL_IS_CLIENT )
  5318. ? "client finished"
  5319. : "server finished";
  5320. mbedtls_sha512_finish_ret( &sha512, padbuf );
  5321. ssl->handshake->tls_prf( session->master, 48, sender,
  5322. padbuf, 48, buf, len );
  5323. MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
  5324. mbedtls_sha512_free( &sha512 );
  5325. mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) );
  5326. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
  5327. }
  5328. #endif /* MBEDTLS_SHA512_C */
  5329. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  5330. static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl )
  5331. {
  5332. MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) );
  5333. /*
  5334. * Free our handshake params
  5335. */
  5336. mbedtls_ssl_handshake_free( ssl );
  5337. mbedtls_free( ssl->handshake );
  5338. ssl->handshake = NULL;
  5339. /*
  5340. * Free the previous transform and swith in the current one
  5341. */
  5342. if( ssl->transform )
  5343. {
  5344. mbedtls_ssl_transform_free( ssl->transform );
  5345. mbedtls_free( ssl->transform );
  5346. }
  5347. ssl->transform = ssl->transform_negotiate;
  5348. ssl->transform_negotiate = NULL;
  5349. MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) );
  5350. }
  5351. void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl )
  5352. {
  5353. int resume = ssl->handshake->resume;
  5354. MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) );
  5355. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  5356. if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
  5357. {
  5358. ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_DONE;
  5359. ssl->renego_records_seen = 0;
  5360. }
  5361. #endif
  5362. /*
  5363. * Free the previous session and switch in the current one
  5364. */
  5365. if( ssl->session )
  5366. {
  5367. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  5368. /* RFC 7366 3.1: keep the EtM state */
  5369. ssl->session_negotiate->encrypt_then_mac =
  5370. ssl->session->encrypt_then_mac;
  5371. #endif
  5372. mbedtls_ssl_session_free( ssl->session );
  5373. mbedtls_free( ssl->session );
  5374. }
  5375. ssl->session = ssl->session_negotiate;
  5376. ssl->session_negotiate = NULL;
  5377. /*
  5378. * Add cache entry
  5379. */
  5380. if( ssl->conf->f_set_cache != NULL &&
  5381. ssl->session->id_len != 0 &&
  5382. resume == 0 )
  5383. {
  5384. if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 )
  5385. MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) );
  5386. }
  5387. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5388. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  5389. ssl->handshake->flight != NULL )
  5390. {
  5391. /* Cancel handshake timer */
  5392. ssl_set_timer( ssl, 0 );
  5393. /* Keep last flight around in case we need to resend it:
  5394. * we need the handshake and transform structures for that */
  5395. MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) );
  5396. }
  5397. else
  5398. #endif
  5399. ssl_handshake_wrapup_free_hs_transform( ssl );
  5400. ssl->state++;
  5401. MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) );
  5402. }
  5403. int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl )
  5404. {
  5405. int ret, hash_len;
  5406. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) );
  5407. ssl_update_out_pointers( ssl, ssl->transform_negotiate );
  5408. ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint );
  5409. /*
  5410. * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites
  5411. * may define some other value. Currently (early 2016), no defined
  5412. * ciphersuite does this (and this is unlikely to change as activity has
  5413. * moved to TLS 1.3 now) so we can keep the hardcoded 12 here.
  5414. */
  5415. hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12;
  5416. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  5417. ssl->verify_data_len = hash_len;
  5418. memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len );
  5419. #endif
  5420. ssl->out_msglen = 4 + hash_len;
  5421. ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  5422. ssl->out_msg[0] = MBEDTLS_SSL_HS_FINISHED;
  5423. /*
  5424. * In case of session resuming, invert the client and server
  5425. * ChangeCipherSpec messages order.
  5426. */
  5427. if( ssl->handshake->resume != 0 )
  5428. {
  5429. #if defined(MBEDTLS_SSL_CLI_C)
  5430. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  5431. ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
  5432. #endif
  5433. #if defined(MBEDTLS_SSL_SRV_C)
  5434. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  5435. ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
  5436. #endif
  5437. }
  5438. else
  5439. ssl->state++;
  5440. /*
  5441. * Switch to our negotiated transform and session parameters for outbound
  5442. * data.
  5443. */
  5444. MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) );
  5445. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5446. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5447. {
  5448. unsigned char i;
  5449. /* Remember current epoch settings for resending */
  5450. ssl->handshake->alt_transform_out = ssl->transform_out;
  5451. memcpy( ssl->handshake->alt_out_ctr, ssl->cur_out_ctr, 8 );
  5452. /* Set sequence_number to zero */
  5453. memset( ssl->cur_out_ctr + 2, 0, 6 );
  5454. /* Increment epoch */
  5455. for( i = 2; i > 0; i-- )
  5456. if( ++ssl->cur_out_ctr[i - 1] != 0 )
  5457. break;
  5458. /* The loop goes to its end iff the counter is wrapping */
  5459. if( i == 0 )
  5460. {
  5461. MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
  5462. return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
  5463. }
  5464. }
  5465. else
  5466. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  5467. memset( ssl->cur_out_ctr, 0, 8 );
  5468. ssl->transform_out = ssl->transform_negotiate;
  5469. ssl->session_out = ssl->session_negotiate;
  5470. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  5471. if( mbedtls_ssl_hw_record_activate != NULL )
  5472. {
  5473. if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
  5474. {
  5475. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
  5476. return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  5477. }
  5478. }
  5479. #endif
  5480. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5481. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5482. mbedtls_ssl_send_flight_completed( ssl );
  5483. #endif
  5484. if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  5485. {
  5486. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  5487. return( ret );
  5488. }
  5489. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5490. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  5491. ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
  5492. {
  5493. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
  5494. return( ret );
  5495. }
  5496. #endif
  5497. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) );
  5498. return( 0 );
  5499. }
  5500. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  5501. #define SSL_MAX_HASH_LEN 36
  5502. #else
  5503. #define SSL_MAX_HASH_LEN 12
  5504. #endif
  5505. int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl )
  5506. {
  5507. int ret;
  5508. unsigned int hash_len;
  5509. unsigned char buf[SSL_MAX_HASH_LEN];
  5510. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) );
  5511. ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 );
  5512. if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  5513. {
  5514. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  5515. return( ret );
  5516. }
  5517. if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
  5518. {
  5519. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
  5520. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5521. MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  5522. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  5523. }
  5524. /* There is currently no ciphersuite using another length with TLS 1.2 */
  5525. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  5526. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  5527. hash_len = 36;
  5528. else
  5529. #endif
  5530. hash_len = 12;
  5531. if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED ||
  5532. ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len )
  5533. {
  5534. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
  5535. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5536. MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  5537. return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
  5538. }
  5539. if( mbedtls_ssl_safer_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ),
  5540. buf, hash_len ) != 0 )
  5541. {
  5542. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
  5543. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5544. MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  5545. return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
  5546. }
  5547. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  5548. ssl->verify_data_len = hash_len;
  5549. memcpy( ssl->peer_verify_data, buf, hash_len );
  5550. #endif
  5551. if( ssl->handshake->resume != 0 )
  5552. {
  5553. #if defined(MBEDTLS_SSL_CLI_C)
  5554. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  5555. ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
  5556. #endif
  5557. #if defined(MBEDTLS_SSL_SRV_C)
  5558. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  5559. ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
  5560. #endif
  5561. }
  5562. else
  5563. ssl->state++;
  5564. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5565. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5566. mbedtls_ssl_recv_flight_completed( ssl );
  5567. #endif
  5568. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) );
  5569. return( 0 );
  5570. }
  5571. static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake )
  5572. {
  5573. memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) );
  5574. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  5575. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  5576. mbedtls_md5_init( &handshake->fin_md5 );
  5577. mbedtls_sha1_init( &handshake->fin_sha1 );
  5578. mbedtls_md5_starts_ret( &handshake->fin_md5 );
  5579. mbedtls_sha1_starts_ret( &handshake->fin_sha1 );
  5580. #endif
  5581. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  5582. #if defined(MBEDTLS_SHA256_C)
  5583. mbedtls_sha256_init( &handshake->fin_sha256 );
  5584. mbedtls_sha256_starts_ret( &handshake->fin_sha256, 0 );
  5585. #endif
  5586. #if defined(MBEDTLS_SHA512_C)
  5587. mbedtls_sha512_init( &handshake->fin_sha512 );
  5588. mbedtls_sha512_starts_ret( &handshake->fin_sha512, 1 );
  5589. #endif
  5590. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  5591. handshake->update_checksum = ssl_update_checksum_start;
  5592. #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
  5593. defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  5594. mbedtls_ssl_sig_hash_set_init( &handshake->hash_algs );
  5595. #endif
  5596. #if defined(MBEDTLS_DHM_C)
  5597. mbedtls_dhm_init( &handshake->dhm_ctx );
  5598. #endif
  5599. #if defined(MBEDTLS_ECDH_C)
  5600. mbedtls_ecdh_init( &handshake->ecdh_ctx );
  5601. #endif
  5602. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  5603. mbedtls_ecjpake_init( &handshake->ecjpake_ctx );
  5604. #if defined(MBEDTLS_SSL_CLI_C)
  5605. handshake->ecjpake_cache = NULL;
  5606. handshake->ecjpake_cache_len = 0;
  5607. #endif
  5608. #endif
  5609. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  5610. mbedtls_x509_crt_restart_init( &handshake->ecrs_ctx );
  5611. #endif
  5612. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  5613. handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET;
  5614. #endif
  5615. }
  5616. static void ssl_transform_init( mbedtls_ssl_transform *transform )
  5617. {
  5618. memset( transform, 0, sizeof(mbedtls_ssl_transform) );
  5619. mbedtls_cipher_init( &transform->cipher_ctx_enc );
  5620. mbedtls_cipher_init( &transform->cipher_ctx_dec );
  5621. mbedtls_md_init( &transform->md_ctx_enc );
  5622. mbedtls_md_init( &transform->md_ctx_dec );
  5623. }
  5624. void mbedtls_ssl_session_init( mbedtls_ssl_session *session )
  5625. {
  5626. memset( session, 0, sizeof(mbedtls_ssl_session) );
  5627. }
  5628. static int ssl_handshake_init( mbedtls_ssl_context *ssl )
  5629. {
  5630. /* Clear old handshake information if present */
  5631. if( ssl->transform_negotiate )
  5632. mbedtls_ssl_transform_free( ssl->transform_negotiate );
  5633. if( ssl->session_negotiate )
  5634. mbedtls_ssl_session_free( ssl->session_negotiate );
  5635. if( ssl->handshake )
  5636. mbedtls_ssl_handshake_free( ssl );
  5637. /*
  5638. * Either the pointers are now NULL or cleared properly and can be freed.
  5639. * Now allocate missing structures.
  5640. */
  5641. if( ssl->transform_negotiate == NULL )
  5642. {
  5643. ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) );
  5644. }
  5645. if( ssl->session_negotiate == NULL )
  5646. {
  5647. ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) );
  5648. }
  5649. if( ssl->handshake == NULL )
  5650. {
  5651. ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) );
  5652. }
  5653. /* All pointers should exist and can be directly freed without issue */
  5654. if( ssl->handshake == NULL ||
  5655. ssl->transform_negotiate == NULL ||
  5656. ssl->session_negotiate == NULL )
  5657. {
  5658. MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) );
  5659. mbedtls_free( ssl->handshake );
  5660. mbedtls_free( ssl->transform_negotiate );
  5661. mbedtls_free( ssl->session_negotiate );
  5662. ssl->handshake = NULL;
  5663. ssl->transform_negotiate = NULL;
  5664. ssl->session_negotiate = NULL;
  5665. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  5666. }
  5667. /* Initialize structures */
  5668. mbedtls_ssl_session_init( ssl->session_negotiate );
  5669. ssl_transform_init( ssl->transform_negotiate );
  5670. ssl_handshake_params_init( ssl->handshake );
  5671. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5672. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5673. {
  5674. ssl->handshake->alt_transform_out = ssl->transform_out;
  5675. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  5676. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
  5677. else
  5678. ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
  5679. ssl_set_timer( ssl, 0 );
  5680. }
  5681. #endif
  5682. return( 0 );
  5683. }
  5684. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
  5685. /* Dummy cookie callbacks for defaults */
  5686. static int ssl_cookie_write_dummy( void *ctx,
  5687. unsigned char **p, unsigned char *end,
  5688. const unsigned char *cli_id, size_t cli_id_len )
  5689. {
  5690. ((void) ctx);
  5691. ((void) p);
  5692. ((void) end);
  5693. ((void) cli_id);
  5694. ((void) cli_id_len);
  5695. return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  5696. }
  5697. static int ssl_cookie_check_dummy( void *ctx,
  5698. const unsigned char *cookie, size_t cookie_len,
  5699. const unsigned char *cli_id, size_t cli_id_len )
  5700. {
  5701. ((void) ctx);
  5702. ((void) cookie);
  5703. ((void) cookie_len);
  5704. ((void) cli_id);
  5705. ((void) cli_id_len);
  5706. return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  5707. }
  5708. #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
  5709. /* Once ssl->out_hdr as the address of the beginning of the
  5710. * next outgoing record is set, deduce the other pointers.
  5711. *
  5712. * Note: For TLS, we save the implicit record sequence number
  5713. * (entering MAC computation) in the 8 bytes before ssl->out_hdr,
  5714. * and the caller has to make sure there's space for this.
  5715. */
  5716. static void ssl_update_out_pointers( mbedtls_ssl_context *ssl,
  5717. mbedtls_ssl_transform *transform )
  5718. {
  5719. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5720. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5721. {
  5722. ssl->out_ctr = ssl->out_hdr + 3;
  5723. ssl->out_len = ssl->out_hdr + 11;
  5724. ssl->out_iv = ssl->out_hdr + 13;
  5725. }
  5726. else
  5727. #endif
  5728. {
  5729. ssl->out_ctr = ssl->out_hdr - 8;
  5730. ssl->out_len = ssl->out_hdr + 3;
  5731. ssl->out_iv = ssl->out_hdr + 5;
  5732. }
  5733. /* Adjust out_msg to make space for explicit IV, if used. */
  5734. if( transform != NULL &&
  5735. ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  5736. {
  5737. ssl->out_msg = ssl->out_iv + transform->ivlen - transform->fixed_ivlen;
  5738. }
  5739. else
  5740. ssl->out_msg = ssl->out_iv;
  5741. }
  5742. /* Once ssl->in_hdr as the address of the beginning of the
  5743. * next incoming record is set, deduce the other pointers.
  5744. *
  5745. * Note: For TLS, we save the implicit record sequence number
  5746. * (entering MAC computation) in the 8 bytes before ssl->in_hdr,
  5747. * and the caller has to make sure there's space for this.
  5748. */
  5749. static void ssl_update_in_pointers( mbedtls_ssl_context *ssl,
  5750. mbedtls_ssl_transform *transform )
  5751. {
  5752. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5753. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5754. {
  5755. ssl->in_ctr = ssl->in_hdr + 3;
  5756. ssl->in_len = ssl->in_hdr + 11;
  5757. ssl->in_iv = ssl->in_hdr + 13;
  5758. }
  5759. else
  5760. #endif
  5761. {
  5762. ssl->in_ctr = ssl->in_hdr - 8;
  5763. ssl->in_len = ssl->in_hdr + 3;
  5764. ssl->in_iv = ssl->in_hdr + 5;
  5765. }
  5766. /* Offset in_msg from in_iv to allow space for explicit IV, if used. */
  5767. if( transform != NULL &&
  5768. ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  5769. {
  5770. ssl->in_msg = ssl->in_iv + transform->ivlen - transform->fixed_ivlen;
  5771. }
  5772. else
  5773. ssl->in_msg = ssl->in_iv;
  5774. }
  5775. /*
  5776. * Initialize an SSL context
  5777. */
  5778. void mbedtls_ssl_init( mbedtls_ssl_context *ssl )
  5779. {
  5780. memset( ssl, 0, sizeof( mbedtls_ssl_context ) );
  5781. }
  5782. /*
  5783. * Setup an SSL context
  5784. */
  5785. static void ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl )
  5786. {
  5787. /* Set the incoming and outgoing record pointers. */
  5788. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5789. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5790. {
  5791. ssl->out_hdr = ssl->out_buf;
  5792. ssl->in_hdr = ssl->in_buf;
  5793. }
  5794. else
  5795. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  5796. {
  5797. ssl->out_hdr = ssl->out_buf + 8;
  5798. ssl->in_hdr = ssl->in_buf + 8;
  5799. }
  5800. /* Derive other internal pointers. */
  5801. ssl_update_out_pointers( ssl, NULL /* no transform enabled */ );
  5802. ssl_update_in_pointers ( ssl, NULL /* no transform enabled */ );
  5803. }
  5804. int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
  5805. const mbedtls_ssl_config *conf )
  5806. {
  5807. int ret;
  5808. ssl->conf = conf;
  5809. /*
  5810. * Prepare base structures
  5811. */
  5812. /* Set to NULL in case of an error condition */
  5813. ssl->out_buf = NULL;
  5814. ssl->in_buf = mbedtls_calloc( 1, MBEDTLS_SSL_IN_BUFFER_LEN );
  5815. if( ssl->in_buf == NULL )
  5816. {
  5817. MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_IN_BUFFER_LEN) );
  5818. ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
  5819. goto error;
  5820. }
  5821. ssl->out_buf = mbedtls_calloc( 1, MBEDTLS_SSL_OUT_BUFFER_LEN );
  5822. if( ssl->out_buf == NULL )
  5823. {
  5824. MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_OUT_BUFFER_LEN) );
  5825. ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
  5826. goto error;
  5827. }
  5828. ssl_reset_in_out_pointers( ssl );
  5829. if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
  5830. goto error;
  5831. return( 0 );
  5832. error:
  5833. mbedtls_free( ssl->in_buf );
  5834. mbedtls_free( ssl->out_buf );
  5835. ssl->conf = NULL;
  5836. ssl->in_buf = NULL;
  5837. ssl->out_buf = NULL;
  5838. ssl->in_hdr = NULL;
  5839. ssl->in_ctr = NULL;
  5840. ssl->in_len = NULL;
  5841. ssl->in_iv = NULL;
  5842. ssl->in_msg = NULL;
  5843. ssl->out_hdr = NULL;
  5844. ssl->out_ctr = NULL;
  5845. ssl->out_len = NULL;
  5846. ssl->out_iv = NULL;
  5847. ssl->out_msg = NULL;
  5848. return( ret );
  5849. }
  5850. /*
  5851. * Reset an initialized and used SSL context for re-use while retaining
  5852. * all application-set variables, function pointers and data.
  5853. *
  5854. * If partial is non-zero, keep data in the input buffer and client ID.
  5855. * (Use when a DTLS client reconnects from the same port.)
  5856. */
  5857. static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial )
  5858. {
  5859. int ret;
  5860. #if !defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) || \
  5861. !defined(MBEDTLS_SSL_SRV_C)
  5862. ((void) partial);
  5863. #endif
  5864. ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
  5865. /* Cancel any possibly running timer */
  5866. ssl_set_timer( ssl, 0 );
  5867. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  5868. ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE;
  5869. ssl->renego_records_seen = 0;
  5870. ssl->verify_data_len = 0;
  5871. memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
  5872. memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
  5873. #endif
  5874. ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION;
  5875. ssl->in_offt = NULL;
  5876. ssl_reset_in_out_pointers( ssl );
  5877. ssl->in_msgtype = 0;
  5878. ssl->in_msglen = 0;
  5879. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5880. ssl->next_record_offset = 0;
  5881. ssl->in_epoch = 0;
  5882. #endif
  5883. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  5884. ssl_dtls_replay_reset( ssl );
  5885. #endif
  5886. ssl->in_hslen = 0;
  5887. ssl->nb_zero = 0;
  5888. ssl->keep_current_message = 0;
  5889. ssl->out_msgtype = 0;
  5890. ssl->out_msglen = 0;
  5891. ssl->out_left = 0;
  5892. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  5893. if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED )
  5894. ssl->split_done = 0;
  5895. #endif
  5896. memset( ssl->cur_out_ctr, 0, sizeof( ssl->cur_out_ctr ) );
  5897. ssl->transform_in = NULL;
  5898. ssl->transform_out = NULL;
  5899. ssl->session_in = NULL;
  5900. ssl->session_out = NULL;
  5901. memset( ssl->out_buf, 0, MBEDTLS_SSL_OUT_BUFFER_LEN );
  5902. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
  5903. if( partial == 0 )
  5904. #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
  5905. {
  5906. ssl->in_left = 0;
  5907. memset( ssl->in_buf, 0, MBEDTLS_SSL_IN_BUFFER_LEN );
  5908. }
  5909. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  5910. if( mbedtls_ssl_hw_record_reset != NULL )
  5911. {
  5912. MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_reset()" ) );
  5913. if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 )
  5914. {
  5915. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_reset", ret );
  5916. return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  5917. }
  5918. }
  5919. #endif
  5920. if( ssl->transform )
  5921. {
  5922. mbedtls_ssl_transform_free( ssl->transform );
  5923. mbedtls_free( ssl->transform );
  5924. ssl->transform = NULL;
  5925. }
  5926. if( ssl->session )
  5927. {
  5928. mbedtls_ssl_session_free( ssl->session );
  5929. mbedtls_free( ssl->session );
  5930. ssl->session = NULL;
  5931. }
  5932. #if defined(MBEDTLS_SSL_ALPN)
  5933. ssl->alpn_chosen = NULL;
  5934. #endif
  5935. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
  5936. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE)
  5937. if( partial == 0 )
  5938. #endif
  5939. {
  5940. mbedtls_free( ssl->cli_id );
  5941. ssl->cli_id = NULL;
  5942. ssl->cli_id_len = 0;
  5943. }
  5944. #endif
  5945. if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
  5946. return( ret );
  5947. return( 0 );
  5948. }
  5949. /*
  5950. * Reset an initialized and used SSL context for re-use while retaining
  5951. * all application-set variables, function pointers and data.
  5952. */
  5953. int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl )
  5954. {
  5955. return( ssl_session_reset_int( ssl, 0 ) );
  5956. }
  5957. /*
  5958. * SSL set accessors
  5959. */
  5960. void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint )
  5961. {
  5962. conf->endpoint = endpoint;
  5963. }
  5964. void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport )
  5965. {
  5966. conf->transport = transport;
  5967. }
  5968. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  5969. void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode )
  5970. {
  5971. conf->anti_replay = mode;
  5972. }
  5973. #endif
  5974. #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
  5975. void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit )
  5976. {
  5977. conf->badmac_limit = limit;
  5978. }
  5979. #endif
  5980. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5981. void mbedtls_ssl_set_datagram_packing( mbedtls_ssl_context *ssl,
  5982. unsigned allow_packing )
  5983. {
  5984. ssl->disable_datagram_packing = !allow_packing;
  5985. }
  5986. void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf,
  5987. uint32_t min, uint32_t max )
  5988. {
  5989. conf->hs_timeout_min = min;
  5990. conf->hs_timeout_max = max;
  5991. }
  5992. #endif
  5993. void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode )
  5994. {
  5995. conf->authmode = authmode;
  5996. }
  5997. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  5998. void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf,
  5999. int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  6000. void *p_vrfy )
  6001. {
  6002. conf->f_vrfy = f_vrfy;
  6003. conf->p_vrfy = p_vrfy;
  6004. }
  6005. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  6006. void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf,
  6007. int (*f_rng)(void *, unsigned char *, size_t),
  6008. void *p_rng )
  6009. {
  6010. conf->f_rng = f_rng;
  6011. conf->p_rng = p_rng;
  6012. }
  6013. void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,
  6014. void (*f_dbg)(void *, int, const char *, int, const char *),
  6015. void *p_dbg )
  6016. {
  6017. conf->f_dbg = f_dbg;
  6018. conf->p_dbg = p_dbg;
  6019. }
  6020. void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,
  6021. void *p_bio,
  6022. mbedtls_ssl_send_t *f_send,
  6023. mbedtls_ssl_recv_t *f_recv,
  6024. mbedtls_ssl_recv_timeout_t *f_recv_timeout )
  6025. {
  6026. ssl->p_bio = p_bio;
  6027. ssl->f_send = f_send;
  6028. ssl->f_recv = f_recv;
  6029. ssl->f_recv_timeout = f_recv_timeout;
  6030. }
  6031. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6032. void mbedtls_ssl_set_mtu( mbedtls_ssl_context *ssl, uint16_t mtu )
  6033. {
  6034. ssl->mtu = mtu;
  6035. }
  6036. #endif
  6037. void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout )
  6038. {
  6039. conf->read_timeout = timeout;
  6040. }
  6041. void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,
  6042. void *p_timer,
  6043. mbedtls_ssl_set_timer_t *f_set_timer,
  6044. mbedtls_ssl_get_timer_t *f_get_timer )
  6045. {
  6046. ssl->p_timer = p_timer;
  6047. ssl->f_set_timer = f_set_timer;
  6048. ssl->f_get_timer = f_get_timer;
  6049. /* Make sure we start with no timer running */
  6050. ssl_set_timer( ssl, 0 );
  6051. }
  6052. #if defined(MBEDTLS_SSL_SRV_C)
  6053. void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,
  6054. void *p_cache,
  6055. int (*f_get_cache)(void *, mbedtls_ssl_session *),
  6056. int (*f_set_cache)(void *, const mbedtls_ssl_session *) )
  6057. {
  6058. conf->p_cache = p_cache;
  6059. conf->f_get_cache = f_get_cache;
  6060. conf->f_set_cache = f_set_cache;
  6061. }
  6062. #endif /* MBEDTLS_SSL_SRV_C */
  6063. #if defined(MBEDTLS_SSL_CLI_C)
  6064. int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session )
  6065. {
  6066. int ret;
  6067. if( ssl == NULL ||
  6068. session == NULL ||
  6069. ssl->session_negotiate == NULL ||
  6070. ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
  6071. {
  6072. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6073. }
  6074. if( ( ret = ssl_session_copy( ssl->session_negotiate, session ) ) != 0 )
  6075. return( ret );
  6076. ssl->handshake->resume = 1;
  6077. return( 0 );
  6078. }
  6079. #endif /* MBEDTLS_SSL_CLI_C */
  6080. void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,
  6081. const int *ciphersuites )
  6082. {
  6083. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites;
  6084. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites;
  6085. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites;
  6086. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites;
  6087. }
  6088. void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,
  6089. const int *ciphersuites,
  6090. int major, int minor )
  6091. {
  6092. if( major != MBEDTLS_SSL_MAJOR_VERSION_3 )
  6093. return;
  6094. if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 )
  6095. return;
  6096. conf->ciphersuite_list[minor] = ciphersuites;
  6097. }
  6098. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  6099. void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,
  6100. const mbedtls_x509_crt_profile *profile )
  6101. {
  6102. conf->cert_profile = profile;
  6103. }
  6104. /* Append a new keycert entry to a (possibly empty) list */
  6105. static int ssl_append_key_cert( mbedtls_ssl_key_cert **head,
  6106. mbedtls_x509_crt *cert,
  6107. mbedtls_pk_context *key )
  6108. {
  6109. mbedtls_ssl_key_cert *new_cert;
  6110. new_cert = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) );
  6111. if( new_cert == NULL )
  6112. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  6113. new_cert->cert = cert;
  6114. new_cert->key = key;
  6115. new_cert->next = NULL;
  6116. /* Update head is the list was null, else add to the end */
  6117. if( *head == NULL )
  6118. {
  6119. *head = new_cert;
  6120. }
  6121. else
  6122. {
  6123. mbedtls_ssl_key_cert *cur = *head;
  6124. while( cur->next != NULL )
  6125. cur = cur->next;
  6126. cur->next = new_cert;
  6127. }
  6128. return( 0 );
  6129. }
  6130. int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
  6131. mbedtls_x509_crt *own_cert,
  6132. mbedtls_pk_context *pk_key )
  6133. {
  6134. return( ssl_append_key_cert( &conf->key_cert, own_cert, pk_key ) );
  6135. }
  6136. void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,
  6137. mbedtls_x509_crt *ca_chain,
  6138. mbedtls_x509_crl *ca_crl )
  6139. {
  6140. conf->ca_chain = ca_chain;
  6141. conf->ca_crl = ca_crl;
  6142. }
  6143. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  6144. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  6145. int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl,
  6146. mbedtls_x509_crt *own_cert,
  6147. mbedtls_pk_context *pk_key )
  6148. {
  6149. return( ssl_append_key_cert( &ssl->handshake->sni_key_cert,
  6150. own_cert, pk_key ) );
  6151. }
  6152. void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl,
  6153. mbedtls_x509_crt *ca_chain,
  6154. mbedtls_x509_crl *ca_crl )
  6155. {
  6156. ssl->handshake->sni_ca_chain = ca_chain;
  6157. ssl->handshake->sni_ca_crl = ca_crl;
  6158. }
  6159. void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl,
  6160. int authmode )
  6161. {
  6162. ssl->handshake->sni_authmode = authmode;
  6163. }
  6164. #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
  6165. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  6166. /*
  6167. * Set EC J-PAKE password for current handshake
  6168. */
  6169. int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
  6170. const unsigned char *pw,
  6171. size_t pw_len )
  6172. {
  6173. mbedtls_ecjpake_role role;
  6174. if( ssl->handshake == NULL || ssl->conf == NULL )
  6175. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6176. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  6177. role = MBEDTLS_ECJPAKE_SERVER;
  6178. else
  6179. role = MBEDTLS_ECJPAKE_CLIENT;
  6180. return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx,
  6181. role,
  6182. MBEDTLS_MD_SHA256,
  6183. MBEDTLS_ECP_DP_SECP256R1,
  6184. pw, pw_len ) );
  6185. }
  6186. #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
  6187. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
  6188. int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
  6189. const unsigned char *psk, size_t psk_len,
  6190. const unsigned char *psk_identity, size_t psk_identity_len )
  6191. {
  6192. if( psk == NULL || psk_identity == NULL )
  6193. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6194. if( psk_len > MBEDTLS_PSK_MAX_LEN )
  6195. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6196. /* Identity len will be encoded on two bytes */
  6197. if( ( psk_identity_len >> 16 ) != 0 ||
  6198. psk_identity_len > MBEDTLS_SSL_OUT_CONTENT_LEN )
  6199. {
  6200. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6201. }
  6202. if( conf->psk != NULL )
  6203. {
  6204. mbedtls_platform_zeroize( conf->psk, conf->psk_len );
  6205. mbedtls_free( conf->psk );
  6206. conf->psk = NULL;
  6207. conf->psk_len = 0;
  6208. }
  6209. if( conf->psk_identity != NULL )
  6210. {
  6211. mbedtls_free( conf->psk_identity );
  6212. conf->psk_identity = NULL;
  6213. conf->psk_identity_len = 0;
  6214. }
  6215. if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ||
  6216. ( conf->psk_identity = mbedtls_calloc( 1, psk_identity_len ) ) == NULL )
  6217. {
  6218. mbedtls_free( conf->psk );
  6219. mbedtls_free( conf->psk_identity );
  6220. conf->psk = NULL;
  6221. conf->psk_identity = NULL;
  6222. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  6223. }
  6224. conf->psk_len = psk_len;
  6225. conf->psk_identity_len = psk_identity_len;
  6226. memcpy( conf->psk, psk, conf->psk_len );
  6227. memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len );
  6228. return( 0 );
  6229. }
  6230. int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl,
  6231. const unsigned char *psk, size_t psk_len )
  6232. {
  6233. if( psk == NULL || ssl->handshake == NULL )
  6234. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6235. if( psk_len > MBEDTLS_PSK_MAX_LEN )
  6236. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6237. if( ssl->handshake->psk != NULL )
  6238. {
  6239. mbedtls_platform_zeroize( ssl->handshake->psk,
  6240. ssl->handshake->psk_len );
  6241. mbedtls_free( ssl->handshake->psk );
  6242. ssl->handshake->psk_len = 0;
  6243. }
  6244. if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL )
  6245. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  6246. ssl->handshake->psk_len = psk_len;
  6247. memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len );
  6248. return( 0 );
  6249. }
  6250. void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,
  6251. int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
  6252. size_t),
  6253. void *p_psk )
  6254. {
  6255. conf->f_psk = f_psk;
  6256. conf->p_psk = p_psk;
  6257. }
  6258. #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
  6259. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
  6260. #if !defined(MBEDTLS_DEPRECATED_REMOVED)
  6261. int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G )
  6262. {
  6263. int ret;
  6264. if( ( ret = mbedtls_mpi_read_string( &conf->dhm_P, 16, dhm_P ) ) != 0 ||
  6265. ( ret = mbedtls_mpi_read_string( &conf->dhm_G, 16, dhm_G ) ) != 0 )
  6266. {
  6267. mbedtls_mpi_free( &conf->dhm_P );
  6268. mbedtls_mpi_free( &conf->dhm_G );
  6269. return( ret );
  6270. }
  6271. return( 0 );
  6272. }
  6273. #endif /* MBEDTLS_DEPRECATED_REMOVED */
  6274. int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf,
  6275. const unsigned char *dhm_P, size_t P_len,
  6276. const unsigned char *dhm_G, size_t G_len )
  6277. {
  6278. int ret;
  6279. if( ( ret = mbedtls_mpi_read_binary( &conf->dhm_P, dhm_P, P_len ) ) != 0 ||
  6280. ( ret = mbedtls_mpi_read_binary( &conf->dhm_G, dhm_G, G_len ) ) != 0 )
  6281. {
  6282. mbedtls_mpi_free( &conf->dhm_P );
  6283. mbedtls_mpi_free( &conf->dhm_G );
  6284. return( ret );
  6285. }
  6286. return( 0 );
  6287. }
  6288. int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx )
  6289. {
  6290. int ret;
  6291. if( ( ret = mbedtls_mpi_copy( &conf->dhm_P, &dhm_ctx->P ) ) != 0 ||
  6292. ( ret = mbedtls_mpi_copy( &conf->dhm_G, &dhm_ctx->G ) ) != 0 )
  6293. {
  6294. mbedtls_mpi_free( &conf->dhm_P );
  6295. mbedtls_mpi_free( &conf->dhm_G );
  6296. return( ret );
  6297. }
  6298. return( 0 );
  6299. }
  6300. #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */
  6301. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
  6302. /*
  6303. * Set the minimum length for Diffie-Hellman parameters
  6304. */
  6305. void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf,
  6306. unsigned int bitlen )
  6307. {
  6308. conf->dhm_min_bitlen = bitlen;
  6309. }
  6310. #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
  6311. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  6312. /*
  6313. * Set allowed/preferred hashes for handshake signatures
  6314. */
  6315. void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
  6316. const int *hashes )
  6317. {
  6318. conf->sig_hashes = hashes;
  6319. }
  6320. #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
  6321. #if defined(MBEDTLS_ECP_C)
  6322. /*
  6323. * Set the allowed elliptic curves
  6324. */
  6325. void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,
  6326. const mbedtls_ecp_group_id *curve_list )
  6327. {
  6328. conf->curve_list = curve_list;
  6329. }
  6330. #endif /* MBEDTLS_ECP_C */
  6331. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  6332. int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname )
  6333. {
  6334. /* Initialize to suppress unnecessary compiler warning */
  6335. size_t hostname_len = 0;
  6336. /* Check if new hostname is valid before
  6337. * making any change to current one */
  6338. if( hostname != NULL )
  6339. {
  6340. hostname_len = strlen( hostname );
  6341. if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )
  6342. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6343. }
  6344. /* Now it's clear that we will overwrite the old hostname,
  6345. * so we can free it safely */
  6346. if( ssl->hostname != NULL )
  6347. {
  6348. mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );
  6349. mbedtls_free( ssl->hostname );
  6350. }
  6351. /* Passing NULL as hostname shall clear the old one */
  6352. if( hostname == NULL )
  6353. {
  6354. ssl->hostname = NULL;
  6355. }
  6356. else
  6357. {
  6358. ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 );
  6359. if( ssl->hostname == NULL )
  6360. return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  6361. memcpy( ssl->hostname, hostname, hostname_len );
  6362. ssl->hostname[hostname_len] = '\0';
  6363. }
  6364. return( 0 );
  6365. }
  6366. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  6367. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  6368. void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,
  6369. int (*f_sni)(void *, mbedtls_ssl_context *,
  6370. const unsigned char *, size_t),
  6371. void *p_sni )
  6372. {
  6373. conf->f_sni = f_sni;
  6374. conf->p_sni = p_sni;
  6375. }
  6376. #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
  6377. #if defined(MBEDTLS_SSL_ALPN)
  6378. int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos )
  6379. {
  6380. size_t cur_len, tot_len;
  6381. const char **p;
  6382. /*
  6383. * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings
  6384. * MUST NOT be truncated."
  6385. * We check lengths now rather than later.
  6386. */
  6387. tot_len = 0;
  6388. for( p = protos; *p != NULL; p++ )
  6389. {
  6390. cur_len = strlen( *p );
  6391. tot_len += cur_len;
  6392. if( cur_len == 0 || cur_len > 255 || tot_len > 65535 )
  6393. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6394. }
  6395. conf->alpn_list = protos;
  6396. return( 0 );
  6397. }
  6398. const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl )
  6399. {
  6400. return( ssl->alpn_chosen );
  6401. }
  6402. #endif /* MBEDTLS_SSL_ALPN */
  6403. void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor )
  6404. {
  6405. conf->max_major_ver = major;
  6406. conf->max_minor_ver = minor;
  6407. }
  6408. void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor )
  6409. {
  6410. conf->min_major_ver = major;
  6411. conf->min_minor_ver = minor;
  6412. }
  6413. #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
  6414. void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback )
  6415. {
  6416. conf->fallback = fallback;
  6417. }
  6418. #endif
  6419. #if defined(MBEDTLS_SSL_SRV_C)
  6420. void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf,
  6421. char cert_req_ca_list )
  6422. {
  6423. conf->cert_req_ca_list = cert_req_ca_list;
  6424. }
  6425. #endif
  6426. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  6427. void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm )
  6428. {
  6429. conf->encrypt_then_mac = etm;
  6430. }
  6431. #endif
  6432. #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
  6433. void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems )
  6434. {
  6435. conf->extended_ms = ems;
  6436. }
  6437. #endif
  6438. #if defined(MBEDTLS_ARC4_C)
  6439. void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 )
  6440. {
  6441. conf->arc4_disabled = arc4;
  6442. }
  6443. #endif
  6444. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  6445. int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code )
  6446. {
  6447. if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ||
  6448. ssl_mfl_code_to_length( mfl_code ) > MBEDTLS_TLS_EXT_ADV_CONTENT_LEN )
  6449. {
  6450. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6451. }
  6452. conf->mfl_code = mfl_code;
  6453. return( 0 );
  6454. }
  6455. #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
  6456. #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
  6457. void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate )
  6458. {
  6459. conf->trunc_hmac = truncate;
  6460. }
  6461. #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
  6462. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  6463. void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split )
  6464. {
  6465. conf->cbc_record_splitting = split;
  6466. }
  6467. #endif
  6468. void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy )
  6469. {
  6470. conf->allow_legacy_renegotiation = allow_legacy;
  6471. }
  6472. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  6473. void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation )
  6474. {
  6475. conf->disable_renegotiation = renegotiation;
  6476. }
  6477. void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records )
  6478. {
  6479. conf->renego_max_records = max_records;
  6480. }
  6481. void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,
  6482. const unsigned char period[8] )
  6483. {
  6484. memcpy( conf->renego_period, period, 8 );
  6485. }
  6486. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  6487. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  6488. #if defined(MBEDTLS_SSL_CLI_C)
  6489. void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets )
  6490. {
  6491. conf->session_tickets = use_tickets;
  6492. }
  6493. #endif
  6494. #if defined(MBEDTLS_SSL_SRV_C)
  6495. void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf,
  6496. mbedtls_ssl_ticket_write_t *f_ticket_write,
  6497. mbedtls_ssl_ticket_parse_t *f_ticket_parse,
  6498. void *p_ticket )
  6499. {
  6500. conf->f_ticket_write = f_ticket_write;
  6501. conf->f_ticket_parse = f_ticket_parse;
  6502. conf->p_ticket = p_ticket;
  6503. }
  6504. #endif
  6505. #endif /* MBEDTLS_SSL_SESSION_TICKETS */
  6506. #if defined(MBEDTLS_SSL_EXPORT_KEYS)
  6507. void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf,
  6508. mbedtls_ssl_export_keys_t *f_export_keys,
  6509. void *p_export_keys )
  6510. {
  6511. conf->f_export_keys = f_export_keys;
  6512. conf->p_export_keys = p_export_keys;
  6513. }
  6514. #endif
  6515. #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
  6516. void mbedtls_ssl_conf_async_private_cb(
  6517. mbedtls_ssl_config *conf,
  6518. mbedtls_ssl_async_sign_t *f_async_sign,
  6519. mbedtls_ssl_async_decrypt_t *f_async_decrypt,
  6520. mbedtls_ssl_async_resume_t *f_async_resume,
  6521. mbedtls_ssl_async_cancel_t *f_async_cancel,
  6522. void *async_config_data )
  6523. {
  6524. conf->f_async_sign_start = f_async_sign;
  6525. conf->f_async_decrypt_start = f_async_decrypt;
  6526. conf->f_async_resume = f_async_resume;
  6527. conf->f_async_cancel = f_async_cancel;
  6528. conf->p_async_config_data = async_config_data;
  6529. }
  6530. void *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf )
  6531. {
  6532. return( conf->p_async_config_data );
  6533. }
  6534. void *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl )
  6535. {
  6536. if( ssl->handshake == NULL )
  6537. return( NULL );
  6538. else
  6539. return( ssl->handshake->user_async_ctx );
  6540. }
  6541. void mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl,
  6542. void *ctx )
  6543. {
  6544. if( ssl->handshake != NULL )
  6545. ssl->handshake->user_async_ctx = ctx;
  6546. }
  6547. #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
  6548. /*
  6549. * SSL get accessors
  6550. */
  6551. size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl )
  6552. {
  6553. return( ssl->in_offt == NULL ? 0 : ssl->in_msglen );
  6554. }
  6555. int mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl )
  6556. {
  6557. /*
  6558. * Case A: We're currently holding back
  6559. * a message for further processing.
  6560. */
  6561. if( ssl->keep_current_message == 1 )
  6562. {
  6563. MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: record held back for processing" ) );
  6564. return( 1 );
  6565. }
  6566. /*
  6567. * Case B: Further records are pending in the current datagram.
  6568. */
  6569. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6570. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  6571. ssl->in_left > ssl->next_record_offset )
  6572. {
  6573. MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more records within current datagram" ) );
  6574. return( 1 );
  6575. }
  6576. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  6577. /*
  6578. * Case C: A handshake message is being processed.
  6579. */
  6580. if( ssl->in_hslen > 0 && ssl->in_hslen < ssl->in_msglen )
  6581. {
  6582. MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more handshake messages within current record" ) );
  6583. return( 1 );
  6584. }
  6585. /*
  6586. * Case D: An application data message is being processed
  6587. */
  6588. if( ssl->in_offt != NULL )
  6589. {
  6590. MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: application data record is being processed" ) );
  6591. return( 1 );
  6592. }
  6593. /*
  6594. * In all other cases, the rest of the message can be dropped.
  6595. * As in ssl_get_next_record, this needs to be adapted if
  6596. * we implement support for multiple alerts in single records.
  6597. */
  6598. MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: nothing pending" ) );
  6599. return( 0 );
  6600. }
  6601. uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl )
  6602. {
  6603. if( ssl->session != NULL )
  6604. return( ssl->session->verify_result );
  6605. if( ssl->session_negotiate != NULL )
  6606. return( ssl->session_negotiate->verify_result );
  6607. return( 0xFFFFFFFF );
  6608. }
  6609. const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl )
  6610. {
  6611. if( ssl == NULL || ssl->session == NULL )
  6612. return( NULL );
  6613. return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite );
  6614. }
  6615. const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl )
  6616. {
  6617. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6618. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  6619. {
  6620. switch( ssl->minor_ver )
  6621. {
  6622. case MBEDTLS_SSL_MINOR_VERSION_2:
  6623. return( "DTLSv1.0" );
  6624. case MBEDTLS_SSL_MINOR_VERSION_3:
  6625. return( "DTLSv1.2" );
  6626. default:
  6627. return( "unknown (DTLS)" );
  6628. }
  6629. }
  6630. #endif
  6631. switch( ssl->minor_ver )
  6632. {
  6633. case MBEDTLS_SSL_MINOR_VERSION_0:
  6634. return( "SSLv3.0" );
  6635. case MBEDTLS_SSL_MINOR_VERSION_1:
  6636. return( "TLSv1.0" );
  6637. case MBEDTLS_SSL_MINOR_VERSION_2:
  6638. return( "TLSv1.1" );
  6639. case MBEDTLS_SSL_MINOR_VERSION_3:
  6640. return( "TLSv1.2" );
  6641. default:
  6642. return( "unknown" );
  6643. }
  6644. }
  6645. int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl )
  6646. {
  6647. size_t transform_expansion = 0;
  6648. const mbedtls_ssl_transform *transform = ssl->transform_out;
  6649. unsigned block_size;
  6650. if( transform == NULL )
  6651. return( (int) mbedtls_ssl_hdr_len( ssl ) );
  6652. #if defined(MBEDTLS_ZLIB_SUPPORT)
  6653. if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL )
  6654. return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  6655. #endif
  6656. switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) )
  6657. {
  6658. case MBEDTLS_MODE_GCM:
  6659. case MBEDTLS_MODE_CCM:
  6660. case MBEDTLS_MODE_CHACHAPOLY:
  6661. case MBEDTLS_MODE_STREAM:
  6662. transform_expansion = transform->minlen;
  6663. break;
  6664. case MBEDTLS_MODE_CBC:
  6665. block_size = mbedtls_cipher_get_block_size(
  6666. &transform->cipher_ctx_enc );
  6667. /* Expansion due to the addition of the MAC. */
  6668. transform_expansion += transform->maclen;
  6669. /* Expansion due to the addition of CBC padding;
  6670. * Theoretically up to 256 bytes, but we never use
  6671. * more than the block size of the underlying cipher. */
  6672. transform_expansion += block_size;
  6673. /* For TLS 1.1 or higher, an explicit IV is added
  6674. * after the record header. */
  6675. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  6676. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  6677. transform_expansion += block_size;
  6678. #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
  6679. break;
  6680. default:
  6681. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  6682. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  6683. }
  6684. return( (int)( mbedtls_ssl_hdr_len( ssl ) + transform_expansion ) );
  6685. }
  6686. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  6687. size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl )
  6688. {
  6689. size_t max_len;
  6690. /*
  6691. * Assume mfl_code is correct since it was checked when set
  6692. */
  6693. max_len = ssl_mfl_code_to_length( ssl->conf->mfl_code );
  6694. /* Check if a smaller max length was negotiated */
  6695. if( ssl->session_out != NULL &&
  6696. ssl_mfl_code_to_length( ssl->session_out->mfl_code ) < max_len )
  6697. {
  6698. max_len = ssl_mfl_code_to_length( ssl->session_out->mfl_code );
  6699. }
  6700. /* During a handshake, use the value being negotiated */
  6701. if( ssl->session_negotiate != NULL &&
  6702. ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code ) < max_len )
  6703. {
  6704. max_len = ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code );
  6705. }
  6706. return( max_len );
  6707. }
  6708. #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
  6709. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6710. static size_t ssl_get_current_mtu( const mbedtls_ssl_context *ssl )
  6711. {
  6712. /* Return unlimited mtu for client hello messages to avoid fragmentation. */
  6713. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
  6714. ( ssl->state == MBEDTLS_SSL_CLIENT_HELLO ||
  6715. ssl->state == MBEDTLS_SSL_SERVER_HELLO ) )
  6716. return ( 0 );
  6717. if( ssl->handshake == NULL || ssl->handshake->mtu == 0 )
  6718. return( ssl->mtu );
  6719. if( ssl->mtu == 0 )
  6720. return( ssl->handshake->mtu );
  6721. return( ssl->mtu < ssl->handshake->mtu ?
  6722. ssl->mtu : ssl->handshake->mtu );
  6723. }
  6724. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  6725. int mbedtls_ssl_get_max_out_record_payload( const mbedtls_ssl_context *ssl )
  6726. {
  6727. size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
  6728. #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \
  6729. !defined(MBEDTLS_SSL_PROTO_DTLS)
  6730. (void) ssl;
  6731. #endif
  6732. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  6733. const size_t mfl = mbedtls_ssl_get_max_frag_len( ssl );
  6734. if( max_len > mfl )
  6735. max_len = mfl;
  6736. #endif
  6737. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6738. if( ssl_get_current_mtu( ssl ) != 0 )
  6739. {
  6740. const size_t mtu = ssl_get_current_mtu( ssl );
  6741. const int ret = mbedtls_ssl_get_record_expansion( ssl );
  6742. const size_t overhead = (size_t) ret;
  6743. if( ret < 0 )
  6744. return( ret );
  6745. if( mtu <= overhead )
  6746. {
  6747. MBEDTLS_SSL_DEBUG_MSG( 1, ( "MTU too low for record expansion" ) );
  6748. return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  6749. }
  6750. if( max_len > mtu - overhead )
  6751. max_len = mtu - overhead;
  6752. }
  6753. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  6754. #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \
  6755. !defined(MBEDTLS_SSL_PROTO_DTLS)
  6756. ((void) ssl);
  6757. #endif
  6758. return( (int) max_len );
  6759. }
  6760. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  6761. const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl )
  6762. {
  6763. if( ssl == NULL || ssl->session == NULL )
  6764. return( NULL );
  6765. return( ssl->session->peer_cert );
  6766. }
  6767. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  6768. #if defined(MBEDTLS_SSL_CLI_C)
  6769. int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *dst )
  6770. {
  6771. if( ssl == NULL ||
  6772. dst == NULL ||
  6773. ssl->session == NULL ||
  6774. ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
  6775. {
  6776. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6777. }
  6778. return( ssl_session_copy( dst, ssl->session ) );
  6779. }
  6780. #endif /* MBEDTLS_SSL_CLI_C */
  6781. /*
  6782. * Perform a single step of the SSL handshake
  6783. */
  6784. int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl )
  6785. {
  6786. int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
  6787. if( ssl == NULL || ssl->conf == NULL )
  6788. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6789. #if defined(MBEDTLS_SSL_CLI_C)
  6790. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  6791. ret = mbedtls_ssl_handshake_client_step( ssl );
  6792. #endif
  6793. #if defined(MBEDTLS_SSL_SRV_C)
  6794. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  6795. ret = mbedtls_ssl_handshake_server_step( ssl );
  6796. #endif
  6797. return( ret );
  6798. }
  6799. /*
  6800. * Perform the SSL handshake
  6801. */
  6802. int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl )
  6803. {
  6804. int ret = 0;
  6805. if( ssl == NULL || ssl->conf == NULL )
  6806. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6807. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) );
  6808. while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  6809. {
  6810. ret = mbedtls_ssl_handshake_step( ssl );
  6811. if( ret != 0 )
  6812. break;
  6813. }
  6814. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) );
  6815. return( ret );
  6816. }
  6817. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  6818. #if defined(MBEDTLS_SSL_SRV_C)
  6819. /*
  6820. * Write HelloRequest to request renegotiation on server
  6821. */
  6822. static int ssl_write_hello_request( mbedtls_ssl_context *ssl )
  6823. {
  6824. int ret;
  6825. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) );
  6826. ssl->out_msglen = 4;
  6827. ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  6828. ssl->out_msg[0] = MBEDTLS_SSL_HS_HELLO_REQUEST;
  6829. if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  6830. {
  6831. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  6832. return( ret );
  6833. }
  6834. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) );
  6835. return( 0 );
  6836. }
  6837. #endif /* MBEDTLS_SSL_SRV_C */
  6838. /*
  6839. * Actually renegotiate current connection, triggered by either:
  6840. * - any side: calling mbedtls_ssl_renegotiate(),
  6841. * - client: receiving a HelloRequest during mbedtls_ssl_read(),
  6842. * - server: receiving any handshake message on server during mbedtls_ssl_read() after
  6843. * the initial handshake is completed.
  6844. * If the handshake doesn't complete due to waiting for I/O, it will continue
  6845. * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively.
  6846. */
  6847. static int ssl_start_renegotiation( mbedtls_ssl_context *ssl )
  6848. {
  6849. int ret;
  6850. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) );
  6851. if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
  6852. return( ret );
  6853. /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and
  6854. * the ServerHello will have message_seq = 1" */
  6855. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6856. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  6857. ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
  6858. {
  6859. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  6860. ssl->handshake->out_msg_seq = 1;
  6861. else
  6862. ssl->handshake->in_msg_seq = 1;
  6863. }
  6864. #endif
  6865. ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
  6866. ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS;
  6867. if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
  6868. {
  6869. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
  6870. return( ret );
  6871. }
  6872. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) );
  6873. return( 0 );
  6874. }
  6875. /*
  6876. * Renegotiate current connection on client,
  6877. * or request renegotiation on server
  6878. */
  6879. int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl )
  6880. {
  6881. int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
  6882. if( ssl == NULL || ssl->conf == NULL )
  6883. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6884. #if defined(MBEDTLS_SSL_SRV_C)
  6885. /* On server, just send the request */
  6886. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  6887. {
  6888. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  6889. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6890. ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
  6891. /* Did we already try/start sending HelloRequest? */
  6892. if( ssl->out_left != 0 )
  6893. return( mbedtls_ssl_flush_output( ssl ) );
  6894. return( ssl_write_hello_request( ssl ) );
  6895. }
  6896. #endif /* MBEDTLS_SSL_SRV_C */
  6897. #if defined(MBEDTLS_SSL_CLI_C)
  6898. /*
  6899. * On client, either start the renegotiation process or,
  6900. * if already in progress, continue the handshake
  6901. */
  6902. if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
  6903. {
  6904. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  6905. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6906. if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 )
  6907. {
  6908. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
  6909. return( ret );
  6910. }
  6911. }
  6912. else
  6913. {
  6914. if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
  6915. {
  6916. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
  6917. return( ret );
  6918. }
  6919. }
  6920. #endif /* MBEDTLS_SSL_CLI_C */
  6921. return( ret );
  6922. }
  6923. /*
  6924. * Check record counters and renegotiate if they're above the limit.
  6925. */
  6926. static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl )
  6927. {
  6928. size_t ep_len = ssl_ep_len( ssl );
  6929. int in_ctr_cmp;
  6930. int out_ctr_cmp;
  6931. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ||
  6932. ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||
  6933. ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED )
  6934. {
  6935. return( 0 );
  6936. }
  6937. in_ctr_cmp = memcmp( ssl->in_ctr + ep_len,
  6938. ssl->conf->renego_period + ep_len, 8 - ep_len );
  6939. out_ctr_cmp = memcmp( ssl->cur_out_ctr + ep_len,
  6940. ssl->conf->renego_period + ep_len, 8 - ep_len );
  6941. if( in_ctr_cmp <= 0 && out_ctr_cmp <= 0 )
  6942. {
  6943. return( 0 );
  6944. }
  6945. MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) );
  6946. return( mbedtls_ssl_renegotiate( ssl ) );
  6947. }
  6948. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  6949. /*
  6950. * Receive application data decrypted from the SSL layer
  6951. */
  6952. int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
  6953. {
  6954. int ret;
  6955. size_t n;
  6956. if( ssl == NULL || ssl->conf == NULL )
  6957. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  6958. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) );
  6959. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6960. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  6961. {
  6962. if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  6963. return( ret );
  6964. if( ssl->handshake != NULL &&
  6965. ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
  6966. {
  6967. if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
  6968. return( ret );
  6969. }
  6970. }
  6971. #endif
  6972. /*
  6973. * Check if renegotiation is necessary and/or handshake is
  6974. * in process. If yes, perform/continue, and fall through
  6975. * if an unexpected packet is received while the client
  6976. * is waiting for the ServerHello.
  6977. *
  6978. * (There is no equivalent to the last condition on
  6979. * the server-side as it is not treated as within
  6980. * a handshake while waiting for the ClientHello
  6981. * after a renegotiation request.)
  6982. */
  6983. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  6984. ret = ssl_check_ctr_renegotiate( ssl );
  6985. if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
  6986. ret != 0 )
  6987. {
  6988. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
  6989. return( ret );
  6990. }
  6991. #endif
  6992. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  6993. {
  6994. ret = mbedtls_ssl_handshake( ssl );
  6995. if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
  6996. ret != 0 )
  6997. {
  6998. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
  6999. return( ret );
  7000. }
  7001. }
  7002. /* Loop as long as no application data record is available */
  7003. while( ssl->in_offt == NULL )
  7004. {
  7005. /* Start timer if not already running */
  7006. if( ssl->f_get_timer != NULL &&
  7007. ssl->f_get_timer( ssl->p_timer ) == -1 )
  7008. {
  7009. ssl_set_timer( ssl, ssl->conf->read_timeout );
  7010. }
  7011. if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  7012. {
  7013. if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
  7014. return( 0 );
  7015. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  7016. return( ret );
  7017. }
  7018. if( ssl->in_msglen == 0 &&
  7019. ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA )
  7020. {
  7021. /*
  7022. * OpenSSL sends empty messages to randomize the IV
  7023. */
  7024. if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  7025. {
  7026. if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
  7027. return( 0 );
  7028. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  7029. return( ret );
  7030. }
  7031. }
  7032. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
  7033. {
  7034. MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) );
  7035. /*
  7036. * - For client-side, expect SERVER_HELLO_REQUEST.
  7037. * - For server-side, expect CLIENT_HELLO.
  7038. * - Fail (TLS) or silently drop record (DTLS) in other cases.
  7039. */
  7040. #if defined(MBEDTLS_SSL_CLI_C)
  7041. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
  7042. ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST ||
  7043. ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ) )
  7044. {
  7045. MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) );
  7046. /* With DTLS, drop the packet (probably from last handshake) */
  7047. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7048. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  7049. {
  7050. continue;
  7051. }
  7052. #endif
  7053. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  7054. }
  7055. #endif /* MBEDTLS_SSL_CLI_C */
  7056. #if defined(MBEDTLS_SSL_SRV_C)
  7057. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  7058. ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )
  7059. {
  7060. MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) );
  7061. /* With DTLS, drop the packet (probably from last handshake) */
  7062. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7063. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  7064. {
  7065. continue;
  7066. }
  7067. #endif
  7068. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  7069. }
  7070. #endif /* MBEDTLS_SSL_SRV_C */
  7071. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  7072. /* Determine whether renegotiation attempt should be accepted */
  7073. if( ! ( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
  7074. ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
  7075. ssl->conf->allow_legacy_renegotiation ==
  7076. MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) )
  7077. {
  7078. /*
  7079. * Accept renegotiation request
  7080. */
  7081. /* DTLS clients need to know renego is server-initiated */
  7082. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7083. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  7084. ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  7085. {
  7086. ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
  7087. }
  7088. #endif
  7089. ret = ssl_start_renegotiation( ssl );
  7090. if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
  7091. ret != 0 )
  7092. {
  7093. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
  7094. return( ret );
  7095. }
  7096. }
  7097. else
  7098. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  7099. {
  7100. /*
  7101. * Refuse renegotiation
  7102. */
  7103. MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) );
  7104. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  7105. if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  7106. {
  7107. /* SSLv3 does not have a "no_renegotiation" warning, so
  7108. we send a fatal alert and abort the connection. */
  7109. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  7110. MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  7111. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  7112. }
  7113. else
  7114. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  7115. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  7116. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  7117. if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
  7118. {
  7119. if( ( ret = mbedtls_ssl_send_alert_message( ssl,
  7120. MBEDTLS_SSL_ALERT_LEVEL_WARNING,
  7121. MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 )
  7122. {
  7123. return( ret );
  7124. }
  7125. }
  7126. else
  7127. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 ||
  7128. MBEDTLS_SSL_PROTO_TLS1_2 */
  7129. {
  7130. MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  7131. return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  7132. }
  7133. }
  7134. /* At this point, we don't know whether the renegotiation has been
  7135. * completed or not. The cases to consider are the following:
  7136. * 1) The renegotiation is complete. In this case, no new record
  7137. * has been read yet.
  7138. * 2) The renegotiation is incomplete because the client received
  7139. * an application data record while awaiting the ServerHello.
  7140. * 3) The renegotiation is incomplete because the client received
  7141. * a non-handshake, non-application data message while awaiting
  7142. * the ServerHello.
  7143. * In each of these case, looping will be the proper action:
  7144. * - For 1), the next iteration will read a new record and check
  7145. * if it's application data.
  7146. * - For 2), the loop condition isn't satisfied as application data
  7147. * is present, hence continue is the same as break
  7148. * - For 3), the loop condition is satisfied and read_record
  7149. * will re-deliver the message that was held back by the client
  7150. * when expecting the ServerHello.
  7151. */
  7152. continue;
  7153. }
  7154. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  7155. else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
  7156. {
  7157. if( ssl->conf->renego_max_records >= 0 )
  7158. {
  7159. if( ++ssl->renego_records_seen > ssl->conf->renego_max_records )
  7160. {
  7161. MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
  7162. "but not honored by client" ) );
  7163. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  7164. }
  7165. }
  7166. }
  7167. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  7168. /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */
  7169. if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
  7170. {
  7171. MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) );
  7172. return( MBEDTLS_ERR_SSL_WANT_READ );
  7173. }
  7174. if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
  7175. {
  7176. MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) );
  7177. return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  7178. }
  7179. ssl->in_offt = ssl->in_msg;
  7180. /* We're going to return something now, cancel timer,
  7181. * except if handshake (renegotiation) is in progress */
  7182. if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
  7183. ssl_set_timer( ssl, 0 );
  7184. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7185. /* If we requested renego but received AppData, resend HelloRequest.
  7186. * Do it now, after setting in_offt, to avoid taking this branch
  7187. * again if ssl_write_hello_request() returns WANT_WRITE */
  7188. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
  7189. if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  7190. ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
  7191. {
  7192. if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
  7193. {
  7194. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
  7195. return( ret );
  7196. }
  7197. }
  7198. #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
  7199. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  7200. }
  7201. n = ( len < ssl->in_msglen )
  7202. ? len : ssl->in_msglen;
  7203. memcpy( buf, ssl->in_offt, n );
  7204. ssl->in_msglen -= n;
  7205. if( ssl->in_msglen == 0 )
  7206. {
  7207. /* all bytes consumed */
  7208. ssl->in_offt = NULL;
  7209. ssl->keep_current_message = 0;
  7210. }
  7211. else
  7212. {
  7213. /* more data available */
  7214. ssl->in_offt += n;
  7215. }
  7216. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) );
  7217. return( (int) n );
  7218. }
  7219. /*
  7220. * Send application data to be encrypted by the SSL layer, taking care of max
  7221. * fragment length and buffer size.
  7222. *
  7223. * According to RFC 5246 Section 6.2.1:
  7224. *
  7225. * Zero-length fragments of Application data MAY be sent as they are
  7226. * potentially useful as a traffic analysis countermeasure.
  7227. *
  7228. * Therefore, it is possible that the input message length is 0 and the
  7229. * corresponding return code is 0 on success.
  7230. */
  7231. static int ssl_write_real( mbedtls_ssl_context *ssl,
  7232. const unsigned char *buf, size_t len )
  7233. {
  7234. int ret = mbedtls_ssl_get_max_out_record_payload( ssl );
  7235. const size_t max_len = (size_t) ret;
  7236. if( ret < 0 )
  7237. {
  7238. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_get_max_out_record_payload", ret );
  7239. return( ret );
  7240. }
  7241. if( len > max_len )
  7242. {
  7243. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7244. if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  7245. {
  7246. MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) "
  7247. "maximum fragment length: %d > %d",
  7248. len, max_len ) );
  7249. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7250. }
  7251. else
  7252. #endif
  7253. len = max_len;
  7254. }
  7255. if( ssl->out_left != 0 )
  7256. {
  7257. /*
  7258. * The user has previously tried to send the data and
  7259. * MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially
  7260. * written. In this case, we expect the high-level write function
  7261. * (e.g. mbedtls_ssl_write()) to be called with the same parameters
  7262. */
  7263. if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  7264. {
  7265. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
  7266. return( ret );
  7267. }
  7268. }
  7269. else
  7270. {
  7271. /*
  7272. * The user is trying to send a message the first time, so we need to
  7273. * copy the data into the internal buffers and setup the data structure
  7274. * to keep track of partial writes
  7275. */
  7276. ssl->out_msglen = len;
  7277. ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
  7278. memcpy( ssl->out_msg, buf, len );
  7279. if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
  7280. {
  7281. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
  7282. return( ret );
  7283. }
  7284. }
  7285. return( (int) len );
  7286. }
  7287. /*
  7288. * Write application data, doing 1/n-1 splitting if necessary.
  7289. *
  7290. * With non-blocking I/O, ssl_write_real() may return WANT_WRITE,
  7291. * then the caller will call us again with the same arguments, so
  7292. * remember whether we already did the split or not.
  7293. */
  7294. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  7295. static int ssl_write_split( mbedtls_ssl_context *ssl,
  7296. const unsigned char *buf, size_t len )
  7297. {
  7298. int ret;
  7299. if( ssl->conf->cbc_record_splitting ==
  7300. MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ||
  7301. len <= 1 ||
  7302. ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 ||
  7303. mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc )
  7304. != MBEDTLS_MODE_CBC )
  7305. {
  7306. return( ssl_write_real( ssl, buf, len ) );
  7307. }
  7308. if( ssl->split_done == 0 )
  7309. {
  7310. if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 )
  7311. return( ret );
  7312. ssl->split_done = 1;
  7313. }
  7314. if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 )
  7315. return( ret );
  7316. ssl->split_done = 0;
  7317. return( ret + 1 );
  7318. }
  7319. #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
  7320. /*
  7321. * Write application data (public-facing wrapper)
  7322. */
  7323. int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len )
  7324. {
  7325. int ret;
  7326. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) );
  7327. if( ssl == NULL || ssl->conf == NULL )
  7328. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7329. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  7330. if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
  7331. {
  7332. MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
  7333. return( ret );
  7334. }
  7335. #endif
  7336. if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  7337. {
  7338. if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
  7339. {
  7340. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
  7341. return( ret );
  7342. }
  7343. }
  7344. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  7345. ret = ssl_write_split( ssl, buf, len );
  7346. #else
  7347. ret = ssl_write_real( ssl, buf, len );
  7348. #endif
  7349. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) );
  7350. return( ret );
  7351. }
  7352. /*
  7353. * Notify the peer that the connection is being closed
  7354. */
  7355. int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl )
  7356. {
  7357. int ret;
  7358. if( ssl == NULL || ssl->conf == NULL )
  7359. return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7360. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
  7361. if( ssl->out_left != 0 )
  7362. return( mbedtls_ssl_flush_output( ssl ) );
  7363. if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
  7364. {
  7365. if( ( ret = mbedtls_ssl_send_alert_message( ssl,
  7366. MBEDTLS_SSL_ALERT_LEVEL_WARNING,
  7367. MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )
  7368. {
  7369. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret );
  7370. return( ret );
  7371. }
  7372. }
  7373. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) );
  7374. return( 0 );
  7375. }
  7376. void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform )
  7377. {
  7378. if( transform == NULL )
  7379. return;
  7380. #if defined(MBEDTLS_ZLIB_SUPPORT)
  7381. deflateEnd( &transform->ctx_deflate );
  7382. inflateEnd( &transform->ctx_inflate );
  7383. #endif
  7384. mbedtls_cipher_free( &transform->cipher_ctx_enc );
  7385. mbedtls_cipher_free( &transform->cipher_ctx_dec );
  7386. mbedtls_md_free( &transform->md_ctx_enc );
  7387. mbedtls_md_free( &transform->md_ctx_dec );
  7388. mbedtls_platform_zeroize( transform, sizeof( mbedtls_ssl_transform ) );
  7389. }
  7390. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7391. static void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert )
  7392. {
  7393. mbedtls_ssl_key_cert *cur = key_cert, *next;
  7394. while( cur != NULL )
  7395. {
  7396. next = cur->next;
  7397. mbedtls_free( cur );
  7398. cur = next;
  7399. }
  7400. }
  7401. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  7402. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7403. static void ssl_buffering_free( mbedtls_ssl_context *ssl )
  7404. {
  7405. unsigned offset;
  7406. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  7407. if( hs == NULL )
  7408. return;
  7409. ssl_free_buffered_record( ssl );
  7410. for( offset = 0; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ )
  7411. ssl_buffering_free_slot( ssl, offset );
  7412. }
  7413. static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
  7414. uint8_t slot )
  7415. {
  7416. mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  7417. mbedtls_ssl_hs_buffer * const hs_buf = &hs->buffering.hs[slot];
  7418. if( slot >= MBEDTLS_SSL_MAX_BUFFERED_HS )
  7419. return;
  7420. if( hs_buf->is_valid == 1 )
  7421. {
  7422. hs->buffering.total_bytes_buffered -= hs_buf->data_len;
  7423. mbedtls_platform_zeroize( hs_buf->data, hs_buf->data_len );
  7424. mbedtls_free( hs_buf->data );
  7425. memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) );
  7426. }
  7427. }
  7428. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  7429. void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl )
  7430. {
  7431. mbedtls_ssl_handshake_params *handshake = ssl->handshake;
  7432. if( handshake == NULL )
  7433. return;
  7434. #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
  7435. if( ssl->conf->f_async_cancel != NULL && handshake->async_in_progress != 0 )
  7436. {
  7437. ssl->conf->f_async_cancel( ssl );
  7438. handshake->async_in_progress = 0;
  7439. }
  7440. #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
  7441. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  7442. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  7443. mbedtls_md5_free( &handshake->fin_md5 );
  7444. mbedtls_sha1_free( &handshake->fin_sha1 );
  7445. #endif
  7446. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  7447. #if defined(MBEDTLS_SHA256_C)
  7448. mbedtls_sha256_free( &handshake->fin_sha256 );
  7449. #endif
  7450. #if defined(MBEDTLS_SHA512_C)
  7451. mbedtls_sha512_free( &handshake->fin_sha512 );
  7452. #endif
  7453. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  7454. #if defined(MBEDTLS_DHM_C)
  7455. mbedtls_dhm_free( &handshake->dhm_ctx );
  7456. #endif
  7457. #if defined(MBEDTLS_ECDH_C)
  7458. mbedtls_ecdh_free( &handshake->ecdh_ctx );
  7459. #endif
  7460. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  7461. mbedtls_ecjpake_free( &handshake->ecjpake_ctx );
  7462. #if defined(MBEDTLS_SSL_CLI_C)
  7463. mbedtls_free( handshake->ecjpake_cache );
  7464. handshake->ecjpake_cache = NULL;
  7465. handshake->ecjpake_cache_len = 0;
  7466. #endif
  7467. #endif
  7468. #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
  7469. defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  7470. /* explicit void pointer cast for buggy MS compiler */
  7471. mbedtls_free( (void *) handshake->curves );
  7472. #endif
  7473. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
  7474. if( handshake->psk != NULL )
  7475. {
  7476. mbedtls_platform_zeroize( handshake->psk, handshake->psk_len );
  7477. mbedtls_free( handshake->psk );
  7478. }
  7479. #endif
  7480. #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
  7481. defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  7482. /*
  7483. * Free only the linked list wrapper, not the keys themselves
  7484. * since the belong to the SNI callback
  7485. */
  7486. if( handshake->sni_key_cert != NULL )
  7487. {
  7488. mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next;
  7489. while( cur != NULL )
  7490. {
  7491. next = cur->next;
  7492. mbedtls_free( cur );
  7493. cur = next;
  7494. }
  7495. }
  7496. #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */
  7497. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  7498. mbedtls_x509_crt_restart_free( &handshake->ecrs_ctx );
  7499. #endif
  7500. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7501. mbedtls_free( handshake->verify_cookie );
  7502. ssl_flight_free( handshake->flight );
  7503. ssl_buffering_free( ssl );
  7504. #endif
  7505. mbedtls_platform_zeroize( handshake,
  7506. sizeof( mbedtls_ssl_handshake_params ) );
  7507. }
  7508. void mbedtls_ssl_session_free( mbedtls_ssl_session *session )
  7509. {
  7510. if( session == NULL )
  7511. return;
  7512. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7513. if( session->peer_cert != NULL )
  7514. {
  7515. mbedtls_x509_crt_free( session->peer_cert );
  7516. mbedtls_free( session->peer_cert );
  7517. }
  7518. #endif
  7519. #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
  7520. mbedtls_free( session->ticket );
  7521. #endif
  7522. mbedtls_platform_zeroize( session, sizeof( mbedtls_ssl_session ) );
  7523. }
  7524. /*
  7525. * Free an SSL context
  7526. */
  7527. void mbedtls_ssl_free( mbedtls_ssl_context *ssl )
  7528. {
  7529. if( ssl == NULL )
  7530. return;
  7531. MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) );
  7532. if( ssl->out_buf != NULL )
  7533. {
  7534. mbedtls_platform_zeroize( ssl->out_buf, MBEDTLS_SSL_OUT_BUFFER_LEN );
  7535. mbedtls_free( ssl->out_buf );
  7536. }
  7537. if( ssl->in_buf != NULL )
  7538. {
  7539. mbedtls_platform_zeroize( ssl->in_buf, MBEDTLS_SSL_IN_BUFFER_LEN );
  7540. mbedtls_free( ssl->in_buf );
  7541. }
  7542. #if defined(MBEDTLS_ZLIB_SUPPORT)
  7543. if( ssl->compress_buf != NULL )
  7544. {
  7545. mbedtls_platform_zeroize( ssl->compress_buf, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );
  7546. mbedtls_free( ssl->compress_buf );
  7547. }
  7548. #endif
  7549. if( ssl->transform )
  7550. {
  7551. mbedtls_ssl_transform_free( ssl->transform );
  7552. mbedtls_free( ssl->transform );
  7553. }
  7554. if( ssl->handshake )
  7555. {
  7556. mbedtls_ssl_handshake_free( ssl );
  7557. mbedtls_ssl_transform_free( ssl->transform_negotiate );
  7558. mbedtls_ssl_session_free( ssl->session_negotiate );
  7559. mbedtls_free( ssl->handshake );
  7560. mbedtls_free( ssl->transform_negotiate );
  7561. mbedtls_free( ssl->session_negotiate );
  7562. }
  7563. if( ssl->session )
  7564. {
  7565. mbedtls_ssl_session_free( ssl->session );
  7566. mbedtls_free( ssl->session );
  7567. }
  7568. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7569. if( ssl->hostname != NULL )
  7570. {
  7571. mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );
  7572. mbedtls_free( ssl->hostname );
  7573. }
  7574. #endif
  7575. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  7576. if( mbedtls_ssl_hw_record_finish != NULL )
  7577. {
  7578. MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_finish()" ) );
  7579. mbedtls_ssl_hw_record_finish( ssl );
  7580. }
  7581. #endif
  7582. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
  7583. mbedtls_free( ssl->cli_id );
  7584. #endif
  7585. MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) );
  7586. /* Actually clear after last debug message */
  7587. mbedtls_platform_zeroize( ssl, sizeof( mbedtls_ssl_context ) );
  7588. }
  7589. /*
  7590. * Initialze mbedtls_ssl_config
  7591. */
  7592. void mbedtls_ssl_config_init( mbedtls_ssl_config *conf )
  7593. {
  7594. memset( conf, 0, sizeof( mbedtls_ssl_config ) );
  7595. }
  7596. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  7597. static int ssl_preset_default_hashes[] = {
  7598. #if defined(MBEDTLS_SHA512_C)
  7599. MBEDTLS_MD_SHA512,
  7600. MBEDTLS_MD_SHA384,
  7601. #endif
  7602. #if defined(MBEDTLS_SHA256_C)
  7603. MBEDTLS_MD_SHA256,
  7604. MBEDTLS_MD_SHA224,
  7605. #endif
  7606. #if defined(MBEDTLS_SHA1_C) && defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE)
  7607. MBEDTLS_MD_SHA1,
  7608. #endif
  7609. MBEDTLS_MD_NONE
  7610. };
  7611. #endif
  7612. static int ssl_preset_suiteb_ciphersuites[] = {
  7613. MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  7614. MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  7615. 0
  7616. };
  7617. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  7618. static int ssl_preset_suiteb_hashes[] = {
  7619. MBEDTLS_MD_SHA256,
  7620. MBEDTLS_MD_SHA384,
  7621. MBEDTLS_MD_NONE
  7622. };
  7623. #endif
  7624. #if defined(MBEDTLS_ECP_C)
  7625. static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = {
  7626. MBEDTLS_ECP_DP_SECP256R1,
  7627. MBEDTLS_ECP_DP_SECP384R1,
  7628. MBEDTLS_ECP_DP_NONE
  7629. };
  7630. #endif
  7631. /*
  7632. * Load default in mbedtls_ssl_config
  7633. */
  7634. int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
  7635. int endpoint, int transport, int preset )
  7636. {
  7637. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
  7638. int ret;
  7639. #endif
  7640. /* Use the functions here so that they are covered in tests,
  7641. * but otherwise access member directly for efficiency */
  7642. mbedtls_ssl_conf_endpoint( conf, endpoint );
  7643. mbedtls_ssl_conf_transport( conf, transport );
  7644. /*
  7645. * Things that are common to all presets
  7646. */
  7647. #if defined(MBEDTLS_SSL_CLI_C)
  7648. if( endpoint == MBEDTLS_SSL_IS_CLIENT )
  7649. {
  7650. conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
  7651. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  7652. conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED;
  7653. #endif
  7654. }
  7655. #endif
  7656. #if defined(MBEDTLS_ARC4_C)
  7657. conf->arc4_disabled = MBEDTLS_SSL_ARC4_DISABLED;
  7658. #endif
  7659. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  7660. conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
  7661. #endif
  7662. #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
  7663. conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
  7664. #endif
  7665. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  7666. conf->cbc_record_splitting = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED;
  7667. #endif
  7668. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
  7669. conf->f_cookie_write = ssl_cookie_write_dummy;
  7670. conf->f_cookie_check = ssl_cookie_check_dummy;
  7671. #endif
  7672. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  7673. conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED;
  7674. #endif
  7675. #if defined(MBEDTLS_SSL_SRV_C)
  7676. conf->cert_req_ca_list = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED;
  7677. #endif
  7678. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7679. conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN;
  7680. conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX;
  7681. #endif
  7682. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  7683. conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT;
  7684. memset( conf->renego_period, 0x00, 2 );
  7685. memset( conf->renego_period + 2, 0xFF, 6 );
  7686. #endif
  7687. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
  7688. if( endpoint == MBEDTLS_SSL_IS_SERVER )
  7689. {
  7690. const unsigned char dhm_p[] =
  7691. MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN;
  7692. const unsigned char dhm_g[] =
  7693. MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN;
  7694. if ( ( ret = mbedtls_ssl_conf_dh_param_bin( conf,
  7695. dhm_p, sizeof( dhm_p ),
  7696. dhm_g, sizeof( dhm_g ) ) ) != 0 )
  7697. {
  7698. return( ret );
  7699. }
  7700. }
  7701. #endif
  7702. /*
  7703. * Preset-specific defaults
  7704. */
  7705. switch( preset )
  7706. {
  7707. /*
  7708. * NSA Suite B
  7709. */
  7710. case MBEDTLS_SSL_PRESET_SUITEB:
  7711. conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
  7712. conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */
  7713. conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
  7714. conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
  7715. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
  7716. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
  7717. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
  7718. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
  7719. ssl_preset_suiteb_ciphersuites;
  7720. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7721. conf->cert_profile = &mbedtls_x509_crt_profile_suiteb;
  7722. #endif
  7723. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  7724. conf->sig_hashes = ssl_preset_suiteb_hashes;
  7725. #endif
  7726. #if defined(MBEDTLS_ECP_C)
  7727. conf->curve_list = ssl_preset_suiteb_curves;
  7728. #endif
  7729. break;
  7730. /*
  7731. * Default
  7732. */
  7733. default:
  7734. conf->min_major_ver = ( MBEDTLS_SSL_MIN_MAJOR_VERSION >
  7735. MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION ) ?
  7736. MBEDTLS_SSL_MIN_MAJOR_VERSION :
  7737. MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION;
  7738. conf->min_minor_ver = ( MBEDTLS_SSL_MIN_MINOR_VERSION >
  7739. MBEDTLS_SSL_MIN_VALID_MINOR_VERSION ) ?
  7740. MBEDTLS_SSL_MIN_MINOR_VERSION :
  7741. MBEDTLS_SSL_MIN_VALID_MINOR_VERSION;
  7742. conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
  7743. conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
  7744. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7745. if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  7746. conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_2;
  7747. #endif
  7748. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
  7749. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
  7750. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
  7751. conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
  7752. mbedtls_ssl_list_ciphersuites();
  7753. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7754. conf->cert_profile = &mbedtls_x509_crt_profile_default;
  7755. #endif
  7756. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  7757. conf->sig_hashes = ssl_preset_default_hashes;
  7758. #endif
  7759. #if defined(MBEDTLS_ECP_C)
  7760. conf->curve_list = mbedtls_ecp_grp_id_list();
  7761. #endif
  7762. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
  7763. conf->dhm_min_bitlen = 1024;
  7764. #endif
  7765. }
  7766. return( 0 );
  7767. }
  7768. /*
  7769. * Free mbedtls_ssl_config
  7770. */
  7771. void mbedtls_ssl_config_free( mbedtls_ssl_config *conf )
  7772. {
  7773. #if defined(MBEDTLS_DHM_C)
  7774. mbedtls_mpi_free( &conf->dhm_P );
  7775. mbedtls_mpi_free( &conf->dhm_G );
  7776. #endif
  7777. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
  7778. if( conf->psk != NULL )
  7779. {
  7780. mbedtls_platform_zeroize( conf->psk, conf->psk_len );
  7781. mbedtls_free( conf->psk );
  7782. conf->psk = NULL;
  7783. conf->psk_len = 0;
  7784. }
  7785. if( conf->psk_identity != NULL )
  7786. {
  7787. mbedtls_platform_zeroize( conf->psk_identity, conf->psk_identity_len );
  7788. mbedtls_free( conf->psk_identity );
  7789. conf->psk_identity = NULL;
  7790. conf->psk_identity_len = 0;
  7791. }
  7792. #endif
  7793. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7794. ssl_key_cert_free( conf->key_cert );
  7795. #endif
  7796. mbedtls_platform_zeroize( conf, sizeof( mbedtls_ssl_config ) );
  7797. }
  7798. #if defined(MBEDTLS_PK_C) && \
  7799. ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) )
  7800. /*
  7801. * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX
  7802. */
  7803. unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk )
  7804. {
  7805. #if defined(MBEDTLS_RSA_C)
  7806. if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) )
  7807. return( MBEDTLS_SSL_SIG_RSA );
  7808. #endif
  7809. #if defined(MBEDTLS_ECDSA_C)
  7810. if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) )
  7811. return( MBEDTLS_SSL_SIG_ECDSA );
  7812. #endif
  7813. return( MBEDTLS_SSL_SIG_ANON );
  7814. }
  7815. unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type )
  7816. {
  7817. switch( type ) {
  7818. case MBEDTLS_PK_RSA:
  7819. return( MBEDTLS_SSL_SIG_RSA );
  7820. case MBEDTLS_PK_ECDSA:
  7821. case MBEDTLS_PK_ECKEY:
  7822. return( MBEDTLS_SSL_SIG_ECDSA );
  7823. default:
  7824. return( MBEDTLS_SSL_SIG_ANON );
  7825. }
  7826. }
  7827. mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig )
  7828. {
  7829. switch( sig )
  7830. {
  7831. #if defined(MBEDTLS_RSA_C)
  7832. case MBEDTLS_SSL_SIG_RSA:
  7833. return( MBEDTLS_PK_RSA );
  7834. #endif
  7835. #if defined(MBEDTLS_ECDSA_C)
  7836. case MBEDTLS_SSL_SIG_ECDSA:
  7837. return( MBEDTLS_PK_ECDSA );
  7838. #endif
  7839. default:
  7840. return( MBEDTLS_PK_NONE );
  7841. }
  7842. }
  7843. #endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */
  7844. #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
  7845. defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  7846. /* Find an entry in a signature-hash set matching a given hash algorithm. */
  7847. mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set,
  7848. mbedtls_pk_type_t sig_alg )
  7849. {
  7850. switch( sig_alg )
  7851. {
  7852. case MBEDTLS_PK_RSA:
  7853. return( set->rsa );
  7854. case MBEDTLS_PK_ECDSA:
  7855. return( set->ecdsa );
  7856. default:
  7857. return( MBEDTLS_MD_NONE );
  7858. }
  7859. }
  7860. /* Add a signature-hash-pair to a signature-hash set */
  7861. void mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set,
  7862. mbedtls_pk_type_t sig_alg,
  7863. mbedtls_md_type_t md_alg )
  7864. {
  7865. switch( sig_alg )
  7866. {
  7867. case MBEDTLS_PK_RSA:
  7868. if( set->rsa == MBEDTLS_MD_NONE )
  7869. set->rsa = md_alg;
  7870. break;
  7871. case MBEDTLS_PK_ECDSA:
  7872. if( set->ecdsa == MBEDTLS_MD_NONE )
  7873. set->ecdsa = md_alg;
  7874. break;
  7875. default:
  7876. break;
  7877. }
  7878. }
  7879. /* Allow exactly one hash algorithm for each signature. */
  7880. void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set,
  7881. mbedtls_md_type_t md_alg )
  7882. {
  7883. set->rsa = md_alg;
  7884. set->ecdsa = md_alg;
  7885. }
  7886. #endif /* MBEDTLS_SSL_PROTO_TLS1_2) &&
  7887. MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
  7888. /*
  7889. * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX
  7890. */
  7891. mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash )
  7892. {
  7893. switch( hash )
  7894. {
  7895. #if defined(MBEDTLS_MD5_C)
  7896. case MBEDTLS_SSL_HASH_MD5:
  7897. return( MBEDTLS_MD_MD5 );
  7898. #endif
  7899. #if defined(MBEDTLS_SHA1_C)
  7900. case MBEDTLS_SSL_HASH_SHA1:
  7901. return( MBEDTLS_MD_SHA1 );
  7902. #endif
  7903. #if defined(MBEDTLS_SHA256_C)
  7904. case MBEDTLS_SSL_HASH_SHA224:
  7905. return( MBEDTLS_MD_SHA224 );
  7906. case MBEDTLS_SSL_HASH_SHA256:
  7907. return( MBEDTLS_MD_SHA256 );
  7908. #endif
  7909. #if defined(MBEDTLS_SHA512_C)
  7910. case MBEDTLS_SSL_HASH_SHA384:
  7911. return( MBEDTLS_MD_SHA384 );
  7912. case MBEDTLS_SSL_HASH_SHA512:
  7913. return( MBEDTLS_MD_SHA512 );
  7914. #endif
  7915. default:
  7916. return( MBEDTLS_MD_NONE );
  7917. }
  7918. }
  7919. /*
  7920. * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX
  7921. */
  7922. unsigned char mbedtls_ssl_hash_from_md_alg( int md )
  7923. {
  7924. switch( md )
  7925. {
  7926. #if defined(MBEDTLS_MD5_C)
  7927. case MBEDTLS_MD_MD5:
  7928. return( MBEDTLS_SSL_HASH_MD5 );
  7929. #endif
  7930. #if defined(MBEDTLS_SHA1_C)
  7931. case MBEDTLS_MD_SHA1:
  7932. return( MBEDTLS_SSL_HASH_SHA1 );
  7933. #endif
  7934. #if defined(MBEDTLS_SHA256_C)
  7935. case MBEDTLS_MD_SHA224:
  7936. return( MBEDTLS_SSL_HASH_SHA224 );
  7937. case MBEDTLS_MD_SHA256:
  7938. return( MBEDTLS_SSL_HASH_SHA256 );
  7939. #endif
  7940. #if defined(MBEDTLS_SHA512_C)
  7941. case MBEDTLS_MD_SHA384:
  7942. return( MBEDTLS_SSL_HASH_SHA384 );
  7943. case MBEDTLS_MD_SHA512:
  7944. return( MBEDTLS_SSL_HASH_SHA512 );
  7945. #endif
  7946. default:
  7947. return( MBEDTLS_SSL_HASH_NONE );
  7948. }
  7949. }
  7950. #if defined(MBEDTLS_ECP_C)
  7951. /*
  7952. * Check if a curve proposed by the peer is in our list.
  7953. * Return 0 if we're willing to use it, -1 otherwise.
  7954. */
  7955. int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id )
  7956. {
  7957. const mbedtls_ecp_group_id *gid;
  7958. if( ssl->conf->curve_list == NULL )
  7959. return( -1 );
  7960. for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )
  7961. if( *gid == grp_id )
  7962. return( 0 );
  7963. return( -1 );
  7964. }
  7965. #endif /* MBEDTLS_ECP_C */
  7966. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  7967. /*
  7968. * Check if a hash proposed by the peer is in our list.
  7969. * Return 0 if we're willing to use it, -1 otherwise.
  7970. */
  7971. int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl,
  7972. mbedtls_md_type_t md )
  7973. {
  7974. const int *cur;
  7975. if( ssl->conf->sig_hashes == NULL )
  7976. return( -1 );
  7977. for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )
  7978. if( *cur == (int) md )
  7979. return( 0 );
  7980. return( -1 );
  7981. }
  7982. #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
  7983. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7984. int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert,
  7985. const mbedtls_ssl_ciphersuite_t *ciphersuite,
  7986. int cert_endpoint,
  7987. uint32_t *flags )
  7988. {
  7989. int ret = 0;
  7990. #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
  7991. int usage = 0;
  7992. #endif
  7993. #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
  7994. const char *ext_oid;
  7995. size_t ext_len;
  7996. #endif
  7997. #if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) && \
  7998. !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
  7999. ((void) cert);
  8000. ((void) cert_endpoint);
  8001. ((void) flags);
  8002. #endif
  8003. #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
  8004. if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
  8005. {
  8006. /* Server part of the key exchange */
  8007. switch( ciphersuite->key_exchange )
  8008. {
  8009. case MBEDTLS_KEY_EXCHANGE_RSA:
  8010. case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
  8011. usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
  8012. break;
  8013. case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
  8014. case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
  8015. case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
  8016. usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
  8017. break;
  8018. case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
  8019. case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
  8020. usage = MBEDTLS_X509_KU_KEY_AGREEMENT;
  8021. break;
  8022. /* Don't use default: we want warnings when adding new values */
  8023. case MBEDTLS_KEY_EXCHANGE_NONE:
  8024. case MBEDTLS_KEY_EXCHANGE_PSK:
  8025. case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
  8026. case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
  8027. case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
  8028. usage = 0;
  8029. }
  8030. }
  8031. else
  8032. {
  8033. /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */
  8034. usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
  8035. }
  8036. if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 )
  8037. {
  8038. *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE;
  8039. ret = -1;
  8040. }
  8041. #else
  8042. ((void) ciphersuite);
  8043. #endif /* MBEDTLS_X509_CHECK_KEY_USAGE */
  8044. #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
  8045. if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
  8046. {
  8047. ext_oid = MBEDTLS_OID_SERVER_AUTH;
  8048. ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH );
  8049. }
  8050. else
  8051. {
  8052. ext_oid = MBEDTLS_OID_CLIENT_AUTH;
  8053. ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH );
  8054. }
  8055. if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 )
  8056. {
  8057. *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE;
  8058. ret = -1;
  8059. }
  8060. #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
  8061. return( ret );
  8062. }
  8063. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  8064. /*
  8065. * Convert version numbers to/from wire format
  8066. * and, for DTLS, to/from TLS equivalent.
  8067. *
  8068. * For TLS this is the identity.
  8069. * For DTLS, use 1's complement (v -> 255 - v, and then map as follows:
  8070. * 1.0 <-> 3.2 (DTLS 1.0 is based on TLS 1.1)
  8071. * 1.x <-> 3.x+1 for x != 0 (DTLS 1.2 based on TLS 1.2)
  8072. */
  8073. void mbedtls_ssl_write_version( int major, int minor, int transport,
  8074. unsigned char ver[2] )
  8075. {
  8076. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  8077. if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  8078. {
  8079. if( minor == MBEDTLS_SSL_MINOR_VERSION_2 )
  8080. --minor; /* DTLS 1.0 stored as TLS 1.1 internally */
  8081. ver[0] = (unsigned char)( 255 - ( major - 2 ) );
  8082. ver[1] = (unsigned char)( 255 - ( minor - 1 ) );
  8083. }
  8084. else
  8085. #else
  8086. ((void) transport);
  8087. #endif
  8088. {
  8089. ver[0] = (unsigned char) major;
  8090. ver[1] = (unsigned char) minor;
  8091. }
  8092. }
  8093. void mbedtls_ssl_read_version( int *major, int *minor, int transport,
  8094. const unsigned char ver[2] )
  8095. {
  8096. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  8097. if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  8098. {
  8099. *major = 255 - ver[0] + 2;
  8100. *minor = 255 - ver[1] + 1;
  8101. if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 )
  8102. ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */
  8103. }
  8104. else
  8105. #else
  8106. ((void) transport);
  8107. #endif
  8108. {
  8109. *major = ver[0];
  8110. *minor = ver[1];
  8111. }
  8112. }
  8113. int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md )
  8114. {
  8115. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  8116. if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
  8117. return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
  8118. switch( md )
  8119. {
  8120. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  8121. #if defined(MBEDTLS_MD5_C)
  8122. case MBEDTLS_SSL_HASH_MD5:
  8123. return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
  8124. #endif
  8125. #if defined(MBEDTLS_SHA1_C)
  8126. case MBEDTLS_SSL_HASH_SHA1:
  8127. ssl->handshake->calc_verify = ssl_calc_verify_tls;
  8128. break;
  8129. #endif
  8130. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
  8131. #if defined(MBEDTLS_SHA512_C)
  8132. case MBEDTLS_SSL_HASH_SHA384:
  8133. ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384;
  8134. break;
  8135. #endif
  8136. #if defined(MBEDTLS_SHA256_C)
  8137. case MBEDTLS_SSL_HASH_SHA256:
  8138. ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256;
  8139. break;
  8140. #endif
  8141. default:
  8142. return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
  8143. }
  8144. return 0;
  8145. #else /* !MBEDTLS_SSL_PROTO_TLS1_2 */
  8146. (void) ssl;
  8147. (void) md;
  8148. return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
  8149. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  8150. }
  8151. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  8152. defined(MBEDTLS_SSL_PROTO_TLS1_1)
  8153. int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl,
  8154. unsigned char *output,
  8155. unsigned char *data, size_t data_len )
  8156. {
  8157. int ret = 0;
  8158. mbedtls_md5_context mbedtls_md5;
  8159. mbedtls_sha1_context mbedtls_sha1;
  8160. mbedtls_md5_init( &mbedtls_md5 );
  8161. mbedtls_sha1_init( &mbedtls_sha1 );
  8162. /*
  8163. * digitally-signed struct {
  8164. * opaque md5_hash[16];
  8165. * opaque sha_hash[20];
  8166. * };
  8167. *
  8168. * md5_hash
  8169. * MD5(ClientHello.random + ServerHello.random
  8170. * + ServerParams);
  8171. * sha_hash
  8172. * SHA(ClientHello.random + ServerHello.random
  8173. * + ServerParams);
  8174. */
  8175. if( ( ret = mbedtls_md5_starts_ret( &mbedtls_md5 ) ) != 0 )
  8176. {
  8177. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_starts_ret", ret );
  8178. goto exit;
  8179. }
  8180. if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5,
  8181. ssl->handshake->randbytes, 64 ) ) != 0 )
  8182. {
  8183. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret );
  8184. goto exit;
  8185. }
  8186. if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5, data, data_len ) ) != 0 )
  8187. {
  8188. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret );
  8189. goto exit;
  8190. }
  8191. if( ( ret = mbedtls_md5_finish_ret( &mbedtls_md5, output ) ) != 0 )
  8192. {
  8193. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_finish_ret", ret );
  8194. goto exit;
  8195. }
  8196. if( ( ret = mbedtls_sha1_starts_ret( &mbedtls_sha1 ) ) != 0 )
  8197. {
  8198. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_starts_ret", ret );
  8199. goto exit;
  8200. }
  8201. if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1,
  8202. ssl->handshake->randbytes, 64 ) ) != 0 )
  8203. {
  8204. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret );
  8205. goto exit;
  8206. }
  8207. if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1, data,
  8208. data_len ) ) != 0 )
  8209. {
  8210. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret );
  8211. goto exit;
  8212. }
  8213. if( ( ret = mbedtls_sha1_finish_ret( &mbedtls_sha1,
  8214. output + 16 ) ) != 0 )
  8215. {
  8216. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_finish_ret", ret );
  8217. goto exit;
  8218. }
  8219. exit:
  8220. mbedtls_md5_free( &mbedtls_md5 );
  8221. mbedtls_sha1_free( &mbedtls_sha1 );
  8222. if( ret != 0 )
  8223. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  8224. MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
  8225. return( ret );
  8226. }
  8227. #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
  8228. MBEDTLS_SSL_PROTO_TLS1_1 */
  8229. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  8230. defined(MBEDTLS_SSL_PROTO_TLS1_2)
  8231. int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
  8232. unsigned char *hash, size_t *hashlen,
  8233. unsigned char *data, size_t data_len,
  8234. mbedtls_md_type_t md_alg )
  8235. {
  8236. int ret = 0;
  8237. mbedtls_md_context_t ctx;
  8238. const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
  8239. *hashlen = mbedtls_md_get_size( md_info );
  8240. mbedtls_md_init( &ctx );
  8241. /*
  8242. * digitally-signed struct {
  8243. * opaque client_random[32];
  8244. * opaque server_random[32];
  8245. * ServerDHParams params;
  8246. * };
  8247. */
  8248. if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 )
  8249. {
  8250. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
  8251. goto exit;
  8252. }
  8253. if( ( ret = mbedtls_md_starts( &ctx ) ) != 0 )
  8254. {
  8255. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_starts", ret );
  8256. goto exit;
  8257. }
  8258. if( ( ret = mbedtls_md_update( &ctx, ssl->handshake->randbytes, 64 ) ) != 0 )
  8259. {
  8260. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
  8261. goto exit;
  8262. }
  8263. if( ( ret = mbedtls_md_update( &ctx, data, data_len ) ) != 0 )
  8264. {
  8265. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
  8266. goto exit;
  8267. }
  8268. if( ( ret = mbedtls_md_finish( &ctx, hash ) ) != 0 )
  8269. {
  8270. MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_finish", ret );
  8271. goto exit;
  8272. }
  8273. exit:
  8274. mbedtls_md_free( &ctx );
  8275. if( ret != 0 )
  8276. mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  8277. MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
  8278. return( ret );
  8279. }
  8280. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
  8281. MBEDTLS_SSL_PROTO_TLS1_2 */
  8282. #endif /* MBEDTLS_SSL_TLS_C */