tls13.c 403 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503
  1. /* tls13.c
  2. *
  3. * Copyright (C) 2006-2022 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. /*
  22. * BUILD_GCM
  23. * Enables AES-GCM ciphersuites.
  24. * HAVE_AESCCM
  25. * Enables AES-CCM ciphersuites.
  26. * HAVE_SESSION_TICKET
  27. * Enables session tickets - required for TLS 1.3 resumption.
  28. * NO_PSK
  29. * Do not enable Pre-Shared Keys.
  30. * HAVE_KEYING_MATERIAL
  31. * Enables exporting keying material based on section 7.5 of RFC 8446.
  32. * WOLFSSL_ASYNC_CRYPT
  33. * Enables the use of asynchronous cryptographic operations.
  34. * This is available for ciphers and certificates.
  35. * HAVE_CHACHA && HAVE_POLY1305
  36. * Enables use of CHACHA20-POLY1305 ciphersuites.
  37. * WOLFSSL_DEBUG_TLS
  38. * Writes out details of TLS 1.3 protocol including handshake message buffers
  39. * and key generation input and output.
  40. * WOLFSSL_EARLY_DATA
  41. * Allow 0-RTT Handshake using Early Data extensions and handshake message
  42. * WOLFSSL_EARLY_DATA_GROUP
  43. * Group EarlyData message with ClientHello when sending
  44. * WOLFSSL_NO_SERVER_GROUPS_EXT
  45. * Do not send the server's groups in an extension when the server's top
  46. * preference is not in client's list.
  47. * WOLFSSL_POST_HANDSHAKE_AUTH
  48. * Allow TLS v1.3 code to perform post-handshake authentication of the
  49. * client.
  50. * WOLFSSL_SEND_HRR_COOKIE
  51. * Send a cookie in hello_retry_request message to enable stateless tracking
  52. * of ClientHello replies.
  53. * WOLFSSL_TLS13
  54. * Enable TLS 1.3 protocol implementation.
  55. * WOLFSSL_TLS13_MIDDLEBOX_COMPAT
  56. * Enable middlebox compatibility in the TLS 1.3 handshake.
  57. * This includes sending ChangeCipherSpec before encrypted messages and
  58. * including a session id.
  59. * WOLFSSL_TLS13_SHA512
  60. * Allow generation of SHA-512 digests in handshake - no ciphersuite
  61. * requires SHA-512 at this time.
  62. * WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
  63. * Allow a NewSessionTicket message to be sent by server before Client's
  64. * Finished message.
  65. * See TLS v1.3 specification, Section 4.6.1, Paragraph 4 (Note).
  66. * WOLFSSL_PSK_ONE_ID
  67. * When only one PSK ID is used and only one call to the PSK callback can
  68. * be made per connect.
  69. * You cannot use wc_psk_client_cs_callback type callback on client.
  70. * WOLFSSL_CHECK_ALERT_ON_ERR
  71. * Check for alerts during the handshake in the event of an error.
  72. * WOLFSSL_NO_CLIENT_CERT_ERROR
  73. * Requires client to set a client certificate
  74. * WOLFSSL_PSK_MULTI_ID_PER_CS
  75. * When multiple PSK identities are available for the same cipher suite.
  76. * Sets the first byte of the client identity to the count of identites
  77. * that have been seen so far for the cipher suite.
  78. * WOLFSSL_CHECK_SIG_FAULTS
  79. * Verifies the ECC signature after signing in case of faults in the
  80. * calculation of the signature. Useful when signature fault injection is a
  81. * possible attack.
  82. * WOLFSSL_32BIT_MILLI_TIME
  83. * Function TimeNowInMilliseconds() returns an unsigned 32-bit value.
  84. * Default behavior is to return a signed 64-bit value.
  85. */
  86. #ifdef HAVE_CONFIG_H
  87. #include <config.h>
  88. #endif
  89. #include <wolfssl/wolfcrypt/settings.h>
  90. #ifdef WOLFSSL_TLS13
  91. #ifdef HAVE_SESSION_TICKET
  92. #include <wolfssl/wolfcrypt/wc_port.h>
  93. #endif
  94. #ifndef WOLFCRYPT_ONLY
  95. #ifdef HAVE_ERRNO_H
  96. #include <errno.h>
  97. #endif
  98. #if defined(__MACH__) || defined(__FreeBSD__)
  99. #include <sys/time.h>
  100. #endif /* __MACH__ || __FreeBSD__ */
  101. #include <wolfssl/internal.h>
  102. #include <wolfssl/error-ssl.h>
  103. #include <wolfssl/wolfcrypt/asn.h>
  104. #include <wolfssl/wolfcrypt/dh.h>
  105. #include <wolfssl/wolfcrypt/kdf.h>
  106. #ifdef NO_INLINE
  107. #include <wolfssl/wolfcrypt/misc.h>
  108. #else
  109. #define WOLFSSL_MISC_INCLUDED
  110. #include <wolfcrypt/src/misc.c>
  111. #endif
  112. #ifdef __sun
  113. #include <sys/filio.h>
  114. #endif
  115. #ifndef TRUE
  116. #define TRUE 1
  117. #endif
  118. #ifndef FALSE
  119. #define FALSE 0
  120. #endif
  121. #ifndef HAVE_HKDF
  122. #ifndef _MSC_VER
  123. #error "The build option HAVE_HKDF is required for TLS 1.3"
  124. #else
  125. #pragma message("error: The build option HAVE_HKDF is required for TLS 1.3")
  126. #endif
  127. #endif
  128. #ifndef HAVE_TLS_EXTENSIONS
  129. #ifndef _MSC_VER
  130. #error "The build option HAVE_TLS_EXTENSIONS is required for TLS 1.3"
  131. #else
  132. #pragma message("error: The build option HAVE_TLS_EXTENSIONS is required for TLS 1.3")
  133. #endif
  134. #endif
  135. /* Set ret to error value and jump to label.
  136. *
  137. * err The error value to set.
  138. * eLabel The label to jump to.
  139. */
  140. #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
  141. /* Size of the TLS v1.3 label use when deriving keys. */
  142. #define TLS13_PROTOCOL_LABEL_SZ 6
  143. /* The protocol label for TLS v1.3. */
  144. static const byte tls13ProtocolLabel[TLS13_PROTOCOL_LABEL_SZ + 1] = "tls13 ";
  145. #ifdef WOLFSSL_DTLS13
  146. #define DTLS13_PROTOCOL_LABEL_SZ 6
  147. static const byte dtls13ProtocolLabel[DTLS13_PROTOCOL_LABEL_SZ + 1] = "dtls13";
  148. #endif /* WOLFSSL_DTLS13 */
  149. /* Derive a key from a message.
  150. *
  151. * ssl The SSL/TLS object.
  152. * output The buffer to hold the derived key.
  153. * outputLen The length of the derived key.
  154. * secret The secret used to derive the key (HMAC secret).
  155. * label The label used to distinguish the context.
  156. * labelLen The length of the label.
  157. * msg The message data to derive key from.
  158. * msgLen The length of the message data to derive key from.
  159. * hashAlgo The hash algorithm to use in the HMAC.
  160. * returns 0 on success, otherwise failure.
  161. */
  162. static int DeriveKeyMsg(WOLFSSL* ssl, byte* output, int outputLen,
  163. const byte* secret, const byte* label, word32 labelLen,
  164. byte* msg, int msgLen, int hashAlgo)
  165. {
  166. byte hash[WC_MAX_DIGEST_SIZE];
  167. Digest digest;
  168. word32 hashSz = 0;
  169. const byte* protocol;
  170. word32 protocolLen;
  171. int digestAlg = -1;
  172. int ret = BAD_FUNC_ARG;
  173. switch (hashAlgo) {
  174. #ifndef NO_WOLFSSL_SHA256
  175. case sha256_mac:
  176. ret = wc_InitSha256_ex(&digest.sha256, ssl->heap, INVALID_DEVID);
  177. if (ret == 0) {
  178. ret = wc_Sha256Update(&digest.sha256, msg, msgLen);
  179. if (ret == 0)
  180. ret = wc_Sha256Final(&digest.sha256, hash);
  181. wc_Sha256Free(&digest.sha256);
  182. }
  183. hashSz = WC_SHA256_DIGEST_SIZE;
  184. digestAlg = WC_SHA256;
  185. break;
  186. #endif
  187. #ifdef WOLFSSL_SHA384
  188. case sha384_mac:
  189. ret = wc_InitSha384_ex(&digest.sha384, ssl->heap, INVALID_DEVID);
  190. if (ret == 0) {
  191. ret = wc_Sha384Update(&digest.sha384, msg, msgLen);
  192. if (ret == 0)
  193. ret = wc_Sha384Final(&digest.sha384, hash);
  194. wc_Sha384Free(&digest.sha384);
  195. }
  196. hashSz = WC_SHA384_DIGEST_SIZE;
  197. digestAlg = WC_SHA384;
  198. break;
  199. #endif
  200. #ifdef WOLFSSL_TLS13_SHA512
  201. case sha512_mac:
  202. ret = wc_InitSha512_ex(&digest.sha512, ssl->heap, INVALID_DEVID);
  203. if (ret == 0) {
  204. ret = wc_Sha512Update(&digest.sha512, msg, msgLen);
  205. if (ret == 0)
  206. ret = wc_Sha512Final(&digest.sha512, hash);
  207. wc_Sha512Free(&digest.sha512);
  208. }
  209. hashSz = WC_SHA512_DIGEST_SIZE;
  210. digestAlg = WC_SHA512;
  211. break;
  212. #endif
  213. default:
  214. digestAlg = -1;
  215. break;
  216. }
  217. if (digestAlg < 0)
  218. return HASH_TYPE_E;
  219. if (ret != 0)
  220. return ret;
  221. switch (ssl->version.minor) {
  222. case TLSv1_3_MINOR:
  223. protocol = tls13ProtocolLabel;
  224. protocolLen = TLS13_PROTOCOL_LABEL_SZ;
  225. break;
  226. #ifdef WOLFSSL_DTLS13
  227. case DTLSv1_3_MINOR:
  228. if (!ssl->options.dtls)
  229. return VERSION_ERROR;
  230. protocol = dtls13ProtocolLabel;
  231. protocolLen = DTLS13_PROTOCOL_LABEL_SZ;
  232. break;
  233. #endif /* WOLFSSL_DTLS13 */
  234. default:
  235. return VERSION_ERROR;
  236. }
  237. if (outputLen == -1)
  238. outputLen = hashSz;
  239. PRIVATE_KEY_UNLOCK();
  240. ret = wc_Tls13_HKDF_Expand_Label(output, outputLen, secret, hashSz,
  241. protocol, protocolLen, label, labelLen,
  242. hash, hashSz, digestAlg);
  243. PRIVATE_KEY_LOCK();
  244. return ret;
  245. }
  246. /* Derive a key.
  247. *
  248. * ssl The SSL/TLS object.
  249. * output The buffer to hold the derived key.
  250. * outputLen The length of the derived key.
  251. * secret The secret used to derive the key (HMAC secret).
  252. * label The label used to distinguish the context.
  253. * labelLen The length of the label.
  254. * hashAlgo The hash algorithm to use in the HMAC.
  255. * includeMsgs Whether to include a hash of the handshake messages so far.
  256. * returns 0 on success, otherwise failure.
  257. */
  258. int Tls13DeriveKey(WOLFSSL* ssl, byte* output, int outputLen,
  259. const byte* secret, const byte* label, word32 labelLen,
  260. int hashAlgo, int includeMsgs)
  261. {
  262. int ret = 0;
  263. byte hash[WC_MAX_DIGEST_SIZE];
  264. word32 hashSz = 0;
  265. word32 hashOutSz = 0;
  266. const byte* protocol;
  267. word32 protocolLen;
  268. int digestAlg = 0;
  269. switch (hashAlgo) {
  270. #ifndef NO_SHA256
  271. case sha256_mac:
  272. hashSz = WC_SHA256_DIGEST_SIZE;
  273. digestAlg = WC_SHA256;
  274. if (includeMsgs)
  275. ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
  276. break;
  277. #endif
  278. #ifdef WOLFSSL_SHA384
  279. case sha384_mac:
  280. hashSz = WC_SHA384_DIGEST_SIZE;
  281. digestAlg = WC_SHA384;
  282. if (includeMsgs)
  283. ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
  284. break;
  285. #endif
  286. #ifdef WOLFSSL_TLS13_SHA512
  287. case sha512_mac:
  288. hashSz = WC_SHA512_DIGEST_SIZE;
  289. digestAlg = WC_SHA512;
  290. if (includeMsgs)
  291. ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
  292. break;
  293. #endif
  294. default:
  295. ret = HASH_TYPE_E;
  296. break;
  297. }
  298. if (ret != 0)
  299. return ret;
  300. protocol = tls13ProtocolLabel;
  301. protocolLen = TLS13_PROTOCOL_LABEL_SZ;
  302. #ifdef WOLFSSL_DTLS13
  303. if (ssl->options.dtls) {
  304. protocol = dtls13ProtocolLabel;
  305. protocolLen = DTLS13_PROTOCOL_LABEL_SZ;
  306. }
  307. #endif /* WOLFSSL_DTLS13 */
  308. if (outputLen == -1)
  309. outputLen = hashSz;
  310. if (includeMsgs)
  311. hashOutSz = hashSz;
  312. /* hash buffer may not be fully initialized, but the sending length won't
  313. * extend beyond the initialized span.
  314. */
  315. PRAGMA_GCC_DIAG_PUSH;
  316. PRAGMA_GCC("GCC diagnostic ignored \"-Wmaybe-uninitialized\"");
  317. PRIVATE_KEY_UNLOCK();
  318. #if defined(HAVE_FIPS) && defined(wc_Tls13_HKDF_Expand_Label)
  319. ret = wc_Tls13_HKDF_Expand_Label_fips(output, outputLen, secret, hashSz,
  320. protocol, protocolLen, label, labelLen,
  321. hash, hashOutSz, digestAlg);
  322. #else
  323. ret = wc_Tls13_HKDF_Expand_Label(output, outputLen, secret, hashSz,
  324. protocol, protocolLen, label, labelLen,
  325. hash, hashOutSz, digestAlg);
  326. #endif
  327. PRIVATE_KEY_LOCK();
  328. #ifdef WOLFSSL_CHECK_MEM_ZERO
  329. wc_MemZero_Add("TLS 1.3 derived key", output, outputLen);
  330. #endif
  331. return ret;
  332. PRAGMA_GCC_DIAG_POP;
  333. }
  334. /* Convert TLS mac ID to a hash algorithm ID
  335. *
  336. * mac Mac ID to convert
  337. * returns hash ID on success, or the NONE type.
  338. */
  339. static WC_INLINE int mac2hash(int mac)
  340. {
  341. int hash;
  342. switch (mac) {
  343. #ifndef NO_SHA256
  344. case sha256_mac:
  345. hash = WC_SHA256;
  346. break;
  347. #endif
  348. #ifdef WOLFSSL_SHA384
  349. case sha384_mac:
  350. hash = WC_SHA384;
  351. break;
  352. #endif
  353. #ifdef WOLFSSL_TLS13_SHA512
  354. case sha512_mac:
  355. hash = WC_SHA512;
  356. break;
  357. #endif
  358. default:
  359. hash = WC_HASH_TYPE_NONE;
  360. }
  361. return hash;
  362. }
  363. #ifndef NO_PSK
  364. /* The length of the binder key label. */
  365. #define BINDER_KEY_LABEL_SZ 10
  366. /* The binder key label. */
  367. static const byte binderKeyLabel[BINDER_KEY_LABEL_SZ + 1] =
  368. "ext binder";
  369. /* Derive the binder key.
  370. *
  371. * ssl The SSL/TLS object.
  372. * key The derived key.
  373. * returns 0 on success, otherwise failure.
  374. */
  375. static int DeriveBinderKey(WOLFSSL* ssl, byte* key)
  376. {
  377. WOLFSSL_MSG("Derive Binder Key");
  378. if (ssl == NULL || ssl->arrays == NULL) {
  379. return BAD_FUNC_ARG;
  380. }
  381. return DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
  382. binderKeyLabel, BINDER_KEY_LABEL_SZ,
  383. NULL, 0, ssl->specs.mac_algorithm);
  384. }
  385. #endif /* !NO_PSK */
  386. #if defined(HAVE_SESSION_TICKET) && \
  387. (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER))
  388. /* The length of the binder key resume label. */
  389. #define BINDER_KEY_RESUME_LABEL_SZ 10
  390. /* The binder key resume label. */
  391. static const byte binderKeyResumeLabel[BINDER_KEY_RESUME_LABEL_SZ + 1] =
  392. "res binder";
  393. /* Derive the binder resumption key.
  394. *
  395. * ssl The SSL/TLS object.
  396. * key The derived key.
  397. * returns 0 on success, otherwise failure.
  398. */
  399. static int DeriveBinderKeyResume(WOLFSSL* ssl, byte* key)
  400. {
  401. WOLFSSL_MSG("Derive Binder Key - Resumption");
  402. if (ssl == NULL || ssl->arrays == NULL) {
  403. return BAD_FUNC_ARG;
  404. }
  405. return DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
  406. binderKeyResumeLabel, BINDER_KEY_RESUME_LABEL_SZ,
  407. NULL, 0, ssl->specs.mac_algorithm);
  408. }
  409. #endif /* HAVE_SESSION_TICKET && (!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) */
  410. #ifdef WOLFSSL_EARLY_DATA
  411. /* The length of the early traffic label. */
  412. #define EARLY_TRAFFIC_LABEL_SZ 11
  413. /* The early traffic label. */
  414. static const byte earlyTrafficLabel[EARLY_TRAFFIC_LABEL_SZ + 1] =
  415. "c e traffic";
  416. /* Derive the early traffic key.
  417. *
  418. * ssl The SSL/TLS object.
  419. * key The derived key.
  420. * returns 0 on success, otherwise failure.
  421. */
  422. static int DeriveEarlyTrafficSecret(WOLFSSL* ssl, byte* key)
  423. {
  424. int ret;
  425. WOLFSSL_MSG("Derive Early Traffic Secret");
  426. if (ssl == NULL || ssl->arrays == NULL) {
  427. return BAD_FUNC_ARG;
  428. }
  429. ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->secret,
  430. earlyTrafficLabel, EARLY_TRAFFIC_LABEL_SZ,
  431. ssl->specs.mac_algorithm, 1);
  432. #ifdef HAVE_SECRET_CALLBACK
  433. if (ret == 0 && ssl->tls13SecretCb != NULL) {
  434. ret = ssl->tls13SecretCb(ssl, CLIENT_EARLY_TRAFFIC_SECRET, key,
  435. ssl->specs.hash_size, ssl->tls13SecretCtx);
  436. if (ret != 0) {
  437. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  438. return TLS13_SECRET_CB_E;
  439. }
  440. }
  441. #ifdef OPENSSL_EXTRA
  442. if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
  443. ret = ssl->tls13KeyLogCb(ssl, CLIENT_EARLY_TRAFFIC_SECRET, key,
  444. ssl->specs.hash_size, NULL);
  445. if (ret != 0) {
  446. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  447. return TLS13_SECRET_CB_E;
  448. }
  449. }
  450. #endif /* OPENSSL_EXTRA */
  451. #endif /* HAVE_SECRET_CALLBACK */
  452. return ret;
  453. }
  454. #endif
  455. /* The length of the client handshake label. */
  456. #define CLIENT_HANDSHAKE_LABEL_SZ 12
  457. /* The client handshake label. */
  458. static const byte clientHandshakeLabel[CLIENT_HANDSHAKE_LABEL_SZ + 1] =
  459. "c hs traffic";
  460. /* Derive the client handshake key.
  461. *
  462. * ssl The SSL/TLS object.
  463. * key The derived key.
  464. * returns 0 on success, otherwise failure.
  465. */
  466. static int DeriveClientHandshakeSecret(WOLFSSL* ssl, byte* key)
  467. {
  468. int ret;
  469. WOLFSSL_MSG("Derive Client Handshake Secret");
  470. if (ssl == NULL || ssl->arrays == NULL) {
  471. return BAD_FUNC_ARG;
  472. }
  473. ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->preMasterSecret,
  474. clientHandshakeLabel, CLIENT_HANDSHAKE_LABEL_SZ,
  475. ssl->specs.mac_algorithm, 1);
  476. #ifdef HAVE_SECRET_CALLBACK
  477. if (ret == 0 && ssl->tls13SecretCb != NULL) {
  478. ret = ssl->tls13SecretCb(ssl, CLIENT_HANDSHAKE_TRAFFIC_SECRET, key,
  479. ssl->specs.hash_size, ssl->tls13SecretCtx);
  480. if (ret != 0) {
  481. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  482. return TLS13_SECRET_CB_E;
  483. }
  484. }
  485. #ifdef OPENSSL_EXTRA
  486. if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
  487. ret = ssl->tls13KeyLogCb(ssl, CLIENT_HANDSHAKE_TRAFFIC_SECRET, key,
  488. ssl->specs.hash_size, NULL);
  489. if (ret != 0) {
  490. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  491. return TLS13_SECRET_CB_E;
  492. }
  493. }
  494. #endif /* OPENSSL_EXTRA */
  495. #endif /* HAVE_SECRET_CALLBACK */
  496. return ret;
  497. }
  498. /* The length of the server handshake label. */
  499. #define SERVER_HANDSHAKE_LABEL_SZ 12
  500. /* The server handshake label. */
  501. static const byte serverHandshakeLabel[SERVER_HANDSHAKE_LABEL_SZ + 1] =
  502. "s hs traffic";
  503. /* Derive the server handshake key.
  504. *
  505. * ssl The SSL/TLS object.
  506. * key The derived key.
  507. * returns 0 on success, otherwise failure.
  508. */
  509. static int DeriveServerHandshakeSecret(WOLFSSL* ssl, byte* key)
  510. {
  511. int ret;
  512. WOLFSSL_MSG("Derive Server Handshake Secret");
  513. if (ssl == NULL || ssl->arrays == NULL) {
  514. return BAD_FUNC_ARG;
  515. }
  516. ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->preMasterSecret,
  517. serverHandshakeLabel, SERVER_HANDSHAKE_LABEL_SZ,
  518. ssl->specs.mac_algorithm, 1);
  519. #ifdef HAVE_SECRET_CALLBACK
  520. if (ret == 0 && ssl->tls13SecretCb != NULL) {
  521. ret = ssl->tls13SecretCb(ssl, SERVER_HANDSHAKE_TRAFFIC_SECRET, key,
  522. ssl->specs.hash_size, ssl->tls13SecretCtx);
  523. if (ret != 0) {
  524. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  525. return TLS13_SECRET_CB_E;
  526. }
  527. }
  528. #ifdef OPENSSL_EXTRA
  529. if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
  530. ret = ssl->tls13KeyLogCb(ssl, SERVER_HANDSHAKE_TRAFFIC_SECRET, key,
  531. ssl->specs.hash_size, NULL);
  532. if (ret != 0) {
  533. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  534. return TLS13_SECRET_CB_E;
  535. }
  536. }
  537. #endif /* OPENSSL_EXTRA */
  538. #endif /* HAVE_SECRET_CALLBACK */
  539. return ret;
  540. }
  541. /* The length of the client application traffic label. */
  542. #define CLIENT_APP_LABEL_SZ 12
  543. /* The client application traffic label. */
  544. static const byte clientAppLabel[CLIENT_APP_LABEL_SZ + 1] =
  545. "c ap traffic";
  546. /* Derive the client application traffic key.
  547. *
  548. * ssl The SSL/TLS object.
  549. * key The derived key.
  550. * returns 0 on success, otherwise failure.
  551. */
  552. static int DeriveClientTrafficSecret(WOLFSSL* ssl, byte* key)
  553. {
  554. int ret;
  555. WOLFSSL_MSG("Derive Client Traffic Secret");
  556. if (ssl == NULL || ssl->arrays == NULL) {
  557. return BAD_FUNC_ARG;
  558. }
  559. ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
  560. clientAppLabel, CLIENT_APP_LABEL_SZ,
  561. ssl->specs.mac_algorithm, 1);
  562. #ifdef HAVE_SECRET_CALLBACK
  563. if (ret == 0 && ssl->tls13SecretCb != NULL) {
  564. ret = ssl->tls13SecretCb(ssl, CLIENT_TRAFFIC_SECRET, key,
  565. ssl->specs.hash_size, ssl->tls13SecretCtx);
  566. if (ret != 0) {
  567. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  568. return TLS13_SECRET_CB_E;
  569. }
  570. }
  571. #ifdef OPENSSL_EXTRA
  572. if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
  573. ret = ssl->tls13KeyLogCb(ssl, CLIENT_TRAFFIC_SECRET, key,
  574. ssl->specs.hash_size, NULL);
  575. if (ret != 0) {
  576. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  577. return TLS13_SECRET_CB_E;
  578. }
  579. }
  580. #endif /* OPENSSL_EXTRA */
  581. #endif /* HAVE_SECRET_CALLBACK */
  582. return ret;
  583. }
  584. /* The length of the server application traffic label. */
  585. #define SERVER_APP_LABEL_SZ 12
  586. /* The server application traffic label. */
  587. static const byte serverAppLabel[SERVER_APP_LABEL_SZ + 1] =
  588. "s ap traffic";
  589. /* Derive the server application traffic key.
  590. *
  591. * ssl The SSL/TLS object.
  592. * key The derived key.
  593. * returns 0 on success, otherwise failure.
  594. */
  595. static int DeriveServerTrafficSecret(WOLFSSL* ssl, byte* key)
  596. {
  597. int ret;
  598. WOLFSSL_MSG("Derive Server Traffic Secret");
  599. if (ssl == NULL || ssl->arrays == NULL) {
  600. return BAD_FUNC_ARG;
  601. }
  602. ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
  603. serverAppLabel, SERVER_APP_LABEL_SZ,
  604. ssl->specs.mac_algorithm, 1);
  605. #ifdef HAVE_SECRET_CALLBACK
  606. if (ret == 0 && ssl->tls13SecretCb != NULL) {
  607. ret = ssl->tls13SecretCb(ssl, SERVER_TRAFFIC_SECRET, key,
  608. ssl->specs.hash_size, ssl->tls13SecretCtx);
  609. if (ret != 0) {
  610. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  611. return TLS13_SECRET_CB_E;
  612. }
  613. }
  614. #ifdef OPENSSL_EXTRA
  615. if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
  616. ret = ssl->tls13KeyLogCb(ssl, SERVER_TRAFFIC_SECRET, key,
  617. ssl->specs.hash_size, NULL);
  618. if (ret != 0) {
  619. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  620. return TLS13_SECRET_CB_E;
  621. }
  622. }
  623. #endif /* OPENSSL_EXTRA */
  624. #endif /* HAVE_SECRET_CALLBACK */
  625. return ret;
  626. }
  627. #ifdef HAVE_KEYING_MATERIAL
  628. /* The length of the exporter master secret label. */
  629. #define EXPORTER_MASTER_LABEL_SZ 10
  630. /* The exporter master secret label. */
  631. static const byte exporterMasterLabel[EXPORTER_MASTER_LABEL_SZ + 1] =
  632. "exp master";
  633. /* Derive the exporter secret.
  634. *
  635. * ssl The SSL/TLS object.
  636. * key The derived key.
  637. * returns 0 on success, otherwise failure.
  638. */
  639. static int DeriveExporterSecret(WOLFSSL* ssl, byte* key)
  640. {
  641. int ret;
  642. WOLFSSL_ENTER("Derive Exporter Secret");
  643. if (ssl == NULL || ssl->arrays == NULL) {
  644. return BAD_FUNC_ARG;
  645. }
  646. ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
  647. exporterMasterLabel, EXPORTER_MASTER_LABEL_SZ,
  648. ssl->specs.mac_algorithm, 1);
  649. #ifdef HAVE_SECRET_CALLBACK
  650. if (ret == 0 && ssl->tls13SecretCb != NULL) {
  651. ret = ssl->tls13SecretCb(ssl, EXPORTER_SECRET, key,
  652. ssl->specs.hash_size, ssl->tls13SecretCtx);
  653. if (ret != 0) {
  654. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  655. return TLS13_SECRET_CB_E;
  656. }
  657. }
  658. #ifdef OPENSSL_EXTRA
  659. if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
  660. ret = ssl->tls13KeyLogCb(ssl, EXPORTER_SECRET, key,
  661. ssl->specs.hash_size, NULL);
  662. if (ret != 0) {
  663. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  664. return TLS13_SECRET_CB_E;
  665. }
  666. }
  667. #endif /* OPENSSL_EXTRA */
  668. #endif /* HAVE_SECRET_CALLBACK */
  669. return ret;
  670. }
  671. /* The length of the exporter label. */
  672. #define EXPORTER_LABEL_SZ 8
  673. /* The exporter label. */
  674. static const byte exporterLabel[EXPORTER_LABEL_SZ + 1] =
  675. "exporter";
  676. /* Hash("") */
  677. #ifndef NO_SHA256
  678. static const byte emptySHA256Hash[] = {
  679. 0xE3, 0xB0, 0xC4, 0x42, 0x98, 0xFC, 0x1C, 0x14, 0x9A, 0xFB, 0xF4, 0xC8,
  680. 0x99, 0x6F, 0xB9, 0x24, 0x27, 0xAE, 0x41, 0xE4, 0x64, 0x9B, 0x93, 0x4C,
  681. 0xA4, 0x95, 0x99, 0x1B, 0x78, 0x52, 0xB8, 0x55
  682. };
  683. #endif
  684. #ifdef WOLFSSL_SHA384
  685. static const byte emptySHA384Hash[] = {
  686. 0x38, 0xB0, 0x60, 0xA7, 0x51, 0xAC, 0x96, 0x38, 0x4C, 0xD9, 0x32, 0x7E,
  687. 0xB1, 0xB1, 0xE3, 0x6A, 0x21, 0xFD, 0xB7, 0x11, 0x14, 0xBE, 0x07, 0x43,
  688. 0x4C, 0x0C, 0xC7, 0xBF, 0x63, 0xF6, 0xE1, 0xDA, 0x27, 0x4E, 0xDE, 0xBF,
  689. 0xE7, 0x6F, 0x65, 0xFB, 0xD5, 0x1A, 0xD2, 0xF1, 0x48, 0x98, 0xB9, 0x5B
  690. };
  691. #endif
  692. #ifdef WOLFSSL_TLS13_SHA512
  693. static const byte emptySHA512Hash[] = {
  694. 0xCF, 0x83, 0xE1, 0x35, 0x7E, 0xEF, 0xB8, 0xBD, 0xF1, 0x54, 0x28, 0x50,
  695. 0xD6, 0x6D, 0x80, 0x07, 0xD6, 0x20, 0xE4, 0x05, 0x0B, 0x57, 0x15, 0xDC,
  696. 0x83, 0xF4, 0xA9, 0x21, 0xD3, 0x6C, 0xE9, 0xCE, 0x47, 0xD0, 0xD1, 0x3C,
  697. 0x5D, 0x85, 0xF2, 0xB0, 0xFF, 0x83, 0x18, 0xD2, 0x87, 0x7E, 0xEC, 0x2F,
  698. 0x63, 0xB9, 0x31, 0xBD, 0x47, 0x41, 0x7A, 0x81, 0xA5, 0x38, 0x32, 0x7A,
  699. 0xF9, 0x27, 0xDA, 0x3E
  700. };
  701. #endif
  702. /**
  703. * Implement section 7.5 of RFC 8446
  704. * @return 0 on success
  705. * <0 on failure
  706. */
  707. int Tls13_Exporter(WOLFSSL* ssl, unsigned char *out, size_t outLen,
  708. const char *label, size_t labelLen,
  709. const unsigned char *context, size_t contextLen)
  710. {
  711. int ret;
  712. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  713. int hashLen = 0;
  714. byte hashOut[WC_MAX_DIGEST_SIZE];
  715. const byte* emptyHash = NULL;
  716. byte firstExpand[WC_MAX_DIGEST_SIZE];
  717. const byte* protocol = tls13ProtocolLabel;
  718. word32 protocolLen = TLS13_PROTOCOL_LABEL_SZ;
  719. if (ssl->version.minor != TLSv1_3_MINOR)
  720. return VERSION_ERROR;
  721. switch (ssl->specs.mac_algorithm) {
  722. #ifndef NO_SHA256
  723. case sha256_mac:
  724. hashType = WC_HASH_TYPE_SHA256;
  725. hashLen = WC_SHA256_DIGEST_SIZE;
  726. emptyHash = emptySHA256Hash;
  727. break;
  728. #endif
  729. #ifdef WOLFSSL_SHA384
  730. case sha384_mac:
  731. hashType = WC_HASH_TYPE_SHA384;
  732. hashLen = WC_SHA384_DIGEST_SIZE;
  733. emptyHash = emptySHA384Hash;
  734. break;
  735. #endif
  736. #ifdef WOLFSSL_TLS13_SHA512
  737. case sha512_mac:
  738. hashType = WC_HASH_TYPE_SHA512;
  739. hashLen = WC_SHA512_DIGEST_SIZE;
  740. emptyHash = emptySHA512Hash;
  741. break;
  742. #endif
  743. }
  744. /* Derive-Secret(Secret, label, "") */
  745. PRIVATE_KEY_UNLOCK();
  746. ret = wc_Tls13_HKDF_Expand_Label(firstExpand, hashLen,
  747. ssl->arrays->exporterSecret, hashLen,
  748. protocol, protocolLen, (byte*)label, (word32)labelLen,
  749. emptyHash, hashLen, hashType);
  750. PRIVATE_KEY_LOCK();
  751. if (ret != 0)
  752. return ret;
  753. /* Hash(context_value) */
  754. ret = wc_Hash(hashType, context, (word32)contextLen, hashOut, WC_MAX_DIGEST_SIZE);
  755. if (ret != 0)
  756. return ret;
  757. PRIVATE_KEY_UNLOCK();
  758. ret = wc_Tls13_HKDF_Expand_Label(out, (word32)outLen, firstExpand, hashLen,
  759. protocol, protocolLen, exporterLabel, EXPORTER_LABEL_SZ,
  760. hashOut, hashLen, hashType);
  761. PRIVATE_KEY_LOCK();
  762. return ret;
  763. }
  764. #endif
  765. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  766. /* The length of the resumption master secret label. */
  767. #define RESUME_MASTER_LABEL_SZ 10
  768. /* The resumption master secret label. */
  769. static const byte resumeMasterLabel[RESUME_MASTER_LABEL_SZ + 1] =
  770. "res master";
  771. /* Derive the resumption secret.
  772. *
  773. * ssl The SSL/TLS object.
  774. * key The derived key.
  775. * returns 0 on success, otherwise failure.
  776. */
  777. int DeriveResumptionSecret(WOLFSSL* ssl, byte* key)
  778. {
  779. byte* masterSecret;
  780. WOLFSSL_MSG("Derive Resumption Secret");
  781. if (ssl == NULL) {
  782. return BAD_FUNC_ARG;
  783. }
  784. if (ssl->arrays != NULL) {
  785. masterSecret = ssl->arrays->masterSecret;
  786. }
  787. else {
  788. masterSecret = ssl->session->masterSecret;
  789. }
  790. return Tls13DeriveKey(ssl, key, -1, masterSecret, resumeMasterLabel,
  791. RESUME_MASTER_LABEL_SZ, ssl->specs.mac_algorithm, 1);
  792. }
  793. #endif
  794. /* Length of the finished label. */
  795. #define FINISHED_LABEL_SZ 8
  796. /* Finished label for generating finished key. */
  797. static const byte finishedLabel[FINISHED_LABEL_SZ+1] = "finished";
  798. /* Derive the finished secret.
  799. *
  800. * ssl The SSL/TLS object.
  801. * key The key to use with the HMAC.
  802. * secret The derived secret.
  803. * returns 0 on success, otherwise failure.
  804. */
  805. static int DeriveFinishedSecret(WOLFSSL* ssl, byte* key, byte* secret)
  806. {
  807. WOLFSSL_MSG("Derive Finished Secret");
  808. return Tls13DeriveKey(ssl, secret, -1, key, finishedLabel, FINISHED_LABEL_SZ,
  809. ssl->specs.mac_algorithm, 0);
  810. }
  811. /* The length of the application traffic label. */
  812. #define APP_TRAFFIC_LABEL_SZ 11
  813. /* The application traffic label. */
  814. static const byte appTrafficLabel[APP_TRAFFIC_LABEL_SZ + 1] =
  815. "traffic upd";
  816. /* Update the traffic secret.
  817. *
  818. * ssl The SSL/TLS object.
  819. * secret The previous secret and derived secret.
  820. * returns 0 on success, otherwise failure.
  821. */
  822. static int DeriveTrafficSecret(WOLFSSL* ssl, byte* secret)
  823. {
  824. WOLFSSL_MSG("Derive New Application Traffic Secret");
  825. return Tls13DeriveKey(ssl, secret, -1, secret,
  826. appTrafficLabel, APP_TRAFFIC_LABEL_SZ,
  827. ssl->specs.mac_algorithm, 0);
  828. }
  829. static int Tls13_HKDF_Extract(WOLFSSL *ssl, byte* prk, const byte* salt, int saltLen,
  830. byte* ikm, int ikmLen, int digest)
  831. {
  832. int ret;
  833. #ifdef HAVE_PK_CALLBACKS
  834. void *cb_ctx = ssl->HkdfExtractCtx;
  835. CallbackHKDFExtract cb = ssl->ctx->HkdfExtractCb;
  836. if (cb != NULL) {
  837. ret = cb(prk, salt, saltLen, ikm, ikmLen, digest, cb_ctx);
  838. }
  839. else
  840. #endif
  841. {
  842. (void)ssl;
  843. ret = wc_Tls13_HKDF_Extract(prk, salt, saltLen, ikm, ikmLen, digest);
  844. }
  845. return ret;
  846. }
  847. /* Derive the early secret using HKDF Extract.
  848. *
  849. * ssl The SSL/TLS object.
  850. */
  851. int DeriveEarlySecret(WOLFSSL* ssl)
  852. {
  853. int ret;
  854. WOLFSSL_MSG("Derive Early Secret");
  855. if (ssl == NULL || ssl->arrays == NULL) {
  856. return BAD_FUNC_ARG;
  857. }
  858. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  859. ret = tsip_Tls13DeriveEarlySecret(ssl);
  860. if (ret != CRYPTOCB_UNAVAILABLE)
  861. return ret;
  862. #endif
  863. PRIVATE_KEY_UNLOCK();
  864. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  865. ret = Tls13_HKDF_Extract(ssl, ssl->arrays->secret, NULL, 0,
  866. ssl->arrays->psk_key, ssl->arrays->psk_keySz,
  867. mac2hash(ssl->specs.mac_algorithm));
  868. #else
  869. ret = Tls13_HKDF_Extract(ssl, ssl->arrays->secret, NULL, 0,
  870. ssl->arrays->masterSecret, 0, mac2hash(ssl->specs.mac_algorithm));
  871. #endif
  872. PRIVATE_KEY_LOCK();
  873. return ret;
  874. }
  875. /* The length of the derived label. */
  876. #define DERIVED_LABEL_SZ 7
  877. /* The derived label. */
  878. static const byte derivedLabel[DERIVED_LABEL_SZ + 1] =
  879. "derived";
  880. /* Derive the handshake secret using HKDF Extract.
  881. *
  882. * ssl The SSL/TLS object.
  883. */
  884. int DeriveHandshakeSecret(WOLFSSL* ssl)
  885. {
  886. byte key[WC_MAX_DIGEST_SIZE];
  887. int ret;
  888. WOLFSSL_MSG("Derive Handshake Secret");
  889. if (ssl == NULL || ssl->arrays == NULL) {
  890. return BAD_FUNC_ARG;
  891. }
  892. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  893. ret = tsip_Tls13DeriveHandshakeSecret(ssl);
  894. if (ret != CRYPTOCB_UNAVAILABLE)
  895. return ret;
  896. #endif
  897. ret = DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
  898. derivedLabel, DERIVED_LABEL_SZ,
  899. NULL, 0, ssl->specs.mac_algorithm);
  900. if (ret != 0)
  901. return ret;
  902. PRIVATE_KEY_UNLOCK();
  903. ret = Tls13_HKDF_Extract(ssl, ssl->arrays->preMasterSecret,
  904. key, ssl->specs.hash_size,
  905. ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz,
  906. mac2hash(ssl->specs.mac_algorithm));
  907. PRIVATE_KEY_LOCK();
  908. return ret;
  909. }
  910. /* Derive the master secret using HKDF Extract.
  911. *
  912. * ssl The SSL/TLS object.
  913. */
  914. int DeriveMasterSecret(WOLFSSL* ssl)
  915. {
  916. byte key[WC_MAX_DIGEST_SIZE];
  917. int ret;
  918. WOLFSSL_MSG("Derive Master Secret");
  919. if (ssl == NULL || ssl->arrays == NULL) {
  920. return BAD_FUNC_ARG;
  921. }
  922. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  923. ret = tsip_Tls13DeriveMasterSecret(ssl);
  924. if (ret != CRYPTOCB_UNAVAILABLE)
  925. return ret;
  926. #endif
  927. ret = DeriveKeyMsg(ssl, key, -1, ssl->arrays->preMasterSecret,
  928. derivedLabel, DERIVED_LABEL_SZ,
  929. NULL, 0, ssl->specs.mac_algorithm);
  930. if (ret != 0)
  931. return ret;
  932. PRIVATE_KEY_UNLOCK();
  933. ret = Tls13_HKDF_Extract(ssl, ssl->arrays->masterSecret,
  934. key, ssl->specs.hash_size,
  935. ssl->arrays->masterSecret, 0, mac2hash(ssl->specs.mac_algorithm));
  936. PRIVATE_KEY_LOCK();
  937. #ifdef HAVE_KEYING_MATERIAL
  938. if (ret != 0)
  939. return ret;
  940. /* Calculate exporter secret only when saving arrays */
  941. if (ssl->options.saveArrays)
  942. ret = DeriveExporterSecret(ssl, ssl->arrays->exporterSecret);
  943. #endif
  944. return ret;
  945. }
  946. #if defined(HAVE_SESSION_TICKET)
  947. /* Length of the resumption label. */
  948. #define RESUMPTION_LABEL_SZ 10
  949. /* Resumption label for generating PSK associated with the ticket. */
  950. static const byte resumptionLabel[RESUMPTION_LABEL_SZ+1] = "resumption";
  951. /* Derive the PSK associated with the ticket.
  952. *
  953. * ssl The SSL/TLS object.
  954. * nonce The nonce to derive with.
  955. * nonceLen The length of the nonce to derive with.
  956. * secret The derived secret.
  957. * returns 0 on success, otherwise failure.
  958. */
  959. int DeriveResumptionPSK(WOLFSSL* ssl, byte* nonce, byte nonceLen, byte* secret)
  960. {
  961. int digestAlg;
  962. /* Only one protocol version defined at this time. */
  963. const byte* protocol = tls13ProtocolLabel;
  964. word32 protocolLen = TLS13_PROTOCOL_LABEL_SZ;
  965. int ret;
  966. WOLFSSL_MSG("Derive Resumption PSK");
  967. switch (ssl->specs.mac_algorithm) {
  968. #ifndef NO_SHA256
  969. case sha256_mac:
  970. digestAlg = WC_SHA256;
  971. break;
  972. #endif
  973. #ifdef WOLFSSL_SHA384
  974. case sha384_mac:
  975. digestAlg = WC_SHA384;
  976. break;
  977. #endif
  978. #ifdef WOLFSSL_TLS13_SHA512
  979. case sha512_mac:
  980. digestAlg = WC_SHA512;
  981. break;
  982. #endif
  983. default:
  984. return BAD_FUNC_ARG;
  985. }
  986. PRIVATE_KEY_UNLOCK();
  987. #if defined(WOLFSSL_TICKET_NONCE_MALLOC) && \
  988. (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
  989. ret = wc_Tls13_HKDF_Expand_Label_Alloc(secret, ssl->specs.hash_size,
  990. ssl->session->masterSecret, ssl->specs.hash_size, protocol, protocolLen,
  991. resumptionLabel, RESUMPTION_LABEL_SZ, nonce, nonceLen, digestAlg,
  992. ssl->heap);
  993. #else
  994. ret = wc_Tls13_HKDF_Expand_Label(secret, ssl->specs.hash_size,
  995. ssl->session->masterSecret, ssl->specs.hash_size, protocol, protocolLen,
  996. resumptionLabel, RESUMPTION_LABEL_SZ, nonce, nonceLen, digestAlg);
  997. #endif /* !defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3) */
  998. PRIVATE_KEY_LOCK();
  999. return ret;
  1000. }
  1001. #endif /* HAVE_SESSION_TICKET */
  1002. /* Calculate the HMAC of message data to this point.
  1003. *
  1004. * ssl The SSL/TLS object.
  1005. * key The HMAC key.
  1006. * hash The hash result - verify data.
  1007. * returns length of verify data generated.
  1008. */
  1009. static int BuildTls13HandshakeHmac(WOLFSSL* ssl, byte* key, byte* hash,
  1010. word32* pHashSz)
  1011. {
  1012. Hmac verifyHmac;
  1013. int hashType = WC_SHA256;
  1014. int hashSz = WC_SHA256_DIGEST_SIZE;
  1015. int ret = BAD_FUNC_ARG;
  1016. if (ssl == NULL || key == NULL || hash == NULL) {
  1017. return BAD_FUNC_ARG;
  1018. }
  1019. /* Get the hash of the previous handshake messages. */
  1020. switch (ssl->specs.mac_algorithm) {
  1021. #ifndef NO_SHA256
  1022. case sha256_mac:
  1023. hashType = WC_SHA256;
  1024. hashSz = WC_SHA256_DIGEST_SIZE;
  1025. ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
  1026. break;
  1027. #endif /* !NO_SHA256 */
  1028. #ifdef WOLFSSL_SHA384
  1029. case sha384_mac:
  1030. hashType = WC_SHA384;
  1031. hashSz = WC_SHA384_DIGEST_SIZE;
  1032. ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
  1033. break;
  1034. #endif /* WOLFSSL_SHA384 */
  1035. #ifdef WOLFSSL_TLS13_SHA512
  1036. case sha512_mac:
  1037. hashType = WC_SHA512;
  1038. hashSz = WC_SHA512_DIGEST_SIZE;
  1039. ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
  1040. break;
  1041. #endif /* WOLFSSL_TLS13_SHA512 */
  1042. default:
  1043. break;
  1044. }
  1045. if (ret != 0)
  1046. return ret;
  1047. #ifdef WOLFSSL_DEBUG_TLS
  1048. WOLFSSL_MSG(" Key");
  1049. WOLFSSL_BUFFER(key, ssl->specs.hash_size);
  1050. WOLFSSL_MSG(" Msg Hash");
  1051. WOLFSSL_BUFFER(hash, hashSz);
  1052. #endif
  1053. /* Calculate the verify data. */
  1054. ret = wc_HmacInit(&verifyHmac, ssl->heap, ssl->devId);
  1055. if (ret == 0) {
  1056. ret = wc_HmacSetKey(&verifyHmac, hashType, key, ssl->specs.hash_size);
  1057. if (ret == 0)
  1058. ret = wc_HmacUpdate(&verifyHmac, hash, hashSz);
  1059. if (ret == 0)
  1060. ret = wc_HmacFinal(&verifyHmac, hash);
  1061. wc_HmacFree(&verifyHmac);
  1062. }
  1063. #ifdef WOLFSSL_DEBUG_TLS
  1064. WOLFSSL_MSG(" Hash");
  1065. WOLFSSL_BUFFER(hash, hashSz);
  1066. #endif
  1067. if (pHashSz)
  1068. *pHashSz = hashSz;
  1069. return ret;
  1070. }
  1071. /* The length of the label to use when deriving keys. */
  1072. #define WRITE_KEY_LABEL_SZ 3
  1073. /* The length of the label to use when deriving IVs. */
  1074. #define WRITE_IV_LABEL_SZ 2
  1075. /* The label to use when deriving keys. */
  1076. static const byte writeKeyLabel[WRITE_KEY_LABEL_SZ+1] = "key";
  1077. /* The label to use when deriving IVs. */
  1078. static const byte writeIVLabel[WRITE_IV_LABEL_SZ+1] = "iv";
  1079. /* Derive the keys and IVs for TLS v1.3.
  1080. *
  1081. * ssl The SSL/TLS object.
  1082. * secret early_data_key when deriving the key and IV for encrypting early
  1083. * data application data and end_of_early_data messages.
  1084. * handshake_key when deriving keys and IVs for encrypting handshake
  1085. * messages.
  1086. * traffic_key when deriving first keys and IVs for encrypting
  1087. * traffic messages.
  1088. * update_traffic_key when deriving next keys and IVs for encrypting
  1089. * traffic messages.
  1090. * side ENCRYPT_SIDE_ONLY when only encryption secret needs to be derived.
  1091. * DECRYPT_SIDE_ONLY when only decryption secret needs to be derived.
  1092. * ENCRYPT_AND_DECRYPT_SIDE when both secret needs to be derived.
  1093. * store 1 indicates to derive the keys and IVs from derived secret and
  1094. * store ready for provisioning.
  1095. * returns 0 on success, otherwise failure.
  1096. */
  1097. int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store)
  1098. {
  1099. int ret = BAD_FUNC_ARG; /* Assume failure */
  1100. int i = 0;
  1101. #ifdef WOLFSSL_SMALL_STACK
  1102. byte* key_dig;
  1103. #else
  1104. byte key_dig[MAX_PRF_DIG];
  1105. #endif
  1106. int provision;
  1107. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  1108. ret = tsip_Tls13DeriveKeys(ssl, secret, side);
  1109. if (ret != CRYPTOCB_UNAVAILABLE) {
  1110. return ret;
  1111. }
  1112. ret = BAD_FUNC_ARG; /* Assume failure */
  1113. #endif
  1114. #ifdef WOLFSSL_SMALL_STACK
  1115. key_dig = (byte*)XMALLOC(MAX_PRF_DIG, ssl->heap, DYNAMIC_TYPE_DIGEST);
  1116. if (key_dig == NULL)
  1117. return MEMORY_E;
  1118. #endif
  1119. if (side == ENCRYPT_AND_DECRYPT_SIDE) {
  1120. provision = PROVISION_CLIENT_SERVER;
  1121. }
  1122. else {
  1123. provision = ((ssl->options.side != WOLFSSL_CLIENT_END) ^
  1124. (side == ENCRYPT_SIDE_ONLY)) ? PROVISION_CLIENT :
  1125. PROVISION_SERVER;
  1126. }
  1127. /* Derive the appropriate secret to use in the HKDF. */
  1128. switch (secret) {
  1129. #ifdef WOLFSSL_EARLY_DATA
  1130. case early_data_key:
  1131. ret = DeriveEarlyTrafficSecret(ssl, ssl->clientSecret);
  1132. if (ret != 0)
  1133. goto end;
  1134. break;
  1135. #endif
  1136. case handshake_key:
  1137. if (provision & PROVISION_CLIENT) {
  1138. ret = DeriveClientHandshakeSecret(ssl,
  1139. ssl->clientSecret);
  1140. if (ret != 0)
  1141. goto end;
  1142. }
  1143. if (provision & PROVISION_SERVER) {
  1144. ret = DeriveServerHandshakeSecret(ssl,
  1145. ssl->serverSecret);
  1146. if (ret != 0)
  1147. goto end;
  1148. }
  1149. break;
  1150. case traffic_key:
  1151. if (provision & PROVISION_CLIENT) {
  1152. ret = DeriveClientTrafficSecret(ssl, ssl->clientSecret);
  1153. if (ret != 0)
  1154. goto end;
  1155. }
  1156. if (provision & PROVISION_SERVER) {
  1157. ret = DeriveServerTrafficSecret(ssl, ssl->serverSecret);
  1158. if (ret != 0)
  1159. goto end;
  1160. }
  1161. break;
  1162. case update_traffic_key:
  1163. if (provision & PROVISION_CLIENT) {
  1164. ret = DeriveTrafficSecret(ssl, ssl->clientSecret);
  1165. if (ret != 0)
  1166. goto end;
  1167. }
  1168. if (provision & PROVISION_SERVER) {
  1169. ret = DeriveTrafficSecret(ssl, ssl->serverSecret);
  1170. if (ret != 0)
  1171. goto end;
  1172. }
  1173. break;
  1174. default:
  1175. break;
  1176. }
  1177. #ifdef WOLFSSL_QUIC
  1178. if (WOLFSSL_IS_QUIC(ssl)) {
  1179. ret = wolfSSL_quic_forward_secrets(ssl, secret, side);
  1180. if (ret != 0)
  1181. goto end;
  1182. }
  1183. #endif /* WOLFSSL_QUIC */
  1184. if (!store)
  1185. goto end;
  1186. /* Key data = client key | server key | client IV | server IV */
  1187. if (provision & PROVISION_CLIENT) {
  1188. /* Derive the client key. */
  1189. WOLFSSL_MSG("Derive Client Key");
  1190. ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
  1191. ssl->clientSecret, writeKeyLabel,
  1192. WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0);
  1193. if (ret != 0)
  1194. goto end;
  1195. i += ssl->specs.key_size;
  1196. }
  1197. if (provision & PROVISION_SERVER) {
  1198. /* Derive the server key. */
  1199. WOLFSSL_MSG("Derive Server Key");
  1200. ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
  1201. ssl->serverSecret, writeKeyLabel,
  1202. WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0);
  1203. if (ret != 0)
  1204. goto end;
  1205. i += ssl->specs.key_size;
  1206. }
  1207. if (provision & PROVISION_CLIENT) {
  1208. /* Derive the client IV. */
  1209. WOLFSSL_MSG("Derive Client IV");
  1210. ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
  1211. ssl->clientSecret, writeIVLabel,
  1212. WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0);
  1213. if (ret != 0)
  1214. goto end;
  1215. i += ssl->specs.iv_size;
  1216. }
  1217. if (provision & PROVISION_SERVER) {
  1218. /* Derive the server IV. */
  1219. WOLFSSL_MSG("Derive Server IV");
  1220. ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
  1221. ssl->serverSecret, writeIVLabel,
  1222. WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0);
  1223. if (ret != 0)
  1224. goto end;
  1225. i += ssl->specs.iv_size;
  1226. }
  1227. /* Store keys and IVs but don't activate them. */
  1228. ret = StoreKeys(ssl, key_dig, provision);
  1229. #ifdef WOLFSSL_DTLS13
  1230. if (ret != 0)
  1231. goto end;
  1232. if (ssl->options.dtls) {
  1233. ret = Dtls13DeriveSnKeys(ssl, provision);
  1234. if (ret != 0)
  1235. return ret;
  1236. }
  1237. #endif /* WOLFSSL_DTLS13 */
  1238. end:
  1239. ForceZero(key_dig, i);
  1240. #ifdef WOLFSSL_SMALL_STACK
  1241. XFREE(key_dig, ssl->heap, DYNAMIC_TYPE_DIGEST);
  1242. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  1243. wc_MemZero_Check(key_dig, MAX_PRF_DIG);
  1244. #endif
  1245. if (ret != 0) {
  1246. WOLFSSL_ERROR_VERBOSE(ret);
  1247. }
  1248. return ret;
  1249. }
  1250. #if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  1251. #ifdef WOLFSSL_32BIT_MILLI_TIME
  1252. #ifndef NO_ASN_TIME
  1253. #if defined(USER_TICKS)
  1254. #if 0
  1255. word32 TimeNowInMilliseconds(void)
  1256. {
  1257. /*
  1258. write your own clock tick function if don't want gettimeofday()
  1259. needs millisecond accuracy but doesn't have to correlated to EPOCH
  1260. */
  1261. }
  1262. #endif
  1263. #elif defined(TIME_OVERRIDES)
  1264. #if !defined(NO_ASN) && !defined(NO_ASN_TIME)
  1265. word32 TimeNowInMilliseconds(void)
  1266. {
  1267. return (word32) wc_Time(0) * 1000;
  1268. }
  1269. #else
  1270. #ifndef HAVE_TIME_T_TYPE
  1271. typedef long time_t;
  1272. #endif
  1273. extern time_t XTIME(time_t * timer);
  1274. /* The time in milliseconds.
  1275. * Used for tickets to represent difference between when first seen and when
  1276. * sending.
  1277. *
  1278. * returns the time in milliseconds as a 32-bit value.
  1279. */
  1280. word32 TimeNowInMilliseconds(void)
  1281. {
  1282. return (word32) XTIME(0) * 1000;
  1283. }
  1284. #endif
  1285. #elif defined(XTIME_MS)
  1286. word32 TimeNowInMilliseconds(void)
  1287. {
  1288. return (word32)XTIME_MS(0);
  1289. }
  1290. #elif defined(USE_WINDOWS_API)
  1291. /* The time in milliseconds.
  1292. * Used for tickets to represent difference between when first seen and when
  1293. * sending.
  1294. *
  1295. * returns the time in milliseconds as a 32-bit value.
  1296. */
  1297. word32 TimeNowInMilliseconds(void)
  1298. {
  1299. static int init = 0;
  1300. static LARGE_INTEGER freq;
  1301. LARGE_INTEGER count;
  1302. if (!init) {
  1303. QueryPerformanceFrequency(&freq);
  1304. init = 1;
  1305. }
  1306. QueryPerformanceCounter(&count);
  1307. return (word32)(count.QuadPart / (freq.QuadPart / 1000));
  1308. }
  1309. #elif defined(HAVE_RTP_SYS)
  1310. #include "rtptime.h"
  1311. /* The time in milliseconds.
  1312. * Used for tickets to represent difference between when first seen and when
  1313. * sending.
  1314. *
  1315. * returns the time in milliseconds as a 32-bit value.
  1316. */
  1317. word32 TimeNowInMilliseconds(void)
  1318. {
  1319. return (word32)rtp_get_system_sec() * 1000;
  1320. }
  1321. #elif defined(WOLFSSL_DEOS)
  1322. word32 TimeNowInMilliseconds(void)
  1323. {
  1324. const word32 systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
  1325. word32 *systemTickPtr = systemTickPointer();
  1326. return (word32) (*systemTickPtr/systemTickTimeInHz) * 1000;
  1327. }
  1328. #elif defined(MICRIUM)
  1329. /* The time in milliseconds.
  1330. * Used for tickets to represent difference between when first seen and when
  1331. * sending.
  1332. *
  1333. * returns the time in milliseconds as a 32-bit value.
  1334. */
  1335. word32 TimeNowInMilliseconds(void)
  1336. {
  1337. OS_TICK ticks = 0;
  1338. OS_ERR err;
  1339. ticks = OSTimeGet(&err);
  1340. return (word32) (ticks / OSCfg_TickRate_Hz) * 1000;
  1341. }
  1342. #elif defined(MICROCHIP_TCPIP_V5)
  1343. /* The time in milliseconds.
  1344. * Used for tickets to represent difference between when first seen and when
  1345. * sending.
  1346. *
  1347. * returns the time in milliseconds as a 32-bit value.
  1348. */
  1349. word32 TimeNowInMilliseconds(void)
  1350. {
  1351. return (word32) (TickGet() / (TICKS_PER_SECOND / 1000));
  1352. }
  1353. #elif defined(MICROCHIP_TCPIP)
  1354. #if defined(MICROCHIP_MPLAB_HARMONY)
  1355. #include <system/tmr/sys_tmr.h>
  1356. /* The time in milliseconds.
  1357. * Used for tickets to represent difference between when first seen and when
  1358. * sending.
  1359. *
  1360. * returns the time in milliseconds as a 32-bit value.
  1361. */
  1362. word32 TimeNowInMilliseconds(void)
  1363. {
  1364. return (word32)(SYS_TMR_TickCountGet() /
  1365. (SYS_TMR_TickCounterFrequencyGet() / 1000));
  1366. }
  1367. #else
  1368. /* The time in milliseconds.
  1369. * Used for tickets to represent difference between when first seen and when
  1370. * sending.
  1371. *
  1372. * returns the time in milliseconds as a 32-bit value.
  1373. */
  1374. word32 TimeNowInMilliseconds(void)
  1375. {
  1376. return (word32)(SYS_TICK_Get() / (SYS_TICK_TicksPerSecondGet() / 1000));
  1377. }
  1378. #endif
  1379. #elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
  1380. /* The time in milliseconds.
  1381. * Used for tickets to represent difference between when first seen and when
  1382. * sending.
  1383. *
  1384. * returns the time in milliseconds as a 32-bit value.
  1385. */
  1386. word32 TimeNowInMilliseconds(void)
  1387. {
  1388. TIME_STRUCT mqxTime;
  1389. _time_get_elapsed(&mqxTime);
  1390. return (word32) mqxTime.SECONDS * 1000;
  1391. }
  1392. #elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS)
  1393. #include "include/task.h"
  1394. /* The time in milliseconds.
  1395. * Used for tickets to represent difference between when first seen and when
  1396. * sending.
  1397. *
  1398. * returns the time in milliseconds as a 32-bit value.
  1399. */
  1400. word32 TimeNowInMilliseconds(void)
  1401. {
  1402. return (unsigned int)(((float)xTaskGetTickCount()) /
  1403. (configTICK_RATE_HZ / 1000));
  1404. }
  1405. #elif defined(FREESCALE_KSDK_BM)
  1406. #include "lwip/sys.h" /* lwIP */
  1407. /* The time in milliseconds.
  1408. * Used for tickets to represent difference between when first seen and when
  1409. * sending.
  1410. *
  1411. * returns the time in milliseconds as a 32-bit value.
  1412. */
  1413. word32 TimeNowInMilliseconds(void)
  1414. {
  1415. return sys_now();
  1416. }
  1417. #elif defined(WOLFSSL_TIRTOS)
  1418. /* The time in milliseconds.
  1419. * Used for tickets to represent difference between when first seen and when
  1420. * sending.
  1421. *
  1422. * returns the time in milliseconds as a 32-bit value.
  1423. */
  1424. word32 TimeNowInMilliseconds(void)
  1425. {
  1426. return (word32) Seconds_get() * 1000;
  1427. }
  1428. #elif defined(WOLFSSL_UTASKER)
  1429. /* The time in milliseconds.
  1430. * Used for tickets to represent difference between when first seen and when
  1431. * sending.
  1432. *
  1433. * returns the time in milliseconds as a 32-bit value.
  1434. */
  1435. word32 TimeNowInMilliseconds(void)
  1436. {
  1437. return (word32)(uTaskerSystemTick / (TICK_RESOLUTION / 1000));
  1438. }
  1439. #elif defined(WOLFSSL_LINUXKM)
  1440. word32 TimeNowInMilliseconds(void)
  1441. {
  1442. s64 t;
  1443. #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0)
  1444. struct timespec ts;
  1445. getnstimeofday(&ts);
  1446. t = ts.tv_sec * (s64)1000;
  1447. t += ts.tv_nsec / (s64)1000000;
  1448. #else
  1449. struct timespec64 ts;
  1450. #if LINUX_VERSION_CODE < KERNEL_VERSION(5, 0, 0)
  1451. ts = current_kernel_time64();
  1452. #else
  1453. ktime_get_coarse_real_ts64(&ts);
  1454. #endif
  1455. t = ts.tv_sec * 1000L;
  1456. t += ts.tv_nsec / 1000000L;
  1457. #endif
  1458. return (word32)t;
  1459. }
  1460. #elif defined(WOLFSSL_QNX_CAAM)
  1461. word32 TimeNowInMilliseconds(void)
  1462. {
  1463. struct timespec now;
  1464. clock_gettime(CLOCK_REALTIME, &now);
  1465. return (word32)(now.tv_sec * 1000 + now.tv_nsec / 1000000);
  1466. }
  1467. #elif defined(FUSION_RTOS)
  1468. /* The time in milliseconds.
  1469. * Used for tickets to represent difference between when first seen and when
  1470. * sending.
  1471. *
  1472. * returns the time in milliseconds as a 32-bit value.
  1473. */
  1474. word32 TimeNowInMilliseconds(void)
  1475. {
  1476. struct timeval now;
  1477. if (FCL_GETTIMEOFDAY(&now, 0) < 0)
  1478. return 0;
  1479. /* Convert to milliseconds number. */
  1480. return (word32)(now.tv_sec * 1000 + now.tv_usec / 1000);
  1481. }
  1482. #elif defined(WOLFSSL_ZEPHYR)
  1483. word32 TimeNowInMilliseconds(void)
  1484. {
  1485. #if defined(CONFIG_ARCH_POSIX)
  1486. k_cpu_idle();
  1487. #endif
  1488. return (word32)k_uptime_get() / 1000;
  1489. }
  1490. #else
  1491. /* The time in milliseconds.
  1492. * Used for tickets to represent difference between when first seen and when
  1493. * sending.
  1494. *
  1495. * returns the time in milliseconds as a 32-bit value.
  1496. */
  1497. word32 TimeNowInMilliseconds(void)
  1498. {
  1499. struct timeval now;
  1500. if (gettimeofday(&now, 0) < 0)
  1501. return 0;
  1502. /* Convert to milliseconds number. */
  1503. return (word32)(now.tv_sec * 1000 + now.tv_usec / 1000);
  1504. }
  1505. #endif
  1506. #else
  1507. /* user must supply time in milliseconds function:
  1508. * word32 TimeNowInMilliseconds(void);
  1509. * The response is milliseconds elapsed
  1510. */
  1511. #endif /* !NO_ASN_TIME */
  1512. #else
  1513. #ifndef NO_ASN_TIME
  1514. #if defined(USER_TICKS)
  1515. #if 0
  1516. sword64 TimeNowInMilliseconds(void)
  1517. {
  1518. /*
  1519. write your own clock tick function if don't want gettimeofday()
  1520. needs millisecond accuracy but doesn't have to correlated to EPOCH
  1521. */
  1522. }
  1523. #endif
  1524. #elif defined(TIME_OVERRIDES)
  1525. #if !defined(NO_ASN) && !defined(NO_ASN_TIME)
  1526. sword64 TimeNowInMilliseconds(void)
  1527. {
  1528. return (sword64) wc_Time(0) * 1000;
  1529. }
  1530. #else
  1531. #ifndef HAVE_TIME_T_TYPE
  1532. typedef long time_t;
  1533. #endif
  1534. extern time_t XTIME(time_t * timer);
  1535. /* The time in milliseconds.
  1536. * Used for tickets to represent difference between when first seen and when
  1537. * sending.
  1538. *
  1539. * returns the time in milliseconds as a 32-bit value.
  1540. */
  1541. sword64 TimeNowInMilliseconds(void)
  1542. {
  1543. return (sword64) XTIME(0) * 1000;
  1544. }
  1545. #endif
  1546. #elif defined(XTIME_MS)
  1547. sword64 TimeNowInMilliseconds(void)
  1548. {
  1549. return (sword64)XTIME_MS(0);
  1550. }
  1551. #elif defined(USE_WINDOWS_API)
  1552. /* The time in milliseconds.
  1553. * Used for tickets to represent difference between when first seen and when
  1554. * sending.
  1555. *
  1556. * returns the time in milliseconds as a 64-bit value.
  1557. */
  1558. sword64 TimeNowInMilliseconds(void)
  1559. {
  1560. static int init = 0;
  1561. static LARGE_INTEGER freq;
  1562. LARGE_INTEGER count;
  1563. if (!init) {
  1564. QueryPerformanceFrequency(&freq);
  1565. init = 1;
  1566. }
  1567. QueryPerformanceCounter(&count);
  1568. return (sword64)(count.QuadPart / (freq.QuadPart / 1000));
  1569. }
  1570. #elif defined(HAVE_RTP_SYS)
  1571. #include "rtptime.h"
  1572. /* The time in milliseconds.
  1573. * Used for tickets to represent difference between when first seen and when
  1574. * sending.
  1575. *
  1576. * returns the time in milliseconds as a 64-bit value.
  1577. */
  1578. sword64 TimeNowInMilliseconds(void)
  1579. {
  1580. return (sword64)rtp_get_system_sec() * 1000;
  1581. }
  1582. #elif defined(WOLFSSL_DEOS)
  1583. sword64 TimeNowInMilliseconds(void)
  1584. {
  1585. const word32 systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
  1586. word32 *systemTickPtr = systemTickPointer();
  1587. return (sword64) (*systemTickPtr/systemTickTimeInHz) * 1000;
  1588. }
  1589. #elif defined(MICRIUM)
  1590. /* The time in milliseconds.
  1591. * Used for tickets to represent difference between when first seen and when
  1592. * sending.
  1593. *
  1594. * returns the time in milliseconds as a 64-bit value.
  1595. */
  1596. sword64 TimeNowInMilliseconds(void)
  1597. {
  1598. OS_TICK ticks = 0;
  1599. OS_ERR err;
  1600. ticks = OSTimeGet(&err);
  1601. return (sword64) (ticks / OSCfg_TickRate_Hz) * 1000;
  1602. }
  1603. #elif defined(MICROCHIP_TCPIP_V5)
  1604. /* The time in milliseconds.
  1605. * Used for tickets to represent difference between when first seen and when
  1606. * sending.
  1607. *
  1608. * returns the time in milliseconds as a 64-bit value.
  1609. */
  1610. sword64 TimeNowInMilliseconds(void)
  1611. {
  1612. return (sword64) (TickGet() / (TICKS_PER_SECOND / 1000));
  1613. }
  1614. #elif defined(MICROCHIP_TCPIP)
  1615. #if defined(MICROCHIP_MPLAB_HARMONY)
  1616. #include <system/tmr/sys_tmr.h>
  1617. /* The time in milliseconds.
  1618. * Used for tickets to represent difference between when first seen and when
  1619. * sending.
  1620. *
  1621. * returns the time in milliseconds as a 64-bit value.
  1622. */
  1623. sword64 TimeNowInMilliseconds(void)
  1624. {
  1625. return (sword64)SYS_TMR_TickCountGet() /
  1626. (SYS_TMR_TickCounterFrequencyGet() / 1000);
  1627. }
  1628. #else
  1629. /* The time in milliseconds.
  1630. * Used for tickets to represent difference between when first seen and when
  1631. * sending.
  1632. *
  1633. * returns the time in milliseconds as a 64-bit value.
  1634. */
  1635. sword64 TimeNowInMilliseconds(void)
  1636. {
  1637. return (sword64)SYS_TICK_Get() / (SYS_TICK_TicksPerSecondGet() / 1000);
  1638. }
  1639. #endif
  1640. #elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
  1641. /* The time in milliseconds.
  1642. * Used for tickets to represent difference between when first seen and when
  1643. * sending.
  1644. *
  1645. * returns the time in milliseconds as a 64-bit value.
  1646. */
  1647. sword64 TimeNowInMilliseconds(void)
  1648. {
  1649. TIME_STRUCT mqxTime;
  1650. _time_get_elapsed(&mqxTime);
  1651. return (sword64) mqxTime.SECONDS * 1000;
  1652. }
  1653. #elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS)
  1654. #include "include/task.h"
  1655. /* The time in milliseconds.
  1656. * Used for tickets to represent difference between when first seen and when
  1657. * sending.
  1658. *
  1659. * returns the time in milliseconds as a 64-bit value.
  1660. */
  1661. sword64 TimeNowInMilliseconds(void)
  1662. {
  1663. return (sword64)xTaskGetTickCount() / (configTICK_RATE_HZ / 1000);
  1664. }
  1665. #elif defined(FREESCALE_KSDK_BM)
  1666. #include "lwip/sys.h" /* lwIP */
  1667. /* The time in milliseconds.
  1668. * Used for tickets to represent difference between when first seen and when
  1669. * sending.
  1670. *
  1671. * returns the time in milliseconds as a 64-bit value.
  1672. */
  1673. sword64 TimeNowInMilliseconds(void)
  1674. {
  1675. return sys_now();
  1676. }
  1677. #elif defined(WOLFSSL_TIRTOS)
  1678. /* The time in milliseconds.
  1679. * Used for tickets to represent difference between when first seen and when
  1680. * sending.
  1681. *
  1682. * returns the time in milliseconds as a 64-bit value.
  1683. */
  1684. sword64 TimeNowInMilliseconds(void)
  1685. {
  1686. return (sword64) Seconds_get() * 1000;
  1687. }
  1688. #elif defined(WOLFSSL_UTASKER)
  1689. /* The time in milliseconds.
  1690. * Used for tickets to represent difference between when first seen and when
  1691. * sending.
  1692. *
  1693. * returns the time in milliseconds as a 64-bit value.
  1694. */
  1695. sword64 TimeNowInMilliseconds(void)
  1696. {
  1697. return (sword64)(uTaskerSystemTick / (TICK_RESOLUTION / 1000));
  1698. }
  1699. #elif defined(WOLFSSL_LINUXKM)
  1700. sword64 TimeNowInMilliseconds(void)
  1701. {
  1702. s64 t;
  1703. #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0)
  1704. struct timespec ts;
  1705. getnstimeofday(&ts);
  1706. t = ts.tv_sec * (s64)1000;
  1707. t += ts.tv_nsec / (s64)1000000;
  1708. #else
  1709. struct timespec64 ts;
  1710. #if LINUX_VERSION_CODE < KERNEL_VERSION(5, 0, 0)
  1711. ts = current_kernel_time64();
  1712. #else
  1713. ktime_get_coarse_real_ts64(&ts);
  1714. #endif
  1715. t = ts.tv_sec * 1000L;
  1716. t += ts.tv_nsec / 1000000L;
  1717. #endif
  1718. return (sword64)t;
  1719. }
  1720. #elif defined(WOLFSSL_QNX_CAAM)
  1721. sword64 TimeNowInMilliseconds(void)
  1722. {
  1723. struct timespec now;
  1724. clock_gettime(CLOCK_REALTIME, &now);
  1725. return (sword64)(now.tv_sec * 1000 + now.tv_nsec / 1000000);
  1726. }
  1727. #elif defined(FUSION_RTOS)
  1728. /* The time in milliseconds.
  1729. * Used for tickets to represent difference between when first seen and when
  1730. * sending.
  1731. *
  1732. * returns the time in milliseconds as a 64-bit value.
  1733. */
  1734. sword64 TimeNowInMilliseconds(void)
  1735. {
  1736. struct timeval now;
  1737. if (FCL_GETTIMEOFDAY(&now, 0) < 0)
  1738. return 0;
  1739. /* Convert to milliseconds number. */
  1740. return (sword64)now.tv_sec * 1000 + now.tv_usec / 1000;
  1741. }
  1742. #elif defined(WOLFSSL_ZEPHYR)
  1743. sword64 TimeNowInMilliseconds(void)
  1744. {
  1745. #if defined(CONFIG_ARCH_POSIX)
  1746. k_cpu_idle();
  1747. #endif
  1748. return (sword64)k_uptime_get() / 1000;
  1749. }
  1750. #else
  1751. /* The time in milliseconds.
  1752. * Used for tickets to represent difference between when first seen and when
  1753. * sending.
  1754. *
  1755. * returns the time in milliseconds as a 64-bit value.
  1756. */
  1757. sword64 TimeNowInMilliseconds(void)
  1758. {
  1759. struct timeval now;
  1760. if (gettimeofday(&now, 0) < 0)
  1761. return 0;
  1762. /* Convert to milliseconds number. */
  1763. return (sword64)now.tv_sec * 1000 + now.tv_usec / 1000;
  1764. }
  1765. #endif
  1766. #else
  1767. /* user must supply time in milliseconds function:
  1768. * sword64 TimeNowInMilliseconds(void);
  1769. * The response is milliseconds elapsed
  1770. */
  1771. #endif /* !NO_ASN_TIME */
  1772. #endif /* WOLFSSL_32BIT_MILLI_TIME */
  1773. #endif /* HAVE_SESSION_TICKET || !NO_PSK */
  1774. /* Extract the handshake header information.
  1775. *
  1776. * ssl The SSL/TLS object.
  1777. * input The buffer holding the message data.
  1778. * inOutIdx On entry, the index into the buffer of the handshake data.
  1779. * On exit, the start of the handshake data.
  1780. * type Type of handshake message.
  1781. * size The length of the handshake message data.
  1782. * totalSz The total size of data in the buffer.
  1783. * returns BUFFER_E if there is not enough input data and 0 on success.
  1784. */
  1785. static int GetHandshakeHeader(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  1786. byte* type, word32* size, word32 totalSz)
  1787. {
  1788. const byte* ptr = input + *inOutIdx;
  1789. (void)ssl;
  1790. *inOutIdx += HANDSHAKE_HEADER_SZ;
  1791. if (*inOutIdx > totalSz)
  1792. return BUFFER_E;
  1793. *type = ptr[0];
  1794. c24to32(&ptr[1], size);
  1795. return 0;
  1796. }
  1797. /* Add record layer header to message.
  1798. *
  1799. * output The buffer to write the record layer header into.
  1800. * length The length of the record data.
  1801. * type The type of record message.
  1802. * ssl The SSL/TLS object.
  1803. */
  1804. static void AddTls13RecordHeader(byte* output, word32 length, byte type,
  1805. WOLFSSL* ssl)
  1806. {
  1807. RecordLayerHeader* rl;
  1808. rl = (RecordLayerHeader*)output;
  1809. rl->type = type;
  1810. rl->pvMajor = ssl->version.major;
  1811. /* NOTE: May be TLSv1_MINOR when sending first ClientHello. */
  1812. rl->pvMinor = TLSv1_2_MINOR;
  1813. c16toa((word16)length, rl->length);
  1814. }
  1815. /* Add handshake header to message.
  1816. *
  1817. * output The buffer to write the handshake header into.
  1818. * length The length of the handshake data.
  1819. * fragOffset The offset of the fragment data. (DTLS)
  1820. * fragLength The length of the fragment data. (DTLS)
  1821. * type The type of handshake message.
  1822. * ssl The SSL/TLS object. (DTLS)
  1823. */
  1824. static void AddTls13HandShakeHeader(byte* output, word32 length,
  1825. word32 fragOffset, word32 fragLength,
  1826. byte type, WOLFSSL* ssl)
  1827. {
  1828. HandShakeHeader* hs;
  1829. (void)fragOffset;
  1830. (void)fragLength;
  1831. (void)ssl;
  1832. #ifdef WOLFSSL_DTLS13
  1833. /* message_hash type is used for a syntetic message that replaces the first
  1834. ClientHello in the hash transcript when using HelloRetryRequest. It will
  1835. never be transmitted and, as the DTLS-only fields must not be considered
  1836. when computing the hash transcript, we can avoid to use the DTLS
  1837. handshake header. */
  1838. if (ssl->options.dtls && type != message_hash) {
  1839. Dtls13HandshakeAddHeader(ssl, output, (enum HandShakeType)type, length);
  1840. return;
  1841. }
  1842. #endif /* WOLFSSL_DTLS13 */
  1843. /* handshake header */
  1844. hs = (HandShakeHeader*)output;
  1845. hs->type = type;
  1846. c32to24(length, hs->length);
  1847. }
  1848. /* Add both record layer and handshake header to message.
  1849. *
  1850. * output The buffer to write the headers into.
  1851. * length The length of the handshake data.
  1852. * type The type of record layer message.
  1853. * ssl The SSL/TLS object. (DTLS)
  1854. */
  1855. static void AddTls13Headers(byte* output, word32 length, byte type,
  1856. WOLFSSL* ssl)
  1857. {
  1858. word32 lengthAdj = HANDSHAKE_HEADER_SZ;
  1859. word32 outputAdj = RECORD_HEADER_SZ;
  1860. #ifdef WOLFSSL_DTLS13
  1861. if (ssl->options.dtls) {
  1862. Dtls13AddHeaders(output, length, (enum HandShakeType)type, ssl);
  1863. return;
  1864. }
  1865. #endif /* WOLFSSL_DTLS13 */
  1866. AddTls13RecordHeader(output, length + lengthAdj, handshake, ssl);
  1867. AddTls13HandShakeHeader(output + outputAdj, length, 0, length, type, ssl);
  1868. }
  1869. #if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) \
  1870. && !defined(NO_CERTS)
  1871. /* Add both record layer and fragment handshake header to message.
  1872. *
  1873. * output The buffer to write the headers into.
  1874. * fragOffset The offset of the fragment data. (DTLS)
  1875. * fragLength The length of the fragment data. (DTLS)
  1876. * length The length of the handshake data.
  1877. * type The type of record layer message.
  1878. * ssl The SSL/TLS object. (DTLS)
  1879. */
  1880. static void AddTls13FragHeaders(byte* output, word32 fragSz, word32 fragOffset,
  1881. word32 length, byte type, WOLFSSL* ssl)
  1882. {
  1883. word32 lengthAdj = HANDSHAKE_HEADER_SZ;
  1884. word32 outputAdj = RECORD_HEADER_SZ;
  1885. (void)fragSz;
  1886. #ifdef WOLFSSL_DTLS13
  1887. /* we ignore fragmentation fields here because fragmentation logic for
  1888. DTLS1.3 is inside dtls13_handshake_send(). */
  1889. if (ssl->options.dtls) {
  1890. Dtls13AddHeaders(output, length, (enum HandShakeType)type, ssl);
  1891. return;
  1892. }
  1893. #endif /* WOLFSSL_DTLS13 */
  1894. AddTls13RecordHeader(output, fragSz + lengthAdj, handshake, ssl);
  1895. AddTls13HandShakeHeader(output + outputAdj, length, fragOffset, fragSz,
  1896. type, ssl);
  1897. }
  1898. #endif /* (!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) && !NO_CERTS */
  1899. /* Write the sequence number into the buffer.
  1900. * No DTLS v1.3 support.
  1901. *
  1902. * ssl The SSL/TLS object.
  1903. * verifyOrder Which set of sequence numbers to use.
  1904. * out The buffer to write into.
  1905. */
  1906. static WC_INLINE void WriteSEQTls13(WOLFSSL* ssl, int verifyOrder, byte* out)
  1907. {
  1908. word32 seq[2] = {0, 0};
  1909. if (ssl->options.dtls) {
  1910. #ifdef WOLFSSL_DTLS13
  1911. Dtls13GetSeq(ssl, verifyOrder, seq, 1);
  1912. #endif /* WOLFSSL_DTLS13 */
  1913. }
  1914. else if (verifyOrder == PEER_ORDER) {
  1915. seq[0] = ssl->keys.peer_sequence_number_hi;
  1916. seq[1] = ssl->keys.peer_sequence_number_lo++;
  1917. /* handle rollover */
  1918. if (seq[1] > ssl->keys.peer_sequence_number_lo)
  1919. ssl->keys.peer_sequence_number_hi++;
  1920. }
  1921. else {
  1922. seq[0] = ssl->keys.sequence_number_hi;
  1923. seq[1] = ssl->keys.sequence_number_lo++;
  1924. /* handle rollover */
  1925. if (seq[1] > ssl->keys.sequence_number_lo)
  1926. ssl->keys.sequence_number_hi++;
  1927. }
  1928. c32toa(seq[0], out);
  1929. c32toa(seq[1], out + OPAQUE32_LEN);
  1930. }
  1931. /* Build the nonce for TLS v1.3 encryption and decryption.
  1932. *
  1933. * ssl The SSL/TLS object.
  1934. * nonce The nonce data to use when encrypting or decrypting.
  1935. * iv The derived IV.
  1936. * order The side on which the message is to be or was sent.
  1937. */
  1938. static WC_INLINE void BuildTls13Nonce(WOLFSSL* ssl, byte* nonce, const byte* iv,
  1939. int order)
  1940. {
  1941. int i;
  1942. /* The nonce is the IV with the sequence XORed into the last bytes. */
  1943. WriteSEQTls13(ssl, order, nonce + AEAD_NONCE_SZ - SEQ_SZ);
  1944. for (i = 0; i < AEAD_NONCE_SZ - SEQ_SZ; i++)
  1945. nonce[i] = iv[i];
  1946. for (; i < AEAD_NONCE_SZ; i++)
  1947. nonce[i] ^= iv[i];
  1948. }
  1949. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  1950. /* Encrypt with ChaCha20 and create authentication tag with Poly1305.
  1951. *
  1952. * ssl The SSL/TLS object.
  1953. * output The buffer to write encrypted data and authentication tag into.
  1954. * May be the same pointer as input.
  1955. * input The data to encrypt.
  1956. * sz The number of bytes to encrypt.
  1957. * nonce The nonce to use with ChaCha20.
  1958. * aad The additional authentication data.
  1959. * aadSz The size of the addition authentication data.
  1960. * tag The authentication tag buffer.
  1961. * returns 0 on success, otherwise failure.
  1962. */
  1963. static int ChaCha20Poly1305_Encrypt(WOLFSSL* ssl, byte* output,
  1964. const byte* input, word16 sz, byte* nonce,
  1965. const byte* aad, word16 aadSz, byte* tag)
  1966. {
  1967. int ret = 0;
  1968. byte poly[CHACHA20_256_KEY_SIZE];
  1969. /* Poly1305 key is 256 bits of zero encrypted with ChaCha20. */
  1970. XMEMSET(poly, 0, sizeof(poly));
  1971. /* Set the nonce for ChaCha and get Poly1305 key. */
  1972. ret = wc_Chacha_SetIV(ssl->encrypt.chacha, nonce, 0);
  1973. if (ret != 0)
  1974. return ret;
  1975. /* Create Poly1305 key using ChaCha20 keystream. */
  1976. ret = wc_Chacha_Process(ssl->encrypt.chacha, poly, poly, sizeof(poly));
  1977. if (ret != 0)
  1978. return ret;
  1979. #ifdef WOLFSSL_CHECK_MEM_ZERO
  1980. wc_MemZero_Add("ChaCha20Poly1305_Encrypt poly", poly, sizeof(poly));
  1981. #endif
  1982. ret = wc_Chacha_SetIV(ssl->encrypt.chacha, nonce, 1);
  1983. if (ret != 0)
  1984. return ret;
  1985. /* Encrypt the plain text. */
  1986. ret = wc_Chacha_Process(ssl->encrypt.chacha, output, input, sz);
  1987. if (ret != 0) {
  1988. ForceZero(poly, sizeof(poly));
  1989. #ifdef WOLFSSL_CHECK_MEM_ZERO
  1990. wc_MemZero_Check(poly, sizeof(poly));
  1991. #endif
  1992. return ret;
  1993. }
  1994. /* Set key for Poly1305. */
  1995. ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly, sizeof(poly));
  1996. ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
  1997. #ifdef WOLFSSL_CHECK_MEM_ZERO
  1998. wc_MemZero_Check(poly, sizeof(poly));
  1999. #endif
  2000. if (ret != 0)
  2001. return ret;
  2002. /* Add authentication code of encrypted data to end. */
  2003. ret = wc_Poly1305_MAC(ssl->auth.poly1305, aad, aadSz, output, sz, tag,
  2004. POLY1305_AUTH_SZ);
  2005. return ret;
  2006. }
  2007. #endif
  2008. #ifdef HAVE_NULL_CIPHER
  2009. /* Create authentication tag and copy data over input.
  2010. *
  2011. * ssl The SSL/TLS object.
  2012. * output The buffer to copy data into.
  2013. * May be the same pointer as input.
  2014. * input The data.
  2015. * sz The number of bytes of data.
  2016. * nonce The nonce to use with authentication.
  2017. * aad The additional authentication data.
  2018. * aadSz The size of the addition authentication data.
  2019. * tag The authentication tag buffer.
  2020. * returns 0 on success, otherwise failure.
  2021. */
  2022. static int Tls13IntegrityOnly_Encrypt(WOLFSSL* ssl, byte* output,
  2023. const byte* input, word16 sz,
  2024. const byte* nonce,
  2025. const byte* aad, word16 aadSz, byte* tag)
  2026. {
  2027. int ret;
  2028. /* HMAC: nonce | aad | input */
  2029. ret = wc_HmacUpdate(ssl->encrypt.hmac, nonce, HMAC_NONCE_SZ);
  2030. if (ret == 0)
  2031. ret = wc_HmacUpdate(ssl->encrypt.hmac, aad, aadSz);
  2032. if (ret == 0)
  2033. ret = wc_HmacUpdate(ssl->encrypt.hmac, input, sz);
  2034. if (ret == 0)
  2035. ret = wc_HmacFinal(ssl->encrypt.hmac, tag);
  2036. /* Copy the input to output if not the same buffer */
  2037. if (ret == 0 && output != input)
  2038. XMEMCPY(output, input, sz);
  2039. return ret;
  2040. }
  2041. #endif
  2042. /* Encrypt data for TLS v1.3.
  2043. *
  2044. * ssl The SSL/TLS object.
  2045. * output The buffer to write encrypted data and authentication tag into.
  2046. * May be the same pointer as input.
  2047. * input The record header and data to encrypt.
  2048. * sz The number of bytes to encrypt.
  2049. * aad The additional authentication data.
  2050. * aadSz The size of the addition authentication data.
  2051. * asyncOkay If non-zero can return WC_PENDING_E, otherwise blocks on crypto
  2052. * returns 0 on success, otherwise failure.
  2053. */
  2054. static int EncryptTls13(WOLFSSL* ssl, byte* output, const byte* input,
  2055. word16 sz, const byte* aad, word16 aadSz, int asyncOkay)
  2056. {
  2057. int ret = 0;
  2058. word16 dataSz = sz - ssl->specs.aead_mac_size;
  2059. word16 macSz = ssl->specs.aead_mac_size;
  2060. word32 nonceSz = 0;
  2061. #ifdef WOLFSSL_ASYNC_CRYPT
  2062. WC_ASYNC_DEV* asyncDev = NULL;
  2063. word32 event_flags = WC_ASYNC_FLAG_CALL_AGAIN;
  2064. #endif
  2065. WOLFSSL_ENTER("EncryptTls13");
  2066. (void)output;
  2067. (void)input;
  2068. (void)sz;
  2069. (void)dataSz;
  2070. (void)macSz;
  2071. (void)asyncOkay;
  2072. (void)nonceSz;
  2073. #ifdef WOLFSSL_ASYNC_CRYPT
  2074. if (ssl->error == WC_PENDING_E) {
  2075. ssl->error = 0; /* clear async */
  2076. }
  2077. #endif
  2078. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  2079. ret = tsip_Tls13AesEncrypt(ssl, output, input, dataSz);
  2080. if (ret != CRYPTOCB_UNAVAILABLE) {
  2081. if (ret > 0) {
  2082. ret = 0; /* tsip_Tls13AesEncrypt returns output size */
  2083. }
  2084. return ret;
  2085. }
  2086. ret = 0;
  2087. #endif /* WOLFSSL_RENESAS_TSIP_TLS && WOLFSSL_RENESAS_TSIP_VER >= 115 */
  2088. switch (ssl->encrypt.state) {
  2089. case CIPHER_STATE_BEGIN:
  2090. {
  2091. #ifdef WOLFSSL_DEBUG_TLS
  2092. WOLFSSL_MSG("Data to encrypt");
  2093. WOLFSSL_BUFFER(input, dataSz);
  2094. WOLFSSL_MSG("Additional Authentication Data");
  2095. WOLFSSL_BUFFER(aad, aadSz);
  2096. #endif
  2097. #ifdef WOLFSSL_CIPHER_TEXT_CHECK
  2098. if (ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) {
  2099. XMEMCPY(ssl->encrypt.sanityCheck, input,
  2100. min(dataSz, sizeof(ssl->encrypt.sanityCheck)));
  2101. }
  2102. #endif
  2103. #ifdef CIPHER_NONCE
  2104. if (ssl->encrypt.nonce == NULL) {
  2105. ssl->encrypt.nonce = (byte*)XMALLOC(AEAD_NONCE_SZ,
  2106. ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
  2107. #ifdef WOLFSSL_CHECK_MEM_ZERO
  2108. if (ssl->encrypt.nonce != NULL) {
  2109. wc_MemZero_Add("EncryptTls13 nonce", ssl->encrypt.nonce,
  2110. AEAD_NONCE_SZ);
  2111. }
  2112. #endif
  2113. }
  2114. if (ssl->encrypt.nonce == NULL)
  2115. return MEMORY_E;
  2116. BuildTls13Nonce(ssl, ssl->encrypt.nonce, ssl->keys.aead_enc_imp_IV,
  2117. CUR_ORDER);
  2118. #endif
  2119. /* Advance state and proceed */
  2120. ssl->encrypt.state = CIPHER_STATE_DO;
  2121. }
  2122. FALL_THROUGH;
  2123. case CIPHER_STATE_DO:
  2124. {
  2125. switch (ssl->specs.bulk_cipher_algorithm) {
  2126. #ifdef BUILD_AESGCM
  2127. case wolfssl_aes_gcm:
  2128. #ifdef WOLFSSL_ASYNC_CRYPT
  2129. /* initialize event */
  2130. asyncDev = &ssl->encrypt.aes->asyncDev;
  2131. ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
  2132. if (ret != 0)
  2133. break;
  2134. #endif
  2135. nonceSz = AESGCM_NONCE_SZ;
  2136. #if ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
  2137. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
  2138. ret = wc_AesGcmEncrypt(ssl->encrypt.aes, output, input,
  2139. dataSz, ssl->encrypt.nonce, nonceSz,
  2140. output + dataSz, macSz, aad, aadSz);
  2141. #else
  2142. ret = wc_AesGcmSetExtIV(ssl->encrypt.aes,
  2143. ssl->encrypt.nonce, nonceSz);
  2144. if (ret == 0) {
  2145. ret = wc_AesGcmEncrypt_ex(ssl->encrypt.aes, output,
  2146. input, dataSz, ssl->encrypt.nonce, nonceSz,
  2147. output + dataSz, macSz, aad, aadSz);
  2148. }
  2149. #endif
  2150. break;
  2151. #endif
  2152. #ifdef HAVE_AESCCM
  2153. case wolfssl_aes_ccm:
  2154. #ifdef WOLFSSL_ASYNC_CRYPT
  2155. /* initialize event */
  2156. asyncDev = &ssl->encrypt.aes->asyncDev;
  2157. ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
  2158. if (ret != 0)
  2159. break;
  2160. #endif
  2161. nonceSz = AESCCM_NONCE_SZ;
  2162. #if ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
  2163. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
  2164. ret = wc_AesCcmEncrypt(ssl->encrypt.aes, output, input,
  2165. dataSz, ssl->encrypt.nonce, nonceSz,
  2166. output + dataSz, macSz, aad, aadSz);
  2167. #else
  2168. ret = wc_AesCcmSetNonce(ssl->encrypt.aes,
  2169. ssl->encrypt.nonce, nonceSz);
  2170. if (ret == 0) {
  2171. ret = wc_AesCcmEncrypt_ex(ssl->encrypt.aes, output,
  2172. input, dataSz, ssl->encrypt.nonce, nonceSz,
  2173. output + dataSz, macSz, aad, aadSz);
  2174. }
  2175. #endif
  2176. break;
  2177. #endif
  2178. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  2179. case wolfssl_chacha:
  2180. ret = ChaCha20Poly1305_Encrypt(ssl, output, input, dataSz,
  2181. ssl->encrypt.nonce, aad, aadSz, output + dataSz);
  2182. break;
  2183. #endif
  2184. #ifdef HAVE_NULL_CIPHER
  2185. case wolfssl_cipher_null:
  2186. ret = Tls13IntegrityOnly_Encrypt(ssl, output, input, dataSz,
  2187. ssl->encrypt.nonce, aad, aadSz, output + dataSz);
  2188. break;
  2189. #endif
  2190. default:
  2191. WOLFSSL_MSG("wolfSSL Encrypt programming error");
  2192. return ENCRYPT_ERROR;
  2193. }
  2194. /* Advance state */
  2195. ssl->encrypt.state = CIPHER_STATE_END;
  2196. #ifdef WOLFSSL_ASYNC_CRYPT
  2197. if (ret == WC_PENDING_E) {
  2198. /* if async is not okay, then block */
  2199. if (!asyncOkay) {
  2200. ret = wc_AsyncWait(ret, asyncDev, event_flags);
  2201. }
  2202. else {
  2203. /* If pending, then leave and return will resume below */
  2204. return wolfSSL_AsyncPush(ssl, asyncDev);
  2205. }
  2206. }
  2207. #endif
  2208. }
  2209. FALL_THROUGH;
  2210. case CIPHER_STATE_END:
  2211. {
  2212. #ifdef WOLFSSL_DEBUG_TLS
  2213. #ifdef CIPHER_NONCE
  2214. WOLFSSL_MSG("Nonce");
  2215. WOLFSSL_BUFFER(ssl->encrypt.nonce, ssl->specs.iv_size);
  2216. #endif
  2217. WOLFSSL_MSG("Encrypted data");
  2218. WOLFSSL_BUFFER(output, dataSz);
  2219. WOLFSSL_MSG("Authentication Tag");
  2220. WOLFSSL_BUFFER(output + dataSz, macSz);
  2221. #endif
  2222. #ifdef WOLFSSL_CIPHER_TEXT_CHECK
  2223. if (ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null &&
  2224. XMEMCMP(output, ssl->encrypt.sanityCheck,
  2225. min(dataSz, sizeof(ssl->encrypt.sanityCheck))) == 0) {
  2226. WOLFSSL_MSG("EncryptTls13 sanity check failed! Glitch?");
  2227. return ENCRYPT_ERROR;
  2228. }
  2229. ForceZero(ssl->encrypt.sanityCheck,
  2230. sizeof(ssl->encrypt.sanityCheck));
  2231. #endif
  2232. #ifdef WOLFSSL_CHECK_MEM_ZERO
  2233. if ((ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) &&
  2234. (output != input) && (ret == 0)) {
  2235. wc_MemZero_Add("TLS 1.3 Encrypt plaintext", input, sz);
  2236. }
  2237. #endif
  2238. #ifdef CIPHER_NONCE
  2239. ForceZero(ssl->encrypt.nonce, AEAD_NONCE_SZ);
  2240. #endif
  2241. break;
  2242. }
  2243. default:
  2244. break;
  2245. }
  2246. /* Reset state */
  2247. ssl->encrypt.state = CIPHER_STATE_BEGIN;
  2248. return ret;
  2249. }
  2250. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  2251. /* Decrypt with ChaCha20 and check authentication tag with Poly1305.
  2252. *
  2253. * ssl The SSL/TLS object.
  2254. * output The buffer to write decrypted data into.
  2255. * May be the same pointer as input.
  2256. * input The data to decrypt.
  2257. * sz The number of bytes to decrypt.
  2258. * nonce The nonce to use with ChaCha20.
  2259. * aad The additional authentication data.
  2260. * aadSz The size of the addition authentication data.
  2261. * tagIn The authentication tag data from packet.
  2262. * returns 0 on success, otherwise failure.
  2263. */
  2264. static int ChaCha20Poly1305_Decrypt(WOLFSSL* ssl, byte* output,
  2265. const byte* input, word16 sz, byte* nonce,
  2266. const byte* aad, word16 aadSz,
  2267. const byte* tagIn)
  2268. {
  2269. int ret;
  2270. byte tag[POLY1305_AUTH_SZ];
  2271. byte poly[CHACHA20_256_KEY_SIZE]; /* generated key for mac */
  2272. /* Poly1305 key is 256 bits of zero encrypted with ChaCha20. */
  2273. XMEMSET(poly, 0, sizeof(poly));
  2274. /* Set nonce and get Poly1305 key. */
  2275. ret = wc_Chacha_SetIV(ssl->decrypt.chacha, nonce, 0);
  2276. if (ret != 0)
  2277. return ret;
  2278. /* Use ChaCha20 keystream to get Poly1305 key for tag. */
  2279. ret = wc_Chacha_Process(ssl->decrypt.chacha, poly, poly, sizeof(poly));
  2280. if (ret != 0)
  2281. return ret;
  2282. #ifdef WOLFSSL_CHECK_MEM_ZERO
  2283. wc_MemZero_Add("ChaCha20Poly1305_Decrypt poly", poly, sizeof(poly));
  2284. #endif
  2285. ret = wc_Chacha_SetIV(ssl->decrypt.chacha, nonce, 1);
  2286. if (ret != 0) {
  2287. ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
  2288. #ifdef WOLFSSL_CHECK_MEM_ZERO
  2289. wc_MemZero_Check(poly, sizeof(poly));
  2290. #endif
  2291. return ret;
  2292. }
  2293. /* Set key for Poly1305. */
  2294. ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly, sizeof(poly));
  2295. ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
  2296. #ifdef WOLFSSL_CHECK_MEM_ZERO
  2297. wc_MemZero_Check(poly, sizeof(poly));
  2298. #endif
  2299. if (ret != 0)
  2300. return ret;
  2301. /* Generate authentication tag for encrypted data. */
  2302. if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, aad, aadSz, input, sz, tag,
  2303. sizeof(tag))) != 0) {
  2304. return ret;
  2305. }
  2306. /* Check tag sent along with packet. */
  2307. if (ConstantCompare(tagIn, tag, POLY1305_AUTH_SZ) != 0) {
  2308. WOLFSSL_MSG("MAC did not match");
  2309. return VERIFY_MAC_ERROR;
  2310. }
  2311. /* If the tag was good decrypt message. */
  2312. ret = wc_Chacha_Process(ssl->decrypt.chacha, output, input, sz);
  2313. return ret;
  2314. }
  2315. #endif
  2316. #ifdef HAVE_NULL_CIPHER
  2317. /* Check HMAC tag and copy over input.
  2318. *
  2319. * ssl The SSL/TLS object.
  2320. * output The buffer to copy data into.
  2321. * May be the same pointer as input.
  2322. * input The data.
  2323. * sz The number of bytes of data.
  2324. * nonce The nonce to use with authentication.
  2325. * aad The additional authentication data.
  2326. * aadSz The size of the addition authentication data.
  2327. * tagIn The authentication tag data from packet.
  2328. * returns 0 on success, otherwise failure.
  2329. */
  2330. static int Tls13IntegrityOnly_Decrypt(WOLFSSL* ssl, byte* output,
  2331. const byte* input, word16 sz,
  2332. const byte* nonce,
  2333. const byte* aad, word16 aadSz,
  2334. const byte* tagIn)
  2335. {
  2336. int ret;
  2337. byte hmac[WC_MAX_DIGEST_SIZE];
  2338. /* HMAC: nonce | aad | input */
  2339. ret = wc_HmacUpdate(ssl->decrypt.hmac, nonce, HMAC_NONCE_SZ);
  2340. if (ret == 0)
  2341. ret = wc_HmacUpdate(ssl->decrypt.hmac, aad, aadSz);
  2342. if (ret == 0)
  2343. ret = wc_HmacUpdate(ssl->decrypt.hmac, input, sz);
  2344. if (ret == 0)
  2345. ret = wc_HmacFinal(ssl->decrypt.hmac, hmac);
  2346. /* Check authentication tag matches */
  2347. if (ret == 0 && ConstantCompare(tagIn, hmac, ssl->specs.hash_size) != 0)
  2348. ret = DECRYPT_ERROR;
  2349. /* Copy the input to output if not the same buffer */
  2350. if (ret == 0 && output != input)
  2351. XMEMCPY(output, input, sz);
  2352. return ret;
  2353. }
  2354. #endif
  2355. /* Decrypt data for TLS v1.3.
  2356. *
  2357. * ssl The SSL/TLS object.
  2358. * output The buffer to write decrypted data into.
  2359. * May be the same pointer as input.
  2360. * input The data to decrypt and authentication tag.
  2361. * sz The length of the encrypted data plus authentication tag.
  2362. * aad The additional authentication data.
  2363. * aadSz The size of the addition authentication data.
  2364. * returns 0 on success, otherwise failure.
  2365. */
  2366. int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz,
  2367. const byte* aad, word16 aadSz)
  2368. {
  2369. int ret = 0;
  2370. word16 dataSz = sz - ssl->specs.aead_mac_size;
  2371. word16 macSz = ssl->specs.aead_mac_size;
  2372. word32 nonceSz = 0;
  2373. WOLFSSL_ENTER("DecryptTls13");
  2374. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  2375. ret = tsip_Tls13AesDecrypt(ssl, output, input, sz);
  2376. if (ret != CRYPTOCB_UNAVAILABLE) {
  2377. #ifndef WOLFSSL_EARLY_DATA
  2378. if (ret < 0) {
  2379. ret = VERIFY_MAC_ERROR;
  2380. WOLFSSL_ERROR_VERBOSE(ret);
  2381. }
  2382. #endif
  2383. return ret;
  2384. }
  2385. #endif
  2386. #ifdef WOLFSSL_ASYNC_CRYPT
  2387. ret = wolfSSL_AsyncPop(ssl, &ssl->decrypt.state);
  2388. if (ret != WC_NOT_PENDING_E) {
  2389. /* check for still pending */
  2390. if (ret == WC_PENDING_E)
  2391. return ret;
  2392. ssl->error = 0; /* clear async */
  2393. /* let failures through so CIPHER_STATE_END logic is run */
  2394. }
  2395. else
  2396. #endif
  2397. {
  2398. /* Reset state */
  2399. ret = 0;
  2400. ssl->decrypt.state = CIPHER_STATE_BEGIN;
  2401. }
  2402. (void)output;
  2403. (void)input;
  2404. (void)sz;
  2405. (void)dataSz;
  2406. (void)macSz;
  2407. (void)nonceSz;
  2408. switch (ssl->decrypt.state) {
  2409. case CIPHER_STATE_BEGIN:
  2410. {
  2411. #ifdef WOLFSSL_DEBUG_TLS
  2412. WOLFSSL_MSG("Data to decrypt");
  2413. WOLFSSL_BUFFER(input, dataSz);
  2414. WOLFSSL_MSG("Additional Authentication Data");
  2415. WOLFSSL_BUFFER(aad, aadSz);
  2416. WOLFSSL_MSG("Authentication tag");
  2417. WOLFSSL_BUFFER(input + dataSz, macSz);
  2418. #endif
  2419. #ifdef CIPHER_NONCE
  2420. if (ssl->decrypt.nonce == NULL) {
  2421. ssl->decrypt.nonce = (byte*)XMALLOC(AEAD_NONCE_SZ,
  2422. ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
  2423. #ifdef WOLFSSL_CHECK_MEM_ZERO
  2424. if (ssl->decrypt.nonce != NULL) {
  2425. wc_MemZero_Add("DecryptTls13 nonce", ssl->decrypt.nonce,
  2426. AEAD_NONCE_SZ);
  2427. }
  2428. #endif
  2429. }
  2430. if (ssl->decrypt.nonce == NULL)
  2431. return MEMORY_E;
  2432. BuildTls13Nonce(ssl, ssl->decrypt.nonce, ssl->keys.aead_dec_imp_IV,
  2433. PEER_ORDER);
  2434. #endif
  2435. /* Advance state and proceed */
  2436. ssl->decrypt.state = CIPHER_STATE_DO;
  2437. }
  2438. FALL_THROUGH;
  2439. case CIPHER_STATE_DO:
  2440. {
  2441. switch (ssl->specs.bulk_cipher_algorithm) {
  2442. #ifdef BUILD_AESGCM
  2443. case wolfssl_aes_gcm:
  2444. #ifdef WOLFSSL_ASYNC_CRYPT
  2445. /* initialize event */
  2446. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
  2447. WC_ASYNC_FLAG_NONE);
  2448. if (ret != 0)
  2449. break;
  2450. #endif
  2451. nonceSz = AESGCM_NONCE_SZ;
  2452. ret = wc_AesGcmDecrypt(ssl->decrypt.aes, output, input,
  2453. dataSz, ssl->decrypt.nonce, nonceSz,
  2454. input + dataSz, macSz, aad, aadSz);
  2455. #ifdef WOLFSSL_ASYNC_CRYPT
  2456. if (ret == WC_PENDING_E) {
  2457. ret = wolfSSL_AsyncPush(ssl,
  2458. &ssl->decrypt.aes->asyncDev);
  2459. }
  2460. #endif
  2461. break;
  2462. #endif
  2463. #ifdef HAVE_AESCCM
  2464. case wolfssl_aes_ccm:
  2465. #ifdef WOLFSSL_ASYNC_CRYPT
  2466. /* initialize event */
  2467. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
  2468. WC_ASYNC_FLAG_NONE);
  2469. if (ret != 0)
  2470. break;
  2471. #endif
  2472. nonceSz = AESCCM_NONCE_SZ;
  2473. ret = wc_AesCcmDecrypt(ssl->decrypt.aes, output, input,
  2474. dataSz, ssl->decrypt.nonce, nonceSz,
  2475. input + dataSz, macSz, aad, aadSz);
  2476. #ifdef WOLFSSL_ASYNC_CRYPT
  2477. if (ret == WC_PENDING_E) {
  2478. ret = wolfSSL_AsyncPush(ssl,
  2479. &ssl->decrypt.aes->asyncDev);
  2480. }
  2481. #endif
  2482. break;
  2483. #endif
  2484. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  2485. case wolfssl_chacha:
  2486. ret = ChaCha20Poly1305_Decrypt(ssl, output, input, dataSz,
  2487. ssl->decrypt.nonce, aad, aadSz, input + dataSz);
  2488. break;
  2489. #endif
  2490. #ifdef HAVE_NULL_CIPHER
  2491. case wolfssl_cipher_null:
  2492. ret = Tls13IntegrityOnly_Decrypt(ssl, output, input, dataSz,
  2493. ssl->decrypt.nonce, aad, aadSz, input + dataSz);
  2494. break;
  2495. #endif
  2496. default:
  2497. WOLFSSL_MSG("wolfSSL Decrypt programming error");
  2498. return DECRYPT_ERROR;
  2499. }
  2500. /* Advance state */
  2501. ssl->decrypt.state = CIPHER_STATE_END;
  2502. #ifdef WOLFSSL_ASYNC_CRYPT
  2503. /* If pending, leave now */
  2504. if (ret == WC_PENDING_E) {
  2505. return ret;
  2506. }
  2507. #endif
  2508. }
  2509. FALL_THROUGH;
  2510. case CIPHER_STATE_END:
  2511. {
  2512. #ifdef WOLFSSL_DEBUG_TLS
  2513. #ifdef CIPHER_NONCE
  2514. WOLFSSL_MSG("Nonce");
  2515. WOLFSSL_BUFFER(ssl->decrypt.nonce, ssl->specs.iv_size);
  2516. #endif
  2517. WOLFSSL_MSG("Decrypted data");
  2518. WOLFSSL_BUFFER(output, dataSz);
  2519. #endif
  2520. #ifdef WOLFSSL_CHECK_MEM_ZERO
  2521. if ((ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) &&
  2522. (ret == 0)) {
  2523. wc_MemZero_Add("TLS 1.3 Decrypted data", output, sz);
  2524. }
  2525. #endif
  2526. #ifdef CIPHER_NONCE
  2527. ForceZero(ssl->decrypt.nonce, AEAD_NONCE_SZ);
  2528. #endif
  2529. break;
  2530. }
  2531. default:
  2532. break;
  2533. }
  2534. if (ret < 0) {
  2535. WOLFSSL_ERROR_VERBOSE(ret);
  2536. }
  2537. return ret;
  2538. }
  2539. /* Persistable BuildTls13Message arguments */
  2540. typedef struct BuildMsg13Args {
  2541. word32 sz;
  2542. word32 idx;
  2543. word32 headerSz;
  2544. word16 size;
  2545. } BuildMsg13Args;
  2546. static void FreeBuildMsg13Args(WOLFSSL* ssl, void* pArgs)
  2547. {
  2548. BuildMsg13Args* args = (BuildMsg13Args*)pArgs;
  2549. (void)ssl;
  2550. (void)args;
  2551. /* no allocations in BuildTls13Message */
  2552. }
  2553. /* Build SSL Message, encrypted.
  2554. * TLS v1.3 encryption is AEAD only.
  2555. *
  2556. * ssl The SSL/TLS object.
  2557. * output The buffer to write record message to.
  2558. * outSz Size of the buffer being written into.
  2559. * input The record data to encrypt (excluding record header).
  2560. * inSz The size of the record data.
  2561. * type The recorder header content type.
  2562. * hashOutput Whether to hash the unencrypted record data.
  2563. * sizeOnly Only want the size of the record message.
  2564. * asyncOkay If non-zero can return WC_PENDING_E, otherwise blocks on crypto
  2565. * returns the size of the encrypted record message or negative value on error.
  2566. */
  2567. int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input,
  2568. int inSz, int type, int hashOutput, int sizeOnly, int asyncOkay)
  2569. {
  2570. int ret;
  2571. BuildMsg13Args* args;
  2572. BuildMsg13Args lcl_args;
  2573. WOLFSSL_ENTER("BuildTls13Message");
  2574. #ifdef WOLFSSL_ASYNC_CRYPT
  2575. ret = WC_NOT_PENDING_E;
  2576. if (asyncOkay) {
  2577. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  2578. if (ssl->async == NULL) {
  2579. ssl->async = (struct WOLFSSL_ASYNC*)
  2580. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  2581. DYNAMIC_TYPE_ASYNC);
  2582. if (ssl->async == NULL)
  2583. return MEMORY_E;
  2584. }
  2585. args = (BuildMsg13Args*)ssl->async->args;
  2586. ret = wolfSSL_AsyncPop(ssl, &ssl->options.buildMsgState);
  2587. if (ret != WC_NOT_PENDING_E) {
  2588. /* Check for error */
  2589. if (ret < 0)
  2590. goto exit_buildmsg;
  2591. }
  2592. }
  2593. else
  2594. #endif
  2595. {
  2596. args = &lcl_args;
  2597. }
  2598. /* Reset state */
  2599. #ifdef WOLFSSL_ASYNC_CRYPT
  2600. if (ret == WC_NOT_PENDING_E)
  2601. #endif
  2602. {
  2603. ret = 0;
  2604. ssl->options.buildMsgState = BUILD_MSG_BEGIN;
  2605. XMEMSET(args, 0, sizeof(BuildMsg13Args));
  2606. args->headerSz = RECORD_HEADER_SZ;
  2607. #ifdef WOLFSSL_DTLS13
  2608. if (ssl->options.dtls)
  2609. args->headerSz = Dtls13GetRlHeaderLength(ssl, 1);
  2610. #endif /* WOLFSSL_DTLS13 */
  2611. args->sz = args->headerSz + inSz;
  2612. args->idx = args->headerSz;
  2613. #ifdef WOLFSSL_ASYNC_CRYPT
  2614. if (asyncOkay)
  2615. ssl->async->freeArgs = FreeBuildMsg13Args;
  2616. #endif
  2617. }
  2618. switch (ssl->options.buildMsgState) {
  2619. case BUILD_MSG_BEGIN:
  2620. {
  2621. /* catch mistaken sizeOnly parameter */
  2622. if (sizeOnly) {
  2623. if (output || input) {
  2624. WOLFSSL_MSG("BuildTls13Message with sizeOnly "
  2625. "doesn't need input or output");
  2626. return BAD_FUNC_ARG;
  2627. }
  2628. }
  2629. else if (output == NULL || input == NULL) {
  2630. return BAD_FUNC_ARG;
  2631. }
  2632. /* Record layer content type at the end of record data. */
  2633. args->sz++;
  2634. /* Authentication data at the end. */
  2635. args->sz += ssl->specs.aead_mac_size;
  2636. if (sizeOnly)
  2637. return args->sz;
  2638. if (args->sz > (word32)outSz) {
  2639. WOLFSSL_MSG("Oops, want to write past output buffer size");
  2640. return BUFFER_E;
  2641. }
  2642. /* Record data length. */
  2643. args->size = (word16)(args->sz - args->headerSz);
  2644. /* Write/update the record header with the new size.
  2645. * Always have the content type as application data for encrypted
  2646. * messages in TLS v1.3.
  2647. */
  2648. if (ssl->options.dtls) {
  2649. #ifdef WOLFSSL_DTLS13
  2650. Dtls13RlAddCiphertextHeader(ssl, output, args->size);
  2651. #endif /* WOLFSSL_DTLS13 */
  2652. }
  2653. else {
  2654. AddTls13RecordHeader(output, args->size, application_data, ssl);
  2655. }
  2656. /* TLS v1.3 can do in place encryption. */
  2657. if (input != output + args->idx)
  2658. XMEMCPY(output + args->idx, input, inSz);
  2659. args->idx += inSz;
  2660. ssl->options.buildMsgState = BUILD_MSG_HASH;
  2661. }
  2662. FALL_THROUGH;
  2663. case BUILD_MSG_HASH:
  2664. {
  2665. if (hashOutput) {
  2666. ret = HashOutput(ssl, output, args->headerSz + inSz, 0);
  2667. if (ret != 0)
  2668. goto exit_buildmsg;
  2669. }
  2670. /* The real record content type goes at the end of the data. */
  2671. output[args->idx++] = (byte)type;
  2672. ssl->options.buildMsgState = BUILD_MSG_ENCRYPT;
  2673. }
  2674. FALL_THROUGH;
  2675. case BUILD_MSG_ENCRYPT:
  2676. {
  2677. #ifdef WOLFSSL_QUIC
  2678. if (WOLFSSL_IS_QUIC(ssl)) {
  2679. /* QUIC does not use encryption of the TLS Record Layer.
  2680. * Return the original length + added headers
  2681. * and restore it in the record header. */
  2682. AddTls13RecordHeader(output, inSz, type, ssl);
  2683. ret = args->headerSz + inSz;
  2684. goto exit_buildmsg;
  2685. }
  2686. #endif
  2687. #ifdef ATOMIC_USER
  2688. if (ssl->ctx->MacEncryptCb) {
  2689. /* User Record Layer Callback handling */
  2690. byte* mac = output + args->idx;
  2691. output += args->headerSz;
  2692. ret = ssl->ctx->MacEncryptCb(ssl, mac, output, inSz, type, 0,
  2693. output, output, args->size, ssl->MacEncryptCtx);
  2694. }
  2695. else
  2696. #endif
  2697. {
  2698. const byte* aad = output;
  2699. output += args->headerSz;
  2700. ret = EncryptTls13(ssl, output, output, args->size, aad,
  2701. (word16)args->headerSz, asyncOkay);
  2702. #ifdef WOLFSSL_DTLS13
  2703. if (ret == 0 && ssl->options.dtls) {
  2704. /* AAD points to the header. Reuse the variable */
  2705. ret = Dtls13EncryptRecordNumber(ssl, (byte*)aad, (word16)args->sz);
  2706. }
  2707. #endif /* WOLFSSL_DTLS13 */
  2708. }
  2709. break;
  2710. }
  2711. default:
  2712. break;
  2713. }
  2714. exit_buildmsg:
  2715. WOLFSSL_LEAVE("BuildTls13Message", ret);
  2716. #ifdef WOLFSSL_ASYNC_CRYPT
  2717. if (ret == WC_PENDING_E) {
  2718. return ret;
  2719. }
  2720. #endif
  2721. /* make sure build message state is reset */
  2722. ssl->options.buildMsgState = BUILD_MSG_BEGIN;
  2723. /* return sz on success */
  2724. if (ret == 0) {
  2725. ret = args->sz;
  2726. }
  2727. else {
  2728. WOLFSSL_ERROR_VERBOSE(ret);
  2729. }
  2730. /* Final cleanup */
  2731. #ifdef WOLFSSL_ASYNC_CRYPT
  2732. if (asyncOkay)
  2733. FreeAsyncCtx(ssl, 0);
  2734. else
  2735. #endif
  2736. FreeBuildMsg13Args(ssl, args);
  2737. return ret;
  2738. }
  2739. #if !defined(NO_WOLFSSL_CLIENT) || (!defined(NO_WOLFSSL_SERVER) && \
  2740. (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
  2741. defined(WOLFSSL_PSK_ONE_ID)) \
  2742. /* Find the cipher suite in the suites set in the SSL.
  2743. *
  2744. * ssl SSL/TLS object.
  2745. * suite Cipher suite to look for.
  2746. * returns 1 when suite is found in SSL/TLS object's list and 0 otherwise.
  2747. */
  2748. static int FindSuiteSSL(WOLFSSL* ssl, byte* suite)
  2749. {
  2750. word16 i;
  2751. for (i = 0; i < ssl->suites->suiteSz; i += 2) {
  2752. if (ssl->suites->suites[i+0] == suite[0] &&
  2753. ssl->suites->suites[i+1] == suite[1]) {
  2754. return 1;
  2755. }
  2756. }
  2757. return 0;
  2758. }
  2759. #endif
  2760. #ifndef NO_PSK
  2761. /* Get the MAC algorithm for the TLS 1.3 cipher suite.
  2762. *
  2763. * @param [in] suite.
  2764. * @return A value from wc_MACAlgorithm enumeration.
  2765. */
  2766. byte SuiteMac(byte* suite)
  2767. {
  2768. byte mac = no_mac;
  2769. if (suite[0] == TLS13_BYTE) {
  2770. switch (suite[1]) {
  2771. #ifdef BUILD_TLS_AES_128_GCM_SHA256
  2772. case TLS_AES_128_GCM_SHA256:
  2773. mac = sha256_mac;
  2774. break;
  2775. #endif
  2776. #ifdef BUILD_TLS_CHACHA20_POLY1305_SHA256
  2777. case TLS_CHACHA20_POLY1305_SHA256:
  2778. mac = sha256_mac;
  2779. break;
  2780. #endif
  2781. #ifdef BUILD_TLS_AES_128_CCM_SHA256
  2782. case TLS_AES_128_CCM_SHA256:
  2783. mac = sha256_mac;
  2784. break;
  2785. #endif
  2786. #ifdef BUILD_TLS_AES_128_CCM_8_SHA256
  2787. case TLS_AES_128_CCM_8_SHA256:
  2788. mac = sha256_mac;
  2789. break;
  2790. #endif
  2791. #ifdef BUILD_TLS_AES_256_GCM_SHA384
  2792. case TLS_AES_256_GCM_SHA384:
  2793. mac = sha384_mac;
  2794. break;
  2795. #endif
  2796. default:
  2797. break;
  2798. }
  2799. }
  2800. #ifdef HAVE_NULL_CIPHER
  2801. else if (suite[0] == ECC_BYTE) {
  2802. switch (suite[1]) {
  2803. #ifdef BUILD_TLS_SHA256_SHA256
  2804. case TLS_SHA256_SHA256:
  2805. mac = sha256_mac;
  2806. break;
  2807. #endif
  2808. #ifdef BUILD_TLS_SHA384_SHA384
  2809. case TLS_SHA384_SHA384:
  2810. mac = sha384_mac;
  2811. break;
  2812. #endif
  2813. default:
  2814. break;
  2815. }
  2816. }
  2817. #endif
  2818. return mac;
  2819. }
  2820. #endif
  2821. #if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
  2822. /* Create Cookie extension using the hash of the first ClientHello.
  2823. *
  2824. * ssl SSL/TLS object.
  2825. * hash The hash data.
  2826. * hashSz The size of the hash data in bytes.
  2827. * returns 0 on success, otherwise failure.
  2828. */
  2829. static int CreateCookie(WOLFSSL* ssl, byte* hash, byte hashSz)
  2830. {
  2831. int ret;
  2832. byte mac[WC_MAX_DIGEST_SIZE] = {0};
  2833. Hmac cookieHmac;
  2834. byte cookieType = 0;
  2835. byte macSz = 0;
  2836. #if !defined(NO_SHA) && defined(NO_SHA256)
  2837. cookieType = SHA;
  2838. macSz = WC_SHA_DIGEST_SIZE;
  2839. #endif /* NO_SHA */
  2840. #ifndef NO_SHA256
  2841. cookieType = WC_SHA256;
  2842. macSz = WC_SHA256_DIGEST_SIZE;
  2843. #endif /* NO_SHA256 */
  2844. ret = wc_HmacInit(&cookieHmac, ssl->heap, INVALID_DEVID);
  2845. if (ret == 0) {
  2846. ret = wc_HmacSetKey(&cookieHmac, cookieType,
  2847. ssl->buffers.tls13CookieSecret.buffer,
  2848. ssl->buffers.tls13CookieSecret.length);
  2849. }
  2850. if (ret == 0)
  2851. ret = wc_HmacUpdate(&cookieHmac, hash, hashSz);
  2852. #ifdef WOLFSSL_DTLS13
  2853. /* Tie cookie to peer address */
  2854. if (ret == 0) {
  2855. if (ssl->options.dtls && ssl->buffers.dtlsCtx.peer.sz > 0) {
  2856. ret = wc_HmacUpdate(&cookieHmac,
  2857. (byte*)ssl->buffers.dtlsCtx.peer.sa,
  2858. ssl->buffers.dtlsCtx.peer.sz);
  2859. }
  2860. }
  2861. #endif
  2862. if (ret == 0)
  2863. ret = wc_HmacFinal(&cookieHmac, mac);
  2864. wc_HmacFree(&cookieHmac);
  2865. if (ret != 0)
  2866. return ret;
  2867. /* The cookie data is the hash and the integrity check. */
  2868. return TLSX_Cookie_Use(ssl, hash, hashSz, mac, macSz, 1);
  2869. }
  2870. #endif
  2871. #define HRR_MAX_HS_HEADER_SZ HANDSHAKE_HEADER_SZ
  2872. /* Restart the handshake hash with a hash of the previous messages.
  2873. *
  2874. * ssl The SSL/TLS object.
  2875. * returns 0 on success, otherwise failure.
  2876. */
  2877. int RestartHandshakeHash(WOLFSSL* ssl)
  2878. {
  2879. int ret;
  2880. Hashes hashes;
  2881. byte header[HRR_MAX_HS_HEADER_SZ] = {0};
  2882. byte* hash = NULL;
  2883. byte hashSz = 0;
  2884. ret = BuildCertHashes(ssl, &hashes);
  2885. if (ret != 0)
  2886. return ret;
  2887. switch (ssl->specs.mac_algorithm) {
  2888. #ifndef NO_SHA256
  2889. case sha256_mac:
  2890. hash = hashes.sha256;
  2891. break;
  2892. #endif
  2893. #ifdef WOLFSSL_SHA384
  2894. case sha384_mac:
  2895. hash = hashes.sha384;
  2896. break;
  2897. #endif
  2898. #ifdef WOLFSSL_TLS13_SHA512
  2899. case sha512_mac:
  2900. hash = hashes.sha512;
  2901. break;
  2902. #endif
  2903. }
  2904. hashSz = ssl->specs.hash_size;
  2905. /* check hash */
  2906. if (hash == NULL && hashSz > 0)
  2907. return BAD_FUNC_ARG;
  2908. AddTls13HandShakeHeader(header, hashSz, 0, 0, message_hash, ssl);
  2909. #ifdef WOLFSSL_DEBUG_TLS
  2910. WOLFSSL_MSG("Restart Hash");
  2911. WOLFSSL_BUFFER(hash, hashSz);
  2912. #endif
  2913. #if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
  2914. if (ssl->options.sendCookie && ssl->options.side == WOLFSSL_SERVER_END) {
  2915. byte cookie[OPAQUE8_LEN + WC_MAX_DIGEST_SIZE + OPAQUE16_LEN * 2];
  2916. TLSX* ext;
  2917. word32 idx = 0;
  2918. /* Cookie Data = Hash Len | Hash | CS | KeyShare Group */
  2919. cookie[idx++] = hashSz;
  2920. if (hash)
  2921. XMEMCPY(cookie + idx, hash, hashSz);
  2922. idx += hashSz;
  2923. cookie[idx++] = ssl->options.cipherSuite0;
  2924. cookie[idx++] = ssl->options.cipherSuite;
  2925. if ((ext = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE)) != NULL) {
  2926. KeyShareEntry* kse = (KeyShareEntry*)ext->data;
  2927. c16toa(kse->group, cookie + idx);
  2928. idx += OPAQUE16_LEN;
  2929. }
  2930. return CreateCookie(ssl, cookie, idx);
  2931. }
  2932. #endif
  2933. ret = InitHandshakeHashes(ssl);
  2934. if (ret != 0)
  2935. return ret;
  2936. ret = HashRaw(ssl, header, sizeof(header));
  2937. if (ret != 0)
  2938. return ret;
  2939. return HashRaw(ssl, hash, hashSz);
  2940. }
  2941. #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
  2942. /* The value in the random field of a ServerHello to indicate
  2943. * HelloRetryRequest.
  2944. */
  2945. static byte helloRetryRequestRandom[] = {
  2946. 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
  2947. 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
  2948. 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
  2949. 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
  2950. };
  2951. #endif
  2952. #ifndef NO_WOLFSSL_CLIENT
  2953. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  2954. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_PSK_ONE_ID) && \
  2955. !defined(NO_PSK)
  2956. /**
  2957. * convert mac algorithm to WOLFSSL_EVP_MD
  2958. * @param mac_alg mac algorithm
  2959. * @return const WOLFSSL_EVP_MD on successful, otherwise NULL
  2960. */
  2961. static const WOLFSSL_EVP_MD* ssl_handshake_md(const byte mac_alg)
  2962. {
  2963. switch(mac_alg) {
  2964. case no_mac:
  2965. #ifndef NO_MD5
  2966. case md5_mac:
  2967. return wolfSSL_EVP_md5();
  2968. #endif
  2969. #ifndef NO_SHA
  2970. case sha_mac:
  2971. return wolfSSL_EVP_sha1();
  2972. #endif
  2973. #ifdef WOLFSSL_SHA224
  2974. case sha224_mac:
  2975. return wolfSSL_EVP_sha224();
  2976. #endif
  2977. case sha256_mac:
  2978. return wolfSSL_EVP_sha256();
  2979. #ifdef WOLFSSL_SHA384
  2980. case sha384_mac:
  2981. return wolfSSL_EVP_sha384();
  2982. #endif
  2983. #ifdef WOLFSSL_SHA512
  2984. case sha512_mac:
  2985. return wolfSSL_EVP_sha512();
  2986. #endif
  2987. case rmd_mac:
  2988. case blake2b_mac:
  2989. WOLFSSL_MSG("no suitable EVP_MD");
  2990. return NULL;
  2991. default:
  2992. WOLFSSL_MSG("Unknown mac algorithm");
  2993. return NULL;
  2994. }
  2995. }
  2996. #endif
  2997. /* Setup pre-shared key based on the details in the extension data.
  2998. *
  2999. * ssl SSL/TLS object.
  3000. * psk Pre-shared key extension data.
  3001. * clientHello Whether called from client_hello construction.
  3002. * returns 0 on success, PSK_KEY_ERROR when the client PSK callback fails and
  3003. * other negative value on failure.
  3004. */
  3005. static int SetupPskKey(WOLFSSL* ssl, PreSharedKey* psk, int clientHello)
  3006. {
  3007. #if defined(HAVE_SESSION_TICKET) || !defined(WOLFSSL_PSK_ONE_ID)
  3008. int ret;
  3009. #endif
  3010. byte suite[2];
  3011. if (psk == NULL)
  3012. return BAD_FUNC_ARG;
  3013. suite[0] = ssl->options.cipherSuite0;
  3014. suite[1] = ssl->options.cipherSuite;
  3015. #ifdef HAVE_SESSION_TICKET
  3016. if (psk->resumption) {
  3017. if (clientHello) {
  3018. /* Ensure cipher suite is supported or changed suite to one with
  3019. * the same MAC algorithm. */
  3020. if (!FindSuiteSSL(ssl, suite)) {
  3021. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  3022. return PSK_KEY_ERROR;
  3023. }
  3024. /* Setting mac for binder and keys for deriving EarlyData. */
  3025. ret = SetCipherSpecs(ssl);
  3026. if (ret != 0)
  3027. return ret;
  3028. }
  3029. #ifdef WOLFSSL_EARLY_DATA
  3030. if (ssl->session->maxEarlyDataSz == 0)
  3031. ssl->earlyData = no_early_data;
  3032. #endif
  3033. /* Resumption PSK is master secret. */
  3034. ssl->arrays->psk_keySz = ssl->specs.hash_size;
  3035. if ((ret = DeriveResumptionPSK(ssl, ssl->session->ticketNonce.data,
  3036. ssl->session->ticketNonce.len, ssl->arrays->psk_key)) != 0) {
  3037. return ret;
  3038. }
  3039. if (!clientHello) {
  3040. /* CLIENT: using secret in ticket for peer authentication. */
  3041. ssl->options.peerAuthGood = 1;
  3042. }
  3043. }
  3044. #endif
  3045. #ifndef NO_PSK
  3046. if (!psk->resumption) {
  3047. /* Get the pre-shared key. */
  3048. #ifndef WOLFSSL_PSK_ONE_ID
  3049. const char* cipherName = NULL;
  3050. #ifdef OPENSSL_EXTRA
  3051. WOLFSSL_SESSION* psksession = NULL;
  3052. #endif
  3053. /* Set the client identity to use. */
  3054. XMEMSET(ssl->arrays->client_identity, 0,
  3055. sizeof(ssl->arrays->client_identity));
  3056. XMEMCPY(ssl->arrays->client_identity, psk->identity, psk->identityLen);
  3057. #ifdef WOLFSSL_DEBUG_TLS
  3058. WOLFSSL_MSG("PSK cipher suite:");
  3059. WOLFSSL_MSG(GetCipherNameInternal(psk->cipherSuite0, psk->cipherSuite));
  3060. #endif
  3061. /* Get the pre-shared key. */
  3062. #ifdef OPENSSL_EXTRA
  3063. if (ssl->options.session_psk_cb != NULL) {
  3064. const unsigned char* id = NULL;
  3065. size_t idlen = 0;
  3066. const WOLFSSL_EVP_MD* handshake_md = NULL;
  3067. if (ssl->msgsReceived.got_hello_retry_request >= 1) {
  3068. handshake_md = ssl_handshake_md(ssl->specs.mac_algorithm);
  3069. }
  3070. /* OpenSSL compatible callback that gets cached session. */
  3071. if (ssl->options.session_psk_cb(ssl, handshake_md, &id, &idlen,
  3072. &psksession) == 0) {
  3073. wolfSSL_FreeSession(ssl->ctx, psksession);
  3074. WOLFSSL_MSG("psk session callback failed");
  3075. return PSK_KEY_ERROR;
  3076. }
  3077. if (psksession != NULL) {
  3078. if (idlen > MAX_PSK_KEY_LEN) {
  3079. wolfSSL_FreeSession(ssl->ctx, psksession);
  3080. WOLFSSL_MSG("psk key length is too long");
  3081. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  3082. return PSK_KEY_ERROR;
  3083. }
  3084. ssl->arrays->psk_keySz = (word32)idlen;
  3085. XMEMCPY(ssl->arrays->psk_key, id, idlen);
  3086. suite[0] = psksession->cipherSuite0;
  3087. suite[1] = psksession->cipherSuite;
  3088. /* Not needed anymore. */
  3089. wolfSSL_FreeSession(ssl->ctx, psksession);
  3090. /* Leave pointer not NULL to indicate success with callback. */
  3091. }
  3092. }
  3093. if (psksession != NULL) {
  3094. /* Don't try other callbacks - we have an answer. */
  3095. }
  3096. else
  3097. #endif /* OPENSSL_EXTRA */
  3098. if (ssl->options.client_psk_cs_cb != NULL) {
  3099. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  3100. ssl->arrays->client_identity[0] = 0;
  3101. #endif
  3102. /* Lookup key again for next identity. */
  3103. ssl->arrays->psk_keySz = ssl->options.client_psk_cs_cb(
  3104. ssl, ssl->arrays->server_hint,
  3105. ssl->arrays->client_identity, MAX_PSK_ID_LEN,
  3106. ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
  3107. GetCipherNameInternal(psk->cipherSuite0, psk->cipherSuite));
  3108. if (clientHello) {
  3109. /* Use PSK cipher suite. */
  3110. ssl->options.cipherSuite0 = psk->cipherSuite0;
  3111. ssl->options.cipherSuite = psk->cipherSuite;
  3112. }
  3113. else {
  3114. byte pskCS[2] = { psk->cipherSuite0, psk->cipherSuite };
  3115. /* Ensure PSK and negotiated cipher suites have same hash. */
  3116. if (SuiteMac(pskCS) != SuiteMac(suite)) {
  3117. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  3118. return PSK_KEY_ERROR;
  3119. }
  3120. /* Negotiated cipher suite is to be used - update PSK. */
  3121. psk->cipherSuite0 = suite[0];
  3122. psk->cipherSuite = suite[1];
  3123. }
  3124. }
  3125. else if (ssl->options.client_psk_tls13_cb != NULL) {
  3126. byte cipherSuite0;
  3127. byte cipherSuite;
  3128. int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
  3129. ssl->arrays->psk_keySz = ssl->options.client_psk_tls13_cb(ssl,
  3130. ssl->arrays->server_hint, ssl->arrays->client_identity,
  3131. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
  3132. &cipherName);
  3133. if (GetCipherSuiteFromName(cipherName, &cipherSuite0,
  3134. &cipherSuite, &cipherSuiteFlags) != 0) {
  3135. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  3136. return PSK_KEY_ERROR;
  3137. }
  3138. ssl->options.cipherSuite0 = cipherSuite0;
  3139. ssl->options.cipherSuite = cipherSuite;
  3140. (void)cipherSuiteFlags;
  3141. }
  3142. else {
  3143. ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
  3144. ssl->arrays->server_hint, ssl->arrays->client_identity,
  3145. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
  3146. ssl->options.cipherSuite0 = TLS13_BYTE;
  3147. ssl->options.cipherSuite = WOLFSSL_DEF_PSK_CIPHER;
  3148. }
  3149. if (ssl->arrays->psk_keySz == 0 ||
  3150. ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  3151. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  3152. return PSK_KEY_ERROR;
  3153. }
  3154. ret = SetCipherSpecs(ssl);
  3155. if (ret != 0)
  3156. return ret;
  3157. #else
  3158. /* PSK information loaded during setting of default TLS extensions. */
  3159. #endif /* !WOLFSSL_PSK_ONE_ID */
  3160. if (!clientHello && (psk->cipherSuite0 != suite[0] ||
  3161. psk->cipherSuite != suite[1])) {
  3162. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  3163. return PSK_KEY_ERROR;
  3164. }
  3165. if (!clientHello) {
  3166. /* CLIENT: using PSK for peer authentication. */
  3167. ssl->options.peerAuthGood = 1;
  3168. }
  3169. }
  3170. #endif
  3171. if (ssl->options.noPskDheKe) {
  3172. ssl->arrays->preMasterSz = 0;
  3173. }
  3174. /* Derive the early secret using the PSK. */
  3175. return DeriveEarlySecret(ssl);
  3176. }
  3177. /* Derive and write the binders into the ClientHello in space left when
  3178. * writing the Pre-Shared Key extension.
  3179. *
  3180. * ssl The SSL/TLS object.
  3181. * output The buffer containing the ClientHello.
  3182. * idx The index at the end of the completed ClientHello.
  3183. * returns 0 on success and otherwise failure.
  3184. */
  3185. static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx)
  3186. {
  3187. int ret;
  3188. TLSX* ext;
  3189. PreSharedKey* current;
  3190. byte binderKey[WC_MAX_DIGEST_SIZE];
  3191. word16 len;
  3192. WOLFSSL_ENTER("WritePSKBinders");
  3193. ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
  3194. if (ext == NULL)
  3195. return SANITY_MSG_E;
  3196. /* Get the size of the binders to determine where to write binders. */
  3197. ret = TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
  3198. client_hello, &len);
  3199. if (ret < 0)
  3200. return ret;
  3201. idx -= len;
  3202. /* Hash truncated ClientHello - up to binders. */
  3203. #ifdef WOLFSSL_DTLS13
  3204. if (ssl->options.dtls)
  3205. ret = Dtls13HashHandshake(ssl, output + Dtls13GetRlHeaderLength(ssl, 0),
  3206. idx - Dtls13GetRlHeaderLength(ssl, 0));
  3207. else
  3208. #endif /* WOLFSSL_DTLS13 */
  3209. ret = HashOutput(ssl, output, idx, 0);
  3210. if (ret != 0)
  3211. return ret;
  3212. current = (PreSharedKey*)ext->data;
  3213. #ifdef WOLFSSL_CHECK_MEM_ZERO
  3214. if (current != NULL) {
  3215. wc_MemZero_Add("WritePSKBinders binderKey", binderKey,
  3216. sizeof(binderKey));
  3217. }
  3218. #endif
  3219. /* Calculate the binder for each identity based on previous handshake data.
  3220. */
  3221. while (current != NULL) {
  3222. if ((ret = SetupPskKey(ssl, current, 1)) != 0)
  3223. break;
  3224. #ifdef HAVE_SESSION_TICKET
  3225. if (current->resumption)
  3226. ret = DeriveBinderKeyResume(ssl, binderKey);
  3227. #endif
  3228. #ifndef NO_PSK
  3229. if (!current->resumption)
  3230. ret = DeriveBinderKey(ssl, binderKey);
  3231. #endif
  3232. if (ret != 0)
  3233. break;
  3234. /* Derive the Finished message secret. */
  3235. ret = DeriveFinishedSecret(ssl, binderKey,
  3236. ssl->keys.client_write_MAC_secret);
  3237. if (ret != 0)
  3238. break;
  3239. /* Build the HMAC of the handshake message data = binder. */
  3240. ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret,
  3241. current->binder, &current->binderLen);
  3242. if (ret != 0)
  3243. break;
  3244. current = current->next;
  3245. }
  3246. ForceZero(binderKey, sizeof(binderKey));
  3247. #ifdef WOLFSSL_CHECK_MEM_ZERO
  3248. wc_MemZero_Check(binderKey, sizeof(binderKey));
  3249. #endif
  3250. if (ret != 0)
  3251. return ret;
  3252. /* Data entered into extension, now write to message. */
  3253. ret = TLSX_PreSharedKey_WriteBinders((PreSharedKey*)ext->data, output + idx,
  3254. client_hello, &len);
  3255. if (ret < 0)
  3256. return ret;
  3257. /* Hash binders to complete the hash of the ClientHello. */
  3258. ret = HashRaw(ssl, output + idx, len);
  3259. if (ret < 0)
  3260. return ret;
  3261. #ifdef WOLFSSL_EARLY_DATA
  3262. if (ssl->earlyData != no_early_data) {
  3263. if ((ret = SetupPskKey(ssl, (PreSharedKey*)ext->data, 1)) != 0)
  3264. return ret;
  3265. /* Derive early data encryption key. */
  3266. ret = DeriveTls13Keys(ssl, early_data_key, ENCRYPT_SIDE_ONLY, 1);
  3267. if (ret != 0)
  3268. return ret;
  3269. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  3270. return ret;
  3271. #ifdef WOLFSSL_DTLS13
  3272. if (ssl->options.dtls) {
  3273. ret = Dtls13NewEpoch(
  3274. ssl, w64From32(0x0, DTLS13_EPOCH_EARLYDATA), ENCRYPT_SIDE_ONLY);
  3275. if (ret != 0)
  3276. return ret;
  3277. }
  3278. #endif /* WOLFSSL_DTLS13 */
  3279. }
  3280. #endif
  3281. WOLFSSL_LEAVE("WritePSKBinders", ret);
  3282. return ret;
  3283. }
  3284. #endif
  3285. /* handle generation of TLS 1.3 client_hello (1) */
  3286. /* Send a ClientHello message to the server.
  3287. * Include the information required to start a handshake with servers using
  3288. * protocol versions less than TLS v1.3.
  3289. * Only a client will send this message.
  3290. *
  3291. * ssl The SSL/TLS object.
  3292. * returns 0 on success and otherwise failure.
  3293. */
  3294. typedef struct Sch13Args {
  3295. byte* output;
  3296. word32 idx;
  3297. int sendSz;
  3298. word16 length;
  3299. } Sch13Args;
  3300. int SendTls13ClientHello(WOLFSSL* ssl)
  3301. {
  3302. int ret;
  3303. #ifdef WOLFSSL_ASYNC_CRYPT
  3304. Sch13Args* args = NULL;
  3305. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  3306. #else
  3307. Sch13Args args[1];
  3308. #endif
  3309. byte major, tls12minor;
  3310. WOLFSSL_START(WC_FUNC_CLIENT_HELLO_SEND);
  3311. WOLFSSL_ENTER("SendTls13ClientHello");
  3312. if (ssl == NULL) {
  3313. return BAD_FUNC_ARG;
  3314. }
  3315. ssl->options.buildingMsg = 1;
  3316. major = SSLv3_MAJOR;
  3317. tls12minor = TLSv1_2_MINOR;
  3318. #ifdef WOLFSSL_DTLS13
  3319. if (ssl->options.dtls) {
  3320. major = DTLS_MAJOR;
  3321. tls12minor = DTLSv1_2_MINOR;
  3322. }
  3323. #endif /* WOLFSSL_DTLS */
  3324. #ifdef HAVE_SESSION_TICKET
  3325. if (ssl->options.resuming &&
  3326. (ssl->session->version.major != ssl->version.major ||
  3327. ssl->session->version.minor != ssl->version.minor)) {
  3328. #ifndef WOLFSSL_NO_TLS12
  3329. if (ssl->session->version.major == ssl->version.major &&
  3330. ssl->session->version.minor < ssl->version.minor) {
  3331. /* Cannot resume with a different protocol version. */
  3332. ssl->options.resuming = 0;
  3333. ssl->version.major = ssl->session->version.major;
  3334. ssl->version.minor = ssl->session->version.minor;
  3335. return SendClientHello(ssl);
  3336. }
  3337. else
  3338. #endif
  3339. {
  3340. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  3341. return VERSION_ERROR;
  3342. }
  3343. }
  3344. #endif
  3345. if (ssl->suites == NULL) {
  3346. WOLFSSL_MSG("Bad suites pointer in SendTls13ClientHello");
  3347. return SUITES_ERROR;
  3348. }
  3349. #ifdef WOLFSSL_ASYNC_CRYPT
  3350. if (ssl->async == NULL) {
  3351. ssl->async = (struct WOLFSSL_ASYNC*)
  3352. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  3353. DYNAMIC_TYPE_ASYNC);
  3354. if (ssl->async == NULL)
  3355. return MEMORY_E;
  3356. ssl->async->freeArgs = NULL;
  3357. }
  3358. args = (Sch13Args*)ssl->async->args;
  3359. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  3360. if (ret != WC_NOT_PENDING_E) {
  3361. /* Check for error */
  3362. if (ret < 0)
  3363. return ret;
  3364. }
  3365. else
  3366. #endif
  3367. {
  3368. /* Reset state */
  3369. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  3370. XMEMSET(args, 0, sizeof(Sch13Args));
  3371. }
  3372. switch (ssl->options.asyncState) {
  3373. case TLS_ASYNC_BEGIN:
  3374. {
  3375. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  3376. #ifdef WOLFSSL_DTLS13
  3377. if (ssl->options.dtls)
  3378. args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  3379. #endif /* WOLFSSL_DTLS13 */
  3380. /* Version | Random | Session Id | Cipher Suites | Compression */
  3381. args->length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->suites->suiteSz +
  3382. SUITE_LEN + COMP_LEN + ENUM_LEN;
  3383. #ifdef WOLFSSL_QUIC
  3384. if (WOLFSSL_IS_QUIC(ssl)) {
  3385. /* RFC 9001 ch. 8.4 sessionID in ClientHello MUST be 0 length */
  3386. ssl->session->sessionIDSz = 0;
  3387. ssl->options.tls13MiddleBoxCompat = 0;
  3388. }
  3389. else
  3390. #endif
  3391. #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
  3392. {
  3393. args->length += ID_LEN;
  3394. ssl->options.tls13MiddleBoxCompat = 1;
  3395. }
  3396. #else
  3397. if (ssl->session->sessionIDSz > 0)
  3398. args->length += ssl->session->sessionIDSz;
  3399. #endif
  3400. #ifdef WOLFSSL_DTLS13
  3401. if (ssl->options.dtls) {
  3402. /* legacy_cookie_id len */
  3403. args->length += ENUM_LEN;
  3404. /* server sent us an HelloVerifyRequest and we allow downgrade */
  3405. if (ssl->arrays->cookieSz > 0 && ssl->options.downgrade)
  3406. args->length += ssl->arrays->cookieSz;
  3407. }
  3408. #endif /* WOLFSSL_DTLS13 */
  3409. /* Advance state and proceed */
  3410. ssl->options.asyncState = TLS_ASYNC_BUILD;
  3411. } /* case TLS_ASYNC_BEGIN */
  3412. FALL_THROUGH;
  3413. case TLS_ASYNC_BUILD:
  3414. case TLS_ASYNC_DO:
  3415. {
  3416. /* Auto populate extensions supported unless user defined. */
  3417. if ((ret = TLSX_PopulateExtensions(ssl, 0)) != 0)
  3418. return ret;
  3419. /* Advance state and proceed */
  3420. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  3421. } /* case TLS_ASYNC_BUILD */
  3422. FALL_THROUGH;
  3423. case TLS_ASYNC_FINALIZE:
  3424. {
  3425. #ifdef WOLFSSL_EARLY_DATA
  3426. #ifndef NO_PSK
  3427. if (!ssl->options.resuming &&
  3428. ssl->options.client_psk_tls13_cb == NULL &&
  3429. ssl->options.client_psk_cb == NULL)
  3430. #else
  3431. if (!ssl->options.resuming)
  3432. #endif
  3433. ssl->earlyData = no_early_data;
  3434. if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
  3435. ssl->earlyData = no_early_data;
  3436. if (ssl->earlyData == no_early_data)
  3437. TLSX_Remove(&ssl->extensions, TLSX_EARLY_DATA, ssl->heap);
  3438. if (ssl->earlyData != no_early_data &&
  3439. (ret = TLSX_EarlyData_Use(ssl, 0, 0)) < 0) {
  3440. return ret;
  3441. }
  3442. #endif
  3443. #ifdef WOLFSSL_QUIC
  3444. if (WOLFSSL_IS_QUIC(ssl) && IsAtLeastTLSv1_3(ssl->version)) {
  3445. ret = wolfSSL_quic_add_transport_extensions(ssl, client_hello);
  3446. if (ret != 0)
  3447. return ret;
  3448. }
  3449. #endif
  3450. /* Include length of TLS extensions. */
  3451. ret = TLSX_GetRequestSize(ssl, client_hello, &args->length);
  3452. if (ret != 0)
  3453. return ret;
  3454. /* Total message size. */
  3455. args->sendSz = args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
  3456. #ifdef WOLFSSL_DTLS13
  3457. if (ssl->options.dtls)
  3458. args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  3459. #endif /* WOLFSSL_DTLS13 */
  3460. /* Check buffers are big enough and grow if needed. */
  3461. if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0)
  3462. return ret;
  3463. /* Get position in output buffer to write new message to. */
  3464. args->output = ssl->buffers.outputBuffer.buffer +
  3465. ssl->buffers.outputBuffer.length;
  3466. /* Put the record and handshake headers on. */
  3467. AddTls13Headers(args->output, args->length, client_hello, ssl);
  3468. /* Protocol version - negotiation now in extension: supported_versions. */
  3469. args->output[args->idx++] = major;
  3470. args->output[args->idx++] = tls12minor;
  3471. /* Keep for downgrade. */
  3472. ssl->chVersion = ssl->version;
  3473. if (ssl->arrays == NULL) {
  3474. return BAD_FUNC_ARG;
  3475. }
  3476. /* Client Random */
  3477. if (ssl->options.connectState == CONNECT_BEGIN) {
  3478. ret = wc_RNG_GenerateBlock(ssl->rng, args->output + args->idx, RAN_LEN);
  3479. if (ret != 0)
  3480. return ret;
  3481. /* Store random for possible second ClientHello. */
  3482. XMEMCPY(ssl->arrays->clientRandom, args->output + args->idx, RAN_LEN);
  3483. }
  3484. else
  3485. XMEMCPY(args->output + args->idx, ssl->arrays->clientRandom, RAN_LEN);
  3486. args->idx += RAN_LEN;
  3487. if (ssl->session->sessionIDSz > 0) {
  3488. /* Session resumption for old versions of protocol. */
  3489. args->output[args->idx++] = ID_LEN;
  3490. XMEMCPY(args->output + args->idx, ssl->session->sessionID,
  3491. ssl->session->sessionIDSz);
  3492. args->idx += ID_LEN;
  3493. }
  3494. else {
  3495. #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
  3496. if (ssl->options.tls13MiddleBoxCompat) {
  3497. args->output[args->idx++] = ID_LEN;
  3498. XMEMCPY(args->output + args->idx, ssl->arrays->clientRandom, ID_LEN);
  3499. args->idx += ID_LEN;
  3500. }
  3501. else
  3502. #endif /* WOLFSSL_TLS13_MIDDLEBOX_COMPAT */
  3503. {
  3504. /* TLS v1.3 does not use session id - 0 length. */
  3505. args->output[args->idx++] = 0;
  3506. }
  3507. }
  3508. #ifdef WOLFSSL_DTLS13
  3509. if (ssl->options.dtls) {
  3510. args->output[args->idx++] = ssl->arrays->cookieSz;
  3511. if (ssl->arrays->cookieSz > 0) {
  3512. /* We have a cookie saved, so the server sent us an
  3513. * HelloVerifyRequest, it means it is a v1.2 server */
  3514. if (!ssl->options.downgrade)
  3515. return VERSION_ERROR;
  3516. XMEMCPY(args->output + args->idx, ssl->arrays->cookie,
  3517. ssl->arrays->cookieSz);
  3518. args->idx += ssl->arrays->cookieSz;
  3519. }
  3520. }
  3521. #endif /* WOLFSSL_DTLS13 */
  3522. /* Cipher suites */
  3523. c16toa(ssl->suites->suiteSz, args->output + args->idx);
  3524. args->idx += OPAQUE16_LEN;
  3525. XMEMCPY(args->output + args->idx, &ssl->suites->suites,
  3526. ssl->suites->suiteSz);
  3527. args->idx += ssl->suites->suiteSz;
  3528. #ifdef WOLFSSL_DEBUG_TLS
  3529. {
  3530. int ii;
  3531. WOLFSSL_MSG("Ciphers:");
  3532. for (ii = 0 ; ii < ssl->suites->suiteSz; ii += 2) {
  3533. WOLFSSL_MSG(GetCipherNameInternal(ssl->suites->suites[ii+0],
  3534. ssl->suites->suites[ii+1]));
  3535. }
  3536. }
  3537. #endif
  3538. /* Compression not supported in TLS v1.3. */
  3539. args->output[args->idx++] = COMP_LEN;
  3540. args->output[args->idx++] = NO_COMPRESSION;
  3541. /* Write out extensions for a request. */
  3542. args->length = 0;
  3543. ret = TLSX_WriteRequest(ssl, args->output + args->idx, client_hello,
  3544. &args->length);
  3545. if (ret != 0)
  3546. return ret;
  3547. args->idx += args->length;
  3548. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  3549. /* Resumption has a specific set of extensions and binder is calculated
  3550. * for each identity.
  3551. */
  3552. if (TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY)) {
  3553. ret = WritePSKBinders(ssl, args->output, args->idx);
  3554. }
  3555. else
  3556. #endif
  3557. {
  3558. #ifdef WOLFSSL_DTLS13
  3559. if (ssl->options.dtls)
  3560. ret = Dtls13HashHandshake(ssl,
  3561. args->output + Dtls13GetRlHeaderLength(ssl, 0),
  3562. (word16)args->idx - Dtls13GetRlHeaderLength(ssl, 0));
  3563. else
  3564. #endif /* WOLFSSL_DTLS13 */
  3565. ret = HashOutput(ssl, args->output, args->idx, 0);
  3566. }
  3567. if (ret != 0)
  3568. return ret;
  3569. ssl->options.clientState = CLIENT_HELLO_COMPLETE;
  3570. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  3571. if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
  3572. if (ssl->toInfoOn) {
  3573. AddPacketInfo(ssl, "ClientHello", handshake, args->output, args->sendSz,
  3574. WRITE_PROTO, ssl->heap);
  3575. }
  3576. #endif
  3577. ssl->options.buildingMsg = 0;
  3578. #ifdef WOLFSSL_DTLS13
  3579. if (ssl->options.dtls) {
  3580. ret = Dtls13HandshakeSend(ssl, args->output, (word16)args->sendSz,
  3581. (word16)args->idx, client_hello, 0);
  3582. WOLFSSL_LEAVE("SendTls13ClientHello", ret);
  3583. WOLFSSL_END(WC_FUNC_CLIENT_HELLO_SEND);
  3584. return ret;
  3585. }
  3586. #endif /* WOLFSSL_DTLS13 */
  3587. ssl->buffers.outputBuffer.length += args->sendSz;
  3588. /* Advance state and proceed */
  3589. ssl->options.asyncState = TLS_ASYNC_END;
  3590. /* case TLS_ASYNC_BUILD */
  3591. FALL_THROUGH;
  3592. case TLS_ASYNC_END:
  3593. #ifdef WOLFSSL_EARLY_DATA_GROUP
  3594. /* QUIC needs to forward records at their encryption level
  3595. * and is therefore unable to group here */
  3596. if (ssl->earlyData == no_early_data || WOLFSSL_IS_QUIC(ssl))
  3597. #endif
  3598. ret = SendBuffered(ssl);
  3599. break;
  3600. }
  3601. default:
  3602. ret = INPUT_CASE_ERROR;
  3603. } /* switch (ssl->options.asyncState) */
  3604. #ifdef WOLFSSL_ASYNC_CRYPT
  3605. if (ret == 0)
  3606. FreeAsyncCtx(ssl, 0);
  3607. #endif
  3608. WOLFSSL_LEAVE("SendTls13ClientHello", ret);
  3609. WOLFSSL_END(WC_FUNC_CLIENT_HELLO_SEND);
  3610. return ret;
  3611. }
  3612. #if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_CLIENT)
  3613. static int Dtls13DoDowngrade(WOLFSSL* ssl)
  3614. {
  3615. int ret;
  3616. if (ssl->dtls13ClientHello == NULL)
  3617. return BAD_STATE_E;
  3618. /* v1.3 and v1.2 hash messages to compute the transcript hash. When we are
  3619. * using DTLSv1.3 we hash the first clientHello following v1.3 but the
  3620. * server can negotiate a lower version. So we need to re-hash the
  3621. * clientHello to adhere to DTLS <= v1.2 rules. */
  3622. ret = InitHandshakeHashes(ssl);
  3623. if (ret != 0)
  3624. return ret;
  3625. ret = HashRaw(ssl, ssl->dtls13ClientHello, ssl->dtls13ClientHelloSz);
  3626. XFREE(ssl->dtls13ClientHello, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
  3627. ssl->dtls13ClientHello = NULL;
  3628. ssl->dtls13ClientHelloSz = 0;
  3629. ssl->keys.dtls_sequence_number_hi =
  3630. (word16)w64GetHigh32(ssl->dtls13EncryptEpoch->nextSeqNumber);
  3631. ssl->keys.dtls_sequence_number_lo =
  3632. w64GetLow32(ssl->dtls13EncryptEpoch->nextSeqNumber);
  3633. return ret;
  3634. }
  3635. #endif /* WOLFSSL_DTLS13 && !WOLFSSL_NO_CLIENT*/
  3636. /* handle processing of TLS 1.3 server_hello (2) and hello_retry_request (6) */
  3637. /* Handle the ServerHello message from the server.
  3638. * Only a client will receive this message.
  3639. *
  3640. * ssl The SSL/TLS object.
  3641. * input The message buffer.
  3642. * inOutIdx On entry, the index into the message buffer of ServerHello.
  3643. * On exit, the index of byte after the ServerHello message.
  3644. * helloSz The length of the current handshake message.
  3645. * returns 0 on success and otherwise failure.
  3646. */
  3647. typedef struct Dsh13Args {
  3648. ProtocolVersion pv;
  3649. word32 idx;
  3650. word32 begin;
  3651. const byte* sessId;
  3652. word16 totalExtSz;
  3653. byte sessIdSz;
  3654. byte extMsgType;
  3655. } Dsh13Args;
  3656. int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  3657. word32 helloSz, byte* extMsgType)
  3658. {
  3659. int ret;
  3660. byte suite[2];
  3661. byte tls12minor;
  3662. #ifdef WOLFSSL_ASYNC_CRYPT
  3663. Dsh13Args* args = NULL;
  3664. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  3665. #else
  3666. Dsh13Args args[1];
  3667. #endif
  3668. WOLFSSL_START(WC_FUNC_SERVER_HELLO_DO);
  3669. WOLFSSL_ENTER("DoTls13ServerHello");
  3670. tls12minor = TLSv1_2_MINOR;
  3671. #ifdef WOLFSSL_DTLS13
  3672. if (ssl->options.dtls)
  3673. tls12minor = DTLSv1_2_MINOR;
  3674. #endif /* WOLFSSL_DTLS13 */
  3675. if (ssl == NULL || ssl->arrays == NULL)
  3676. return BAD_FUNC_ARG;
  3677. #ifdef WOLFSSL_ASYNC_CRYPT
  3678. if (ssl->async == NULL) {
  3679. ssl->async = (struct WOLFSSL_ASYNC*)
  3680. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  3681. DYNAMIC_TYPE_ASYNC);
  3682. if (ssl->async == NULL)
  3683. return MEMORY_E;
  3684. ssl->async->freeArgs = NULL;
  3685. }
  3686. args = (Dsh13Args*)ssl->async->args;
  3687. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  3688. if (ret != WC_NOT_PENDING_E) {
  3689. /* Check for error */
  3690. if (ret < 0) {
  3691. if (ret == WC_PENDING_E) {
  3692. /* Mark message as not received so it can process again */
  3693. ssl->msgsReceived.got_server_hello = 0;
  3694. }
  3695. return ret;
  3696. }
  3697. }
  3698. else
  3699. #endif
  3700. {
  3701. /* Reset state */
  3702. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  3703. XMEMSET(args, 0, sizeof(Dsh13Args));
  3704. }
  3705. switch (ssl->options.asyncState) {
  3706. case TLS_ASYNC_BEGIN:
  3707. {
  3708. byte b;
  3709. #ifdef WOLFSSL_CALLBACKS
  3710. if (ssl->hsInfoOn) AddPacketName(ssl, "ServerHello");
  3711. if (ssl->toInfoOn) AddLateName("ServerHello", &ssl->timeoutInfo);
  3712. #endif
  3713. /* Protocol version length check. */
  3714. if (helloSz < OPAQUE16_LEN)
  3715. return BUFFER_ERROR;
  3716. args->idx = *inOutIdx;
  3717. args->begin = args->idx;
  3718. /* Protocol version */
  3719. XMEMCPY(&args->pv, input + args->idx, OPAQUE16_LEN);
  3720. args->idx += OPAQUE16_LEN;
  3721. #ifdef WOLFSSL_DTLS
  3722. if (ssl->options.dtls &&
  3723. (args->pv.major != DTLS_MAJOR || args->pv.minor == DTLS_BOGUS_MINOR))
  3724. return VERSION_ERROR;
  3725. #endif /* WOLFSSL_DTLS */
  3726. #ifndef WOLFSSL_NO_TLS12
  3727. {
  3728. byte wantDowngrade;
  3729. wantDowngrade = args->pv.major == ssl->version.major &&
  3730. args->pv.minor < TLSv1_2_MINOR;
  3731. #ifdef WOLFSSL_DTLS13
  3732. if (ssl->options.dtls)
  3733. wantDowngrade = args->pv.major == ssl->version.major &&
  3734. args->pv.minor > DTLSv1_2_MINOR;
  3735. #endif /* WOLFSSL_DTLS13 */
  3736. if (wantDowngrade && ssl->options.downgrade) {
  3737. /* Force client hello version 1.2 to work for static RSA. */
  3738. ssl->chVersion.minor = TLSv1_2_MINOR;
  3739. ssl->version.minor = TLSv1_2_MINOR;
  3740. #ifdef WOLFSSL_DTLS13
  3741. if (ssl->options.dtls) {
  3742. ssl->chVersion.minor = DTLSv1_2_MINOR;
  3743. ssl->version.minor = DTLSv1_2_MINOR;
  3744. ret = Dtls13DoDowngrade(ssl);
  3745. if (ret != 0)
  3746. return ret;
  3747. }
  3748. #endif /* WOLFSSL_DTLS13 */
  3749. return DoServerHello(ssl, input, inOutIdx, helloSz);
  3750. }
  3751. }
  3752. #endif
  3753. if (args->pv.major != ssl->version.major ||
  3754. args->pv.minor != tls12minor) {
  3755. SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version);
  3756. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  3757. return VERSION_ERROR;
  3758. }
  3759. /* Random and session id length check */
  3760. if ((args->idx - args->begin) + RAN_LEN + ENUM_LEN > helloSz)
  3761. return BUFFER_ERROR;
  3762. /* Check if hello retry request */
  3763. if (XMEMCMP(input + args->idx, helloRetryRequestRandom, RAN_LEN) == 0) {
  3764. WOLFSSL_MSG("HelloRetryRequest format");
  3765. *extMsgType = hello_retry_request;
  3766. /* A HelloRetryRequest comes in as an ServerHello for MiddleBox compat.
  3767. * Found message to be a HelloRetryRequest.
  3768. * Don't allow more than one HelloRetryRequest or ServerHello.
  3769. */
  3770. if (ssl->msgsReceived.got_hello_retry_request) {
  3771. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  3772. return DUPLICATE_MSG_E;
  3773. }
  3774. }
  3775. args->extMsgType = *extMsgType;
  3776. /* Server random - keep for debugging. */
  3777. XMEMCPY(ssl->arrays->serverRandom, input + args->idx, RAN_LEN);
  3778. args->idx += RAN_LEN;
  3779. /* Session id */
  3780. args->sessIdSz = input[args->idx++];
  3781. if ((args->idx - args->begin) + args->sessIdSz > helloSz)
  3782. return BUFFER_ERROR;
  3783. args->sessId = input + args->idx;
  3784. args->idx += args->sessIdSz;
  3785. ssl->options.haveSessionId = 1;
  3786. /* Ciphersuite and compression check */
  3787. if ((args->idx - args->begin) + OPAQUE16_LEN + OPAQUE8_LEN > helloSz)
  3788. return BUFFER_ERROR;
  3789. /* Set the cipher suite from the message. */
  3790. ssl->options.cipherSuite0 = input[args->idx++];
  3791. ssl->options.cipherSuite = input[args->idx++];
  3792. #ifdef WOLFSSL_DEBUG_TLS
  3793. WOLFSSL_MSG("Chosen cipher suite:");
  3794. WOLFSSL_MSG(GetCipherNameInternal(ssl->options.cipherSuite0,
  3795. ssl->options.cipherSuite));
  3796. #endif
  3797. /* Compression */
  3798. b = input[args->idx++];
  3799. if (b != 0) {
  3800. WOLFSSL_MSG("Must be no compression types in list");
  3801. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  3802. return INVALID_PARAMETER;
  3803. }
  3804. if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz) {
  3805. if (!ssl->options.downgrade)
  3806. return BUFFER_ERROR;
  3807. #ifndef WOLFSSL_NO_TLS12
  3808. /* Force client hello version 1.2 to work for static RSA. */
  3809. ssl->chVersion.minor = TLSv1_2_MINOR;
  3810. ssl->version.minor = TLSv1_2_MINOR;
  3811. #ifdef WOLFSSL_DTLS13
  3812. if (ssl->options.dtls) {
  3813. ssl->chVersion.minor = DTLSv1_2_MINOR;
  3814. ssl->version.minor = DTLSv1_2_MINOR;
  3815. ret = Dtls13DoDowngrade(ssl);
  3816. if (ret != 0)
  3817. return ret;
  3818. }
  3819. #endif /* WOLFSSL_DTLS13 */
  3820. #endif
  3821. ssl->options.haveEMS = 0;
  3822. if (args->pv.minor < ssl->options.minDowngrade) {
  3823. SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version);
  3824. return VERSION_ERROR;
  3825. }
  3826. #ifndef WOLFSSL_NO_TLS12
  3827. return DoServerHello(ssl, input, inOutIdx, helloSz);
  3828. #else
  3829. SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version);
  3830. return VERSION_ERROR;
  3831. #endif
  3832. }
  3833. if ((args->idx - args->begin) < helloSz) {
  3834. int foundVersion;
  3835. /* Get extension length and length check. */
  3836. if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
  3837. return BUFFER_ERROR;
  3838. ato16(&input[args->idx], &args->totalExtSz);
  3839. args->idx += OPAQUE16_LEN;
  3840. if ((args->idx - args->begin) + args->totalExtSz > helloSz)
  3841. return BUFFER_ERROR;
  3842. /* Need to negotiate version first. */
  3843. if ((ret = TLSX_ParseVersion(ssl, input + args->idx,
  3844. args->totalExtSz, *extMsgType, &foundVersion))) {
  3845. return ret;
  3846. }
  3847. if (!foundVersion) {
  3848. if (!ssl->options.downgrade) {
  3849. WOLFSSL_MSG("Server trying to downgrade to version less than "
  3850. "TLS v1.3");
  3851. SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version);
  3852. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  3853. return VERSION_ERROR;
  3854. }
  3855. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  3856. defined(WOLFSSL_WPAS_SMALL)
  3857. /* Check if client has disabled TLS 1.2 */
  3858. if (args->pv.minor == TLSv1_2_MINOR &&
  3859. (ssl->options.mask & SSL_OP_NO_TLSv1_2) == SSL_OP_NO_TLSv1_2) {
  3860. WOLFSSL_MSG("\tOption set to not allow TLSv1.2");
  3861. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  3862. return VERSION_ERROR;
  3863. }
  3864. #endif
  3865. if (!ssl->options.dtls &&
  3866. args->pv.minor < ssl->options.minDowngrade) {
  3867. SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version);
  3868. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  3869. return VERSION_ERROR;
  3870. }
  3871. if (ssl->options.dtls &&
  3872. args->pv.minor > ssl->options.minDowngrade) {
  3873. SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version);
  3874. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  3875. return VERSION_ERROR;
  3876. }
  3877. ssl->version.minor = args->pv.minor;
  3878. #ifdef WOLFSSL_DTLS13
  3879. if (ssl->options.dtls) {
  3880. ret = Dtls13DoDowngrade(ssl);
  3881. if (ret != 0)
  3882. return ret;
  3883. }
  3884. #endif /* WOLFSSL_DTLS13 */
  3885. }
  3886. }
  3887. #ifdef WOLFSSL_DTLS13
  3888. /* we are sure that version is >= v1.3 now, we can get rid of buffered
  3889. * ClientHello that was buffered to re-compute the hash in case of
  3890. * downgrade */
  3891. if (ssl->options.dtls && ssl->dtls13ClientHello != NULL) {
  3892. XFREE(ssl->dtls13ClientHello, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
  3893. ssl->dtls13ClientHello = NULL;
  3894. ssl->dtls13ClientHelloSz = 0;
  3895. }
  3896. #endif /* WOLFSSL_DTLS13 */
  3897. /* Advance state and proceed */
  3898. ssl->options.asyncState = TLS_ASYNC_BUILD;
  3899. } /* case TLS_ASYNC_BEGIN */
  3900. FALL_THROUGH;
  3901. case TLS_ASYNC_BUILD:
  3902. case TLS_ASYNC_DO:
  3903. {
  3904. /* restore message type */
  3905. *extMsgType = args->extMsgType;
  3906. if (args->totalExtSz > 0) {
  3907. /* Parse and handle extensions. */
  3908. ret = TLSX_Parse(ssl, input + args->idx, args->totalExtSz,
  3909. *extMsgType, NULL);
  3910. if (ret != 0) {
  3911. #ifdef WOLFSSL_ASYNC_CRYPT
  3912. /* Handle async operation */
  3913. if (ret == WC_PENDING_E) {
  3914. /* Mark message as not received so it can process again */
  3915. ssl->msgsReceived.got_server_hello = 0;
  3916. }
  3917. #endif
  3918. return ret;
  3919. }
  3920. if (*extMsgType == hello_retry_request) {
  3921. /* Update counts to reflect change of message type. */
  3922. ssl->msgsReceived.got_hello_retry_request = 1;
  3923. ssl->msgsReceived.got_server_hello = 0;
  3924. }
  3925. args->idx += args->totalExtSz;
  3926. }
  3927. #ifdef WOLFSSL_DTLS_CID
  3928. if (ssl->options.useDtlsCID && *extMsgType == server_hello)
  3929. DtlsCIDOnExtensionsParsed(ssl);
  3930. #endif /* WOLFSSL_DTLS_CID */
  3931. *inOutIdx = args->idx;
  3932. ssl->options.serverState = SERVER_HELLO_COMPLETE;
  3933. #ifdef HAVE_SECRET_CALLBACK
  3934. if (ssl->sessionSecretCb != NULL
  3935. #ifdef HAVE_SESSION_TICKET
  3936. && ssl->session->ticketLen > 0
  3937. #endif
  3938. ) {
  3939. int secretSz = SECRET_LEN;
  3940. ret = ssl->sessionSecretCb(ssl, ssl->session->masterSecret,
  3941. &secretSz, ssl->sessionSecretCtx);
  3942. if (ret != 0 || secretSz != SECRET_LEN) {
  3943. WOLFSSL_ERROR_VERBOSE(SESSION_SECRET_CB_E);
  3944. return SESSION_SECRET_CB_E;
  3945. }
  3946. }
  3947. #endif /* HAVE_SECRET_CALLBACK */
  3948. /* Version only negotiated in extensions for TLS v1.3.
  3949. * Only now do we know how to deal with session id.
  3950. */
  3951. if (!IsAtLeastTLSv1_3(ssl->version)) {
  3952. #ifndef WOLFSSL_NO_TLS12
  3953. ssl->arrays->sessionIDSz = args->sessIdSz;
  3954. if (ssl->arrays->sessionIDSz > ID_LEN) {
  3955. WOLFSSL_MSG("Invalid session ID size");
  3956. ssl->arrays->sessionIDSz = 0;
  3957. return BUFFER_ERROR;
  3958. }
  3959. else if (ssl->arrays->sessionIDSz) {
  3960. XMEMCPY(ssl->arrays->sessionID, args->sessId,
  3961. ssl->arrays->sessionIDSz);
  3962. ssl->options.haveSessionId = 1;
  3963. }
  3964. /* Force client hello version 1.2 to work for static RSA. */
  3965. ssl->chVersion.minor = TLSv1_2_MINOR;
  3966. /* Complete TLS v1.2 processing of ServerHello. */
  3967. ret = CompleteServerHello(ssl);
  3968. #else
  3969. WOLFSSL_MSG("Client using higher version, fatal error");
  3970. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  3971. ret = VERSION_ERROR;
  3972. #endif
  3973. WOLFSSL_LEAVE("DoTls13ServerHello", ret);
  3974. return ret;
  3975. }
  3976. /* Advance state and proceed */
  3977. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  3978. } /* case TLS_ASYNC_BUILD || TLS_ASYNC_DO */
  3979. FALL_THROUGH;
  3980. case TLS_ASYNC_FINALIZE:
  3981. {
  3982. #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
  3983. if (ssl->options.tls13MiddleBoxCompat) {
  3984. if (args->sessIdSz == 0) {
  3985. WOLFSSL_MSG("args->sessIdSz == 0");
  3986. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  3987. return INVALID_PARAMETER;
  3988. }
  3989. if (ssl->session->sessionIDSz != 0) {
  3990. if (ssl->session->sessionIDSz != args->sessIdSz ||
  3991. XMEMCMP(ssl->session->sessionID, args->sessId,
  3992. args->sessIdSz) != 0) {
  3993. WOLFSSL_MSG("session id doesn't match");
  3994. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  3995. return INVALID_PARAMETER;
  3996. }
  3997. }
  3998. else if (XMEMCMP(ssl->arrays->clientRandom, args->sessId,
  3999. args->sessIdSz) != 0) {
  4000. WOLFSSL_MSG("session id doesn't match client random");
  4001. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  4002. return INVALID_PARAMETER;
  4003. }
  4004. }
  4005. else
  4006. #endif /* WOLFSSL_TLS13_MIDDLEBOX_COMPAT */
  4007. #ifdef WOLFSSL_QUIC
  4008. if (WOLFSSL_IS_QUIC(ssl)) {
  4009. if (args->sessIdSz != 0) {
  4010. WOLFSSL_MSG("args->sessIdSz != 0");
  4011. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  4012. return INVALID_PARAMETER;
  4013. }
  4014. }
  4015. else
  4016. #endif /* WOLFSSL_QUIC */
  4017. if (args->sessIdSz != ssl->session->sessionIDSz || (args->sessIdSz > 0 &&
  4018. XMEMCMP(ssl->session->sessionID, args->sessId, args->sessIdSz) != 0))
  4019. {
  4020. WOLFSSL_MSG("Server sent different session id");
  4021. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  4022. return INVALID_PARAMETER;
  4023. }
  4024. ret = SetCipherSpecs(ssl);
  4025. if (ret != 0)
  4026. return ret;
  4027. #ifdef HAVE_NULL_CIPHER
  4028. if (ssl->options.cipherSuite0 == ECC_BYTE &&
  4029. (ssl->options.cipherSuite == TLS_SHA256_SHA256 ||
  4030. ssl->options.cipherSuite == TLS_SHA384_SHA384)) {
  4031. ;
  4032. }
  4033. else
  4034. #endif
  4035. /* Check that the negotiated ciphersuite matches protocol version. */
  4036. if (ssl->options.cipherSuite0 != TLS13_BYTE) {
  4037. WOLFSSL_MSG("Server sent non-TLS13 cipher suite in TLS 1.3 packet");
  4038. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  4039. return INVALID_PARAMETER;
  4040. }
  4041. suite[0] = ssl->options.cipherSuite0;
  4042. suite[1] = ssl->options.cipherSuite;
  4043. if (!FindSuiteSSL(ssl, suite)) {
  4044. WOLFSSL_MSG("Cipher suite not supported on client");
  4045. WOLFSSL_ERROR_VERBOSE(MATCH_SUITE_ERROR);
  4046. return MATCH_SUITE_ERROR;
  4047. }
  4048. if (*extMsgType == server_hello) {
  4049. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  4050. PreSharedKey* psk = NULL;
  4051. TLSX* ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
  4052. if (ext != NULL)
  4053. psk = (PreSharedKey*)ext->data;
  4054. while (psk != NULL && !psk->chosen)
  4055. psk = psk->next;
  4056. if (psk == NULL) {
  4057. ssl->options.resuming = 0;
  4058. ssl->arrays->psk_keySz = 0;
  4059. XMEMSET(ssl->arrays->psk_key, 0, MAX_PSK_KEY_LEN);
  4060. }
  4061. else {
  4062. if ((ret = SetupPskKey(ssl, psk, 0)) != 0)
  4063. return ret;
  4064. ssl->options.pskNegotiated = 1;
  4065. }
  4066. #endif
  4067. ssl->keys.encryptionOn = 1;
  4068. ssl->options.serverState = SERVER_HELLO_COMPLETE;
  4069. }
  4070. else {
  4071. ssl->options.tls1_3 = 1;
  4072. ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
  4073. ret = RestartHandshakeHash(ssl);
  4074. }
  4075. break;
  4076. } /* case TLS_ASYNC_FINALIZE */
  4077. default:
  4078. ret = INPUT_CASE_ERROR;
  4079. } /* switch (ssl->options.asyncState) */
  4080. #ifdef WOLFSSL_ASYNC_CRYPT
  4081. if (ret == 0)
  4082. FreeAsyncCtx(ssl, 0);
  4083. #endif
  4084. WOLFSSL_LEAVE("DoTls13ServerHello", ret);
  4085. WOLFSSL_END(WC_FUNC_SERVER_HELLO_DO);
  4086. return ret;
  4087. }
  4088. /* handle processing TLS 1.3 encrypted_extensions (8) */
  4089. /* Parse and handle an EncryptedExtensions message.
  4090. * Only a client will receive this message.
  4091. *
  4092. * ssl The SSL/TLS object.
  4093. * input The message buffer.
  4094. * inOutIdx On entry, the index into the message buffer of
  4095. * EncryptedExtensions.
  4096. * On exit, the index of byte after the EncryptedExtensions
  4097. * message.
  4098. * totalSz The length of the current handshake message.
  4099. * returns 0 on success and otherwise failure.
  4100. */
  4101. static int DoTls13EncryptedExtensions(WOLFSSL* ssl, const byte* input,
  4102. word32* inOutIdx, word32 totalSz)
  4103. {
  4104. int ret;
  4105. word32 begin = *inOutIdx;
  4106. word32 i = begin;
  4107. word16 totalExtSz;
  4108. WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_DO);
  4109. WOLFSSL_ENTER("DoTls13EncryptedExtensions");
  4110. #ifdef WOLFSSL_CALLBACKS
  4111. if (ssl->hsInfoOn) AddPacketName(ssl, "EncryptedExtensions");
  4112. if (ssl->toInfoOn) AddLateName("EncryptedExtensions", &ssl->timeoutInfo);
  4113. #endif
  4114. /* Length field of extension data. */
  4115. if (totalSz < OPAQUE16_LEN)
  4116. return BUFFER_ERROR;
  4117. ato16(&input[i], &totalExtSz);
  4118. i += OPAQUE16_LEN;
  4119. /* Extension data. */
  4120. if (i - begin + totalExtSz > totalSz)
  4121. return BUFFER_ERROR;
  4122. if ((ret = TLSX_Parse(ssl, input + i, totalExtSz, encrypted_extensions,
  4123. NULL))) {
  4124. return ret;
  4125. }
  4126. /* Move index to byte after message. */
  4127. *inOutIdx = i + totalExtSz;
  4128. /* Always encrypted. */
  4129. *inOutIdx += ssl->keys.padSz;
  4130. #ifdef WOLFSSL_EARLY_DATA
  4131. if (ssl->earlyData != no_early_data) {
  4132. TLSX* ext = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  4133. if (ext == NULL || !ext->val)
  4134. ssl->earlyData = no_early_data;
  4135. }
  4136. #endif
  4137. #ifdef WOLFSSL_EARLY_DATA
  4138. if (ssl->earlyData == no_early_data) {
  4139. ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY);
  4140. if (ret != 0)
  4141. return ret;
  4142. }
  4143. #endif
  4144. ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
  4145. WOLFSSL_LEAVE("DoTls13EncryptedExtensions", ret);
  4146. WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_DO);
  4147. return ret;
  4148. }
  4149. #ifndef NO_CERTS
  4150. /* handle processing TLS v1.3 certificate_request (13) */
  4151. /* Handle a TLS v1.3 CertificateRequest message.
  4152. * This message is always encrypted.
  4153. * Only a client will receive this message.
  4154. *
  4155. * ssl The SSL/TLS object.
  4156. * input The message buffer.
  4157. * inOutIdx On entry, the index into the message buffer of CertificateRequest.
  4158. * On exit, the index of byte after the CertificateRequest message.
  4159. * size The length of the current handshake message.
  4160. * returns 0 on success and otherwise failure.
  4161. */
  4162. static int DoTls13CertificateRequest(WOLFSSL* ssl, const byte* input,
  4163. word32* inOutIdx, word32 size)
  4164. {
  4165. word16 len;
  4166. word32 begin = *inOutIdx;
  4167. int ret = 0;
  4168. Suites peerSuites;
  4169. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  4170. CertReqCtx* certReqCtx;
  4171. #endif
  4172. WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_DO);
  4173. WOLFSSL_ENTER("DoTls13CertificateRequest");
  4174. XMEMSET(&peerSuites, 0, sizeof(Suites));
  4175. #ifdef WOLFSSL_CALLBACKS
  4176. if (ssl->hsInfoOn) AddPacketName(ssl, "CertificateRequest");
  4177. if (ssl->toInfoOn) AddLateName("CertificateRequest", &ssl->timeoutInfo);
  4178. #endif
  4179. if (OPAQUE8_LEN > size)
  4180. return BUFFER_ERROR;
  4181. /* Length of the request context. */
  4182. len = input[(*inOutIdx)++];
  4183. if ((*inOutIdx - begin) + len > size)
  4184. return BUFFER_ERROR;
  4185. if (ssl->options.connectState < FINISHED_DONE && len > 0)
  4186. return BUFFER_ERROR;
  4187. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  4188. /* CertReqCtx has one byte at end for context value.
  4189. * Increase size to handle other implementations sending more than one byte.
  4190. * That is, allocate extra space, over one byte, to hold the context value.
  4191. */
  4192. certReqCtx = (CertReqCtx*)XMALLOC(sizeof(CertReqCtx) + len - 1, ssl->heap,
  4193. DYNAMIC_TYPE_TMP_BUFFER);
  4194. if (certReqCtx == NULL)
  4195. return MEMORY_E;
  4196. certReqCtx->next = ssl->certReqCtx;
  4197. certReqCtx->len = len;
  4198. XMEMCPY(&certReqCtx->ctx, input + *inOutIdx, len);
  4199. ssl->certReqCtx = certReqCtx;
  4200. #endif
  4201. *inOutIdx += len;
  4202. /* TODO: Add support for more extensions:
  4203. * signed_certificate_timestamp, certificate_authorities, oid_filters.
  4204. */
  4205. /* Certificate extensions */
  4206. if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
  4207. return BUFFER_ERROR;
  4208. ato16(input + *inOutIdx, &len);
  4209. *inOutIdx += OPAQUE16_LEN;
  4210. if ((*inOutIdx - begin) + len > size)
  4211. return BUFFER_ERROR;
  4212. if (len == 0)
  4213. return INVALID_PARAMETER;
  4214. if ((ret = TLSX_Parse(ssl, input + *inOutIdx, len, certificate_request,
  4215. &peerSuites))) {
  4216. return ret;
  4217. }
  4218. *inOutIdx += len;
  4219. if ((ssl->buffers.certificate && ssl->buffers.certificate->buffer &&
  4220. ((ssl->buffers.key && ssl->buffers.key->buffer)
  4221. #ifdef HAVE_PK_CALLBACKS
  4222. || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
  4223. #endif
  4224. ))
  4225. #ifdef OPENSSL_EXTRA
  4226. || ssl->ctx->certSetupCb != NULL
  4227. #endif
  4228. ) {
  4229. if (PickHashSigAlgo(ssl, peerSuites.hashSigAlgo,
  4230. peerSuites.hashSigAlgoSz) != 0) {
  4231. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  4232. return INVALID_PARAMETER;
  4233. }
  4234. ssl->options.sendVerify = SEND_CERT;
  4235. }
  4236. else {
  4237. #ifndef WOLFSSL_NO_CLIENT_CERT_ERROR
  4238. ssl->options.sendVerify = SEND_BLANK_CERT;
  4239. #else
  4240. WOLFSSL_MSG("Certificate required but none set on client");
  4241. SendAlert(ssl, alert_fatal, illegal_parameter);
  4242. WOLFSSL_ERROR_VERBOSE(NO_CERT_ERROR);
  4243. return NO_CERT_ERROR;
  4244. #endif
  4245. }
  4246. /* This message is always encrypted so add encryption padding. */
  4247. *inOutIdx += ssl->keys.padSz;
  4248. WOLFSSL_LEAVE("DoTls13CertificateRequest", ret);
  4249. WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_DO);
  4250. return ret;
  4251. }
  4252. #endif /* !NO_CERTS */
  4253. #endif /* !NO_WOLFSSL_CLIENT */
  4254. #ifndef NO_WOLFSSL_SERVER
  4255. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  4256. /* Refine list of supported cipher suites to those common to server and client.
  4257. *
  4258. * ssl SSL/TLS object.
  4259. * peerSuites The peer's advertised list of supported cipher suites.
  4260. */
  4261. static void RefineSuites(WOLFSSL* ssl, Suites* peerSuites)
  4262. {
  4263. byte suites[WOLFSSL_MAX_SUITE_SZ];
  4264. word16 suiteSz = 0;
  4265. word16 i;
  4266. word16 j;
  4267. XMEMSET(suites, 0, WOLFSSL_MAX_SUITE_SZ);
  4268. if (!ssl->options.useClientOrder) {
  4269. /* Server order refining. */
  4270. for (i = 0; i < ssl->suites->suiteSz; i += 2) {
  4271. for (j = 0; j < peerSuites->suiteSz; j += 2) {
  4272. if ((ssl->suites->suites[i+0] == peerSuites->suites[j+0]) &&
  4273. (ssl->suites->suites[i+1] == peerSuites->suites[j+1])) {
  4274. suites[suiteSz++] = peerSuites->suites[j+0];
  4275. suites[suiteSz++] = peerSuites->suites[j+1];
  4276. break;
  4277. }
  4278. }
  4279. if (suiteSz == WOLFSSL_MAX_SUITE_SZ)
  4280. break;
  4281. }
  4282. }
  4283. else {
  4284. /* Client order refining. */
  4285. for (j = 0; j < peerSuites->suiteSz; j += 2) {
  4286. for (i = 0; i < ssl->suites->suiteSz; i += 2) {
  4287. if ((ssl->suites->suites[i+0] == peerSuites->suites[j+0]) &&
  4288. (ssl->suites->suites[i+1] == peerSuites->suites[j+1])) {
  4289. suites[suiteSz++] = peerSuites->suites[j+0];
  4290. suites[suiteSz++] = peerSuites->suites[j+1];
  4291. break;
  4292. }
  4293. }
  4294. if (suiteSz == WOLFSSL_MAX_SUITE_SZ)
  4295. break;
  4296. }
  4297. }
  4298. ssl->suites->suiteSz = suiteSz;
  4299. XMEMCPY(ssl->suites->suites, &suites, sizeof(suites));
  4300. #ifdef WOLFSSL_DEBUG_TLS
  4301. {
  4302. int ii;
  4303. WOLFSSL_MSG("Refined Ciphers:");
  4304. for (ii = 0 ; ii < ssl->suites->suiteSz; ii += 2) {
  4305. WOLFSSL_MSG(GetCipherNameInternal(ssl->suites->suites[ii+0],
  4306. ssl->suites->suites[ii+1]));
  4307. }
  4308. }
  4309. #endif
  4310. }
  4311. #ifndef NO_PSK
  4312. /* Attempt to find the PSK (not session ticket) that matches.
  4313. *
  4314. * @param [in, out] ssl The SSL/TLS object.
  4315. * @param [in] psk A pre-shared key from the extension.
  4316. * @param [out] suite Cipher suite to use with PSK.
  4317. * @param [out] err Error code.
  4318. * PSK_KEY_ERROR when key is too big or ticket age is
  4319. * invalid,
  4320. * UNSUPPORTED_SUITE on invalid suite.
  4321. * Other error when attempting to derive early secret.
  4322. * @return 1 when a match found - but check error code.
  4323. * @return 0 when no match found.
  4324. */
  4325. static int FindPsk(WOLFSSL* ssl, PreSharedKey* psk, byte* suite, int* err)
  4326. {
  4327. int ret = 0;
  4328. int found = 0;
  4329. const char* cipherName = NULL;
  4330. byte cipherSuite0 = TLS13_BYTE;
  4331. byte cipherSuite = WOLFSSL_DEF_PSK_CIPHER;
  4332. Arrays* sa = ssl->arrays;
  4333. if (ssl->options.server_psk_tls13_cb != NULL) {
  4334. sa->psk_keySz = ssl->options.server_psk_tls13_cb(ssl,
  4335. sa->client_identity, sa->psk_key, MAX_PSK_KEY_LEN, &cipherName);
  4336. if (sa->psk_keySz != 0) {
  4337. int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
  4338. found = (GetCipherSuiteFromName(cipherName, &cipherSuite0,
  4339. &cipherSuite, &cipherSuiteFlags) == 0);
  4340. (void)cipherSuiteFlags;
  4341. }
  4342. }
  4343. if (!found && (ssl->options.server_psk_cb != NULL)) {
  4344. sa->psk_keySz = ssl->options.server_psk_cb(ssl,
  4345. sa->client_identity, sa->psk_key,
  4346. MAX_PSK_KEY_LEN);
  4347. found = (sa->psk_keySz != 0);
  4348. }
  4349. if (found) {
  4350. if (sa->psk_keySz > MAX_PSK_KEY_LEN) {
  4351. ret = PSK_KEY_ERROR;
  4352. WOLFSSL_ERROR_VERBOSE(ret);
  4353. }
  4354. if (ret == 0) {
  4355. #ifndef WOLFSSL_PSK_ONE_ID
  4356. /* Check whether PSK ciphersuite is in SSL. */
  4357. found = (suite[0] == cipherSuite0) && (suite[1] == cipherSuite);
  4358. #else
  4359. /* Check whether PSK ciphersuite is in SSL. */
  4360. suite[0] = cipherSuite0;
  4361. suite[1] = cipherSuite;
  4362. found = FindSuiteSSL(ssl, suite);
  4363. #endif
  4364. }
  4365. if ((ret == 0) && found) {
  4366. /* Default to ciphersuite if cb doesn't specify. */
  4367. ssl->options.resuming = 0;
  4368. /* Don't send certificate request when using PSK. */
  4369. ssl->options.verifyPeer = 0;
  4370. /* PSK age is always zero. */
  4371. if (psk->ticketAge != ssl->session->ticketAdd) {
  4372. ret = PSK_KEY_ERROR;
  4373. WOLFSSL_ERROR_VERBOSE(ret);
  4374. }
  4375. }
  4376. if ((ret == 0) && found) {
  4377. /* Set PSK ciphersuite into SSL. */
  4378. ssl->options.cipherSuite0 = suite[0];
  4379. ssl->options.cipherSuite = suite[1];
  4380. ret = SetCipherSpecs(ssl);
  4381. }
  4382. if ((ret == 0) && found) {
  4383. /* Derive the early secret using the PSK. */
  4384. ret = DeriveEarlySecret(ssl);
  4385. }
  4386. if ((ret == 0) && found) {
  4387. /* PSK negotiation has succeeded */
  4388. ssl->options.isPSK = 1;
  4389. /* SERVER: using PSK for peer authentication. */
  4390. ssl->options.peerAuthGood = 1;
  4391. }
  4392. }
  4393. *err = ret;
  4394. return found;
  4395. }
  4396. #endif
  4397. /* Handle any Pre-Shared Key (PSK) extension.
  4398. * Find a PSK that supports the cipher suite passed in.
  4399. *
  4400. * ssl SSL/TLS object.
  4401. * suite Cipher suite to find PSK for.
  4402. * usingPSK 1=Indicates handshake is using Pre-Shared Keys (2=Ephemeral)
  4403. * first Set to 1 if first in extension
  4404. * returns 0 on success and otherwise failure.
  4405. */
  4406. static int DoPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 inputSz,
  4407. byte* suite, int* usingPSK, int* first)
  4408. {
  4409. int ret = 0;
  4410. TLSX* ext;
  4411. PreSharedKey* current;
  4412. byte binderKey[WC_MAX_DIGEST_SIZE];
  4413. byte binder[WC_MAX_DIGEST_SIZE];
  4414. word32 binderLen;
  4415. WOLFSSL_ENTER("DoPreSharedKeys");
  4416. ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
  4417. if (ext == NULL) {
  4418. WOLFSSL_MSG("No pre shared extension keys found");
  4419. return BAD_FUNC_ARG;
  4420. }
  4421. /* Look through all client's pre-shared keys for a match. */
  4422. current = (PreSharedKey*)ext->data;
  4423. while (current != NULL) {
  4424. #ifndef NO_PSK
  4425. if (current->identityLen > MAX_PSK_ID_LEN) {
  4426. return BUFFER_ERROR;
  4427. }
  4428. XMEMCPY(ssl->arrays->client_identity, current->identity,
  4429. current->identityLen);
  4430. ssl->arrays->client_identity[current->identityLen] = '\0';
  4431. #endif
  4432. #ifdef HAVE_SESSION_TICKET
  4433. /* Decode the identity. */
  4434. ret = DoClientTicket(ssl, current->identity, current->identityLen);
  4435. #ifdef WOLFSSL_ASYNC_CRYPT
  4436. if (ret == WC_PENDING_E)
  4437. return ret;
  4438. #endif
  4439. if (ret == WOLFSSL_TICKET_RET_OK) {
  4440. #ifdef WOLFSSL_32BIT_MILLI_TIME
  4441. word32 now;
  4442. sword64 diff;
  4443. now = TimeNowInMilliseconds();
  4444. if (now == 0)
  4445. return GETTIME_ERROR;
  4446. /* Difference between now and time ticket constructed
  4447. * (from decrypted ticket). */
  4448. diff = now;
  4449. diff -= ssl->session->ticketSeen;
  4450. if (diff > (sword64)ssl->timeout * 1000 ||
  4451. diff > (sword64)TLS13_MAX_TICKET_AGE * 1000) {
  4452. current = current->next;
  4453. continue;
  4454. }
  4455. #else
  4456. sword64 diff;
  4457. diff = TimeNowInMilliseconds();
  4458. if (diff == 0)
  4459. return GETTIME_ERROR;
  4460. /* Difference between now and time ticket constructed
  4461. * (from decrypted ticket). */
  4462. diff -= ssl->session->ticketSeen;
  4463. if (diff > (sword64)ssl->timeout * 1000 ||
  4464. diff > (sword64)TLS13_MAX_TICKET_AGE * 1000) {
  4465. current = current->next;
  4466. continue;
  4467. }
  4468. #endif
  4469. /* Subtract client's ticket age and unobfuscate. */
  4470. diff -= current->ticketAge;
  4471. diff += ssl->session->ticketAdd;
  4472. /* Check session and ticket age timeout.
  4473. * Allow +/- 1000 milliseconds on ticket age.
  4474. */
  4475. if (diff < -1000 || diff - MAX_TICKET_AGE_DIFF * 1000 > 1000) {
  4476. current = current->next;
  4477. continue;
  4478. }
  4479. #ifndef WOLFSSL_PSK_ONE_ID
  4480. /* Check whether resumption is possible based on suites in SSL and
  4481. * ciphersuite in ticket.
  4482. */
  4483. if ((suite[0] != ssl->session->cipherSuite0) ||
  4484. (suite[1] != ssl->session->cipherSuite)) {
  4485. current = current->next;
  4486. continue;
  4487. }
  4488. #else
  4489. suite[0] = ssl->session->cipherSuite0;
  4490. suite[1] = ssl->session->cipherSuite;
  4491. if (!FindSuiteSSL(ssl, suite)) {
  4492. current = current->next;
  4493. continue;
  4494. }
  4495. #endif
  4496. /* SERVER: using secret in session ticket for peer auth. */
  4497. ssl->options.peerAuthGood = 1;
  4498. #ifdef WOLFSSL_EARLY_DATA
  4499. ssl->options.maxEarlyDataSz = ssl->session->maxEarlyDataSz;
  4500. #endif
  4501. /* Use the same cipher suite as before and set up for use. */
  4502. ssl->options.cipherSuite0 = ssl->session->cipherSuite0;
  4503. ssl->options.cipherSuite = ssl->session->cipherSuite;
  4504. ret = SetCipherSpecs(ssl);
  4505. if (ret != 0)
  4506. return ret;
  4507. /* Resumption PSK is resumption master secret. */
  4508. ssl->arrays->psk_keySz = ssl->specs.hash_size;
  4509. if ((ret = DeriveResumptionPSK(ssl, ssl->session->ticketNonce.data,
  4510. ssl->session->ticketNonce.len, ssl->arrays->psk_key)) != 0) {
  4511. return ret;
  4512. }
  4513. /* Derive the early secret using the PSK. */
  4514. ret = DeriveEarlySecret(ssl);
  4515. if (ret != 0)
  4516. return ret;
  4517. /* Hash data up to binders for deriving binders in PSK extension. */
  4518. ret = HashInput(ssl, input, inputSz);
  4519. if (ret < 0)
  4520. return ret;
  4521. /* Derive the binder key to use with HMAC. */
  4522. ret = DeriveBinderKeyResume(ssl, binderKey);
  4523. if (ret != 0)
  4524. return ret;
  4525. }
  4526. else
  4527. #endif
  4528. #ifndef NO_PSK
  4529. if (FindPsk(ssl, current, suite, &ret)) {
  4530. if (ret != 0)
  4531. return ret;
  4532. ret = HashInput(ssl, input, inputSz);
  4533. if (ret < 0)
  4534. return ret;
  4535. /* Derive the binder key to use with HMAC. */
  4536. ret = DeriveBinderKey(ssl, binderKey);
  4537. if (ret != 0)
  4538. return ret;
  4539. }
  4540. else
  4541. #endif
  4542. {
  4543. current = current->next;
  4544. continue;
  4545. }
  4546. ssl->options.sendVerify = 0;
  4547. /* Derive the Finished message secret. */
  4548. ret = DeriveFinishedSecret(ssl, binderKey,
  4549. ssl->keys.client_write_MAC_secret);
  4550. if (ret != 0)
  4551. return ret;
  4552. /* Derive the binder and compare with the one in the extension. */
  4553. ret = BuildTls13HandshakeHmac(ssl,
  4554. ssl->keys.client_write_MAC_secret, binder, &binderLen);
  4555. if (ret != 0)
  4556. return ret;
  4557. if (binderLen != current->binderLen ||
  4558. XMEMCMP(binder, current->binder, binderLen) != 0) {
  4559. WOLFSSL_ERROR_VERBOSE(BAD_BINDER);
  4560. return BAD_BINDER;
  4561. }
  4562. /* This PSK works, no need to try any more. */
  4563. current->chosen = 1;
  4564. ext->resp = 1;
  4565. break;
  4566. }
  4567. if (current == NULL) {
  4568. #ifdef WOLFSSL_PSK_ID_PROTECTION
  4569. #ifndef NO_CERTS
  4570. if (ssl->buffers.certChainCnt != 0)
  4571. return 0;
  4572. #endif
  4573. WOLFSSL_ERROR_VERBOSE(BAD_BINDER);
  4574. return BAD_BINDER;
  4575. #else
  4576. return 0;
  4577. #endif
  4578. }
  4579. *first = (current == ext->data);
  4580. *usingPSK = 1;
  4581. WOLFSSL_LEAVE("DoPreSharedKeys", ret);
  4582. return ret;
  4583. }
  4584. /* Handle any Pre-Shared Key (PSK) extension.
  4585. * Must do this in ClientHello as it requires a hash of the truncated message.
  4586. * Don't know size of binders until Pre-Shared Key extension has been parsed.
  4587. *
  4588. * ssl SSL/TLS object.
  4589. * input ClientHello message.
  4590. * helloSz Size of the ClientHello message (including binders if present).
  4591. * clSuites Client's cipher suite list.
  4592. * usingPSK Indicates handshake is using Pre-Shared Keys.
  4593. */
  4594. static int CheckPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 helloSz,
  4595. Suites* clSuites, int* usingPSK)
  4596. {
  4597. int ret;
  4598. TLSX* ext;
  4599. word16 bindersLen;
  4600. int first = 0;
  4601. #ifndef WOLFSSL_PSK_ONE_ID
  4602. int i;
  4603. #else
  4604. byte suite[2];
  4605. #endif
  4606. WOLFSSL_ENTER("CheckPreSharedKeys");
  4607. ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
  4608. if (ext == NULL) {
  4609. #ifdef WOLFSSL_EARLY_DATA
  4610. ssl->earlyData = no_early_data;
  4611. #endif
  4612. if (usingPSK)
  4613. *usingPSK = 0;
  4614. /* Hash data up to binders for deriving binders in PSK extension. */
  4615. ret = HashInput(ssl, input, helloSz);
  4616. return ret;
  4617. }
  4618. /* Extensions pushed on stack/list and PSK must be last. */
  4619. if (ssl->extensions != ext) {
  4620. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  4621. return PSK_KEY_ERROR;
  4622. }
  4623. /* Assume we are going to resume with a pre-shared key. */
  4624. ssl->options.resuming = 1;
  4625. /* Find the pre-shared key extension and calculate hash of truncated
  4626. * ClientHello for binders.
  4627. */
  4628. ret = TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
  4629. client_hello, &bindersLen);
  4630. if (ret < 0)
  4631. return ret;
  4632. /* Refine list for PSK processing. */
  4633. RefineSuites(ssl, clSuites);
  4634. #ifndef WOLFSSL_PSK_ONE_ID
  4635. if (usingPSK == NULL)
  4636. return BAD_FUNC_ARG;
  4637. /* Server list has only common suites from refining in server or client
  4638. * order. */
  4639. for (i = 0; !(*usingPSK) && i < ssl->suites->suiteSz; i += 2) {
  4640. ret = DoPreSharedKeys(ssl, input, helloSz - bindersLen,
  4641. ssl->suites->suites + i, usingPSK, &first);
  4642. if (ret != 0) {
  4643. return ret;
  4644. }
  4645. }
  4646. #else
  4647. ret = DoPreSharedKeys(ssl, input, helloSz - bindersLen, suite, usingPSK,
  4648. &first);
  4649. if (ret != 0)
  4650. return ret;
  4651. #endif
  4652. if (*usingPSK) {
  4653. /* While verifying the selected PSK, we updated the
  4654. * handshake hash up to the binder bytes in the PSK extensions.
  4655. * Continuing, we need the rest of the ClientHello hashed as well.
  4656. */
  4657. ret = HashRaw(ssl, input + helloSz - bindersLen, bindersLen);
  4658. }
  4659. else {
  4660. /* No suitable PSK found, Hash the complete ClientHello,
  4661. * as caller expect it after we return */
  4662. ret = HashInput(ssl, input, helloSz);
  4663. }
  4664. if (ret != 0)
  4665. return ret;
  4666. if (*usingPSK != 0) {
  4667. word16 modes;
  4668. #ifdef WOLFSSL_EARLY_DATA
  4669. TLSX* extEarlyData;
  4670. extEarlyData = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  4671. if (extEarlyData != NULL) {
  4672. /* Check if accepting early data and first PSK. */
  4673. if (ssl->earlyData != no_early_data && first) {
  4674. extEarlyData->resp = 1;
  4675. /* Derive early data decryption key. */
  4676. ret = DeriveTls13Keys(ssl, early_data_key, DECRYPT_SIDE_ONLY,
  4677. 1);
  4678. if (ret != 0)
  4679. return ret;
  4680. if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
  4681. return ret;
  4682. #ifdef WOLFSSL_DTLS13
  4683. if (ssl->options.dtls) {
  4684. ret = Dtls13NewEpoch(ssl,
  4685. w64From32(0x0, DTLS13_EPOCH_EARLYDATA),
  4686. DECRYPT_SIDE_ONLY);
  4687. if (ret != 0)
  4688. return ret;
  4689. }
  4690. #endif /* WOLFSSL_DTLS13 */
  4691. ssl->earlyData = process_early_data;
  4692. }
  4693. else
  4694. extEarlyData->resp = 0;
  4695. }
  4696. #endif
  4697. /* Get the PSK key exchange modes the client wants to negotiate. */
  4698. ext = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
  4699. if (ext == NULL) {
  4700. WOLFSSL_ERROR_VERBOSE(MISSING_HANDSHAKE_DATA);
  4701. return MISSING_HANDSHAKE_DATA;
  4702. }
  4703. modes = ext->val;
  4704. #ifdef HAVE_SUPPORTED_CURVES
  4705. ext = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  4706. /* Use (EC)DHE for forward-security if possible. */
  4707. if ((modes & (1 << PSK_DHE_KE)) != 0 && !ssl->options.noPskDheKe &&
  4708. ext != NULL) {
  4709. /* Only use named group used in last session. */
  4710. ssl->namedGroup = ssl->session->namedGroup;
  4711. *usingPSK = 2; /* generate new ephemeral key */
  4712. }
  4713. else
  4714. #endif
  4715. {
  4716. if ((modes & (1 << PSK_KE)) == 0) {
  4717. WOLFSSL_MSG("psk_ke mode does not allow key share");
  4718. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  4719. return PSK_KEY_ERROR;
  4720. }
  4721. ssl->options.noPskDheKe = 1;
  4722. ssl->arrays->preMasterSz = 0;
  4723. *usingPSK = 1;
  4724. }
  4725. }
  4726. #ifdef WOLFSSL_PSK_ID_PROTECTION
  4727. else {
  4728. #ifndef NO_CERTS
  4729. if (ssl->buffers.certChainCnt != 0)
  4730. return 0;
  4731. #endif
  4732. WOLFSSL_ERROR_VERBOSE(BAD_BINDER);
  4733. return BAD_BINDER;
  4734. }
  4735. #endif
  4736. WOLFSSL_LEAVE("CheckPreSharedKeys", ret);
  4737. return 0;
  4738. }
  4739. #endif /* HAVE_SESSION_TICKET || !NO_PSK */
  4740. #if defined(WOLFSSL_SEND_HRR_COOKIE)
  4741. /* Check that the Cookie data's integrity.
  4742. *
  4743. * ssl SSL/TLS object.
  4744. * cookie The cookie data - hash and MAC.
  4745. * cookieSz The length of the cookie data in bytes.
  4746. * returns Length of the hash on success, otherwise failure.
  4747. */
  4748. static int CheckCookie(WOLFSSL* ssl, byte* cookie, byte cookieSz)
  4749. {
  4750. int ret;
  4751. byte mac[WC_MAX_DIGEST_SIZE] = {0};
  4752. Hmac cookieHmac;
  4753. byte cookieType = 0;
  4754. byte macSz = 0;
  4755. #if !defined(NO_SHA) && defined(NO_SHA256)
  4756. cookieType = SHA;
  4757. macSz = WC_SHA_DIGEST_SIZE;
  4758. #endif /* NO_SHA */
  4759. #ifndef NO_SHA256
  4760. cookieType = WC_SHA256;
  4761. macSz = WC_SHA256_DIGEST_SIZE;
  4762. #endif /* NO_SHA256 */
  4763. if (cookieSz < ssl->specs.hash_size + macSz)
  4764. return HRR_COOKIE_ERROR;
  4765. cookieSz -= macSz;
  4766. ret = wc_HmacInit(&cookieHmac, ssl->heap, INVALID_DEVID);
  4767. if (ret == 0) {
  4768. ret = wc_HmacSetKey(&cookieHmac, cookieType,
  4769. ssl->buffers.tls13CookieSecret.buffer,
  4770. ssl->buffers.tls13CookieSecret.length);
  4771. }
  4772. if (ret == 0)
  4773. ret = wc_HmacUpdate(&cookieHmac, cookie, cookieSz);
  4774. #ifdef WOLFSSL_DTLS13
  4775. /* Tie cookie to peer address */
  4776. if (ret == 0) {
  4777. if (ssl->options.dtls && ssl->buffers.dtlsCtx.peer.sz > 0) {
  4778. ret = wc_HmacUpdate(&cookieHmac,
  4779. (byte*)ssl->buffers.dtlsCtx.peer.sa,
  4780. ssl->buffers.dtlsCtx.peer.sz);
  4781. }
  4782. }
  4783. #endif
  4784. if (ret == 0)
  4785. ret = wc_HmacFinal(&cookieHmac, mac);
  4786. wc_HmacFree(&cookieHmac);
  4787. if (ret != 0)
  4788. return ret;
  4789. if (ConstantCompare(cookie + cookieSz, mac, macSz) != 0) {
  4790. WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
  4791. return HRR_COOKIE_ERROR;
  4792. }
  4793. return cookieSz;
  4794. }
  4795. /* Length of the KeyShare Extension */
  4796. #define HRR_KEY_SHARE_SZ (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
  4797. /* Length of the Supported Versions Extension */
  4798. #define HRR_VERSIONS_SZ (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
  4799. /* Length of the Cookie Extension excluding cookie data */
  4800. #define HRR_COOKIE_HDR_SZ (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
  4801. /* PV | Random | Session Id | CipherSuite | Compression | Ext Len */
  4802. #define HRR_BODY_SZ (VERSION_SZ + RAN_LEN + ENUM_LEN + ID_LEN + \
  4803. SUITE_LEN + COMP_LEN + OPAQUE16_LEN)
  4804. /* HH | PV | CipherSuite | Ext Len | Key Share | Supported Version | Cookie */
  4805. #define MAX_HRR_SZ (HRR_MAX_HS_HEADER_SZ + \
  4806. HRR_BODY_SZ + \
  4807. HRR_KEY_SHARE_SZ + \
  4808. HRR_VERSIONS_SZ + \
  4809. HRR_COOKIE_HDR_SZ)
  4810. /* Restart the handshake hash from the cookie value.
  4811. *
  4812. * ssl SSL/TLS object.
  4813. * cookie Cookie data from client.
  4814. * returns 0 on success, otherwise failure.
  4815. */
  4816. static int RestartHandshakeHashWithCookie(WOLFSSL* ssl, Cookie* cookie)
  4817. {
  4818. byte header[HRR_MAX_HS_HEADER_SZ] = {0};
  4819. byte hrr[MAX_HRR_SZ] = {0};
  4820. int hrrIdx;
  4821. word32 idx;
  4822. byte hashSz;
  4823. byte* cookieData;
  4824. byte cookieDataSz;
  4825. word16 length;
  4826. int keyShareExt = 0;
  4827. int ret;
  4828. cookieDataSz = ret = CheckCookie(ssl, &cookie->data, cookie->len);
  4829. if (ret < 0)
  4830. return ret;
  4831. hashSz = cookie->data;
  4832. cookieData = &cookie->data;
  4833. idx = OPAQUE8_LEN;
  4834. /* Restart handshake hash with synthetic message hash. */
  4835. AddTls13HandShakeHeader(header, hashSz, 0, 0, message_hash, ssl);
  4836. if ((ret = InitHandshakeHashes(ssl)) != 0)
  4837. return ret;
  4838. if ((ret = HashRaw(ssl, header, sizeof(header))) != 0)
  4839. return ret;
  4840. #ifdef WOLFSSL_DEBUG_TLS
  4841. WOLFSSL_MSG("Restart Hash from Cookie");
  4842. WOLFSSL_BUFFER(cookieData + idx, hashSz);
  4843. #endif
  4844. if ((ret = HashRaw(ssl, cookieData + idx, hashSz)) != 0)
  4845. return ret;
  4846. /* Reconstruct the HelloRetryMessage for handshake hash. */
  4847. length = HRR_BODY_SZ - ID_LEN + ssl->session->sessionIDSz +
  4848. HRR_COOKIE_HDR_SZ + cookie->len;
  4849. length += HRR_VERSIONS_SZ;
  4850. /* HashSz (1 byte) + Hash (HashSz bytes) + CipherSuite (2 bytes) */
  4851. if (cookieDataSz > OPAQUE8_LEN + hashSz + OPAQUE16_LEN) {
  4852. keyShareExt = 1;
  4853. length += HRR_KEY_SHARE_SZ;
  4854. }
  4855. AddTls13HandShakeHeader(hrr, length, 0, 0, server_hello, ssl);
  4856. idx += hashSz;
  4857. hrrIdx = HANDSHAKE_HEADER_SZ;
  4858. #ifdef WOLFSSL_DTLS13
  4859. if (ssl->options.dtls)
  4860. hrrIdx += DTLS_HANDSHAKE_EXTRA;
  4861. #endif /* WOLFSSL_DTLS13 */
  4862. /* The negotiated protocol version. */
  4863. hrr[hrrIdx++] = ssl->version.major;
  4864. hrr[hrrIdx++] = ssl->options.dtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR;
  4865. /* HelloRetryRequest message has fixed value for random. */
  4866. XMEMCPY(hrr + hrrIdx, helloRetryRequestRandom, RAN_LEN);
  4867. hrrIdx += RAN_LEN;
  4868. hrr[hrrIdx++] = ssl->session->sessionIDSz;
  4869. if (ssl->session->sessionIDSz > 0) {
  4870. XMEMCPY(hrr + hrrIdx, ssl->session->sessionID, ssl->session->sessionIDSz);
  4871. hrrIdx += ssl->session->sessionIDSz;
  4872. }
  4873. /* Cipher Suite */
  4874. hrr[hrrIdx++] = cookieData[idx++];
  4875. hrr[hrrIdx++] = cookieData[idx++];
  4876. /* Compression not supported in TLS v1.3. */
  4877. hrr[hrrIdx++] = 0;
  4878. /* Extensions' length */
  4879. length -= HRR_BODY_SZ - ID_LEN + ssl->session->sessionIDSz;
  4880. c16toa(length, hrr + hrrIdx);
  4881. hrrIdx += 2;
  4882. /* Optional KeyShare Extension */
  4883. if (keyShareExt) {
  4884. c16toa(TLSX_KEY_SHARE, hrr + hrrIdx);
  4885. hrrIdx += 2;
  4886. c16toa(OPAQUE16_LEN, hrr + hrrIdx);
  4887. hrrIdx += 2;
  4888. hrr[hrrIdx++] = cookieData[idx++];
  4889. hrr[hrrIdx++] = cookieData[idx++];
  4890. }
  4891. c16toa(TLSX_SUPPORTED_VERSIONS, hrr + hrrIdx);
  4892. hrrIdx += 2;
  4893. c16toa(OPAQUE16_LEN, hrr + hrrIdx);
  4894. hrrIdx += 2;
  4895. #ifdef WOLFSSL_TLS13_DRAFT
  4896. hrr[hrrIdx++] = TLS_DRAFT_MAJOR;
  4897. hrr[hrrIdx++] = TLS_DRAFT_MINOR;
  4898. #else
  4899. hrr[hrrIdx++] = ssl->version.major;
  4900. hrr[hrrIdx++] = ssl->version.minor;
  4901. #endif
  4902. /* Mandatory Cookie Extension */
  4903. c16toa(TLSX_COOKIE, hrr + hrrIdx);
  4904. hrrIdx += 2;
  4905. c16toa(cookie->len + OPAQUE16_LEN, hrr + hrrIdx);
  4906. hrrIdx += 2;
  4907. c16toa(cookie->len, hrr + hrrIdx);
  4908. hrrIdx += 2;
  4909. #ifdef WOLFSSL_DEBUG_TLS
  4910. WOLFSSL_MSG("Reconstructed HelloRetryRequest");
  4911. WOLFSSL_BUFFER(hrr, hrrIdx);
  4912. WOLFSSL_MSG("Cookie");
  4913. WOLFSSL_BUFFER(cookieData, cookie->len);
  4914. #endif
  4915. #ifdef WOLFSSL_DTLS13
  4916. if (ssl->options.dtls) {
  4917. ret = Dtls13HashHandshake(ssl, hrr, hrrIdx);
  4918. }
  4919. else
  4920. #endif /* WOLFSSL_DTLS13 */
  4921. {
  4922. ret = HashRaw(ssl, hrr, hrrIdx);
  4923. }
  4924. if (ret != 0)
  4925. return ret;
  4926. return HashRaw(ssl, cookieData, cookie->len);
  4927. }
  4928. #endif
  4929. /* Do SupportedVersion extension for TLS v1.3+ otherwise it is not.
  4930. *
  4931. * ssl The SSL/TLS object.
  4932. * input The message buffer.
  4933. * i The index into the message buffer of ClientHello.
  4934. * helloSz The length of the current handshake message.
  4935. * returns 0 on success and otherwise failure.
  4936. */
  4937. static int DoTls13SupportedVersions(WOLFSSL* ssl, const byte* input, word32 i,
  4938. word32 helloSz, int* wantDowngrade)
  4939. {
  4940. int ret;
  4941. byte b;
  4942. word16 suiteSz;
  4943. word16 totalExtSz;
  4944. int foundVersion = 0;
  4945. /* Client random */
  4946. i += RAN_LEN;
  4947. /* Session id - not used in TLS v1.3 */
  4948. b = input[i++];
  4949. if (i + b > helloSz) {
  4950. return BUFFER_ERROR;
  4951. }
  4952. i += b;
  4953. #ifdef WOLFSSL_DTLS13
  4954. if (ssl->options.dtls) {
  4955. /* legacy_cookie - not used in DTLS v1.3 */
  4956. b = input[i++];
  4957. if (i + b > helloSz) {
  4958. return BUFFER_ERROR;
  4959. }
  4960. i += b;
  4961. }
  4962. #endif /* WOLFSSL_DTLS13 */
  4963. /* Cipher suites */
  4964. if (i + OPAQUE16_LEN > helloSz)
  4965. return BUFFER_ERROR;
  4966. ato16(input + i, &suiteSz);
  4967. i += OPAQUE16_LEN;
  4968. if (i + suiteSz + 1 > helloSz)
  4969. return BUFFER_ERROR;
  4970. i += suiteSz;
  4971. /* Compression */
  4972. b = input[i++];
  4973. if (i + b > helloSz)
  4974. return BUFFER_ERROR;
  4975. i += b;
  4976. /* TLS 1.3 must have extensions */
  4977. if (i < helloSz) {
  4978. if (i + OPAQUE16_LEN > helloSz)
  4979. return BUFFER_ERROR;
  4980. ato16(&input[i], &totalExtSz);
  4981. i += OPAQUE16_LEN;
  4982. if (totalExtSz != helloSz - i)
  4983. return BUFFER_ERROR;
  4984. /* Need to negotiate version first. */
  4985. if ((ret = TLSX_ParseVersion(ssl, input + i, totalExtSz, client_hello,
  4986. &foundVersion))) {
  4987. return ret;
  4988. }
  4989. }
  4990. *wantDowngrade = !foundVersion || !IsAtLeastTLSv1_3(ssl->version);
  4991. return 0;
  4992. }
  4993. /* Handle a ClientHello handshake message.
  4994. * If the protocol version in the message is not TLS v1.3 or higher, use
  4995. * DoClientHello()
  4996. * Only a server will receive this message.
  4997. *
  4998. * ssl The SSL/TLS object.
  4999. * input The message buffer.
  5000. * inOutIdx On entry, the index into the message buffer of ClientHello.
  5001. * On exit, the index of byte after the ClientHello message and
  5002. * padding.
  5003. * helloSz The length of the current handshake message.
  5004. * returns 0 on success and otherwise failure.
  5005. */
  5006. typedef struct Dch13Args {
  5007. ProtocolVersion pv;
  5008. Suites* clSuites;
  5009. word32 idx;
  5010. word32 begin;
  5011. int usingPSK;
  5012. } Dch13Args;
  5013. static void FreeDch13Args(WOLFSSL* ssl, void* pArgs)
  5014. {
  5015. Dch13Args* args = (Dch13Args*)pArgs;
  5016. (void)ssl;
  5017. if (args && args->clSuites) {
  5018. XFREE(args->clSuites, ssl->heap, DYNAMIC_TYPE_SUITES);
  5019. args->clSuites = NULL;
  5020. }
  5021. }
  5022. int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  5023. word32 helloSz)
  5024. {
  5025. int ret;
  5026. #ifdef WOLFSSL_ASYNC_CRYPT
  5027. Dch13Args* args = NULL;
  5028. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  5029. #else
  5030. Dch13Args args[1];
  5031. #endif
  5032. WOLFSSL_START(WC_FUNC_CLIENT_HELLO_DO);
  5033. WOLFSSL_ENTER("DoTls13ClientHello");
  5034. #ifdef WOLFSSL_ASYNC_CRYPT
  5035. if (ssl->async == NULL) {
  5036. ssl->async = (struct WOLFSSL_ASYNC*)
  5037. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  5038. DYNAMIC_TYPE_ASYNC);
  5039. if (ssl->async == NULL)
  5040. ERROR_OUT(MEMORY_E, exit_dch);
  5041. }
  5042. args = (Dch13Args*)ssl->async->args;
  5043. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  5044. if (ret != WC_NOT_PENDING_E) {
  5045. /* Check for error */
  5046. if (ret < 0) {
  5047. goto exit_dch;
  5048. }
  5049. }
  5050. else
  5051. #endif
  5052. {
  5053. /* Reset state */
  5054. ret = VERSION_ERROR;
  5055. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  5056. XMEMSET(args, 0, sizeof(Dch13Args));
  5057. #ifdef WOLFSSL_ASYNC_CRYPT
  5058. ssl->async->freeArgs = FreeDch13Args;
  5059. #endif
  5060. }
  5061. switch (ssl->options.asyncState) {
  5062. case TLS_ASYNC_BEGIN:
  5063. {
  5064. byte b;
  5065. byte sessIdSz;
  5066. int wantDowngrade = 0;
  5067. word16 totalExtSz = 0;
  5068. #ifdef WOLFSSL_CALLBACKS
  5069. if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
  5070. if (ssl->toInfoOn) AddLateName("ClientHello", &ssl->timeoutInfo);
  5071. #endif
  5072. args->idx = *inOutIdx;
  5073. args->begin = args->idx;
  5074. /* protocol version, random and session id length check */
  5075. if (OPAQUE16_LEN + RAN_LEN + OPAQUE8_LEN > helloSz) {
  5076. ERROR_OUT(BUFFER_ERROR, exit_dch);
  5077. }
  5078. /* Protocol version */
  5079. XMEMCPY(&args->pv, input + args->idx, OPAQUE16_LEN);
  5080. ssl->chVersion = args->pv; /* store */
  5081. args->idx += OPAQUE16_LEN;
  5082. /* this check pass for DTLS Major (0xff) */
  5083. if (args->pv.major < SSLv3_MAJOR) {
  5084. WOLFSSL_MSG("Legacy version field contains unsupported value");
  5085. SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version);
  5086. ERROR_OUT(INVALID_PARAMETER, exit_dch);
  5087. }
  5088. #ifdef WOLFSSL_DTLS13
  5089. if (ssl->options.dtls &&
  5090. args->pv.major == DTLS_MAJOR && args->pv.minor > DTLSv1_2_MINOR) {
  5091. wantDowngrade = 1;
  5092. ssl->version.minor = args->pv.minor;
  5093. }
  5094. #endif /* WOLFSSL_DTLS13 */
  5095. if (!ssl->options.dtls) {
  5096. /* Legacy protocol version cannot negotiate TLS 1.3 or higher. */
  5097. if (args->pv.major > SSLv3_MAJOR || (args->pv.major == SSLv3_MAJOR &&
  5098. args->pv.minor >= TLSv1_3_MINOR)) {
  5099. args->pv.major = SSLv3_MAJOR;
  5100. args->pv.minor = TLSv1_2_MINOR;
  5101. wantDowngrade = 1;
  5102. ssl->version.minor = args->pv.minor;
  5103. }
  5104. /* Legacy version must be [ SSLv3_MAJOR, TLSv1_2_MINOR ] for TLS v1.3 */
  5105. else if (args->pv.major == SSLv3_MAJOR &&
  5106. args->pv.minor < TLSv1_2_MINOR) {
  5107. wantDowngrade = 1;
  5108. ssl->version.minor = args->pv.minor;
  5109. }
  5110. }
  5111. if (!wantDowngrade) {
  5112. ret = DoTls13SupportedVersions(ssl, input + args->begin,
  5113. args->idx - args->begin, helloSz, &wantDowngrade);
  5114. if (ret < 0)
  5115. goto exit_dch;
  5116. }
  5117. if (wantDowngrade) {
  5118. #ifndef WOLFSSL_NO_TLS12
  5119. if (!ssl->options.downgrade) {
  5120. WOLFSSL_MSG("Client trying to connect with lesser version than "
  5121. "TLS v1.3");
  5122. ERROR_OUT(VERSION_ERROR, exit_dch);
  5123. }
  5124. if ((!ssl->options.dtls
  5125. && args->pv.minor < ssl->options.minDowngrade) ||
  5126. (ssl->options.dtls && args->pv.minor > ssl->options.minDowngrade)) {
  5127. WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
  5128. ERROR_OUT(VERSION_ERROR, exit_dch);
  5129. }
  5130. ret = HashInput(ssl, input + args->begin, helloSz);
  5131. if (ret == 0) {
  5132. ret = DoClientHello(ssl, input, inOutIdx, helloSz);
  5133. }
  5134. goto exit_dch;
  5135. #else
  5136. WOLFSSL_MSG("Client trying to connect with lesser version than "
  5137. "TLS v1.3");
  5138. ERROR_OUT(VERSION_ERROR, exit_dch);
  5139. #endif
  5140. }
  5141. /* From here on we are a TLS 1.3 ClientHello. */
  5142. /* Client random */
  5143. XMEMCPY(ssl->arrays->clientRandom, input + args->idx, RAN_LEN);
  5144. args->idx += RAN_LEN;
  5145. #ifdef WOLFSSL_DEBUG_TLS
  5146. WOLFSSL_MSG("client random");
  5147. WOLFSSL_BUFFER(ssl->arrays->clientRandom, RAN_LEN);
  5148. #endif
  5149. sessIdSz = input[args->idx++];
  5150. if (sessIdSz != ID_LEN && sessIdSz != 0)
  5151. ERROR_OUT(INVALID_PARAMETER, exit_dch);
  5152. if (sessIdSz + args->idx > helloSz) {
  5153. ERROR_OUT(BUFFER_ERROR, exit_dch);
  5154. }
  5155. ssl->session->sessionIDSz = sessIdSz;
  5156. if (sessIdSz == ID_LEN) {
  5157. XMEMCPY(ssl->session->sessionID, input + args->idx, sessIdSz);
  5158. args->idx += ID_LEN;
  5159. }
  5160. #ifdef WOLFSSL_DTLS13
  5161. /* legacy_cookie */
  5162. if (ssl->options.dtls)
  5163. args->idx += OPAQUE8_LEN;
  5164. #endif /* WOLFSSL_DTLS13 */
  5165. args->clSuites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap,
  5166. DYNAMIC_TYPE_SUITES);
  5167. if (args->clSuites == NULL) {
  5168. ERROR_OUT(MEMORY_E, exit_dch);
  5169. }
  5170. /* Cipher suites */
  5171. if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
  5172. ERROR_OUT(BUFFER_ERROR, exit_dch);
  5173. ato16(&input[args->idx], &args->clSuites->suiteSz);
  5174. args->idx += OPAQUE16_LEN;
  5175. if ((args->clSuites->suiteSz % 2) != 0) {
  5176. ERROR_OUT(INVALID_PARAMETER, exit_dch);
  5177. }
  5178. /* suites and compression length check */
  5179. if ((args->idx - args->begin) + args->clSuites->suiteSz + OPAQUE8_LEN > helloSz)
  5180. ERROR_OUT(BUFFER_ERROR, exit_dch);
  5181. if (args->clSuites->suiteSz > WOLFSSL_MAX_SUITE_SZ)
  5182. ERROR_OUT(BUFFER_ERROR, exit_dch);
  5183. XMEMCPY(args->clSuites->suites, input + args->idx, args->clSuites->suiteSz);
  5184. args->idx += args->clSuites->suiteSz;
  5185. args->clSuites->hashSigAlgoSz = 0;
  5186. /* Compression */
  5187. b = input[args->idx++];
  5188. if ((args->idx - args->begin) + b > helloSz)
  5189. ERROR_OUT(BUFFER_ERROR, exit_dch);
  5190. if (b != COMP_LEN) {
  5191. WOLFSSL_MSG("Must be one compression type in list");
  5192. ERROR_OUT(INVALID_PARAMETER, exit_dch);
  5193. }
  5194. b = input[args->idx++];
  5195. if (b != NO_COMPRESSION) {
  5196. WOLFSSL_MSG("Must be no compression type in list");
  5197. ERROR_OUT(INVALID_PARAMETER, exit_dch);
  5198. }
  5199. /* Extensions */
  5200. if ((args->idx - args->begin) == helloSz)
  5201. ERROR_OUT(BUFFER_ERROR, exit_dch);
  5202. if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
  5203. ERROR_OUT(BUFFER_ERROR, exit_dch);
  5204. ato16(&input[args->idx], &totalExtSz);
  5205. args->idx += OPAQUE16_LEN;
  5206. if ((args->idx - args->begin) + totalExtSz > helloSz)
  5207. ERROR_OUT(BUFFER_ERROR, exit_dch);
  5208. /* Auto populate extensions supported unless user defined. */
  5209. if ((ret = TLSX_PopulateExtensions(ssl, 1)) != 0)
  5210. goto exit_dch;
  5211. /* Parse extensions */
  5212. if ((ret = TLSX_Parse(ssl, input + args->idx, totalExtSz, client_hello,
  5213. args->clSuites))) {
  5214. goto exit_dch;
  5215. }
  5216. #ifdef HAVE_SNI
  5217. if ((ret = SNI_Callback(ssl)) != 0)
  5218. return ret;
  5219. ssl->options.side = WOLFSSL_SERVER_END;
  5220. #endif
  5221. args->idx += totalExtSz;
  5222. ssl->options.haveSessionId = 1;
  5223. ssl->options.sendVerify = SEND_CERT;
  5224. #if defined(WOLFSSL_SEND_HRR_COOKIE)
  5225. if (ssl->options.sendCookie &&
  5226. (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE
  5227. #ifdef WOLFSSL_DTLS13
  5228. /* Always check for a valid cookie since we may have already
  5229. * sent a HRR but we reset the state. */
  5230. || ssl->options.dtls
  5231. #endif
  5232. )) {
  5233. TLSX* ext = TLSX_Find(ssl->extensions, TLSX_COOKIE);
  5234. if (ext != NULL) {
  5235. /* Ensure the cookie came from client and isn't the one in the
  5236. * response - HelloRetryRequest.
  5237. */
  5238. if (ext->resp == 0) {
  5239. ret = RestartHandshakeHashWithCookie(ssl, (Cookie*)ext->data);
  5240. #ifdef WOLFSSL_DTLS13
  5241. /* Send a new cookie request */
  5242. if (ret == HRR_COOKIE_ERROR && ssl->options.dtls)
  5243. ssl->options.serverState = NULL_STATE;
  5244. else
  5245. #endif
  5246. if (ret != 0)
  5247. goto exit_dch;
  5248. ssl->options.serverState = SERVER_HELLO_COMPLETE;
  5249. }
  5250. else {
  5251. #ifdef WOLFSSL_DTLS13
  5252. if (ssl->options.dtls)
  5253. ssl->options.serverState = NULL_STATE;
  5254. else
  5255. #endif
  5256. ERROR_OUT(HRR_COOKIE_ERROR, exit_dch);
  5257. }
  5258. }
  5259. else
  5260. #ifdef WOLFSSL_DTLS13
  5261. if (!ssl->options.dtls)
  5262. #endif
  5263. ERROR_OUT(HRR_COOKIE_ERROR, exit_dch);
  5264. }
  5265. #endif
  5266. #if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
  5267. defined(HAVE_TLS_EXTENSIONS)
  5268. ret = CheckPreSharedKeys(ssl, input + args->begin, helloSz, args->clSuites,
  5269. &args->usingPSK);
  5270. if (ret != 0)
  5271. goto exit_dch;
  5272. #else
  5273. if ((ret = HashInput(ssl, input + args->begin, helloSz)) != 0)
  5274. goto exit_dch;
  5275. #endif
  5276. #if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
  5277. defined(HAVE_TLS_EXTENSIONS)
  5278. if (!args->usingPSK)
  5279. #endif
  5280. {
  5281. /* Not using PSK so don't require no KE. */
  5282. ssl->options.noPskDheKe = 0;
  5283. #ifndef NO_CERTS
  5284. if (TLSX_Find(ssl->extensions, TLSX_KEY_SHARE) == NULL) {
  5285. WOLFSSL_MSG("Client did not send a KeyShare extension");
  5286. SendAlert(ssl, alert_fatal, missing_extension);
  5287. ERROR_OUT(INCOMPLETE_DATA, exit_dch);
  5288. }
  5289. if (TLSX_Find(ssl->extensions, TLSX_SIGNATURE_ALGORITHMS) == NULL) {
  5290. WOLFSSL_MSG("Client did not send a SignatureAlgorithms extension");
  5291. SendAlert(ssl, alert_fatal, missing_extension);
  5292. ERROR_OUT(INCOMPLETE_DATA, exit_dch);
  5293. }
  5294. #else
  5295. ERROR_OUT(INVALID_PARAMETER, exit_dch);
  5296. #endif
  5297. }
  5298. /* Advance state and proceed */
  5299. ssl->options.asyncState = TLS_ASYNC_BUILD;
  5300. } /* case TLS_ASYNC_BEGIN */
  5301. FALL_THROUGH;
  5302. case TLS_ASYNC_BUILD:
  5303. case TLS_ASYNC_DO:
  5304. {
  5305. #ifndef NO_CERTS
  5306. if (!args->usingPSK) {
  5307. if ((ret = MatchSuite(ssl, args->clSuites)) < 0) {
  5308. #ifdef WOLFSSL_ASYNC_CRYPT
  5309. if (ret == WC_PENDING_E)
  5310. goto exit_dch;
  5311. #endif
  5312. WOLFSSL_MSG("Unsupported cipher suite, ClientHello");
  5313. SendAlert(ssl, alert_fatal, handshake_failure);
  5314. goto exit_dch;
  5315. }
  5316. }
  5317. else
  5318. #endif
  5319. #ifdef HAVE_SUPPORTED_CURVES
  5320. if (args->usingPSK == 2) {
  5321. /* Pick key share and Generate a new key if not present. */
  5322. int doHelloRetry = 0;
  5323. ret = TLSX_KeyShare_Establish(ssl, &doHelloRetry);
  5324. if (doHelloRetry) {
  5325. ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
  5326. if (ret != WC_PENDING_E)
  5327. ret = 0; /* for hello_retry return 0 */
  5328. }
  5329. if (ret != 0)
  5330. goto exit_dch;
  5331. }
  5332. #endif
  5333. /* Advance state and proceed */
  5334. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  5335. } /* case TLS_ASYNC_BUILD || TLS_ASYNC_DO */
  5336. FALL_THROUGH;
  5337. case TLS_ASYNC_FINALIZE:
  5338. {
  5339. *inOutIdx = args->idx;
  5340. ssl->options.clientState = CLIENT_HELLO_COMPLETE;
  5341. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  5342. ssl->options.pskNegotiated = (args->usingPSK != 0);
  5343. #endif
  5344. if (!args->usingPSK) {
  5345. #ifndef NO_CERTS
  5346. #ifdef HAVE_NULL_CIPHER
  5347. if (ssl->options.cipherSuite0 == ECC_BYTE &&
  5348. (ssl->options.cipherSuite == TLS_SHA256_SHA256 ||
  5349. ssl->options.cipherSuite == TLS_SHA384_SHA384)) {
  5350. ;
  5351. }
  5352. else
  5353. #endif
  5354. /* Check that the negotiated ciphersuite matches protocol version. */
  5355. if (ssl->options.cipherSuite0 != TLS13_BYTE) {
  5356. WOLFSSL_MSG("Negotiated ciphersuite from lesser version than "
  5357. "TLS v1.3");
  5358. SendAlert(ssl, alert_fatal, handshake_failure);
  5359. ERROR_OUT(VERSION_ERROR, exit_dch);
  5360. }
  5361. #ifdef HAVE_SESSION_TICKET
  5362. if (ssl->options.resuming) {
  5363. ssl->options.resuming = 0;
  5364. XMEMSET(ssl->arrays->psk_key, 0, ssl->specs.hash_size);
  5365. }
  5366. #endif
  5367. /* Derive early secret for handshake secret. */
  5368. if ((ret = DeriveEarlySecret(ssl)) != 0)
  5369. goto exit_dch;
  5370. #endif /* !NO_CERTS */
  5371. }
  5372. break;
  5373. } /* case TLS_ASYNC_FINALIZE */
  5374. default:
  5375. ret = INPUT_CASE_ERROR;
  5376. } /* switch (ssl->options.asyncState) */
  5377. #if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  5378. /* We are using DTLSv13 and set the HRR cookie secret, use the cookie to
  5379. perform a return-routability check. */
  5380. if (ret == 0 && ssl->options.dtls && ssl->options.sendCookie &&
  5381. ssl->options.serverState < SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  5382. /* ssl->options.serverState < SERVER_HELLO_RETRY_REQUEST_COMPLETE
  5383. so the client already provided a good KeyShareEntry. In this case
  5384. we don't add the KEY_SHARE extension to the HelloRetryRequest or
  5385. in the Cookie. The RFC8446 forbids to select a supported group
  5386. with KeyShare extension in HelloRetryRequest if the client
  5387. already provided a KeyShareEntry for that group. See rfc8446
  5388. section 4.1.4 */
  5389. TLSX_Remove(&ssl->extensions, TLSX_KEY_SHARE, ssl->heap);
  5390. /* send an HRR (see wolfSSL_Accept_TLSv13()) */
  5391. ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
  5392. }
  5393. #endif /* WOLFSSL_DTLS13 */
  5394. #ifdef WOLFSSL_DTLS_CID
  5395. /* do not modify CID state if we are sending an HRR */
  5396. if (ssl->options.useDtlsCID &&
  5397. ssl->options.serverState != SERVER_HELLO_RETRY_REQUEST_COMPLETE)
  5398. DtlsCIDOnExtensionsParsed(ssl);
  5399. #endif /* WOLFSSL_DTLS_CID */
  5400. exit_dch:
  5401. WOLFSSL_LEAVE("DoTls13ClientHello", ret);
  5402. #ifdef WOLFSSL_ASYNC_CRYPT
  5403. if (ret == WC_PENDING_E) {
  5404. ssl->msgsReceived.got_client_hello = 0;
  5405. return ret;
  5406. }
  5407. #endif
  5408. if (ret == VERSION_ERROR)
  5409. SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version);
  5410. FreeDch13Args(ssl, args);
  5411. #ifdef WOLFSSL_ASYNC_CRYPT
  5412. FreeAsyncCtx(ssl, 0);
  5413. #endif
  5414. WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
  5415. if (ret != 0) {
  5416. WOLFSSL_ERROR_VERBOSE(ret);
  5417. }
  5418. return ret;
  5419. }
  5420. /* Send TLS v1.3 ServerHello message to client.
  5421. * Only a server will send this message.
  5422. *
  5423. * ssl The SSL/TLS object.
  5424. * returns 0 on success, otherwise failure.
  5425. */
  5426. /* handle generation of TLS 1.3 server_hello (2) */
  5427. int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType)
  5428. {
  5429. int ret;
  5430. byte* output;
  5431. word16 length;
  5432. word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  5433. int sendSz;
  5434. WOLFSSL_START(WC_FUNC_SERVER_HELLO_SEND);
  5435. WOLFSSL_ENTER("SendTls13ServerHello");
  5436. if (extMsgType == hello_retry_request) {
  5437. WOLFSSL_MSG("wolfSSL Sending HelloRetryRequest");
  5438. if ((ret = RestartHandshakeHash(ssl)) < 0)
  5439. return ret;
  5440. }
  5441. ssl->options.buildingMsg = 1;
  5442. #ifdef WOLFSSL_DTLS13
  5443. if (ssl->options.dtls)
  5444. idx = DTLS_RECORD_HEADER_SZ + DTLS_HANDSHAKE_HEADER_SZ;
  5445. #endif /* WOLFSSL_DTLS13 */
  5446. /* Protocol version, server random, session id, cipher suite, compression
  5447. * and extensions.
  5448. */
  5449. length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->session->sessionIDSz +
  5450. SUITE_LEN + COMP_LEN;
  5451. ret = TLSX_GetResponseSize(ssl, extMsgType, &length);
  5452. if (ret != 0)
  5453. return ret;
  5454. sendSz = idx + length;
  5455. /* Check buffers are big enough and grow if needed. */
  5456. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  5457. return ret;
  5458. /* Get position in output buffer to write new message to. */
  5459. output = ssl->buffers.outputBuffer.buffer +
  5460. ssl->buffers.outputBuffer.length;
  5461. /* Put the record and handshake headers on. */
  5462. AddTls13Headers(output, length, server_hello, ssl);
  5463. /* The protocol version must be TLS v1.2 for middleboxes. */
  5464. output[idx++] = ssl->version.major;
  5465. output[idx++] = ssl->options.dtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR;
  5466. if (extMsgType == server_hello) {
  5467. /* Generate server random. */
  5468. if ((ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN)) != 0)
  5469. return ret;
  5470. }
  5471. else {
  5472. /* HelloRetryRequest message has fixed value for random. */
  5473. XMEMCPY(output + idx, helloRetryRequestRandom, RAN_LEN);
  5474. }
  5475. /* Store in SSL for debugging. */
  5476. XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN);
  5477. idx += RAN_LEN;
  5478. #ifdef WOLFSSL_DEBUG_TLS
  5479. WOLFSSL_MSG("Server random");
  5480. WOLFSSL_BUFFER(ssl->arrays->serverRandom, RAN_LEN);
  5481. #endif
  5482. output[idx++] = ssl->session->sessionIDSz;
  5483. if (ssl->session->sessionIDSz > 0) {
  5484. XMEMCPY(output + idx, ssl->session->sessionID, ssl->session->sessionIDSz);
  5485. idx += ssl->session->sessionIDSz;
  5486. }
  5487. /* Chosen cipher suite */
  5488. output[idx++] = ssl->options.cipherSuite0;
  5489. output[idx++] = ssl->options.cipherSuite;
  5490. #ifdef WOLFSSL_DEBUG_TLS
  5491. WOLFSSL_MSG("Chosen cipher suite:");
  5492. WOLFSSL_MSG(GetCipherNameInternal(ssl->options.cipherSuite0,
  5493. ssl->options.cipherSuite));
  5494. #endif
  5495. /* Compression not supported in TLS v1.3. */
  5496. output[idx++] = 0;
  5497. /* Extensions */
  5498. ret = TLSX_WriteResponse(ssl, output + idx, extMsgType, NULL);
  5499. if (ret != 0)
  5500. return ret;
  5501. #ifdef WOLFSSL_SEND_HRR_COOKIE
  5502. if (ssl->options.sendCookie && extMsgType == hello_retry_request) {
  5503. /* Reset the hashes from here. We will be able to restart the hashes
  5504. * from the cookie in RestartHandshakeHashWithCookie */
  5505. ret = InitHandshakeHashes(ssl);
  5506. }
  5507. else
  5508. #endif
  5509. {
  5510. #ifdef WOLFSSL_DTLS13
  5511. if (ssl->options.dtls) {
  5512. ret = Dtls13HashHandshake(
  5513. ssl,
  5514. output + Dtls13GetRlHeaderLength(ssl, 0) ,
  5515. (word16)sendSz - Dtls13GetRlHeaderLength(ssl, 0));
  5516. }
  5517. else
  5518. #endif /* WOLFSSL_DTLS13 */
  5519. {
  5520. ret = HashOutput(ssl, output, sendSz, 0);
  5521. }
  5522. }
  5523. if (ret != 0)
  5524. return ret;
  5525. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  5526. if (ssl->hsInfoOn)
  5527. AddPacketName(ssl, "ServerHello");
  5528. if (ssl->toInfoOn) {
  5529. AddPacketInfo(ssl, "ServerHello", handshake, output, sendSz,
  5530. WRITE_PROTO, ssl->heap);
  5531. }
  5532. #endif
  5533. if (extMsgType == server_hello)
  5534. ssl->options.serverState = SERVER_HELLO_COMPLETE;
  5535. ssl->options.buildingMsg = 0;
  5536. #ifdef WOLFSSL_DTLS13
  5537. if (ssl->options.dtls) {
  5538. ret = Dtls13HandshakeSend(ssl, output, (word16)sendSz, (word16)sendSz,
  5539. (enum HandShakeType)extMsgType, 0);
  5540. WOLFSSL_LEAVE("SendTls13ServerHello", ret);
  5541. WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
  5542. return ret;
  5543. }
  5544. #endif /* WOLFSSL_DTLS13 */
  5545. ssl->buffers.outputBuffer.length += sendSz;
  5546. if (!ssl->options.groupMessages || extMsgType != server_hello)
  5547. ret = SendBuffered(ssl);
  5548. WOLFSSL_LEAVE("SendTls13ServerHello", ret);
  5549. WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
  5550. return ret;
  5551. }
  5552. /* handle generation of TLS 1.3 encrypted_extensions (8) */
  5553. /* Send the rest of the extensions encrypted under the handshake key.
  5554. * This message is always encrypted in TLS v1.3.
  5555. * Only a server will send this message.
  5556. *
  5557. * ssl The SSL/TLS object.
  5558. * returns 0 on success, otherwise failure.
  5559. */
  5560. static int SendTls13EncryptedExtensions(WOLFSSL* ssl)
  5561. {
  5562. int ret;
  5563. byte* output;
  5564. word16 length = 0;
  5565. word32 idx;
  5566. int sendSz;
  5567. WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
  5568. WOLFSSL_ENTER("SendTls13EncryptedExtensions");
  5569. ssl->options.buildingMsg = 1;
  5570. ssl->keys.encryptionOn = 1;
  5571. #ifdef WOLFSSL_DTLS13
  5572. if (ssl->options.dtls) {
  5573. idx = Dtls13GetHeadersLength(ssl, encrypted_extensions);
  5574. }
  5575. else
  5576. #endif /* WOLFSSL_DTLS13 */
  5577. {
  5578. idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  5579. }
  5580. #if defined(HAVE_SUPPORTED_CURVES) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  5581. if ((ret = TLSX_SupportedCurve_CheckPriority(ssl)) != 0)
  5582. return ret;
  5583. #endif
  5584. /* Derive the handshake secret now that we are at first message to be
  5585. * encrypted under the keys.
  5586. */
  5587. if ((ret = DeriveHandshakeSecret(ssl)) != 0)
  5588. return ret;
  5589. if ((ret = DeriveTls13Keys(ssl, handshake_key,
  5590. ENCRYPT_AND_DECRYPT_SIDE, 1)) != 0)
  5591. return ret;
  5592. /* Setup encrypt/decrypt keys for following messages. */
  5593. #ifdef WOLFSSL_EARLY_DATA
  5594. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  5595. return ret;
  5596. if (ssl->earlyData != process_early_data) {
  5597. if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
  5598. return ret;
  5599. }
  5600. #else
  5601. if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0)
  5602. return ret;
  5603. #endif
  5604. #ifdef WOLFSSL_QUIC
  5605. if (IsAtLeastTLSv1_3(ssl->version) && WOLFSSL_IS_QUIC(ssl)) {
  5606. ret = wolfSSL_quic_add_transport_extensions(ssl, encrypted_extensions);
  5607. if (ret != 0)
  5608. return ret;
  5609. }
  5610. #endif
  5611. #ifdef WOLFSSL_DTLS13
  5612. if (ssl->options.dtls) {
  5613. w64wrapper epochHandshake = w64From32(0, DTLS13_EPOCH_HANDSHAKE);
  5614. ssl->dtls13Epoch = epochHandshake;
  5615. ret = Dtls13NewEpoch(
  5616. ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE);
  5617. if (ret != 0)
  5618. return ret;
  5619. ret = Dtls13SetEpochKeys(
  5620. ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE);
  5621. if (ret != 0)
  5622. return ret;
  5623. }
  5624. #endif /* WOLFSSL_DTLS13 */
  5625. ret = TLSX_GetResponseSize(ssl, encrypted_extensions, &length);
  5626. if (ret != 0)
  5627. return ret;
  5628. sendSz = idx + length;
  5629. /* Encryption always on. */
  5630. sendSz += MAX_MSG_EXTRA;
  5631. /* Check buffers are big enough and grow if needed. */
  5632. ret = CheckAvailableSize(ssl, sendSz);
  5633. if (ret != 0)
  5634. return ret;
  5635. /* Get position in output buffer to write new message to. */
  5636. output = ssl->buffers.outputBuffer.buffer +
  5637. ssl->buffers.outputBuffer.length;
  5638. /* Put the record and handshake headers on. */
  5639. AddTls13Headers(output, length, encrypted_extensions, ssl);
  5640. ret = TLSX_WriteResponse(ssl, output + idx, encrypted_extensions, NULL);
  5641. if (ret != 0)
  5642. return ret;
  5643. idx += length;
  5644. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  5645. if (ssl->hsInfoOn)
  5646. AddPacketName(ssl, "EncryptedExtensions");
  5647. if (ssl->toInfoOn) {
  5648. AddPacketInfo(ssl, "EncryptedExtensions", handshake, output,
  5649. sendSz, WRITE_PROTO, ssl->heap);
  5650. }
  5651. #endif
  5652. #ifdef WOLFSSL_DTLS13
  5653. if (ssl->options.dtls) {
  5654. ssl->options.buildingMsg = 0;
  5655. ret = Dtls13HandshakeSend(ssl, output, (word16)sendSz, (word16)idx,
  5656. encrypted_extensions, 1);
  5657. if (ret == 0)
  5658. ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
  5659. WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret);
  5660. WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
  5661. return ret;
  5662. }
  5663. #endif /* WOLFSSL_DTLS13 */
  5664. /* This handshake message is always encrypted. */
  5665. sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
  5666. idx - RECORD_HEADER_SZ, handshake, 1, 0, 0);
  5667. if (sendSz < 0)
  5668. return sendSz;
  5669. ssl->buffers.outputBuffer.length += sendSz;
  5670. ssl->options.buildingMsg = 0;
  5671. ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
  5672. if (!ssl->options.groupMessages)
  5673. ret = SendBuffered(ssl);
  5674. WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret);
  5675. WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
  5676. return ret;
  5677. }
  5678. #ifndef NO_CERTS
  5679. /* handle generation TLS v1.3 certificate_request (13) */
  5680. /* Send the TLS v1.3 CertificateRequest message.
  5681. * This message is always encrypted in TLS v1.3.
  5682. * Only a server will send this message.
  5683. *
  5684. * ssl SSL/TLS object.
  5685. * reqCtx Request context.
  5686. * reqCtxLen Length of context. 0 when sending as part of handshake.
  5687. * returns 0 on success, otherwise failure.
  5688. */
  5689. static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx,
  5690. int reqCtxLen)
  5691. {
  5692. byte* output;
  5693. int ret;
  5694. int sendSz;
  5695. word32 i;
  5696. word16 reqSz;
  5697. TLSX* ext;
  5698. WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_SEND);
  5699. WOLFSSL_ENTER("SendTls13CertificateRequest");
  5700. ssl->options.buildingMsg = 1;
  5701. if (ssl->options.side == WOLFSSL_SERVER_END)
  5702. InitSuitesHashSigAlgo(ssl->suites, 1, 1, 1, 1,
  5703. 0, 1, ssl->buffers.keySz);
  5704. ext = TLSX_Find(ssl->extensions, TLSX_SIGNATURE_ALGORITHMS);
  5705. if (ext == NULL)
  5706. return EXT_MISSING;
  5707. ext->resp = 0;
  5708. i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  5709. #ifdef WOLFSSL_DTLS13
  5710. if (ssl->options.dtls)
  5711. i = Dtls13GetRlHeaderLength(ssl, 1) + DTLS_HANDSHAKE_HEADER_SZ;
  5712. #endif /* WOLFSSL_DTLS13 */
  5713. reqSz = (word16)(OPAQUE8_LEN + reqCtxLen);
  5714. ret = TLSX_GetRequestSize(ssl, certificate_request, &reqSz);
  5715. if (ret != 0)
  5716. return ret;
  5717. sendSz = i + reqSz;
  5718. /* Always encrypted and make room for padding. */
  5719. sendSz += MAX_MSG_EXTRA;
  5720. /* Check buffers are big enough and grow if needed. */
  5721. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  5722. return ret;
  5723. /* Get position in output buffer to write new message to. */
  5724. output = ssl->buffers.outputBuffer.buffer +
  5725. ssl->buffers.outputBuffer.length;
  5726. /* Put the record and handshake headers on. */
  5727. AddTls13Headers(output, reqSz, certificate_request, ssl);
  5728. /* Certificate request context. */
  5729. output[i++] = (byte)reqCtxLen;
  5730. if (reqCtxLen != 0) {
  5731. XMEMCPY(output + i, reqCtx, reqCtxLen);
  5732. i += reqCtxLen;
  5733. }
  5734. /* Certificate extensions. */
  5735. reqSz = 0;
  5736. ret = TLSX_WriteRequest(ssl, output + i, certificate_request, &reqSz);
  5737. if (ret != 0)
  5738. return ret;
  5739. i += reqSz;
  5740. #ifdef WOLFSSL_DTLS13
  5741. if (ssl->options.dtls) {
  5742. ssl->options.buildingMsg = 0;
  5743. ret =
  5744. Dtls13HandshakeSend(ssl, output, (word16)sendSz, (word16)i,
  5745. certificate_request, 1);
  5746. WOLFSSL_LEAVE("SendTls13CertificateRequest", ret);
  5747. WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
  5748. return ret;
  5749. }
  5750. #endif /* WOLFSSL_DTLS13 */
  5751. /* Always encrypted. */
  5752. sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
  5753. i - RECORD_HEADER_SZ, handshake, 1, 0, 0);
  5754. if (sendSz < 0)
  5755. return sendSz;
  5756. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  5757. if (ssl->hsInfoOn)
  5758. AddPacketName(ssl, "CertificateRequest");
  5759. if (ssl->toInfoOn) {
  5760. AddPacketInfo(ssl, "CertificateRequest", handshake, output,
  5761. sendSz, WRITE_PROTO, ssl->heap);
  5762. }
  5763. #endif
  5764. ssl->buffers.outputBuffer.length += sendSz;
  5765. ssl->options.buildingMsg = 0;
  5766. if (!ssl->options.groupMessages)
  5767. ret = SendBuffered(ssl);
  5768. WOLFSSL_LEAVE("SendTls13CertificateRequest", ret);
  5769. WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
  5770. return ret;
  5771. }
  5772. #endif /* NO_CERTS */
  5773. #endif /* NO_WOLFSSL_SERVER */
  5774. #ifndef NO_CERTS
  5775. #if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  5776. defined(HAVE_ED448) || defined(HAVE_PQC)
  5777. /* Encode the signature algorithm into buffer.
  5778. *
  5779. * hashalgo The hash algorithm.
  5780. * hsType The signature type.
  5781. * output The buffer to encode into.
  5782. */
  5783. static WC_INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output)
  5784. {
  5785. switch (hsType) {
  5786. #ifdef HAVE_ECC
  5787. case ecc_dsa_sa_algo:
  5788. output[0] = hashAlgo;
  5789. output[1] = ecc_dsa_sa_algo;
  5790. break;
  5791. #endif
  5792. #ifdef HAVE_ED25519
  5793. /* ED25519: 0x0807 */
  5794. case ed25519_sa_algo:
  5795. output[0] = ED25519_SA_MAJOR;
  5796. output[1] = ED25519_SA_MINOR;
  5797. (void)hashAlgo;
  5798. break;
  5799. #endif
  5800. #ifdef HAVE_ED448
  5801. /* ED448: 0x0808 */
  5802. case ed448_sa_algo:
  5803. output[0] = ED448_SA_MAJOR;
  5804. output[1] = ED448_SA_MINOR;
  5805. (void)hashAlgo;
  5806. break;
  5807. #endif
  5808. #ifndef NO_RSA
  5809. /* PSS signatures: 0x080[4-6] */
  5810. case rsa_pss_sa_algo:
  5811. output[0] = rsa_pss_sa_algo;
  5812. output[1] = hashAlgo;
  5813. break;
  5814. #endif
  5815. #ifdef HAVE_PQC
  5816. #ifdef HAVE_FALCON
  5817. case falcon_level1_sa_algo:
  5818. output[0] = FALCON_LEVEL1_SA_MAJOR;
  5819. output[1] = FALCON_LEVEL1_SA_MINOR;
  5820. break;
  5821. case falcon_level5_sa_algo:
  5822. output[0] = FALCON_LEVEL5_SA_MAJOR;
  5823. output[1] = FALCON_LEVEL5_SA_MINOR;
  5824. break;
  5825. #endif
  5826. #ifdef HAVE_DILITHIUM
  5827. case dilithium_level2_sa_algo:
  5828. output[0] = DILITHIUM_LEVEL2_SA_MAJOR;
  5829. output[1] = DILITHIUM_LEVEL2_SA_MINOR;
  5830. break;
  5831. case dilithium_level3_sa_algo:
  5832. output[0] = DILITHIUM_LEVEL3_SA_MAJOR;
  5833. output[1] = DILITHIUM_LEVEL3_SA_MINOR;
  5834. break;
  5835. case dilithium_level5_sa_algo:
  5836. output[0] = DILITHIUM_LEVEL5_SA_MAJOR;
  5837. output[1] = DILITHIUM_LEVEL5_SA_MINOR;
  5838. break;
  5839. case dilithium_aes_level2_sa_algo:
  5840. output[0] = DILITHIUM_AES_LEVEL2_SA_MAJOR;
  5841. output[1] = DILITHIUM_AES_LEVEL2_SA_MINOR;
  5842. break;
  5843. case dilithium_aes_level3_sa_algo:
  5844. output[0] = DILITHIUM_AES_LEVEL3_SA_MAJOR;
  5845. output[1] = DILITHIUM_AES_LEVEL3_SA_MINOR;
  5846. break;
  5847. case dilithium_aes_level5_sa_algo:
  5848. output[0] = DILITHIUM_AES_LEVEL5_SA_MAJOR;
  5849. output[1] = DILITHIUM_AES_LEVEL5_SA_MINOR;
  5850. break;
  5851. #endif
  5852. #endif
  5853. default:
  5854. break;
  5855. }
  5856. }
  5857. /* Decode the signature algorithm.
  5858. *
  5859. * input The encoded signature algorithm.
  5860. * hashalgo The hash algorithm.
  5861. * hsType The signature type.
  5862. * returns INVALID_PARAMETER if not recognized and 0 otherwise.
  5863. */
  5864. static WC_INLINE int DecodeTls13SigAlg(byte* input, byte* hashAlgo,
  5865. byte* hsType)
  5866. {
  5867. int ret = 0;
  5868. switch (input[0]) {
  5869. case NEW_SA_MAJOR:
  5870. /* PSS signatures: 0x080[4-6] */
  5871. if (input[1] >= sha256_mac && input[1] <= sha512_mac) {
  5872. *hsType = input[0];
  5873. *hashAlgo = input[1];
  5874. }
  5875. #ifdef HAVE_ED25519
  5876. /* ED25519: 0x0807 */
  5877. else if (input[1] == ED25519_SA_MINOR) {
  5878. *hsType = ed25519_sa_algo;
  5879. /* Hash performed as part of sign/verify operation. */
  5880. *hashAlgo = sha512_mac;
  5881. }
  5882. #endif
  5883. #ifdef HAVE_ED448
  5884. /* ED448: 0x0808 */
  5885. else if (input[1] == ED448_SA_MINOR) {
  5886. *hsType = ed448_sa_algo;
  5887. /* Hash performed as part of sign/verify operation. */
  5888. *hashAlgo = sha512_mac;
  5889. }
  5890. #endif
  5891. else
  5892. ret = INVALID_PARAMETER;
  5893. break;
  5894. #ifdef HAVE_PQC
  5895. case PQC_SA_MAJOR:
  5896. #if defined(HAVE_FALCON)
  5897. if (input[1] == FALCON_LEVEL1_SA_MINOR) {
  5898. *hsType = falcon_level1_sa_algo;
  5899. /* Hash performed as part of sign/verify operation. */
  5900. *hashAlgo = sha512_mac;
  5901. } else if (input[1] == FALCON_LEVEL5_SA_MINOR) {
  5902. *hsType = falcon_level5_sa_algo;
  5903. /* Hash performed as part of sign/verify operation. */
  5904. *hashAlgo = sha512_mac;
  5905. }
  5906. else
  5907. #endif /* HAVE_FALCON */
  5908. #if defined(HAVE_DILITHIUM)
  5909. if (input[1] == DILITHIUM_LEVEL2_SA_MINOR) {
  5910. *hsType = dilithium_level2_sa_algo;
  5911. /* Hash performed as part of sign/verify operation. */
  5912. *hashAlgo = sha512_mac;
  5913. } else if (input[1] == DILITHIUM_LEVEL3_SA_MINOR) {
  5914. *hsType = dilithium_level3_sa_algo;
  5915. /* Hash performed as part of sign/verify operation. */
  5916. *hashAlgo = sha512_mac;
  5917. } else if (input[1] == DILITHIUM_LEVEL5_SA_MINOR) {
  5918. *hsType = dilithium_level5_sa_algo;
  5919. /* Hash performed as part of sign/verify operation. */
  5920. *hashAlgo = sha512_mac;
  5921. } else if (input[1] == DILITHIUM_AES_LEVEL2_SA_MINOR) {
  5922. *hsType = dilithium_aes_level2_sa_algo;
  5923. /* Hash performed as part of sign/verify operation. */
  5924. *hashAlgo = sha512_mac;
  5925. } else if (input[1] == DILITHIUM_AES_LEVEL3_SA_MINOR) {
  5926. *hsType = dilithium_aes_level3_sa_algo;
  5927. /* Hash performed as part of sign/verify operation. */
  5928. *hashAlgo = sha512_mac;
  5929. } else if (input[1] == DILITHIUM_AES_LEVEL5_SA_MINOR) {
  5930. *hsType = dilithium_aes_level5_sa_algo;
  5931. /* Hash performed as part of sign/verify operation. */
  5932. *hashAlgo = sha512_mac;
  5933. }
  5934. else
  5935. #endif /* HAVE_DILITHIUM */
  5936. {
  5937. ret = INVALID_PARAMETER;
  5938. }
  5939. break;
  5940. #endif
  5941. default:
  5942. *hashAlgo = input[0];
  5943. *hsType = input[1];
  5944. break;
  5945. }
  5946. return ret;
  5947. }
  5948. /* Get the hash of the messages so far.
  5949. *
  5950. * ssl The SSL/TLS object.
  5951. * hash The buffer to write the hash to.
  5952. * returns the length of the hash.
  5953. */
  5954. static WC_INLINE int GetMsgHash(WOLFSSL* ssl, byte* hash)
  5955. {
  5956. int ret = 0;
  5957. switch (ssl->specs.mac_algorithm) {
  5958. #ifndef NO_SHA256
  5959. case sha256_mac:
  5960. ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
  5961. if (ret == 0)
  5962. ret = WC_SHA256_DIGEST_SIZE;
  5963. break;
  5964. #endif /* !NO_SHA256 */
  5965. #ifdef WOLFSSL_SHA384
  5966. case sha384_mac:
  5967. ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
  5968. if (ret == 0)
  5969. ret = WC_SHA384_DIGEST_SIZE;
  5970. break;
  5971. #endif /* WOLFSSL_SHA384 */
  5972. #ifdef WOLFSSL_TLS13_SHA512
  5973. case sha512_mac:
  5974. ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
  5975. if (ret == 0)
  5976. ret = WC_SHA512_DIGEST_SIZE;
  5977. break;
  5978. #endif /* WOLFSSL_TLS13_SHA512 */
  5979. default:
  5980. break;
  5981. }
  5982. return ret;
  5983. }
  5984. /* The length of the certificate verification label - client and server. */
  5985. #define CERT_VFY_LABEL_SZ 34
  5986. /* The server certificate verification label. */
  5987. static const byte serverCertVfyLabel[CERT_VFY_LABEL_SZ] =
  5988. "TLS 1.3, server CertificateVerify";
  5989. /* The client certificate verification label. */
  5990. static const byte clientCertVfyLabel[CERT_VFY_LABEL_SZ] =
  5991. "TLS 1.3, client CertificateVerify";
  5992. /* The number of prefix bytes for signature data. */
  5993. #define SIGNING_DATA_PREFIX_SZ 64
  5994. /* The prefix byte in the signature data. */
  5995. #define SIGNING_DATA_PREFIX_BYTE 0x20
  5996. /* Maximum length of the signature data. */
  5997. #define MAX_SIG_DATA_SZ (SIGNING_DATA_PREFIX_SZ + \
  5998. CERT_VFY_LABEL_SZ + \
  5999. WC_MAX_DIGEST_SIZE)
  6000. /* Create the signature data for TLS v1.3 certificate verification.
  6001. *
  6002. * ssl The SSL/TLS object.
  6003. * sigData The signature data.
  6004. * sigDataSz The length of the signature data.
  6005. * check Indicates this is a check not create.
  6006. */
  6007. static int CreateSigData(WOLFSSL* ssl, byte* sigData, word16* sigDataSz,
  6008. int check)
  6009. {
  6010. word16 idx;
  6011. int side = ssl->options.side;
  6012. int ret;
  6013. /* Signature Data = Prefix | Label | Handshake Hash */
  6014. XMEMSET(sigData, SIGNING_DATA_PREFIX_BYTE, SIGNING_DATA_PREFIX_SZ);
  6015. idx = SIGNING_DATA_PREFIX_SZ;
  6016. if ((side == WOLFSSL_SERVER_END && check) ||
  6017. (side == WOLFSSL_CLIENT_END && !check)) {
  6018. XMEMCPY(&sigData[idx], clientCertVfyLabel, CERT_VFY_LABEL_SZ);
  6019. }
  6020. if ((side == WOLFSSL_CLIENT_END && check) ||
  6021. (side == WOLFSSL_SERVER_END && !check)) {
  6022. XMEMCPY(&sigData[idx], serverCertVfyLabel, CERT_VFY_LABEL_SZ);
  6023. }
  6024. idx += CERT_VFY_LABEL_SZ;
  6025. ret = GetMsgHash(ssl, &sigData[idx]);
  6026. if (ret < 0)
  6027. return ret;
  6028. *sigDataSz = (word16)(idx + ret);
  6029. ret = 0;
  6030. return ret;
  6031. }
  6032. #ifndef NO_RSA
  6033. /* Encode the PKCS #1.5 RSA signature.
  6034. *
  6035. * sig The buffer to place the encoded signature into.
  6036. * sigData The data to be signed.
  6037. * sigDataSz The size of the data to be signed.
  6038. * hashAlgo The hash algorithm to use when signing.
  6039. * returns the length of the encoded signature or negative on error.
  6040. */
  6041. static int CreateRSAEncodedSig(byte* sig, byte* sigData, int sigDataSz,
  6042. int sigAlgo, int hashAlgo)
  6043. {
  6044. Digest digest;
  6045. int hashSz = 0;
  6046. int ret = BAD_FUNC_ARG;
  6047. byte* hash;
  6048. (void)sigAlgo;
  6049. hash = sig;
  6050. /* Digest the signature data. */
  6051. switch (hashAlgo) {
  6052. #ifndef NO_WOLFSSL_SHA256
  6053. case sha256_mac:
  6054. ret = wc_InitSha256(&digest.sha256);
  6055. if (ret == 0) {
  6056. ret = wc_Sha256Update(&digest.sha256, sigData, sigDataSz);
  6057. if (ret == 0)
  6058. ret = wc_Sha256Final(&digest.sha256, hash);
  6059. wc_Sha256Free(&digest.sha256);
  6060. }
  6061. hashSz = WC_SHA256_DIGEST_SIZE;
  6062. break;
  6063. #endif
  6064. #ifdef WOLFSSL_SHA384
  6065. case sha384_mac:
  6066. ret = wc_InitSha384(&digest.sha384);
  6067. if (ret == 0) {
  6068. ret = wc_Sha384Update(&digest.sha384, sigData, sigDataSz);
  6069. if (ret == 0)
  6070. ret = wc_Sha384Final(&digest.sha384, hash);
  6071. wc_Sha384Free(&digest.sha384);
  6072. }
  6073. hashSz = WC_SHA384_DIGEST_SIZE;
  6074. break;
  6075. #endif
  6076. #ifdef WOLFSSL_SHA512
  6077. case sha512_mac:
  6078. ret = wc_InitSha512(&digest.sha512);
  6079. if (ret == 0) {
  6080. ret = wc_Sha512Update(&digest.sha512, sigData, sigDataSz);
  6081. if (ret == 0)
  6082. ret = wc_Sha512Final(&digest.sha512, hash);
  6083. wc_Sha512Free(&digest.sha512);
  6084. }
  6085. hashSz = WC_SHA512_DIGEST_SIZE;
  6086. break;
  6087. #endif
  6088. }
  6089. if (ret != 0)
  6090. return ret;
  6091. return hashSz;
  6092. }
  6093. #endif /* !NO_RSA */
  6094. #ifdef HAVE_ECC
  6095. /* Encode the ECC signature.
  6096. *
  6097. * sigData The data to be signed.
  6098. * sigDataSz The size of the data to be signed.
  6099. * hashAlgo The hash algorithm to use when signing.
  6100. * returns the length of the encoded signature or negative on error.
  6101. */
  6102. static int CreateECCEncodedSig(byte* sigData, int sigDataSz, int hashAlgo)
  6103. {
  6104. Digest digest;
  6105. int hashSz = 0;
  6106. int ret = BAD_FUNC_ARG;
  6107. /* Digest the signature data. */
  6108. switch (hashAlgo) {
  6109. #ifndef NO_WOLFSSL_SHA256
  6110. case sha256_mac:
  6111. ret = wc_InitSha256(&digest.sha256);
  6112. if (ret == 0) {
  6113. ret = wc_Sha256Update(&digest.sha256, sigData, sigDataSz);
  6114. if (ret == 0)
  6115. ret = wc_Sha256Final(&digest.sha256, sigData);
  6116. wc_Sha256Free(&digest.sha256);
  6117. }
  6118. hashSz = WC_SHA256_DIGEST_SIZE;
  6119. break;
  6120. #endif
  6121. #ifdef WOLFSSL_SHA384
  6122. case sha384_mac:
  6123. ret = wc_InitSha384(&digest.sha384);
  6124. if (ret == 0) {
  6125. ret = wc_Sha384Update(&digest.sha384, sigData, sigDataSz);
  6126. if (ret == 0)
  6127. ret = wc_Sha384Final(&digest.sha384, sigData);
  6128. wc_Sha384Free(&digest.sha384);
  6129. }
  6130. hashSz = WC_SHA384_DIGEST_SIZE;
  6131. break;
  6132. #endif
  6133. #ifdef WOLFSSL_SHA512
  6134. case sha512_mac:
  6135. ret = wc_InitSha512(&digest.sha512);
  6136. if (ret == 0) {
  6137. ret = wc_Sha512Update(&digest.sha512, sigData, sigDataSz);
  6138. if (ret == 0)
  6139. ret = wc_Sha512Final(&digest.sha512, sigData);
  6140. wc_Sha512Free(&digest.sha512);
  6141. }
  6142. hashSz = WC_SHA512_DIGEST_SIZE;
  6143. break;
  6144. #endif
  6145. default:
  6146. break;
  6147. }
  6148. if (ret != 0)
  6149. return ret;
  6150. return hashSz;
  6151. }
  6152. #endif /* HAVE_ECC */
  6153. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  6154. /* Check that the decrypted signature matches the encoded signature
  6155. * based on the digest of the signature data.
  6156. *
  6157. * ssl The SSL/TLS object.
  6158. * sigAlgo The signature algorithm used to generate signature.
  6159. * hashAlgo The hash algorithm used to generate signature.
  6160. * decSig The decrypted signature.
  6161. * decSigSz The size of the decrypted signature.
  6162. * returns 0 on success, otherwise failure.
  6163. */
  6164. static int CheckRSASignature(WOLFSSL* ssl, int sigAlgo, int hashAlgo,
  6165. byte* decSig, word32 decSigSz)
  6166. {
  6167. int ret = 0;
  6168. byte sigData[MAX_SIG_DATA_SZ];
  6169. word16 sigDataSz;
  6170. word32 sigSz;
  6171. ret = CreateSigData(ssl, sigData, &sigDataSz, 1);
  6172. if (ret != 0)
  6173. return ret;
  6174. if (sigAlgo == rsa_pss_sa_algo) {
  6175. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  6176. ret = ConvertHashPss(hashAlgo, &hashType, NULL);
  6177. if (ret < 0)
  6178. return ret;
  6179. /* PSS signature can be done in-place */
  6180. ret = CreateRSAEncodedSig(sigData, sigData, sigDataSz,
  6181. sigAlgo, hashAlgo);
  6182. if (ret < 0)
  6183. return ret;
  6184. sigSz = ret;
  6185. ret = wc_RsaPSS_CheckPadding(sigData, sigSz, decSig, decSigSz,
  6186. hashType);
  6187. }
  6188. return ret;
  6189. }
  6190. #endif /* !NO_RSA && WC_RSA_PSS */
  6191. #endif /* !NO_RSA || HAVE_ECC */
  6192. #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
  6193. /* Get the next certificate from the list for writing into the TLS v1.3
  6194. * Certificate message.
  6195. *
  6196. * data The certificate list.
  6197. * length The length of the certificate data in the list.
  6198. * idx The index of the next certificate.
  6199. * returns the length of the certificate data. 0 indicates no more certificates
  6200. * in the list.
  6201. */
  6202. static word32 NextCert(byte* data, word32 length, word32* idx)
  6203. {
  6204. word32 len;
  6205. /* Is index at end of list. */
  6206. if (*idx == length)
  6207. return 0;
  6208. /* Length of the current ASN.1 encoded certificate. */
  6209. c24to32(data + *idx, &len);
  6210. /* Include the length field. */
  6211. len += 3;
  6212. /* Move index to next certificate and return the current certificate's
  6213. * length.
  6214. */
  6215. *idx += len;
  6216. return len;
  6217. }
  6218. /* Add certificate data and empty extension to output up to the fragment size.
  6219. *
  6220. * ssl SSL/TLS object.
  6221. * cert The certificate data to write out.
  6222. * len The length of the certificate data.
  6223. * extSz Length of the extension data with the certificate.
  6224. * idx The start of the certificate data to write out.
  6225. * fragSz The maximum size of this fragment.
  6226. * output The buffer to write to.
  6227. * returns the number of bytes written.
  6228. */
  6229. static word32 AddCertExt(WOLFSSL* ssl, byte* cert, word32 len, word16 extSz,
  6230. word32 idx, word32 fragSz, byte* output)
  6231. {
  6232. word32 i = 0;
  6233. word32 copySz = min(len - idx, fragSz);
  6234. if (idx < len) {
  6235. XMEMCPY(output, cert + idx, copySz);
  6236. i = copySz;
  6237. if (copySz == fragSz)
  6238. return i;
  6239. }
  6240. copySz = len + extSz - idx - i;
  6241. if (extSz == OPAQUE16_LEN) {
  6242. if (copySz <= fragSz) {
  6243. /* Empty extension */
  6244. output[i++] = 0;
  6245. output[i++] = 0;
  6246. }
  6247. }
  6248. else {
  6249. byte* certExts = ssl->buffers.certExts->buffer + idx + i - len;
  6250. /* Put out as much of the extensions' data as will fit in fragment. */
  6251. if (copySz > fragSz - i)
  6252. copySz = fragSz - i;
  6253. XMEMCPY(output + i, certExts, copySz);
  6254. i += copySz;
  6255. }
  6256. return i;
  6257. }
  6258. /* handle generation TLS v1.3 certificate (11) */
  6259. /* Send the certificate for this end and any CAs that help with validation.
  6260. * This message is always encrypted in TLS v1.3.
  6261. *
  6262. * ssl The SSL/TLS object.
  6263. * returns 0 on success, otherwise failure.
  6264. */
  6265. static int SendTls13Certificate(WOLFSSL* ssl)
  6266. {
  6267. int ret = 0;
  6268. word32 certSz, certChainSz, headerSz, listSz, payloadSz;
  6269. word16 extSz = 0;
  6270. word32 length, maxFragment;
  6271. word32 len = 0;
  6272. word32 idx = 0;
  6273. word32 offset = OPAQUE16_LEN;
  6274. byte* p = NULL;
  6275. byte certReqCtxLen = 0;
  6276. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  6277. byte* certReqCtx = NULL;
  6278. #endif
  6279. #ifdef OPENSSL_EXTRA
  6280. WOLFSSL_X509* x509 = NULL;
  6281. WOLFSSL_EVP_PKEY* pkey = NULL;
  6282. #endif
  6283. WOLFSSL_START(WC_FUNC_CERTIFICATE_SEND);
  6284. WOLFSSL_ENTER("SendTls13Certificate");
  6285. ssl->options.buildingMsg = 1;
  6286. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  6287. if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->certReqCtx != NULL) {
  6288. certReqCtxLen = ssl->certReqCtx->len;
  6289. certReqCtx = &ssl->certReqCtx->ctx;
  6290. }
  6291. #endif
  6292. #ifdef OPENSSL_EXTRA
  6293. /* call client cert callback if no cert has been loaded */
  6294. if ((ssl->ctx->CBClientCert != NULL) &&
  6295. (!ssl->buffers.certificate || !ssl->buffers.certificate->buffer)) {
  6296. ret = ssl->ctx->CBClientCert(ssl, &x509, &pkey);
  6297. if (ret == 1) {
  6298. if ((wolfSSL_CTX_use_certificate(ssl->ctx, x509) == WOLFSSL_SUCCESS) &&
  6299. (wolfSSL_CTX_use_PrivateKey(ssl->ctx, pkey) == WOLFSSL_SUCCESS)) {
  6300. ssl->options.sendVerify = SEND_CERT;
  6301. }
  6302. wolfSSL_X509_free(x509);
  6303. wolfSSL_EVP_PKEY_free(pkey);
  6304. }
  6305. }
  6306. #endif
  6307. if (ssl->options.sendVerify == SEND_BLANK_CERT) {
  6308. certSz = 0;
  6309. certChainSz = 0;
  6310. headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ;
  6311. length = headerSz;
  6312. listSz = 0;
  6313. }
  6314. else {
  6315. #ifdef OPENSSL_EXTRA
  6316. if ((ret = CertSetupCbWrapper(ssl)) != 0)
  6317. return ret;
  6318. #endif
  6319. if (!ssl->buffers.certificate) {
  6320. WOLFSSL_MSG("Send Cert missing certificate buffer");
  6321. return BUFFER_ERROR;
  6322. }
  6323. /* Certificate Data */
  6324. certSz = ssl->buffers.certificate->length;
  6325. /* Cert Req Ctx Len | Cert Req Ctx | Cert List Len | Cert Data Len */
  6326. headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ +
  6327. CERT_HEADER_SZ;
  6328. ret = TLSX_GetResponseSize(ssl, certificate, &extSz);
  6329. if (ret < 0)
  6330. return ret;
  6331. /* Create extensions' data if none already present. */
  6332. if (extSz > OPAQUE16_LEN && ssl->buffers.certExts == NULL) {
  6333. ret = AllocDer(&ssl->buffers.certExts, extSz, CERT_TYPE, ssl->heap);
  6334. if (ret < 0)
  6335. return ret;
  6336. extSz = 0;
  6337. ret = TLSX_WriteResponse(ssl, ssl->buffers.certExts->buffer,
  6338. certificate, &extSz);
  6339. if (ret < 0)
  6340. return ret;
  6341. }
  6342. /* Length of message data with one certificate and extensions. */
  6343. length = headerSz + certSz + extSz;
  6344. /* Length of list data with one certificate and extensions. */
  6345. listSz = CERT_HEADER_SZ + certSz + extSz;
  6346. /* Send rest of chain if sending cert (chain has leading size/s). */
  6347. if (certSz > 0 && ssl->buffers.certChainCnt > 0) {
  6348. p = ssl->buffers.certChain->buffer;
  6349. /* Chain length including extensions. */
  6350. certChainSz = ssl->buffers.certChain->length +
  6351. OPAQUE16_LEN * ssl->buffers.certChainCnt;
  6352. length += certChainSz;
  6353. listSz += certChainSz;
  6354. }
  6355. else
  6356. certChainSz = 0;
  6357. }
  6358. payloadSz = length;
  6359. if (ssl->fragOffset != 0)
  6360. length -= (ssl->fragOffset + headerSz);
  6361. maxFragment = wolfSSL_GetMaxFragSize(ssl, MAX_RECORD_SIZE);
  6362. while (length > 0 && ret == 0) {
  6363. byte* output = NULL;
  6364. word32 fragSz = 0;
  6365. word32 i = RECORD_HEADER_SZ;
  6366. int sendSz = RECORD_HEADER_SZ;
  6367. #ifdef WOLFSSL_DTLS13
  6368. if (ssl->options.dtls) {
  6369. i = Dtls13GetRlHeaderLength(ssl, 1);
  6370. sendSz = (int)i;
  6371. }
  6372. #endif /* WOLFSSL_DTLS13 */
  6373. if (ssl->fragOffset == 0) {
  6374. if (headerSz + certSz + extSz + certChainSz <=
  6375. maxFragment - HANDSHAKE_HEADER_SZ) {
  6376. fragSz = headerSz + certSz + extSz + certChainSz;
  6377. }
  6378. #ifdef WOLFSSL_DTLS13
  6379. else if (ssl->options.dtls){
  6380. /* short-circuit the fragmentation logic here. DTLS
  6381. fragmentation will be done in dtls13HandshakeSend() */
  6382. fragSz = headerSz + certSz + extSz + certChainSz;
  6383. }
  6384. #endif /* WOLFSSL_DTLS13 */
  6385. else {
  6386. fragSz = maxFragment - HANDSHAKE_HEADER_SZ;
  6387. }
  6388. sendSz += fragSz + HANDSHAKE_HEADER_SZ;
  6389. i += HANDSHAKE_HEADER_SZ;
  6390. #ifdef WOLFSSL_DTLS13
  6391. if (ssl->options.dtls) {
  6392. sendSz += DTLS_HANDSHAKE_EXTRA;
  6393. i += DTLS_HANDSHAKE_EXTRA;
  6394. }
  6395. #endif /* WOLFSSL_DTLS13 */
  6396. }
  6397. else {
  6398. fragSz = min(length, maxFragment);
  6399. sendSz += fragSz;
  6400. }
  6401. sendSz += MAX_MSG_EXTRA;
  6402. /* Check buffers are big enough and grow if needed. */
  6403. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  6404. return ret;
  6405. /* Get position in output buffer to write new message to. */
  6406. output = ssl->buffers.outputBuffer.buffer +
  6407. ssl->buffers.outputBuffer.length;
  6408. if (ssl->fragOffset == 0) {
  6409. AddTls13FragHeaders(output, fragSz, 0, payloadSz, certificate, ssl);
  6410. /* Request context. */
  6411. output[i++] = certReqCtxLen;
  6412. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  6413. if (certReqCtxLen > 0) {
  6414. XMEMCPY(output + i, certReqCtx, certReqCtxLen);
  6415. i += certReqCtxLen;
  6416. }
  6417. #endif
  6418. length -= OPAQUE8_LEN + certReqCtxLen;
  6419. fragSz -= OPAQUE8_LEN + certReqCtxLen;
  6420. /* Certificate list length. */
  6421. c32to24(listSz, output + i);
  6422. i += CERT_HEADER_SZ;
  6423. length -= CERT_HEADER_SZ;
  6424. fragSz -= CERT_HEADER_SZ;
  6425. /* Leaf certificate data length. */
  6426. if (certSz > 0) {
  6427. c32to24(certSz, output + i);
  6428. i += CERT_HEADER_SZ;
  6429. length -= CERT_HEADER_SZ;
  6430. fragSz -= CERT_HEADER_SZ;
  6431. }
  6432. }
  6433. else
  6434. AddTls13RecordHeader(output, fragSz, handshake, ssl);
  6435. if (certSz > 0 && ssl->fragOffset < certSz + extSz) {
  6436. /* Put in the leaf certificate with extensions. */
  6437. word32 copySz = AddCertExt(ssl, ssl->buffers.certificate->buffer,
  6438. certSz, extSz, ssl->fragOffset, fragSz, output + i);
  6439. i += copySz;
  6440. ssl->fragOffset += copySz;
  6441. length -= copySz;
  6442. fragSz -= copySz;
  6443. if (ssl->fragOffset == certSz + extSz)
  6444. FreeDer(&ssl->buffers.certExts);
  6445. }
  6446. if (certChainSz > 0 && fragSz > 0) {
  6447. /* Put in the CA certificates with empty extensions. */
  6448. while (fragSz > 0) {
  6449. word32 l;
  6450. if (offset == len + OPAQUE16_LEN) {
  6451. /* Find next CA certificate to write out. */
  6452. offset = 0;
  6453. /* Point to the start of current cert in chain buffer. */
  6454. p = ssl->buffers.certChain->buffer + idx;
  6455. len = NextCert(ssl->buffers.certChain->buffer,
  6456. ssl->buffers.certChain->length, &idx);
  6457. if (len == 0)
  6458. break;
  6459. }
  6460. /* Write out certificate and empty extension. */
  6461. l = AddCertExt(ssl, p, len, OPAQUE16_LEN, offset, fragSz,
  6462. output + i);
  6463. i += l;
  6464. ssl->fragOffset += l;
  6465. length -= l;
  6466. fragSz -= l;
  6467. offset += l;
  6468. }
  6469. }
  6470. if ((int)i - RECORD_HEADER_SZ < 0) {
  6471. WOLFSSL_MSG("Send Cert bad inputSz");
  6472. return BUFFER_E;
  6473. }
  6474. #ifdef WOLFSSL_DTLS13
  6475. if (ssl->options.dtls) {
  6476. /* DTLS1.3 uses a separate variable and logic for fragments */
  6477. ssl->options.buildingMsg = 0;
  6478. ssl->fragOffset = 0;
  6479. ret = Dtls13HandshakeSend(ssl, output, (word16)sendSz, (word16)i,
  6480. certificate, 1);
  6481. }
  6482. else
  6483. #endif /* WOLFSSL_DTLS13 */
  6484. {
  6485. /* This message is always encrypted. */
  6486. sendSz = BuildTls13Message(ssl, output, sendSz,
  6487. output + RECORD_HEADER_SZ, i - RECORD_HEADER_SZ, handshake, 1,
  6488. 0, 0);
  6489. if (sendSz < 0)
  6490. return sendSz;
  6491. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  6492. if (ssl->hsInfoOn)
  6493. AddPacketName(ssl, "Certificate");
  6494. if (ssl->toInfoOn) {
  6495. AddPacketInfo(ssl, "Certificate", handshake, output,
  6496. sendSz, WRITE_PROTO, ssl->heap);
  6497. }
  6498. #endif
  6499. ssl->buffers.outputBuffer.length += sendSz;
  6500. ssl->options.buildingMsg = 0;
  6501. if (!ssl->options.groupMessages)
  6502. ret = SendBuffered(ssl);
  6503. }
  6504. }
  6505. if (ret != WANT_WRITE) {
  6506. /* Clean up the fragment offset. */
  6507. ssl->options.buildingMsg = 0;
  6508. ssl->fragOffset = 0;
  6509. if (ssl->options.side == WOLFSSL_SERVER_END)
  6510. ssl->options.serverState = SERVER_CERT_COMPLETE;
  6511. }
  6512. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  6513. if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->certReqCtx != NULL) {
  6514. CertReqCtx* ctx = ssl->certReqCtx;
  6515. ssl->certReqCtx = ssl->certReqCtx->next;
  6516. XFREE(ctx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  6517. }
  6518. #endif
  6519. WOLFSSL_LEAVE("SendTls13Certificate", ret);
  6520. WOLFSSL_END(WC_FUNC_CERTIFICATE_SEND);
  6521. return ret;
  6522. }
  6523. #if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  6524. defined(HAVE_ED448) || defined(HAVE_PQC)) && \
  6525. (!defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH))
  6526. typedef struct Scv13Args {
  6527. byte* output; /* not allocated */
  6528. byte* verify; /* not allocated */
  6529. word32 idx;
  6530. word32 sigLen;
  6531. int sendSz;
  6532. word16 length;
  6533. byte sigAlgo;
  6534. byte* sigData;
  6535. word16 sigDataSz;
  6536. } Scv13Args;
  6537. static void FreeScv13Args(WOLFSSL* ssl, void* pArgs)
  6538. {
  6539. Scv13Args* args = (Scv13Args*)pArgs;
  6540. (void)ssl;
  6541. if (args && args->sigData) {
  6542. XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  6543. args->sigData = NULL;
  6544. }
  6545. }
  6546. /* handle generation TLS v1.3 certificate_verify (15) */
  6547. /* Send the TLS v1.3 CertificateVerify message.
  6548. * A hash of all the message so far is used.
  6549. * The signed data is:
  6550. * 0x20 * 64 | context string | 0x00 | hash of messages
  6551. * This message is always encrypted in TLS v1.3.
  6552. *
  6553. * ssl The SSL/TLS object.
  6554. * returns 0 on success, otherwise failure.
  6555. */
  6556. static int SendTls13CertificateVerify(WOLFSSL* ssl)
  6557. {
  6558. int ret = 0;
  6559. buffer* sig = &ssl->buffers.sig;
  6560. #ifdef WOLFSSL_ASYNC_CRYPT
  6561. Scv13Args* args = NULL;
  6562. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  6563. #else
  6564. Scv13Args args[1];
  6565. #endif
  6566. #ifdef WOLFSSL_DTLS13
  6567. int recordLayerHdrExtra;
  6568. #endif /* WOLFSSL_DTLS13 */
  6569. WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_SEND);
  6570. WOLFSSL_ENTER("SendTls13CertificateVerify");
  6571. ssl->options.buildingMsg = 1;
  6572. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  6573. ret = tsip_Tls13SendCertVerify(ssl);
  6574. if (ret != CRYPTOCB_UNAVAILABLE) {
  6575. goto exit_scv;
  6576. }
  6577. ret = 0;
  6578. #endif /* WOLFSSL_RENESAS_TSIP_TLS && WOLFSSL_RENESAS_TSIP_VER >= 115 */
  6579. #ifdef WOLFSSL_DTLS13
  6580. /* can be negative */
  6581. if (ssl->options.dtls)
  6582. recordLayerHdrExtra = Dtls13GetRlHeaderLength(ssl, 1) - RECORD_HEADER_SZ;
  6583. else
  6584. recordLayerHdrExtra = 0;
  6585. #endif /* WOLFSSL_DTLS13 */
  6586. #ifdef WOLFSSL_ASYNC_CRYPT
  6587. if (ssl->async == NULL) {
  6588. ssl->async = (struct WOLFSSL_ASYNC*)
  6589. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  6590. DYNAMIC_TYPE_ASYNC);
  6591. if (ssl->async == NULL)
  6592. ERROR_OUT(MEMORY_E, exit_scv);
  6593. }
  6594. args = (Scv13Args*)ssl->async->args;
  6595. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  6596. if (ret != WC_NOT_PENDING_E) {
  6597. /* Check for error */
  6598. if (ret < 0)
  6599. goto exit_scv;
  6600. }
  6601. else
  6602. #endif
  6603. {
  6604. /* Reset state */
  6605. ret = 0;
  6606. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  6607. XMEMSET(args, 0, sizeof(Scv13Args));
  6608. #ifdef WOLFSSL_ASYNC_CRYPT
  6609. ssl->async->freeArgs = FreeScv13Args;
  6610. #endif
  6611. }
  6612. switch(ssl->options.asyncState)
  6613. {
  6614. case TLS_ASYNC_BEGIN:
  6615. {
  6616. if (ssl->options.sendVerify == SEND_BLANK_CERT) {
  6617. return 0; /* sent blank cert, can't verify */
  6618. }
  6619. args->sendSz = MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA;
  6620. /* Always encrypted. */
  6621. args->sendSz += MAX_MSG_EXTRA;
  6622. /* check for available size */
  6623. if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
  6624. goto exit_scv;
  6625. }
  6626. /* get output buffer */
  6627. args->output = ssl->buffers.outputBuffer.buffer +
  6628. ssl->buffers.outputBuffer.length;
  6629. /* Advance state and proceed */
  6630. ssl->options.asyncState = TLS_ASYNC_BUILD;
  6631. } /* case TLS_ASYNC_BEGIN */
  6632. FALL_THROUGH;
  6633. case TLS_ASYNC_BUILD:
  6634. {
  6635. int rem = ssl->buffers.outputBuffer.bufferSize
  6636. - ssl->buffers.outputBuffer.length
  6637. - RECORD_HEADER_SZ - HANDSHAKE_HEADER_SZ;
  6638. /* idx is used to track verify pointer offset to output */
  6639. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  6640. args->verify =
  6641. &args->output[RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ];
  6642. #ifdef WOLFSSL_DTLS13
  6643. if (ssl->options.dtls) {
  6644. rem -= recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
  6645. args->idx += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
  6646. args->verify += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
  6647. }
  6648. #endif /* WOLFSSL_DTLS13 */
  6649. if (ssl->buffers.key == NULL) {
  6650. #ifdef HAVE_PK_CALLBACKS
  6651. if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
  6652. args->length = GetPrivateKeySigSize(ssl);
  6653. else
  6654. #endif
  6655. ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
  6656. }
  6657. else {
  6658. ret = DecodePrivateKey(ssl, &args->length);
  6659. if (ret != 0)
  6660. goto exit_scv;
  6661. }
  6662. if (rem < 0 || args->length > rem) {
  6663. ERROR_OUT(BUFFER_E, exit_scv);
  6664. }
  6665. if (args->length == 0) {
  6666. ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
  6667. }
  6668. /* Add signature algorithm. */
  6669. if (ssl->hsType == DYNAMIC_TYPE_RSA)
  6670. args->sigAlgo = rsa_pss_sa_algo;
  6671. #ifdef HAVE_ECC
  6672. else if (ssl->hsType == DYNAMIC_TYPE_ECC)
  6673. args->sigAlgo = ecc_dsa_sa_algo;
  6674. #endif
  6675. #ifdef HAVE_ED25519
  6676. else if (ssl->hsType == DYNAMIC_TYPE_ED25519)
  6677. args->sigAlgo = ed25519_sa_algo;
  6678. #endif
  6679. #ifdef HAVE_ED448
  6680. else if (ssl->hsType == DYNAMIC_TYPE_ED448)
  6681. args->sigAlgo = ed448_sa_algo;
  6682. #endif
  6683. #if defined(HAVE_PQC)
  6684. #if defined(HAVE_FALCON)
  6685. else if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
  6686. falcon_key* fkey = (falcon_key*)ssl->hsKey;
  6687. byte level = 0;
  6688. if (wc_falcon_get_level(fkey, &level) != 0) {
  6689. ERROR_OUT(ALGO_ID_E, exit_scv);
  6690. }
  6691. if (level == 1) {
  6692. args->sigAlgo = falcon_level1_sa_algo;
  6693. }
  6694. else if (level == 5) {
  6695. args->sigAlgo = falcon_level5_sa_algo;
  6696. }
  6697. else {
  6698. ERROR_OUT(ALGO_ID_E, exit_scv);
  6699. }
  6700. }
  6701. #endif /* HAVE_FALCON */
  6702. #if defined(HAVE_DILITHIUM)
  6703. else if (ssl->hsType == DYNAMIC_TYPE_DILITHIUM) {
  6704. dilithium_key* fkey = (dilithium_key*)ssl->hsKey;
  6705. byte level = 0;
  6706. byte sym = 0;
  6707. if (wc_dilithium_get_level_and_sym(fkey, &level, &sym) != 0) {
  6708. ERROR_OUT(ALGO_ID_E, exit_scv);
  6709. }
  6710. if ((level == 2) && (sym == SHAKE_VARIANT)) {
  6711. args->sigAlgo = dilithium_level2_sa_algo;
  6712. }
  6713. else if ((level == 3) && (sym == SHAKE_VARIANT)) {
  6714. args->sigAlgo = dilithium_level3_sa_algo;
  6715. }
  6716. else if ((level == 5) && (sym == SHAKE_VARIANT)) {
  6717. args->sigAlgo = dilithium_level5_sa_algo;
  6718. }
  6719. else if ((level == 2) && (sym == AES_VARIANT)) {
  6720. args->sigAlgo = dilithium_aes_level2_sa_algo;
  6721. }
  6722. else if ((level == 3) && (sym == AES_VARIANT)) {
  6723. args->sigAlgo = dilithium_aes_level3_sa_algo;
  6724. }
  6725. else if ((level == 5) && (sym == AES_VARIANT)) {
  6726. args->sigAlgo = dilithium_aes_level5_sa_algo;
  6727. }
  6728. else {
  6729. ERROR_OUT(ALGO_ID_E, exit_scv);
  6730. }
  6731. }
  6732. #endif /* HAVE_DILITHIUM */
  6733. #endif /* HAVE_PQC */
  6734. else {
  6735. ERROR_OUT(ALGO_ID_E, exit_scv);
  6736. }
  6737. EncodeSigAlg(ssl->suites->hashAlgo, args->sigAlgo, args->verify);
  6738. if (ssl->hsType == DYNAMIC_TYPE_RSA) {
  6739. int sigLen = MAX_SIG_DATA_SZ;
  6740. if (args->length > MAX_SIG_DATA_SZ)
  6741. sigLen = args->length;
  6742. args->sigData = (byte*)XMALLOC(sigLen, ssl->heap,
  6743. DYNAMIC_TYPE_SIGNATURE);
  6744. }
  6745. else {
  6746. args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
  6747. DYNAMIC_TYPE_SIGNATURE);
  6748. }
  6749. if (args->sigData == NULL) {
  6750. ERROR_OUT(MEMORY_E, exit_scv);
  6751. }
  6752. /* Create the data to be signed. */
  6753. ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 0);
  6754. if (ret != 0)
  6755. goto exit_scv;
  6756. #ifndef NO_RSA
  6757. if (ssl->hsType == DYNAMIC_TYPE_RSA) {
  6758. /* build encoded signature buffer */
  6759. sig->length = WC_MAX_DIGEST_SIZE;
  6760. sig->buffer = (byte*)XMALLOC(sig->length, ssl->heap,
  6761. DYNAMIC_TYPE_SIGNATURE);
  6762. if (sig->buffer == NULL) {
  6763. ERROR_OUT(MEMORY_E, exit_scv);
  6764. }
  6765. ret = CreateRSAEncodedSig(sig->buffer, args->sigData,
  6766. args->sigDataSz, args->sigAlgo, ssl->suites->hashAlgo);
  6767. if (ret < 0)
  6768. goto exit_scv;
  6769. sig->length = ret;
  6770. ret = 0;
  6771. /* Maximum size of RSA Signature. */
  6772. args->sigLen = args->length;
  6773. }
  6774. #endif /* !NO_RSA */
  6775. #ifdef HAVE_ECC
  6776. if (ssl->hsType == DYNAMIC_TYPE_ECC) {
  6777. sig->length = args->sendSz - args->idx - HASH_SIG_SIZE -
  6778. VERIFY_HEADER;
  6779. ret = CreateECCEncodedSig(args->sigData,
  6780. args->sigDataSz, ssl->suites->hashAlgo);
  6781. if (ret < 0)
  6782. goto exit_scv;
  6783. args->sigDataSz = (word16)ret;
  6784. ret = 0;
  6785. }
  6786. #endif /* HAVE_ECC */
  6787. #ifdef HAVE_ED25519
  6788. if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
  6789. ret = Ed25519CheckPubKey(ssl);
  6790. if (ret < 0) {
  6791. ERROR_OUT(ret, exit_scv);
  6792. }
  6793. sig->length = ED25519_SIG_SIZE;
  6794. }
  6795. #endif /* HAVE_ED25519 */
  6796. #ifdef HAVE_ED448
  6797. if (ssl->hsType == DYNAMIC_TYPE_ED448) {
  6798. ret = Ed448CheckPubKey(ssl);
  6799. if (ret < 0) {
  6800. ERROR_OUT(ret, exit_scv);
  6801. }
  6802. sig->length = ED448_SIG_SIZE;
  6803. }
  6804. #endif /* HAVE_ED448 */
  6805. #if defined(HAVE_PQC)
  6806. #if defined(HAVE_FALCON)
  6807. if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
  6808. sig->length = FALCON_MAX_SIG_SIZE;
  6809. }
  6810. #endif
  6811. #if defined(HAVE_DILITHIUM)
  6812. if (ssl->hsType == DYNAMIC_TYPE_DILITHIUM) {
  6813. sig->length = DILITHIUM_MAX_SIG_SIZE;
  6814. }
  6815. #endif
  6816. #endif /* HAVE_PQC */
  6817. /* Advance state and proceed */
  6818. ssl->options.asyncState = TLS_ASYNC_DO;
  6819. } /* case TLS_ASYNC_BUILD */
  6820. FALL_THROUGH;
  6821. case TLS_ASYNC_DO:
  6822. {
  6823. #ifdef HAVE_ECC
  6824. if (ssl->hsType == DYNAMIC_TYPE_ECC) {
  6825. ret = EccSign(ssl, args->sigData, args->sigDataSz,
  6826. args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
  6827. (word32*)&sig->length, (ecc_key*)ssl->hsKey,
  6828. #ifdef HAVE_PK_CALLBACKS
  6829. ssl->buffers.key
  6830. #else
  6831. NULL
  6832. #endif
  6833. );
  6834. args->length = (word16)sig->length;
  6835. }
  6836. #endif /* HAVE_ECC */
  6837. #ifdef HAVE_ED25519
  6838. if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
  6839. ret = Ed25519Sign(ssl, args->sigData, args->sigDataSz,
  6840. args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
  6841. (word32*)&sig->length, (ed25519_key*)ssl->hsKey,
  6842. #ifdef HAVE_PK_CALLBACKS
  6843. ssl->buffers.key
  6844. #else
  6845. NULL
  6846. #endif
  6847. );
  6848. args->length = (word16)sig->length;
  6849. }
  6850. #endif
  6851. #ifdef HAVE_ED448
  6852. if (ssl->hsType == DYNAMIC_TYPE_ED448) {
  6853. ret = Ed448Sign(ssl, args->sigData, args->sigDataSz,
  6854. args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
  6855. (word32*)&sig->length, (ed448_key*)ssl->hsKey,
  6856. #ifdef HAVE_PK_CALLBACKS
  6857. ssl->buffers.key
  6858. #else
  6859. NULL
  6860. #endif
  6861. );
  6862. args->length = (word16)sig->length;
  6863. }
  6864. #endif
  6865. #if defined(HAVE_PQC)
  6866. #if defined(HAVE_FALCON)
  6867. if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
  6868. ret = wc_falcon_sign_msg(args->sigData, args->sigDataSz,
  6869. args->verify + HASH_SIG_SIZE +
  6870. VERIFY_HEADER, (word32*)&sig->length,
  6871. (falcon_key*)ssl->hsKey);
  6872. args->length = (word16)sig->length;
  6873. }
  6874. #endif
  6875. #if defined(HAVE_DILITHIUM)
  6876. if (ssl->hsType == DYNAMIC_TYPE_DILITHIUM) {
  6877. ret = wc_dilithium_sign_msg(args->sigData, args->sigDataSz,
  6878. args->verify + HASH_SIG_SIZE +
  6879. VERIFY_HEADER, (word32*)&sig->length,
  6880. (dilithium_key*)ssl->hsKey);
  6881. args->length = (word16)sig->length;
  6882. }
  6883. #endif
  6884. #endif /* HAVE_PQC */
  6885. #ifndef NO_RSA
  6886. if (ssl->hsType == DYNAMIC_TYPE_RSA) {
  6887. ret = RsaSign(ssl, sig->buffer, (word32)sig->length,
  6888. args->verify + HASH_SIG_SIZE + VERIFY_HEADER, &args->sigLen,
  6889. args->sigAlgo, ssl->suites->hashAlgo,
  6890. (RsaKey*)ssl->hsKey,
  6891. ssl->buffers.key
  6892. );
  6893. if (ret == 0) {
  6894. args->length = (word16)args->sigLen;
  6895. XMEMCPY(args->sigData,
  6896. args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
  6897. args->sigLen);
  6898. }
  6899. }
  6900. #endif /* !NO_RSA */
  6901. /* Check for error */
  6902. if (ret != 0) {
  6903. goto exit_scv;
  6904. }
  6905. /* Add signature length. */
  6906. c16toa(args->length, args->verify + HASH_SIG_SIZE);
  6907. /* Advance state and proceed */
  6908. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  6909. } /* case TLS_ASYNC_DO */
  6910. FALL_THROUGH;
  6911. case TLS_ASYNC_VERIFY:
  6912. {
  6913. #ifndef NO_RSA
  6914. if (ssl->hsType == DYNAMIC_TYPE_RSA) {
  6915. /* check for signature faults */
  6916. ret = VerifyRsaSign(ssl, args->sigData, args->sigLen,
  6917. sig->buffer, (word32)sig->length, args->sigAlgo,
  6918. ssl->suites->hashAlgo, (RsaKey*)ssl->hsKey,
  6919. ssl->buffers.key
  6920. );
  6921. }
  6922. #endif /* !NO_RSA */
  6923. #if defined(HAVE_ECC) && defined(WOLFSSL_CHECK_SIG_FAULTS)
  6924. if (ssl->hsType == DYNAMIC_TYPE_ECC) {
  6925. ret = EccVerify(ssl,
  6926. args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
  6927. sig->length, args->sigData, args->sigDataSz,
  6928. (ecc_key*)ssl->hsKey,
  6929. #ifdef HAVE_PK_CALLBACKS
  6930. ssl->buffers.key
  6931. #else
  6932. NULL
  6933. #endif
  6934. );
  6935. }
  6936. #endif
  6937. /* Check for error */
  6938. if (ret != 0) {
  6939. goto exit_scv;
  6940. }
  6941. /* Advance state and proceed */
  6942. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  6943. } /* case TLS_ASYNC_VERIFY */
  6944. FALL_THROUGH;
  6945. case TLS_ASYNC_FINALIZE:
  6946. {
  6947. /* Put the record and handshake headers on. */
  6948. AddTls13Headers(args->output, args->length + HASH_SIG_SIZE +
  6949. VERIFY_HEADER, certificate_verify, ssl);
  6950. args->sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ +
  6951. args->length + HASH_SIG_SIZE + VERIFY_HEADER;
  6952. #ifdef WOLFSSL_DTLS13
  6953. if (ssl->options.dtls)
  6954. args->sendSz += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
  6955. #endif /* WOLFSSL_DTLS13 */
  6956. /* Advance state and proceed */
  6957. ssl->options.asyncState = TLS_ASYNC_END;
  6958. } /* case TLS_ASYNC_FINALIZE */
  6959. FALL_THROUGH;
  6960. case TLS_ASYNC_END:
  6961. {
  6962. #ifdef WOLFSSL_DTLS13
  6963. if (ssl->options.dtls) {
  6964. ssl->options.buildingMsg = 0;
  6965. ret = Dtls13HandshakeSend(ssl, args->output,
  6966. MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA + MAX_MSG_EXTRA,
  6967. (word16)args->sendSz, certificate_verify, 1);
  6968. if (ret != 0)
  6969. goto exit_scv;
  6970. break;
  6971. }
  6972. #endif /* WOLFSSL_DTLS13 */
  6973. /* This message is always encrypted. */
  6974. ret = BuildTls13Message(ssl, args->output,
  6975. MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA,
  6976. args->output + RECORD_HEADER_SZ,
  6977. args->sendSz - RECORD_HEADER_SZ, handshake,
  6978. 1, 0, 0);
  6979. if (ret < 0) {
  6980. goto exit_scv;
  6981. }
  6982. else {
  6983. args->sendSz = ret;
  6984. ret = 0;
  6985. }
  6986. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  6987. if (ssl->hsInfoOn)
  6988. AddPacketName(ssl, "CertificateVerify");
  6989. if (ssl->toInfoOn) {
  6990. AddPacketInfo(ssl, "CertificateVerify", handshake,
  6991. args->output, args->sendSz, WRITE_PROTO, ssl->heap);
  6992. }
  6993. #endif
  6994. ssl->buffers.outputBuffer.length += args->sendSz;
  6995. ssl->options.buildingMsg = 0;
  6996. if (!ssl->options.groupMessages)
  6997. ret = SendBuffered(ssl);
  6998. break;
  6999. }
  7000. default:
  7001. ret = INPUT_CASE_ERROR;
  7002. } /* switch(ssl->options.asyncState) */
  7003. exit_scv:
  7004. WOLFSSL_LEAVE("SendTls13CertificateVerify", ret);
  7005. WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_SEND);
  7006. #ifdef WOLFSSL_ASYNC_CRYPT
  7007. /* Handle async operation */
  7008. if (ret == WC_PENDING_E) {
  7009. return ret;
  7010. }
  7011. #endif /* WOLFSSL_ASYNC_CRYPT */
  7012. /* Final cleanup */
  7013. FreeScv13Args(ssl, args);
  7014. FreeKeyExchange(ssl);
  7015. #ifdef WOLFSSL_ASYNC_IO
  7016. /* Cleanup async */
  7017. FreeAsyncCtx(ssl, 0);
  7018. #endif
  7019. if (ret != 0) {
  7020. WOLFSSL_ERROR_VERBOSE(ret);
  7021. }
  7022. return ret;
  7023. }
  7024. #endif
  7025. #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */
  7026. #if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
  7027. /* handle processing TLS v1.3 certificate (11) */
  7028. /* Parse and handle a TLS v1.3 Certificate message.
  7029. *
  7030. * ssl The SSL/TLS object.
  7031. * input The message buffer.
  7032. * inOutIdx On entry, the index into the message buffer of Certificate.
  7033. * On exit, the index of byte after the Certificate message.
  7034. * totalSz The length of the current handshake message.
  7035. * returns 0 on success and otherwise failure.
  7036. */
  7037. static int DoTls13Certificate(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  7038. word32 totalSz)
  7039. {
  7040. int ret = 0;
  7041. WOLFSSL_START(WC_FUNC_CERTIFICATE_DO);
  7042. WOLFSSL_ENTER("DoTls13Certificate");
  7043. #ifdef WOLFSSL_DTLS13
  7044. if (ssl->options.dtls && ssl->options.handShakeDone) {
  7045. /* certificate needs some special care after the handshake */
  7046. ret = Dtls13RtxProcessingCertificate(
  7047. ssl, input + *inOutIdx, totalSz);
  7048. }
  7049. #endif /* WOLFSSL_DTLS13 */
  7050. if (ret == 0)
  7051. ret = ProcessPeerCerts(ssl, input, inOutIdx, totalSz);
  7052. if (ret == 0) {
  7053. #if !defined(NO_WOLFSSL_CLIENT)
  7054. if (ssl->options.side == WOLFSSL_CLIENT_END)
  7055. ssl->options.serverState = SERVER_CERT_COMPLETE;
  7056. #endif
  7057. #if !defined(NO_WOLFSSL_SERVER) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  7058. if (ssl->options.side == WOLFSSL_SERVER_END &&
  7059. ssl->options.handShakeState == HANDSHAKE_DONE) {
  7060. /* reset handshake states */
  7061. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  7062. ssl->options.acceptState = TICKET_SENT;
  7063. ssl->options.handShakeState = SERVER_FINISHED_COMPLETE;
  7064. }
  7065. #endif
  7066. }
  7067. WOLFSSL_LEAVE("DoTls13Certificate", ret);
  7068. WOLFSSL_END(WC_FUNC_CERTIFICATE_DO);
  7069. return ret;
  7070. }
  7071. #endif
  7072. #if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  7073. defined(HAVE_ED448)
  7074. typedef struct Dcv13Args {
  7075. byte* output; /* not allocated */
  7076. word32 sendSz;
  7077. word16 sz;
  7078. word32 sigSz;
  7079. word32 idx;
  7080. word32 begin;
  7081. byte hashAlgo;
  7082. byte sigAlgo;
  7083. byte* sigData;
  7084. word16 sigDataSz;
  7085. } Dcv13Args;
  7086. static void FreeDcv13Args(WOLFSSL* ssl, void* pArgs)
  7087. {
  7088. Dcv13Args* args = (Dcv13Args*)pArgs;
  7089. if (args && args->sigData != NULL) {
  7090. XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  7091. args->sigData = NULL;
  7092. }
  7093. (void)ssl;
  7094. }
  7095. /* handle processing TLS v1.3 certificate_verify (15) */
  7096. /* Parse and handle a TLS v1.3 CertificateVerify message.
  7097. *
  7098. * ssl The SSL/TLS object.
  7099. * input The message buffer.
  7100. * inOutIdx On entry, the index into the message buffer of
  7101. * CertificateVerify.
  7102. * On exit, the index of byte after the CertificateVerify message.
  7103. * totalSz The length of the current handshake message.
  7104. * returns 0 on success and otherwise failure.
  7105. */
  7106. static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input,
  7107. word32* inOutIdx, word32 totalSz)
  7108. {
  7109. int ret = 0;
  7110. buffer* sig = &ssl->buffers.sig;
  7111. #ifdef WOLFSSL_ASYNC_CRYPT
  7112. Dcv13Args* args = NULL;
  7113. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  7114. #else
  7115. Dcv13Args args[1];
  7116. #endif
  7117. WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_DO);
  7118. WOLFSSL_ENTER("DoTls13CertificateVerify");
  7119. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  7120. ret = tsip_Tls13CertificateVerify(ssl, input, inOutIdx, totalSz);
  7121. if (ret != CRYPTOCB_UNAVAILABLE) {
  7122. goto exit_dcv;
  7123. }
  7124. ret = 0;
  7125. #endif
  7126. #ifdef WOLFSSL_ASYNC_CRYPT
  7127. if (ssl->async == NULL) {
  7128. ssl->async = (struct WOLFSSL_ASYNC*)
  7129. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  7130. DYNAMIC_TYPE_ASYNC);
  7131. if (ssl->async == NULL)
  7132. ERROR_OUT(MEMORY_E, exit_dcv);
  7133. }
  7134. args = (Dcv13Args*)ssl->async->args;
  7135. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  7136. if (ret != WC_NOT_PENDING_E) {
  7137. /* Check for error */
  7138. if (ret < 0)
  7139. goto exit_dcv;
  7140. }
  7141. else
  7142. #endif
  7143. {
  7144. /* Reset state */
  7145. ret = 0;
  7146. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  7147. XMEMSET(args, 0, sizeof(Dcv13Args));
  7148. args->hashAlgo = sha_mac;
  7149. args->sigAlgo = anonymous_sa_algo;
  7150. args->idx = *inOutIdx;
  7151. args->begin = *inOutIdx;
  7152. #ifdef WOLFSSL_ASYNC_CRYPT
  7153. ssl->async->freeArgs = FreeDcv13Args;
  7154. #endif
  7155. }
  7156. switch(ssl->options.asyncState)
  7157. {
  7158. case TLS_ASYNC_BEGIN:
  7159. {
  7160. #ifdef WOLFSSL_CALLBACKS
  7161. if (ssl->hsInfoOn) AddPacketName(ssl, "CertificateVerify");
  7162. if (ssl->toInfoOn) AddLateName("CertificateVerify",
  7163. &ssl->timeoutInfo);
  7164. #endif
  7165. /* Advance state and proceed */
  7166. ssl->options.asyncState = TLS_ASYNC_BUILD;
  7167. } /* case TLS_ASYNC_BEGIN */
  7168. FALL_THROUGH;
  7169. case TLS_ASYNC_BUILD:
  7170. {
  7171. int validSigAlgo;
  7172. /* Signature algorithm. */
  7173. if ((args->idx - args->begin) + ENUM_LEN + ENUM_LEN > totalSz) {
  7174. ERROR_OUT(BUFFER_ERROR, exit_dcv);
  7175. }
  7176. ret = DecodeTls13SigAlg(input + args->idx, &args->hashAlgo,
  7177. &args->sigAlgo);
  7178. if (ret < 0)
  7179. goto exit_dcv;
  7180. args->idx += OPAQUE16_LEN;
  7181. /* Signature length. */
  7182. if ((args->idx - args->begin) + OPAQUE16_LEN > totalSz) {
  7183. ERROR_OUT(BUFFER_ERROR, exit_dcv);
  7184. }
  7185. ato16(input + args->idx, &args->sz);
  7186. args->idx += OPAQUE16_LEN;
  7187. /* Signature data. */
  7188. if ((args->idx - args->begin) + args->sz > totalSz ||
  7189. args->sz > ENCRYPT_LEN) {
  7190. ERROR_OUT(BUFFER_ERROR, exit_dcv);
  7191. }
  7192. /* Check for public key of required type. */
  7193. /* Assume invalid unless signature algo matches the key provided */
  7194. validSigAlgo = 0;
  7195. #ifdef HAVE_ED25519
  7196. if (args->sigAlgo == ed25519_sa_algo) {
  7197. WOLFSSL_MSG("Peer sent ED25519 sig");
  7198. validSigAlgo = (ssl->peerEd25519Key != NULL) &&
  7199. ssl->peerEd25519KeyPresent;
  7200. }
  7201. #endif
  7202. #ifdef HAVE_ED448
  7203. if (args->sigAlgo == ed448_sa_algo) {
  7204. WOLFSSL_MSG("Peer sent ED448 sig");
  7205. validSigAlgo = (ssl->peerEd448Key != NULL) &&
  7206. ssl->peerEd448KeyPresent;
  7207. }
  7208. #endif
  7209. #ifdef HAVE_ECC
  7210. if (args->sigAlgo == ecc_dsa_sa_algo) {
  7211. WOLFSSL_MSG("Peer sent ECC sig");
  7212. validSigAlgo = (ssl->peerEccDsaKey != NULL) &&
  7213. ssl->peerEccDsaKeyPresent;
  7214. }
  7215. #endif
  7216. #ifdef HAVE_PQC
  7217. if (args->sigAlgo == falcon_level1_sa_algo) {
  7218. WOLFSSL_MSG("Peer sent Falcon Level 1 sig");
  7219. validSigAlgo = (ssl->peerFalconKey != NULL) &&
  7220. ssl->peerFalconKeyPresent;
  7221. }
  7222. if (args->sigAlgo == falcon_level5_sa_algo) {
  7223. WOLFSSL_MSG("Peer sent Falcon Level 5 sig");
  7224. validSigAlgo = (ssl->peerFalconKey != NULL) &&
  7225. ssl->peerFalconKeyPresent;
  7226. }
  7227. if (args->sigAlgo == dilithium_level2_sa_algo) {
  7228. WOLFSSL_MSG("Peer sent Dilithium Level 2 sig");
  7229. validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
  7230. ssl->peerDilithiumKeyPresent;
  7231. }
  7232. if (args->sigAlgo == dilithium_level3_sa_algo) {
  7233. WOLFSSL_MSG("Peer sent Dilithium Level 3 sig");
  7234. validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
  7235. ssl->peerDilithiumKeyPresent;
  7236. }
  7237. if (args->sigAlgo == dilithium_level5_sa_algo) {
  7238. WOLFSSL_MSG("Peer sent Dilithium Level 5 sig");
  7239. validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
  7240. ssl->peerDilithiumKeyPresent;
  7241. }
  7242. if (args->sigAlgo == dilithium_aes_level2_sa_algo) {
  7243. WOLFSSL_MSG("Peer sent Dilithium AES Level 2 sig");
  7244. validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
  7245. ssl->peerDilithiumKeyPresent;
  7246. }
  7247. if (args->sigAlgo == dilithium_aes_level3_sa_algo) {
  7248. WOLFSSL_MSG("Peer sent Dilithium AES Level 3 sig");
  7249. validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
  7250. ssl->peerDilithiumKeyPresent;
  7251. }
  7252. if (args->sigAlgo == dilithium_aes_level5_sa_algo) {
  7253. WOLFSSL_MSG("Peer sent Dilithium AES Level 5 sig");
  7254. validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
  7255. ssl->peerDilithiumKeyPresent;
  7256. }
  7257. #endif
  7258. #ifndef NO_RSA
  7259. if (args->sigAlgo == rsa_sa_algo) {
  7260. WOLFSSL_MSG("Peer sent PKCS#1.5 algo - not valid TLS 1.3");
  7261. ERROR_OUT(INVALID_PARAMETER, exit_dcv);
  7262. }
  7263. if (args->sigAlgo == rsa_pss_sa_algo) {
  7264. WOLFSSL_MSG("Peer sent RSA sig");
  7265. validSigAlgo = (ssl->peerRsaKey != NULL) &&
  7266. ssl->peerRsaKeyPresent;
  7267. }
  7268. #endif
  7269. if (!validSigAlgo) {
  7270. WOLFSSL_MSG("Sig algo doesn't correspond to certficate");
  7271. ERROR_OUT(SIG_VERIFY_E, exit_dcv);
  7272. }
  7273. sig->buffer = (byte*)XMALLOC(args->sz, ssl->heap,
  7274. DYNAMIC_TYPE_SIGNATURE);
  7275. if (sig->buffer == NULL) {
  7276. ERROR_OUT(MEMORY_E, exit_dcv);
  7277. }
  7278. sig->length = args->sz;
  7279. XMEMCPY(sig->buffer, input + args->idx, args->sz);
  7280. #ifdef HAVE_ECC
  7281. if (ssl->peerEccDsaKeyPresent) {
  7282. WOLFSSL_MSG("Doing ECC peer cert verify");
  7283. args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
  7284. DYNAMIC_TYPE_SIGNATURE);
  7285. if (args->sigData == NULL) {
  7286. ERROR_OUT(MEMORY_E, exit_dcv);
  7287. }
  7288. ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
  7289. if (ret != 0)
  7290. goto exit_dcv;
  7291. ret = CreateECCEncodedSig(args->sigData,
  7292. args->sigDataSz, args->hashAlgo);
  7293. if (ret < 0)
  7294. goto exit_dcv;
  7295. args->sigDataSz = (word16)ret;
  7296. ret = 0;
  7297. }
  7298. #endif
  7299. #ifdef HAVE_ED25519
  7300. if (ssl->peerEd25519KeyPresent) {
  7301. WOLFSSL_MSG("Doing ED25519 peer cert verify");
  7302. args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
  7303. DYNAMIC_TYPE_SIGNATURE);
  7304. if (args->sigData == NULL) {
  7305. ERROR_OUT(MEMORY_E, exit_dcv);
  7306. }
  7307. CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
  7308. ret = 0;
  7309. }
  7310. #endif
  7311. #ifdef HAVE_ED448
  7312. if (ssl->peerEd448KeyPresent) {
  7313. WOLFSSL_MSG("Doing ED448 peer cert verify");
  7314. args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
  7315. DYNAMIC_TYPE_SIGNATURE);
  7316. if (args->sigData == NULL) {
  7317. ERROR_OUT(MEMORY_E, exit_dcv);
  7318. }
  7319. CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
  7320. ret = 0;
  7321. }
  7322. #endif
  7323. #ifdef HAVE_PQC
  7324. if (ssl->peerFalconKeyPresent) {
  7325. WOLFSSL_MSG("Doing Falcon peer cert verify");
  7326. args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
  7327. DYNAMIC_TYPE_SIGNATURE);
  7328. if (args->sigData == NULL) {
  7329. ERROR_OUT(MEMORY_E, exit_dcv);
  7330. }
  7331. CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
  7332. ret = 0;
  7333. }
  7334. if (ssl->peerDilithiumKeyPresent) {
  7335. WOLFSSL_MSG("Doing Dilithium peer cert verify");
  7336. args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
  7337. DYNAMIC_TYPE_SIGNATURE);
  7338. if (args->sigData == NULL) {
  7339. ERROR_OUT(MEMORY_E, exit_dcv);
  7340. }
  7341. CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
  7342. ret = 0;
  7343. }
  7344. #endif
  7345. /* Advance state and proceed */
  7346. ssl->options.asyncState = TLS_ASYNC_DO;
  7347. } /* case TLS_ASYNC_BUILD */
  7348. FALL_THROUGH;
  7349. case TLS_ASYNC_DO:
  7350. {
  7351. #ifndef NO_RSA
  7352. if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
  7353. ret = RsaVerify(ssl, sig->buffer, (word32)sig->length, &args->output,
  7354. args->sigAlgo, args->hashAlgo, ssl->peerRsaKey,
  7355. #ifdef HAVE_PK_CALLBACKS
  7356. &ssl->buffers.peerRsaKey
  7357. #else
  7358. NULL
  7359. #endif
  7360. );
  7361. if (ret >= 0) {
  7362. args->sendSz = ret;
  7363. ret = 0;
  7364. }
  7365. }
  7366. #endif /* !NO_RSA */
  7367. #ifdef HAVE_ECC
  7368. if (ssl->peerEccDsaKeyPresent) {
  7369. ret = EccVerify(ssl, input + args->idx, args->sz,
  7370. args->sigData, args->sigDataSz,
  7371. ssl->peerEccDsaKey,
  7372. #ifdef HAVE_PK_CALLBACKS
  7373. &ssl->buffers.peerEccDsaKey
  7374. #else
  7375. NULL
  7376. #endif
  7377. );
  7378. if (ret >= 0) {
  7379. /* CLIENT/SERVER: data verified with public key from
  7380. * certificate. */
  7381. ssl->options.peerAuthGood = 1;
  7382. FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
  7383. ssl->peerEccDsaKeyPresent = 0;
  7384. }
  7385. }
  7386. #endif /* HAVE_ECC */
  7387. #ifdef HAVE_ED25519
  7388. if (ssl->peerEd25519KeyPresent) {
  7389. ret = Ed25519Verify(ssl, input + args->idx, args->sz,
  7390. args->sigData, args->sigDataSz,
  7391. ssl->peerEd25519Key,
  7392. #ifdef HAVE_PK_CALLBACKS
  7393. &ssl->buffers.peerEd25519Key
  7394. #else
  7395. NULL
  7396. #endif
  7397. );
  7398. if (ret >= 0) {
  7399. /* CLIENT/SERVER: data verified with public key from
  7400. * certificate. */
  7401. ssl->options.peerAuthGood = 1;
  7402. FreeKey(ssl, DYNAMIC_TYPE_ED25519,
  7403. (void**)&ssl->peerEd25519Key);
  7404. ssl->peerEd25519KeyPresent = 0;
  7405. }
  7406. }
  7407. #endif
  7408. #ifdef HAVE_ED448
  7409. if (ssl->peerEd448KeyPresent) {
  7410. ret = Ed448Verify(ssl, input + args->idx, args->sz,
  7411. args->sigData, args->sigDataSz,
  7412. ssl->peerEd448Key,
  7413. #ifdef HAVE_PK_CALLBACKS
  7414. &ssl->buffers.peerEd448Key
  7415. #else
  7416. NULL
  7417. #endif
  7418. );
  7419. if (ret >= 0) {
  7420. /* CLIENT/SERVER: data verified with public key from
  7421. * certificate. */
  7422. ssl->options.peerAuthGood = 1;
  7423. FreeKey(ssl, DYNAMIC_TYPE_ED448,
  7424. (void**)&ssl->peerEd448Key);
  7425. ssl->peerEd448KeyPresent = 0;
  7426. }
  7427. }
  7428. #endif
  7429. #if defined(HAVE_PQC) && defined(HAVE_FALCON)
  7430. if (ssl->peerFalconKeyPresent) {
  7431. int res = 0;
  7432. WOLFSSL_MSG("Doing Falcon peer cert verify");
  7433. ret = wc_falcon_verify_msg(input + args->idx, args->sz,
  7434. args->sigData, args->sigDataSz,
  7435. &res, ssl->peerFalconKey);
  7436. if ((ret >= 0) && (res == 1)) {
  7437. /* CLIENT/SERVER: data verified with public key from
  7438. * certificate. */
  7439. ssl->options.peerAuthGood = 1;
  7440. FreeKey(ssl, DYNAMIC_TYPE_FALCON,
  7441. (void**)&ssl->peerFalconKey);
  7442. ssl->peerFalconKeyPresent = 0;
  7443. }
  7444. }
  7445. #endif /* HAVE_PQC && HAVE_FALCON */
  7446. #if defined(HAVE_PQC) && defined(HAVE_DILITHIUM)
  7447. if (ssl->peerDilithiumKeyPresent) {
  7448. int res = 0;
  7449. WOLFSSL_MSG("Doing Dilithium peer cert verify");
  7450. ret = wc_dilithium_verify_msg(input + args->idx, args->sz,
  7451. args->sigData, args->sigDataSz,
  7452. &res, ssl->peerDilithiumKey);
  7453. if ((ret >= 0) && (res == 1)) {
  7454. /* CLIENT/SERVER: data verified with public key from
  7455. * certificate. */
  7456. ssl->options.peerAuthGood = 1;
  7457. FreeKey(ssl, DYNAMIC_TYPE_DILITHIUM,
  7458. (void**)&ssl->peerDilithiumKey);
  7459. ssl->peerDilithiumKeyPresent = 0;
  7460. }
  7461. }
  7462. #endif /* HAVE_PQC && HAVE_DILITHIUM */
  7463. /* Check for error */
  7464. if (ret != 0) {
  7465. goto exit_dcv;
  7466. }
  7467. /* Advance state and proceed */
  7468. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  7469. } /* case TLS_ASYNC_DO */
  7470. FALL_THROUGH;
  7471. case TLS_ASYNC_VERIFY:
  7472. {
  7473. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  7474. if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
  7475. ret = CheckRSASignature(ssl, args->sigAlgo, args->hashAlgo,
  7476. args->output, args->sendSz);
  7477. if (ret != 0)
  7478. goto exit_dcv;
  7479. /* CLIENT/SERVER: data verified with public key from
  7480. * certificate. */
  7481. ssl->peerRsaKeyPresent = 0;
  7482. FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
  7483. ssl->options.peerAuthGood = 1;
  7484. }
  7485. #endif /* !NO_RSA && WC_RSA_PSS */
  7486. /* Advance state and proceed */
  7487. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  7488. } /* case TLS_ASYNC_VERIFY */
  7489. FALL_THROUGH;
  7490. case TLS_ASYNC_FINALIZE:
  7491. {
  7492. ssl->options.havePeerVerify = 1;
  7493. /* Set final index */
  7494. args->idx += args->sz;
  7495. *inOutIdx = args->idx;
  7496. /* Encryption is always on: add padding */
  7497. *inOutIdx += ssl->keys.padSz;
  7498. /* Advance state and proceed */
  7499. ssl->options.asyncState = TLS_ASYNC_END;
  7500. #if !defined(NO_WOLFSSL_CLIENT)
  7501. if (ssl->options.side == WOLFSSL_CLIENT_END)
  7502. ssl->options.serverState = SERVER_CERT_VERIFY_COMPLETE;
  7503. #endif
  7504. } /* case TLS_ASYNC_FINALIZE */
  7505. FALL_THROUGH;
  7506. case TLS_ASYNC_END:
  7507. {
  7508. break;
  7509. }
  7510. default:
  7511. ret = INPUT_CASE_ERROR;
  7512. } /* switch(ssl->options.asyncState) */
  7513. exit_dcv:
  7514. WOLFSSL_LEAVE("DoTls13CertificateVerify", ret);
  7515. WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_DO);
  7516. #ifdef WOLFSSL_ASYNC_CRYPT
  7517. /* Handle async operation */
  7518. if (ret == WC_PENDING_E) {
  7519. /* Mark message as not received so it can process again */
  7520. ssl->msgsReceived.got_certificate_verify = 0;
  7521. return ret;
  7522. }
  7523. else
  7524. #endif /* WOLFSSL_ASYNC_CRYPT */
  7525. if (ret != 0) {
  7526. WOLFSSL_ERROR_VERBOSE(ret);
  7527. if (ret != INVALID_PARAMETER) {
  7528. SendAlert(ssl, alert_fatal, decrypt_error);
  7529. }
  7530. }
  7531. /* Final cleanup */
  7532. FreeDcv13Args(ssl, args);
  7533. FreeKeyExchange(ssl);
  7534. #ifdef WOLFSSL_ASYNC_IO
  7535. /* Cleanup async */
  7536. FreeAsyncCtx(ssl, 0);
  7537. #endif
  7538. return ret;
  7539. }
  7540. #endif /* !NO_RSA || HAVE_ECC */
  7541. #endif /* !NO_CERTS */
  7542. /* Parse and handle a TLS v1.3 Finished message.
  7543. *
  7544. * ssl The SSL/TLS object.
  7545. * input The message buffer.
  7546. * inOutIdx On entry, the index into the message buffer of Finished.
  7547. * On exit, the index of byte after the Finished message and padding.
  7548. * size Length of message data.
  7549. * totalSz Length of remaining data in the message buffer.
  7550. * sniff Indicates whether we are sniffing packets.
  7551. * returns 0 on success and otherwise failure.
  7552. */
  7553. int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  7554. word32 size, word32 totalSz, int sniff)
  7555. {
  7556. int ret;
  7557. word32 finishedSz = 0;
  7558. byte* secret;
  7559. byte mac[WC_MAX_DIGEST_SIZE];
  7560. WOLFSSL_START(WC_FUNC_FINISHED_DO);
  7561. WOLFSSL_ENTER("DoTls13Finished");
  7562. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
  7563. /* verify the client sent certificate if required */
  7564. if (ssl->options.side == WOLFSSL_SERVER_END && !ssl->options.resuming &&
  7565. (ssl->options.mutualAuth || ssl->options.failNoCert)) {
  7566. #ifdef OPENSSL_COMPATIBLE_DEFAULTS
  7567. if (ssl->options.isPSK) {
  7568. WOLFSSL_MSG("TLS v1.3 client used PSK but cert required. Allowing "
  7569. "for OpenSSL compatibility");
  7570. }
  7571. else
  7572. #endif
  7573. if (!ssl->options.havePeerCert || !ssl->options.havePeerVerify) {
  7574. ret = NO_PEER_CERT; /* NO_PEER_VERIFY */
  7575. WOLFSSL_MSG("TLS v1.3 client did not present peer cert");
  7576. DoCertFatalAlert(ssl, ret);
  7577. return ret;
  7578. }
  7579. }
  7580. #endif
  7581. /* check against totalSz */
  7582. if (*inOutIdx + size > totalSz)
  7583. return BUFFER_E;
  7584. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  7585. ret = tsip_Tls13HandleFinished(ssl, input, inOutIdx, size, totalSz);
  7586. if (ret == 0) {
  7587. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  7588. return ret;
  7589. }
  7590. if (ret == VERIFY_FINISHED_ERROR) {
  7591. SendAlert(ssl, alert_fatal, decrypt_error);
  7592. return ret;
  7593. }
  7594. if (ret != CRYPTOCB_UNAVAILABLE) {
  7595. /* other errors */
  7596. return ret;
  7597. }
  7598. ret = 0;
  7599. #endif /* WOLFSSL_RENESAS_TSIP_TLS && WOLFSSL_RENESAS_TSIP_VER >= 115 */
  7600. if (ssl->options.handShakeDone) {
  7601. ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
  7602. ssl->keys.client_write_MAC_secret);
  7603. if (ret != 0)
  7604. return ret;
  7605. secret = ssl->keys.client_write_MAC_secret;
  7606. }
  7607. else if (ssl->options.side == WOLFSSL_CLIENT_END) {
  7608. /* All the handshake messages have been received to calculate
  7609. * client and server finished keys.
  7610. */
  7611. ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
  7612. ssl->keys.client_write_MAC_secret);
  7613. if (ret != 0)
  7614. return ret;
  7615. ret = DeriveFinishedSecret(ssl, ssl->serverSecret,
  7616. ssl->keys.server_write_MAC_secret);
  7617. if (ret != 0)
  7618. return ret;
  7619. secret = ssl->keys.server_write_MAC_secret;
  7620. }
  7621. else {
  7622. secret = ssl->keys.client_write_MAC_secret;
  7623. }
  7624. if (sniff == NO_SNIFF) {
  7625. ret = BuildTls13HandshakeHmac(ssl, secret, mac, &finishedSz);
  7626. #ifdef WOLFSSL_HAVE_TLS_UNIQUE
  7627. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  7628. XMEMCPY(ssl->serverFinished, mac, finishedSz);
  7629. ssl->serverFinished_len = finishedSz;
  7630. }
  7631. else {
  7632. XMEMCPY(ssl->clientFinished, mac, finishedSz);
  7633. ssl->clientFinished_len = finishedSz;
  7634. }
  7635. #endif /* WOLFSSL_HAVE_TLS_UNIQUE */
  7636. if (ret != 0)
  7637. return ret;
  7638. if (size != finishedSz)
  7639. return BUFFER_ERROR;
  7640. }
  7641. #ifdef WOLFSSL_CALLBACKS
  7642. if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
  7643. if (ssl->toInfoOn) AddLateName("Finished", &ssl->timeoutInfo);
  7644. #endif
  7645. if (sniff == NO_SNIFF) {
  7646. /* Actually check verify data. */
  7647. if (XMEMCMP(input + *inOutIdx, mac, size) != 0){
  7648. WOLFSSL_MSG("Verify finished error on hashes");
  7649. SendAlert(ssl, alert_fatal, decrypt_error);
  7650. WOLFSSL_ERROR_VERBOSE(VERIFY_FINISHED_ERROR);
  7651. return VERIFY_FINISHED_ERROR;
  7652. }
  7653. }
  7654. /* Force input exhaustion at ProcessReply by consuming padSz. */
  7655. *inOutIdx += size + ssl->keys.padSz;
  7656. if (ssl->options.side == WOLFSSL_SERVER_END &&
  7657. !ssl->options.handShakeDone) {
  7658. #ifdef WOLFSSL_EARLY_DATA
  7659. if (ssl->earlyData != no_early_data) {
  7660. if ((ret = DeriveTls13Keys(ssl, no_key, DECRYPT_SIDE_ONLY, 1)) != 0)
  7661. return ret;
  7662. }
  7663. #endif
  7664. /* Setup keys for application data messages from client. */
  7665. if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
  7666. return ret;
  7667. }
  7668. #ifndef NO_WOLFSSL_CLIENT
  7669. if (ssl->options.side == WOLFSSL_CLIENT_END)
  7670. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  7671. #endif
  7672. #ifndef NO_WOLFSSL_SERVER
  7673. if (ssl->options.side == WOLFSSL_SERVER_END) {
  7674. ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
  7675. ssl->options.handShakeState = HANDSHAKE_DONE;
  7676. ssl->options.handShakeDone = 1;
  7677. }
  7678. #endif
  7679. #if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_EARLY_DATA)
  7680. if (ssl->options.dtls && ssl->earlyData > early_data_ext) {
  7681. /* DTLSv1.3 has no EndOfearlydata messages. We stop processing EarlyData
  7682. as soon we receive the client's finished message */
  7683. ssl->earlyData = done_early_data;
  7684. }
  7685. #endif /* WOLFSSL_DTLS13 && WOLFSSL_EARLY_DATA */
  7686. #if defined(WOLFSSL_QUIC) && defined(WOLFSSL_EARLY_DATA)
  7687. if (WOLFSSL_IS_QUIC(ssl) && ssl->earlyData > early_data_ext) {
  7688. /* QUIC has no EndOfEarlyData messages. We stop processing EarlyData
  7689. as soon we receive the client's finished message */
  7690. ssl->earlyData = done_early_data;
  7691. }
  7692. #endif /* WOLFSSL_QUIC && WOLFSSL_EARLY_DATA */
  7693. WOLFSSL_LEAVE("DoTls13Finished", 0);
  7694. WOLFSSL_END(WC_FUNC_FINISHED_DO);
  7695. return 0;
  7696. }
  7697. #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
  7698. /* Send the TLS v1.3 Finished message.
  7699. *
  7700. * ssl The SSL/TLS object.
  7701. * returns 0 on success, otherwise failure.
  7702. */
  7703. static int SendTls13Finished(WOLFSSL* ssl)
  7704. {
  7705. int sendSz;
  7706. int finishedSz = ssl->specs.hash_size;
  7707. byte* input;
  7708. byte* output;
  7709. int ret;
  7710. int headerSz = HANDSHAKE_HEADER_SZ;
  7711. int outputSz;
  7712. byte* secret;
  7713. #ifdef WOLFSSL_DTLS13
  7714. int dtlsRet = 0, isDtls = 0;
  7715. #endif /* WOLFSSL_DTLS13 */
  7716. WOLFSSL_START(WC_FUNC_FINISHED_SEND);
  7717. WOLFSSL_ENTER("SendTls13Finished");
  7718. ssl->options.buildingMsg = 1;
  7719. #ifdef WOLFSSL_DTLS13
  7720. if (ssl->options.dtls) {
  7721. headerSz = DTLS_HANDSHAKE_HEADER_SZ;
  7722. /* using isDtls instead of ssl->options.dtls will abide clang static
  7723. analyzer on unsing an uninitialized value */
  7724. isDtls = 1;
  7725. }
  7726. #endif /* WOLFSSL_DTLS13 */
  7727. outputSz = WC_MAX_DIGEST_SIZE + DTLS_HANDSHAKE_HEADER_SZ + MAX_MSG_EXTRA;
  7728. /* Check buffers are big enough and grow if needed. */
  7729. if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
  7730. return ret;
  7731. /* get output buffer */
  7732. output = ssl->buffers.outputBuffer.buffer +
  7733. ssl->buffers.outputBuffer.length;
  7734. input = output + RECORD_HEADER_SZ;
  7735. #ifdef WOLFSSL_DTLS13
  7736. if (isDtls)
  7737. input = output + Dtls13GetRlHeaderLength(ssl, 1);
  7738. #endif /* WOLFSSL_DTLS13 */
  7739. AddTls13HandShakeHeader(input, finishedSz, 0, finishedSz, finished, ssl);
  7740. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  7741. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  7742. ret = tsip_Tls13SendFinished(ssl, output, outputSz, input, 1);
  7743. if (ret != CRYPTOCB_UNAVAILABLE) {
  7744. return ret;
  7745. }
  7746. ret = 0;
  7747. }
  7748. #endif /* WOLFSSL_RENESAS_TSIP_TLS && WOLFSSL_RENESAS_TSIP_VER >= 115 */
  7749. /* make finished hashes */
  7750. if (ssl->options.handShakeDone) {
  7751. ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
  7752. ssl->keys.client_write_MAC_secret);
  7753. if (ret != 0)
  7754. return ret;
  7755. secret = ssl->keys.client_write_MAC_secret;
  7756. }
  7757. else if (ssl->options.side == WOLFSSL_CLIENT_END)
  7758. secret = ssl->keys.client_write_MAC_secret;
  7759. else {
  7760. /* All the handshake messages have been done to calculate client and
  7761. * server finished keys.
  7762. */
  7763. ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
  7764. ssl->keys.client_write_MAC_secret);
  7765. if (ret != 0)
  7766. return ret;
  7767. ret = DeriveFinishedSecret(ssl, ssl->serverSecret,
  7768. ssl->keys.server_write_MAC_secret);
  7769. if (ret != 0)
  7770. return ret;
  7771. secret = ssl->keys.server_write_MAC_secret;
  7772. }
  7773. ret = BuildTls13HandshakeHmac(ssl, secret, &input[headerSz], NULL);
  7774. if (ret != 0)
  7775. return ret;
  7776. #ifdef WOLFSSL_HAVE_TLS_UNIQUE
  7777. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  7778. XMEMCPY(ssl->clientFinished, &input[headerSz], finishedSz);
  7779. ssl->clientFinished_len = finishedSz;
  7780. }
  7781. else {
  7782. XMEMCPY(ssl->serverFinished, &input[headerSz], finishedSz);
  7783. ssl->serverFinished_len = finishedSz;
  7784. }
  7785. #endif /* WOLFSSL_HAVE_TLS_UNIQUE */
  7786. #ifdef WOLFSSL_DTLS13
  7787. if (isDtls) {
  7788. dtlsRet = Dtls13HandshakeSend(ssl, output, (word16)outputSz,
  7789. (word16)(Dtls13GetRlHeaderLength(ssl, 1) + headerSz + finishedSz), finished,
  7790. 1);
  7791. if (dtlsRet != 0 && dtlsRet != WANT_WRITE)
  7792. return ret;
  7793. } else
  7794. #endif /* WOLFSSL_DTLS13 */
  7795. {
  7796. /* This message is always encrypted. */
  7797. sendSz = BuildTls13Message(ssl, output, outputSz, input,
  7798. headerSz + finishedSz, handshake, 1, 0, 0);
  7799. if (sendSz < 0) {
  7800. WOLFSSL_ERROR_VERBOSE(BUILD_MSG_ERROR);
  7801. return BUILD_MSG_ERROR;
  7802. }
  7803. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  7804. if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
  7805. if (ssl->toInfoOn) {
  7806. AddPacketInfo(ssl, "Finished", handshake, output, sendSz,
  7807. WRITE_PROTO, ssl->heap);
  7808. }
  7809. #endif
  7810. ssl->buffers.outputBuffer.length += sendSz;
  7811. ssl->options.buildingMsg = 0;
  7812. }
  7813. if (ssl->options.side == WOLFSSL_SERVER_END) {
  7814. #ifdef WOLFSSL_EARLY_DATA
  7815. byte storeTrafficDecKeys = ssl->earlyData == no_early_data;
  7816. #endif
  7817. /* Can send application data now. */
  7818. if ((ret = DeriveMasterSecret(ssl)) != 0)
  7819. return ret;
  7820. /* Last use of preMasterSecret - zeroize as soon as possible. */
  7821. ForceZero(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  7822. #ifdef WOLFSSL_EARLY_DATA
  7823. #ifdef WOLFSSL_DTLS13
  7824. /* DTLS13 dynamically change keys and it needs all
  7825. the keys in ssl->keys to save the keying material */
  7826. if (isDtls)
  7827. storeTrafficDecKeys = 1;
  7828. #endif /* WOLFSSL_DTLS13 */
  7829. if ((ret = DeriveTls13Keys(ssl, traffic_key, ENCRYPT_SIDE_ONLY, 1))
  7830. != 0) {
  7831. return ret;
  7832. }
  7833. if ((ret = DeriveTls13Keys(ssl, traffic_key, DECRYPT_SIDE_ONLY,
  7834. storeTrafficDecKeys)) != 0) {
  7835. return ret;
  7836. }
  7837. #else
  7838. if ((ret = DeriveTls13Keys(ssl, traffic_key, ENCRYPT_AND_DECRYPT_SIDE,
  7839. 1)) != 0) {
  7840. return ret;
  7841. }
  7842. #endif
  7843. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  7844. return ret;
  7845. #ifdef WOLFSSL_DTLS13
  7846. if (isDtls) {
  7847. w64wrapper epochTraffic0;
  7848. epochTraffic0 = w64From32(0, DTLS13_EPOCH_TRAFFIC0);
  7849. ssl->dtls13Epoch = epochTraffic0;
  7850. ssl->dtls13PeerEpoch = epochTraffic0;
  7851. ret = Dtls13NewEpoch(
  7852. ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE);
  7853. if (ret != 0)
  7854. return ret;
  7855. ret = Dtls13SetEpochKeys(
  7856. ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE);
  7857. if (ret != 0)
  7858. return ret;
  7859. }
  7860. #endif /* WOLFSSL_DTLS13 */
  7861. }
  7862. if (ssl->options.side == WOLFSSL_CLIENT_END &&
  7863. !ssl->options.handShakeDone) {
  7864. #ifdef WOLFSSL_EARLY_DATA
  7865. if (ssl->earlyData != no_early_data) {
  7866. if ((ret = DeriveTls13Keys(ssl, no_key, ENCRYPT_AND_DECRYPT_SIDE,
  7867. 1)) != 0) {
  7868. return ret;
  7869. }
  7870. }
  7871. #endif
  7872. /* Setup keys for application data messages. */
  7873. if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0)
  7874. return ret;
  7875. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  7876. ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret);
  7877. if (ret != 0)
  7878. return ret;
  7879. #endif
  7880. #ifdef WOLFSSL_DTLS13
  7881. if (isDtls) {
  7882. w64wrapper epochTraffic0;
  7883. epochTraffic0 = w64From32(0, DTLS13_EPOCH_TRAFFIC0);
  7884. ssl->dtls13Epoch = epochTraffic0;
  7885. ssl->dtls13PeerEpoch = epochTraffic0;
  7886. ret = Dtls13NewEpoch(
  7887. ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE);
  7888. if (ret != 0)
  7889. return ret;
  7890. ret = Dtls13SetEpochKeys(
  7891. ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE);
  7892. if (ret != 0)
  7893. return ret;
  7894. }
  7895. #endif /* WOLFSSL_DTLS13 */
  7896. }
  7897. #ifndef NO_WOLFSSL_CLIENT
  7898. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  7899. ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
  7900. ssl->options.handShakeState = HANDSHAKE_DONE;
  7901. ssl->options.handShakeDone = 1;
  7902. }
  7903. #endif
  7904. #ifndef NO_WOLFSSL_SERVER
  7905. if (ssl->options.side == WOLFSSL_SERVER_END) {
  7906. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  7907. }
  7908. #endif
  7909. #ifdef WOLFSSL_DTLS13
  7910. if (isDtls) {
  7911. WOLFSSL_LEAVE("SendTls13Finished", ret);
  7912. WOLFSSL_END(WC_FUNC_FINISHED_SEND);
  7913. return dtlsRet;
  7914. }
  7915. #endif /* WOLFSSL_DTLS13 */
  7916. if ((ret = SendBuffered(ssl)) != 0)
  7917. return ret;
  7918. WOLFSSL_LEAVE("SendTls13Finished", ret);
  7919. WOLFSSL_END(WC_FUNC_FINISHED_SEND);
  7920. return ret;
  7921. }
  7922. #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */
  7923. /* handle generation TLS v1.3 key_update (24) */
  7924. /* Send the TLS v1.3 KeyUpdate message.
  7925. *
  7926. * ssl The SSL/TLS object.
  7927. * returns 0 on success, otherwise failure.
  7928. */
  7929. static int SendTls13KeyUpdate(WOLFSSL* ssl)
  7930. {
  7931. int sendSz;
  7932. byte* input;
  7933. byte* output;
  7934. int ret;
  7935. int headerSz = HANDSHAKE_HEADER_SZ;
  7936. int outputSz;
  7937. word32 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  7938. WOLFSSL_START(WC_FUNC_KEY_UPDATE_SEND);
  7939. WOLFSSL_ENTER("SendTls13KeyUpdate");
  7940. #ifdef WOLFSSL_DTLS13
  7941. if (ssl->options.dtls)
  7942. i = Dtls13GetRlHeaderLength(ssl, 1) + DTLS_HANDSHAKE_HEADER_SZ;
  7943. #endif /* WOLFSSL_DTLS13 */
  7944. outputSz = OPAQUE8_LEN + MAX_MSG_EXTRA;
  7945. /* Check buffers are big enough and grow if needed. */
  7946. if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
  7947. return ret;
  7948. /* get output buffer */
  7949. output = ssl->buffers.outputBuffer.buffer +
  7950. ssl->buffers.outputBuffer.length;
  7951. input = output + RECORD_HEADER_SZ;
  7952. #ifdef WOLFSSL_DTLS13
  7953. if (ssl->options.dtls)
  7954. input = output + Dtls13GetRlHeaderLength(ssl, 1);
  7955. #endif /* WOLFSSL_DTLS13 */
  7956. AddTls13Headers(output, OPAQUE8_LEN, key_update, ssl);
  7957. /* If:
  7958. * 1. I haven't sent a KeyUpdate requesting a response and
  7959. * 2. This isn't responding to peer KeyUpdate requiring a response then,
  7960. * I want a response.
  7961. */
  7962. ssl->keys.updateResponseReq = output[i++] =
  7963. !ssl->keys.updateResponseReq && !ssl->keys.keyUpdateRespond;
  7964. /* Sent response, no longer need to respond. */
  7965. ssl->keys.keyUpdateRespond = 0;
  7966. #ifdef WOLFSSL_DTLS13
  7967. if (ssl->options.dtls) {
  7968. ret = Dtls13HandshakeSend(ssl, output, (word16)outputSz,
  7969. OPAQUE8_LEN + Dtls13GetRlHeaderLength(ssl, 1) +
  7970. DTLS_HANDSHAKE_HEADER_SZ,
  7971. key_update, 0);
  7972. }
  7973. else
  7974. #endif /* WOLFSSL_DTLS13 */
  7975. {
  7976. /* This message is always encrypted. */
  7977. sendSz = BuildTls13Message(ssl, output, outputSz, input,
  7978. headerSz + OPAQUE8_LEN, handshake, 0, 0, 0);
  7979. if (sendSz < 0)
  7980. return BUILD_MSG_ERROR;
  7981. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  7982. if (ssl->hsInfoOn) AddPacketName(ssl, "KeyUpdate");
  7983. if (ssl->toInfoOn) {
  7984. AddPacketInfo(ssl, "KeyUpdate", handshake, output, sendSz,
  7985. WRITE_PROTO, ssl->heap);
  7986. }
  7987. #endif
  7988. ssl->buffers.outputBuffer.length += sendSz;
  7989. ret = SendBuffered(ssl);
  7990. if (ret != 0 && ret != WANT_WRITE)
  7991. return ret;
  7992. }
  7993. /* In DTLS we must wait for the ack before setting up the new keys */
  7994. if (!ssl->options.dtls) {
  7995. /* Future traffic uses new encryption keys. */
  7996. if ((ret = DeriveTls13Keys(
  7997. ssl, update_traffic_key, ENCRYPT_SIDE_ONLY, 1))
  7998. != 0)
  7999. return ret;
  8000. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  8001. return ret;
  8002. }
  8003. WOLFSSL_LEAVE("SendTls13KeyUpdate", ret);
  8004. WOLFSSL_END(WC_FUNC_KEY_UPDATE_SEND);
  8005. return ret;
  8006. }
  8007. /* handle processing TLS v1.3 key_update (24) */
  8008. /* Parse and handle a TLS v1.3 KeyUpdate message.
  8009. *
  8010. * ssl The SSL/TLS object.
  8011. * input The message buffer.
  8012. * inOutIdx On entry, the index into the message buffer of Finished.
  8013. * On exit, the index of byte after the Finished message and padding.
  8014. * totalSz The length of the current handshake message.
  8015. * returns 0 on success and otherwise failure.
  8016. */
  8017. static int DoTls13KeyUpdate(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  8018. word32 totalSz)
  8019. {
  8020. int ret;
  8021. word32 i = *inOutIdx;
  8022. WOLFSSL_START(WC_FUNC_KEY_UPDATE_DO);
  8023. WOLFSSL_ENTER("DoTls13KeyUpdate");
  8024. /* check against totalSz */
  8025. if (OPAQUE8_LEN != totalSz)
  8026. return BUFFER_E;
  8027. switch (input[i]) {
  8028. case update_not_requested:
  8029. /* This message in response to any outstanding request. */
  8030. ssl->keys.keyUpdateRespond = 0;
  8031. ssl->keys.updateResponseReq = 0;
  8032. break;
  8033. case update_requested:
  8034. /* New key update requiring a response. */
  8035. ssl->keys.keyUpdateRespond = 1;
  8036. break;
  8037. default:
  8038. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  8039. return INVALID_PARAMETER;
  8040. }
  8041. /* Move index to byte after message. */
  8042. *inOutIdx += totalSz;
  8043. /* Always encrypted. */
  8044. *inOutIdx += ssl->keys.padSz;
  8045. /* Future traffic uses new decryption keys. */
  8046. if ((ret = DeriveTls13Keys(ssl, update_traffic_key, DECRYPT_SIDE_ONLY, 1))
  8047. != 0) {
  8048. return ret;
  8049. }
  8050. if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
  8051. return ret;
  8052. #ifdef WOLFSSL_DTLS13
  8053. if (ssl->options.dtls) {
  8054. w64Increment(&ssl->dtls13PeerEpoch);
  8055. ret = Dtls13NewEpoch(ssl, ssl->dtls13PeerEpoch, DECRYPT_SIDE_ONLY);
  8056. if (ret != 0)
  8057. return ret;
  8058. ret = Dtls13SetEpochKeys(ssl, ssl->dtls13PeerEpoch, DECRYPT_SIDE_ONLY);
  8059. if (ret != 0)
  8060. return ret;
  8061. }
  8062. #endif /* WOLFSSL_DTLS13 */
  8063. if (ssl->keys.keyUpdateRespond) {
  8064. #ifdef WOLFSSL_DTLS13
  8065. /* we already sent a keyUpdate (either in response to a previous
  8066. KeyUpdate or initiated by the application) and we are waiting for the
  8067. ack. We can't send a new KeyUpdate right away but to honor the RFC we
  8068. should send another KeyUpdate after the one in-flight is acked. We
  8069. don't do that as it looks redundant, it will make the code more
  8070. complex and I don't see a good use case for that. */
  8071. if (ssl->options.dtls && ssl->dtls13WaitKeyUpdateAck) {
  8072. ssl->keys.keyUpdateRespond = 0;
  8073. return 0;
  8074. }
  8075. #endif /* WOLFSSL_DTLS13 */
  8076. return SendTls13KeyUpdate(ssl);
  8077. }
  8078. WOLFSSL_LEAVE("DoTls13KeyUpdate", ret);
  8079. WOLFSSL_END(WC_FUNC_KEY_UPDATE_DO);
  8080. return 0;
  8081. }
  8082. #ifdef WOLFSSL_EARLY_DATA
  8083. #ifndef NO_WOLFSSL_CLIENT
  8084. /* Send the TLS v1.3 EndOfEarlyData message to indicate that there will be no
  8085. * more early application data.
  8086. * The encryption key now changes to the pre-calculated handshake key.
  8087. *
  8088. * ssl The SSL/TLS object.
  8089. * returns 0 on success and otherwise failure.
  8090. */
  8091. static int SendTls13EndOfEarlyData(WOLFSSL* ssl)
  8092. {
  8093. byte* output;
  8094. int ret;
  8095. int sendSz;
  8096. word32 length;
  8097. word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  8098. WOLFSSL_START(WC_FUNC_END_OF_EARLY_DATA_SEND);
  8099. WOLFSSL_ENTER("SendTls13EndOfEarlyData");
  8100. length = 0;
  8101. sendSz = idx + length + MAX_MSG_EXTRA;
  8102. ssl->options.buildingMsg = 1;
  8103. /* Check buffers are big enough and grow if needed. */
  8104. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  8105. return ret;
  8106. /* Get position in output buffer to write new message to. */
  8107. output = ssl->buffers.outputBuffer.buffer +
  8108. ssl->buffers.outputBuffer.length;
  8109. /* Put the record and handshake headers on. */
  8110. AddTls13Headers(output, length, end_of_early_data, ssl);
  8111. /* This message is always encrypted. */
  8112. sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
  8113. idx - RECORD_HEADER_SZ, handshake, 1, 0, 0);
  8114. if (sendSz < 0)
  8115. return sendSz;
  8116. ssl->buffers.outputBuffer.length += sendSz;
  8117. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  8118. return ret;
  8119. ssl->options.buildingMsg = 0;
  8120. if (!ssl->options.groupMessages)
  8121. ret = SendBuffered(ssl);
  8122. WOLFSSL_LEAVE("SendTls13EndOfEarlyData", ret);
  8123. WOLFSSL_END(WC_FUNC_END_OF_EARLY_DATA_SEND);
  8124. return ret;
  8125. }
  8126. #endif /* !NO_WOLFSSL_CLIENT */
  8127. #ifndef NO_WOLFSSL_SERVER
  8128. /* handle processing of TLS 1.3 end_of_early_data (5) */
  8129. /* Parse the TLS v1.3 EndOfEarlyData message that indicates that there will be
  8130. * no more early application data.
  8131. * The decryption key now changes to the pre-calculated handshake key.
  8132. *
  8133. * ssl The SSL/TLS object.
  8134. * returns 0 on success and otherwise failure.
  8135. */
  8136. static int DoTls13EndOfEarlyData(WOLFSSL* ssl, const byte* input,
  8137. word32* inOutIdx, word32 size)
  8138. {
  8139. int ret;
  8140. word32 begin = *inOutIdx;
  8141. (void)input;
  8142. WOLFSSL_START(WC_FUNC_END_OF_EARLY_DATA_DO);
  8143. WOLFSSL_ENTER("DoTls13EndOfEarlyData");
  8144. if ((*inOutIdx - begin) != size)
  8145. return BUFFER_ERROR;
  8146. if (ssl->earlyData == no_early_data) {
  8147. WOLFSSL_MSG("EndOfEarlyData received unexpectedly");
  8148. SendAlert(ssl, alert_fatal, unexpected_message);
  8149. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8150. return OUT_OF_ORDER_E;
  8151. }
  8152. ssl->earlyData = done_early_data;
  8153. /* Always encrypted. */
  8154. *inOutIdx += ssl->keys.padSz;
  8155. ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY);
  8156. WOLFSSL_LEAVE("DoTls13EndOfEarlyData", ret);
  8157. WOLFSSL_END(WC_FUNC_END_OF_EARLY_DATA_DO);
  8158. return ret;
  8159. }
  8160. #endif /* !NO_WOLFSSL_SERVER */
  8161. #endif /* WOLFSSL_EARLY_DATA */
  8162. #if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \
  8163. (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
  8164. int SessionTicketNoncePopulate(WOLFSSL_SESSION *session, const byte *nonce,
  8165. byte len)
  8166. {
  8167. if (session->ticketNonce.data
  8168. != session->ticketNonce.dataStatic) {
  8169. XFREE(session->ticketNonce.data, heap,
  8170. DYNAMIC_TYPE_SESSION_TICK);
  8171. session->ticketNonce.data = session->ticketNonce.dataStatic;
  8172. session->ticketNonce.len = 0;
  8173. }
  8174. if (len > MAX_TICKET_NONCE_STATIC_SZ) {
  8175. WOLFSSL_MSG("Using dynamic nonce buffer");
  8176. session->ticketNonce.data = (byte*)XMALLOC(len,
  8177. session->heap, DYNAMIC_TYPE_SESSION_TICK);
  8178. if (session->ticketNonce.data == NULL)
  8179. return MEMORY_ERROR;
  8180. }
  8181. XMEMCPY(session->ticketNonce.data, nonce, len);
  8182. session->ticketNonce.len = len;
  8183. return 0;
  8184. }
  8185. #endif
  8186. #ifndef NO_WOLFSSL_CLIENT
  8187. /* Handle a New Session Ticket handshake message.
  8188. * Message contains the information required to perform resumption.
  8189. *
  8190. * ssl The SSL/TLS object.
  8191. * input The message buffer.
  8192. * inOutIdx On entry, the index into the message buffer of Finished.
  8193. * On exit, the index of byte after the Finished message and padding.
  8194. * size The length of the current handshake message.
  8195. * returns 0 on success, otherwise failure.
  8196. */
  8197. static int DoTls13NewSessionTicket(WOLFSSL* ssl, const byte* input,
  8198. word32* inOutIdx, word32 size)
  8199. {
  8200. #ifdef HAVE_SESSION_TICKET
  8201. int ret;
  8202. word32 begin = *inOutIdx;
  8203. word32 lifetime;
  8204. word32 ageAdd;
  8205. word16 length;
  8206. #ifdef WOLFSSL_32BIT_MILLI_TIME
  8207. word32 now;
  8208. #else
  8209. sword64 now;
  8210. #endif
  8211. const byte* nonce;
  8212. byte nonceLength;
  8213. WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_DO);
  8214. WOLFSSL_ENTER("DoTls13NewSessionTicket");
  8215. /* Lifetime hint. */
  8216. if ((*inOutIdx - begin) + SESSION_HINT_SZ > size)
  8217. return BUFFER_ERROR;
  8218. ato32(input + *inOutIdx, &lifetime);
  8219. *inOutIdx += SESSION_HINT_SZ;
  8220. if (lifetime > MAX_LIFETIME) {
  8221. WOLFSSL_ERROR_VERBOSE(SERVER_HINT_ERROR);
  8222. return SERVER_HINT_ERROR;
  8223. }
  8224. /* Age add. */
  8225. if ((*inOutIdx - begin) + SESSION_ADD_SZ > size)
  8226. return BUFFER_ERROR;
  8227. ato32(input + *inOutIdx, &ageAdd);
  8228. *inOutIdx += SESSION_ADD_SZ;
  8229. /* Ticket nonce. */
  8230. if ((*inOutIdx - begin) + 1 > size)
  8231. return BUFFER_ERROR;
  8232. nonceLength = input[*inOutIdx];
  8233. #if !defined(WOLFSSL_TICKET_NONCE_MALLOC) && \
  8234. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3))
  8235. if (nonceLength > MAX_TICKET_NONCE_STATIC_SZ) {
  8236. WOLFSSL_MSG("Nonce length not supported");
  8237. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  8238. return INVALID_PARAMETER;
  8239. }
  8240. #endif /* WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3) */
  8241. *inOutIdx += 1;
  8242. if ((*inOutIdx - begin) + nonceLength > size)
  8243. return BUFFER_ERROR;
  8244. nonce = input + *inOutIdx;
  8245. *inOutIdx += nonceLength;
  8246. /* Ticket length. */
  8247. if ((*inOutIdx - begin) + LENGTH_SZ > size)
  8248. return BUFFER_ERROR;
  8249. ato16(input + *inOutIdx, &length);
  8250. *inOutIdx += LENGTH_SZ;
  8251. if ((*inOutIdx - begin) + length > size)
  8252. return BUFFER_ERROR;
  8253. if ((ret = SetTicket(ssl, input + *inOutIdx, length)) != 0)
  8254. return ret;
  8255. *inOutIdx += length;
  8256. now = TimeNowInMilliseconds();
  8257. if (now == 0)
  8258. return GETTIME_ERROR;
  8259. /* Copy in ticket data (server identity). */
  8260. ssl->timeout = lifetime;
  8261. ssl->session->timeout = lifetime;
  8262. ssl->session->cipherSuite0 = ssl->options.cipherSuite0;
  8263. ssl->session->cipherSuite = ssl->options.cipherSuite;
  8264. ssl->session->ticketSeen = now;
  8265. ssl->session->ticketAdd = ageAdd;
  8266. #ifdef WOLFSSL_EARLY_DATA
  8267. ssl->session->maxEarlyDataSz = ssl->options.maxEarlyDataSz;
  8268. #endif
  8269. #if defined(WOLFSSL_TICKET_NONCE_MALLOC) && \
  8270. (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
  8271. ret = SessionTicketNoncePopulate(ssl->session, nonce, nonceLength);
  8272. if (ret != 0)
  8273. return ret;
  8274. #else
  8275. ssl->session->ticketNonce.len = nonceLength;
  8276. if (nonceLength > MAX_TICKET_NONCE_STATIC_SZ) {
  8277. ret = BUFFER_ERROR;
  8278. return ret;
  8279. }
  8280. if (nonceLength > 0)
  8281. XMEMCPY(ssl->session->ticketNonce.data, nonce, nonceLength);
  8282. #endif /* defined(WOLFSSL_TICKET_NONCE_MALLOC) && FIPS_VERSION_GE(5,3) */
  8283. ssl->session->namedGroup = ssl->namedGroup;
  8284. if ((*inOutIdx - begin) + EXTS_SZ > size)
  8285. return BUFFER_ERROR;
  8286. ato16(input + *inOutIdx, &length);
  8287. *inOutIdx += EXTS_SZ;
  8288. if ((*inOutIdx - begin) + length != size)
  8289. return BUFFER_ERROR;
  8290. #ifdef WOLFSSL_EARLY_DATA
  8291. ret = TLSX_Parse(ssl, (byte *)input + (*inOutIdx), length, session_ticket,
  8292. NULL);
  8293. if (ret != 0)
  8294. return ret;
  8295. #endif
  8296. *inOutIdx += length;
  8297. #ifndef NO_SESSION_CACHE
  8298. AddSession(ssl);
  8299. #endif
  8300. /* Always encrypted. */
  8301. *inOutIdx += ssl->keys.padSz;
  8302. ssl->expect_session_ticket = 0;
  8303. #else
  8304. (void)ssl;
  8305. (void)input;
  8306. WOLFSSL_ENTER("DoTls13NewSessionTicket");
  8307. *inOutIdx += size + ssl->keys.padSz;
  8308. #endif /* HAVE_SESSION_TICKET */
  8309. WOLFSSL_LEAVE("DoTls13NewSessionTicket", 0);
  8310. WOLFSSL_END(WC_FUNC_NEW_SESSION_TICKET_DO);
  8311. return 0;
  8312. }
  8313. #endif /* NO_WOLFSSL_CLIENT */
  8314. #ifndef NO_WOLFSSL_SERVER
  8315. #ifdef HAVE_SESSION_TICKET
  8316. #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
  8317. /* Offset of the MAC size in the finished message. */
  8318. #define FINISHED_MSG_SIZE_OFFSET 3
  8319. /* Calculate the resumption secret which includes the unseen client finished
  8320. * message.
  8321. *
  8322. * ssl The SSL/TLS object.
  8323. * returns 0 on success, otherwise failure.
  8324. */
  8325. static int ExpectedResumptionSecret(WOLFSSL* ssl)
  8326. {
  8327. int ret;
  8328. word32 finishedSz = 0;
  8329. byte mac[WC_MAX_DIGEST_SIZE];
  8330. Digest digest;
  8331. static byte header[] = { 0x14, 0x00, 0x00, 0x00 };
  8332. /* Copy the running hash so we can restore it after. */
  8333. switch (ssl->specs.mac_algorithm) {
  8334. #ifndef NO_SHA256
  8335. case sha256_mac:
  8336. ret = wc_Sha256Copy(&ssl->hsHashes->hashSha256, &digest.sha256);
  8337. if (ret != 0)
  8338. return ret;
  8339. break;
  8340. #endif
  8341. #ifdef WOLFSSL_SHA384
  8342. case sha384_mac:
  8343. ret = wc_Sha384Copy(&ssl->hsHashes->hashSha384, &digest.sha384);
  8344. if (ret != 0)
  8345. return ret;
  8346. break;
  8347. #endif
  8348. #ifdef WOLFSSL_TLS13_SHA512
  8349. case sha512_mac:
  8350. ret = wc_Sha512Copy(&ssl->hsHashes->hashSha512, &digest.sha512);
  8351. if (ret != 0)
  8352. return ret;
  8353. break;
  8354. #endif
  8355. }
  8356. /* Generate the Client's Finished message and hash it. */
  8357. ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret, mac,
  8358. &finishedSz);
  8359. if (ret != 0)
  8360. return ret;
  8361. header[FINISHED_MSG_SIZE_OFFSET] = finishedSz;
  8362. #ifdef WOLFSSL_EARLY_DATA
  8363. if (ssl->earlyData != no_early_data) {
  8364. static byte endOfEarlyData[] = { 0x05, 0x00, 0x00, 0x00 };
  8365. ret = HashRaw(ssl, endOfEarlyData, sizeof(endOfEarlyData));
  8366. if (ret != 0)
  8367. return ret;
  8368. }
  8369. #endif
  8370. if ((ret = HashRaw(ssl, header, sizeof(header))) != 0)
  8371. return ret;
  8372. if ((ret = HashRaw(ssl, mac, finishedSz)) != 0)
  8373. return ret;
  8374. if ((ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret)) != 0)
  8375. return ret;
  8376. /* Restore the hash inline with currently seen messages. */
  8377. switch (ssl->specs.mac_algorithm) {
  8378. #ifndef NO_SHA256
  8379. case sha256_mac:
  8380. wc_Sha256Free(&ssl->hsHashes->hashSha256);
  8381. ret = wc_Sha256Copy(&digest.sha256, &ssl->hsHashes->hashSha256);
  8382. wc_Sha256Free(&digest.sha256);
  8383. if (ret != 0)
  8384. return ret;
  8385. break;
  8386. #endif
  8387. #ifdef WOLFSSL_SHA384
  8388. case sha384_mac:
  8389. wc_Sha384Free(&ssl->hsHashes->hashSha384);
  8390. ret = wc_Sha384Copy(&digest.sha384, &ssl->hsHashes->hashSha384);
  8391. wc_Sha384Free(&digest.sha384);
  8392. if (ret != 0)
  8393. return ret;
  8394. break;
  8395. #endif
  8396. #ifdef WOLFSSL_TLS13_SHA512
  8397. case sha512_mac:
  8398. wc_Sha512Free(&ssl->hsHashes->hashSha512);
  8399. ret = wc_Sha512Copy(&digest.sha512, &ssl->hsHashes->hashSha512);
  8400. wc_Sha512Free(&digest.sha512);
  8401. if (ret != 0)
  8402. return ret;
  8403. break;
  8404. #endif
  8405. }
  8406. return ret;
  8407. }
  8408. #endif
  8409. /* Send New Session Ticket handshake message.
  8410. * Message contains the information required to perform resumption.
  8411. *
  8412. * ssl The SSL/TLS object.
  8413. * returns 0 on success, otherwise failure.
  8414. */
  8415. static int SendTls13NewSessionTicket(WOLFSSL* ssl)
  8416. {
  8417. byte* output;
  8418. int ret;
  8419. int sendSz;
  8420. word16 extSz;
  8421. word32 length;
  8422. word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  8423. WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_SEND);
  8424. WOLFSSL_ENTER("SendTls13NewSessionTicket");
  8425. #ifdef WOLFSSL_DTLS13
  8426. if (ssl->options.dtls)
  8427. idx = Dtls13GetRlHeaderLength(ssl, 1) + DTLS_HANDSHAKE_HEADER_SZ;
  8428. #endif /* WOLFSSL_DTLS13 */
  8429. #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
  8430. if (!ssl->msgsReceived.got_finished) {
  8431. if ((ret = ExpectedResumptionSecret(ssl)) != 0)
  8432. return ret;
  8433. }
  8434. #endif
  8435. /* Start ticket nonce at 0 and go up to 255. */
  8436. if (ssl->session->ticketNonce.len == 0) {
  8437. ssl->session->ticketNonce.len = DEF_TICKET_NONCE_SZ;
  8438. ssl->session->ticketNonce.data[0] = 0;
  8439. }
  8440. else
  8441. #ifdef WOLFSSL_ASYNC_CRYPT
  8442. if (ssl->error != WC_PENDING_E)
  8443. #endif
  8444. {
  8445. ssl->session->ticketNonce.data[0]++;
  8446. }
  8447. if (!ssl->options.noTicketTls13) {
  8448. if ((ret = CreateTicket(ssl)) != 0)
  8449. return ret;
  8450. }
  8451. #ifdef WOLFSSL_EARLY_DATA
  8452. ssl->session->maxEarlyDataSz = ssl->options.maxEarlyDataSz;
  8453. if (ssl->session->maxEarlyDataSz > 0)
  8454. TLSX_EarlyData_Use(ssl, ssl->session->maxEarlyDataSz, 1);
  8455. extSz = 0;
  8456. ret = TLSX_GetResponseSize(ssl, session_ticket, &extSz);
  8457. if (ret != 0)
  8458. return ret;
  8459. #else
  8460. extSz = EXTS_SZ;
  8461. #endif
  8462. /* Lifetime | Age Add | Ticket | Extensions */
  8463. length = SESSION_HINT_SZ + SESSION_ADD_SZ + LENGTH_SZ +
  8464. ssl->session->ticketLen + extSz;
  8465. /* Nonce */
  8466. length += TICKET_NONCE_LEN_SZ + DEF_TICKET_NONCE_SZ;
  8467. sendSz = idx + length + MAX_MSG_EXTRA;
  8468. /* Check buffers are big enough and grow if needed. */
  8469. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  8470. return ret;
  8471. /* Get position in output buffer to write new message to. */
  8472. output = ssl->buffers.outputBuffer.buffer +
  8473. ssl->buffers.outputBuffer.length;
  8474. /* Put the record and handshake headers on. */
  8475. AddTls13Headers(output, length, session_ticket, ssl);
  8476. /* Lifetime hint */
  8477. c32toa(ssl->ctx->ticketHint, output + idx);
  8478. idx += SESSION_HINT_SZ;
  8479. /* Age add - obfuscator */
  8480. c32toa(ssl->session->ticketAdd, output + idx);
  8481. idx += SESSION_ADD_SZ;
  8482. output[idx++] = ssl->session->ticketNonce.len;
  8483. output[idx++] = ssl->session->ticketNonce.data[0];
  8484. /* length */
  8485. c16toa(ssl->session->ticketLen, output + idx);
  8486. idx += LENGTH_SZ;
  8487. /* ticket */
  8488. XMEMCPY(output + idx, ssl->session->ticket, ssl->session->ticketLen);
  8489. idx += ssl->session->ticketLen;
  8490. #ifdef WOLFSSL_EARLY_DATA
  8491. extSz = 0;
  8492. ret = TLSX_WriteResponse(ssl, output + idx, session_ticket, &extSz);
  8493. if (ret != 0)
  8494. return ret;
  8495. idx += extSz;
  8496. #else
  8497. /* No extension support - empty extensions. */
  8498. c16toa(0, output + idx);
  8499. idx += EXTS_SZ;
  8500. #endif
  8501. ssl->options.haveSessionId = 1;
  8502. #ifndef NO_SESSION_CACHE
  8503. AddSession(ssl);
  8504. #endif
  8505. #ifdef WOLFSSL_DTLS13
  8506. if (ssl->options.dtls)
  8507. return Dtls13HandshakeSend(ssl, output, sendSz, idx, session_ticket, 0);
  8508. #endif /* WOLFSSL_DTLS13 */
  8509. /* This message is always encrypted. */
  8510. sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
  8511. idx - RECORD_HEADER_SZ, handshake, 0, 0, 0);
  8512. if (sendSz < 0)
  8513. return sendSz;
  8514. ssl->buffers.outputBuffer.length += sendSz;
  8515. /* Always send as this is either directly after server's Finished or only
  8516. * message after client's Finished.
  8517. */
  8518. ret = SendBuffered(ssl);
  8519. WOLFSSL_LEAVE("SendTls13NewSessionTicket", 0);
  8520. WOLFSSL_END(WC_FUNC_NEW_SESSION_TICKET_SEND);
  8521. return ret;
  8522. }
  8523. #endif /* HAVE_SESSION_TICKET */
  8524. #endif /* NO_WOLFSSL_SERVER */
  8525. /* Make sure no duplicates, no fast forward, or other problems
  8526. *
  8527. * ssl The SSL/TLS object.
  8528. * type Type of handshake message received.
  8529. * returns 0 on success, otherwise failure.
  8530. */
  8531. static int SanityCheckTls13MsgReceived(WOLFSSL* ssl, byte type)
  8532. {
  8533. /* verify not a duplicate, mark received, check state */
  8534. switch (type) {
  8535. #ifndef NO_WOLFSSL_SERVER
  8536. case client_hello:
  8537. #ifndef NO_WOLFSSL_CLIENT
  8538. /* Only valid when received on SERVER side. */
  8539. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  8540. WOLFSSL_MSG("ClientHello received by client");
  8541. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  8542. return SIDE_ERROR;
  8543. }
  8544. #endif
  8545. /* Check state. */
  8546. if (ssl->options.clientState >= CLIENT_HELLO_COMPLETE) {
  8547. WOLFSSL_MSG("ClientHello received out of order");
  8548. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8549. return OUT_OF_ORDER_E;
  8550. }
  8551. /* Check previously seen. */
  8552. /* Initial and after HelloRetryRequest - no more than 2. */
  8553. if (ssl->msgsReceived.got_client_hello == 2) {
  8554. WOLFSSL_MSG("Too many ClientHello received");
  8555. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8556. return DUPLICATE_MSG_E;
  8557. }
  8558. /* Second only after HelloRetryRequest seen. */
  8559. if (ssl->msgsReceived.got_client_hello == 1 &&
  8560. ssl->options.serverState !=
  8561. SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  8562. WOLFSSL_MSG("Duplicate ClientHello received");
  8563. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8564. return DUPLICATE_MSG_E;
  8565. }
  8566. ssl->msgsReceived.got_client_hello++;
  8567. break;
  8568. #endif
  8569. #ifndef NO_WOLFSSL_CLIENT
  8570. case server_hello:
  8571. #ifndef NO_WOLFSSL_SERVER
  8572. /* Only valid when received on CLIENT side. */
  8573. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8574. WOLFSSL_MSG("ServerHello received by server");
  8575. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  8576. return SIDE_ERROR;
  8577. }
  8578. #endif
  8579. /* Check state. */
  8580. if (ssl->options.serverState >= SERVER_HELLO_COMPLETE) {
  8581. WOLFSSL_MSG("ServerHello received out of order");
  8582. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8583. return OUT_OF_ORDER_E;
  8584. }
  8585. /* Check previously seen. */
  8586. /* Only once after ClientHello.
  8587. * HelloRetryRequest has ServerHello type but count fixed up later
  8588. * - see DoTls13ServerHello().
  8589. */
  8590. if (ssl->msgsReceived.got_server_hello) {
  8591. WOLFSSL_MSG("Duplicate ServerHello received");
  8592. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8593. return DUPLICATE_MSG_E;
  8594. }
  8595. ssl->msgsReceived.got_server_hello = 1;
  8596. break;
  8597. #endif
  8598. #ifndef NO_WOLFSSL_CLIENT
  8599. case session_ticket:
  8600. #ifndef NO_WOLFSSL_SERVER
  8601. /* Only valid when received on CLIENT side. */
  8602. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8603. WOLFSSL_MSG("NewSessionTicket received by server");
  8604. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  8605. return SIDE_ERROR;
  8606. }
  8607. #endif
  8608. /* Check state. */
  8609. #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
  8610. /* Only allowed after server's Finished message. */
  8611. if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
  8612. WOLFSSL_MSG("NewSessionTicket received out of order");
  8613. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8614. return OUT_OF_ORDER_E;
  8615. }
  8616. #else
  8617. /* Only allowed after client's Finished message. */
  8618. if (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
  8619. WOLFSSL_MSG("NewSessionTicket received out of order");
  8620. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8621. return OUT_OF_ORDER_E;
  8622. }
  8623. #endif
  8624. /* Many SessionTickets can be sent. */
  8625. ssl->msgsReceived.got_session_ticket = 1;
  8626. break;
  8627. #endif
  8628. #ifndef NO_WOLFSSL_SERVER
  8629. #ifdef WOLFSSL_EARLY_DATA
  8630. case end_of_early_data:
  8631. #ifndef NO_WOLFSSL_CLIENT
  8632. /* Only valid when received on SERVER side. */
  8633. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  8634. WOLFSSL_MSG("EndOfEarlyData received by client");
  8635. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  8636. return SIDE_ERROR;
  8637. }
  8638. #endif
  8639. /* Check state. */
  8640. /* Only after server's Finished and before client's Finished. */
  8641. if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
  8642. WOLFSSL_MSG("EndOfEarlyData received out of order");
  8643. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8644. return OUT_OF_ORDER_E;
  8645. }
  8646. if (ssl->options.clientState >= CLIENT_FINISHED_COMPLETE) {
  8647. WOLFSSL_MSG("EndOfEarlyData received out of order");
  8648. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8649. return OUT_OF_ORDER_E;
  8650. }
  8651. /* Check previously seen. */
  8652. if (ssl->msgsReceived.got_end_of_early_data) {
  8653. WOLFSSL_MSG("Too many EndOfEarlyData received");
  8654. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8655. return DUPLICATE_MSG_E;
  8656. }
  8657. ssl->msgsReceived.got_end_of_early_data = 1;
  8658. break;
  8659. #endif
  8660. #endif
  8661. #ifndef NO_WOLFSSL_CLIENT
  8662. case encrypted_extensions:
  8663. #ifndef NO_WOLFSSL_SERVER
  8664. /* Only valid when received on CLIENT side. */
  8665. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8666. WOLFSSL_MSG("EncryptedExtensions received by server");
  8667. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  8668. return SIDE_ERROR;
  8669. }
  8670. #endif
  8671. /* Check state. */
  8672. /* Must be received directly after ServerHello.
  8673. * DoTls13EncryptedExtensions() changes state to:
  8674. * SERVER_ENCRYPTED_EXTENSIONS_COMPLETE.
  8675. */
  8676. if (ssl->options.serverState != SERVER_HELLO_COMPLETE) {
  8677. WOLFSSL_MSG("EncryptedExtensions received out of order");
  8678. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8679. return OUT_OF_ORDER_E;
  8680. }
  8681. /* Check previously seen. */
  8682. if (ssl->msgsReceived.got_encrypted_extensions) {
  8683. WOLFSSL_MSG("Duplicate EncryptedExtensions received");
  8684. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8685. return DUPLICATE_MSG_E;
  8686. }
  8687. ssl->msgsReceived.got_encrypted_extensions = 1;
  8688. break;
  8689. #endif
  8690. case certificate:
  8691. /* Valid on both sides. */
  8692. #ifndef NO_WOLFSSL_CLIENT
  8693. /* Check state. */
  8694. /* On client, seen after EncryptedExtension and CertificateRequest
  8695. * (if sent) and before CertificateVerify and Finished.
  8696. * DoTls13Certificate() sets serverState to SERVER_CERT_COMPLETE.
  8697. */
  8698. if (ssl->options.side == WOLFSSL_CLIENT_END &&
  8699. ssl->options.serverState !=
  8700. SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
  8701. WOLFSSL_MSG("Certificate received out of order - Client");
  8702. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8703. return OUT_OF_ORDER_E;
  8704. }
  8705. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  8706. /* Server's authenticating with PSK must not send this. */
  8707. if (ssl->options.side == WOLFSSL_CLIENT_END &&
  8708. ssl->options.serverState == SERVER_CERT_COMPLETE &&
  8709. ssl->options.pskNegotiated) {
  8710. WOLFSSL_MSG("Certificate received while using PSK");
  8711. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8712. return SANITY_MSG_E;
  8713. }
  8714. #endif
  8715. #endif
  8716. #ifndef NO_WOLFSSL_SERVER
  8717. /* Check state. */
  8718. /* On Server, valid after ClientHello received and ServerFinished
  8719. * sent. */
  8720. if (ssl->options.side == WOLFSSL_SERVER_END &&
  8721. ssl->options.clientState != CLIENT_HELLO_COMPLETE &&
  8722. ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
  8723. WOLFSSL_MSG("Certificate received out of order - Server");
  8724. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8725. return OUT_OF_ORDER_E;
  8726. }
  8727. #endif
  8728. /* Check previously seen. */
  8729. if (ssl->msgsReceived.got_certificate) {
  8730. WOLFSSL_MSG("Duplicate Certificate received");
  8731. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8732. return DUPLICATE_MSG_E;
  8733. }
  8734. ssl->msgsReceived.got_certificate = 1;
  8735. break;
  8736. #ifndef NO_WOLFSSL_CLIENT
  8737. case certificate_request:
  8738. #ifndef NO_WOLFSSL_SERVER
  8739. /* Only valid when received on CLIENT side. */
  8740. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8741. WOLFSSL_MSG("CertificateRequest received by server");
  8742. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  8743. return SIDE_ERROR;
  8744. }
  8745. #endif
  8746. /* Check state. */
  8747. #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
  8748. /* Only valid when sent after EncryptedExtensions and before
  8749. * Certificate. */
  8750. if (ssl->options.serverState !=
  8751. SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
  8752. WOLFSSL_MSG("CertificateRequest received out of order");
  8753. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8754. return OUT_OF_ORDER_E;
  8755. }
  8756. #else
  8757. /* Valid when sent after EncryptedExtensions and before Certificate
  8758. * and after both client and server have sent Finished (Post
  8759. * Handshake Authentication). */
  8760. if (ssl->options.serverState !=
  8761. SERVER_ENCRYPTED_EXTENSIONS_COMPLETE &&
  8762. (ssl->options.serverState < SERVER_FINISHED_COMPLETE ||
  8763. ssl->options.clientState != CLIENT_FINISHED_COMPLETE)) {
  8764. WOLFSSL_MSG("CertificateRequest received out of order");
  8765. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8766. return OUT_OF_ORDER_E;
  8767. }
  8768. #endif
  8769. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  8770. /* Server's authenticating with PSK must not send this. */
  8771. if (ssl->options.pskNegotiated) {
  8772. WOLFSSL_MSG("CertificateRequest received while using PSK");
  8773. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8774. return SANITY_MSG_E;
  8775. }
  8776. #endif
  8777. /* Check previously seen. */
  8778. #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
  8779. /* Only once during handshake. */
  8780. if (ssl->msgsReceived.got_certificate_request) {
  8781. WOLFSSL_MSG("Duplicate CertificateRequest received");
  8782. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8783. return DUPLICATE_MSG_E;
  8784. }
  8785. #else
  8786. /* Only once during handshake. */
  8787. if (ssl->msgsReceived.got_certificate_request &&
  8788. ssl->options.clientState != CLIENT_FINISHED_COMPLETE) {
  8789. WOLFSSL_MSG("Duplicate CertificateRequest received");
  8790. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8791. return DUPLICATE_MSG_E;
  8792. }
  8793. #endif
  8794. ssl->msgsReceived.got_certificate_request = 1;
  8795. break;
  8796. #endif
  8797. case certificate_verify:
  8798. /* Valid on both sides. */
  8799. #ifndef NO_WOLFSSL_CLIENT
  8800. /* Check state on client.
  8801. * Valid only directly after a Certificate message. */
  8802. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  8803. if (ssl->options.serverState != SERVER_CERT_COMPLETE) {
  8804. WOLFSSL_MSG("No Cert before CertVerify");
  8805. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8806. return OUT_OF_ORDER_E;
  8807. }
  8808. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  8809. /* Server's authenticating with PSK must not send this. */
  8810. if (ssl->options.pskNegotiated) {
  8811. WOLFSSL_MSG("CertificateVerify received while using PSK");
  8812. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8813. return SANITY_MSG_E;
  8814. }
  8815. #endif
  8816. }
  8817. #endif
  8818. #ifndef NO_WOLFSSL_SERVER
  8819. /* Check state on server. */
  8820. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8821. /* Server must have sent Finished message. */
  8822. if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
  8823. WOLFSSL_MSG("CertificateVerify received out of order");
  8824. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8825. return OUT_OF_ORDER_E;
  8826. }
  8827. /* Valid only directly after a Certificate message. */
  8828. if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
  8829. WOLFSSL_MSG("CertificateVerify before ClientHello done");
  8830. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8831. return OUT_OF_ORDER_E;
  8832. }
  8833. if (!ssl->msgsReceived.got_certificate) {
  8834. WOLFSSL_MSG("No Cert before CertificateVerify");
  8835. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8836. return OUT_OF_ORDER_E;
  8837. }
  8838. }
  8839. #endif
  8840. /* Check previously seen. */
  8841. if (ssl->msgsReceived.got_certificate_verify) {
  8842. WOLFSSL_MSG("Duplicate CertificateVerify received");
  8843. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8844. return DUPLICATE_MSG_E;
  8845. }
  8846. ssl->msgsReceived.got_certificate_verify = 1;
  8847. break;
  8848. case finished:
  8849. /* Valid on both sides. */
  8850. #ifndef NO_WOLFSSL_CLIENT
  8851. /* Check state on client. */
  8852. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  8853. /* After sending ClientHello */
  8854. if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
  8855. WOLFSSL_MSG("Finished received out of order - clientState");
  8856. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8857. return OUT_OF_ORDER_E;
  8858. }
  8859. /* Must have seen certificate and verify from server except when
  8860. * using PSK. */
  8861. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  8862. if (ssl->options.pskNegotiated) {
  8863. if (ssl->options.serverState !=
  8864. SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
  8865. WOLFSSL_MSG("Finished received out of order - PSK");
  8866. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8867. return OUT_OF_ORDER_E;
  8868. }
  8869. }
  8870. else
  8871. #endif
  8872. if (ssl->options.serverState != SERVER_CERT_VERIFY_COMPLETE) {
  8873. WOLFSSL_MSG("Finished received out of order - serverState");
  8874. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8875. return OUT_OF_ORDER_E;
  8876. }
  8877. }
  8878. #endif
  8879. #ifndef NO_WOLFSSL_SERVER
  8880. /* Check state on server. */
  8881. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8882. if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
  8883. WOLFSSL_MSG("Finished received out of order - serverState");
  8884. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8885. return OUT_OF_ORDER_E;
  8886. }
  8887. if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
  8888. WOLFSSL_MSG("Finished received out of order - clientState");
  8889. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8890. return OUT_OF_ORDER_E;
  8891. }
  8892. #ifdef WOLFSSL_EARLY_DATA
  8893. if (ssl->earlyData == process_early_data &&
  8894. /* early data may be lost when using DTLS */
  8895. !ssl->options.dtls
  8896. /* QUIC does not use EndOfEarlyData records */
  8897. && !WOLFSSL_IS_QUIC(ssl)) {
  8898. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8899. return OUT_OF_ORDER_E;
  8900. }
  8901. #endif
  8902. }
  8903. #endif
  8904. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  8905. if (!ssl->options.pskNegotiated)
  8906. #endif
  8907. {
  8908. /* Must have received a Certificate message from client if
  8909. * verifying the peer. Empty certificate message indicates
  8910. * no certificate available.
  8911. */
  8912. if (ssl->options.verifyPeer &&
  8913. !ssl->msgsReceived.got_certificate) {
  8914. WOLFSSL_MSG("Finished received out of order - "
  8915. "missing Certificate message");
  8916. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8917. return OUT_OF_ORDER_E;
  8918. }
  8919. /* Mutual authentication on server requires a certificate from
  8920. * peer. Verify peer set on client side requires a certificate
  8921. * from peer as not doing PSK.
  8922. */
  8923. if ((ssl->options.mutualAuth ||
  8924. (ssl->options.side == WOLFSSL_CLIENT_END &&
  8925. ssl->options.verifyPeer)) && !ssl->options.havePeerCert) {
  8926. WOLFSSL_MSG("Finished received out of order - "
  8927. "no valid certificate");
  8928. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8929. return OUT_OF_ORDER_E;
  8930. }
  8931. /* Must have received a valid CertificateVerify if verifying
  8932. * peer and got a peer certificate.
  8933. */
  8934. if ((ssl->options.mutualAuth || ssl->options.verifyPeer) &&
  8935. ssl->options.havePeerCert && !ssl->options.havePeerVerify) {
  8936. WOLFSSL_MSG("Finished received out of order - "
  8937. "Certificate message but no CertificateVerify");
  8938. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8939. return OUT_OF_ORDER_E;
  8940. }
  8941. }
  8942. /* Check previously seen. */
  8943. if (ssl->msgsReceived.got_finished) {
  8944. WOLFSSL_MSG("Duplicate Finished received");
  8945. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8946. return DUPLICATE_MSG_E;
  8947. }
  8948. ssl->msgsReceived.got_finished = 1;
  8949. break;
  8950. case key_update:
  8951. /* Valid on both sides. */
  8952. /* Check state.
  8953. * Client and server must have received finished message from other
  8954. * side.
  8955. */
  8956. if (!ssl->msgsReceived.got_finished) {
  8957. WOLFSSL_MSG("No KeyUpdate before Finished");
  8958. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8959. return OUT_OF_ORDER_E;
  8960. }
  8961. /* Multiple KeyUpdates can be sent. */
  8962. break;
  8963. #if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12)
  8964. case hello_verify_request:
  8965. if (!ssl->options.dtls) {
  8966. WOLFSSL_MSG("HelloVerifyRequest when not in DTLS");
  8967. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8968. return OUT_OF_ORDER_E;
  8969. }
  8970. if (ssl->msgsReceived.got_hello_verify_request) {
  8971. WOLFSSL_MSG("Duplicate HelloVerifyRequest received");
  8972. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8973. return DUPLICATE_MSG_E;
  8974. }
  8975. ssl->msgsReceived.got_hello_verify_request = 1;
  8976. if (ssl->msgsReceived.got_hello_retry_request) {
  8977. WOLFSSL_MSG(
  8978. "Both HelloVerifyRequest and HelloRetryRequest received");
  8979. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8980. return DUPLICATE_MSG_E;
  8981. }
  8982. if (ssl->options.serverState >=
  8983. SERVER_HELLO_RETRY_REQUEST_COMPLETE ||
  8984. ssl->options.connectState != CLIENT_HELLO_SENT) {
  8985. WOLFSSL_MSG("HelloVerifyRequest received out of order");
  8986. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8987. return OUT_OF_ORDER_E;
  8988. }
  8989. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8990. WOLFSSL_MSG("HelloVerifyRequest recevied on the server");
  8991. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  8992. return SIDE_ERROR;
  8993. }
  8994. if (!ssl->options.downgrade ||
  8995. ssl->options.minDowngrade < DTLSv1_2_MINOR) {
  8996. WOLFSSL_MSG(
  8997. "HelloVerifyRequest recevied but not DTLSv1.2 allowed");
  8998. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  8999. return VERSION_ERROR;
  9000. }
  9001. break;
  9002. #endif /* WOLFSSL_DTLS13 && !WOLFSSL_NO_TLS12*/
  9003. default:
  9004. WOLFSSL_MSG("Unknown message type");
  9005. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9006. return SANITY_MSG_E;
  9007. }
  9008. return 0;
  9009. }
  9010. /* Handle a type of handshake message that has been received.
  9011. *
  9012. * ssl The SSL/TLS object.
  9013. * input The message buffer.
  9014. * inOutIdx On entry, the index into the buffer of the current message.
  9015. * On exit, the index into the buffer of the next message.
  9016. * size The length of the current handshake message.
  9017. * totalSz Length of remaining data in the message buffer.
  9018. * returns 0 on success and otherwise failure.
  9019. */
  9020. int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  9021. byte type, word32 size, word32 totalSz)
  9022. {
  9023. int ret = 0;
  9024. word32 inIdx = *inOutIdx;
  9025. (void)totalSz;
  9026. WOLFSSL_ENTER("DoTls13HandShakeMsgType");
  9027. /* make sure we can read the message */
  9028. if (*inOutIdx + size > totalSz)
  9029. return INCOMPLETE_DATA;
  9030. /* sanity check msg received */
  9031. if ((ret = SanityCheckTls13MsgReceived(ssl, type)) != 0) {
  9032. WOLFSSL_MSG("Sanity Check on handshake message type received failed");
  9033. if (ret == VERSION_ERROR)
  9034. SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version);
  9035. else
  9036. SendAlert(ssl, alert_fatal, unexpected_message);
  9037. return ret;
  9038. }
  9039. #if defined(WOLFSSL_CALLBACKS)
  9040. /* add name later, add on record and handshake header part back on */
  9041. if (ssl->toInfoOn) {
  9042. int add = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  9043. AddPacketInfo(ssl, 0, handshake, input + *inOutIdx - add,
  9044. size + add, READ_PROTO, ssl->heap);
  9045. AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
  9046. }
  9047. #endif
  9048. if (ssl->options.handShakeState == HANDSHAKE_DONE &&
  9049. type != session_ticket && type != certificate_request &&
  9050. type != certificate && type != key_update && type != finished) {
  9051. WOLFSSL_MSG("HandShake message after handshake complete");
  9052. SendAlert(ssl, alert_fatal, unexpected_message);
  9053. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  9054. return OUT_OF_ORDER_E;
  9055. }
  9056. if (ssl->options.side == WOLFSSL_CLIENT_END &&
  9057. ssl->options.serverState == NULL_STATE &&
  9058. type != server_hello && type != hello_retry_request
  9059. #if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12)
  9060. && (!ssl->options.dtls || type != hello_verify_request)
  9061. #endif /* defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12) */
  9062. ) {
  9063. WOLFSSL_MSG("First server message not server hello");
  9064. SendAlert(ssl, alert_fatal, unexpected_message);
  9065. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  9066. return OUT_OF_ORDER_E;
  9067. }
  9068. if (ssl->options.side == WOLFSSL_SERVER_END &&
  9069. ssl->options.clientState == NULL_STATE && type != client_hello) {
  9070. WOLFSSL_MSG("First client message not client hello");
  9071. SendAlert(ssl, alert_fatal, unexpected_message);
  9072. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  9073. return OUT_OF_ORDER_E;
  9074. }
  9075. /* above checks handshake state */
  9076. switch (type) {
  9077. #ifndef NO_WOLFSSL_CLIENT
  9078. /* Messages only received by client. */
  9079. case server_hello:
  9080. WOLFSSL_MSG("processing server hello");
  9081. ret = DoTls13ServerHello(ssl, input, inOutIdx, size, &type);
  9082. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  9083. ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  9084. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  9085. if (ssl->options.resuming || !IsAtLeastTLSv1_2(ssl) ||
  9086. IsAtLeastTLSv1_3(ssl->version)) {
  9087. ssl->options.cacheMessages = 0;
  9088. if ((ssl->hsHashes != NULL) && (ssl->hsHashes->messages != NULL)) {
  9089. ForceZero(ssl->hsHashes->messages, ssl->hsHashes->length);
  9090. XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES);
  9091. ssl->hsHashes->messages = NULL;
  9092. }
  9093. }
  9094. #endif
  9095. break;
  9096. case encrypted_extensions:
  9097. WOLFSSL_MSG("processing encrypted extensions");
  9098. ret = DoTls13EncryptedExtensions(ssl, input, inOutIdx, size);
  9099. break;
  9100. #ifndef NO_CERTS
  9101. case certificate_request:
  9102. WOLFSSL_MSG("processing certificate request");
  9103. ret = DoTls13CertificateRequest(ssl, input, inOutIdx, size);
  9104. break;
  9105. #endif
  9106. case session_ticket:
  9107. WOLFSSL_MSG("processing new session ticket");
  9108. ret = DoTls13NewSessionTicket(ssl, input, inOutIdx, size);
  9109. break;
  9110. #endif /* !NO_WOLFSSL_CLIENT */
  9111. #ifndef NO_WOLFSSL_SERVER
  9112. /* Messages only received by server. */
  9113. case client_hello:
  9114. WOLFSSL_MSG("processing client hello");
  9115. ret = DoTls13ClientHello(ssl, input, inOutIdx, size);
  9116. break;
  9117. #ifdef WOLFSSL_EARLY_DATA
  9118. case end_of_early_data:
  9119. WOLFSSL_MSG("processing end of early data");
  9120. ret = DoTls13EndOfEarlyData(ssl, input, inOutIdx, size);
  9121. break;
  9122. #endif
  9123. #endif /* !NO_WOLFSSL_SERVER */
  9124. /* Messages received by both client and server. */
  9125. #if !defined(NO_CERTS) && (!defined(NO_WOLFSSL_CLIENT) || \
  9126. !defined(WOLFSSL_NO_CLIENT_AUTH))
  9127. case certificate:
  9128. WOLFSSL_MSG("processing certificate");
  9129. ret = DoTls13Certificate(ssl, input, inOutIdx, size);
  9130. break;
  9131. #endif
  9132. #if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  9133. defined(HAVE_ED448) || defined(HAVE_PQC)
  9134. case certificate_verify:
  9135. WOLFSSL_MSG("processing certificate verify");
  9136. ret = DoTls13CertificateVerify(ssl, input, inOutIdx, size);
  9137. break;
  9138. #endif
  9139. case finished:
  9140. WOLFSSL_MSG("processing finished");
  9141. ret = DoTls13Finished(ssl, input, inOutIdx, size, totalSz, NO_SNIFF);
  9142. break;
  9143. case key_update:
  9144. WOLFSSL_MSG("processing key update");
  9145. ret = DoTls13KeyUpdate(ssl, input, inOutIdx, size);
  9146. break;
  9147. #if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12)
  9148. case hello_verify_request:
  9149. WOLFSSL_MSG("processing hello verify request");
  9150. ret = DoHelloVerifyRequest(ssl, input, inOutIdx, size);
  9151. break;
  9152. #endif
  9153. default:
  9154. WOLFSSL_MSG("Unknown handshake message type");
  9155. ret = UNKNOWN_HANDSHAKE_TYPE;
  9156. break;
  9157. }
  9158. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_ASYNC_IO)
  9159. /* if async, offset index so this msg will be processed again */
  9160. /* NOTE: check this now before other calls can overwrite ret */
  9161. if ((ret == WC_PENDING_E || ret == OCSP_WANT_READ) && *inOutIdx > 0) {
  9162. /* DTLS always stores a message in a buffer when async is enable, so we
  9163. * don't need to adjust for the extra bytes here (*inOutIdx is always
  9164. * == 0) */
  9165. *inOutIdx -= HANDSHAKE_HEADER_SZ;
  9166. }
  9167. #endif
  9168. /* reset error */
  9169. if (ret == 0 && ssl->error == WC_PENDING_E)
  9170. ssl->error = 0;
  9171. if (ret == 0 && type != client_hello && type != session_ticket &&
  9172. type != key_update) {
  9173. ret = HashInput(ssl, input + inIdx, size);
  9174. }
  9175. if (ret == BUFFER_ERROR || ret == MISSING_HANDSHAKE_DATA)
  9176. SendAlert(ssl, alert_fatal, decode_error);
  9177. else if (ret == EXT_NOT_ALLOWED || ret == PEER_KEY_ERROR ||
  9178. ret == ECC_PEERKEY_ERROR || ret == BAD_KEY_SHARE_DATA ||
  9179. ret == PSK_KEY_ERROR || ret == INVALID_PARAMETER) {
  9180. SendAlert(ssl, alert_fatal, illegal_parameter);
  9181. }
  9182. if (ret == 0 && ssl->options.tls1_3) {
  9183. /* Need to hash input message before deriving secrets. */
  9184. #ifndef NO_WOLFSSL_CLIENT
  9185. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  9186. if (type == server_hello) {
  9187. if ((ret = DeriveEarlySecret(ssl)) != 0)
  9188. return ret;
  9189. if ((ret = DeriveHandshakeSecret(ssl)) != 0)
  9190. return ret;
  9191. if ((ret = DeriveTls13Keys(ssl, handshake_key,
  9192. ENCRYPT_AND_DECRYPT_SIDE, 1)) != 0) {
  9193. return ret;
  9194. }
  9195. #ifdef WOLFSSL_EARLY_DATA
  9196. if (ssl->earlyData != no_early_data) {
  9197. if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
  9198. return ret;
  9199. }
  9200. else
  9201. #endif
  9202. if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0)
  9203. return ret;
  9204. #ifdef WOLFSSL_DTLS13
  9205. if (ssl->options.dtls) {
  9206. w64wrapper epochHandshake;
  9207. epochHandshake = w64From32(0, DTLS13_EPOCH_HANDSHAKE);
  9208. ssl->dtls13Epoch = epochHandshake;
  9209. ssl->dtls13PeerEpoch = epochHandshake;
  9210. ret = Dtls13NewEpoch(
  9211. ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE);
  9212. if (ret != 0)
  9213. return ret;
  9214. ret = Dtls13SetEpochKeys(
  9215. ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE);
  9216. if (ret != 0)
  9217. return ret;
  9218. }
  9219. #endif /* WOLFSSL_DTLS13 */
  9220. }
  9221. if (type == finished) {
  9222. if ((ret = DeriveMasterSecret(ssl)) != 0)
  9223. return ret;
  9224. /* Last use of preMasterSecret - zeroize as soon as possible. */
  9225. ForceZero(ssl->arrays->preMasterSecret,
  9226. ssl->arrays->preMasterSz);
  9227. #ifdef WOLFSSL_EARLY_DATA
  9228. #ifdef WOLFSSL_QUIC
  9229. if (WOLFSSL_IS_QUIC(ssl) && ssl->earlyData != no_early_data) {
  9230. /* QUIC never sends/receives EndOfEarlyData, but having
  9231. * early data means the last encrpytion keys had not been
  9232. * set yet. */
  9233. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  9234. return ret;
  9235. }
  9236. #endif
  9237. if ((ret = DeriveTls13Keys(ssl, traffic_key,
  9238. ENCRYPT_AND_DECRYPT_SIDE,
  9239. ssl->earlyData == no_early_data)) != 0) {
  9240. return ret;
  9241. }
  9242. #else
  9243. if ((ret = DeriveTls13Keys(ssl, traffic_key,
  9244. ENCRYPT_AND_DECRYPT_SIDE, 1)) != 0) {
  9245. return ret;
  9246. }
  9247. #endif
  9248. }
  9249. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  9250. if (type == certificate_request &&
  9251. ssl->options.handShakeState == HANDSHAKE_DONE) {
  9252. /* reset handshake states */
  9253. ssl->options.clientState = CLIENT_HELLO_COMPLETE;
  9254. ssl->options.connectState = FIRST_REPLY_DONE;
  9255. ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
  9256. ssl->options.processReply = 0; /* doProcessInit */
  9257. /*
  9258. DTLSv1.3 note: We can't reset serverState to
  9259. SERVER_FINISHED_COMPLETE with the goal that this connect
  9260. blocks until the cert/cert_verify/finished flight gets ACKed
  9261. by the server. The problem is that we will invoke
  9262. ProcessReplyEx() in that case, but we came here from
  9263. ProcessReplyEx() and it is not re-entrant safe (the input
  9264. buffer would still have the certificate_request message). */
  9265. if (wolfSSL_connect_TLSv13(ssl) != WOLFSSL_SUCCESS) {
  9266. ret = ssl->error;
  9267. if (ret != WC_PENDING_E)
  9268. ret = POST_HAND_AUTH_ERROR;
  9269. }
  9270. }
  9271. #endif
  9272. }
  9273. #endif /* NO_WOLFSSL_CLIENT */
  9274. #ifndef NO_WOLFSSL_SERVER
  9275. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  9276. if (ssl->options.side == WOLFSSL_SERVER_END && type == finished) {
  9277. ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret);
  9278. if (ret != 0)
  9279. return ret;
  9280. }
  9281. #endif
  9282. #endif /* NO_WOLFSSL_SERVER */
  9283. }
  9284. WOLFSSL_LEAVE("DoTls13HandShakeMsgType()", ret);
  9285. return ret;
  9286. }
  9287. /* Handle a handshake message that has been received.
  9288. *
  9289. * ssl The SSL/TLS object.
  9290. * input The message buffer.
  9291. * inOutIdx On entry, the index into the buffer of the current message.
  9292. * On exit, the index into the buffer of the next message.
  9293. * totalSz Length of remaining data in the message buffer.
  9294. * returns 0 on success and otherwise failure.
  9295. */
  9296. int DoTls13HandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  9297. word32 totalSz)
  9298. {
  9299. int ret = 0;
  9300. word32 inputLength;
  9301. byte type;
  9302. word32 size = 0;
  9303. WOLFSSL_ENTER("DoTls13HandShakeMsg()");
  9304. if (ssl->arrays == NULL) {
  9305. if (GetHandshakeHeader(ssl, input, inOutIdx, &type, &size,
  9306. totalSz) != 0) {
  9307. SendAlert(ssl, alert_fatal, unexpected_message);
  9308. WOLFSSL_ERROR_VERBOSE(PARSE_ERROR);
  9309. return PARSE_ERROR;
  9310. }
  9311. return DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
  9312. totalSz);
  9313. }
  9314. inputLength = ssl->buffers.inputBuffer.length - *inOutIdx - ssl->keys.padSz;
  9315. /* If there is a pending fragmented handshake message,
  9316. * pending message size will be non-zero. */
  9317. if (ssl->arrays->pendingMsgSz == 0) {
  9318. if (GetHandshakeHeader(ssl, input, inOutIdx, &type, &size,
  9319. totalSz) != 0) {
  9320. WOLFSSL_ERROR_VERBOSE(PARSE_ERROR);
  9321. return PARSE_ERROR;
  9322. }
  9323. /* Cap the maximum size of a handshake message to something reasonable.
  9324. * By default is the maximum size of a certificate message assuming
  9325. * nine 2048-bit RSA certificates in the chain. */
  9326. if (size > MAX_HANDSHAKE_SZ) {
  9327. WOLFSSL_MSG("Handshake message too large");
  9328. WOLFSSL_ERROR_VERBOSE(HANDSHAKE_SIZE_ERROR);
  9329. return HANDSHAKE_SIZE_ERROR;
  9330. }
  9331. /* size is the size of the certificate message payload */
  9332. if (inputLength - HANDSHAKE_HEADER_SZ < size) {
  9333. ssl->arrays->pendingMsgType = type;
  9334. ssl->arrays->pendingMsgSz = size + HANDSHAKE_HEADER_SZ;
  9335. ssl->arrays->pendingMsg = (byte*)XMALLOC(size + HANDSHAKE_HEADER_SZ,
  9336. ssl->heap,
  9337. DYNAMIC_TYPE_ARRAYS);
  9338. if (ssl->arrays->pendingMsg == NULL)
  9339. return MEMORY_E;
  9340. XMEMCPY(ssl->arrays->pendingMsg,
  9341. input + *inOutIdx - HANDSHAKE_HEADER_SZ,
  9342. inputLength);
  9343. ssl->arrays->pendingMsgOffset = inputLength;
  9344. *inOutIdx += inputLength + ssl->keys.padSz - HANDSHAKE_HEADER_SZ;
  9345. return 0;
  9346. }
  9347. ret = DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
  9348. totalSz);
  9349. }
  9350. else {
  9351. if (inputLength + ssl->arrays->pendingMsgOffset >
  9352. ssl->arrays->pendingMsgSz) {
  9353. inputLength = ssl->arrays->pendingMsgSz -
  9354. ssl->arrays->pendingMsgOffset;
  9355. }
  9356. XMEMCPY(ssl->arrays->pendingMsg + ssl->arrays->pendingMsgOffset,
  9357. input + *inOutIdx, inputLength);
  9358. ssl->arrays->pendingMsgOffset += inputLength;
  9359. *inOutIdx += inputLength + ssl->keys.padSz;
  9360. if (ssl->arrays->pendingMsgOffset == ssl->arrays->pendingMsgSz)
  9361. {
  9362. word32 idx = 0;
  9363. ret = DoTls13HandShakeMsgType(ssl,
  9364. ssl->arrays->pendingMsg + HANDSHAKE_HEADER_SZ,
  9365. &idx, ssl->arrays->pendingMsgType,
  9366. ssl->arrays->pendingMsgSz - HANDSHAKE_HEADER_SZ,
  9367. ssl->arrays->pendingMsgSz);
  9368. #ifdef WOLFSSL_ASYNC_CRYPT
  9369. if (ret == WC_PENDING_E) {
  9370. /* setup to process fragment again */
  9371. ssl->arrays->pendingMsgOffset -= inputLength;
  9372. *inOutIdx -= inputLength + ssl->keys.padSz;
  9373. }
  9374. else
  9375. #endif
  9376. {
  9377. XFREE(ssl->arrays->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
  9378. ssl->arrays->pendingMsg = NULL;
  9379. ssl->arrays->pendingMsgSz = 0;
  9380. }
  9381. }
  9382. }
  9383. WOLFSSL_LEAVE("DoTls13HandShakeMsg()", ret);
  9384. return ret;
  9385. }
  9386. #ifndef NO_WOLFSSL_CLIENT
  9387. /* The client connecting to the server.
  9388. * The protocol version is expecting to be TLS v1.3.
  9389. * If the server downgrades, and older versions of the protocol are compiled
  9390. * in, the client will fallback to wolfSSL_connect().
  9391. * Please see note at top of README if you get an error from connect.
  9392. *
  9393. * ssl The SSL/TLS object.
  9394. * returns WOLFSSL_SUCCESS on successful handshake, WOLFSSL_FATAL_ERROR when
  9395. * unrecoverable error occurs and 0 otherwise.
  9396. * For more error information use wolfSSL_get_error().
  9397. */
  9398. int wolfSSL_connect_TLSv13(WOLFSSL* ssl)
  9399. {
  9400. int advanceState;
  9401. int ret = 0;
  9402. WOLFSSL_ENTER("wolfSSL_connect_TLSv13()");
  9403. #ifdef HAVE_ERRNO_H
  9404. errno = 0;
  9405. #endif
  9406. if (ssl == NULL)
  9407. return BAD_FUNC_ARG;
  9408. if (ssl->options.side != WOLFSSL_CLIENT_END) {
  9409. ssl->error = SIDE_ERROR;
  9410. WOLFSSL_ERROR(ssl->error);
  9411. return WOLFSSL_FATAL_ERROR;
  9412. }
  9413. /* make sure this wolfSSL object has arrays and rng setup. Protects
  9414. * case where the WOLFSSL object is re-used via wolfSSL_clear() */
  9415. if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
  9416. return ret;
  9417. }
  9418. #ifdef WOLFSSL_WOLFSENTRY_HOOKS
  9419. if ((ssl->ConnectFilter != NULL) &&
  9420. (ssl->options.connectState == CONNECT_BEGIN))
  9421. {
  9422. wolfSSL_netfilter_decision_t res;
  9423. if ((ssl->ConnectFilter(ssl, ssl->ConnectFilter_arg, &res) ==
  9424. WOLFSSL_SUCCESS) &&
  9425. (res == WOLFSSL_NETFILTER_REJECT)) {
  9426. ssl->error = SOCKET_FILTERED_E;
  9427. WOLFSSL_ERROR(ssl->error);
  9428. return WOLFSSL_FATAL_ERROR;
  9429. }
  9430. }
  9431. #endif /* WOLFSSL_WOLFSENTRY_HOOKS */
  9432. /* fragOffset is non-zero when sending fragments. On the last
  9433. * fragment, fragOffset is zero again, and the state can be
  9434. * advanced. Also, only advance from states in which we send data */
  9435. advanceState = (ssl->options.connectState == CONNECT_BEGIN ||
  9436. ssl->options.connectState == HELLO_AGAIN ||
  9437. (ssl->options.connectState >= FIRST_REPLY_DONE &&
  9438. ssl->options.connectState <= FIRST_REPLY_FOURTH));
  9439. #ifdef WOLFSSL_DTLS13
  9440. if (ssl->options.dtls)
  9441. advanceState = advanceState && !ssl->dtls13SendingFragments
  9442. && !ssl->dtls13SendingAckOrRtx;
  9443. #endif /* WOLFSSL_DTLS13 */
  9444. if (ssl->buffers.outputBuffer.length > 0
  9445. #ifdef WOLFSSL_ASYNC_CRYPT
  9446. /* do not send buffered or advance state if last error was an
  9447. async pending operation */
  9448. && ssl->error != WC_PENDING_E
  9449. #endif
  9450. ) {
  9451. if ((ssl->error = SendBuffered(ssl)) == 0) {
  9452. if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
  9453. if (advanceState) {
  9454. #ifdef WOLFSSL_DTLS13
  9455. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version) &&
  9456. ssl->options.connectState == FIRST_REPLY_FOURTH) {
  9457. /* WAIT_FINISHED_ACK is a state added afterwards, but it
  9458. can't follow FIRST_REPLY_FOURTH in the enum order. Indeed
  9459. the value of the enum ConnectState is stored in
  9460. serialized session. This would make importing serialized
  9461. session from other wolfSSL version incompatible */
  9462. ssl->options.connectState = WAIT_FINISHED_ACK;
  9463. }
  9464. else
  9465. #endif /* WOLFSSL_DTLS13 */
  9466. {
  9467. ssl->options.connectState++;
  9468. }
  9469. WOLFSSL_MSG("connect state: "
  9470. "Advanced from last buffered fragment send");
  9471. #ifdef WOLFSSL_ASYNC_IO
  9472. FreeAsyncCtx(ssl, 0);
  9473. #endif
  9474. }
  9475. }
  9476. else {
  9477. WOLFSSL_MSG("connect state: "
  9478. "Not advanced, more fragments to send");
  9479. }
  9480. #ifdef WOLFSSL_DTLS13
  9481. if (ssl->options.dtls)
  9482. ssl->dtls13SendingAckOrRtx = 0;
  9483. #endif /* WOLFSSL_DTLS13 */
  9484. }
  9485. else {
  9486. ssl->error = ret;
  9487. WOLFSSL_ERROR(ssl->error);
  9488. return WOLFSSL_FATAL_ERROR;
  9489. }
  9490. }
  9491. ret = RetrySendAlert(ssl);
  9492. if (ret != 0) {
  9493. ssl->error = ret;
  9494. WOLFSSL_ERROR(ssl->error);
  9495. return WOLFSSL_FATAL_ERROR;
  9496. }
  9497. #ifdef WOLFSSL_DTLS13
  9498. if (ssl->options.dtls && ssl->dtls13SendingFragments) {
  9499. if ((ssl->error = Dtls13FragmentsContinue(ssl)) != 0) {
  9500. WOLFSSL_ERROR(ssl->error);
  9501. return WOLFSSL_FATAL_ERROR;
  9502. }
  9503. /* we sent all the fragments. Advance state. */
  9504. ssl->options.connectState++;
  9505. }
  9506. #endif /* WOLFSSL_DTLS13 */
  9507. switch (ssl->options.connectState) {
  9508. case CONNECT_BEGIN:
  9509. /* Always send client hello first. */
  9510. if ((ssl->error = SendTls13ClientHello(ssl)) != 0) {
  9511. WOLFSSL_ERROR(ssl->error);
  9512. return WOLFSSL_FATAL_ERROR;
  9513. }
  9514. ssl->options.connectState = CLIENT_HELLO_SENT;
  9515. WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT");
  9516. #ifdef WOLFSSL_EARLY_DATA
  9517. if (ssl->earlyData != no_early_data) {
  9518. #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
  9519. if (!ssl->options.dtls && ssl->options.tls13MiddleBoxCompat) {
  9520. if ((ssl->error = SendChangeCipher(ssl)) != 0) {
  9521. WOLFSSL_ERROR(ssl->error);
  9522. return WOLFSSL_FATAL_ERROR;
  9523. }
  9524. ssl->options.sentChangeCipher = 1;
  9525. }
  9526. #endif
  9527. ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
  9528. return WOLFSSL_SUCCESS;
  9529. }
  9530. #endif
  9531. FALL_THROUGH;
  9532. case CLIENT_HELLO_SENT:
  9533. /* Get the response/s from the server. */
  9534. while (ssl->options.serverState <
  9535. SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  9536. if ((ssl->error = ProcessReply(ssl)) < 0) {
  9537. WOLFSSL_ERROR(ssl->error);
  9538. return WOLFSSL_FATAL_ERROR;
  9539. }
  9540. #ifdef WOLFSSL_DTLS13
  9541. if (ssl->options.dtls) {
  9542. if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
  9543. WOLFSSL_ERROR(ssl->error);
  9544. return WOLFSSL_FATAL_ERROR;
  9545. }
  9546. }
  9547. #endif /* WOLFSSL_DTLS13 */
  9548. }
  9549. if (!ssl->options.tls1_3) {
  9550. #ifndef WOLFSSL_NO_TLS12
  9551. if (ssl->options.downgrade)
  9552. return wolfSSL_connect(ssl);
  9553. #endif
  9554. WOLFSSL_MSG("Client using higher version, fatal error");
  9555. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  9556. return VERSION_ERROR;
  9557. }
  9558. ssl->options.connectState = HELLO_AGAIN;
  9559. WOLFSSL_MSG("connect state: HELLO_AGAIN");
  9560. FALL_THROUGH;
  9561. case HELLO_AGAIN:
  9562. if (ssl->options.serverState ==
  9563. SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  9564. #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
  9565. if (!ssl->options.dtls && !ssl->options.sentChangeCipher
  9566. && ssl->options.tls13MiddleBoxCompat) {
  9567. if ((ssl->error = SendChangeCipher(ssl)) != 0) {
  9568. WOLFSSL_ERROR(ssl->error);
  9569. return WOLFSSL_FATAL_ERROR;
  9570. }
  9571. ssl->options.sentChangeCipher = 1;
  9572. }
  9573. #endif
  9574. /* Try again with different security parameters. */
  9575. if ((ssl->error = SendTls13ClientHello(ssl)) != 0) {
  9576. WOLFSSL_ERROR(ssl->error);
  9577. return WOLFSSL_FATAL_ERROR;
  9578. }
  9579. }
  9580. ssl->options.connectState = HELLO_AGAIN_REPLY;
  9581. WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY");
  9582. FALL_THROUGH;
  9583. case HELLO_AGAIN_REPLY:
  9584. /* Get the response/s from the server. */
  9585. while (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
  9586. if ((ssl->error = ProcessReply(ssl)) < 0) {
  9587. WOLFSSL_ERROR(ssl->error);
  9588. return WOLFSSL_FATAL_ERROR;
  9589. }
  9590. #ifdef WOLFSSL_DTLS13
  9591. if (ssl->options.dtls) {
  9592. if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
  9593. WOLFSSL_ERROR(ssl->error);
  9594. return WOLFSSL_FATAL_ERROR;
  9595. }
  9596. }
  9597. #endif /* WOLFSSL_DTLS13 */
  9598. }
  9599. ssl->options.connectState = FIRST_REPLY_DONE;
  9600. WOLFSSL_MSG("connect state: FIRST_REPLY_DONE");
  9601. FALL_THROUGH;
  9602. case FIRST_REPLY_DONE:
  9603. if (ssl->options.certOnly)
  9604. return WOLFSSL_SUCCESS;
  9605. #ifdef WOLFSSL_EARLY_DATA
  9606. if (!ssl->options.dtls && ssl->earlyData != no_early_data
  9607. && !WOLFSSL_IS_QUIC(ssl)) {
  9608. if ((ssl->error = SendTls13EndOfEarlyData(ssl)) != 0) {
  9609. WOLFSSL_ERROR(ssl->error);
  9610. return WOLFSSL_FATAL_ERROR;
  9611. }
  9612. WOLFSSL_MSG("sent: end_of_early_data");
  9613. }
  9614. #endif
  9615. ssl->options.connectState = FIRST_REPLY_FIRST;
  9616. WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST");
  9617. FALL_THROUGH;
  9618. case FIRST_REPLY_FIRST:
  9619. #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
  9620. if (!ssl->options.sentChangeCipher && !ssl->options.dtls
  9621. && ssl->options.tls13MiddleBoxCompat) {
  9622. if ((ssl->error = SendChangeCipher(ssl)) != 0) {
  9623. WOLFSSL_ERROR(ssl->error);
  9624. return WOLFSSL_FATAL_ERROR;
  9625. }
  9626. ssl->options.sentChangeCipher = 1;
  9627. }
  9628. #endif
  9629. ssl->options.connectState = FIRST_REPLY_SECOND;
  9630. WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
  9631. FALL_THROUGH;
  9632. case FIRST_REPLY_SECOND:
  9633. /* CLIENT: check peer authentication. */
  9634. if (!ssl->options.peerAuthGood) {
  9635. WOLFSSL_MSG("Server authentication did not happen");
  9636. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  9637. return WOLFSSL_FATAL_ERROR;
  9638. }
  9639. #ifndef NO_CERTS
  9640. if (!ssl->options.resuming && ssl->options.sendVerify) {
  9641. ssl->error = SendTls13Certificate(ssl);
  9642. if (ssl->error != 0) {
  9643. #ifdef WOLFSSL_CHECK_ALERT_ON_ERR
  9644. ProcessReplyEx(ssl, 1); /* See if an alert was sent. */
  9645. #endif
  9646. WOLFSSL_ERROR(ssl->error);
  9647. return WOLFSSL_FATAL_ERROR;
  9648. }
  9649. WOLFSSL_MSG("sent: certificate");
  9650. }
  9651. #endif
  9652. ssl->options.connectState = FIRST_REPLY_THIRD;
  9653. WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
  9654. FALL_THROUGH;
  9655. case FIRST_REPLY_THIRD:
  9656. #if (!defined(NO_CERTS) && (!defined(NO_RSA) || defined(HAVE_ECC) || \
  9657. defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  9658. defined(HAVE_PQC))) && (!defined(NO_WOLFSSL_SERVER) || \
  9659. !defined(WOLFSSL_NO_CLIENT_AUTH))
  9660. if (!ssl->options.resuming && ssl->options.sendVerify) {
  9661. ssl->error = SendTls13CertificateVerify(ssl);
  9662. if (ssl->error != 0) {
  9663. #ifdef WOLFSSL_CHECK_ALERT_ON_ERR
  9664. ProcessReplyEx(ssl, 1); /* See if an alert was sent. */
  9665. #endif
  9666. WOLFSSL_ERROR(ssl->error);
  9667. return WOLFSSL_FATAL_ERROR;
  9668. }
  9669. WOLFSSL_MSG("sent: certificate verify");
  9670. }
  9671. #endif
  9672. ssl->options.connectState = FIRST_REPLY_FOURTH;
  9673. WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH");
  9674. FALL_THROUGH;
  9675. case FIRST_REPLY_FOURTH:
  9676. if ((ssl->error = SendTls13Finished(ssl)) != 0) {
  9677. #ifdef WOLFSSL_CHECK_ALERT_ON_ERR
  9678. ProcessReplyEx(ssl, 1); /* See if an alert was sent. */
  9679. #endif
  9680. WOLFSSL_ERROR(ssl->error);
  9681. return WOLFSSL_FATAL_ERROR;
  9682. }
  9683. WOLFSSL_MSG("sent: finished");
  9684. #ifdef WOLFSSL_DTLS13
  9685. ssl->options.connectState = WAIT_FINISHED_ACK;
  9686. WOLFSSL_MSG("connect state: WAIT_FINISHED_ACK");
  9687. FALL_THROUGH;
  9688. case WAIT_FINISHED_ACK:
  9689. if (ssl->options.dtls) {
  9690. while (ssl->options.serverState != SERVER_FINISHED_ACKED) {
  9691. if ((ssl->error = ProcessReply(ssl)) < 0) {
  9692. WOLFSSL_ERROR(ssl->error);
  9693. return WOLFSSL_FATAL_ERROR;
  9694. }
  9695. if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
  9696. WOLFSSL_ERROR(ssl->error);
  9697. return WOLFSSL_FATAL_ERROR;
  9698. }
  9699. }
  9700. }
  9701. #endif /* WOLFSSL_DTLS13 */
  9702. ssl->options.connectState = FINISHED_DONE;
  9703. WOLFSSL_MSG("connect state: FINISHED_DONE");
  9704. FALL_THROUGH;
  9705. case FINISHED_DONE:
  9706. #ifndef NO_HANDSHAKE_DONE_CB
  9707. if (ssl->hsDoneCb != NULL) {
  9708. int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
  9709. if (cbret < 0) {
  9710. ssl->error = cbret;
  9711. WOLFSSL_ERROR_VERBOSE(ssl->error);
  9712. WOLFSSL_MSG("HandShake Done Cb don't continue error");
  9713. return WOLFSSL_FATAL_ERROR;
  9714. }
  9715. }
  9716. #endif /* NO_HANDSHAKE_DONE_CB */
  9717. if (!ssl->options.keepResources) {
  9718. FreeHandshakeResources(ssl);
  9719. }
  9720. #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
  9721. /* Free the remaining async context if not using it for crypto */
  9722. FreeAsyncCtx(ssl, 1);
  9723. #endif
  9724. ssl->error = 0; /* clear the error */
  9725. WOLFSSL_LEAVE("wolfSSL_connect_TLSv13()", WOLFSSL_SUCCESS);
  9726. return WOLFSSL_SUCCESS;
  9727. default:
  9728. WOLFSSL_MSG("Unknown connect state ERROR");
  9729. return WOLFSSL_FATAL_ERROR; /* unknown connect state */
  9730. }
  9731. }
  9732. #endif
  9733. #if defined(WOLFSSL_SEND_HRR_COOKIE)
  9734. /* Send a cookie with the HelloRetryRequest to avoid storing state.
  9735. *
  9736. * ssl SSL/TLS object.
  9737. * secret Secret to use when generating integrity check for cookie.
  9738. * A value of NULL indicates to generate a new random secret.
  9739. * secretSz Size of secret data in bytes.
  9740. * Use a value of 0 to indicate use of default size.
  9741. * returns BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3, SIDE_ERROR when
  9742. * called on a client; WOLFSSL_SUCCESS on success and otherwise failure.
  9743. */
  9744. int wolfSSL_send_hrr_cookie(WOLFSSL* ssl, const unsigned char* secret,
  9745. unsigned int secretSz)
  9746. {
  9747. int ret;
  9748. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  9749. return BAD_FUNC_ARG;
  9750. #ifndef NO_WOLFSSL_SERVER
  9751. if (ssl->options.side == WOLFSSL_CLIENT_END)
  9752. return SIDE_ERROR;
  9753. if (secretSz == 0) {
  9754. #if !defined(NO_SHA) && defined(NO_SHA256)
  9755. secretSz = WC_SHA_DIGEST_SIZE;
  9756. #endif /* NO_SHA */
  9757. #ifndef NO_SHA256
  9758. secretSz = WC_SHA256_DIGEST_SIZE;
  9759. #endif /* NO_SHA256 */
  9760. }
  9761. if (secretSz != ssl->buffers.tls13CookieSecret.length) {
  9762. byte* newSecret;
  9763. if (ssl->buffers.tls13CookieSecret.buffer != NULL) {
  9764. ForceZero(ssl->buffers.tls13CookieSecret.buffer,
  9765. ssl->buffers.tls13CookieSecret.length);
  9766. XFREE(ssl->buffers.tls13CookieSecret.buffer,
  9767. ssl->heap, DYNAMIC_TYPE_COOKIE_PWD);
  9768. }
  9769. newSecret = (byte*)XMALLOC(secretSz, ssl->heap,
  9770. DYNAMIC_TYPE_COOKIE_PWD);
  9771. if (newSecret == NULL) {
  9772. ssl->buffers.tls13CookieSecret.buffer = NULL;
  9773. ssl->buffers.tls13CookieSecret.length = 0;
  9774. WOLFSSL_MSG("couldn't allocate new cookie secret");
  9775. return MEMORY_ERROR;
  9776. }
  9777. ssl->buffers.tls13CookieSecret.buffer = newSecret;
  9778. ssl->buffers.tls13CookieSecret.length = secretSz;
  9779. #ifdef WOLFSSL_CHECK_MEM_ZERO
  9780. wc_MemZero_Add("wolfSSL_send_hrr_cookie secret",
  9781. ssl->buffers.tls13CookieSecret.buffer,
  9782. ssl->buffers.tls13CookieSecret.length);
  9783. #endif
  9784. }
  9785. /* If the supplied secret is NULL, randomly generate a new secret. */
  9786. if (secret == NULL) {
  9787. ret = wc_RNG_GenerateBlock(ssl->rng,
  9788. ssl->buffers.tls13CookieSecret.buffer, secretSz);
  9789. if (ret < 0)
  9790. return ret;
  9791. }
  9792. else
  9793. XMEMCPY(ssl->buffers.tls13CookieSecret.buffer, secret, secretSz);
  9794. ssl->options.sendCookie = 1;
  9795. ret = WOLFSSL_SUCCESS;
  9796. #else
  9797. (void)secret;
  9798. (void)secretSz;
  9799. ret = SIDE_ERROR;
  9800. #endif
  9801. return ret;
  9802. }
  9803. int wolfSSL_disable_hrr_cookie(WOLFSSL* ssl)
  9804. {
  9805. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  9806. return BAD_FUNC_ARG;
  9807. #ifdef NO_WOLFSSL_SERVER
  9808. return SIDE_ERROR
  9809. #else
  9810. if (ssl->options.side == WOLFSSL_CLIENT_END)
  9811. return SIDE_ERROR;
  9812. if (ssl->buffers.tls13CookieSecret.buffer != NULL) {
  9813. ForceZero(ssl->buffers.tls13CookieSecret.buffer,
  9814. ssl->buffers.tls13CookieSecret.length);
  9815. XFREE(ssl->buffers.tls13CookieSecret.buffer, ssl->heap,
  9816. DYNAMIC_TYPE_COOKIE_PWD);
  9817. ssl->buffers.tls13CookieSecret.buffer = NULL;
  9818. ssl->buffers.tls13CookieSecret.length = 0;
  9819. }
  9820. ssl->options.sendCookie = 0;
  9821. return WOLFSSL_SUCCESS;
  9822. #endif /* NO_WOLFSSL_SERVER */
  9823. }
  9824. #endif /* defined(WOLFSSL_SEND_HRR_COOKIE) */
  9825. #ifdef HAVE_SUPPORTED_CURVES
  9826. /* Create a key share entry from group.
  9827. * Generates a key pair.
  9828. *
  9829. * ssl The SSL/TLS object.
  9830. * group The named group.
  9831. * returns 0 on success, otherwise failure.
  9832. * for async can return WC_PENDING_E and should be called again
  9833. */
  9834. int wolfSSL_UseKeyShare(WOLFSSL* ssl, word16 group)
  9835. {
  9836. int ret;
  9837. if (ssl == NULL)
  9838. return BAD_FUNC_ARG;
  9839. #ifdef WOLFSSL_ASYNC_CRYPT
  9840. ret = wolfSSL_AsyncPop(ssl, NULL);
  9841. if (ret != WC_NOT_PENDING_E) {
  9842. /* Check for error */
  9843. if (ret < 0)
  9844. return ret;
  9845. }
  9846. #endif
  9847. #ifdef HAVE_PQC
  9848. if (WOLFSSL_NAMED_GROUP_IS_PQC(group)) {
  9849. if (ssl->ctx != NULL && ssl->ctx->method != NULL &&
  9850. !IsAtLeastTLSv1_3(ssl->version)) {
  9851. return BAD_FUNC_ARG;
  9852. }
  9853. if (ssl->options.side == WOLFSSL_SERVER_END) {
  9854. /* If I am the server of a KEM connection, do not do keygen because I'm
  9855. * going to encapsulate with the client's public key. Note that I might
  9856. * be the client and ssl->option.side has not been properly set yet. In
  9857. * that case the KeyGen operation will be deferred to connection time. */
  9858. return WOLFSSL_SUCCESS;
  9859. }
  9860. }
  9861. #endif
  9862. #if defined(NO_TLS)
  9863. (void)ret;
  9864. (void)group;
  9865. #else
  9866. ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL);
  9867. if (ret != 0)
  9868. return ret;
  9869. #endif /* NO_TLS */
  9870. return WOLFSSL_SUCCESS;
  9871. }
  9872. /* Send no key share entries - use HelloRetryRequest to negotiate shared group.
  9873. *
  9874. * ssl The SSL/TLS object.
  9875. * returns 0 on success, otherwise failure.
  9876. */
  9877. int wolfSSL_NoKeyShares(WOLFSSL* ssl)
  9878. {
  9879. int ret;
  9880. if (ssl == NULL)
  9881. return BAD_FUNC_ARG;
  9882. if (ssl->options.side == WOLFSSL_SERVER_END)
  9883. return SIDE_ERROR;
  9884. #if defined(NO_TLS)
  9885. (void)ret;
  9886. #else
  9887. ret = TLSX_KeyShare_Empty(ssl);
  9888. if (ret != 0)
  9889. return ret;
  9890. #endif /* NO_TLS */
  9891. return WOLFSSL_SUCCESS;
  9892. }
  9893. #endif
  9894. /* Do not send a ticket after TLS v1.3 handshake for resumption.
  9895. *
  9896. * ctx The SSL/TLS CTX object.
  9897. * returns BAD_FUNC_ARG when ctx is NULL and 0 on success.
  9898. */
  9899. int wolfSSL_CTX_no_ticket_TLSv13(WOLFSSL_CTX* ctx)
  9900. {
  9901. if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
  9902. return BAD_FUNC_ARG;
  9903. if (ctx->method->side == WOLFSSL_CLIENT_END)
  9904. return SIDE_ERROR;
  9905. #ifdef HAVE_SESSION_TICKET
  9906. ctx->noTicketTls13 = 1;
  9907. #endif
  9908. return 0;
  9909. }
  9910. /* Do not send a ticket after TLS v1.3 handshake for resumption.
  9911. *
  9912. * ssl The SSL/TLS object.
  9913. * returns BAD_FUNC_ARG when ssl is NULL, not using TLS v1.3, or called on
  9914. * a client and 0 on success.
  9915. */
  9916. int wolfSSL_no_ticket_TLSv13(WOLFSSL* ssl)
  9917. {
  9918. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  9919. return BAD_FUNC_ARG;
  9920. if (ssl->options.side == WOLFSSL_CLIENT_END)
  9921. return SIDE_ERROR;
  9922. #ifdef HAVE_SESSION_TICKET
  9923. ssl->options.noTicketTls13 = 1;
  9924. #endif
  9925. return 0;
  9926. }
  9927. /* Disallow (EC)DHE key exchange when using pre-shared keys.
  9928. *
  9929. * ctx The SSL/TLS CTX object.
  9930. * returns BAD_FUNC_ARG when ctx is NULL and 0 on success.
  9931. */
  9932. int wolfSSL_CTX_no_dhe_psk(WOLFSSL_CTX* ctx)
  9933. {
  9934. if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
  9935. return BAD_FUNC_ARG;
  9936. ctx->noPskDheKe = 1;
  9937. return 0;
  9938. }
  9939. /* Disallow (EC)DHE key exchange when using pre-shared keys.
  9940. *
  9941. * ssl The SSL/TLS object.
  9942. * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3 and 0 on
  9943. * success.
  9944. */
  9945. int wolfSSL_no_dhe_psk(WOLFSSL* ssl)
  9946. {
  9947. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  9948. return BAD_FUNC_ARG;
  9949. ssl->options.noPskDheKe = 1;
  9950. return 0;
  9951. }
  9952. int Tls13UpdateKeys(WOLFSSL* ssl)
  9953. {
  9954. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  9955. return BAD_FUNC_ARG;
  9956. #ifdef WOLFSSL_DTLS13
  9957. /* we are already waiting for the ack of a sent key update message. We can't
  9958. send another one before receiving its ack. Either wolfSSL_update_keys()
  9959. was invoked multiple times over a short period of time or we replied to a
  9960. KeyUpdate with update request. We'll just ignore sending this
  9961. KeyUpdate. */
  9962. /* TODO: add WOLFSSL_ERROR_ALREADY_IN_PROGRESS type of error here */
  9963. if (ssl->options.dtls && ssl->dtls13WaitKeyUpdateAck)
  9964. return 0;
  9965. #endif /* WOLFSSL_DTLS13 */
  9966. return SendTls13KeyUpdate(ssl);
  9967. }
  9968. /* Update the keys for encryption and decryption.
  9969. * If using non-blocking I/O and WOLFSSL_ERROR_WANT_WRITE is returned then
  9970. * calling wolfSSL_write() will have the message sent when ready.
  9971. *
  9972. * ssl The SSL/TLS object.
  9973. * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
  9974. * WOLFSSL_ERROR_WANT_WRITE when non-blocking I/O is not ready to write,
  9975. * WOLFSSL_SUCCESS on success and otherwise failure.
  9976. */
  9977. int wolfSSL_update_keys(WOLFSSL* ssl)
  9978. {
  9979. int ret;
  9980. ret = Tls13UpdateKeys(ssl);
  9981. if (ret == WANT_WRITE)
  9982. ret = WOLFSSL_ERROR_WANT_WRITE;
  9983. else if (ret == 0)
  9984. ret = WOLFSSL_SUCCESS;
  9985. return ret;
  9986. }
  9987. /* Whether a response is waiting for key update request.
  9988. *
  9989. * ssl The SSL/TLS object.
  9990. * required 0 when no key update response required.
  9991. * 1 when no key update response required.
  9992. * return 0 on success.
  9993. * return BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3
  9994. */
  9995. int wolfSSL_key_update_response(WOLFSSL* ssl, int* required)
  9996. {
  9997. if (required == NULL || ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  9998. return BAD_FUNC_ARG;
  9999. *required = ssl->keys.updateResponseReq;
  10000. return 0;
  10001. }
  10002. #if !defined(NO_CERTS) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  10003. /* Allow post-handshake authentication in TLS v1.3 connections.
  10004. *
  10005. * ctx The SSL/TLS CTX object.
  10006. * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a client and
  10007. * 0 on success.
  10008. */
  10009. int wolfSSL_CTX_allow_post_handshake_auth(WOLFSSL_CTX* ctx)
  10010. {
  10011. if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
  10012. return BAD_FUNC_ARG;
  10013. if (ctx->method->side == WOLFSSL_SERVER_END)
  10014. return SIDE_ERROR;
  10015. ctx->postHandshakeAuth = 1;
  10016. return 0;
  10017. }
  10018. /* Allow post-handshake authentication in TLS v1.3 connection.
  10019. *
  10020. * ssl The SSL/TLS object.
  10021. * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
  10022. * SIDE_ERROR when not a client and 0 on success.
  10023. */
  10024. int wolfSSL_allow_post_handshake_auth(WOLFSSL* ssl)
  10025. {
  10026. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  10027. return BAD_FUNC_ARG;
  10028. if (ssl->options.side == WOLFSSL_SERVER_END)
  10029. return SIDE_ERROR;
  10030. ssl->options.postHandshakeAuth = 1;
  10031. return 0;
  10032. }
  10033. /* Request a certificate of the client.
  10034. * Can be called any time after handshake completion.
  10035. * A maximum of 256 requests can be sent on a connection.
  10036. *
  10037. * ssl SSL/TLS object.
  10038. */
  10039. int wolfSSL_request_certificate(WOLFSSL* ssl)
  10040. {
  10041. int ret;
  10042. #ifndef NO_WOLFSSL_SERVER
  10043. CertReqCtx* certReqCtx;
  10044. #endif
  10045. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  10046. return BAD_FUNC_ARG;
  10047. #ifndef NO_WOLFSSL_SERVER
  10048. if (ssl->options.side == WOLFSSL_CLIENT_END)
  10049. return SIDE_ERROR;
  10050. if (ssl->options.handShakeState != HANDSHAKE_DONE)
  10051. return NOT_READY_ERROR;
  10052. if (!ssl->options.postHandshakeAuth)
  10053. return POST_HAND_AUTH_ERROR;
  10054. certReqCtx = (CertReqCtx*)XMALLOC(sizeof(CertReqCtx), ssl->heap,
  10055. DYNAMIC_TYPE_TMP_BUFFER);
  10056. if (certReqCtx == NULL)
  10057. return MEMORY_E;
  10058. XMEMSET(certReqCtx, 0, sizeof(CertReqCtx));
  10059. certReqCtx->next = ssl->certReqCtx;
  10060. certReqCtx->len = 1;
  10061. if (certReqCtx->next != NULL)
  10062. certReqCtx->ctx = certReqCtx->next->ctx + 1;
  10063. ssl->certReqCtx = certReqCtx;
  10064. ssl->msgsReceived.got_certificate = 0;
  10065. ssl->msgsReceived.got_certificate_verify = 0;
  10066. ssl->msgsReceived.got_finished = 0;
  10067. ret = SendTls13CertificateRequest(ssl, &certReqCtx->ctx, certReqCtx->len);
  10068. if (ret == WANT_WRITE)
  10069. ret = WOLFSSL_ERROR_WANT_WRITE;
  10070. else if (ret == 0)
  10071. ret = WOLFSSL_SUCCESS;
  10072. #else
  10073. ret = SIDE_ERROR;
  10074. #endif
  10075. return ret;
  10076. }
  10077. #endif /* !NO_CERTS && WOLFSSL_POST_HANDSHAKE_AUTH */
  10078. #if !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  10079. /* Get the preferred key exchange group.
  10080. *
  10081. * ssl The SSL/TLS object.
  10082. * returns BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3,
  10083. * SIDE_ERROR when not a client, NOT_READY_ERROR when handshake not complete
  10084. * and group number on success.
  10085. */
  10086. int wolfSSL_preferred_group(WOLFSSL* ssl)
  10087. {
  10088. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  10089. return BAD_FUNC_ARG;
  10090. #ifndef NO_WOLFSSL_CLIENT
  10091. if (ssl->options.side == WOLFSSL_SERVER_END)
  10092. return SIDE_ERROR;
  10093. if (ssl->options.handShakeState != HANDSHAKE_DONE)
  10094. return NOT_READY_ERROR;
  10095. #ifdef HAVE_SUPPORTED_CURVES
  10096. /* Return supported groups only. */
  10097. return TLSX_SupportedCurve_Preferred(ssl, 1);
  10098. #else
  10099. return 0;
  10100. #endif
  10101. #else
  10102. return SIDE_ERROR;
  10103. #endif
  10104. }
  10105. #endif
  10106. #if defined(HAVE_SUPPORTED_CURVES)
  10107. /* Sets the key exchange groups in rank order on a context.
  10108. *
  10109. * ctx SSL/TLS context object.
  10110. * groups Array of groups.
  10111. * count Number of groups in array.
  10112. * returns BAD_FUNC_ARG when ctx or groups is NULL, not using TLS v1.3 or
  10113. * count is greater than WOLFSSL_MAX_GROUP_COUNT and WOLFSSL_SUCCESS on success.
  10114. */
  10115. int wolfSSL_CTX_set_groups(WOLFSSL_CTX* ctx, int* groups, int count)
  10116. {
  10117. int ret, i;
  10118. WOLFSSL_ENTER("wolfSSL_CTX_set_groups");
  10119. if (ctx == NULL || groups == NULL || count > WOLFSSL_MAX_GROUP_COUNT)
  10120. return BAD_FUNC_ARG;
  10121. if (!IsAtLeastTLSv1_3(ctx->method->version))
  10122. return BAD_FUNC_ARG;
  10123. ctx->numGroups = 0;
  10124. #if !defined(NO_TLS)
  10125. TLSX_Remove(&ctx->extensions, TLSX_SUPPORTED_GROUPS, ctx->heap);
  10126. #endif /* !NO_TLS */
  10127. for (i = 0; i < count; i++) {
  10128. /* Call to wolfSSL_CTX_UseSupportedCurve also checks if input groups
  10129. * are valid */
  10130. if ((ret = wolfSSL_CTX_UseSupportedCurve(ctx, (word16)groups[i]))
  10131. != WOLFSSL_SUCCESS) {
  10132. #if !defined(NO_TLS)
  10133. TLSX_Remove(&ctx->extensions, TLSX_SUPPORTED_GROUPS, ctx->heap);
  10134. #endif /* !NO_TLS */
  10135. return ret;
  10136. }
  10137. ctx->group[i] = (word16)groups[i];
  10138. }
  10139. ctx->numGroups = (byte)count;
  10140. return WOLFSSL_SUCCESS;
  10141. }
  10142. /* Sets the key exchange groups in rank order.
  10143. *
  10144. * ssl SSL/TLS object.
  10145. * groups Array of groups.
  10146. * count Number of groups in array.
  10147. * returns BAD_FUNC_ARG when ssl or groups is NULL, not using TLS v1.3 or
  10148. * count is greater than WOLFSSL_MAX_GROUP_COUNT and WOLFSSL_SUCCESS on success.
  10149. */
  10150. int wolfSSL_set_groups(WOLFSSL* ssl, int* groups, int count)
  10151. {
  10152. int ret, i;
  10153. WOLFSSL_ENTER("wolfSSL_set_groups");
  10154. if (ssl == NULL || groups == NULL || count > WOLFSSL_MAX_GROUP_COUNT)
  10155. return BAD_FUNC_ARG;
  10156. if (!IsAtLeastTLSv1_3(ssl->version))
  10157. return BAD_FUNC_ARG;
  10158. ssl->numGroups = 0;
  10159. #if !defined(NO_TLS)
  10160. TLSX_Remove(&ssl->extensions, TLSX_SUPPORTED_GROUPS, ssl->heap);
  10161. #endif /* !NO_TLS */
  10162. for (i = 0; i < count; i++) {
  10163. /* Call to wolfSSL_UseSupportedCurve also checks if input groups
  10164. * are valid */
  10165. if ((ret = wolfSSL_UseSupportedCurve(ssl, (word16)groups[i]))
  10166. != WOLFSSL_SUCCESS) {
  10167. #if !defined(NO_TLS)
  10168. TLSX_Remove(&ssl->extensions, TLSX_SUPPORTED_GROUPS, ssl->heap);
  10169. #endif /* !NO_TLS */
  10170. return ret;
  10171. }
  10172. ssl->group[i] = (word16)groups[i];
  10173. }
  10174. ssl->numGroups = (byte)count;
  10175. return WOLFSSL_SUCCESS;
  10176. }
  10177. #endif /* HAVE_SUPPORTED_CURVES */
  10178. #ifndef NO_PSK
  10179. /* Set the PSK callback, that is passed the cipher suite, for a client to use
  10180. * against context object.
  10181. *
  10182. * @param [in, out] ctx SSL/TLS context object.
  10183. * @param [in] cb Client PSK callback passed a cipher suite.
  10184. */
  10185. void wolfSSL_CTX_set_psk_client_cs_callback(WOLFSSL_CTX* ctx,
  10186. wc_psk_client_cs_callback cb)
  10187. {
  10188. WOLFSSL_ENTER("SSL_CTX_set_psk_client_cs_callback");
  10189. if (ctx == NULL)
  10190. return;
  10191. ctx->havePSK = 1;
  10192. ctx->client_psk_cs_cb = cb;
  10193. }
  10194. /* Set the PSK callback, that is passed the cipher suite, for a client to use
  10195. * against SSL object.
  10196. *
  10197. * @param [in, out] ssl SSL/TLS object.
  10198. * @param [in] cb Client PSK callback passed a cipher suite.
  10199. */
  10200. void wolfSSL_set_psk_client_cs_callback(WOLFSSL* ssl,
  10201. wc_psk_client_cs_callback cb)
  10202. {
  10203. byte haveRSA = 1;
  10204. int keySz = 0;
  10205. WOLFSSL_ENTER("SSL_set_psk_client_cs_callback");
  10206. if (ssl == NULL)
  10207. return;
  10208. ssl->options.havePSK = 1;
  10209. ssl->options.client_psk_cs_cb = cb;
  10210. #ifdef NO_RSA
  10211. haveRSA = 0;
  10212. #endif
  10213. #ifndef NO_CERTS
  10214. keySz = ssl->buffers.keySz;
  10215. #endif
  10216. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
  10217. ssl->options.haveDH, ssl->options.haveECDSAsig,
  10218. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  10219. ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
  10220. ssl->options.haveAnon, TRUE, ssl->options.side);
  10221. }
  10222. /* Set the PSK callback that returns the cipher suite for a client to use
  10223. * against context object.
  10224. *
  10225. * @param [in, out] ctx SSL/TLS context object.
  10226. * @param [in] cb Client PSK callback returning cipher suite.
  10227. */
  10228. void wolfSSL_CTX_set_psk_client_tls13_callback(WOLFSSL_CTX* ctx,
  10229. wc_psk_client_tls13_callback cb)
  10230. {
  10231. WOLFSSL_ENTER("SSL_CTX_set_psk_client_tls13_callback");
  10232. if (ctx == NULL)
  10233. return;
  10234. ctx->havePSK = 1;
  10235. ctx->client_psk_tls13_cb = cb;
  10236. }
  10237. /* Set the PSK callback that returns the cipher suite for a client to use
  10238. * against SSL object.
  10239. *
  10240. * @param [in, out] ssl SSL/TLS object.
  10241. * @param [in] cb Client PSK callback returning cipher suite.
  10242. */
  10243. void wolfSSL_set_psk_client_tls13_callback(WOLFSSL* ssl,
  10244. wc_psk_client_tls13_callback cb)
  10245. {
  10246. byte haveRSA = 1;
  10247. int keySz = 0;
  10248. WOLFSSL_ENTER("SSL_set_psk_client_tls13_callback");
  10249. if (ssl == NULL)
  10250. return;
  10251. ssl->options.havePSK = 1;
  10252. ssl->options.client_psk_tls13_cb = cb;
  10253. #ifdef NO_RSA
  10254. haveRSA = 0;
  10255. #endif
  10256. #ifndef NO_CERTS
  10257. keySz = ssl->buffers.keySz;
  10258. #endif
  10259. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
  10260. ssl->options.haveDH, ssl->options.haveECDSAsig,
  10261. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  10262. ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
  10263. ssl->options.haveAnon, TRUE, ssl->options.side);
  10264. }
  10265. /* Set the PSK callback that returns the cipher suite for a server to use
  10266. * against context object.
  10267. *
  10268. * @param [in, out] ctx SSL/TLS context object.
  10269. * @param [in] cb Server PSK callback returning cipher suite.
  10270. */
  10271. void wolfSSL_CTX_set_psk_server_tls13_callback(WOLFSSL_CTX* ctx,
  10272. wc_psk_server_tls13_callback cb)
  10273. {
  10274. WOLFSSL_ENTER("SSL_CTX_set_psk_server_tls13_callback");
  10275. if (ctx == NULL)
  10276. return;
  10277. ctx->havePSK = 1;
  10278. ctx->server_psk_tls13_cb = cb;
  10279. }
  10280. /* Set the PSK callback that returns the cipher suite for a server to use
  10281. * against SSL object.
  10282. *
  10283. * @param [in, out] ssl SSL/TLS object.
  10284. * @param [in] cb Server PSK callback returning cipher suite.
  10285. */
  10286. void wolfSSL_set_psk_server_tls13_callback(WOLFSSL* ssl,
  10287. wc_psk_server_tls13_callback cb)
  10288. {
  10289. byte haveRSA = 1;
  10290. int keySz = 0;
  10291. WOLFSSL_ENTER("SSL_set_psk_server_tls13_callback");
  10292. if (ssl == NULL)
  10293. return;
  10294. ssl->options.havePSK = 1;
  10295. ssl->options.server_psk_tls13_cb = cb;
  10296. #ifdef NO_RSA
  10297. haveRSA = 0;
  10298. #endif
  10299. #ifndef NO_CERTS
  10300. keySz = ssl->buffers.keySz;
  10301. #endif
  10302. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
  10303. ssl->options.haveDH, ssl->options.haveECDSAsig,
  10304. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  10305. ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
  10306. ssl->options.haveAnon, TRUE, ssl->options.side);
  10307. }
  10308. /* Get name of first supported cipher suite that uses the hash indicated.
  10309. *
  10310. * @param [in] ssl SSL/TLS object.
  10311. * @param [in] hash Name of hash algorithm. e.g. "SHA256", "SHA384"
  10312. * @return Name of cipher suite.
  10313. * @return NULL on failure.
  10314. */
  10315. const char* wolfSSL_get_cipher_name_by_hash(WOLFSSL* ssl, const char* hash)
  10316. {
  10317. const char* name = NULL;
  10318. byte mac = no_mac;
  10319. int i;
  10320. if (XSTRCMP(hash, "SHA256") == 0) {
  10321. mac = sha256_mac;
  10322. }
  10323. else if (XSTRCMP(hash, "SHA384") == 0) {
  10324. mac = sha384_mac;
  10325. }
  10326. if (mac != no_mac) {
  10327. for (i = 0; i < ssl->suites->suiteSz; i += 2) {
  10328. if (SuiteMac(ssl->suites->suites + i) == mac) {
  10329. name = GetCipherNameInternal(ssl->suites->suites[i + 0],
  10330. ssl->suites->suites[i + 1]);
  10331. break;
  10332. }
  10333. }
  10334. }
  10335. return name;
  10336. }
  10337. #endif /* !NO_PSK */
  10338. #ifndef NO_WOLFSSL_SERVER
  10339. #if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  10340. static void DtlsResetState(WOLFSSL *ssl)
  10341. {
  10342. /* Reset the state so that we can statelessly await the
  10343. * ClientHello that contains the cookie. */
  10344. /* Reset DTLS window */
  10345. w64Zero(&ssl->dtls13Epochs[0].nextSeqNumber);
  10346. w64Zero(&ssl->dtls13Epochs[0].nextPeerSeqNumber);
  10347. XMEMSET(ssl->dtls13Epochs[0].window, 0,
  10348. sizeof(ssl->dtls13Epochs[0].window));
  10349. ssl->keys.dtls_expected_peer_handshake_number = 0;
  10350. ssl->keys.dtls_handshake_number = 0;
  10351. ssl->msgsReceived.got_client_hello = 0;
  10352. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10353. /* Remove cookie so that it will get computed again */
  10354. TLSX_Remove(&ssl->extensions, TLSX_COOKIE, ssl->heap);
  10355. #endif
  10356. /* Reset states */
  10357. ssl->options.serverState = NULL_STATE;
  10358. ssl->options.clientState = NULL_STATE;
  10359. ssl->options.connectState = CONNECT_BEGIN;
  10360. ssl->options.acceptState = ACCEPT_BEGIN;
  10361. ssl->options.handShakeState = NULL_STATE;
  10362. Dtls13FreeFsmResources(ssl);
  10363. }
  10364. static int DtlsAcceptStateless(WOLFSSL *ssl)
  10365. {
  10366. int ret;
  10367. if (!ssl->options.dtls)
  10368. return 0;
  10369. switch (ssl->options.acceptState) {
  10370. case TLS13_ACCEPT_BEGIN:
  10371. while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
  10372. ret = ProcessReply(ssl);
  10373. if (ret != 0)
  10374. return ret;
  10375. }
  10376. if (!IsAtLeastTLSv1_3(ssl->version))
  10377. return wolfSSL_accept(ssl);
  10378. ssl->options.acceptState = TLS13_ACCEPT_CLIENT_HELLO_DONE;
  10379. WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
  10380. FALL_THROUGH;
  10381. case TLS13_ACCEPT_CLIENT_HELLO_DONE:
  10382. if (ssl->options.serverState ==
  10383. SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  10384. ret = SendTls13ServerHello(ssl, hello_retry_request);
  10385. DtlsResetState(ssl);
  10386. return ret;
  10387. }
  10388. ssl->options.acceptState = TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE;
  10389. WOLFSSL_MSG("accept state ACCEPT_HELLO_RETRY_REQUEST_DONE");
  10390. FALL_THROUGH;
  10391. default:
  10392. return 0;
  10393. }
  10394. return 0;
  10395. }
  10396. #endif /* WOLFSSL_DTLS13 */
  10397. /* The server accepting a connection from a client.
  10398. * The protocol version is expecting to be TLS v1.3.
  10399. * If the client downgrades, and older versions of the protocol are compiled
  10400. * in, the server will fallback to wolfSSL_accept().
  10401. * Please see note at top of README if you get an error from accept.
  10402. *
  10403. * ssl The SSL/TLS object.
  10404. * returns WOLFSSL_SUCCESS on successful handshake, WOLFSSL_FATAL_ERROR when
  10405. * unrecoverable error occurs and 0 otherwise.
  10406. * For more error information use wolfSSL_get_error().
  10407. */
  10408. int wolfSSL_accept_TLSv13(WOLFSSL* ssl)
  10409. {
  10410. #if !defined(NO_CERTS) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  10411. word16 havePSK = 0;
  10412. #endif
  10413. int advanceState;
  10414. int ret = 0;
  10415. WOLFSSL_ENTER("SSL_accept_TLSv13()");
  10416. #ifdef HAVE_ERRNO_H
  10417. errno = 0;
  10418. #endif
  10419. if (ssl == NULL)
  10420. return WOLFSSL_FATAL_ERROR;
  10421. #if !defined(NO_CERTS) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  10422. havePSK = ssl->options.havePSK;
  10423. #endif
  10424. if (ssl->options.side != WOLFSSL_SERVER_END) {
  10425. ssl->error = SIDE_ERROR;
  10426. WOLFSSL_ERROR(ssl->error);
  10427. return WOLFSSL_FATAL_ERROR;
  10428. }
  10429. /* make sure this wolfSSL object has arrays and rng setup. Protects
  10430. * case where the WOLFSSL object is re-used via wolfSSL_clear() */
  10431. if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
  10432. return ret;
  10433. }
  10434. #ifdef WOLFSSL_WOLFSENTRY_HOOKS
  10435. if ((ssl->AcceptFilter != NULL) &&
  10436. ((ssl->options.acceptState == TLS13_ACCEPT_BEGIN)
  10437. #ifdef HAVE_SECURE_RENEGOTIATION
  10438. || (ssl->options.acceptState == TLS13_ACCEPT_BEGIN_RENEG)
  10439. #endif
  10440. ))
  10441. {
  10442. wolfSSL_netfilter_decision_t res;
  10443. if ((ssl->AcceptFilter(ssl, ssl->AcceptFilter_arg, &res) ==
  10444. WOLFSSL_SUCCESS) &&
  10445. (res == WOLFSSL_NETFILTER_REJECT)) {
  10446. ssl->error = SOCKET_FILTERED_E;
  10447. WOLFSSL_ERROR(ssl->error);
  10448. return WOLFSSL_FATAL_ERROR;
  10449. }
  10450. }
  10451. #endif /* WOLFSSL_WOLFSENTRY_HOOKS */
  10452. #ifndef NO_CERTS
  10453. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10454. if (!havePSK)
  10455. #endif
  10456. {
  10457. #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \
  10458. defined(WOLFSSL_NGINX) || defined (WOLFSSL_HAPROXY)
  10459. if (ssl->ctx->certSetupCb != NULL) {
  10460. WOLFSSL_MSG("CertSetupCb set. server cert and "
  10461. "key not checked");
  10462. }
  10463. else
  10464. #endif
  10465. {
  10466. if (!ssl->buffers.certificate ||
  10467. !ssl->buffers.certificate->buffer) {
  10468. WOLFSSL_MSG("accept error: server cert required");
  10469. ssl->error = NO_PRIVATE_KEY;
  10470. WOLFSSL_ERROR(ssl->error);
  10471. return WOLFSSL_FATAL_ERROR;
  10472. }
  10473. if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
  10474. /* allow no private key if using existing key */
  10475. #ifdef WOLF_PRIVATE_KEY_ID
  10476. if (ssl->devId != INVALID_DEVID
  10477. #ifdef HAVE_PK_CALLBACKS
  10478. || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
  10479. #endif
  10480. ) {
  10481. WOLFSSL_MSG("Allowing no server private key (external)");
  10482. }
  10483. else
  10484. #endif
  10485. {
  10486. WOLFSSL_MSG("accept error: server key required");
  10487. ssl->error = NO_PRIVATE_KEY;
  10488. WOLFSSL_ERROR(ssl->error);
  10489. return WOLFSSL_FATAL_ERROR;
  10490. }
  10491. }
  10492. }
  10493. }
  10494. #endif /* NO_CERTS */
  10495. if (ssl->buffers.outputBuffer.length > 0
  10496. #ifdef WOLFSSL_ASYNC_CRYPT
  10497. /* do not send buffered or advance state if last error was an
  10498. async pending operation */
  10499. && ssl->error != WC_PENDING_E
  10500. #endif
  10501. ) {
  10502. /* fragOffset is non-zero when sending fragments. On the last
  10503. * fragment, fragOffset is zero again, and the state can be
  10504. * advanced. */
  10505. advanceState =
  10506. (ssl->options.acceptState == TLS13_ACCEPT_CLIENT_HELLO_DONE ||
  10507. ssl->options.acceptState ==
  10508. TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE ||
  10509. ssl->options.acceptState == TLS13_ACCEPT_SECOND_REPLY_DONE ||
  10510. ssl->options.acceptState == TLS13_SERVER_HELLO_SENT ||
  10511. ssl->options.acceptState == TLS13_ACCEPT_THIRD_REPLY_DONE ||
  10512. ssl->options.acceptState == TLS13_SERVER_EXTENSIONS_SENT ||
  10513. ssl->options.acceptState == TLS13_CERT_REQ_SENT ||
  10514. ssl->options.acceptState == TLS13_CERT_SENT ||
  10515. ssl->options.acceptState == TLS13_CERT_VERIFY_SENT ||
  10516. ssl->options.acceptState == TLS13_ACCEPT_FINISHED_SENT ||
  10517. ssl->options.acceptState == TLS13_ACCEPT_FINISHED_DONE);
  10518. #ifdef WOLFSSL_DTLS13
  10519. if (ssl->options.dtls)
  10520. advanceState = advanceState && !ssl->dtls13SendingFragments
  10521. && !ssl->dtls13SendingAckOrRtx;
  10522. #endif /* WOLFSSL_DTLS13 */
  10523. if ((ssl->error = SendBuffered(ssl)) == 0) {
  10524. if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
  10525. if (advanceState) {
  10526. ssl->options.acceptState++;
  10527. WOLFSSL_MSG("accept state: "
  10528. "Advanced from last buffered fragment send");
  10529. #ifdef WOLFSSL_ASYNC_IO
  10530. FreeAsyncCtx(ssl, 0);
  10531. #endif
  10532. }
  10533. }
  10534. else {
  10535. WOLFSSL_MSG("accept state: "
  10536. "Not advanced, more fragments to send");
  10537. }
  10538. #ifdef WOLFSSL_DTLS13
  10539. if (ssl->options.dtls)
  10540. ssl->dtls13SendingAckOrRtx = 0;
  10541. #endif /* WOLFSSL_DTLS13 */
  10542. }
  10543. else {
  10544. ssl->error = ret;
  10545. WOLFSSL_ERROR(ssl->error);
  10546. return WOLFSSL_FATAL_ERROR;
  10547. }
  10548. }
  10549. ret = RetrySendAlert(ssl);
  10550. if (ret != 0) {
  10551. ssl->error = ret;
  10552. WOLFSSL_ERROR(ssl->error);
  10553. return WOLFSSL_FATAL_ERROR;
  10554. }
  10555. #ifdef WOLFSSL_DTLS13
  10556. if (ssl->options.dtls && ssl->dtls13SendingFragments) {
  10557. if ((ssl->error = Dtls13FragmentsContinue(ssl)) != 0) {
  10558. WOLFSSL_ERROR(ssl->error);
  10559. return WOLFSSL_FATAL_ERROR;
  10560. }
  10561. /* we sent all the fragments. Advance state. */
  10562. ssl->options.acceptState++;
  10563. }
  10564. #endif /* WOLFSSL_DTLS13 */
  10565. #if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  10566. if (ssl->options.dtls && ssl->options.sendCookie) {
  10567. while (ssl->options.serverState < SERVER_HELLO_COMPLETE) {
  10568. ret = DtlsAcceptStateless(ssl);
  10569. if (ret != 0) {
  10570. ssl->error = ret;
  10571. WOLFSSL_ERROR(ssl->error);
  10572. return WOLFSSL_FATAL_ERROR;
  10573. }
  10574. }
  10575. }
  10576. #endif /* defined(WOLFSSL_DTLS13) && defined(WOLFSSL_SEND_HRR_COOKIE) */
  10577. switch (ssl->options.acceptState) {
  10578. #ifdef HAVE_SECURE_RENEGOTIATION
  10579. case TLS13_ACCEPT_BEGIN_RENEG:
  10580. #endif
  10581. case TLS13_ACCEPT_BEGIN :
  10582. /* get client_hello */
  10583. while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
  10584. if ((ssl->error = ProcessReply(ssl)) < 0) {
  10585. WOLFSSL_ERROR(ssl->error);
  10586. return WOLFSSL_FATAL_ERROR;
  10587. }
  10588. #ifdef WOLFSSL_DTLS13
  10589. if (ssl->options.dtls) {
  10590. if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
  10591. WOLFSSL_ERROR(ssl->error);
  10592. return WOLFSSL_FATAL_ERROR;
  10593. }
  10594. }
  10595. #endif /* WOLFSSL_DTLS13 */
  10596. }
  10597. ssl->options.acceptState = TLS13_ACCEPT_CLIENT_HELLO_DONE;
  10598. WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
  10599. if (!IsAtLeastTLSv1_3(ssl->version))
  10600. return wolfSSL_accept(ssl);
  10601. FALL_THROUGH;
  10602. case TLS13_ACCEPT_CLIENT_HELLO_DONE :
  10603. if (ssl->options.serverState ==
  10604. SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  10605. if ((ssl->error = SendTls13ServerHello(ssl,
  10606. hello_retry_request)) != 0) {
  10607. WOLFSSL_ERROR(ssl->error);
  10608. return WOLFSSL_FATAL_ERROR;
  10609. }
  10610. }
  10611. ssl->options.acceptState = TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE;
  10612. WOLFSSL_MSG("accept state ACCEPT_HELLO_RETRY_REQUEST_DONE");
  10613. FALL_THROUGH;
  10614. case TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE :
  10615. #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
  10616. if (!ssl->options.dtls && ssl->options.tls13MiddleBoxCompat
  10617. && ssl->options.serverState ==
  10618. SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  10619. if ((ssl->error = SendChangeCipher(ssl)) != 0) {
  10620. WOLFSSL_ERROR(ssl->error);
  10621. return WOLFSSL_FATAL_ERROR;
  10622. }
  10623. ssl->options.sentChangeCipher = 1;
  10624. ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
  10625. }
  10626. #endif
  10627. ssl->options.acceptState = TLS13_ACCEPT_FIRST_REPLY_DONE;
  10628. WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
  10629. FALL_THROUGH;
  10630. case TLS13_ACCEPT_FIRST_REPLY_DONE :
  10631. if (ssl->options.serverState ==
  10632. SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  10633. ssl->options.clientState = CLIENT_HELLO_RETRY;
  10634. while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
  10635. if ((ssl->error = ProcessReply(ssl)) < 0) {
  10636. WOLFSSL_ERROR(ssl->error);
  10637. return WOLFSSL_FATAL_ERROR;
  10638. }
  10639. #ifdef WOLFSSL_DTLS13
  10640. if (ssl->options.dtls) {
  10641. if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
  10642. WOLFSSL_ERROR(ssl->error);
  10643. return WOLFSSL_FATAL_ERROR;
  10644. }
  10645. }
  10646. #endif /* WOLFSSL_DTLS13 */
  10647. }
  10648. }
  10649. ssl->options.acceptState = TLS13_ACCEPT_SECOND_REPLY_DONE;
  10650. WOLFSSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE");
  10651. FALL_THROUGH;
  10652. case TLS13_ACCEPT_SECOND_REPLY_DONE :
  10653. #ifdef WOLFSSL_DTLS
  10654. if (ssl->chGoodCb != NULL) {
  10655. int cbret = ssl->chGoodCb(ssl, ssl->chGoodCtx);
  10656. if (cbret < 0) {
  10657. ssl->error = cbret;
  10658. WOLFSSL_MSG("ClientHello Good Cb don't continue error");
  10659. return WOLFSSL_FATAL_ERROR;
  10660. }
  10661. }
  10662. #endif
  10663. if ((ssl->error = SendTls13ServerHello(ssl, server_hello)) != 0) {
  10664. WOLFSSL_ERROR(ssl->error);
  10665. return WOLFSSL_FATAL_ERROR;
  10666. }
  10667. ssl->options.acceptState = TLS13_SERVER_HELLO_SENT;
  10668. WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
  10669. FALL_THROUGH;
  10670. case TLS13_SERVER_HELLO_SENT :
  10671. #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
  10672. if (!ssl->options.dtls && ssl->options.tls13MiddleBoxCompat
  10673. && !ssl->options.sentChangeCipher && !ssl->options.dtls) {
  10674. if ((ssl->error = SendChangeCipher(ssl)) != 0) {
  10675. WOLFSSL_ERROR(ssl->error);
  10676. return WOLFSSL_FATAL_ERROR;
  10677. }
  10678. ssl->options.sentChangeCipher = 1;
  10679. }
  10680. #endif
  10681. ssl->options.acceptState = TLS13_ACCEPT_THIRD_REPLY_DONE;
  10682. WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
  10683. FALL_THROUGH;
  10684. case TLS13_ACCEPT_THIRD_REPLY_DONE :
  10685. #ifdef HAVE_SUPPORTED_CURVES
  10686. if (!ssl->options.noPskDheKe) {
  10687. ssl->error = TLSX_KeyShare_DeriveSecret(ssl);
  10688. if (ssl->error != 0)
  10689. return WOLFSSL_FATAL_ERROR;
  10690. }
  10691. #endif
  10692. if ((ssl->error = SendTls13EncryptedExtensions(ssl)) != 0) {
  10693. WOLFSSL_ERROR(ssl->error);
  10694. return WOLFSSL_FATAL_ERROR;
  10695. }
  10696. ssl->options.acceptState = TLS13_SERVER_EXTENSIONS_SENT;
  10697. WOLFSSL_MSG("accept state SERVER_EXTENSIONS_SENT");
  10698. FALL_THROUGH;
  10699. case TLS13_SERVER_EXTENSIONS_SENT :
  10700. #ifndef NO_CERTS
  10701. if (!ssl->options.resuming) {
  10702. if (ssl->options.verifyPeer
  10703. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10704. && !ssl->options.verifyPostHandshake
  10705. #endif
  10706. ) {
  10707. ssl->error = SendTls13CertificateRequest(ssl, NULL, 0);
  10708. if (ssl->error != 0) {
  10709. WOLFSSL_ERROR(ssl->error);
  10710. return WOLFSSL_FATAL_ERROR;
  10711. }
  10712. }
  10713. else {
  10714. /* SERVER: Peer auth good if not verifying client. */
  10715. ssl->options.peerAuthGood = 1;
  10716. }
  10717. }
  10718. #endif
  10719. ssl->options.acceptState = TLS13_CERT_REQ_SENT;
  10720. WOLFSSL_MSG("accept state CERT_REQ_SENT");
  10721. FALL_THROUGH;
  10722. case TLS13_CERT_REQ_SENT :
  10723. #ifndef NO_CERTS
  10724. if (!ssl->options.resuming && ssl->options.sendVerify) {
  10725. if ((ssl->error = SendTls13Certificate(ssl)) != 0) {
  10726. WOLFSSL_ERROR(ssl->error);
  10727. return WOLFSSL_FATAL_ERROR;
  10728. }
  10729. }
  10730. #endif
  10731. ssl->options.acceptState = TLS13_CERT_SENT;
  10732. WOLFSSL_MSG("accept state CERT_SENT");
  10733. FALL_THROUGH;
  10734. case TLS13_CERT_SENT :
  10735. #if !defined(NO_CERTS) && (!defined(NO_RSA) || defined(HAVE_ECC) || \
  10736. defined(HAVE_ED25519) || defined(HAVE_ED448) || defined(HAVE_PQC))
  10737. if (!ssl->options.resuming && ssl->options.sendVerify) {
  10738. if ((ssl->error = SendTls13CertificateVerify(ssl)) != 0) {
  10739. WOLFSSL_ERROR(ssl->error);
  10740. return WOLFSSL_FATAL_ERROR;
  10741. }
  10742. }
  10743. #endif
  10744. ssl->options.acceptState = TLS13_CERT_VERIFY_SENT;
  10745. WOLFSSL_MSG("accept state CERT_VERIFY_SENT");
  10746. FALL_THROUGH;
  10747. case TLS13_CERT_VERIFY_SENT :
  10748. if ((ssl->error = SendTls13Finished(ssl)) != 0) {
  10749. WOLFSSL_ERROR(ssl->error);
  10750. return WOLFSSL_FATAL_ERROR;
  10751. }
  10752. ssl->options.acceptState = TLS13_ACCEPT_FINISHED_SENT;
  10753. WOLFSSL_MSG("accept state ACCEPT_FINISHED_SENT");
  10754. #ifdef WOLFSSL_EARLY_DATA
  10755. if (ssl->earlyData != no_early_data) {
  10756. ssl->options.handShakeState = SERVER_FINISHED_COMPLETE;
  10757. return WOLFSSL_SUCCESS;
  10758. }
  10759. #endif
  10760. FALL_THROUGH;
  10761. case TLS13_ACCEPT_FINISHED_SENT :
  10762. #ifdef HAVE_SESSION_TICKET
  10763. #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
  10764. if (!ssl->options.verifyPeer && !ssl->options.noTicketTls13 &&
  10765. ssl->ctx->ticketEncCb != NULL) {
  10766. if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
  10767. WOLFSSL_ERROR(ssl->error);
  10768. return WOLFSSL_FATAL_ERROR;
  10769. }
  10770. ssl->options.ticketsSent = 1;
  10771. }
  10772. #endif
  10773. #endif /* HAVE_SESSION_TICKET */
  10774. ssl->options.acceptState = TLS13_PRE_TICKET_SENT;
  10775. WOLFSSL_MSG("accept state TICKET_SENT");
  10776. FALL_THROUGH;
  10777. case TLS13_PRE_TICKET_SENT :
  10778. while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
  10779. if ( (ssl->error = ProcessReply(ssl)) < 0) {
  10780. WOLFSSL_ERROR(ssl->error);
  10781. return WOLFSSL_FATAL_ERROR;
  10782. }
  10783. #ifdef WOLFSSL_DTLS13
  10784. if (ssl->options.dtls) {
  10785. if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
  10786. WOLFSSL_ERROR(ssl->error);
  10787. return WOLFSSL_FATAL_ERROR;
  10788. }
  10789. }
  10790. #endif /* WOLFSSL_DTLS13 */
  10791. }
  10792. ssl->options.acceptState = TLS13_ACCEPT_FINISHED_DONE;
  10793. WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
  10794. FALL_THROUGH;
  10795. case TLS13_ACCEPT_FINISHED_DONE :
  10796. /* SERVER: When not resuming and verifying peer but no certificate
  10797. * received and not failing when not received then peer auth good.
  10798. */
  10799. if (!ssl->options.resuming && ssl->options.verifyPeer &&
  10800. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10801. !ssl->options.verifyPostHandshake &&
  10802. #endif
  10803. !ssl->options.havePeerCert && !ssl->options.failNoCert) {
  10804. ssl->options.peerAuthGood = 1;
  10805. }
  10806. /* SERVER: check peer authentication. */
  10807. if (!ssl->options.peerAuthGood) {
  10808. WOLFSSL_MSG("Client authentication did not happen");
  10809. return WOLFSSL_FATAL_ERROR;
  10810. }
  10811. #ifdef HAVE_SESSION_TICKET
  10812. while (ssl->options.ticketsSent < ssl->options.maxTicketTls13) {
  10813. if (!ssl->options.noTicketTls13 && ssl->ctx->ticketEncCb
  10814. != NULL) {
  10815. if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
  10816. WOLFSSL_ERROR(ssl->error);
  10817. return WOLFSSL_FATAL_ERROR;
  10818. }
  10819. }
  10820. ssl->options.ticketsSent++;
  10821. /* only one session ticket is sent on session resumption */
  10822. if (ssl->options.resuming) {
  10823. break;
  10824. }
  10825. }
  10826. #endif /* HAVE_SESSION_TICKET */
  10827. ssl->options.acceptState = TLS13_TICKET_SENT;
  10828. WOLFSSL_MSG("accept state TICKET_SENT");
  10829. FALL_THROUGH;
  10830. case TLS13_TICKET_SENT :
  10831. #ifndef NO_HANDSHAKE_DONE_CB
  10832. if (ssl->hsDoneCb) {
  10833. int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
  10834. if (cbret < 0) {
  10835. ssl->error = cbret;
  10836. WOLFSSL_MSG("HandShake Done Cb don't continue error");
  10837. return WOLFSSL_FATAL_ERROR;
  10838. }
  10839. }
  10840. #endif /* NO_HANDSHAKE_DONE_CB */
  10841. if (!ssl->options.keepResources) {
  10842. FreeHandshakeResources(ssl);
  10843. }
  10844. #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
  10845. /* Free the remaining async context if not using it for crypto */
  10846. FreeAsyncCtx(ssl, 1);
  10847. #endif
  10848. ssl->error = 0; /* clear the error */
  10849. WOLFSSL_LEAVE("SSL_accept()", WOLFSSL_SUCCESS);
  10850. return WOLFSSL_SUCCESS;
  10851. default :
  10852. WOLFSSL_MSG("Unknown accept state ERROR");
  10853. return WOLFSSL_FATAL_ERROR;
  10854. }
  10855. }
  10856. #endif
  10857. #if !defined(NO_WOLFSSL_SERVER) && defined(HAVE_SESSION_TICKET)
  10858. /* Server sends a session ticket to the peer.
  10859. *
  10860. * RFC 8446, section 4.6.1, para 1.
  10861. *
  10862. * ssl The SSL/TLS object.
  10863. * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
  10864. * SIDE_ERROR when not a server,
  10865. * NOT_READY_ERROR when handshake not complete,
  10866. * WOLFSSL_FATAL_ERROR when creating or sending message fails, and
  10867. * WOLFSSL_SUCCESS on success.
  10868. */
  10869. int wolfSSL_send_SessionTicket(WOLFSSL* ssl)
  10870. {
  10871. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  10872. return BAD_FUNC_ARG;
  10873. if (ssl->options.side == WOLFSSL_CLIENT_END)
  10874. return SIDE_ERROR;
  10875. if (ssl->options.handShakeState != HANDSHAKE_DONE)
  10876. return NOT_READY_ERROR;
  10877. if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
  10878. WOLFSSL_ERROR(ssl->error);
  10879. return WOLFSSL_FATAL_ERROR;
  10880. }
  10881. ssl->options.ticketsSent++;
  10882. return WOLFSSL_SUCCESS;
  10883. }
  10884. #endif
  10885. #ifdef WOLFSSL_EARLY_DATA
  10886. /* Sets the maximum amount of early data that can be seen by server when using
  10887. * session tickets for resumption.
  10888. * A value of zero indicates no early data is to be sent by client using session
  10889. * tickets.
  10890. *
  10891. * ctx The SSL/TLS CTX object.
  10892. * sz Maximum size of the early data.
  10893. * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
  10894. * 0 on success.
  10895. */
  10896. int wolfSSL_CTX_set_max_early_data(WOLFSSL_CTX* ctx, unsigned int sz)
  10897. {
  10898. if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
  10899. return BAD_FUNC_ARG;
  10900. if (ctx->method->side == WOLFSSL_CLIENT_END)
  10901. return SIDE_ERROR;
  10902. ctx->maxEarlyDataSz = sz;
  10903. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_ERROR_CODE_OPENSSL)
  10904. /* 1 on success in OpenSSL*/
  10905. return WOLFSSL_SUCCESS;
  10906. #else
  10907. return 0;
  10908. #endif
  10909. }
  10910. /* Sets the maximum amount of early data that can be seen by server when using
  10911. * session tickets for resumption.
  10912. * A value of zero indicates no early data is to be sent by client using session
  10913. * tickets.
  10914. *
  10915. * ssl The SSL/TLS object.
  10916. * sz Maximum size of the early data.
  10917. * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
  10918. * SIDE_ERROR when not a server and 0 on success.
  10919. */
  10920. int wolfSSL_set_max_early_data(WOLFSSL* ssl, unsigned int sz)
  10921. {
  10922. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  10923. return BAD_FUNC_ARG;
  10924. if (ssl->options.side == WOLFSSL_CLIENT_END)
  10925. return SIDE_ERROR;
  10926. ssl->options.maxEarlyDataSz = sz;
  10927. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_ERROR_CODE_OPENSSL)
  10928. /* 1 on success in OpenSSL*/
  10929. return WOLFSSL_SUCCESS;
  10930. #else
  10931. return 0;
  10932. #endif
  10933. }
  10934. /* Gets the maximum amount of early data that can be seen by server when using
  10935. * session tickets for resumption.
  10936. * A value of zero indicates no early data is to be sent by client using session
  10937. * tickets.
  10938. *
  10939. * ctx The SSL/TLS CTX object.
  10940. * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
  10941. * returns the maximum amount of early data to be set
  10942. */
  10943. int wolfSSL_CTX_get_max_early_data(WOLFSSL_CTX* ctx)
  10944. {
  10945. if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
  10946. return BAD_FUNC_ARG;
  10947. if (ctx->method->side == WOLFSSL_CLIENT_END)
  10948. return SIDE_ERROR;
  10949. return ctx->maxEarlyDataSz;
  10950. }
  10951. /* Gets the maximum amount of early data that can be seen by server when using
  10952. * session tickets for resumption.
  10953. * A value of zero indicates no early data is to be sent by client using session
  10954. * tickets.
  10955. *
  10956. * ssl The SSL/TLS object.
  10957. * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
  10958. * SIDE_ERROR when not a server and
  10959. * returns the maximum amount of early data to be set
  10960. */
  10961. int wolfSSL_get_max_early_data(WOLFSSL* ssl)
  10962. {
  10963. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  10964. return BAD_FUNC_ARG;
  10965. if (ssl->options.side == WOLFSSL_CLIENT_END)
  10966. return SIDE_ERROR;
  10967. return ssl->options.maxEarlyDataSz;
  10968. }
  10969. /* Write early data to the server.
  10970. *
  10971. * ssl The SSL/TLS object.
  10972. * data Early data to write
  10973. * sz The size of the early data in bytes.
  10974. * outSz The number of early data bytes written.
  10975. * returns BAD_FUNC_ARG when: ssl, data or outSz is NULL; sz is negative;
  10976. * or not using TLS v1.3. SIDE ERROR when not a server. Otherwise the number of
  10977. * early data bytes written.
  10978. */
  10979. int wolfSSL_write_early_data(WOLFSSL* ssl, const void* data, int sz, int* outSz)
  10980. {
  10981. int ret = 0;
  10982. WOLFSSL_ENTER("SSL_write_early_data()");
  10983. if (ssl == NULL || data == NULL || sz < 0 || outSz == NULL)
  10984. return BAD_FUNC_ARG;
  10985. if (!IsAtLeastTLSv1_3(ssl->version))
  10986. return BAD_FUNC_ARG;
  10987. #ifndef NO_WOLFSSL_CLIENT
  10988. if (ssl->options.side == WOLFSSL_SERVER_END)
  10989. return SIDE_ERROR;
  10990. if (ssl->options.handShakeState == NULL_STATE) {
  10991. if (ssl->error != WC_PENDING_E)
  10992. ssl->earlyData = expecting_early_data;
  10993. ret = wolfSSL_connect_TLSv13(ssl);
  10994. if (ret != WOLFSSL_SUCCESS)
  10995. return WOLFSSL_FATAL_ERROR;
  10996. /* on client side, status is set to rejected */
  10997. /* until sever accepts the early data extension. */
  10998. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_REJECTED;
  10999. }
  11000. if (ssl->options.handShakeState == CLIENT_HELLO_COMPLETE) {
  11001. #ifdef OPENSSL_EXTRA
  11002. /* when processed early data exceeds max size */
  11003. if (ssl->session->maxEarlyDataSz > 0 &&
  11004. (ssl->earlyDataSz + sz > ssl->session->maxEarlyDataSz)) {
  11005. ssl->error = TOO_MUCH_EARLY_DATA;
  11006. return WOLFSSL_FATAL_ERROR;
  11007. }
  11008. #endif
  11009. ret = SendData(ssl, data, sz);
  11010. if (ret > 0) {
  11011. *outSz = ret;
  11012. /* store amount of processed early data from client */
  11013. ssl->earlyDataSz += ret;
  11014. }
  11015. }
  11016. #else
  11017. return SIDE_ERROR;
  11018. #endif
  11019. WOLFSSL_LEAVE("SSL_write_early_data()", ret);
  11020. if (ret < 0)
  11021. ret = WOLFSSL_FATAL_ERROR;
  11022. return ret;
  11023. }
  11024. /* Read the any early data from the client.
  11025. *
  11026. * ssl The SSL/TLS object.
  11027. * data Buffer to put the early data into.
  11028. * sz The size of the buffer in bytes.
  11029. * outSz The number of early data bytes read.
  11030. * returns BAD_FUNC_ARG when: ssl, data or outSz is NULL; sz is negative;
  11031. * or not using TLS v1.3. SIDE ERROR when not a server. Otherwise the number of
  11032. * early data bytes read.
  11033. */
  11034. int wolfSSL_read_early_data(WOLFSSL* ssl, void* data, int sz, int* outSz)
  11035. {
  11036. int ret = 0;
  11037. WOLFSSL_ENTER("wolfSSL_read_early_data()");
  11038. if (ssl == NULL || data == NULL || sz < 0 || outSz == NULL)
  11039. return BAD_FUNC_ARG;
  11040. if (!IsAtLeastTLSv1_3(ssl->version))
  11041. return BAD_FUNC_ARG;
  11042. #ifndef NO_WOLFSSL_SERVER
  11043. if (ssl->options.side == WOLFSSL_CLIENT_END)
  11044. return SIDE_ERROR;
  11045. if (ssl->options.handShakeState == NULL_STATE) {
  11046. if (ssl->error != WC_PENDING_E)
  11047. ssl->earlyData = expecting_early_data;
  11048. ret = wolfSSL_accept_TLSv13(ssl);
  11049. if (ret <= 0)
  11050. return WOLFSSL_FATAL_ERROR;
  11051. }
  11052. if (ssl->options.handShakeState == SERVER_FINISHED_COMPLETE) {
  11053. ret = ReceiveData(ssl, (byte*)data, sz, FALSE);
  11054. if (ret > 0)
  11055. *outSz = ret;
  11056. if (ssl->error == ZERO_RETURN) {
  11057. ssl->error = WOLFSSL_ERROR_NONE;
  11058. #ifdef WOLFSSL_DTLS13
  11059. if (ssl->options.dtls) {
  11060. ret = Dtls13DoScheduledWork(ssl);
  11061. if (ret < 0) {
  11062. ssl->error = ret;
  11063. WOLFSSL_ERROR(ssl->error);
  11064. return WOLFSSL_FATAL_ERROR;
  11065. }
  11066. }
  11067. #endif /* WOLFSSL_DTLS13 */
  11068. }
  11069. }
  11070. else
  11071. ret = 0;
  11072. #else
  11073. return SIDE_ERROR;
  11074. #endif
  11075. WOLFSSL_LEAVE("wolfSSL_read_early_data()", ret);
  11076. if (ret < 0)
  11077. ret = WOLFSSL_FATAL_ERROR;
  11078. return ret;
  11079. }
  11080. /* Returns early data status
  11081. *
  11082. * ssl The SSL/TLS object.
  11083. * returns WOLFSSL_EARLY_DATA_ACCEPTED if the data was accepted
  11084. * WOLFSSL_EARLY_DATA_REJECTED if the data was rejected
  11085. * WOLFSSL_EARLY_DATA_NOT_SENT if no early data was sent
  11086. */
  11087. int wolfSSL_get_early_data_status(const WOLFSSL* ssl)
  11088. {
  11089. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  11090. return BAD_FUNC_ARG;
  11091. return ssl->earlyDataStatus;
  11092. }
  11093. #endif
  11094. #ifdef HAVE_SECRET_CALLBACK
  11095. int wolfSSL_set_tls13_secret_cb(WOLFSSL* ssl, Tls13SecretCb cb, void* ctx)
  11096. {
  11097. WOLFSSL_ENTER("wolfSSL_set_tls13_secret_cb");
  11098. if (ssl == NULL)
  11099. return WOLFSSL_FATAL_ERROR;
  11100. ssl->tls13SecretCb = cb;
  11101. ssl->tls13SecretCtx = ctx;
  11102. return WOLFSSL_SUCCESS;
  11103. }
  11104. #endif
  11105. #undef ERROR_OUT
  11106. #endif /* !WOLFCRYPT_ONLY */
  11107. #endif /* WOLFSSL_TLS13 */