ssl_msg.c 183 KB

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