ssl_msg.c 205 KB

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