ssl_tls.c 315 KB

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