1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420 |
- /* internal.c
- *
- * Copyright (C) 2006-2020 wolfSSL Inc.
- *
- * This file is part of wolfSSL.
- *
- * wolfSSL is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * wolfSSL is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
- */
- #ifdef HAVE_CONFIG_H
- #include <config.h>
- #endif
- #include <wolfssl/wolfcrypt/settings.h>
- /*
- * WOLFSSL_SMALL_CERT_VERIFY:
- * Verify the certificate signature without using DecodedCert. Doubles up
- * on some code but allows smaller peak heap memory usage.
- * Cannot be used with WOLFSSL_NONBLOCK_OCSP.
- * WOLFSSL_ALT_CERT_CHAINS:
- * Allows CA's to be presented by peer, but not part of a valid chain.
- * Default wolfSSL behavior is to require validation of all presented peer
- * certificates. This also allows loading intermediate CA's as trusted
- * and ignoring no signer failures for CA's up the chain to root.
- */
- #ifdef EXTERNAL_OPTS_OPENVPN
- #error EXTERNAL_OPTS_OPENVPN should not be defined\
- when building wolfSSL
- #endif
- #ifndef WOLFCRYPT_ONLY
- #include <wolfssl/internal.h>
- #include <wolfssl/error-ssl.h>
- #include <wolfssl/wolfcrypt/asn.h>
- #include <wolfssl/wolfcrypt/dh.h>
- #ifdef NO_INLINE
- #include <wolfssl/wolfcrypt/misc.h>
- #else
- #define WOLFSSL_MISC_INCLUDED
- #include <wolfcrypt/src/misc.c>
- #endif
- #if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA)
- #include <wolfssl/wolfcrypt/srp.h>
- #endif
- #ifdef HAVE_LIBZ
- #include "zlib.h"
- #endif
- #ifdef HAVE_NTRU
- #include "libntruencrypt/ntru_crypto.h"
- #endif
- #if defined(DEBUG_WOLFSSL) || defined(SHOW_SECRETS) || \
- defined(CHACHA_AEAD_TEST) || defined(WOLFSSL_SESSION_EXPORT_DEBUG)
- #ifndef NO_STDIO_FILESYSTEM
- #include <stdio.h>
- #endif
- #endif
- #ifdef __sun
- #include <sys/filio.h>
- #endif
- #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
- #ifdef _MSC_VER
- /* disable for while(0) cases at the .c level for now */
- #pragma warning(disable:4127)
- #endif
- #if defined(WOLFSSL_CALLBACKS) && !defined(LARGE_STATIC_BUFFERS)
- #error \
- WOLFSSL_CALLBACKS needs LARGE_STATIC_BUFFERS, please add LARGE_STATIC_BUFFERS
- #endif
- #if defined(HAVE_SECURE_RENEGOTIATION) && defined(HAVE_RENEGOTIATION_INDICATION)
- #error Cannot use both secure-renegotiation and renegotiation-indication
- #endif
- #ifndef WOLFSSL_NO_TLS12
- #ifndef NO_WOLFSSL_CLIENT
- static int DoHelloVerifyRequest(WOLFSSL* ssl, const byte* input, word32*,
- word32);
- static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, word32*,
- word32);
- #ifndef NO_CERTS
- static int DoCertificateRequest(WOLFSSL* ssl, const byte* input, word32*,
- word32);
- #endif
- #ifdef HAVE_SESSION_TICKET
- static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32*,
- word32);
- #endif
- #endif
- #ifndef NO_WOLFSSL_SERVER
- static int DoClientKeyExchange(WOLFSSL* ssl, byte* input, word32*, word32);
- #if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
- defined(HAVE_ED448)) && !defined(WOLFSSL_NO_CLIENT_AUTH)
- static int DoCertificateVerify(WOLFSSL* ssl, byte*, word32*, word32);
- #endif
- #ifdef WOLFSSL_DTLS
- static int SendHelloVerifyRequest(WOLFSSL*, const byte*, byte);
- #endif /* WOLFSSL_DTLS */
- #endif
- #endif /* !WOLFSSL_NO_TLS12 */
- #ifdef WOLFSSL_DTLS
- static WC_INLINE int DtlsCheckWindow(WOLFSSL* ssl);
- static WC_INLINE int DtlsUpdateWindow(WOLFSSL* ssl);
- #endif
- enum processReply {
- doProcessInit = 0,
- #ifndef NO_WOLFSSL_SERVER
- runProcessOldClientHello,
- #endif
- getRecordLayerHeader,
- getData,
- verifyEncryptedMessage,
- decryptMessage,
- verifyMessage,
- runProcessingOneMessage
- };
- #ifndef WOLFSSL_NO_TLS12
- #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT)
- /* Server random bytes for TLS v1.3 described downgrade protection mechanism. */
- static const byte tls13Downgrade[7] = {
- 0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44
- };
- #define TLS13_DOWNGRADE_SZ sizeof(tls13Downgrade)
- #endif /* !NO_WOLFSSL_SERVER || !NO_WOLFSSL_CLIENT */
- #if !defined(NO_OLD_TLS) && !defined(WOLFSSL_AEAD_ONLY)
- static int SSL_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz,
- int padSz, int content, int verify);
- #endif
- #endif /* !WOLFSSL_NO_TLS12 */
- #ifdef HAVE_QSH
- int QSH_Init(WOLFSSL* ssl);
- #endif
- #ifdef WOLFSSL_RENESAS_TSIP_TLS
- int tsip_useable(const WOLFSSL *ssl);
- int tsip_generatePremasterSecret();
- int tsip_generateEncryptPreMasterSecret(WOLFSSL *ssl, byte *out, word32 *outSz);
- #endif
- int IsTLS(const WOLFSSL* ssl)
- {
- if (ssl->version.major == SSLv3_MAJOR && ssl->version.minor >=TLSv1_MINOR)
- return 1;
- return 0;
- }
- int IsAtLeastTLSv1_2(const WOLFSSL* ssl)
- {
- if (ssl->version.major == SSLv3_MAJOR && ssl->version.minor >=TLSv1_2_MINOR)
- return 1;
- #ifdef WOLFSSL_DTLS
- if (ssl->version.major == DTLS_MAJOR && ssl->version.minor <= DTLSv1_2_MINOR)
- return 1;
- #endif
- return 0;
- }
- int IsAtLeastTLSv1_3(const ProtocolVersion pv)
- {
- return (pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_3_MINOR);
- }
- static WC_INLINE int IsEncryptionOn(WOLFSSL* ssl, int isSend)
- {
- (void)isSend;
- #ifdef WOLFSSL_DTLS
- /* For DTLS, epoch 0 is always not encrypted. */
- if (ssl->options.dtls && !isSend && ssl->keys.curEpoch == 0)
- return 0;
- #endif /* WOLFSSL_DTLS */
- #ifdef WOLFSSL_TLS13
- if (isSend)
- return ssl->encrypt.setup;
- else
- return ssl->decrypt.setup;
- #else
- return ssl->keys.encryptionOn;
- #endif
- }
- #if defined(WOLFSSL_DTLS) || !defined(WOLFSSL_NO_TLS12)
- /* If SCTP is not enabled returns the state of the dtls option.
- * If SCTP is enabled returns dtls && !sctp. */
- static WC_INLINE int IsDtlsNotSctpMode(WOLFSSL* ssl)
- {
- int result = ssl->options.dtls;
- if (result) {
- #ifdef WOLFSSL_SCTP
- result = !ssl->options.dtlsSctp;
- #endif
- }
- return result;
- }
- #endif /* DTLS || !WOLFSSL_NO_TLS12 */
- #ifdef HAVE_QSH
- /* free all structs that where used with QSH */
- static int QSH_FreeAll(WOLFSSL* ssl)
- {
- QSHKey* key = ssl->QSH_Key;
- QSHKey* preKey = NULL;
- QSHSecret* secret = ssl->QSH_secret;
- QSHScheme* list = NULL;
- QSHScheme* preList = NULL;
- /* free elements in struct */
- while (key) {
- preKey = key;
- if (key->pri.buffer) {
- ForceZero(key->pri.buffer, key->pri.length);
- XFREE(key->pri.buffer, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
- }
- if (key->pub.buffer)
- XFREE(key->pub.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- key = (QSHKey*)key->next;
- /* free struct */
- XFREE(preKey, ssl->heap, DYNAMIC_TYPE_QSH);
- }
- /* free all of peers QSH keys */
- key = ssl->peerQSHKey;
- while (key) {
- preKey = key;
- if (key->pri.buffer) {
- ForceZero(key->pri.buffer, key->pri.length);
- XFREE(key->pri.buffer, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
- }
- if (key->pub.buffer)
- XFREE(key->pub.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- key = (QSHKey*)key->next;
- /* free struct */
- XFREE(preKey, ssl->heap, DYNAMIC_TYPE_QSH);
- }
- key = NULL;
- /* free secret information */
- if (secret) {
- /* free up the QSHScheme list in QSHSecret */
- if (secret->list)
- list = secret->list;
- while (list) {
- preList = list;
- if (list->PK)
- XFREE(list->PK, ssl->heap, DYNAMIC_TYPE_SECRET);
- list = (QSHScheme*)list->next;
- XFREE(preList, ssl->heap, DYNAMIC_TYPE_QSH);
- }
- /* free secret buffers */
- if (secret->SerSi) {
- if (secret->SerSi->buffer) {
- /* clear extra secret material that supplemented Master Secret*/
- ForceZero(secret->SerSi->buffer, secret->SerSi->length);
- XFREE(secret->SerSi->buffer, ssl->heap, DYNAMIC_TYPE_SECRET);
- }
- XFREE(secret->SerSi, ssl->heap, DYNAMIC_TYPE_SECRET);
- }
- if (secret->CliSi) {
- if (secret->CliSi->buffer) {
- /* clear extra secret material that supplemented Master Secret*/
- ForceZero(secret->CliSi->buffer, secret->CliSi->length);
- XFREE(secret->CliSi->buffer, ssl->heap, DYNAMIC_TYPE_SECRET);
- }
- XFREE(secret->CliSi, ssl->heap, DYNAMIC_TYPE_SECRET);
- }
- }
- XFREE(secret, ssl->heap, DYNAMIC_TYPE_QSH);
- secret = NULL;
- return 0;
- }
- #endif
- #ifdef HAVE_NTRU
- static WOLFSSL_GLOBAL WC_RNG* rng;
- static WOLFSSL_GLOBAL wolfSSL_Mutex* rngMutex;
- static word32 GetEntropy(unsigned char* out, word32 num_bytes)
- {
- int ret = 0;
- if (rng == NULL) {
- if ((rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), 0,
- DYNAMIC_TYPE_RNG)) == NULL)
- return DRBG_OUT_OF_MEMORY;
- wc_InitRng(rng);
- }
- if (rngMutex == NULL) {
- if ((rngMutex = (wolfSSL_Mutex*)XMALLOC(sizeof(wolfSSL_Mutex), 0,
- DYNAMIC_TYPE_MUTEX)) == NULL)
- return DRBG_OUT_OF_MEMORY;
- wc_InitMutex(rngMutex);
- }
- ret |= wc_LockMutex(rngMutex);
- ret |= wc_RNG_GenerateBlock(rng, out, num_bytes);
- ret |= wc_UnLockMutex(rngMutex);
- if (ret != 0)
- return DRBG_ENTROPY_FAIL;
- return DRBG_OK;
- }
- #endif /* HAVE_NTRU */
- #ifdef HAVE_LIBZ
- /* alloc user allocs to work with zlib */
- static void* myAlloc(void* opaque, unsigned int item, unsigned int size)
- {
- (void)opaque;
- return XMALLOC(item * size, opaque, DYNAMIC_TYPE_LIBZ);
- }
- static void myFree(void* opaque, void* memory)
- {
- (void)opaque;
- XFREE(memory, opaque, DYNAMIC_TYPE_LIBZ);
- }
- /* init zlib comp/decomp streams, 0 on success */
- static int InitStreams(WOLFSSL* ssl)
- {
- ssl->c_stream.zalloc = (alloc_func)myAlloc;
- ssl->c_stream.zfree = (free_func)myFree;
- ssl->c_stream.opaque = (voidpf)ssl->heap;
- if (deflateInit(&ssl->c_stream, Z_DEFAULT_COMPRESSION) != Z_OK)
- return ZLIB_INIT_ERROR;
- ssl->didStreamInit = 1;
- ssl->d_stream.zalloc = (alloc_func)myAlloc;
- ssl->d_stream.zfree = (free_func)myFree;
- ssl->d_stream.opaque = (voidpf)ssl->heap;
- if (inflateInit(&ssl->d_stream) != Z_OK) return ZLIB_INIT_ERROR;
- return 0;
- }
- static void FreeStreams(WOLFSSL* ssl)
- {
- if (ssl->didStreamInit) {
- deflateEnd(&ssl->c_stream);
- inflateEnd(&ssl->d_stream);
- }
- }
- /* compress in to out, return out size or error */
- static int myCompress(WOLFSSL* ssl, byte* in, int inSz, byte* out, int outSz)
- {
- int err;
- int currTotal = (int)ssl->c_stream.total_out;
- ssl->c_stream.next_in = in;
- ssl->c_stream.avail_in = inSz;
- ssl->c_stream.next_out = out;
- ssl->c_stream.avail_out = outSz;
- err = deflate(&ssl->c_stream, Z_SYNC_FLUSH);
- if (err != Z_OK && err != Z_STREAM_END) return ZLIB_COMPRESS_ERROR;
- return (int)ssl->c_stream.total_out - currTotal;
- }
- /* decompress in to out, return out size or error */
- static int myDeCompress(WOLFSSL* ssl, byte* in,int inSz, byte* out,int outSz)
- {
- int err;
- int currTotal = (int)ssl->d_stream.total_out;
- ssl->d_stream.next_in = in;
- ssl->d_stream.avail_in = inSz;
- ssl->d_stream.next_out = out;
- ssl->d_stream.avail_out = outSz;
- err = inflate(&ssl->d_stream, Z_SYNC_FLUSH);
- if (err != Z_OK && err != Z_STREAM_END) return ZLIB_DECOMPRESS_ERROR;
- return (int)ssl->d_stream.total_out - currTotal;
- }
- #endif /* HAVE_LIBZ */
- #ifdef WOLFSSL_SESSION_EXPORT
- #ifdef WOLFSSL_DTLS
- /* serializes the cipher specs struct for exporting */
- static int ExportCipherSpecState(WOLFSSL* ssl, byte* exp, word32 len, byte ver)
- {
- word32 idx = 0;
- CipherSpecs* specs;
- WOLFSSL_ENTER("ExportCipherSpecState");
- if (exp == NULL || ssl == NULL) {
- return BAD_FUNC_ARG;
- }
- specs= &(ssl->specs);
- if (DTLS_EXPORT_SPC_SZ > len) {
- return BUFFER_E;
- }
- XMEMSET(exp, 0, DTLS_EXPORT_SPC_SZ);
- c16toa(specs->key_size, exp + idx); idx += OPAQUE16_LEN;
- c16toa(specs->iv_size, exp + idx); idx += OPAQUE16_LEN;
- c16toa(specs->block_size, exp + idx); idx += OPAQUE16_LEN;
- c16toa(specs->aead_mac_size, exp + idx); idx += OPAQUE16_LEN;
- exp[idx++] = specs->bulk_cipher_algorithm;
- exp[idx++] = specs->cipher_type;
- exp[idx++] = specs->mac_algorithm;
- exp[idx++] = specs->kea;
- exp[idx++] = specs->sig_algo;
- exp[idx++] = specs->hash_size;
- exp[idx++] = specs->pad_size;
- exp[idx++] = specs->static_ecdh;
- if (idx != DTLS_EXPORT_SPC_SZ) {
- WOLFSSL_MSG("DTLS_EXPORT_SPC_SZ needs updated and export version");
- return DTLS_EXPORT_VER_E;
- }
- WOLFSSL_LEAVE("ExportCipherSpecState", idx);
- (void)ver;
- return idx;
- }
- /* serializes the key struct for exporting */
- static int ExportKeyState(WOLFSSL* ssl, byte* exp, word32 len, byte ver,
- byte small)
- {
- word32 idx = 0;
- byte sz;
- Keys* keys;
- WOLFSSL_ENTER("ExportKeyState");
- if (exp == NULL || ssl == NULL) {
- return BAD_FUNC_ARG;
- }
- keys = &(ssl->keys);
- if (DTLS_EXPORT_MIN_KEY_SZ > len) {
- WOLFSSL_MSG("Buffer not large enough for minimum key struct size");
- return BUFFER_E;
- }
- XMEMSET(exp, 0, DTLS_EXPORT_MIN_KEY_SZ);
- c32toa(keys->peer_sequence_number_hi, exp + idx); idx += OPAQUE32_LEN;
- c32toa(keys->peer_sequence_number_lo, exp + idx); idx += OPAQUE32_LEN;
- c32toa(keys->sequence_number_hi, exp + idx); idx += OPAQUE32_LEN;
- c32toa(keys->sequence_number_lo, exp + idx); idx += OPAQUE32_LEN;
- c16toa(keys->peerSeq[0].nextEpoch, exp + idx); idx += OPAQUE16_LEN;
- c16toa(keys->peerSeq[0].nextSeq_hi, exp + idx); idx += OPAQUE16_LEN;
- c32toa(keys->peerSeq[0].nextSeq_lo, exp + idx); idx += OPAQUE32_LEN;
- c16toa(keys->curEpoch, exp + idx); idx += OPAQUE16_LEN;
- c16toa(keys->curSeq_hi, exp + idx); idx += OPAQUE16_LEN;
- c32toa(keys->curSeq_lo, exp + idx); idx += OPAQUE32_LEN;
- c16toa(keys->peerSeq[0].prevSeq_hi, exp + idx); idx += OPAQUE16_LEN;
- c32toa(keys->peerSeq[0].prevSeq_lo, exp + idx); idx += OPAQUE32_LEN;
- c16toa(keys->dtls_peer_handshake_number, exp + idx); idx += OPAQUE16_LEN;
- c16toa(keys->dtls_expected_peer_handshake_number, exp + idx);
- idx += OPAQUE16_LEN;
- c16toa(keys->dtls_sequence_number_hi, exp + idx); idx += OPAQUE16_LEN;
- c32toa(keys->dtls_sequence_number_lo, exp + idx); idx += OPAQUE32_LEN;
- c16toa(keys->dtls_prev_sequence_number_hi, exp + idx); idx += OPAQUE16_LEN;
- c32toa(keys->dtls_prev_sequence_number_lo, exp + idx); idx += OPAQUE32_LEN;
- c16toa(keys->dtls_epoch, exp + idx); idx += OPAQUE16_LEN;
- c16toa(keys->dtls_handshake_number, exp + idx); idx += OPAQUE16_LEN;
- c32toa(keys->encryptSz, exp + idx); idx += OPAQUE32_LEN;
- c32toa(keys->padSz, exp + idx); idx += OPAQUE32_LEN;
- exp[idx++] = keys->encryptionOn;
- exp[idx++] = keys->decryptedCur;
- /* from here on the buffer needs checked because is variable length that
- * can be larger than DTLS_EXPORT_MIN_KEY_SZ */
- {
- word32 i;
- if ((OPAQUE16_LEN * 2) + idx +
- (2 * (WOLFSSL_DTLS_WINDOW_WORDS * OPAQUE32_LEN)) > len) {
- WOLFSSL_MSG("Buffer not large enough for WOLFSSL_DTLS_WINDOW_WORDS");
- return BUFFER_E;
- }
- c16toa(WOLFSSL_DTLS_WINDOW_WORDS, exp + idx); idx += OPAQUE16_LEN;
- for (i = 0; i < WOLFSSL_DTLS_WINDOW_WORDS; i++) {
- c32toa(keys->peerSeq[0].window[i], exp + idx);
- idx += OPAQUE32_LEN;
- }
- c16toa(WOLFSSL_DTLS_WINDOW_WORDS, exp + idx); idx += OPAQUE16_LEN;
- for (i = 0; i < WOLFSSL_DTLS_WINDOW_WORDS; i++) {
- c32toa(keys->peerSeq[0].prevWindow[i], exp + idx);
- idx += OPAQUE32_LEN;
- }
- }
- if (idx >= len) {
- WOLFSSL_MSG("Buffer not large enough for truncated hmac flag");
- return BUFFER_E;
- }
- #ifdef HAVE_TRUNCATED_HMAC
- sz = ssl->truncated_hmac ? TRUNCATED_HMAC_SZ: ssl->specs.hash_size;
- exp[idx++] = ssl->truncated_hmac;
- #else
- sz = ssl->specs.hash_size;
- exp[idx++] = 0; /* no truncated hmac */
- #endif
- sz = (small)? 0: sz;
- if (idx + (sz * 2) + OPAQUE8_LEN > len) {
- WOLFSSL_MSG("Buffer not large enough for MAC secret");
- return BUFFER_E;
- }
- exp[idx++] = sz;
- if (sz > 0) {
- #ifndef WOLFSSL_AEAD_ONLY
- XMEMCPY(exp + idx, keys->client_write_MAC_secret, sz); idx += sz;
- XMEMCPY(exp + idx, keys->server_write_MAC_secret, sz); idx += sz;
- #else
- XMEMSET(exp + idx, 0, sz); idx += sz;
- XMEMSET(exp + idx, 0, sz); idx += sz;
- #endif
- }
- sz = (small)? 0: ssl->specs.key_size;
- if (idx + (sz * 2) + OPAQUE8_LEN > len) {
- WOLFSSL_MSG("Buffer not large enough for write key");
- return BUFFER_E;
- }
- exp[idx++] = sz;
- if (sz > 0) {
- XMEMCPY(exp + idx, keys->client_write_key, sz); idx += sz;
- XMEMCPY(exp + idx, keys->server_write_key, sz); idx += sz;
- }
- sz = (small)? 0: ssl->specs.iv_size;
- if (idx + (sz * 2) + OPAQUE8_LEN + AEAD_MAX_EXP_SZ > len) {
- WOLFSSL_MSG("Buffer not large enough for IVs");
- return BUFFER_E;
- }
- exp[idx++] = sz;
- if (sz > 0) {
- XMEMCPY(exp + idx, keys->client_write_IV, sz); idx += sz;
- XMEMCPY(exp + idx, keys->server_write_IV, sz); idx += sz;
- }
- XMEMCPY(exp + idx, keys->aead_exp_IV, AEAD_MAX_EXP_SZ);
- idx += AEAD_MAX_EXP_SZ;
- sz = (small)? 0: AEAD_MAX_IMP_SZ;
- if (idx + (sz * 2) + OPAQUE8_LEN > len) {
- WOLFSSL_MSG("Buffer not large enough for imp IVs");
- return BUFFER_E;
- }
- exp[idx++] = sz;
- if (sz > 0) {
- XMEMCPY(exp + idx, keys->aead_enc_imp_IV, sz); idx += sz;
- XMEMCPY(exp + idx, keys->aead_dec_imp_IV, sz); idx += sz;
- }
- /* DTLS_EXPORT_KEY_SZ is max value. idx size can vary */
- if (idx > DTLS_EXPORT_KEY_SZ) {
- WOLFSSL_MSG("DTLS_EXPORT_KEY_SZ needs updated and export version");
- return DTLS_EXPORT_VER_E;
- }
- WOLFSSL_LEAVE("ExportKeyState", idx);
- (void)ver;
- return idx;
- }
- static int ImportCipherSpecState(WOLFSSL* ssl, byte* exp, word32 len, byte ver)
- {
- word32 idx = 0;
- CipherSpecs* specs;
- WOLFSSL_ENTER("ImportCipherSpecState");
- if (exp == NULL || ssl == NULL) {
- return BAD_FUNC_ARG;
- }
- specs= &(ssl->specs);
- if (DTLS_EXPORT_SPC_SZ > len) {
- WOLFSSL_MSG("Buffer not large enough for max spec struct size");
- return BUFFER_E;
- }
- ato16(exp + idx, &specs->key_size); idx += OPAQUE16_LEN;
- ato16(exp + idx, &specs->iv_size); idx += OPAQUE16_LEN;
- ato16(exp + idx, &specs->block_size); idx += OPAQUE16_LEN;
- ato16(exp + idx, &specs->aead_mac_size); idx += OPAQUE16_LEN;
- specs->bulk_cipher_algorithm = exp[idx++];
- specs->cipher_type = exp[idx++];
- specs->mac_algorithm = exp[idx++];
- specs->kea = exp[idx++];
- specs->sig_algo = exp[idx++];
- specs->hash_size = exp[idx++];
- specs->pad_size = exp[idx++];
- specs->static_ecdh = exp[idx++];
- WOLFSSL_LEAVE("ImportCipherSpecState", idx);
- (void)ver;
- return idx;
- }
- static int ImportKeyState(WOLFSSL* ssl, byte* exp, word32 len, byte ver)
- {
- word32 idx = 0;
- byte sz;
- Keys* keys;
- WOLFSSL_ENTER("ImportKeyState");
- if (exp == NULL || ssl == NULL) {
- return BAD_FUNC_ARG;
- }
- keys = &(ssl->keys);
- /* check minimum length -- includes byte used for size indicators */
- if (len < DTLS_EXPORT_MIN_KEY_SZ) {
- WOLFSSL_MSG("Buffer not large enough for minimum expected size");
- return BUFFER_E;
- }
- ato32(exp + idx, &keys->peer_sequence_number_hi); idx += OPAQUE32_LEN;
- ato32(exp + idx, &keys->peer_sequence_number_lo); idx += OPAQUE32_LEN;
- ato32(exp + idx, &keys->sequence_number_hi); idx += OPAQUE32_LEN;
- ato32(exp + idx, &keys->sequence_number_lo); idx += OPAQUE32_LEN;
- ato16(exp + idx, &keys->peerSeq[0].nextEpoch); idx += OPAQUE16_LEN;
- ato16(exp + idx, &keys->peerSeq[0].nextSeq_hi); idx += OPAQUE16_LEN;
- ato32(exp + idx, &keys->peerSeq[0].nextSeq_lo); idx += OPAQUE32_LEN;
- ato16(exp + idx, &keys->curEpoch); idx += OPAQUE16_LEN;
- ato16(exp + idx, &keys->curSeq_hi); idx += OPAQUE16_LEN;
- ato32(exp + idx, &keys->curSeq_lo); idx += OPAQUE32_LEN;
- ato16(exp + idx, &keys->peerSeq[0].prevSeq_hi); idx += OPAQUE16_LEN;
- ato32(exp + idx, &keys->peerSeq[0].prevSeq_lo); idx += OPAQUE32_LEN;
- ato16(exp + idx, &keys->dtls_peer_handshake_number); idx += OPAQUE16_LEN;
- ato16(exp + idx, &keys->dtls_expected_peer_handshake_number);
- idx += OPAQUE16_LEN;
- ato16(exp + idx, &keys->dtls_sequence_number_hi); idx += OPAQUE16_LEN;
- ato32(exp + idx, &keys->dtls_sequence_number_lo); idx += OPAQUE32_LEN;
- ato16(exp + idx, &keys->dtls_prev_sequence_number_hi); idx += OPAQUE16_LEN;
- ato32(exp + idx, &keys->dtls_prev_sequence_number_lo); idx += OPAQUE32_LEN;
- ato16(exp + idx, &keys->dtls_epoch); idx += OPAQUE16_LEN;
- ato16(exp + idx, &keys->dtls_handshake_number); idx += OPAQUE16_LEN;
- ato32(exp + idx, &keys->encryptSz); idx += OPAQUE32_LEN;
- ato32(exp + idx, &keys->padSz); idx += OPAQUE32_LEN;
- keys->encryptionOn = exp[idx++];
- keys->decryptedCur = exp[idx++];
- {
- word16 i, wordCount, wordAdj = 0;
- /* do window */
- ato16(exp + idx, &wordCount);
- idx += OPAQUE16_LEN;
- if (wordCount > WOLFSSL_DTLS_WINDOW_WORDS) {
- wordCount = WOLFSSL_DTLS_WINDOW_WORDS;
- wordAdj = (WOLFSSL_DTLS_WINDOW_WORDS - wordCount) * sizeof(word32);
- }
- XMEMSET(keys->peerSeq[0].window, 0xFF, DTLS_SEQ_SZ);
- for (i = 0; i < wordCount; i++) {
- ato32(exp + idx, &keys->peerSeq[0].window[i]);
- idx += OPAQUE32_LEN;
- }
- idx += wordAdj;
- /* do prevWindow */
- ato16(exp + idx, &wordCount);
- idx += OPAQUE16_LEN;
- if (wordCount > WOLFSSL_DTLS_WINDOW_WORDS) {
- wordCount = WOLFSSL_DTLS_WINDOW_WORDS;
- wordAdj = (WOLFSSL_DTLS_WINDOW_WORDS - wordCount) * sizeof(word32);
- }
- XMEMSET(keys->peerSeq[0].prevWindow, 0xFF, DTLS_SEQ_SZ);
- for (i = 0; i < wordCount; i++) {
- ato32(exp + idx, &keys->peerSeq[0].prevWindow[i]);
- idx += OPAQUE32_LEN;
- }
- idx += wordAdj;
- }
- #ifdef HAVE_TRUNCATED_HMAC
- ssl->truncated_hmac = exp[idx++];
- #else
- idx++; /* no truncated hmac */
- #endif
- sz = exp[idx++];
- #ifndef WOLFSSL_AEAD_ONLY
- if (sz > sizeof(keys->client_write_MAC_secret) || (sz * 2) + idx > len) {
- WOLFSSL_MSG("Buffer not large enough for MAC import");
- return BUFFER_E;
- }
- if (sz > 0) {
- XMEMCPY(keys->client_write_MAC_secret, exp + idx, sz); idx += sz;
- XMEMCPY(keys->server_write_MAC_secret, exp + idx, sz); idx += sz;
- }
- #else
- if (sz + idx > len) {
- return BUFFER_E;
- }
- idx += sz; idx += sz;
- #endif
- sz = exp[idx++];
- if (sz > sizeof(keys->client_write_key) || (sz * 2) + idx > len) {
- WOLFSSL_MSG("Buffer not large enough for key import");
- return BUFFER_E;
- }
- if (sz > 0) {
- XMEMCPY(keys->client_write_key, exp + idx, sz); idx += sz;
- XMEMCPY(keys->server_write_key, exp + idx, sz); idx += sz;
- }
- sz = exp[idx++];
- if (sz > sizeof(keys->client_write_IV) || (sz * 2) + idx > len) {
- WOLFSSL_MSG("Buffer not large enough for write IV import");
- return BUFFER_E;
- }
- if (sz > 0) {
- XMEMCPY(keys->client_write_IV, exp + idx, sz); idx += sz;
- XMEMCPY(keys->server_write_IV, exp + idx, sz); idx += sz;
- }
- XMEMCPY(keys->aead_exp_IV, exp + idx, AEAD_MAX_EXP_SZ);
- idx += AEAD_MAX_EXP_SZ;
- sz = exp[idx++];
- if (sz > sizeof(keys->aead_enc_imp_IV) || (sz * 2) + idx > len) {
- WOLFSSL_MSG("Buffer not large enough for imp IV import");
- return BUFFER_E;
- }
- if (sz > 0) {
- XMEMCPY(keys->aead_enc_imp_IV, exp + idx, sz); idx += sz;
- XMEMCPY(keys->aead_dec_imp_IV, exp + idx, sz); idx += sz;
- }
- WOLFSSL_LEAVE("ImportKeyState", idx);
- (void)ver;
- return idx;
- }
- /* copy over necessary information from Options struct to buffer
- * On success returns size of buffer used on failure returns a negative value */
- static int dtls_export_new(WOLFSSL* ssl, byte* exp, word32 len, byte ver)
- {
- int idx = 0;
- word16 zero = 0;
- Options* options = &ssl->options;
- WOLFSSL_ENTER("dtls_export_new");
- if (exp == NULL || options == NULL || len < DTLS_EXPORT_OPT_SZ) {
- return BAD_FUNC_ARG;
- }
- XMEMSET(exp, 0, DTLS_EXPORT_OPT_SZ);
- /* these options are kept and sent to indicate verify status and strength
- * of handshake */
- exp[idx++] = options->sendVerify;
- exp[idx++] = options->verifyPeer;
- exp[idx++] = options->verifyNone;
- exp[idx++] = options->downgrade;
- #ifndef NO_DH
- c16toa(options->minDhKeySz, exp + idx); idx += OPAQUE16_LEN;
- c16toa(options->maxDhKeySz, exp + idx); idx += OPAQUE16_LEN;
- c16toa(options->dhKeySz, exp + idx); idx += OPAQUE16_LEN;
- #else
- c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
- c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
- c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
- #endif
- #ifndef NO_RSA
- c16toa((word16)(options->minRsaKeySz), exp + idx); idx += OPAQUE16_LEN;
- #else
- c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
- #endif
- #ifdef HAVE_ECC
- c16toa((word16)(options->minEccKeySz), exp + idx); idx += OPAQUE16_LEN;
- #else
- c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
- #endif
- /* these options are kept to indicate state and behavior */
- #ifndef NO_PSK
- exp[idx++] = options->havePSK;
- #else
- exp[idx++] = 0;
- #endif
- exp[idx++] = options->sessionCacheOff;
- exp[idx++] = options->sessionCacheFlushOff;
- exp[idx++] = options->side;
- exp[idx++] = options->resuming;
- exp[idx++] = options->haveSessionId;
- exp[idx++] = options->tls;
- exp[idx++] = options->tls1_1;
- exp[idx++] = options->dtls;
- exp[idx++] = options->connReset;
- exp[idx++] = options->isClosed;
- exp[idx++] = options->closeNotify;
- exp[idx++] = options->sentNotify;
- exp[idx++] = options->usingCompression;
- exp[idx++] = options->haveRSA;
- exp[idx++] = options->haveECC;
- exp[idx++] = options->haveDH;
- exp[idx++] = options->haveNTRU;
- exp[idx++] = options->haveQSH;
- exp[idx++] = options->haveECDSAsig;
- exp[idx++] = options->haveStaticECC;
- exp[idx++] = options->havePeerVerify;
- exp[idx++] = options->usingPSK_cipher;
- exp[idx++] = options->usingAnon_cipher;
- exp[idx++] = options->sendAlertState;
- exp[idx++] = options->partialWrite;
- exp[idx++] = options->quietShutdown;
- exp[idx++] = options->groupMessages;
- #ifdef HAVE_POLY1305
- exp[idx++] = options->oldPoly;
- #else
- exp[idx++] = 0;
- #endif
- #ifdef HAVE_ANON
- exp[idx++] = options->haveAnon;
- #else
- exp[idx++] = 0;
- #endif
- #ifdef HAVE_SESSION_TICKET
- exp[idx++] = options->createTicket;
- exp[idx++] = options->useTicket;
- #ifdef WOLFSSL_TLS13
- if (ver > DTLS_EXPORT_VERSION_3) {
- exp[idx++] = options->noTicketTls13;
- }
- #else
- if (ver > DTLS_EXPORT_VERSION_3) {
- exp[idx++] = 0;
- }
- #endif
- #else
- exp[idx++] = 0;
- exp[idx++] = 0;
- if (ver > DTLS_EXPORT_VERSION_3) {
- exp[idx++] = 0;
- }
- #endif
- exp[idx++] = options->processReply;
- exp[idx++] = options->cipherSuite0;
- exp[idx++] = options->cipherSuite;
- exp[idx++] = options->serverState;
- exp[idx++] = options->clientState;
- exp[idx++] = options->handShakeState;
- exp[idx++] = options->handShakeDone;
- exp[idx++] = options->minDowngrade;
- exp[idx++] = options->connectState;
- exp[idx++] = options->acceptState;
- exp[idx++] = options->asyncState;
- /* version of connection */
- exp[idx++] = ssl->version.major;
- exp[idx++] = ssl->version.minor;
- (void)zero;
- /* check if changes were made and notify of need to update export version */
- switch (ver) {
- case DTLS_EXPORT_VERSION_3:
- if (idx != DTLS_EXPORT_OPT_SZ_3) {
- WOLFSSL_MSG("Update DTLS_EXPORT_OPT_SZ and version of export");
- return DTLS_EXPORT_VER_E;
- }
- break;
- case DTLS_EXPORT_VERSION:
- if (idx != DTLS_EXPORT_OPT_SZ) {
- WOLFSSL_MSG("Update DTLS_EXPORT_OPT_SZ and version of export");
- return DTLS_EXPORT_VER_E;
- }
- break;
- default:
- WOLFSSL_MSG("New version case needs added to wolfSSL export");
- return DTLS_EXPORT_VER_E;
- }
- WOLFSSL_LEAVE("dtls_export_new", idx);
- return idx;
- }
- /* copy items from Export struct to Options struct
- * On success returns size of buffer used on failure returns a negative value */
- static int dtls_export_load(WOLFSSL* ssl, byte* exp, word32 len, byte ver)
- {
- int idx = 0;
- Options* options = &ssl->options;
- switch (ver) {
- case DTLS_EXPORT_VERSION:
- if (len < DTLS_EXPORT_OPT_SZ) {
- WOLFSSL_MSG("Sanity check on buffer size failed");
- return BAD_FUNC_ARG;
- }
- break;
- case DTLS_EXPORT_VERSION_3:
- if (len < DTLS_EXPORT_OPT_SZ_3) {
- WOLFSSL_MSG("Sanity check on buffer size failed");
- return BAD_FUNC_ARG;
- }
- break;
- default:
- WOLFSSL_MSG("Export version not supported");
- return BAD_FUNC_ARG;
- }
- if (exp == NULL || options == NULL) {
- return BAD_FUNC_ARG;
- }
- /* these options are kept and sent to indicate verify status and strength
- * of handshake */
- options->sendVerify = exp[idx++];
- options->verifyPeer = exp[idx++];
- options->verifyNone = exp[idx++];
- options->downgrade = exp[idx++];
- #ifndef NO_DH
- ato16(exp + idx, &(options->minDhKeySz)); idx += OPAQUE16_LEN;
- ato16(exp + idx, &(options->maxDhKeySz)); idx += OPAQUE16_LEN;
- ato16(exp + idx, &(options->dhKeySz)); idx += OPAQUE16_LEN;
- #else
- idx += OPAQUE16_LEN;
- idx += OPAQUE16_LEN;
- idx += OPAQUE16_LEN;
- #endif
- #ifndef NO_RSA
- ato16(exp + idx, (word16*)&(options->minRsaKeySz)); idx += OPAQUE16_LEN;
- #else
- idx += OPAQUE16_LEN;
- #endif
- #ifdef HAVE_ECC
- ato16(exp + idx, (word16*)&(options->minEccKeySz)); idx += OPAQUE16_LEN;
- #else
- idx += OPAQUE16_LEN;
- #endif
- /* these options are kept to indicate state and behavior */
- #ifndef NO_PSK
- options->havePSK = exp[idx++];
- #else
- idx++;
- #endif
- options->sessionCacheOff = exp[idx++];
- options->sessionCacheFlushOff = exp[idx++];
- options->side = exp[idx++];
- options->resuming = exp[idx++];
- options->haveSessionId = exp[idx++];
- options->tls = exp[idx++];
- options->tls1_1 = exp[idx++];
- options->dtls = exp[idx++];
- options->connReset = exp[idx++];
- options->isClosed = exp[idx++];
- options->closeNotify = exp[idx++];
- options->sentNotify = exp[idx++];
- options->usingCompression = exp[idx++];
- options->haveRSA = exp[idx++];
- options->haveECC = exp[idx++];
- options->haveDH = exp[idx++];
- options->haveNTRU = exp[idx++];
- options->haveQSH = exp[idx++];
- options->haveECDSAsig = exp[idx++];
- options->haveStaticECC = exp[idx++];
- options->havePeerVerify = exp[idx++];
- options->usingPSK_cipher = exp[idx++];
- options->usingAnon_cipher = exp[idx++];
- options->sendAlertState = exp[idx++];
- options->partialWrite = exp[idx++];
- options->quietShutdown = exp[idx++];
- options->groupMessages = exp[idx++];
- #ifdef HAVE_POLY1305
- options->oldPoly = exp[idx++]; /* set when to use old rfc way of poly*/
- #else
- idx++;
- #endif
- #ifdef HAVE_ANON
- options->haveAnon = exp[idx++]; /* User wants to allow Anon suites */
- #else
- idx++;
- #endif
- #ifdef HAVE_SESSION_TICKET
- options->createTicket = exp[idx++]; /* Server to create new Ticket */
- options->useTicket = exp[idx++]; /* Use Ticket not session cache */
- #ifdef WOLFSSL_TLS13
- if (ver > DTLS_EXPORT_VERSION_3) {
- options->noTicketTls13 = exp[idx++];/* Server won't create new Ticket */
- }
- #else
- if (ver > DTLS_EXPORT_VERSION_3) {
- exp[idx++] = 0;
- }
- #endif
- #else
- idx++;
- idx++;
- if (ver > DTLS_EXPORT_VERSION_3) {
- idx++;
- }
- #endif
- options->processReply = exp[idx++];
- options->cipherSuite0 = exp[idx++];
- options->cipherSuite = exp[idx++];
- options->serverState = exp[idx++];
- options->clientState = exp[idx++];
- options->handShakeState = exp[idx++];
- options->handShakeDone = exp[idx++];
- options->minDowngrade = exp[idx++];
- options->connectState = exp[idx++];
- options->acceptState = exp[idx++];
- options->asyncState = exp[idx++];
- /* version of connection */
- if (ssl->version.major != exp[idx++] || ssl->version.minor != exp[idx++]) {
- WOLFSSL_MSG("Version mismatch ie DTLS v1 vs v1.2");
- return VERSION_ERROR;
- }
- return idx;
- }
- #ifndef WOLFSSL_SESSION_EXPORT_NOPEER
- static int ExportPeerInfo(WOLFSSL* ssl, byte* exp, word32 len, byte ver)
- {
- int idx = 0;
- int ipSz = DTLS_EXPORT_IP; /* start as max size */
- int fam = 0;
- word16 port = 0;
- char ip[DTLS_EXPORT_IP];
- if (ver != DTLS_EXPORT_VERSION) {
- WOLFSSL_MSG("Export version not supported");
- return BAD_FUNC_ARG;
- }
- if (ssl == NULL || exp == NULL || len < sizeof(ip) + 3 * DTLS_EXPORT_LEN) {
- return BAD_FUNC_ARG;
- }
- if (ssl->ctx->CBGetPeer == NULL) {
- WOLFSSL_MSG("No get peer call back set");
- return BAD_FUNC_ARG;
- }
- if (ssl->ctx->CBGetPeer(ssl, ip, &ipSz, &port, &fam) != WOLFSSL_SUCCESS) {
- WOLFSSL_MSG("Get peer callback error");
- return SOCKET_ERROR_E;
- }
- /* check that ipSz/fam is not negative or too large since user can set cb */
- if (ipSz < 0 || ipSz > DTLS_EXPORT_IP || fam < 0) {
- WOLFSSL_MSG("Bad ipSz or fam returned from get peer callback");
- return SOCKET_ERROR_E;
- }
- c16toa((word16)fam, exp + idx); idx += DTLS_EXPORT_LEN;
- c16toa((word16)ipSz, exp + idx); idx += DTLS_EXPORT_LEN;
- XMEMCPY(exp + idx, ip, ipSz); idx += ipSz;
- c16toa(port, exp + idx); idx += DTLS_EXPORT_LEN;
- return idx;
- }
- #endif /* !WOLFSSL_SESSION_EXPORT_NOPEER */
- static int ImportPeerInfo(WOLFSSL* ssl, byte* buf, word32 len, byte ver)
- {
- word16 idx = 0;
- word16 ipSz;
- word16 fam;
- word16 port;
- char ip[DTLS_EXPORT_IP];
- if (ver != DTLS_EXPORT_VERSION && ver != DTLS_EXPORT_VERSION_3) {
- WOLFSSL_MSG("Export version not supported");
- return BAD_FUNC_ARG;
- }
- if (len == 0) {
- WOLFSSL_MSG("No peer info sent");
- return 0;
- }
- if (ssl == NULL || buf == NULL || len < 3 * DTLS_EXPORT_LEN) {
- return BAD_FUNC_ARG;
- }
- /* import sin family */
- ato16(buf + idx, &fam); idx += DTLS_EXPORT_LEN;
- /* import ip address idx, and ipSz are unsigned but cast for enum */
- ato16(buf + idx, &ipSz); idx += DTLS_EXPORT_LEN;
- if (ipSz >= sizeof(ip) || (word16)(idx + ipSz + DTLS_EXPORT_LEN) > len) {
- return BUFFER_E;
- }
- XMEMSET(ip, 0, sizeof(ip));
- XMEMCPY(ip, buf + idx, ipSz); idx += ipSz;
- ip[ipSz] = '\0'; /* with check that ipSz less than ip this is valid */
- ato16(buf + idx, &port); idx += DTLS_EXPORT_LEN;
- /* sanity check for a function to call, then use it to import peer info */
- if (ssl->ctx->CBSetPeer == NULL) {
- WOLFSSL_MSG("No set peer function");
- return BAD_FUNC_ARG;
- }
- if (ssl->ctx->CBSetPeer(ssl, ip, ipSz, port, fam) != WOLFSSL_SUCCESS) {
- WOLFSSL_MSG("Error setting peer info");
- return SOCKET_ERROR_E;
- }
- return idx;
- }
- /* WOLFSSL_LOCAL function that serializes the current WOLFSSL session state only
- * buf is used to hold the serialized WOLFSSL struct and sz is the size of buf
- * passed in.
- * On success returns the size of serialized session state.*/
- int wolfSSL_dtls_export_state_internal(WOLFSSL* ssl, byte* buf, word32 sz)
- {
- int ret;
- word32 idx = 0;
- word32 totalLen = 0;
- WOLFSSL_ENTER("wolfSSL_dtls_export_state_internal");
- if (buf == NULL || ssl == NULL) {
- WOLFSSL_LEAVE("wolfSSL_dtls_export_state_internal", BAD_FUNC_ARG);
- return BAD_FUNC_ARG;
- }
- totalLen += DTLS_EXPORT_LEN * 2; /* 2 protocol bytes and 2 length bytes */
- /* each of the following have a 2 byte length before data */
- totalLen += DTLS_EXPORT_LEN + DTLS_EXPORT_MIN_KEY_SZ;
- if (totalLen > sz) {
- WOLFSSL_LEAVE("wolfSSL_dtls_export_state_internal", BUFFER_E);
- return BUFFER_E;
- }
- buf[idx++] = (byte)DTLS_EXPORT_STATE_PRO;
- buf[idx++] = ((byte)DTLS_EXPORT_STATE_PRO & 0xF0) |
- ((byte)DTLS_EXPORT_VERSION & 0X0F);
- idx += DTLS_EXPORT_LEN; /* leave room for total length */
- /* export keys struct and dtls state -- variable length stored in ret */
- idx += DTLS_EXPORT_LEN; /* leave room for length */
- if ((ret = ExportKeyState(ssl, buf + idx, sz - idx,
- DTLS_EXPORT_VERSION, 1)) < 0) {
- WOLFSSL_LEAVE("wolfSSL_dtls_export_state_internal", ret);
- return ret;
- }
- c16toa((word16)ret, buf + idx - DTLS_EXPORT_LEN); idx += ret;
- /* place total length of exported buffer minus 2 bytes protocol/version */
- c16toa((word16)(idx - DTLS_EXPORT_LEN), buf + DTLS_EXPORT_LEN);
- #ifdef WOLFSSL_SESSION_EXPORT_DEBUG
- /* if compiled with debug options then print the version, protocol, size */
- {
- char debug[256];
- XSNPRINTF(debug, sizeof(debug), "Exporting DTLS session state\n"
- "\tVersion : %d\n\tProtocol : %02X%01X\n\tLength of: %d\n\n"
- , (int)DTLS_EXPORT_VERSION, buf[0], (buf[1] >> 4), idx - 2);
- WOLFSSL_MSG(debug);
- }
- #endif /* WOLFSSL_SESSION_EXPORT_DEBUG */
- WOLFSSL_LEAVE("wolfSSL_dtls_export_state_internal", idx);
- return idx;
- }
- /* WOLFSSL_LOCAL function that serializes the current WOLFSSL session
- * buf is used to hold the serialized WOLFSSL struct and sz is the size of buf
- * passed in.
- * On success returns the size of serialized session.*/
- int wolfSSL_dtls_export_internal(WOLFSSL* ssl, byte* buf, word32 sz)
- {
- int ret;
- word32 idx = 0;
- word32 totalLen = 0;
- WOLFSSL_ENTER("wolfSSL_dtls_export_internal");
- if (buf == NULL || ssl == NULL) {
- WOLFSSL_LEAVE("wolfSSL_dtls_export_internal", BAD_FUNC_ARG);
- return BAD_FUNC_ARG;
- }
- totalLen += DTLS_EXPORT_LEN * 2; /* 2 protocol bytes and 2 length bytes */
- /* each of the following have a 2 byte length before data */
- totalLen += DTLS_EXPORT_LEN + DTLS_EXPORT_OPT_SZ;
- totalLen += DTLS_EXPORT_LEN + DTLS_EXPORT_KEY_SZ;
- totalLen += DTLS_EXPORT_LEN + DTLS_EXPORT_SPC_SZ;
- totalLen += DTLS_EXPORT_LEN + ssl->buffers.dtlsCtx.peer.sz;
- if (totalLen > sz) {
- WOLFSSL_LEAVE("wolfSSL_dtls_export_internal", BUFFER_E);
- return BUFFER_E;
- }
- buf[idx++] = (byte)DTLS_EXPORT_PRO;
- buf[idx++] = ((byte)DTLS_EXPORT_PRO & 0xF0) |
- ((byte)DTLS_EXPORT_VERSION & 0X0F);
- idx += DTLS_EXPORT_LEN; /* leave spot for length */
- c16toa((word16)DTLS_EXPORT_OPT_SZ, buf + idx); idx += DTLS_EXPORT_LEN;
- if ((ret = dtls_export_new(ssl, buf + idx, sz - idx,
- DTLS_EXPORT_VERSION)) < 0) {
- WOLFSSL_LEAVE("wolfSSL_dtls_export_internal", ret);
- return ret;
- }
- idx += ret;
- /* export keys struct and dtls state -- variable length stored in ret */
- idx += DTLS_EXPORT_LEN; /* leave room for length */
- if ((ret = ExportKeyState(ssl, buf + idx, sz - idx,
- DTLS_EXPORT_VERSION, 0)) < 0) {
- WOLFSSL_LEAVE("wolfSSL_dtls_export_internal", ret);
- return ret;
- }
- c16toa((word16)ret, buf + idx - DTLS_EXPORT_LEN); idx += ret;
- /* export of cipher specs struct */
- c16toa((word16)DTLS_EXPORT_SPC_SZ, buf + idx); idx += DTLS_EXPORT_LEN;
- if ((ret = ExportCipherSpecState(ssl, buf + idx, sz - idx,
- DTLS_EXPORT_VERSION)) < 0) {
- WOLFSSL_LEAVE("wolfSSL_dtls_export_internal", ret);
- return ret;
- }
- idx += ret;
- /* export of dtls peer information */
- idx += DTLS_EXPORT_LEN;
- #ifdef WOLFSSL_SESSION_EXPORT_NOPEER
- ret = 0; /* not saving peer port/ip information */
- #else
- if ((ret = ExportPeerInfo(ssl, buf + idx, sz - idx,
- DTLS_EXPORT_VERSION)) < 0) {
- WOLFSSL_LEAVE("wolfSSL_dtls_export_internal", ret);
- return ret;
- }
- #endif
- c16toa(ret, buf + idx - DTLS_EXPORT_LEN);
- idx += ret;
- /* place total length of exported buffer minus 2 bytes protocol/version */
- c16toa((word16)(idx - DTLS_EXPORT_LEN), buf + DTLS_EXPORT_LEN);
- /* if compiled with debug options then print the version, protocol, size */
- #ifdef WOLFSSL_SESSION_EXPORT_DEBUG
- {
- char debug[256];
- XSNPRINTF(debug, sizeof(debug), "Exporting DTLS session\n"
- "\tVersion : %d\n\tProtocol : %02X%01X\n\tLength of: %d\n\n"
- , (int)DTLS_EXPORT_VERSION, buf[0], (buf[1] >> 4), idx - 2);
- WOLFSSL_MSG(debug);
- }
- #endif /* WOLFSSL_SESSION_EXPORT_DEBUG */
- WOLFSSL_LEAVE("wolfSSL_dtls_export_internal", idx);
- return idx;
- }
- /* On success return amount of buffer consumed */
- int wolfSSL_dtls_import_state_internal(WOLFSSL* ssl, byte* buf, word32 sz)
- {
- word32 idx = 0;
- word16 length = 0;
- int version;
- int ret;
- WOLFSSL_ENTER("wolfSSL_dtls_import_state_internal");
- /* check at least enough room for protocol and length */
- if (sz < DTLS_EXPORT_LEN * 2 || ssl == NULL) {
- WOLFSSL_LEAVE("wolfSSL_dtls_import_state_internal", BAD_FUNC_ARG);
- return BAD_FUNC_ARG;
- }
- if (buf[idx++] != (byte)DTLS_EXPORT_STATE_PRO ||
- (buf[idx] & 0xF0) != ((byte)DTLS_EXPORT_PRO & 0xF0)) {
- WOLFSSL_MSG("Incorrect protocol");
- return BAD_FUNC_ARG;
- }
- version = buf[idx++] & 0x0F;
- ato16(buf + idx, &length); idx += DTLS_EXPORT_LEN;
- if (length > sz - DTLS_EXPORT_LEN) { /* subtract 2 for protocol */
- WOLFSSL_MSG("Buffer size sanity check failed");
- return BUFFER_E;
- }
- #ifdef WOLFSSL_SESSION_EXPORT_DEBUG
- /* if compiled with debug options then print the version, protocol, size */
- {
- char debug[256];
- XSNPRINTF(debug, sizeof(debug), "Importing DTLS session state\n"
- "\tVersion : %d\n\tProtocol : %02X%01X\n\tLength of: %d\n\n"
- , (int)version, buf[0], (buf[1] >> 4), length);
- WOLFSSL_MSG(debug);
- }
- #endif /* WOLFSSL_SESSION_EXPORT_DEBUG */
- /* perform sanity checks and extract Options information used */
- switch (version) {
- case DTLS_EXPORT_VERSION:
- break;
- default:
- WOLFSSL_MSG("Bad export state version");
- return BAD_FUNC_ARG;
- }
- /* perform sanity checks and extract Keys struct */
- if (DTLS_EXPORT_LEN + idx > sz) {
- WOLFSSL_MSG("Import Key struct error");
- return BUFFER_E;
- }
- ato16(buf + idx, &length); idx += DTLS_EXPORT_LEN;
- if (length > DTLS_EXPORT_KEY_SZ || length + idx > sz) {
- WOLFSSL_MSG("Import Key struct error");
- return BUFFER_E;
- }
- if ((ret = ImportKeyState(ssl, buf + idx, length, version)) < 0) {
- WOLFSSL_MSG("Import Key struct error");
- WOLFSSL_LEAVE("wolfSSL_dtls_import_state_internal", ret);
- return ret;
- }
- idx += ret;
- WOLFSSL_LEAVE("wolfSSL_dtls_import_state_internal", ret);
- return ret;
- }
- /* On success return amount of buffer consumed */
- int wolfSSL_dtls_import_internal(WOLFSSL* ssl, byte* buf, word32 sz)
- {
- word32 idx = 0;
- word16 length = 0;
- int version;
- int ret;
- int optSz;
- WOLFSSL_ENTER("wolfSSL_dtls_import_internal");
- /* check at least enough room for protocol and length */
- if (sz < DTLS_EXPORT_LEN * 2 || ssl == NULL) {
- return BAD_FUNC_ARG;
- }
- /* sanity check on protocol ID and size of buffer */
- if (buf[idx++] != (byte)DTLS_EXPORT_PRO ||
- (buf[idx] & 0xF0) != ((byte)DTLS_EXPORT_PRO & 0xF0)) {
- /* don't increment on second idx to next get version */
- /* check if importing state only */
- return wolfSSL_dtls_import_state_internal(ssl, buf, sz);
- }
- version = buf[idx++] & 0x0F;
- ato16(buf + idx, &length); idx += DTLS_EXPORT_LEN;
- if (length > sz - DTLS_EXPORT_LEN) { /* subtract 2 for protocol */
- return BUFFER_E;
- }
- /* if compiled with debug options then print the version, protocol, size */
- #ifdef WOLFSSL_SESSION_EXPORT_DEBUG
- {
- char debug[256];
- XSNPRINTF(debug, sizeof(debug), "Importing DTLS session\n"
- "\tVersion : %d\n\tProtocol : %02X%01X\n\tLength of: %d\n\n"
- , (int)version, buf[0], (buf[1] >> 4), length);
- WOLFSSL_MSG(debug);
- }
- #endif /* WOLFSSL_SESSION_EXPORT_DEBUG */
- /* perform sanity checks and extract Options information used */
- switch (version) {
- case DTLS_EXPORT_VERSION:
- optSz = DTLS_EXPORT_OPT_SZ;
- break;
- case DTLS_EXPORT_VERSION_3:
- WOLFSSL_MSG("Importing older version 3");
- optSz = DTLS_EXPORT_OPT_SZ_3;
- break;
- default:
- WOLFSSL_MSG("Bad export version");
- return BAD_FUNC_ARG;
- }
- if (DTLS_EXPORT_LEN + optSz + idx > sz) {
- WOLFSSL_MSG("Import Options struct error");
- return BUFFER_E;
- }
- ato16(buf + idx, &length); idx += DTLS_EXPORT_LEN;
- if (length != optSz) {
- WOLFSSL_MSG("Import Options struct error");
- return BUFFER_E;
- }
- if ((ret = dtls_export_load(ssl, buf + idx, length, version)) < 0) {
- WOLFSSL_MSG("Import Options struct error");
- return ret;
- }
- idx += length;
- /* perform sanity checks and extract Keys struct */
- if (DTLS_EXPORT_LEN + idx > sz) {
- WOLFSSL_MSG("Import Key struct error");
- return BUFFER_E;
- }
- ato16(buf + idx, &length); idx += DTLS_EXPORT_LEN;
- if (length > DTLS_EXPORT_KEY_SZ || length + idx > sz) {
- WOLFSSL_MSG("Import Key struct error");
- return BUFFER_E;
- }
- if ((ret = ImportKeyState(ssl, buf + idx, length, version)) < 0) {
- WOLFSSL_MSG("Import Key struct error");
- return ret;
- }
- idx += ret;
- /* perform sanity checks and extract CipherSpecs struct */
- if (DTLS_EXPORT_LEN + DTLS_EXPORT_SPC_SZ + idx > sz) {
- WOLFSSL_MSG("Import CipherSpecs struct error");
- return BUFFER_E;
- }
- ato16(buf + idx, &length); idx += DTLS_EXPORT_LEN;
- if ( length != DTLS_EXPORT_SPC_SZ) {
- WOLFSSL_MSG("Import CipherSpecs struct error");
- return BUFFER_E;
- }
- if ((ret = ImportCipherSpecState(ssl, buf + idx, length, version)) < 0) {
- WOLFSSL_MSG("Import CipherSpecs struct error");
- return ret;
- }
- idx += ret;
- /* perform sanity checks and extract DTLS peer info */
- if (DTLS_EXPORT_LEN + idx > sz) {
- WOLFSSL_MSG("Import DTLS peer info error");
- return BUFFER_E;
- }
- ato16(buf + idx, &length); idx += DTLS_EXPORT_LEN;
- if (idx + length > sz) {
- WOLFSSL_MSG("Import DTLS peer info error");
- return BUFFER_E;
- }
- if ((ret = ImportPeerInfo(ssl, buf + idx, length, version)) < 0) {
- WOLFSSL_MSG("Import Peer Addr error");
- return ret;
- }
- idx += ret;
- SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE);
- /* set hmac function to use when verifying */
- if (ssl->options.tls == 1 || ssl->options.tls1_1 == 1 ||
- ssl->options.dtls == 1) {
- ssl->hmac = TLS_hmac;
- }
- /* make sure is a valid suite used */
- if (wolfSSL_get_cipher(ssl) == NULL) {
- WOLFSSL_MSG("Can not match cipher suite imported");
- return MATCH_SUITE_ERROR;
- }
- /* do not allow stream ciphers with DTLS, except for NULL cipher */
- if (ssl->specs.cipher_type == stream &&
- ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) {
- WOLFSSL_MSG("Can not import stream ciphers for DTLS");
- return SANITY_CIPHER_E;
- }
- return idx;
- }
- #endif /* WOLFSSL_DTLS */
- #endif /* WOLFSSL_SESSION_EXPORT */
- void InitSSL_Method(WOLFSSL_METHOD* method, ProtocolVersion pv)
- {
- method->version = pv;
- method->side = WOLFSSL_CLIENT_END;
- method->downgrade = 0;
- }
- #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
- int InitSSL_Side(WOLFSSL* ssl, word16 side)
- {
- if (ssl == NULL)
- return BAD_FUNC_ARG;
- /* set side */
- ssl->options.side = side;
- /* reset options that are side specific */
- #ifdef HAVE_NTRU
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- ssl->options.haveNTRU = 1; /* always on client side */
- /* server can turn on by loading key */
- }
- #endif
- #ifdef HAVE_ECC
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- ssl->options.haveECDSAsig = 1; /* always on client side */
- ssl->options.haveECC = 1; /* server turns on with ECC key cert */
- ssl->options.haveStaticECC = 1; /* server can turn on by loading key */
- }
- #elif defined(HAVE_ED25519) || defined(HAVE_ED448)
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- ssl->options.haveECDSAsig = 1; /* always on client side */
- ssl->options.haveECC = 1; /* server turns on with ECC key cert */
- }
- #endif
- #if defined(HAVE_EXTENDED_MASTER) && !defined(NO_WOLFSSL_CLIENT)
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- if ((ssl->ctx->method->version.major == SSLv3_MAJOR) &&
- (ssl->ctx->method->version.minor >= TLSv1_MINOR)) {
- ssl->options.haveEMS = 1;
- }
- #ifdef WOLFSSL_DTLS
- if (ssl->ctx->method->version.major == DTLS_MAJOR)
- ssl->options.haveEMS = 1;
- #endif /* WOLFSSL_DTLS */
- }
- #endif /* HAVE_EXTENDED_MASTER && !NO_WOLFSSL_CLIENT */
- #if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
- if (ssl->options.dtls && ssl->options.side == WOLFSSL_SERVER_END) {
- int ret;
- ret = wolfSSL_DTLS_SetCookieSecret(ssl, NULL, 0);
- if (ret != 0) {
- WOLFSSL_MSG("DTLS Cookie Secret error");
- return ret;
- }
- }
- #endif /* WOLFSSL_DTLS && !NO_WOLFSSL_SERVER */
- return InitSSL_Suites(ssl);
- }
- #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
- /* Initialize SSL context, return 0 on success */
- int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap)
- {
- int ret = 0;
- XMEMSET(ctx, 0, sizeof(WOLFSSL_CTX));
- ctx->method = method;
- ctx->refCount = 1; /* so either CTX_free or SSL_free can release */
- ctx->heap = ctx; /* defaults to self */
- ctx->timeout = WOLFSSL_SESSION_TIMEOUT;
- ctx->minDowngrade = WOLFSSL_MIN_DOWNGRADE; /* current default: TLSv1_MINOR */
- if (wc_InitMutex(&ctx->countMutex) < 0) {
- WOLFSSL_MSG("Mutex error on CTX init");
- ctx->err = CTX_INIT_MUTEX_E;
- return BAD_MUTEX_E;
- }
- #ifndef NO_DH
- ctx->minDhKeySz = MIN_DHKEY_SZ;
- ctx->maxDhKeySz = MAX_DHKEY_SZ;
- #endif
- #ifndef NO_RSA
- ctx->minRsaKeySz = MIN_RSAKEY_SZ;
- #endif
- #ifdef HAVE_ECC
- ctx->minEccKeySz = MIN_ECCKEY_SZ;
- ctx->eccTempKeySz = ECDHE_SIZE;
- #endif
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- ctx->verifyDepth = MAX_CHAIN_DEPTH;
- #endif
- #ifdef OPENSSL_EXTRA
- ctx->cbioFlag = WOLFSSL_CBIO_NONE;
- #endif
- #ifndef WOLFSSL_USER_IO
- #ifdef MICRIUM
- ctx->CBIORecv = MicriumReceive;
- ctx->CBIOSend = MicriumSend;
- #ifdef WOLFSSL_DTLS
- if (method->version.major == DTLS_MAJOR) {
- ctx->CBIORecv = MicriumReceiveFrom;
- ctx->CBIOSend = MicriumSendTo;
- }
- #ifdef WOLFSSL_SESSION_EXPORT
- #error Micrium port does not support DTLS session export yet
- #endif
- #endif
- #elif defined WOLFSSL_UIP
- ctx->CBIORecv = uIPReceive;
- ctx->CBIOSend = uIPSend;
- #ifdef WOLFSSL_DTLS
- if (method->version.major == DTLS_MAJOR) {
- ctx->CBIOSendTo = uIPSendTo;
- ctx->CBIORecvFrom = uIPRecvFrom;
- }
- #endif
- #else
- ctx->CBIORecv = EmbedReceive;
- ctx->CBIOSend = EmbedSend;
- #ifdef WOLFSSL_DTLS
- if (method->version.major == DTLS_MAJOR) {
- ctx->CBIORecv = EmbedReceiveFrom;
- ctx->CBIOSend = EmbedSendTo;
- }
- #ifdef WOLFSSL_SESSION_EXPORT
- ctx->CBGetPeer = EmbedGetPeer;
- ctx->CBSetPeer = EmbedSetPeer;
- #endif
- #endif
- #endif /* MICRIUM */
- #endif /* WOLFSSL_USER_IO */
- #ifdef HAVE_NETX
- ctx->CBIORecv = NetX_Receive;
- ctx->CBIOSend = NetX_Send;
- #elif defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP)
- ctx->CBIORecv = Mynewt_Receive;
- ctx->CBIOSend = Mynewt_Send;
- #elif defined(WOLFSSL_GNRC)
- ctx->CBIORecv = GNRC_ReceiveFrom;
- ctx->CBIOSend = GNRC_SendTo;
- #endif
- #ifdef HAVE_NTRU
- if (method->side == WOLFSSL_CLIENT_END)
- ctx->haveNTRU = 1; /* always on client side */
- /* server can turn on by loading key */
- #endif
- #ifdef HAVE_ECC
- if (method->side == WOLFSSL_CLIENT_END) {
- ctx->haveECDSAsig = 1; /* always on client side */
- ctx->haveECC = 1; /* server turns on with ECC key cert */
- ctx->haveStaticECC = 1; /* server can turn on by loading key */
- }
- #elif defined(HAVE_ED25519) || defined(HAVE_ED448)
- if (method->side == WOLFSSL_CLIENT_END) {
- ctx->haveECDSAsig = 1; /* always on client side */
- ctx->haveECC = 1; /* server turns on with ECC key cert */
- }
- #endif
- ctx->devId = INVALID_DEVID;
- #if defined(WOLFSSL_DTLS)
- #ifdef WOLFSSL_SCTP
- ctx->dtlsMtuSz = MAX_RECORD_SIZE;
- #elif defined(WOLFSSL_DTLS_MTU)
- ctx->dtlsMtuSz = MAX_MTU;
- #endif
- #endif
- #ifndef NO_CERTS
- ctx->cm = wolfSSL_CertManagerNew_ex(heap);
- if (ctx->cm == NULL) {
- WOLFSSL_MSG("Bad Cert Manager New");
- return BAD_CERT_MANAGER_ERROR;
- }
- #ifdef OPENSSL_EXTRA
- /* setup WOLFSSL_X509_STORE */
- ctx->x509_store.cm = ctx->cm;
- #endif
- #endif
- #if defined(HAVE_EXTENDED_MASTER) && !defined(NO_WOLFSSL_CLIENT)
- if (method->side == WOLFSSL_CLIENT_END) {
- if ((method->version.major == SSLv3_MAJOR) &&
- (method->version.minor >= TLSv1_MINOR)) {
- ctx->haveEMS = 1;
- }
- #ifdef WOLFSSL_DTLS
- if (method->version.major == DTLS_MAJOR)
- ctx->haveEMS = 1;
- #endif /* WOLFSSL_DTLS */
- }
- #endif /* HAVE_EXTENDED_MASTER && !NO_WOLFSSL_CLIENT */
- #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER)
- ctx->ticketHint = SESSION_TICKET_HINT_DEFAULT;
- #endif
- #ifdef HAVE_WOLF_EVENT
- ret = wolfEventQueue_Init(&ctx->event_queue);
- #endif /* HAVE_WOLF_EVENT */
- #ifdef WOLFSSL_EARLY_DATA
- ctx->maxEarlyDataSz = MAX_EARLY_DATA_SZ;
- #endif
- ctx->heap = heap; /* wolfSSL_CTX_load_static_memory sets */
- ctx->verifyDepth = MAX_CHAIN_DEPTH;
- return ret;
- }
- /* In case contexts are held in array and don't want to free actual ctx */
- void SSL_CtxResourceFree(WOLFSSL_CTX* ctx)
- {
- #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) && \
- defined(HAVE_TLS_EXTENSIONS) && !defined(NO_WOLFSSL_SERVER)
- int i;
- #endif
- #ifdef HAVE_WOLF_EVENT
- wolfEventQueue_Free(&ctx->event_queue);
- #endif /* HAVE_WOLF_EVENT */
- #ifdef WOLFSSL_STATIC_MEMORY
- if (ctx->onHeap == 1) {
- XFREE(ctx->method, ctx->heap, DYNAMIC_TYPE_METHOD);
- }
- else {
- XFREE(ctx->method, NULL, DYNAMIC_TYPE_METHOD);
- }
- #else
- XFREE(ctx->method, ctx->heap, DYNAMIC_TYPE_METHOD);
- #endif
- ctx->method = NULL;
- if (ctx->suites) {
- XFREE(ctx->suites, ctx->heap, DYNAMIC_TYPE_SUITES);
- ctx->suites = NULL;
- }
- #ifndef NO_DH
- XFREE(ctx->serverDH_G.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- ctx->serverDH_G.buffer = NULL;
- XFREE(ctx->serverDH_P.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- ctx->serverDH_P.buffer = NULL;
- #endif /* !NO_DH */
- #ifdef SINGLE_THREADED
- if (ctx->rng) {
- wc_FreeRng(ctx->rng);
- XFREE(ctx->rng, ctx->heap, DYNAMIC_TYPE_RNG);
- ctx->rng = NULL;
- }
- #endif /* SINGLE_THREADED */
- #ifndef NO_CERTS
- FreeDer(&ctx->privateKey);
- FreeDer(&ctx->certificate);
- #ifdef KEEP_OUR_CERT
- if (ctx->ourCert && ctx->ownOurCert) {
- FreeX509(ctx->ourCert);
- XFREE(ctx->ourCert, ctx->heap, DYNAMIC_TYPE_X509);
- ctx->ourCert = NULL;
- }
- #endif /* KEEP_OUR_CERT */
- FreeDer(&ctx->certChain);
- wolfSSL_CertManagerFree(ctx->cm);
- ctx->cm = NULL;
- #ifdef OPENSSL_EXTRA
- /* ctx->cm was free'd so cm of x509 store should now be NULL */
- if (ctx->x509_store_pt != NULL) {
- ctx->x509_store_pt->cm = NULL;
- }
- wolfSSL_X509_STORE_free(ctx->x509_store_pt);
- while (ctx->ca_names != NULL) {
- WOLFSSL_STACK *next = ctx->ca_names->next;
- wolfSSL_X509_NAME_free(ctx->ca_names->data.name);
- XFREE(ctx->ca_names, NULL, DYNAMIC_TYPE_OPENSSL);
- ctx->ca_names = next;
- }
- #endif
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
- while (ctx->x509Chain != NULL) {
- WOLFSSL_STACK *next = ctx->x509Chain->next;
- wolfSSL_X509_free(ctx->x509Chain->data.x509);
- XFREE(ctx->x509Chain, NULL, DYNAMIC_TYPE_OPENSSL);
- ctx->x509Chain = next;
- }
- #endif
- #endif /* !NO_CERTS */
- #ifdef HAVE_TLS_EXTENSIONS
- TLSX_FreeAll(ctx->extensions, ctx->heap);
- #ifndef NO_WOLFSSL_SERVER
- #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
- || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
- if (ctx->certOcspRequest) {
- FreeOcspRequest(ctx->certOcspRequest);
- XFREE(ctx->certOcspRequest, ctx->heap, DYNAMIC_TYPE_OCSP_REQUEST);
- }
- #endif
- #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
- for (i = 0; i < MAX_CHAIN_DEPTH; i++) {
- if (ctx->chainOcspRequest[i]) {
- FreeOcspRequest(ctx->chainOcspRequest[i]);
- XFREE(ctx->chainOcspRequest[i], ctx->heap, DYNAMIC_TYPE_OCSP_REQUEST);
- ctx->chainOcspRequest[i] = NULL;
- }
- }
- #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
- #endif /* !NO_WOLFSSL_SERVER */
- #endif /* HAVE_TLS_EXTENSIONS */
- #ifdef OPENSSL_EXTRA
- if(ctx->alpn_cli_protos) {
- XFREE((void *)ctx->alpn_cli_protos, NULL, DYNAMIC_TYPE_OPENSSL);
- ctx->alpn_cli_protos = NULL;
- }
- #endif
- #ifdef WOLFSSL_STATIC_MEMORY
- if (ctx->heap != NULL) {
- #ifdef WOLFSSL_HEAP_TEST
- /* avoid dereferencing a test value */
- if (ctx->heap != (void*)WOLFSSL_HEAP_TEST)
- #endif
- {
- WOLFSSL_HEAP_HINT* hint = (WOLFSSL_HEAP_HINT*)(ctx->heap);
- wc_FreeMutex(&((WOLFSSL_HEAP*)(hint->memory))->memory_mutex);
- }
- }
- #endif /* WOLFSSL_STATIC_MEMORY */
- }
- void FreeSSL_Ctx(WOLFSSL_CTX* ctx)
- {
- int refCount;
- /* decrement CTX reference count */
- if ((refCount = SSL_CTX_RefCount(ctx, -1)) < 0) {
- /* check error state, if mutex error code then mutex init failed but
- * CTX was still malloc'd */
- if (ctx->err == CTX_INIT_MUTEX_E) {
- SSL_CtxResourceFree(ctx);
- XFREE(ctx, ctx->heap, DYNAMIC_TYPE_CTX);
- }
- return;
- }
- if (refCount == 0) {
- void* heap = ctx->heap;
- WOLFSSL_MSG("CTX ref count down to 0, doing full free");
- SSL_CtxResourceFree(ctx);
- wc_FreeMutex(&ctx->countMutex);
- #ifdef WOLFSSL_STATIC_MEMORY
- if (ctx->onHeap == 0) {
- heap = NULL;
- }
- #endif
- XFREE(ctx, heap, DYNAMIC_TYPE_CTX);
- (void)heap; /* not used in some builds */
- }
- else {
- (void)ctx;
- WOLFSSL_MSG("CTX ref count not 0 yet, no free");
- }
- }
- /* Set cipher pointers to null */
- void InitCiphers(WOLFSSL* ssl)
- {
- #ifdef BUILD_ARC4
- ssl->encrypt.arc4 = NULL;
- ssl->decrypt.arc4 = NULL;
- #endif
- #ifdef BUILD_DES3
- ssl->encrypt.des3 = NULL;
- ssl->decrypt.des3 = NULL;
- #endif
- #ifdef BUILD_AES
- ssl->encrypt.aes = NULL;
- ssl->decrypt.aes = NULL;
- #endif
- #ifdef HAVE_CAMELLIA
- ssl->encrypt.cam = NULL;
- ssl->decrypt.cam = NULL;
- #endif
- #ifdef HAVE_HC128
- ssl->encrypt.hc128 = NULL;
- ssl->decrypt.hc128 = NULL;
- #endif
- #ifdef BUILD_RABBIT
- ssl->encrypt.rabbit = NULL;
- ssl->decrypt.rabbit = NULL;
- #endif
- #ifdef HAVE_CHACHA
- ssl->encrypt.chacha = NULL;
- ssl->decrypt.chacha = NULL;
- #endif
- #if defined(HAVE_POLY1305) && defined(HAVE_ONE_TIME_AUTH)
- ssl->auth.poly1305 = NULL;
- #endif
- ssl->encrypt.setup = 0;
- ssl->decrypt.setup = 0;
- #ifdef HAVE_ONE_TIME_AUTH
- ssl->auth.setup = 0;
- #endif
- #ifdef HAVE_IDEA
- ssl->encrypt.idea = NULL;
- ssl->decrypt.idea = NULL;
- #endif
- }
- /* Free ciphers */
- void FreeCiphers(WOLFSSL* ssl)
- {
- (void)ssl;
- #ifdef BUILD_ARC4
- wc_Arc4Free(ssl->encrypt.arc4);
- wc_Arc4Free(ssl->decrypt.arc4);
- XFREE(ssl->encrypt.arc4, ssl->heap, DYNAMIC_TYPE_CIPHER);
- XFREE(ssl->decrypt.arc4, ssl->heap, DYNAMIC_TYPE_CIPHER);
- #endif
- #ifdef BUILD_DES3
- wc_Des3Free(ssl->encrypt.des3);
- wc_Des3Free(ssl->decrypt.des3);
- XFREE(ssl->encrypt.des3, ssl->heap, DYNAMIC_TYPE_CIPHER);
- XFREE(ssl->decrypt.des3, ssl->heap, DYNAMIC_TYPE_CIPHER);
- #endif
- #if defined(BUILD_AES) || defined(BUILD_AESGCM) /* See: InitKeys() in keys.c
- * on addition of BUILD_AESGCM
- * check (enc->aes, dec->aes) */
- wc_AesFree(ssl->encrypt.aes);
- wc_AesFree(ssl->decrypt.aes);
- #if (defined(BUILD_AESGCM) || defined(HAVE_AESCCM)) && \
- !defined(WOLFSSL_NO_TLS12)
- XFREE(ssl->decrypt.additional, ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
- XFREE(ssl->encrypt.additional, ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
- #endif
- XFREE(ssl->encrypt.aes, ssl->heap, DYNAMIC_TYPE_CIPHER);
- XFREE(ssl->decrypt.aes, ssl->heap, DYNAMIC_TYPE_CIPHER);
- #endif
- #ifdef CIPHER_NONCE
- XFREE(ssl->decrypt.nonce, ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
- XFREE(ssl->encrypt.nonce, ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
- #endif
- #ifdef HAVE_CAMELLIA
- XFREE(ssl->encrypt.cam, ssl->heap, DYNAMIC_TYPE_CIPHER);
- XFREE(ssl->decrypt.cam, ssl->heap, DYNAMIC_TYPE_CIPHER);
- #endif
- #ifdef HAVE_HC128
- XFREE(ssl->encrypt.hc128, ssl->heap, DYNAMIC_TYPE_CIPHER);
- XFREE(ssl->decrypt.hc128, ssl->heap, DYNAMIC_TYPE_CIPHER);
- #endif
- #ifdef BUILD_RABBIT
- XFREE(ssl->encrypt.rabbit, ssl->heap, DYNAMIC_TYPE_CIPHER);
- XFREE(ssl->decrypt.rabbit, ssl->heap, DYNAMIC_TYPE_CIPHER);
- #endif
- #ifdef HAVE_CHACHA
- XFREE(ssl->encrypt.chacha, ssl->heap, DYNAMIC_TYPE_CIPHER);
- XFREE(ssl->decrypt.chacha, ssl->heap, DYNAMIC_TYPE_CIPHER);
- #endif
- #if defined(HAVE_POLY1305) && defined(HAVE_ONE_TIME_AUTH)
- XFREE(ssl->auth.poly1305, ssl->heap, DYNAMIC_TYPE_CIPHER);
- #endif
- #ifdef HAVE_IDEA
- XFREE(ssl->encrypt.idea, ssl->heap, DYNAMIC_TYPE_CIPHER);
- XFREE(ssl->decrypt.idea, ssl->heap, DYNAMIC_TYPE_CIPHER);
- #endif
- #if defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER)
- wc_HmacFree(ssl->encrypt.hmac);
- wc_HmacFree(ssl->decrypt.hmac);
- XFREE(ssl->encrypt.hmac, ssl->heap, DYNAMIC_TYPE_CIPHER);
- XFREE(ssl->decrypt.hmac, ssl->heap, DYNAMIC_TYPE_CIPHER);
- #endif
- }
- void InitCipherSpecs(CipherSpecs* cs)
- {
- XMEMSET(cs, 0, sizeof(CipherSpecs));
- cs->bulk_cipher_algorithm = INVALID_BYTE;
- cs->cipher_type = INVALID_BYTE;
- cs->mac_algorithm = INVALID_BYTE;
- cs->kea = INVALID_BYTE;
- cs->sig_algo = INVALID_BYTE;
- }
- #if defined(USE_ECDSA_KEYSZ_HASH_ALGO) || (defined(WOLFSSL_TLS13) && \
- defined(HAVE_ECC))
- static int GetMacDigestSize(byte macAlgo)
- {
- switch (macAlgo) {
- #ifndef NO_SHA
- case sha_mac:
- return WC_SHA_DIGEST_SIZE;
- #endif
- #ifndef NO_SHA256
- case sha256_mac:
- return WC_SHA256_DIGEST_SIZE;
- #endif
- #ifdef WOLFSSL_SHA384
- case sha384_mac:
- return WC_SHA384_DIGEST_SIZE;
- #endif
- #ifdef WOLFSSL_SHA512
- case sha512_mac:
- return WC_SHA512_DIGEST_SIZE;
- #endif
- default:
- break;
- }
- return NOT_COMPILED_IN;
- }
- #endif /* USE_ECDSA_KEYSZ_HASH_ALGO */
- static WC_INLINE void AddSuiteHashSigAlgo(Suites* suites, byte macAlgo, byte sigAlgo,
- int keySz, word16* inOutIdx)
- {
- int addSigAlgo = 1;
- #ifdef USE_ECDSA_KEYSZ_HASH_ALGO
- if (sigAlgo == ecc_dsa_sa_algo) {
- int digestSz = GetMacDigestSize(macAlgo);
- /* do not add sig/algos with digest size larger than key size */
- if (digestSz <= 0 || (keySz > 0 && digestSz > keySz)) {
- addSigAlgo = 0;
- }
- }
- #else
- (void)keySz;
- #endif /* USE_ECDSA_KEYSZ_HASH_ALGO */
- if (addSigAlgo) {
- #ifdef WC_RSA_PSS
- if (sigAlgo == rsa_pss_sa_algo) {
- /* RSA PSS is sig then mac */
- suites->hashSigAlgo[*inOutIdx] = sigAlgo;
- *inOutIdx += 1;
- suites->hashSigAlgo[*inOutIdx] = macAlgo;
- *inOutIdx += 1;
- #ifdef WOLFSSL_TLS13
- /* Add the certificate algorithm as well */
- suites->hashSigAlgo[*inOutIdx] = sigAlgo;
- *inOutIdx += 1;
- suites->hashSigAlgo[*inOutIdx] = PSS_RSAE_TO_PSS_PSS(macAlgo);
- *inOutIdx += 1;
- #endif
- }
- else
- #endif
- {
- suites->hashSigAlgo[*inOutIdx] = macAlgo;
- *inOutIdx += 1;
- suites->hashSigAlgo[*inOutIdx] = sigAlgo;
- *inOutIdx += 1;
- }
- }
- }
- void InitSuitesHashSigAlgo(Suites* suites, int haveECDSAsig, int haveRSAsig,
- int haveAnon, int tls1_2, int keySz)
- {
- word16 idx = 0;
- (void)tls1_2;
- (void)keySz;
- #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
- if (haveECDSAsig) {
- #ifdef HAVE_ECC
- #ifdef WOLFSSL_SHA512
- AddSuiteHashSigAlgo(suites, sha512_mac, ecc_dsa_sa_algo, keySz, &idx);
- #endif
- #ifdef WOLFSSL_SHA384
- AddSuiteHashSigAlgo(suites, sha384_mac, ecc_dsa_sa_algo, keySz, &idx);
- #endif
- #ifndef NO_SHA256
- AddSuiteHashSigAlgo(suites, sha256_mac, ecc_dsa_sa_algo, keySz, &idx);
- #endif
- #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
- defined(WOLFSSL_ALLOW_TLS_SHA1))
- AddSuiteHashSigAlgo(suites, sha_mac, ecc_dsa_sa_algo, keySz, &idx);
- #endif
- #endif
- #ifdef HAVE_ED25519
- AddSuiteHashSigAlgo(suites, ED25519_SA_MAJOR, ED25519_SA_MINOR, keySz,
- &idx);
- #endif
- #ifdef HAVE_ED448
- AddSuiteHashSigAlgo(suites, ED448_SA_MAJOR, ED448_SA_MINOR, keySz,
- &idx);
- #endif
- }
- #endif /* HAVE_ECC || HAVE_ED25519 || defined(HAVE_ED448 */
- if (haveRSAsig) {
- #ifdef WC_RSA_PSS
- if (tls1_2) {
- #ifdef WOLFSSL_SHA512
- AddSuiteHashSigAlgo(suites, sha512_mac, rsa_pss_sa_algo, keySz,
- &idx);
- #endif
- #ifdef WOLFSSL_SHA384
- AddSuiteHashSigAlgo(suites, sha384_mac, rsa_pss_sa_algo, keySz,
- &idx);
- #endif
- #ifndef NO_SHA256
- AddSuiteHashSigAlgo(suites, sha256_mac, rsa_pss_sa_algo, keySz,
- &idx);
- #endif
- }
- #endif
- #ifdef WOLFSSL_SHA512
- AddSuiteHashSigAlgo(suites, sha512_mac, rsa_sa_algo, keySz, &idx);
- #endif
- #ifdef WOLFSSL_SHA384
- AddSuiteHashSigAlgo(suites, sha384_mac, rsa_sa_algo, keySz, &idx);
- #endif
- #ifndef NO_SHA256
- AddSuiteHashSigAlgo(suites, sha256_mac, rsa_sa_algo, keySz, &idx);
- #endif
- #ifdef WOLFSSL_SHA224
- AddSuiteHashSigAlgo(suites, sha224_mac, rsa_sa_algo, keySz, &idx);
- #endif
- #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
- defined(WOLFSSL_ALLOW_TLS_SHA1))
- AddSuiteHashSigAlgo(suites, sha_mac, rsa_sa_algo, keySz, &idx);
- #endif
- }
- #ifdef HAVE_ANON
- if (haveAnon) {
- AddSuiteHashSigAlgo(suites, sha_mac, anonymous_sa_algo, keySz, &idx);
- }
- #endif
- (void)haveAnon;
- (void)haveECDSAsig;
- suites->hashSigAlgoSz = idx;
- }
- void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA,
- word16 havePSK, word16 haveDH, word16 haveNTRU,
- word16 haveECDSAsig, word16 haveECC,
- word16 haveStaticECC, int side)
- {
- word16 idx = 0;
- int tls = pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_MINOR;
- int tls1_2 = pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_2_MINOR;
- #ifdef WOLFSSL_TLS13
- int tls1_3 = IsAtLeastTLSv1_3(pv);
- #endif
- int dtls = 0;
- int haveRSAsig = 1;
- (void)tls; /* shut up compiler */
- (void)tls1_2;
- (void)dtls;
- (void)haveDH;
- (void)havePSK;
- (void)haveNTRU;
- (void)haveStaticECC;
- (void)haveECC;
- (void)side;
- (void)haveRSA; /* some builds won't read */
- (void)haveRSAsig; /* non ecc builds won't read */
- if (suites == NULL) {
- WOLFSSL_MSG("InitSuites pointer error");
- return;
- }
- if (suites->setSuites)
- return; /* trust user settings, don't override */
- #ifdef WOLFSSL_TLS13
- #ifdef BUILD_TLS_AES_128_GCM_SHA256
- if (tls1_3) {
- suites->suites[idx++] = TLS13_BYTE;
- suites->suites[idx++] = TLS_AES_128_GCM_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_AES_256_GCM_SHA384
- if (tls1_3) {
- suites->suites[idx++] = TLS13_BYTE;
- suites->suites[idx++] = TLS_AES_256_GCM_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_CHACHA20_POLY1305_SHA256
- if (tls1_3) {
- suites->suites[idx++] = TLS13_BYTE;
- suites->suites[idx++] = TLS_CHACHA20_POLY1305_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_AES_128_CCM_SHA256
- if (tls1_3) {
- suites->suites[idx++] = TLS13_BYTE;
- suites->suites[idx++] = TLS_AES_128_CCM_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_AES_128_CCM_8_SHA256
- if (tls1_3) {
- suites->suites[idx++] = TLS13_BYTE;
- suites->suites[idx++] = TLS_AES_128_CCM_8_SHA256;
- }
- #endif
- #ifdef HAVE_NULL_CIPHER
- #ifdef BUILD_TLS_SHA256_SHA256
- if (tls1_3) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_SHA256_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_SHA384_SHA384
- if (tls1_3) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_SHA384_SHA384;
- }
- #endif
- #endif
- #endif /* WOLFSSL_TLS13 */
- #ifndef WOLFSSL_NO_TLS12
- #if !defined(NO_WOLFSSL_SERVER) && !defined(NO_RSA)
- if (side == WOLFSSL_SERVER_END && haveStaticECC) {
- haveRSA = 0; /* can't do RSA with ECDSA key */
- }
- if (side == WOLFSSL_SERVER_END && haveECDSAsig) {
- haveRSAsig = 0; /* can't have RSA sig if signed by ECDSA */
- }
- #endif /* !NO_WOLFSSL_SERVER */
- #ifdef WOLFSSL_DTLS
- if (pv.major == DTLS_MAJOR) {
- dtls = 1;
- tls = 1;
- /* May be dead assignments dependent upon configuration */
- (void) dtls;
- (void) tls;
- tls1_2 = pv.minor <= DTLSv1_2_MINOR;
- }
- #endif
- #ifdef HAVE_RENEGOTIATION_INDICATION
- if (side == WOLFSSL_CLIENT_END) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV;
- }
- #endif
- #ifdef BUILD_TLS_QSH
- if (tls) {
- suites->suites[idx++] = QSH_BYTE;
- suites->suites[idx++] = TLS_QSH;
- }
- #endif
- #ifdef BUILD_TLS_NTRU_RSA_WITH_AES_256_CBC_SHA
- if (tls && haveNTRU && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_NTRU_RSA_WITH_AES_256_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_NTRU_RSA_WITH_AES_128_CBC_SHA
- if (tls && haveNTRU && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_NTRU_RSA_WITH_AES_128_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_NTRU_RSA_WITH_RC4_128_SHA
- if (!dtls && tls && haveNTRU && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_NTRU_RSA_WITH_RC4_128_SHA;
- }
- #endif
- #ifdef BUILD_TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA
- if (tls && haveNTRU && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
- if (tls1_2 && haveECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
- if (tls1_2 && haveECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
- if (tls1_2 && haveRSA) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
- if (tls1_2 && haveRSA) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
- if (tls1_2 && haveDH && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_GCM_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
- if (tls1_2 && haveDH && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_128_GCM_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_256_GCM_SHA384
- if (tls1_2 && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_AES_256_GCM_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256
- if (tls1_2 && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_AES_128_GCM_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
- if (tls1_2 && haveECC && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
- if (tls1_2 && haveECC && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
- if (tls1_2 && haveRSAsig && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
- if (tls1_2 && haveRSAsig && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
- if (tls1_2 && haveDH && havePSK) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_256_GCM_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_DH_anon_WITH_AES_128_CBC_SHA
- if (tls1_2 && haveDH) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DH_anon_WITH_AES_128_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_DH_anon_WITH_AES_256_GCM_SHA384
- if (tls1_2 && haveDH) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DH_anon_WITH_AES_256_GCM_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
- if (tls1_2 && haveDH && havePSK) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_128_GCM_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_256_GCM_SHA384
- if (tls1_2 && havePSK) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_PSK_WITH_AES_256_GCM_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_128_GCM_SHA256
- if (tls1_2 && havePSK) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_PSK_WITH_AES_128_GCM_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
- if (tls1_2 && haveECC) {
- suites->suites[idx++] = CHACHA_BYTE;
- suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
- if (tls1_2 && haveRSA) {
- suites->suites[idx++] = CHACHA_BYTE;
- suites->suites[idx++] = TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
- if (tls1_2 && haveRSA) {
- suites->suites[idx++] = CHACHA_BYTE;
- suites->suites[idx++] = TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256;
- }
- #endif
- /* Place as higher priority for MYSQL */
- #if defined(WOLFSSL_MYSQL_COMPATIBLE)
- #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
- if (tls && haveDH && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA;
- }
- #endif
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
- if (tls1_2 && haveRSA) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
- if (tls1_2 && haveECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
- if (tls1_2 && haveRSAsig && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
- if (tls1_2 && haveECC && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
- if (tls1_2 && haveRSA) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
- if (tls1_2 && haveECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
- if (tls1_2 && haveRSAsig && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
- if (tls1_2 && haveECC && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
- if (tls && haveECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
- if (tls && haveECC && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
- if (tls && haveECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
- if (tls && haveECC && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
- if (!dtls && tls && haveECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_RC4_128_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_RC4_128_SHA
- if (!dtls && tls && haveECC && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_RC4_128_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
- if (tls && haveECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
- if (tls && haveECC && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
- if (tls && haveRSA) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
- if (tls && haveRSAsig && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_256_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
- if (tls && haveRSA) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
- if (tls && haveRSAsig && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_128_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_RC4_128_SHA
- if (!dtls && tls && haveRSA) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_RSA_WITH_RC4_128_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_RC4_128_SHA
- if (!dtls && tls && haveRSAsig && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_RSA_WITH_RC4_128_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
- if (tls && haveRSA) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
- if (tls && haveRSAsig && haveStaticECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM
- if (tls1_2 && haveECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CCM;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
- if (tls1_2 && haveECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8
- if (tls1_2 && haveECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_128_CCM_8
- if (tls1_2 && haveRSA) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_AES_128_CCM_8;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_256_CCM_8
- if (tls1_2 && haveRSA) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_AES_256_CCM_8;
- }
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && haveDH && haveRSA)
- #else
- if (tls && haveDH && haveRSA)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && haveDH && haveRSA)
- #else
- if (tls && haveDH && haveRSA)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_128_CBC_SHA256;
- }
- #endif
- /* Place as higher priority for MYSQL testing */
- #if !defined(WOLFSSL_MYSQL_COMPATIBLE)
- #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
- if (tls && haveDH && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA;
- }
- #endif
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA
- if (tls && haveDH && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_128_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
- if (tls && haveDH && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_256_CBC_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && haveRSA)
- #else
- if (tls && haveRSA)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_AES_256_CBC_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_128_CBC_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && haveRSA)
- #else
- if (tls && haveRSA)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_AES_128_CBC_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_256_CBC_SHA
- if (tls && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_AES_256_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_128_CBC_SHA
- if (tls && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_AES_128_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256
- if (tls1_2 && haveECC) {
- suites->suites[idx++] = CHACHA_BYTE;
- suites->suites[idx++] =
- TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
- if (tls1_2 && haveRSA) {
- suites->suites[idx++] = CHACHA_BYTE;
- suites->suites[idx++] = TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
- if (tls1_2 && haveRSA) {
- suites->suites[idx++] = CHACHA_BYTE;
- suites->suites[idx++] = TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_NULL_SHA
- if (tls && haveECC) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_NULL_SHA;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_NULL_MD5
- if (tls && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_NULL_MD5;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_NULL_SHA
- if (tls && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_NULL_SHA;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_NULL_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && haveRSA)
- #else
- if (tls && haveRSA)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_NULL_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA
- if (tls && havePSK) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_PSK_WITH_AES_256_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && haveDH && havePSK)
- #else
- if (tls && haveDH && havePSK)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_256_CBC_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA384
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && havePSK)
- #else
- if (tls && havePSK)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_PSK_WITH_AES_256_CBC_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && haveDH && havePSK)
- #else
- if (tls && haveDH && havePSK)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_128_CBC_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && havePSK)
- #else
- if (tls1 && havePSK)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_PSK_WITH_AES_128_CBC_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA
- if (tls && havePSK) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_PSK_WITH_AES_128_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CCM
- if (tls && haveDH && havePSK) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_128_CCM;
- }
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_CCM
- if (tls && haveDH && havePSK) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_256_CCM;
- }
- #endif
- #ifdef BUILD_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && havePSK)
- #else
- if (tls && havePSK)
- #endif
- {
- suites->suites[idx++] = CHACHA_BYTE;
- suites->suites[idx++] = TLS_PSK_WITH_CHACHA20_POLY1305_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && havePSK)
- #else
- if (tls && havePSK)
- #endif
- {
- suites->suites[idx++] = CHACHA_BYTE;
- suites->suites[idx++] = TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && havePSK)
- #else
- if (tls && havePSK)
- #endif
- {
- suites->suites[idx++] = CHACHA_BYTE;
- suites->suites[idx++] = TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && havePSK)
- #else
- if (tls && havePSK)
- #endif
- {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM
- if (tls && havePSK) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_PSK_WITH_AES_128_CCM;
- }
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_256_CCM
- if (tls && havePSK) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_PSK_WITH_AES_256_CCM;
- }
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM_8
- if (tls && havePSK) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_PSK_WITH_AES_128_CCM_8;
- }
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_256_CCM_8
- if (tls && havePSK) {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_PSK_WITH_AES_256_CCM_8;
- }
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_NULL_SHA384
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && haveDH && havePSK)
- #else
- if (tls && haveDH && havePSK)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_PSK_WITH_NULL_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_PSK_WITH_NULL_SHA384
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && havePSK)
- #else
- if (tls && havePSK)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_PSK_WITH_NULL_SHA384;
- }
- #endif
- #ifdef BUILD_TLS_ECDHE_PSK_WITH_NULL_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && havePSK)
- #else
- if (tls && havePSK)
- #endif
- {
- suites->suites[idx++] = ECC_BYTE;
- suites->suites[idx++] = TLS_ECDHE_PSK_WITH_NULL_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_NULL_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && haveDH && havePSK)
- #else
- if (tls && haveDH && havePSK)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_PSK_WITH_NULL_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_PSK_WITH_NULL_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && havePSK)
- #else
- if (tls && havePSK)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_PSK_WITH_NULL_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_PSK_WITH_NULL_SHA
- if (tls && havePSK) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_PSK_WITH_NULL_SHA;
- }
- #endif
- #ifdef BUILD_SSL_RSA_WITH_RC4_128_SHA
- if (!dtls && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = SSL_RSA_WITH_RC4_128_SHA;
- }
- #endif
- #ifdef BUILD_SSL_RSA_WITH_RC4_128_MD5
- if (!dtls && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = SSL_RSA_WITH_RC4_128_MD5;
- }
- #endif
- #ifdef BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA
- if (haveRSA ) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = SSL_RSA_WITH_3DES_EDE_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_HC_128_MD5
- if (!dtls && tls && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_HC_128_MD5;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_HC_128_SHA
- if (!dtls && tls && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_HC_128_SHA;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_RABBIT_SHA
- if (!dtls && tls && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_RABBIT_SHA;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
- if (tls && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_128_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
- if (tls && haveDH && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
- if (tls && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_256_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
- if (tls && haveDH && haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && haveRSA)
- #else
- if (tls && haveRSA)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && haveDH && haveRSA)
- #else
- if (tls && haveDH && haveRSA)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && haveRSA)
- #else
- if (tls && haveRSA)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256;
- }
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256
- #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
- if (tls1_2 && haveDH && haveRSA)
- #else
- if (tls && haveDH && haveRSA)
- #endif
- {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256;
- }
- #endif
- #ifdef BUILD_SSL_RSA_WITH_IDEA_CBC_SHA
- if (haveRSA) {
- suites->suites[idx++] = CIPHER_BYTE;
- suites->suites[idx++] = SSL_RSA_WITH_IDEA_CBC_SHA;
- }
- #endif
- #endif /* !WOLFSSL_NO_TLS12 */
- suites->suiteSz = idx;
- InitSuitesHashSigAlgo(suites, haveECDSAsig | haveECC, haveRSAsig | haveRSA,
- 0, tls1_2, keySz);
- }
- #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_CERTS) || \
- (!defined(NO_WOLFSSL_CLIENT) && (!defined(NO_DH) || defined(HAVE_ECC)))
- /* Decode the signature algorithm.
- *
- * input The encoded signature algorithm.
- * hashalgo The hash algorithm.
- * hsType The signature type.
- */
- static WC_INLINE void DecodeSigAlg(const byte* input, byte* hashAlgo, byte* hsType)
- {
- switch (input[0]) {
- case NEW_SA_MAJOR:
- #ifdef HAVE_ED25519
- /* ED25519: 0x0807 */
- if (input[1] == ED25519_SA_MINOR) {
- *hsType = ed25519_sa_algo;
- /* Hash performed as part of sign/verify operation. */
- *hashAlgo = sha512_mac;
- }
- else
- #endif
- #ifdef HAVE_ED448
- /* ED448: 0x0808 */
- if (input[1] == ED448_SA_MINOR) {
- *hsType = ed448_sa_algo;
- /* Hash performed as part of sign/verify operation. */
- *hashAlgo = sha512_mac;
- }
- else
- #endif
- #ifdef WC_RSA_PSS
- /* PSS PSS signatures: 0x080[9-b] */
- if (input[1] >= pss_sha256 && input[1] <= pss_sha512) {
- *hsType = rsa_pss_pss_algo;
- *hashAlgo = PSS_PSS_HASH_TO_MAC(input[1]);
- }
- else
- #endif
- {
- *hsType = input[0];
- *hashAlgo = input[1];
- }
- break;
- default:
- *hashAlgo = input[0];
- *hsType = input[1];
- break;
- }
- }
- #endif /* !NO_WOLFSSL_SERVER || !NO_CERTS */
- #ifndef WOLFSSL_NO_TLS12
- #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT)
- #if !defined(NO_DH) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448) || (!defined(NO_RSA) && defined(WC_RSA_PSS))
- static enum wc_HashType HashAlgoToType(int hashAlgo)
- {
- switch (hashAlgo) {
- #ifdef WOLFSSL_SHA512
- case sha512_mac:
- return WC_HASH_TYPE_SHA512;
- #endif
- #ifdef WOLFSSL_SHA384
- case sha384_mac:
- return WC_HASH_TYPE_SHA384;
- #endif
- #ifndef NO_SHA256
- case sha256_mac:
- return WC_HASH_TYPE_SHA256;
- #endif
- #ifdef WOLFSSL_SHA224
- case sha224_mac:
- return WC_HASH_TYPE_SHA224;
- #endif
- #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
- defined(WOLFSSL_ALLOW_TLS_SHA1))
- case sha_mac:
- return WC_HASH_TYPE_SHA;
- #endif
- default:
- WOLFSSL_MSG("Bad hash sig algo");
- break;
- }
- return WC_HASH_TYPE_NONE;
- }
- #endif /* !NO_DH || HAVE_ECC || (!NO_RSA && WC_RSA_PSS) */
- #endif /* !NO_WOLFSSL_SERVER || !NO_WOLFSSL_CLIENT */
- #endif /* !WOLFSSL_NO_TLS12 */
- #ifndef NO_CERTS
- void InitX509Name(WOLFSSL_X509_NAME* name, int dynamicFlag)
- {
- (void)dynamicFlag;
- if (name != NULL) {
- name->name = name->staticName;
- name->dynamicName = 0;
- name->sz = 0;
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- XMEMSET(&name->fullName, 0, sizeof(DecodedName));
- XMEMSET(&name->cnEntry, 0, sizeof(WOLFSSL_X509_NAME_ENTRY));
- XMEMSET(&name->extra, 0, sizeof(name->extra));
- name->cnEntry.value = &(name->cnEntry.data); /* point to internal data*/
- name->cnEntry.nid = ASN_COMMON_NAME;
- name->x509 = NULL;
- #endif /* OPENSSL_EXTRA */
- }
- }
- void FreeX509Name(WOLFSSL_X509_NAME* name, void* heap)
- {
- if (name != NULL) {
- if (name->dynamicName) {
- XFREE(name->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
- name->name = NULL;
- }
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- {
- int i;
- if (name->fullName.fullName != NULL) {
- XFREE(name->fullName.fullName, heap, DYNAMIC_TYPE_X509);
- name->fullName.fullName = NULL;
- }
- for (i = 0; i < MAX_NAME_ENTRIES; i++) {
- /* free ASN1 string data */
- if (name->extra[i].set && name->extra[i].data.data != NULL) {
- XFREE(name->extra[i].data.data, heap, DYNAMIC_TYPE_OPENSSL);
- }
- }
- wolfSSL_ASN1_OBJECT_free(&name->cnEntry.object);
- }
- #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
- }
- (void)heap;
- }
- /* Initialize wolfSSL X509 type */
- void InitX509(WOLFSSL_X509* x509, int dynamicFlag, void* heap)
- {
- if (x509 == NULL) {
- WOLFSSL_MSG("Null parameter passed in!");
- return;
- }
- XMEMSET(x509, 0, sizeof(WOLFSSL_X509));
- x509->heap = heap;
- InitX509Name(&x509->issuer, 0);
- InitX509Name(&x509->subject, 0);
- x509->dynamicMemory = (byte)dynamicFlag;
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
- x509->refCount = 1;
- (void)wc_InitMutex(&x509->refMutex);
- #endif
- }
- /* Free wolfSSL X509 type */
- void FreeX509(WOLFSSL_X509* x509)
- {
- if (x509 == NULL)
- return;
- FreeX509Name(&x509->issuer, x509->heap);
- FreeX509Name(&x509->subject, x509->heap);
- if (x509->pubKey.buffer) {
- XFREE(x509->pubKey.buffer, x509->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- x509->pubKey.buffer = NULL;
- }
- FreeDer(&x509->derCert);
- XFREE(x509->sig.buffer, x509->heap, DYNAMIC_TYPE_SIGNATURE);
- x509->sig.buffer = NULL;
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- XFREE(x509->authKeyId, x509->heap, DYNAMIC_TYPE_X509_EXT);
- x509->authKeyId = NULL;
- XFREE(x509->subjKeyId, x509->heap, DYNAMIC_TYPE_X509_EXT);
- x509->subjKeyId = NULL;
- if (x509->authInfo != NULL) {
- XFREE(x509->authInfo, x509->heap, DYNAMIC_TYPE_X509_EXT);
- x509->authInfo = NULL;
- }
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
- if (x509->authInfoCaIssuer != NULL) {
- XFREE(x509->authInfoCaIssuer, x509->heap, DYNAMIC_TYPE_X509_EXT);
- }
- if (x509->ext_sk != NULL) {
- wolfSSL_sk_X509_EXTENSION_free(x509->ext_sk);
- }
- #endif /* OPENSSL_ALL || WOLFSSL_QT */
- #ifdef OPENSSL_EXTRA
- /* Free serialNumber that was set by wolfSSL_X509_get_serialNumber */
- if (x509->serialNumber != NULL) {
- wolfSSL_ASN1_INTEGER_free(x509->serialNumber);
- }
- #endif
- if (x509->extKeyUsageSrc != NULL) {
- XFREE(x509->extKeyUsageSrc, x509->heap, DYNAMIC_TYPE_X509_EXT);
- x509->extKeyUsageSrc= NULL;
- }
- #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
- #if defined(OPENSSL_ALL)
- if (x509->algor.algorithm) {
- wolfSSL_ASN1_OBJECT_free(x509->algor.algorithm);
- x509->algor.algorithm = NULL;
- }
- if (x509->key.algor) {
- wolfSSL_X509_ALGOR_free(x509->key.algor);
- x509->key.algor = NULL;
- }
- if (x509->key.pkey) {
- wolfSSL_EVP_PKEY_free(x509->key.pkey);
- x509->key.pkey = NULL;
- }
- #endif /* OPENSSL_ALL */
- if (x509->altNames) {
- FreeAltNames(x509->altNames, x509->heap);
- x509->altNames = NULL;
- }
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
- wc_FreeMutex(&x509->refMutex);
- #endif
- }
- #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT)
- #if !defined(WOLFSSL_NO_TLS12)
- /* Encode the signature algorithm into buffer.
- *
- * hashalgo The hash algorithm.
- * hsType The signature type.
- * output The buffer to encode into.
- */
- static WC_INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output)
- {
- switch (hsType) {
- #ifdef HAVE_ECC
- case ecc_dsa_sa_algo:
- output[0] = hashAlgo;
- output[1] = ecc_dsa_sa_algo;
- break;
- #endif
- #ifdef HAVE_ED25519
- case ed25519_sa_algo:
- output[0] = ED25519_SA_MAJOR;
- output[1] = ED25519_SA_MINOR;
- (void)hashAlgo;
- break;
- #endif
- #ifdef HAVE_ED448
- case ed448_sa_algo:
- output[0] = ED448_SA_MAJOR;
- output[1] = ED448_SA_MINOR;
- (void)hashAlgo;
- break;
- #endif
- #ifndef NO_RSA
- case rsa_sa_algo:
- output[0] = hashAlgo;
- output[1] = rsa_sa_algo;
- break;
- #ifdef WC_RSA_PSS
- /* PSS signatures: 0x080[4-6] */
- case rsa_pss_sa_algo:
- output[0] = rsa_pss_sa_algo;
- output[1] = hashAlgo;
- break;
- #endif
- #endif
- }
- (void)hashAlgo;
- (void)output;
- }
- #endif
- #if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_NO_CLIENT_AUTH)
- static void SetDigest(WOLFSSL* ssl, int hashAlgo)
- {
- switch (hashAlgo) {
- #ifndef NO_SHA
- case sha_mac:
- ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha;
- ssl->buffers.digest.length = WC_SHA_DIGEST_SIZE;
- break;
- #endif /* !NO_SHA */
- #ifndef NO_SHA256
- case sha256_mac:
- ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha256;
- ssl->buffers.digest.length = WC_SHA256_DIGEST_SIZE;
- break;
- #endif /* !NO_SHA256 */
- #ifdef WOLFSSL_SHA384
- case sha384_mac:
- ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha384;
- ssl->buffers.digest.length = WC_SHA384_DIGEST_SIZE;
- break;
- #endif /* WOLFSSL_SHA384 */
- #ifdef WOLFSSL_SHA512
- case sha512_mac:
- ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha512;
- ssl->buffers.digest.length = WC_SHA512_DIGEST_SIZE;
- break;
- #endif /* WOLFSSL_SHA512 */
- } /* switch */
- }
- #endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_NO_CLIENT_AUTH */
- #endif /* !NO_WOLFSSL_SERVER || !NO_WOLFSSL_CLIENT */
- #endif /* !NO_CERTS */
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- static word32 MacSize(WOLFSSL* ssl)
- {
- #ifdef HAVE_TRUNCATED_HMAC
- word32 digestSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
- : ssl->specs.hash_size;
- #else
- word32 digestSz = ssl->specs.hash_size;
- #endif
- return digestSz;
- }
- #endif /* HAVE_ENCRYPT_THEN_MAC && !WOLFSSL_AEAD_ONLY */
- #ifndef NO_RSA
- #ifndef WOLFSSL_NO_TLS12
- #if !defined(NO_WOLFSSL_SERVER) || (!defined(NO_WOLFSSL_CLIENT) && \
- !defined(WOLFSSL_NO_CLIENT_AUTH))
- static int TypeHash(int hashAlgo)
- {
- switch (hashAlgo) {
- #ifdef WOLFSSL_SHA512
- case sha512_mac:
- return SHA512h;
- #endif
- #ifdef WOLFSSL_SHA384
- case sha384_mac:
- return SHA384h;
- #endif
- #ifndef NO_SHA256
- case sha256_mac:
- return SHA256h;
- #endif
- #ifdef WOLFSSL_SHA224
- case sha224_mac:
- return SHA224h;
- #endif
- #ifndef NO_SHA
- case sha_mac:
- return SHAh;
- #endif
- }
- return 0;
- }
- #endif /* !NO_WOLFSSL_SERVER && !NO_WOLFSSL_CLIENT */
- #endif /* !WOLFSSL_NO_TLS12 */
- #if defined(WC_RSA_PSS)
- int ConvertHashPss(int hashAlgo, enum wc_HashType* hashType, int* mgf)
- {
- switch (hashAlgo) {
- #ifdef WOLFSSL_SHA512
- case sha512_mac:
- *hashType = WC_HASH_TYPE_SHA512;
- if (mgf != NULL)
- *mgf = WC_MGF1SHA512;
- break;
- #endif
- #ifdef WOLFSSL_SHA384
- case sha384_mac:
- *hashType = WC_HASH_TYPE_SHA384;
- if (mgf != NULL)
- *mgf = WC_MGF1SHA384;
- break;
- #endif
- #ifndef NO_SHA256
- case sha256_mac:
- *hashType = WC_HASH_TYPE_SHA256;
- if (mgf != NULL)
- *mgf = WC_MGF1SHA256;
- break;
- #endif
- default:
- return BAD_FUNC_ARG;
- }
- return 0;
- }
- #endif
- #if !defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH)
- int RsaSign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out,
- word32* outSz, int sigAlgo, int hashAlgo, RsaKey* key,
- DerBuffer* keyBufInfo)
- {
- int ret;
- #ifdef HAVE_PK_CALLBACKS
- const byte* keyBuf = NULL;
- word32 keySz = 0;
- if (keyBufInfo) {
- keyBuf = keyBufInfo->buffer;
- keySz = keyBufInfo->length;
- }
- #endif
- (void)ssl;
- (void)keyBufInfo;
- (void)sigAlgo;
- (void)hashAlgo;
- WOLFSSL_ENTER("RsaSign");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- if (key) {
- ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- return ret;
- }
- #endif
- #if defined(WC_RSA_PSS)
- if (sigAlgo == rsa_pss_sa_algo) {
- enum wc_HashType hashType = WC_HASH_TYPE_NONE;
- int mgf = 0;
- ret = ConvertHashPss(hashAlgo, &hashType, &mgf);
- if (ret != 0)
- return ret;
- #if defined(HAVE_PK_CALLBACKS)
- if (ssl->ctx->RsaPssSignCb) {
- void* ctx = wolfSSL_GetRsaPssSignCtx(ssl);
- ret = ssl->ctx->RsaPssSignCb(ssl, in, inSz, out, outSz,
- TypeHash(hashAlgo), mgf,
- keyBuf, keySz, ctx);
- }
- else
- #endif
- {
- ret = wc_RsaPSS_Sign(in, inSz, out, *outSz, hashType, mgf, key,
- ssl->rng);
- }
- }
- else
- #endif
- #if defined(HAVE_PK_CALLBACKS)
- if (ssl->ctx->RsaSignCb) {
- void* ctx = wolfSSL_GetRsaSignCtx(ssl);
- ret = ssl->ctx->RsaSignCb(ssl, in, inSz, out, outSz, keyBuf, keySz,
- ctx);
- }
- else
- #endif /*HAVE_PK_CALLBACKS */
- ret = wc_RsaSSL_Sign(in, inSz, out, *outSz, key, ssl->rng);
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (key && ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- /* For positive response return in outSz */
- if (ret > 0) {
- *outSz = ret;
- ret = 0;
- }
- WOLFSSL_LEAVE("RsaSign", ret);
- return ret;
- }
- #endif
- int RsaVerify(WOLFSSL* ssl, byte* in, word32 inSz, byte** out, int sigAlgo,
- int hashAlgo, RsaKey* key, buffer* keyBufInfo)
- {
- int ret;
- #ifdef HAVE_PK_CALLBACKS
- const byte* keyBuf = NULL;
- word32 keySz = 0;
- if (keyBufInfo) {
- keyBuf = keyBufInfo->buffer;
- keySz = keyBufInfo->length;
- }
- #endif
- (void)ssl;
- (void)keyBufInfo;
- (void)sigAlgo;
- (void)hashAlgo;
- WOLFSSL_ENTER("RsaVerify");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- return ret;
- #endif
- #if defined(WC_RSA_PSS)
- if (sigAlgo == rsa_pss_sa_algo) {
- enum wc_HashType hashType = WC_HASH_TYPE_NONE;
- int mgf = 0;
- ret = ConvertHashPss(hashAlgo, &hashType, &mgf);
- if (ret != 0)
- return ret;
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->RsaPssVerifyCb) {
- void* ctx = wolfSSL_GetRsaPssVerifyCtx(ssl);
- ret = ssl->ctx->RsaPssVerifyCb(ssl, in, inSz, out,
- TypeHash(hashAlgo), mgf,
- keyBuf, keySz, ctx);
- }
- else
- #endif /*HAVE_PK_CALLBACKS */
- ret = wc_RsaPSS_VerifyInline(in, inSz, out, hashType, mgf, key);
- }
- else
- #endif
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->RsaVerifyCb) {
- void* ctx = wolfSSL_GetRsaVerifyCtx(ssl);
- ret = ssl->ctx->RsaVerifyCb(ssl, in, inSz, out, keyBuf, keySz, ctx);
- }
- else
- #endif /*HAVE_PK_CALLBACKS */
- {
- ret = wc_RsaSSL_VerifyInline(in, inSz, out, key);
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- WOLFSSL_LEAVE("RsaVerify", ret);
- return ret;
- }
- /* Verify RSA signature, 0 on success */
- /* This function is used to check the sign result */
- int VerifyRsaSign(WOLFSSL* ssl, byte* verifySig, word32 sigSz,
- const byte* plain, word32 plainSz, int sigAlgo, int hashAlgo, RsaKey* key,
- DerBuffer* keyBufInfo)
- {
- byte* out = NULL; /* inline result */
- int ret;
- #ifdef HAVE_PK_CALLBACKS
- const byte* keyBuf = NULL;
- word32 keySz = 0;
- if (keyBufInfo) {
- keyBuf = keyBufInfo->buffer;
- keySz = keyBufInfo->length;
- }
- #endif
- (void)ssl;
- (void)keyBufInfo;
- (void)sigAlgo;
- (void)hashAlgo;
- WOLFSSL_ENTER("VerifyRsaSign");
- if (verifySig == NULL || plain == NULL) {
- return BAD_FUNC_ARG;
- }
- if (sigSz > ENCRYPT_LEN) {
- WOLFSSL_MSG("Signature buffer too big");
- return BUFFER_E;
- }
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- if (key) {
- ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- return ret;
- }
- #endif
- #if defined(WC_RSA_PSS)
- if (sigAlgo == rsa_pss_sa_algo) {
- enum wc_HashType hashType = WC_HASH_TYPE_NONE;
- int mgf = 0;
- ret = ConvertHashPss(hashAlgo, &hashType, &mgf);
- if (ret != 0)
- return ret;
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->RsaPssSignCheckCb) {
- /* The key buffer includes private/public portion,
- but only public is used */
- /* If HSM hardware is checking the signature result you can
- optionally skip the sign check and return 0 */
- /* The ctx here is the RsaSignCtx set using wolfSSL_SetRsaSignCtx */
- void* ctx = wolfSSL_GetRsaPssSignCtx(ssl);
- ret = ssl->ctx->RsaPssSignCheckCb(ssl, verifySig, sigSz, &out,
- TypeHash(hashAlgo), mgf,
- keyBuf, keySz, ctx);
- if (ret > 0) {
- ret = wc_RsaPSS_CheckPadding(plain, plainSz, out, ret,
- hashType);
- if (ret != 0)
- ret = VERIFY_CERT_ERROR;
- }
- }
- else
- #endif /* HAVE_PK_CALLBACKS */
- {
- ret = wc_RsaPSS_VerifyInline(verifySig, sigSz, &out, hashType, mgf,
- key);
- if (ret > 0) {
- #ifdef HAVE_SELFTEST
- ret = wc_RsaPSS_CheckPadding(plain, plainSz, out, ret,
- hashType);
- #else
- ret = wc_RsaPSS_CheckPadding_ex(plain, plainSz, out, ret,
- hashType, -1,
- mp_count_bits(&key->n));
- #endif
- if (ret != 0)
- ret = VERIFY_CERT_ERROR;
- }
- }
- }
- else
- #endif /* WC_RSA_PSS */
- {
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->RsaSignCheckCb) {
- /* The key buffer includes private/public portion,
- but only public is used */
- /* If HSM hardware is checking the signature result you can
- optionally skip the sign check and return 0 */
- /* The ctx here is the RsaSignCtx set using wolfSSL_SetRsaSignCtx */
- void* ctx = wolfSSL_GetRsaSignCtx(ssl);
- ret = ssl->ctx->RsaSignCheckCb(ssl, verifySig, sigSz, &out,
- keyBuf, keySz, ctx);
- }
- else
- #endif /* HAVE_PK_CALLBACKS */
- {
- ret = wc_RsaSSL_VerifyInline(verifySig, sigSz, &out, key);
- }
- if (ret > 0) {
- if (ret != (int)plainSz || !out ||
- XMEMCMP(plain, out, plainSz) != 0) {
- WOLFSSL_MSG("RSA Signature verification failed");
- ret = RSA_SIGN_FAULT;
- } else {
- ret = 0; /* RSA reset */
- }
- }
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (key && ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- WOLFSSL_LEAVE("VerifyRsaSign", ret);
- return ret;
- }
- #ifndef WOLFSSL_NO_TLS12
- #if !defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH)
- int RsaDec(WOLFSSL* ssl, byte* in, word32 inSz, byte** out, word32* outSz,
- RsaKey* key, DerBuffer* keyBufInfo)
- {
- int ret;
- #ifdef HAVE_PK_CALLBACKS
- const byte* keyBuf = NULL;
- word32 keySz = 0;
- if (keyBufInfo) {
- keyBuf = keyBufInfo->buffer;
- keySz = keyBufInfo->length;
- }
- #endif
- (void)ssl;
- (void)keyBufInfo;
- WOLFSSL_ENTER("RsaDec");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- return ret;
- #endif
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->RsaDecCb) {
- void* ctx = wolfSSL_GetRsaDecCtx(ssl);
- ret = ssl->ctx->RsaDecCb(ssl, in, inSz, out, keyBuf, keySz, ctx);
- }
- else
- #endif /* HAVE_PK_CALLBACKS */
- {
- #ifdef WC_RSA_BLINDING
- ret = wc_RsaSetRNG(key, ssl->rng);
- if (ret != 0)
- return ret;
- #endif
- ret = wc_RsaPrivateDecryptInline(in, inSz, out, key);
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- /* For positive response return in outSz */
- if (ret > 0) {
- *outSz = ret;
- ret = 0;
- }
- WOLFSSL_LEAVE("RsaDec", ret);
- return ret;
- }
- #endif /* !NO_WOLFSSL_SERVER) || !WOLFSSL_NO_CLIENT_AUTH */
- int RsaEnc(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out, word32* outSz,
- RsaKey* key, buffer* keyBufInfo)
- {
- int ret;
- #ifdef HAVE_PK_CALLBACKS
- const byte* keyBuf = NULL;
- word32 keySz = 0;
- if (keyBufInfo) {
- keyBuf = keyBufInfo->buffer;
- keySz = keyBufInfo->length;
- }
- #endif
- (void)ssl;
- (void)keyBufInfo;
- WOLFSSL_ENTER("RsaEnc");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- return ret;
- #endif
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->RsaEncCb) {
- void* ctx = wolfSSL_GetRsaEncCtx(ssl);
- ret = ssl->ctx->RsaEncCb(ssl, in, inSz, out, outSz, keyBuf, keySz, ctx);
- }
- else
- #endif /* HAVE_PK_CALLBACKS */
- {
- ret = wc_RsaPublicEncrypt(in, inSz, out, *outSz, key, ssl->rng);
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- /* For positive response return in outSz */
- if (ret > 0) {
- *outSz = ret;
- ret = 0;
- }
- WOLFSSL_LEAVE("RsaEnc", ret);
- return ret;
- }
- #endif /* !WOLFSSL_NO_TLS12 */
- #endif /* NO_RSA */
- #ifdef HAVE_ECC
- int EccSign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out,
- word32* outSz, ecc_key* key, DerBuffer* keyBufInfo)
- {
- int ret;
- #ifdef HAVE_PK_CALLBACKS
- const byte* keyBuf = NULL;
- word32 keySz = 0;
- if (keyBufInfo) {
- keyBuf = keyBufInfo->buffer;
- keySz = keyBufInfo->length;
- }
- #endif
- (void)ssl;
- (void)keyBufInfo;
- WOLFSSL_ENTER("EccSign");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- if (key) {
- ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- return ret;
- }
- #endif
- #if defined(HAVE_PK_CALLBACKS)
- if (ssl->ctx->EccSignCb) {
- void* ctx = wolfSSL_GetEccSignCtx(ssl);
- ret = ssl->ctx->EccSignCb(ssl, in, inSz, out, outSz, keyBuf,
- keySz, ctx);
- }
- else
- #endif /* HAVE_PK_CALLBACKS */
- {
- ret = wc_ecc_sign_hash(in, inSz, out, outSz, ssl->rng, key);
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (key && ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- WOLFSSL_LEAVE("EccSign", ret);
- return ret;
- }
- int EccVerify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* out,
- word32 outSz, ecc_key* key, buffer* keyBufInfo)
- {
- int ret;
- #ifdef HAVE_PK_CALLBACKS
- const byte* keyBuf = NULL;
- word32 keySz = 0;
- if (keyBufInfo) {
- keyBuf = keyBufInfo->buffer;
- keySz = keyBufInfo->length;
- }
- #endif
- (void)ssl;
- (void)keyBufInfo;
- WOLFSSL_ENTER("EccVerify");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- return ret;
- #endif
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->EccVerifyCb) {
- void* ctx = wolfSSL_GetEccVerifyCtx(ssl);
- ret = ssl->ctx->EccVerifyCb(ssl, in, inSz, out, outSz, keyBuf, keySz,
- &ssl->eccVerifyRes, ctx);
- }
- else
- #endif /* HAVE_PK_CALLBACKS */
- {
- ret = wc_ecc_verify_hash(in, inSz, out, outSz, &ssl->eccVerifyRes, key);
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
- }
- else
- #endif /* WOLFSSL_ASYNC_CRYPT */
- {
- ret = (ret != 0 || ssl->eccVerifyRes == 0) ? VERIFY_SIGN_ERROR : 0;
- }
- WOLFSSL_LEAVE("EccVerify", ret);
- return ret;
- }
- #ifdef HAVE_PK_CALLBACKS
- /* Gets ECC key for shared secret callback testing
- * Client side: returns peer key
- * Server side: returns private key
- */
- static int EccGetKey(WOLFSSL* ssl, ecc_key** otherKey)
- {
- int ret = NO_PEER_KEY;
- ecc_key* tmpKey = NULL;
- if (ssl == NULL || otherKey == NULL) {
- return BAD_FUNC_ARG;
- }
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- if (ssl->specs.static_ecdh) {
- if (!ssl->peerEccDsaKey || !ssl->peerEccDsaKeyPresent ||
- !ssl->peerEccDsaKey->dp) {
- return NO_PEER_KEY;
- }
- tmpKey = (struct ecc_key*)ssl->peerEccDsaKey;
- }
- else {
- if (!ssl->peerEccKey || !ssl->peerEccKeyPresent ||
- !ssl->peerEccKey->dp) {
- return NO_PEER_KEY;
- }
- tmpKey = (struct ecc_key*)ssl->peerEccKey;
- }
- }
- else if (ssl->options.side == WOLFSSL_SERVER_END) {
- if (ssl->specs.static_ecdh) {
- if (ssl->hsKey == NULL) {
- return NO_PRIVATE_KEY;
- }
- tmpKey = (struct ecc_key*)ssl->hsKey;
- }
- else {
- if (!ssl->eccTempKeyPresent) {
- return NO_PRIVATE_KEY;
- }
- tmpKey = (struct ecc_key*)ssl->eccTempKey;
- }
- }
- if (tmpKey) {
- *otherKey = tmpKey;
- ret = 0;
- }
- return ret;
- }
- #endif /* HAVE_PK_CALLBACKS */
- int EccSharedSecret(WOLFSSL* ssl, ecc_key* priv_key, ecc_key* pub_key,
- byte* pubKeyDer, word32* pubKeySz, byte* out, word32* outlen,
- int side)
- {
- int ret;
- #ifdef HAVE_PK_CALLBACKS
- ecc_key* otherKey = NULL;
- #endif
- #ifdef WOLFSSL_ASYNC_CRYPT
- WC_ASYNC_DEV* asyncDev = &priv_key->asyncDev;
- #endif
- (void)ssl;
- (void)pubKeyDer;
- (void)pubKeySz;
- (void)side;
- WOLFSSL_ENTER("EccSharedSecret");
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->EccSharedSecretCb) {
- ret = EccGetKey(ssl, &otherKey);
- if (ret != 0)
- return ret;
- #ifdef WOLFSSL_ASYNC_CRYPT
- asyncDev = &otherKey->asyncDev;
- #endif
- }
- #endif
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- return ret;
- #endif
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->EccSharedSecretCb) {
- void* ctx = wolfSSL_GetEccSharedSecretCtx(ssl);
- ret = ssl->ctx->EccSharedSecretCb(ssl, otherKey, pubKeyDer,
- pubKeySz, out, outlen, side, ctx);
- }
- else
- #endif
- {
- ret = wc_ecc_shared_secret(priv_key, pub_key, out, outlen);
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- WOLFSSL_LEAVE("EccSharedSecret", ret);
- return ret;
- }
- int EccMakeKey(WOLFSSL* ssl, ecc_key* key, ecc_key* peer)
- {
- int ret = 0;
- int keySz = 0;
- int ecc_curve = ECC_CURVE_DEF;
- WOLFSSL_ENTER("EccMakeKey");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_NONE);
- if (ret != 0)
- return ret;
- #endif
- /* get key size */
- if (peer == NULL) {
- keySz = ssl->eccTempKeySz;
- }
- else {
- keySz = peer->dp->size;
- }
- /* get curve type */
- if (ssl->ecdhCurveOID > 0) {
- ecc_curve = wc_ecc_get_oid(ssl->ecdhCurveOID, NULL, NULL);
- }
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->EccKeyGenCb) {
- void* ctx = wolfSSL_GetEccKeyGenCtx(ssl);
- ret = ssl->ctx->EccKeyGenCb(ssl, key, keySz, ecc_curve, ctx);
- }
- else
- #endif
- {
- ret = wc_ecc_make_key_ex(ssl->rng, keySz, key, ecc_curve);
- }
- /* make sure the curve is set for TLS */
- if (ret == 0 && key->dp) {
- ssl->ecdhCurveOID = key->dp->oidSum;
- #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
- ssl->namedGroup = 0;
- #endif
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- WOLFSSL_LEAVE("EccMakeKey", ret);
- return ret;
- }
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- /* Check whether the key contains a public key.
- * If not then pull it out of the leaf certificate.
- *
- * ssl SSL/TLS object.
- * returns MEMORY_E when unable to allocate memory, a parsing error, otherwise
- * 0 on success.
- */
- int Ed25519CheckPubKey(WOLFSSL* ssl)
- {
- ed25519_key* key = (ed25519_key*)ssl->hsKey;
- int ret = 0;
- /* Public key required for signing. */
- if (!key->pubKeySet) {
- DerBuffer* leaf = ssl->buffers.certificate;
- DecodedCert* cert = (DecodedCert*)XMALLOC(sizeof(*cert),
- ssl->heap, DYNAMIC_TYPE_DCERT);
- if (cert == NULL)
- ret = MEMORY_E;
- if (ret == 0) {
- InitDecodedCert(cert, leaf->buffer, leaf->length, ssl->heap);
- ret = DecodeToKey(cert, 0);
- }
- if (ret == 0) {
- ret = wc_ed25519_import_public(cert->publicKey, cert->pubKeySize,
- key);
- }
- if (cert != NULL) {
- FreeDecodedCert(cert);
- XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
- }
- }
- return ret;
- }
- /* Sign the data using EdDSA and key using Ed25519.
- *
- * ssl SSL object.
- * in Data or message to sign.
- * inSz Length of the data.
- * out Buffer to hold signature.
- * outSz On entry, size of the buffer. On exit, the size of the signature.
- * key The private Ed25519 key data.
- * keySz The length of the private key data in bytes.
- * ctx The callback context.
- * returns 0 on success, otherwise the value is an error.
- */
- int Ed25519Sign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out,
- word32* outSz, ed25519_key* key, DerBuffer* keyBufInfo)
- {
- int ret;
- #ifdef HAVE_PK_CALLBACKS
- const byte* keyBuf = NULL;
- word32 keySz = 0;
- if (keyBufInfo) {
- keyBuf = keyBufInfo->buffer;
- keySz = keyBufInfo->length;
- }
- #endif
- (void)ssl;
- (void)keyBufInfo;
- WOLFSSL_ENTER("Ed25519Sign");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- return ret;
- #endif
- #if defined(HAVE_PK_CALLBACKS)
- if (ssl->ctx->Ed25519SignCb) {
- void* ctx = wolfSSL_GetEd25519SignCtx(ssl);
- ret = ssl->ctx->Ed25519SignCb(ssl, in, inSz, out, outSz, keyBuf,
- keySz, ctx);
- }
- else
- #endif /* HAVE_PK_CALLBACKS */
- {
- ret = wc_ed25519_sign_msg(in, inSz, out, outSz, key);
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- WOLFSSL_LEAVE("Ed25519Sign", ret);
- return ret;
- }
- /* Verify the data using EdDSA and key using Ed25519.
- *
- * ssl SSL object.
- * in Signature data.
- * inSz Length of the signature data in bytes.
- * msg Message to verify.
- * outSz Length of message in bytes.
- * key The public Ed25519 key data.
- * keySz The length of the private key data in bytes.
- * ctx The callback context.
- * returns 0 on success, otherwise the value is an error.
- */
- int Ed25519Verify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* msg,
- word32 msgSz, ed25519_key* key, buffer* keyBufInfo)
- {
- int ret;
- #ifdef HAVE_PK_CALLBACKS
- const byte* keyBuf = NULL;
- word32 keySz = 0;
- if (keyBufInfo) {
- keyBuf = keyBufInfo->buffer;
- keySz = keyBufInfo->length;
- }
- #endif
- (void)ssl;
- (void)keyBufInfo;
- WOLFSSL_ENTER("Ed25519Verify");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- return ret;
- #endif
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->Ed25519VerifyCb) {
- void* ctx = wolfSSL_GetEd25519VerifyCtx(ssl);
- ret = ssl->ctx->Ed25519VerifyCb(ssl, in, inSz, msg, msgSz, keyBuf,
- keySz, &ssl->eccVerifyRes, ctx);
- }
- else
- #endif /* HAVE_PK_CALLBACKS */
- {
- ret = wc_ed25519_verify_msg(in, inSz, msg, msgSz,
- &ssl->eccVerifyRes, key);
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
- }
- else
- #endif /* WOLFSSL_ASYNC_CRYPT */
- {
- ret = (ret != 0 || ssl->eccVerifyRes == 0) ? VERIFY_SIGN_ERROR : 0;
- }
- WOLFSSL_LEAVE("Ed25519Verify", ret);
- return ret;
- }
- #endif /* HAVE_ED25519 */
- #ifndef WOLFSSL_NO_TLS12
- #ifdef HAVE_CURVE25519
- #ifdef HAVE_PK_CALLBACKS
- /* Gets X25519 key for shared secret callback testing
- * Client side: returns peer key
- * Server side: returns private key
- */
- static int X25519GetKey(WOLFSSL* ssl, curve25519_key** otherKey)
- {
- int ret = NO_PEER_KEY;
- struct curve25519_key* tmpKey = NULL;
- if (ssl == NULL || otherKey == NULL) {
- return BAD_FUNC_ARG;
- }
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- if (!ssl->peerX25519Key || !ssl->peerX25519KeyPresent ||
- !ssl->peerX25519Key->dp) {
- return NO_PEER_KEY;
- }
- tmpKey = (struct curve25519_key*)ssl->peerX25519Key;
- }
- else if (ssl->options.side == WOLFSSL_SERVER_END) {
- if (!ssl->eccTempKeyPresent) {
- return NO_PRIVATE_KEY;
- }
- tmpKey = (struct curve25519_key*)ssl->eccTempKey;
- }
- if (tmpKey) {
- *otherKey = (curve25519_key *)tmpKey;
- ret = 0;
- }
- return ret;
- }
- #endif /* HAVE_PK_CALLBACKS */
- static int X25519SharedSecret(WOLFSSL* ssl, curve25519_key* priv_key,
- curve25519_key* pub_key, byte* pubKeyDer, word32* pubKeySz,
- byte* out, word32* outlen, int side)
- {
- int ret;
- (void)ssl;
- (void)pubKeyDer;
- (void)pubKeySz;
- (void)side;
- WOLFSSL_ENTER("X25519SharedSecret");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &priv_key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- return ret;
- #endif
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->X25519SharedSecretCb) {
- curve25519_key* otherKey = NULL;
- ret = X25519GetKey(ssl, &otherKey);
- if (ret == 0) {
- void* ctx = wolfSSL_GetX25519SharedSecretCtx(ssl);
- ret = ssl->ctx->X25519SharedSecretCb(ssl, otherKey, pubKeyDer,
- pubKeySz, out, outlen, side, ctx);
- }
- }
- else
- #endif
- {
- ret = wc_curve25519_shared_secret_ex(priv_key, pub_key, out, outlen,
- EC25519_LITTLE_ENDIAN);
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &priv_key->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- WOLFSSL_LEAVE("X25519SharedSecret", ret);
- return ret;
- }
- static int X25519MakeKey(WOLFSSL* ssl, curve25519_key* key,
- curve25519_key* peer)
- {
- int ret = 0;
- (void)peer;
- WOLFSSL_ENTER("X25519MakeKey");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_NONE);
- if (ret != 0)
- return ret;
- #endif
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->X25519KeyGenCb) {
- void* ctx = wolfSSL_GetX25519KeyGenCtx(ssl);
- ret = ssl->ctx->X25519KeyGenCb(ssl, key, CURVE25519_KEYSIZE, ctx);
- }
- else
- #endif
- {
- ret = wc_curve25519_make_key(ssl->rng, CURVE25519_KEYSIZE, key);
- }
- if (ret == 0) {
- ssl->ecdhCurveOID = ECC_X25519_OID;
- #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
- ssl->namedGroup = 0;
- #endif
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- WOLFSSL_LEAVE("X25519MakeKey", ret);
- return ret;
- }
- #endif /* HAVE_CURVE25519 */
- #ifdef HAVE_ED448
- /* Check whether the key contains a public key.
- * If not then pull it out of the leaf certificate.
- *
- * ssl SSL/TLS object.
- * returns MEMORY_E when unable to allocate memory, a parsing error, otherwise
- * 0 on success.
- */
- int Ed448CheckPubKey(WOLFSSL* ssl)
- {
- ed448_key* key = (ed448_key*)ssl->hsKey;
- int ret = 0;
- /* Public key required for signing. */
- if (!key->pubKeySet) {
- DerBuffer* leaf = ssl->buffers.certificate;
- DecodedCert* cert = (DecodedCert*)XMALLOC(sizeof(*cert), ssl->heap,
- DYNAMIC_TYPE_DCERT);
- if (cert == NULL)
- ret = MEMORY_E;
- if (ret == 0) {
- InitDecodedCert(cert, leaf->buffer, leaf->length, ssl->heap);
- ret = DecodeToKey(cert, 0);
- }
- if (ret == 0) {
- ret = wc_ed448_import_public(cert->publicKey, cert->pubKeySize,
- key);
- }
- if (cert != NULL) {
- FreeDecodedCert(cert);
- XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
- }
- }
- return ret;
- }
- /* Sign the data using EdDSA and key using Ed448.
- *
- * ssl SSL object.
- * in Data or message to sign.
- * inSz Length of the data.
- * out Buffer to hold signature.
- * outSz On entry, size of the buffer. On exit, the size of the signature.
- * key The private Ed448 key data.
- * keySz The length of the private key data in bytes.
- * ctx The callback context.
- * returns 0 on success, otherwise the value is an error.
- */
- int Ed448Sign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out,
- word32* outSz, ed448_key* key, DerBuffer* keyBufInfo)
- {
- int ret;
- #ifdef HAVE_PK_CALLBACKS
- const byte* keyBuf = NULL;
- word32 keySz = 0;
- if (keyBufInfo) {
- keyBuf = keyBufInfo->buffer;
- keySz = keyBufInfo->length;
- }
- #endif
- (void)ssl;
- (void)keyBufInfo;
- WOLFSSL_ENTER("Ed448Sign");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- return ret;
- #endif
- #if defined(HAVE_PK_CALLBACKS)
- if (ssl->ctx->Ed448SignCb) {
- void* ctx = wolfSSL_GetEd448SignCtx(ssl);
- ret = ssl->ctx->Ed448SignCb(ssl, in, inSz, out, outSz, keyBuf, keySz,
- ctx);
- }
- else
- #endif /* HAVE_PK_CALLBACKS */
- {
- ret = wc_ed448_sign_msg(in, inSz, out, outSz, key, NULL, 0);
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- WOLFSSL_LEAVE("Ed448Sign", ret);
- return ret;
- }
- /* Verify the data using EdDSA and key using Ed448.
- *
- * ssl SSL object.
- * in Signature data.
- * inSz Length of the signature data in bytes.
- * msg Message to verify.
- * outSz Length of message in bytes.
- * key The public Ed448 key data.
- * keySz The length of the private key data in bytes.
- * ctx The callback context.
- * returns 0 on success, otherwise the value is an error.
- */
- int Ed448Verify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* msg,
- word32 msgSz, ed448_key* key, buffer* keyBufInfo)
- {
- int ret;
- #ifdef HAVE_PK_CALLBACKS
- const byte* keyBuf = NULL;
- word32 keySz = 0;
- if (keyBufInfo) {
- keyBuf = keyBufInfo->buffer;
- keySz = keyBufInfo->length;
- }
- #endif
- (void)ssl;
- (void)keyBufInfo;
- WOLFSSL_ENTER("Ed448Verify");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- return ret;
- #endif
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->Ed448VerifyCb) {
- void* ctx = wolfSSL_GetEd448VerifyCtx(ssl);
- ret = ssl->ctx->Ed448VerifyCb(ssl, in, inSz, msg, msgSz, keyBuf, keySz,
- &ssl->eccVerifyRes, ctx);
- }
- else
- #endif /* HAVE_PK_CALLBACKS */
- {
- ret = wc_ed448_verify_msg(in, inSz, msg, msgSz, &ssl->eccVerifyRes, key,
- NULL, 0);
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
- }
- else
- #endif /* WOLFSSL_ASYNC_CRYPT */
- {
- ret = (ret != 0 || ssl->eccVerifyRes == 0) ? VERIFY_SIGN_ERROR : 0;
- }
- WOLFSSL_LEAVE("Ed448Verify", ret);
- return ret;
- }
- #endif /* HAVE_ED448 */
- #ifdef HAVE_CURVE448
- #ifdef HAVE_PK_CALLBACKS
- /* Gets X448 key for shared secret callback testing
- * Client side: returns peer key
- * Server side: returns private key
- */
- static int X448GetKey(WOLFSSL* ssl, curve448_key** otherKey)
- {
- int ret = NO_PEER_KEY;
- struct curve448_key* tmpKey = NULL;
- if (ssl == NULL || otherKey == NULL) {
- return BAD_FUNC_ARG;
- }
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- if (!ssl->peerX448Key || !ssl->peerX448KeyPresent) {
- return NO_PEER_KEY;
- }
- tmpKey = (struct curve448_key*)ssl->peerX448Key;
- }
- else if (ssl->options.side == WOLFSSL_SERVER_END) {
- if (!ssl->eccTempKeyPresent) {
- return NO_PRIVATE_KEY;
- }
- tmpKey = (struct curve448_key*)ssl->eccTempKey;
- }
- if (tmpKey) {
- *otherKey = (curve448_key *)tmpKey;
- ret = 0;
- }
- return ret;
- }
- #endif /* HAVE_PK_CALLBACKS */
- static int X448SharedSecret(WOLFSSL* ssl, curve448_key* priv_key,
- curve448_key* pub_key, byte* pubKeyDer,
- word32* pubKeySz, byte* out, word32* outlen,
- int side)
- {
- int ret;
- (void)ssl;
- (void)pubKeyDer;
- (void)pubKeySz;
- (void)side;
- WOLFSSL_ENTER("X448SharedSecret");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &priv_key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- return ret;
- #endif
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->X448SharedSecretCb) {
- curve448_key* otherKey = NULL;
- ret = X448GetKey(ssl, &otherKey);
- if (ret == 0) {
- void* ctx = wolfSSL_GetX448SharedSecretCtx(ssl);
- ret = ssl->ctx->X448SharedSecretCb(ssl, otherKey, pubKeyDer,
- pubKeySz, out, outlen, side, ctx);
- }
- }
- else
- #endif
- {
- ret = wc_curve448_shared_secret_ex(priv_key, pub_key, out, outlen,
- EC448_LITTLE_ENDIAN);
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &priv_key->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- WOLFSSL_LEAVE("X448SharedSecret", ret);
- return ret;
- }
- static int X448MakeKey(WOLFSSL* ssl, curve448_key* key, curve448_key* peer)
- {
- int ret = 0;
- (void)peer;
- WOLFSSL_ENTER("X448MakeKey");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_NONE);
- if (ret != 0)
- return ret;
- #endif
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->X448KeyGenCb) {
- void* ctx = wolfSSL_GetX448KeyGenCtx(ssl);
- ret = ssl->ctx->X448KeyGenCb(ssl, key, CURVE448_KEY_SIZE, ctx);
- }
- else
- #endif
- {
- ret = wc_curve448_make_key(ssl->rng, CURVE448_KEY_SIZE, key);
- }
- if (ret == 0) {
- ssl->ecdhCurveOID = ECC_X448_OID;
- #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
- ssl->namedGroup = 0;
- #endif
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- WOLFSSL_LEAVE("X448MakeKey", ret);
- return ret;
- }
- #endif /* HAVE_CURVE448 */
- #if !defined(NO_CERTS) || !defined(NO_PSK)
- #if !defined(NO_DH)
- int DhGenKeyPair(WOLFSSL* ssl, DhKey* dhKey,
- byte* priv, word32* privSz,
- byte* pub, word32* pubSz)
- {
- int ret;
- WOLFSSL_ENTER("DhGenKeyPair");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &dhKey->asyncDev, WC_ASYNC_FLAG_NONE);
- if (ret != 0)
- return ret;
- #endif
- ret = wc_DhGenerateKeyPair(dhKey, ssl->rng, priv, privSz, pub, pubSz);
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &dhKey->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- WOLFSSL_LEAVE("DhGenKeyPair", ret);
- return ret;
- }
- int DhAgree(WOLFSSL* ssl, DhKey* dhKey,
- const byte* priv, word32 privSz,
- const byte* otherPub, word32 otherPubSz,
- byte* agree, word32* agreeSz)
- {
- int ret;
- (void)ssl;
- WOLFSSL_ENTER("DhAgree");
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &dhKey->asyncDev, WC_ASYNC_FLAG_NONE);
- if (ret != 0)
- return ret;
- #endif
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->ctx->DhAgreeCb) {
- void* ctx = wolfSSL_GetDhAgreeCtx(ssl);
- WOLFSSL_MSG("Calling DhAgree Callback Function");
- ret = ssl->ctx->DhAgreeCb(ssl, dhKey, priv, privSz,
- otherPub, otherPubSz, agree, agreeSz, ctx);
- }
- else
- #endif
- {
- #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
- ret = wc_DhCheckPubValue(ssl->buffers.serverDH_P.buffer,
- ssl->buffers.serverDH_P.length, otherPub, otherPubSz);
- if (ret != 0) {
- #ifdef OPENSSL_EXTRA
- SendAlert(ssl, alert_fatal, illegal_parameter);
- #endif
- }
- else
- #endif
- {
- ret = wc_DhAgree(dhKey, agree, agreeSz, priv, privSz, otherPub,
- otherPubSz);
- }
- }
- /* Handle async pending response */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &dhKey->asyncDev);
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- WOLFSSL_LEAVE("DhAgree", ret);
- return ret;
- }
- #endif /* !NO_DH */
- #endif /* !NO_CERTS || !NO_PSK */
- #endif /* !WOLFSSL_NO_TLS12 */
- #ifdef HAVE_PK_CALLBACKS
- int wolfSSL_IsPrivatePkSet(WOLFSSL* ssl)
- {
- int pkcbset = 0;
- (void)ssl;
- #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
- !defined(NO_RSA)
- if (0
- #ifdef HAVE_ECC
- || (ssl->ctx->EccSignCb != NULL &&
- ssl->buffers.keyType == ecc_dsa_sa_algo)
- #endif
- #ifdef HAVE_ED25519
- || (ssl->ctx->Ed25519SignCb != NULL &&
- ssl->buffers.keyType == ed25519_sa_algo)
- #endif
- #ifdef HAVE_ED448
- || (ssl->ctx->Ed448SignCb != NULL &&
- ssl->buffers.keyType == ed448_sa_algo)
- #endif
- #ifndef NO_RSA
- || (ssl->ctx->RsaSignCb != NULL && ssl->buffers.keyType == rsa_sa_algo)
- || (ssl->ctx->RsaDecCb != NULL && ssl->buffers.keyType == rsa_kea)
- #ifdef WC_RSA_PSS
- || (ssl->ctx->RsaPssSignCb != NULL &&
- ssl->buffers.keyType == rsa_pss_sa_algo)
- #endif
- #endif
- ) {
- pkcbset = 1;
- }
- #endif
- return pkcbset;
- }
- int wolfSSL_CTX_IsPrivatePkSet(WOLFSSL_CTX* ctx)
- {
- int pkcbset = 0;
- (void)ctx;
- #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
- !defined(NO_RSA)
- if (0
- #ifdef HAVE_ECC
- || ctx->EccSignCb != NULL
- #endif
- #ifdef HAVE_ED25519
- || ctx->Ed25519SignCb != NULL
- #endif
- #ifdef HAVE_ED448
- || ctx->Ed448SignCb != NULL
- #endif
- #ifndef NO_RSA
- || ctx->RsaSignCb != NULL
- || ctx->RsaDecCb != NULL
- #ifdef WC_RSA_PSS
- || ctx->RsaPssSignCb != NULL
- #endif
- #endif
- ) {
- pkcbset = 1;
- }
- #endif
- return pkcbset;
- }
- #endif /* HAVE_PK_CALLBACKS */
- int InitSSL_Suites(WOLFSSL* ssl)
- {
- int keySz = 0;
- byte havePSK = 0;
- byte haveAnon = 0;
- byte haveRSA = 0;
- byte haveMcast = 0;
- (void)haveAnon; /* Squash unused var warnings */
- (void)haveMcast;
- if (!ssl)
- return BAD_FUNC_ARG;
- #ifndef NO_RSA
- haveRSA = 1;
- #endif
- #ifndef NO_PSK
- havePSK = (byte)ssl->options.havePSK;
- #endif /* NO_PSK */
- #ifdef HAVE_ANON
- haveAnon = (byte)ssl->options.haveAnon;
- #endif /* HAVE_ANON*/
- #ifdef WOLFSSL_MULTICAST
- haveMcast = (byte)ssl->options.haveMcast;
- #endif /* WOLFSSL_MULTICAST */
- #ifdef WOLFSSL_EARLY_DATA
- if (ssl->options.side == WOLFSSL_SERVER_END)
- ssl->options.maxEarlyDataSz = ssl->ctx->maxEarlyDataSz;
- #endif
- #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
- ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
- (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
- ssl->options.cacheMessages = ssl->options.side == WOLFSSL_SERVER_END ||
- ssl->buffers.keyType == ed25519_sa_algo ||
- ssl->buffers.keyType == ed448_sa_algo;
- #endif
- #ifndef NO_CERTS
- keySz = ssl->buffers.keySz;
- #endif
- /* make sure server has DH parms, and add PSK if there, add NTRU too */
- if (ssl->options.side == WOLFSSL_SERVER_END) {
- InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
- ssl->options.haveDH, ssl->options.haveNTRU,
- ssl->options.haveECDSAsig, ssl->options.haveECC,
- ssl->options.haveStaticECC, ssl->options.side);
- }
- else {
- InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
- TRUE, ssl->options.haveNTRU,
- ssl->options.haveECDSAsig, ssl->options.haveECC,
- ssl->options.haveStaticECC, ssl->options.side);
- }
- #if !defined(NO_CERTS) && !defined(WOLFSSL_SESSION_EXPORT)
- /* make sure server has cert and key unless using PSK, Anon, or
- * Multicast. This should be true even if just switching ssl ctx */
- if (ssl->options.side == WOLFSSL_SERVER_END &&
- !havePSK && !haveAnon && !haveMcast) {
- /* server certificate must be loaded */
- if (!ssl->buffers.certificate || !ssl->buffers.certificate->buffer) {
- WOLFSSL_MSG("Server missing certificate");
- return NO_PRIVATE_KEY;
- }
- /* allow no private key if using PK callbacks and CB is set */
- #ifdef HAVE_PK_CALLBACKS
- if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) {
- WOLFSSL_MSG("Using PK for server private key");
- }
- else
- #endif
- if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
- WOLFSSL_MSG("Server missing private key");
- return NO_PRIVATE_KEY;
- }
- }
- #endif
- return WOLFSSL_SUCCESS;
- }
- /* returns new reference count. Arg incr positive=up or negative=down */
- int SSL_CTX_RefCount(WOLFSSL_CTX* ctx, int incr)
- {
- int refCount;
- if (ctx == NULL) {
- return BAD_FUNC_ARG;
- }
- if (wc_LockMutex(&ctx->countMutex) != 0) {
- WOLFSSL_MSG("Couldn't lock CTX count mutex");
- return BAD_MUTEX_E;
- }
- ctx->refCount += incr;
- /* make sure refCount is never negative */
- if (ctx->refCount < 0) {
- ctx->refCount = 0;
- }
- refCount = ctx->refCount;
- wc_UnLockMutex(&ctx->countMutex);
- return refCount;
- }
- /* This function inherits a WOLFSSL_CTX's fields into an SSL object.
- It is used during initialization and to switch an ssl's CTX with
- wolfSSL_Set_SSL_CTX. Requires ssl->suites alloc and ssl-arrays with PSK
- unless writeDup is on.
- ssl object to initialize
- ctx parent factory
- writeDup flag indicating this is a write dup only
- WOLFSSL_SUCCESS return value on success */
- int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
- {
- int ret;
- byte newSSL;
- if (!ssl || !ctx)
- return BAD_FUNC_ARG;
- #ifndef SINGLE_THREADED
- if (ssl->suites == NULL && !writeDup)
- return BAD_FUNC_ARG;
- #endif
- newSSL = ssl->ctx == NULL; /* Assign after null check */
- #ifndef NO_PSK
- if (ctx->server_hint[0] && ssl->arrays == NULL && !writeDup) {
- return BAD_FUNC_ARG; /* needed for copy below */
- }
- #endif
- /* decrement previous CTX reference count if exists.
- * This should only happen if switching ctxs!*/
- if (!newSSL) {
- WOLFSSL_MSG("freeing old ctx to decrement reference count. Switching ctx.");
- wolfSSL_CTX_free(ssl->ctx);
- }
- /* increment CTX reference count */
- if ((ret = SSL_CTX_RefCount(ctx, 1)) < 0) {
- return ret;
- }
- ret = WOLFSSL_SUCCESS; /* set default ret */
- ssl->ctx = ctx; /* only for passing to calls, options could change */
- ssl->version = ctx->method->version;
- #ifdef HAVE_ECC
- ssl->eccTempKeySz = ctx->eccTempKeySz;
- ssl->ecdhCurveOID = ctx->ecdhCurveOID;
- #endif
- #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
- ssl->pkCurveOID = ctx->pkCurveOID;
- #endif
- #ifdef OPENSSL_EXTRA
- ssl->options.mask = ctx->mask;
- ssl->CBIS = ctx->CBIS;
- #endif
- ssl->timeout = ctx->timeout;
- ssl->verifyCallback = ctx->verifyCallback;
- ssl->options.side = ctx->method->side;
- ssl->options.downgrade = ctx->method->downgrade;
- ssl->options.minDowngrade = ctx->minDowngrade;
- ssl->options.haveDH = ctx->haveDH;
- ssl->options.haveNTRU = ctx->haveNTRU;
- ssl->options.haveECDSAsig = ctx->haveECDSAsig;
- ssl->options.haveECC = ctx->haveECC;
- ssl->options.haveStaticECC = ctx->haveStaticECC;
- #ifndef NO_PSK
- ssl->options.havePSK = ctx->havePSK;
- ssl->options.client_psk_cb = ctx->client_psk_cb;
- ssl->options.server_psk_cb = ctx->server_psk_cb;
- #ifdef WOLFSSL_TLS13
- ssl->options.client_psk_tls13_cb = ctx->client_psk_tls13_cb;
- ssl->options.server_psk_tls13_cb = ctx->server_psk_tls13_cb;
- #endif
- #endif /* NO_PSK */
- #ifdef WOLFSSL_EARLY_DATA
- if (ssl->options.side == WOLFSSL_SERVER_END)
- ssl->options.maxEarlyDataSz = ctx->maxEarlyDataSz;
- #endif
- #ifdef HAVE_ANON
- ssl->options.haveAnon = ctx->haveAnon;
- #endif
- #ifndef NO_DH
- ssl->options.minDhKeySz = ctx->minDhKeySz;
- ssl->options.maxDhKeySz = ctx->maxDhKeySz;
- #endif
- #ifndef NO_RSA
- ssl->options.minRsaKeySz = ctx->minRsaKeySz;
- #endif
- #ifdef HAVE_ECC
- ssl->options.minEccKeySz = ctx->minEccKeySz;
- #endif
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- ssl->options.verifyDepth = ctx->verifyDepth;
- #endif
- ssl->options.sessionCacheOff = ctx->sessionCacheOff;
- ssl->options.sessionCacheFlushOff = ctx->sessionCacheFlushOff;
- #ifdef HAVE_EXT_CACHE
- ssl->options.internalCacheOff = ctx->internalCacheOff;
- #endif
- ssl->options.verifyPeer = ctx->verifyPeer;
- ssl->options.verifyNone = ctx->verifyNone;
- ssl->options.failNoCert = ctx->failNoCert;
- ssl->options.failNoCertxPSK = ctx->failNoCertxPSK;
- ssl->options.sendVerify = ctx->sendVerify;
- ssl->options.partialWrite = ctx->partialWrite;
- ssl->options.quietShutdown = ctx->quietShutdown;
- ssl->options.groupMessages = ctx->groupMessages;
- #ifndef NO_DH
- #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
- !defined(HAVE_SELFTEST)
- ssl->options.dhKeyTested = ctx->dhKeyTested;
- #endif
- ssl->buffers.serverDH_P = ctx->serverDH_P;
- ssl->buffers.serverDH_G = ctx->serverDH_G;
- #endif
- #ifndef NO_CERTS
- /* ctx still owns certificate, certChain, key, dh, and cm */
- ssl->buffers.certificate = ctx->certificate;
- ssl->buffers.certChain = ctx->certChain;
- #ifdef WOLFSSL_TLS13
- ssl->buffers.certChainCnt = ctx->certChainCnt;
- #endif
- ssl->buffers.key = ctx->privateKey;
- ssl->buffers.keyType = ctx->privateKeyType;
- ssl->buffers.keyId = ctx->privateKeyId;
- ssl->buffers.keySz = ctx->privateKeySz;
- ssl->buffers.keyDevId = ctx->privateKeyDevId;
- #endif
- #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
- ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
- (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
- ssl->options.cacheMessages = ssl->options.side == WOLFSSL_SERVER_END ||
- ssl->buffers.keyType == ed25519_sa_algo ||
- ssl->buffers.keyType == ed448_sa_algo;
- #endif
- #ifdef WOLFSSL_ASYNC_CRYPT
- ssl->devId = ctx->devId;
- #endif
- if (writeDup == 0) {
- #ifndef NO_PSK
- if (ctx->server_hint[0]) { /* set in CTX */
- XSTRNCPY(ssl->arrays->server_hint, ctx->server_hint,
- sizeof(ssl->arrays->server_hint));
- ssl->arrays->server_hint[MAX_PSK_ID_LEN] = '\0'; /* null term */
- }
- #endif /* NO_PSK */
- if (ctx->suites) {
- #ifndef SINGLE_THREADED
- *ssl->suites = *ctx->suites;
- #else
- ssl->suites = ctx->suites;
- #endif
- }
- else {
- XMEMSET(ssl->suites, 0, sizeof(Suites));
- }
- if (ssl->options.side != WOLFSSL_NEITHER_END) {
- /* Defer initializing suites until accept or connect */
- ret = InitSSL_Suites(ssl);
- }
- } /* writeDup check */
- #ifdef WOLFSSL_SESSION_EXPORT
- #ifdef WOLFSSL_DTLS
- ssl->dtls_export = ctx->dtls_export; /* export function for session */
- #endif
- #endif
- ssl->CBIORecv = ctx->CBIORecv;
- ssl->CBIOSend = ctx->CBIOSend;
- #ifdef OPENSSL_EXTRA
- ssl->readAhead = ctx->readAhead;
- #endif
- ssl->verifyDepth = ctx->verifyDepth;
- return ret;
- }
- int InitHandshakeHashes(WOLFSSL* ssl)
- {
- int ret;
- /* make sure existing handshake hashes are free'd */
- if (ssl->hsHashes != NULL) {
- FreeHandshakeHashes(ssl);
- }
- /* allocate handshake hashes */
- ssl->hsHashes = (HS_Hashes*)XMALLOC(sizeof(HS_Hashes), ssl->heap,
- DYNAMIC_TYPE_HASHES);
- if (ssl->hsHashes == NULL) {
- WOLFSSL_MSG("HS_Hashes Memory error");
- return MEMORY_E;
- }
- XMEMSET(ssl->hsHashes, 0, sizeof(HS_Hashes));
- #ifndef NO_OLD_TLS
- #ifndef NO_MD5
- ret = wc_InitMd5_ex(&ssl->hsHashes->hashMd5, ssl->heap, ssl->devId);
- if (ret != 0)
- return ret;
- #if defined(WOLFSSL_HASH_FLAGS) || defined(WOLF_CRYPTO_CB)
- wc_Md5SetFlags(&ssl->hsHashes->hashMd5, WC_HASH_FLAG_WILLCOPY);
- #endif
- #endif
- #ifndef NO_SHA
- ret = wc_InitSha_ex(&ssl->hsHashes->hashSha, ssl->heap, ssl->devId);
- if (ret != 0)
- return ret;
- #if defined(WOLFSSL_HASH_FLAGS) || defined(WOLF_CRYPTO_CB)
- wc_ShaSetFlags(&ssl->hsHashes->hashSha, WC_HASH_FLAG_WILLCOPY);
- #endif
- #endif
- #endif /* !NO_OLD_TLS */
- #ifndef NO_SHA256
- ret = wc_InitSha256_ex(&ssl->hsHashes->hashSha256, ssl->heap, ssl->devId);
- if (ret != 0)
- return ret;
- #if defined(WOLFSSL_HASH_FLAGS) || defined(WOLF_CRYPTO_CB)
- wc_Sha256SetFlags(&ssl->hsHashes->hashSha256, WC_HASH_FLAG_WILLCOPY);
- #endif
- #endif
- #ifdef WOLFSSL_SHA384
- ret = wc_InitSha384_ex(&ssl->hsHashes->hashSha384, ssl->heap, ssl->devId);
- if (ret != 0)
- return ret;
- #if defined(WOLFSSL_HASH_FLAGS) || defined(WOLF_CRYPTO_CB)
- wc_Sha384SetFlags(&ssl->hsHashes->hashSha384, WC_HASH_FLAG_WILLCOPY);
- #endif
- #endif
- #ifdef WOLFSSL_SHA512
- ret = wc_InitSha512_ex(&ssl->hsHashes->hashSha512, ssl->heap, ssl->devId);
- if (ret != 0)
- return ret;
- #if defined(WOLFSSL_HASH_FLAGS) || defined(WOLF_CRYPTO_CB)
- wc_Sha512SetFlags(&ssl->hsHashes->hashSha512, WC_HASH_FLAG_WILLCOPY);
- #endif
- #endif
- return ret;
- }
- void FreeHandshakeHashes(WOLFSSL* ssl)
- {
- if (ssl->hsHashes) {
- #ifndef NO_OLD_TLS
- #ifndef NO_MD5
- wc_Md5Free(&ssl->hsHashes->hashMd5);
- #endif
- #ifndef NO_SHA
- wc_ShaFree(&ssl->hsHashes->hashSha);
- #endif
- #endif /* !NO_OLD_TLS */
- #ifndef NO_SHA256
- wc_Sha256Free(&ssl->hsHashes->hashSha256);
- #endif
- #ifdef WOLFSSL_SHA384
- wc_Sha384Free(&ssl->hsHashes->hashSha384);
- #endif
- #ifdef WOLFSSL_SHA512
- wc_Sha512Free(&ssl->hsHashes->hashSha512);
- #endif
- #if (defined(HAVE_ED25519) || defined(HAVE_ED448)) && \
- !defined(WOLFSSL_NO_CLIENT_AUTH)
- if (ssl->hsHashes->messages != NULL) {
- XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES);
- ssl->hsHashes->messages = NULL;
- }
- #endif
- XFREE(ssl->hsHashes, ssl->heap, DYNAMIC_TYPE_HASHES);
- ssl->hsHashes = NULL;
- }
- }
- /* init everything to 0, NULL, default values before calling anything that may
- fail so that destructor has a "good" state to cleanup
- ssl object to initialize
- ctx parent factory
- writeDup flag indicating this is a write dup only
- 0 on success */
- int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
- {
- int ret;
- XMEMSET(ssl, 0, sizeof(WOLFSSL));
- #if defined(WOLFSSL_STATIC_MEMORY)
- if (ctx->heap != NULL) {
- WOLFSSL_HEAP_HINT* ssl_hint;
- WOLFSSL_HEAP_HINT* ctx_hint;
- /* avoid dereferencing a test value */
- #ifdef WOLFSSL_HEAP_TEST
- if (ctx->heap == (void*)WOLFSSL_HEAP_TEST) {
- ssl->heap = ctx->heap;
- }
- else {
- #endif
- ssl->heap = (WOLFSSL_HEAP_HINT*)XMALLOC(sizeof(WOLFSSL_HEAP_HINT),
- ctx->heap, DYNAMIC_TYPE_SSL);
- if (ssl->heap == NULL) {
- return MEMORY_E;
- }
- XMEMSET(ssl->heap, 0, sizeof(WOLFSSL_HEAP_HINT));
- ssl_hint = ((WOLFSSL_HEAP_HINT*)(ssl->heap));
- ctx_hint = ((WOLFSSL_HEAP_HINT*)(ctx->heap));
- /* lock and check IO count / handshake count */
- if (wc_LockMutex(&(ctx_hint->memory->memory_mutex)) != 0) {
- WOLFSSL_MSG("Bad memory_mutex lock");
- XFREE(ssl->heap, ctx->heap, DYNAMIC_TYPE_SSL);
- ssl->heap = NULL; /* free and set to NULL for IO counter */
- return BAD_MUTEX_E;
- }
- if (ctx_hint->memory->maxHa > 0 &&
- ctx_hint->memory->maxHa <= ctx_hint->memory->curHa) {
- WOLFSSL_MSG("At max number of handshakes for static memory");
- wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
- XFREE(ssl->heap, ctx->heap, DYNAMIC_TYPE_SSL);
- ssl->heap = NULL; /* free and set to NULL for IO counter */
- return MEMORY_E;
- }
- if (ctx_hint->memory->maxIO > 0 &&
- ctx_hint->memory->maxIO <= ctx_hint->memory->curIO) {
- WOLFSSL_MSG("At max number of IO allowed for static memory");
- wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
- XFREE(ssl->heap, ctx->heap, DYNAMIC_TYPE_SSL);
- ssl->heap = NULL; /* free and set to NULL for IO counter */
- return MEMORY_E;
- }
- ctx_hint->memory->curIO++;
- ctx_hint->memory->curHa++;
- ssl_hint->memory = ctx_hint->memory;
- ssl_hint->haFlag = 1;
- wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
- /* check if tracking stats */
- if (ctx_hint->memory->flag & WOLFMEM_TRACK_STATS) {
- ssl_hint->stats = (WOLFSSL_MEM_CONN_STATS*)XMALLOC(
- sizeof(WOLFSSL_MEM_CONN_STATS), ctx->heap, DYNAMIC_TYPE_SSL);
- if (ssl_hint->stats == NULL) {
- return MEMORY_E;
- }
- XMEMSET(ssl_hint->stats, 0, sizeof(WOLFSSL_MEM_CONN_STATS));
- }
- /* check if using fixed IO buffers */
- if (ctx_hint->memory->flag & WOLFMEM_IO_POOL_FIXED) {
- if (wc_LockMutex(&(ctx_hint->memory->memory_mutex)) != 0) {
- WOLFSSL_MSG("Bad memory_mutex lock");
- return BAD_MUTEX_E;
- }
- if (SetFixedIO(ctx_hint->memory, &(ssl_hint->inBuf)) != 1) {
- wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
- return MEMORY_E;
- }
- if (SetFixedIO(ctx_hint->memory, &(ssl_hint->outBuf)) != 1) {
- wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
- return MEMORY_E;
- }
- if (ssl_hint->outBuf == NULL || ssl_hint->inBuf == NULL) {
- WOLFSSL_MSG("Not enough memory to create fixed IO buffers");
- wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
- return MEMORY_E;
- }
- wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
- }
- #ifdef WOLFSSL_HEAP_TEST
- }
- #endif
- }
- else {
- ssl->heap = ctx->heap;
- }
- #else
- ssl->heap = ctx->heap; /* carry over user heap without static memory */
- #endif /* WOLFSSL_STATIC_MEMORY */
- ssl->buffers.inputBuffer.buffer = ssl->buffers.inputBuffer.staticBuffer;
- ssl->buffers.inputBuffer.bufferSize = STATIC_BUFFER_LEN;
- ssl->buffers.outputBuffer.buffer = ssl->buffers.outputBuffer.staticBuffer;
- ssl->buffers.outputBuffer.bufferSize = STATIC_BUFFER_LEN;
- #ifdef KEEP_PEER_CERT
- InitX509(&ssl->peerCert, 0, ssl->heap);
- #endif
- ssl->rfd = -1; /* set to invalid descriptor */
- ssl->wfd = -1;
- ssl->devId = ctx->devId; /* device for async HW (from wolfAsync_DevOpen) */
- ssl->IOCB_ReadCtx = &ssl->rfd; /* prevent invalid pointer access if not */
- ssl->IOCB_WriteCtx = &ssl->wfd; /* correctly set */
- #ifdef HAVE_NETX
- ssl->IOCB_ReadCtx = &ssl->nxCtx; /* default NetX IO ctx, same for read */
- ssl->IOCB_WriteCtx = &ssl->nxCtx; /* and write */
- #elif defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP)
- ssl->mnCtx = mynewt_ctx_new();
- if(!ssl->mnCtx) {
- return MEMORY_E;
- }
- ssl->IOCB_ReadCtx = ssl->mnCtx; /* default Mynewt IO ctx, same for read */
- ssl->IOCB_WriteCtx = ssl->mnCtx; /* and write */
- #elif defined (WOLFSSL_GNRC)
- ssl->IOCB_ReadCtx = ssl->gnrcCtx;
- ssl->IOCB_WriteCtx = ssl->gnrcCtx;
- #endif
- /* initialize states */
- ssl->options.serverState = NULL_STATE;
- ssl->options.clientState = NULL_STATE;
- ssl->options.connectState = CONNECT_BEGIN;
- ssl->options.acceptState = ACCEPT_BEGIN;
- ssl->options.handShakeState = NULL_STATE;
- ssl->options.processReply = doProcessInit;
- ssl->options.asyncState = TLS_ASYNC_BEGIN;
- ssl->options.buildMsgState = BUILD_MSG_BEGIN;
- ssl->encrypt.state = CIPHER_STATE_BEGIN;
- ssl->decrypt.state = CIPHER_STATE_BEGIN;
- #ifndef NO_DH
- #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
- !defined(HAVE_SELFTEST)
- ssl->options.dhDoKeyTest = 1;
- #endif
- #endif
- #ifdef WOLFSSL_DTLS
- #ifdef WOLFSSL_SCTP
- ssl->options.dtlsSctp = ctx->dtlsSctp;
- #endif
- #if defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU)
- ssl->dtlsMtuSz = ctx->dtlsMtuSz;
- ssl->dtls_expected_rx = ssl->dtlsMtuSz;
- #else
- ssl->dtls_expected_rx = MAX_MTU;
- #endif
- ssl->dtls_timeout_init = DTLS_TIMEOUT_INIT;
- ssl->dtls_timeout_max = DTLS_TIMEOUT_MAX;
- ssl->dtls_timeout = ssl->dtls_timeout_init;
- ssl->buffers.dtlsCtx.rfd = -1;
- ssl->buffers.dtlsCtx.wfd = -1;
- #endif
- #ifndef WOLFSSL_AEAD_ONLY
- #ifndef NO_OLD_TLS
- ssl->hmac = SSL_hmac; /* default to SSLv3 */
- #elif !defined(WOLFSSL_NO_TLS12)
- ssl->hmac = TLS_hmac;
- #endif
- #endif
- ssl->cipher.ssl = ssl;
- #ifdef HAVE_EXTENDED_MASTER
- ssl->options.haveEMS = ctx->haveEMS;
- #endif
- ssl->options.useClientOrder = ctx->useClientOrder;
- ssl->options.mutualAuth = ctx->mutualAuth;
- #ifdef WOLFSSL_TLS13
- #ifdef HAVE_SESSION_TICKET
- ssl->options.noTicketTls13 = ctx->noTicketTls13;
- #endif
- ssl->options.noPskDheKe = ctx->noPskDheKe;
- #if defined(WOLFSSL_POST_HANDSHAKE_AUTH)
- ssl->options.postHandshakeAuth = ctx->postHandshakeAuth;
- #endif
- if (ctx->numGroups > 0) {
- XMEMCPY(ssl->group, ctx->group, sizeof(*ctx->group) * ctx->numGroups);
- ssl->numGroups = ctx->numGroups;
- }
- #endif
- #ifdef HAVE_TLS_EXTENSIONS
- #ifdef HAVE_MAX_FRAGMENT
- ssl->max_fragment = MAX_RECORD_SIZE;
- #endif
- #ifdef HAVE_ALPN
- ssl->alpn_client_list = NULL;
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
- ssl->alpnSelect = ctx->alpnSelect;
- ssl->alpnSelectArg = ctx->alpnSelectArg;
- #endif
- #endif
- #ifdef HAVE_SUPPORTED_CURVES
- ssl->options.userCurves = ctx->userCurves;
- #endif
- #endif /* HAVE_TLS_EXTENSIONS */
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- ssl->options.disallowEncThenMac = ctx->disallowEncThenMac;
- #endif
- /* default alert state (none) */
- ssl->alert_history.last_rx.code = -1;
- ssl->alert_history.last_rx.level = -1;
- ssl->alert_history.last_tx.code = -1;
- ssl->alert_history.last_tx.level = -1;
- #ifdef OPENSSL_EXTRA
- /* copy over application session context ID */
- ssl->sessionCtxSz = ctx->sessionCtxSz;
- XMEMCPY(ssl->sessionCtx, ctx->sessionCtx, ctx->sessionCtxSz);
- ssl->cbioFlag = ctx->cbioFlag;
- #endif
- InitCiphers(ssl);
- InitCipherSpecs(&ssl->specs);
- /* all done with init, now can return errors, call other stuff */
- if (!writeDup) {
- /* arrays */
- ssl->arrays = (Arrays*)XMALLOC(sizeof(Arrays), ssl->heap,
- DYNAMIC_TYPE_ARRAYS);
- if (ssl->arrays == NULL) {
- WOLFSSL_MSG("Arrays Memory error");
- return MEMORY_E;
- }
- XMEMSET(ssl->arrays, 0, sizeof(Arrays));
- #if defined(WOLFSSL_TLS13) || defined(WOLFSSL_SNIFFER)
- ssl->arrays->preMasterSz = ENCRYPT_LEN;
- ssl->arrays->preMasterSecret = (byte*)XMALLOC(ENCRYPT_LEN, ssl->heap,
- DYNAMIC_TYPE_SECRET);
- if (ssl->arrays->preMasterSecret == NULL) {
- return MEMORY_E;
- }
- XMEMSET(ssl->arrays->preMasterSecret, 0, ENCRYPT_LEN);
- #endif
- #ifdef OPENSSL_EXTRA
- if ((ssl->param = (WOLFSSL_X509_VERIFY_PARAM*)XMALLOC(
- sizeof(WOLFSSL_X509_VERIFY_PARAM),
- ssl->heap, DYNAMIC_TYPE_OPENSSL)) == NULL) {
- WOLFSSL_MSG("ssl->param memory error");
- return MEMORY_E;
- }
- XMEMSET(ssl->param, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM));
- #endif
- #ifdef SINGLE_THREADED
- if (ctx->suites == NULL)
- #endif
- {
- /* suites */
- ssl->suites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap,
- DYNAMIC_TYPE_SUITES);
- if (ssl->suites == NULL) {
- WOLFSSL_MSG("Suites Memory error");
- return MEMORY_E;
- }
- #ifdef OPENSSL_ALL
- ssl->suites->stack = NULL;
- #endif
- #ifdef SINGLE_THREADED
- ssl->options.ownSuites = 1;
- #endif
- }
- #ifdef SINGLE_THREADED
- else {
- ssl->options.ownSuites = 0;
- }
- #endif
- }
- /* Initialize SSL with the appropriate fields from it's ctx */
- /* requires valid arrays and suites unless writeDup ing */
- if ((ret = SetSSL_CTX(ssl, ctx, writeDup)) != WOLFSSL_SUCCESS)
- return ret;
- ssl->options.dtls = ssl->version.major == DTLS_MAJOR;
- #ifdef SINGLE_THREADED
- ssl->rng = ctx->rng; /* CTX may have one, if so use it */
- #endif
- if (ssl->rng == NULL) {
- /* RNG */
- ssl->rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), ssl->heap,DYNAMIC_TYPE_RNG);
- if (ssl->rng == NULL) {
- WOLFSSL_MSG("RNG Memory error");
- return MEMORY_E;
- }
- XMEMSET(ssl->rng, 0, sizeof(WC_RNG));
- ssl->options.weOwnRng = 1;
- /* FIPS RNG API does not accept a heap hint */
- #ifndef HAVE_FIPS
- if ( (ret = wc_InitRng_ex(ssl->rng, ssl->heap, ssl->devId)) != 0) {
- WOLFSSL_MSG("RNG Init error");
- return ret;
- }
- #else
- if ( (ret = wc_InitRng(ssl->rng)) != 0) {
- WOLFSSL_MSG("RNG Init error");
- return ret;
- }
- #endif
- }
- #ifdef HAVE_WRITE_DUP
- if (writeDup) {
- /* all done */
- return 0;
- }
- #endif
- /* hsHashes */
- ret = InitHandshakeHashes(ssl);
- if (ret != 0)
- return ret;
- #if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
- if (ssl->options.dtls && ssl->options.side == WOLFSSL_SERVER_END) {
- ret = wolfSSL_DTLS_SetCookieSecret(ssl, NULL, 0);
- if (ret != 0) {
- WOLFSSL_MSG("DTLS Cookie Secret error");
- return ret;
- }
- }
- #endif /* WOLFSSL_DTLS && !NO_WOLFSSL_SERVER */
- #ifdef HAVE_SECRET_CALLBACK
- ssl->sessionSecretCb = NULL;
- ssl->sessionSecretCtx = NULL;
- #ifdef WOLFSSL_TLS13
- ssl->tls13SecretCb = NULL;
- ssl->tls13SecretCtx = NULL;
- #endif
- #endif
- #ifdef HAVE_SESSION_TICKET
- ssl->session.ticket = ssl->session.staticTicket;
- #endif
- #ifdef WOLFSSL_MULTICAST
- if (ctx->haveMcast) {
- int i;
- ssl->options.haveMcast = 1;
- ssl->options.mcastID = ctx->mcastID;
- /* Force the state to look like handshake has completed. */
- /* Keying material is supplied externally. */
- ssl->options.serverState = SERVER_FINISHED_COMPLETE;
- ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
- ssl->options.connectState = SECOND_REPLY_DONE;
- ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE;
- ssl->options.handShakeState = HANDSHAKE_DONE;
- ssl->options.handShakeDone = 1;
- for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++)
- ssl->keys.peerSeq[i].peerId = INVALID_PEER_ID;
- }
- #endif
- #ifdef HAVE_SECURE_RENEGOTIATION
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- int useSecureReneg = ssl->ctx->useSecureReneg;
- /* use secure renegotiation by default (not recommend) */
- #ifdef WOLFSSL_SECURE_RENEGOTIATION_ON_BY_DEFAULT
- useSecureReneg = 1;
- #endif
- if (useSecureReneg) {
- ret = wolfSSL_UseSecureRenegotiation(ssl);
- if (ret != WOLFSSL_SUCCESS)
- return ret;
- }
- }
- #endif /* HAVE_SECURE_RENEGOTIATION */
- return 0;
- }
- /* free use of temporary arrays */
- void FreeArrays(WOLFSSL* ssl, int keep)
- {
- if (ssl->arrays) {
- if (keep) {
- /* keeps session id for user retrieval */
- XMEMCPY(ssl->session.sessionID, ssl->arrays->sessionID, ID_LEN);
- ssl->session.sessionIDSz = ssl->arrays->sessionIDSz;
- }
- if (ssl->arrays->preMasterSecret) {
- XFREE(ssl->arrays->preMasterSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
- ssl->arrays->preMasterSecret = NULL;
- }
- XFREE(ssl->arrays->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
- ssl->arrays->pendingMsg = NULL;
- ForceZero(ssl->arrays, sizeof(Arrays)); /* clear arrays struct */
- }
- XFREE(ssl->arrays, ssl->heap, DYNAMIC_TYPE_ARRAYS);
- ssl->arrays = NULL;
- }
- void FreeKey(WOLFSSL* ssl, int type, void** pKey)
- {
- if (ssl && pKey && *pKey) {
- switch (type) {
- #ifndef NO_RSA
- case DYNAMIC_TYPE_RSA:
- wc_FreeRsaKey((RsaKey*)*pKey);
- break;
- #endif /* ! NO_RSA */
- #ifdef HAVE_ECC
- case DYNAMIC_TYPE_ECC:
- wc_ecc_free((ecc_key*)*pKey);
- break;
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- case DYNAMIC_TYPE_ED25519:
- wc_ed25519_free((ed25519_key*)*pKey);
- break;
- #endif /* HAVE_ED25519 */
- #ifdef HAVE_CURVE25519
- case DYNAMIC_TYPE_CURVE25519:
- wc_curve25519_free((curve25519_key*)*pKey);
- break;
- #endif /* HAVE_CURVE25519 */
- #ifdef HAVE_ED448
- case DYNAMIC_TYPE_ED448:
- wc_ed448_free((ed448_key*)*pKey);
- break;
- #endif /* HAVE_ED448 */
- #ifdef HAVE_CURVE448
- case DYNAMIC_TYPE_CURVE448:
- wc_curve448_free((curve448_key*)*pKey);
- break;
- #endif /* HAVE_CURVE448 */
- #ifndef NO_DH
- case DYNAMIC_TYPE_DH:
- wc_FreeDhKey((DhKey*)*pKey);
- break;
- #endif /* !NO_DH */
- default:
- break;
- }
- XFREE(*pKey, ssl->heap, type);
- /* Reset pointer */
- *pKey = NULL;
- }
- }
- int AllocKey(WOLFSSL* ssl, int type, void** pKey)
- {
- int ret = BAD_FUNC_ARG;
- int sz = 0;
- if (ssl == NULL || pKey == NULL) {
- return BAD_FUNC_ARG;
- }
- /* Sanity check key destination */
- if (*pKey != NULL) {
- WOLFSSL_MSG("Key already present!");
- return BAD_STATE_E;
- }
- /* Determine size */
- switch (type) {
- #ifndef NO_RSA
- case DYNAMIC_TYPE_RSA:
- sz = sizeof(RsaKey);
- break;
- #endif /* ! NO_RSA */
- #ifdef HAVE_ECC
- case DYNAMIC_TYPE_ECC:
- sz = sizeof(ecc_key);
- break;
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- case DYNAMIC_TYPE_ED25519:
- sz = sizeof(ed25519_key);
- break;
- #endif /* HAVE_ED25519 */
- #ifdef HAVE_CURVE25519
- case DYNAMIC_TYPE_CURVE25519:
- sz = sizeof(curve25519_key);
- break;
- #endif /* HAVE_CURVE25519 */
- #ifdef HAVE_ED448
- case DYNAMIC_TYPE_ED448:
- sz = sizeof(ed448_key);
- break;
- #endif /* HAVE_ED448 */
- #ifdef HAVE_CURVE448
- case DYNAMIC_TYPE_CURVE448:
- sz = sizeof(curve448_key);
- break;
- #endif /* HAVE_CURVE448 */
- #ifndef NO_DH
- case DYNAMIC_TYPE_DH:
- sz = sizeof(DhKey);
- break;
- #endif /* !NO_DH */
- default:
- return BAD_FUNC_ARG;
- }
- if (sz == 0) {
- return NOT_COMPILED_IN;
- }
- /* Allocate memory for key */
- *pKey = XMALLOC(sz, ssl->heap, type);
- if (*pKey == NULL) {
- return MEMORY_E;
- }
- /* Initialize key */
- switch (type) {
- #ifndef NO_RSA
- case DYNAMIC_TYPE_RSA:
- ret = wc_InitRsaKey_ex((RsaKey*)*pKey, ssl->heap, ssl->devId);
- break;
- #endif /* ! NO_RSA */
- #ifdef HAVE_ECC
- case DYNAMIC_TYPE_ECC:
- ret = wc_ecc_init_ex((ecc_key*)*pKey, ssl->heap, ssl->devId);
- break;
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- case DYNAMIC_TYPE_ED25519:
- wc_ed25519_init((ed25519_key*)*pKey);
- ret = 0;
- break;
- #endif /* HAVE_CURVE25519 */
- #ifdef HAVE_CURVE25519
- case DYNAMIC_TYPE_CURVE25519:
- wc_curve25519_init((curve25519_key*)*pKey);
- ret = 0;
- break;
- #endif /* HAVE_CURVE25519 */
- #ifdef HAVE_ED448
- case DYNAMIC_TYPE_ED448:
- wc_ed448_init((ed448_key*)*pKey);
- ret = 0;
- break;
- #endif /* HAVE_CURVE448 */
- #ifdef HAVE_CURVE448
- case DYNAMIC_TYPE_CURVE448:
- wc_curve448_init((curve448_key*)*pKey);
- ret = 0;
- break;
- #endif /* HAVE_CURVE448 */
- #ifndef NO_DH
- case DYNAMIC_TYPE_DH:
- ret = wc_InitDhKey_ex((DhKey*)*pKey, ssl->heap, ssl->devId);
- break;
- #endif /* !NO_DH */
- default:
- return BAD_FUNC_ARG;
- }
- /* On error free handshake key */
- if (ret != 0) {
- FreeKey(ssl, type, pKey);
- }
- return ret;
- }
- #if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
- defined(HAVE_CURVE25519) || defined(HHAVE_ED448) || defined(HAVE_CURVE448)
- static int ReuseKey(WOLFSSL* ssl, int type, void* pKey)
- {
- int ret = 0;
- (void)ssl;
- switch (type) {
- #ifndef NO_RSA
- case DYNAMIC_TYPE_RSA:
- wc_FreeRsaKey((RsaKey*)pKey);
- ret = wc_InitRsaKey_ex((RsaKey*)pKey, ssl->heap, ssl->devId);
- break;
- #endif /* ! NO_RSA */
- #ifdef HAVE_ECC
- case DYNAMIC_TYPE_ECC:
- wc_ecc_free((ecc_key*)pKey);
- ret = wc_ecc_init_ex((ecc_key*)pKey, ssl->heap, ssl->devId);
- break;
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- case DYNAMIC_TYPE_ED25519:
- wc_ed25519_free((ed25519_key*)pKey);
- ret = wc_ed25519_init((ed25519_key*)pKey);
- break;
- #endif /* HAVE_CURVE25519 */
- #ifdef HAVE_CURVE25519
- case DYNAMIC_TYPE_CURVE25519:
- wc_curve25519_free((curve25519_key*)pKey);
- ret = wc_curve25519_init((curve25519_key*)pKey);
- break;
- #endif /* HAVE_CURVE25519 */
- #ifdef HAVE_ED448
- case DYNAMIC_TYPE_ED448:
- wc_ed448_free((ed448_key*)pKey);
- ret = wc_ed448_init((ed448_key*)pKey);
- break;
- #endif /* HAVE_CURVE448 */
- #ifdef HAVE_CURVE448
- case DYNAMIC_TYPE_CURVE448:
- wc_curve448_free((curve448_key*)pKey);
- ret = wc_curve448_init((curve448_key*)pKey);
- break;
- #endif /* HAVE_CURVE448 */
- #ifndef NO_DH
- case DYNAMIC_TYPE_DH:
- wc_FreeDhKey((DhKey*)pKey);
- ret = wc_InitDhKey_ex((DhKey*)pKey, ssl->heap, ssl->devId);
- break;
- #endif /* !NO_DH */
- default:
- return BAD_FUNC_ARG;
- }
- return ret;
- }
- #endif
- void FreeKeyExchange(WOLFSSL* ssl)
- {
- /* Cleanup signature buffer */
- if (ssl->buffers.sig.buffer) {
- XFREE(ssl->buffers.sig.buffer, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- ssl->buffers.sig.buffer = NULL;
- ssl->buffers.sig.length = 0;
- }
- /* Cleanup digest buffer */
- if (ssl->buffers.digest.buffer) {
- XFREE(ssl->buffers.digest.buffer, ssl->heap, DYNAMIC_TYPE_DIGEST);
- ssl->buffers.digest.buffer = NULL;
- ssl->buffers.digest.length = 0;
- }
- /* Free handshake key */
- FreeKey(ssl, ssl->hsType, &ssl->hsKey);
- #ifndef NO_DH
- /* Free temp DH key */
- FreeKey(ssl, DYNAMIC_TYPE_DH, (void**)&ssl->buffers.serverDH_Key);
- #endif
- /* Cleanup async */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ssl->async.freeArgs) {
- ssl->async.freeArgs(ssl, ssl->async.args);
- ssl->async.freeArgs = NULL;
- }
- #endif
- }
- /* Free up all memory used by Suites structure from WOLFSSL */
- void FreeSuites(WOLFSSL* ssl)
- {
- #ifdef SINGLE_THREADED
- if (ssl->options.ownSuites)
- #endif
- {
- #ifdef OPENSSL_ALL
- wolfSSL_sk_SSL_CIPHER_free(ssl->suites->stack);
- #endif
- XFREE(ssl->suites, ssl->heap, DYNAMIC_TYPE_SUITES);
- }
- ssl->suites = NULL;
- }
- /* In case holding SSL object in array and don't want to free actual ssl */
- void SSL_ResourceFree(WOLFSSL* ssl)
- {
- /* Note: any resources used during the handshake should be released in the
- * function FreeHandshakeResources(). Be careful with the special cases
- * like the RNG which may optionally be kept for the whole session. (For
- * example with the RNG, it isn't used beyond the handshake except when
- * using stream ciphers where it is retained. */
- FreeCiphers(ssl);
- FreeArrays(ssl, 0);
- FreeKeyExchange(ssl);
- if (ssl->options.weOwnRng) {
- wc_FreeRng(ssl->rng);
- XFREE(ssl->rng, ssl->heap, DYNAMIC_TYPE_RNG);
- }
- FreeSuites(ssl);
- FreeHandshakeHashes(ssl);
- XFREE(ssl->buffers.domainName.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
- /* clear keys struct after session */
- ForceZero(&ssl->keys, sizeof(Keys));
- #ifdef WOLFSSL_TLS13
- if (ssl->options.tls1_3) {
- ForceZero(&ssl->clientSecret, sizeof(ssl->clientSecret));
- ForceZero(&ssl->serverSecret, sizeof(ssl->serverSecret));
- }
- #endif
- #ifndef NO_DH
- if (ssl->buffers.serverDH_Priv.buffer) {
- ForceZero(ssl->buffers.serverDH_Priv.buffer,
- ssl->buffers.serverDH_Priv.length);
- }
- XFREE(ssl->buffers.serverDH_Priv.buffer, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
- XFREE(ssl->buffers.serverDH_Pub.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- /* parameters (p,g) may be owned by ctx */
- if (ssl->buffers.weOwnDH) {
- XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- }
- #endif /* !NO_DH */
- #ifndef NO_CERTS
- ssl->keepCert = 0; /* make sure certificate is free'd */
- wolfSSL_UnloadCertsKeys(ssl);
- #endif
- #ifndef NO_RSA
- FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
- ssl->peerRsaKeyPresent = 0;
- #endif
- #ifdef WOLFSSL_RENESAS_TSIP_TLS
- XFREE(ssl->peerTsipEncRsaKeyIndex, ssl->heap, DYNAMIC_TYPE_RSA);
- #endif
- if (ssl->buffers.inputBuffer.dynamicFlag)
- ShrinkInputBuffer(ssl, FORCED_FREE);
- if (ssl->buffers.outputBuffer.dynamicFlag)
- ShrinkOutputBuffer(ssl);
- #if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
- XFREE(ssl->buffers.tls13CookieSecret.buffer, ssl->heap,
- DYNAMIC_TYPE_COOKIE_PWD);
- #endif
- #ifdef WOLFSSL_DTLS
- DtlsMsgPoolReset(ssl);
- if (ssl->dtls_rx_msg_list != NULL) {
- DtlsMsgListDelete(ssl->dtls_rx_msg_list, ssl->heap);
- ssl->dtls_rx_msg_list = NULL;
- ssl->dtls_rx_msg_list_sz = 0;
- }
- XFREE(ssl->buffers.dtlsCtx.peer.sa, ssl->heap, DYNAMIC_TYPE_SOCKADDR);
- ssl->buffers.dtlsCtx.peer.sa = NULL;
- #ifndef NO_WOLFSSL_SERVER
- XFREE(ssl->buffers.dtlsCookieSecret.buffer, ssl->heap,
- DYNAMIC_TYPE_COOKIE_PWD);
- #endif
- #endif /* WOLFSSL_DTLS */
- #ifdef OPENSSL_EXTRA
- if (ssl->biord != ssl->biowr) /* only free write if different */
- wolfSSL_BIO_free(ssl->biowr);
- wolfSSL_BIO_free(ssl->biord); /* always free read bio */
- ssl->biowr = NULL;
- ssl->biord = NULL;
- #endif
- #ifdef HAVE_LIBZ
- FreeStreams(ssl);
- #endif
- #ifdef HAVE_ECC
- FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccKey);
- ssl->peerEccKeyPresent = 0;
- FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
- ssl->peerEccDsaKeyPresent = 0;
- #endif
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) ||defined(HAVE_CURVE448)
- {
- int dtype = 0;
- #ifdef HAVE_ECC
- dtype = DYNAMIC_TYPE_ECC;
- #endif
- #ifdef HAVE_CURVE25519
- if (ssl->peerX25519KeyPresent
- #ifdef HAVE_ECC
- || ssl->eccTempKeyPresent == DYNAMIC_TYPE_CURVE25519
- #endif /* HAVE_ECC */
- )
- {
- dtype = DYNAMIC_TYPE_CURVE25519;
- }
- #endif /* HAVE_CURVE25519 */
- #ifdef HAVE_CURVE448
- if (ssl->peerX448KeyPresent
- #ifdef HAVE_ECC
- || ssl->eccTempKeyPresent == DYNAMIC_TYPE_CURVE448
- #endif /* HAVE_ECC */
- )
- {
- dtype = DYNAMIC_TYPE_CURVE448;
- }
- #endif /* HAVE_CURVE448 */
- FreeKey(ssl, dtype, (void**)&ssl->eccTempKey);
- ssl->eccTempKeyPresent = 0;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #ifdef HAVE_CURVE25519
- FreeKey(ssl, DYNAMIC_TYPE_CURVE25519, (void**)&ssl->peerX25519Key);
- ssl->peerX25519KeyPresent = 0;
- #endif
- #ifdef HAVE_ED25519
- FreeKey(ssl, DYNAMIC_TYPE_ED25519, (void**)&ssl->peerEd25519Key);
- ssl->peerEd25519KeyPresent = 0;
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->buffers.peerEd25519Key.buffer != NULL) {
- XFREE(ssl->buffers.peerEd25519Key.buffer, ssl->heap,
- DYNAMIC_TYPE_ED25519);
- ssl->buffers.peerEd25519Key.buffer = NULL;
- }
- #endif
- #endif
- #ifdef HAVE_CURVE448
- FreeKey(ssl, DYNAMIC_TYPE_CURVE448, (void**)&ssl->peerX448Key);
- ssl->peerX448KeyPresent = 0;
- #endif
- #ifdef HAVE_ED448
- FreeKey(ssl, DYNAMIC_TYPE_ED448, (void**)&ssl->peerEd448Key);
- ssl->peerEd448KeyPresent = 0;
- #ifdef HAVE_PK_CALLBACKS
- if (ssl->buffers.peerEd448Key.buffer != NULL) {
- XFREE(ssl->buffers.peerEd448Key.buffer, ssl->heap,
- DYNAMIC_TYPE_ED448);
- ssl->buffers.peerEd448Key.buffer = NULL;
- }
- #endif
- #endif
- #ifdef HAVE_PK_CALLBACKS
- #ifdef HAVE_ECC
- XFREE(ssl->buffers.peerEccDsaKey.buffer, ssl->heap, DYNAMIC_TYPE_ECC);
- #endif /* HAVE_ECC */
- #ifndef NO_RSA
- XFREE(ssl->buffers.peerRsaKey.buffer, ssl->heap, DYNAMIC_TYPE_RSA);
- #endif /* NO_RSA */
- #endif /* HAVE_PK_CALLBACKS */
- #ifdef HAVE_TLS_EXTENSIONS
- TLSX_FreeAll(ssl->extensions, ssl->heap);
- #ifdef HAVE_ALPN
- if (ssl->alpn_client_list != NULL) {
- XFREE(ssl->alpn_client_list, ssl->heap, DYNAMIC_TYPE_ALPN);
- ssl->alpn_client_list = NULL;
- }
- #endif
- #endif /* HAVE_TLS_EXTENSIONS */
- #if defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP)
- if (ssl->mnCtx) {
- mynewt_ctx_clear(ssl->mnCtx);
- ssl->mnCtx = NULL;
- }
- #endif
- #ifdef HAVE_NETX
- if (ssl->nxCtx.nxPacket)
- nx_packet_release(ssl->nxCtx.nxPacket);
- #endif
- #ifdef KEEP_PEER_CERT
- FreeX509(&ssl->peerCert);
- #endif
- #ifdef HAVE_SESSION_TICKET
- if (ssl->session.isDynamic) {
- XFREE(ssl->session.ticket, ssl->heap, DYNAMIC_TYPE_SESSION_TICK);
- ssl->session.ticket = ssl->session.staticTicket;
- ssl->session.isDynamic = 0;
- ssl->session.ticketLen = 0;
- }
- #endif
- #ifdef HAVE_EXT_CACHE
- wolfSSL_SESSION_free(ssl->extSession);
- #endif
- #ifdef HAVE_WRITE_DUP
- if (ssl->dupWrite) {
- FreeWriteDup(ssl);
- }
- #endif
- #ifdef OPENSSL_EXTRA
- if (ssl->param) {
- XFREE(ssl->param, ssl->heap, DYNAMIC_TYPE_OPENSSL);
- }
- #endif
- #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
- while (ssl->certReqCtx != NULL) {
- CertReqCtx* curr = ssl->certReqCtx;
- ssl->certReqCtx = curr->next;
- XFREE(curr, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif
- #ifdef WOLFSSL_STATIC_MEMORY
- /* check if using fixed io buffers and free them */
- if (ssl->heap != NULL) {
- #ifdef WOLFSSL_HEAP_TEST
- /* avoid dereferencing a test value */
- if (ssl->heap != (void*)WOLFSSL_HEAP_TEST) {
- #endif
- WOLFSSL_HEAP_HINT* ssl_hint = (WOLFSSL_HEAP_HINT*)ssl->heap;
- WOLFSSL_HEAP* ctx_heap;
- void* heap = ssl->ctx ? ssl->ctx->heap : ssl->heap;
- ctx_heap = ssl_hint->memory;
- if (wc_LockMutex(&(ctx_heap->memory_mutex)) != 0) {
- WOLFSSL_MSG("Bad memory_mutex lock");
- }
- ctx_heap->curIO--;
- if (FreeFixedIO(ctx_heap, &(ssl_hint->outBuf)) != 1) {
- WOLFSSL_MSG("Error freeing fixed output buffer");
- }
- if (FreeFixedIO(ctx_heap, &(ssl_hint->inBuf)) != 1) {
- WOLFSSL_MSG("Error freeing fixed output buffer");
- }
- if (ssl_hint->haFlag) { /* check if handshake count has been decreased*/
- ctx_heap->curHa--;
- }
- wc_UnLockMutex(&(ctx_heap->memory_mutex));
- /* check if tracking stats */
- if (ctx_heap->flag & WOLFMEM_TRACK_STATS) {
- XFREE(ssl_hint->stats, heap, DYNAMIC_TYPE_SSL);
- }
- XFREE(ssl->heap, heap, DYNAMIC_TYPE_SSL);
- #ifdef WOLFSSL_HEAP_TEST
- }
- #endif
- }
- #endif /* WOLFSSL_STATIC_MEMORY */
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
- wolfSSL_sk_CIPHER_free(ssl->supportedCiphers);
- wolfSSL_sk_X509_free(ssl->peerCertChain);
- #endif
- }
- /* Free any handshake resources no longer needed */
- void FreeHandshakeResources(WOLFSSL* ssl)
- {
- #ifdef HAVE_SECURE_RENEGOTIATION
- if (ssl->secure_renegotiation && ssl->secure_renegotiation->enabled) {
- WOLFSSL_MSG("Secure Renegotiation needs to retain handshake resources");
- return;
- }
- #endif
- /* input buffer */
- if (ssl->buffers.inputBuffer.dynamicFlag)
- ShrinkInputBuffer(ssl, NO_FORCED_FREE);
- #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
- if (!ssl->options.tls1_3)
- #endif
- {
- #ifndef OPENSSL_ALL
- /* free suites unless using compatibility layer */
- FreeSuites(ssl);
- #endif
- /* hsHashes */
- FreeHandshakeHashes(ssl);
- }
- /* RNG */
- if (ssl->options.tls1_1 == 0
- #ifndef WOLFSSL_AEAD_ONLY
- || ssl->specs.cipher_type == stream
- #endif
- #if defined(WOLFSSL_TLS13)
- #if !defined(WOLFSSL_POST_HANDSHAKE_AUTH)
- || ssl->options.tls1_3
- #elif !defined(HAVE_SESSION_TICKET)
- || (ssl->options.tls1_3 && ssl->options.side == WOLFSSL_SERVER_END)
- #endif
- #endif
- ) {
- if (ssl->options.weOwnRng) {
- wc_FreeRng(ssl->rng);
- XFREE(ssl->rng, ssl->heap, DYNAMIC_TYPE_RNG);
- ssl->rng = NULL;
- ssl->options.weOwnRng = 0;
- }
- }
- #ifdef WOLFSSL_DTLS
- /* DTLS_POOL */
- if (ssl->options.dtls) {
- DtlsMsgPoolReset(ssl);
- DtlsMsgListDelete(ssl->dtls_rx_msg_list, ssl->heap);
- ssl->dtls_rx_msg_list = NULL;
- ssl->dtls_rx_msg_list_sz = 0;
- }
- #endif
- #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) && \
- defined(HAVE_SESSION_TICKET)
- if (!ssl->options.tls1_3)
- #endif
- /* arrays */
- if (ssl->options.saveArrays == 0)
- FreeArrays(ssl, 1);
- #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
- if (!ssl->options.tls1_3 || ssl->options.side == WOLFSSL_CLIENT_END)
- #endif
- {
- #ifndef NO_RSA
- /* peerRsaKey */
- FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
- ssl->peerRsaKeyPresent = 0;
- #endif
- #ifdef HAVE_ECC
- FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
- ssl->peerEccDsaKeyPresent = 0;
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- FreeKey(ssl, DYNAMIC_TYPE_ED25519, (void**)&ssl->peerEd25519Key);
- ssl->peerEd25519KeyPresent = 0;
- #endif /* HAVE_ED25519 */
- #ifdef HAVE_ED448
- FreeKey(ssl, DYNAMIC_TYPE_ED448, (void**)&ssl->peerEd448Key);
- ssl->peerEd448KeyPresent = 0;
- #endif /* HAVE_ED448 */
- }
- #ifdef HAVE_ECC
- FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccKey);
- ssl->peerEccKeyPresent = 0;
- #endif
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
- {
- int dtype;
- #ifdef HAVE_ECC
- dtype = DYNAMIC_TYPE_ECC;
- #endif
- #ifdef HAVE_CURVE25519
- #ifdef HAVE_ECC
- if (ssl->peerX25519KeyPresent ||
- ssl->eccTempKeyPresent == DYNAMIC_TYPE_CURVE25519)
- #endif /* HAVE_ECC */
- {
- dtype = DYNAMIC_TYPE_CURVE25519;
- }
- #endif /* HAVE_CURVE25519 */
- #ifdef HAVE_CURVE448
- #ifdef HAVE_ECC
- if (ssl->peerX448KeyPresent ||
- ssl->eccTempKeyPresent == DYNAMIC_TYPE_CURVE448)
- #endif /* HAVE_ECC */
- {
- dtype = DYNAMIC_TYPE_CURVE448;
- }
- #endif /* HAVE_CURVE448 */
- FreeKey(ssl, dtype, (void**)&ssl->eccTempKey);
- ssl->eccTempKeyPresent = 0;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #ifdef HAVE_CURVE25519
- FreeKey(ssl, DYNAMIC_TYPE_CURVE25519, (void**)&ssl->peerX25519Key);
- ssl->peerX25519KeyPresent = 0;
- #endif
- #ifdef HAVE_CURVE448
- FreeKey(ssl, DYNAMIC_TYPE_CURVE448, (void**)&ssl->peerX448Key);
- ssl->peerX448KeyPresent = 0;
- #endif
- #ifndef NO_DH
- if (ssl->buffers.serverDH_Priv.buffer) {
- ForceZero(ssl->buffers.serverDH_Priv.buffer,
- ssl->buffers.serverDH_Priv.length);
- }
- XFREE(ssl->buffers.serverDH_Priv.buffer, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
- ssl->buffers.serverDH_Priv.buffer = NULL;
- XFREE(ssl->buffers.serverDH_Pub.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- ssl->buffers.serverDH_Pub.buffer = NULL;
- /* parameters (p,g) may be owned by ctx */
- if (ssl->buffers.weOwnDH) {
- XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- ssl->buffers.serverDH_G.buffer = NULL;
- XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- ssl->buffers.serverDH_P.buffer = NULL;
- }
- #endif /* !NO_DH */
- #ifndef NO_CERTS
- wolfSSL_UnloadCertsKeys(ssl);
- #endif
- #ifdef HAVE_PK_CALLBACKS
- #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
- if (!ssl->options.tls1_3 || ssl->options.side == WOLFSSL_CLIENT_END)
- #endif
- {
- #ifdef HAVE_ECC
- XFREE(ssl->buffers.peerEccDsaKey.buffer, ssl->heap, DYNAMIC_TYPE_ECC);
- ssl->buffers.peerEccDsaKey.buffer = NULL;
- #endif /* HAVE_ECC */
- #ifndef NO_RSA
- XFREE(ssl->buffers.peerRsaKey.buffer, ssl->heap, DYNAMIC_TYPE_RSA);
- ssl->buffers.peerRsaKey.buffer = NULL;
- #endif /* NO_RSA */
- #ifdef HAVE_ED25519
- XFREE(ssl->buffers.peerEd25519Key.buffer, ssl->heap,
- DYNAMIC_TYPE_ED25519);
- ssl->buffers.peerEd25519Key.buffer = NULL;
- #endif
- #ifdef HAVE_ED448
- XFREE(ssl->buffers.peerEd448Key.buffer, ssl->heap, DYNAMIC_TYPE_ED448);
- ssl->buffers.peerEd448Key.buffer = NULL;
- #endif
- }
- #endif /* HAVE_PK_CALLBACKS */
- #ifdef HAVE_QSH
- QSH_FreeAll(ssl);
- #endif
- #ifdef HAVE_SESSION_TICKET
- if (ssl->session.isDynamic) {
- XFREE(ssl->session.ticket, ssl->heap, DYNAMIC_TYPE_SESSION_TICK);
- ssl->session.ticket = ssl->session.staticTicket;
- ssl->session.isDynamic = 0;
- ssl->session.ticketLen = 0;
- }
- #endif
- #if defined(HAVE_TLS_EXTENSIONS) && !defined(HAVE_SNI) && \
- !defined(HAVE_ALPN) && !defined(WOLFSSL_POST_HANDSHAKE_AUTH)
- /* Some extensions need to be kept for post-handshake querying. */
- TLSX_FreeAll(ssl->extensions, ssl->heap);
- ssl->extensions = NULL;
- #endif
- #ifdef WOLFSSL_STATIC_MEMORY
- /* when done with handshake decrement current handshake count */
- if (ssl->heap != NULL) {
- #ifdef WOLFSSL_HEAP_TEST
- /* avoid dereferencing a test value */
- if (ssl->heap != (void*)WOLFSSL_HEAP_TEST) {
- #endif
- WOLFSSL_HEAP_HINT* ssl_hint = (WOLFSSL_HEAP_HINT*)ssl->heap;
- WOLFSSL_HEAP* ctx_heap;
- ctx_heap = ssl_hint->memory;
- if (wc_LockMutex(&(ctx_heap->memory_mutex)) != 0) {
- WOLFSSL_MSG("Bad memory_mutex lock");
- }
- ctx_heap->curHa--;
- ssl_hint->haFlag = 0; /* set to zero since handshake has been dec */
- wc_UnLockMutex(&(ctx_heap->memory_mutex));
- #ifdef WOLFSSL_HEAP_TEST
- }
- #endif
- }
- #endif /* WOLFSSL_STATIC_MEMORY */
- }
- /* heap argument is the heap hint used when creating SSL */
- void FreeSSL(WOLFSSL* ssl, void* heap)
- {
- if (ssl->ctx) {
- FreeSSL_Ctx(ssl->ctx); /* will decrement and free underlying CTX if 0 */
- }
- SSL_ResourceFree(ssl);
- XFREE(ssl, heap, DYNAMIC_TYPE_SSL);
- (void)heap;
- }
- #if !defined(NO_OLD_TLS) || defined(WOLFSSL_DTLS) || \
- ((defined(HAVE_CHACHA) || defined(HAVE_AESCCM) || defined(HAVE_AESGCM)) \
- && defined(HAVE_AEAD))
- #if defined(WOLFSSL_DTLS) || !defined(WOLFSSL_NO_TLS12)
- static WC_INLINE void GetSEQIncrement(WOLFSSL* ssl, int verify, word32 seq[2])
- {
- if (verify) {
- seq[0] = ssl->keys.peer_sequence_number_hi;
- seq[1] = ssl->keys.peer_sequence_number_lo++;
- if (seq[1] > ssl->keys.peer_sequence_number_lo) {
- /* handle rollover */
- ssl->keys.peer_sequence_number_hi++;
- }
- }
- else {
- seq[0] = ssl->keys.sequence_number_hi;
- seq[1] = ssl->keys.sequence_number_lo++;
- if (seq[1] > ssl->keys.sequence_number_lo) {
- /* handle rollover */
- ssl->keys.sequence_number_hi++;
- }
- }
- }
- #endif /* WOLFSSL_DTLS || !WOLFSSL_NO_TLS12 */
- #ifdef WOLFSSL_DTLS
- static WC_INLINE void DtlsGetSEQ(WOLFSSL* ssl, int order, word32 seq[2])
- {
- if (order == PREV_ORDER) {
- /* Previous epoch case */
- if (ssl->options.haveMcast) {
- #ifdef WOLFSSL_MULTICAST
- seq[0] = (((word32)ssl->keys.dtls_epoch - 1) << 16) |
- (ssl->options.mcastID << 8) |
- (ssl->keys.dtls_prev_sequence_number_hi & 0xFF);
- #endif
- }
- else
- seq[0] = (((word32)ssl->keys.dtls_epoch - 1) << 16) |
- (ssl->keys.dtls_prev_sequence_number_hi & 0xFFFF);
- seq[1] = ssl->keys.dtls_prev_sequence_number_lo;
- }
- else if (order == PEER_ORDER) {
- if (ssl->options.haveMcast) {
- #ifdef WOLFSSL_MULTICAST
- seq[0] = ((word32)ssl->keys.curEpoch << 16) |
- (ssl->keys.curPeerId << 8) |
- (ssl->keys.curSeq_hi & 0xFF);
- #endif
- }
- else
- seq[0] = ((word32)ssl->keys.curEpoch << 16) |
- (ssl->keys.curSeq_hi & 0xFFFF);
- seq[1] = ssl->keys.curSeq_lo; /* explicit from peer */
- }
- else {
- if (ssl->options.haveMcast) {
- #ifdef WOLFSSL_MULTICAST
- seq[0] = ((word32)ssl->keys.dtls_epoch << 16) |
- (ssl->options.mcastID << 8) |
- (ssl->keys.dtls_sequence_number_hi & 0xFF);
- #endif
- }
- else
- seq[0] = ((word32)ssl->keys.dtls_epoch << 16) |
- (ssl->keys.dtls_sequence_number_hi & 0xFFFF);
- seq[1] = ssl->keys.dtls_sequence_number_lo;
- }
- }
- static WC_INLINE void DtlsSEQIncrement(WOLFSSL* ssl, int order)
- {
- word32 seq;
- if (order == PREV_ORDER) {
- seq = ssl->keys.dtls_prev_sequence_number_lo++;
- if (seq > ssl->keys.dtls_prev_sequence_number_lo) {
- /* handle rollover */
- ssl->keys.dtls_prev_sequence_number_hi++;
- }
- }
- else if (order == PEER_ORDER) {
- seq = ssl->keys.peer_sequence_number_lo++;
- if (seq > ssl->keys.peer_sequence_number_lo) {
- /* handle rollover */
- ssl->keys.peer_sequence_number_hi++;
- }
- }
- else {
- seq = ssl->keys.dtls_sequence_number_lo++;
- if (seq > ssl->keys.dtls_sequence_number_lo) {
- /* handle rollover */
- ssl->keys.dtls_sequence_number_hi++;
- }
- }
- }
- #endif /* WOLFSSL_DTLS */
- #if defined(WOLFSSL_DTLS) || !defined(WOLFSSL_NO_TLS12)
- static WC_INLINE void WriteSEQ(WOLFSSL* ssl, int verifyOrder, byte* out)
- {
- word32 seq[2] = {0, 0};
- if (!ssl->options.dtls) {
- GetSEQIncrement(ssl, verifyOrder, seq);
- }
- else {
- #ifdef WOLFSSL_DTLS
- DtlsGetSEQ(ssl, verifyOrder, seq);
- #endif
- }
- c32toa(seq[0], out);
- c32toa(seq[1], out + OPAQUE32_LEN);
- }
- #endif /* WOLFSSL_DTLS || !WOLFSSL_NO_TLS12 */
- #endif /* !NO_OLD_TLS || WOLFSSL_DTLS ||
- * ((HAVE_CHACHA || HAVE_AESCCM || HAVE_AESGCM) && HAVE_AEAD) */
- #ifdef WOLFSSL_DTLS
- /* functions for managing DTLS datagram reordering */
- /* Need to allocate space for the handshake message header. The hashing
- * routines assume the message pointer is still within the buffer that
- * has the headers, and will include those headers in the hash. The store
- * routines need to take that into account as well. New will allocate
- * extra space for the headers. */
- DtlsMsg* DtlsMsgNew(word32 sz, void* heap)
- {
- DtlsMsg* msg;
- (void)heap;
- msg = (DtlsMsg*)XMALLOC(sizeof(DtlsMsg), heap, DYNAMIC_TYPE_DTLS_MSG);
- if (msg != NULL) {
- XMEMSET(msg, 0, sizeof(DtlsMsg));
- msg->buf = (byte*)XMALLOC(sz + DTLS_HANDSHAKE_HEADER_SZ,
- heap, DYNAMIC_TYPE_DTLS_BUFFER);
- if (msg->buf != NULL) {
- msg->sz = sz;
- msg->type = no_shake;
- msg->msg = msg->buf + DTLS_HANDSHAKE_HEADER_SZ;
- }
- else {
- XFREE(msg, heap, DYNAMIC_TYPE_DTLS_MSG);
- msg = NULL;
- }
- }
- return msg;
- }
- void DtlsMsgDelete(DtlsMsg* item, void* heap)
- {
- (void)heap;
- if (item != NULL) {
- DtlsFrag* cur = item->fragList;
- while (cur != NULL) {
- DtlsFrag* next = cur->next;
- XFREE(cur, heap, DYNAMIC_TYPE_DTLS_FRAG);
- cur = next;
- }
- if (item->buf != NULL)
- XFREE(item->buf, heap, DYNAMIC_TYPE_DTLS_BUFFER);
- XFREE(item, heap, DYNAMIC_TYPE_DTLS_MSG);
- }
- }
- void DtlsMsgListDelete(DtlsMsg* head, void* heap)
- {
- DtlsMsg* next;
- while (head) {
- next = head->next;
- DtlsMsgDelete(head, heap);
- head = next;
- }
- }
- /* Create a DTLS Fragment from *begin - end, adjust new *begin and bytesLeft */
- static DtlsFrag* CreateFragment(word32* begin, word32 end, const byte* data,
- byte* buf, word32* bytesLeft, void* heap)
- {
- DtlsFrag* newFrag;
- word32 added = end - *begin + 1;
- (void)heap;
- newFrag = (DtlsFrag*)XMALLOC(sizeof(DtlsFrag), heap,
- DYNAMIC_TYPE_DTLS_FRAG);
- if (newFrag != NULL) {
- newFrag->next = NULL;
- newFrag->begin = *begin;
- newFrag->end = end;
- XMEMCPY(buf + *begin, data, added);
- *bytesLeft -= added;
- *begin = newFrag->end + 1;
- }
- return newFrag;
- }
- int DtlsMsgSet(DtlsMsg* msg, word32 seq, const byte* data, byte type,
- word32 fragOffset, word32 fragSz, void* heap)
- {
- if (msg != NULL && data != NULL && msg->fragSz <= msg->sz &&
- (fragOffset + fragSz) <= msg->sz) {
- DtlsFrag* cur = msg->fragList;
- DtlsFrag* prev = cur;
- DtlsFrag* newFrag;
- word32 bytesLeft = fragSz; /* could be overlapping fragment */
- word32 startOffset = fragOffset;
- word32 added;
- msg->seq = seq;
- msg->type = type;
- if (fragOffset == 0) {
- XMEMCPY(msg->buf, data - DTLS_HANDSHAKE_HEADER_SZ,
- DTLS_HANDSHAKE_HEADER_SZ);
- c32to24(msg->sz, msg->msg - DTLS_HANDSHAKE_FRAG_SZ);
- }
- /* if no message data, just return */
- if (fragSz == 0)
- return 0;
- /* if list is empty add full fragment to front */
- if (cur == NULL) {
- newFrag = CreateFragment(&fragOffset, fragOffset + fragSz - 1, data,
- msg->msg, &bytesLeft, heap);
- if (newFrag == NULL)
- return MEMORY_E;
- msg->fragSz = fragSz;
- msg->fragList = newFrag;
- return 0;
- }
- /* add to front if before current front, up to next->begin */
- if (fragOffset < cur->begin) {
- word32 end = fragOffset + fragSz - 1;
- if (end >= cur->begin)
- end = cur->begin - 1;
- added = end - fragOffset + 1;
- newFrag = CreateFragment(&fragOffset, end, data, msg->msg,
- &bytesLeft, heap);
- if (newFrag == NULL)
- return MEMORY_E;
- msg->fragSz += added;
- newFrag->next = cur;
- msg->fragList = newFrag;
- }
- /* while we have bytes left, try to find a gap to fill */
- while (bytesLeft > 0) {
- /* get previous packet in list */
- while (cur && (fragOffset >= cur->begin)) {
- prev = cur;
- cur = cur->next;
- }
- /* don't add duplicate data */
- if (prev->end >= fragOffset) {
- if ( (fragOffset + bytesLeft - 1) <= prev->end)
- return 0;
- fragOffset = prev->end + 1;
- bytesLeft = startOffset + fragSz - fragOffset;
- }
- if (cur == NULL)
- /* we're at the end */
- added = bytesLeft;
- else
- /* we're in between two frames */
- added = min(bytesLeft, cur->begin - fragOffset);
- /* data already there */
- if (added == 0)
- continue;
- newFrag = CreateFragment(&fragOffset, fragOffset + added - 1,
- data + fragOffset - startOffset,
- msg->msg, &bytesLeft, heap);
- if (newFrag == NULL)
- return MEMORY_E;
- msg->fragSz += added;
- newFrag->next = prev->next;
- prev->next = newFrag;
- }
- }
- return 0;
- }
- DtlsMsg* DtlsMsgFind(DtlsMsg* head, word32 seq)
- {
- while (head != NULL && head->seq != seq) {
- head = head->next;
- }
- return head;
- }
- void DtlsMsgStore(WOLFSSL* ssl, word32 seq, const byte* data,
- word32 dataSz, byte type, word32 fragOffset, word32 fragSz, void* heap)
- {
- /* See if seq exists in the list. If it isn't in the list, make
- * a new item of size dataSz, copy fragSz bytes from data to msg->msg
- * starting at offset fragOffset, and add fragSz to msg->fragSz. If
- * the seq is in the list and it isn't full, copy fragSz bytes from
- * data to msg->msg starting at offset fragOffset, and add fragSz to
- * msg->fragSz. Insertions take into account data already in the list
- * in case there are overlaps in the handshake message due to retransmit
- * messages. The new item should be inserted into the list in its
- * proper position.
- *
- * 1. Find seq in list, or where seq should go in list. If seq not in
- * list, create new item and insert into list. Either case, keep
- * pointer to item.
- * 2. Copy the data from the message to the stored message where it
- * belongs without overlaps.
- */
- DtlsMsg* head = ssl->dtls_rx_msg_list;
- if (head != NULL) {
- DtlsMsg* cur = DtlsMsgFind(head, seq);
- if (cur == NULL) {
- cur = DtlsMsgNew(dataSz, heap);
- if (cur != NULL) {
- if (DtlsMsgSet(cur, seq, data, type,
- fragOffset, fragSz, heap) < 0) {
- DtlsMsgDelete(cur, heap);
- }
- else {
- ssl->dtls_rx_msg_list_sz++;
- head = DtlsMsgInsert(head, cur);
- }
- }
- }
- else {
- /* If this fails, the data is just dropped. */
- DtlsMsgSet(cur, seq, data, type, fragOffset, fragSz, heap);
- }
- }
- else {
- head = DtlsMsgNew(dataSz, heap);
- if (DtlsMsgSet(head, seq, data, type, fragOffset, fragSz, heap) < 0) {
- DtlsMsgDelete(head, heap);
- head = NULL;
- }
- else {
- ssl->dtls_rx_msg_list_sz++;
- }
- }
- ssl->dtls_rx_msg_list = head;
- }
- /* DtlsMsgInsert() is an in-order insert. */
- DtlsMsg* DtlsMsgInsert(DtlsMsg* head, DtlsMsg* item)
- {
- if (head == NULL || item->seq < head->seq) {
- item->next = head;
- head = item;
- }
- else if (head->next == NULL) {
- head->next = item;
- }
- else {
- DtlsMsg* cur = head->next;
- DtlsMsg* prev = head;
- while (cur) {
- if (item->seq < cur->seq) {
- item->next = cur;
- prev->next = item;
- break;
- }
- prev = cur;
- cur = cur->next;
- }
- if (cur == NULL) {
- prev->next = item;
- }
- }
- return head;
- }
- /* DtlsMsgPoolSave() adds the message to the end of the stored transmit list. */
- int DtlsMsgPoolSave(WOLFSSL* ssl, const byte* data, word32 dataSz)
- {
- DtlsMsg* item;
- int ret = 0;
- WOLFSSL_ENTER("DtlsMsgPoolSave()");
- if (ssl->dtls_tx_msg_list_sz > DTLS_POOL_SZ) {
- WOLFSSL_ERROR(DTLS_POOL_SZ_E);
- return DTLS_POOL_SZ_E;
- }
- item = DtlsMsgNew(dataSz, ssl->heap);
- if (item != NULL) {
- DtlsMsg* cur = ssl->dtls_tx_msg_list;
- XMEMCPY(item->buf, data, dataSz);
- item->sz = dataSz;
- item->seq = ssl->keys.dtls_epoch;
- if (cur == NULL)
- ssl->dtls_tx_msg_list = item;
- else {
- while (cur->next)
- cur = cur->next;
- cur->next = item;
- }
- ssl->dtls_tx_msg_list_sz++;
- }
- else
- ret = MEMORY_E;
- WOLFSSL_LEAVE("DtlsMsgPoolSave()", ret);
- return ret;
- }
- /* DtlsMsgPoolTimeout() updates the timeout time. */
- int DtlsMsgPoolTimeout(WOLFSSL* ssl)
- {
- int result = -1;
- if (ssl->dtls_timeout < ssl->dtls_timeout_max) {
- ssl->dtls_timeout *= DTLS_TIMEOUT_MULTIPLIER;
- result = 0;
- }
- WOLFSSL_LEAVE("DtlsMsgPoolTimeout()", result);
- return result;
- }
- /* DtlsMsgPoolReset() deletes the stored transmit list and resets the timeout
- * value. */
- void DtlsMsgPoolReset(WOLFSSL* ssl)
- {
- WOLFSSL_ENTER("DtlsMsgPoolReset()");
- if (ssl->dtls_tx_msg_list) {
- DtlsMsgListDelete(ssl->dtls_tx_msg_list, ssl->heap);
- ssl->dtls_tx_msg_list = NULL;
- ssl->dtls_tx_msg = NULL;
- ssl->dtls_tx_msg_list_sz = 0;
- ssl->dtls_timeout = ssl->dtls_timeout_init;
- }
- }
- int VerifyForDtlsMsgPoolSend(WOLFSSL* ssl, byte type, word32 fragOffset)
- {
- /**
- * only the first message from previous flight should be valid
- * to be used for triggering retransmission of whole DtlsMsgPool.
- * change cipher suite type is not verified here
- */
- return ((fragOffset == 0) &&
- (((ssl->options.side == WOLFSSL_SERVER_END) &&
- ((type == client_hello) ||
- ((ssl->options.verifyPeer) && (type == certificate)) ||
- ((!ssl->options.verifyPeer) && (type == client_key_exchange)))) ||
- ((ssl->options.side == WOLFSSL_CLIENT_END) &&
- (type == server_hello))));
- }
- /* DtlsMsgPoolSend() will send the stored transmit list. The stored list is
- * updated with new sequence numbers, and will be re-encrypted if needed. */
- int DtlsMsgPoolSend(WOLFSSL* ssl, int sendOnlyFirstPacket)
- {
- int ret = 0;
- DtlsMsg* pool;
- WOLFSSL_ENTER("DtlsMsgPoolSend()");
- pool = ssl->dtls_tx_msg == NULL ? ssl->dtls_tx_msg_list : ssl->dtls_tx_msg;
- if (pool != NULL) {
- if ((ssl->options.side == WOLFSSL_SERVER_END &&
- !(ssl->options.acceptState == SERVER_HELLO_DONE ||
- ssl->options.acceptState == ACCEPT_FINISHED_DONE ||
- ssl->options.acceptState == ACCEPT_THIRD_REPLY_DONE)) ||
- (ssl->options.side == WOLFSSL_CLIENT_END &&
- !(ssl->options.connectState == CLIENT_HELLO_SENT ||
- ssl->options.connectState == HELLO_AGAIN_REPLY ||
- ssl->options.connectState == FINISHED_DONE ||
- ssl->options.connectState == SECOND_REPLY_DONE))) {
- WOLFSSL_ERROR(DTLS_RETX_OVER_TX);
- ssl->error = DTLS_RETX_OVER_TX;
- return WOLFSSL_FATAL_ERROR;
- }
- while (pool != NULL) {
- if (pool->seq == 0) {
- DtlsRecordLayerHeader* dtls;
- int epochOrder;
- dtls = (DtlsRecordLayerHeader*)pool->buf;
- /* If the stored record's epoch is 0, and the currently set
- * epoch is 0, use the "current order" sequence number.
- * If the stored record's epoch is 0 and the currently set
- * epoch is not 0, the stored record is considered a "previous
- * order" sequence number. */
- epochOrder = (ssl->keys.dtls_epoch == 0) ?
- CUR_ORDER : PREV_ORDER;
- WriteSEQ(ssl, epochOrder, dtls->sequence_number);
- DtlsSEQIncrement(ssl, epochOrder);
- if ((ret = CheckAvailableSize(ssl, pool->sz)) != 0) {
- WOLFSSL_ERROR(ret);
- return ret;
- }
- XMEMCPY(ssl->buffers.outputBuffer.buffer,
- pool->buf, pool->sz);
- ssl->buffers.outputBuffer.idx = 0;
- ssl->buffers.outputBuffer.length = pool->sz;
- }
- else if (pool->seq == ssl->keys.dtls_epoch) {
- byte* input;
- byte* output;
- int inputSz, sendSz;
- input = pool->buf;
- inputSz = pool->sz;
- sendSz = inputSz + MAX_MSG_EXTRA;
- if ((ret = CheckAvailableSize(ssl, sendSz)) != 0) {
- WOLFSSL_ERROR(ret);
- return ret;
- }
- output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
- handshake, 0, 0, 0);
- if (sendSz < 0) {
- WOLFSSL_ERROR(BUILD_MSG_ERROR);
- return BUILD_MSG_ERROR;
- }
- ssl->buffers.outputBuffer.length += sendSz;
- }
- ret = SendBuffered(ssl);
- if (ret < 0) {
- WOLFSSL_ERROR(ret);
- return ret;
- }
- /**
- * on server side, retransmission is being triggered only by sending
- * first message of given flight, in order to trigger client
- * to retransmit its whole flight. Sending the whole previous flight
- * could lead to retransmission of previous client flight for each
- * server message from previous flight. Therefore one message should
- * be enough to do the trick.
- */
- if (sendOnlyFirstPacket &&
- ssl->options.side == WOLFSSL_SERVER_END) {
- pool = NULL;
- }
- else
- pool = pool->next;
- ssl->dtls_tx_msg = pool;
- }
- }
- WOLFSSL_LEAVE("DtlsMsgPoolSend()", ret);
- return ret;
- }
- #endif /* WOLFSSL_DTLS */
- #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
- ProtocolVersion MakeSSLv3(void)
- {
- ProtocolVersion pv;
- pv.major = SSLv3_MAJOR;
- pv.minor = SSLv3_MINOR;
- return pv;
- }
- #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
- #ifdef WOLFSSL_DTLS
- ProtocolVersion MakeDTLSv1(void)
- {
- ProtocolVersion pv;
- pv.major = DTLS_MAJOR;
- pv.minor = DTLS_MINOR;
- return pv;
- }
- #ifndef WOLFSSL_NO_TLS12
- ProtocolVersion MakeDTLSv1_2(void)
- {
- ProtocolVersion pv;
- pv.major = DTLS_MAJOR;
- pv.minor = DTLSv1_2_MINOR;
- return pv;
- }
- #endif /* !WOLFSSL_NO_TLS12 */
- #endif /* WOLFSSL_DTLS */
- #ifndef NO_ASN_TIME
- #if defined(USER_TICKS)
- #if 0
- word32 LowResTimer(void)
- {
- /*
- write your own clock tick function if don't want time(0)
- needs second accuracy but doesn't have to correlated to EPOCH
- */
- }
- #endif
- #elif defined(TIME_OVERRIDES)
- /* use same asn time overrides unless user wants tick override above */
- #ifndef HAVE_TIME_T_TYPE
- typedef long time_t;
- #endif
- extern time_t XTIME(time_t * timer);
- word32 LowResTimer(void)
- {
- return (word32) XTIME(0);
- }
- #elif defined(USE_WINDOWS_API)
- word32 LowResTimer(void)
- {
- static int init = 0;
- static LARGE_INTEGER freq;
- LARGE_INTEGER count;
- if (!init) {
- QueryPerformanceFrequency(&freq);
- init = 1;
- }
- QueryPerformanceCounter(&count);
- return (word32)(count.QuadPart / freq.QuadPart);
- }
- #elif defined(HAVE_RTP_SYS)
- #include "rtptime.h"
- word32 LowResTimer(void)
- {
- return (word32)rtp_get_system_sec();
- }
- #elif defined(WOLFSSL_DEOS)
- word32 LowResTimer(void)
- {
- const uint32_t systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
- uint32_t *systemTickPtr = systemTickPointer();
- return (word32) *systemTickPtr/systemTickTimeInHz;
- }
- #elif defined(MICRIUM)
- word32 LowResTimer(void)
- {
- OS_TICK ticks = 0;
- OS_ERR err;
- ticks = OSTimeGet(&err);
- return (word32) (ticks / OSCfg_TickRate_Hz);
- }
- #elif defined(MICROCHIP_TCPIP_V5)
- word32 LowResTimer(void)
- {
- return (word32) (TickGet() / TICKS_PER_SECOND);
- }
- #elif defined(MICROCHIP_TCPIP)
- #if defined(MICROCHIP_MPLAB_HARMONY)
- #include <system/tmr/sys_tmr.h>
- word32 LowResTimer(void)
- {
- return (word32) (SYS_TMR_TickCountGet() /
- SYS_TMR_TickCounterFrequencyGet());
- }
- #else
- word32 LowResTimer(void)
- {
- return (word32) (SYS_TICK_Get() / SYS_TICK_TicksPerSecondGet());
- }
- #endif
- #elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
- word32 LowResTimer(void)
- {
- TIME_STRUCT mqxTime;
- _time_get_elapsed(&mqxTime);
- return (word32) mqxTime.SECONDS;
- }
- #elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS)
- #include "include/task.h"
- unsigned int LowResTimer(void)
- {
- return (unsigned int)(((float)xTaskGetTickCount())/configTICK_RATE_HZ);
- }
- #elif defined(FREERTOS)
- #include "task.h"
- unsigned int LowResTimer(void)
- {
- return (unsigned int)(((float)xTaskGetTickCount())/configTICK_RATE_HZ);
- }
- #elif defined(FREESCALE_KSDK_BM)
- #include "lwip/sys.h" /* lwIP */
- word32 LowResTimer(void)
- {
- return sys_now()/1000;
- }
- #elif defined(WOLFSSL_TIRTOS)
- word32 LowResTimer(void)
- {
- return (word32) Seconds_get();
- }
- #elif defined(WOLFSSL_XILINX)
- #include "xrtcpsu.h"
- word32 LowResTimer(void)
- {
- XRtcPsu_Config* con;
- XRtcPsu rtc;
- con = XRtcPsu_LookupConfig(XPAR_XRTCPSU_0_DEVICE_ID);
- if (con != NULL) {
- if (XRtcPsu_CfgInitialize(&rtc, con, con->BaseAddr)
- == XST_SUCCESS) {
- return (word32)XRtcPsu_GetCurrentTime(&rtc);
- }
- else {
- WOLFSSL_MSG("Unable to initialize RTC");
- }
- }
- return 0;
- }
- #elif defined(WOLFSSL_UTASKER)
- word32 LowResTimer(void)
- {
- return (word32)(uTaskerSystemTick / TICK_RESOLUTION);
- }
- #elif defined(WOLFSSL_NUCLEUS_1_2)
- #define NU_TICKS_PER_SECOND 100
- word32 LowResTimer(void)
- {
- /* returns number of 10ms ticks, so 100 ticks/sec */
- return NU_Retrieve_Clock() / NU_TICKS_PER_SECOND;
- }
- #elif defined(WOLFSSL_APACHE_MYNEWT)
- #include "os/os_time.h"
- word32 LowResTimer(void)
- {
- word32 now;
- struct os_timeval tv;
- os_gettimeofday(&tv, NULL);
- now = (word32)tv.tv_sec;
- return now;
- }
- #elif defined(WOLFSSL_ZEPHYR)
- word32 LowResTimer(void)
- {
- return k_uptime_get() / 1000;
- }
- #else
- /* Posix style time */
- #if !defined(USER_TIME) && !defined(USE_WOLF_TM)
- #include <time.h>
- #endif
- word32 LowResTimer(void)
- {
- return (word32)XTIME(0);
- }
- #endif
- #endif /* !NO_ASN_TIME */
- #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
- ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
- (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
- /* Store the message for use with CertificateVerify using EdDSA.
- *
- * ssl SSL/TLS object.
- * data Message to store.
- * sz Size of message to store.
- * returns MEMORY_E if not able to reallocate, otherwise 0.
- */
- static int EdDSA_Update(WOLFSSL* ssl, const byte* data, int sz)
- {
- int ret = 0;
- byte* msgs;
- if (ssl->options.cacheMessages) {
- msgs = (byte*)XREALLOC(ssl->hsHashes->messages,
- ssl->hsHashes->length + sz,
- ssl->heap, DYNAMIC_TYPE_HASHES);
- if (msgs == NULL)
- ret = MEMORY_E;
- if (ret == 0) {
- ssl->hsHashes->messages = msgs;
- XMEMCPY(msgs + ssl->hsHashes->length, data, sz);
- ssl->hsHashes->prevLen = ssl->hsHashes->length;
- ssl->hsHashes->length += sz;
- }
- }
- return ret;
- }
- #endif /* (HAVE_ED25519 || HAVE_ED448) && !WOLFSSL_NO_CLIENT_AUTH */
- #ifndef NO_CERTS
- int HashOutputRaw(WOLFSSL* ssl, const byte* output, int sz)
- {
- int ret = 0;
- (void)output;
- (void)sz;
- if (ssl->hsHashes == NULL)
- return BAD_FUNC_ARG;
- #ifdef HAVE_FUZZER
- if (ssl->fuzzerCb)
- ssl->fuzzerCb(ssl, output, sz, FUZZ_HASH, ssl->fuzzerCtx);
- #endif
- #ifndef NO_OLD_TLS
- #ifndef NO_SHA
- wc_ShaUpdate(&ssl->hsHashes->hashSha, output, sz);
- #endif
- #ifndef NO_MD5
- wc_Md5Update(&ssl->hsHashes->hashMd5, output, sz);
- #endif
- #endif /* NO_OLD_TLS */
- if (IsAtLeastTLSv1_2(ssl)) {
- #ifndef NO_SHA256
- ret = wc_Sha256Update(&ssl->hsHashes->hashSha256, output, sz);
- if (ret != 0)
- return ret;
- #endif
- #ifdef WOLFSSL_SHA384
- ret = wc_Sha384Update(&ssl->hsHashes->hashSha384, output, sz);
- if (ret != 0)
- return ret;
- #endif
- #ifdef WOLFSSL_SHA512
- ret = wc_Sha512Update(&ssl->hsHashes->hashSha512, output, sz);
- if (ret != 0)
- return ret;
- #endif
- #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
- ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
- (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
- ret = EdDSA_Update(ssl, output, sz);
- if (ret != 0)
- return ret;
- #endif
- }
- return ret;
- }
- #endif /* NO_CERTS */
- /* add output to md5 and sha handshake hashes, exclude record header */
- int HashOutput(WOLFSSL* ssl, const byte* output, int sz, int ivSz)
- {
- int ret = 0;
- const byte* adj;
- if (ssl->hsHashes == NULL)
- return BAD_FUNC_ARG;
- adj = output + RECORD_HEADER_SZ + ivSz;
- sz -= RECORD_HEADER_SZ;
- #ifdef HAVE_FUZZER
- if (ssl->fuzzerCb)
- ssl->fuzzerCb(ssl, output, sz, FUZZ_HASH, ssl->fuzzerCtx);
- #endif
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- adj += DTLS_RECORD_EXTRA;
- sz -= DTLS_RECORD_EXTRA;
- }
- #endif
- #ifndef NO_OLD_TLS
- #ifndef NO_SHA
- wc_ShaUpdate(&ssl->hsHashes->hashSha, adj, sz);
- #endif
- #ifndef NO_MD5
- wc_Md5Update(&ssl->hsHashes->hashMd5, adj, sz);
- #endif
- #endif
- if (IsAtLeastTLSv1_2(ssl)) {
- #ifndef NO_SHA256
- ret = wc_Sha256Update(&ssl->hsHashes->hashSha256, adj, sz);
- if (ret != 0)
- return ret;
- #endif
- #ifdef WOLFSSL_SHA384
- ret = wc_Sha384Update(&ssl->hsHashes->hashSha384, adj, sz);
- if (ret != 0)
- return ret;
- #endif
- #ifdef WOLFSSL_SHA512
- ret = wc_Sha512Update(&ssl->hsHashes->hashSha512, adj, sz);
- if (ret != 0)
- return ret;
- #endif
- #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
- ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
- (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
- ret = EdDSA_Update(ssl, adj, sz);
- if (ret != 0)
- return ret;
- #endif
- }
- return ret;
- }
- /* add input to md5 and sha handshake hashes, include handshake header */
- int HashInput(WOLFSSL* ssl, const byte* input, int sz)
- {
- int ret = 0;
- const byte* adj;
- adj = input - HANDSHAKE_HEADER_SZ;
- sz += HANDSHAKE_HEADER_SZ;
- (void)adj;
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- adj -= DTLS_HANDSHAKE_EXTRA;
- sz += DTLS_HANDSHAKE_EXTRA;
- }
- #endif
- if (ssl->hsHashes == NULL) {
- return BAD_FUNC_ARG;
- }
- #ifndef NO_OLD_TLS
- #ifndef NO_SHA
- wc_ShaUpdate(&ssl->hsHashes->hashSha, adj, sz);
- #endif
- #ifndef NO_MD5
- wc_Md5Update(&ssl->hsHashes->hashMd5, adj, sz);
- #endif
- #endif
- if (IsAtLeastTLSv1_2(ssl)) {
- #ifndef NO_SHA256
- ret = wc_Sha256Update(&ssl->hsHashes->hashSha256, adj, sz);
- if (ret != 0)
- return ret;
- #endif
- #ifdef WOLFSSL_SHA384
- ret = wc_Sha384Update(&ssl->hsHashes->hashSha384, adj, sz);
- if (ret != 0)
- return ret;
- #endif
- #ifdef WOLFSSL_SHA512
- ret = wc_Sha512Update(&ssl->hsHashes->hashSha512, adj, sz);
- if (ret != 0)
- return ret;
- #endif
- #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
- ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
- (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
- ret = EdDSA_Update(ssl, adj, sz);
- if (ret != 0)
- return ret;
- #endif
- }
- return ret;
- }
- /* add record layer header for message */
- static void AddRecordHeader(byte* output, word32 length, byte type, WOLFSSL* ssl)
- {
- RecordLayerHeader* rl;
- /* record layer header */
- rl = (RecordLayerHeader*)output;
- if (rl == NULL) {
- return;
- }
- rl->type = type;
- rl->pvMajor = ssl->version.major; /* type and version same in each */
- #ifdef WOLFSSL_TLS13
- if (IsAtLeastTLSv1_3(ssl->version)) {
- #ifdef WOLFSSL_TLS13_DRAFT_18
- rl->pvMinor = TLSv1_MINOR;
- #else
- rl->pvMinor = TLSv1_2_MINOR;
- #endif
- }
- else
- #endif
- rl->pvMinor = ssl->version.minor;
- #ifdef WOLFSSL_ALTERNATIVE_DOWNGRADE
- if (ssl->options.side == WOLFSSL_CLIENT_END
- && ssl->options.connectState == CONNECT_BEGIN
- && !ssl->options.resuming) {
- rl->pvMinor = ssl->options.downgrade ? ssl->options.minDowngrade
- : ssl->version.minor;
- }
- #endif
- if (!ssl->options.dtls) {
- c16toa((word16)length, rl->length);
- }
- else {
- #ifdef WOLFSSL_DTLS
- DtlsRecordLayerHeader* dtls;
- /* dtls record layer header extensions */
- dtls = (DtlsRecordLayerHeader*)output;
- WriteSEQ(ssl, 0, dtls->sequence_number);
- c16toa((word16)length, dtls->length);
- #endif
- }
- }
- #if !defined(WOLFSSL_NO_TLS12) || (defined(HAVE_SESSION_TICKET) && \
- !defined(NO_WOLFSSL_SERVER))
- /* add handshake header for message */
- static void AddHandShakeHeader(byte* output, word32 length,
- word32 fragOffset, word32 fragLength,
- byte type, WOLFSSL* ssl)
- {
- HandShakeHeader* hs;
- (void)fragOffset;
- (void)fragLength;
- (void)ssl;
- /* handshake header */
- hs = (HandShakeHeader*)output;
- if (hs == NULL)
- return;
- hs->type = type;
- c32to24(length, hs->length); /* type and length same for each */
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- DtlsHandShakeHeader* dtls;
- /* dtls handshake header extensions */
- dtls = (DtlsHandShakeHeader*)output;
- c16toa(ssl->keys.dtls_handshake_number++, dtls->message_seq);
- c32to24(fragOffset, dtls->fragment_offset);
- c32to24(fragLength, dtls->fragment_length);
- }
- #endif
- }
- /* add both headers for handshake message */
- static void AddHeaders(byte* output, word32 length, byte type, WOLFSSL* ssl)
- {
- word32 lengthAdj = HANDSHAKE_HEADER_SZ;
- word32 outputAdj = RECORD_HEADER_SZ;
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- lengthAdj += DTLS_HANDSHAKE_EXTRA;
- outputAdj += DTLS_RECORD_EXTRA;
- }
- #endif
- AddRecordHeader(output, length + lengthAdj, handshake, ssl);
- AddHandShakeHeader(output + outputAdj, length, 0, length, type, ssl);
- }
- #endif /* !WOLFSSL_NO_TLS12 || (HAVE_SESSION_TICKET && !NO_WOLFSSL_SERVER) */
- #ifndef WOLFSSL_NO_TLS12
- #if !defined(NO_CERTS) && (!defined(NO_WOLFSSL_SERVER) || \
- !defined(WOLFSSL_NO_CLIENT_AUTH))
- static void AddFragHeaders(byte* output, word32 fragSz, word32 fragOffset,
- word32 length, byte type, WOLFSSL* ssl)
- {
- word32 lengthAdj = HANDSHAKE_HEADER_SZ;
- word32 outputAdj = RECORD_HEADER_SZ;
- (void)fragSz;
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- lengthAdj += DTLS_HANDSHAKE_EXTRA;
- outputAdj += DTLS_RECORD_EXTRA;
- }
- #endif
- AddRecordHeader(output, fragSz + lengthAdj, handshake, ssl);
- AddHandShakeHeader(output + outputAdj, length, fragOffset, fragSz, type, ssl);
- }
- #endif /* NO_CERTS */
- #endif /* !WOLFSSL_NO_TLS12 */
- /* return bytes received, -1 on error */
- static int wolfSSLReceive(WOLFSSL* ssl, byte* buf, word32 sz)
- {
- int recvd;
- if (ssl->CBIORecv == NULL) {
- WOLFSSL_MSG("Your IO Recv callback is null, please set");
- return -1;
- }
- retry:
- recvd = ssl->CBIORecv(ssl, (char *)buf, (int)sz, ssl->IOCB_ReadCtx);
- if (recvd < 0) {
- switch (recvd) {
- case WOLFSSL_CBIO_ERR_GENERAL: /* general/unknown error */
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD)
- if (ssl->biord) {
- /* If retry and read flags are set, return WANT_READ */
- if ((ssl->biord->flags & WOLFSSL_BIO_FLAG_READ) &&
- (ssl->biord->flags & WOLFSSL_BIO_FLAG_RETRY)) {
- return WANT_READ;
- }
- }
- #endif
- return -1;
- case WOLFSSL_CBIO_ERR_WANT_READ: /* want read, would block */
- return WANT_READ;
- case WOLFSSL_CBIO_ERR_CONN_RST: /* connection reset */
- #ifdef USE_WINDOWS_API
- if (ssl->options.dtls) {
- goto retry;
- }
- #endif
- ssl->options.connReset = 1;
- return -1;
- case WOLFSSL_CBIO_ERR_ISR: /* interrupt */
- /* see if we got our timeout */
- #ifdef WOLFSSL_CALLBACKS
- if (ssl->toInfoOn) {
- struct itimerval timeout;
- getitimer(ITIMER_REAL, &timeout);
- if (timeout.it_value.tv_sec == 0 &&
- timeout.it_value.tv_usec == 0) {
- XSTRNCPY(ssl->timeoutInfo.timeoutName,
- "recv() timeout", MAX_TIMEOUT_NAME_SZ);
- ssl->timeoutInfo.timeoutName[
- MAX_TIMEOUT_NAME_SZ] = '\0';
- WOLFSSL_MSG("Got our timeout");
- return WANT_READ;
- }
- }
- #endif
- goto retry;
- case WOLFSSL_CBIO_ERR_CONN_CLOSE: /* peer closed connection */
- ssl->options.isClosed = 1;
- return -1;
- case WOLFSSL_CBIO_ERR_TIMEOUT:
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl) &&
- !ssl->options.handShakeDone &&
- DtlsMsgPoolTimeout(ssl) == 0 &&
- DtlsMsgPoolSend(ssl, 0) == 0) {
- /* retry read for DTLS during handshake only */
- goto retry;
- }
- #endif
- return -1;
- default:
- WOLFSSL_MSG("Unexpected recv return code");
- return recvd;
- }
- }
- return recvd;
- }
- /* Switch dynamic output buffer back to static, buffer is assumed clear */
- void ShrinkOutputBuffer(WOLFSSL* ssl)
- {
- WOLFSSL_MSG("Shrinking output buffer\n");
- XFREE(ssl->buffers.outputBuffer.buffer - ssl->buffers.outputBuffer.offset,
- ssl->heap, DYNAMIC_TYPE_OUT_BUFFER);
- ssl->buffers.outputBuffer.buffer = ssl->buffers.outputBuffer.staticBuffer;
- ssl->buffers.outputBuffer.bufferSize = STATIC_BUFFER_LEN;
- ssl->buffers.outputBuffer.dynamicFlag = 0;
- ssl->buffers.outputBuffer.offset = 0;
- }
- /* Switch dynamic input buffer back to static, keep any remaining input */
- /* forced free means cleaning up */
- void ShrinkInputBuffer(WOLFSSL* ssl, int forcedFree)
- {
- int usedLength = ssl->buffers.inputBuffer.length -
- ssl->buffers.inputBuffer.idx;
- if (!forcedFree && usedLength > STATIC_BUFFER_LEN)
- return;
- WOLFSSL_MSG("Shrinking input buffer\n");
- if (!forcedFree && usedLength > 0)
- XMEMCPY(ssl->buffers.inputBuffer.staticBuffer,
- ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.idx,
- usedLength);
- XFREE(ssl->buffers.inputBuffer.buffer - ssl->buffers.inputBuffer.offset,
- ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- ssl->buffers.inputBuffer.buffer = ssl->buffers.inputBuffer.staticBuffer;
- ssl->buffers.inputBuffer.bufferSize = STATIC_BUFFER_LEN;
- ssl->buffers.inputBuffer.dynamicFlag = 0;
- ssl->buffers.inputBuffer.offset = 0;
- ssl->buffers.inputBuffer.idx = 0;
- ssl->buffers.inputBuffer.length = usedLength;
- }
- int SendBuffered(WOLFSSL* ssl)
- {
- if (ssl->CBIOSend == NULL) {
- WOLFSSL_MSG("Your IO Send callback is null, please set");
- return SOCKET_ERROR_E;
- }
- #ifdef WOLFSSL_DEBUG_TLS
- if (ssl->buffers.outputBuffer.idx == 0) {
- WOLFSSL_MSG("Data to send");
- WOLFSSL_BUFFER(ssl->buffers.outputBuffer.buffer,
- ssl->buffers.outputBuffer.length);
- }
- #endif
- while (ssl->buffers.outputBuffer.length > 0) {
- int sent = ssl->CBIOSend(ssl,
- (char*)ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.idx,
- (int)ssl->buffers.outputBuffer.length,
- ssl->IOCB_WriteCtx);
- if (sent < 0) {
- switch (sent) {
- case WOLFSSL_CBIO_ERR_WANT_WRITE: /* would block */
- return WANT_WRITE;
- case WOLFSSL_CBIO_ERR_CONN_RST: /* connection reset */
- ssl->options.connReset = 1;
- break;
- case WOLFSSL_CBIO_ERR_ISR: /* interrupt */
- /* see if we got our timeout */
- #ifdef WOLFSSL_CALLBACKS
- if (ssl->toInfoOn) {
- struct itimerval timeout;
- getitimer(ITIMER_REAL, &timeout);
- if (timeout.it_value.tv_sec == 0 &&
- timeout.it_value.tv_usec == 0) {
- XSTRNCPY(ssl->timeoutInfo.timeoutName,
- "send() timeout", MAX_TIMEOUT_NAME_SZ);
- ssl->timeoutInfo.timeoutName[
- MAX_TIMEOUT_NAME_SZ] = '\0';
- WOLFSSL_MSG("Got our timeout");
- return WANT_WRITE;
- }
- }
- #endif
- continue;
- case WOLFSSL_CBIO_ERR_CONN_CLOSE: /* epipe / conn closed */
- ssl->options.connReset = 1; /* treat same as reset */
- break;
- default:
- return SOCKET_ERROR_E;
- }
- return SOCKET_ERROR_E;
- }
- if (sent > (int)ssl->buffers.outputBuffer.length) {
- WOLFSSL_MSG("SendBuffered() out of bounds read");
- return SEND_OOB_READ_E;
- }
- ssl->buffers.outputBuffer.idx += sent;
- ssl->buffers.outputBuffer.length -= sent;
- }
- ssl->buffers.outputBuffer.idx = 0;
- if (ssl->buffers.outputBuffer.dynamicFlag)
- ShrinkOutputBuffer(ssl);
- return 0;
- }
- /* Grow the output buffer */
- static WC_INLINE int GrowOutputBuffer(WOLFSSL* ssl, int size)
- {
- byte* tmp;
- #if WOLFSSL_GENERAL_ALIGNMENT > 0
- byte hdrSz = ssl->options.dtls ? DTLS_RECORD_HEADER_SZ :
- RECORD_HEADER_SZ;
- byte align = WOLFSSL_GENERAL_ALIGNMENT;
- #else
- const byte align = WOLFSSL_GENERAL_ALIGNMENT;
- #endif
- #if WOLFSSL_GENERAL_ALIGNMENT > 0
- /* the encrypted data will be offset from the front of the buffer by
- the header, if the user wants encrypted alignment they need
- to define their alignment requirement */
- if (align) {
- while (align < hdrSz)
- align *= 2;
- }
- #endif
- tmp = (byte*)XMALLOC(size + ssl->buffers.outputBuffer.length + align,
- ssl->heap, DYNAMIC_TYPE_OUT_BUFFER);
- WOLFSSL_MSG("growing output buffer\n");
- if (tmp == NULL)
- return MEMORY_E;
- #if WOLFSSL_GENERAL_ALIGNMENT > 0
- if (align)
- tmp += align - hdrSz;
- #endif
- #ifdef WOLFSSL_STATIC_MEMORY
- /* can be from IO memory pool which does not need copy if same buffer */
- if (ssl->buffers.outputBuffer.length &&
- tmp == ssl->buffers.outputBuffer.buffer) {
- ssl->buffers.outputBuffer.bufferSize =
- size + ssl->buffers.outputBuffer.length;
- return 0;
- }
- #endif
- if (ssl->buffers.outputBuffer.length)
- XMEMCPY(tmp, ssl->buffers.outputBuffer.buffer,
- ssl->buffers.outputBuffer.length);
- if (ssl->buffers.outputBuffer.dynamicFlag)
- XFREE(ssl->buffers.outputBuffer.buffer -
- ssl->buffers.outputBuffer.offset, ssl->heap,
- DYNAMIC_TYPE_OUT_BUFFER);
- ssl->buffers.outputBuffer.dynamicFlag = 1;
- #if WOLFSSL_GENERAL_ALIGNMENT > 0
- if (align)
- ssl->buffers.outputBuffer.offset = align - hdrSz;
- else
- #endif
- ssl->buffers.outputBuffer.offset = 0;
- ssl->buffers.outputBuffer.buffer = tmp;
- ssl->buffers.outputBuffer.bufferSize = size +
- ssl->buffers.outputBuffer.length;
- return 0;
- }
- /* Grow the input buffer, should only be to read cert or big app data */
- int GrowInputBuffer(WOLFSSL* ssl, int size, int usedLength)
- {
- byte* tmp;
- #if defined(WOLFSSL_DTLS) || WOLFSSL_GENERAL_ALIGNMENT > 0
- byte align = ssl->options.dtls ? WOLFSSL_GENERAL_ALIGNMENT : 0;
- byte hdrSz = DTLS_RECORD_HEADER_SZ;
- #else
- const byte align = WOLFSSL_GENERAL_ALIGNMENT;
- #endif
- #if defined(WOLFSSL_DTLS) || WOLFSSL_GENERAL_ALIGNMENT > 0
- /* the encrypted data will be offset from the front of the buffer by
- the dtls record header, if the user wants encrypted alignment they need
- to define their alignment requirement. in tls we read record header
- to get size of record and put actual data back at front, so don't need */
- if (align) {
- while (align < hdrSz)
- align *= 2;
- }
- #endif
- if (usedLength < 0 || size < 0) {
- WOLFSSL_MSG("GrowInputBuffer() called with negative number");
- return BAD_FUNC_ARG;
- }
- tmp = (byte*)XMALLOC(size + usedLength + align,
- ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- WOLFSSL_MSG("growing input buffer\n");
- if (tmp == NULL)
- return MEMORY_E;
- #if defined(WOLFSSL_DTLS) || WOLFSSL_GENERAL_ALIGNMENT > 0
- if (align)
- tmp += align - hdrSz;
- #endif
- #ifdef WOLFSSL_STATIC_MEMORY
- /* can be from IO memory pool which does not need copy if same buffer */
- if (usedLength && tmp == ssl->buffers.inputBuffer.buffer) {
- ssl->buffers.inputBuffer.bufferSize = size + usedLength;
- ssl->buffers.inputBuffer.idx = 0;
- ssl->buffers.inputBuffer.length = usedLength;
- return 0;
- }
- #endif
- if (usedLength)
- XMEMCPY(tmp, ssl->buffers.inputBuffer.buffer +
- ssl->buffers.inputBuffer.idx, usedLength);
- if (ssl->buffers.inputBuffer.dynamicFlag)
- XFREE(ssl->buffers.inputBuffer.buffer - ssl->buffers.inputBuffer.offset,
- ssl->heap,DYNAMIC_TYPE_IN_BUFFER);
- ssl->buffers.inputBuffer.dynamicFlag = 1;
- #if defined(WOLFSSL_DTLS) || WOLFSSL_GENERAL_ALIGNMENT > 0
- if (align)
- ssl->buffers.inputBuffer.offset = align - hdrSz;
- else
- #endif
- ssl->buffers.inputBuffer.offset = 0;
- ssl->buffers.inputBuffer.buffer = tmp;
- ssl->buffers.inputBuffer.bufferSize = size + usedLength;
- ssl->buffers.inputBuffer.idx = 0;
- ssl->buffers.inputBuffer.length = usedLength;
- return 0;
- }
- /* check available size into output buffer, make room if needed */
- int CheckAvailableSize(WOLFSSL *ssl, int size)
- {
- if (size < 0) {
- WOLFSSL_MSG("CheckAvailableSize() called with negative number");
- return BAD_FUNC_ARG;
- }
- if (ssl->buffers.outputBuffer.bufferSize - ssl->buffers.outputBuffer.length
- < (word32)size) {
- if (GrowOutputBuffer(ssl, size) < 0)
- return MEMORY_E;
- }
- return 0;
- }
- /* do all verify and sanity checks on record header */
- static int GetRecordHeader(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
- RecordLayerHeader* rh, word16 *size)
- {
- if (!ssl->options.dtls) {
- #ifdef HAVE_FUZZER
- if (ssl->fuzzerCb)
- ssl->fuzzerCb(ssl, input + *inOutIdx, RECORD_HEADER_SZ, FUZZ_HEAD,
- ssl->fuzzerCtx);
- #endif
- XMEMCPY(rh, input + *inOutIdx, RECORD_HEADER_SZ);
- *inOutIdx += RECORD_HEADER_SZ;
- ato16(rh->length, size);
- }
- else {
- #ifdef WOLFSSL_DTLS
- #ifdef HAVE_FUZZER
- if (ssl->fuzzerCb)
- ssl->fuzzerCb(ssl, input + *inOutIdx, DTLS_RECORD_HEADER_SZ,
- FUZZ_HEAD, ssl->fuzzerCtx);
- #endif
- /* type and version in same sport */
- XMEMCPY(rh, input + *inOutIdx, ENUM_LEN + VERSION_SZ);
- *inOutIdx += ENUM_LEN + VERSION_SZ;
- ato16(input + *inOutIdx, &ssl->keys.curEpoch);
- *inOutIdx += OPAQUE16_LEN;
- if (ssl->options.haveMcast) {
- #ifdef WOLFSSL_MULTICAST
- ssl->keys.curPeerId = input[*inOutIdx];
- ssl->keys.curSeq_hi = input[*inOutIdx+1];
- #endif
- }
- else
- ato16(input + *inOutIdx, &ssl->keys.curSeq_hi);
- *inOutIdx += OPAQUE16_LEN;
- ato32(input + *inOutIdx, &ssl->keys.curSeq_lo);
- *inOutIdx += OPAQUE32_LEN; /* advance past rest of seq */
- ato16(input + *inOutIdx, size);
- *inOutIdx += LENGTH_SZ;
- #endif
- }
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl) && !DtlsCheckWindow(ssl)) {
- WOLFSSL_LEAVE("GetRecordHeader()", SEQUENCE_ERROR);
- return SEQUENCE_ERROR;
- }
- #endif
- /* catch version mismatch */
- #ifndef WOLFSSL_TLS13
- if (rh->pvMajor != ssl->version.major || rh->pvMinor != ssl->version.minor)
- #else
- if (rh->pvMajor != ssl->version.major ||
- (rh->pvMinor != ssl->version.minor &&
- #ifdef WOLFSSL_TLS13_DRAFT_18
- (!IsAtLeastTLSv1_3(ssl->version) || rh->pvMinor != TLSv1_MINOR)
- #else
- (!IsAtLeastTLSv1_3(ssl->version) || rh->pvMinor != TLSv1_2_MINOR)
- #endif
- ))
- #endif
- {
- if (ssl->options.side == WOLFSSL_SERVER_END &&
- ssl->options.acceptState < ACCEPT_FIRST_REPLY_DONE)
- WOLFSSL_MSG("Client attempting to connect with different version");
- else if (ssl->options.side == WOLFSSL_CLIENT_END &&
- ssl->options.downgrade &&
- ssl->options.connectState < FIRST_REPLY_DONE)
- WOLFSSL_MSG("Server attempting to accept with different version");
- else if (ssl->options.dtls && rh->type == handshake)
- /* Check the DTLS handshake message RH version later. */
- WOLFSSL_MSG("DTLS handshake, skip RH version number check");
- else {
- WOLFSSL_MSG("SSL version error");
- /* send alert per RFC5246 Appendix E. Backward Compatibility */
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- #ifdef WOLFSSL_MYSQL_COMPATIBLE
- SendAlert(ssl, alert_fatal, wc_protocol_version);
- #else
- SendAlert(ssl, alert_fatal, protocol_version);
- #endif
- }
- return VERSION_ERROR; /* only use requested version */
- }
- }
- /* record layer length check */
- #ifdef HAVE_MAX_FRAGMENT
- if (*size > (ssl->max_fragment + MAX_COMP_EXTRA + MAX_MSG_EXTRA)) {
- SendAlert(ssl, alert_fatal, record_overflow);
- return LENGTH_ERROR;
- }
- #else
- if (*size > (MAX_RECORD_SIZE + MAX_COMP_EXTRA + MAX_MSG_EXTRA))
- return LENGTH_ERROR;
- #endif
- /* verify record type here as well */
- switch (rh->type) {
- case handshake:
- case change_cipher_spec:
- case application_data:
- case alert:
- break;
- case no_type:
- default:
- WOLFSSL_MSG("Unknown Record Type");
- return UNKNOWN_RECORD_TYPE;
- }
- /* haven't decrypted this record yet */
- ssl->keys.decryptedCur = 0;
- return 0;
- }
- #ifndef WOLFSSL_NO_TLS12
- static int GetHandShakeHeader(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
- byte *type, word32 *size, word32 totalSz)
- {
- const byte *ptr = input + *inOutIdx;
- (void)ssl;
- *inOutIdx += HANDSHAKE_HEADER_SZ;
- if (*inOutIdx > totalSz)
- return BUFFER_E;
- *type = ptr[0];
- c24to32(&ptr[1], size);
- return 0;
- }
- #endif
- #ifdef WOLFSSL_DTLS
- static int GetDtlsHandShakeHeader(WOLFSSL* ssl, const byte* input,
- word32* inOutIdx, byte *type, word32 *size,
- word32 *fragOffset, word32 *fragSz,
- word32 totalSz)
- {
- word32 idx = *inOutIdx;
- *inOutIdx += HANDSHAKE_HEADER_SZ + DTLS_HANDSHAKE_EXTRA;
- if (*inOutIdx > totalSz) {
- WOLFSSL_ERROR(BUFFER_E);
- return BUFFER_E;
- }
- *type = input[idx++];
- c24to32(input + idx, size);
- idx += OPAQUE24_LEN;
- ato16(input + idx, &ssl->keys.dtls_peer_handshake_number);
- idx += DTLS_HANDSHAKE_SEQ_SZ;
- c24to32(input + idx, fragOffset);
- idx += DTLS_HANDSHAKE_FRAG_SZ;
- c24to32(input + idx, fragSz);
- if (ssl->curRL.pvMajor != ssl->version.major ||
- ssl->curRL.pvMinor != ssl->version.minor) {
- if (*type != client_hello && *type != hello_verify_request) {
- WOLFSSL_ERROR(VERSION_ERROR);
- return VERSION_ERROR;
- }
- else {
- WOLFSSL_MSG("DTLS Handshake ignoring hello or verify version");
- }
- }
- return 0;
- }
- #endif
- #if !defined(NO_OLD_TLS) || \
- (defined(NO_OLD_TLS) && defined(WOLFSSL_ALLOW_TLS_SHA1))
- /* fill with MD5 pad size since biggest required */
- static const byte PAD1[PAD_MD5] =
- { 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
- };
- static const byte PAD2[PAD_MD5] =
- { 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
- 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
- 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
- 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
- 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
- 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
- };
- #endif /* !NO_OLD_TLS || (NO_OLD_TLS && WOLFSSL_ALLOW_TLS_SHA1) */
- #ifndef NO_OLD_TLS
- /* calculate MD5 hash for finished */
- #ifdef WOLFSSL_TI_HASH
- #include <wolfssl/wolfcrypt/hash.h>
- #endif
- static int BuildMD5(WOLFSSL* ssl, Hashes* hashes, const byte* sender)
- {
- int ret;
- byte md5_result[WC_MD5_DIGEST_SIZE];
- #ifdef WOLFSSL_SMALL_STACK
- wc_Md5* md5 = (wc_Md5*)XMALLOC(sizeof(wc_Md5), ssl->heap, DYNAMIC_TYPE_HASHCTX);
- if (md5 == NULL)
- return MEMORY_E;
- #else
- wc_Md5 md5[1];
- #endif
- /* make md5 inner */
- ret = wc_Md5Copy(&ssl->hsHashes->hashMd5, md5);
- if (ret == 0)
- ret = wc_Md5Update(md5, sender, SIZEOF_SENDER);
- if (ret == 0)
- ret = wc_Md5Update(md5, ssl->arrays->masterSecret,SECRET_LEN);
- if (ret == 0)
- ret = wc_Md5Update(md5, PAD1, PAD_MD5);
- if (ret == 0)
- ret = wc_Md5Final(md5, md5_result);
- /* make md5 outer */
- if (ret == 0) {
- ret = wc_InitMd5_ex(md5, ssl->heap, ssl->devId);
- if (ret == 0) {
- ret = wc_Md5Update(md5, ssl->arrays->masterSecret,SECRET_LEN);
- if (ret == 0)
- ret = wc_Md5Update(md5, PAD2, PAD_MD5);
- if (ret == 0)
- ret = wc_Md5Update(md5, md5_result, WC_MD5_DIGEST_SIZE);
- if (ret == 0)
- ret = wc_Md5Final(md5, hashes->md5);
- wc_Md5Free(md5);
- }
- }
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(md5, ssl->heap, DYNAMIC_TYPE_HASHCTX);
- #endif
- return ret;
- }
- /* calculate SHA hash for finished */
- static int BuildSHA(WOLFSSL* ssl, Hashes* hashes, const byte* sender)
- {
- int ret;
- byte sha_result[WC_SHA_DIGEST_SIZE];
- #ifdef WOLFSSL_SMALL_STACK
- wc_Sha* sha = (wc_Sha*)XMALLOC(sizeof(wc_Sha), ssl->heap, DYNAMIC_TYPE_HASHCTX);
- if (sha == NULL)
- return MEMORY_E;
- #else
- wc_Sha sha[1];
- #endif
- /* make sha inner */
- ret = wc_ShaCopy(&ssl->hsHashes->hashSha, sha); /* Save current position */
- if (ret == 0)
- ret = wc_ShaUpdate(sha, sender, SIZEOF_SENDER);
- if (ret == 0)
- ret = wc_ShaUpdate(sha, ssl->arrays->masterSecret,SECRET_LEN);
- if (ret == 0)
- ret = wc_ShaUpdate(sha, PAD1, PAD_SHA);
- if (ret == 0)
- ret = wc_ShaFinal(sha, sha_result);
- /* make sha outer */
- if (ret == 0) {
- ret = wc_InitSha_ex(sha, ssl->heap, ssl->devId);
- if (ret == 0) {
- ret = wc_ShaUpdate(sha, ssl->arrays->masterSecret,SECRET_LEN);
- if (ret == 0)
- ret = wc_ShaUpdate(sha, PAD2, PAD_SHA);
- if (ret == 0)
- ret = wc_ShaUpdate(sha, sha_result, WC_SHA_DIGEST_SIZE);
- if (ret == 0)
- ret = wc_ShaFinal(sha, hashes->sha);
- wc_ShaFree(sha);
- }
- }
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(sha, ssl->heap, DYNAMIC_TYPE_HASHCTX);
- #endif
- return ret;
- }
- #endif
- #ifndef WOLFSSL_NO_TLS12
- /* Finished doesn't support SHA512, not SHA512 cipher suites yet */
- static int BuildFinished(WOLFSSL* ssl, Hashes* hashes, const byte* sender)
- {
- int ret = 0;
- if (ssl == NULL)
- return BAD_FUNC_ARG;
- #ifndef NO_TLS
- if (ssl->options.tls) {
- ret = BuildTlsFinished(ssl, hashes, sender);
- }
- #endif
- #ifndef NO_OLD_TLS
- if (!ssl->options.tls) {
- ret = BuildMD5(ssl, hashes, sender);
- if (ret == 0) {
- ret = BuildSHA(ssl, hashes, sender);
- }
- }
- #endif
- return ret;
- }
- #endif /* WOLFSSL_NO_TLS12 */
- #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT)
- /* cipher requirements */
- enum {
- REQUIRES_RSA,
- REQUIRES_DHE,
- REQUIRES_ECC,
- REQUIRES_ECC_STATIC,
- REQUIRES_PSK,
- REQUIRES_NTRU,
- REQUIRES_RSA_SIG,
- REQUIRES_AEAD
- };
- /* Does this cipher suite (first, second) have the requirement
- an ephemeral key exchange will still require the key for signing
- the key exchange so ECHDE_RSA requires an rsa key thus rsa_kea */
- static int CipherRequires(byte first, byte second, int requirement)
- {
- (void)requirement;
- #ifndef WOLFSSL_NO_TLS12
- #ifdef HAVE_CHACHA
- if (first == CHACHA_BYTE) {
- switch (second) {
- case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 :
- if (requirement == REQUIRES_ECC)
- return 1;
- break;
- case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 :
- if (requirement == REQUIRES_RSA)
- return 1;
- if (requirement == REQUIRES_DHE)
- return 1;
- break;
- case TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- case TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
- if (requirement == REQUIRES_ECC)
- return 1;
- break;
- case TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
- if (requirement == REQUIRES_RSA)
- return 1;
- if (requirement == REQUIRES_DHE)
- return 1;
- break;
- case TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 :
- if (requirement == REQUIRES_PSK)
- return 1;
- break;
- case TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 :
- if (requirement == REQUIRES_PSK)
- return 1;
- break;
- case TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 :
- if (requirement == REQUIRES_PSK)
- return 1;
- if (requirement == REQUIRES_DHE)
- return 1;
- break;
- }
- if (requirement == REQUIRES_AEAD)
- return 1;
- }
- #endif /* HAVE_CHACHA */
- /* ECC extensions */
- if (first == ECC_BYTE) {
- switch (second) {
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
- #ifndef NO_RSA
- case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA :
- if (requirement == REQUIRES_ECC_STATIC)
- return 1;
- if (requirement == REQUIRES_RSA_SIG)
- return 1;
- break;
- #ifndef NO_DES3
- case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA :
- if (requirement == REQUIRES_ECC_STATIC)
- return 1;
- if (requirement == REQUIRES_RSA_SIG)
- return 1;
- break;
- #endif /* !NO_DES3 */
- #ifndef NO_RC4
- case TLS_ECDHE_RSA_WITH_RC4_128_SHA :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- case TLS_ECDH_RSA_WITH_RC4_128_SHA :
- if (requirement == REQUIRES_ECC_STATIC)
- return 1;
- if (requirement == REQUIRES_RSA_SIG)
- return 1;
- break;
- #endif /* !NO_RC4 */
- #endif /* NO_RSA */
- #ifndef NO_DES3
- case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA :
- if (requirement == REQUIRES_ECC)
- return 1;
- break;
- case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA :
- if (requirement == REQUIRES_ECC_STATIC)
- return 1;
- break;
- #endif /* !NO_DES3 */
- #ifndef NO_RC4
- case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA :
- if (requirement == REQUIRES_ECC)
- return 1;
- break;
- case TLS_ECDH_ECDSA_WITH_RC4_128_SHA :
- if (requirement == REQUIRES_ECC_STATIC)
- return 1;
- break;
- #endif /* !NO_RC4 */
- #ifndef NO_RSA
- case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA :
- if (requirement == REQUIRES_ECC_STATIC)
- return 1;
- if (requirement == REQUIRES_RSA_SIG)
- return 1;
- break;
- #endif /* !NO_RSA */
- case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA :
- if (requirement == REQUIRES_ECC)
- return 1;
- break;
- case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA :
- if (requirement == REQUIRES_ECC_STATIC)
- return 1;
- break;
- case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA :
- if (requirement == REQUIRES_ECC)
- return 1;
- break;
- case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA :
- if (requirement == REQUIRES_ECC_STATIC)
- return 1;
- break;
- case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 :
- if (requirement == REQUIRES_ECC)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 :
- if (requirement == REQUIRES_ECC)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- case TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 :
- if (requirement == REQUIRES_ECC_STATIC)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- case TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 :
- if (requirement == REQUIRES_ECC_STATIC)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #ifndef NO_RSA
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
- case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 :
- if (requirement == REQUIRES_RSA)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 :
- if (requirement == REQUIRES_RSA)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- case TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 :
- if (requirement == REQUIRES_ECC_STATIC)
- return 1;
- if (requirement == REQUIRES_RSA_SIG)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- case TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 :
- if (requirement == REQUIRES_ECC_STATIC)
- return 1;
- if (requirement == REQUIRES_RSA_SIG)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #ifdef HAVE_AESCCM
- case TLS_RSA_WITH_AES_128_CCM_8 :
- case TLS_RSA_WITH_AES_256_CCM_8 :
- if (requirement == REQUIRES_RSA)
- return 1;
- if (requirement == REQUIRES_RSA_SIG)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- #endif /* HAVE_AESCCM */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
- case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 :
- case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 :
- case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 :
- if (requirement == REQUIRES_RSA_SIG)
- return 1;
- if (requirement == REQUIRES_ECC_STATIC)
- return 1;
- break;
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #endif /* !NO_RSA */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
- case TLS_ECDHE_ECDSA_WITH_AES_128_CCM :
- case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 :
- case TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 :
- if (requirement == REQUIRES_ECC)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 :
- case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 :
- if (requirement == REQUIRES_ECC)
- return 1;
- break;
- case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 :
- case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 :
- if (requirement == REQUIRES_ECC)
- return 1;
- if (requirement == REQUIRES_ECC_STATIC)
- return 1;
- break;
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #ifndef NO_PSK
- case TLS_PSK_WITH_AES_128_CCM:
- case TLS_PSK_WITH_AES_256_CCM:
- case TLS_PSK_WITH_AES_128_CCM_8:
- case TLS_PSK_WITH_AES_256_CCM_8:
- if (requirement == REQUIRES_PSK)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- case TLS_DHE_PSK_WITH_AES_128_CCM:
- case TLS_DHE_PSK_WITH_AES_256_CCM:
- if (requirement == REQUIRES_PSK)
- return 1;
- if (requirement == REQUIRES_DHE)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- #endif /* !NO_PSK */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
- case TLS_ECDHE_ECDSA_WITH_NULL_SHA :
- if (requirement == REQUIRES_ECC)
- return 1;
- break;
- case TLS_ECDHE_PSK_WITH_NULL_SHA256 :
- if (requirement == REQUIRES_PSK)
- return 1;
- break;
- case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 :
- if (requirement == REQUIRES_PSK)
- return 1;
- break;
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #if defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER)
- case TLS_SHA256_SHA256:
- break;
- case TLS_SHA384_SHA384:
- break;
- #endif
- default:
- WOLFSSL_MSG("Unsupported cipher suite, CipherRequires ECC");
- return 0;
- } /* switch */
- } /* if */
- #endif /* !WOLFSSL_NO_TLS12 */
- /* Distinct TLS v1.3 cipher suites with cipher and digest only. */
- if (first == TLS13_BYTE) {
- switch (second) {
- #ifdef WOLFSSL_TLS13
- case TLS_AES_128_GCM_SHA256:
- case TLS_AES_256_GCM_SHA384:
- case TLS_CHACHA20_POLY1305_SHA256:
- case TLS_AES_128_CCM_SHA256:
- case TLS_AES_128_CCM_8_SHA256:
- break;
- #endif
- default:
- WOLFSSL_MSG("Unsupported cipher suite, CipherRequires "
- "TLS v1.3");
- return 0;
- }
- }
- #ifndef WOLFSSL_NO_TLS12
- if (first != ECC_BYTE && first != CHACHA_BYTE &&
- first != TLS13_BYTE) { /* normal suites */
- switch (second) {
- #ifndef NO_RSA
- #ifndef NO_RC4
- case SSL_RSA_WITH_RC4_128_SHA :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- case SSL_RSA_WITH_RC4_128_MD5 :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- #endif /* NO_RC4 */
- case SSL_RSA_WITH_3DES_EDE_CBC_SHA :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- #ifdef HAVE_NTRU
- case TLS_NTRU_RSA_WITH_RC4_128_SHA :
- if (requirement == REQUIRES_NTRU)
- return 1;
- break;
- #endif /* HAVE_NTRU */
- case TLS_RSA_WITH_AES_128_CBC_SHA :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- case TLS_RSA_WITH_AES_128_CBC_SHA256 :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- #ifdef HAVE_NTRU
- case TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA :
- if (requirement == REQUIRES_NTRU)
- return 1;
- break;
- #endif /* HAVE_NTRU */
- case TLS_RSA_WITH_AES_256_CBC_SHA :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- #ifdef HAVE_NTRU
- case TLS_NTRU_RSA_WITH_AES_128_CBC_SHA :
- if (requirement == REQUIRES_NTRU)
- return 1;
- break;
- #endif /* HAVE_NTRU */
- case TLS_RSA_WITH_AES_256_CBC_SHA256 :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- case TLS_RSA_WITH_NULL_MD5 :
- case TLS_RSA_WITH_NULL_SHA :
- case TLS_RSA_WITH_NULL_SHA256 :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- #ifdef HAVE_NTRU
- case TLS_NTRU_RSA_WITH_AES_256_CBC_SHA :
- if (requirement == REQUIRES_NTRU)
- return 1;
- break;
- #endif /* HAVE_NTRU */
- #ifdef HAVE_IDEA
- case SSL_RSA_WITH_IDEA_CBC_SHA :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- #endif /* HAVE_IDEA */
- #endif /* !NO_RSA */
- #ifndef NO_PSK
- case TLS_PSK_WITH_AES_128_GCM_SHA256 :
- if (requirement == REQUIRES_PSK)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- case TLS_PSK_WITH_AES_256_GCM_SHA384 :
- if (requirement == REQUIRES_PSK)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- case TLS_PSK_WITH_AES_128_CBC_SHA256 :
- case TLS_PSK_WITH_AES_256_CBC_SHA384 :
- case TLS_PSK_WITH_AES_128_CBC_SHA :
- case TLS_PSK_WITH_AES_256_CBC_SHA :
- case TLS_PSK_WITH_NULL_SHA384 :
- case TLS_PSK_WITH_NULL_SHA256 :
- case TLS_PSK_WITH_NULL_SHA :
- if (requirement == REQUIRES_PSK)
- return 1;
- break;
- case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 :
- case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 :
- if (requirement == REQUIRES_DHE)
- return 1;
- if (requirement == REQUIRES_PSK)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 :
- case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 :
- case TLS_DHE_PSK_WITH_NULL_SHA384 :
- case TLS_DHE_PSK_WITH_NULL_SHA256 :
- if (requirement == REQUIRES_DHE)
- return 1;
- if (requirement == REQUIRES_PSK)
- return 1;
- break;
- #endif /* NO_PSK */
- #ifndef NO_RSA
- case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 :
- if (requirement == REQUIRES_RSA)
- return 1;
- if (requirement == REQUIRES_DHE)
- return 1;
- break;
- case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 :
- if (requirement == REQUIRES_RSA)
- return 1;
- if (requirement == REQUIRES_DHE)
- return 1;
- break;
- case TLS_DHE_RSA_WITH_AES_128_CBC_SHA :
- if (requirement == REQUIRES_RSA)
- return 1;
- if (requirement == REQUIRES_DHE)
- return 1;
- break;
- case TLS_DHE_RSA_WITH_AES_256_CBC_SHA :
- if (requirement == REQUIRES_RSA)
- return 1;
- if (requirement == REQUIRES_DHE)
- return 1;
- break;
- #ifndef NO_HC128
- case TLS_RSA_WITH_HC_128_MD5 :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- case TLS_RSA_WITH_HC_128_SHA :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- #endif /* NO_HC128 */
- #ifndef NO_RABBIT
- case TLS_RSA_WITH_RABBIT_SHA :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- #endif /* !NO_RABBIT */
- case TLS_RSA_WITH_AES_128_GCM_SHA256 :
- case TLS_RSA_WITH_AES_256_GCM_SHA384 :
- if (requirement == REQUIRES_RSA)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 :
- case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 :
- if (requirement == REQUIRES_RSA)
- return 1;
- if (requirement == REQUIRES_DHE)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- #ifdef HAVE_CAMELLIA
- case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA :
- case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA :
- case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 :
- case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 :
- if (requirement == REQUIRES_RSA)
- return 1;
- break;
- case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA :
- case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA :
- case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 :
- case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 :
- if (requirement == REQUIRES_RSA)
- return 1;
- if (requirement == REQUIRES_RSA_SIG)
- return 1;
- if (requirement == REQUIRES_DHE)
- return 1;
- break;
- #endif /* HAVE_CAMELLIA */
- case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
- if (requirement == REQUIRES_RSA)
- return 1;
- if (requirement == REQUIRES_RSA_SIG)
- return 1;
- if (requirement == REQUIRES_DHE)
- return 1;
- break;
- #endif
- #ifdef HAVE_ANON
- case TLS_DH_anon_WITH_AES_128_CBC_SHA :
- if (requirement == REQUIRES_DHE)
- return 1;
- break;
- case TLS_DH_anon_WITH_AES_256_GCM_SHA384:
- if (requirement == REQUIRES_DHE)
- return 1;
- if (requirement == REQUIRES_AEAD)
- return 1;
- break;
- #endif
- #ifdef WOLFSSL_MULTICAST
- case WDM_WITH_NULL_SHA256 :
- break;
- #endif
- default:
- WOLFSSL_MSG("Unsupported cipher suite, CipherRequires");
- return 0;
- } /* switch */
- } /* if ECC / Normal suites else */
- #endif /* !WOLFSSL_NO_TLS12 */
- return 0;
- }
- #endif /* !NO_WOLFSSL_SERVER && !NO_WOLFSSL_CLIENT */
- #ifndef NO_CERTS
- /* Match names with wildcards, each wildcard can represent a single name
- component or fragment but not multiple names, i.e.,
- *.z.com matches y.z.com but not x.y.z.com
- return 1 on success */
- int MatchDomainName(const char* pattern, int len, const char* str)
- {
- int ret = 0;
- char p, s;
- if (pattern == NULL || str == NULL || len <= 0)
- return 0;
- while (len > 0) {
- p = (char)XTOLOWER((unsigned char)*pattern++);
- if (p == '\0')
- break;
- if (p == '*') {
- while (--len > 0 &&
- (p = (char)XTOLOWER((unsigned char)*pattern++)) == '*') {
- }
- if (len == 0)
- p = '\0';
- while ( (s = (char)XTOLOWER((unsigned char) *str)) != '\0') {
- if (s == p)
- break;
- if (s == '.')
- return 0;
- str++;
- }
- }
- else {
- if (p != (char)XTOLOWER((unsigned char) *str))
- return 0;
- }
- if (len > 0) {
- str++;
- len--;
- }
- }
- if (*str == '\0' && len == 0) {
- ret = 1; /* success */
- }
- return ret;
- }
- /* try to find an altName match to domain, return 1 on success */
- int CheckAltNames(DecodedCert* dCert, char* domain)
- {
- int match = 0;
- DNS_entry* altName = NULL;
- WOLFSSL_MSG("Checking AltNames");
- if (dCert)
- altName = dCert->altNames;
- while (altName) {
- WOLFSSL_MSG("\tindividual AltName check");
- if (MatchDomainName(altName->name, altName->len, domain)){
- match = 1;
- break;
- }
- altName = altName->next;
- }
- return match;
- }
- #ifdef OPENSSL_EXTRA
- /* Check that alternative names, if they exists, match the domain.
- * Fail if there are wild patterns and they didn't match.
- * Check the common name if no alternative names matched.
- *
- * dCert Decoded cert to get the alternative names from.
- * domain Domain name to compare against.
- * checkCN Whether to check the common name.
- * returns whether there was a problem in matching.
- */
- static int CheckForAltNames(DecodedCert* dCert, char* domain, int* checkCN)
- {
- int match;
- DNS_entry* altName = NULL;
- WOLFSSL_MSG("Checking AltNames");
- if (dCert)
- altName = dCert->altNames;
- *checkCN = altName == NULL;
- match = 0;
- while (altName) {
- WOLFSSL_MSG("\tindividual AltName check");
- if (MatchDomainName(altName->name, altName->len, domain)) {
- match = 1;
- *checkCN = 0;
- break;
- }
- /* No matches and wild pattern match failed. */
- else if (altName->name && altName->len >=1 &&
- altName->name[0] == '*' && match == 0) {
- match = -1;
- }
- altName = altName->next;
- }
- return match != -1;
- }
- /* Check the domain name matches the subject alternative name or the subject
- * name.
- *
- * dcert Decoded certificate.
- * domainName The domain name.
- * domainNameLen The length of the domain name.
- * returns DOMAIN_NAME_MISMATCH when no match found and 0 on success.
- */
- int CheckHostName(DecodedCert* dCert, char *domainName, size_t domainNameLen)
- {
- int checkCN;
- /* Assume name is NUL terminated. */
- (void)domainNameLen;
- if (CheckForAltNames(dCert, domainName, &checkCN) == 0) {
- WOLFSSL_MSG("DomainName match on alt names failed too");
- return DOMAIN_NAME_MISMATCH;
- }
- if (checkCN == 1) {
- if (MatchDomainName(dCert->subjectCN, dCert->subjectCNLen,
- domainName) == 0) {
- WOLFSSL_MSG("DomainName match on common name failed");
- return DOMAIN_NAME_MISMATCH;
- }
- }
- return 0;
- }
- int CheckIPAddr(DecodedCert* dCert, char* ipasc)
- {
- WOLFSSL_MSG("Checking IPAddr");
- return CheckHostName(dCert, ipasc, (size_t)XSTRLEN(ipasc));
- }
- #endif
- #ifdef SESSION_CERTS
- static void AddSessionCertToChain(WOLFSSL_X509_CHAIN* chain,
- byte* certBuf, word32 certSz)
- {
- if (chain->count < MAX_CHAIN_DEPTH &&
- certSz < MAX_X509_SIZE) {
- chain->certs[chain->count].length = certSz;
- XMEMCPY(chain->certs[chain->count].buffer, certBuf, certSz);
- chain->count++;
- }
- else {
- WOLFSSL_MSG("Couldn't store chain cert for session");
- }
- }
- #endif
- #if defined(KEEP_PEER_CERT) || defined(SESSION_CERTS) || \
- defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- /* Copy parts X509 needs from Decoded cert, 0 on success */
- /* The same DecodedCert cannot be copied to WOLFSSL_X509 twice otherwise the
- * altNames pointers could be free'd by second x509 still active by first */
- int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert)
- {
- int ret = 0;
- if (x509 == NULL || dCert == NULL ||
- dCert->subjectCNLen < 0)
- return BAD_FUNC_ARG;
- x509->version = dCert->version + 1;
- XSTRNCPY(x509->issuer.name, dCert->issuer, ASN_NAME_MAX);
- x509->issuer.name[ASN_NAME_MAX - 1] = '\0';
- x509->issuer.sz = (int)XSTRLEN(x509->issuer.name) + 1;
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- if (dCert->issuerName.fullName != NULL) {
- XMEMCPY(&x509->issuer.fullName,
- &dCert->issuerName, sizeof(DecodedName));
- x509->issuer.fullName.fullName = (char*)XMALLOC(
- dCert->issuerName.fullNameLen, x509->heap,
- DYNAMIC_TYPE_X509);
- if (x509->issuer.fullName.fullName != NULL)
- XMEMCPY(x509->issuer.fullName.fullName,
- dCert->issuerName.fullName, dCert->issuerName.fullNameLen);
- }
- x509->issuer.x509 = x509;
- #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
- XSTRNCPY(x509->subject.name, dCert->subject, ASN_NAME_MAX);
- x509->subject.name[ASN_NAME_MAX - 1] = '\0';
- x509->subject.sz = (int)XSTRLEN(x509->subject.name) + 1;
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- if (dCert->subjectName.fullName != NULL) {
- XMEMCPY(&x509->subject.fullName,
- &dCert->subjectName, sizeof(DecodedName));
- x509->subject.fullName.fullName = (char*)XMALLOC(
- dCert->subjectName.fullNameLen, x509->heap, DYNAMIC_TYPE_X509);
- if (x509->subject.fullName.fullName != NULL)
- XMEMCPY(x509->subject.fullName.fullName,
- dCert->subjectName.fullName, dCert->subjectName.fullNameLen);
- }
- x509->subject.x509 = x509;
- #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
- x509->subject.rawLen = min(dCert->subjectRawLen, sizeof(x509->subject.raw));
- XMEMCPY(x509->subject.raw, dCert->subjectRaw, x509->subject.rawLen);
- #ifdef WOLFSSL_CERT_EXT
- x509->issuer.rawLen = min(dCert->issuerRawLen, sizeof(x509->issuer.raw));
- XMEMCPY(x509->issuer.raw, dCert->issuerRaw, x509->issuer.rawLen);
- #endif
- #endif
- XMEMCPY(x509->serial, dCert->serial, EXTERNAL_SERIAL_SIZE);
- x509->serialSz = dCert->serialSz;
- if (dCert->subjectCN && dCert->subjectCNLen < ASN_NAME_MAX) {
- XMEMCPY(x509->subjectCN, dCert->subjectCN, dCert->subjectCNLen);
- x509->subjectCN[dCert->subjectCNLen] = '\0';
- }
- else
- x509->subjectCN[0] = '\0';
- #ifdef WOLFSSL_SEP
- {
- int minSz = min(dCert->deviceTypeSz, EXTERNAL_SERIAL_SIZE);
- if (minSz > 0) {
- x509->deviceTypeSz = minSz;
- XMEMCPY(x509->deviceType, dCert->deviceType, minSz);
- }
- else
- x509->deviceTypeSz = 0;
- minSz = min(dCert->hwTypeSz, EXTERNAL_SERIAL_SIZE);
- if (minSz > 0) {
- x509->hwTypeSz = minSz;
- XMEMCPY(x509->hwType, dCert->hwType, minSz);
- }
- else
- x509->hwTypeSz = 0;
- minSz = min(dCert->hwSerialNumSz, EXTERNAL_SERIAL_SIZE);
- if (minSz > 0) {
- x509->hwSerialNumSz = minSz;
- XMEMCPY(x509->hwSerialNum, dCert->hwSerialNum, minSz);
- }
- else
- x509->hwSerialNumSz = 0;
- }
- #endif /* WOLFSSL_SEP */
- {
- int minSz;
- if (dCert->beforeDateLen > 0) {
- minSz = min(dCert->beforeDate[1], MAX_DATE_SZ);
- x509->notBefore.type = dCert->beforeDate[0];
- x509->notBefore.length = minSz;
- XMEMCPY(x509->notBefore.data, &dCert->beforeDate[2], minSz);
- }
- else
- x509->notBefore.length = 0;
- if (dCert->afterDateLen > 0) {
- minSz = min(dCert->afterDate[1], MAX_DATE_SZ);
- x509->notAfter.type = dCert->afterDate[0];
- x509->notAfter.length = minSz;
- XMEMCPY(x509->notAfter.data, &dCert->afterDate[2], minSz);
- }
- else
- x509->notAfter.length = 0;
- }
- if (dCert->publicKey != NULL && dCert->pubKeySize != 0) {
- x509->pubKey.buffer = (byte*)XMALLOC(
- dCert->pubKeySize, x509->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- if (x509->pubKey.buffer != NULL) {
- x509->pubKeyOID = dCert->keyOID;
- x509->pubKey.length = dCert->pubKeySize;
- XMEMCPY(x509->pubKey.buffer, dCert->publicKey, dCert->pubKeySize);
- }
- else
- ret = MEMORY_E;
- #if defined(OPENSSL_ALL)
- if (ret == 0) {
- x509->key.pubKeyOID = dCert->keyOID;
- if (!x509->key.algor) {
- x509->key.algor = wolfSSL_X509_ALGOR_new();
- } else {
- wolfSSL_ASN1_OBJECT_free(x509->key.algor->algorithm);
- }
- if (!(x509->key.algor->algorithm =
- wolfSSL_OBJ_nid2obj(dCert->keyOID))) {
- ret = PUBLIC_KEY_E;
- }
- wolfSSL_EVP_PKEY_free(x509->key.pkey);
- if (!(x509->key.pkey = wolfSSL_d2i_PUBKEY(NULL,
- &dCert->publicKey,
- dCert->pubKeySize))) {
- ret = PUBLIC_KEY_E;
- }
- }
- #endif
- }
- if (dCert->signature != NULL && dCert->sigLength != 0 &&
- dCert->sigLength <= MAX_ENCODED_SIG_SZ) {
- x509->sig.buffer = (byte*)XMALLOC(
- dCert->sigLength, x509->heap, DYNAMIC_TYPE_SIGNATURE);
- if (x509->sig.buffer == NULL) {
- ret = MEMORY_E;
- }
- else {
- XMEMCPY(x509->sig.buffer, dCert->signature, dCert->sigLength);
- x509->sig.length = dCert->sigLength;
- x509->sigOID = dCert->signatureOID;
- }
- #if defined(OPENSSL_ALL)
- wolfSSL_ASN1_OBJECT_free(x509->algor.algorithm);
- if (!(x509->algor.algorithm =
- wolfSSL_OBJ_nid2obj(dCert->signatureOID))) {
- ret = PUBLIC_KEY_E;
- }
- #endif
- }
- /* store cert for potential retrieval */
- if (AllocDer(&x509->derCert, dCert->maxIdx, CERT_TYPE, x509->heap) == 0) {
- XMEMCPY(x509->derCert->buffer, dCert->source, dCert->maxIdx);
- }
- else {
- ret = MEMORY_E;
- }
- x509->altNames = dCert->altNames;
- dCert->weOwnAltNames = 0;
- x509->altNamesNext = x509->altNames; /* index hint */
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
- !defined(IGNORE_NAME_CONSTRAINTS)
- /* add copies of alternate emails from dCert to X509 */
- if (dCert->altEmailNames != NULL) {
- DNS_entry* cur = dCert->altEmailNames;
- while (cur != NULL) {
- if (cur->type == ASN_RFC822_TYPE) {
- DNS_entry* dnsEntry;
- int strLen = cur->len;
- dnsEntry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), x509->heap,
- DYNAMIC_TYPE_ALTNAME);
- if (dnsEntry == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- return MEMORY_E;
- }
- dnsEntry->type = ASN_RFC822_TYPE;
- dnsEntry->name = (char*)XMALLOC(strLen + 1, x509->heap,
- DYNAMIC_TYPE_ALTNAME);
- if (dnsEntry->name == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- XFREE(dnsEntry, x509->heap, DYNAMIC_TYPE_ALTNAME);
- return MEMORY_E;
- }
- dnsEntry->len = strLen;
- XMEMCPY(dnsEntry->name, cur->name, strLen);
- dnsEntry->name[strLen] = '\0';
- dnsEntry->next = x509->altNames;
- x509->altNames = dnsEntry;
- }
- cur = cur->next;
- }
- }
- #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
- x509->isCa = dCert->isCA;
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- x509->pathLength = dCert->pathLength;
- x509->keyUsage = dCert->extKeyUsage;
- x509->CRLdistSet = dCert->extCRLdistSet;
- x509->CRLdistCrit = dCert->extCRLdistCrit;
- x509->CRLInfo = dCert->extCrlInfo;
- x509->CRLInfoSz = dCert->extCrlInfoSz;
- x509->authInfoSet = dCert->extAuthInfoSet;
- x509->authInfoCrit = dCert->extAuthInfoCrit;
- if (dCert->extAuthInfo != NULL && dCert->extAuthInfoSz > 0) {
- x509->authInfo = (byte*)XMALLOC(dCert->extAuthInfoSz, x509->heap,
- DYNAMIC_TYPE_X509_EXT);
- if (x509->authInfo != NULL) {
- XMEMCPY(x509->authInfo, dCert->extAuthInfo, dCert->extAuthInfoSz);
- x509->authInfoSz = dCert->extAuthInfoSz;
- }
- else {
- ret = MEMORY_E;
- }
- }
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
- if (dCert->extAuthInfoCaIssuer != NULL && dCert->extAuthInfoCaIssuerSz > 0) {
- x509->authInfoCaIssuer = (byte*)XMALLOC(dCert->extAuthInfoCaIssuerSz, x509->heap,
- DYNAMIC_TYPE_X509_EXT);
- if (x509->authInfoCaIssuer != NULL) {
- XMEMCPY(x509->authInfoCaIssuer, dCert->extAuthInfoCaIssuer, dCert->extAuthInfoCaIssuerSz);
- x509->authInfoCaIssuerSz = dCert->extAuthInfoCaIssuerSz;
- }
- else {
- ret = MEMORY_E;
- }
- }
- #endif
- x509->basicConstSet = dCert->extBasicConstSet;
- x509->basicConstCrit = dCert->extBasicConstCrit;
- x509->basicConstPlSet = dCert->pathLengthSet;
- x509->subjAltNameSet = dCert->extSubjAltNameSet;
- x509->subjAltNameCrit = dCert->extSubjAltNameCrit;
- x509->authKeyIdSet = dCert->extAuthKeyIdSet;
- x509->authKeyIdCrit = dCert->extAuthKeyIdCrit;
- if (dCert->extAuthKeyIdSrc != NULL && dCert->extAuthKeyIdSz != 0) {
- x509->authKeyId = (byte*)XMALLOC(dCert->extAuthKeyIdSz, x509->heap,
- DYNAMIC_TYPE_X509_EXT);
- if (x509->authKeyId != NULL) {
- XMEMCPY(x509->authKeyId,
- dCert->extAuthKeyIdSrc, dCert->extAuthKeyIdSz);
- x509->authKeyIdSz = dCert->extAuthKeyIdSz;
- }
- else
- ret = MEMORY_E;
- }
- x509->subjKeyIdSet = dCert->extSubjKeyIdSet;
- x509->subjKeyIdCrit = dCert->extSubjKeyIdCrit;
- if (dCert->extSubjKeyIdSrc != NULL && dCert->extSubjKeyIdSz != 0) {
- x509->subjKeyId = (byte*)XMALLOC(dCert->extSubjKeyIdSz, x509->heap,
- DYNAMIC_TYPE_X509_EXT);
- if (x509->subjKeyId != NULL) {
- XMEMCPY(x509->subjKeyId,
- dCert->extSubjKeyIdSrc, dCert->extSubjKeyIdSz);
- x509->subjKeyIdSz = dCert->extSubjKeyIdSz;
- }
- else
- ret = MEMORY_E;
- }
- x509->keyUsageSet = dCert->extKeyUsageSet;
- x509->keyUsageCrit = dCert->extKeyUsageCrit;
- if (dCert->extExtKeyUsageSrc != NULL && dCert->extExtKeyUsageSz > 0) {
- x509->extKeyUsageSrc = (byte*)XMALLOC(dCert->extExtKeyUsageSz,
- x509->heap, DYNAMIC_TYPE_X509_EXT);
- if (x509->extKeyUsageSrc != NULL) {
- XMEMCPY(x509->extKeyUsageSrc, dCert->extExtKeyUsageSrc,
- dCert->extExtKeyUsageSz);
- x509->extKeyUsageSz = dCert->extExtKeyUsageSz;
- x509->extKeyUsageCrit = dCert->extExtKeyUsageCrit;
- x509->extKeyUsageCount = dCert->extExtKeyUsageCount;
- }
- else {
- ret = MEMORY_E;
- }
- }
- #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT)
- x509->certPolicySet = dCert->extCertPolicySet;
- x509->certPolicyCrit = dCert->extCertPolicyCrit;
- #endif /* WOLFSSL_SEP || WOLFSSL_QT */
- #ifdef WOLFSSL_CERT_EXT
- {
- int i;
- for (i = 0; i < dCert->extCertPoliciesNb && i < MAX_CERTPOL_NB; i++)
- XMEMCPY(x509->certPolicies[i], dCert->extCertPolicies[i],
- MAX_CERTPOL_SZ);
- x509->certPoliciesNb = dCert->extCertPoliciesNb;
- }
- #endif /* WOLFSSL_CERT_EXT */
- #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
- #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
- x509->pkCurveOID = dCert->pkCurveOID;
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- return ret;
- }
- #endif /* KEEP_PEER_CERT || SESSION_CERTS */
- #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
- (defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) && !defined(WOLFSSL_NO_TLS12))
- static int ProcessCSR(WOLFSSL* ssl, byte* input, word32* inOutIdx,
- word32 status_length)
- {
- int ret = 0;
- OcspRequest* request;
- #ifdef WOLFSSL_SMALL_STACK
- CertStatus* status;
- OcspResponse* response;
- #else
- CertStatus status[1];
- OcspResponse response[1];
- #endif
- do {
- #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
- if (ssl->status_request) {
- request = (OcspRequest*)TLSX_CSR_GetRequest(ssl->extensions);
- ssl->status_request = 0;
- break;
- }
- #endif
- #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
- if (ssl->status_request_v2) {
- request = (OcspRequest*)TLSX_CSR2_GetRequest(ssl->extensions,
- WOLFSSL_CSR2_OCSP, 0);
- ssl->status_request_v2 = 0;
- break;
- }
- #endif
- return BUFFER_ERROR;
- } while(0);
- if (request == NULL)
- return BAD_CERTIFICATE_STATUS_ERROR; /* not expected */
- #ifdef WOLFSSL_SMALL_STACK
- status = (CertStatus*)XMALLOC(sizeof(CertStatus), ssl->heap,
- DYNAMIC_TYPE_OCSP_STATUS);
- response = (OcspResponse*)XMALLOC(sizeof(OcspResponse), ssl->heap,
- DYNAMIC_TYPE_OCSP_REQUEST);
- if (status == NULL || response == NULL) {
- if (status)
- XFREE(status, NULL, DYNAMIC_TYPE_OCSP_STATUS);
- if (response)
- XFREE(response, NULL, DYNAMIC_TYPE_OCSP_REQUEST);
- return MEMORY_ERROR;
- }
- #endif
- InitOcspResponse(response, status, input +*inOutIdx, status_length);
- if (OcspResponseDecode(response, ssl->ctx->cm, ssl->heap, 0) != 0)
- ret = BAD_CERTIFICATE_STATUS_ERROR;
- else if (CompareOcspReqResp(request, response) != 0)
- ret = BAD_CERTIFICATE_STATUS_ERROR;
- else if (response->responseStatus != OCSP_SUCCESSFUL)
- ret = BAD_CERTIFICATE_STATUS_ERROR;
- else if (response->status->status == CERT_REVOKED)
- ret = OCSP_CERT_REVOKED;
- else if (response->status->status != CERT_GOOD)
- ret = BAD_CERTIFICATE_STATUS_ERROR;
- *inOutIdx += status_length;
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(status, ssl->heap, DYNAMIC_TYPE_OCSP_STATUS);
- XFREE(response, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
- #endif
- return ret;
- }
- #endif
- #ifdef HAVE_PK_CALLBACKS
- #ifdef HAVE_ECC
- static int SigPkCbEccVerify(const unsigned char* sig, unsigned int sigSz,
- const unsigned char* hash, unsigned int hashSz,
- const unsigned char* keyDer, unsigned int keySz,
- int* result, void* ctx)
- {
- int ret = NOT_COMPILED_IN;
- WOLFSSL* ssl = (WOLFSSL*)ctx;
- if (ssl && ssl->ctx->EccVerifyCb) {
- ret = ssl->ctx->EccVerifyCb(ssl, sig, sigSz, hash, hashSz,
- keyDer, keySz, result, ssl->EccVerifyCtx);
- }
- return ret;
- }
- #endif
- #ifndef NO_RSA
- static int SigPkCbRsaVerify(unsigned char* sig, unsigned int sigSz,
- unsigned char** out, const unsigned char* keyDer, unsigned int keySz,
- void* ctx)
- {
- int ret = NOT_COMPILED_IN;
- WOLFSSL* ssl = (WOLFSSL*)ctx;
- if (ssl && ssl->ctx->RsaVerifyCb) {
- ret = ssl->ctx->RsaVerifyCb(ssl, sig, sigSz, out, keyDer, keySz,
- ssl->RsaVerifyCtx);
- }
- return ret;
- }
- #endif
- int InitSigPkCb(WOLFSSL* ssl, SignatureCtx* sigCtx)
- {
- if (ssl == NULL || sigCtx == NULL)
- return BAD_FUNC_ARG;
- /* only setup the verify callback if a PK is set */
- #ifdef HAVE_ECC
- if (ssl->ctx->EccVerifyCb) {
- sigCtx->pkCbEcc = SigPkCbEccVerify;
- sigCtx->pkCtxEcc = ssl;
- }
- #endif
- #ifndef NO_RSA
- /* only setup the verify callback if a PK is set */
- if (ssl->ctx->RsaVerifyCb) {
- sigCtx->pkCbRsa = SigPkCbRsaVerify;
- sigCtx->pkCtxRsa = ssl;
- }
- #endif
- return 0;
- }
- #endif /* HAVE_PK_CALLBACKS */
- #if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
- static void DoCertFatalAlert(WOLFSSL* ssl, int ret)
- {
- int alertWhy;
- if (ssl == NULL || ret == 0) {
- return;
- }
- /* Determine alert reason */
- alertWhy = bad_certificate;
- if (ret == ASN_AFTER_DATE_E || ret == ASN_BEFORE_DATE_E) {
- alertWhy = certificate_expired;
- }
- #if (defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD))
- else if (ret == CRL_CERT_REVOKED) {
- alertWhy = certificate_revoked;
- }
- #endif
- else if (ret == NO_PEER_CERT) {
- #ifdef WOLFSSL_TLS13
- if (ssl->options.tls1_3) {
- alertWhy = certificate_required;
- }
- else
- #endif
- {
- alertWhy = handshake_failure;
- }
- }
- /* send fatal alert and mark connection closed */
- SendAlert(ssl, alert_fatal, alertWhy); /* try to send */
- ssl->options.isClosed = 1;
- }
- /* WOLFSSL_ALWAYS_VERIFY_CB: Use verify callback for success or failure cases */
- /* WOLFSSL_VERIFY_CB_ALL_CERTS: Issue callback for all intermediate certificates */
- /* Callback is issued for certificate presented in TLS Certificate (11) packet.
- * The intermediates are done first then peer leaf cert last. Use the
- * store->error_depth member to determine index (0=peer, >1 intermediates)
- */
- int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret,
- ProcPeerCertArgs* args)
- {
- int verify_ok = 0, use_cb = 0;
- void *heap = (ssl != NULL) ? ssl->heap : cm->heap;
- /* Determine if verify was okay */
- if (ret == 0) {
- verify_ok = 1;
- }
- /* Determine if verify callback should be used */
- if (ret != 0) {
- if ((ssl != NULL) && (!ssl->options.verifyNone)) {
- use_cb = 1; /* always report errors */
- }
- }
- #ifdef WOLFSSL_ALWAYS_VERIFY_CB
- /* always use verify callback on peer leaf cert */
- if (args->certIdx == 0) {
- use_cb = 1;
- }
- #endif
- #ifdef WOLFSSL_VERIFY_CB_ALL_CERTS
- /* perform verify callback on other intermediate certs (not just peer) */
- if (args->certIdx > 0) {
- use_cb = 1;
- }
- #endif
- #if defined(OPENSSL_EXTRA)
- /* perform domain name check on the peer certificate */
- if (args->dCertInit && args->dCert && (ssl != NULL) &&
- ssl->param && ssl->param->hostName[0]) {
- /* If altNames names is present, then subject common name is ignored */
- if (args->dCert->altNames != NULL) {
- if (CheckAltNames(args->dCert, ssl->param->hostName) == 0 ) {
- if (ret == 0) {
- ret = DOMAIN_NAME_MISMATCH;
- }
- }
- }
- else {
- if (args->dCert->subjectCN) {
- if (MatchDomainName(args->dCert->subjectCN,
- args->dCert->subjectCNLen,
- ssl->param->hostName) == 0) {
- if (ret == 0) {
- ret = DOMAIN_NAME_MISMATCH;
- }
- }
- }
- }
- }
- /* perform IP address check on the peer certificate */
- if ((args->dCertInit != 0) && (args->dCert != NULL) && (ssl != NULL) &&
- (ssl->param != NULL) && (XSTRLEN(ssl->param->ipasc) > 0)) {
- if (CheckIPAddr(args->dCert, ssl->param->ipasc) != 0) {
- if (ret == 0) {
- ret = IPADDR_MISMATCH;
- }
- }
- }
- #endif
- /* if verify callback has been set */
- if ((use_cb && (ssl != NULL) && ((ssl->verifyCallback != NULL)
- #ifdef OPENSSL_ALL
- || (ssl->ctx->verifyCertCb != NULL)
- #endif
- ))
- #ifndef NO_WOLFSSL_CM_VERIFY
- || (cm->verifyCallback != NULL)
- #endif
- ) {
- int verifyFail = 0;
- #ifdef WOLFSSL_SMALL_STACK
- WOLFSSL_X509_STORE_CTX* store;
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- WOLFSSL_X509* x509;
- #endif
- char* domain = NULL;
- #else
- WOLFSSL_X509_STORE_CTX store[1];
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- WOLFSSL_X509 x509[1];
- #endif
- char domain[ASN_NAME_MAX];
- #endif
- #ifdef WOLFSSL_SMALL_STACK
- store = (WOLFSSL_X509_STORE_CTX*)XMALLOC(
- sizeof(WOLFSSL_X509_STORE_CTX), heap, DYNAMIC_TYPE_X509_STORE);
- if (store == NULL) {
- return MEMORY_E;
- }
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- x509 = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), heap,
- DYNAMIC_TYPE_X509);
- if (x509 == NULL) {
- XFREE(store, heap, DYNAMIC_TYPE_X509);
- return MEMORY_E;
- }
- #endif
- domain = (char*)XMALLOC(ASN_NAME_MAX, heap, DYNAMIC_TYPE_STRING);
- if (domain == NULL) {
- XFREE(store, heap, DYNAMIC_TYPE_X509);
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- XFREE(x509, heap, DYNAMIC_TYPE_X509);
- #endif
- return MEMORY_E;
- }
- #endif /* WOLFSSL_SMALL_STACK */
- XMEMSET(store, 0, sizeof(WOLFSSL_X509_STORE_CTX));
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- XMEMSET(x509, 0, sizeof(WOLFSSL_X509));
- #endif
- domain[0] = '\0';
- /* build subject CN as string to return in store */
- if (args->dCertInit && args->dCert && args->dCert->subjectCN) {
- int subjectCNLen = args->dCert->subjectCNLen;
- if (subjectCNLen > ASN_NAME_MAX-1)
- subjectCNLen = ASN_NAME_MAX-1;
- if (subjectCNLen > 0) {
- XMEMCPY(domain, args->dCert->subjectCN, subjectCNLen);
- domain[subjectCNLen] = '\0';
- }
- }
- store->error = ret;
- store->error_depth = args->certIdx;
- store->discardSessionCerts = 0;
- store->domain = domain;
- store->userCtx = (ssl != NULL) ? ssl->verifyCbCtx : cm;
- store->certs = args->certs;
- store->totalCerts = args->totalCerts;
- #if defined(HAVE_EX_DATA) || defined(FORTRESS)
- if (wolfSSL_CRYPTO_set_ex_data(&store->ex_data, 0, ssl)
- != WOLFSSL_SUCCESS) {
- WOLFSSL_MSG("Failed to store ssl context in WOLFSSL_X509_STORE_CTX");
- }
- #endif
- if (ssl != NULL) {
- #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
- if (ssl->ctx->x509_store_pt != NULL) {
- store->store = ssl->ctx->x509_store_pt;
- }
- else {
- store->store = &ssl->ctx->x509_store;
- }
- #if defined(OPENSSL_EXTRA)
- store->depth = args->count;
- store->param = (WOLFSSL_X509_VERIFY_PARAM*)XMALLOC(
- sizeof(WOLFSSL_X509_VERIFY_PARAM),
- heap, DYNAMIC_TYPE_OPENSSL);
- if (store->param == NULL) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(domain, heap, DYNAMIC_TYPE_STRING);
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- XFREE(x509, heap, DYNAMIC_TYPE_X509);
- #endif
- XFREE(store, heap, DYNAMIC_TYPE_X509_STORE);
- #endif
- return MEMORY_E;
- }
- XMEMSET(store->param, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM));
- /* Overwrite with non-default param values in SSL */
- if (ssl->param) {
- if (ssl->param->check_time)
- store->param->check_time = ssl->param->check_time;
- if (ssl->param->flags)
- store->param->flags = ssl->param->flags;
- if (ssl->param->hostName[0])
- XMEMCPY(store->param->hostName, ssl->param->hostName,
- WOLFSSL_HOST_NAME_MAX);
- }
- #endif /* defined(OPENSSL_EXTRA) */
- #endif /* defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)*/
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- #ifdef KEEP_PEER_CERT
- if (args->certIdx == 0) {
- store->current_cert = &ssl->peerCert; /* use existing X509 */
- }
- else
- #endif
- {
- InitX509(x509, 0, heap);
- if (CopyDecodedToX509(x509, args->dCert) == 0) {
- store->current_cert = x509;
- }
- else {
- FreeX509(x509);
- }
- }
- #endif
- #ifdef SESSION_CERTS
- store->sesChain = &ssl->session.chain;
- #endif
- }
- #ifndef NO_WOLFSSL_CM_VERIFY
- /* non-zero return code indicates failure override */
- if ((cm != NULL) && (cm->verifyCallback != NULL)) {
- store->userCtx = cm;
- if (cm->verifyCallback(verify_ok, store)) {
- if (ret != 0) {
- WOLFSSL_MSG("Verify CM callback overriding error!");
- ret = 0;
- }
- }
- else {
- verifyFail = 1;
- }
- }
- #endif
- if (ssl != NULL) {
- #ifdef OPENSSL_ALL
- /* non-zero return code indicates failure override */
- if (ssl->ctx->verifyCertCb) {
- if (ssl->ctx->verifyCertCb(store, ssl->ctx->verifyCertCbArg)) {
- if (ret != 0) {
- WOLFSSL_MSG("Verify Cert callback overriding error!");
- ret = 0;
- }
- }
- else {
- verifyFail = 1;
- }
- }
- #endif
- /* non-zero return code indicates failure override */
- if (ssl->verifyCallback) {
- if (ssl->verifyCallback(verify_ok, store)) {
- if (ret != 0) {
- WOLFSSL_MSG("Verify callback overriding error!");
- ret = 0;
- }
- }
- else {
- verifyFail = 1;
- }
- }
- }
- if (verifyFail) {
- /* induce error if one not present */
- if (ret == 0) {
- ret = VERIFY_CERT_ERROR;
- }
- /* mark as verify error */
- args->verifyErr = 1;
- }
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- if (args->certIdx > 0)
- FreeX509(x509);
- #endif
- #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
- wolfSSL_sk_X509_free(store->chain);
- store->chain = NULL;
- #endif
- #ifdef SESSION_CERTS
- if ((ssl != NULL) && (store->discardSessionCerts)) {
- WOLFSSL_MSG("Verify callback requested discard sess certs");
- ssl->session.chain.count = 0;
- #ifdef WOLFSSL_ALT_CERT_CHAINS
- ssl->session.altChain.count = 0;
- #endif
- }
- #endif /* SESSION_CERTS */
- #ifdef OPENSSL_EXTRA
- if ((ssl != NULL) && (store->param)) {
- XFREE(store->param, heap, DYNAMIC_TYPE_OPENSSL);
- }
- #endif
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(domain, heap, DYNAMIC_TYPE_STRING);
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- XFREE(x509, heap, DYNAMIC_TYPE_X509);
- #endif
- XFREE(store, heap, DYNAMIC_TYPE_X509_STORE);
- #endif
- }
- (void)heap;
- return ret;
- }
- static void FreeProcPeerCertArgs(WOLFSSL* ssl, void* pArgs)
- {
- ProcPeerCertArgs* args = (ProcPeerCertArgs*)pArgs;
- (void)ssl;
- if (args->certs) {
- XFREE(args->certs, ssl->heap, DYNAMIC_TYPE_DER);
- args->certs = NULL;
- }
- #ifdef WOLFSSL_TLS13
- if (args->exts) {
- XFREE(args->exts, ssl->heap, DYNAMIC_TYPE_CERT_EXT);
- args->exts = NULL;
- }
- #endif
- if (args->dCert) {
- if (args->dCertInit) {
- FreeDecodedCert(args->dCert);
- args->dCertInit = 0;
- }
- XFREE(args->dCert, ssl->heap, DYNAMIC_TYPE_DCERT);
- args->dCert = NULL;
- }
- }
- static int ProcessPeerCertParse(WOLFSSL* ssl, ProcPeerCertArgs* args,
- int certType, int verify, byte** pSubjectHash, int* pAlreadySigner)
- {
- int ret = 0;
- buffer* cert;
- byte* subjectHash = NULL;
- int alreadySigner = 0;
- #ifdef WOLFSSL_SMALL_CERT_VERIFY
- int sigRet = 0;
- #endif
- if (ssl == NULL || args == NULL)
- return BAD_FUNC_ARG;
- /* check to make sure certificate index is valid */
- if (args->certIdx > args->count)
- return BUFFER_E;
- /* check if returning from non-blocking OCSP */
- /* skip this section because cert is already initialized and parsed */
- #ifdef WOLFSSL_NONBLOCK_OCSP
- if (args->lastErr == OCSP_WANT_READ) {
- args->lastErr = 0; /* clear error */
- return 0;
- }
- #endif
- #ifdef WOLFSSL_TRUST_PEER_CERT
- /* we have trusted peer */
- if (args->haveTrustPeer) {
- return 0;
- }
- #endif
- /* get certificate buffer */
- cert = &args->certs[args->certIdx];
- #ifdef WOLFSSL_SMALL_CERT_VERIFY
- if (verify == VERIFY) {
- /* for small cert verify, release decoded cert during signature check to
- reduce peak memory usage */
- if (args->dCert != NULL) {
- if (args->dCertInit) {
- FreeDecodedCert(args->dCert);
- args->dCertInit = 0;
- }
- XFREE(args->dCert, ssl->heap, DYNAMIC_TYPE_DCERT);
- args->dCert = NULL;
- }
- /* perform cert parsing and signature check */
- sigRet = CheckCertSignature(cert->buffer, cert->length,
- ssl->heap, ssl->ctx->cm);
- /* fail on errors here after the ParseCertRelative call, so dCert is populated */
- /* verify name only in ParseCertRelative below, signature check done */
- verify = VERIFY_NAME;
- }
- #endif /* WOLFSSL_SMALL_CERT_VERIFY */
- /* make sure the decoded cert structure is allocated and initialized */
- if (!args->dCertInit
- #ifdef WOLFSSL_SMALL_CERT_VERIFY
- || args->dCert == NULL
- #endif
- ) {
- #ifdef WOLFSSL_SMALL_CERT_VERIFY
- if (args->dCert == NULL) {
- args->dCert = (DecodedCert*)XMALLOC(
- sizeof(DecodedCert), ssl->heap,
- DYNAMIC_TYPE_DCERT);
- if (args->dCert == NULL) {
- return MEMORY_E;
- }
- }
- #endif
- InitDecodedCert(args->dCert, cert->buffer, cert->length, ssl->heap);
- args->dCertInit = 1;
- args->dCert->sigCtx.devId = ssl->devId;
- #ifdef WOLFSSL_ASYNC_CRYPT
- args->dCert->sigCtx.asyncCtx = ssl;
- #endif
- #ifdef HAVE_PK_CALLBACKS
- /* setup the PK callback context */
- ret = InitSigPkCb(ssl, &args->dCert->sigCtx);
- if (ret != 0)
- return ret;
- #endif
- }
- /* Parse Certificate */
- ret = ParseCertRelative(args->dCert, certType, verify, ssl->ctx->cm);
- /* perform below checks for date failure cases */
- if (ret == 0 || ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
- /* get subject and determine if already loaded */
- #ifndef NO_SKID
- if (args->dCert->extAuthKeyIdSet)
- subjectHash = args->dCert->extSubjKeyId;
- else
- #endif
- subjectHash = args->dCert->subjectHash;
- alreadySigner = AlreadySigner(ssl->ctx->cm, subjectHash);
- }
- #ifdef WOLFSSL_SMALL_CERT_VERIFY
- /* get signature check failures from above */
- if (ret == 0)
- ret = sigRet;
- #endif
- if (pSubjectHash)
- *pSubjectHash = subjectHash;
- if (pAlreadySigner)
- *pAlreadySigner = alreadySigner;
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl,
- args->dCert->sigCtx.asyncDev);
- }
- #endif
- return ret;
- }
- /* Check key sizes for certs. Is redundant check since
- ProcessBuffer also performs this check. */
- static int ProcessPeerCertCheckKey(WOLFSSL* ssl, ProcPeerCertArgs* args)
- {
- int ret = 0;
- if (ssl->options.verifyNone) {
- return ret;
- }
- switch (args->dCert->keyOID) {
- #ifndef NO_RSA
- case RSAk:
- if (ssl->options.minRsaKeySz < 0 ||
- args->dCert->pubKeySize <
- (word16)ssl->options.minRsaKeySz) {
- WOLFSSL_MSG(
- "RSA key size in cert chain error");
- ret = RSA_KEY_SIZE_E;
- }
- break;
- #endif /* !NO_RSA */
- #ifdef HAVE_ECC
- case ECDSAk:
- if (ssl->options.minEccKeySz < 0 ||
- args->dCert->pubKeySize <
- (word16)ssl->options.minEccKeySz) {
- WOLFSSL_MSG(
- "ECC key size in cert chain error");
- ret = ECC_KEY_SIZE_E;
- }
- break;
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- case ED25519k:
- if (ssl->options.minEccKeySz < 0 ||
- ED25519_KEY_SIZE < (word16)ssl->options.minEccKeySz) {
- WOLFSSL_MSG(
- "ECC key size in cert chain error");
- ret = ECC_KEY_SIZE_E;
- }
- break;
- #endif /* HAVE_ED25519 */
- #ifdef HAVE_ED448
- case ED448k:
- if (ssl->options.minEccKeySz < 0 ||
- ED448_KEY_SIZE < (word16)ssl->options.minEccKeySz) {
- WOLFSSL_MSG(
- "ECC key size in cert chain error");
- ret = ECC_KEY_SIZE_E;
- }
- break;
- #endif /* HAVE_ED448 */
- default:
- WOLFSSL_MSG("Key size not checked");
- /* key not being checked for size if not in
- switch */
- break;
- }
- return ret;
- }
- int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx,
- word32 totalSz)
- {
- int ret = 0;
- #ifdef WOLFSSL_ASYNC_CRYPT
- ProcPeerCertArgs* args = (ProcPeerCertArgs*)ssl->async.args;
- typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
- (void)sizeof(args_test);
- #elif defined(WOLFSSL_NONBLOCK_OCSP)
- ProcPeerCertArgs* args = ssl->nonblockarg;
- #elif defined(WOLFSSL_SMALL_STACK)
- ProcPeerCertArgs* args = NULL;
- #else
- ProcPeerCertArgs args[1];
- #endif
- byte* subjectHash = NULL;
- int alreadySigner = 0;
- WOLFSSL_ENTER("ProcessPeerCerts");
- #ifdef WOLFSSL_ASYNC_CRYPT
- ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
- if (ret != WC_NOT_PENDING_E) {
- /* Check for error */
- if (ret < 0)
- goto exit_ppc;
- }
- else
- #elif defined(WOLFSSL_NONBLOCK_OCSP)
- if (args == NULL) {
- args = (ProcPeerCertArgs*)XMALLOC(
- sizeof(ProcPeerCertArgs), ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (args == NULL) {
- ERROR_OUT(MEMORY_E, exit_ppc);
- }
- }
- if (ssl->nonblockarg == NULL) /* new args */
- #elif defined(WOLFSSL_SMALL_STACK)
- args = (ProcPeerCertArgs*)XMALLOC(
- sizeof(ProcPeerCertArgs), ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (args == NULL) {
- ERROR_OUT(MEMORY_E, exit_ppc);
- }
- #endif
- {
- /* Reset state */
- ret = 0;
- ssl->options.asyncState = TLS_ASYNC_BEGIN;
- XMEMSET(args, 0, sizeof(ProcPeerCertArgs));
- args->idx = *inOutIdx;
- args->begin = *inOutIdx;
- #ifdef WOLFSSL_ASYNC_CRYPT
- ssl->async.freeArgs = FreeProcPeerCertArgs;
- #elif defined(WOLFSSL_NONBLOCK_OCSP)
- ssl->nonblockarg = args;
- #endif
- }
- switch (ssl->options.asyncState)
- {
- case TLS_ASYNC_BEGIN:
- {
- word32 listSz;
- #ifdef WOLFSSL_CALLBACKS
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "Certificate");
- if (ssl->toInfoOn)
- AddLateName("Certificate", &ssl->timeoutInfo);
- #endif
- #ifdef WOLFSSL_TLS13
- if (ssl->options.tls1_3) {
- byte ctxSz;
- /* Certificate Request Context */
- if ((args->idx - args->begin) + OPAQUE8_LEN > totalSz)
- ERROR_OUT(BUFFER_ERROR, exit_ppc);
- ctxSz = *(input + args->idx);
- args->idx++;
- if ((args->idx - args->begin) + ctxSz > totalSz)
- ERROR_OUT(BUFFER_ERROR, exit_ppc);
- #ifndef NO_WOLFSSL_CLIENT
- /* Must be empty when received from server. */
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- if (ctxSz != 0) {
- ERROR_OUT(INVALID_CERT_CTX_E, exit_ppc);
- }
- }
- #endif
- #ifndef NO_WOLFSSL_SERVER
- /* Must contain value sent in request. */
- if (ssl->options.side == WOLFSSL_SERVER_END) {
- if (ssl->options.handShakeState != HANDSHAKE_DONE &&
- ctxSz != 0) {
- ERROR_OUT(INVALID_CERT_CTX_E, exit_ppc);
- }
- else if (ssl->options.handShakeState == HANDSHAKE_DONE) {
- #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
- CertReqCtx* curr = ssl->certReqCtx;
- CertReqCtx* prev = NULL;
- while (curr != NULL) {
- if ((ctxSz == curr->len) &&
- XMEMCMP(&curr->ctx, input + args->idx, ctxSz)
- == 0) {
- if (prev != NULL)
- prev->next = curr->next;
- else
- ssl->certReqCtx = curr->next;
- XFREE(curr, ssl->heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- break;
- }
- prev = curr;
- curr = curr->next;
- }
- if (curr == NULL)
- #endif
- ERROR_OUT(INVALID_CERT_CTX_E, exit_ppc);
- }
- }
- #endif
- args->idx += ctxSz;
- #ifdef OPENSSL_EXTRA
- /* allocate buffer for cert extensions */
- args->exts = (buffer*)XMALLOC(sizeof(buffer) *
- (ssl->verifyDepth + 1), ssl->heap, DYNAMIC_TYPE_CERT_EXT);
- if (args->exts == NULL) {
- ERROR_OUT(MEMORY_E, exit_ppc);
- }
- #else
- /* allocate buffer for cert extensions */
- args->exts = (buffer*)XMALLOC(sizeof(buffer) * MAX_CHAIN_DEPTH,
- ssl->heap, DYNAMIC_TYPE_CERT_EXT);
- if (args->exts == NULL) {
- ERROR_OUT(MEMORY_E, exit_ppc);
- }
- #endif
- }
- #endif
- /* allocate buffer for certs */
- #ifdef OPENSSL_EXTRA
- args->certs = (buffer*)XMALLOC(sizeof(buffer) *
- (ssl->verifyDepth + 1), ssl->heap, DYNAMIC_TYPE_DER);
- if (args->certs == NULL) {
- ERROR_OUT(MEMORY_E, exit_ppc);
- }
- XMEMSET(args->certs, 0, sizeof(buffer) * (ssl->verifyDepth + 1));
- #else
- args->certs = (buffer*)XMALLOC(sizeof(buffer) * MAX_CHAIN_DEPTH,
- ssl->heap, DYNAMIC_TYPE_DER);
- if (args->certs == NULL) {
- ERROR_OUT(MEMORY_E, exit_ppc);
- }
- XMEMSET(args->certs, 0, sizeof(buffer) * MAX_CHAIN_DEPTH);
- #endif /* OPENSSL_EXTRA */
- /* Certificate List */
- if ((args->idx - args->begin) + OPAQUE24_LEN > totalSz) {
- ERROR_OUT(BUFFER_ERROR, exit_ppc);
- }
- c24to32(input + args->idx, &listSz);
- args->idx += OPAQUE24_LEN;
- if (listSz > MAX_CERTIFICATE_SZ) {
- ERROR_OUT(BUFFER_ERROR, exit_ppc);
- }
- if ((args->idx - args->begin) + listSz != totalSz) {
- ERROR_OUT(BUFFER_ERROR, exit_ppc);
- }
- WOLFSSL_MSG("Loading peer's cert chain");
- /* first put cert chain into buffer so can verify top down
- we're sent bottom up */
- while (listSz) {
- word32 certSz;
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- if (args->totalCerts > ssl->verifyDepth) {
- ssl->peerVerifyRet = X509_V_ERR_CERT_CHAIN_TOO_LONG;
- ERROR_OUT(MAX_CHAIN_ERROR, exit_ppc);
- }
- #else
- if (args->totalCerts >= ssl->verifyDepth ||
- args->totalCerts >= MAX_CHAIN_DEPTH) {
- ERROR_OUT(MAX_CHAIN_ERROR, exit_ppc);
- }
- #endif
- if ((args->idx - args->begin) + OPAQUE24_LEN > totalSz) {
- ERROR_OUT(BUFFER_ERROR, exit_ppc);
- }
- c24to32(input + args->idx, &certSz);
- args->idx += OPAQUE24_LEN;
- if ((args->idx - args->begin) + certSz > totalSz) {
- ERROR_OUT(BUFFER_ERROR, exit_ppc);
- }
- args->certs[args->totalCerts].length = certSz;
- args->certs[args->totalCerts].buffer = input + args->idx;
- #ifdef SESSION_CERTS
- AddSessionCertToChain(&ssl->session.chain,
- input + args->idx, certSz);
- #endif /* SESSION_CERTS */
- args->idx += certSz;
- listSz -= certSz + CERT_HEADER_SZ;
- #ifdef WOLFSSL_TLS13
- /* Extensions */
- if (ssl->options.tls1_3) {
- word16 extSz;
- if ((args->idx - args->begin) + OPAQUE16_LEN > totalSz) {
- ERROR_OUT(BUFFER_ERROR, exit_ppc);
- }
- ato16(input + args->idx, &extSz);
- args->idx += OPAQUE16_LEN;
- if ((args->idx - args->begin) + extSz > totalSz) {
- ERROR_OUT(BUFFER_ERROR, exit_ppc);
- }
- /* Store extension data info for later processing. */
- args->exts[args->totalCerts].length = extSz;
- args->exts[args->totalCerts].buffer = input + args->idx;
- args->idx += extSz;
- listSz -= extSz + OPAQUE16_LEN;
- ret = TLSX_Parse(ssl, args->exts[args->totalCerts].buffer,
- args->exts[args->totalCerts].length, certificate, NULL);
- if (ret < 0) {
- ERROR_OUT(ret, exit_ppc);
- }
- }
- #endif
- args->totalCerts++;
- WOLFSSL_MSG("\tPut another cert into chain");
- } /* while (listSz) */
- args->count = args->totalCerts;
- args->certIdx = 0; /* select peer cert (first one) */
- if (args->count == 0 && ssl->options.mutualAuth &&
- ssl->options.side == WOLFSSL_SERVER_END) {
- ret = NO_PEER_CERT;
- DoCertFatalAlert(ssl, ret);
- }
- args->dCertInit = 0;
- #ifndef WOLFSSL_SMALL_CERT_VERIFY
- args->dCert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
- DYNAMIC_TYPE_DCERT);
- if (args->dCert == NULL) {
- ERROR_OUT(MEMORY_E, exit_ppc);
- }
- XMEMSET(args->dCert, 0, sizeof(DecodedCert));
- #endif
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_BUILD;
- } /* case TLS_ASYNC_BEGIN */
- FALL_THROUGH;
- case TLS_ASYNC_BUILD:
- {
- if (args->count > 0) {
- /* check for trusted peer and get untrustedDepth */
- #if defined(WOLFSSL_TRUST_PEER_CERT) || defined(OPENSSL_EXTRA)
- if (args->certIdx == 0) {
- #ifdef WOLFSSL_TRUST_PEER_CERT
- TrustedPeerCert* tp;
- int matchType = WC_MATCH_NAME;
- #endif
- ret = ProcessPeerCertParse(ssl, args, CERT_TYPE, NO_VERIFY,
- &subjectHash, &alreadySigner);
- if (ret != 0)
- goto exit_ppc;
- #ifdef OPENSSL_EXTRA
- /* Determine untrusted depth */
- if (!alreadySigner && (!args->dCert ||
- !args->dCertInit || !args->dCert->selfSigned)) {
- args->untrustedDepth = 1;
- }
- #endif
- #ifdef WOLFSSL_TRUST_PEER_CERT
- #ifndef NO_SKID
- if (args->dCert->extAuthKeyIdSet)
- matchType = WC_MATCH_SKID;
- #endif
- tp = GetTrustedPeer(ssl->ctx->cm, subjectHash, matchType);
- WOLFSSL_MSG("Checking for trusted peer cert");
- if (tp && MatchTrustedPeer(tp, args->dCert)) {
- WOLFSSL_MSG("Found matching trusted peer cert");
- args->haveTrustPeer = 1;
- }
- else if (tp == NULL) {
- /* no trusted peer cert */
- WOLFSSL_MSG("No matching trusted peer cert. Checking CAs");
- }
- else {
- WOLFSSL_MSG("Trusted peer cert did not match!");
- }
- if (!args->haveTrustPeer)
- #endif
- {
- /* free cert if not trusted peer */
- FreeDecodedCert(args->dCert);
- args->dCertInit = 0;
- }
- }
- #endif /* WOLFSSL_TRUST_PEER_CERT || OPENSSL_EXTRA */
- /* check certificate up to peer's first */
- /* do not verify chain if trusted peer cert found */
- while (args->count > 1
- #ifdef WOLFSSL_TRUST_PEER_CERT
- && !args->haveTrustPeer
- #endif /* WOLFSSL_TRUST_PEER_CERT */
- ) {
- int skipAddCA = 0;
- /* select last certificate */
- args->certIdx = args->count - 1;
- ret = ProcessPeerCertParse(ssl, args, CERT_TYPE,
- !ssl->options.verifyNone ? VERIFY : NO_VERIFY,
- &subjectHash, &alreadySigner);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E)
- goto exit_ppc;
- #endif
- if (ret == 0) {
- ret = ProcessPeerCertCheckKey(ssl, args);
- }
- if (ret == 0 && args->dCert->isCA == 0) {
- WOLFSSL_MSG("Chain cert is not a CA, not adding as one");
- }
- else if (ret == 0 && ssl->options.verifyNone) {
- WOLFSSL_MSG("Chain cert not verified by option, "
- "not adding as CA");
- }
- else if (ret == 0) {
- #ifdef OPENSSL_EXTRA
- if (args->certIdx > args->untrustedDepth) {
- args->untrustedDepth = (char)args->certIdx + 1;
- }
- #endif
- if (alreadySigner) {
- WOLFSSL_MSG("Verified CA from chain and already had it");
- }
- }
- else {
- WOLFSSL_MSG("Failed to verify CA from chain");
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- ssl->peerVerifyRet = X509_V_ERR_INVALID_CA;
- #endif
- }
- #if defined(HAVE_OCSP) || defined(HAVE_CRL)
- if (ret == 0) {
- int doCrlLookup = 1;
- #ifdef HAVE_OCSP
- #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
- if (ssl->status_request_v2) {
- ret = TLSX_CSR2_InitRequests(ssl->extensions,
- args->dCert, 0, ssl->heap);
- }
- else /* skips OCSP and force CRL check */
- #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
- if (ssl->ctx->cm->ocspEnabled &&
- ssl->ctx->cm->ocspCheckAll) {
- WOLFSSL_MSG("Doing Non Leaf OCSP check");
- ret = CheckCertOCSP_ex(ssl->ctx->cm->ocsp,
- args->dCert, NULL, ssl);
- #ifdef WOLFSSL_NONBLOCK_OCSP
- if (ret == OCSP_WANT_READ) {
- args->lastErr = ret;
- goto exit_ppc;
- }
- #endif
- doCrlLookup = (ret == OCSP_CERT_UNKNOWN);
- if (ret != 0) {
- doCrlLookup = 0;
- WOLFSSL_MSG("\tOCSP Lookup not ok");
- }
- }
- #endif /* HAVE_OCSP */
- #ifdef HAVE_CRL
- if (ret == 0 && doCrlLookup &&
- ssl->ctx->cm->crlEnabled &&
- ssl->ctx->cm->crlCheckAll) {
- WOLFSSL_MSG("Doing Non Leaf CRL check");
- ret = CheckCertCRL(ssl->ctx->cm->crl, args->dCert);
- #ifdef WOLFSSL_NONBLOCK_OCSP
- if (ret == OCSP_WANT_READ) {
- args->lastErr = ret;
- goto exit_ppc;
- }
- #endif
- if (ret != 0) {
- WOLFSSL_MSG("\tCRL check not ok");
- }
- }
- #endif /* HAVE_CRL */
- (void)doCrlLookup;
- }
- #endif /* HAVE_OCSP || HAVE_CRL */
- /* Do verify callback */
- ret = DoVerifyCallback(ssl->ctx->cm, ssl, ret, args);
- #ifdef WOLFSSL_ALT_CERT_CHAINS
- /* For alternate cert chain, its okay for a CA cert to fail
- with ASN_NO_SIGNER_E here. The "alternate" certificate
- chain mode only requires that the peer certificate
- validate to a trusted CA */
- if (ret != 0 && args->dCert->isCA) {
- if (ret == ASN_NO_SIGNER_E) {
- if (!ssl->options.usingAltCertChain) {
- WOLFSSL_MSG("Trying alternate cert chain");
- ssl->options.usingAltCertChain = 1;
- }
- ret = 0; /* clear error and continue */
- }
- /* do not add to certificate manager */
- skipAddCA = 1;
- }
- #endif /* WOLFSSL_ALT_CERT_CHAINS */
- /* If valid CA then add to Certificate Manager */
- if (ret == 0 && args->dCert->isCA &&
- !ssl->options.verifyNone && !skipAddCA) {
- buffer* cert = &args->certs[args->certIdx];
- /* Is valid CA */
- #if defined(SESSION_CERTS) && defined(WOLFSSL_ALT_CERT_CHAINS)
- /* if using alternate chain, store the cert used */
- if (ssl->options.usingAltCertChain) {
- AddSessionCertToChain(&ssl->session.altChain,
- cert->buffer, cert->length);
- }
- #endif /* SESSION_CERTS && WOLFSSL_ALT_CERT_CHAINS */
- if (!alreadySigner) {
- DerBuffer* add = NULL;
- ret = AllocDer(&add, cert->length, CA_TYPE, ssl->heap);
- if (ret < 0)
- goto exit_ppc;
- XMEMCPY(add->buffer, cert->buffer, cert->length);
- /* CA already verified above in ParseCertRelative */
- WOLFSSL_MSG("Adding CA from chain");
- ret = AddCA(ssl->ctx->cm, &add, WOLFSSL_CHAIN_CA,
- NO_VERIFY);
- if (ret == WOLFSSL_SUCCESS) {
- ret = 0;
- }
- }
- }
- /* Handle error codes */
- if (ret != 0) {
- if (!ssl->options.verifyNone) {
- DoCertFatalAlert(ssl, ret);
- }
- ssl->error = ret; /* Report SSL error */
- if (args->lastErr == 0) {
- args->lastErr = ret; /* save error from last time */
- ret = 0; /* reset error */
- }
- }
- FreeDecodedCert(args->dCert);
- args->dCertInit = 0;
- args->count--;
- } /* while (count > 0 && !args->haveTrustPeer) */
- } /* if (count > 0) */
- /* Check for error */
- if (ret != 0) {
- goto exit_ppc;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_DO;
- } /* case TLS_ASYNC_BUILD */
- FALL_THROUGH;
- case TLS_ASYNC_DO:
- {
- /* peer's, may not have one if blank client cert sent by TLSv1.2 */
- if (args->count > 0) {
- WOLFSSL_MSG("Verifying Peer's cert");
- /* select peer cert (first one) */
- args->certIdx = 0;
- ret = ProcessPeerCertParse(ssl, args, CERT_TYPE,
- !ssl->options.verifyNone ? VERIFY : NO_VERIFY,
- &subjectHash, &alreadySigner);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E)
- goto exit_ppc;
- #endif
- if (ret == 0) {
- WOLFSSL_MSG("Verified Peer's cert");
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- ssl->peerVerifyRet = X509_V_OK;
- #endif
- #if defined(SESSION_CERTS) && defined(WOLFSSL_ALT_CERT_CHAINS)
- /* if using alternate chain, store the cert used */
- if (ssl->options.usingAltCertChain) {
- buffer* cert = &args->certs[args->certIdx];
- AddSessionCertToChain(&ssl->session.altChain,
- cert->buffer, cert->length);
- }
- #endif /* SESSION_CERTS && WOLFSSL_ALT_CERT_CHAINS */
- /* check if fatal error */
- if (args->verifyErr) {
- args->fatal = 1;
- if (ret == 0) {
- ret = args->lastErr;
- }
- }
- else {
- args->fatal = 0;
- }
- }
- else if (ret == ASN_PARSE_E || ret == BUFFER_E) {
- WOLFSSL_MSG("Got Peer cert ASN PARSE or BUFFER ERROR");
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- SendAlert(ssl, alert_fatal, bad_certificate);
- ssl->peerVerifyRet = X509_V_ERR_CERT_REJECTED;
- #endif
- args->fatal = 1;
- }
- else {
- WOLFSSL_MSG("Failed to verify Peer's cert");
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- ssl->peerVerifyRet = X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE;
- #endif
- if (ssl->verifyCallback) {
- WOLFSSL_MSG(
- "\tCallback override available, will continue");
- /* check if fatal error */
- args->fatal = (args->verifyErr) ? 1 : 0;
- }
- else {
- WOLFSSL_MSG("\tNo callback override available, fatal");
- args->fatal = 1;
- #ifdef OPENSSL_EXTRA
- SendAlert(ssl, alert_fatal, bad_certificate);
- #endif
- }
- }
- #ifdef HAVE_SECURE_RENEGOTIATION
- if (args->fatal == 0 && !IsAtLeastTLSv1_3(ssl->version)
- && ssl->secure_renegotiation
- && ssl->secure_renegotiation->enabled) {
- if (IsEncryptionOn(ssl, 0)) {
- /* compare against previous time */
- if (ssl->secure_renegotiation->subject_hash_set) {
- if (XMEMCMP(args->dCert->subjectHash,
- ssl->secure_renegotiation->subject_hash,
- KEYID_SIZE) != 0) {
- WOLFSSL_MSG(
- "Peer sent different cert during scr, fatal");
- args->fatal = 1;
- ret = SCR_DIFFERENT_CERT_E;
- }
- }
- }
- /* cache peer's hash */
- if (args->fatal == 0) {
- XMEMCPY(ssl->secure_renegotiation->subject_hash,
- args->dCert->subjectHash, KEYID_SIZE);
- ssl->secure_renegotiation->subject_hash_set = 1;
- }
- }
- #endif /* HAVE_SECURE_RENEGOTIATION */
- } /* if (count > 0) */
- /* Check for error */
- if (args->fatal && ret != 0) {
- goto exit_ppc;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_VERIFY;
- } /* case TLS_ASYNC_DO */
- FALL_THROUGH;
- case TLS_ASYNC_VERIFY:
- {
- if (args->count > 0) {
- #if defined(HAVE_OCSP) || defined(HAVE_CRL)
- if (args->fatal == 0) {
- int doLookup = 1;
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
- if (ssl->status_request) {
- args->fatal = TLSX_CSR_InitRequest(ssl->extensions,
- args->dCert, ssl->heap);
- doLookup = 0;
- #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
- if (ssl->options.tls1_3) {
- TLSX* ext = TLSX_Find(ssl->extensions,
- TLSX_STATUS_REQUEST);
- if (ext != NULL) {
- word32 idx = 0;
- CertificateStatusRequest* csr =
- (CertificateStatusRequest*)ext->data;
- ret = ProcessCSR(ssl, csr->response.buffer,
- &idx, csr->response.length);
- if (ret < 0)
- goto exit_ppc;
- }
- }
- #endif
- }
- #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
- #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
- if (ssl->status_request_v2) {
- args->fatal = TLSX_CSR2_InitRequests(ssl->extensions,
- args->dCert, 1, ssl->heap);
- doLookup = 0;
- }
- #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
- }
- #ifdef HAVE_OCSP
- if (doLookup && ssl->ctx->cm->ocspEnabled) {
- WOLFSSL_MSG("Doing Leaf OCSP check");
- ret = CheckCertOCSP_ex(ssl->ctx->cm->ocsp,
- args->dCert, NULL, ssl);
- #ifdef WOLFSSL_NONBLOCK_OCSP
- if (ret == OCSP_WANT_READ) {
- goto exit_ppc;
- }
- #endif
- doLookup = (ret == OCSP_CERT_UNKNOWN);
- if (ret != 0) {
- WOLFSSL_MSG("\tOCSP Lookup not ok");
- args->fatal = 0;
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- ssl->peerVerifyRet = X509_V_ERR_CERT_REJECTED;
- #endif
- }
- }
- #endif /* HAVE_OCSP */
- #ifdef HAVE_CRL
- if (doLookup && ssl->ctx->cm->crlEnabled) {
- WOLFSSL_MSG("Doing Leaf CRL check");
- ret = CheckCertCRL(ssl->ctx->cm->crl, args->dCert);
- #ifdef WOLFSSL_NONBLOCK_OCSP
- if (ret == OCSP_WANT_READ) {
- goto exit_ppc;
- }
- #endif
- if (ret != 0) {
- WOLFSSL_MSG("\tCRL check not ok");
- args->fatal = 0;
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- ssl->peerVerifyRet = X509_V_ERR_CERT_REJECTED;
- #endif
- }
- }
- #endif /* HAVE_CRL */
- (void)doLookup;
- }
- #endif /* HAVE_OCSP || HAVE_CRL */
- #ifdef KEEP_PEER_CERT
- if (args->fatal == 0) {
- int copyRet = 0;
- #ifdef HAVE_SECURE_RENEGOTIATION
- if (ssl->secure_renegotiation &&
- ssl->secure_renegotiation->enabled) {
- /* free old peer cert */
- FreeX509(&ssl->peerCert);
- }
- #endif
- /* set X509 format for peer cert */
- copyRet = CopyDecodedToX509(&ssl->peerCert, args->dCert);
- if (copyRet == MEMORY_E) {
- args->fatal = 1;
- }
- }
- #endif /* KEEP_PEER_CERT */
- #ifndef IGNORE_KEY_EXTENSIONS
- #if defined(OPENSSL_EXTRA)
- /* when compatibility layer is turned on and no verify is
- * set then ignore the certificate key extension */
- if (args->dCert->extKeyUsageSet &&
- args->dCert->extKeyUsageCrit == 0 &&
- ssl->options.verifyNone) {
- WOLFSSL_MSG("Not verifying certificate key usage");
- }
- else
- #endif
- if (args->dCert->extKeyUsageSet) {
- if ((ssl->specs.kea == rsa_kea) &&
- (ssl->options.side == WOLFSSL_CLIENT_END) &&
- (args->dCert->extKeyUsage & KEYUSE_KEY_ENCIPHER) == 0) {
- ret = KEYUSE_ENCIPHER_E;
- }
- if ((ssl->specs.sig_algo == rsa_sa_algo ||
- (ssl->specs.sig_algo == ecc_dsa_sa_algo &&
- !ssl->specs.static_ecdh)) &&
- (args->dCert->extKeyUsage & KEYUSE_DIGITAL_SIG) == 0) {
- WOLFSSL_MSG("KeyUse Digital Sig not set");
- ret = KEYUSE_SIGNATURE_E;
- }
- }
- #if defined(OPENSSL_EXTRA)
- /* when compatibility layer is turned on and no verify is
- * set then ignore the certificate key extension */
- if (args->dCert->extExtKeyUsageSet &&
- args->dCert->extExtKeyUsageCrit == 0 &&
- ssl->options.verifyNone) {
- WOLFSSL_MSG("Not verifying certificate ext key usage");
- }
- else
- #endif
- if (args->dCert->extExtKeyUsageSet) {
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- if ((args->dCert->extExtKeyUsage &
- (EXTKEYUSE_ANY | EXTKEYUSE_SERVER_AUTH)) == 0) {
- WOLFSSL_MSG("ExtKeyUse Server Auth not set");
- ret = EXTKEYUSE_AUTH_E;
- }
- }
- else {
- if ((args->dCert->extExtKeyUsage &
- (EXTKEYUSE_ANY | EXTKEYUSE_CLIENT_AUTH)) == 0) {
- WOLFSSL_MSG("ExtKeyUse Client Auth not set");
- ret = EXTKEYUSE_AUTH_E;
- }
- }
- }
- #endif /* IGNORE_KEY_EXTENSIONS */
- if (args->fatal) {
- ssl->error = ret;
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- SendAlert(ssl, alert_fatal, bad_certificate);
- ssl->peerVerifyRet = X509_V_ERR_CERT_REJECTED;
- #endif
- goto exit_ppc;
- }
- ssl->options.havePeerCert = 1;
- if (!ssl->options.verifyNone && ssl->buffers.domainName.buffer) {
- #ifndef WOLFSSL_ALLOW_NO_CN_IN_SAN
- /* Per RFC 5280 section 4.2.1.6, "Whenever such identities
- * are to be bound into a certificate, the subject
- * alternative name extension MUST be used." */
- if (args->dCert->altNames) {
- if (CheckAltNames(args->dCert,
- (char*)ssl->buffers.domainName.buffer) == 0 ) {
- WOLFSSL_MSG("DomainName match on alt names failed");
- /* try to get peer key still */
- ret = DOMAIN_NAME_MISMATCH;
- }
- }
- else {
- if (MatchDomainName(
- args->dCert->subjectCN,
- args->dCert->subjectCNLen,
- (char*)ssl->buffers.domainName.buffer) == 0) {
- WOLFSSL_MSG("DomainName match on common name failed");
- ret = DOMAIN_NAME_MISMATCH;
- }
- }
- #else /* WOLFSSL_ALL_NO_CN_IN_SAN */
- /* Old behavior. */
- if (MatchDomainName(args->dCert->subjectCN,
- args->dCert->subjectCNLen,
- (char*)ssl->buffers.domainName.buffer) == 0) {
- WOLFSSL_MSG("DomainName match on common name failed");
- if (CheckAltNames(args->dCert,
- (char*)ssl->buffers.domainName.buffer) == 0 ) {
- WOLFSSL_MSG(
- "DomainName match on alt names failed too");
- /* try to get peer key still */
- ret = DOMAIN_NAME_MISMATCH;
- }
- }
- #endif /* WOLFSSL_ALL_NO_CN_IN_SAN */
- }
- /* decode peer key */
- switch (args->dCert->keyOID) {
- #ifndef NO_RSA
- case RSAk:
- {
- word32 keyIdx = 0;
- int keyRet = 0;
- if (ssl->peerRsaKey == NULL) {
- keyRet = AllocKey(ssl, DYNAMIC_TYPE_RSA,
- (void**)&ssl->peerRsaKey);
- } else if (ssl->peerRsaKeyPresent) {
- keyRet = ReuseKey(ssl, DYNAMIC_TYPE_RSA,
- ssl->peerRsaKey);
- ssl->peerRsaKeyPresent = 0;
- }
- if (keyRet != 0 || wc_RsaPublicKeyDecode(
- args->dCert->publicKey, &keyIdx, ssl->peerRsaKey,
- args->dCert->pubKeySize) != 0) {
- ret = PEER_KEY_ERROR;
- }
- else {
- ssl->peerRsaKeyPresent = 1;
- #ifdef WOLFSSL_RENESAS_TSIP_TLS
- /* copy encrypted tsip key index into ssl object */
- if (args->dCert->tsip_encRsaKeyIdx) {
- if (!ssl->peerTsipEncRsaKeyIndex) {
- ssl->peerTsipEncRsaKeyIndex = (byte*)XMALLOC(
- TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
- ssl->heap, DYNAMIC_TYPE_RSA);
- if (!ssl->peerTsipEncRsaKeyIndex) {
- args->lastErr = MEMORY_E;
- goto exit_ppc;
- }
- }
- XMEMCPY(ssl->peerTsipEncRsaKeyIndex,
- args->dCert->tsip_encRsaKeyIdx,
- TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY);
- }
- #endif
- #ifdef HAVE_PK_CALLBACKS
- #ifndef NO_RSA
- #ifdef HAVE_SECURE_RENEGOTIATION
- if (ssl->buffers.peerRsaKey.buffer) {
- XFREE(ssl->buffers.peerRsaKey.buffer,
- ssl->heap, DYNAMIC_TYPE_RSA);
- ssl->buffers.peerRsaKey.buffer = NULL;
- }
- #endif
- ssl->buffers.peerRsaKey.buffer =
- (byte*)XMALLOC(args->dCert->pubKeySize,
- ssl->heap, DYNAMIC_TYPE_RSA);
- if (ssl->buffers.peerRsaKey.buffer == NULL) {
- ret = MEMORY_ERROR;
- }
- else {
- XMEMCPY(ssl->buffers.peerRsaKey.buffer,
- args->dCert->publicKey,
- args->dCert->pubKeySize);
- ssl->buffers.peerRsaKey.length =
- args->dCert->pubKeySize;
- }
- #endif /* NO_RSA */
- #endif /* HAVE_PK_CALLBACKS */
- }
- /* check size of peer RSA key */
- if (ret == 0 && ssl->peerRsaKeyPresent &&
- !ssl->options.verifyNone &&
- wc_RsaEncryptSize(ssl->peerRsaKey)
- < ssl->options.minRsaKeySz) {
- ret = RSA_KEY_SIZE_E;
- WOLFSSL_MSG("Peer RSA key is too small");
- }
- break;
- }
- #endif /* NO_RSA */
- #ifdef HAVE_NTRU
- case NTRUk:
- {
- if (args->dCert->pubKeySize > sizeof(ssl->peerNtruKey)) {
- ret = PEER_KEY_ERROR;
- }
- else {
- XMEMCPY(ssl->peerNtruKey, args->dCert->publicKey,
- args->dCert->pubKeySize);
- ssl->peerNtruKeyLen =
- (word16)args->dCert->pubKeySize;
- ssl->peerNtruKeyPresent = 1;
- }
- break;
- }
- #endif /* HAVE_NTRU */
- #ifdef HAVE_ECC
- case ECDSAk:
- {
- int keyRet = 0;
- word32 idx = 0;
- if (ssl->peerEccDsaKey == NULL) {
- /* alloc/init on demand */
- keyRet = AllocKey(ssl, DYNAMIC_TYPE_ECC,
- (void**)&ssl->peerEccDsaKey);
- } else if (ssl->peerEccDsaKeyPresent) {
- keyRet = ReuseKey(ssl, DYNAMIC_TYPE_ECC,
- ssl->peerEccDsaKey);
- ssl->peerEccDsaKeyPresent = 0;
- }
- if (keyRet != 0 ||
- wc_EccPublicKeyDecode(args->dCert->publicKey, &idx,
- ssl->peerEccDsaKey,
- args->dCert->pubKeySize) != 0) {
- ret = PEER_KEY_ERROR;
- }
- else {
- ssl->peerEccDsaKeyPresent = 1;
- #ifdef HAVE_PK_CALLBACKS
- ssl->buffers.peerEccDsaKey.buffer =
- (byte*)XMALLOC(args->dCert->pubKeySize,
- ssl->heap, DYNAMIC_TYPE_ECC);
- if (ssl->buffers.peerEccDsaKey.buffer == NULL) {
- ERROR_OUT(MEMORY_ERROR, exit_ppc);
- }
- else {
- XMEMCPY(ssl->buffers.peerEccDsaKey.buffer,
- args->dCert->publicKey,
- args->dCert->pubKeySize);
- ssl->buffers.peerEccDsaKey.length =
- args->dCert->pubKeySize;
- }
- #endif /* HAVE_PK_CALLBACKS */
- }
- /* check size of peer ECC key */
- if (ret == 0 && ssl->peerEccDsaKeyPresent &&
- !ssl->options.verifyNone &&
- wc_ecc_size(ssl->peerEccDsaKey)
- < ssl->options.minEccKeySz) {
- ret = ECC_KEY_SIZE_E;
- WOLFSSL_MSG("Peer ECC key is too small");
- }
- break;
- }
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- case ED25519k:
- {
- int keyRet = 0;
- if (ssl->peerEd25519Key == NULL) {
- /* alloc/init on demand */
- keyRet = AllocKey(ssl, DYNAMIC_TYPE_ED25519,
- (void**)&ssl->peerEd25519Key);
- } else if (ssl->peerEd25519KeyPresent) {
- keyRet = ReuseKey(ssl, DYNAMIC_TYPE_ED25519,
- ssl->peerEd25519Key);
- ssl->peerEd25519KeyPresent = 0;
- }
- if (keyRet != 0 ||
- wc_ed25519_import_public(args->dCert->publicKey,
- args->dCert->pubKeySize,
- ssl->peerEd25519Key)
- != 0) {
- ret = PEER_KEY_ERROR;
- }
- else {
- ssl->peerEd25519KeyPresent = 1;
- #ifdef HAVE_PK_CALLBACKS
- ssl->buffers.peerEd25519Key.buffer =
- (byte*)XMALLOC(args->dCert->pubKeySize,
- ssl->heap, DYNAMIC_TYPE_ED25519);
- if (ssl->buffers.peerEd25519Key.buffer == NULL) {
- ERROR_OUT(MEMORY_ERROR, exit_ppc);
- }
- else {
- XMEMCPY(ssl->buffers.peerEd25519Key.buffer,
- args->dCert->publicKey,
- args->dCert->pubKeySize);
- ssl->buffers.peerEd25519Key.length =
- args->dCert->pubKeySize;
- }
- #endif /*HAVE_PK_CALLBACKS */
- }
- /* check size of peer ECC key */
- if (ret == 0 && ssl->peerEd25519KeyPresent &&
- !ssl->options.verifyNone &&
- ED25519_KEY_SIZE < ssl->options.minEccKeySz) {
- ret = ECC_KEY_SIZE_E;
- WOLFSSL_MSG("Peer ECC key is too small");
- }
- break;
- }
- #endif /* HAVE_ED25519 */
- #ifdef HAVE_ED448
- case ED448k:
- {
- int keyRet = 0;
- if (ssl->peerEd448Key == NULL) {
- /* alloc/init on demand */
- keyRet = AllocKey(ssl, DYNAMIC_TYPE_ED448,
- (void**)&ssl->peerEd448Key);
- } else if (ssl->peerEd448KeyPresent) {
- keyRet = ReuseKey(ssl, DYNAMIC_TYPE_ED448,
- ssl->peerEd448Key);
- ssl->peerEd448KeyPresent = 0;
- }
- if (keyRet != 0 ||
- wc_ed448_import_public(args->dCert->publicKey,
- args->dCert->pubKeySize,
- ssl->peerEd448Key) != 0) {
- ret = PEER_KEY_ERROR;
- }
- else {
- ssl->peerEd448KeyPresent = 1;
- #ifdef HAVE_PK_CALLBACKS
- ssl->buffers.peerEd448Key.buffer =
- (byte*)XMALLOC(args->dCert->pubKeySize,
- ssl->heap, DYNAMIC_TYPE_ED448);
- if (ssl->buffers.peerEd448Key.buffer == NULL) {
- ERROR_OUT(MEMORY_ERROR, exit_ppc);
- }
- else {
- XMEMCPY(ssl->buffers.peerEd448Key.buffer,
- args->dCert->publicKey,
- args->dCert->pubKeySize);
- ssl->buffers.peerEd448Key.length =
- args->dCert->pubKeySize;
- }
- #endif /*HAVE_PK_CALLBACKS */
- }
- /* check size of peer ECC key */
- if (ret == 0 && ssl->peerEd448KeyPresent &&
- !ssl->options.verifyNone &&
- ED448_KEY_SIZE < ssl->options.minEccKeySz) {
- ret = ECC_KEY_SIZE_E;
- WOLFSSL_MSG("Peer ECC key is too small");
- }
- break;
- }
- #endif /* HAVE_ED448 */
- default:
- break;
- }
- /* args->dCert free'd in function cleanup after callback */
- } /* if (count > 0) */
- /* Check for error */
- if (args->fatal && ret != 0) {
- goto exit_ppc;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_FINALIZE;
- } /* case TLS_ASYNC_VERIFY */
- FALL_THROUGH;
- case TLS_ASYNC_FINALIZE:
- {
- /* load last error */
- if (args->lastErr != 0 && ret == 0) {
- ret = args->lastErr;
- }
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- if (args->untrustedDepth > ssl->options.verifyDepth) {
- ssl->peerVerifyRet = X509_V_ERR_CERT_CHAIN_TOO_LONG;
- ret = MAX_CHAIN_ERROR;
- }
- #endif
- /* Do verify callback */
- ret = DoVerifyCallback(ssl->ctx->cm, ssl, ret, args);
- if (ssl->options.verifyNone &&
- (ret == CRL_MISSING || ret == CRL_CERT_REVOKED)) {
- WOLFSSL_MSG("Ignoring CRL problem based on verify setting");
- ret = ssl->error = 0;
- }
- if (ret != 0) {
- if (!ssl->options.verifyNone) {
- DoCertFatalAlert(ssl, ret);
- }
- ssl->error = ret; /* Report SSL error */
- }
- if (ret == 0 && ssl->options.side == WOLFSSL_CLIENT_END) {
- ssl->options.serverState = SERVER_CERT_COMPLETE;
- }
- if (IsEncryptionOn(ssl, 0)) {
- args->idx += ssl->keys.padSz;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead)
- args->idx += MacSize(ssl);
- #endif
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_END;
- } /* case TLS_ASYNC_FINALIZE */
- FALL_THROUGH;
- case TLS_ASYNC_END:
- {
- /* Set final index */
- *inOutIdx = args->idx;
- break;
- }
- default:
- ret = INPUT_CASE_ERROR;
- break;
- } /* switch(ssl->options.asyncState) */
- exit_ppc:
- WOLFSSL_LEAVE("ProcessPeerCerts", ret);
- #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
- if (ret == WC_PENDING_E || ret == OCSP_WANT_READ) {
- /* Mark message as not received so it can process again */
- ssl->msgsReceived.got_certificate = 0;
- return ret;
- }
- #endif /* WOLFSSL_ASYNC_CRYPT || WOLFSSL_NONBLOCK_OCSP */
- FreeProcPeerCertArgs(ssl, args);
- #if defined(WOLFSSL_ASYNC_CRYPT)
- #elif defined(WOLFSSL_NONBLOCK_OCSP)
- XFREE(args, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
- ssl->nonblockarg = NULL;
- #elif defined(WOLFSSL_SMALL_STACK)
- XFREE(args, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- FreeKeyExchange(ssl);
- return ret;
- }
- #endif
- #ifndef WOLFSSL_NO_TLS12
- #if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
- /* handle processing of certificate (11) */
- static int DoCertificate(WOLFSSL* ssl, byte* input, word32* inOutIdx,
- word32 size)
- {
- int ret;
- WOLFSSL_START(WC_FUNC_CERTIFICATE_DO);
- WOLFSSL_ENTER("DoCertificate");
- #ifdef SESSION_CERTS
- /* Reset the session cert chain count in case the session resume failed. */
- ssl->session.chain.count = 0;
- #ifdef WOLFSSL_ALT_CERT_CHAINS
- ssl->session.altChain.count = 0;
- #endif
- #endif /* SESSION_CERTS */
- ret = ProcessPeerCerts(ssl, input, inOutIdx, size);
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (ret == BUFFER_ERROR || ret == ASN_PARSE_E)
- SendAlert(ssl, alert_fatal, decode_error);
- #endif
- #ifdef OPENSSL_EXTRA
- ssl->options.serverState = SERVER_CERT_COMPLETE;
- #endif
- WOLFSSL_LEAVE("DoCertificate", ret);
- WOLFSSL_END(WC_FUNC_CERTIFICATE_DO);
- return ret;
- }
- /* handle processing of certificate_status (22) */
- static int DoCertificateStatus(WOLFSSL* ssl, byte* input, word32* inOutIdx,
- word32 size)
- {
- int ret = 0;
- byte status_type;
- word32 status_length;
- WOLFSSL_START(WC_FUNC_CERTIFICATE_STATUS_DO);
- WOLFSSL_ENTER("DoCertificateStatus");
- if (size < ENUM_LEN + OPAQUE24_LEN)
- return BUFFER_ERROR;
- status_type = input[(*inOutIdx)++];
- c24to32(input + *inOutIdx, &status_length);
- *inOutIdx += OPAQUE24_LEN;
- if (size != ENUM_LEN + OPAQUE24_LEN + status_length)
- return BUFFER_ERROR;
- switch (status_type) {
- #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
- || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
- /* WOLFSSL_CSR_OCSP overlaps with WOLFSSL_CSR2_OCSP */
- case WOLFSSL_CSR2_OCSP:
- ret = ProcessCSR(ssl, input, inOutIdx, status_length);
- break;
- #endif
- #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
- case WOLFSSL_CSR2_OCSP_MULTI: {
- OcspRequest* request;
- word32 list_length = status_length;
- byte idx = 0;
- #ifdef WOLFSSL_SMALL_STACK
- CertStatus* status;
- OcspResponse* response;
- #else
- CertStatus status[1];
- OcspResponse response[1];
- #endif
- do {
- if (ssl->status_request_v2) {
- ssl->status_request_v2 = 0;
- break;
- }
- return BUFFER_ERROR;
- } while(0);
- #ifdef WOLFSSL_SMALL_STACK
- status = (CertStatus*)XMALLOC(sizeof(CertStatus), ssl->heap,
- DYNAMIC_TYPE_OCSP_STATUS);
- response = (OcspResponse*)XMALLOC(sizeof(OcspResponse), ssl->heap,
- DYNAMIC_TYPE_OCSP_REQUEST);
- if (status == NULL || response == NULL) {
- if (status)
- XFREE(status, ssl->heap, DYNAMIC_TYPE_OCSP_STATUS);
- if (response)
- XFREE(response, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
- return MEMORY_ERROR;
- }
- #endif
- while (list_length && ret == 0) {
- if (OPAQUE24_LEN > list_length) {
- ret = BUFFER_ERROR;
- break;
- }
- c24to32(input + *inOutIdx, &status_length);
- *inOutIdx += OPAQUE24_LEN;
- list_length -= OPAQUE24_LEN;
- if (status_length > list_length) {
- ret = BUFFER_ERROR;
- break;
- }
- if (status_length) {
- InitOcspResponse(response, status, input +*inOutIdx,
- status_length);
- if ((OcspResponseDecode(response, ssl->ctx->cm, ssl->heap,
- 0) != 0)
- || (response->responseStatus != OCSP_SUCCESSFUL)
- || (response->status->status != CERT_GOOD))
- ret = BAD_CERTIFICATE_STATUS_ERROR;
- while (ret == 0) {
- request = (OcspRequest*)TLSX_CSR2_GetRequest(
- ssl->extensions, status_type, idx++);
- if (request == NULL)
- ret = BAD_CERTIFICATE_STATUS_ERROR;
- else if (CompareOcspReqResp(request, response) == 0)
- break;
- else if (idx == 1) /* server cert must be OK */
- ret = BAD_CERTIFICATE_STATUS_ERROR;
- }
- *inOutIdx += status_length;
- list_length -= status_length;
- }
- }
- #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
- ssl->status_request_v2 = 0;
- #endif
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(status, NULL, DYNAMIC_TYPE_OCSP_STATUS);
- XFREE(response, NULL, DYNAMIC_TYPE_OCSP_REQUEST);
- #endif
- }
- break;
- #endif
- default:
- ret = BUFFER_ERROR;
- }
- if (ret != 0)
- SendAlert(ssl, alert_fatal, bad_certificate_status_response);
- if (IsEncryptionOn(ssl, 0)) {
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead) {
- word32 digestSz = MacSize(ssl);
- if (*inOutIdx + ssl->keys.padSz + digestSz > size)
- return BUFFER_E;
- *inOutIdx += ssl->keys.padSz + digestSz;
- }
- else
- #endif
- {
- if (*inOutIdx + ssl->keys.padSz > size)
- return BUFFER_E;
- *inOutIdx += ssl->keys.padSz;
- }
- }
- WOLFSSL_LEAVE("DoCertificateStatus", ret);
- WOLFSSL_END(WC_FUNC_CERTIFICATE_STATUS_DO);
- return ret;
- }
- #endif
- #endif /* !WOLFSSL_NO_TLS12 */
- #endif /* !NO_CERTS */
- #ifndef WOLFSSL_NO_TLS12
- static int DoHelloRequest(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
- word32 size, word32 totalSz)
- {
- (void)input;
- WOLFSSL_START(WC_FUNC_HELLO_REQUEST_DO);
- WOLFSSL_ENTER("DoHelloRequest");
- if (size) /* must be 0 */
- return BUFFER_ERROR;
- if (IsEncryptionOn(ssl, 0)) {
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead) {
- word32 digestSz = MacSize(ssl);
- if (*inOutIdx + ssl->keys.padSz + digestSz > totalSz)
- return BUFFER_E;
- *inOutIdx += ssl->keys.padSz + digestSz;
- }
- else
- #endif
- {
- /* access beyond input + size should be checked against totalSz */
- if (*inOutIdx + ssl->keys.padSz > totalSz)
- return BUFFER_E;
- *inOutIdx += ssl->keys.padSz;
- }
- }
- if (ssl->options.side == WOLFSSL_SERVER_END) {
- SendAlert(ssl, alert_fatal, unexpected_message); /* try */
- return FATAL_ERROR;
- }
- #ifdef HAVE_SECURE_RENEGOTIATION
- else if (ssl->secure_renegotiation && ssl->secure_renegotiation->enabled) {
- ssl->secure_renegotiation->startScr = 1;
- WOLFSSL_LEAVE("DoHelloRequest", 0);
- WOLFSSL_END(WC_FUNC_HELLO_REQUEST_DO);
- return 0;
- }
- #endif
- else {
- return SendAlert(ssl, alert_warning, no_renegotiation);
- }
- }
- int DoFinished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, word32 size,
- word32 totalSz, int sniff)
- {
- word32 finishedSz = (ssl->options.tls ? TLS_FINISHED_SZ : FINISHED_SZ);
- WOLFSSL_START(WC_FUNC_FINISHED_DO);
- WOLFSSL_ENTER("DoFinished");
- if (finishedSz != size)
- return BUFFER_ERROR;
- /* check against totalSz */
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead) {
- if (*inOutIdx + size + ssl->keys.padSz + MacSize(ssl) > totalSz)
- return BUFFER_E;
- }
- else
- #endif
- {
- if (*inOutIdx + size + ssl->keys.padSz > totalSz)
- return BUFFER_E;
- }
- #ifdef WOLFSSL_CALLBACKS
- if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
- if (ssl->toInfoOn) AddLateName("Finished", &ssl->timeoutInfo);
- #endif
- if (sniff == NO_SNIFF) {
- if (XMEMCMP(input + *inOutIdx, &ssl->hsHashes->verifyHashes,size) != 0){
- WOLFSSL_MSG("Verify finished error on hashes");
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, decrypt_error);
- #endif
- return VERIFY_FINISHED_ERROR;
- }
- }
- #ifdef HAVE_SECURE_RENEGOTIATION
- if (ssl->secure_renegotiation) {
- /* save peer's state */
- if (ssl->options.side == WOLFSSL_CLIENT_END)
- XMEMCPY(ssl->secure_renegotiation->server_verify_data,
- input + *inOutIdx, TLS_FINISHED_SZ);
- else
- XMEMCPY(ssl->secure_renegotiation->client_verify_data,
- input + *inOutIdx, TLS_FINISHED_SZ);
- ssl->secure_renegotiation->verifySet = 1;
- }
- #endif
- /* force input exhaustion at ProcessReply consuming padSz */
- *inOutIdx += size + ssl->keys.padSz;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead)
- *inOutIdx += MacSize(ssl);
- #endif
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- ssl->options.serverState = SERVER_FINISHED_COMPLETE;
- #ifdef OPENSSL_EXTRA
- ssl->cbmode = SSL_CB_MODE_WRITE;
- ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
- #endif
- if (!ssl->options.resuming) {
- #ifdef OPENSSL_EXTRA
- if (ssl->CBIS != NULL) {
- ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, SSL_SUCCESS);
- }
- #endif
- ssl->options.handShakeState = HANDSHAKE_DONE;
- ssl->options.handShakeDone = 1;
- }
- }
- else {
- ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
- #ifdef OPENSSL_EXTRA
- ssl->cbmode = SSL_CB_MODE_READ;
- ssl->options.serverState = SERVER_FINISHED_COMPLETE;
- #endif
- if (ssl->options.resuming) {
- #ifdef OPENSSL_EXTRA
- if (ssl->CBIS != NULL) {
- ssl->CBIS(ssl, SSL_CB_ACCEPT_LOOP, SSL_SUCCESS);
- }
- #endif
- ssl->options.handShakeState = HANDSHAKE_DONE;
- ssl->options.handShakeDone = 1;
- }
- }
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- DtlsMsgPoolReset(ssl);
- }
- #endif
- WOLFSSL_LEAVE("DoFinished", 0);
- WOLFSSL_END(WC_FUNC_FINISHED_DO);
- return 0;
- }
- /* Make sure no duplicates, no fast forward, or other problems; 0 on success */
- static int SanityCheckMsgReceived(WOLFSSL* ssl, byte type)
- {
- /* verify not a duplicate, mark received, check state */
- switch (type) {
- #ifndef NO_WOLFSSL_CLIENT
- case hello_request:
- if (ssl->msgsReceived.got_hello_request) {
- WOLFSSL_MSG("Duplicate HelloRequest received");
- return DUPLICATE_MSG_E;
- }
- ssl->msgsReceived.got_hello_request = 1;
- break;
- #endif
- #ifndef NO_WOLFSSL_SERVER
- case client_hello:
- if (ssl->msgsReceived.got_client_hello) {
- WOLFSSL_MSG("Duplicate ClientHello received");
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, unexpected_message);
- #endif
- return DUPLICATE_MSG_E;
- }
- ssl->msgsReceived.got_client_hello = 1;
- break;
- #endif
- #ifndef NO_WOLFSSL_CLIENT
- case server_hello:
- if (ssl->msgsReceived.got_server_hello) {
- WOLFSSL_MSG("Duplicate ServerHello received");
- return DUPLICATE_MSG_E;
- }
- ssl->msgsReceived.got_server_hello = 1;
- break;
- #endif
- #ifndef NO_WOLFSSL_CLIENT
- case hello_verify_request:
- if (ssl->msgsReceived.got_hello_verify_request) {
- WOLFSSL_MSG("Duplicate HelloVerifyRequest received");
- return DUPLICATE_MSG_E;
- }
- ssl->msgsReceived.got_hello_verify_request = 1;
- break;
- #endif
- #ifndef NO_WOLFSSL_CLIENT
- case session_ticket:
- if (ssl->msgsReceived.got_session_ticket) {
- WOLFSSL_MSG("Duplicate SessionTicket received");
- return DUPLICATE_MSG_E;
- }
- ssl->msgsReceived.got_session_ticket = 1;
- break;
- #endif
- case certificate:
- if (ssl->msgsReceived.got_certificate) {
- WOLFSSL_MSG("Duplicate Certificate received");
- return DUPLICATE_MSG_E;
- }
- ssl->msgsReceived.got_certificate = 1;
- #ifndef NO_WOLFSSL_CLIENT
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- if ( ssl->msgsReceived.got_server_hello == 0) {
- WOLFSSL_MSG("No ServerHello before Cert");
- return OUT_OF_ORDER_E;
- }
- }
- #endif
- #ifndef NO_WOLFSSL_SERVER
- if (ssl->options.side == WOLFSSL_SERVER_END) {
- if ( ssl->msgsReceived.got_client_hello == 0) {
- WOLFSSL_MSG("No ClientHello before Cert");
- return OUT_OF_ORDER_E;
- }
- }
- #endif
- break;
- #ifndef NO_WOLFSSL_CLIENT
- case certificate_status:
- if (ssl->msgsReceived.got_certificate_status) {
- WOLFSSL_MSG("Duplicate CertificateSatatus received");
- return DUPLICATE_MSG_E;
- }
- ssl->msgsReceived.got_certificate_status = 1;
- if (ssl->msgsReceived.got_certificate == 0) {
- WOLFSSL_MSG("No Certificate before CertificateStatus");
- return OUT_OF_ORDER_E;
- }
- if (ssl->msgsReceived.got_server_key_exchange != 0) {
- WOLFSSL_MSG("CertificateStatus after ServerKeyExchange");
- return OUT_OF_ORDER_E;
- }
- break;
- #endif
- #ifndef NO_WOLFSSL_CLIENT
- case server_key_exchange:
- if (ssl->msgsReceived.got_server_key_exchange) {
- WOLFSSL_MSG("Duplicate ServerKeyExchange received");
- return DUPLICATE_MSG_E;
- }
- ssl->msgsReceived.got_server_key_exchange = 1;
- if (ssl->msgsReceived.got_server_hello == 0) {
- WOLFSSL_MSG("No ServerHello before ServerKeyExchange");
- return OUT_OF_ORDER_E;
- }
- if (ssl->msgsReceived.got_certificate_status == 0) {
- #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
- if (ssl->status_request) {
- int ret;
- WOLFSSL_MSG("No CertificateStatus before ServerKeyExchange");
- if ((ret = TLSX_CSR_ForceRequest(ssl)) != 0)
- return ret;
- }
- #endif
- #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
- if (ssl->status_request_v2) {
- int ret;
- WOLFSSL_MSG("No CertificateStatus before ServerKeyExchange");
- if ((ret = TLSX_CSR2_ForceRequest(ssl)) != 0)
- return ret;
- }
- #endif
- }
- break;
- #endif
- #ifndef NO_WOLFSSL_CLIENT
- case certificate_request:
- if (ssl->msgsReceived.got_certificate_request) {
- WOLFSSL_MSG("Duplicate CertificateRequest received");
- return DUPLICATE_MSG_E;
- }
- ssl->msgsReceived.got_certificate_request = 1;
- break;
- #endif
- #ifndef NO_WOLFSSL_CLIENT
- case server_hello_done:
- if (ssl->msgsReceived.got_server_hello_done) {
- WOLFSSL_MSG("Duplicate ServerHelloDone received");
- return DUPLICATE_MSG_E;
- }
- ssl->msgsReceived.got_server_hello_done = 1;
- if (ssl->msgsReceived.got_certificate == 0) {
- if (ssl->specs.kea == psk_kea ||
- ssl->specs.kea == dhe_psk_kea ||
- ssl->specs.kea == ecdhe_psk_kea ||
- ssl->options.usingAnon_cipher) {
- WOLFSSL_MSG("No Cert required");
- } else {
- WOLFSSL_MSG("No Certificate before ServerHelloDone");
- return OUT_OF_ORDER_E;
- }
- }
- if (ssl->msgsReceived.got_server_key_exchange == 0) {
- int pskNoServerHint = 0; /* not required in this case */
- #ifndef NO_PSK
- if (ssl->specs.kea == psk_kea &&
- ssl->arrays != NULL &&
- ssl->arrays->server_hint[0] == 0)
- pskNoServerHint = 1;
- #endif
- if (ssl->specs.static_ecdh == 1 ||
- ssl->specs.kea == rsa_kea ||
- ssl->specs.kea == ntru_kea ||
- pskNoServerHint) {
- WOLFSSL_MSG("No KeyExchange required");
- } else {
- WOLFSSL_MSG("No ServerKeyExchange before ServerDone");
- return OUT_OF_ORDER_E;
- }
- }
- break;
- #endif
- #ifndef NO_WOLFSSL_SERVER
- case certificate_verify:
- if (ssl->msgsReceived.got_certificate_verify) {
- WOLFSSL_MSG("Duplicate CertificateVerify received");
- return DUPLICATE_MSG_E;
- }
- ssl->msgsReceived.got_certificate_verify = 1;
- if ( ssl->msgsReceived.got_certificate == 0) {
- WOLFSSL_MSG("No Cert before CertVerify");
- return OUT_OF_ORDER_E;
- }
- break;
- #endif
- #ifndef NO_WOLFSSL_SERVER
- case client_key_exchange:
- if (ssl->msgsReceived.got_client_key_exchange) {
- WOLFSSL_MSG("Duplicate ClientKeyExchange received");
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, unexpected_message);
- #endif
- return DUPLICATE_MSG_E;
- }
- ssl->msgsReceived.got_client_key_exchange = 1;
- if (ssl->msgsReceived.got_client_hello == 0) {
- WOLFSSL_MSG("No ClientHello before ClientKeyExchange");
- return OUT_OF_ORDER_E;
- }
- break;
- #endif
- case finished:
- if (ssl->msgsReceived.got_finished) {
- WOLFSSL_MSG("Duplicate Finished received");
- return DUPLICATE_MSG_E;
- }
- ssl->msgsReceived.got_finished = 1;
- if (ssl->msgsReceived.got_change_cipher == 0) {
- WOLFSSL_MSG("Finished received before ChangeCipher");
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, unexpected_message);
- #endif
- return NO_CHANGE_CIPHER_E;
- }
- break;
- case change_cipher_hs:
- if (ssl->msgsReceived.got_change_cipher) {
- WOLFSSL_MSG("Duplicate ChangeCipher received");
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, unexpected_message);
- #endif
- return DUPLICATE_MSG_E;
- }
- /* DTLS is going to ignore the CCS message if the client key
- * exchange message wasn't received yet. */
- if (!ssl->options.dtls)
- ssl->msgsReceived.got_change_cipher = 1;
- #ifndef NO_WOLFSSL_CLIENT
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- if (!ssl->options.resuming) {
- if (ssl->msgsReceived.got_server_hello_done == 0) {
- WOLFSSL_MSG("No ServerHelloDone before ChangeCipher");
- return OUT_OF_ORDER_E;
- }
- }
- else {
- if (ssl->msgsReceived.got_server_hello == 0) {
- WOLFSSL_MSG("No ServerHello before ChangeCipher on Resume");
- return OUT_OF_ORDER_E;
- }
- }
- #ifdef HAVE_SESSION_TICKET
- if (ssl->expect_session_ticket) {
- WOLFSSL_MSG("Expected session ticket missing");
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls)
- return OUT_OF_ORDER_E;
- #endif
- return SESSION_TICKET_EXPECT_E;
- }
- #endif
- }
- #endif
- #ifndef NO_WOLFSSL_SERVER
- if (ssl->options.side == WOLFSSL_SERVER_END) {
- if (!ssl->options.resuming &&
- ssl->msgsReceived.got_client_key_exchange == 0) {
- WOLFSSL_MSG("No ClientKeyExchange before ChangeCipher");
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, unexpected_message);
- #endif
- return OUT_OF_ORDER_E;
- }
- #ifndef NO_CERTS
- if (ssl->options.verifyPeer &&
- ssl->options.havePeerCert) {
- if (!ssl->options.havePeerVerify) {
- WOLFSSL_MSG("client didn't send cert verify");
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls)
- return OUT_OF_ORDER_E;
- #endif
- return NO_PEER_VERIFY;
- }
- }
- #endif
- }
- #endif
- if (ssl->options.dtls)
- ssl->msgsReceived.got_change_cipher = 1;
- break;
- default:
- WOLFSSL_MSG("Unknown message type");
- return SANITY_MSG_E;
- }
- return 0;
- }
- static int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx,
- byte type, word32 size, word32 totalSz)
- {
- int ret = 0;
- word32 expectedIdx;
- WOLFSSL_ENTER("DoHandShakeMsgType");
- #ifdef WOLFSSL_TLS13
- if (type == hello_retry_request) {
- return DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
- totalSz);
- }
- #endif
- /* make sure can read the message */
- if (*inOutIdx + size > totalSz) {
- WOLFSSL_MSG("Incomplete Data");
- return INCOMPLETE_DATA;
- }
- expectedIdx = *inOutIdx + size +
- (ssl->keys.encryptionOn ? ssl->keys.padSz : 0);
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead && ssl->keys.encryptionOn)
- expectedIdx += MacSize(ssl);
- #endif
- #if !defined(WOLFSSL_NO_SERVER) && \
- defined(HAVE_SECURE_RENEGOTIATION) && \
- defined(HAVE_SERVER_RENEGOTIATION_INFO)
- if (ssl->options.handShakeDone && type == client_hello &&
- ssl->secure_renegotiation &&
- ssl->secure_renegotiation->enabled)
- {
- WOLFSSL_MSG("Reset handshake state");
- XMEMSET(&ssl->msgsReceived, 0, sizeof(MsgsReceived));
- ssl->options.serverState = NULL_STATE;
- ssl->options.clientState = NULL_STATE;
- ssl->options.connectState = CONNECT_BEGIN;
- ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
- ssl->options.handShakeState = NULL_STATE;
- ssl->secure_renegotiation->cache_status = SCR_CACHE_NEEDED;
- ret = InitHandshakeHashes(ssl);
- if (ret != 0)
- return ret;
- }
- #endif
- /* sanity check msg received */
- if ( (ret = SanityCheckMsgReceived(ssl, type)) != 0) {
- WOLFSSL_MSG("Sanity Check on handshake message type received failed");
- return ret;
- }
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- /* add name later, add on record and handshake header part back on */
- if (ssl->toInfoOn) {
- int add = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
- AddPacketInfo(ssl, 0, handshake, input + *inOutIdx - add,
- size + add, READ_PROTO, ssl->heap);
- #ifdef WOLFSSL_CALLBACKS
- AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
- #endif
- }
- #endif
- if (ssl->options.handShakeState == HANDSHAKE_DONE && type != hello_request){
- WOLFSSL_MSG("HandShake message after handshake complete");
- SendAlert(ssl, alert_fatal, unexpected_message);
- return OUT_OF_ORDER_E;
- }
- if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.dtls == 0 &&
- ssl->options.serverState == NULL_STATE && type != server_hello) {
- WOLFSSL_MSG("First server message not server hello");
- SendAlert(ssl, alert_fatal, unexpected_message);
- return OUT_OF_ORDER_E;
- }
- if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.dtls &&
- type == server_hello_done &&
- ssl->options.serverState < SERVER_HELLO_COMPLETE) {
- WOLFSSL_MSG("Server hello done received before server hello in DTLS");
- SendAlert(ssl, alert_fatal, unexpected_message);
- return OUT_OF_ORDER_E;
- }
- if (ssl->options.side == WOLFSSL_SERVER_END &&
- ssl->options.clientState == NULL_STATE && type != client_hello) {
- WOLFSSL_MSG("First client message not client hello");
- SendAlert(ssl, alert_fatal, unexpected_message);
- return OUT_OF_ORDER_E;
- }
- /* above checks handshake state */
- /* hello_request not hashed */
- /* Also, skip hashing the client_hello message here for DTLS. It will be
- * hashed later if the DTLS cookie is correct. */
- if (type != hello_request &&
- !(IsDtlsNotSctpMode(ssl) && type == client_hello)
- #ifdef WOLFSSL_ASYNC_CRYPT
- && ssl->error != WC_PENDING_E
- #endif
- #ifdef WOLFSSL_NONBLOCK_OCSP
- && ssl->error != OCSP_WANT_READ
- #endif
- ) {
- ret = HashInput(ssl, input + *inOutIdx, size);
- if (ret != 0) {
- WOLFSSL_MSG("Incomplete handshake hashes");
- return ret;
- }
- }
- #ifdef OPENSSL_EXTRA
- if (ssl->CBIS != NULL){
- ssl->cbmode = SSL_CB_MODE_READ;
- ssl->cbtype = type;
- ssl->CBIS(ssl, SSL_CB_ACCEPT_LOOP, SSL_SUCCESS);
- }
- #endif
- switch (type) {
- case hello_request:
- WOLFSSL_MSG("processing hello request");
- ret = DoHelloRequest(ssl, input, inOutIdx, size, totalSz);
- break;
- #ifndef NO_WOLFSSL_CLIENT
- case hello_verify_request:
- WOLFSSL_MSG("processing hello verify request");
- ret = DoHelloVerifyRequest(ssl, input,inOutIdx, size);
- break;
- case server_hello:
- WOLFSSL_MSG("processing server hello");
- ret = DoServerHello(ssl, input, inOutIdx, size);
- #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
- ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
- (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
- if (ssl->options.resuming || !IsAtLeastTLSv1_2(ssl) ||
- IsAtLeastTLSv1_3(ssl->version)) {
- #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
- if (ret != WC_PENDING_E && ret != OCSP_WANT_READ)
- #endif
- {
- ssl->options.cacheMessages = 0;
- if (ssl->hsHashes->messages != NULL) {
- XFREE(ssl->hsHashes->messages, ssl->heap,
- DYNAMIC_TYPE_HASHES);
- ssl->hsHashes->messages = NULL;
- }
- }
- }
- #endif
- break;
- #ifndef NO_CERTS
- case certificate_request:
- WOLFSSL_MSG("processing certificate request");
- ret = DoCertificateRequest(ssl, input, inOutIdx, size);
- break;
- #endif
- case server_key_exchange:
- WOLFSSL_MSG("processing server key exchange");
- ret = DoServerKeyExchange(ssl, input, inOutIdx, size);
- break;
- #ifdef HAVE_SESSION_TICKET
- case session_ticket:
- WOLFSSL_MSG("processing session ticket");
- ret = DoSessionTicket(ssl, input, inOutIdx, size);
- break;
- #endif /* HAVE_SESSION_TICKET */
- #endif
- #if !defined(NO_CERTS) && (!defined(NO_WOLFSSL_CLIENT) || \
- !defined(WOLFSSL_NO_CLIENT_AUTH))
- case certificate:
- WOLFSSL_MSG("processing certificate");
- ret = DoCertificate(ssl, input, inOutIdx, size);
- break;
- case certificate_status:
- WOLFSSL_MSG("processing certificate status");
- ret = DoCertificateStatus(ssl, input, inOutIdx, size);
- break;
- #endif
- case server_hello_done:
- WOLFSSL_MSG("processing server hello done");
- #ifdef WOLFSSL_CALLBACKS
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "ServerHelloDone");
- if (ssl->toInfoOn)
- AddLateName("ServerHelloDone", &ssl->timeoutInfo);
- #endif
- ssl->options.serverState = SERVER_HELLODONE_COMPLETE;
- if (IsEncryptionOn(ssl, 0)) {
- *inOutIdx += ssl->keys.padSz;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead)
- *inOutIdx += MacSize(ssl);
- #endif
- }
- if (ssl->options.resuming) {
- WOLFSSL_MSG("Not resuming as thought");
- ssl->options.resuming = 0;
- }
- break;
- case finished:
- WOLFSSL_MSG("processing finished");
- ret = DoFinished(ssl, input, inOutIdx, size, totalSz, NO_SNIFF);
- break;
- #ifndef NO_WOLFSSL_SERVER
- case client_hello:
- WOLFSSL_MSG("processing client hello");
- ret = DoClientHello(ssl, input, inOutIdx, size);
- #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
- ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
- (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
- if (ssl->options.resuming || !ssl->options.verifyPeer || \
- !IsAtLeastTLSv1_2(ssl) || IsAtLeastTLSv1_3(ssl->version)) {
- #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
- if (ret != WC_PENDING_E && ret != OCSP_WANT_READ)
- #endif
- {
- ssl->options.cacheMessages = 0;
- if (ssl->hsHashes->messages != NULL) {
- XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES);
- ssl->hsHashes->messages = NULL;
- }
- }
- }
- #endif
- if (IsEncryptionOn(ssl, 0)) {
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead) {
- word32 digestSz = MacSize(ssl);
- if (*inOutIdx + ssl->keys.padSz + digestSz > totalSz)
- return BUFFER_E;
- *inOutIdx += ssl->keys.padSz + digestSz;
- }
- else
- #endif
- {
- /* access beyond input + size should be checked against totalSz
- */
- if (*inOutIdx + ssl->keys.padSz > totalSz)
- return BUFFER_E;
- *inOutIdx += ssl->keys.padSz;
- }
- }
- break;
- case client_key_exchange:
- WOLFSSL_MSG("processing client key exchange");
- ret = DoClientKeyExchange(ssl, input, inOutIdx, size);
- break;
- #if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
- defined(HAVE_ED448)) && !defined(WOLFSSL_NO_CLIENT_AUTH)
- case certificate_verify:
- WOLFSSL_MSG("processing certificate verify");
- ret = DoCertificateVerify(ssl, input, inOutIdx, size);
- break;
- #endif /* (!NO_RSA || ECC || ED25519 || ED448) && !WOLFSSL_NO_CLIENT_AUTH */
- #endif /* !NO_WOLFSSL_SERVER */
- default:
- WOLFSSL_MSG("Unknown handshake message type");
- ret = UNKNOWN_HANDSHAKE_TYPE;
- break;
- }
- if (ret == 0 && expectedIdx != *inOutIdx) {
- WOLFSSL_MSG("Extra data in handshake message");
- if (!ssl->options.dtls)
- SendAlert(ssl, alert_fatal, decode_error);
- ret = DECODE_E;
- }
- if (ret == 0 && ssl->buffers.inputBuffer.dynamicFlag
- #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
- /* do not shrink input for async or non-block */
- && ssl->error != WC_PENDING_E && ssl->error != OCSP_WANT_READ
- #endif
- ) {
- ShrinkInputBuffer(ssl, NO_FORCED_FREE);
- }
- #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
- /* if async, offset index so this msg will be processed again */
- if ((ret == WC_PENDING_E || ret == OCSP_WANT_READ) && *inOutIdx > 0) {
- *inOutIdx -= HANDSHAKE_HEADER_SZ;
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- *inOutIdx -= DTLS_HANDSHAKE_EXTRA;
- }
- #endif
- }
- /* make sure async error is cleared */
- if (ret == 0 && (ssl->error == WC_PENDING_E || ssl->error == OCSP_WANT_READ)) {
- ssl->error = 0;
- }
- #endif /* WOLFSSL_ASYNC_CRYPT || WOLFSSL_NONBLOCK_OCSP */
- WOLFSSL_LEAVE("DoHandShakeMsgType()", ret);
- return ret;
- }
- static int DoHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx,
- word32 totalSz)
- {
- int ret = 0;
- word32 inputLength;
- WOLFSSL_ENTER("DoHandShakeMsg()");
- if (ssl->arrays == NULL) {
- byte type;
- word32 size;
- if (GetHandShakeHeader(ssl,input,inOutIdx,&type, &size, totalSz) != 0)
- return PARSE_ERROR;
- ssl->options.handShakeState = type;
- return DoHandShakeMsgType(ssl, input, inOutIdx, type, size, totalSz);
- }
- inputLength = ssl->buffers.inputBuffer.length - *inOutIdx;
- /* If there is a pending fragmented handshake message,
- * pending message size will be non-zero. */
- if (ssl->arrays->pendingMsgSz == 0) {
- byte type;
- word32 size;
- if (GetHandShakeHeader(ssl,input, inOutIdx, &type, &size, totalSz) != 0)
- return PARSE_ERROR;
- /* Cap the maximum size of a handshake message to something reasonable.
- * By default is the maximum size of a certificate message assuming
- * nine 2048-bit RSA certificates in the chain. */
- if (size > MAX_HANDSHAKE_SZ) {
- WOLFSSL_MSG("Handshake message too large");
- return HANDSHAKE_SIZE_ERROR;
- }
- /* size is the size of the certificate message payload */
- if (inputLength - HANDSHAKE_HEADER_SZ < size) {
- ssl->arrays->pendingMsgType = type;
- ssl->arrays->pendingMsgSz = size + HANDSHAKE_HEADER_SZ;
- ssl->arrays->pendingMsg = (byte*)XMALLOC(size + HANDSHAKE_HEADER_SZ,
- ssl->heap,
- DYNAMIC_TYPE_ARRAYS);
- if (ssl->arrays->pendingMsg == NULL)
- return MEMORY_E;
- XMEMCPY(ssl->arrays->pendingMsg,
- input + *inOutIdx - HANDSHAKE_HEADER_SZ,
- inputLength);
- ssl->arrays->pendingMsgOffset = inputLength;
- *inOutIdx += inputLength - HANDSHAKE_HEADER_SZ;
- return 0;
- }
- ret = DoHandShakeMsgType(ssl, input, inOutIdx, type, size, totalSz);
- }
- else {
- word32 pendSz =
- ssl->arrays->pendingMsgSz - ssl->arrays->pendingMsgOffset;
- /* Catch the case where there may be the remainder of a fragmented
- * handshake message and the next handshake message in the same
- * record. */
- if (inputLength > pendSz)
- inputLength = pendSz;
- XMEMCPY(ssl->arrays->pendingMsg + ssl->arrays->pendingMsgOffset,
- input + *inOutIdx, inputLength);
- ssl->arrays->pendingMsgOffset += inputLength;
- *inOutIdx += inputLength;
- if (ssl->arrays->pendingMsgOffset == ssl->arrays->pendingMsgSz)
- {
- word32 idx = HANDSHAKE_HEADER_SZ;
- ret = DoHandShakeMsgType(ssl,
- ssl->arrays->pendingMsg,
- &idx, ssl->arrays->pendingMsgType,
- ssl->arrays->pendingMsgSz - idx,
- ssl->arrays->pendingMsgSz);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- /* setup to process fragment again */
- ssl->arrays->pendingMsgOffset -= inputLength;
- *inOutIdx -= inputLength;
- }
- else
- #endif
- {
- XFREE(ssl->arrays->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
- ssl->arrays->pendingMsg = NULL;
- ssl->arrays->pendingMsgSz = 0;
- }
- }
- }
- WOLFSSL_LEAVE("DoHandShakeMsg()", ret);
- return ret;
- }
- #endif /* !WOLFSSL_NO_TLS12 */
- #ifdef WOLFSSL_DTLS
- static WC_INLINE int DtlsCheckWindow(WOLFSSL* ssl)
- {
- word32* window;
- word16 cur_hi, next_hi;
- word32 cur_lo, next_lo, diff;
- int curLT;
- WOLFSSL_DTLS_PEERSEQ* peerSeq = NULL;
- if (!ssl->options.haveMcast)
- peerSeq = ssl->keys.peerSeq;
- else {
- #ifdef WOLFSSL_MULTICAST
- WOLFSSL_DTLS_PEERSEQ* p;
- int i;
- for (i = 0, p = ssl->keys.peerSeq;
- i < WOLFSSL_DTLS_PEERSEQ_SZ;
- i++, p++) {
- if (p->peerId == ssl->keys.curPeerId) {
- peerSeq = p;
- break;
- }
- }
- #endif
- }
- if (peerSeq == NULL) {
- WOLFSSL_MSG("Could not find peer sequence");
- return 0;
- }
- if (ssl->keys.curEpoch == peerSeq->nextEpoch) {
- next_hi = peerSeq->nextSeq_hi;
- next_lo = peerSeq->nextSeq_lo;
- window = peerSeq->window;
- }
- else if (ssl->keys.curEpoch == peerSeq->nextEpoch - 1) {
- next_hi = peerSeq->prevSeq_hi;
- next_lo = peerSeq->prevSeq_lo;
- window = peerSeq->prevWindow;
- }
- else {
- return 0;
- }
- cur_hi = ssl->keys.curSeq_hi;
- cur_lo = ssl->keys.curSeq_lo;
- /* If the difference between next and cur is > 2^32, way outside window. */
- if ((cur_hi > next_hi + 1) || (next_hi > cur_hi + 1)) {
- WOLFSSL_MSG("Current record from way too far in the future.");
- return 0;
- }
- if (cur_hi == next_hi) {
- curLT = cur_lo < next_lo;
- diff = curLT ? next_lo - cur_lo : cur_lo - next_lo;
- }
- else {
- curLT = cur_hi < next_hi;
- diff = curLT ? cur_lo - next_lo : next_lo - cur_lo;
- }
- /* Check to see that the next value is greater than the number of messages
- * trackable in the window, and that the difference between the next
- * expected sequence number and the received sequence number is inside the
- * window. */
- if ((next_hi || next_lo > DTLS_SEQ_BITS) &&
- curLT && (diff > DTLS_SEQ_BITS)) {
- WOLFSSL_MSG("Current record sequence number from the past.");
- return 0;
- }
- #ifndef WOLFSSL_DTLS_ALLOW_FUTURE
- else if (!curLT && (diff > DTLS_SEQ_BITS)) {
- WOLFSSL_MSG("Rejecting message too far into the future.");
- return 0;
- }
- #endif
- else if (curLT) {
- word32 idx = diff / DTLS_WORD_BITS;
- word32 newDiff = diff % DTLS_WORD_BITS;
- /* verify idx is valid for window array */
- if (idx >= WOLFSSL_DTLS_WINDOW_WORDS) {
- WOLFSSL_MSG("Invalid DTLS windows index");
- return 0;
- }
- if (window[idx] & (1 << newDiff)) {
- WOLFSSL_MSG("Current record sequence number already received.");
- return 0;
- }
- }
- return 1;
- }
- #ifdef WOLFSSL_MULTICAST
- static WC_INLINE word32 UpdateHighwaterMark(word32 cur, word32 first,
- word32 second, word32 max)
- {
- word32 newCur = 0;
- if (cur < first)
- newCur = first;
- else if (cur < second)
- newCur = second;
- else if (cur < max)
- newCur = max;
- return newCur;
- }
- #endif /* WOLFSSL_MULTICAST */
- static WC_INLINE int DtlsUpdateWindow(WOLFSSL* ssl)
- {
- word32* window;
- word32* next_lo;
- word16* next_hi;
- int curLT;
- word32 cur_lo, diff;
- word16 cur_hi;
- WOLFSSL_DTLS_PEERSEQ* peerSeq = ssl->keys.peerSeq;
- cur_hi = ssl->keys.curSeq_hi;
- cur_lo = ssl->keys.curSeq_lo;
- #ifdef WOLFSSL_MULTICAST
- if (ssl->options.haveMcast) {
- WOLFSSL_DTLS_PEERSEQ* p;
- int i;
- peerSeq = NULL;
- for (i = 0, p = ssl->keys.peerSeq;
- i < WOLFSSL_DTLS_PEERSEQ_SZ;
- i++, p++) {
- if (p->peerId == ssl->keys.curPeerId) {
- peerSeq = p;
- break;
- }
- }
- if (peerSeq == NULL) {
- WOLFSSL_MSG("Couldn't find that peer ID to update window.");
- return 0;
- }
- if (p->highwaterMark && cur_lo >= p->highwaterMark) {
- int cbError = 0;
- if (ssl->ctx->mcastHwCb)
- cbError = ssl->ctx->mcastHwCb(p->peerId,
- ssl->ctx->mcastMaxSeq,
- cur_lo, ssl->mcastHwCbCtx);
- if (cbError) {
- WOLFSSL_MSG("Multicast highwater callback returned an error.");
- return MCAST_HIGHWATER_CB_E;
- }
- p->highwaterMark = UpdateHighwaterMark(cur_lo,
- ssl->ctx->mcastFirstSeq,
- ssl->ctx->mcastSecondSeq,
- ssl->ctx->mcastMaxSeq);
- }
- }
- #endif
- if (ssl->keys.curEpoch == peerSeq->nextEpoch) {
- next_hi = &peerSeq->nextSeq_hi;
- next_lo = &peerSeq->nextSeq_lo;
- window = peerSeq->window;
- }
- else {
- next_hi = &peerSeq->prevSeq_hi;
- next_lo = &peerSeq->prevSeq_lo;
- window = peerSeq->prevWindow;
- }
- if (cur_hi == *next_hi) {
- curLT = cur_lo < *next_lo;
- diff = curLT ? *next_lo - cur_lo : cur_lo - *next_lo;
- }
- else {
- curLT = cur_hi < *next_hi;
- diff = curLT ? cur_lo - *next_lo : *next_lo - cur_lo;
- }
- if (curLT) {
- word32 idx = diff / DTLS_WORD_BITS;
- word32 newDiff = diff % DTLS_WORD_BITS;
- if (idx < WOLFSSL_DTLS_WINDOW_WORDS)
- window[idx] |= (1 << newDiff);
- }
- else {
- if (diff >= DTLS_SEQ_BITS)
- XMEMSET(window, 0, DTLS_SEQ_SZ);
- else {
- word32 idx, newDiff, temp, i;
- word32 oldWindow[WOLFSSL_DTLS_WINDOW_WORDS];
- temp = 0;
- diff++;
- idx = diff / DTLS_WORD_BITS;
- newDiff = diff % DTLS_WORD_BITS;
- XMEMCPY(oldWindow, window, sizeof(oldWindow));
- for (i = 0; i < WOLFSSL_DTLS_WINDOW_WORDS; i++) {
- if (i < idx)
- window[i] = 0;
- else {
- temp |= (oldWindow[i-idx] << newDiff);
- window[i] = temp;
- temp = oldWindow[i-idx] >> (DTLS_WORD_BITS - newDiff - 1);
- }
- }
- }
- window[0] |= 1;
- *next_lo = cur_lo + 1;
- if (*next_lo < cur_lo)
- (*next_hi)++;
- }
- return 1;
- }
- static int DtlsMsgDrain(WOLFSSL* ssl)
- {
- DtlsMsg* item = ssl->dtls_rx_msg_list;
- int ret = 0;
- WOLFSSL_ENTER("DtlsMsgDrain()");
- /* While there is an item in the store list, and it is the expected
- * message, and it is complete, and there hasn't been an error in the
- * last message... */
- while (item != NULL &&
- ssl->keys.dtls_expected_peer_handshake_number == item->seq &&
- item->fragSz == item->sz &&
- ret == 0) {
- word32 idx = 0;
- ssl->keys.dtls_expected_peer_handshake_number++;
- ret = DoHandShakeMsgType(ssl, item->msg,
- &idx, item->type, item->sz, item->sz);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ssl->keys.dtls_expected_peer_handshake_number--;
- break;
- }
- #endif
- ssl->dtls_rx_msg_list = item->next;
- DtlsMsgDelete(item, ssl->heap);
- item = ssl->dtls_rx_msg_list;
- ssl->dtls_rx_msg_list_sz--;
- }
- WOLFSSL_LEAVE("DtlsMsgDrain()", ret);
- return ret;
- }
- static int DoDtlsHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx,
- word32 totalSz)
- {
- byte type;
- word32 size;
- word32 fragOffset, fragSz;
- int ret = 0;
- WOLFSSL_ENTER("DoDtlsHandShakeMsg()");
- /* process any pending DTLS messages - this flow can happen with async */
- if (ssl->dtls_rx_msg_list != NULL) {
- ret = DtlsMsgDrain(ssl);
- if (ret != 0)
- return ret;
- /* if done processing fragment exit with success */
- if (totalSz == *inOutIdx)
- return ret;
- }
- /* parse header */
- if (GetDtlsHandShakeHeader(ssl, input, inOutIdx, &type,
- &size, &fragOffset, &fragSz, totalSz) != 0) {
- WOLFSSL_ERROR(PARSE_ERROR);
- return PARSE_ERROR;
- }
- /* Cap the maximum size of a handshake message to something reasonable.
- * By default is the maximum size of a certificate message assuming
- * nine 2048-bit RSA certificates in the chain. */
- if (size > MAX_HANDSHAKE_SZ) {
- WOLFSSL_MSG("Handshake message too large");
- return HANDSHAKE_SIZE_ERROR;
- }
- /* check that we have complete fragment */
- if (*inOutIdx + fragSz > totalSz) {
- WOLFSSL_ERROR(INCOMPLETE_DATA);
- return INCOMPLETE_DATA;
- }
- /* Check the handshake sequence number first. If out of order,
- * add the current message to the list. If the message is in order,
- * but it is a fragment, add the current message to the list, then
- * check the head of the list to see if it is complete, if so, pop
- * it out as the current message. If the message is complete and in
- * order, process it. Check the head of the list to see if it is in
- * order, if so, process it. (Repeat until list exhausted.) If the
- * head is out of order, return for more processing.
- */
- if (ssl->keys.dtls_peer_handshake_number >
- ssl->keys.dtls_expected_peer_handshake_number) {
- /* Current message is out of order. It will get stored in the list.
- * Storing also takes care of defragmentation. If the messages is a
- * client hello, we need to process this out of order; the server
- * is not supposed to keep state, but the second client hello will
- * have a different handshake sequence number than is expected, and
- * the server shouldn't be expecting any particular handshake sequence
- * number. (If the cookie changes multiple times in quick succession,
- * the client could be sending multiple new client hello messages
- * with newer and newer cookies.) */
- if (type != client_hello) {
- if (ssl->dtls_rx_msg_list_sz < DTLS_POOL_SZ) {
- DtlsMsgStore(ssl, ssl->keys.dtls_peer_handshake_number,
- input + *inOutIdx, size, type,
- fragOffset, fragSz, ssl->heap);
- }
- *inOutIdx += fragSz;
- ret = 0;
- }
- else {
- ret = DoHandShakeMsgType(ssl, input, inOutIdx, type, size, totalSz);
- if (ret == 0) {
- ssl->keys.dtls_expected_peer_handshake_number =
- ssl->keys.dtls_peer_handshake_number + 1;
- }
- }
- }
- else if (ssl->keys.dtls_peer_handshake_number <
- ssl->keys.dtls_expected_peer_handshake_number) {
- /* Already saw this message and processed it. It can be ignored. */
- *inOutIdx += fragSz;
- if(type == finished ) {
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead) {
- word32 digestSz = MacSize(ssl);
- if (*inOutIdx + ssl->keys.padSz + digestSz > totalSz)
- return BUFFER_E;
- *inOutIdx += ssl->keys.padSz + digestSz;
- }
- else
- #endif
- {
- if (*inOutIdx + ssl->keys.padSz > totalSz) {
- WOLFSSL_ERROR(BUFFER_E);
- return BUFFER_E;
- }
- *inOutIdx += ssl->keys.padSz;
- }
- }
- if (IsDtlsNotSctpMode(ssl) &&
- VerifyForDtlsMsgPoolSend(ssl, type, fragOffset)) {
- ret = DtlsMsgPoolSend(ssl, 0);
- }
- }
- else if (fragSz < size) {
- /* Since this branch is in order, but fragmented, dtls_rx_msg_list will
- * be pointing to the message with this fragment in it. Check it to see
- * if it is completed. */
- if (ssl->dtls_rx_msg_list_sz < DTLS_POOL_SZ) {
- DtlsMsgStore(ssl, ssl->keys.dtls_peer_handshake_number,
- input + *inOutIdx, size, type,
- fragOffset, fragSz, ssl->heap);
- }
- *inOutIdx += fragSz;
- ret = 0;
- if (ssl->dtls_rx_msg_list != NULL &&
- ssl->dtls_rx_msg_list->fragSz >= ssl->dtls_rx_msg_list->sz)
- ret = DtlsMsgDrain(ssl);
- }
- else {
- /* This branch is in order next, and a complete message. */
- ret = DoHandShakeMsgType(ssl, input, inOutIdx, type, size, totalSz);
- if (ret == 0) {
- if (type != client_hello || !IsDtlsNotSctpMode(ssl))
- ssl->keys.dtls_expected_peer_handshake_number++;
- if (ssl->dtls_rx_msg_list != NULL) {
- ret = DtlsMsgDrain(ssl);
- }
- }
- }
- WOLFSSL_LEAVE("DoDtlsHandShakeMsg()", ret);
- return ret;
- }
- #endif
- #ifndef WOLFSSL_NO_TLS12
- #ifdef HAVE_AEAD
- #if !defined(NO_PUBLIC_GCM_SET_IV) && \
- (((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
- (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2))) || \
- (defined(HAVE_POLY1305) && defined(HAVE_CHACHA)))
- static WC_INLINE void AeadIncrementExpIV(WOLFSSL* ssl)
- {
- int i;
- for (i = AEAD_MAX_EXP_SZ-1; i >= 0; i--) {
- if (++ssl->keys.aead_exp_IV[i]) return;
- }
- }
- #endif
- #if defined(HAVE_POLY1305) && defined(HAVE_CHACHA)
- /* Used for the older version of creating AEAD tags with Poly1305 */
- static int Poly1305TagOld(WOLFSSL* ssl, byte* additional, const byte* out,
- byte* cipher, word16 sz, byte* tag)
- {
- int ret = 0;
- int msglen = (sz - ssl->specs.aead_mac_size);
- word32 keySz = 32;
- byte padding[8]; /* used to temporarily store lengths */
- #ifdef CHACHA_AEAD_TEST
- printf("Using old version of poly1305 input.\n");
- #endif
- if (msglen < 0)
- return INPUT_CASE_ERROR;
- if ((ret = wc_Poly1305SetKey(ssl->auth.poly1305, cipher, keySz)) != 0)
- return ret;
- if ((ret = wc_Poly1305Update(ssl->auth.poly1305, additional,
- AEAD_AUTH_DATA_SZ)) != 0)
- return ret;
- /* length of additional input plus padding */
- XMEMSET(padding, 0, sizeof(padding));
- padding[0] = AEAD_AUTH_DATA_SZ;
- if ((ret = wc_Poly1305Update(ssl->auth.poly1305, padding,
- sizeof(padding))) != 0)
- return ret;
- /* add cipher info and then its length */
- XMEMSET(padding, 0, sizeof(padding));
- if ((ret = wc_Poly1305Update(ssl->auth.poly1305, out, msglen)) != 0)
- return ret;
- /* 32 bit size of cipher to 64 bit endian */
- padding[0] = msglen & 0xff;
- padding[1] = (msglen >> 8) & 0xff;
- padding[2] = ((word32)msglen >> 16) & 0xff;
- padding[3] = ((word32)msglen >> 24) & 0xff;
- if ((ret = wc_Poly1305Update(ssl->auth.poly1305, padding, sizeof(padding)))
- != 0)
- return ret;
- /* generate tag */
- if ((ret = wc_Poly1305Final(ssl->auth.poly1305, tag)) != 0)
- return ret;
- return ret;
- }
- /* When the flag oldPoly is not set this follows RFC7905. When oldPoly is set
- * the implementation follows an older draft for creating the nonce and MAC.
- * The flag oldPoly gets set automatically depending on what cipher suite was
- * negotiated in the handshake. This is able to be done because the IDs for the
- * cipher suites was updated in RFC7905 giving unique values for the older
- * draft in comparison to the more recent RFC.
- *
- * ssl WOLFSSL structure to get cipher and TLS state from
- * out output buffer to hold encrypted data
- * input data to encrypt
- * sz size of input
- *
- * Return 0 on success negative values in error case
- */
- static int ChachaAEADEncrypt(WOLFSSL* ssl, byte* out, const byte* input,
- word16 sz)
- {
- const byte* additionalSrc = input - RECORD_HEADER_SZ;
- int ret = 0;
- word32 msgLen = (sz - ssl->specs.aead_mac_size);
- byte tag[POLY1305_AUTH_SZ];
- byte add[AEAD_AUTH_DATA_SZ];
- byte nonce[CHACHA20_NONCE_SZ];
- byte poly[CHACHA20_256_KEY_SIZE]; /* generated key for poly1305 */
- #ifdef CHACHA_AEAD_TEST
- int i;
- #endif
- XMEMSET(tag, 0, sizeof(tag));
- XMEMSET(nonce, 0, sizeof(nonce));
- XMEMSET(poly, 0, sizeof(poly));
- XMEMSET(add, 0, sizeof(add));
- /* opaque SEQ number stored for AD */
- WriteSEQ(ssl, CUR_ORDER, add);
- if (ssl->options.oldPoly != 0) {
- /* get nonce. SEQ should not be incremented again here */
- XMEMCPY(nonce + CHACHA20_OLD_OFFSET, add, OPAQUE32_LEN * 2);
- }
- /* Store the type, version. Unfortunately, they are in
- * the input buffer ahead of the plaintext. */
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- additionalSrc -= DTLS_HANDSHAKE_EXTRA;
- }
- #endif
- /* add TLS message size to additional data */
- add[AEAD_AUTH_DATA_SZ - 2] = (msgLen >> 8) & 0xff;
- add[AEAD_AUTH_DATA_SZ - 1] = msgLen & 0xff;
- XMEMCPY(add + AEAD_TYPE_OFFSET, additionalSrc, 3);
- #ifdef CHACHA_AEAD_TEST
- printf("Encrypt Additional : ");
- for (i = 0; i < AEAD_AUTH_DATA_SZ; i++) {
- printf("%02x", add[i]);
- }
- printf("\n\n");
- printf("input before encryption :\n");
- for (i = 0; i < sz; i++) {
- printf("%02x", input[i]);
- if ((i + 1) % 16 == 0)
- printf("\n");
- }
- printf("\n");
- #endif
- if (ssl->options.oldPoly == 0) {
- /* nonce is formed by 4 0x00 byte padded to the left followed by 8 byte
- * record sequence number XORed with client_write_IV/server_write_IV */
- XMEMCPY(nonce, ssl->keys.aead_enc_imp_IV, CHACHA20_IMP_IV_SZ);
- nonce[4] ^= add[0];
- nonce[5] ^= add[1];
- nonce[6] ^= add[2];
- nonce[7] ^= add[3];
- nonce[8] ^= add[4];
- nonce[9] ^= add[5];
- nonce[10] ^= add[6];
- nonce[11] ^= add[7];
- }
- /* set the nonce for chacha and get poly1305 key */
- if ((ret = wc_Chacha_SetIV(ssl->encrypt.chacha, nonce, 0)) != 0) {
- ForceZero(nonce, CHACHA20_NONCE_SZ);
- return ret;
- }
- /* create Poly1305 key using chacha20 keystream */
- if ((ret = wc_Chacha_Process(ssl->encrypt.chacha, poly,
- poly, sizeof(poly))) != 0) {
- ForceZero(nonce, CHACHA20_NONCE_SZ);
- return ret;
- }
- /* set the counter after getting poly1305 key */
- if ((ret = wc_Chacha_SetIV(ssl->encrypt.chacha, nonce, 1)) != 0) {
- ForceZero(nonce, CHACHA20_NONCE_SZ);
- return ret;
- }
- ForceZero(nonce, CHACHA20_NONCE_SZ); /* done with nonce, clear it */
- /* encrypt the plain text */
- if ((ret = wc_Chacha_Process(ssl->encrypt.chacha, out,
- input, msgLen)) != 0) {
- ForceZero(poly, sizeof(poly));
- return ret;
- }
- /* get the poly1305 tag using either old padding scheme or more recent */
- if (ssl->options.oldPoly != 0) {
- if ((ret = Poly1305TagOld(ssl, add, (const byte* )out,
- poly, sz, tag)) != 0) {
- ForceZero(poly, sizeof(poly));
- return ret;
- }
- }
- else {
- if ((ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly,
- sizeof(poly))) != 0) {
- ForceZero(poly, sizeof(poly));
- return ret;
- }
- if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, add,
- sizeof(add), out, msgLen, tag, sizeof(tag))) != 0) {
- ForceZero(poly, sizeof(poly));
- return ret;
- }
- }
- ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
- /* append tag to ciphertext */
- XMEMCPY(out + msgLen, tag, sizeof(tag));
- AeadIncrementExpIV(ssl);
- #ifdef CHACHA_AEAD_TEST
- printf("mac tag :\n");
- for (i = 0; i < 16; i++) {
- printf("%02x", tag[i]);
- if ((i + 1) % 16 == 0)
- printf("\n");
- }
- printf("\n\noutput after encrypt :\n");
- for (i = 0; i < sz; i++) {
- printf("%02x", out[i]);
- if ((i + 1) % 16 == 0)
- printf("\n");
- }
- printf("\n");
- #endif
- return ret;
- }
- /* When the flag oldPoly is not set this follows RFC7905. When oldPoly is set
- * the implementation follows an older draft for creating the nonce and MAC.
- * The flag oldPoly gets set automatically depending on what cipher suite was
- * negotiated in the handshake. This is able to be done because the IDs for the
- * cipher suites was updated in RFC7905 giving unique values for the older
- * draft in comparison to the more recent RFC.
- *
- * ssl WOLFSSL structure to get cipher and TLS state from
- * plain output buffer to hold decrypted data
- * input data to decrypt
- * sz size of input
- *
- * Return 0 on success negative values in error case
- */
- static int ChachaAEADDecrypt(WOLFSSL* ssl, byte* plain, const byte* input,
- word16 sz)
- {
- byte add[AEAD_AUTH_DATA_SZ];
- byte nonce[CHACHA20_NONCE_SZ];
- byte tag[POLY1305_AUTH_SZ];
- byte poly[CHACHA20_256_KEY_SIZE]; /* generated key for mac */
- int ret = 0;
- int msgLen = (sz - ssl->specs.aead_mac_size);
- #ifdef CHACHA_AEAD_TEST
- int i;
- printf("input before decrypt :\n");
- for (i = 0; i < sz; i++) {
- printf("%02x", input[i]);
- if ((i + 1) % 16 == 0)
- printf("\n");
- }
- printf("\n");
- #endif
- XMEMSET(tag, 0, sizeof(tag));
- XMEMSET(poly, 0, sizeof(poly));
- XMEMSET(nonce, 0, sizeof(nonce));
- XMEMSET(add, 0, sizeof(add));
- /* sequence number field is 64-bits */
- WriteSEQ(ssl, PEER_ORDER, add);
- if (ssl->options.oldPoly != 0) {
- /* get nonce, SEQ should not be incremented again here */
- XMEMCPY(nonce + CHACHA20_OLD_OFFSET, add, OPAQUE32_LEN * 2);
- }
- /* get AD info */
- /* Store the type, version. */
- add[AEAD_TYPE_OFFSET] = ssl->curRL.type;
- add[AEAD_VMAJ_OFFSET] = ssl->curRL.pvMajor;
- add[AEAD_VMIN_OFFSET] = ssl->curRL.pvMinor;
- /* add TLS message size to additional data */
- add[AEAD_AUTH_DATA_SZ - 2] = (msgLen >> 8) & 0xff;
- add[AEAD_AUTH_DATA_SZ - 1] = msgLen & 0xff;
- #ifdef CHACHA_AEAD_TEST
- printf("Decrypt Additional : ");
- for (i = 0; i < AEAD_AUTH_DATA_SZ; i++) {
- printf("%02x", add[i]);
- }
- printf("\n\n");
- #endif
- if (ssl->options.oldPoly == 0) {
- /* nonce is formed by 4 0x00 byte padded to the left followed by 8 byte
- * record sequence number XORed with client_write_IV/server_write_IV */
- XMEMCPY(nonce, ssl->keys.aead_dec_imp_IV, CHACHA20_IMP_IV_SZ);
- nonce[4] ^= add[0];
- nonce[5] ^= add[1];
- nonce[6] ^= add[2];
- nonce[7] ^= add[3];
- nonce[8] ^= add[4];
- nonce[9] ^= add[5];
- nonce[10] ^= add[6];
- nonce[11] ^= add[7];
- }
- /* set nonce and get poly1305 key */
- if ((ret = wc_Chacha_SetIV(ssl->decrypt.chacha, nonce, 0)) != 0) {
- ForceZero(nonce, CHACHA20_NONCE_SZ);
- return ret;
- }
- /* use chacha20 keystream to get poly1305 key for tag */
- if ((ret = wc_Chacha_Process(ssl->decrypt.chacha, poly,
- poly, sizeof(poly))) != 0) {
- ForceZero(nonce, CHACHA20_NONCE_SZ);
- return ret;
- }
- /* set counter after getting poly1305 key */
- if ((ret = wc_Chacha_SetIV(ssl->decrypt.chacha, nonce, 1)) != 0) {
- ForceZero(nonce, CHACHA20_NONCE_SZ);
- return ret;
- }
- ForceZero(nonce, CHACHA20_NONCE_SZ); /* done with nonce, clear it */
- /* get the tag using Poly1305 */
- if (ssl->options.oldPoly != 0) {
- if ((ret = Poly1305TagOld(ssl, add, input, poly, sz, tag)) != 0) {
- ForceZero(poly, sizeof(poly));
- return ret;
- }
- }
- else {
- if ((ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly,
- sizeof(poly))) != 0) {
- ForceZero(poly, sizeof(poly));
- return ret;
- }
- if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, add,
- sizeof(add), (byte*)input, msgLen, tag, sizeof(tag))) != 0) {
- ForceZero(poly, sizeof(poly));
- return ret;
- }
- }
- ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
- /* check tag sent along with packet */
- if (ConstantCompare(input + msgLen, tag, ssl->specs.aead_mac_size) != 0) {
- WOLFSSL_MSG("MAC did not match");
- if (!ssl->options.dtls)
- SendAlert(ssl, alert_fatal, bad_record_mac);
- return VERIFY_MAC_ERROR;
- }
- /* if the tag was good decrypt message */
- if ((ret = wc_Chacha_Process(ssl->decrypt.chacha, plain,
- input, msgLen)) != 0)
- return ret;
- #ifdef CHACHA_AEAD_TEST
- printf("plain after decrypt :\n");
- for (i = 0; i < sz; i++) {
- printf("%02x", plain[i]);
- if ((i + 1) % 16 == 0)
- printf("\n");
- }
- printf("\n");
- #endif
- return ret;
- }
- #endif /* HAVE_CHACHA && HAVE_POLY1305 */
- #endif /* HAVE_AEAD */
- #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
- #if !defined(NO_GCM_ENCRYPT_EXTRA) && \
- ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
- (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
- /* The following type is used to share code between AES-GCM and AES-CCM. */
- typedef int (*AesAuthEncryptFunc)(Aes* aes, byte* out,
- const byte* in, word32 sz,
- byte* iv, word32 ivSz,
- byte* authTag, word32 authTagSz,
- const byte* authIn, word32 authInSz);
- #define AES_AUTH_ENCRYPT_FUNC AesAuthEncryptFunc
- #define AES_GCM_ENCRYPT wc_AesGcmEncrypt_ex
- #define AES_CCM_ENCRYPT wc_AesCcmEncrypt_ex
- #else
- #define AES_AUTH_ENCRYPT_FUNC wc_AesAuthEncryptFunc
- #define AES_GCM_ENCRYPT wc_AesGcmEncrypt
- #define AES_CCM_ENCRYPT wc_AesCcmEncrypt
- #endif
- #endif
- static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input,
- word16 sz, int asyncOkay)
- {
- int ret = 0;
- #ifdef WOLFSSL_ASYNC_CRYPT
- WC_ASYNC_DEV* asyncDev = NULL;
- word32 event_flags = WC_ASYNC_FLAG_CALL_AGAIN;
- #else
- (void)asyncOkay;
- #endif
- (void)out;
- (void)input;
- (void)sz;
- switch (ssl->specs.bulk_cipher_algorithm) {
- #ifdef BUILD_ARC4
- case wolfssl_rc4:
- wc_Arc4Process(ssl->encrypt.arc4, out, input, sz);
- break;
- #endif
- #ifdef BUILD_DES3
- case wolfssl_triple_des:
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- asyncDev = &ssl->encrypt.des3->asyncDev;
- ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
- if (ret != 0)
- break;
- #endif
- ret = wc_Des3_CbcEncrypt(ssl->encrypt.des3, out, input, sz);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E && asyncOkay) {
- ret = wolfSSL_AsyncPush(ssl, asyncDev);
- }
- #endif
- break;
- #endif
- #if defined(BUILD_AES) && defined(HAVE_AES_CBC)
- case wolfssl_aes:
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- asyncDev = &ssl->encrypt.aes->asyncDev;
- ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
- if (ret != 0)
- break;
- #endif
- #if defined(WOLFSSL_RENESAS_TSIP_TLS) && \
- !defined(NO_WOLFSSL_RENESAS_TSIP_TLS_SESSION)
- if (tsip_useable(ssl)) {
- ret = wc_tsip_AesCbcEncrypt(ssl->encrypt.aes, out, input, sz);
- } else
- #endif
- ret = wc_AesCbcEncrypt(ssl->encrypt.aes, out, input, sz);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E && asyncOkay) {
- ret = wolfSSL_AsyncPush(ssl, asyncDev);
- }
- #endif
- break;
- #endif
- #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
- case wolfssl_aes_gcm:
- case wolfssl_aes_ccm:/* GCM AEAD macros use same size as CCM */
- {
- AES_AUTH_ENCRYPT_FUNC aes_auth_fn;
- const byte* additionalSrc;
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- asyncDev = &ssl->encrypt.aes->asyncDev;
- ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
- if (ret != 0)
- break;
- #endif
- #if defined(BUILD_AESGCM) && defined(HAVE_AESCCM)
- aes_auth_fn = (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm)
- ? AES_GCM_ENCRYPT : AES_CCM_ENCRYPT;
- #elif defined(BUILD_AESGCM)
- aes_auth_fn = AES_GCM_ENCRYPT;
- #else
- aes_auth_fn = AES_CCM_ENCRYPT;
- #endif
- additionalSrc = input - 5;
- XMEMSET(ssl->encrypt.additional, 0, AEAD_AUTH_DATA_SZ);
- /* sequence number field is 64-bits */
- WriteSEQ(ssl, CUR_ORDER, ssl->encrypt.additional);
- /* Store the type, version. Unfortunately, they are in
- * the input buffer ahead of the plaintext. */
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- additionalSrc -= DTLS_HANDSHAKE_EXTRA;
- }
- #endif
- XMEMCPY(ssl->encrypt.additional + AEAD_TYPE_OFFSET,
- additionalSrc, 3);
- /* Store the length of the plain text minus the explicit
- * IV length minus the authentication tag size. */
- c16toa(sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
- ssl->encrypt.additional + AEAD_LEN_OFFSET);
- #if !defined(NO_PUBLIC_GCM_SET_IV) && \
- ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
- (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
- XMEMCPY(ssl->encrypt.nonce,
- ssl->keys.aead_enc_imp_IV, AESGCM_IMP_IV_SZ);
- XMEMCPY(ssl->encrypt.nonce + AESGCM_IMP_IV_SZ,
- ssl->keys.aead_exp_IV, AESGCM_EXP_IV_SZ);
- #endif
- ret = aes_auth_fn(ssl->encrypt.aes,
- out + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ,
- sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
- ssl->encrypt.nonce, AESGCM_NONCE_SZ,
- out + sz - ssl->specs.aead_mac_size,
- ssl->specs.aead_mac_size,
- ssl->encrypt.additional, AEAD_AUTH_DATA_SZ);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E && asyncOkay) {
- ret = wolfSSL_AsyncPush(ssl, asyncDev);
- }
- #endif
- #if !defined(NO_PUBLIC_GCM_SET_IV) && \
- ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
- (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
- XMEMCPY(out,
- ssl->encrypt.nonce + AESGCM_IMP_IV_SZ, AESGCM_EXP_IV_SZ);
- #endif
- }
- break;
- #endif /* BUILD_AESGCM || HAVE_AESCCM */
- #ifdef HAVE_CAMELLIA
- case wolfssl_camellia:
- ret = wc_CamelliaCbcEncrypt(ssl->encrypt.cam, out, input, sz);
- break;
- #endif
- #ifdef HAVE_HC128
- case wolfssl_hc128:
- ret = wc_Hc128_Process(ssl->encrypt.hc128, out, input, sz);
- break;
- #endif
- #ifdef BUILD_RABBIT
- case wolfssl_rabbit:
- ret = wc_RabbitProcess(ssl->encrypt.rabbit, out, input, sz);
- break;
- #endif
- #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
- case wolfssl_chacha:
- ret = ChachaAEADEncrypt(ssl, out, input, sz);
- break;
- #endif
- #ifdef HAVE_NULL_CIPHER
- case wolfssl_cipher_null:
- if (input != out) {
- XMEMMOVE(out, input, sz);
- }
- break;
- #endif
- #ifdef HAVE_IDEA
- case wolfssl_idea:
- ret = wc_IdeaCbcEncrypt(ssl->encrypt.idea, out, input, sz);
- break;
- #endif
- default:
- WOLFSSL_MSG("wolfSSL Encrypt programming error");
- ret = ENCRYPT_ERROR;
- }
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* if async is not okay, then block */
- if (ret == WC_PENDING_E && !asyncOkay) {
- ret = wc_AsyncWait(ret, asyncDev, event_flags);
- }
- #endif
- return ret;
- }
- static WC_INLINE int Encrypt(WOLFSSL* ssl, byte* out, const byte* input, word16 sz,
- int asyncOkay)
- {
- int ret = 0;
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ssl->error == WC_PENDING_E) {
- ssl->error = 0; /* clear async */
- }
- #endif
- switch (ssl->encrypt.state) {
- case CIPHER_STATE_BEGIN:
- {
- if (ssl->encrypt.setup == 0) {
- WOLFSSL_MSG("Encrypt ciphers not setup");
- return ENCRYPT_ERROR;
- }
- #ifdef HAVE_FUZZER
- if (ssl->fuzzerCb)
- ssl->fuzzerCb(ssl, input, sz, FUZZ_ENCRYPT, ssl->fuzzerCtx);
- #endif
- #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
- /* make sure AES GCM/CCM memory is allocated */
- /* free for these happens in FreeCiphers */
- if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm ||
- ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
- /* make sure auth iv and auth are allocated */
- if (ssl->encrypt.additional == NULL)
- ssl->encrypt.additional = (byte*)XMALLOC(AEAD_AUTH_DATA_SZ,
- ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
- if (ssl->encrypt.nonce == NULL)
- ssl->encrypt.nonce = (byte*)XMALLOC(AESGCM_NONCE_SZ,
- ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
- if (ssl->encrypt.additional == NULL ||
- ssl->encrypt.nonce == NULL) {
- return MEMORY_E;
- }
- }
- #endif /* BUILD_AESGCM || HAVE_AESCCM */
- /* Advance state and proceed */
- ssl->encrypt.state = CIPHER_STATE_DO;
- }
- FALL_THROUGH;
- case CIPHER_STATE_DO:
- {
- ret = EncryptDo(ssl, out, input, sz, asyncOkay);
- /* Advance state */
- ssl->encrypt.state = CIPHER_STATE_END;
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* If pending, then leave and return will resume below */
- if (ret == WC_PENDING_E) {
- return ret;
- }
- #endif
- }
- FALL_THROUGH;
- case CIPHER_STATE_END:
- {
- #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
- if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm ||
- ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm)
- {
- /* finalize authentication cipher */
- #if !defined(NO_PUBLIC_GCM_SET_IV) && \
- ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
- (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
- AeadIncrementExpIV(ssl);
- #endif
- if (ssl->encrypt.nonce)
- ForceZero(ssl->encrypt.nonce, AESGCM_NONCE_SZ);
- }
- #endif /* BUILD_AESGCM || HAVE_AESCCM */
- break;
- }
- }
- /* Reset state */
- ssl->encrypt.state = CIPHER_STATE_BEGIN;
- return ret;
- }
- static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input,
- word16 sz)
- {
- int ret = 0;
- (void)plain;
- (void)input;
- (void)sz;
- switch (ssl->specs.bulk_cipher_algorithm)
- {
- #ifdef BUILD_ARC4
- case wolfssl_rc4:
- wc_Arc4Process(ssl->decrypt.arc4, plain, input, sz);
- break;
- #endif
- #ifdef BUILD_DES3
- case wolfssl_triple_des:
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.des3->asyncDev,
- WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- break;
- #endif
- ret = wc_Des3_CbcDecrypt(ssl->decrypt.des3, plain, input, sz);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.des3->asyncDev);
- }
- #endif
- break;
- #endif
- #if defined(BUILD_AES) && defined(HAVE_AES_CBC)
- case wolfssl_aes:
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
- WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- break;
- #endif
- #if defined(WOLFSSL_RENESAS_TSIP_TLS) && \
- !defined(NO_WOLFSSL_RENESAS_TSIP_TLS_SESSION)
- if (tsip_useable(ssl)) {
- ret = wc_tsip_AesCbcDecrypt(ssl->decrypt.aes, plain, input, sz);
- } else
- #endif
- ret = wc_AesCbcDecrypt(ssl->decrypt.aes, plain, input, sz);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev);
- }
- #endif
- break;
- #endif
- #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
- case wolfssl_aes_gcm:
- case wolfssl_aes_ccm: /* GCM AEAD macros use same size as CCM */
- {
- wc_AesAuthDecryptFunc aes_auth_fn;
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* initialize event */
- ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
- WC_ASYNC_FLAG_CALL_AGAIN);
- if (ret != 0)
- break;
- #endif
- #if defined(BUILD_AESGCM) && defined(HAVE_AESCCM)
- aes_auth_fn = (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm)
- ? wc_AesGcmDecrypt : wc_AesCcmDecrypt;
- #elif defined(BUILD_AESGCM)
- aes_auth_fn = wc_AesGcmDecrypt;
- #else
- aes_auth_fn = wc_AesCcmDecrypt;
- #endif
- XMEMSET(ssl->decrypt.additional, 0, AEAD_AUTH_DATA_SZ);
- /* sequence number field is 64-bits */
- WriteSEQ(ssl, PEER_ORDER, ssl->decrypt.additional);
- ssl->decrypt.additional[AEAD_TYPE_OFFSET] = ssl->curRL.type;
- ssl->decrypt.additional[AEAD_VMAJ_OFFSET] = ssl->curRL.pvMajor;
- ssl->decrypt.additional[AEAD_VMIN_OFFSET] = ssl->curRL.pvMinor;
- c16toa(sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
- ssl->decrypt.additional + AEAD_LEN_OFFSET);
- XMEMCPY(ssl->decrypt.nonce, ssl->keys.aead_dec_imp_IV,
- AESGCM_IMP_IV_SZ);
- XMEMCPY(ssl->decrypt.nonce + AESGCM_IMP_IV_SZ, input,
- AESGCM_EXP_IV_SZ);
- if ((ret = aes_auth_fn(ssl->decrypt.aes,
- plain + AESGCM_EXP_IV_SZ,
- input + AESGCM_EXP_IV_SZ,
- sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
- ssl->decrypt.nonce, AESGCM_NONCE_SZ,
- input + sz - ssl->specs.aead_mac_size,
- ssl->specs.aead_mac_size,
- ssl->decrypt.additional, AEAD_AUTH_DATA_SZ)) < 0) {
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev);
- }
- #endif
- }
- }
- break;
- #endif /* BUILD_AESGCM || HAVE_AESCCM */
- #ifdef HAVE_CAMELLIA
- case wolfssl_camellia:
- ret = wc_CamelliaCbcDecrypt(ssl->decrypt.cam, plain, input, sz);
- break;
- #endif
- #ifdef HAVE_HC128
- case wolfssl_hc128:
- ret = wc_Hc128_Process(ssl->decrypt.hc128, plain, input, sz);
- break;
- #endif
- #ifdef BUILD_RABBIT
- case wolfssl_rabbit:
- ret = wc_RabbitProcess(ssl->decrypt.rabbit, plain, input, sz);
- break;
- #endif
- #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
- case wolfssl_chacha:
- ret = ChachaAEADDecrypt(ssl, plain, input, sz);
- break;
- #endif
- #ifdef HAVE_NULL_CIPHER
- case wolfssl_cipher_null:
- if (input != plain) {
- XMEMMOVE(plain, input, sz);
- }
- break;
- #endif
- #ifdef HAVE_IDEA
- case wolfssl_idea:
- ret = wc_IdeaCbcDecrypt(ssl->decrypt.idea, plain, input, sz);
- break;
- #endif
- default:
- WOLFSSL_MSG("wolfSSL Decrypt programming error");
- ret = DECRYPT_ERROR;
- }
- return ret;
- }
- static WC_INLINE int Decrypt(WOLFSSL* ssl, byte* plain, const byte* input,
- word16 sz)
- {
- int ret = 0;
- #ifdef WOLFSSL_ASYNC_CRYPT
- ret = wolfSSL_AsyncPop(ssl, &ssl->decrypt.state);
- if (ret != WC_NOT_PENDING_E) {
- /* check for still pending */
- if (ret == WC_PENDING_E)
- return ret;
- ssl->error = 0; /* clear async */
- /* let failures through so CIPHER_STATE_END logic is run */
- }
- else
- #endif
- {
- /* Reset state */
- ret = 0;
- ssl->decrypt.state = CIPHER_STATE_BEGIN;
- }
- switch (ssl->decrypt.state) {
- case CIPHER_STATE_BEGIN:
- {
- if (ssl->decrypt.setup == 0) {
- WOLFSSL_MSG("Decrypt ciphers not setup");
- return DECRYPT_ERROR;
- }
- #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
- /* make sure AES GCM/CCM memory is allocated */
- /* free for these happens in FreeCiphers */
- if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm ||
- ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
- /* make sure auth iv and auth are allocated */
- if (ssl->decrypt.additional == NULL)
- ssl->decrypt.additional = (byte*)XMALLOC(AEAD_AUTH_DATA_SZ,
- ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
- if (ssl->decrypt.nonce == NULL)
- ssl->decrypt.nonce = (byte*)XMALLOC(AESGCM_NONCE_SZ,
- ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
- if (ssl->decrypt.additional == NULL ||
- ssl->decrypt.nonce == NULL) {
- return MEMORY_E;
- }
- }
- #endif /* BUILD_AESGCM || HAVE_AESCCM */
- /* Advance state and proceed */
- ssl->decrypt.state = CIPHER_STATE_DO;
- }
- FALL_THROUGH;
- case CIPHER_STATE_DO:
- {
- ret = DecryptDo(ssl, plain, input, sz);
- /* Advance state */
- ssl->decrypt.state = CIPHER_STATE_END;
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* If pending, leave and return below */
- if (ret == WC_PENDING_E) {
- return ret;
- }
- #endif
- }
- FALL_THROUGH;
- case CIPHER_STATE_END:
- {
- #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
- /* make sure AES GCM/CCM nonce is cleared */
- if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm ||
- ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
- if (ssl->decrypt.nonce)
- ForceZero(ssl->decrypt.nonce, AESGCM_NONCE_SZ);
- if (ret < 0)
- ret = VERIFY_MAC_ERROR;
- }
- #endif /* BUILD_AESGCM || HAVE_AESCCM */
- break;
- }
- }
- /* Reset state */
- ssl->decrypt.state = CIPHER_STATE_BEGIN;
- /* handle mac error case */
- if (ret == VERIFY_MAC_ERROR) {
- if (!ssl->options.dtls)
- SendAlert(ssl, alert_fatal, bad_record_mac);
- #ifdef WOLFSSL_DTLS_DROP_STATS
- ssl->macDropCount++;
- #endif /* WOLFSSL_DTLS_DROP_STATS */
- }
- return ret;
- }
- #endif /* !WOLFSSL_NO_TLS12 */
- /* Check conditions for a cipher to have an explicit IV.
- *
- * ssl The SSL/TLS object.
- * returns 1 if the cipher in use has an explicit IV and 0 otherwise.
- */
- static WC_INLINE int CipherHasExpIV(WOLFSSL *ssl)
- {
- #ifdef WOLFSSL_TLS13
- if (ssl->options.tls1_3)
- return 0;
- #endif
- return (ssl->specs.cipher_type == aead) &&
- (ssl->specs.bulk_cipher_algorithm != wolfssl_chacha);
- }
- /* check cipher text size for sanity */
- static int SanityCheckCipherText(WOLFSSL* ssl, word32 encryptSz)
- {
- #ifdef HAVE_TRUNCATED_HMAC
- word32 minLength = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
- : ssl->specs.hash_size;
- #else
- word32 minLength = ssl->specs.hash_size; /* covers stream */
- #endif
- #ifndef WOLFSSL_AEAD_ONLY
- if (ssl->specs.cipher_type == block) {
- #ifdef HAVE_ENCRYPT_THEN_MAC
- if (ssl->options.startedETMRead) {
- if ((encryptSz - MacSize(ssl)) % ssl->specs.block_size) {
- WOLFSSL_MSG("Block ciphertext not block size");
- return SANITY_CIPHER_E;
- }
- }
- else
- #endif
- if (encryptSz % ssl->specs.block_size) {
- WOLFSSL_MSG("Block ciphertext not block size");
- return SANITY_CIPHER_E;
- }
- minLength++; /* pad byte */
- if (ssl->specs.block_size > minLength)
- minLength = ssl->specs.block_size;
- if (ssl->options.tls1_1)
- minLength += ssl->specs.block_size; /* explicit IV */
- }
- else
- #endif
- if (ssl->specs.cipher_type == aead) {
- minLength = ssl->specs.aead_mac_size; /* authTag size */
- if (CipherHasExpIV(ssl))
- minLength += AESGCM_EXP_IV_SZ; /* explicit IV */
- }
- if (encryptSz < minLength) {
- WOLFSSL_MSG("Ciphertext not minimum size");
- return SANITY_CIPHER_E;
- }
- return 0;
- }
- #ifndef WOLFSSL_AEAD_ONLY
- /* check all length bytes for the pad value, return 0 on success */
- static int PadCheck(const byte* a, byte pad, int length)
- {
- int i;
- int compareSum = 0;
- for (i = 0; i < length; i++) {
- compareSum |= a[i] ^ pad;
- }
- return compareSum;
- }
- /* Mask the padding bytes with the expected values.
- * Constant time implementation - does maximum pad size possible.
- *
- * data Message data.
- * sz Size of the message including MAC and padding and padding length.
- * macSz Size of the MAC.
- * returns 0 on success, otherwise failure.
- */
- static byte MaskPadding(const byte* data, int sz, int macSz)
- {
- int i;
- int checkSz = sz - 1;
- byte paddingSz = data[sz - 1];
- byte mask;
- byte good = ctMaskGT(paddingSz, sz - 1 - macSz);
- if (checkSz > TLS_MAX_PAD_SZ)
- checkSz = TLS_MAX_PAD_SZ;
- for (i = 0; i < checkSz; i++) {
- mask = ctMaskLTE(i, paddingSz);
- good |= mask & (data[sz - 1 - i] ^ paddingSz);
- }
- return good;
- }
- /* Mask the MAC in the message with the MAC calculated.
- * Constant time implementation - starts looking for MAC where maximum padding
- * size has it.
- *
- * data Message data.
- * sz Size of the message including MAC and padding and padding length.
- * macSz Size of the MAC data.
- * expMac Expected MAC value.
- * returns 0 on success, otherwise failure.
- */
- static byte MaskMac(const byte* data, int sz, int macSz, byte* expMac)
- {
- int i, j;
- unsigned char mac[WC_MAX_DIGEST_SIZE];
- int scanStart = sz - 1 - TLS_MAX_PAD_SZ - macSz;
- int macEnd = sz - 1 - data[sz - 1];
- int macStart = macEnd - macSz;
- int r = 0;
- unsigned char started, notEnded;
- unsigned char good = 0;
- scanStart &= ctMaskIntGTE(scanStart, 0);
- macStart &= ctMaskIntGTE(macStart, 0);
- /* Div on Intel has different speeds depending on value.
- * Use a bitwise AND or mod a specific value (converted to mul). */
- if ((macSz & (macSz - 1)) == 0)
- r = (macSz - (scanStart - macStart)) & (macSz - 1);
- #ifndef NO_SHA
- else if (macSz == WC_SHA_DIGEST_SIZE)
- r = (macSz - (scanStart - macStart)) % WC_SHA_DIGEST_SIZE;
- #endif
- #ifdef WOLFSSL_SHA384
- else if (macSz == WC_SHA384_DIGEST_SIZE)
- r = (macSz - (scanStart - macStart)) % WC_SHA384_DIGEST_SIZE;
- #endif
- XMEMSET(mac, 0, macSz);
- for (i = scanStart; i < sz; i += macSz) {
- for (j = 0; j < macSz && j + i < sz; j++) {
- started = ctMaskGTE(i + j, macStart);
- notEnded = ctMaskLT(i + j, macEnd);
- mac[j] |= started & notEnded & data[i + j];
- }
- }
- if ((macSz & (macSz - 1)) == 0) {
- for (i = 0; i < macSz; i++)
- good |= expMac[i] ^ mac[(i + r) & (macSz - 1)];
- }
- #ifndef NO_SHA
- else if (macSz == WC_SHA_DIGEST_SIZE) {
- for (i = 0; i < macSz; i++)
- good |= expMac[i] ^ mac[(i + r) % WC_SHA_DIGEST_SIZE];
- }
- #endif
- #ifdef WOLFSSL_SHA384
- else if (macSz == WC_SHA384_DIGEST_SIZE) {
- for (i = 0; i < macSz; i++)
- good |= expMac[i] ^ mac[(i + r) % WC_SHA384_DIGEST_SIZE];
- }
- #endif
- return good;
- }
- /* timing resistant pad/verify check, return 0 on success */
- int TimingPadVerify(WOLFSSL* ssl, const byte* input, int padLen, int macSz,
- int pLen, int content)
- {
- byte verify[WC_MAX_DIGEST_SIZE];
- byte good;
- int ret = 0;
- good = MaskPadding(input, pLen, macSz);
- /* 4th argument has potential to underflow, ssl->hmac function should
- * either increment the size by (macSz + padLen + 1) before use or check on
- * the size to make sure is valid. */
- ret = ssl->hmac(ssl, verify, input, pLen - macSz - padLen - 1, padLen,
- content, 1);
- good |= MaskMac(input, pLen, ssl->specs.hash_size, verify);
- /* Non-zero on failure. */
- good = (byte)~(word32)good;
- good &= good >> 4;
- good &= good >> 2;
- good &= good >> 1;
- /* Make ret negative on masking failure. */
- ret -= 1 - good;
- /* Treat any failure as verify MAC error. */
- if (ret != 0)
- ret = VERIFY_MAC_ERROR;
- return ret;
- }
- #endif
- int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx)
- {
- word32 msgSz = ssl->keys.encryptSz;
- word32 idx = *inOutIdx;
- int dataSz;
- int ivExtra = 0;
- byte* rawData = input + idx; /* keep current for hmac */
- #ifdef HAVE_LIBZ
- byte decomp[MAX_RECORD_SIZE + MAX_COMP_EXTRA];
- #endif
- #ifdef WOLFSSL_EARLY_DATA
- if (ssl->options.tls1_3 && ssl->options.handShakeDone == 0) {
- if (ssl->options.side == WOLFSSL_SERVER_END &&
- ssl->earlyData != no_early_data &&
- ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
- ssl->earlyDataSz += ssl->curSize;
- if (ssl->earlyDataSz <= ssl->options.maxEarlyDataSz) {
- WOLFSSL_MSG("Ignoring EarlyData!");
- *inOutIdx = ssl->buffers.inputBuffer.length;
- return 0;
- }
- WOLFSSL_MSG("Too much EarlyData!");
- }
- }
- #endif
- if (ssl->options.handShakeDone == 0) {
- WOLFSSL_MSG("Received App data before a handshake completed");
- SendAlert(ssl, alert_fatal, unexpected_message);
- return OUT_OF_ORDER_E;
- }
- #ifndef WOLFSSL_AEAD_ONLY
- if (ssl->specs.cipher_type == block) {
- if (ssl->options.tls1_1)
- ivExtra = ssl->specs.block_size;
- }
- else
- #endif
- if (ssl->specs.cipher_type == aead) {
- if (CipherHasExpIV(ssl))
- ivExtra = AESGCM_EXP_IV_SZ;
- }
- dataSz = msgSz - ivExtra - ssl->keys.padSz;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead)
- dataSz -= MacSize(ssl);
- #endif
- if (dataSz < 0) {
- WOLFSSL_MSG("App data buffer error, malicious input?");
- SendAlert(ssl, alert_fatal, unexpected_message);
- return BUFFER_ERROR;
- }
- #ifdef WOLFSSL_EARLY_DATA
- if (ssl->earlyData > early_data_ext) {
- if (ssl->earlyDataSz + dataSz > ssl->options.maxEarlyDataSz) {
- SendAlert(ssl, alert_fatal, unexpected_message);
- return WOLFSSL_FATAL_ERROR;
- }
- ssl->earlyDataSz += dataSz;
- }
- #endif
- /* read data */
- if (dataSz) {
- int rawSz = dataSz; /* keep raw size for idx adjustment */
- #ifdef HAVE_LIBZ
- if (ssl->options.usingCompression) {
- dataSz = myDeCompress(ssl, rawData, dataSz, decomp, sizeof(decomp));
- if (dataSz < 0) return dataSz;
- }
- #endif
- idx += rawSz;
- ssl->buffers.clearOutputBuffer.buffer = rawData;
- ssl->buffers.clearOutputBuffer.length = dataSz;
- }
- idx += ssl->keys.padSz;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead)
- idx += MacSize(ssl);
- #endif
- #ifdef HAVE_LIBZ
- /* decompress could be bigger, overwrite after verify */
- if (ssl->options.usingCompression)
- XMEMMOVE(rawData, decomp, dataSz);
- #endif
- *inOutIdx = idx;
- return 0;
- }
- /* process alert, return level */
- static int DoAlert(WOLFSSL* ssl, byte* input, word32* inOutIdx, int* type,
- word32 totalSz)
- {
- byte level;
- byte code;
- word32 dataSz = totalSz - *inOutIdx;
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "Alert");
- if (ssl->toInfoOn)
- /* add record header back on to info + alert bytes level/code */
- AddPacketInfo(ssl, "Alert", alert, input + *inOutIdx -
- RECORD_HEADER_SZ, RECORD_HEADER_SZ + ALERT_SIZE,
- READ_PROTO, ssl->heap);
- #endif
- if (IsEncryptionOn(ssl, 0)) {
- dataSz -= ssl->keys.padSz;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead)
- dataSz -= MacSize(ssl);
- #endif
- }
- /* make sure can read the message */
- if (dataSz != ALERT_SIZE) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, unexpected_message);
- #endif
- return BUFFER_E;
- }
- level = input[(*inOutIdx)++];
- code = input[(*inOutIdx)++];
- ssl->alert_history.last_rx.code = code;
- ssl->alert_history.last_rx.level = level;
- *type = code;
- if (level == alert_fatal) {
- ssl->options.isClosed = 1; /* Don't send close_notify */
- }
- if (++ssl->options.alertCount >= WOLFSSL_ALERT_COUNT_MAX) {
- WOLFSSL_MSG("Alert count exceeded");
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (level != alert_warning || code != close_notify)
- SendAlert(ssl, alert_fatal, unexpected_message);
- #endif
- return ALERT_COUNT_E;
- }
- WOLFSSL_MSG("Got alert");
- if (*type == close_notify) {
- WOLFSSL_MSG("\tclose notify");
- ssl->options.closeNotify = 1;
- }
- #ifdef WOLFSSL_TLS13
- if (*type == decode_error) {
- WOLFSSL_MSG("\tdecode error");
- }
- if (*type == illegal_parameter) {
- WOLFSSL_MSG("\tillegal parameter");
- }
- #endif
- WOLFSSL_ERROR(*type);
- if (IsEncryptionOn(ssl, 0)) {
- *inOutIdx += ssl->keys.padSz;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead)
- *inOutIdx += MacSize(ssl);
- #endif
- }
- return level;
- }
- static int GetInputData(WOLFSSL *ssl, word32 size)
- {
- int in;
- int inSz;
- int maxLength;
- int usedLength;
- int dtlsExtra = 0;
- /* check max input length */
- usedLength = ssl->buffers.inputBuffer.length - ssl->buffers.inputBuffer.idx;
- maxLength = ssl->buffers.inputBuffer.bufferSize - usedLength;
- inSz = (int)(size - usedLength); /* from last partial read */
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- if (size < ssl->dtls_expected_rx)
- dtlsExtra = (int)(ssl->dtls_expected_rx - size);
- inSz = ssl->dtls_expected_rx;
- }
- #endif
- /* check that no lengths or size values are negative */
- if (usedLength < 0 || maxLength < 0 || inSz <= 0) {
- return BUFFER_ERROR;
- }
- if (inSz > maxLength) {
- if (GrowInputBuffer(ssl, size + dtlsExtra, usedLength) < 0)
- return MEMORY_E;
- }
- /* Put buffer data at start if not there */
- if (usedLength > 0 && ssl->buffers.inputBuffer.idx != 0)
- XMEMMOVE(ssl->buffers.inputBuffer.buffer,
- ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.idx,
- usedLength);
- /* remove processed data */
- ssl->buffers.inputBuffer.idx = 0;
- ssl->buffers.inputBuffer.length = usedLength;
- /* read data from network */
- do {
- in = wolfSSLReceive(ssl,
- ssl->buffers.inputBuffer.buffer +
- ssl->buffers.inputBuffer.length,
- inSz);
- if (in == WANT_READ)
- return WANT_READ;
- if (in < 0)
- return SOCKET_ERROR_E;
- if (in > inSz)
- return RECV_OVERFLOW_E;
- ssl->buffers.inputBuffer.length += in;
- inSz -= in;
- } while (ssl->buffers.inputBuffer.length < size);
- #ifdef WOLFSSL_DEBUG_TLS
- if (ssl->buffers.inputBuffer.idx == 0) {
- WOLFSSL_MSG("Data received");
- WOLFSSL_BUFFER(ssl->buffers.inputBuffer.buffer,
- ssl->buffers.inputBuffer.length);
- }
- #endif
- return 0;
- }
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- static WC_INLINE int VerifyMacEnc(WOLFSSL* ssl, const byte* input, word32 msgSz,
- int content)
- {
- int ret;
- #ifdef HAVE_TRUNCATED_HMAC
- word32 digestSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
- : ssl->specs.hash_size;
- #else
- word32 digestSz = ssl->specs.hash_size;
- #endif
- byte verify[WC_MAX_DIGEST_SIZE];
- WOLFSSL_MSG("Verify MAC of Encrypted Data");
- if (msgSz < digestSz) {
- return VERIFY_MAC_ERROR;
- }
- ret = ssl->hmac(ssl, verify, input, msgSz - digestSz, -1, content, 1);
- ret |= ConstantCompare(verify, input + msgSz - digestSz, digestSz);
- if (ret != 0) {
- return VERIFY_MAC_ERROR;
- }
- return 0;
- }
- #endif
- static WC_INLINE int VerifyMac(WOLFSSL* ssl, const byte* input, word32 msgSz,
- int content, word32* padSz)
- {
- #if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
- int ivExtra = 0;
- int ret;
- word32 pad = 0;
- word32 padByte = 0;
- #ifdef HAVE_TRUNCATED_HMAC
- word32 digestSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
- : ssl->specs.hash_size;
- #else
- word32 digestSz = ssl->specs.hash_size;
- #endif
- byte verify[WC_MAX_DIGEST_SIZE];
- if (ssl->specs.cipher_type == block) {
- if (ssl->options.tls1_1)
- ivExtra = ssl->specs.block_size;
- pad = *(input + msgSz - ivExtra - 1);
- padByte = 1;
- if (ssl->options.tls) {
- ret = TimingPadVerify(ssl, input, pad, digestSz, msgSz - ivExtra,
- content);
- if (ret != 0)
- return ret;
- }
- else { /* sslv3, some implementations have bad padding, but don't
- * allow bad read */
- int badPadLen = 0;
- byte dmy[sizeof(WOLFSSL) >= MAX_PAD_SIZE ? 1 : MAX_PAD_SIZE] = {0};
- byte* dummy = sizeof(dmy) < MAX_PAD_SIZE ? (byte*) ssl : dmy;
- (void)dmy;
- if (pad > (msgSz - digestSz - 1)) {
- WOLFSSL_MSG("Plain Len not long enough for pad/mac");
- pad = 0; /* no bad read */
- badPadLen = 1;
- }
- PadCheck(dummy, (byte)pad, MAX_PAD_SIZE); /* timing only */
- ret = ssl->hmac(ssl, verify, input, msgSz - digestSz - pad - 1, pad,
- content, 1);
- if (ConstantCompare(verify, input + msgSz - digestSz - pad - 1,
- digestSz) != 0)
- return VERIFY_MAC_ERROR;
- if (ret != 0 || badPadLen)
- return VERIFY_MAC_ERROR;
- }
- }
- else if (ssl->specs.cipher_type == stream) {
- ret = ssl->hmac(ssl, verify, input, msgSz - digestSz, -1, content, 1);
- if (ConstantCompare(verify, input + msgSz - digestSz, digestSz) != 0){
- return VERIFY_MAC_ERROR;
- }
- if (ret != 0)
- return VERIFY_MAC_ERROR;
- }
- #endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
- if (ssl->specs.cipher_type == aead) {
- *padSz = ssl->specs.aead_mac_size;
- }
- #if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
- else {
- *padSz = digestSz + pad + padByte;
- }
- #endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
- (void)input;
- (void)msgSz;
- (void)content;
- return 0;
- }
- /* process input requests, return 0 is done, 1 is call again to complete, and
- negative number is error */
- int ProcessReply(WOLFSSL* ssl)
- {
- int ret = 0, type, readSz;
- int atomicUser = 0;
- word32 startIdx = 0;
- #if defined(WOLFSSL_DTLS)
- int used;
- #endif
- #ifdef ATOMIC_USER
- if (ssl->ctx->DecryptVerifyCb)
- atomicUser = 1;
- #endif
- if (ssl->error != 0 && ssl->error != WANT_READ && ssl->error != WANT_WRITE
- #ifdef WOLFSSL_ASYNC_CRYPT
- && ssl->error != WC_PENDING_E
- #endif
- #ifdef WOLFSSL_NONBLOCK_OCSP
- && ssl->error != OCSP_WANT_READ
- #endif
- ) {
- WOLFSSL_MSG("ProcessReply retry in error state, not allowed");
- return ssl->error;
- }
- for (;;) {
- switch (ssl->options.processReply) {
- /* in the WOLFSSL_SERVER case, get the first byte for detecting
- * old client hello */
- case doProcessInit:
- readSz = RECORD_HEADER_SZ;
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls)
- readSz = DTLS_RECORD_HEADER_SZ;
- #endif
- /* get header or return error */
- if (!ssl->options.dtls) {
- if ((ret = GetInputData(ssl, readSz)) < 0)
- return ret;
- } else {
- #ifdef WOLFSSL_DTLS
- /* read ahead may already have header */
- used = ssl->buffers.inputBuffer.length -
- ssl->buffers.inputBuffer.idx;
- if (used < readSz) {
- if ((ret = GetInputData(ssl, readSz)) < 0)
- return ret;
- }
- #endif
- }
- #ifdef OLD_HELLO_ALLOWED
- /* see if sending SSLv2 client hello */
- if ( ssl->options.side == WOLFSSL_SERVER_END &&
- ssl->options.clientState == NULL_STATE &&
- ssl->buffers.inputBuffer.buffer[ssl->buffers.inputBuffer.idx]
- != handshake) {
- byte b0, b1;
- ssl->options.processReply = runProcessOldClientHello;
- /* sanity checks before getting size at front */
- if (ssl->buffers.inputBuffer.buffer[
- ssl->buffers.inputBuffer.idx + OPAQUE16_LEN] != OLD_HELLO_ID) {
- WOLFSSL_MSG("Not a valid old client hello");
- return PARSE_ERROR;
- }
- if (ssl->buffers.inputBuffer.buffer[
- ssl->buffers.inputBuffer.idx + OPAQUE24_LEN] != SSLv3_MAJOR &&
- ssl->buffers.inputBuffer.buffer[
- ssl->buffers.inputBuffer.idx + OPAQUE24_LEN] != DTLS_MAJOR) {
- WOLFSSL_MSG("Not a valid version in old client hello");
- return PARSE_ERROR;
- }
- /* how many bytes need ProcessOldClientHello */
- b0 =
- ssl->buffers.inputBuffer.buffer[ssl->buffers.inputBuffer.idx++];
- b1 =
- ssl->buffers.inputBuffer.buffer[ssl->buffers.inputBuffer.idx++];
- ssl->curSize = (word16)(((b0 & 0x7f) << 8) | b1);
- }
- else {
- ssl->options.processReply = getRecordLayerHeader;
- continue;
- }
- FALL_THROUGH;
- /* in the WOLFSSL_SERVER case, run the old client hello */
- case runProcessOldClientHello:
- /* get sz bytes or return error */
- if (!ssl->options.dtls) {
- if ((ret = GetInputData(ssl, ssl->curSize)) < 0)
- return ret;
- } else {
- #ifdef WOLFSSL_DTLS
- /* read ahead may already have */
- used = ssl->buffers.inputBuffer.length -
- ssl->buffers.inputBuffer.idx;
- if (used < ssl->curSize)
- if ((ret = GetInputData(ssl, ssl->curSize)) < 0)
- return ret;
- #endif /* WOLFSSL_DTLS */
- }
- ret = ProcessOldClientHello(ssl, ssl->buffers.inputBuffer.buffer,
- &ssl->buffers.inputBuffer.idx,
- ssl->buffers.inputBuffer.length -
- ssl->buffers.inputBuffer.idx,
- ssl->curSize);
- if (ret < 0)
- return ret;
- else if (ssl->buffers.inputBuffer.idx ==
- ssl->buffers.inputBuffer.length) {
- ssl->options.processReply = doProcessInit;
- return 0;
- }
- #endif /* OLD_HELLO_ALLOWED */
- FALL_THROUGH;
- /* get the record layer header */
- case getRecordLayerHeader:
- ret = GetRecordHeader(ssl, ssl->buffers.inputBuffer.buffer,
- &ssl->buffers.inputBuffer.idx,
- &ssl->curRL, &ssl->curSize);
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls && ret == SEQUENCE_ERROR) {
- WOLFSSL_MSG("Silently dropping out of order DTLS message");
- ssl->options.processReply = doProcessInit;
- ssl->buffers.inputBuffer.length = 0;
- ssl->buffers.inputBuffer.idx = 0;
- #ifdef WOLFSSL_DTLS_DROP_STATS
- ssl->replayDropCount++;
- #endif /* WOLFSSL_DTLS_DROP_STATS */
- if (IsDtlsNotSctpMode(ssl) && ssl->options.dtlsHsRetain) {
- ret = DtlsMsgPoolSend(ssl, 0);
- if (ret != 0)
- return ret;
- }
- continue;
- }
- #endif
- if (ret != 0)
- return ret;
- #ifdef WOLFSSL_TLS13
- if (IsAtLeastTLSv1_3(ssl->version) && IsEncryptionOn(ssl, 0) &&
- ssl->curRL.type != application_data &&
- ssl->curRL.type != change_cipher_spec) {
- SendAlert(ssl, alert_fatal, unexpected_message);
- return PARSE_ERROR;
- }
- #endif
- ssl->options.processReply = getData;
- FALL_THROUGH;
- /* retrieve record layer data */
- case getData:
- /* get sz bytes or return error */
- if (!ssl->options.dtls) {
- if ((ret = GetInputData(ssl, ssl->curSize)) < 0) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (ret != WANT_READ)
- SendAlert(ssl, alert_fatal, bad_record_mac);
- #endif
- return ret;
- }
- }
- else {
- #ifdef WOLFSSL_DTLS
- /* read ahead may already have */
- used = ssl->buffers.inputBuffer.length -
- ssl->buffers.inputBuffer.idx;
- if (used < ssl->curSize)
- if ((ret = GetInputData(ssl, ssl->curSize)) < 0)
- return ret;
- #endif
- }
- if (IsEncryptionOn(ssl, 0)) {
- int tooLong = 0;
- #ifdef WOLFSSL_TLS13
- if (IsAtLeastTLSv1_3(ssl->version)) {
- tooLong = ssl->curSize > MAX_TLS13_ENC_SZ;
- tooLong |= ssl->curSize - ssl->specs.aead_mac_size >
- MAX_TLS13_PLAIN_SZ;
- }
- #endif
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (!IsAtLeastTLSv1_3(ssl->version))
- tooLong = ssl->curSize > MAX_TLS_CIPHER_SZ;
- #endif
- if (tooLong) {
- WOLFSSL_MSG("Encrypted data too long");
- #if defined(WOLFSSL_TLS13) || defined(WOLFSSL_EXTRA_ALERTS)
- SendAlert(ssl, alert_fatal, record_overflow);
- #endif
- return BUFFER_ERROR;
- }
- }
- ssl->keys.padSz = 0;
- ssl->options.processReply = verifyEncryptedMessage;
- startIdx = ssl->buffers.inputBuffer.idx; /* in case > 1 msg per */
- FALL_THROUGH;
- /* verify digest of encrypted message */
- case verifyEncryptedMessage:
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 0 &&
- !atomicUser && ssl->options.startedETMRead) {
- ret = VerifyMacEnc(ssl, ssl->buffers.inputBuffer.buffer +
- ssl->buffers.inputBuffer.idx,
- ssl->curSize, ssl->curRL.type);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E)
- return ret;
- #endif
- if (ret < 0) {
- WOLFSSL_MSG("VerifyMacEnc failed");
- WOLFSSL_ERROR(ret);
- #ifdef WOLFSSL_DTLS
- /* If in DTLS mode, if the decrypt fails for any
- * reason, pretend the datagram never happened. */
- if (ssl->options.dtls) {
- ssl->options.processReply = doProcessInit;
- ssl->buffers.inputBuffer.idx =
- ssl->buffers.inputBuffer.length;
- #ifdef WOLFSSL_DTLS_DROP_STATS
- ssl->macDropCount++;
- #endif /* WOLFSSL_DTLS_DROP_STATS */
- }
- #endif /* WOLFSSL_DTLS */
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (!ssl->options.dtls)
- SendAlert(ssl, alert_fatal, bad_record_mac);
- #endif
- return DECRYPT_ERROR;
- }
- ssl->keys.encryptSz = ssl->curSize;
- }
- #endif
- ssl->options.processReply = decryptMessage;
- FALL_THROUGH;
- /* decrypt message */
- case decryptMessage:
- #if !defined(WOLFSSL_TLS13) || defined(WOLFSSL_TLS13_DRAFT_18)
- if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 0)
- #else
- if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 0 &&
- (!IsAtLeastTLSv1_3(ssl->version) ||
- ssl->curRL.type != change_cipher_spec))
- #endif
- {
- bufferStatic* in = &ssl->buffers.inputBuffer;
- ret = SanityCheckCipherText(ssl, ssl->curSize);
- if (ret < 0) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, bad_record_mac);
- #endif
- return ret;
- }
- if (atomicUser) {
- #ifdef ATOMIC_USER
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead) {
- ret = ssl->ctx->VerifyDecryptCb(ssl,
- in->buffer + in->idx, in->buffer + in->idx,
- ssl->curSize - MacSize(ssl),
- ssl->curRL.type, 1, &ssl->keys.padSz,
- ssl->DecryptVerifyCtx);
- }
- else
- #endif
- {
- ret = ssl->ctx->DecryptVerifyCb(ssl,
- in->buffer + in->idx,
- in->buffer + in->idx,
- ssl->curSize, ssl->curRL.type, 1,
- &ssl->keys.padSz, ssl->DecryptVerifyCtx);
- }
- #endif /* ATOMIC_USER */
- }
- else {
- if (!ssl->options.tls1_3) {
- #ifndef WOLFSSL_NO_TLS12
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead) {
- word32 digestSz = MacSize(ssl);
- ret = Decrypt(ssl,
- in->buffer + in->idx,
- in->buffer + in->idx,
- ssl->curSize - digestSz);
- ssl->keys.padSz =
- in->buffer[in->idx + ssl->curSize - digestSz - 1];
- ssl->keys.padSz += 1;
- ssl->keys.decryptedCur = 1;
- }
- else
- #endif
- {
- ret = Decrypt(ssl,
- in->buffer + in->idx,
- in->buffer + in->idx,
- ssl->curSize);
- }
- #else
- ret = DECRYPT_ERROR;
- #endif
- }
- else
- {
- #ifdef WOLFSSL_TLS13
- #if defined(WOLFSSL_TLS13_DRAFT_18) || \
- defined(WOLFSSL_TLS13_DRAFT_22) || \
- defined(WOLFSSL_TLS13_DRAFT_23)
- ret = DecryptTls13(ssl,
- in->buffer + in->idx,
- in->buffer + in->idx,
- ssl->curSize, NULL, 0);
- #else
- ret = DecryptTls13(ssl,
- in->buffer + in->idx,
- in->buffer + in->idx,
- ssl->curSize,
- (byte*)&ssl->curRL, RECORD_HEADER_SZ);
- #endif
- #else
- ret = DECRYPT_ERROR;
- #endif /* WOLFSSL_TLS13 */
- }
- }
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E)
- return ret;
- #endif
- if (ret >= 0) {
- #ifndef WOLFSSL_NO_TLS12
- /* handle success */
- #ifndef WOLFSSL_AEAD_ONLY
- if (ssl->options.tls1_1 && ssl->specs.cipher_type == block)
- ssl->buffers.inputBuffer.idx += ssl->specs.block_size;
- #endif
- /* go past TLSv1.1 IV */
- if (CipherHasExpIV(ssl))
- ssl->buffers.inputBuffer.idx += AESGCM_EXP_IV_SZ;
- #endif
- }
- else {
- WOLFSSL_MSG("Decrypt failed");
- WOLFSSL_ERROR(ret);
- #ifdef WOLFSSL_EARLY_DATA
- if (ssl->options.tls1_3) {
- if (ssl->options.side == WOLFSSL_SERVER_END &&
- ssl->earlyData != no_early_data &&
- ssl->options.clientState <
- CLIENT_FINISHED_COMPLETE) {
- ssl->earlyDataSz += ssl->curSize;
- if (ssl->earlyDataSz <=
- ssl->options.maxEarlyDataSz) {
- WOLFSSL_MSG("Ignoring EarlyData!");
- if (ssl->keys.peer_sequence_number_lo-- == 0)
- ssl->keys.peer_sequence_number_hi--;
- ssl->options.processReply = doProcessInit;
- ssl->buffers.inputBuffer.idx =
- ssl->buffers.inputBuffer.length;
- return 0;
- }
- WOLFSSL_MSG("Too much EarlyData!");
- }
- SendAlert(ssl, alert_fatal, bad_record_mac);
- }
- #endif
- #ifdef WOLFSSL_DTLS
- /* If in DTLS mode, if the decrypt fails for any
- * reason, pretend the datagram never happened. */
- if (ssl->options.dtls) {
- ssl->options.processReply = doProcessInit;
- ssl->buffers.inputBuffer.idx =
- ssl->buffers.inputBuffer.length;
- #ifdef WOLFSSL_DTLS_DROP_STATS
- ssl->macDropCount++;
- #endif /* WOLFSSL_DTLS_DROP_STATS */
- }
- #endif /* WOLFSSL_DTLS */
- return DECRYPT_ERROR;
- }
- }
- ssl->options.processReply = verifyMessage;
- FALL_THROUGH;
- /* verify digest of message */
- case verifyMessage:
- #if !defined(WOLFSSL_TLS13) || defined(WOLFSSL_TLS13_DRAFT_18)
- if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 0)
- #else
- if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 0 &&
- (!IsAtLeastTLSv1_3(ssl->version) ||
- ssl->curRL.type != change_cipher_spec))
- #endif
- {
- if (!atomicUser
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- && !ssl->options.startedETMRead
- #endif
- ) {
- ret = VerifyMac(ssl, ssl->buffers.inputBuffer.buffer +
- ssl->buffers.inputBuffer.idx,
- ssl->curSize, ssl->curRL.type,
- &ssl->keys.padSz);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E)
- return ret;
- #endif
- if (ret < 0) {
- WOLFSSL_MSG("VerifyMac failed");
- WOLFSSL_ERROR(ret);
- #ifdef WOLFSSL_DTLS
- /* If in DTLS mode, if the decrypt fails for any
- * reason, pretend the datagram never happened. */
- if (ssl->options.dtls) {
- ssl->options.processReply = doProcessInit;
- ssl->buffers.inputBuffer.idx =
- ssl->buffers.inputBuffer.length;
- #ifdef WOLFSSL_DTLS_DROP_STATS
- ssl->macDropCount++;
- #endif /* WOLFSSL_DTLS_DROP_STATS */
- }
- #endif /* WOLFSSL_DTLS */
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (!ssl->options.dtls)
- SendAlert(ssl, alert_fatal, bad_record_mac);
- #endif
- return DECRYPT_ERROR;
- }
- }
- ssl->keys.encryptSz = ssl->curSize;
- ssl->keys.decryptedCur = 1;
- #ifdef WOLFSSL_TLS13
- if (ssl->options.tls1_3) {
- word16 i = (word16)(ssl->buffers.inputBuffer.length -
- ssl->keys.padSz);
- /* Remove padding from end of plain text. */
- for (--i; i > ssl->buffers.inputBuffer.idx; i--) {
- if (ssl->buffers.inputBuffer.buffer[i] != 0)
- break;
- }
- /* Get the real content type from the end of the data. */
- ssl->curRL.type = ssl->buffers.inputBuffer.buffer[i];
- ssl->keys.padSz = ssl->buffers.inputBuffer.length - i;
- }
- #endif
- }
- ssl->options.processReply = runProcessingOneMessage;
- FALL_THROUGH;
- /* the record layer is here */
- case runProcessingOneMessage:
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (IsEncryptionOn(ssl, 0) && ssl->options.startedETMRead) {
- if (ssl->buffers.inputBuffer.length - ssl->keys.padSz -
- ssl->buffers.inputBuffer.idx -
- MacSize(ssl) > MAX_PLAINTEXT_SZ) {
- WOLFSSL_MSG("Plaintext too long - Encrypt-Then-MAC");
- #if defined(WOLFSSL_EXTRA_ALERTS)
- SendAlert(ssl, alert_fatal, record_overflow);
- #endif
- return BUFFER_ERROR;
- }
- }
- else
- #endif
- if (ssl->buffers.inputBuffer.length - ssl->keys.padSz -
- ssl->buffers.inputBuffer.idx > MAX_PLAINTEXT_SZ) {
- WOLFSSL_MSG("Plaintext too long");
- #if defined(WOLFSSL_TLS13) || defined(WOLFSSL_EXTRA_ALERTS)
- SendAlert(ssl, alert_fatal, record_overflow);
- #endif
- return BUFFER_ERROR;
- }
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- DtlsUpdateWindow(ssl);
- }
- #endif /* WOLFSSL_DTLS */
- WOLFSSL_MSG("received record layer msg");
- switch (ssl->curRL.type) {
- case handshake :
- /* debugging in DoHandShakeMsg */
- if (ssl->options.dtls) {
- #ifdef WOLFSSL_DTLS
- ret = DoDtlsHandShakeMsg(ssl,
- ssl->buffers.inputBuffer.buffer,
- &ssl->buffers.inputBuffer.idx,
- ssl->buffers.inputBuffer.length);
- #endif
- }
- else if (!IsAtLeastTLSv1_3(ssl->version)) {
- #ifndef WOLFSSL_NO_TLS12
- ret = DoHandShakeMsg(ssl,
- ssl->buffers.inputBuffer.buffer,
- &ssl->buffers.inputBuffer.idx,
- ssl->buffers.inputBuffer.length);
- #else
- ret = BUFFER_ERROR;
- #endif
- }
- else {
- #ifdef WOLFSSL_TLS13
- ssl->msgsReceived.got_change_cipher = 0;
- ret = DoTls13HandShakeMsg(ssl,
- ssl->buffers.inputBuffer.buffer,
- &ssl->buffers.inputBuffer.idx,
- ssl->buffers.inputBuffer.length);
- #ifdef WOLFSSL_EARLY_DATA
- if (ret != 0)
- return ret;
- if (ssl->options.side == WOLFSSL_SERVER_END &&
- ssl->earlyData > early_data_ext &&
- ssl->options.handShakeState == HANDSHAKE_DONE) {
- ssl->earlyData = no_early_data;
- ssl->options.processReply = doProcessInit;
- return ZERO_RETURN;
- }
- #endif
- #else
- ret = BUFFER_ERROR;
- #endif
- }
- if (ret != 0) {
- WOLFSSL_ERROR(ret);
- return ret;
- }
- break;
- case change_cipher_spec:
- WOLFSSL_MSG("got CHANGE CIPHER SPEC");
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "ChangeCipher");
- /* add record header back on info */
- if (ssl->toInfoOn) {
- AddPacketInfo(ssl, "ChangeCipher",
- change_cipher_spec,
- ssl->buffers.inputBuffer.buffer +
- ssl->buffers.inputBuffer.idx - RECORD_HEADER_SZ,
- 1 + RECORD_HEADER_SZ, READ_PROTO, ssl->heap);
- #ifdef WOLFSSL_CALLBACKS
- AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
- #endif
- }
- #endif
- #ifdef WOLFSSL_TLS13
- #ifdef WOLFSSL_TLS13_DRAFT_18
- if (IsAtLeastTLSv1_3(ssl->version)) {
- SendAlert(ssl, alert_fatal, illegal_parameter);
- return UNKNOWN_RECORD_TYPE;
- }
- #else
- if (IsAtLeastTLSv1_3(ssl->version)) {
- word32 i = ssl->buffers.inputBuffer.idx;
- if (ssl->options.handShakeState == HANDSHAKE_DONE) {
- SendAlert(ssl, alert_fatal, unexpected_message);
- return UNKNOWN_RECORD_TYPE;
- }
- if (ssl->curSize != 1 ||
- ssl->buffers.inputBuffer.buffer[i] != 1) {
- SendAlert(ssl, alert_fatal, illegal_parameter);
- return UNKNOWN_RECORD_TYPE;
- }
- ssl->buffers.inputBuffer.idx++;
- if (!ssl->msgsReceived.got_change_cipher) {
- ssl->msgsReceived.got_change_cipher = 1;
- }
- else {
- SendAlert(ssl, alert_fatal, illegal_parameter);
- return UNKNOWN_RECORD_TYPE;
- }
- break;
- }
- #endif
- #endif
- #ifndef WOLFSSL_NO_TLS12
- ret = SanityCheckMsgReceived(ssl, change_cipher_hs);
- if (ret != 0) {
- if (!ssl->options.dtls) {
- return ret;
- }
- else {
- #ifdef WOLFSSL_DTLS
- /* Check for duplicate CCS message in DTLS mode.
- * DTLS allows for duplicate messages, and it should be
- * skipped. Also skip if out of order. */
- if (ret != DUPLICATE_MSG_E && ret != OUT_OF_ORDER_E)
- return ret;
- if (IsDtlsNotSctpMode(ssl)) {
- ret = DtlsMsgPoolSend(ssl, 1);
- if (ret != 0)
- return ret;
- }
- if (ssl->curSize != 1) {
- WOLFSSL_MSG("Malicious or corrupted"
- " duplicate ChangeCipher msg");
- return LENGTH_ERROR;
- }
- ssl->buffers.inputBuffer.idx++;
- break;
- #endif /* WOLFSSL_DTLS */
- }
- }
- if (IsEncryptionOn(ssl, 0) && ssl->options.handShakeDone) {
- ssl->buffers.inputBuffer.idx += ssl->keys.padSz;
- ssl->curSize -= (word16) ssl->buffers.inputBuffer.idx;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead) {
- word32 digestSz = MacSize(ssl);
- ssl->buffers.inputBuffer.idx += digestSz;
- ssl->curSize -= digestSz;
- }
- #endif
- }
- if (ssl->curSize != 1) {
- WOLFSSL_MSG("Malicious or corrupted ChangeCipher msg");
- return LENGTH_ERROR;
- }
- ssl->buffers.inputBuffer.idx++;
- ssl->keys.encryptionOn = 1;
- /* setup decrypt keys for following messages */
- /* XXX This might not be what we want to do when
- * receiving a CCS with multicast. We update the
- * key when the application updates them. */
- if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
- return ret;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- ssl->options.startedETMRead = ssl->options.encThenMac;
- #endif
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- WOLFSSL_DTLS_PEERSEQ* peerSeq = ssl->keys.peerSeq;
- #ifdef WOLFSSL_MULTICAST
- if (ssl->options.haveMcast) {
- peerSeq += ssl->keys.curPeerId;
- peerSeq->highwaterMark = UpdateHighwaterMark(0,
- ssl->ctx->mcastFirstSeq,
- ssl->ctx->mcastSecondSeq,
- ssl->ctx->mcastMaxSeq);
- }
- #endif
- peerSeq->nextEpoch++;
- peerSeq->prevSeq_lo = peerSeq->nextSeq_lo;
- peerSeq->prevSeq_hi = peerSeq->nextSeq_hi;
- peerSeq->nextSeq_lo = 0;
- peerSeq->nextSeq_hi = 0;
- XMEMCPY(peerSeq->prevWindow, peerSeq->window,
- DTLS_SEQ_SZ);
- XMEMSET(peerSeq->window, 0, DTLS_SEQ_SZ);
- }
- #endif
- #ifdef HAVE_LIBZ
- if (ssl->options.usingCompression)
- if ( (ret = InitStreams(ssl)) != 0)
- return ret;
- #endif
- ret = BuildFinished(ssl, &ssl->hsHashes->verifyHashes,
- ssl->options.side == WOLFSSL_CLIENT_END ?
- server : client);
- if (ret != 0)
- return ret;
- #endif /* !WOLFSSL_NO_TLS12 */
- break;
- case application_data:
- WOLFSSL_MSG("got app DATA");
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls && ssl->options.dtlsHsRetain) {
- FreeHandshakeResources(ssl);
- ssl->options.dtlsHsRetain = 0;
- }
- #endif
- #ifdef WOLFSSL_TLS13
- if (ssl->keys.keyUpdateRespond) {
- WOLFSSL_MSG("No KeyUpdate from peer seen");
- return SANITY_MSG_E;
- }
- #endif
- if ((ret = DoApplicationData(ssl,
- ssl->buffers.inputBuffer.buffer,
- &ssl->buffers.inputBuffer.idx))
- != 0) {
- WOLFSSL_ERROR(ret);
- return ret;
- }
- break;
- case alert:
- WOLFSSL_MSG("got ALERT!");
- ret = DoAlert(ssl, ssl->buffers.inputBuffer.buffer,
- &ssl->buffers.inputBuffer.idx, &type,
- ssl->buffers.inputBuffer.length);
- if (ret == alert_fatal)
- return FATAL_ERROR;
- else if (ret < 0)
- return ret;
- /* catch warnings that are handled as errors */
- if (type == close_notify)
- return ssl->error = ZERO_RETURN;
- if (type == decrypt_error)
- return FATAL_ERROR;
- break;
- default:
- WOLFSSL_ERROR(UNKNOWN_RECORD_TYPE);
- return UNKNOWN_RECORD_TYPE;
- }
- ssl->options.processReply = doProcessInit;
- /* input exhausted? */
- if (ssl->buffers.inputBuffer.idx >= ssl->buffers.inputBuffer.length)
- return 0;
- /* more messages per record */
- else if ((ssl->buffers.inputBuffer.idx - startIdx) < ssl->curSize) {
- WOLFSSL_MSG("More messages in record");
- ssl->options.processReply = runProcessingOneMessage;
- if (IsEncryptionOn(ssl, 0)) {
- WOLFSSL_MSG("Bundled encrypted messages, remove middle pad");
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead) {
- word32 digestSz = MacSize(ssl);
- if (ssl->buffers.inputBuffer.idx >=
- ssl->keys.padSz + digestSz) {
- ssl->buffers.inputBuffer.idx -=
- ssl->keys.padSz + digestSz;
- }
- else {
- WOLFSSL_MSG("\tmiddle padding error");
- return FATAL_ERROR;
- }
- }
- else
- #endif
- {
- if (ssl->buffers.inputBuffer.idx >= ssl->keys.padSz) {
- ssl->buffers.inputBuffer.idx -= ssl->keys.padSz;
- }
- else {
- WOLFSSL_MSG("\tmiddle padding error");
- return FATAL_ERROR;
- }
- }
- }
- continue;
- }
- /* more records */
- else {
- WOLFSSL_MSG("More records in input");
- ssl->options.processReply = doProcessInit;
- continue;
- }
- default:
- WOLFSSL_MSG("Bad process input state, programming error");
- return INPUT_CASE_ERROR;
- }
- }
- }
- int SendChangeCipher(WOLFSSL* ssl)
- {
- byte *output;
- int sendSz = RECORD_HEADER_SZ + ENUM_LEN;
- int idx = RECORD_HEADER_SZ;
- int ret;
- #ifdef OPENSSL_EXTRA
- ssl->cbmode = SSL_CB_MODE_WRITE;
- if (ssl->options.side == WOLFSSL_SERVER_END){
- ssl->options.serverState = SERVER_CHANGECIPHERSPEC_COMPLETE;
- if (ssl->CBIS != NULL)
- ssl->CBIS(ssl, SSL_CB_ACCEPT_LOOP, SSL_SUCCESS);
- }
- else{
- ssl->options.clientState =
- CLIENT_CHANGECIPHERSPEC_COMPLETE;
- if (ssl->CBIS != NULL)
- ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, SSL_SUCCESS);
- }
- #endif
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- sendSz += DTLS_RECORD_EXTRA;
- idx += DTLS_RECORD_EXTRA;
- }
- #endif
- /* are we in scr */
- if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone) {
- sendSz += MAX_MSG_EXTRA;
- }
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
- return ret;
- /* get output buffer */
- output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- AddRecordHeader(output, 1, change_cipher_spec, ssl);
- output[idx] = 1; /* turn it on */
- if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone) {
- byte input[ENUM_LEN];
- int inputSz = ENUM_LEN;
- input[0] = 1; /* turn it on */
- sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
- change_cipher_spec, 0, 0, 0);
- if (sendSz < 0) {
- return sendSz;
- }
- }
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- DtlsSEQIncrement(ssl, CUR_ORDER);
- if ((ret = DtlsMsgPoolSave(ssl, output, sendSz)) != 0)
- return ret;
- }
- #endif
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ssl->hsInfoOn) AddPacketName(ssl, "ChangeCipher");
- if (ssl->toInfoOn)
- AddPacketInfo(ssl, "ChangeCipher", change_cipher_spec, output,
- sendSz, WRITE_PROTO, ssl->heap);
- #endif
- ssl->buffers.outputBuffer.length += sendSz;
- if (ssl->options.groupMessages)
- return 0;
- #if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_DEBUG_DTLS)
- else if (ssl->options.dtls) {
- /* If using DTLS, force the ChangeCipherSpec message to be in the
- * same datagram as the finished message. */
- return 0;
- }
- #endif
- else
- return SendBuffered(ssl);
- }
- #if !defined(NO_OLD_TLS) && !defined(WOLFSSL_AEAD_ONLY)
- static int SSL_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz,
- int padLen, int content, int verify)
- {
- byte result[WC_MAX_DIGEST_SIZE];
- word32 digestSz = ssl->specs.hash_size; /* actual sizes */
- word32 padSz = ssl->specs.pad_size;
- int ret = 0;
- wc_Md5 md5;
- wc_Sha sha;
- /* data */
- byte seq[SEQ_SZ];
- byte conLen[ENUM_LEN + LENGTH_SZ]; /* content & length */
- const byte* macSecret = wolfSSL_GetMacSecret(ssl, verify);
- (void)padLen;
- #ifdef HAVE_FUZZER
- if (ssl->fuzzerCb)
- ssl->fuzzerCb(ssl, in, sz, FUZZ_HMAC, ssl->fuzzerCtx);
- #endif
- XMEMSET(seq, 0, SEQ_SZ);
- conLen[0] = (byte)content;
- c16toa((word16)sz, &conLen[ENUM_LEN]);
- WriteSEQ(ssl, verify, seq);
- if (ssl->specs.mac_algorithm == md5_mac) {
- ret = wc_InitMd5_ex(&md5, ssl->heap, ssl->devId);
- if (ret != 0)
- return ret;
- /* inner */
- ret = wc_Md5Update(&md5, macSecret, digestSz);
- ret |= wc_Md5Update(&md5, PAD1, padSz);
- ret |= wc_Md5Update(&md5, seq, SEQ_SZ);
- ret |= wc_Md5Update(&md5, conLen, sizeof(conLen));
- /* in buffer */
- ret |= wc_Md5Update(&md5, in, sz);
- if (ret != 0)
- return VERIFY_MAC_ERROR;
- ret = wc_Md5Final(&md5, result);
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* TODO: Make non-blocking */
- if (ret == WC_PENDING_E) {
- ret = wc_AsyncWait(ret, &md5.asyncDev, WC_ASYNC_FLAG_NONE);
- }
- #endif
- if (ret != 0)
- return VERIFY_MAC_ERROR;
- /* outer */
- ret = wc_Md5Update(&md5, macSecret, digestSz);
- ret |= wc_Md5Update(&md5, PAD2, padSz);
- ret |= wc_Md5Update(&md5, result, digestSz);
- if (ret != 0)
- return VERIFY_MAC_ERROR;
- ret = wc_Md5Final(&md5, digest);
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* TODO: Make non-blocking */
- if (ret == WC_PENDING_E) {
- ret = wc_AsyncWait(ret, &md5.asyncDev, WC_ASYNC_FLAG_NONE);
- }
- #endif
- if (ret != 0)
- return VERIFY_MAC_ERROR;
- wc_Md5Free(&md5);
- }
- else {
- ret = wc_InitSha_ex(&sha, ssl->heap, ssl->devId);
- if (ret != 0)
- return ret;
- /* inner */
- ret = wc_ShaUpdate(&sha, macSecret, digestSz);
- ret |= wc_ShaUpdate(&sha, PAD1, padSz);
- ret |= wc_ShaUpdate(&sha, seq, SEQ_SZ);
- ret |= wc_ShaUpdate(&sha, conLen, sizeof(conLen));
- /* in buffer */
- ret |= wc_ShaUpdate(&sha, in, sz);
- if (ret != 0)
- return VERIFY_MAC_ERROR;
- ret = wc_ShaFinal(&sha, result);
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* TODO: Make non-blocking */
- if (ret == WC_PENDING_E) {
- ret = wc_AsyncWait(ret, &sha.asyncDev, WC_ASYNC_FLAG_NONE);
- }
- #endif
- if (ret != 0)
- return VERIFY_MAC_ERROR;
- /* outer */
- ret = wc_ShaUpdate(&sha, macSecret, digestSz);
- ret |= wc_ShaUpdate(&sha, PAD2, padSz);
- ret |= wc_ShaUpdate(&sha, result, digestSz);
- if (ret != 0)
- return VERIFY_MAC_ERROR;
- ret = wc_ShaFinal(&sha, digest);
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* TODO: Make non-blocking */
- if (ret == WC_PENDING_E) {
- ret = wc_AsyncWait(ret, &sha.asyncDev, WC_ASYNC_FLAG_NONE);
- }
- #endif
- if (ret != 0)
- return VERIFY_MAC_ERROR;
- wc_ShaFree(&sha);
- }
- return 0;
- }
- #endif /* !NO_OLD_TLS && !WOLFSSL_AEAD_ONLY */
- #ifndef NO_CERTS
- #if !defined(NO_MD5) && !defined(NO_OLD_TLS)
- static int BuildMD5_CertVerify(WOLFSSL* ssl, byte* digest)
- {
- int ret;
- byte md5_result[WC_MD5_DIGEST_SIZE];
- #ifdef WOLFSSL_SMALL_STACK
- wc_Md5* md5 = (wc_Md5*)XMALLOC(sizeof(wc_Md5), ssl->heap, DYNAMIC_TYPE_HASHCTX);
- #else
- wc_Md5 md5[1];
- #endif
- /* make md5 inner */
- ret = wc_Md5Copy(&ssl->hsHashes->hashMd5, md5); /* Save current position */
- if (ret == 0)
- ret = wc_Md5Update(md5, ssl->arrays->masterSecret,SECRET_LEN);
- if (ret == 0)
- ret = wc_Md5Update(md5, PAD1, PAD_MD5);
- if (ret == 0)
- ret = wc_Md5Final(md5, md5_result);
- /* make md5 outer */
- if (ret == 0) {
- ret = wc_InitMd5_ex(md5, ssl->heap, ssl->devId);
- if (ret == 0) {
- ret = wc_Md5Update(md5, ssl->arrays->masterSecret, SECRET_LEN);
- if (ret == 0)
- ret = wc_Md5Update(md5, PAD2, PAD_MD5);
- if (ret == 0)
- ret = wc_Md5Update(md5, md5_result, WC_MD5_DIGEST_SIZE);
- if (ret == 0)
- ret = wc_Md5Final(md5, digest);
- wc_Md5Free(md5);
- }
- }
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(md5, ssl->heap, DYNAMIC_TYPE_HASHCTX);
- #endif
- return ret;
- }
- #endif /* !NO_MD5 && !NO_OLD_TLS */
- #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
- defined(WOLFSSL_ALLOW_TLS_SHA1))
- static int BuildSHA_CertVerify(WOLFSSL* ssl, byte* digest)
- {
- int ret;
- byte sha_result[WC_SHA_DIGEST_SIZE];
- #ifdef WOLFSSL_SMALL_STACK
- wc_Sha* sha = (wc_Sha*)XMALLOC(sizeof(wc_Sha), ssl->heap, DYNAMIC_TYPE_HASHCTX);
- #else
- wc_Sha sha[1];
- #endif
- /* make sha inner */
- ret = wc_ShaCopy(&ssl->hsHashes->hashSha, sha); /* Save current position */
- if (ret == 0)
- ret = wc_ShaUpdate(sha, ssl->arrays->masterSecret,SECRET_LEN);
- if (ret == 0)
- ret = wc_ShaUpdate(sha, PAD1, PAD_SHA);
- if (ret == 0)
- ret = wc_ShaFinal(sha, sha_result);
- /* make sha outer */
- if (ret == 0) {
- ret = wc_InitSha_ex(sha, ssl->heap, ssl->devId);
- if (ret == 0) {
- ret = wc_ShaUpdate(sha, ssl->arrays->masterSecret,SECRET_LEN);
- if (ret == 0)
- ret = wc_ShaUpdate(sha, PAD2, PAD_SHA);
- if (ret == 0)
- ret = wc_ShaUpdate(sha, sha_result, WC_SHA_DIGEST_SIZE);
- if (ret == 0)
- ret = wc_ShaFinal(sha, digest);
- wc_ShaFree(sha);
- }
- }
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(sha, ssl->heap, DYNAMIC_TYPE_HASHCTX);
- #endif
- return ret;
- }
- #endif /* !NO_SHA && (!NO_OLD_TLS || WOLFSSL_ALLOW_TLS_SHA1) */
- int BuildCertHashes(WOLFSSL* ssl, Hashes* hashes)
- {
- int ret = 0;
- (void)hashes;
- if (ssl->options.tls) {
- #if !defined(NO_MD5) && !defined(NO_OLD_TLS)
- ret = wc_Md5GetHash(&ssl->hsHashes->hashMd5, hashes->md5);
- if (ret != 0)
- return ret;
- #endif
- #if !defined(NO_SHA)
- ret = wc_ShaGetHash(&ssl->hsHashes->hashSha, hashes->sha);
- if (ret != 0)
- return ret;
- #endif
- if (IsAtLeastTLSv1_2(ssl)) {
- #ifndef NO_SHA256
- ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256,
- hashes->sha256);
- if (ret != 0)
- return ret;
- #endif
- #ifdef WOLFSSL_SHA384
- ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384,
- hashes->sha384);
- if (ret != 0)
- return ret;
- #endif
- #ifdef WOLFSSL_SHA512
- ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512,
- hashes->sha512);
- if (ret != 0)
- return ret;
- #endif
- }
- }
- else {
- #if !defined(NO_MD5) && !defined(NO_OLD_TLS)
- ret = BuildMD5_CertVerify(ssl, hashes->md5);
- if (ret != 0)
- return ret;
- #endif
- #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
- defined(WOLFSSL_ALLOW_TLS_SHA1))
- ret = BuildSHA_CertVerify(ssl, hashes->sha);
- if (ret != 0)
- return ret;
- #endif
- }
- return ret;
- }
- #endif /* !NO_CERTS */
- #ifndef WOLFSSL_NO_TLS12
- /* Persistable BuildMessage arguments */
- typedef struct BuildMsgArgs {
- word32 digestSz;
- word32 sz;
- word32 pad;
- word32 idx;
- word32 headerSz;
- word16 size;
- word32 ivSz; /* TLSv1.1 IV */
- byte* iv;
- } BuildMsgArgs;
- static void FreeBuildMsgArgs(WOLFSSL* ssl, void* pArgs)
- {
- BuildMsgArgs* args = (BuildMsgArgs*)pArgs;
- (void)ssl;
- (void)args;
- if (args->iv) {
- XFREE(args->iv, ssl->heap, DYNAMIC_TYPE_SALT);
- args->iv = NULL;
- }
- }
- #endif
- /* Build SSL Message, encrypted */
- int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input,
- int inSz, int type, int hashOutput, int sizeOnly, int asyncOkay)
- {
- #ifndef WOLFSSL_NO_TLS12
- int ret = 0;
- BuildMsgArgs* args;
- BuildMsgArgs lcl_args;
- #ifdef WOLFSSL_ASYNC_CRYPT
- args = (BuildMsgArgs*)ssl->async.args;
- typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
- (void)sizeof(args_test);
- #endif
- #endif
- WOLFSSL_ENTER("BuildMessage");
- if (ssl == NULL) {
- return BAD_FUNC_ARG;
- }
- #ifdef WOLFSSL_NO_TLS12
- return BuildTls13Message(ssl, output, outSz, input, inSz, type,
- hashOutput, sizeOnly, asyncOkay);
- #else
- #ifdef WOLFSSL_TLS13
- if (ssl->options.tls1_3) {
- return BuildTls13Message(ssl, output, outSz, input, inSz, type,
- hashOutput, sizeOnly, asyncOkay);
- }
- #endif
- ret = WC_NOT_PENDING_E;
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (asyncOkay) {
- ret = wolfSSL_AsyncPop(ssl, &ssl->options.buildMsgState);
- if (ret != WC_NOT_PENDING_E) {
- /* Check for error */
- if (ret < 0)
- goto exit_buildmsg;
- }
- }
- else
- #endif
- {
- args = &lcl_args;
- }
- /* Reset state */
- if (ret == WC_NOT_PENDING_E) {
- ret = 0;
- ssl->options.buildMsgState = BUILD_MSG_BEGIN;
- XMEMSET(args, 0, sizeof(BuildMsgArgs));
- args->sz = RECORD_HEADER_SZ + inSz;
- args->idx = RECORD_HEADER_SZ;
- args->headerSz = RECORD_HEADER_SZ;
- #ifdef WOLFSSL_ASYNC_CRYPT
- ssl->async.freeArgs = FreeBuildMsgArgs;
- #endif
- }
- switch (ssl->options.buildMsgState) {
- case BUILD_MSG_BEGIN:
- {
- /* catch mistaken sizeOnly parameter */
- if (!sizeOnly && (output == NULL || input == NULL) ) {
- ERROR_OUT(BAD_FUNC_ARG, exit_buildmsg);
- }
- if (sizeOnly && (output || input) ) {
- WOLFSSL_MSG("BuildMessage w/sizeOnly doesn't need input/output");
- ERROR_OUT(BAD_FUNC_ARG, exit_buildmsg);
- }
- ssl->options.buildMsgState = BUILD_MSG_SIZE;
- }
- FALL_THROUGH;
- case BUILD_MSG_SIZE:
- {
- args->digestSz = ssl->specs.hash_size;
- #ifdef HAVE_TRUNCATED_HMAC
- if (ssl->truncated_hmac)
- args->digestSz = min(TRUNCATED_HMAC_SZ, args->digestSz);
- #endif
- args->sz += args->digestSz;
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- args->sz += DTLS_RECORD_EXTRA;
- args->idx += DTLS_RECORD_EXTRA;
- args->headerSz += DTLS_RECORD_EXTRA;
- }
- #endif
- #ifndef WOLFSSL_AEAD_ONLY
- if (ssl->specs.cipher_type == block) {
- word32 blockSz = ssl->specs.block_size;
- if (ssl->options.tls1_1) {
- args->ivSz = blockSz;
- args->sz += args->ivSz;
- if (args->ivSz > MAX_IV_SZ)
- ERROR_OUT(BUFFER_E, exit_buildmsg);
- }
- args->sz += 1; /* pad byte */
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMWrite) {
- args->pad = (args->sz - args->headerSz -
- args->digestSz) % blockSz;
- }
- else
- #endif
- args->pad = (args->sz - args->headerSz) % blockSz;
- #ifdef OPENSSL_EXTRA
- if(args->pad != 0)
- #endif
- args->pad = blockSz - args->pad;
- args->sz += args->pad;
- }
- #endif /* WOLFSSL_AEAD_ONLY */
- #ifdef HAVE_AEAD
- if (ssl->specs.cipher_type == aead) {
- if (ssl->specs.bulk_cipher_algorithm != wolfssl_chacha)
- args->ivSz = AESGCM_EXP_IV_SZ;
- args->sz += (args->ivSz + ssl->specs.aead_mac_size - args->digestSz);
- }
- #endif
- /* done with size calculations */
- if (sizeOnly)
- goto exit_buildmsg;
- if (args->sz > (word32)outSz) {
- WOLFSSL_MSG("Oops, want to write past output buffer size");
- ERROR_OUT(BUFFER_E, exit_buildmsg);
- }
- if (args->ivSz > 0) {
- args->iv = (byte*)XMALLOC(args->ivSz, ssl->heap, DYNAMIC_TYPE_SALT);
- if (args->iv == NULL)
- ERROR_OUT(MEMORY_E, exit_buildmsg);
- ret = wc_RNG_GenerateBlock(ssl->rng, args->iv, args->ivSz);
- if (ret != 0)
- goto exit_buildmsg;
- }
- #if !defined(NO_PUBLIC_GCM_SET_IV) && \
- ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
- (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)) && \
- defined(HAVE_AEAD))
- if (ssl->specs.cipher_type == aead) {
- if (ssl->specs.bulk_cipher_algorithm != wolfssl_chacha)
- XMEMCPY(args->iv, ssl->keys.aead_exp_IV, AESGCM_EXP_IV_SZ);
- }
- #endif
- args->size = (word16)(args->sz - args->headerSz); /* include mac and digest */
- AddRecordHeader(output, args->size, (byte)type, ssl);
- /* write to output */
- if (args->ivSz > 0) {
- XMEMCPY(output + args->idx, args->iv,
- min(args->ivSz, MAX_IV_SZ));
- args->idx += args->ivSz;
- }
- XMEMCPY(output + args->idx, input, inSz);
- args->idx += inSz;
- ssl->options.buildMsgState = BUILD_MSG_HASH;
- }
- FALL_THROUGH;
- case BUILD_MSG_HASH:
- {
- if (type == handshake && hashOutput) {
- ret = HashOutput(ssl, output, args->headerSz + inSz, args->ivSz);
- if (ret != 0)
- goto exit_buildmsg;
- }
- #ifndef WOLFSSL_AEAD_ONLY
- if (ssl->specs.cipher_type == block) {
- word32 tmpIdx;
- word32 i;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMWrite)
- tmpIdx = args->idx;
- else
- #endif
- tmpIdx = args->idx + args->digestSz;
- for (i = 0; i <= args->pad; i++)
- output[tmpIdx++] = (byte)args->pad; /* pad byte gets pad value */
- }
- #endif
- ssl->options.buildMsgState = BUILD_MSG_VERIFY_MAC;
- }
- FALL_THROUGH;
- case BUILD_MSG_VERIFY_MAC:
- {
- /* User Record Layer Callback handling */
- #ifdef ATOMIC_USER
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMWrite) {
- if (ssl->ctx->EncryptMacCb) {
- ret = ssl->ctx->EncryptMacCb(ssl, output + args->idx +
- args->pad + 1, type, 0,
- output + args->headerSz,
- output + args->headerSz,
- args->size - args->digestSz,
- ssl->MacEncryptCtx);
- goto exit_buildmsg;
- }
- }
- else
- #endif
- {
- if (ssl->ctx->MacEncryptCb) {
- ret = ssl->ctx->MacEncryptCb(ssl, output + args->idx,
- output + args->headerSz + args->ivSz, inSz,
- type, 0, output + args->headerSz,
- output + args->headerSz, args->size,
- ssl->MacEncryptCtx);
- goto exit_buildmsg;
- }
- }
- #endif
- #ifndef WOLFSSL_AEAD_ONLY
- if (ssl->specs.cipher_type != aead
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- && !ssl->options.startedETMWrite
- #endif
- ) {
- #ifdef HAVE_TRUNCATED_HMAC
- if (ssl->truncated_hmac &&
- ssl->specs.hash_size > args->digestSz) {
- #ifdef WOLFSSL_SMALL_STACK
- byte* hmac;
- #else
- byte hmac[WC_MAX_DIGEST_SIZE];
- #endif
- #ifdef WOLFSSL_SMALL_STACK
- hmac = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, ssl->heap,
- DYNAMIC_TYPE_DIGEST);
- if (hmac == NULL)
- ERROR_OUT(MEMORY_E, exit_buildmsg);
- #endif
- ret = ssl->hmac(ssl, hmac,
- output + args->headerSz + args->ivSz, inSz,
- -1, type, 0);
- XMEMCPY(output + args->idx, hmac, args->digestSz);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(hmac, ssl->heap, DYNAMIC_TYPE_DIGEST);
- #endif
- }
- else
- #endif
- {
- ret = ssl->hmac(ssl, output + args->idx, output +
- args->headerSz + args->ivSz, inSz, -1, type, 0);
- }
- }
- #endif /* WOLFSSL_AEAD_ONLY */
- if (ret != 0)
- goto exit_buildmsg;
- ssl->options.buildMsgState = BUILD_MSG_ENCRYPT;
- }
- FALL_THROUGH;
- case BUILD_MSG_ENCRYPT:
- {
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMWrite) {
- ret = Encrypt(ssl, output + args->headerSz,
- output + args->headerSz,
- args->size - args->digestSz, asyncOkay);
- }
- else
- #endif
- {
- ret = Encrypt(ssl, output + args->headerSz,
- output + args->headerSz, args->size, asyncOkay);
- }
- if (ret != 0)
- goto exit_buildmsg;
- ssl->options.buildMsgState = BUILD_MSG_ENCRYPTED_VERIFY_MAC;
- }
- FALL_THROUGH;
- case BUILD_MSG_ENCRYPTED_VERIFY_MAC:
- {
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMWrite) {
- WOLFSSL_MSG("Calculate MAC of Encrypted Data");
- #ifdef HAVE_TRUNCATED_HMAC
- if (ssl->truncated_hmac &&
- ssl->specs.hash_size > args->digestSz) {
- #ifdef WOLFSSL_SMALL_STACK
- byte* hmac = NULL;
- #else
- byte hmac[WC_MAX_DIGEST_SIZE];
- #endif
- #ifdef WOLFSSL_SMALL_STACK
- hmac = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, ssl->heap,
- DYNAMIC_TYPE_DIGEST);
- if (hmac == NULL)
- ERROR_OUT(MEMORY_E, exit_buildmsg);
- #endif
- ret = ssl->hmac(ssl, hmac, output + args->headerSz,
- args->ivSz + inSz + args->pad + 1, -1, type,
- 0);
- XMEMCPY(output + args->idx + args->pad + 1, hmac,
- args->digestSz);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(hmac, ssl->heap, DYNAMIC_TYPE_DIGEST);
- #endif
- }
- else
- #endif
- {
- ret = ssl->hmac(ssl, output + args->idx + args->pad + 1,
- output + args->headerSz,
- args->ivSz + inSz + args->pad + 1, -1, type,
- 0);
- }
- }
- #endif /* HAVE_ENCRYPT_THEN_MAC && !WOLFSSL_AEAD_ONLY */
- }
- }
- exit_buildmsg:
- WOLFSSL_LEAVE("BuildMessage", ret);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- return ret;
- }
- #endif
- /* make sure build message state is reset */
- ssl->options.buildMsgState = BUILD_MSG_BEGIN;
- #ifdef WOLFSSL_DTLS
- if (ret == 0 && ssl->options.dtls)
- DtlsSEQIncrement(ssl, CUR_ORDER);
- #endif
- /* return sz on success */
- if (ret == 0)
- ret = args->sz;
- /* Final cleanup */
- FreeBuildMsgArgs(ssl, args);
- #ifdef WOLFSSL_ASYNC_CRYPT
- ssl->async.freeArgs = NULL;
- #endif
- return ret;
- #endif /* !WOLFSSL_NO_TLS12 */
- }
- #ifndef WOLFSSL_NO_TLS12
- int SendFinished(WOLFSSL* ssl)
- {
- int sendSz,
- finishedSz = ssl->options.tls ? TLS_FINISHED_SZ :
- FINISHED_SZ;
- byte input[FINISHED_SZ + DTLS_HANDSHAKE_HEADER_SZ]; /* max */
- byte *output;
- Hashes* hashes;
- int ret;
- int headerSz = HANDSHAKE_HEADER_SZ;
- int outputSz;
- WOLFSSL_START(WC_FUNC_FINISHED_SEND);
- WOLFSSL_ENTER("SendFinished");
- /* setup encrypt keys */
- if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
- return ret;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- ssl->options.startedETMWrite = ssl->options.encThenMac;
- #endif
- /* check for available size */
- outputSz = sizeof(input) + MAX_MSG_EXTRA;
- if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
- return ret;
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- headerSz += DTLS_HANDSHAKE_EXTRA;
- ssl->keys.dtls_epoch++;
- ssl->keys.dtls_prev_sequence_number_hi =
- ssl->keys.dtls_sequence_number_hi;
- ssl->keys.dtls_prev_sequence_number_lo =
- ssl->keys.dtls_sequence_number_lo;
- ssl->keys.dtls_sequence_number_hi = 0;
- ssl->keys.dtls_sequence_number_lo = 0;
- }
- #endif
- /* get output buffer */
- output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- AddHandShakeHeader(input, finishedSz, 0, finishedSz, finished, ssl);
- /* make finished hashes */
- hashes = (Hashes*)&input[headerSz];
- ret = BuildFinished(ssl, hashes,
- ssl->options.side == WOLFSSL_CLIENT_END ? client : server);
- if (ret != 0) return ret;
- #ifdef HAVE_SECURE_RENEGOTIATION
- if (ssl->secure_renegotiation) {
- if (ssl->options.side == WOLFSSL_CLIENT_END)
- XMEMCPY(ssl->secure_renegotiation->client_verify_data, hashes,
- TLS_FINISHED_SZ);
- else
- XMEMCPY(ssl->secure_renegotiation->server_verify_data, hashes,
- TLS_FINISHED_SZ);
- }
- #endif
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- if ((ret = DtlsMsgPoolSave(ssl, input, headerSz + finishedSz)) != 0)
- return ret;
- }
- #endif
- sendSz = BuildMessage(ssl, output, outputSz, input, headerSz + finishedSz,
- handshake, 1, 0, 0);
- if (sendSz < 0)
- return BUILD_MSG_ERROR;
- if (!ssl->options.resuming) {
- #ifndef NO_SESSION_CACHE
- AddSession(ssl); /* just try */
- #endif
- if (ssl->options.side == WOLFSSL_SERVER_END) {
- #ifdef OPENSSL_EXTRA
- ssl->options.serverState = SERVER_FINISHED_COMPLETE;
- ssl->cbmode = SSL_CB_MODE_WRITE;
- if (ssl->CBIS != NULL)
- ssl->CBIS(ssl, SSL_CB_HANDSHAKE_DONE, SSL_SUCCESS);
- #endif
- ssl->options.handShakeState = HANDSHAKE_DONE;
- ssl->options.handShakeDone = 1;
- }
- }
- else {
- if (ssl->options.side == WOLFSSL_CLIENT_END) {
- #ifdef OPENSSL_EXTRA
- ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
- ssl->cbmode = SSL_CB_MODE_WRITE;
- if (ssl->CBIS != NULL)
- ssl->CBIS(ssl, SSL_CB_HANDSHAKE_DONE, SSL_SUCCESS);
- #endif
- ssl->options.handShakeState = HANDSHAKE_DONE;
- ssl->options.handShakeDone = 1;
- }
- }
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
- if (ssl->toInfoOn)
- AddPacketInfo(ssl, "Finished", handshake, output, sendSz,
- WRITE_PROTO, ssl->heap);
- #endif
- ssl->buffers.outputBuffer.length += sendSz;
- ret = SendBuffered(ssl);
- WOLFSSL_LEAVE("SendFinished", ret);
- WOLFSSL_END(WC_FUNC_FINISHED_SEND);
- return ret;
- }
- #endif /* WOLFSSL_NO_TLS12 */
- #ifndef NO_WOLFSSL_SERVER
- #if (!defined(WOLFSSL_NO_TLS12) && \
- (defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
- defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))) || \
- (defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST))
- /* Parses and decodes the certificate then initializes "request". In the case
- * of !ssl->buffers.weOwnCert, ssl->ctx->certOcspRequest gets set to "request".
- *
- * Returns 0 on success
- */
- static int CreateOcspRequest(WOLFSSL* ssl, OcspRequest* request,
- DecodedCert* cert, byte* certData, word32 length)
- {
- int ret;
- if (request != NULL)
- XMEMSET(request, 0, sizeof(OcspRequest));
- InitDecodedCert(cert, certData, length, ssl->heap);
- /* TODO: Setup async support here */
- ret = ParseCertRelative(cert, CERT_TYPE, VERIFY, ssl->ctx->cm);
- if (ret != 0) {
- WOLFSSL_MSG("ParseCert failed");
- }
- if (ret == 0)
- ret = InitOcspRequest(request, cert, 0, ssl->heap);
- if (ret == 0) {
- /* make sure ctx OCSP request is updated */
- if (!ssl->buffers.weOwnCert) {
- wolfSSL_Mutex* ocspLock = &ssl->ctx->cm->ocsp_stapling->ocspLock;
- if (wc_LockMutex(ocspLock) == 0) {
- if (ssl->ctx->certOcspRequest == NULL)
- ssl->ctx->certOcspRequest = request;
- wc_UnLockMutex(ocspLock);
- }
- }
- }
- FreeDecodedCert(cert);
- return ret;
- }
- /* Creates OCSP response and places it in variable "response". Memory
- * management for "buffer* response" is up to the caller.
- *
- * Also creates an OcspRequest in the case that ocspRequest is null or that
- * ssl->buffers.weOwnCert is set. In those cases managing ocspRequest free'ing
- * is up to the caller. NOTE: in OcspCreateRequest ssl->ctx->certOcspRequest can
- * be set to point to "ocspRequest" and it then should not be free'd since
- * wolfSSL_CTX_free will take care of it.
- *
- * Returns 0 on success
- */
- int CreateOcspResponse(WOLFSSL* ssl, OcspRequest** ocspRequest,
- buffer* response)
- {
- int ret = 0;
- OcspRequest* request = NULL;
- byte createdRequest = 0;
- if (ssl == NULL || ocspRequest == NULL || response == NULL)
- return BAD_FUNC_ARG;
- XMEMSET(response, 0, sizeof(*response));
- request = *ocspRequest;
- /* unable to fetch status. skip. */
- if (ssl->ctx->cm == NULL || ssl->ctx->cm->ocspStaplingEnabled == 0)
- return 0;
- if (request == NULL || ssl->buffers.weOwnCert) {
- DerBuffer* der = ssl->buffers.certificate;
- #ifdef WOLFSSL_SMALL_STACK
- DecodedCert* cert = NULL;
- #else
- DecodedCert cert[1];
- #endif
- /* unable to fetch status. skip. */
- if (der->buffer == NULL || der->length == 0)
- return 0;
- #ifdef WOLFSSL_SMALL_STACK
- cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
- DYNAMIC_TYPE_DCERT);
- if (cert == NULL)
- return MEMORY_E;
- #endif
- request = (OcspRequest*)XMALLOC(sizeof(OcspRequest), ssl->heap,
- DYNAMIC_TYPE_OCSP_REQUEST);
- if (request == NULL)
- ret = MEMORY_E;
- createdRequest = 1;
- if (ret == 0) {
- ret = CreateOcspRequest(ssl, request, cert, der->buffer,
- der->length);
- }
- if (ret != 0) {
- XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
- request = NULL;
- }
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
- #endif
- }
- if (ret == 0) {
- request->ssl = ssl;
- ret = CheckOcspRequest(ssl->ctx->cm->ocsp_stapling, request, response);
- /* Suppressing, not critical */
- if (ret == OCSP_CERT_REVOKED ||
- ret == OCSP_CERT_UNKNOWN ||
- ret == OCSP_LOOKUP_FAIL) {
- ret = 0;
- }
- }
- /* free request up if error case found otherwise return it */
- if (ret != 0 && createdRequest) {
- FreeOcspRequest(request);
- XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
- }
- if (ret == 0)
- *ocspRequest = request;
- return ret;
- }
- #endif
- #endif /* !NO_WOLFSSL_SERVER */
- #ifndef WOLFSSL_NO_TLS12
- #ifndef NO_CERTS
- #if !defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH)
- /* handle generation of certificate (11) */
- int SendCertificate(WOLFSSL* ssl)
- {
- int ret = 0;
- word32 certSz, certChainSz, headerSz, listSz, payloadSz;
- word32 length, maxFragment;
- WOLFSSL_START(WC_FUNC_CERTIFICATE_SEND);
- WOLFSSL_ENTER("SendCertificate");
- if (ssl->options.usingPSK_cipher || ssl->options.usingAnon_cipher)
- return 0; /* not needed */
- if (ssl->options.sendVerify == SEND_BLANK_CERT) {
- #ifdef OPENSSL_EXTRA
- if (ssl->version.major == SSLv3_MAJOR
- && ssl->version.minor == SSLv3_MINOR){
- SendAlert(ssl, alert_warning, no_certificate);
- return 0;
- } else {
- #endif
- certSz = 0;
- certChainSz = 0;
- headerSz = CERT_HEADER_SZ;
- length = CERT_HEADER_SZ;
- listSz = 0;
- #ifdef OPENSSL_EXTRA
- }
- #endif
- }
- else {
- if (!ssl->buffers.certificate) {
- WOLFSSL_MSG("Send Cert missing certificate buffer");
- return BUFFER_ERROR;
- }
- certSz = ssl->buffers.certificate->length;
- headerSz = 2 * CERT_HEADER_SZ;
- /* list + cert size */
- length = certSz + headerSz;
- listSz = certSz + CERT_HEADER_SZ;
- /* may need to send rest of chain, already has leading size(s) */
- if (certSz && ssl->buffers.certChain) {
- certChainSz = ssl->buffers.certChain->length;
- length += certChainSz;
- listSz += certChainSz;
- }
- else
- certChainSz = 0;
- }
- payloadSz = length;
- if (ssl->fragOffset != 0)
- length -= (ssl->fragOffset + headerSz);
- maxFragment = MAX_RECORD_SIZE;
- if (ssl->options.dtls) {
- #ifdef WOLFSSL_DTLS
- /* The 100 bytes is used to account for the UDP and IP headers.
- It can also include the record padding and MAC if the
- SendCertificate is called for a secure renegotiation. */
- maxFragment = MAX_MTU - DTLS_RECORD_HEADER_SZ
- - DTLS_HANDSHAKE_HEADER_SZ - 100;
- #endif /* WOLFSSL_DTLS */
- }
- maxFragment = wolfSSL_GetMaxRecordSize(ssl, maxFragment);
- while (length > 0 && ret == 0) {
- byte* output = NULL;
- word32 fragSz = 0;
- word32 i = RECORD_HEADER_SZ;
- int sendSz = RECORD_HEADER_SZ;
- if (!ssl->options.dtls) {
- if (ssl->fragOffset == 0) {
- if (headerSz + certSz + certChainSz <=
- maxFragment - HANDSHAKE_HEADER_SZ) {
- fragSz = headerSz + certSz + certChainSz;
- }
- else {
- fragSz = maxFragment - HANDSHAKE_HEADER_SZ;
- }
- sendSz += fragSz + HANDSHAKE_HEADER_SZ;
- i += HANDSHAKE_HEADER_SZ;
- }
- else {
- fragSz = min(length, maxFragment);
- sendSz += fragSz;
- }
- if (IsEncryptionOn(ssl, 1))
- sendSz += MAX_MSG_EXTRA;
- }
- else {
- #ifdef WOLFSSL_DTLS
- fragSz = min(length, maxFragment);
- sendSz += fragSz + DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA
- + HANDSHAKE_HEADER_SZ;
- i += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA
- + HANDSHAKE_HEADER_SZ;
- #endif
- }
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
- return ret;
- /* get output buffer */
- output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- if (ssl->fragOffset == 0) {
- if (!ssl->options.dtls) {
- AddFragHeaders(output, fragSz, 0, payloadSz, certificate, ssl);
- if (!IsEncryptionOn(ssl, 1))
- HashOutputRaw(ssl, output + RECORD_HEADER_SZ,
- HANDSHAKE_HEADER_SZ);
- }
- else {
- #ifdef WOLFSSL_DTLS
- AddHeaders(output, payloadSz, certificate, ssl);
- if (!IsEncryptionOn(ssl, 1))
- HashOutputRaw(ssl,
- output + RECORD_HEADER_SZ + DTLS_RECORD_EXTRA,
- HANDSHAKE_HEADER_SZ + DTLS_HANDSHAKE_EXTRA);
- /* Adding the headers increments these, decrement them for
- * actual message header. */
- ssl->keys.dtls_handshake_number--;
- AddFragHeaders(output, fragSz, 0, payloadSz, certificate, ssl);
- ssl->keys.dtls_handshake_number--;
- #endif /* WOLFSSL_DTLS */
- }
- /* list total */
- c32to24(listSz, output + i);
- if (!IsEncryptionOn(ssl, 1))
- HashOutputRaw(ssl, output + i, CERT_HEADER_SZ);
- i += CERT_HEADER_SZ;
- length -= CERT_HEADER_SZ;
- fragSz -= CERT_HEADER_SZ;
- if (certSz) {
- c32to24(certSz, output + i);
- if (!IsEncryptionOn(ssl, 1))
- HashOutputRaw(ssl, output + i, CERT_HEADER_SZ);
- i += CERT_HEADER_SZ;
- length -= CERT_HEADER_SZ;
- fragSz -= CERT_HEADER_SZ;
- if (!IsEncryptionOn(ssl, 1)) {
- HashOutputRaw(ssl, ssl->buffers.certificate->buffer, certSz);
- if (certChainSz)
- HashOutputRaw(ssl, ssl->buffers.certChain->buffer,
- certChainSz);
- }
- }
- }
- else {
- if (!ssl->options.dtls) {
- AddRecordHeader(output, fragSz, handshake, ssl);
- }
- else {
- #ifdef WOLFSSL_DTLS
- AddFragHeaders(output, fragSz, ssl->fragOffset + headerSz,
- payloadSz, certificate, ssl);
- ssl->keys.dtls_handshake_number--;
- #endif /* WOLFSSL_DTLS */
- }
- }
- /* member */
- if (certSz && ssl->fragOffset < certSz) {
- word32 copySz = min(certSz - ssl->fragOffset, fragSz);
- XMEMCPY(output + i,
- ssl->buffers.certificate->buffer + ssl->fragOffset, copySz);
- i += copySz;
- ssl->fragOffset += copySz;
- length -= copySz;
- fragSz -= copySz;
- }
- if (certChainSz && fragSz) {
- word32 copySz = min(certChainSz + certSz - ssl->fragOffset, fragSz);
- XMEMCPY(output + i,
- ssl->buffers.certChain->buffer + ssl->fragOffset - certSz,
- copySz);
- i += copySz;
- ssl->fragOffset += copySz;
- length -= copySz;
- }
- if (IsEncryptionOn(ssl, 1)) {
- byte* input = NULL;
- int inputSz = i - RECORD_HEADER_SZ; /* build msg adds rec hdr */
- if (inputSz < 0) {
- WOLFSSL_MSG("Send Cert bad inputSz");
- return BUFFER_E;
- }
- if (inputSz > 0) { /* clang thinks could be zero, let's help */
- input = (byte*)XMALLOC(inputSz, ssl->heap,
- DYNAMIC_TYPE_IN_BUFFER);
- if (input == NULL)
- return MEMORY_E;
- XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
- }
- sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
- handshake, 1, 0, 0);
- if (inputSz > 0)
- XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (sendSz < 0)
- return sendSz;
- }
- else {
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls)
- DtlsSEQIncrement(ssl, CUR_ORDER);
- #endif
- }
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- if ((ret = DtlsMsgPoolSave(ssl, output, sendSz)) != 0)
- return ret;
- }
- #endif
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "Certificate");
- if (ssl->toInfoOn)
- AddPacketInfo(ssl, "Certificate", handshake, output, sendSz,
- WRITE_PROTO, ssl->heap);
- #endif
- ssl->buffers.outputBuffer.length += sendSz;
- if (!ssl->options.groupMessages)
- ret = SendBuffered(ssl);
- }
- if (ret != WANT_WRITE) {
- /* Clean up the fragment offset. */
- ssl->fragOffset = 0;
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls)
- ssl->keys.dtls_handshake_number++;
- #endif
- if (ssl->options.side == WOLFSSL_SERVER_END){
- ssl->options.serverState = SERVER_CERT_COMPLETE;
- }
- }
- WOLFSSL_LEAVE("SendCertificate", ret);
- WOLFSSL_END(WC_FUNC_CERTIFICATE_SEND);
- return ret;
- }
- #endif /* !NO_WOLFSSL_SERVER || !WOLFSSL_NO_CLIENT_AUTH */
- /* handle generation of certificate_request (13) */
- int SendCertificateRequest(WOLFSSL* ssl)
- {
- byte *output;
- int ret;
- int sendSz;
- word32 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
- word32 dnLen = 0;
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
- WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
- #endif
- int typeTotal = 1; /* only 1 for now */
- int reqSz = ENUM_LEN + typeTotal + REQ_HEADER_SZ; /* add auth later */
- WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_SEND);
- WOLFSSL_ENTER("SendCertificateRequest");
- if (IsAtLeastTLSv1_2(ssl))
- reqSz += LENGTH_SZ + ssl->suites->hashSigAlgoSz;
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
- /* Certificate Authorities */
- names = ssl->ctx->ca_names;
- while (names != NULL) {
- byte seq[MAX_SEQ_SZ];
- /* 16-bit length | SEQ | Len | DER of name */
- dnLen += OPAQUE16_LEN + SetSequence(names->data.name->rawLen, seq) +
- names->data.name->rawLen;
- names = names->next;
- }
- reqSz += dnLen;
- #endif
- if (ssl->options.usingPSK_cipher || ssl->options.usingAnon_cipher)
- return 0; /* not needed */
- sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ + reqSz;
- if (!ssl->options.dtls) {
- if (IsEncryptionOn(ssl, 1))
- sendSz += MAX_MSG_EXTRA;
- }
- else {
- #ifdef WOLFSSL_DTLS
- sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- i += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- #endif
- }
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
- return ret;
- /* get output buffer */
- output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- AddHeaders(output, reqSz, certificate_request, ssl);
- /* write to output */
- output[i++] = (byte)typeTotal; /* # of types */
- #ifdef HAVE_ECC
- if ((ssl->options.cipherSuite0 == ECC_BYTE ||
- ssl->options.cipherSuite0 == CHACHA_BYTE) &&
- ssl->specs.sig_algo == ecc_dsa_sa_algo) {
- output[i++] = ecdsa_sign;
- } else
- #endif /* HAVE_ECC */
- {
- output[i++] = rsa_sign;
- }
- /* supported hash/sig */
- if (IsAtLeastTLSv1_2(ssl)) {
- c16toa(ssl->suites->hashSigAlgoSz, &output[i]);
- i += OPAQUE16_LEN;
- XMEMCPY(&output[i],
- ssl->suites->hashSigAlgo, ssl->suites->hashSigAlgoSz);
- i += ssl->suites->hashSigAlgoSz;
- }
- /* Certificate Authorities */
- c16toa((word16)dnLen, &output[i]); /* auth's */
- i += REQ_HEADER_SZ;
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
- names = ssl->ctx->ca_names;
- while (names != NULL) {
- byte seq[MAX_SEQ_SZ];
- c16toa((word16)names->data.name->rawLen +
- SetSequence(names->data.name->rawLen, seq), &output[i]);
- i += OPAQUE16_LEN;
- i += SetSequence(names->data.name->rawLen, output + i);
- XMEMCPY(output + i, names->data.name->raw, names->data.name->rawLen);
- i += names->data.name->rawLen;
- names = names->next;
- }
- #endif
- (void)i;
- if (IsEncryptionOn(ssl, 1)) {
- byte* input;
- int inputSz = i - RECORD_HEADER_SZ; /* build msg adds rec hdr */
- input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (input == NULL)
- return MEMORY_E;
- XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
- sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
- handshake, 1, 0, 0);
- XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (sendSz < 0)
- return sendSz;
- } else {
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls)
- DtlsSEQIncrement(ssl, CUR_ORDER);
- if (IsDtlsNotSctpMode(ssl)) {
- if ((ret = DtlsMsgPoolSave(ssl, output, sendSz)) != 0)
- return ret;
- }
- #endif
- ret = HashOutput(ssl, output, sendSz, 0);
- if (ret != 0)
- return ret;
- }
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "CertificateRequest");
- if (ssl->toInfoOn)
- AddPacketInfo(ssl, "CertificateRequest", handshake, output, sendSz,
- WRITE_PROTO, ssl->heap);
- #endif
- ssl->buffers.outputBuffer.length += sendSz;
- if (ssl->options.groupMessages)
- ret = 0;
- else
- ret = SendBuffered(ssl);
- WOLFSSL_LEAVE("SendCertificateRequest", ret);
- WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
- return ret;
- }
- #ifndef NO_WOLFSSL_SERVER
- #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
- || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
- static int BuildCertificateStatus(WOLFSSL* ssl, byte type, buffer* status,
- byte count)
- {
- byte* output = NULL;
- word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
- word32 length = ENUM_LEN;
- int sendSz = 0;
- int ret = 0;
- int i = 0;
- WOLFSSL_ENTER("BuildCertificateStatus");
- switch (type) {
- case WOLFSSL_CSR2_OCSP_MULTI:
- length += OPAQUE24_LEN;
- FALL_THROUGH; /* followed by */
- case WOLFSSL_CSR2_OCSP:
- for (i = 0; i < count; i++)
- length += OPAQUE24_LEN + status[i].length;
- break;
- default:
- return 0;
- }
- sendSz = idx + length;
- if (ssl->keys.encryptionOn)
- sendSz += MAX_MSG_EXTRA;
- if ((ret = CheckAvailableSize(ssl, sendSz)) == 0) {
- output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- AddHeaders(output, length, certificate_status, ssl);
- output[idx++] = type;
- if (type == WOLFSSL_CSR2_OCSP_MULTI) {
- c32to24(length - (ENUM_LEN + OPAQUE24_LEN), output + idx);
- idx += OPAQUE24_LEN;
- }
- for (i = 0; i < count; i++) {
- c32to24(status[i].length, output + idx);
- idx += OPAQUE24_LEN;
- XMEMCPY(output + idx, status[i].buffer, status[i].length);
- idx += status[i].length;
- }
- if (IsEncryptionOn(ssl, 1)) {
- byte* input;
- int inputSz = idx - RECORD_HEADER_SZ;
- input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (input == NULL)
- return MEMORY_E;
- XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
- sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
- handshake, 1, 0, 0);
- XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (sendSz < 0)
- ret = sendSz;
- }
- else {
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls)
- DtlsSEQIncrement(ssl, CUR_ORDER);
- #endif
- ret = HashOutput(ssl, output, sendSz, 0);
- }
- #ifdef WOLFSSL_DTLS
- if (ret == 0 && IsDtlsNotSctpMode(ssl))
- ret = DtlsMsgPoolSave(ssl, output, sendSz);
- #endif
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ret == 0 && ssl->hsInfoOn)
- AddPacketName(ssl, "CertificateStatus");
- if (ret == 0 && ssl->toInfoOn)
- AddPacketInfo(ssl, "CertificateStatus", handshake, output, sendSz,
- WRITE_PROTO, ssl->heap);
- #endif
- if (ret == 0) {
- ssl->buffers.outputBuffer.length += sendSz;
- if (!ssl->options.groupMessages)
- ret = SendBuffered(ssl);
- }
- }
- WOLFSSL_LEAVE("BuildCertificateStatus", ret);
- return ret;
- }
- #endif
- #endif /* NO_WOLFSSL_SERVER */
- /* handle generation of certificate_status (22) */
- int SendCertificateStatus(WOLFSSL* ssl)
- {
- int ret = 0;
- byte status_type = 0;
- WOLFSSL_START(WC_FUNC_CERTIFICATE_STATUS_SEND);
- WOLFSSL_ENTER("SendCertificateStatus");
- (void) ssl;
- #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
- status_type = ssl->status_request;
- #endif
- #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
- status_type = status_type ? status_type : ssl->status_request_v2;
- #endif
- switch (status_type) {
- #ifndef NO_WOLFSSL_SERVER
- #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
- || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
- /* case WOLFSSL_CSR_OCSP: */
- case WOLFSSL_CSR2_OCSP:
- {
- OcspRequest* request = ssl->ctx->certOcspRequest;
- buffer response;
- ret = CreateOcspResponse(ssl, &request, &response);
- /* if a request was successfully created and not stored in
- * ssl->ctx then free it */
- if (ret == 0 && request != ssl->ctx->certOcspRequest) {
- FreeOcspRequest(request);
- XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
- request = NULL;
- }
- if (ret == 0 && response.buffer) {
- ret = BuildCertificateStatus(ssl, status_type, &response, 1);
- XFREE(response.buffer, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
- response.buffer = NULL;
- }
- break;
- }
- #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
- /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
- #if defined HAVE_CERTIFICATE_STATUS_REQUEST_V2
- case WOLFSSL_CSR2_OCSP_MULTI:
- {
- OcspRequest* request = ssl->ctx->certOcspRequest;
- buffer responses[1 + MAX_CHAIN_DEPTH];
- int i = 0;
- XMEMSET(responses, 0, sizeof(responses));
- ret = CreateOcspResponse(ssl, &request, &responses[0]);
- /* if a request was successfully created and not stored in
- * ssl->ctx then free it */
- if (ret == 0 && request != ssl->ctx->certOcspRequest) {
- FreeOcspRequest(request);
- XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
- request = NULL;
- }
- if (ret == 0 && (!ssl->ctx->chainOcspRequest[0]
- || ssl->buffers.weOwnCertChain)) {
- buffer der;
- word32 idx = 0;
- #ifdef WOLFSSL_SMALL_STACK
- DecodedCert* cert;
- #else
- DecodedCert cert[1];
- #endif
- #ifdef WOLFSSL_SMALL_STACK
- cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
- DYNAMIC_TYPE_DCERT);
- if (cert == NULL)
- return MEMORY_E;
- #endif
- request = (OcspRequest*)XMALLOC(sizeof(OcspRequest), ssl->heap,
- DYNAMIC_TYPE_OCSP_REQUEST);
- if (request == NULL) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
- #endif
- return MEMORY_E;
- }
- while (idx + OPAQUE24_LEN < ssl->buffers.certChain->length) {
- c24to32(ssl->buffers.certChain->buffer + idx, &der.length);
- idx += OPAQUE24_LEN;
- der.buffer = ssl->buffers.certChain->buffer + idx;
- idx += der.length;
- if (idx > ssl->buffers.certChain->length)
- break;
- ret = CreateOcspRequest(ssl, request, cert, der.buffer,
- der.length);
- if (ret == 0) {
- request->ssl = ssl;
- ret = CheckOcspRequest(ssl->ctx->cm->ocsp_stapling,
- request, &responses[i + 1]);
- /* Suppressing, not critical */
- if (ret == OCSP_CERT_REVOKED ||
- ret == OCSP_CERT_UNKNOWN ||
- ret == OCSP_LOOKUP_FAIL) {
- ret = 0;
- }
- i++;
- FreeOcspRequest(request);
- }
- }
- XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
- #endif
- }
- else {
- while (ret == 0 &&
- NULL != (request = ssl->ctx->chainOcspRequest[i])) {
- request->ssl = ssl;
- ret = CheckOcspRequest(ssl->ctx->cm->ocsp_stapling,
- request, &responses[++i]);
- /* Suppressing, not critical */
- if (ret == OCSP_CERT_REVOKED ||
- ret == OCSP_CERT_UNKNOWN ||
- ret == OCSP_LOOKUP_FAIL) {
- ret = 0;
- }
- }
- }
- if (responses[0].buffer) {
- if (ret == 0) {
- ret = BuildCertificateStatus(ssl, status_type, responses,
- (byte)i + 1);
- }
- for (i = 0; i < 1 + MAX_CHAIN_DEPTH; i++) {
- if (responses[i].buffer) {
- XFREE(responses[i].buffer, ssl->heap,
- DYNAMIC_TYPE_OCSP_REQUEST);
- }
- }
- }
- break;
- }
- #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
- #endif /* NO_WOLFSSL_SERVER */
- default:
- break;
- }
- WOLFSSL_LEAVE("SendCertificateStatus", ret);
- WOLFSSL_END(WC_FUNC_CERTIFICATE_STATUS_SEND);
- return ret;
- }
- #endif /* !NO_CERTS */
- #endif /* WOLFSSL_NO_TLS12 */
- /* If secure renegotiation is disabled, this will always return false.
- * Otherwise it checks to see if we are currently renegotiating. */
- static WC_INLINE int IsSCR(WOLFSSL* ssl)
- {
- #ifndef HAVE_SECURE_RENEGOTIATION
- (void)ssl;
- #else /* HAVE_SECURE_RENEGOTIATION */
- if (ssl->secure_renegotiation &&
- ssl->secure_renegotiation->enabled &&
- ssl->options.handShakeState != HANDSHAKE_DONE)
- return 1;
- #endif /* HAVE_SECURE_RENEGOTIATION */
- return 0;
- }
- int SendData(WOLFSSL* ssl, const void* data, int sz)
- {
- int sent = 0, /* plainText size */
- sendSz,
- ret,
- dtlsExtra = 0;
- int groupMsgs = 0;
- if (ssl->error == WANT_WRITE
- #ifdef WOLFSSL_ASYNC_CRYPT
- || ssl->error == WC_PENDING_E
- #endif
- ) {
- ssl->error = 0;
- }
- /* don't allow write after decrypt or mac error */
- if (ssl->error == VERIFY_MAC_ERROR || ssl->error == DECRYPT_ERROR) {
- /* For DTLS allow these possible errors and allow the session
- to continue despite them */
- if (ssl->options.dtls) {
- ssl->error = 0;
- }
- else {
- WOLFSSL_MSG("Not allowing write after decrypt or mac error");
- return WOLFSSL_FATAL_ERROR;
- }
- }
- #ifdef WOLFSSL_EARLY_DATA
- if (ssl->earlyData != no_early_data) {
- if (ssl->options.handShakeState == HANDSHAKE_DONE) {
- WOLFSSL_MSG("handshake complete, trying to send early data");
- return BUILD_MSG_ERROR;
- }
- #ifdef WOLFSSL_EARLY_DATA_GROUP
- groupMsgs = 1;
- #endif
- }
- else
- #endif
- if (ssl->options.handShakeState != HANDSHAKE_DONE && !IsSCR(ssl)) {
- int err;
- WOLFSSL_MSG("handshake not complete, trying to finish");
- if ( (err = wolfSSL_negotiate(ssl)) != WOLFSSL_SUCCESS) {
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* if async would block return WANT_WRITE */
- if (ssl->error == WC_PENDING_E) {
- return WOLFSSL_CBIO_ERR_WANT_WRITE;
- }
- #endif
- return err;
- }
- }
- /* last time system socket output buffer was full, try again to send */
- if (!groupMsgs && ssl->buffers.outputBuffer.length > 0) {
- WOLFSSL_MSG("output buffer was full, trying to send again");
- if ( (ssl->error = SendBuffered(ssl)) < 0) {
- WOLFSSL_ERROR(ssl->error);
- if (ssl->error == SOCKET_ERROR_E && (ssl->options.connReset ||
- ssl->options.isClosed)) {
- ssl->error = SOCKET_PEER_CLOSED_E;
- WOLFSSL_ERROR(ssl->error);
- return 0; /* peer reset or closed */
- }
- return ssl->error;
- }
- else {
- /* advance sent to previous sent + plain size just sent */
- sent = ssl->buffers.prevSent + ssl->buffers.plainSz;
- WOLFSSL_MSG("sent write buffered data");
- if (sent > sz) {
- WOLFSSL_MSG("error: write() after WANT_WRITE with short size");
- return ssl->error = BAD_FUNC_ARG;
- }
- }
- }
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- dtlsExtra = DTLS_RECORD_EXTRA;
- }
- #endif
- for (;;) {
- int len;
- byte* out;
- byte* sendBuffer = (byte*)data + sent; /* may switch on comp */
- int buffSz; /* may switch on comp */
- int outputSz;
- #ifdef HAVE_LIBZ
- byte comp[MAX_RECORD_SIZE + MAX_COMP_EXTRA];
- #endif
- if (sent == sz) break;
- len = wolfSSL_GetMaxRecordSize(ssl, sz - sent);
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- len = min(len, MAX_UDP_SIZE);
- }
- #endif
- buffSz = len;
- /* check for available size */
- outputSz = len + COMP_EXTRA + dtlsExtra + MAX_MSG_EXTRA;
- if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
- return ssl->error = ret;
- /* get output buffer */
- out = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- #ifdef HAVE_LIBZ
- if (ssl->options.usingCompression) {
- buffSz = myCompress(ssl, sendBuffer, buffSz, comp, sizeof(comp));
- if (buffSz < 0) {
- return buffSz;
- }
- sendBuffer = comp;
- }
- #endif
- if (!ssl->options.tls1_3) {
- sendSz = BuildMessage(ssl, out, outputSz, sendBuffer, buffSz,
- application_data, 0, 0, 1);
- }
- else {
- #ifdef WOLFSSL_TLS13
- sendSz = BuildTls13Message(ssl, out, outputSz, sendBuffer, buffSz,
- application_data, 0, 0, 1);
- #else
- sendSz = BUFFER_ERROR;
- #endif
- }
- if (sendSz < 0) {
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (sendSz == WC_PENDING_E)
- ssl->error = sendSz;
- #endif
- return BUILD_MSG_ERROR;
- }
- ssl->buffers.outputBuffer.length += sendSz;
- if ( (ssl->error = SendBuffered(ssl)) < 0) {
- WOLFSSL_ERROR(ssl->error);
- /* store for next call if WANT_WRITE or user embedSend() that
- doesn't present like WANT_WRITE */
- ssl->buffers.plainSz = len;
- ssl->buffers.prevSent = sent;
- if (ssl->error == SOCKET_ERROR_E && (ssl->options.connReset ||
- ssl->options.isClosed)) {
- ssl->error = SOCKET_PEER_CLOSED_E;
- WOLFSSL_ERROR(ssl->error);
- return 0; /* peer reset or closed */
- }
- return ssl->error;
- }
- sent += len;
- /* only one message per attempt */
- if (ssl->options.partialWrite == 1) {
- WOLFSSL_MSG("Partial Write on, only sending one record");
- break;
- }
- }
- return sent;
- }
- /* process input data */
- int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek)
- {
- int size;
- WOLFSSL_ENTER("ReceiveData()");
- /* reset error state */
- if (ssl->error == WANT_READ
- #ifdef WOLFSSL_ASYNC_CRYPT
- || ssl->error == WC_PENDING_E
- #endif
- ) {
- ssl->error = 0;
- }
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- /* In DTLS mode, we forgive some errors and allow the session
- * to continue despite them. */
- if (ssl->error == VERIFY_MAC_ERROR || ssl->error == DECRYPT_ERROR)
- ssl->error = 0;
- }
- #endif /* WOLFSSL_DTLS */
- if (ssl->error != 0 && ssl->error != WANT_WRITE) {
- WOLFSSL_MSG("User calling wolfSSL_read in error state, not allowed");
- return ssl->error;
- }
- #ifdef WOLFSSL_EARLY_DATA
- if (ssl->earlyData != no_early_data) {
- }
- else
- #endif
- if (ssl->options.handShakeState != HANDSHAKE_DONE) {
- int err;
- WOLFSSL_MSG("Handshake not complete, trying to finish");
- if ( (err = wolfSSL_negotiate(ssl)) != WOLFSSL_SUCCESS) {
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* if async would block return WANT_WRITE */
- if (ssl->error == WC_PENDING_E) {
- return WOLFSSL_CBIO_ERR_WANT_READ;
- }
- #endif
- return err;
- }
- }
- #ifdef HAVE_SECURE_RENEGOTIATION
- startScr:
- if (ssl->secure_renegotiation && ssl->secure_renegotiation->startScr) {
- int err;
- WOLFSSL_MSG("Need to start scr, server requested");
- if ( (err = wolfSSL_Rehandshake(ssl)) != WOLFSSL_SUCCESS)
- return err;
- ssl->secure_renegotiation->startScr = 0; /* only start once */
- }
- #endif
- while (ssl->buffers.clearOutputBuffer.length == 0) {
- if ( (ssl->error = ProcessReply(ssl)) < 0) {
- WOLFSSL_ERROR(ssl->error);
- if (ssl->error == ZERO_RETURN) {
- WOLFSSL_MSG("Zero return, no more data coming");
- return 0; /* no more data coming */
- }
- if (ssl->error == SOCKET_ERROR_E) {
- if (ssl->options.connReset || ssl->options.isClosed) {
- WOLFSSL_MSG("Peer reset or closed, connection done");
- ssl->error = SOCKET_PEER_CLOSED_E;
- WOLFSSL_ERROR(ssl->error);
- return 0; /* peer reset or closed */
- }
- }
- return ssl->error;
- }
- #ifdef HAVE_SECURE_RENEGOTIATION
- if (ssl->secure_renegotiation &&
- ssl->secure_renegotiation->startScr) {
- goto startScr;
- }
- #endif
- }
- if (sz < (int)ssl->buffers.clearOutputBuffer.length)
- size = sz;
- else
- size = ssl->buffers.clearOutputBuffer.length;
- XMEMCPY(output, ssl->buffers.clearOutputBuffer.buffer, size);
- if (peek == 0) {
- ssl->buffers.clearOutputBuffer.length -= size;
- ssl->buffers.clearOutputBuffer.buffer += size;
- }
- if (ssl->buffers.clearOutputBuffer.length == 0 &&
- ssl->buffers.inputBuffer.dynamicFlag)
- ShrinkInputBuffer(ssl, NO_FORCED_FREE);
- WOLFSSL_LEAVE("ReceiveData()", size);
- return size;
- }
- /* send alert message */
- int SendAlert(WOLFSSL* ssl, int severity, int type)
- {
- byte input[ALERT_SIZE];
- byte *output;
- int sendSz;
- int ret;
- int outputSz;
- int dtlsExtra = 0;
- WOLFSSL_ENTER("SendAlert");
- #ifdef HAVE_WRITE_DUP
- if (ssl->dupWrite && ssl->dupSide == READ_DUP_SIDE) {
- int notifyErr = 0;
- WOLFSSL_MSG("Read dup side cannot write alerts, notifying sibling");
- if (type == close_notify) {
- notifyErr = ZERO_RETURN;
- } else if (severity == alert_fatal) {
- notifyErr = FATAL_ERROR;
- }
- if (notifyErr != 0) {
- return NotifyWriteSide(ssl, notifyErr);
- }
- return 0;
- }
- #endif
- /* if sendalert is called again for nonblocking */
- if (ssl->options.sendAlertState != 0) {
- ret = SendBuffered(ssl);
- if (ret == 0)
- ssl->options.sendAlertState = 0;
- return ret;
- }
- #ifdef OPENSSL_EXTRA
- if (ssl->CBIS != NULL) {
- ssl->CBIS(ssl, SSL_CB_ALERT, type);
- }
- #endif
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls)
- dtlsExtra = DTLS_RECORD_EXTRA;
- #endif
- /* check for available size */
- outputSz = ALERT_SIZE + MAX_MSG_EXTRA + dtlsExtra;
- if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
- return ret;
- /* Check output buffer */
- if (ssl->buffers.outputBuffer.buffer == NULL)
- return BUFFER_E;
- /* get output buffer */
- output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- input[0] = (byte)severity;
- input[1] = (byte)type;
- ssl->alert_history.last_tx.code = type;
- ssl->alert_history.last_tx.level = severity;
- if (severity == alert_fatal) {
- ssl->options.isClosed = 1; /* Don't send close_notify */
- }
- /* only send encrypted alert if handshake actually complete, otherwise
- other side may not be able to handle it */
- if (IsEncryptionOn(ssl, 1) && (IsAtLeastTLSv1_3(ssl->version) ||
- ssl->options.handShakeDone)) {
- sendSz = BuildMessage(ssl, output, outputSz, input, ALERT_SIZE, alert,
- 0, 0, 0);
- }
- else {
- AddRecordHeader(output, ALERT_SIZE, alert, ssl);
- output += RECORD_HEADER_SZ;
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls)
- output += DTLS_RECORD_EXTRA;
- #endif
- XMEMCPY(output, input, ALERT_SIZE);
- sendSz = RECORD_HEADER_SZ + ALERT_SIZE;
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls)
- sendSz += DTLS_RECORD_EXTRA;
- #endif
- }
- if (sendSz < 0)
- return BUILD_MSG_ERROR;
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "Alert");
- if (ssl->toInfoOn)
- AddPacketInfo(ssl, "Alert", alert, output, sendSz, WRITE_PROTO,
- ssl->heap);
- #endif
- ssl->buffers.outputBuffer.length += sendSz;
- ssl->options.sendAlertState = 1;
- ret = SendBuffered(ssl);
- WOLFSSL_LEAVE("SendAlert", ret);
- return ret;
- }
- const char* wolfSSL_ERR_reason_error_string(unsigned long e)
- {
- #ifdef NO_ERROR_STRINGS
- (void)e;
- return "no support for error strings built in";
- #else
- int error = (int)e;
- /* pass to wolfCrypt */
- if (error < MAX_CODE_E && error > MIN_CODE_E) {
- return wc_GetErrorString(error);
- }
- switch (error) {
- #ifdef WOLFSSL_WPAS
- case 0 :
- return "ok";
- #endif
- case UNSUPPORTED_SUITE :
- return "unsupported cipher suite";
- case INPUT_CASE_ERROR :
- return "input state error";
- case PREFIX_ERROR :
- return "bad index to key rounds";
- case MEMORY_ERROR :
- return "out of memory";
- case VERIFY_FINISHED_ERROR :
- return "verify problem on finished";
- case VERIFY_MAC_ERROR :
- return "verify mac problem";
- case PARSE_ERROR :
- return "parse error on header";
- case SIDE_ERROR :
- return "wrong client/server type";
- case NO_PEER_CERT :
- return "peer didn't send cert";
- case UNKNOWN_HANDSHAKE_TYPE :
- return "weird handshake type";
- case SOCKET_ERROR_E :
- return "error state on socket";
- case SOCKET_NODATA :
- return "expected data, not there";
- case INCOMPLETE_DATA :
- return "don't have enough data to complete task";
- case UNKNOWN_RECORD_TYPE :
- return "unknown type in record hdr";
- case DECRYPT_ERROR :
- return "error during decryption";
- case FATAL_ERROR :
- return "received alert fatal error";
- case ENCRYPT_ERROR :
- return "error during encryption";
- case FREAD_ERROR :
- return "fread problem";
- case NO_PEER_KEY :
- return "need peer's key";
- case NO_PRIVATE_KEY :
- return "need the private key";
- case NO_DH_PARAMS :
- return "server missing DH params";
- case RSA_PRIVATE_ERROR :
- return "error during rsa priv op";
- case MATCH_SUITE_ERROR :
- return "can't match cipher suite";
- case COMPRESSION_ERROR :
- return "compression mismatch error";
- case BUILD_MSG_ERROR :
- return "build message failure";
- case BAD_HELLO :
- return "client hello malformed";
- case DOMAIN_NAME_MISMATCH :
- return "peer subject name mismatch";
- case IPADDR_MISMATCH :
- return "peer ip address mismatch";
- case WANT_READ :
- case WOLFSSL_ERROR_WANT_READ :
- return "non-blocking socket wants data to be read";
- case NOT_READY_ERROR :
- return "handshake layer not ready yet, complete first";
- case VERSION_ERROR :
- return "record layer version error";
- case WANT_WRITE :
- case WOLFSSL_ERROR_WANT_WRITE :
- return "non-blocking socket write buffer full";
- case BUFFER_ERROR :
- return "malformed buffer input error";
- case VERIFY_CERT_ERROR :
- return "verify problem on certificate";
- case VERIFY_SIGN_ERROR :
- return "verify problem based on signature";
- case CLIENT_ID_ERROR :
- return "psk client identity error";
- case SERVER_HINT_ERROR:
- return "psk server hint error";
- case PSK_KEY_ERROR:
- return "psk key callback error";
- case NTRU_KEY_ERROR:
- return "NTRU key error";
- case NTRU_DRBG_ERROR:
- return "NTRU drbg error";
- case NTRU_ENCRYPT_ERROR:
- return "NTRU encrypt error";
- case NTRU_DECRYPT_ERROR:
- return "NTRU decrypt error";
- case GETTIME_ERROR:
- return "gettimeofday() error";
- case GETITIMER_ERROR:
- return "getitimer() error";
- case SIGACT_ERROR:
- return "sigaction() error";
- case SETITIMER_ERROR:
- return "setitimer() error";
- case LENGTH_ERROR:
- return "record layer length error";
- case PEER_KEY_ERROR:
- return "cant decode peer key";
- case ZERO_RETURN:
- case WOLFSSL_ERROR_ZERO_RETURN:
- return "peer sent close notify alert";
- case ECC_CURVETYPE_ERROR:
- return "Bad ECC Curve Type or unsupported";
- case ECC_CURVE_ERROR:
- return "Bad ECC Curve or unsupported";
- case ECC_PEERKEY_ERROR:
- return "Bad ECC Peer Key";
- case ECC_MAKEKEY_ERROR:
- return "ECC Make Key failure";
- case ECC_EXPORT_ERROR:
- return "ECC Export Key failure";
- case ECC_SHARED_ERROR:
- return "ECC DHE shared failure";
- case NOT_CA_ERROR:
- return "Not a CA by basic constraint error";
- case HTTP_TIMEOUT:
- return "HTTP timeout for OCSP or CRL req";
- case BAD_CERT_MANAGER_ERROR:
- return "Bad Cert Manager error";
- case OCSP_CERT_REVOKED:
- return "OCSP Cert revoked";
- case CRL_CERT_REVOKED:
- return "CRL Cert revoked";
- case CRL_MISSING:
- return "CRL missing, not loaded";
- case MONITOR_SETUP_E:
- return "CRL monitor setup error";
- case THREAD_CREATE_E:
- return "Thread creation problem";
- case OCSP_NEED_URL:
- return "OCSP need URL";
- case OCSP_CERT_UNKNOWN:
- return "OCSP Cert unknown";
- case OCSP_LOOKUP_FAIL:
- return "OCSP Responder lookup fail";
- case MAX_CHAIN_ERROR:
- return "Maximum Chain Depth Exceeded";
- case COOKIE_ERROR:
- return "DTLS Cookie Error";
- case SEQUENCE_ERROR:
- return "DTLS Sequence Error";
- case SUITES_ERROR:
- return "Suites Pointer Error";
- case OUT_OF_ORDER_E:
- return "Out of order message, fatal";
- case BAD_KEA_TYPE_E:
- return "Bad KEA type found";
- case SANITY_CIPHER_E:
- return "Sanity check on ciphertext failed";
- case RECV_OVERFLOW_E:
- return "Receive callback returned more than requested";
- case GEN_COOKIE_E:
- return "Generate Cookie Error";
- case NO_PEER_VERIFY:
- return "Need peer certificate verify Error";
- case FWRITE_ERROR:
- return "fwrite Error";
- case CACHE_MATCH_ERROR:
- return "Cache restore header match Error";
- case UNKNOWN_SNI_HOST_NAME_E:
- return "Unrecognized host name Error";
- case UNKNOWN_MAX_FRAG_LEN_E:
- return "Unrecognized max frag len Error";
- case KEYUSE_SIGNATURE_E:
- return "Key Use digitalSignature not set Error";
- case KEYUSE_ENCIPHER_E:
- return "Key Use keyEncipherment not set Error";
- case EXTKEYUSE_AUTH_E:
- return "Ext Key Use server/client auth not set Error";
- case SEND_OOB_READ_E:
- return "Send Callback Out of Bounds Read Error";
- case SECURE_RENEGOTIATION_E:
- return "Invalid Renegotiation Error";
- case SESSION_TICKET_LEN_E:
- return "Session Ticket Too Long Error";
- case SESSION_TICKET_EXPECT_E:
- return "Session Ticket Error";
- case SESSION_SECRET_CB_E:
- return "Session Secret Callback Error";
- case NO_CHANGE_CIPHER_E:
- return "Finished received from peer before Change Cipher Error";
- case SANITY_MSG_E:
- return "Sanity Check on message order Error";
- case DUPLICATE_MSG_E:
- return "Duplicate HandShake message Error";
- case SNI_UNSUPPORTED:
- return "Protocol version does not support SNI Error";
- case SOCKET_PEER_CLOSED_E:
- return "Peer closed underlying transport Error";
- case BAD_TICKET_KEY_CB_SZ:
- return "Bad user session ticket key callback Size Error";
- case BAD_TICKET_MSG_SZ:
- return "Bad session ticket message Size Error";
- case BAD_TICKET_ENCRYPT:
- return "Bad user ticket callback encrypt Error";
- case DH_KEY_SIZE_E:
- return "DH key too small Error";
- case SNI_ABSENT_ERROR:
- return "No Server Name Indication extension Error";
- case RSA_SIGN_FAULT:
- return "RSA Signature Fault Error";
- case HANDSHAKE_SIZE_ERROR:
- return "Handshake message too large Error";
- case UNKNOWN_ALPN_PROTOCOL_NAME_E:
- return "Unrecognized protocol name Error";
- case BAD_CERTIFICATE_STATUS_ERROR:
- return "Bad Certificate Status Message Error";
- case OCSP_INVALID_STATUS:
- return "Invalid OCSP Status Error";
- case OCSP_WANT_READ:
- return "OCSP nonblock wants read";
- case RSA_KEY_SIZE_E:
- return "RSA key too small";
- case ECC_KEY_SIZE_E:
- return "ECC key too small";
- case DTLS_EXPORT_VER_E:
- return "Version needs updated after code change or version mismatch";
- case INPUT_SIZE_E:
- return "Input size too large Error";
- case CTX_INIT_MUTEX_E:
- return "Initialize ctx mutex error";
- case EXT_MASTER_SECRET_NEEDED_E:
- return "Extended Master Secret must be enabled to resume EMS session";
- case DTLS_POOL_SZ_E:
- return "Maximum DTLS pool size exceeded";
- case DECODE_E:
- return "Decode handshake message error";
- case WRITE_DUP_READ_E:
- return "Write dup write side can't read error";
- case WRITE_DUP_WRITE_E:
- return "Write dup read side can't write error";
- case INVALID_CERT_CTX_E:
- return "Certificate context does not match request or not empty";
- case BAD_KEY_SHARE_DATA:
- return "The Key Share data contains group that wasn't in Client Hello";
- case MISSING_HANDSHAKE_DATA:
- return "The handshake message is missing required data";
- case BAD_BINDER:
- return "Binder value does not match value server calculated";
- case EXT_NOT_ALLOWED:
- return "Extension type not allowed in handshake message type";
- case INVALID_PARAMETER:
- return "The security parameter is invalid";
- case UNSUPPORTED_EXTENSION:
- return "TLS Extension not requested by the client";
- case PRF_MISSING:
- return "Pseudo-random function is not enabled";
- case KEY_SHARE_ERROR:
- return "Key share extension did not contain a valid named group";
- case POST_HAND_AUTH_ERROR:
- return "Client will not do post handshake authentication";
- case HRR_COOKIE_ERROR:
- return "Cookie does not match one sent in HelloRetryRequest";
- case MCAST_HIGHWATER_CB_E:
- return "Multicast highwater callback returned error";
- case ALERT_COUNT_E:
- return "Alert Count exceeded error";
- case EXT_MISSING:
- return "Required TLS extension missing";
- case DTLS_RETX_OVER_TX:
- return "DTLS interrupting flight transmit with retransmit";
- case DH_PARAMS_NOT_FFDHE_E:
- return "Server DH parameters were not from the FFDHE set as required";
- case TCA_INVALID_ID_TYPE:
- return "TLS Extension Trusted CA ID type invalid";
- case TCA_ABSENT_ERROR:
- return "TLS Extension Trusted CA ID response absent";
- case TSIP_MAC_DIGSZ_E:
- return "TSIP MAC size invalid, must be sized for SHA-1 or SHA-256";
- case CLIENT_CERT_CB_ERROR:
- return "Error importing client cert or key from callback";
- case SSL_SHUTDOWN_ALREADY_DONE_E:
- return "Shutdown has already occurred";
- case TLS13_SECRET_CB_E:
- return "TLS1.3 Secret Callback Error";
- default :
- return "unknown error number";
- }
- #endif /* NO_ERROR_STRINGS */
- }
- void SetErrorString(int error, char* str)
- {
- XSTRNCPY(str, wolfSSL_ERR_reason_error_string(error), WOLFSSL_MAX_ERROR_SZ);
- str[WOLFSSL_MAX_ERROR_SZ-1] = 0;
- }
- #ifndef NO_ERROR_STRINGS
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
- #define SUITE_INFO(x,y,z,w,v,u) {(x),(y),(z),(w),(v),(u)}
- #else
- #define SUITE_INFO(x,y,z,w,v,u) {(x),(y),(z),(w)}
- #endif
- #else
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
- #define SUITE_INFO(x,y,z,w,v,u) {(x),(z),(w),(v),(u)}
- #else
- #define SUITE_INFO(x,y,z,w,v,u) {(x),(z),(w)}
- #endif
- #endif
- static const CipherSuiteInfo cipher_names[] =
- {
- #ifdef BUILD_TLS_AES_128_GCM_SHA256
- SUITE_INFO("TLS13-AES128-GCM-SHA256","TLS_AES_128_GCM_SHA256",TLS13_BYTE,TLS_AES_128_GCM_SHA256, TLSv1_3_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_AES_256_GCM_SHA384
- SUITE_INFO("TLS13-AES256-GCM-SHA384","TLS_AES_256_GCM_SHA384",TLS13_BYTE,TLS_AES_256_GCM_SHA384, TLSv1_3_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_CHACHA20_POLY1305_SHA256
- SUITE_INFO("TLS13-CHACHA20-POLY1305-SHA256","TLS_CHACHA20_POLY1305_SHA256",TLS13_BYTE,TLS_CHACHA20_POLY1305_SHA256, TLSv1_3_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_AES_128_CCM_SHA256
- SUITE_INFO("TLS13-AES128-CCM-SHA256","TLS_AES_128_CCM_SHA256",TLS13_BYTE,TLS_AES_128_CCM_SHA256, TLSv1_3_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_AES_128_CCM_8_SHA256
- SUITE_INFO("TLS13-AES128-CCM-8-SHA256","TLS_AES_128_CCM_8_SHA256",TLS13_BYTE,TLS_AES_128_CCM_8_SHA256,TLSv1_3_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_SHA256_SHA256
- SUITE_INFO("TLS13-SHA256-SHA256","TLS_SHA256_SHA256",ECC_BYTE,TLS_SHA256_SHA256,TLSv1_3_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_SHA384_SHA384
- SUITE_INFO("TLS13-SHA384-SHA384","TLS_SHA384_SHA384",ECC_BYTE,TLS_SHA384_SHA384,TLSv1_3_MINOR, SSLv3_MAJOR),
- #endif
- #ifndef WOLFSSL_NO_TLS12
- #ifdef BUILD_SSL_RSA_WITH_RC4_128_SHA
- SUITE_INFO("RC4-SHA","SSL_RSA_WITH_RC4_128_SHA",CIPHER_BYTE,SSL_RSA_WITH_RC4_128_SHA,SSLv3_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_SSL_RSA_WITH_RC4_128_MD5
- SUITE_INFO("RC4-MD5","SSL_RSA_WITH_RC4_128_MD5",CIPHER_BYTE,SSL_RSA_WITH_RC4_128_MD5,SSLv3_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA
- SUITE_INFO("DES-CBC3-SHA","SSL_RSA_WITH_3DES_EDE_CBC_SHA",CIPHER_BYTE,SSL_RSA_WITH_3DES_EDE_CBC_SHA,SSLv3_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_128_CBC_SHA
- SUITE_INFO("AES128-SHA","TLS_RSA_WITH_AES_128_CBC_SHA",CIPHER_BYTE,TLS_RSA_WITH_AES_128_CBC_SHA,SSLv3_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_256_CBC_SHA
- SUITE_INFO("AES256-SHA","TLS_RSA_WITH_AES_256_CBC_SHA",CIPHER_BYTE,TLS_RSA_WITH_AES_256_CBC_SHA,SSLv3_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_NULL_MD5
- SUITE_INFO("NULL-MD5","TLS_RSA_WITH_NULL_MD5",CIPHER_BYTE,TLS_RSA_WITH_NULL_MD5,SSLv3_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_NULL_SHA
- SUITE_INFO("NULL-SHA","TLS_RSA_WITH_NULL_SHA",CIPHER_BYTE,TLS_RSA_WITH_NULL_SHA,SSLv3_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_NULL_SHA256
- SUITE_INFO("NULL-SHA256","TLS_RSA_WITH_NULL_SHA256",CIPHER_BYTE,TLS_RSA_WITH_NULL_SHA256,TLSv1_2_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA
- SUITE_INFO("DHE-RSA-AES128-SHA","TLS_DHE_RSA_WITH_AES_128_CBC_SHA",CIPHER_BYTE,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,SSLv3_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
- SUITE_INFO("DHE-RSA-AES256-SHA","TLS_DHE_RSA_WITH_AES_256_CBC_SHA",CIPHER_BYTE,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,SSLv3_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
- SUITE_INFO("DHE-PSK-AES256-GCM-SHA384","TLS_DHE_PSK_WITH_AES_256_GCM_SHA384",CIPHER_BYTE,TLS_DHE_PSK_WITH_AES_256_GCM_SHA384,TLSv1_2_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
- SUITE_INFO("DHE-PSK-AES128-GCM-SHA256","TLS_DHE_PSK_WITH_AES_128_GCM_SHA256",CIPHER_BYTE,TLS_DHE_PSK_WITH_AES_128_GCM_SHA256,TLSv1_2_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_256_GCM_SHA384
- SUITE_INFO("PSK-AES256-GCM-SHA384","TLS_PSK_WITH_AES_256_GCM_SHA384",CIPHER_BYTE,TLS_PSK_WITH_AES_256_GCM_SHA384,TLSv1_2_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_128_GCM_SHA256
- SUITE_INFO("PSK-AES128-GCM-SHA256","TLS_PSK_WITH_AES_128_GCM_SHA256",CIPHER_BYTE,TLS_PSK_WITH_AES_128_GCM_SHA256,TLSv1_2_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
- SUITE_INFO("DHE-PSK-AES256-CBC-SHA384","TLS_DHE_PSK_WITH_AES_256_CBC_SHA384",CIPHER_BYTE,TLS_DHE_PSK_WITH_AES_256_CBC_SHA384,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
- SUITE_INFO("DHE-PSK-AES128-CBC-SHA256","TLS_DHE_PSK_WITH_AES_128_CBC_SHA256",CIPHER_BYTE,TLS_DHE_PSK_WITH_AES_128_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA384
- SUITE_INFO("PSK-AES256-CBC-SHA384","TLS_PSK_WITH_AES_256_CBC_SHA384",CIPHER_BYTE,TLS_PSK_WITH_AES_256_CBC_SHA384,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA256
- SUITE_INFO("PSK-AES128-CBC-SHA256","TLS_PSK_WITH_AES_128_CBC_SHA256",CIPHER_BYTE,TLS_PSK_WITH_AES_128_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA
- SUITE_INFO("PSK-AES128-CBC-SHA","TLS_PSK_WITH_AES_128_CBC_SHA",CIPHER_BYTE,TLS_PSK_WITH_AES_128_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA
- SUITE_INFO("PSK-AES256-CBC-SHA","TLS_PSK_WITH_AES_256_CBC_SHA",CIPHER_BYTE,TLS_PSK_WITH_AES_256_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CCM
- SUITE_INFO("DHE-PSK-AES128-CCM","TLS_DHE_PSK_WITH_AES_128_CCM",ECC_BYTE,TLS_DHE_PSK_WITH_AES_128_CCM,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_CCM
- SUITE_INFO("DHE-PSK-AES256-CCM","TLS_DHE_PSK_WITH_AES_256_CCM",ECC_BYTE,TLS_DHE_PSK_WITH_AES_256_CCM,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM
- SUITE_INFO("PSK-AES128-CCM","TLS_PSK_WITH_AES_128_CCM",ECC_BYTE,TLS_PSK_WITH_AES_128_CCM,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_256_CCM
- SUITE_INFO("PSK-AES256-CCM","TLS_PSK_WITH_AES_256_CCM",ECC_BYTE,TLS_PSK_WITH_AES_256_CCM,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM_8
- SUITE_INFO("PSK-AES128-CCM-8","TLS_PSK_WITH_AES_128_CCM_8",ECC_BYTE,TLS_PSK_WITH_AES_128_CCM_8,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_PSK_WITH_AES_256_CCM_8
- SUITE_INFO("PSK-AES256-CCM-8","TLS_PSK_WITH_AES_256_CCM_8",ECC_BYTE,TLS_PSK_WITH_AES_256_CCM_8,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_NULL_SHA384
- SUITE_INFO("DHE-PSK-NULL-SHA384","TLS_DHE_PSK_WITH_NULL_SHA384",CIPHER_BYTE,TLS_DHE_PSK_WITH_NULL_SHA384,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_NULL_SHA256
- SUITE_INFO("DHE-PSK-NULL-SHA256","TLS_DHE_PSK_WITH_NULL_SHA256",CIPHER_BYTE,TLS_DHE_PSK_WITH_NULL_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_PSK_WITH_NULL_SHA384
- SUITE_INFO("PSK-NULL-SHA384","TLS_PSK_WITH_NULL_SHA384",CIPHER_BYTE,TLS_PSK_WITH_NULL_SHA384,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_PSK_WITH_NULL_SHA256
- SUITE_INFO("PSK-NULL-SHA256","TLS_PSK_WITH_NULL_SHA256",CIPHER_BYTE,TLS_PSK_WITH_NULL_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_PSK_WITH_NULL_SHA
- SUITE_INFO("PSK-NULL-SHA","TLS_PSK_WITH_NULL_SHA",CIPHER_BYTE,TLS_PSK_WITH_NULL_SHA,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_HC_128_MD5
- SUITE_INFO("HC128-MD5","TLS_RSA_WITH_HC_128_MD5",CIPHER_BYTE,TLS_RSA_WITH_HC_128_MD5,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_HC_128_SHA
- SUITE_INFO("HC128-SHA","TLS_RSA_WITH_HC_128_SHA",CIPHER_BYTE,TLS_RSA_WITH_HC_128_SHA,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_RABBIT_SHA
- SUITE_INFO("RABBIT-SHA","TLS_RSA_WITH_RABBIT_SHA",CIPHER_BYTE,TLS_RSA_WITH_RABBIT_SHA,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_NTRU_RSA_WITH_RC4_128_SHA
- SUITE_INFO("NTRU-RC4-SHA","TLS_NTRU_RSA_WITH_RC4_128_SHA",CIPHER_BYTE,TLS_NTRU_RSA_WITH_RC4_128_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA
- SUITE_INFO("NTRU-DES-CBC3-SHA","TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA",CIPHER_BYTE,TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_NTRU_RSA_WITH_AES_128_CBC_SHA
- SUITE_INFO("NTRU-AES128-SHA","TLS_NTRU_RSA_WITH_AES_128_CBC_SHA",CIPHER_BYTE,TLS_NTRU_RSA_WITH_AES_128_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_NTRU_RSA_WITH_AES_256_CBC_SHA
- SUITE_INFO("NTRU-AES256-SHA","TLS_NTRU_RSA_WITH_AES_256_CBC_SHA",CIPHER_BYTE,TLS_NTRU_RSA_WITH_AES_256_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_128_CCM_8
- SUITE_INFO("AES128-CCM-8","TLS_RSA_WITH_AES_128_CCM_8",ECC_BYTE,TLS_RSA_WITH_AES_128_CCM_8, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_256_CCM_8
- SUITE_INFO("AES256-CCM-8","TLS_RSA_WITH_AES_256_CCM_8",ECC_BYTE,TLS_RSA_WITH_AES_256_CCM_8, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM
- SUITE_INFO("ECDHE-ECDSA-AES128-CCM","TLS_ECDHE_ECDSA_WITH_AES_128_CCM",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_128_CCM, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
- SUITE_INFO("ECDHE-ECDSA-AES128-CCM-8","TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8
- SUITE_INFO("ECDHE-ECDSA-AES256-CCM-8","TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
- SUITE_INFO("ECDHE-RSA-AES128-SHA","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",ECC_BYTE,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
- SUITE_INFO("ECDHE-RSA-AES256-SHA","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",ECC_BYTE,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
- SUITE_INFO("ECDHE-ECDSA-AES128-SHA","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
- SUITE_INFO("ECDHE-ECDSA-AES256-SHA","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_RC4_128_SHA
- SUITE_INFO("ECDHE-RSA-RC4-SHA","TLS_ECDHE_RSA_WITH_RC4_128_SHA",ECC_BYTE,TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
- SUITE_INFO("ECDHE-RSA-DES-CBC3-SHA","TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",ECC_BYTE,TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
- SUITE_INFO("ECDHE-ECDSA-RC4-SHA","TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
- SUITE_INFO("ECDHE-ECDSA-DES-CBC3-SHA","TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_128_CBC_SHA256
- SUITE_INFO("AES128-SHA256","TLS_RSA_WITH_AES_128_CBC_SHA256",CIPHER_BYTE,TLS_RSA_WITH_AES_128_CBC_SHA256, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_256_CBC_SHA256
- SUITE_INFO("AES256-SHA256","TLS_RSA_WITH_AES_256_CBC_SHA256",CIPHER_BYTE,TLS_RSA_WITH_AES_256_CBC_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
- SUITE_INFO("DHE-RSA-AES128-SHA256","TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",CIPHER_BYTE,TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
- SUITE_INFO("DHE-RSA-AES256-SHA256","TLS_DHE_RSA_WITH_AES_256_CBC_SHA256",CIPHER_BYTE,TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
- SUITE_INFO("ECDH-RSA-AES128-SHA","TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",ECC_BYTE,TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
- SUITE_INFO("ECDH-RSA-AES256-SHA","TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",ECC_BYTE,TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
- SUITE_INFO("ECDH-ECDSA-AES128-SHA","TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",ECC_BYTE,TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
- SUITE_INFO("ECDH-ECDSA-AES256-SHA","TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",ECC_BYTE,TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_RC4_128_SHA
- SUITE_INFO("ECDH-RSA-RC4-SHA","TLS_ECDH_RSA_WITH_RC4_128_SHA",ECC_BYTE,TLS_ECDH_RSA_WITH_RC4_128_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
- SUITE_INFO("ECDH-RSA-DES-CBC3-SHA","TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",ECC_BYTE,TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_RC4_128_SHA
- SUITE_INFO("ECDH-ECDSA-RC4-SHA","TLS_ECDH_ECDSA_WITH_RC4_128_SHA",ECC_BYTE,TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
- SUITE_INFO("ECDH-ECDSA-DES-CBC3-SHA","TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA",ECC_BYTE,TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256
- SUITE_INFO("AES128-GCM-SHA256","TLS_RSA_WITH_AES_128_GCM_SHA256",CIPHER_BYTE,TLS_RSA_WITH_AES_128_GCM_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_AES_256_GCM_SHA384
- SUITE_INFO("AES256-GCM-SHA384","TLS_RSA_WITH_AES_256_GCM_SHA384",CIPHER_BYTE,TLS_RSA_WITH_AES_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
- SUITE_INFO("DHE-RSA-AES128-GCM-SHA256","TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",CIPHER_BYTE,TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
- SUITE_INFO("DHE-RSA-AES256-GCM-SHA384","TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",CIPHER_BYTE,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
- SUITE_INFO("ECDHE-RSA-AES128-GCM-SHA256","TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",ECC_BYTE,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
- SUITE_INFO("ECDHE-RSA-AES256-GCM-SHA384","TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",ECC_BYTE,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
- SUITE_INFO("ECDHE-ECDSA-AES128-GCM-SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
- SUITE_INFO("ECDHE-ECDSA-AES256-GCM-SHA384","TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
- SUITE_INFO("ECDH-RSA-AES128-GCM-SHA256","TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256",ECC_BYTE,TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
- SUITE_INFO("ECDH-RSA-AES256-GCM-SHA384","TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384",ECC_BYTE,TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
- SUITE_INFO("ECDH-ECDSA-AES128-GCM-SHA256","TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256",ECC_BYTE,TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
- SUITE_INFO("ECDH-ECDSA-AES256-GCM-SHA384","TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384",ECC_BYTE,TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
- SUITE_INFO("CAMELLIA128-SHA","TLS_RSA_WITH_CAMELLIA_128_CBC_SHA",CIPHER_BYTE,TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
- SUITE_INFO("DHE-RSA-CAMELLIA128-SHA","TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA",CIPHER_BYTE,TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
- SUITE_INFO("CAMELLIA256-SHA","TLS_RSA_WITH_CAMELLIA_256_CBC_SHA",CIPHER_BYTE,TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
- SUITE_INFO("DHE-RSA-CAMELLIA256-SHA","TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA",CIPHER_BYTE,TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256
- SUITE_INFO("CAMELLIA128-SHA256","TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256",CIPHER_BYTE,TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
- SUITE_INFO("DHE-RSA-CAMELLIA128-SHA256","TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256",CIPHER_BYTE,TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256
- SUITE_INFO("CAMELLIA256-SHA256","TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256",CIPHER_BYTE,TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256
- SUITE_INFO("DHE-RSA-CAMELLIA256-SHA256","TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256",CIPHER_BYTE,TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
- SUITE_INFO("ECDHE-RSA-AES128-SHA256","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",ECC_BYTE,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
- SUITE_INFO("ECDHE-ECDSA-AES128-SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
- SUITE_INFO("ECDH-RSA-AES128-SHA256","TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256",ECC_BYTE,TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
- SUITE_INFO("ECDH-ECDSA-AES128-SHA256","TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256",ECC_BYTE,TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
- SUITE_INFO("ECDHE-RSA-AES256-SHA384","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",ECC_BYTE,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
- SUITE_INFO("ECDHE-ECDSA-AES256-SHA384","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
- SUITE_INFO("ECDH-RSA-AES256-SHA384","TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384",ECC_BYTE,TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
- SUITE_INFO("ECDH-ECDSA-AES256-SHA384","TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384",ECC_BYTE,TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
- SUITE_INFO("ECDHE-RSA-CHACHA20-POLY1305","TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",CHACHA_BYTE,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
- SUITE_INFO("ECDHE-ECDSA-CHACHA20-POLY1305","TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",CHACHA_BYTE,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
- SUITE_INFO("DHE-RSA-CHACHA20-POLY1305","TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256",CHACHA_BYTE,TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
- SUITE_INFO("ECDHE-RSA-CHACHA20-POLY1305-OLD","TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256",CHACHA_BYTE,TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256
- SUITE_INFO("ECDHE-ECDSA-CHACHA20-POLY1305-OLD","TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256",CHACHA_BYTE,TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
- SUITE_INFO("DHE-RSA-CHACHA20-POLY1305-OLD","TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256",CHACHA_BYTE,TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DH_anon_WITH_AES_128_CBC_SHA
- SUITE_INFO("ADH-AES128-SHA","TLS_DH_anon_WITH_AES_128_CBC_SHA",CIPHER_BYTE,TLS_DH_anon_WITH_AES_128_CBC_SHA, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DH_anon_WITH_AES_256_GCM_SHA384
- SUITE_INFO("ADH-AES256-GCM-SHA384","TLS_DH_anon_WITH_AES_256_GCM_SHA384",CIPHER_BYTE,TLS_DH_anon_WITH_AES_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_QSH
- SUITE_INFO("QSH","TLS_QSH",QSH_BYTE,TLS_QSH, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef HAVE_RENEGOTIATION_INDICATION
- SUITE_INFO("RENEGOTIATION-INFO","TLS_EMPTY_RENEGOTIATION_INFO_SCSV",CIPHER_BYTE,TLS_EMPTY_RENEGOTIATION_INFO_SCSV,SSLv3_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_SSL_RSA_WITH_IDEA_CBC_SHA
- SUITE_INFO("IDEA-CBC-SHA","SSL_RSA_WITH_IDEA_CBC_SHA",CIPHER_BYTE,SSL_RSA_WITH_IDEA_CBC_SHA,SSLv3_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_NULL_SHA
- SUITE_INFO("ECDHE-ECDSA-NULL-SHA","TLS_ECDHE_ECDSA_WITH_NULL_SHA",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_NULL_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_PSK_WITH_NULL_SHA256
- SUITE_INFO("ECDHE-PSK-NULL-SHA256","TLS_ECDHE_PSK_WITH_NULL_SHA256",ECC_BYTE,TLS_ECDHE_PSK_WITH_NULL_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
- SUITE_INFO("ECDHE-PSK-AES128-CBC-SHA256","TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256",ECC_BYTE,TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256
- SUITE_INFO("PSK-CHACHA20-POLY1305","TLS_PSK_WITH_CHACHA20_POLY1305_SHA256",CHACHA_BYTE,TLS_PSK_WITH_CHACHA20_POLY1305_SHA256,TLSv1_2_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256
- SUITE_INFO("ECDHE-PSK-CHACHA20-POLY1305","TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256",CHACHA_BYTE,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,TLSv1_2_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256
- SUITE_INFO("DHE-PSK-CHACHA20-POLY1305","TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256",CHACHA_BYTE,TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,TLSv1_2_MINOR,SSLv3_MAJOR),
- #endif
- #ifdef BUILD_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
- SUITE_INFO("EDH-RSA-DES-CBC3-SHA","TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA",CIPHER_BYTE,TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
- #endif
- #ifdef BUILD_WDM_WITH_NULL_SHA256
- SUITE_INFO("WDM-NULL-SHA256","WDM_WITH_NULL_SHA256",CIPHER_BYTE,WDM_WITH_NULL_SHA256, TLSv1_3_MINOR, SSLv3_MAJOR)
- #endif
- #endif /* WOLFSSL_NO_TLS12 */
- };
- /* returns the cipher_names array */
- const CipherSuiteInfo* GetCipherNames(void)
- {
- return cipher_names;
- }
- /* returns the number of elements in the cipher_names array */
- int GetCipherNamesSize(void)
- {
- return (int)(sizeof(cipher_names) / sizeof(CipherSuiteInfo));
- }
- const char* GetCipherNameInternal(const byte cipherSuite0, const byte cipherSuite)
- {
- int i;
- const char* nameInternal = "None";
- for (i = 0; i < GetCipherNamesSize(); i++) {
- if ((cipher_names[i].cipherSuite0 == cipherSuite0) &&
- (cipher_names[i].cipherSuite == cipherSuite)) {
- nameInternal = cipher_names[i].name;
- break;
- }
- }
- return nameInternal;
- }
- #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
- const char* GetCipherKeaStr(char n[][MAX_SEGMENT_SZ]) {
- const char* keaStr = NULL;
- const char *n0,*n1,*n2,*n3,*n4;
- n0 = n[0];
- n1 = n[1];
- n2 = n[2];
- n3 = n[3];
- n4 = n[4];
- if (XSTRNCMP(n0,"ECDHE",5) == 0 && XSTRNCMP(n1,"PSK",3) == 0)
- keaStr = "ECDHEPSK";
- else if (XSTRNCMP(n0,"ECDH",4) == 0)
- keaStr = "ECDH";
- else if (XSTRNCMP(n0,"DHE",3) == 0 && XSTRNCMP(n1,"PSK",3) == 0)
- keaStr = "DHEPSK";
- else if (XSTRNCMP(n0,"DHE",3) == 0)
- keaStr = "DH";
- else if (XSTRNCMP(n0,"RSA",3) == 0 && XSTRNCMP(n1,"PSK",3) == 0)
- keaStr = "RSAPSK";
- else if (XSTRNCMP(n0,"SRP",3) == 0)
- keaStr = "SRP";
- else if (XSTRNCMP(n0,"PSK",3) == 0)
- keaStr = "PSK";
- else if (XSTRNCMP(n0,"EDH",3) == 0)
- keaStr = "EDH";
- else if ((XSTRNCMP(n1,"SHA",3) == 0) || (XSTRNCMP(n2,"SHA",3) == 0) ||
- (XSTRNCMP(n3,"SHA",3) == 0) || (XSTRNCMP(n4,"SHA",3) == 0) ||
- (XSTRNCMP(n2,"RSA",3) == 0) || (XSTRNCMP(n0,"AES128",6) == 0) ||
- (XSTRNCMP(n0,"AES256",6) == 0) || (XSTRNCMP(n1,"MD5",3) == 0))
- keaStr = "RSA";
- else
- keaStr = "unknown";
- return keaStr;
- }
- const char* GetCipherAuthStr(char n[][MAX_SEGMENT_SZ]) {
- const char* authStr = NULL;
- const char *n0,*n1,*n2;
- n0 = n[0];
- n1 = n[1];
- n2 = n[2];
- if ((XSTRNCMP(n0,"AES128",6) == 0) || (XSTRNCMP(n0,"AES256",6) == 0) ||
- ((XSTRNCMP(n0,"TLS13",5) == 0) && ((XSTRNCMP(n1,"AES128",6) == 0) ||
- (XSTRNCMP(n1,"AES256",6) == 0) || (XSTRNCMP(n1,"CHACHA20",8) == 0))) ||
- (XSTRNCMP(n0,"RSA",3) == 0) || (XSTRNCMP(n1,"RSA",3) == 0) ||
- (XSTRNCMP(n1,"SHA",3) == 0) || (XSTRNCMP(n2,"SHA",3) == 0) ||
- (XSTRNCMP(n1,"MD5",3) == 0))
- authStr = "RSA";
- else if (XSTRNCMP(n0,"PSK",3) == 0 || XSTRNCMP(n1,"PSK",3) == 0)
- authStr = "PSK";
- else if (XSTRNCMP(n0,"SRP",3) == 0 && XSTRNCMP(n1,"AES",3) == 0)
- authStr = "SRP";
- else if (XSTRNCMP(n1,"ECDSA",5) == 0)
- authStr = "ECDSA";
- else
- authStr = "unknown";
- return authStr;
- }
- const char* GetCipherEncStr(char n[][MAX_SEGMENT_SZ]) {
- const char* encStr = NULL;
- const char *n0,*n1,*n2,*n3;
- n0 = n[0];
- n1 = n[1];
- n2 = n[2];
- n3 = n[3];
- if ((XSTRNCMP(n0,"AES256",6) == 0 && XSTRNCMP(n1,"GCM",3) == 0) ||
- (XSTRNCMP(n1,"AES256",6) == 0 && XSTRNCMP(n2,"GCM",3) == 0) ||
- (XSTRNCMP(n2,"AES256",6) == 0 && XSTRNCMP(n3,"GCM",3) == 0))
- encStr = "AESGCM(256)";
- else if ((XSTRNCMP(n0,"AES128",6) == 0 && XSTRNCMP(n1,"GCM",3) == 0) ||
- (XSTRNCMP(n1,"AES128",6) == 0 && XSTRNCMP(n2,"GCM",3) == 0) ||
- (XSTRNCMP(n2,"AES128",6) == 0 && XSTRNCMP(n3,"GCM",3) == 0))
- encStr = "AESGCM(128)";
- else if ((XSTRNCMP(n0,"AES128",6) == 0 && XSTRNCMP(n1,"CCM",3) == 0) ||
- (XSTRNCMP(n1,"AES128",6) == 0 && XSTRNCMP(n2,"CCM",3) == 0) ||
- (XSTRNCMP(n2,"AES128",6) == 0 && XSTRNCMP(n3,"CCM",3) == 0))
- encStr = "AESCCM(128)";
- else if ((XSTRNCMP(n0,"AES128",6) == 0) ||
- (XSTRNCMP(n1,"AES128",6) == 0) ||
- (XSTRNCMP(n2,"AES128",6) == 0) ||
- (XSTRNCMP(n1,"AES",3) == 0 && XSTRNCMP(n2,"128",3) == 0) ||
- (XSTRNCMP(n2,"AES",3) == 0 && XSTRNCMP(n3,"128",3) == 0))
- encStr = "AES(128)";
- else if ((XSTRNCMP(n0,"AES256",6) == 0) ||
- (XSTRNCMP(n1,"AES256",6) == 0) ||
- (XSTRNCMP(n2,"AES256",6) == 0) ||
- (XSTRNCMP(n1,"AES",3) == 0 && XSTRNCMP(n2,"256",3) == 0) ||
- (XSTRNCMP(n2,"AES",3) == 0 && XSTRNCMP(n3,"256",3) == 0))
- encStr = "AES(256)";
- else if ((XSTRNCMP(n0,"CAMELLIA256",11) == 0) ||
- (XSTRNCMP(n2,"CAMELLIA256",11) == 0))
- encStr = "CAMELLIA(256)";
- else if ((XSTRNCMP(n0,"CAMELLIA128",11) == 0) ||
- (XSTRNCMP(n2,"CAMELLIA128",11) == 0))
- encStr = "CAMELLIA(128)";
- else if ((XSTRNCMP(n0,"RC4",3) == 0) || (XSTRNCMP(n2,"RC4",3) == 0))
- encStr = "RC4";
- else if (((XSTRNCMP(n0,"DES",3) == 0) || (XSTRNCMP(n2,"DES",3) == 0)) &&
- ((XSTRNCMP(n1,"CBC3",4) == 0) || (XSTRNCMP(n3,"CBC3",4) == 0)))
- encStr = "3DES";
- else if ((XSTRNCMP(n1,"CHACHA20",8) == 0 && XSTRNCMP(n2,"POLY1305",8) == 0) ||
- (XSTRNCMP(n2,"CHACHA20",8) == 0 && XSTRNCMP(n3,"POLY1305",8) == 0))
- encStr = "CHACHA20/POLY1305(256)";
- else if ((XSTRNCMP(n0,"NULL",4) == 0) || (XSTRNCMP(n1,"NULL",4) == 0) ||
- (XSTRNCMP(n2,"NULL",4) == 0) ||
- ((XSTRNCMP(n0,"TLS13",5) == 0) && (XSTRNCMP(n3,"",0) == 0)))
- encStr = "None";
- else if ((XSTRNCMP(n0,"IDEA",4) == 0))
- encStr = "IDEA";
- else if ((XSTRNCMP(n0,"RABBIT",4) == 0))
- encStr = "RABBIT";
- else if ((XSTRNCMP(n0,"HC128",5) == 0))
- encStr = "HC128";
- else
- encStr = "unknown";
- return encStr;
- }
- /* Returns the MAC string of a cipher or "unknown" on failure */
- const char* GetCipherMacStr(char n[][MAX_SEGMENT_SZ]) {
- const char* macStr = NULL;
- const char *n1,*n2,*n3,*n4;
- n1 = n[1];
- n2 = n[2];
- n3 = n[3];
- n4 = n[4];
- if ((XSTRNCMP(n4,"SHA256",6) == 0) || (XSTRNCMP(n3,"SHA256",6) == 0) ||
- (XSTRNCMP(n2,"SHA256",6) == 0) || (XSTRNCMP(n1,"SHA256",6) == 0))
- macStr = "SHA256";
- else if ((XSTRNCMP(n4,"SHA384",6) == 0) ||
- (XSTRNCMP(n3,"SHA384",6) == 0) ||
- (XSTRNCMP(n2,"SHA384",6) == 0) ||
- (XSTRNCMP(n1,"SHA384",6) == 0))
- macStr = "SHA384";
- else if ((XSTRNCMP(n4,"SHA",3) == 0) || (XSTRNCMP(n3,"SHA",3) == 0) ||
- (XSTRNCMP(n2,"SHA",3) == 0) || (XSTRNCMP(n1,"SHA",3) == 0) ||
- (XSTRNCMP(n1,"MD5",3) == 0))
- macStr = "SHA1";
- else if ((XSTRNCMP(n3,"GCM",3) == 0) ||
- (XSTRNCMP(n1,"CCM",3) == 0) ||
- (XSTRNCMP(n2,"CCM",3) == 0) || (XSTRNCMP(n3,"CCM",3) == 0) ||
- (XSTRNCMP(n1,"CHACHA20",8) == 0 && XSTRNCMP(n2,"POLY1305",8) == 0) ||
- (XSTRNCMP(n2,"CHACHA20",8) == 0 && XSTRNCMP(n3,"POLY1305",8) == 0))
- macStr = "AEAD";
- else
- macStr = "unknown";
- return macStr;
- }
- /* Returns the number of bits based on the cipher enc string, or 0 on failure */
- int SetCipherBits(const char* enc) {
- int ret = WOLFSSL_FAILURE;
- if ((XSTRNCMP(enc,"AESGCM(256)",11) == 0) ||
- (XSTRNCMP(enc,"AES(256)",8) == 0) ||
- (XSTRNCMP(enc,"CAMELLIA(256)",13) == 0) ||
- (XSTRNCMP(enc,"CHACHA20/POLY1305(256)",22) == 0))
- ret = 256;
- else if
- ((XSTRNCMP(enc,"3DES",4) == 0))
- ret = 168;
- else if
- ((XSTRNCMP(enc,"AESGCM(128)",11) == 0) ||
- (XSTRNCMP(enc,"AES(128)",8) == 0) ||
- (XSTRNCMP(enc,"CAMELLIA(128)",13) == 0) ||
- (XSTRNCMP(enc,"IDEA",4) == 0) ||
- (XSTRNCMP(enc,"RC4",3) == 0))
- ret = 128;
- else if
- ((XSTRNCMP(enc,"DES",3) == 0))
- ret = 56;
- return ret;
- }
- #endif /* WOLFSSL_QT || OPENSSL_ALL */
- const char* GetCipherNameIana(const byte cipherSuite0, const byte cipherSuite)
- {
- #ifndef NO_ERROR_STRINGS
- int i;
- const char* nameIana = "NONE";
- for (i = 0; i < GetCipherNamesSize(); i++) {
- if ((cipher_names[i].cipherSuite0 == cipherSuite0) &&
- (cipher_names[i].cipherSuite == cipherSuite)) {
- nameIana = cipher_names[i].name_iana;
- break;
- }
- }
- return nameIana;
- #else
- (void)cipherSuite0;
- (void)cipherSuite;
- return NULL;
- #endif
- }
- const char* wolfSSL_get_cipher_name_internal(WOLFSSL* ssl)
- {
- if (ssl == NULL) {
- return NULL;
- }
- return GetCipherNameInternal(ssl->options.cipherSuite0, ssl->options.cipherSuite);
- }
- const char* wolfSSL_get_cipher_name_iana(WOLFSSL* ssl)
- {
- if (ssl == NULL) {
- return NULL;
- }
- return GetCipherNameIana(ssl->options.cipherSuite0, ssl->options.cipherSuite);
- }
- int GetCipherSuiteFromName(const char* name, byte* cipherSuite0,
- byte* cipherSuite)
- {
- int ret = BAD_FUNC_ARG;
- int i;
- unsigned long len = (unsigned long)XSTRLEN(name);
- for (i = 0; i < GetCipherNamesSize(); i++) {
- if (XSTRNCMP(name, cipher_names[i].name, len) == 0) {
- *cipherSuite0 = cipher_names[i].cipherSuite0;
- *cipherSuite = cipher_names[i].cipherSuite;
- ret = 0;
- break;
- }
- }
- return ret;
- }
- /**
- Set the enabled cipher suites.
- @param [out] suites Suites structure.
- @param [in] list List of cipher suites, only supports full name from
- cipher_names[] delimited by ':'.
- @return true on success, else false.
- */
- int SetCipherList(WOLFSSL_CTX* ctx, Suites* suites, const char* list)
- {
- int ret = 0;
- int idx = 0;
- int haveRSAsig = 0;
- int haveECDSAsig = 0;
- int haveAnon = 0;
- const int suiteSz = GetCipherNamesSize();
- char* next = (char*)list;
- if (suites == NULL || list == NULL) {
- WOLFSSL_MSG("SetCipherList parameter error");
- return 0;
- }
- if (next[0] == 0 || XSTRNCMP(next, "ALL", 3) == 0 ||
- XSTRNCMP(next, "DEFAULT", 7) == 0)
- return 1; /* wolfSSL default */
- do {
- char* current = next;
- char name[MAX_SUITE_NAME + 1];
- int i;
- word32 length;
- next = XSTRSTR(next, ":");
- length = min(sizeof(name), !next ? (word32)XSTRLEN(current) /* last */
- : (word32)(next - current));
- XSTRNCPY(name, current, length);
- name[(length == sizeof(name)) ? length - 1 : length] = 0;
- for (i = 0; i < suiteSz; i++) {
- if (XSTRNCMP(name, cipher_names[i].name, sizeof(name)) == 0
- #ifndef NO_ERROR_STRINGS
- || XSTRNCMP(name, cipher_names[i].name_iana, sizeof(name)) == 0
- #endif
- ) {
- #ifdef WOLFSSL_DTLS
- /* don't allow stream ciphers with DTLS */
- if (ctx->method->version.major == DTLS_MAJOR) {
- if (XSTRSTR(name, "RC4") ||
- XSTRSTR(name, "HC128") ||
- XSTRSTR(name, "RABBIT"))
- {
- WOLFSSL_MSG("Stream ciphers not supported with DTLS");
- continue;
- }
- }
- #endif /* WOLFSSL_DTLS */
- if (idx + 1 >= WOLFSSL_MAX_SUITE_SZ) {
- WOLFSSL_MSG("WOLFSSL_MAX_SUITE_SZ set too low");
- return 0; /* suites buffer not large enough, error out */
- }
- suites->suites[idx++] = cipher_names[i].cipherSuite0;
- suites->suites[idx++] = cipher_names[i].cipherSuite;
- /* The suites are either ECDSA, RSA, PSK, or Anon. The RSA
- * suites don't necessarily have RSA in the name. */
- #ifdef WOLFSSL_TLS13
- if (cipher_names[i].cipherSuite0 == TLS13_BYTE ||
- (cipher_names[i].cipherSuite0 == ECC_BYTE &&
- (cipher_names[i].cipherSuite == TLS_SHA256_SHA256 ||
- cipher_names[i].cipherSuite == TLS_SHA384_SHA384))) {
- #ifndef NO_RSA
- haveRSAsig = 1;
- #endif
- #if defined(HAVE_ECC) || defined(HAVE_ED25519) || \
- defined(HAVE_ED448)
- haveECDSAsig = 1;
- #endif
- }
- else
- #endif
- #if defined(HAVE_ECC) || defined(HAVE_ED25519) || \
- defined(HAVE_ED448)
- if ((haveECDSAsig == 0) && XSTRSTR(name, "ECDSA"))
- haveECDSAsig = 1;
- else
- #endif
- #ifdef HAVE_ANON
- if (XSTRSTR(name, "ADH"))
- haveAnon = 1;
- else
- #endif
- if (haveRSAsig == 0
- #ifndef NO_PSK
- && (XSTRSTR(name, "PSK") == NULL)
- #endif
- ) {
- haveRSAsig = 1;
- }
- ret = 1; /* found at least one */
- break;
- }
- }
- }
- while (next++); /* ++ needed to skip ':' */
- if (ret) {
- int keySz = 0;
- #ifndef NO_CERTS
- keySz = ctx->privateKeySz;
- #endif
- suites->setSuites = 1;
- suites->suiteSz = (word16)idx;
- InitSuitesHashSigAlgo(suites, haveECDSAsig, haveRSAsig, haveAnon, 1,
- keySz);
- }
- (void)ctx;
- return ret;
- }
- #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_CERTS)
- int PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo, word32 hashSigAlgoSz)
- {
- word32 i;
- int ret = MATCH_SUITE_ERROR;
- ssl->suites->sigAlgo = ssl->specs.sig_algo;
- /* set defaults */
- if (IsAtLeastTLSv1_3(ssl->version)) {
- ssl->suites->hashAlgo = sha256_mac;
- #ifndef NO_CERTS
- ssl->suites->sigAlgo = ssl->buffers.keyType;
- #endif
- }
- #ifndef WOLFSSL_NO_TLS12
- else if (IsAtLeastTLSv1_2(ssl)) {
- #ifdef WOLFSSL_ALLOW_TLS_SHA1
- ssl->suites->hashAlgo = sha_mac;
- #else
- ssl->suites->hashAlgo = sha256_mac;
- #endif
- }
- else {
- ssl->suites->hashAlgo = sha_mac;
- }
- #endif
- if (hashSigAlgoSz == 0)
- return 0;
- /* i+1 since peek a byte ahead for type */
- for (i = 0; (i+1) < hashSigAlgoSz; i += HELLO_EXT_SIGALGO_SZ) {
- byte hashAlgo = 0, sigAlgo = 0;
- DecodeSigAlg(&hashSigAlgo[i], &hashAlgo, &sigAlgo);
- #ifdef HAVE_ED25519
- if (ssl->pkCurveOID == ECC_ED25519_OID) {
- if (sigAlgo != ed25519_sa_algo)
- continue;
- if (sigAlgo == ed25519_sa_algo &&
- ssl->suites->sigAlgo == ecc_dsa_sa_algo) {
- ssl->suites->sigAlgo = sigAlgo;
- ssl->suites->hashAlgo = sha512_mac;
- ret = 0;
- break;
- }
- }
- #endif
- #ifdef HAVE_ED448
- if (ssl->pkCurveOID == ECC_ED448_OID) {
- if (sigAlgo != ed448_sa_algo)
- continue;
- if (sigAlgo == ed448_sa_algo &&
- ssl->suites->sigAlgo == ecc_dsa_sa_algo) {
- ssl->suites->sigAlgo = sigAlgo;
- ssl->suites->hashAlgo = sha512_mac;
- ret = 0;
- break;
- }
- }
- #endif
- #if defined(WOLFSSL_TLS13) && defined(HAVE_ECC)
- if (IsAtLeastTLSv1_3(ssl->version) && sigAlgo == ssl->suites->sigAlgo &&
- sigAlgo == ecc_dsa_sa_algo) {
- int digestSz = GetMacDigestSize(hashAlgo);
- if (digestSz <= 0)
- continue;
- /* TLS 1.3 signature algorithms for ECDSA match hash length with
- * key size.
- */
- if (digestSz != ssl->buffers.keySz)
- continue;
- ssl->suites->hashAlgo = hashAlgo;
- ssl->suites->sigAlgo = sigAlgo;
- ret = 0;
- break; /* done selected sig/hash algorithms */
- }
- else
- #endif
- /* For ECDSA the `USE_ECDSA_KEYSZ_HASH_ALGO` build option will choose a hash
- * algorithm that matches the ephemeral ECDHE key size or the next highest
- * available. This workaround resolves issue with some peer's that do not
- * properly support scenarios such as a P-256 key hashed with SHA512.
- */
- #if defined(HAVE_ECC) && defined(USE_ECDSA_KEYSZ_HASH_ALGO)
- if (sigAlgo == ssl->suites->sigAlgo && sigAlgo == ecc_dsa_sa_algo) {
- int digestSz = GetMacDigestSize(hashAlgo);
- if (digestSz <= 0)
- continue;
- /* For ecc_dsa_sa_algo, pick hash algo that is curve size unless
- algorithm in not compiled in, then choose next highest */
- if (digestSz == ssl->eccTempKeySz) {
- ssl->suites->hashAlgo = hashAlgo;
- ssl->suites->sigAlgo = sigAlgo;
- #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
- ssl->namedGroup = 0;
- #endif
- ret = 0;
- break; /* done selected sig/hash algorithms */
- }
- /* not strong enough, so keep checking hashSigAlso list */
- if (digestSz < ssl->eccTempKeySz)
- continue;
- /* mark as highest and check remainder of hashSigAlgo list */
- ssl->suites->hashAlgo = hashAlgo;
- ssl->suites->sigAlgo = sigAlgo;
- ret = 0;
- }
- else
- #endif
- #ifdef WC_RSA_PSS
- if (IsAtLeastTLSv1_3(ssl->version) &&
- ssl->suites->sigAlgo == rsa_sa_algo &&
- sigAlgo != rsa_pss_sa_algo) {
- continue;
- }
- else if (sigAlgo == ssl->suites->sigAlgo ||
- (sigAlgo == rsa_pss_sa_algo &&
- (ssl->suites->sigAlgo == rsa_sa_algo)))
- #else
- if (sigAlgo == ssl->suites->sigAlgo)
- #endif
- {
- /* pick highest available between both server and client */
- switch (hashAlgo) {
- case sha_mac:
- #ifdef WOLFSSL_SHA224
- case sha224_mac:
- #endif
- #ifndef NO_SHA256
- case sha256_mac:
- #endif
- #ifdef WOLFSSL_SHA384
- case sha384_mac:
- #endif
- #ifdef WOLFSSL_SHA512
- case sha512_mac:
- #endif
- /* not strong enough, so keep checking hashSigAlso list */
- if (hashAlgo < ssl->suites->hashAlgo) {
- ret = 0;
- continue;
- }
- /* mark as highest and check remainder of hashSigAlgo list */
- ssl->suites->hashAlgo = hashAlgo;
- ssl->suites->sigAlgo = sigAlgo;
- break;
- default:
- continue;
- }
- ret = 0;
- break;
- }
- #if defined(WOLFSSL_TLS13)
- else if (ssl->specs.sig_algo == 0 && IsAtLeastTLSv1_3(ssl->version)) {
- }
- #endif
- else if (ssl->specs.sig_algo == 0)
- {
- ssl->suites->hashAlgo = ssl->specs.mac_algorithm;
- ret = 0;
- }
- }
- return ret;
- }
- #endif /* !defined(NO_WOLFSSL_SERVER) || !defined(NO_CERTS) */
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- /* Initialize HandShakeInfo */
- void InitHandShakeInfo(HandShakeInfo* info, WOLFSSL* ssl)
- {
- int i;
- info->ssl = ssl;
- info->cipherName[0] = 0;
- for (i = 0; i < MAX_PACKETS_HANDSHAKE; i++)
- info->packetNames[i][0] = 0;
- info->numberPackets = 0;
- info->negotiationError = 0;
- }
- /* Set Final HandShakeInfo parameters */
- void FinishHandShakeInfo(HandShakeInfo* info)
- {
- int i;
- int sz = GetCipherNamesSize();
- for (i = 0; i < sz; i++)
- if (info->ssl->options.cipherSuite ==
- (byte)cipher_names[i].cipherSuite) {
- if (info->ssl->options.cipherSuite0 == ECC_BYTE)
- continue; /* ECC suites at end */
- XSTRNCPY(info->cipherName, cipher_names[i].name, MAX_CIPHERNAME_SZ);
- info->cipherName[MAX_CIPHERNAME_SZ] = '\0';
- break;
- }
- /* error max and min are negative numbers */
- if (info->ssl->error <= MIN_PARAM_ERR && info->ssl->error >= MAX_PARAM_ERR)
- info->negotiationError = info->ssl->error;
- }
- /* Add name to info packet names, increase packet name count */
- void AddPacketName(WOLFSSL* ssl, const char* name)
- {
- #ifdef WOLFSSL_CALLBACKS
- HandShakeInfo* info = &ssl->handShakeInfo;
- if (info->numberPackets < MAX_PACKETS_HANDSHAKE) {
- char* packetName = info->packetNames[info->numberPackets];
- XSTRNCPY(packetName, name, MAX_PACKETNAME_SZ);
- packetName[MAX_PACKETNAME_SZ] = '\0';
- info->numberPackets++;
- }
- #endif
- (void)ssl;
- (void)name;
- }
- #ifdef WOLFSSL_CALLBACKS
- /* Initialize TimeoutInfo */
- void InitTimeoutInfo(TimeoutInfo* info)
- {
- int i;
- info->timeoutName[0] = 0;
- info->flags = 0;
- for (i = 0; i < MAX_PACKETS_HANDSHAKE; i++) {
- info->packets[i].packetName[0] = 0;
- info->packets[i].timestamp.tv_sec = 0;
- info->packets[i].timestamp.tv_usec = 0;
- info->packets[i].bufferValue = 0;
- info->packets[i].valueSz = 0;
- }
- info->numberPackets = 0;
- info->timeoutValue.tv_sec = 0;
- info->timeoutValue.tv_usec = 0;
- }
- /* Free TimeoutInfo */
- void FreeTimeoutInfo(TimeoutInfo* info, void* heap)
- {
- int i;
- (void)heap;
- for (i = 0; i < MAX_PACKETS_HANDSHAKE; i++)
- if (info->packets[i].bufferValue) {
- XFREE(info->packets[i].bufferValue, heap, DYNAMIC_TYPE_INFO);
- info->packets[i].bufferValue = 0;
- }
- }
- /* Add packet name to previously added packet info */
- void AddLateName(const char* name, TimeoutInfo* info)
- {
- /* make sure we have a valid previous one */
- if (info->numberPackets > 0 && info->numberPackets <
- MAX_PACKETS_HANDSHAKE) {
- char* packetName = info->packets[info->numberPackets-1].packetName;
- XSTRNCPY(packetName, name, MAX_PACKETNAME_SZ);
- packetName[MAX_PACKETNAME_SZ] = '\0';
- }
- }
- /* Add record header to previously added packet info */
- void AddLateRecordHeader(const RecordLayerHeader* rl, TimeoutInfo* info)
- {
- /* make sure we have a valid previous one */
- if (info->numberPackets > 0 && info->numberPackets <
- MAX_PACKETS_HANDSHAKE) {
- if (info->packets[info->numberPackets - 1].bufferValue)
- XMEMCPY(info->packets[info->numberPackets - 1].bufferValue, rl,
- RECORD_HEADER_SZ);
- else
- XMEMCPY(info->packets[info->numberPackets - 1].value, rl,
- RECORD_HEADER_SZ);
- }
- }
- #endif /* WOLFSSL_CALLBACKS */
- /* Add PacketInfo to TimeoutInfo
- *
- * ssl WOLFSSL structure sending or receiving packet
- * name name of packet being sent
- * type type of packet being sent
- * data data bing sent with packet
- * sz size of data buffer
- * written 1 if this packet is being written to wire, 0 if being read
- * heap custom heap to use for mallocs/frees
- */
- void AddPacketInfo(WOLFSSL* ssl, const char* name, int type,
- const byte* data, int sz, int written, void* heap)
- {
- #ifdef WOLFSSL_CALLBACKS
- TimeoutInfo* info = &ssl->timeoutInfo;
- if (info->numberPackets < (MAX_PACKETS_HANDSHAKE - 1)) {
- WOLFSSL_TIMEVAL currTime;
- /* may add name after */
- if (name) {
- char* packetName = info->packets[info->numberPackets].packetName;
- XSTRNCPY(packetName, name, MAX_PACKETNAME_SZ);
- packetName[MAX_PACKETNAME_SZ] = '\0';
- }
- /* add data, put in buffer if bigger than static buffer */
- info->packets[info->numberPackets].valueSz = sz;
- if (sz < MAX_VALUE_SZ)
- XMEMCPY(info->packets[info->numberPackets].value, data, sz);
- else {
- info->packets[info->numberPackets].bufferValue =
- (byte*)XMALLOC(sz, heap, DYNAMIC_TYPE_INFO);
- if (!info->packets[info->numberPackets].bufferValue)
- /* let next alloc catch, just don't fill, not fatal here */
- info->packets[info->numberPackets].valueSz = 0;
- else
- XMEMCPY(info->packets[info->numberPackets].bufferValue,
- data, sz);
- }
- gettimeofday(&currTime, 0);
- info->packets[info->numberPackets].timestamp.tv_sec =
- currTime.tv_sec;
- info->packets[info->numberPackets].timestamp.tv_usec =
- currTime.tv_usec;
- info->numberPackets++;
- }
- #endif /* WOLFSSL_CALLBACKS */
- #ifdef OPENSSL_EXTRA
- if (ssl->protoMsgCb != NULL && sz > RECORD_HEADER_SZ) {
- /* version from hex to dec 16 is 16^1, 256 from 16^2 and
- 4096 from 16^3 */
- int version = (ssl->version.minor & 0X0F) +
- (ssl->version.minor & 0xF0) * 16 +
- (ssl->version.major & 0X0F) * 256 +
- (ssl->version.major & 0xF0) * 4096;
- ssl->protoMsgCb(written, version, type,
- (const void *)(data + RECORD_HEADER_SZ),
- (size_t)(sz - RECORD_HEADER_SZ),
- ssl, ssl->protoMsgCtx);
- }
- #endif /* OPENSSL_EXTRA */
- (void)written;
- (void)name;
- (void)heap;
- (void)type;
- (void)ssl;
- }
- #endif /* WOLFSSL_CALLBACKS */
- #if !defined(NO_CERTS)
- /* Decode the private key - RSA/ECC/Ed25519/Ed448 - and creates a key object.
- * The signature type is set as well.
- * The maximum length of a signature is returned.
- *
- * ssl The SSL/TLS object.
- * length The length of a signature.
- * returns 0 on success, otherwise failure.
- */
- int DecodePrivateKey(WOLFSSL *ssl, word16* length)
- {
- int ret = BAD_FUNC_ARG;
- int keySz;
- word32 idx;
- #ifdef HAVE_PK_CALLBACKS
- /* allow no private key if using PK callbacks and CB is set */
- if (wolfSSL_IsPrivatePkSet(ssl)) {
- *length = GetPrivateKeySigSize(ssl);
- return 0;
- }
- else
- #endif
- /* make sure private key exists */
- if (ssl->buffers.key == NULL || ssl->buffers.key->buffer == NULL) {
- WOLFSSL_MSG("Private key missing!");
- ERROR_OUT(NO_PRIVATE_KEY, exit_dpk);
- }
- #ifdef HAVE_PKCS11
- if (ssl->buffers.keyDevId != INVALID_DEVID && ssl->buffers.keyId) {
- if (ssl->buffers.keyType == rsa_sa_algo)
- ssl->hsType = DYNAMIC_TYPE_RSA;
- else if (ssl->buffers.keyType == ecc_dsa_sa_algo)
- ssl->hsType = DYNAMIC_TYPE_ECC;
- ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
- if (ret != 0) {
- goto exit_dpk;
- }
- if (ssl->buffers.keyType == rsa_sa_algo) {
- #ifndef NO_RSA
- ret = wc_InitRsaKey_Id((RsaKey*)ssl->hsKey,
- ssl->buffers.key->buffer, ssl->buffers.key->length,
- ssl->heap, ssl->buffers.keyDevId);
- if (ret == 0) {
- if (ssl->buffers.keySz < ssl->options.minRsaKeySz) {
- WOLFSSL_MSG("RSA key size too small");
- ERROR_OUT(RSA_KEY_SIZE_E, exit_dpk);
- }
- /* Return the maximum signature length. */
- *length = (word16)ssl->buffers.keySz;
- }
- #else
- ret = NOT_COMPILED_IN;
- #endif
- }
- else if (ssl->buffers.keyType == ecc_dsa_sa_algo) {
- #ifdef HAVE_ECC
- ret = wc_ecc_init_id((ecc_key*)ssl->hsKey, ssl->buffers.key->buffer,
- ssl->buffers.key->length, ssl->heap,
- ssl->buffers.keyDevId);
- if (ret == 0) {
- if (ssl->buffers.keySz < ssl->options.minEccKeySz) {
- WOLFSSL_MSG("ECC key size too small");
- ERROR_OUT(ECC_KEY_SIZE_E, exit_dpk);
- }
- /* Return the maximum signature length. */
- *length = (word16)wc_ecc_sig_size_calc(ssl->buffers.keySz);
- }
- #else
- ret = NOT_COMPILED_IN;
- #endif
- }
- goto exit_dpk;
- }
- #endif
- #ifndef NO_RSA
- if (ssl->buffers.keyType == rsa_sa_algo || ssl->buffers.keyType == 0) {
- ssl->hsType = DYNAMIC_TYPE_RSA;
- ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
- if (ret != 0) {
- goto exit_dpk;
- }
- WOLFSSL_MSG("Trying RSA private key");
- /* Set start of data to beginning of buffer. */
- idx = 0;
- /* Decode the key assuming it is an RSA private key. */
- ret = wc_RsaPrivateKeyDecode(ssl->buffers.key->buffer, &idx,
- (RsaKey*)ssl->hsKey, ssl->buffers.key->length);
- if (ret == 0) {
- WOLFSSL_MSG("Using RSA private key");
- /* It worked so check it meets minimum key size requirements. */
- keySz = wc_RsaEncryptSize((RsaKey*)ssl->hsKey);
- if (keySz < 0) { /* check if keySz has error case */
- ERROR_OUT(keySz, exit_dpk);
- }
- if (keySz < ssl->options.minRsaKeySz) {
- WOLFSSL_MSG("RSA key size too small");
- ERROR_OUT(RSA_KEY_SIZE_E, exit_dpk);
- }
- /* Return the maximum signature length. */
- *length = (word16)keySz;
- goto exit_dpk;
- }
- }
- #endif /* !NO_RSA */
- #ifdef HAVE_ECC
- #ifndef NO_RSA
- FreeKey(ssl, ssl->hsType, (void**)&ssl->hsKey);
- #endif /* !NO_RSA */
- if (ssl->buffers.keyType == ecc_dsa_sa_algo || ssl->buffers.keyType == 0) {
- ssl->hsType = DYNAMIC_TYPE_ECC;
- ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
- if (ret != 0) {
- goto exit_dpk;
- }
- #ifndef NO_RSA
- WOLFSSL_MSG("Trying ECC private key, RSA didn't work");
- #else
- WOLFSSL_MSG("Trying ECC private key");
- #endif
- /* Set start of data to beginning of buffer. */
- idx = 0;
- /* Decode the key assuming it is an ECC private key. */
- ret = wc_EccPrivateKeyDecode(ssl->buffers.key->buffer, &idx,
- (ecc_key*)ssl->hsKey,
- ssl->buffers.key->length);
- if (ret == 0) {
- WOLFSSL_MSG("Using ECC private key");
- /* Check it meets the minimum ECC key size requirements. */
- keySz = wc_ecc_size((ecc_key*)ssl->hsKey);
- if (keySz < ssl->options.minEccKeySz) {
- WOLFSSL_MSG("ECC key size too small");
- ERROR_OUT(ECC_KEY_SIZE_E, exit_dpk);
- }
- /* Return the maximum signature length. */
- *length = (word16)wc_ecc_sig_size((ecc_key*)ssl->hsKey);
- goto exit_dpk;
- }
- }
- #endif
- #ifdef HAVE_ED25519
- #if !defined(NO_RSA) || defined(HAVE_ECC)
- FreeKey(ssl, ssl->hsType, (void**)&ssl->hsKey);
- #endif
- if (ssl->buffers.keyType == ed25519_sa_algo || ssl->buffers.keyType == 0) {
- ssl->hsType = DYNAMIC_TYPE_ED25519;
- ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
- if (ret != 0) {
- goto exit_dpk;
- }
- #ifdef HAVE_ECC
- WOLFSSL_MSG("Trying ED25519 private key, ECC didn't work");
- #elif !defined(NO_RSA)
- WOLFSSL_MSG("Trying ED25519 private key, RSA didn't work");
- #else
- WOLFSSL_MSG("Trying ED25519 private key");
- #endif
- /* Set start of data to beginning of buffer. */
- idx = 0;
- /* Decode the key assuming it is an ED25519 private key. */
- ret = wc_Ed25519PrivateKeyDecode(ssl->buffers.key->buffer, &idx,
- (ed25519_key*)ssl->hsKey,
- ssl->buffers.key->length);
- if (ret == 0) {
- WOLFSSL_MSG("Using ED25519 private key");
- /* Check it meets the minimum ECC key size requirements. */
- if (ED25519_KEY_SIZE < ssl->options.minEccKeySz) {
- WOLFSSL_MSG("ED25519 key size too small");
- ERROR_OUT(ECC_KEY_SIZE_E, exit_dpk);
- }
- /* Return the maximum signature length. */
- *length = ED25519_SIG_SIZE;
- goto exit_dpk;
- }
- }
- #endif /* HAVE_ED25519 */
- #ifdef HAVE_ED448
- #if !defined(NO_RSA) || defined(HAVE_ECC)
- FreeKey(ssl, ssl->hsType, (void**)&ssl->hsKey);
- #endif
- if (ssl->buffers.keyType == ed448_sa_algo || ssl->buffers.keyType == 0) {
- ssl->hsType = DYNAMIC_TYPE_ED448;
- ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
- if (ret != 0) {
- goto exit_dpk;
- }
- #ifdef HAVE_ED25519
- WOLFSSL_MSG("Trying ED448 private key, ED25519 didn't work");
- #elif defined(HAVE_ECC)
- WOLFSSL_MSG("Trying ED448 private key, ECC didn't work");
- #elif !defined(NO_RSA)
- WOLFSSL_MSG("Trying ED448 private key, RSA didn't work");
- #else
- WOLFSSL_MSG("Trying ED447 private key");
- #endif
- /* Set start of data to beginning of buffer. */
- idx = 0;
- /* Decode the key assuming it is an ED448 private key. */
- ret = wc_Ed448PrivateKeyDecode(ssl->buffers.key->buffer, &idx,
- (ed448_key*)ssl->hsKey,
- ssl->buffers.key->length);
- if (ret == 0) {
- WOLFSSL_MSG("Using ED448 private key");
- /* Check it meets the minimum ECC key size requirements. */
- if (ED448_KEY_SIZE < ssl->options.minEccKeySz) {
- WOLFSSL_MSG("ED448 key size too small");
- ERROR_OUT(ECC_KEY_SIZE_E, exit_dpk);
- }
- /* Return the maximum signature length. */
- *length = ED448_SIG_SIZE;
- goto exit_dpk;
- }
- }
- #endif /* HAVE_ED448 */
- (void)idx;
- (void)keySz;
- (void)length;
- exit_dpk:
- return ret;
- }
- #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
- /* client only parts */
- #ifndef NO_WOLFSSL_CLIENT
- #ifndef WOLFSSL_NO_TLS12
- /* handle generation of client_hello (1) */
- int SendClientHello(WOLFSSL* ssl)
- {
- byte *output;
- word32 length, idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
- int sendSz;
- int idSz = ssl->options.resuming
- ? ssl->session.sessionIDSz
- : 0;
- int ret;
- word16 extSz = 0;
- #ifdef WOLFSSL_TLS13
- if (IsAtLeastTLSv1_3(ssl->version))
- return SendTls13ClientHello(ssl);
- #endif
- WOLFSSL_START(WC_FUNC_CLIENT_HELLO_SEND);
- WOLFSSL_ENTER("SendClientHello");
- if (ssl->suites == NULL) {
- WOLFSSL_MSG("Bad suites pointer in SendClientHello");
- return SUITES_ERROR;
- }
- #ifdef HAVE_SESSION_TICKET
- if (ssl->options.resuming && ssl->session.ticketLen > 0) {
- SessionTicket* ticket;
- ticket = TLSX_SessionTicket_Create(0, ssl->session.ticket,
- ssl->session.ticketLen, ssl->heap);
- if (ticket == NULL) return MEMORY_E;
- ret = TLSX_UseSessionTicket(&ssl->extensions, ticket, ssl->heap);
- if (ret != WOLFSSL_SUCCESS) {
- TLSX_SessionTicket_Free(ticket, ssl->heap);
- return ret;
- }
- idSz = 0;
- }
- #endif
- length = VERSION_SZ + RAN_LEN
- + idSz + ENUM_LEN
- + ssl->suites->suiteSz + SUITE_LEN
- + COMP_LEN + ENUM_LEN;
- #ifdef HAVE_TLS_EXTENSIONS
- /* auto populate extensions supported unless user defined */
- if ((ret = TLSX_PopulateExtensions(ssl, 0)) != 0)
- return ret;
- #ifdef HAVE_QSH
- if (QSH_Init(ssl) != 0)
- return MEMORY_E;
- #endif
- extSz = 0;
- ret = TLSX_GetRequestSize(ssl, client_hello, &extSz);
- if (ret != 0)
- return ret;
- length += extSz;
- #else
- if (IsAtLeastTLSv1_2(ssl) && ssl->suites->hashSigAlgoSz)
- extSz += HELLO_EXT_SZ + HELLO_EXT_SIGALGO_SZ
- + ssl->suites->hashSigAlgoSz;
- #ifdef HAVE_EXTENDED_MASTER
- if (ssl->options.haveEMS)
- extSz += HELLO_EXT_SZ;
- #endif
- if (extSz != 0)
- length += extSz + HELLO_EXT_SZ_SZ;
- #endif
- sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- length += ENUM_LEN; /* cookie */
- if (ssl->arrays->cookieSz != 0) length += ssl->arrays->cookieSz;
- sendSz = length + DTLS_HANDSHAKE_HEADER_SZ + DTLS_RECORD_HEADER_SZ;
- idx += DTLS_HANDSHAKE_EXTRA + DTLS_RECORD_EXTRA;
- }
- #endif
- if (IsEncryptionOn(ssl, 1))
- sendSz += MAX_MSG_EXTRA;
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
- return ret;
- /* get output buffer */
- output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- AddHeaders(output, length, client_hello, ssl);
- /* client hello, first version */
- output[idx++] = ssl->version.major;
- output[idx++] = ssl->version.minor;
- ssl->chVersion = ssl->version; /* store in case changed */
- /* then random */
- if (ssl->options.connectState == CONNECT_BEGIN) {
- ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN);
- if (ret != 0)
- return ret;
- /* store random */
- XMEMCPY(ssl->arrays->clientRandom, output + idx, RAN_LEN);
- } else {
- #ifdef WOLFSSL_DTLS
- /* send same random on hello again */
- XMEMCPY(output + idx, ssl->arrays->clientRandom, RAN_LEN);
- #endif
- }
- idx += RAN_LEN;
- /* then session id */
- output[idx++] = (byte)idSz;
- if (idSz) {
- XMEMCPY(output + idx, ssl->session.sessionID,
- ssl->session.sessionIDSz);
- idx += ssl->session.sessionIDSz;
- }
- /* then DTLS cookie */
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- byte cookieSz = ssl->arrays->cookieSz;
- output[idx++] = cookieSz;
- if (cookieSz) {
- XMEMCPY(&output[idx], ssl->arrays->cookie, cookieSz);
- idx += cookieSz;
- }
- }
- #endif
- /* then cipher suites */
- c16toa(ssl->suites->suiteSz, output + idx);
- idx += OPAQUE16_LEN;
- XMEMCPY(output + idx, &ssl->suites->suites, ssl->suites->suiteSz);
- idx += ssl->suites->suiteSz;
- /* last, compression */
- output[idx++] = COMP_LEN;
- if (ssl->options.usingCompression)
- output[idx++] = ZLIB_COMPRESSION;
- else
- output[idx++] = NO_COMPRESSION;
- #ifdef HAVE_TLS_EXTENSIONS
- extSz = 0;
- ret = TLSX_WriteRequest(ssl, output + idx, client_hello, &extSz);
- if (ret != 0)
- return ret;
- idx += extSz;
- (void)idx; /* suppress analyzer warning, keep idx current */
- #else
- if (extSz != 0) {
- c16toa(extSz, output + idx);
- idx += HELLO_EXT_SZ_SZ;
- if (IsAtLeastTLSv1_2(ssl)) {
- if (ssl->suites->hashSigAlgoSz) {
- word16 i;
- /* extension type */
- c16toa(HELLO_EXT_SIG_ALGO, output + idx);
- idx += HELLO_EXT_TYPE_SZ;
- /* extension data length */
- c16toa(HELLO_EXT_SIGALGO_SZ + ssl->suites->hashSigAlgoSz,
- output + idx);
- idx += HELLO_EXT_SZ_SZ;
- /* sig algos length */
- c16toa(ssl->suites->hashSigAlgoSz, output + idx);
- idx += HELLO_EXT_SIGALGO_SZ;
- for (i=0; i < ssl->suites->hashSigAlgoSz; i++, idx++) {
- output[idx] = ssl->suites->hashSigAlgo[i];
- }
- }
- }
- #ifdef HAVE_EXTENDED_MASTER
- if (ssl->options.haveEMS) {
- c16toa(HELLO_EXT_EXTMS, output + idx);
- idx += HELLO_EXT_TYPE_SZ;
- c16toa(0, output + idx);
- idx += HELLO_EXT_SZ_SZ;
- }
- #endif
- }
- #endif
- if (IsEncryptionOn(ssl, 1)) {
- byte* input;
- int inputSz = idx - RECORD_HEADER_SZ; /* build msg adds rec hdr */
- input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (input == NULL)
- return MEMORY_E;
- XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
- sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
- handshake, 1, 0, 0);
- XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (sendSz < 0)
- return sendSz;
- } else {
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- if ((ret = DtlsMsgPoolSave(ssl, output, sendSz)) != 0)
- return ret;
- }
- if (ssl->options.dtls)
- DtlsSEQIncrement(ssl, CUR_ORDER);
- #endif
- ret = HashOutput(ssl, output, sendSz, 0);
- if (ret != 0)
- return ret;
- }
- ssl->options.clientState = CLIENT_HELLO_COMPLETE;
- #ifdef OPENSSL_EXTRA
- ssl->cbmode = SSL_CB_MODE_WRITE;
- if (ssl->CBIS != NULL)
- ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, SSL_SUCCESS);
- #endif
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
- if (ssl->toInfoOn)
- AddPacketInfo(ssl, "ClientHello", handshake, output, sendSz,
- WRITE_PROTO, ssl->heap);
- #endif
- ssl->buffers.outputBuffer.length += sendSz;
- ret = SendBuffered(ssl);
- WOLFSSL_LEAVE("SendClientHello", ret);
- WOLFSSL_END(WC_FUNC_CLIENT_HELLO_SEND);
- return ret;
- }
- /* handle processing of DTLS hello_verify_request (3) */
- static int DoHelloVerifyRequest(WOLFSSL* ssl, const byte* input,
- word32* inOutIdx, word32 size)
- {
- ProtocolVersion pv;
- byte cookieSz;
- word32 begin = *inOutIdx;
- #ifdef WOLFSSL_CALLBACKS
- if (ssl->hsInfoOn) AddPacketName(ssl, "HelloVerifyRequest");
- if (ssl->toInfoOn) AddLateName("HelloVerifyRequest", &ssl->timeoutInfo);
- #endif
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- DtlsMsgPoolReset(ssl);
- }
- #endif
- if (OPAQUE16_LEN + OPAQUE8_LEN > size)
- return BUFFER_ERROR;
- XMEMCPY(&pv, input + *inOutIdx, OPAQUE16_LEN);
- *inOutIdx += OPAQUE16_LEN;
- if (pv.major != DTLS_MAJOR ||
- (pv.minor != DTLS_MINOR && pv.minor != DTLSv1_2_MINOR))
- return VERSION_ERROR;
- cookieSz = input[(*inOutIdx)++];
- if (cookieSz) {
- if ((*inOutIdx - begin) + cookieSz > size)
- return BUFFER_ERROR;
- #ifdef WOLFSSL_DTLS
- if (cookieSz <= MAX_COOKIE_LEN) {
- XMEMCPY(ssl->arrays->cookie, input + *inOutIdx, cookieSz);
- ssl->arrays->cookieSz = cookieSz;
- }
- #endif
- *inOutIdx += cookieSz;
- }
- ssl->options.serverState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
- return 0;
- }
- static WC_INLINE int DSH_CheckSessionId(WOLFSSL* ssl)
- {
- int ret = 0;
- #ifdef HAVE_SECRET_CALLBACK
- /* If a session secret callback exists, we are using that
- * key instead of the saved session key. */
- ret = ret || (ssl->sessionSecretCb != NULL);
- #endif
- #ifdef HAVE_SESSION_TICKET
- /* server may send blank ticket which may not be expected to indicate
- * existing one ok but will also be sending a new one */
- ret = ret || (ssl->session.ticketLen > 0);
- #endif
- ret = ret ||
- (ssl->options.haveSessionId && XMEMCMP(ssl->arrays->sessionID,
- ssl->session.sessionID, ID_LEN) == 0);
- return ret;
- }
- /* Check the version in the received message is valid and set protocol
- * version to use.
- *
- * ssl The SSL/TLS object.
- * pv The protocol version from the packet.
- * returns 0 on success, otherwise failure.
- */
- int CheckVersion(WOLFSSL *ssl, ProtocolVersion pv)
- {
- #ifdef WOLFSSL_TLS13_DRAFT
- if (pv.major == TLS_DRAFT_MAJOR) {
- pv.major = SSLv3_MAJOR;
- pv.minor = TLSv1_3_MINOR;
- }
- #endif
- #ifdef OPENSSL_EXTRA
- if (ssl->CBIS != NULL) {
- ssl->CBIS(ssl, SSL_CB_HANDSHAKE_START, SSL_SUCCESS);
- }
- #endif
- if (pv.minor > ssl->version.minor) {
- WOLFSSL_MSG("Server using higher version, fatal error");
- return VERSION_ERROR;
- }
- if (pv.minor < ssl->version.minor) {
- WOLFSSL_MSG("server using lower version");
- /* Check for downgrade attack. */
- if (!ssl->options.downgrade) {
- WOLFSSL_MSG("\tno downgrade allowed, fatal error");
- return VERSION_ERROR;
- }
- if (pv.minor < ssl->options.minDowngrade) {
- WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
- return VERSION_ERROR;
- }
- #ifdef HAVE_SECURE_RENEGOTIATION
- if (ssl->secure_renegotiation &&
- ssl->secure_renegotiation->enabled &&
- ssl->options.handShakeDone) {
- WOLFSSL_MSG("Server changed version during scr");
- return VERSION_ERROR;
- }
- #endif
- /* Checks made - OK to downgrade. */
- if (pv.minor == SSLv3_MINOR) {
- /* turn off tls */
- WOLFSSL_MSG("\tdowngrading to SSLv3");
- ssl->options.tls = 0;
- ssl->options.tls1_1 = 0;
- ssl->version.minor = SSLv3_MINOR;
- }
- else if (pv.minor == TLSv1_MINOR) {
- /* turn off tls 1.1+ */
- WOLFSSL_MSG("\tdowngrading to TLSv1");
- ssl->options.tls1_1 = 0;
- ssl->version.minor = TLSv1_MINOR;
- }
- else if (pv.minor == TLSv1_1_MINOR) {
- WOLFSSL_MSG("\tdowngrading to TLSv1.1");
- ssl->version.minor = TLSv1_1_MINOR;
- }
- else if (pv.minor == TLSv1_2_MINOR) {
- WOLFSSL_MSG(" downgrading to TLSv1.2");
- ssl->version.minor = TLSv1_2_MINOR;
- }
- }
- #ifdef OPENSSL_EXTRA
- /* check if option is set to not allow the current version
- * set from either wolfSSL_set_options or wolfSSL_CTX_set_options */
- if (!ssl->options.dtls && ssl->options.downgrade &&
- ssl->options.mask > 0) {
- if (ssl->version.minor == TLSv1_2_MINOR &&
- (ssl->options.mask & SSL_OP_NO_TLSv1_2) == SSL_OP_NO_TLSv1_2) {
- WOLFSSL_MSG("\tOption set to not allow TLSv1.2, Downgrading");
- ssl->version.minor = TLSv1_1_MINOR;
- }
- if (ssl->version.minor == TLSv1_1_MINOR &&
- (ssl->options.mask & SSL_OP_NO_TLSv1_1) == SSL_OP_NO_TLSv1_1) {
- WOLFSSL_MSG("\tOption set to not allow TLSv1.1, Downgrading");
- ssl->options.tls1_1 = 0;
- ssl->version.minor = TLSv1_MINOR;
- }
- if (ssl->version.minor == TLSv1_MINOR &&
- (ssl->options.mask & SSL_OP_NO_TLSv1) == SSL_OP_NO_TLSv1) {
- WOLFSSL_MSG("\tOption set to not allow TLSv1, Downgrading");
- ssl->options.tls = 0;
- ssl->options.tls1_1 = 0;
- ssl->version.minor = SSLv3_MINOR;
- }
- if (ssl->version.minor == SSLv3_MINOR &&
- (ssl->options.mask & SSL_OP_NO_SSLv3) == SSL_OP_NO_SSLv3) {
- WOLFSSL_MSG("\tError, option set to not allow SSLv3");
- return VERSION_ERROR;
- }
- if (ssl->version.minor < ssl->options.minDowngrade) {
- WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
- return VERSION_ERROR;
- }
- }
- #endif
- return 0;
- }
- /* handle processing of server_hello (2) */
- int DoServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
- word32 helloSz)
- {
- byte cs0; /* cipher suite bytes 0, 1 */
- byte cs1;
- ProtocolVersion pv;
- byte compression;
- word32 i = *inOutIdx;
- word32 begin = i;
- int ret;
- WOLFSSL_START(WC_FUNC_SERVER_HELLO_DO);
- WOLFSSL_ENTER("DoServerHello");
- #ifdef WOLFSSL_CALLBACKS
- if (ssl->hsInfoOn) AddPacketName(ssl, "ServerHello");
- if (ssl->toInfoOn) AddLateName("ServerHello", &ssl->timeoutInfo);
- #endif
- /* protocol version, random and session id length check */
- if (OPAQUE16_LEN + RAN_LEN + OPAQUE8_LEN > helloSz)
- return BUFFER_ERROR;
- /* protocol version */
- XMEMCPY(&pv, input + i, OPAQUE16_LEN);
- i += OPAQUE16_LEN;
- ret = CheckVersion(ssl, pv);
- if (ret != 0)
- return ret;
- #ifdef WOLFSSL_TLS13
- if (IsAtLeastTLSv1_3(pv)) {
- byte type = server_hello;
- return DoTls13ServerHello(ssl, input, inOutIdx, helloSz, &type);
- }
- #endif
- /* random */
- XMEMCPY(ssl->arrays->serverRandom, input + i, RAN_LEN);
- i += RAN_LEN;
- /* session id */
- ssl->arrays->sessionIDSz = input[i++];
- if (ssl->arrays->sessionIDSz > ID_LEN) {
- WOLFSSL_MSG("Invalid session ID size");
- ssl->arrays->sessionIDSz = 0;
- return BUFFER_ERROR;
- }
- else if (ssl->arrays->sessionIDSz) {
- if ((i - begin) + ssl->arrays->sessionIDSz > helloSz)
- return BUFFER_ERROR;
- XMEMCPY(ssl->arrays->sessionID, input + i,
- ssl->arrays->sessionIDSz);
- i += ssl->arrays->sessionIDSz;
- ssl->options.haveSessionId = 1;
- }
- /* suite and compression */
- if ((i - begin) + OPAQUE16_LEN + OPAQUE8_LEN > helloSz)
- return BUFFER_ERROR;
- cs0 = input[i++];
- cs1 = input[i++];
- #ifdef HAVE_SECURE_RENEGOTIATION
- if (ssl->secure_renegotiation && ssl->secure_renegotiation->enabled &&
- ssl->options.handShakeDone) {
- if (ssl->options.cipherSuite0 != cs0 ||
- ssl->options.cipherSuite != cs1) {
- WOLFSSL_MSG("Server changed cipher suite during scr");
- return MATCH_SUITE_ERROR;
- }
- }
- #endif
- ssl->options.cipherSuite0 = cs0;
- ssl->options.cipherSuite = cs1;
- compression = input[i++];
- #ifndef WOLFSSL_NO_STRICT_CIPHER_SUITE
- {
- word32 idx, found = 0;
- /* confirm server_hello cipher suite is one sent in client_hello */
- for (idx = 0; idx < ssl->suites->suiteSz; idx += 2) {
- if (ssl->suites->suites[idx] == cs0 &&
- ssl->suites->suites[idx+1] == cs1) {
- found = 1;
- break;
- }
- }
- if (!found) {
- WOLFSSL_MSG("ServerHello did not use cipher suite from ClientHello");
- return MATCH_SUITE_ERROR;
- }
- }
- #endif /* !WOLFSSL_NO_STRICT_CIPHER_SUITE */
- if (compression != NO_COMPRESSION && !ssl->options.usingCompression) {
- WOLFSSL_MSG("Server forcing compression w/o support");
- return COMPRESSION_ERROR;
- }
- if (compression != ZLIB_COMPRESSION && ssl->options.usingCompression) {
- WOLFSSL_MSG("Server refused compression, turning off");
- ssl->options.usingCompression = 0; /* turn off if server refused */
- }
- *inOutIdx = i;
- #ifdef HAVE_TLS_EXTENSIONS
- if ( (i - begin) < helloSz) {
- if (TLSX_SupportExtensions(ssl)) {
- word16 totalExtSz;
- if ((i - begin) + OPAQUE16_LEN > helloSz)
- return BUFFER_ERROR;
- ato16(&input[i], &totalExtSz);
- i += OPAQUE16_LEN;
- if ((i - begin) + totalExtSz > helloSz)
- return BUFFER_ERROR;
- if ((ret = TLSX_Parse(ssl, (byte *) input + i, totalExtSz,
- server_hello, NULL)))
- return ret;
- i += totalExtSz;
- *inOutIdx = i;
- }
- else
- *inOutIdx = begin + helloSz; /* skip extensions */
- }
- else
- ssl->options.haveEMS = 0; /* If no extensions, no EMS */
- #else
- {
- int allowExt = 0;
- byte pendingEMS = 0;
- if ( (i - begin) < helloSz) {
- if (ssl->version.major == SSLv3_MAJOR &&
- ssl->version.minor >= TLSv1_MINOR) {
- allowExt = 1;
- }
- #ifdef WOLFSSL_DTLS
- if (ssl->version.major == DTLS_MAJOR)
- allowExt = 1;
- #endif
- if (allowExt) {
- word16 totalExtSz;
- if ((i - begin) + OPAQUE16_LEN > helloSz)
- return BUFFER_ERROR;
- ato16(&input[i], &totalExtSz);
- i += OPAQUE16_LEN;
- if ((i - begin) + totalExtSz > helloSz)
- return BUFFER_ERROR;
- while (totalExtSz) {
- word16 extId, extSz;
- if (OPAQUE16_LEN + OPAQUE16_LEN > totalExtSz)
- return BUFFER_ERROR;
- ato16(&input[i], &extId);
- i += OPAQUE16_LEN;
- ato16(&input[i], &extSz);
- i += OPAQUE16_LEN;
- if (OPAQUE16_LEN + OPAQUE16_LEN + extSz > totalExtSz)
- return BUFFER_ERROR;
- if (extId == HELLO_EXT_EXTMS)
- pendingEMS = 1;
- else
- i += extSz;
- totalExtSz -= OPAQUE16_LEN + OPAQUE16_LEN + extSz;
- }
- *inOutIdx = i;
- }
- else
- *inOutIdx = begin + helloSz; /* skip extensions */
- }
- if (!pendingEMS && ssl->options.haveEMS)
- ssl->options.haveEMS = 0;
- }
- #endif
- ssl->options.serverState = SERVER_HELLO_COMPLETE;
- if (IsEncryptionOn(ssl, 0)) {
- *inOutIdx += ssl->keys.padSz;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMWrite &&
- ssl->specs.cipher_type == block) {
- *inOutIdx += MacSize(ssl);
- }
- #endif
- }
- #ifdef HAVE_SECRET_CALLBACK
- if (ssl->sessionSecretCb != NULL) {
- int secretSz = SECRET_LEN;
- ret = ssl->sessionSecretCb(ssl, ssl->session.masterSecret,
- &secretSz, ssl->sessionSecretCtx);
- if (ret != 0 || secretSz != SECRET_LEN)
- return SESSION_SECRET_CB_E;
- }
- #endif /* HAVE_SECRET_CALLBACK */
- ret = CompleteServerHello(ssl);
- WOLFSSL_LEAVE("DoServerHello", ret);
- WOLFSSL_END(WC_FUNC_SERVER_HELLO_DO);
- return ret;
- }
- #ifdef WOLFSSL_TLS13
- /* returns 1 if able to do TLS 1.3 otherwise 0 */
- static int TLSv1_3_Capable(WOLFSSL* ssl)
- {
- #ifndef WOLFSSL_TLS13
- return 0;
- #else
- int ret = 0;
- if (IsAtLeastTLSv1_3(ssl->ctx->method->version)) {
- ret = 1;
- }
- #ifdef OPENSSL_EXTRA
- if ((wolfSSL_get_options(ssl) & SSL_OP_NO_TLSv1_3)) {
- /* option set at run time to disable TLS 1.3 */
- ret = 0;
- }
- #endif
- return ret;
- #endif
- }
- #endif /* WOLFSSL_TLS13 */
- int CompleteServerHello(WOLFSSL* ssl)
- {
- int ret;
- if (!ssl->options.resuming) {
- byte* down = ssl->arrays->serverRandom + RAN_LEN -
- TLS13_DOWNGRADE_SZ - 1;
- byte vers = ssl->arrays->serverRandom[RAN_LEN - 1];
- #ifdef WOLFSSL_TLS13
- if (TLSv1_3_Capable(ssl)) {
- /* TLS v1.3 capable client not allowed to downgrade when
- * connecting to TLS v1.3 capable server unless cipher suite
- * demands it.
- */
- if (XMEMCMP(down, tls13Downgrade, TLS13_DOWNGRADE_SZ) == 0 &&
- (vers == 0 || vers == 1)) {
- SendAlert(ssl, alert_fatal, illegal_parameter);
- return VERSION_ERROR;
- }
- }
- else
- #endif
- if (ssl->ctx->method->version.major == SSLv3_MAJOR &&
- ssl->ctx->method->version.minor == TLSv1_2_MINOR) {
- /* TLS v1.2 capable client not allowed to downgrade when
- * connecting to TLS v1.2 capable server.
- */
- if (XMEMCMP(down, tls13Downgrade, TLS13_DOWNGRADE_SZ) == 0 &&
- vers == 0) {
- SendAlert(ssl, alert_fatal, illegal_parameter);
- return VERSION_ERROR;
- }
- }
- }
- else {
- if (DSH_CheckSessionId(ssl)) {
- if (SetCipherSpecs(ssl) == 0) {
- XMEMCPY(ssl->arrays->masterSecret,
- ssl->session.masterSecret, SECRET_LEN);
- #ifdef NO_OLD_TLS
- ret = DeriveTlsKeys(ssl);
- #else
- ret = -1; /* default value */
- #ifndef NO_TLS
- if (ssl->options.tls)
- ret = DeriveTlsKeys(ssl);
- #endif
- if (!ssl->options.tls)
- ret = DeriveKeys(ssl);
- #endif /* NO_OLD_TLS */
- ssl->options.serverState = SERVER_HELLODONE_COMPLETE;
- return ret;
- }
- else {
- WOLFSSL_MSG("Unsupported cipher suite, DoServerHello");
- return UNSUPPORTED_SUITE;
- }
- }
- else {
- WOLFSSL_MSG("Server denied resumption attempt");
- ssl->options.resuming = 0; /* server denied resumption try */
- }
- }
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- DtlsMsgPoolReset(ssl);
- }
- #endif
- return SetCipherSpecs(ssl);
- }
- #endif /* WOLFSSL_NO_TLS12 */
- /* Make sure client setup is valid for this suite, true on success */
- int VerifyClientSuite(WOLFSSL* ssl)
- {
- int havePSK = 0;
- byte first = ssl->options.cipherSuite0;
- byte second = ssl->options.cipherSuite;
- WOLFSSL_ENTER("VerifyClientSuite");
- #ifndef NO_PSK
- havePSK = ssl->options.havePSK;
- #endif
- if (CipherRequires(first, second, REQUIRES_PSK)) {
- WOLFSSL_MSG("Requires PSK");
- if (havePSK == 0) {
- WOLFSSL_MSG("Don't have PSK");
- return 0;
- }
- }
- return 1; /* success */
- }
- #ifndef WOLFSSL_NO_TLS12
- #ifndef NO_CERTS
- /* handle processing of certificate_request (13) */
- static int DoCertificateRequest(WOLFSSL* ssl, const byte* input, word32*
- inOutIdx, word32 size)
- {
- word16 len;
- word32 begin = *inOutIdx;
- #ifdef OPENSSL_EXTRA
- int ret;
- WOLFSSL_X509* x509 = NULL;
- WOLFSSL_EVP_PKEY* pkey = NULL;
- #endif
- WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_DO);
- WOLFSSL_ENTER("DoCertificateRequest");
- #ifdef WOLFSSL_CALLBACKS
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "CertificateRequest");
- if (ssl->toInfoOn)
- AddLateName("CertificateRequest", &ssl->timeoutInfo);
- #endif
- if (OPAQUE8_LEN > size)
- return BUFFER_ERROR;
- len = input[(*inOutIdx)++];
- if ((*inOutIdx - begin) + len > size)
- return BUFFER_ERROR;
- /* types, read in here */
- *inOutIdx += len;
- /* signature and hash signature algorithm */
- if (IsAtLeastTLSv1_2(ssl)) {
- if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
- return BUFFER_ERROR;
- ato16(input + *inOutIdx, &len);
- *inOutIdx += OPAQUE16_LEN;
- if ((*inOutIdx - begin) + len > size)
- return BUFFER_ERROR;
- if (PickHashSigAlgo(ssl, input + *inOutIdx, len) != 0 &&
- ssl->buffers.certificate &&
- ssl->buffers.certificate->buffer) {
- #ifdef HAVE_PK_CALLBACKS
- if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) {
- WOLFSSL_MSG("Using PK for client private key");
- return INVALID_PARAMETER;
- }
- #endif
- if (ssl->buffers.key && ssl->buffers.key->buffer) {
- return INVALID_PARAMETER;
- }
- }
- *inOutIdx += len;
- #ifdef WC_RSA_PSS
- ssl->pssAlgo = 0;
- if (ssl->suites->sigAlgo == rsa_pss_sa_algo)
- ssl->pssAlgo |= 1 << ssl->suites->hashAlgo;
- #endif
- }
- /* authorities */
- if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
- return BUFFER_ERROR;
- ato16(input + *inOutIdx, &len);
- *inOutIdx += OPAQUE16_LEN;
- if ((*inOutIdx - begin) + len > size)
- return BUFFER_ERROR;
- while (len) {
- word16 dnSz;
- if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
- return BUFFER_ERROR;
- ato16(input + *inOutIdx, &dnSz);
- *inOutIdx += OPAQUE16_LEN;
- if ((*inOutIdx - begin) + dnSz > size)
- return BUFFER_ERROR;
- *inOutIdx += dnSz;
- len -= OPAQUE16_LEN + dnSz;
- }
- #ifdef OPENSSL_EXTRA
- /* call client cert callback if no cert has been loaded */
- if ((ssl->ctx->CBClientCert != NULL) &&
- (!ssl->buffers.certificate || !ssl->buffers.certificate->buffer)) {
- ret = ssl->ctx->CBClientCert(ssl, &x509, &pkey);
- if (ret == 1) {
- if ((wolfSSL_use_certificate(ssl, x509) != WOLFSSL_SUCCESS) ||
- (wolfSSL_use_PrivateKey(ssl, pkey) != WOLFSSL_SUCCESS)) {
- return CLIENT_CERT_CB_ERROR;
- }
- wolfSSL_X509_free(x509);
- wolfSSL_EVP_PKEY_free(pkey);
- } else if (ret < 0) {
- return WOLFSSL_ERROR_WANT_X509_LOOKUP;
- }
- }
- #endif
- /* don't send client cert or cert verify if user hasn't provided
- cert and private key */
- if (ssl->buffers.certificate && ssl->buffers.certificate->buffer) {
- #ifdef HAVE_PK_CALLBACKS
- if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) {
- WOLFSSL_MSG("Using PK for client private key");
- ssl->options.sendVerify = SEND_CERT;
- }
- #endif
- if (ssl->buffers.key && ssl->buffers.key->buffer) {
- ssl->options.sendVerify = SEND_CERT;
- }
- }
- #ifdef OPENSSL_EXTRA
- else
- #else
- else if (IsTLS(ssl))
- #endif
- {
- ssl->options.sendVerify = SEND_BLANK_CERT;
- }
- if (IsEncryptionOn(ssl, 0)) {
- *inOutIdx += ssl->keys.padSz;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead)
- *inOutIdx += MacSize(ssl);
- #endif
- }
- WOLFSSL_LEAVE("DoCertificateRequest", 0);
- WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_DO);
- return 0;
- }
- #endif /* !NO_CERTS */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
- static int CheckCurveId(int tlsCurveId)
- {
- int ret = ECC_CURVE_ERROR;
- switch (tlsCurveId) {
- #if defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)
- #ifndef NO_ECC_SECP
- case WOLFSSL_ECC_SECP160R1: return ECC_SECP160R1_OID;
- #endif /* !NO_ECC_SECP */
- #ifdef HAVE_ECC_SECPR2
- case WOLFSSL_ECC_SECP160R2: return ECC_SECP160R2_OID;
- #endif /* HAVE_ECC_SECPR2 */
- #ifdef HAVE_ECC_KOBLITZ
- case WOLFSSL_ECC_SECP160K1: return ECC_SECP160K1_OID;
- #endif /* HAVE_ECC_KOBLITZ */
- #endif
- #if defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)
- #ifndef NO_ECC_SECP
- case WOLFSSL_ECC_SECP192R1: return ECC_SECP192R1_OID;
- #endif /* !NO_ECC_SECP */
- #ifdef HAVE_ECC_KOBLITZ
- case WOLFSSL_ECC_SECP192K1: return ECC_SECP192K1_OID;
- #endif /* HAVE_ECC_KOBLITZ */
- #endif
- #if defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)
- #ifndef NO_ECC_SECP
- case WOLFSSL_ECC_SECP224R1: return ECC_SECP224R1_OID;
- #endif /* !NO_ECC_SECP */
- #ifdef HAVE_ECC_KOBLITZ
- case WOLFSSL_ECC_SECP224K1: return ECC_SECP224K1_OID;
- #endif /* HAVE_ECC_KOBLITZ */
- #endif
- #ifdef HAVE_CURVE25519
- case WOLFSSL_ECC_X25519: return ECC_X25519_OID;
- #endif
- #if !defined(NO_ECC256) || defined(HAVE_ALL_CURVES)
- #ifndef NO_ECC_SECP
- case WOLFSSL_ECC_SECP256R1: return ECC_SECP256R1_OID;
- #endif /* !NO_ECC_SECP */
- #ifdef HAVE_ECC_KOBLITZ
- case WOLFSSL_ECC_SECP256K1: return ECC_SECP256K1_OID;
- #endif /* HAVE_ECC_KOBLITZ */
- #ifdef HAVE_ECC_BRAINPOOL
- case WOLFSSL_ECC_BRAINPOOLP256R1: return ECC_BRAINPOOLP256R1_OID;
- #endif /* HAVE_ECC_BRAINPOOL */
- #endif
- #ifdef HAVE_CURVE448
- case WOLFSSL_ECC_X448: return ECC_X448_OID;
- #endif
- #if defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)
- #ifndef NO_ECC_SECP
- case WOLFSSL_ECC_SECP384R1: return ECC_SECP384R1_OID;
- #endif /* !NO_ECC_SECP */
- #ifdef HAVE_ECC_BRAINPOOL
- case WOLFSSL_ECC_BRAINPOOLP384R1: return ECC_BRAINPOOLP384R1_OID;
- #endif /* HAVE_ECC_BRAINPOOL */
- #endif
- #if defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)
- #ifdef HAVE_ECC_BRAINPOOL
- case WOLFSSL_ECC_BRAINPOOLP512R1: return ECC_BRAINPOOLP512R1_OID;
- #endif /* HAVE_ECC_BRAINPOOL */
- #endif
- #if defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)
- #ifndef NO_ECC_SECP
- case WOLFSSL_ECC_SECP521R1: return ECC_SECP521R1_OID;
- #endif /* !NO_ECC_SECP */
- #endif
- }
- return ret;
- }
- #endif /* HAVE_ECC */
- /* Persistable DoServerKeyExchange arguments */
- typedef struct DskeArgs {
- byte* output; /* not allocated */
- #if !defined(NO_DH) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
- defined(HAVE_ED448)
- byte* verifySig;
- #endif
- word32 idx;
- word32 begin;
- #if !defined(NO_DH) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
- defined(HAVE_ED448)
- word16 verifySigSz;
- #endif
- word16 sigSz;
- byte sigAlgo;
- byte hashAlgo;
- #if !defined(NO_RSA) && defined(WC_RSA_PSS)
- int bits;
- #endif
- } DskeArgs;
- static void FreeDskeArgs(WOLFSSL* ssl, void* pArgs)
- {
- DskeArgs* args = (DskeArgs*)pArgs;
- (void)ssl;
- (void)args;
- #if !defined(NO_DH) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
- defined(HAVE_ED448)
- if (args->verifySig) {
- XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- args->verifySig = NULL;
- }
- #endif
- }
- #ifndef NO_DH
- static int GetDhPublicKey(WOLFSSL* ssl, const byte* input, word32 size,
- DskeArgs* args)
- {
- int ret = 0;
- word16 length;
- #ifdef HAVE_FFDHE
- const DhParams* params = NULL;
- int group = 0;
- #endif
- ssl->buffers.weOwnDH = 1;
- ssl->buffers.serverDH_P.buffer = NULL;
- ssl->buffers.serverDH_G.buffer = NULL;
- ssl->buffers.serverDH_Pub.buffer = NULL;
- /* p */
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_gdpk);
- }
- ato16(input + args->idx, &length);
- args->idx += OPAQUE16_LEN;
- if ((args->idx - args->begin) + length > size) {
- ERROR_OUT(BUFFER_ERROR, exit_gdpk);
- }
- if (length < ssl->options.minDhKeySz) {
- WOLFSSL_MSG("Server using a DH key that is too small");
- SendAlert(ssl, alert_fatal, handshake_failure);
- ERROR_OUT(DH_KEY_SIZE_E, exit_gdpk);
- }
- if (length > ssl->options.maxDhKeySz) {
- WOLFSSL_MSG("Server using a DH key that is too big");
- SendAlert(ssl, alert_fatal, handshake_failure);
- ERROR_OUT(DH_KEY_SIZE_E, exit_gdpk);
- }
- ssl->buffers.serverDH_P.buffer =
- (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- if (ssl->buffers.serverDH_P.buffer) {
- ssl->buffers.serverDH_P.length = length;
- }
- else {
- ERROR_OUT(MEMORY_ERROR, exit_gdpk);
- }
- XMEMCPY(ssl->buffers.serverDH_P.buffer, input + args->idx,
- length);
- args->idx += length;
- ssl->options.dhKeySz = length;
- /* g */
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_gdpk);
- }
- ato16(input + args->idx, &length);
- args->idx += OPAQUE16_LEN;
- if ((args->idx - args->begin) + length > size) {
- ERROR_OUT(BUFFER_ERROR, exit_gdpk);
- }
- ssl->buffers.serverDH_G.buffer =
- (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- if (ssl->buffers.serverDH_G.buffer) {
- ssl->buffers.serverDH_G.length = length;
- }
- else {
- ERROR_OUT(MEMORY_ERROR, exit_gdpk);
- }
- XMEMCPY(ssl->buffers.serverDH_G.buffer, input + args->idx,
- length);
- args->idx += length;
- /* pub */
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_gdpk);
- }
- ato16(input + args->idx, &length);
- args->idx += OPAQUE16_LEN;
- if ((args->idx - args->begin) + length > size) {
- ERROR_OUT(BUFFER_ERROR, exit_gdpk);
- }
- ssl->buffers.serverDH_Pub.buffer =
- (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- if (ssl->buffers.serverDH_Pub.buffer) {
- ssl->buffers.serverDH_Pub.length = length;
- }
- else {
- ERROR_OUT(MEMORY_ERROR, exit_gdpk);
- }
- XMEMCPY(ssl->buffers.serverDH_Pub.buffer, input + args->idx,
- length);
- args->idx += length;
- #ifdef HAVE_FFDHE
- switch (ssl->options.dhKeySz) {
- #ifdef HAVE_FFDHE_2048
- case 2048/8:
- params = wc_Dh_ffdhe2048_Get();
- group = WOLFSSL_FFDHE_2048;
- break;
- #endif
- #ifdef HAVE_FFDHE_3072
- case 3072/8:
- params = wc_Dh_ffdhe3072_Get();
- group = WOLFSSL_FFDHE_3072;
- break;
- #endif
- #ifdef HAVE_FFDHE_4096
- case 4096/8:
- params = wc_Dh_ffdhe4096_Get();
- group = WOLFSSL_FFDHE_4096;
- break;
- #endif
- #ifdef HAVE_FFDHE_6144
- case 6144/8:
- params = wc_Dh_ffdhe6144_Get();
- group = WOLFSSL_FFDHE_6144;
- break;
- #endif
- #ifdef HAVE_FFDHE_8192
- case 8192/8:
- params = wc_Dh_ffdhe8192_Get();
- group = WOLFSSL_FFDHE_8192;
- break;
- #endif
- default:
- break;
- }
- if (params == NULL || params->g_len != ssl->buffers.serverDH_G.length ||
- (XMEMCMP(ssl->buffers.serverDH_G.buffer, params->g,
- params->g_len) != 0) ||
- (XMEMCMP(ssl->buffers.serverDH_P.buffer, params->p,
- params->p_len) != 0)) {
- WOLFSSL_MSG("Server not using FFDHE parameters");
- #ifdef WOLFSSL_REQUIRE_FFDHE
- SendAlert(ssl, alert_fatal, handshake_failure);
- ERROR_OUT(DH_PARAMS_NOT_FFDHE_E, exit_gdpk);
- #endif
- }
- else {
- ssl->namedGroup = group;
- #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
- !defined(HAVE_SELFTEST)
- ssl->options.dhDoKeyTest = 0;
- #endif
- }
- #endif /* HAVE_FFDHE */
- exit_gdpk:
- return ret;
- }
- #endif
- /* handle processing of server_key_exchange (12) */
- static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input,
- word32* inOutIdx, word32 size)
- {
- int ret = 0;
- #ifdef WOLFSSL_ASYNC_CRYPT
- DskeArgs* args = (DskeArgs*)ssl->async.args;
- typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
- (void)sizeof(args_test);
- #else
- DskeArgs args[1];
- #endif
- (void)input;
- (void)size;
- WOLFSSL_START(WC_FUNC_SERVER_KEY_EXCHANGE_DO);
- WOLFSSL_ENTER("DoServerKeyExchange");
- #ifdef WOLFSSL_ASYNC_CRYPT
- ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
- if (ret != WC_NOT_PENDING_E) {
- /* Check for error */
- if (ret < 0)
- goto exit_dske;
- }
- else
- #endif
- {
- /* Reset state */
- ret = 0;
- ssl->options.asyncState = TLS_ASYNC_BEGIN;
- XMEMSET(args, 0, sizeof(DskeArgs));
- args->idx = *inOutIdx;
- args->begin = *inOutIdx;
- args->sigAlgo = ssl->specs.sig_algo;
- args->hashAlgo = sha_mac;
- #ifdef WOLFSSL_ASYNC_CRYPT
- ssl->async.freeArgs = FreeDskeArgs;
- #endif
- }
- switch(ssl->options.asyncState)
- {
- case TLS_ASYNC_BEGIN:
- {
- #ifdef WOLFSSL_CALLBACKS
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "ServerKeyExchange");
- if (ssl->toInfoOn)
- AddLateName("ServerKeyExchange", &ssl->timeoutInfo);
- #endif
- switch(ssl->specs.kea)
- {
- #ifndef NO_PSK
- case psk_kea:
- {
- int srvHintLen;
- word16 length;
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- ato16(input + args->idx, &length);
- args->idx += OPAQUE16_LEN;
- if ((args->idx - args->begin) + length > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- /* get PSK server hint from the wire */
- srvHintLen = min(length, MAX_PSK_ID_LEN);
- XMEMCPY(ssl->arrays->server_hint, input + args->idx,
- srvHintLen);
- ssl->arrays->server_hint[srvHintLen] = '\0'; /* null term */
- args->idx += length;
- break;
- }
- #endif /* !NO_PSK */
- #ifndef NO_DH
- case diffie_hellman_kea:
- {
- ret = GetDhPublicKey(ssl, input, size, args);
- if (ret != 0)
- goto exit_dske;
- break;
- }
- #endif /* !NO_DH */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)
- case ecc_diffie_hellman_kea:
- {
- byte b;
- #ifdef HAVE_ECC
- int curveId;
- #endif
- int curveOid;
- word16 length;
- if ((args->idx - args->begin) + ENUM_LEN + OPAQUE16_LEN +
- OPAQUE8_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- b = input[args->idx++];
- if (b != named_curve) {
- ERROR_OUT(ECC_CURVETYPE_ERROR, exit_dske);
- }
- args->idx += 1; /* curve type, eat leading 0 */
- b = input[args->idx++];
- if ((curveOid = CheckCurveId(b)) < 0) {
- ERROR_OUT(ECC_CURVE_ERROR, exit_dske);
- }
- ssl->ecdhCurveOID = curveOid;
- #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
- ssl->namedGroup = 0;
- #endif
- length = input[args->idx++];
- if ((args->idx - args->begin) + length > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- #ifdef HAVE_CURVE25519
- if (ssl->ecdhCurveOID == ECC_X25519_OID) {
- if (ssl->peerX25519Key == NULL) {
- ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
- (void**)&ssl->peerX25519Key);
- if (ret != 0) {
- goto exit_dske;
- }
- } else if (ssl->peerX25519KeyPresent) {
- ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE25519,
- ssl->peerX25519Key);
- ssl->peerX25519KeyPresent = 0;
- if (ret != 0) {
- goto exit_dske;
- }
- }
- if ((ret = wc_curve25519_check_public(
- input + args->idx, length,
- EC25519_LITTLE_ENDIAN)) != 0) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (ret == BUFFER_E)
- SendAlert(ssl, alert_fatal, decode_error);
- else if (ret == ECC_OUT_OF_RANGE_E)
- SendAlert(ssl, alert_fatal, bad_record_mac);
- else {
- SendAlert(ssl, alert_fatal, illegal_parameter);
- }
- #endif
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
- }
- if (wc_curve25519_import_public_ex(input + args->idx,
- length, ssl->peerX25519Key,
- EC25519_LITTLE_ENDIAN) != 0) {
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
- }
- args->idx += length;
- ssl->peerX25519KeyPresent = 1;
- break;
- }
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->ecdhCurveOID == ECC_X448_OID) {
- if (ssl->peerX448Key == NULL) {
- ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
- (void**)&ssl->peerX448Key);
- if (ret != 0) {
- goto exit_dske;
- }
- } else if (ssl->peerX448KeyPresent) {
- ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE448,
- ssl->peerX448Key);
- ssl->peerX448KeyPresent = 0;
- if (ret != 0) {
- goto exit_dske;
- }
- }
- if ((ret = wc_curve448_check_public(
- input + args->idx, length,
- EC448_LITTLE_ENDIAN)) != 0) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (ret == BUFFER_E)
- SendAlert(ssl, alert_fatal, decode_error);
- else if (ret == ECC_OUT_OF_RANGE_E)
- SendAlert(ssl, alert_fatal, bad_record_mac);
- else {
- SendAlert(ssl, alert_fatal, illegal_parameter);
- }
- #endif
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
- }
- if (wc_curve448_import_public_ex(input + args->idx,
- length, ssl->peerX448Key,
- EC448_LITTLE_ENDIAN) != 0) {
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
- }
- args->idx += length;
- ssl->peerX448KeyPresent = 1;
- break;
- }
- #endif
- #ifdef HAVE_ECC
- if (ssl->peerEccKey == NULL) {
- ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
- (void**)&ssl->peerEccKey);
- if (ret != 0) {
- goto exit_dske;
- }
- } else if (ssl->peerEccKeyPresent) {
- ret = ReuseKey(ssl, DYNAMIC_TYPE_ECC, ssl->peerEccKey);
- ssl->peerEccKeyPresent = 0;
- if (ret != 0) {
- goto exit_dske;
- }
- }
- curveId = wc_ecc_get_oid(curveOid, NULL, NULL);
- if (wc_ecc_import_x963_ex(input + args->idx, length,
- ssl->peerEccKey, curveId) != 0) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, illegal_parameter);
- #endif
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
- }
- args->idx += length;
- ssl->peerEccKeyPresent = 1;
- #endif
- break;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #if !defined(NO_DH) && !defined(NO_PSK)
- case dhe_psk_kea:
- {
- int srvHintLen;
- word16 length;
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- ato16(input + args->idx, &length);
- args->idx += OPAQUE16_LEN;
- if ((args->idx - args->begin) + length > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- /* get PSK server hint from the wire */
- srvHintLen = min(length, MAX_PSK_ID_LEN);
- XMEMCPY(ssl->arrays->server_hint, input + args->idx,
- srvHintLen);
- ssl->arrays->server_hint[srvHintLen] = '\0'; /* null term */
- args->idx += length;
- ret = GetDhPublicKey(ssl, input, size, args);
- if (ret != 0)
- goto exit_dske;
- break;
- }
- #endif /* !NO_DH && !NO_PSK */
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && !defined(NO_PSK)
- case ecdhe_psk_kea:
- {
- byte b;
- int curveOid, curveId;
- int srvHintLen;
- word16 length;
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- ato16(input + args->idx, &length);
- args->idx += OPAQUE16_LEN;
- if ((args->idx - args->begin) + length > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- /* get PSK server hint from the wire */
- srvHintLen = min(length, MAX_PSK_ID_LEN);
- XMEMCPY(ssl->arrays->server_hint, input + args->idx,
- srvHintLen);
- ssl->arrays->server_hint[srvHintLen] = '\0'; /* null term */
- args->idx += length;
- if ((args->idx - args->begin) + ENUM_LEN + OPAQUE16_LEN +
- OPAQUE8_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- /* Check curve name and ID */
- b = input[args->idx++];
- if (b != named_curve) {
- ERROR_OUT(ECC_CURVETYPE_ERROR, exit_dske);
- }
- args->idx += 1; /* curve type, eat leading 0 */
- b = input[args->idx++];
- if ((curveOid = CheckCurveId(b)) < 0) {
- ERROR_OUT(ECC_CURVE_ERROR, exit_dske);
- }
- length = input[args->idx++];
- if ((args->idx - args->begin) + length > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- #ifdef HAVE_CURVE25519
- if (ssl->ecdhCurveOID == ECC_X25519_OID) {
- if (ssl->peerX25519Key == NULL) {
- ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
- (void**)&ssl->peerX25519Key);
- if (ret != 0) {
- goto exit_dske;
- }
- } else if (ssl->peerEccKeyPresent) {
- ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE25519,
- ssl->peerX25519Key);
- ssl->peerX25519KeyPresent = 0;
- if (ret != 0) {
- goto exit_dske;
- }
- }
- if ((ret = wc_curve25519_check_public(
- input + args->idx, length,
- EC25519_LITTLE_ENDIAN)) != 0) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (ret == BUFFER_E)
- SendAlert(ssl, alert_fatal, decode_error);
- else if (ret == ECC_OUT_OF_RANGE_E)
- SendAlert(ssl, alert_fatal, bad_record_mac);
- else {
- SendAlert(ssl, alert_fatal, illegal_parameter);
- }
- #endif
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
- }
- if (wc_curve25519_import_public_ex(input + args->idx,
- length, ssl->peerX25519Key,
- EC25519_LITTLE_ENDIAN) != 0) {
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
- }
- args->idx += length;
- ssl->peerX25519KeyPresent = 1;
- break;
- }
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->ecdhCurveOID == ECC_X448_OID) {
- if (ssl->peerX448Key == NULL) {
- ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
- (void**)&ssl->peerX448Key);
- if (ret != 0) {
- goto exit_dske;
- }
- } else if (ssl->peerEccKeyPresent) {
- ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE448,
- ssl->peerX448Key);
- ssl->peerX448KeyPresent = 0;
- if (ret != 0) {
- goto exit_dske;
- }
- }
- if ((ret = wc_curve448_check_public(
- input + args->idx, length,
- EC448_LITTLE_ENDIAN)) != 0) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (ret == BUFFER_E)
- SendAlert(ssl, alert_fatal, decode_error);
- else if (ret == ECC_OUT_OF_RANGE_E)
- SendAlert(ssl, alert_fatal, bad_record_mac);
- else {
- SendAlert(ssl, alert_fatal, illegal_parameter);
- }
- #endif
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
- }
- if (wc_curve448_import_public_ex(input + args->idx,
- length, ssl->peerX448Key,
- EC448_LITTLE_ENDIAN) != 0) {
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
- }
- args->idx += length;
- ssl->peerX448KeyPresent = 1;
- break;
- }
- #endif
- if (ssl->peerEccKey == NULL) {
- ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
- (void**)&ssl->peerEccKey);
- if (ret != 0) {
- goto exit_dske;
- }
- } else if (ssl->peerEccKeyPresent) {
- ret = ReuseKey(ssl, DYNAMIC_TYPE_ECC, ssl->peerEccKey);
- ssl->peerEccKeyPresent = 0;
- if (ret != 0) {
- goto exit_dske;
- }
- }
- curveId = wc_ecc_get_oid(curveOid, NULL, NULL);
- if (wc_ecc_import_x963_ex(input + args->idx, length,
- ssl->peerEccKey, curveId) != 0) {
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
- }
- args->idx += length;
- ssl->peerEccKeyPresent = 1;
- break;
- }
- #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
- default:
- ret = BAD_KEA_TYPE_E;
- } /* switch(ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_dske;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_BUILD;
- } /* case TLS_ASYNC_BEGIN */
- FALL_THROUGH;
- case TLS_ASYNC_BUILD:
- {
- switch(ssl->specs.kea)
- {
- case psk_kea:
- case dhe_psk_kea:
- case ecdhe_psk_kea:
- {
- /* Nothing to do in this sub-state */
- break;
- }
- case diffie_hellman_kea:
- case ecc_diffie_hellman_kea:
- {
- #if defined(NO_DH) && !defined(HAVE_ECC) && !defined(HAVE_ED25519) \
- && !defined(HAVE_ED448)
- ERROR_OUT(NOT_COMPILED_IN, exit_dske);
- #else
- enum wc_HashType hashType;
- word16 verifySz;
- if (ssl->options.usingAnon_cipher) {
- break;
- }
- verifySz = (word16)(args->idx - args->begin);
- if (verifySz > MAX_DH_SZ) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- if (IsAtLeastTLSv1_2(ssl)) {
- if ((args->idx - args->begin) + ENUM_LEN + ENUM_LEN >
- size) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- DecodeSigAlg(&input[args->idx], &args->hashAlgo,
- &args->sigAlgo);
- args->idx += 2;
- hashType = HashAlgoToType(args->hashAlgo);
- if (hashType == WC_HASH_TYPE_NONE) {
- ERROR_OUT(ALGO_ID_E, exit_dske);
- }
- } else {
- /* only using sha and md5 for rsa */
- #ifndef NO_OLD_TLS
- hashType = WC_HASH_TYPE_SHA;
- if (args->sigAlgo == rsa_sa_algo) {
- hashType = WC_HASH_TYPE_MD5_SHA;
- }
- #else
- ERROR_OUT(ALGO_ID_E, exit_dske);
- #endif
- }
- /* signature */
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- ato16(input + args->idx, &args->verifySigSz);
- args->idx += OPAQUE16_LEN;
- if ((args->idx - args->begin) + args->verifySigSz > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- /* buffer for signature */
- ssl->buffers.sig.buffer = (byte*)XMALLOC(SEED_LEN + verifySz,
- ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- if (ssl->buffers.sig.buffer == NULL) {
- ERROR_OUT(MEMORY_E, exit_dske);
- }
- ssl->buffers.sig.length = SEED_LEN + verifySz;
- /* build message to hash */
- XMEMCPY(ssl->buffers.sig.buffer,
- ssl->arrays->clientRandom, RAN_LEN);
- XMEMCPY(&ssl->buffers.sig.buffer[RAN_LEN],
- ssl->arrays->serverRandom, RAN_LEN);
- XMEMCPY(&ssl->buffers.sig.buffer[RAN_LEN * 2],
- input + args->begin, verifySz); /* message */
- if (args->sigAlgo != ed25519_sa_algo) {
- int digest_sz = wc_HashGetDigestSize(hashType);
- if (digest_sz <= 0) {
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- ssl->buffers.digest.length = (unsigned int)digest_sz;
- /* buffer for hash */
- ssl->buffers.digest.buffer = (byte*)XMALLOC(
- ssl->buffers.digest.length, ssl->heap,
- DYNAMIC_TYPE_DIGEST);
- if (ssl->buffers.digest.buffer == NULL) {
- ERROR_OUT(MEMORY_E, exit_dske);
- }
- /* Perform hash */
- ret = wc_Hash(hashType, ssl->buffers.sig.buffer,
- ssl->buffers.sig.length,
- ssl->buffers.digest.buffer,
- ssl->buffers.digest.length);
- if (ret != 0) {
- goto exit_dske;
- }
- }
- switch (args->sigAlgo)
- {
- #ifndef NO_RSA
- #ifdef WC_RSA_PSS
- case rsa_pss_sa_algo:
- #endif
- case rsa_sa_algo:
- {
- if (ssl->peerRsaKey == NULL ||
- !ssl->peerRsaKeyPresent) {
- ERROR_OUT(NO_PEER_KEY, exit_dske);
- }
- break;
- }
- #endif /* !NO_RSA */
- #ifdef HAVE_ECC
- case ecc_dsa_sa_algo:
- {
- if (!ssl->peerEccDsaKeyPresent) {
- ERROR_OUT(NO_PEER_KEY, exit_dske);
- }
- break;
- }
- #endif /* HAVE_ECC */
- #if defined(HAVE_ED25519)
- case ed25519_sa_algo:
- {
- if (!ssl->peerEd25519KeyPresent) {
- ERROR_OUT(NO_PEER_KEY, exit_dske);
- }
- break;
- }
- #endif /* HAVE_ED25519 */
- #if defined(HAVE_ED448)
- case ed448_sa_algo:
- {
- if (!ssl->peerEd448KeyPresent) {
- ERROR_OUT(NO_PEER_KEY, exit_dske);
- }
- break;
- }
- #endif /* HAVE_ED448 */
- default:
- ret = ALGO_ID_E;
- } /* switch (args->sigAlgo) */
- #endif /* NO_DH && !HAVE_ECC && !HAVE_ED25519 && !HAVE_ED448 */
- break;
- }
- default:
- ret = BAD_KEA_TYPE_E;
- } /* switch(ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_dske;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_DO;
- } /* case TLS_ASYNC_BUILD */
- FALL_THROUGH;
- case TLS_ASYNC_DO:
- {
- switch(ssl->specs.kea)
- {
- case psk_kea:
- case dhe_psk_kea:
- case ecdhe_psk_kea:
- {
- /* Nothing to do in this sub-state */
- break;
- }
- case diffie_hellman_kea:
- case ecc_diffie_hellman_kea:
- {
- #if defined(NO_DH) && !defined(HAVE_ECC) && !defined(HAVE_ED25519) \
- && !defined(HAVE_ED448)
- ERROR_OUT(NOT_COMPILED_IN, exit_dske);
- #else
- if (ssl->options.usingAnon_cipher) {
- break;
- }
- if (args->verifySig == NULL) {
- args->verifySig = (byte*)XMALLOC(args->verifySigSz,
- ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- if (args->verifySig == NULL) {
- ERROR_OUT(MEMORY_E, exit_dske);
- }
- XMEMCPY(args->verifySig, input + args->idx,
- args->verifySigSz);
- }
- switch (args->sigAlgo)
- {
- #ifndef NO_RSA
- #ifdef WC_RSA_PSS
- case rsa_pss_sa_algo:
- #endif
- case rsa_sa_algo:
- {
- ret = RsaVerify(ssl,
- args->verifySig, args->verifySigSz,
- &args->output,
- args->sigAlgo, args->hashAlgo,
- ssl->peerRsaKey,
- #ifdef HAVE_PK_CALLBACKS
- &ssl->buffers.peerRsaKey
- #else
- NULL
- #endif
- );
- if (ret >= 0) {
- args->sigSz = (word16)ret;
- #ifdef WC_RSA_PSS
- args->bits = mp_count_bits(&ssl->peerRsaKey->n);
- #endif
- ret = 0;
- }
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret != WC_PENDING_E)
- #endif
- {
- /* peerRsaKey */
- FreeKey(ssl, DYNAMIC_TYPE_RSA,
- (void**)&ssl->peerRsaKey);
- ssl->peerRsaKeyPresent = 0;
- }
- break;
- }
- #endif /* !NO_RSA */
- #ifdef HAVE_ECC
- case ecc_dsa_sa_algo:
- {
- ret = EccVerify(ssl,
- args->verifySig, args->verifySigSz,
- ssl->buffers.digest.buffer,
- ssl->buffers.digest.length,
- ssl->peerEccDsaKey,
- #ifdef HAVE_PK_CALLBACKS
- &ssl->buffers.peerEccDsaKey
- #else
- NULL
- #endif
- );
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret != WC_PENDING_E)
- #endif
- {
- /* peerEccDsaKey */
- FreeKey(ssl, DYNAMIC_TYPE_ECC,
- (void**)&ssl->peerEccDsaKey);
- ssl->peerEccDsaKeyPresent = 0;
- }
- break;
- }
- #endif /* HAVE_ECC */
- #if defined(HAVE_ED25519)
- case ed25519_sa_algo:
- {
- ret = Ed25519Verify(ssl,
- args->verifySig, args->verifySigSz,
- ssl->buffers.sig.buffer,
- ssl->buffers.sig.length,
- ssl->peerEd25519Key,
- #ifdef HAVE_PK_CALLBACKS
- &ssl->buffers.peerEd25519Key
- #else
- NULL
- #endif
- );
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret != WC_PENDING_E)
- #endif
- {
- /* peerEccDsaKey */
- FreeKey(ssl, DYNAMIC_TYPE_ED25519,
- (void**)&ssl->peerEd25519Key);
- ssl->peerEd25519KeyPresent = 0;
- }
- break;
- }
- #endif /* HAVE_ED25519 */
- #if defined(HAVE_ED448)
- case ed448_sa_algo:
- {
- ret = Ed448Verify(ssl,
- args->verifySig, args->verifySigSz,
- ssl->buffers.sig.buffer,
- ssl->buffers.sig.length,
- ssl->peerEd448Key,
- #ifdef HAVE_PK_CALLBACKS
- &ssl->buffers.peerEd448Key
- #else
- NULL
- #endif
- );
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret != WC_PENDING_E)
- #endif
- {
- /* peerEccDsaKey */
- FreeKey(ssl, DYNAMIC_TYPE_ED448,
- (void**)&ssl->peerEd448Key);
- ssl->peerEd448KeyPresent = 0;
- }
- break;
- }
- #endif /* HAVE_ED448 */
- default:
- ret = ALGO_ID_E;
- } /* switch (sigAlgo) */
- #endif /* NO_DH && !HAVE_ECC && !HAVE_ED25519 && !HAVE_ED448 */
- break;
- }
- default:
- ret = BAD_KEA_TYPE_E;
- } /* switch(ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_dske;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_VERIFY;
- } /* case TLS_ASYNC_DO */
- FALL_THROUGH;
- case TLS_ASYNC_VERIFY:
- {
- switch(ssl->specs.kea)
- {
- case psk_kea:
- case dhe_psk_kea:
- case ecdhe_psk_kea:
- {
- /* Nothing to do in this sub-state */
- break;
- }
- case diffie_hellman_kea:
- case ecc_diffie_hellman_kea:
- {
- #if defined(NO_DH) && !defined(HAVE_ECC) && !defined(HAVE_ED25519) \
- && !defined(HAVE_ED448)
- ERROR_OUT(NOT_COMPILED_IN, exit_dske);
- #else
- if (ssl->options.usingAnon_cipher) {
- break;
- }
- /* increment index after verify is done */
- args->idx += args->verifySigSz;
- switch(args->sigAlgo)
- {
- #ifndef NO_RSA
- #ifdef WC_RSA_PSS
- case rsa_pss_sa_algo:
- #ifdef HAVE_SELFTEST
- ret = wc_RsaPSS_CheckPadding(
- ssl->buffers.digest.buffer,
- ssl->buffers.digest.length,
- args->output, args->sigSz,
- HashAlgoToType(args->hashAlgo));
- #else
- ret = wc_RsaPSS_CheckPadding_ex(
- ssl->buffers.digest.buffer,
- ssl->buffers.digest.length,
- args->output, args->sigSz,
- HashAlgoToType(args->hashAlgo),
- -1, args->bits);
- #endif
- if (ret != 0)
- return ret;
- break;
- #endif
- case rsa_sa_algo:
- {
- if (IsAtLeastTLSv1_2(ssl)) {
- #ifdef WOLFSSL_SMALL_STACK
- byte* encodedSig;
- #else
- byte encodedSig[MAX_ENCODED_SIG_SZ];
- #endif
- word32 encSigSz;
- #ifdef WOLFSSL_SMALL_STACK
- encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
- ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- if (encodedSig == NULL) {
- ERROR_OUT(MEMORY_E, exit_dske);
- }
- #endif
- encSigSz = wc_EncodeSignature(encodedSig,
- ssl->buffers.digest.buffer,
- ssl->buffers.digest.length,
- TypeHash(args->hashAlgo));
- if (encSigSz != args->sigSz || !args->output ||
- XMEMCMP(args->output, encodedSig,
- min(encSigSz, MAX_ENCODED_SIG_SZ)) != 0) {
- ret = VERIFY_SIGN_ERROR;
- }
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(encodedSig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- #endif
- if (ret != 0) {
- goto exit_dske;
- }
- }
- else if (args->sigSz != FINISHED_SZ ||
- !args->output ||
- XMEMCMP(args->output,
- ssl->buffers.digest.buffer,
- FINISHED_SZ) != 0) {
- ERROR_OUT(VERIFY_SIGN_ERROR, exit_dske);
- }
- break;
- }
- #endif /* !NO_RSA */
- #ifdef HAVE_ECC
- case ecc_dsa_sa_algo:
- /* Nothing to do in this algo */
- break;
- #endif /* HAVE_ECC */
- #if defined(HAVE_ED25519)
- case ed25519_sa_algo:
- /* Nothing to do in this algo */
- break;
- #endif /* HAVE_ED25519 */
- #if defined(HAVE_ED448)
- case ed448_sa_algo:
- /* Nothing to do in this algo */
- break;
- #endif /* HAVE_ED448 */
- default:
- ret = ALGO_ID_E;
- } /* switch (sigAlgo) */
- #endif /* NO_DH && !HAVE_ECC && !HAVE_ED25519 && !HAVE_ED448 */
- break;
- }
- default:
- ret = BAD_KEA_TYPE_E;
- } /* switch(ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_dske;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_FINALIZE;
- } /* case TLS_ASYNC_VERIFY */
- FALL_THROUGH;
- case TLS_ASYNC_FINALIZE:
- {
- if (IsEncryptionOn(ssl, 0)) {
- args->idx += ssl->keys.padSz;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead)
- args->idx += MacSize(ssl);
- #endif
- }
- /* QSH extensions */
- #ifdef HAVE_QSH
- if (ssl->peerQSHKeyPresent) {
- word16 name;
- int qshSz;
- /* extension name */
- ato16(input + args->idx, &name);
- args->idx += OPAQUE16_LEN;
- if (name == TLSX_QUANTUM_SAFE_HYBRID) {
- /* if qshSz is larger than 0 it is the length of
- buffer used */
- if ((qshSz = TLSX_QSHCipher_Parse(ssl, input + args->idx,
- size, 0)) < 0) {
- ERROR_OUT(qshSz, exit_dske);
- }
- args->idx += qshSz;
- }
- else {
- /* unknown extension sent server ignored handshake */
- ERROR_OUT(BUFFER_ERROR, exit_dske);
- }
- }
- #endif
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_END;
- } /* case TLS_ASYNC_FINALIZE */
- FALL_THROUGH;
- case TLS_ASYNC_END:
- {
- /* return index */
- *inOutIdx = args->idx;
- ssl->options.serverState = SERVER_KEYEXCHANGE_COMPLETE;
- break;
- }
- default:
- ret = INPUT_CASE_ERROR;
- } /* switch(ssl->options.asyncState) */
- exit_dske:
- WOLFSSL_LEAVE("DoServerKeyExchange", ret);
- WOLFSSL_END(WC_FUNC_SERVER_KEY_EXCHANGE_DO);
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* Handle async operation */
- if (ret == WC_PENDING_E) {
- /* Mark message as not received so it can process again */
- ssl->msgsReceived.got_server_key_exchange = 0;
- return ret;
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- /* Final cleanup */
- FreeDskeArgs(ssl, args);
- FreeKeyExchange(ssl);
- return ret;
- }
- #ifdef HAVE_QSH
- #ifdef HAVE_NTRU
- /* Encrypt a byte array using ntru
- key a struct containing the public key to use
- bufIn array to be encrypted
- inSz size of bufIn array
- bufOut cipher text out
- outSz will be set to the new size of cipher text
- */
- static int NtruSecretEncrypt(QSHKey* key, byte* bufIn, word32 inSz,
- byte* bufOut, word16* outSz)
- {
- int ret;
- DRBG_HANDLE drbg;
- /* sanity checks on input arguments */
- if (key == NULL || bufIn == NULL || bufOut == NULL || outSz == NULL)
- return BAD_FUNC_ARG;
- if (key->pub.buffer == NULL)
- return BAD_FUNC_ARG;
- switch (key->name) {
- case WOLFSSL_NTRU_EESS439:
- case WOLFSSL_NTRU_EESS593:
- case WOLFSSL_NTRU_EESS743:
- break;
- default:
- WOLFSSL_MSG("Unknown QSH encryption key!");
- return -1;
- }
- /* set up ntru drbg */
- ret = ntru_crypto_drbg_external_instantiate(GetEntropy, &drbg);
- if (ret != DRBG_OK)
- return NTRU_DRBG_ERROR;
- /* encrypt the byte array */
- ret = ntru_crypto_ntru_encrypt(drbg, key->pub.length, key->pub.buffer,
- inSz, bufIn, outSz, bufOut);
- ntru_crypto_drbg_uninstantiate(drbg);
- if (ret != NTRU_OK)
- return NTRU_ENCRYPT_ERROR;
- return ret;
- }
- /* Decrypt a byte array using ntru
- key a struct containing the private key to use
- bufIn array to be decrypted
- inSz size of bufIn array
- bufOut plain text out
- outSz will be set to the new size of plain text
- */
- static int NtruSecretDecrypt(QSHKey* key, byte* bufIn, word32 inSz,
- byte* bufOut, word16* outSz)
- {
- int ret;
- DRBG_HANDLE drbg;
- /* sanity checks on input arguments */
- if (key == NULL || bufIn == NULL || bufOut == NULL || outSz == NULL)
- return BAD_FUNC_ARG;
- if (key->pri.buffer == NULL)
- return BAD_FUNC_ARG;
- switch (key->name) {
- case WOLFSSL_NTRU_EESS439:
- case WOLFSSL_NTRU_EESS593:
- case WOLFSSL_NTRU_EESS743:
- break;
- default:
- WOLFSSL_MSG("Unknown QSH decryption key!");
- return -1;
- }
- /* set up drbg */
- ret = ntru_crypto_drbg_external_instantiate(GetEntropy, &drbg);
- if (ret != DRBG_OK)
- return NTRU_DRBG_ERROR;
- /* decrypt cipher text */
- ret = ntru_crypto_ntru_decrypt(key->pri.length, key->pri.buffer,
- inSz, bufIn, outSz, bufOut);
- ntru_crypto_drbg_uninstantiate(drbg);
- if (ret != NTRU_OK)
- return NTRU_ENCRYPT_ERROR;
- return ret;
- }
- #endif /* HAVE_NTRU */
- int QSH_Init(WOLFSSL* ssl)
- {
- /* check so not initializing twice when running DTLS */
- if (ssl->QSH_secret != NULL)
- return 0;
- /* malloc memory for holding generated secret information */
- if ((ssl->QSH_secret = (QSHSecret*)XMALLOC(sizeof(QSHSecret), ssl->heap,
- DYNAMIC_TYPE_QSH)) == NULL)
- return MEMORY_E;
- ssl->QSH_secret->CliSi = (buffer*)XMALLOC(sizeof(buffer), ssl->heap,
- DYNAMIC_TYPE_SECRET);
- if (ssl->QSH_secret->CliSi == NULL)
- return MEMORY_E;
- ssl->QSH_secret->SerSi = (buffer*)XMALLOC(sizeof(buffer), ssl->heap,
- DYNAMIC_TYPE_SECRET);
- if (ssl->QSH_secret->SerSi == NULL)
- return MEMORY_E;
- /* initialize variables */
- ssl->QSH_secret->list = NULL;
- ssl->QSH_secret->CliSi->length = 0;
- ssl->QSH_secret->CliSi->buffer = NULL;
- ssl->QSH_secret->SerSi->length = 0;
- ssl->QSH_secret->SerSi->buffer = NULL;
- return 0;
- }
- static int QSH_Encrypt(QSHKey* key, byte* in, word32 szIn,
- byte* out, word32* szOut)
- {
- int ret = 0;
- word16 size = *szOut;
- (void)in;
- (void)szIn;
- (void)out;
- (void)szOut;
- WOLFSSL_MSG("Encrypting QSH key material");
- switch (key->name) {
- #ifdef HAVE_NTRU
- case WOLFSSL_NTRU_EESS439:
- case WOLFSSL_NTRU_EESS593:
- case WOLFSSL_NTRU_EESS743:
- ret = NtruSecretEncrypt(key, in, szIn, out, &size);
- break;
- #endif
- default:
- WOLFSSL_MSG("Unknown QSH encryption key!");
- return -1;
- }
- *szOut = size;
- return ret;
- }
- /* Decrypt using Quantum Safe Handshake algorithms */
- int QSH_Decrypt(QSHKey* key, byte* in, word32 szIn, byte* out, word16* szOut)
- {
- int ret = 0;
- word16 size = *szOut;
- (void)in;
- (void)szIn;
- (void)out;
- (void)szOut;
- WOLFSSL_MSG("Decrypting QSH key material");
- switch (key->name) {
- #ifdef HAVE_NTRU
- case WOLFSSL_NTRU_EESS439:
- case WOLFSSL_NTRU_EESS593:
- case WOLFSSL_NTRU_EESS743:
- ret = NtruSecretDecrypt(key, in, szIn, out, &size);
- break;
- #endif
- default:
- WOLFSSL_MSG("Unknown QSH decryption key!");
- return -1;
- }
- *szOut = size;
- return ret;
- }
- /* Get the max cipher text for corresponding encryption scheme
- (encrypting 48 or max plain text whichever is smaller)
- */
- static word32 QSH_MaxSecret(QSHKey* key)
- {
- int ret = 0;
- #ifdef HAVE_NTRU
- byte isNtru = 0;
- word16 inSz = 48;
- word16 outSz;
- DRBG_HANDLE drbg = 0;
- byte bufIn[48];
- #endif
- if (key == NULL || key->pub.length == 0)
- return 0;
- switch(key->name) {
- #ifdef HAVE_NTRU
- case WOLFSSL_NTRU_EESS439:
- isNtru = 1;
- break;
- case WOLFSSL_NTRU_EESS593:
- isNtru = 1;
- break;
- case WOLFSSL_NTRU_EESS743:
- isNtru = 1;
- break;
- #endif
- default:
- WOLFSSL_MSG("Unknown QSH encryption scheme size!");
- return 0;
- }
- #ifdef HAVE_NTRU
- if (isNtru) {
- ret = ntru_crypto_drbg_external_instantiate(GetEntropy, &drbg);
- if (ret != DRBG_OK)
- return NTRU_DRBG_ERROR;
- ret = ntru_crypto_ntru_encrypt(drbg, key->pub.length,
- key->pub.buffer, inSz, bufIn, &outSz, NULL);
- if (ret != NTRU_OK) {
- return NTRU_ENCRYPT_ERROR;
- }
- ntru_crypto_drbg_uninstantiate(drbg);
- ret = outSz;
- }
- #endif
- return ret;
- }
- /* Generate the secret byte material for pms
- returns length on success and -1 on fail
- */
- static int QSH_GenerateSerCliSecret(WOLFSSL* ssl, byte isServer)
- {
- int sz = 0;
- int plainSz = 48; /* lesser of 48 and max plain text able to encrypt */
- int offset = 0;
- word32 tmpSz = 0;
- buffer* buf;
- QSHKey* current;
- QSHScheme* schmPre = NULL;
- QSHScheme* schm = NULL;
- if (ssl == NULL)
- return -1;
- WOLFSSL_MSG("Generating QSH secret key material");
- current = ssl->peerQSHKey;
- /* get size of buffer needed */
- while (current) {
- if (current->pub.length != 0) {
- sz += plainSz;
- }
- current = (QSHKey*)current->next;
- }
- /* allocate memory for buffer */
- if (isServer) {
- buf = ssl->QSH_secret->SerSi;
- }
- else {
- buf = ssl->QSH_secret->CliSi;
- }
- buf->length = sz;
- buf->buffer = (byte*)XMALLOC(sz, ssl->heap, DYNAMIC_TYPE_SECRET);
- if (buf->buffer == NULL) {
- WOLFSSL_ERROR(MEMORY_E);
- }
- /* create secret information */
- sz = 0;
- current = ssl->peerQSHKey;
- while (current) {
- schm = (QSHScheme*)XMALLOC(sizeof(QSHScheme), ssl->heap,
- DYNAMIC_TYPE_QSH);
- if (schm == NULL)
- return MEMORY_E;
- /* initialize variables */
- schm->name = 0;
- schm->PK = NULL;
- schm->PKLen = 0;
- schm->next = NULL;
- if (ssl->QSH_secret->list == NULL) {
- ssl->QSH_secret->list = schm;
- }
- else {
- if (schmPre)
- schmPre->next = schm;
- }
- tmpSz = QSH_MaxSecret(current);
- if ((schm->PK = (byte*)XMALLOC(tmpSz, ssl->heap,
- DYNAMIC_TYPE_SECRET)) == NULL)
- return -1;
- /* store info for writing extension */
- schm->name = current->name;
- /* no key to use for encryption */
- if (tmpSz == 0) {
- current = (QSHKey*)current->next;
- continue;
- }
- if (wc_RNG_GenerateBlock(ssl->rng, buf->buffer + offset, plainSz)
- != 0) {
- return -1;
- }
- if (QSH_Encrypt(current, buf->buffer + offset, plainSz, schm->PK,
- &tmpSz) != 0) {
- return -1;
- }
- schm->PKLen = tmpSz;
- sz += tmpSz;
- offset += plainSz;
- schmPre = schm;
- current = (QSHKey*)current->next;
- }
- return sz;
- }
- static word32 QSH_KeyGetSize(WOLFSSL* ssl)
- {
- word32 sz = 0;
- QSHKey* current;
- if (ssl == NULL)
- return -1;
- current = ssl->peerQSHKey;
- sz += OPAQUE16_LEN; /* type of extension ie 0x00 0x18 */
- sz += OPAQUE24_LEN;
- /* get size of buffer needed */
- while (current) {
- sz += OPAQUE16_LEN; /* scheme id */
- sz += OPAQUE16_LEN; /* encrypted key len*/
- sz += QSH_MaxSecret(current);
- current = (QSHKey*)current->next;
- }
- return sz;
- }
- /* handle QSH key Exchange
- return 0 on success
- */
- static word32 QSH_KeyExchangeWrite(WOLFSSL* ssl, byte isServer)
- {
- int ret = 0;
- WOLFSSL_ENTER("QSH KeyExchange");
- ret = QSH_GenerateSerCliSecret(ssl, isServer);
- if (ret < 0)
- return MEMORY_E;
- return 0;
- }
- #endif /* HAVE_QSH */
- typedef struct SckeArgs {
- byte* output; /* not allocated */
- byte* encSecret;
- byte* input;
- word32 encSz;
- word32 length;
- int sendSz;
- int inputSz;
- } SckeArgs;
- static void FreeSckeArgs(WOLFSSL* ssl, void* pArgs)
- {
- SckeArgs* args = (SckeArgs*)pArgs;
- (void)ssl;
- if (args->encSecret) {
- XFREE(args->encSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
- args->encSecret = NULL;
- }
- if (args->input) {
- XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- args->input = NULL;
- }
- }
- /* handle generation client_key_exchange (16) */
- int SendClientKeyExchange(WOLFSSL* ssl)
- {
- int ret = 0;
- #ifdef WOLFSSL_ASYNC_CRYPT
- SckeArgs* args = (SckeArgs*)ssl->async.args;
- typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
- (void)sizeof(args_test);
- #else
- SckeArgs args[1];
- #endif
- WOLFSSL_START(WC_FUNC_CLIENT_KEY_EXCHANGE_SEND);
- WOLFSSL_ENTER("SendClientKeyExchange");
- #ifdef OPENSSL_EXTRA
- ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
- ssl->cbmode = SSL_CB_MODE_WRITE;
- if (ssl->CBIS != NULL)
- ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, SSL_SUCCESS);
- #endif
- #ifdef WOLFSSL_ASYNC_CRYPT
- ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
- if (ret != WC_NOT_PENDING_E) {
- /* Check for error */
- if (ret < 0)
- goto exit_scke;
- }
- else
- #endif
- {
- /* Reset state */
- ret = 0;
- ssl->options.asyncState = TLS_ASYNC_BEGIN;
- XMEMSET(args, 0, sizeof(SckeArgs));
- #ifdef WOLFSSL_ASYNC_CRYPT
- ssl->async.freeArgs = FreeSckeArgs;
- #endif
- }
- switch(ssl->options.asyncState)
- {
- case TLS_ASYNC_BEGIN:
- {
- switch (ssl->specs.kea) {
- #ifndef NO_RSA
- case rsa_kea:
- if (ssl->peerRsaKey == NULL ||
- ssl->peerRsaKeyPresent == 0) {
- ERROR_OUT(NO_PEER_KEY, exit_scke);
- }
- break;
- #endif
- #ifndef NO_DH
- case diffie_hellman_kea:
- if (ssl->buffers.serverDH_P.buffer == NULL ||
- ssl->buffers.serverDH_G.buffer == NULL ||
- ssl->buffers.serverDH_Pub.buffer == NULL) {
- ERROR_OUT(NO_PEER_KEY, exit_scke);
- }
- break;
- #endif /* NO_DH */
- #ifndef NO_PSK
- case psk_kea:
- /* sanity check that PSK client callback has been set */
- if (ssl->options.client_psk_cb == NULL) {
- WOLFSSL_MSG("No client PSK callback set");
- ERROR_OUT(PSK_KEY_ERROR, exit_scke);
- }
- break;
- #endif /* NO_PSK */
- #if !defined(NO_DH) && !defined(NO_PSK)
- case dhe_psk_kea:
- if (ssl->buffers.serverDH_P.buffer == NULL ||
- ssl->buffers.serverDH_G.buffer == NULL ||
- ssl->buffers.serverDH_Pub.buffer == NULL) {
- ERROR_OUT(NO_PEER_KEY, exit_scke);
- }
- /* sanity check that PSK client callback has been set */
- if (ssl->options.client_psk_cb == NULL) {
- WOLFSSL_MSG("No client PSK callback set");
- ERROR_OUT(PSK_KEY_ERROR, exit_scke);
- }
- break;
- #endif /* !NO_DH && !NO_PSK */
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && !defined(NO_PSK)
- case ecdhe_psk_kea:
- /* sanity check that PSK client callback has been set */
- if (ssl->options.client_psk_cb == NULL) {
- WOLFSSL_MSG("No client PSK callback set");
- ERROR_OUT(PSK_KEY_ERROR, exit_scke);
- }
- #ifdef HAVE_CURVE25519
- if (ssl->peerX25519KeyPresent) {
- /* Check client ECC public key */
- if (!ssl->peerX25519Key || !ssl->peerX25519Key->dp) {
- ERROR_OUT(NO_PEER_KEY, exit_scke);
- }
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->X25519SharedSecretCb != NULL) {
- break;
- }
- #endif
- /* create private key */
- ssl->hsType = DYNAMIC_TYPE_CURVE25519;
- ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
- if (ret != 0) {
- goto exit_scke;
- }
- ret = X25519MakeKey(ssl, (curve25519_key*)ssl->hsKey,
- ssl->peerX25519Key);
- break;
- }
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->peerX448KeyPresent) {
- /* Check client ECC public key */
- if (!ssl->peerX448Key) {
- ERROR_OUT(NO_PEER_KEY, exit_scke);
- }
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->X448SharedSecretCb != NULL) {
- break;
- }
- #endif
- /* create private key */
- ssl->hsType = DYNAMIC_TYPE_CURVE448;
- ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
- if (ret != 0) {
- goto exit_scke;
- }
- ret = X448MakeKey(ssl, (curve448_key*)ssl->hsKey,
- ssl->peerX448Key);
- break;
- }
- #endif
- /* Check client ECC public key */
- if (!ssl->peerEccKey || !ssl->peerEccKeyPresent ||
- !ssl->peerEccKey->dp) {
- ERROR_OUT(NO_PEER_KEY, exit_scke);
- }
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->EccSharedSecretCb != NULL) {
- break;
- }
- #endif
- /* create ephemeral private key */
- ssl->hsType = DYNAMIC_TYPE_ECC;
- ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
- if (ret != 0) {
- goto exit_scke;
- }
- ret = EccMakeKey(ssl, (ecc_key*)ssl->hsKey, ssl->peerEccKey);
- break;
- #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
- #ifdef HAVE_NTRU
- case ntru_kea:
- if (ssl->peerNtruKeyPresent == 0) {
- ERROR_OUT(NO_PEER_KEY, exit_scke);
- }
- break;
- #endif /* HAVE_NTRU */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)
- case ecc_diffie_hellman_kea:
- {
- #ifdef HAVE_ECC
- ecc_key* peerKey;
- #endif
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- #ifdef HAVE_CURVE25519
- if (ssl->ecdhCurveOID == ECC_X25519_OID) {
- if (ssl->ctx->X25519SharedSecretCb != NULL)
- break;
- }
- else
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->ecdhCurveOID == ECC_X448_OID) {
- if (ssl->ctx->X448SharedSecretCb != NULL)
- break;
- }
- else
- #endif
- if (ssl->ctx->EccSharedSecretCb != NULL) {
- break;
- }
- #endif /* HAVE_PK_CALLBACKS */
- #ifdef HAVE_CURVE25519
- if (ssl->peerX25519KeyPresent) {
- if (!ssl->peerX25519Key || !ssl->peerX25519Key->dp) {
- ERROR_OUT(NO_PEER_KEY, exit_scke);
- }
- /* create private key */
- ssl->hsType = DYNAMIC_TYPE_CURVE25519;
- ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
- if (ret != 0) {
- goto exit_scke;
- }
- ret = X25519MakeKey(ssl, (curve25519_key*)ssl->hsKey,
- ssl->peerX25519Key);
- break;
- }
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->peerX448KeyPresent) {
- if (!ssl->peerX448Key) {
- ERROR_OUT(NO_PEER_KEY, exit_scke);
- }
- /* create private key */
- ssl->hsType = DYNAMIC_TYPE_CURVE448;
- ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
- if (ret != 0) {
- goto exit_scke;
- }
- ret = X448MakeKey(ssl, (curve448_key*)ssl->hsKey,
- ssl->peerX448Key);
- break;
- }
- #endif
- #ifdef HAVE_ECC
- if (ssl->specs.static_ecdh) {
- /* Note: EccDsa is really fixed Ecc key here */
- if (!ssl->peerEccDsaKey || !ssl->peerEccDsaKeyPresent) {
- ERROR_OUT(NO_PEER_KEY, exit_scke);
- }
- peerKey = ssl->peerEccDsaKey;
- }
- else {
- if (!ssl->peerEccKey || !ssl->peerEccKeyPresent) {
- ERROR_OUT(NO_PEER_KEY, exit_scke);
- }
- peerKey = ssl->peerEccKey;
- }
- if (peerKey == NULL) {
- ERROR_OUT(NO_PEER_KEY, exit_scke);
- }
- /* create ephemeral private key */
- ssl->hsType = DYNAMIC_TYPE_ECC;
- ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
- if (ret != 0) {
- goto exit_scke;
- }
- ret = EccMakeKey(ssl, (ecc_key*)ssl->hsKey, peerKey);
- #endif
- break;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- default:
- ret = BAD_KEA_TYPE_E;
- } /* switch(ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_scke;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_BUILD;
- } /* case TLS_ASYNC_BEGIN */
- FALL_THROUGH;
- case TLS_ASYNC_BUILD:
- {
- args->encSz = MAX_ENCRYPT_SZ;
- args->encSecret = (byte*)XMALLOC(args->encSz, ssl->heap,
- DYNAMIC_TYPE_SECRET);
- if (args->encSecret == NULL) {
- ERROR_OUT(MEMORY_E, exit_scke);
- }
- if (ssl->arrays->preMasterSecret == NULL) {
- ssl->arrays->preMasterSz = ENCRYPT_LEN;
- ssl->arrays->preMasterSecret = (byte*)XMALLOC(ENCRYPT_LEN,
- ssl->heap, DYNAMIC_TYPE_SECRET);
- if (ssl->arrays->preMasterSecret == NULL) {
- ERROR_OUT(MEMORY_E, exit_scke);
- }
- XMEMSET(ssl->arrays->preMasterSecret, 0, ENCRYPT_LEN);
- }
- switch(ssl->specs.kea)
- {
- #ifndef NO_RSA
- case rsa_kea:
- {
- /* build PreMasterSecret with RNG data */
- #if defined(WOLFSSL_RENESAS_TSIP_TLS) && \
- !defined(NO_WOLFSSL_RENESAS_TSIP_TLS_SESSION)
- if (tsip_useable(ssl)) {
- ret = tsip_generatePremasterSecret(
- &ssl->arrays->preMasterSecret[VERSION_SZ],
- ENCRYPT_LEN - VERSION_SZ);
- } else {
- #endif
- ret = wc_RNG_GenerateBlock(ssl->rng,
- &ssl->arrays->preMasterSecret[VERSION_SZ],
- SECRET_LEN - VERSION_SZ);
- #if defined(WOLFSSL_RENESAS_TSIP_TLS) && \
- !defined(NO_WOLFSSL_RENESAS_TSIP_TLS_SESSION)
- }
- #endif
- if (ret != 0) {
- goto exit_scke;
- }
- ssl->arrays->preMasterSecret[0] = ssl->chVersion.major;
- ssl->arrays->preMasterSecret[1] = ssl->chVersion.minor;
- ssl->arrays->preMasterSz = SECRET_LEN;
- break;
- }
- #endif /* !NO_RSA */
- #ifndef NO_DH
- case diffie_hellman_kea:
- {
- ssl->buffers.sig.length = ENCRYPT_LEN;
- ssl->buffers.sig.buffer = (byte*)XMALLOC(ENCRYPT_LEN,
- ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- if (ssl->buffers.sig.buffer == NULL) {
- ERROR_OUT(MEMORY_E, exit_scke);
- }
- ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
- (void**)&ssl->buffers.serverDH_Key);
- if (ret != 0) {
- goto exit_scke;
- }
- #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \
- !defined(WOLFSSL_OLD_PRIME_CHECK)
- if (ssl->options.dhDoKeyTest &&
- !ssl->options.dhKeyTested)
- {
- ret = wc_DhSetCheckKey(ssl->buffers.serverDH_Key,
- ssl->buffers.serverDH_P.buffer,
- ssl->buffers.serverDH_P.length,
- ssl->buffers.serverDH_G.buffer,
- ssl->buffers.serverDH_G.length,
- NULL, 0, 0, ssl->rng);
- if (ret != 0) {
- goto exit_scke;
- }
- ssl->options.dhKeyTested = 1;
- }
- else
- #endif
- {
- ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
- ssl->buffers.serverDH_P.buffer,
- ssl->buffers.serverDH_P.length,
- ssl->buffers.serverDH_G.buffer,
- ssl->buffers.serverDH_G.length);
- if (ret != 0) {
- goto exit_scke;
- }
- }
- /* for DH, encSecret is Yc, agree is pre-master */
- ret = DhGenKeyPair(ssl, ssl->buffers.serverDH_Key,
- ssl->buffers.sig.buffer, (word32*)&ssl->buffers.sig.length,
- args->encSecret, &args->encSz);
- /* set the max agree result size */
- ssl->arrays->preMasterSz = ENCRYPT_LEN;
- break;
- }
- #endif /* !NO_DH */
- #ifndef NO_PSK
- case psk_kea:
- {
- byte* pms = ssl->arrays->preMasterSecret;
- ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
- ssl->arrays->server_hint, ssl->arrays->client_identity,
- MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
- if (ssl->arrays->psk_keySz == 0 ||
- ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
- ERROR_OUT(PSK_KEY_ERROR, exit_scke);
- }
- ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0'; /* null term */
- args->encSz = (word32)XSTRLEN(ssl->arrays->client_identity);
- if (args->encSz > MAX_PSK_ID_LEN) {
- ERROR_OUT(CLIENT_ID_ERROR, exit_scke);
- }
- XMEMCPY(args->encSecret, ssl->arrays->client_identity,
- args->encSz);
- /* make psk pre master secret */
- /* length of key + length 0s + length of key + key */
- c16toa((word16)ssl->arrays->psk_keySz, pms);
- pms += OPAQUE16_LEN;
- XMEMSET(pms, 0, ssl->arrays->psk_keySz);
- pms += ssl->arrays->psk_keySz;
- c16toa((word16)ssl->arrays->psk_keySz, pms);
- pms += OPAQUE16_LEN;
- XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
- ssl->arrays->preMasterSz = (ssl->arrays->psk_keySz * 2) +
- (2 * OPAQUE16_LEN);
- ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz);
- ssl->arrays->psk_keySz = 0; /* No further need */
- break;
- }
- #endif /* !NO_PSK */
- #if !defined(NO_DH) && !defined(NO_PSK)
- case dhe_psk_kea:
- {
- word32 esSz = 0;
- args->output = args->encSecret;
- ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
- ssl->arrays->server_hint, ssl->arrays->client_identity,
- MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
- if (ssl->arrays->psk_keySz == 0 ||
- ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
- ERROR_OUT(PSK_KEY_ERROR, exit_scke);
- }
- ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0'; /* null term */
- esSz = (word32)XSTRLEN(ssl->arrays->client_identity);
- if (esSz > MAX_PSK_ID_LEN) {
- ERROR_OUT(CLIENT_ID_ERROR, exit_scke);
- }
- ssl->buffers.sig.length = ENCRYPT_LEN;
- ssl->buffers.sig.buffer = (byte*)XMALLOC(ENCRYPT_LEN,
- ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- if (ssl->buffers.sig.buffer == NULL) {
- ERROR_OUT(MEMORY_E, exit_scke);
- }
- c16toa((word16)esSz, args->output);
- args->output += OPAQUE16_LEN;
- XMEMCPY(args->output, ssl->arrays->client_identity, esSz);
- args->output += esSz;
- args->encSz = esSz + OPAQUE16_LEN;
- args->length = 0;
- ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
- (void**)&ssl->buffers.serverDH_Key);
- if (ret != 0) {
- goto exit_scke;
- }
- #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \
- !defined(WOLFSSL_OLD_PRIME_CHECK)
- if (ssl->options.dhDoKeyTest &&
- !ssl->options.dhKeyTested)
- {
- ret = wc_DhSetCheckKey(ssl->buffers.serverDH_Key,
- ssl->buffers.serverDH_P.buffer,
- ssl->buffers.serverDH_P.length,
- ssl->buffers.serverDH_G.buffer,
- ssl->buffers.serverDH_G.length,
- NULL, 0, 0, ssl->rng);
- if (ret != 0) {
- goto exit_scke;
- }
- ssl->options.dhKeyTested = 1;
- }
- else
- #endif
- {
- ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
- ssl->buffers.serverDH_P.buffer,
- ssl->buffers.serverDH_P.length,
- ssl->buffers.serverDH_G.buffer,
- ssl->buffers.serverDH_G.length);
- if (ret != 0) {
- goto exit_scke;
- }
- }
- /* for DH, encSecret is Yc, agree is pre-master */
- ret = DhGenKeyPair(ssl, ssl->buffers.serverDH_Key,
- ssl->buffers.sig.buffer, (word32*)&ssl->buffers.sig.length,
- args->output + OPAQUE16_LEN, &args->length);
- break;
- }
- #endif /* !NO_DH && !NO_PSK */
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && !defined(NO_PSK)
- case ecdhe_psk_kea:
- {
- word32 esSz = 0;
- args->output = args->encSecret;
- /* Send PSK client identity */
- ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
- ssl->arrays->server_hint, ssl->arrays->client_identity,
- MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
- if (ssl->arrays->psk_keySz == 0 ||
- ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
- ERROR_OUT(PSK_KEY_ERROR, exit_scke);
- }
- ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0'; /* null term */
- esSz = (word32)XSTRLEN(ssl->arrays->client_identity);
- if (esSz > MAX_PSK_ID_LEN) {
- ERROR_OUT(CLIENT_ID_ERROR, exit_scke);
- }
- /* place size and identity in output buffer sz:identity */
- c16toa((word16)esSz, args->output);
- args->output += OPAQUE16_LEN;
- XMEMCPY(args->output, ssl->arrays->client_identity, esSz);
- args->output += esSz;
- args->encSz = esSz + OPAQUE16_LEN;
- /* length is used for public key size */
- args->length = MAX_ENCRYPT_SZ;
- /* Create shared ECC key leaving room at the beginning
- of buffer for size of shared key. */
- ssl->arrays->preMasterSz = ENCRYPT_LEN - OPAQUE16_LEN;
- #ifdef HAVE_CURVE25519
- if (ssl->ecdhCurveOID == ECC_X25519_OID) {
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->X25519SharedSecretCb != NULL) {
- break;
- }
- #endif
- ret = wc_curve25519_export_public_ex(
- (curve25519_key*)ssl->hsKey,
- args->output + OPAQUE8_LEN, &args->length,
- EC25519_LITTLE_ENDIAN);
- if (ret != 0) {
- ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
- }
- break;
- }
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->ecdhCurveOID == ECC_X448_OID) {
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->X448SharedSecretCb != NULL) {
- break;
- }
- #endif
- ret = wc_curve448_export_public_ex(
- (curve448_key*)ssl->hsKey,
- args->output + OPAQUE8_LEN, &args->length,
- EC448_LITTLE_ENDIAN);
- if (ret != 0) {
- ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
- }
- break;
- }
- #endif
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->EccSharedSecretCb != NULL) {
- break;
- }
- #endif
- /* Place ECC key in output buffer, leaving room for size */
- ret = wc_ecc_export_x963((ecc_key*)ssl->hsKey,
- args->output + OPAQUE8_LEN, &args->length);
- if (ret != 0) {
- ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
- }
- break;
- }
- #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
- #ifdef HAVE_NTRU
- case ntru_kea:
- {
- ret = wc_RNG_GenerateBlock(ssl->rng,
- ssl->arrays->preMasterSecret, SECRET_LEN);
- if (ret != 0) {
- goto exit_scke;
- }
- ssl->arrays->preMasterSz = SECRET_LEN;
- args->encSz = MAX_ENCRYPT_SZ;
- break;
- }
- #endif /* HAVE_NTRU */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)
- case ecc_diffie_hellman_kea:
- {
- ssl->arrays->preMasterSz = ENCRYPT_LEN;
- #ifdef HAVE_CURVE25519
- if (ssl->hsType == DYNAMIC_TYPE_CURVE25519) {
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->X25519SharedSecretCb != NULL) {
- break;
- }
- #endif
- ret = wc_curve25519_export_public_ex(
- (curve25519_key*)ssl->hsKey,
- args->encSecret + OPAQUE8_LEN, &args->encSz,
- EC25519_LITTLE_ENDIAN);
- if (ret != 0) {
- ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
- }
- break;
- }
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->hsType == DYNAMIC_TYPE_CURVE448) {
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->X448SharedSecretCb != NULL) {
- break;
- }
- #endif
- ret = wc_curve448_export_public_ex(
- (curve448_key*)ssl->hsKey,
- args->encSecret + OPAQUE8_LEN, &args->encSz,
- EC448_LITTLE_ENDIAN);
- if (ret != 0) {
- ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
- }
- break;
- }
- #endif
- #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->EccSharedSecretCb != NULL) {
- break;
- }
- #endif
- /* Place ECC key in buffer, leaving room for size */
- ret = wc_ecc_export_x963((ecc_key*)ssl->hsKey,
- args->encSecret + OPAQUE8_LEN, &args->encSz);
- if (ret != 0) {
- ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
- }
- #endif /* HAVE_ECC */
- break;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- default:
- ret = BAD_KEA_TYPE_E;
- } /* switch(ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_scke;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_DO;
- } /* case TLS_ASYNC_BUILD */
- FALL_THROUGH;
- case TLS_ASYNC_DO:
- {
- switch(ssl->specs.kea)
- {
- #ifndef NO_RSA
- case rsa_kea:
- {
- #if defined(WOLFSSL_RENESAS_TSIP_TLS) && \
- !defined(NO_WOLFSSL_RENESAS_TSIP_TLS_SESSION)
- if (tsip_useable(ssl) &&
- wc_RsaEncryptSize(ssl->peerRsaKey) == 256) {
- ret = tsip_generateEncryptPreMasterSecret(ssl,
- args->encSecret,
- &args->encSz);
- } else
- #endif
- ret = RsaEnc(ssl,
- ssl->arrays->preMasterSecret, SECRET_LEN,
- args->encSecret, &args->encSz,
- ssl->peerRsaKey,
- #if defined(HAVE_PK_CALLBACKS)
- &ssl->buffers.peerRsaKey
- #else
- NULL
- #endif
- );
- break;
- }
- #endif /* !NO_RSA */
- #ifndef NO_DH
- case diffie_hellman_kea:
- {
- ret = DhAgree(ssl, ssl->buffers.serverDH_Key,
- ssl->buffers.sig.buffer, ssl->buffers.sig.length,
- ssl->buffers.serverDH_Pub.buffer,
- ssl->buffers.serverDH_Pub.length,
- ssl->arrays->preMasterSecret,
- &ssl->arrays->preMasterSz);
- break;
- }
- #endif /* !NO_DH */
- #ifndef NO_PSK
- case psk_kea:
- {
- break;
- }
- #endif /* !NO_PSK */
- #if !defined(NO_DH) && !defined(NO_PSK)
- case dhe_psk_kea:
- {
- ret = DhAgree(ssl, ssl->buffers.serverDH_Key,
- ssl->buffers.sig.buffer, ssl->buffers.sig.length,
- ssl->buffers.serverDH_Pub.buffer,
- ssl->buffers.serverDH_Pub.length,
- ssl->arrays->preMasterSecret + OPAQUE16_LEN,
- &ssl->arrays->preMasterSz);
- break;
- }
- #endif /* !NO_DH && !NO_PSK */
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && !defined(NO_PSK)
- case ecdhe_psk_kea:
- {
- #ifdef HAVE_CURVE25519
- if (ssl->peerX25519KeyPresent) {
- ret = X25519SharedSecret(ssl,
- (curve25519_key*)ssl->hsKey, ssl->peerX25519Key,
- args->output + OPAQUE8_LEN, &args->length,
- ssl->arrays->preMasterSecret + OPAQUE16_LEN,
- &ssl->arrays->preMasterSz,
- WOLFSSL_CLIENT_END
- );
- if (!ssl->specs.static_ecdh
- #ifdef WOLFSSL_ASYNC_CRYPT
- && ret != WC_PENDING_E
- #endif
- ) {
- FreeKey(ssl, DYNAMIC_TYPE_CURVE25519,
- (void**)&ssl->peerX25519Key);
- ssl->peerX25519KeyPresent = 0;
- }
- break;
- }
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->peerX448KeyPresent) {
- ret = X448SharedSecret(ssl,
- (curve448_key*)ssl->hsKey, ssl->peerX448Key,
- args->output + OPAQUE8_LEN, &args->length,
- ssl->arrays->preMasterSecret + OPAQUE16_LEN,
- &ssl->arrays->preMasterSz,
- WOLFSSL_CLIENT_END
- );
- if (!ssl->specs.static_ecdh
- #ifdef WOLFSSL_ASYNC_CRYPT
- && ret != WC_PENDING_E
- #endif
- ) {
- FreeKey(ssl, DYNAMIC_TYPE_CURVE448,
- (void**)&ssl->peerX448Key);
- ssl->peerX448KeyPresent = 0;
- }
- break;
- }
- #endif
- ret = EccSharedSecret(ssl,
- (ecc_key*)ssl->hsKey, ssl->peerEccKey,
- args->output + OPAQUE8_LEN, &args->length,
- ssl->arrays->preMasterSecret + OPAQUE16_LEN,
- &ssl->arrays->preMasterSz,
- WOLFSSL_CLIENT_END
- );
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret != WC_PENDING_E)
- #endif
- {
- FreeKey(ssl, DYNAMIC_TYPE_ECC,
- (void**)&ssl->peerEccKey);
- ssl->peerEccKeyPresent = 0;
- }
- break;
- }
- #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
- #ifdef HAVE_NTRU
- case ntru_kea:
- {
- word32 rc;
- word16 tmpEncSz = (word16)args->encSz;
- DRBG_HANDLE drbg;
- rc = ntru_crypto_drbg_external_instantiate(GetEntropy, &drbg);
- if (rc != DRBG_OK) {
- ERROR_OUT(NTRU_DRBG_ERROR, exit_scke);
- }
- rc = ntru_crypto_ntru_encrypt(drbg, ssl->peerNtruKeyLen,
- ssl->peerNtruKey,
- ssl->arrays->preMasterSz,
- ssl->arrays->preMasterSecret,
- &tmpEncSz,
- args->encSecret);
- args->encSz = tmpEncSz;
- ntru_crypto_drbg_uninstantiate(drbg);
- if (rc != NTRU_OK) {
- ERROR_OUT(NTRU_ENCRYPT_ERROR, exit_scke);
- }
- ret = 0;
- break;
- }
- #endif /* HAVE_NTRU */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)
- case ecc_diffie_hellman_kea:
- {
- #ifdef HAVE_ECC
- ecc_key* peerKey;
- #endif
- #ifdef HAVE_CURVE25519
- if (ssl->peerX25519KeyPresent) {
- ret = X25519SharedSecret(ssl,
- (curve25519_key*)ssl->hsKey, ssl->peerX25519Key,
- args->encSecret + OPAQUE8_LEN, &args->encSz,
- ssl->arrays->preMasterSecret,
- &ssl->arrays->preMasterSz,
- WOLFSSL_CLIENT_END
- );
- if (!ssl->specs.static_ecdh
- #ifdef WOLFSSL_ASYNC_CRYPT
- && ret != WC_PENDING_E
- #endif
- ) {
- FreeKey(ssl, DYNAMIC_TYPE_CURVE25519,
- (void**)&ssl->peerX25519Key);
- ssl->peerX25519KeyPresent = 0;
- }
- break;
- }
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->peerX448KeyPresent) {
- ret = X448SharedSecret(ssl,
- (curve448_key*)ssl->hsKey, ssl->peerX448Key,
- args->encSecret + OPAQUE8_LEN, &args->encSz,
- ssl->arrays->preMasterSecret,
- &ssl->arrays->preMasterSz,
- WOLFSSL_CLIENT_END
- );
- if (!ssl->specs.static_ecdh
- #ifdef WOLFSSL_ASYNC_CRYPT
- && ret != WC_PENDING_E
- #endif
- ) {
- FreeKey(ssl, DYNAMIC_TYPE_CURVE448,
- (void**)&ssl->peerX448Key);
- ssl->peerX448KeyPresent = 0;
- }
- break;
- }
- #endif
- #ifdef HAVE_ECC
- peerKey = (ssl->specs.static_ecdh) ?
- ssl->peerEccDsaKey : ssl->peerEccKey;
- ret = EccSharedSecret(ssl,
- (ecc_key*)ssl->hsKey, peerKey,
- args->encSecret + OPAQUE8_LEN, &args->encSz,
- ssl->arrays->preMasterSecret,
- &ssl->arrays->preMasterSz,
- WOLFSSL_CLIENT_END
- );
- if (!ssl->specs.static_ecdh
- #ifdef WOLFSSL_ASYNC_CRYPT
- && ret != WC_PENDING_E
- #endif
- && !ssl->options.keepResources) {
- FreeKey(ssl, DYNAMIC_TYPE_ECC,
- (void**)&ssl->peerEccKey);
- ssl->peerEccKeyPresent = 0;
- }
- #endif
- break;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- default:
- ret = BAD_KEA_TYPE_E;
- } /* switch(ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_scke;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_VERIFY;
- } /* case TLS_ASYNC_DO */
- FALL_THROUGH;
- case TLS_ASYNC_VERIFY:
- {
- switch(ssl->specs.kea)
- {
- #ifndef NO_RSA
- case rsa_kea:
- {
- break;
- }
- #endif /* !NO_RSA */
- #ifndef NO_DH
- case diffie_hellman_kea:
- {
- break;
- }
- #endif /* !NO_DH */
- #ifndef NO_PSK
- case psk_kea:
- {
- break;
- }
- #endif /* !NO_PSK */
- #if !defined(NO_DH) && !defined(NO_PSK)
- case dhe_psk_kea:
- {
- byte* pms = ssl->arrays->preMasterSecret;
- /* validate args */
- if (args->output == NULL || args->length == 0) {
- ERROR_OUT(BAD_FUNC_ARG, exit_scke);
- }
- c16toa((word16)args->length, args->output);
- args->encSz += args->length + OPAQUE16_LEN;
- c16toa((word16)ssl->arrays->preMasterSz, pms);
- ssl->arrays->preMasterSz += OPAQUE16_LEN;
- pms += ssl->arrays->preMasterSz;
- /* make psk pre master secret */
- /* length of key + length 0s + length of key + key */
- c16toa((word16)ssl->arrays->psk_keySz, pms);
- pms += OPAQUE16_LEN;
- XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
- ssl->arrays->preMasterSz +=
- ssl->arrays->psk_keySz + OPAQUE16_LEN;
- ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz);
- ssl->arrays->psk_keySz = 0; /* No further need */
- break;
- }
- #endif /* !NO_DH && !NO_PSK */
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && !defined(NO_PSK)
- case ecdhe_psk_kea:
- {
- byte* pms = ssl->arrays->preMasterSecret;
- /* validate args */
- if (args->output == NULL || args->length > ENCRYPT_LEN) {
- ERROR_OUT(BAD_FUNC_ARG, exit_scke);
- }
- /* place size of public key in output buffer */
- *args->output = (byte)args->length;
- args->encSz += args->length + OPAQUE8_LEN;
- /* Create pre master secret is the concatenation of
- eccSize + eccSharedKey + pskSize + pskKey */
- c16toa((word16)ssl->arrays->preMasterSz, pms);
- ssl->arrays->preMasterSz += OPAQUE16_LEN;
- pms += ssl->arrays->preMasterSz;
- c16toa((word16)ssl->arrays->psk_keySz, pms);
- pms += OPAQUE16_LEN;
- XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
- ssl->arrays->preMasterSz +=
- ssl->arrays->psk_keySz + OPAQUE16_LEN;
- ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz);
- ssl->arrays->psk_keySz = 0; /* No further need */
- break;
- }
- #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
- #ifdef HAVE_NTRU
- case ntru_kea:
- {
- break;
- }
- #endif /* HAVE_NTRU */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)
- case ecc_diffie_hellman_kea:
- {
- /* place size of public key in buffer */
- *args->encSecret = (byte)args->encSz;
- args->encSz += OPAQUE8_LEN;
- break;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- default:
- ret = BAD_KEA_TYPE_E;
- } /* switch(ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_scke;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_FINALIZE;
- } /* case TLS_ASYNC_VERIFY */
- FALL_THROUGH;
- case TLS_ASYNC_FINALIZE:
- {
- word32 tlsSz = 0;
- word32 idx = 0;
- #ifdef HAVE_QSH
- word32 qshSz = 0;
- if (ssl->peerQSHKeyPresent) {
- qshSz = QSH_KeyGetSize(ssl);
- }
- #endif
- if (ssl->options.tls || ssl->specs.kea == diffie_hellman_kea) {
- tlsSz = 2;
- }
- if (ssl->specs.kea == ecc_diffie_hellman_kea ||
- ssl->specs.kea == dhe_psk_kea ||
- ssl->specs.kea == ecdhe_psk_kea) { /* always off */
- tlsSz = 0;
- }
- idx = HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
- args->sendSz = args->encSz + tlsSz + idx;
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- idx += DTLS_HANDSHAKE_EXTRA + DTLS_RECORD_EXTRA;
- args->sendSz += DTLS_HANDSHAKE_EXTRA + DTLS_RECORD_EXTRA;
- }
- #endif
- if (IsEncryptionOn(ssl, 1)) {
- args->sendSz += MAX_MSG_EXTRA;
- }
- #ifdef HAVE_QSH
- args->encSz += qshSz;
- args->sendSz += qshSz;
- #endif
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
- goto exit_scke;
- }
- /* get output buffer */
- args->output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- #ifdef HAVE_QSH
- if (ssl->peerQSHKeyPresent) {
- byte idxSave = idx;
- idx = args->sendSz - qshSz;
- if (QSH_KeyExchangeWrite(ssl, 0) != 0) {
- ERROR_OUT(MEMORY_E, exit_scke);
- }
- /* extension type */
- c16toa(TLSX_QUANTUM_SAFE_HYBRID, args->output + idx);
- idx += OPAQUE16_LEN;
- /* write to output and check amount written */
- if (TLSX_QSHPK_Write(ssl->QSH_secret->list,
- args->output + idx) > qshSz - OPAQUE16_LEN) {
- ERROR_OUT(MEMORY_E, exit_scke);
- }
- idx = idxSave;
- }
- #endif
- AddHeaders(args->output, args->encSz + tlsSz, client_key_exchange, ssl);
- #ifdef HAVE_QSH
- if (ssl->peerQSHKeyPresent) {
- args->encSz -= qshSz;
- }
- #endif
- if (tlsSz) {
- c16toa((word16)args->encSz, &args->output[idx]);
- idx += OPAQUE16_LEN;
- }
- XMEMCPY(args->output + idx, args->encSecret, args->encSz);
- idx += args->encSz;
- if (IsEncryptionOn(ssl, 1)) {
- args->inputSz = idx - RECORD_HEADER_SZ; /* buildmsg adds rechdr */
- args->input = (byte*)XMALLOC(args->inputSz, ssl->heap,
- DYNAMIC_TYPE_IN_BUFFER);
- if (args->input == NULL) {
- ERROR_OUT(MEMORY_E, exit_scke);
- }
- XMEMCPY(args->input, args->output + RECORD_HEADER_SZ,
- args->inputSz);
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_END;
- } /* case TLS_ASYNC_FINALIZE */
- FALL_THROUGH;
- case TLS_ASYNC_END:
- {
- if (IsEncryptionOn(ssl, 1)) {
- ret = BuildMessage(ssl, args->output, args->sendSz,
- args->input, args->inputSz, handshake, 1, 0, 0);
- XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- args->input = NULL; /* make sure its not double free'd on cleanup */
- if (ret >= 0) {
- args->sendSz = ret;
- ret = 0;
- }
- }
- else {
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls)
- DtlsSEQIncrement(ssl, CUR_ORDER);
- #endif
- ret = HashOutput(ssl, args->output, args->sendSz, 0);
- }
- if (ret != 0) {
- goto exit_scke;
- }
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- if ((ret = DtlsMsgPoolSave(ssl, args->output, args->sendSz)) != 0) {
- goto exit_scke;
- }
- }
- #endif
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "ClientKeyExchange");
- if (ssl->toInfoOn)
- AddPacketInfo(ssl, "ClientKeyExchange", handshake,
- args->output, args->sendSz, WRITE_PROTO, ssl->heap);
- #endif
- ssl->buffers.outputBuffer.length += args->sendSz;
- if (!ssl->options.groupMessages) {
- ret = SendBuffered(ssl);
- }
- if (ret == 0 || ret == WANT_WRITE) {
- int tmpRet = MakeMasterSecret(ssl);
- if (tmpRet != 0) {
- ret = tmpRet; /* save WANT_WRITE unless more serious */
- }
- ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
- }
- break;
- }
- default:
- ret = INPUT_CASE_ERROR;
- } /* switch(ssl->options.asyncState) */
- exit_scke:
- WOLFSSL_LEAVE("SendClientKeyExchange", ret);
- WOLFSSL_END(WC_FUNC_CLIENT_KEY_EXCHANGE_SEND);
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* Handle async operation */
- if (ret == WC_PENDING_E)
- return ret;
- #endif
- /* No further need for PMS */
- if (ssl->arrays->preMasterSecret != NULL) {
- ForceZero(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
- }
- ssl->arrays->preMasterSz = 0;
- /* Final cleanup */
- FreeSckeArgs(ssl, args);
- FreeKeyExchange(ssl);
- return ret;
- }
- #endif /* !WOLFSSL_NO_TLS12 */
- #ifndef NO_CERTS
- #ifdef HAVE_PK_CALLBACKS
- int GetPrivateKeySigSize(WOLFSSL* ssl)
- {
- int sigSz = 0;
- if (ssl == NULL)
- return 0;
- switch (ssl->buffers.keyType) {
- #ifndef NO_RSA
- #ifdef WC_RSA_PSS
- case rsa_pss_sa_algo:
- #endif
- case rsa_sa_algo:
- sigSz = ssl->buffers.keySz;
- ssl->hsType = DYNAMIC_TYPE_RSA;
- break;
- #endif
- #ifdef HAVE_ECC
- case ecc_dsa_sa_algo:
- sigSz = wc_ecc_sig_size_calc(ssl->buffers.keySz);
- ssl->hsType = DYNAMIC_TYPE_ECC;
- break;
- #endif
- #ifdef HAVE_ED25519
- case ed25519_sa_algo:
- sigSz = ED25519_SIG_SIZE; /* fixed known value */
- ssl->hsType = DYNAMIC_TYPE_ED25519;
- break;
- #endif
- #ifdef HAVE_ED448
- case ed448_sa_algo:
- sigSz = ED448_SIG_SIZE; /* fixed known value */
- ssl->hsType = DYNAMIC_TYPE_ED448;
- break;
- #endif
- default:
- break;
- }
- return sigSz;
- }
- #endif /* HAVE_PK_CALLBACKS */
- #ifndef WOLFSSL_NO_TLS12
- #ifndef WOLFSSL_NO_CLIENT_AUTH
- typedef struct ScvArgs {
- byte* output; /* not allocated */
- #ifndef NO_RSA
- byte* verifySig;
- #endif
- byte* verify; /* not allocated */
- byte* input;
- word32 idx;
- word32 extraSz;
- word32 sigSz;
- int sendSz;
- int inputSz;
- word16 length;
- byte sigAlgo;
- } ScvArgs;
- static void FreeScvArgs(WOLFSSL* ssl, void* pArgs)
- {
- ScvArgs* args = (ScvArgs*)pArgs;
- (void)ssl;
- #ifndef NO_RSA
- if (args->verifySig) {
- XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- args->verifySig = NULL;
- }
- #endif
- if (args->input) {
- XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- args->input = NULL;
- }
- }
- /* handle generation of certificate_verify (15) */
- int SendCertificateVerify(WOLFSSL* ssl)
- {
- int ret = 0;
- #ifdef WOLFSSL_ASYNC_CRYPT
- ScvArgs* args = (ScvArgs*)ssl->async.args;
- typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
- (void)sizeof(args_test);
- #else
- ScvArgs args[1];
- #endif
- WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_SEND);
- WOLFSSL_ENTER("SendCertificateVerify");
- #ifdef WOLFSSL_ASYNC_CRYPT
- ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
- if (ret != WC_NOT_PENDING_E) {
- /* Check for error */
- if (ret < 0)
- goto exit_scv;
- }
- else
- #endif
- {
- /* Reset state */
- ret = 0;
- ssl->options.asyncState = TLS_ASYNC_BEGIN;
- XMEMSET(args, 0, sizeof(ScvArgs));
- #ifdef WOLFSSL_ASYNC_CRYPT
- ssl->async.freeArgs = FreeScvArgs;
- #endif
- }
- switch(ssl->options.asyncState)
- {
- case TLS_ASYNC_BEGIN:
- {
- if (ssl->options.sendVerify == SEND_BLANK_CERT) {
- return 0; /* sent blank cert, can't verify */
- }
- args->sendSz = MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA;
- if (IsEncryptionOn(ssl, 1)) {
- args->sendSz += MAX_MSG_EXTRA;
- }
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
- goto exit_scv;
- }
- /* get output buffer */
- args->output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_BUILD;
- } /* case TLS_ASYNC_BEGIN */
- FALL_THROUGH;
- case TLS_ASYNC_BUILD:
- {
- ret = BuildCertHashes(ssl, &ssl->hsHashes->certHashes);
- if (ret != 0) {
- goto exit_scv;
- }
- if (ssl->buffers.key == NULL) {
- #ifdef HAVE_PK_CALLBACKS
- if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
- args->length = GetPrivateKeySigSize(ssl);
- else
- #endif
- ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
- }
- else {
- /* Decode private key. */
- ret = DecodePrivateKey(ssl, &args->length);
- if (ret != 0) {
- goto exit_scv;
- }
- }
- if (args->length == 0) {
- ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
- }
- /* idx is used to track verify pointer offset to output */
- args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
- args->verify = &args->output[RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ];
- args->extraSz = 0; /* tls 1.2 hash/sig */
- /* build encoded signature buffer */
- ssl->buffers.sig.length = MAX_ENCODED_SIG_SZ;
- ssl->buffers.sig.buffer = (byte*)XMALLOC(ssl->buffers.sig.length,
- ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- if (ssl->buffers.sig.buffer == NULL) {
- ERROR_OUT(MEMORY_E, exit_scv);
- }
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- args->verify += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- }
- #endif
- #ifndef NO_OLD_TLS
- #ifndef NO_SHA
- /* old tls default */
- SetDigest(ssl, sha_mac);
- #endif
- #else
- #ifndef NO_SHA256
- /* new tls default */
- SetDigest(ssl, sha256_mac);
- #endif
- #endif /* !NO_OLD_TLS */
- if (ssl->hsType == DYNAMIC_TYPE_RSA) {
- #ifdef WC_RSA_PSS
- if (IsAtLeastTLSv1_2(ssl) &&
- (ssl->pssAlgo & (1 << ssl->suites->hashAlgo))) {
- args->sigAlgo = rsa_pss_sa_algo;
- }
- else
- #endif
- args->sigAlgo = rsa_sa_algo;
- }
- else if (ssl->hsType == DYNAMIC_TYPE_ECC)
- args->sigAlgo = ecc_dsa_sa_algo;
- else if (ssl->hsType == DYNAMIC_TYPE_ED25519)
- args->sigAlgo = ed25519_sa_algo;
- else if (ssl->hsType == DYNAMIC_TYPE_ED448)
- args->sigAlgo = ed448_sa_algo;
- if (IsAtLeastTLSv1_2(ssl)) {
- EncodeSigAlg(ssl->suites->hashAlgo, args->sigAlgo,
- args->verify);
- args->extraSz = HASH_SIG_SIZE;
- SetDigest(ssl, ssl->suites->hashAlgo);
- }
- #ifndef NO_OLD_TLS
- else {
- /* if old TLS load MD5 and SHA hash as value to sign */
- XMEMCPY(ssl->buffers.sig.buffer,
- (byte*)ssl->hsHashes->certHashes.md5, FINISHED_SZ);
- }
- #endif
- #ifndef NO_RSA
- if (args->sigAlgo == rsa_sa_algo) {
- ssl->buffers.sig.length = FINISHED_SZ;
- args->sigSz = ENCRYPT_LEN;
- if (IsAtLeastTLSv1_2(ssl)) {
- ssl->buffers.sig.length = wc_EncodeSignature(
- ssl->buffers.sig.buffer, ssl->buffers.digest.buffer,
- ssl->buffers.digest.length,
- TypeHash(ssl->suites->hashAlgo));
- }
- /* prepend hdr */
- c16toa(args->length, args->verify + args->extraSz);
- }
- #ifdef WC_RSA_PSS
- else if (args->sigAlgo == rsa_pss_sa_algo) {
- XMEMCPY(ssl->buffers.sig.buffer, ssl->buffers.digest.buffer,
- ssl->buffers.digest.length);
- ssl->buffers.sig.length = ssl->buffers.digest.length;
- args->sigSz = ENCRYPT_LEN;
- /* prepend hdr */
- c16toa(args->length, args->verify + args->extraSz);
- }
- #endif
- #endif /* !NO_RSA */
- #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
- if (args->sigAlgo == ed25519_sa_algo) {
- ret = Ed25519CheckPubKey(ssl);
- if (ret != 0)
- goto exit_scv;
- }
- #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
- #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
- if (args->sigAlgo == ed448_sa_algo) {
- ret = Ed448CheckPubKey(ssl);
- if (ret != 0)
- goto exit_scv;
- }
- #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_DO;
- } /* case TLS_ASYNC_BUILD */
- FALL_THROUGH;
- case TLS_ASYNC_DO:
- {
- #ifdef HAVE_ECC
- if (ssl->hsType == DYNAMIC_TYPE_ECC) {
- ecc_key* key = (ecc_key*)ssl->hsKey;
- ret = EccSign(ssl,
- ssl->buffers.digest.buffer, ssl->buffers.digest.length,
- ssl->buffers.sig.buffer, (word32*)&ssl->buffers.sig.length,
- key,
- #ifdef HAVE_PK_CALLBACKS
- ssl->buffers.key
- #else
- NULL
- #endif
- );
- }
- #endif /* HAVE_ECC */
- #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
- if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
- ed25519_key* key = (ed25519_key*)ssl->hsKey;
- ret = Ed25519Sign(ssl,
- ssl->hsHashes->messages, ssl->hsHashes->length,
- ssl->buffers.sig.buffer, (word32*)&ssl->buffers.sig.length,
- key,
- #ifdef HAVE_PK_CALLBACKS
- ssl->buffers.key
- #else
- NULL
- #endif
- );
- }
- #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
- #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
- if (ssl->hsType == DYNAMIC_TYPE_ED448) {
- ed448_key* key = (ed448_key*)ssl->hsKey;
- ret = Ed448Sign(ssl,
- ssl->hsHashes->messages, ssl->hsHashes->length,
- ssl->buffers.sig.buffer, (word32*)&ssl->buffers.sig.length,
- key,
- #ifdef HAVE_PK_CALLBACKS
- ssl->buffers.key
- #else
- NULL
- #endif
- );
- }
- #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
- #ifndef NO_RSA
- if (ssl->hsType == DYNAMIC_TYPE_RSA) {
- RsaKey* key = (RsaKey*)ssl->hsKey;
- /* restore verify pointer */
- args->verify = &args->output[args->idx];
- ret = RsaSign(ssl,
- ssl->buffers.sig.buffer, ssl->buffers.sig.length,
- args->verify + args->extraSz + VERIFY_HEADER, &args->sigSz,
- args->sigAlgo, ssl->suites->hashAlgo, key,
- ssl->buffers.key
- );
- }
- #endif /* !NO_RSA */
- /* Check for error */
- if (ret != 0) {
- goto exit_scv;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_VERIFY;
- } /* case TLS_ASYNC_DO */
- FALL_THROUGH;
- case TLS_ASYNC_VERIFY:
- {
- /* restore verify pointer */
- args->verify = &args->output[args->idx];
- switch (ssl->hsType) {
- #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
- #ifdef HAVE_ECC
- case DYNAMIC_TYPE_ECC:
- #endif
- #ifdef HAVE_ED25519
- case DYNAMIC_TYPE_ED25519:
- #endif
- #ifdef HAVE_ED448
- case DYNAMIC_TYPE_ED448:
- #endif
- args->length = (word16)ssl->buffers.sig.length;
- /* prepend hdr */
- c16toa(args->length, args->verify + args->extraSz);
- XMEMCPY(args->verify + args->extraSz + VERIFY_HEADER,
- ssl->buffers.sig.buffer, ssl->buffers.sig.length);
- break;
- #endif
- #ifndef NO_RSA
- case DYNAMIC_TYPE_RSA:
- {
- RsaKey* key = (RsaKey*)ssl->hsKey;
- if (args->verifySig == NULL) {
- args->verifySig = (byte*)XMALLOC(args->sigSz, ssl->heap,
- DYNAMIC_TYPE_SIGNATURE);
- if (args->verifySig == NULL) {
- ERROR_OUT(MEMORY_E, exit_scv);
- }
- XMEMCPY(args->verifySig, args->verify + args->extraSz +
- VERIFY_HEADER, args->sigSz);
- }
- /* check for signature faults */
- ret = VerifyRsaSign(ssl,
- args->verifySig, args->sigSz,
- ssl->buffers.sig.buffer, ssl->buffers.sig.length,
- args->sigAlgo, ssl->suites->hashAlgo, key,
- ssl->buffers.key
- );
- break;
- }
- #endif /* !NO_RSA */
- default:
- break;
- }
- /* Check for error */
- if (ret != 0) {
- goto exit_scv;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_FINALIZE;
- } /* case TLS_ASYNC_VERIFY */
- FALL_THROUGH;
- case TLS_ASYNC_FINALIZE:
- {
- if (args->output == NULL) {
- ERROR_OUT(BUFFER_ERROR, exit_scv);
- }
- AddHeaders(args->output, (word32)args->length + args->extraSz +
- VERIFY_HEADER, certificate_verify, ssl);
- args->sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ +
- (word32)args->length + args->extraSz + VERIFY_HEADER;
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- }
- #endif
- if (IsEncryptionOn(ssl, 1)) {
- args->inputSz = args->sendSz - RECORD_HEADER_SZ;
- /* build msg adds rec hdr */
- args->input = (byte*)XMALLOC(args->inputSz, ssl->heap,
- DYNAMIC_TYPE_IN_BUFFER);
- if (args->input == NULL) {
- ERROR_OUT(MEMORY_E, exit_scv);
- }
- XMEMCPY(args->input, args->output + RECORD_HEADER_SZ,
- args->inputSz);
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_END;
- } /* case TLS_ASYNC_FINALIZE */
- FALL_THROUGH;
- case TLS_ASYNC_END:
- {
- if (IsEncryptionOn(ssl, 1)) {
- ret = BuildMessage(ssl, args->output,
- MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA,
- args->input, args->inputSz, handshake,
- 1, 0, 1);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E)
- goto exit_scv;
- #endif
- XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- args->input = NULL; /* make sure its not double free'd on cleanup */
- if (ret >= 0) {
- args->sendSz = ret;
- ret = 0;
- }
- }
- else {
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls)
- DtlsSEQIncrement(ssl, CUR_ORDER);
- #endif
- ret = HashOutput(ssl, args->output, args->sendSz, 0);
- }
- if (ret != 0) {
- goto exit_scv;
- }
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- ret = DtlsMsgPoolSave(ssl, args->output, args->sendSz);
- }
- #endif
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "CertificateVerify");
- if (ssl->toInfoOn)
- AddPacketInfo(ssl, "CertificateVerify", handshake,
- args->output, args->sendSz, WRITE_PROTO, ssl->heap);
- #endif
- ssl->buffers.outputBuffer.length += args->sendSz;
- if (!ssl->options.groupMessages) {
- ret = SendBuffered(ssl);
- }
- break;
- }
- default:
- ret = INPUT_CASE_ERROR;
- } /* switch(ssl->options.asyncState) */
- exit_scv:
- WOLFSSL_LEAVE("SendCertificateVerify", ret);
- WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_SEND);
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* Handle async operation */
- if (ret == WC_PENDING_E) {
- return ret;
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- /* Digest is not allocated, so do this to prevent free */
- ssl->buffers.digest.buffer = NULL;
- ssl->buffers.digest.length = 0;
- /* Final cleanup */
- FreeScvArgs(ssl, args);
- FreeKeyExchange(ssl);
- return ret;
- }
- #endif /* WOLFSSL_NO_CLIENT_AUTH */
- #endif /* WOLFSSL_NO_TLS12 */
- #endif /* NO_CERTS */
- #ifdef HAVE_SESSION_TICKET
- int SetTicket(WOLFSSL* ssl, const byte* ticket, word32 length)
- {
- /* Free old dynamic ticket if we already had one */
- if (ssl->session.isDynamic) {
- XFREE(ssl->session.ticket, ssl->heap, DYNAMIC_TYPE_SESSION_TICK);
- ssl->session.ticket = ssl->session.staticTicket;
- ssl->session.isDynamic = 0;
- }
- if (length > sizeof(ssl->session.staticTicket)) {
- byte* sessionTicket =
- (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_SESSION_TICK);
- if (sessionTicket == NULL)
- return MEMORY_E;
- ssl->session.ticket = sessionTicket;
- ssl->session.isDynamic = 1;
- }
- ssl->session.ticketLen = (word16)length;
- if (length > 0) {
- XMEMCPY(ssl->session.ticket, ticket, length);
- if (ssl->session_ticket_cb != NULL) {
- ssl->session_ticket_cb(ssl,
- ssl->session.ticket, ssl->session.ticketLen,
- ssl->session_ticket_ctx);
- }
- /* Create a fake sessionID based on the ticket, this will
- * supersede the existing session cache info. */
- ssl->options.haveSessionId = 1;
- #ifdef WOLFSSL_TLS13
- if (ssl->options.tls1_3) {
- XMEMCPY(ssl->session.sessionID,
- ssl->session.ticket + length - ID_LEN, ID_LEN);
- }
- else
- #endif
- XMEMCPY(ssl->arrays->sessionID,
- ssl->session.ticket + length - ID_LEN, ID_LEN);
- }
- return 0;
- }
- #ifndef WOLFSSL_NO_TLS12
- /* handle processing of session_ticket (4) */
- static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
- word32 size)
- {
- word32 begin = *inOutIdx;
- word32 lifetime;
- word16 length;
- int ret;
- if (ssl->expect_session_ticket == 0) {
- WOLFSSL_MSG("Unexpected session ticket");
- return SESSION_TICKET_EXPECT_E;
- }
- if (OPAQUE32_LEN > size)
- return BUFFER_ERROR;
- ato32(input + *inOutIdx, &lifetime);
- *inOutIdx += OPAQUE32_LEN;
- if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
- return BUFFER_ERROR;
- ato16(input + *inOutIdx, &length);
- *inOutIdx += OPAQUE16_LEN;
- if ((*inOutIdx - begin) + length > size)
- return BUFFER_ERROR;
- if ((ret = SetTicket(ssl, input + *inOutIdx, length)) != 0)
- return ret;
- *inOutIdx += length;
- if (length > 0) {
- ssl->timeout = lifetime;
- #ifndef NO_SESSION_CACHE
- AddSession(ssl);
- #endif
- }
- if (IsEncryptionOn(ssl, 0)) {
- *inOutIdx += ssl->keys.padSz;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead)
- *inOutIdx += MacSize(ssl);
- #endif
- }
- ssl->expect_session_ticket = 0;
- return 0;
- }
- #endif /* !WOLFSSL_NO_TLS12 */
- #endif /* HAVE_SESSION_TICKET */
- #endif /* NO_WOLFSSL_CLIENT */
- #ifdef HAVE_ECC
- /* returns the WOLFSSL_* version of the curve from the OID sum */
- word16 GetCurveByOID(int oidSum) {
- switch(oidSum) {
- #if defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)
- #ifndef NO_ECC_SECP
- case ECC_SECP160R1_OID:
- return WOLFSSL_ECC_SECP160R1;
- #endif /* !NO_ECC_SECP */
- #ifdef HAVE_ECC_SECPR2
- case ECC_SECP160R2_OID:
- return WOLFSSL_ECC_SECP160R2;
- #endif /* HAVE_ECC_SECPR2 */
- #ifdef HAVE_ECC_KOBLITZ
- case ECC_SECP160K1_OID:
- return WOLFSSL_ECC_SECP160K1;
- #endif /* HAVE_ECC_KOBLITZ */
- #endif
- #if defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)
- #ifndef NO_ECC_SECP
- case ECC_SECP192R1_OID:
- return WOLFSSL_ECC_SECP192R1;
- #endif /* !NO_ECC_SECP */
- #ifdef HAVE_ECC_KOBLITZ
- case ECC_SECP192K1_OID:
- return WOLFSSL_ECC_SECP192K1;
- #endif /* HAVE_ECC_KOBLITZ */
- #endif
- #if defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)
- #ifndef NO_ECC_SECP
- case ECC_SECP224R1_OID:
- return WOLFSSL_ECC_SECP224R1;
- #endif /* !NO_ECC_SECP */
- #ifdef HAVE_ECC_KOBLITZ
- case ECC_SECP224K1_OID:
- return WOLFSSL_ECC_SECP224K1;
- #endif /* HAVE_ECC_KOBLITZ */
- #endif
- #if !defined(NO_ECC256) || defined(HAVE_ALL_CURVES)
- #ifndef NO_ECC_SECP
- case ECC_SECP256R1_OID:
- return WOLFSSL_ECC_SECP256R1;
- #endif /* !NO_ECC_SECP */
- #ifdef HAVE_ECC_KOBLITZ
- case ECC_SECP256K1_OID:
- return WOLFSSL_ECC_SECP256K1;
- #endif /* HAVE_ECC_KOBLITZ */
- #ifdef HAVE_ECC_BRAINPOOL
- case ECC_BRAINPOOLP256R1_OID:
- return WOLFSSL_ECC_BRAINPOOLP256R1;
- #endif /* HAVE_ECC_BRAINPOOL */
- #endif
- #if defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)
- #ifndef NO_ECC_SECP
- case ECC_SECP384R1_OID:
- return WOLFSSL_ECC_SECP384R1;
- #endif /* !NO_ECC_SECP */
- #ifdef HAVE_ECC_BRAINPOOL
- case ECC_BRAINPOOLP384R1_OID:
- return WOLFSSL_ECC_BRAINPOOLP384R1;
- #endif /* HAVE_ECC_BRAINPOOL */
- #endif
- #if defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)
- #ifdef HAVE_ECC_BRAINPOOL
- case ECC_BRAINPOOLP512R1_OID:
- return WOLFSSL_ECC_BRAINPOOLP512R1;
- #endif /* HAVE_ECC_BRAINPOOL */
- #endif
- #if defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)
- #ifndef NO_ECC_SECP
- case ECC_SECP521R1_OID:
- return WOLFSSL_ECC_SECP521R1;
- #endif /* !NO_ECC_SECP */
- #endif
- default:
- WOLFSSL_MSG("Curve OID not compiled in or implemented");
- return 0;
- }
- }
- #endif /* HAVE_ECC */
- #ifndef NO_WOLFSSL_SERVER
- #ifndef WOLFSSL_NO_TLS12
- /* handle generation of server_hello (2) */
- int SendServerHello(WOLFSSL* ssl)
- {
- int ret;
- byte *output;
- word16 length;
- word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
- int sendSz;
- byte sessIdSz = ID_LEN;
- byte echoId = 0; /* ticket echo id flag */
- byte cacheOff = 0; /* session cache off flag */
- WOLFSSL_START(WC_FUNC_SERVER_HELLO_SEND);
- WOLFSSL_ENTER("SendServerHello");
- length = VERSION_SZ + RAN_LEN
- + ID_LEN + ENUM_LEN
- + SUITE_LEN
- + ENUM_LEN;
- #ifdef HAVE_TLS_EXTENSIONS
- ret = TLSX_GetResponseSize(ssl, server_hello, &length);
- if (ret != 0)
- return ret;
- #ifdef HAVE_SESSION_TICKET
- if (ssl->options.useTicket) {
- /* echo session id sz can be 0,32 or bogus len in between */
- sessIdSz = ssl->arrays->sessionIDSz;
- if (sessIdSz > ID_LEN) {
- WOLFSSL_MSG("Bad bogus session id len");
- return BUFFER_ERROR;
- }
- if (!IsAtLeastTLSv1_3(ssl->version))
- length -= (ID_LEN - sessIdSz); /* adjust ID_LEN assumption */
- echoId = 1;
- }
- #endif /* HAVE_SESSION_TICKET */
- #else
- if (ssl->options.haveEMS) {
- length += HELLO_EXT_SZ_SZ + HELLO_EXT_SZ;
- }
- #endif
- /* is the session cache off at build or runtime */
- #ifdef NO_SESSION_CACHE
- cacheOff = 1;
- #else
- if (ssl->options.sessionCacheOff == 1) {
- cacheOff = 1;
- }
- #endif
- /* if no session cache don't send a session ID unless we're echoing
- * an ID as part of session tickets */
- if (echoId == 0 && cacheOff == 1) {
- length -= ID_LEN; /* adjust ID_LEN assumption */
- sessIdSz = 0;
- }
- sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- /* Server Hello should use the same sequence number as the
- * Client Hello. */
- ssl->keys.dtls_sequence_number_hi = ssl->keys.curSeq_hi;
- ssl->keys.dtls_sequence_number_lo = ssl->keys.curSeq_lo;
- idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- }
- #endif /* WOLFSSL_DTLS */
- if (IsEncryptionOn(ssl, 1))
- sendSz += MAX_MSG_EXTRA;
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
- return ret;
- /* get output buffer */
- output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- AddHeaders(output, length, server_hello, ssl);
- /* now write to output */
- /* first version */
- output[idx++] = (byte)ssl->version.major;
- output[idx++] = (byte)ssl->version.minor;
- /* then random and session id */
- if (!ssl->options.resuming) {
- /* generate random part and session id */
- ret = wc_RNG_GenerateBlock(ssl->rng, output + idx,
- RAN_LEN + sizeof(sessIdSz) + sessIdSz);
- if (ret != 0)
- return ret;
- #ifdef WOLFSSL_TLS13
- if (TLSv1_3_Capable(ssl)) {
- /* TLS v1.3 capable server downgraded. */
- XMEMCPY(output + idx + RAN_LEN - (TLS13_DOWNGRADE_SZ + 1),
- tls13Downgrade, TLS13_DOWNGRADE_SZ);
- output[idx + RAN_LEN - 1] = (byte)IsAtLeastTLSv1_2(ssl);
- }
- else
- #endif
- if (ssl->ctx->method->version.major == SSLv3_MAJOR &&
- ssl->ctx->method->version.minor == TLSv1_2_MINOR &&
- !IsAtLeastTLSv1_2(ssl)) {
- /* TLS v1.2 capable server downgraded. */
- XMEMCPY(output + idx + RAN_LEN - (TLS13_DOWNGRADE_SZ + 1),
- tls13Downgrade, TLS13_DOWNGRADE_SZ);
- output[idx + RAN_LEN - 1] = 0;
- }
- /* store info in SSL for later */
- XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN);
- idx += RAN_LEN;
- output[idx++] = sessIdSz;
- XMEMCPY(ssl->arrays->sessionID, output + idx, sessIdSz);
- ssl->arrays->sessionIDSz = sessIdSz;
- }
- else {
- /* If resuming, use info from SSL */
- XMEMCPY(output + idx, ssl->arrays->serverRandom, RAN_LEN);
- idx += RAN_LEN;
- output[idx++] = sessIdSz;
- XMEMCPY(output + idx, ssl->arrays->sessionID, sessIdSz);
- }
- idx += sessIdSz;
- #ifdef SHOW_SECRETS
- {
- int j;
- printf("server random: ");
- for (j = 0; j < RAN_LEN; j++)
- printf("%02x", ssl->arrays->serverRandom[j]);
- printf("\n");
- }
- #endif
- /* then cipher suite */
- output[idx++] = ssl->options.cipherSuite0;
- output[idx++] = ssl->options.cipherSuite;
- /* then compression */
- if (ssl->options.usingCompression)
- output[idx++] = ZLIB_COMPRESSION;
- else
- output[idx++] = NO_COMPRESSION;
- /* last, extensions */
- #ifdef HAVE_TLS_EXTENSIONS
- {
- word16 offset = 0;
- ret = TLSX_WriteResponse(ssl, output + idx, server_hello, &offset);
- if (ret != 0)
- return ret;
- idx += offset;
- }
- #else
- #ifdef HAVE_EXTENDED_MASTER
- if (ssl->options.haveEMS) {
- c16toa(HELLO_EXT_SZ, output + idx);
- idx += HELLO_EXT_SZ_SZ;
- c16toa(HELLO_EXT_EXTMS, output + idx);
- idx += HELLO_EXT_TYPE_SZ;
- c16toa(0, output + idx);
- /*idx += HELLO_EXT_SZ_SZ;*/
- /* idx is not used after this point. uncomment the line above
- * if adding any more extensions in the future. */
- }
- #endif
- #endif
- if (IsEncryptionOn(ssl, 1)) {
- byte* input;
- int inputSz = idx - RECORD_HEADER_SZ; /* build msg adds rec hdr */
- input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (input == NULL)
- return MEMORY_E;
- XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
- sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
- handshake, 1, 0, 0);
- XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (sendSz < 0)
- return sendSz;
- } else {
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls)
- DtlsSEQIncrement(ssl, CUR_ORDER);
- #endif
- ret = HashOutput(ssl, output, sendSz, 0);
- if (ret != 0)
- return ret;
- }
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "ServerHello");
- if (ssl->toInfoOn)
- AddPacketInfo(ssl, "ServerHello", handshake, output, sendSz,
- WRITE_PROTO, ssl->heap);
- #endif
- ssl->options.serverState = SERVER_HELLO_COMPLETE;
- ssl->buffers.outputBuffer.length += sendSz;
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- if ((ret = DtlsMsgPoolSave(ssl, output, sendSz)) != 0)
- return ret;
- }
- #endif
- if (ssl->options.groupMessages)
- ret = 0;
- else
- ret = SendBuffered(ssl);
- WOLFSSL_LEAVE("SendServerHello", ret);
- WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
- return ret;
- }
- #if defined(HAVE_ECC)
- static byte SetCurveId(ecc_key* key)
- {
- if (key == NULL || key->dp == NULL) {
- WOLFSSL_MSG("SetCurveId: Invalid key!");
- return 0;
- }
- return (byte)GetCurveByOID(key->dp->oidSum);
- }
- #endif /* HAVE_ECC */
- typedef struct SskeArgs {
- byte* output; /* not allocated */
- #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
- (!defined(NO_DH) && !defined(NO_RSA))
- byte* sigDataBuf;
- #endif
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
- byte* exportBuf;
- #endif
- #ifndef NO_RSA
- byte* verifySig;
- #endif
- byte* input;
- word32 idx;
- word32 tmpSigSz;
- word32 length;
- word32 sigSz;
- #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
- (!defined(NO_DH) && !defined(NO_RSA))
- word32 sigDataSz;
- #endif
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
- word32 exportSz;
- #endif
- #ifdef HAVE_QSH
- word32 qshSz;
- #endif
- int sendSz;
- int inputSz;
- } SskeArgs;
- static void FreeSskeArgs(WOLFSSL* ssl, void* pArgs)
- {
- SskeArgs* args = (SskeArgs*)pArgs;
- (void)ssl;
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
- if (args->exportBuf) {
- XFREE(args->exportBuf, ssl->heap, DYNAMIC_TYPE_DER);
- args->exportBuf = NULL;
- }
- #endif
- #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
- (!defined(NO_DH) && !defined(NO_RSA))
- if (args->sigDataBuf) {
- XFREE(args->sigDataBuf, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- args->sigDataBuf = NULL;
- }
- #endif
- #ifndef NO_RSA
- if (args->verifySig) {
- XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- args->verifySig = NULL;
- }
- #endif
- (void)args;
- }
- /* handle generation of server_key_exchange (12) */
- int SendServerKeyExchange(WOLFSSL* ssl)
- {
- int ret;
- #ifdef WOLFSSL_ASYNC_CRYPT
- SskeArgs* args = (SskeArgs*)ssl->async.args;
- typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
- (void)sizeof(args_test);
- #else
- SskeArgs args[1];
- #endif
- WOLFSSL_START(WC_FUNC_SERVER_KEY_EXCHANGE_SEND);
- WOLFSSL_ENTER("SendServerKeyExchange");
- #ifdef WOLFSSL_ASYNC_CRYPT
- ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
- if (ret != WC_NOT_PENDING_E) {
- /* Check for error */
- if (ret < 0)
- goto exit_sske;
- }
- else
- #endif
- {
- /* Reset state */
- ret = 0;
- ssl->options.asyncState = TLS_ASYNC_BEGIN;
- XMEMSET(args, 0, sizeof(SskeArgs));
- #ifdef WOLFSSL_ASYNC_CRYPT
- ssl->async.freeArgs = FreeSskeArgs;
- #endif
- }
- switch(ssl->options.asyncState)
- {
- case TLS_ASYNC_BEGIN:
- {
- #ifdef HAVE_QSH
- if (ssl->peerQSHKeyPresent && ssl->options.haveQSH) {
- args->qshSz = QSH_KeyGetSize(ssl);
- }
- #endif
- /* Do some checks / debug msgs */
- switch(ssl->specs.kea)
- {
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && !defined(NO_PSK)
- case ecdhe_psk_kea:
- {
- WOLFSSL_MSG("Using ephemeral ECDH PSK");
- break;
- }
- #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
- #if defined(HAVE_ECC)
- case ecc_diffie_hellman_kea:
- {
- if (ssl->specs.static_ecdh) {
- WOLFSSL_MSG("Using Static ECDH, not sending "
- "ServerKeyExchange");
- ERROR_OUT(0, exit_sske);
- }
- WOLFSSL_MSG("Using ephemeral ECDH");
- break;
- }
- #endif /* HAVE_ECC */
- }
- /* Preparing keys */
- switch(ssl->specs.kea)
- {
- #ifndef NO_PSK
- case psk_kea:
- {
- /* Nothing to do in this sub-state */
- break;
- }
- #endif /* !NO_PSK */
- #if !defined(NO_DH) && (!defined(NO_PSK) || !defined(NO_RSA))
- #if !defined(NO_PSK)
- case dhe_psk_kea:
- #endif
- #if !defined(NO_RSA)
- case diffie_hellman_kea:
- #endif
- {
- /* Allocate DH key buffers and generate key */
- if (ssl->buffers.serverDH_P.buffer == NULL ||
- ssl->buffers.serverDH_G.buffer == NULL) {
- ERROR_OUT(NO_DH_PARAMS, exit_sske);
- }
- if (ssl->buffers.serverDH_Pub.buffer == NULL) {
- /* Free'd in SSL_ResourceFree and FreeHandshakeResources */
- ssl->buffers.serverDH_Pub.buffer = (byte*)XMALLOC(
- ssl->buffers.serverDH_P.length + OPAQUE16_LEN,
- ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- if (ssl->buffers.serverDH_Pub.buffer == NULL) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- }
- if (ssl->buffers.serverDH_Priv.buffer == NULL) {
- /* Free'd in SSL_ResourceFree and FreeHandshakeResources */
- ssl->buffers.serverDH_Priv.buffer = (byte*)XMALLOC(
- ssl->buffers.serverDH_P.length + OPAQUE16_LEN,
- ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
- if (ssl->buffers.serverDH_Priv.buffer == NULL) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- }
- ssl->options.dhKeySz =
- (word16)ssl->buffers.serverDH_P.length;
- ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
- (void**)&ssl->buffers.serverDH_Key);
- if (ret != 0) {
- goto exit_sske;
- }
- #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
- !defined(HAVE_FIPS) && \
- !defined(HAVE_SELFTEST)
- if (ssl->options.dhDoKeyTest &&
- !ssl->options.dhKeyTested)
- {
- ret = wc_DhSetCheckKey(
- ssl->buffers.serverDH_Key,
- ssl->buffers.serverDH_P.buffer,
- ssl->buffers.serverDH_P.length,
- ssl->buffers.serverDH_G.buffer,
- ssl->buffers.serverDH_G.length,
- NULL, 0, 0, ssl->rng);
- if (ret != 0) {
- goto exit_sske;
- }
- ssl->options.dhKeyTested = 1;
- }
- else
- #endif
- {
- ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
- ssl->buffers.serverDH_P.buffer,
- ssl->buffers.serverDH_P.length,
- ssl->buffers.serverDH_G.buffer,
- ssl->buffers.serverDH_G.length);
- if (ret != 0) {
- goto exit_sske;
- }
- }
- ret = DhGenKeyPair(ssl, ssl->buffers.serverDH_Key,
- ssl->buffers.serverDH_Priv.buffer,
- (word32*)&ssl->buffers.serverDH_Priv.length,
- ssl->buffers.serverDH_Pub.buffer,
- (word32*)&ssl->buffers.serverDH_Pub.length);
- break;
- }
- #endif /* !NO_DH && (!NO_PSK || !NO_RSA) */
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && !defined(NO_PSK)
- case ecdhe_psk_kea:
- /* Fall through to create temp ECC key */
- #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)
- case ecc_diffie_hellman_kea:
- {
- #ifdef HAVE_CURVE25519
- if (ssl->ecdhCurveOID == ECC_X25519_OID) {
- /* need ephemeral key now, create it if missing */
- if (ssl->eccTempKey == NULL) {
- /* alloc/init on demand */
- ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
- (void**)&ssl->eccTempKey);
- if (ret != 0) {
- goto exit_sske;
- }
- }
- if (ssl->eccTempKeyPresent == 0) {
- ret = X25519MakeKey(ssl,
- (curve25519_key*)ssl->eccTempKey, NULL);
- if (ret == 0 || ret == WC_PENDING_E) {
- ssl->eccTempKeyPresent =
- DYNAMIC_TYPE_CURVE25519;
- }
- }
- break;
- }
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->ecdhCurveOID == ECC_X448_OID) {
- /* need ephemeral key now, create it if missing */
- if (ssl->eccTempKey == NULL) {
- /* alloc/init on demand */
- ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
- (void**)&ssl->eccTempKey);
- if (ret != 0) {
- goto exit_sske;
- }
- }
- if (ssl->eccTempKeyPresent == 0) {
- ret = X448MakeKey(ssl,
- (curve448_key*)ssl->eccTempKey, NULL);
- if (ret == 0 || ret == WC_PENDING_E) {
- ssl->eccTempKeyPresent =
- DYNAMIC_TYPE_CURVE448;
- }
- }
- break;
- }
- #endif
- #ifdef HAVE_ECC
- /* need ephemeral key now, create it if missing */
- if (ssl->eccTempKey == NULL) {
- /* alloc/init on demand */
- ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
- (void**)&ssl->eccTempKey);
- if (ret != 0) {
- goto exit_sske;
- }
- }
- if (ssl->eccTempKeyPresent == 0) {
- ret = EccMakeKey(ssl, ssl->eccTempKey, NULL);
- if (ret == 0 || ret == WC_PENDING_E) {
- ssl->eccTempKeyPresent = DYNAMIC_TYPE_ECC;
- }
- }
- #endif
- break;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- default:
- /* Skip ServerKeyExchange */
- goto exit_sske;
- } /* switch(ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_sske;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_BUILD;
- } /* case TLS_ASYNC_BEGIN */
- FALL_THROUGH;
- case TLS_ASYNC_BUILD:
- {
- #if (!defined(NO_DH) && !defined(NO_RSA)) || (defined(HAVE_ECC) || \
- defined(HAVE_CURVE25519) || defined(HAVE_CURVE448))
- word32 preSigSz, preSigIdx;
- #endif
- switch(ssl->specs.kea)
- {
- #ifndef NO_PSK
- case psk_kea:
- {
- args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
- if (ssl->arrays->server_hint[0] == 0) {
- ERROR_OUT(0, exit_sske); /* don't send */
- }
- /* include size part */
- args->length = (word32)XSTRLEN(ssl->arrays->server_hint);
- if (args->length > MAX_PSK_ID_LEN) {
- ERROR_OUT(SERVER_HINT_ERROR, exit_sske);
- }
- args->length += HINT_LEN_SZ;
- args->sendSz = args->length + HANDSHAKE_HEADER_SZ +
- RECORD_HEADER_SZ;
- #ifdef HAVE_QSH
- args->length += args->qshSz;
- args->sendSz += args->qshSz;
- #endif
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- }
- #endif
- if (IsEncryptionOn(ssl, 1)) {
- args->sendSz += MAX_MSG_EXTRA;
- }
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
- goto exit_sske;
- }
- /* get output buffer */
- args->output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- AddHeaders(args->output, args->length,
- server_key_exchange, ssl);
- /* key data */
- #ifdef HAVE_QSH
- c16toa((word16)(args->length - args->qshSz -
- HINT_LEN_SZ), args->output + args->idx);
- #else
- c16toa((word16)(args->length - HINT_LEN_SZ),
- args->output + args->idx);
- #endif
- args->idx += HINT_LEN_SZ;
- XMEMCPY(args->output + args->idx,
- ssl->arrays->server_hint,
- args->length - HINT_LEN_SZ);
- break;
- }
- #endif /* !NO_PSK */
- #if !defined(NO_DH) && !defined(NO_PSK)
- case dhe_psk_kea:
- {
- word32 hintLen;
- args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
- args->length = LENGTH_SZ * 3 + /* p, g, pub */
- ssl->buffers.serverDH_P.length +
- ssl->buffers.serverDH_G.length +
- ssl->buffers.serverDH_Pub.length;
- /* include size part */
- hintLen = (word32)XSTRLEN(ssl->arrays->server_hint);
- if (hintLen > MAX_PSK_ID_LEN) {
- ERROR_OUT(SERVER_HINT_ERROR, exit_sske);
- }
- args->length += hintLen + HINT_LEN_SZ;
- args->sendSz = args->length + HANDSHAKE_HEADER_SZ +
- RECORD_HEADER_SZ;
- #ifdef HAVE_QSH
- args->length += args->qshSz;
- args->sendSz += args->qshSz;
- #endif
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- }
- #endif
- if (IsEncryptionOn(ssl, 1)) {
- args->sendSz += MAX_MSG_EXTRA;
- }
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
- goto exit_sske;
- }
- /* get output buffer */
- args->output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- AddHeaders(args->output, args->length,
- server_key_exchange, ssl);
- /* key data */
- c16toa((word16)hintLen, args->output + args->idx);
- args->idx += HINT_LEN_SZ;
- XMEMCPY(args->output + args->idx,
- ssl->arrays->server_hint, hintLen);
- args->idx += hintLen;
- /* add p, g, pub */
- c16toa((word16)ssl->buffers.serverDH_P.length,
- args->output + args->idx);
- args->idx += LENGTH_SZ;
- XMEMCPY(args->output + args->idx,
- ssl->buffers.serverDH_P.buffer,
- ssl->buffers.serverDH_P.length);
- args->idx += ssl->buffers.serverDH_P.length;
- /* g */
- c16toa((word16)ssl->buffers.serverDH_G.length,
- args->output + args->idx);
- args->idx += LENGTH_SZ;
- XMEMCPY(args->output + args->idx,
- ssl->buffers.serverDH_G.buffer,
- ssl->buffers.serverDH_G.length);
- args->idx += ssl->buffers.serverDH_G.length;
- /* pub */
- c16toa((word16)ssl->buffers.serverDH_Pub.length,
- args->output + args->idx);
- args->idx += LENGTH_SZ;
- XMEMCPY(args->output + args->idx,
- ssl->buffers.serverDH_Pub.buffer,
- ssl->buffers.serverDH_Pub.length);
- /* No need to update idx, since sizes are already set */
- /* args->idx += ssl->buffers.serverDH_Pub.length; */
- break;
- }
- #endif /* !defined(NO_DH) && !defined(NO_PSK) */
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && !defined(NO_PSK)
- case ecdhe_psk_kea:
- {
- word32 hintLen;
- /* curve type, named curve, length(1) */
- args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
- args->length = ENUM_LEN + CURVE_LEN + ENUM_LEN;
- args->exportSz = MAX_EXPORT_ECC_SZ;
- args->exportBuf = (byte*)XMALLOC(args->exportSz,
- ssl->heap, DYNAMIC_TYPE_DER);
- if (args->exportBuf == NULL) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- #ifdef HAVE_CURVE25519
- if (ssl->ecdhCurveOID == ECC_X25519_OID) {
- if (wc_curve25519_export_public_ex(
- (curve25519_key*)ssl->eccTempKey,
- args->exportBuf, &args->exportSz,
- EC25519_LITTLE_ENDIAN) != 0) {
- ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
- }
- }
- else
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->ecdhCurveOID == ECC_X448_OID) {
- if (wc_curve448_export_public_ex(
- (curve448_key*)ssl->eccTempKey,
- args->exportBuf, &args->exportSz,
- EC448_LITTLE_ENDIAN) != 0) {
- ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
- }
- }
- else
- #endif
- {
- if (wc_ecc_export_x963(ssl->eccTempKey,
- args->exportBuf, &args->exportSz) != 0) {
- ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
- }
- }
- args->length += args->exportSz;
- /* include size part */
- hintLen = (word32)XSTRLEN(ssl->arrays->server_hint);
- if (hintLen > MAX_PSK_ID_LEN) {
- ERROR_OUT(SERVER_HINT_ERROR, exit_sske);
- }
- args->length += hintLen + HINT_LEN_SZ;
- args->sendSz = args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
- #ifdef HAVE_QSH
- args->length += args->qshSz;
- args->sendSz += args->qshSz;
- #endif
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- }
- #endif
- if (IsEncryptionOn(ssl, 1)) {
- args->sendSz += MAX_MSG_EXTRA;
- }
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
- goto exit_sske;
- }
- /* get output buffer */
- args->output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- /* key data */
- c16toa((word16)hintLen, args->output + args->idx);
- args->idx += HINT_LEN_SZ;
- XMEMCPY(args->output + args->idx,
- ssl->arrays->server_hint, hintLen);
- args->idx += hintLen;
- /* ECC key exchange data */
- args->output[args->idx++] = named_curve;
- args->output[args->idx++] = 0x00; /* leading zero */
- #ifdef HAVE_CURVE25519
- if (ssl->ecdhCurveOID == ECC_X25519_OID)
- args->output[args->idx++] = WOLFSSL_ECC_X25519;
- else
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->ecdhCurveOID == ECC_X448_OID)
- args->output[args->idx++] = WOLFSSL_ECC_X448;
- else
- #endif
- {
- #ifdef HAVE_ECC
- args->output[args->idx++] =
- SetCurveId(ssl->eccTempKey);
- #endif
- }
- args->output[args->idx++] = (byte)args->exportSz;
- XMEMCPY(args->output + args->idx, args->exportBuf,
- args->exportSz);
- break;
- }
- #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)
- case ecc_diffie_hellman_kea:
- {
- enum wc_HashType hashType;
- /* curve type, named curve, length(1) */
- args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
- args->length = ENUM_LEN + CURVE_LEN + ENUM_LEN;
- /* Export temp ECC key and add to length */
- args->exportSz = MAX_EXPORT_ECC_SZ;
- args->exportBuf = (byte*)XMALLOC(args->exportSz,
- ssl->heap, DYNAMIC_TYPE_DER);
- if (args->exportBuf == NULL) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- #ifdef HAVE_CURVE25519
- if (ssl->ecdhCurveOID == ECC_X25519_OID) {
- if (wc_curve25519_export_public_ex(
- (curve25519_key*)ssl->eccTempKey,
- args->exportBuf, &args->exportSz,
- EC25519_LITTLE_ENDIAN) != 0) {
- ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
- }
- }
- else
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->ecdhCurveOID == ECC_X448_OID) {
- if (wc_curve448_export_public_ex(
- (curve448_key*)ssl->eccTempKey,
- args->exportBuf, &args->exportSz,
- EC448_LITTLE_ENDIAN) != 0) {
- ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
- }
- }
- else
- #endif
- {
- #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
- if (wc_ecc_export_x963(ssl->eccTempKey,
- args->exportBuf, &args->exportSz) != 0) {
- ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
- }
- #endif
- }
- args->length += args->exportSz;
- preSigSz = args->length;
- preSigIdx = args->idx;
- if (ssl->buffers.key == NULL) {
- #ifdef HAVE_PK_CALLBACKS
- if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) {
- args->tmpSigSz = GetPrivateKeySigSize(ssl);
- if (args->tmpSigSz == 0) {
- ERROR_OUT(NO_PRIVATE_KEY, exit_sske);
- }
- }
- else
- #endif
- ERROR_OUT(NO_PRIVATE_KEY, exit_sske);
- }
- else {
- switch(ssl->suites->sigAlgo) {
- #ifndef NO_RSA
- #ifdef WC_RSA_PSS
- case rsa_pss_sa_algo:
- #endif
- case rsa_sa_algo:
- {
- word16 keySz;
- ssl->buffers.keyType = rsa_sa_algo;
- ret = DecodePrivateKey(ssl, &keySz);
- if (ret != 0) {
- goto exit_sske;
- }
- args->tmpSigSz = (word32)keySz;
- break;
- }
- #endif /* !NO_RSA */
- #ifdef HAVE_ECC
- case ecc_dsa_sa_algo:
- {
- word16 keySz;
- ssl->buffers.keyType = ecc_dsa_sa_algo;
- ret = DecodePrivateKey(ssl, &keySz);
- if (ret != 0) {
- goto exit_sske;
- }
- /* worst case estimate */
- args->tmpSigSz = keySz;
- break;
- }
- #endif
- #ifdef HAVE_ED25519
- case ed25519_sa_algo:
- {
- word16 keySz;
- ssl->buffers.keyType = ed25519_sa_algo;
- ret = DecodePrivateKey(ssl, &keySz);
- if (ret != 0) {
- goto exit_sske;
- }
- /* worst case estimate */
- args->tmpSigSz = ED25519_SIG_SIZE;
- break;
- }
- #endif /* HAVE_ED25519 */
- #ifdef HAVE_ED448
- case ed448_sa_algo:
- {
- word16 keySz;
- ssl->buffers.keyType = ed448_sa_algo;
- ret = DecodePrivateKey(ssl, &keySz);
- if (ret != 0) {
- goto exit_sske;
- }
- /* worst case estimate */
- args->tmpSigSz = ED448_SIG_SIZE;
- break;
- }
- #endif /* HAVE_ED448 */
- default:
- ERROR_OUT(ALGO_ID_E, exit_sske); /* unsupported type */
- } /* switch(ssl->specs.sig_algo) */
- }
- /* sig length */
- args->length += LENGTH_SZ;
- args->length += args->tmpSigSz;
- if (IsAtLeastTLSv1_2(ssl)) {
- args->length += HASH_SIG_SIZE;
- }
- args->sendSz = args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
- #ifdef HAVE_QSH
- args->length += args->qshSz;
- args->sendSz += args->qshSz;
- #endif
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- preSigIdx = args->idx;
- }
- #endif
- if (IsEncryptionOn(ssl, 1)) {
- args->sendSz += MAX_MSG_EXTRA;
- }
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
- goto exit_sske;
- }
- /* get output buffer */
- args->output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- /* record and message headers will be added below, when we're sure
- of the sig length */
- /* key exchange data */
- args->output[args->idx++] = named_curve;
- args->output[args->idx++] = 0x00; /* leading zero */
- #ifdef HAVE_CURVE25519
- if (ssl->ecdhCurveOID == ECC_X25519_OID)
- args->output[args->idx++] = WOLFSSL_ECC_X25519;
- else
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->ecdhCurveOID == ECC_X448_OID)
- args->output[args->idx++] = WOLFSSL_ECC_X448;
- else
- #endif
- {
- #ifdef HAVE_ECC
- args->output[args->idx++] =
- SetCurveId(ssl->eccTempKey);
- #endif
- }
- args->output[args->idx++] = (byte)args->exportSz;
- XMEMCPY(args->output + args->idx, args->exportBuf, args->exportSz);
- args->idx += args->exportSz;
- /* Determine hash type */
- if (IsAtLeastTLSv1_2(ssl)) {
- EncodeSigAlg(ssl->suites->hashAlgo,
- ssl->suites->sigAlgo,
- &args->output[args->idx]);
- args->idx += 2;
- hashType = HashAlgoToType(ssl->suites->hashAlgo);
- if (hashType == WC_HASH_TYPE_NONE) {
- ERROR_OUT(ALGO_ID_E, exit_sske);
- }
- } else {
- /* only using sha and md5 for rsa */
- #ifndef NO_OLD_TLS
- hashType = WC_HASH_TYPE_SHA;
- if (ssl->suites->sigAlgo == rsa_sa_algo) {
- hashType = WC_HASH_TYPE_MD5_SHA;
- }
- #else
- ERROR_OUT(ALGO_ID_E, exit_sske);
- #endif
- }
- /* Signature length will be written later, when we're sure what it is */
- #ifdef HAVE_FUZZER
- if (ssl->fuzzerCb) {
- ssl->fuzzerCb(ssl, args->output + preSigIdx,
- preSigSz, FUZZ_SIGNATURE, ssl->fuzzerCtx);
- }
- #endif
- /* Assemble buffer to hash for signature */
- args->sigDataSz = RAN_LEN + RAN_LEN + preSigSz;
- args->sigDataBuf = (byte*)XMALLOC(args->sigDataSz,
- ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- if (args->sigDataBuf == NULL) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- XMEMCPY(args->sigDataBuf, ssl->arrays->clientRandom,
- RAN_LEN);
- XMEMCPY(args->sigDataBuf+RAN_LEN,
- ssl->arrays->serverRandom, RAN_LEN);
- XMEMCPY(args->sigDataBuf+RAN_LEN+RAN_LEN,
- args->output + preSigIdx, preSigSz);
- if (ssl->suites->sigAlgo != ed25519_sa_algo &&
- ssl->suites->sigAlgo != ed448_sa_algo) {
- ssl->buffers.sig.length =
- wc_HashGetDigestSize(hashType);
- if ((int)ssl->buffers.sig.length < 0) {
- ERROR_OUT(HASH_TYPE_E, exit_sske);
- }
- ssl->buffers.sig.buffer = (byte*)XMALLOC(
- ssl->buffers.sig.length,
- ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- if (ssl->buffers.sig.buffer == NULL) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- /* Perform hash */
- ret = wc_Hash(hashType, args->sigDataBuf,
- args->sigDataSz,
- ssl->buffers.sig.buffer,
- ssl->buffers.sig.length);
- if (ret != 0) {
- goto exit_sske;
- }
- }
- args->sigSz = args->tmpSigSz;
- /* Sign hash to create signature */
- switch (ssl->suites->sigAlgo)
- {
- #ifndef NO_RSA
- case rsa_sa_algo:
- {
- /* For TLS 1.2 re-encode signature */
- if (IsAtLeastTLSv1_2(ssl)) {
- byte* encodedSig = (byte*)XMALLOC(
- MAX_ENCODED_SIG_SZ, ssl->heap,
- DYNAMIC_TYPE_SIGNATURE);
- if (encodedSig == NULL) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- ssl->buffers.sig.length =
- wc_EncodeSignature(encodedSig,
- ssl->buffers.sig.buffer,
- ssl->buffers.sig.length,
- TypeHash(ssl->suites->hashAlgo));
- /* Replace sig buffer with new one */
- XFREE(ssl->buffers.sig.buffer, ssl->heap,
- DYNAMIC_TYPE_SIGNATURE);
- ssl->buffers.sig.buffer = encodedSig;
- }
- /* write sig size here */
- c16toa((word16)args->sigSz,
- args->output + args->idx);
- args->idx += LENGTH_SZ;
- break;
- }
- #ifdef WC_RSA_PSS
- case rsa_pss_sa_algo:
- /* write sig size here */
- c16toa((word16)args->sigSz,
- args->output + args->idx);
- args->idx += LENGTH_SZ;
- break;
- #endif
- #endif /* !NO_RSA */
- case ecc_dsa_sa_algo:
- {
- break;
- }
- #ifdef HAVE_ED25519
- case ed25519_sa_algo:
- ret = Ed25519CheckPubKey(ssl);
- if (ret != 0)
- goto exit_sske;
- break;
- #endif /* HAVE_ED25519 */
- #ifdef HAVE_ED448
- case ed448_sa_algo:
- ret = Ed448CheckPubKey(ssl);
- if (ret != 0)
- goto exit_sske;
- break;
- #endif /* HAVE_ED448 */
- } /* switch(ssl->specs.sig_algo) */
- break;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #if !defined(NO_DH) && !defined(NO_RSA)
- case diffie_hellman_kea:
- {
- enum wc_HashType hashType;
- args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
- args->length = LENGTH_SZ * 3; /* p, g, pub */
- args->length += ssl->buffers.serverDH_P.length +
- ssl->buffers.serverDH_G.length +
- ssl->buffers.serverDH_Pub.length;
- preSigIdx = args->idx;
- preSigSz = args->length;
- if (!ssl->options.usingAnon_cipher) {
- word16 keySz;
- /* sig length */
- args->length += LENGTH_SZ;
- if (ssl->buffers.key == NULL) {
- #ifdef HAVE_PK_CALLBACKS
- if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
- keySz = (word32)GetPrivateKeySigSize(ssl);
- else
- #endif
- ERROR_OUT(NO_PRIVATE_KEY, exit_sske);
- }
- else
- {
- if (ssl->buffers.keyType == 0)
- ssl->buffers.keyType = rsa_sa_algo;
- ret = DecodePrivateKey(ssl, &keySz);
- if (ret != 0) {
- goto exit_sske;
- }
- }
- if (keySz == 0) { /* test if keySz has error */
- ERROR_OUT(keySz, exit_sske);
- }
- args->tmpSigSz = (word32)keySz;
- args->length += args->tmpSigSz;
- if (IsAtLeastTLSv1_2(ssl)) {
- args->length += HASH_SIG_SIZE;
- }
- }
- args->sendSz = args->length + HANDSHAKE_HEADER_SZ +
- RECORD_HEADER_SZ;
- #ifdef HAVE_QSH
- args->length += args->qshSz;
- args->sendSz += args->qshSz;
- #endif
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- preSigIdx = args->idx;
- }
- #endif
- if (IsEncryptionOn(ssl, 1)) {
- args->sendSz += MAX_MSG_EXTRA;
- }
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
- goto exit_sske;
- }
- /* get output buffer */
- args->output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- AddHeaders(args->output, args->length,
- server_key_exchange, ssl);
- /* add p, g, pub */
- c16toa((word16)ssl->buffers.serverDH_P.length,
- args->output + args->idx);
- args->idx += LENGTH_SZ;
- XMEMCPY(args->output + args->idx,
- ssl->buffers.serverDH_P.buffer,
- ssl->buffers.serverDH_P.length);
- args->idx += ssl->buffers.serverDH_P.length;
- /* g */
- c16toa((word16)ssl->buffers.serverDH_G.length,
- args->output + args->idx);
- args->idx += LENGTH_SZ;
- XMEMCPY(args->output + args->idx,
- ssl->buffers.serverDH_G.buffer,
- ssl->buffers.serverDH_G.length);
- args->idx += ssl->buffers.serverDH_G.length;
- /* pub */
- c16toa((word16)ssl->buffers.serverDH_Pub.length,
- args->output + args->idx);
- args->idx += LENGTH_SZ;
- XMEMCPY(args->output + args->idx,
- ssl->buffers.serverDH_Pub.buffer,
- ssl->buffers.serverDH_Pub.length);
- args->idx += ssl->buffers.serverDH_Pub.length;
- #ifdef HAVE_FUZZER
- if (ssl->fuzzerCb) {
- ssl->fuzzerCb(ssl, args->output + preSigIdx,
- preSigSz, FUZZ_SIGNATURE, ssl->fuzzerCtx);
- }
- #endif
- if (ssl->options.usingAnon_cipher) {
- break;
- }
- /* Determine hash type */
- if (IsAtLeastTLSv1_2(ssl)) {
- EncodeSigAlg(ssl->suites->hashAlgo,
- ssl->suites->sigAlgo,
- &args->output[args->idx]);
- args->idx += 2;
- hashType = HashAlgoToType(ssl->suites->hashAlgo);
- if (hashType == WC_HASH_TYPE_NONE) {
- ERROR_OUT(ALGO_ID_E, exit_sske);
- }
- } else {
- /* only using sha and md5 for rsa */
- #ifndef NO_OLD_TLS
- hashType = WC_HASH_TYPE_SHA;
- if (ssl->suites->sigAlgo == rsa_sa_algo) {
- hashType = WC_HASH_TYPE_MD5_SHA;
- }
- #else
- ERROR_OUT(ALGO_ID_E, exit_sske);
- #endif
- }
- /* signature size */
- c16toa((word16)args->tmpSigSz, args->output + args->idx);
- args->idx += LENGTH_SZ;
- /* Assemble buffer to hash for signature */
- args->sigDataSz = RAN_LEN + RAN_LEN + preSigSz;
- args->sigDataBuf = (byte*)XMALLOC(args->sigDataSz,
- ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- if (args->sigDataBuf == NULL) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- XMEMCPY(args->sigDataBuf, ssl->arrays->clientRandom,
- RAN_LEN);
- XMEMCPY(args->sigDataBuf+RAN_LEN,
- ssl->arrays->serverRandom, RAN_LEN);
- XMEMCPY(args->sigDataBuf+RAN_LEN+RAN_LEN,
- args->output + preSigIdx, preSigSz);
- if (ssl->suites->sigAlgo != ed25519_sa_algo &&
- ssl->suites->sigAlgo != ed448_sa_algo) {
- ssl->buffers.sig.length =
- wc_HashGetDigestSize(hashType);
- ssl->buffers.sig.buffer = (byte*)XMALLOC(
- ssl->buffers.sig.length, ssl->heap,
- DYNAMIC_TYPE_SIGNATURE);
- if (ssl->buffers.sig.buffer == NULL) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- /* Perform hash */
- ret = wc_Hash(hashType, args->sigDataBuf,
- args->sigDataSz,
- ssl->buffers.sig.buffer,
- ssl->buffers.sig.length);
- if (ret != 0) {
- goto exit_sske;
- }
- }
- args->sigSz = args->tmpSigSz;
- /* Sign hash to create signature */
- switch (ssl->suites->sigAlgo)
- {
- #ifndef NO_RSA
- case rsa_sa_algo:
- {
- /* For TLS 1.2 re-encode signature */
- if (IsAtLeastTLSv1_2(ssl)) {
- byte* encodedSig = (byte*)XMALLOC(
- MAX_ENCODED_SIG_SZ, ssl->heap,
- DYNAMIC_TYPE_SIGNATURE);
- if (encodedSig == NULL) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- ssl->buffers.sig.length =
- wc_EncodeSignature(encodedSig,
- ssl->buffers.sig.buffer,
- ssl->buffers.sig.length,
- TypeHash(ssl->suites->hashAlgo));
- /* Replace sig buffer with new one */
- XFREE(ssl->buffers.sig.buffer, ssl->heap,
- DYNAMIC_TYPE_SIGNATURE);
- ssl->buffers.sig.buffer = encodedSig;
- }
- break;
- }
- #endif /* NO_RSA */
- } /* switch (ssl->suites->sigAlgo) */
- break;
- }
- #endif /* !defined(NO_DH) && !defined(NO_RSA) */
- } /* switch(ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_sske;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_DO;
- } /* case TLS_ASYNC_BUILD */
- FALL_THROUGH;
- case TLS_ASYNC_DO:
- {
- switch(ssl->specs.kea)
- {
- #ifndef NO_PSK
- case psk_kea:
- {
- break;
- }
- #endif /* !NO_PSK */
- #if !defined(NO_DH) && !defined(NO_PSK)
- case dhe_psk_kea:
- {
- break;
- }
- #endif /* !defined(NO_DH) && !defined(NO_PSK) */
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && !defined(NO_PSK)
- case ecdhe_psk_kea:
- {
- break;
- }
- #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
- #if defined(HAVE_ECC) || defined(HAVE_ED25519) || \
- defined(HAVE_ED448)
- case ecc_diffie_hellman_kea:
- {
- /* Sign hash to create signature */
- switch (ssl->suites->sigAlgo)
- {
- #ifndef NO_RSA
- #ifdef WC_RSA_PSS
- case rsa_pss_sa_algo:
- #endif
- case rsa_sa_algo:
- {
- RsaKey* key = (RsaKey*)ssl->hsKey;
- ret = RsaSign(ssl,
- ssl->buffers.sig.buffer,
- ssl->buffers.sig.length,
- args->output + args->idx,
- &args->sigSz,
- ssl->suites->sigAlgo, ssl->suites->hashAlgo,
- key,
- ssl->buffers.key
- );
- break;
- }
- #endif /* !NO_RSA */
- #ifdef HAVE_ECC
- case ecc_dsa_sa_algo:
- {
- ecc_key* key = (ecc_key*)ssl->hsKey;
- ret = EccSign(ssl,
- ssl->buffers.sig.buffer,
- ssl->buffers.sig.length,
- args->output + LENGTH_SZ + args->idx,
- &args->sigSz,
- key,
- #ifdef HAVE_PK_CALLBACKS
- ssl->buffers.key
- #else
- NULL
- #endif
- );
- break;
- }
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- case ed25519_sa_algo:
- {
- ed25519_key* key = (ed25519_key*)ssl->hsKey;
- ret = Ed25519Sign(ssl,
- args->sigDataBuf, args->sigDataSz,
- args->output + LENGTH_SZ + args->idx,
- &args->sigSz,
- key,
- #ifdef HAVE_PK_CALLBACKS
- ssl->buffers.key
- #else
- NULL
- #endif
- );
- break;
- }
- #endif
- #ifdef HAVE_ED448
- case ed448_sa_algo:
- {
- ed448_key* key = (ed448_key*)ssl->hsKey;
- ret = Ed448Sign(ssl,
- args->sigDataBuf, args->sigDataSz,
- args->output + LENGTH_SZ + args->idx,
- &args->sigSz,
- key,
- #ifdef HAVE_PK_CALLBACKS
- ssl->buffers.key
- #else
- NULL
- #endif
- );
- break;
- }
- #endif
- } /* switch(ssl->specs.sig_algo) */
- break;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #if !defined(NO_DH) && !defined(NO_RSA)
- case diffie_hellman_kea:
- {
- /* Sign hash to create signature */
- switch (ssl->suites->sigAlgo)
- {
- #ifndef NO_RSA
- #ifdef WC_RSA_PSS
- case rsa_pss_sa_algo:
- #endif
- case rsa_sa_algo:
- {
- RsaKey* key = (RsaKey*)ssl->hsKey;
- if (ssl->options.usingAnon_cipher) {
- break;
- }
- ret = RsaSign(ssl,
- ssl->buffers.sig.buffer,
- ssl->buffers.sig.length,
- args->output + args->idx,
- &args->sigSz,
- ssl->suites->sigAlgo, ssl->suites->hashAlgo,
- key,
- ssl->buffers.key
- );
- break;
- }
- #endif /* NO_RSA */
- } /* switch (ssl->suites->sigAlgo) */
- break;
- }
- #endif /* !defined(NO_DH) && !defined(NO_RSA) */
- } /* switch(ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_sske;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_VERIFY;
- } /* case TLS_ASYNC_DO */
- FALL_THROUGH;
- case TLS_ASYNC_VERIFY:
- {
- switch(ssl->specs.kea)
- {
- #ifndef NO_PSK
- case psk_kea:
- {
- /* Nothing to do in this sub-state */
- break;
- }
- #endif /* !NO_PSK */
- #if !defined(NO_DH) && !defined(NO_PSK)
- case dhe_psk_kea:
- {
- /* Nothing to do in this sub-state */
- break;
- }
- #endif /* !defined(NO_DH) && !defined(NO_PSK) */
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && !defined(NO_PSK)
- case ecdhe_psk_kea:
- {
- /* Nothing to do in this sub-state */
- break;
- }
- #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)
- case ecc_diffie_hellman_kea:
- {
- switch(ssl->suites->sigAlgo)
- {
- #ifndef NO_RSA
- #ifdef WC_RSA_PSS
- case rsa_pss_sa_algo:
- #endif
- case rsa_sa_algo:
- {
- RsaKey* key = (RsaKey*)ssl->hsKey;
- if (args->verifySig == NULL) {
- if (args->sigSz == 0) {
- ERROR_OUT(BAD_COND_E, exit_sske);
- }
- args->verifySig = (byte*)XMALLOC(
- args->sigSz, ssl->heap,
- DYNAMIC_TYPE_SIGNATURE);
- if (!args->verifySig) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- XMEMCPY(args->verifySig,
- args->output + args->idx, args->sigSz);
- }
- /* check for signature faults */
- ret = VerifyRsaSign(ssl,
- args->verifySig, args->sigSz,
- ssl->buffers.sig.buffer,
- ssl->buffers.sig.length,
- ssl->suites->sigAlgo, ssl->suites->hashAlgo,
- key, ssl->buffers.key
- );
- break;
- }
- #endif
- case ecc_dsa_sa_algo:
- #ifdef HAVE_ED25519
- case ed25519_sa_algo:
- #endif
- #ifdef HAVE_ED448
- case ed448_sa_algo:
- #endif
- {
- /* Now that we know the real sig size, write it. */
- c16toa((word16)args->sigSz,
- args->output + args->idx);
- /* And adjust length and sendSz from estimates */
- args->length += args->sigSz - args->tmpSigSz;
- args->sendSz += args->sigSz - args->tmpSigSz;
- break;
- }
- default:
- ERROR_OUT(ALGO_ID_E, exit_sske); /* unsupported type */
- } /* switch(ssl->specs.sig_algo) */
- break;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #if !defined(NO_DH) && !defined(NO_RSA)
- case diffie_hellman_kea:
- {
- switch (ssl->suites->sigAlgo)
- {
- #ifndef NO_RSA
- #ifndef WC_RSA_PSS
- case rsa_pss_sa_algo:
- #endif
- case rsa_sa_algo:
- {
- RsaKey* key = (RsaKey*)ssl->hsKey;
- if (ssl->options.usingAnon_cipher) {
- break;
- }
- if (args->verifySig == NULL) {
- if (args->sigSz == 0) {
- ERROR_OUT(BAD_COND_E, exit_sske);
- }
- args->verifySig = (byte*)XMALLOC(
- args->sigSz, ssl->heap,
- DYNAMIC_TYPE_SIGNATURE);
- if (!args->verifySig) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- XMEMCPY(args->verifySig,
- args->output + args->idx, args->sigSz);
- }
- /* check for signature faults */
- ret = VerifyRsaSign(ssl,
- args->verifySig, args->sigSz,
- ssl->buffers.sig.buffer,
- ssl->buffers.sig.length,
- ssl->suites->sigAlgo, ssl->suites->hashAlgo,
- key, ssl->buffers.key
- );
- break;
- }
- #endif
- } /* switch (ssl->suites->sigAlgo) */
- break;
- }
- #endif /* !defined(NO_DH) && !defined(NO_RSA) */
- } /* switch(ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_sske;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_FINALIZE;
- } /* case TLS_ASYNC_VERIFY */
- FALL_THROUGH;
- case TLS_ASYNC_FINALIZE:
- {
- #ifdef HAVE_QSH
- if (ssl->peerQSHKeyPresent) {
- if (args->qshSz > 0) {
- args->idx = args->sendSz - args->qshSz;
- if (QSH_KeyExchangeWrite(ssl, 1) != 0) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- /* extension type */
- c16toa(TLSX_QUANTUM_SAFE_HYBRID,
- args->output + args->idx);
- args->idx += OPAQUE16_LEN;
- /* write to output and check amount written */
- if (TLSX_QSHPK_Write(ssl->QSH_secret->list,
- args->output + args->idx) >
- args->qshSz - OPAQUE16_LEN) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- }
- }
- #endif
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)
- if (ssl->specs.kea == ecdhe_psk_kea ||
- ssl->specs.kea == ecc_diffie_hellman_kea) {
- /* Check output to make sure it was set */
- if (args->output) {
- AddHeaders(args->output, args->length,
- server_key_exchange, ssl);
- }
- else {
- ERROR_OUT(BUFFER_ERROR, exit_sske);
- }
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- if (IsEncryptionOn(ssl, 1)) {
- args->inputSz = args->length + HANDSHAKE_HEADER_SZ;
- /* buildmsg adds rechdr */
- args->input = (byte*)XMALLOC(args->inputSz, ssl->heap,
- DYNAMIC_TYPE_IN_BUFFER);
- if (args->input == NULL) {
- ERROR_OUT(MEMORY_E, exit_sske);
- }
- if (args->output == NULL) {
- ERROR_OUT(BUFFER_ERROR, exit_sske);
- }
- XMEMCPY(args->input, args->output + RECORD_HEADER_SZ,
- args->inputSz);
- ret = BuildMessage(ssl, args->output, args->sendSz,
- args->input, args->inputSz, handshake, 1, 0, 0);
- XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- args->input = NULL;
- /* make sure its not double free'd on cleanup */
- if (ret >= 0) {
- args->sendSz = ret;
- ret = 0;
- }
- }
- else {
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- if ((ret = DtlsMsgPoolSave(ssl,
- args->output, args->sendSz)) != 0) {
- goto exit_sske;
- }
- }
- if (ssl->options.dtls)
- DtlsSEQIncrement(ssl, CUR_ORDER);
- #endif
- ret = HashOutput(ssl, args->output, args->sendSz, 0);
- if (ret != 0) {
- goto exit_sske;
- }
- }
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ssl->hsInfoOn) {
- AddPacketName(ssl, "ServerKeyExchange");
- }
- if (ssl->toInfoOn) {
- AddPacketInfo(ssl, "ServerKeyExchange", handshake,
- args->output, args->sendSz, WRITE_PROTO, ssl->heap);
- }
- #endif
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_END;
- } /* case TLS_ASYNC_FINALIZE */
- FALL_THROUGH;
- case TLS_ASYNC_END:
- {
- ssl->buffers.outputBuffer.length += args->sendSz;
- if (!ssl->options.groupMessages) {
- ret = SendBuffered(ssl);
- }
- ssl->options.serverState = SERVER_KEYEXCHANGE_COMPLETE;
- break;
- }
- default:
- ret = INPUT_CASE_ERROR;
- } /* switch(ssl->options.asyncState) */
- exit_sske:
- WOLFSSL_LEAVE("SendServerKeyExchange", ret);
- WOLFSSL_END(WC_FUNC_SERVER_KEY_EXCHANGE_SEND);
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* Handle async operation */
- if (ret == WC_PENDING_E)
- return ret;
- #endif /* WOLFSSL_ASYNC_CRYPT */
- /* Final cleanup */
- FreeSskeArgs(ssl, args);
- FreeKeyExchange(ssl);
- return ret;
- }
- #if defined(HAVE_SERVER_RENEGOTIATION_INFO) || defined(HAVE_FALLBACK_SCSV) || \
- defined(OPENSSL_ALL)
- /* search suites for specific one, idx on success, negative on error */
- #ifndef WOLFSSL_TLS13
- static
- #endif
- int FindSuite(Suites* suites, byte first, byte second)
- {
- int i;
- if (suites == NULL || suites->suiteSz == 0) {
- WOLFSSL_MSG("Suites pointer error or suiteSz 0");
- return SUITES_ERROR;
- }
- for (i = 0; i < suites->suiteSz-1; i += SUITE_LEN) {
- if (suites->suites[i] == first &&
- suites->suites[i+1] == second )
- return i;
- }
- return MATCH_SUITE_ERROR;
- }
- #endif
- #endif /* !WOLFSSL_NO_TLS12 */
- /* Make sure server cert/key are valid for this suite, true on success */
- static int VerifyServerSuite(WOLFSSL* ssl, word16 idx)
- {
- int haveRSA = !ssl->options.haveStaticECC;
- int havePSK = 0;
- byte first;
- byte second;
- WOLFSSL_ENTER("VerifyServerSuite");
- if (ssl->suites == NULL) {
- WOLFSSL_MSG("Suites pointer error");
- return 0;
- }
- first = ssl->suites->suites[idx];
- second = ssl->suites->suites[idx+1];
- #ifndef NO_PSK
- havePSK = ssl->options.havePSK;
- #endif
- if (ssl->options.haveNTRU)
- haveRSA = 0;
- if (CipherRequires(first, second, REQUIRES_RSA)) {
- WOLFSSL_MSG("Requires RSA");
- if (haveRSA == 0) {
- WOLFSSL_MSG("Don't have RSA");
- return 0;
- }
- }
- if (CipherRequires(first, second, REQUIRES_DHE)) {
- WOLFSSL_MSG("Requires DHE");
- if (ssl->options.haveDH == 0) {
- WOLFSSL_MSG("Don't have DHE");
- return 0;
- }
- }
- if (CipherRequires(first, second, REQUIRES_ECC)) {
- WOLFSSL_MSG("Requires ECC");
- if (ssl->options.haveECC == 0) {
- WOLFSSL_MSG("Don't have ECC");
- return 0;
- }
- }
- if (CipherRequires(first, second, REQUIRES_ECC_STATIC)) {
- WOLFSSL_MSG("Requires static ECC");
- if (ssl->options.haveStaticECC == 0) {
- WOLFSSL_MSG("Don't have static ECC");
- return 0;
- }
- }
- if (CipherRequires(first, second, REQUIRES_PSK)) {
- WOLFSSL_MSG("Requires PSK");
- if (havePSK == 0) {
- WOLFSSL_MSG("Don't have PSK");
- return 0;
- }
- }
- if (CipherRequires(first, second, REQUIRES_NTRU)) {
- WOLFSSL_MSG("Requires NTRU");
- if (ssl->options.haveNTRU == 0) {
- WOLFSSL_MSG("Don't have NTRU");
- return 0;
- }
- }
- if (CipherRequires(first, second, REQUIRES_RSA_SIG)) {
- WOLFSSL_MSG("Requires RSA Signature");
- if (ssl->options.side == WOLFSSL_SERVER_END &&
- ssl->options.haveECDSAsig == 1) {
- WOLFSSL_MSG("Don't have RSA Signature");
- return 0;
- }
- }
- #if !defined(WOLFSSL_OLDTLS_AEAD_CIPHERSUITES)
- if (CipherRequires(first, second, REQUIRES_AEAD)) {
- WOLFSSL_MSG("Requires AEAD");
- if (ssl->version.major == SSLv3_MAJOR &&
- ssl->version.minor < TLSv1_2_MINOR) {
- WOLFSSL_MSG("Version of SSL does not support AEAD ciphers");
- return 0;
- }
- }
- #endif
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && defined(HAVE_SUPPORTED_CURVES)
- if (!TLSX_ValidateSupportedCurves(ssl, first, second)) {
- WOLFSSL_MSG("Don't have matching curves");
- return 0;
- }
- #endif
- /* ECCDHE is always supported if ECC on */
- #ifdef HAVE_QSH
- /* need to negotiate a classic suite in addition to TLS_QSH */
- if (first == QSH_BYTE && second == TLS_QSH) {
- if (TLSX_SupportExtensions(ssl)) {
- ssl->options.haveQSH = 1; /* matched TLS_QSH */
- }
- else {
- WOLFSSL_MSG("Version of SSL connection does not support "
- "TLS_QSH");
- }
- return 0;
- }
- #endif
- #ifdef WOLFSSL_TLS13
- if (IsAtLeastTLSv1_3(ssl->version) &&
- ssl->options.side == WOLFSSL_SERVER_END) {
- /* Try to establish a key share. */
- int ret = TLSX_KeyShare_Establish(ssl);
- if (ret == KEY_SHARE_ERROR)
- ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
- else if (ret != 0)
- return 0;
- }
- else if (first == TLS13_BYTE || (first == ECC_BYTE &&
- (second == TLS_SHA256_SHA256 || second == TLS_SHA384_SHA384))) {
- /* Can't negotiate TLS 1.3 cipher suites with lower protocol
- * version. */
- return 0;
- }
- #endif
- return 1;
- }
- #ifndef NO_WOLFSSL_SERVER
- static int CompareSuites(WOLFSSL* ssl, Suites* peerSuites, word16 i,
- word16 j)
- {
- if (ssl->suites->suites[i] == peerSuites->suites[j] &&
- ssl->suites->suites[i+1] == peerSuites->suites[j+1] ) {
- if (VerifyServerSuite(ssl, i)) {
- int result;
- WOLFSSL_MSG("Verified suite validity");
- ssl->options.cipherSuite0 = ssl->suites->suites[i];
- ssl->options.cipherSuite = ssl->suites->suites[i+1];
- result = SetCipherSpecs(ssl);
- if (result == 0) {
- result = PickHashSigAlgo(ssl, peerSuites->hashSigAlgo,
- peerSuites->hashSigAlgoSz);
- }
- return result;
- }
- else {
- WOLFSSL_MSG("Could not verify suite validity, continue");
- }
- }
- return MATCH_SUITE_ERROR;
- }
- int MatchSuite(WOLFSSL* ssl, Suites* peerSuites)
- {
- int ret;
- word16 i, j;
- WOLFSSL_ENTER("MatchSuite");
- /* & 0x1 equivalent % 2 */
- if (peerSuites->suiteSz == 0 || peerSuites->suiteSz & 0x1)
- return BUFFER_ERROR;
- if (ssl->suites == NULL)
- return SUITES_ERROR;
- if (!ssl->options.useClientOrder) {
- /* Server order */
- for (i = 0; i < ssl->suites->suiteSz; i += 2) {
- for (j = 0; j < peerSuites->suiteSz; j += 2) {
- ret = CompareSuites(ssl, peerSuites, i, j);
- if (ret != MATCH_SUITE_ERROR)
- return ret;
- }
- }
- }
- else {
- /* Client order */
- for (j = 0; j < peerSuites->suiteSz; j += 2) {
- for (i = 0; i < ssl->suites->suiteSz; i += 2) {
- ret = CompareSuites(ssl, peerSuites, i, j);
- if (ret != MATCH_SUITE_ERROR)
- return ret;
- }
- }
- }
- return MATCH_SUITE_ERROR;
- }
- #endif
- #ifdef OLD_HELLO_ALLOWED
- /* process old style client hello, deprecate? */
- int ProcessOldClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
- word32 inSz, word16 sz)
- {
- word32 idx = *inOutIdx;
- word16 sessionSz;
- word16 randomSz;
- word16 i, j;
- ProtocolVersion pv;
- Suites clSuites;
- int ret = -1;
- (void)inSz;
- WOLFSSL_MSG("Got old format client hello");
- #ifdef WOLFSSL_CALLBACKS
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "ClientHello");
- if (ssl->toInfoOn)
- AddLateName("ClientHello", &ssl->timeoutInfo);
- #endif
- /* manually hash input since different format */
- #ifndef NO_OLD_TLS
- #ifndef NO_MD5
- wc_Md5Update(&ssl->hsHashes->hashMd5, input + idx, sz);
- #endif
- #ifndef NO_SHA
- wc_ShaUpdate(&ssl->hsHashes->hashSha, input + idx, sz);
- #endif
- #endif
- #ifndef NO_SHA256
- if (IsAtLeastTLSv1_2(ssl)) {
- int shaRet = wc_Sha256Update(&ssl->hsHashes->hashSha256,
- input + idx, sz);
- if (shaRet != 0)
- return shaRet;
- }
- #endif
- /* does this value mean client_hello? */
- idx++;
- /* version */
- pv.major = input[idx++];
- pv.minor = input[idx++];
- ssl->chVersion = pv; /* store */
- if (ssl->version.minor > pv.minor) {
- byte haveRSA = 0;
- byte havePSK = 0;
- int keySz = 0;
- if (!ssl->options.downgrade) {
- WOLFSSL_MSG("Client trying to connect with lesser version");
- return VERSION_ERROR;
- }
- if (pv.minor < ssl->options.minDowngrade) {
- WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
- return VERSION_ERROR;
- }
- if (pv.minor == SSLv3_MINOR) {
- /* turn off tls */
- WOLFSSL_MSG("\tdowngrading to SSLv3");
- ssl->options.tls = 0;
- ssl->options.tls1_1 = 0;
- ssl->version.minor = SSLv3_MINOR;
- }
- else if (pv.minor == TLSv1_MINOR) {
- WOLFSSL_MSG("\tdowngrading to TLSv1");
- /* turn off tls 1.1+ */
- ssl->options.tls1_1 = 0;
- ssl->version.minor = TLSv1_MINOR;
- }
- else if (pv.minor == TLSv1_1_MINOR) {
- WOLFSSL_MSG("\tdowngrading to TLSv1.1");
- ssl->version.minor = TLSv1_1_MINOR;
- }
- else if (pv.minor == TLSv1_2_MINOR) {
- WOLFSSL_MSG(" downgrading to TLSv1.2");
- ssl->version.minor = TLSv1_2_MINOR;
- }
- #ifndef NO_RSA
- haveRSA = 1;
- #endif
- #ifndef NO_PSK
- havePSK = ssl->options.havePSK;
- #endif
- #ifndef NO_CERTS
- keySz = ssl->buffers.keySz;
- #endif
- InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
- ssl->options.haveDH, ssl->options.haveNTRU,
- ssl->options.haveECDSAsig, ssl->options.haveECC,
- ssl->options.haveStaticECC, ssl->options.side);
- }
- /* suite size */
- ato16(&input[idx], &clSuites.suiteSz);
- idx += OPAQUE16_LEN;
- if (clSuites.suiteSz > WOLFSSL_MAX_SUITE_SZ)
- return BUFFER_ERROR;
- clSuites.hashSigAlgoSz = 0;
- /* session size */
- ato16(&input[idx], &sessionSz);
- idx += OPAQUE16_LEN;
- if (sessionSz > ID_LEN)
- return BUFFER_ERROR;
- /* random size */
- ato16(&input[idx], &randomSz);
- idx += OPAQUE16_LEN;
- if (randomSz > RAN_LEN)
- return BUFFER_ERROR;
- /* suites */
- for (i = 0, j = 0; i < clSuites.suiteSz; i += 3) {
- byte first = input[idx++];
- if (!first) { /* implicit: skip sslv2 type */
- XMEMCPY(&clSuites.suites[j], &input[idx], SUITE_LEN);
- j += SUITE_LEN;
- }
- idx += SUITE_LEN;
- }
- clSuites.suiteSz = j;
- /* session id */
- if (sessionSz) {
- XMEMCPY(ssl->arrays->sessionID, input + idx, sessionSz);
- ssl->arrays->sessionIDSz = (byte)sessionSz;
- idx += sessionSz;
- ssl->options.resuming = 1;
- }
- /* random */
- if (randomSz < RAN_LEN)
- XMEMSET(ssl->arrays->clientRandom, 0, RAN_LEN - randomSz);
- XMEMCPY(&ssl->arrays->clientRandom[RAN_LEN - randomSz], input + idx,
- randomSz);
- idx += randomSz;
- if (ssl->options.usingCompression)
- ssl->options.usingCompression = 0; /* turn off */
- ssl->options.clientState = CLIENT_HELLO_COMPLETE;
- ssl->cbmode = SSL_CB_MODE_WRITE;
- *inOutIdx = idx;
- ssl->options.haveSessionId = 1;
- /* DoClientHello uses same resume code */
- if (ssl->options.resuming) { /* let's try */
- WOLFSSL_SESSION* session = GetSession(ssl,
- ssl->arrays->masterSecret, 1);
- #ifdef HAVE_SESSION_TICKET
- if (ssl->options.useTicket == 1) {
- session = &ssl->session;
- }
- #endif
- if (!session) {
- WOLFSSL_MSG("Session lookup for resume failed");
- ssl->options.resuming = 0;
- } else {
- #ifdef HAVE_EXT_CACHE
- wolfSSL_SESSION_free(session);
- #endif
- if (MatchSuite(ssl, &clSuites) < 0) {
- WOLFSSL_MSG("Unsupported cipher suite, OldClientHello");
- return UNSUPPORTED_SUITE;
- }
- ret = wc_RNG_GenerateBlock(ssl->rng, ssl->arrays->serverRandom,
- RAN_LEN);
- if (ret != 0)
- return ret;
- #ifdef NO_OLD_TLS
- ret = DeriveTlsKeys(ssl);
- #else
- #ifndef NO_TLS
- if (ssl->options.tls)
- ret = DeriveTlsKeys(ssl);
- #endif
- if (!ssl->options.tls)
- ret = DeriveKeys(ssl);
- #endif
- ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
- return ret;
- }
- }
- ret = MatchSuite(ssl, &clSuites);
- if (ret != 0)return ret;
- return SanityCheckMsgReceived(ssl, client_hello);
- }
- #endif /* OLD_HELLO_ALLOWED */
- #ifndef WOLFSSL_NO_TLS12
- int HandleTlsResumption(WOLFSSL* ssl, int bogusID, Suites* clSuites)
- {
- int ret = 0;
- WOLFSSL_SESSION* session;
- (void)bogusID;
- session = GetSession(ssl, ssl->arrays->masterSecret, 1);
- #ifdef HAVE_SESSION_TICKET
- if (ssl->options.useTicket == 1) {
- session = &ssl->session;
- } else if (bogusID == 1 && ssl->options.rejectTicket == 0) {
- WOLFSSL_MSG("Bogus session ID without session ticket");
- return BUFFER_ERROR;
- }
- #endif
- if (!session) {
- WOLFSSL_MSG("Session lookup for resume failed");
- ssl->options.resuming = 0;
- }
- else if (session->haveEMS != ssl->options.haveEMS) {
- /* RFC 7627, 5.3, server-side */
- /* if old sess didn't have EMS, but new does, full handshake */
- if (!session->haveEMS && ssl->options.haveEMS) {
- WOLFSSL_MSG("Attempting to resume a session that didn't "
- "use EMS with a new session with EMS. Do full "
- "handshake.");
- ssl->options.resuming = 0;
- }
- /* if old sess used EMS, but new doesn't, MUST abort */
- else if (session->haveEMS && !ssl->options.haveEMS) {
- WOLFSSL_MSG("Trying to resume a session with EMS without "
- "using EMS");
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, handshake_failure);
- #endif
- return EXT_MASTER_SECRET_NEEDED_E;
- }
- #ifdef HAVE_EXT_CACHE
- wolfSSL_SESSION_free(session);
- #endif
- }
- else {
- #ifndef NO_RESUME_SUITE_CHECK
- int j;
- /* Check client suites include the one in session */
- for (j = 0; j < clSuites->suiteSz; j += 2) {
- if (clSuites->suites[j] == session->cipherSuite0 &&
- clSuites->suites[j+1] == session->cipherSuite) {
- break;
- }
- }
- if (j == clSuites->suiteSz) {
- WOLFSSL_MSG("Prev session's cipher suite not in ClientHello");
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, illegal_parameter);
- #endif
- return UNSUPPORTED_SUITE;
- }
- #endif
- #ifdef HAVE_EXT_CACHE
- wolfSSL_SESSION_free(session);
- #endif
- if (MatchSuite(ssl, clSuites) < 0) {
- WOLFSSL_MSG("Unsupported cipher suite, ClientHello");
- return UNSUPPORTED_SUITE;
- }
- ret = wc_RNG_GenerateBlock(ssl->rng, ssl->arrays->serverRandom,
- RAN_LEN);
- if (ret != 0)
- return ret;
- #ifdef NO_OLD_TLS
- ret = DeriveTlsKeys(ssl);
- #else
- #ifndef NO_TLS
- if (ssl->options.tls)
- ret = DeriveTlsKeys(ssl);
- #endif
- if (!ssl->options.tls)
- ret = DeriveKeys(ssl);
- #endif
- ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
- }
- return ret;
- }
- /* handle processing of client_hello (1) */
- int DoClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
- word32 helloSz)
- {
- byte b;
- byte bogusID = 0; /* flag for a bogus session id */
- ProtocolVersion pv;
- Suites clSuites;
- word32 i = *inOutIdx;
- word32 begin = i;
- int ret = 0;
- #ifdef WOLFSSL_DTLS
- Hmac cookieHmac;
- byte peerCookie[MAX_COOKIE_LEN];
- byte peerCookieSz = 0;
- byte cookieType;
- byte cookieSz = 0;
- XMEMSET(&cookieHmac, 0, sizeof(Hmac));
- #endif /* WOLFSSL_DTLS */
- WOLFSSL_START(WC_FUNC_CLIENT_HELLO_DO);
- WOLFSSL_ENTER("DoClientHello");
- #ifdef WOLFSSL_CALLBACKS
- if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
- if (ssl->toInfoOn) AddLateName("ClientHello", &ssl->timeoutInfo);
- #endif
- /* protocol version, random and session id length check */
- if (OPAQUE16_LEN + RAN_LEN + OPAQUE8_LEN > helloSz)
- return BUFFER_ERROR;
- /* protocol version */
- XMEMCPY(&pv, input + i, OPAQUE16_LEN);
- ssl->chVersion = pv; /* store */
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- #if defined(NO_SHA) && defined(NO_SHA256)
- #error "DTLS needs either SHA or SHA-256"
- #endif /* NO_SHA && NO_SHA256 */
- #if !defined(NO_SHA) && defined(NO_SHA256)
- cookieType = WC_SHA;
- cookieSz = WC_SHA_DIGEST_SIZE;
- #endif /* NO_SHA */
- #ifndef NO_SHA256
- cookieType = WC_SHA256;
- cookieSz = WC_SHA256_DIGEST_SIZE;
- #endif /* NO_SHA256 */
- ret = wc_HmacSetKey(&cookieHmac, cookieType,
- ssl->buffers.dtlsCookieSecret.buffer,
- ssl->buffers.dtlsCookieSecret.length);
- if (ret != 0) return ret;
- ret = wc_HmacUpdate(&cookieHmac,
- (const byte*)ssl->buffers.dtlsCtx.peer.sa,
- ssl->buffers.dtlsCtx.peer.sz);
- if (ret != 0) return ret;
- ret = wc_HmacUpdate(&cookieHmac, input + i, OPAQUE16_LEN);
- if (ret != 0) return ret;
- }
- #endif /* WOLFSSL_DTLS */
- i += OPAQUE16_LEN;
- /* Legacy protocol version cannot negotiate TLS 1.3 or higher. */
- if (pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_3_MINOR)
- pv.minor = TLSv1_2_MINOR;
- if ((!ssl->options.dtls && ssl->version.minor > pv.minor) ||
- (ssl->options.dtls && ssl->version.minor != DTLS_MINOR
- && ssl->version.minor != DTLSv1_2_MINOR && pv.minor != DTLS_MINOR
- && pv.minor != DTLSv1_2_MINOR)) {
- word16 haveRSA = 0;
- word16 havePSK = 0;
- int keySz = 0;
- if (!ssl->options.downgrade) {
- WOLFSSL_MSG("Client trying to connect with lesser version");
- return VERSION_ERROR;
- }
- if (pv.minor < ssl->options.minDowngrade) {
- WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
- return VERSION_ERROR;
- }
- if (pv.minor == SSLv3_MINOR) {
- /* turn off tls */
- WOLFSSL_MSG("\tdowngrading to SSLv3");
- ssl->options.tls = 0;
- ssl->options.tls1_1 = 0;
- ssl->version.minor = SSLv3_MINOR;
- }
- else if (pv.minor == TLSv1_MINOR) {
- /* turn off tls 1.1+ */
- WOLFSSL_MSG("\tdowngrading to TLSv1");
- ssl->options.tls1_1 = 0;
- ssl->version.minor = TLSv1_MINOR;
- }
- else if (pv.minor == TLSv1_1_MINOR) {
- WOLFSSL_MSG("\tdowngrading to TLSv1.1");
- ssl->version.minor = TLSv1_1_MINOR;
- }
- else if (pv.minor == TLSv1_2_MINOR) {
- WOLFSSL_MSG(" downgrading to TLSv1.2");
- ssl->version.minor = TLSv1_2_MINOR;
- }
- #ifndef NO_RSA
- haveRSA = 1;
- #endif
- #ifndef NO_PSK
- havePSK = ssl->options.havePSK;
- #endif
- #ifndef NO_CERTS
- keySz = ssl->buffers.keySz;
- #endif
- InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
- ssl->options.haveDH, ssl->options.haveNTRU,
- ssl->options.haveECDSAsig, ssl->options.haveECC,
- ssl->options.haveStaticECC, ssl->options.side);
- }
- #ifdef OPENSSL_EXTRA
- /* check if option is set to not allow the current version
- * set from either wolfSSL_set_options or wolfSSL_CTX_set_options */
- if (!ssl->options.dtls && ssl->options.downgrade &&
- ssl->options.mask > 0) {
- int reset = 0;
- if (ssl->version.minor == TLSv1_2_MINOR &&
- (ssl->options.mask & SSL_OP_NO_TLSv1_2) == SSL_OP_NO_TLSv1_2) {
- WOLFSSL_MSG("\tOption set to not allow TLSv1.2, Downgrading");
- ssl->version.minor = TLSv1_1_MINOR;
- reset = 1;
- }
- if (ssl->version.minor == TLSv1_1_MINOR &&
- (ssl->options.mask & SSL_OP_NO_TLSv1_1) == SSL_OP_NO_TLSv1_1) {
- WOLFSSL_MSG("\tOption set to not allow TLSv1.1, Downgrading");
- ssl->options.tls1_1 = 0;
- ssl->version.minor = TLSv1_MINOR;
- reset = 1;
- }
- if (ssl->version.minor == TLSv1_MINOR &&
- (ssl->options.mask & SSL_OP_NO_TLSv1) == SSL_OP_NO_TLSv1) {
- WOLFSSL_MSG("\tOption set to not allow TLSv1, Downgrading");
- ssl->options.tls = 0;
- ssl->options.tls1_1 = 0;
- ssl->version.minor = SSLv3_MINOR;
- reset = 1;
- }
- if (ssl->version.minor == SSLv3_MINOR &&
- (ssl->options.mask & SSL_OP_NO_SSLv3) == SSL_OP_NO_SSLv3) {
- WOLFSSL_MSG("\tError, option set to not allow SSLv3");
- return VERSION_ERROR;
- }
- if (ssl->version.minor < ssl->options.minDowngrade) {
- WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
- return VERSION_ERROR;
- }
- if (reset) {
- word16 haveRSA = 0;
- word16 havePSK = 0;
- int keySz = 0;
- #ifndef NO_RSA
- haveRSA = 1;
- #endif
- #ifndef NO_PSK
- havePSK = ssl->options.havePSK;
- #endif
- #ifndef NO_CERTS
- keySz = ssl->buffers.keySz;
- #endif
- /* reset cipher suites to account for TLS version change */
- InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
- ssl->options.haveDH, ssl->options.haveNTRU,
- ssl->options.haveECDSAsig, ssl->options.haveECC,
- ssl->options.haveStaticECC, ssl->options.side);
- }
- }
- #endif
- /* random */
- XMEMCPY(ssl->arrays->clientRandom, input + i, RAN_LEN);
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- ret = wc_HmacUpdate(&cookieHmac, input + i, RAN_LEN);
- if (ret != 0) return ret;
- }
- #endif /* WOLFSSL_DTLS */
- i += RAN_LEN;
- #ifdef SHOW_SECRETS
- {
- int j;
- printf("client random: ");
- for (j = 0; j < RAN_LEN; j++)
- printf("%02x", ssl->arrays->clientRandom[j]);
- printf("\n");
- }
- #endif
- /* session id */
- b = input[i++];
- #ifdef HAVE_SESSION_TICKET
- if (b > 0 && b < ID_LEN) {
- bogusID = 1;
- WOLFSSL_MSG("Client sent bogus session id, let's allow for echo");
- }
- #endif
- if (b == ID_LEN || bogusID) {
- if ((i - begin) + b > helloSz)
- return BUFFER_ERROR;
- XMEMCPY(ssl->arrays->sessionID, input + i, b);
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- ret = wc_HmacUpdate(&cookieHmac, input + i - 1, b + 1);
- if (ret != 0) return ret;
- }
- #endif /* WOLFSSL_DTLS */
- ssl->arrays->sessionIDSz = b;
- i += b;
- ssl->options.resuming = 1; /* client wants to resume */
- WOLFSSL_MSG("Client wants to resume session");
- }
- else if (b) {
- WOLFSSL_MSG("Invalid session ID size");
- return BUFFER_ERROR; /* session ID nor 0 neither 32 bytes long */
- }
- #ifdef WOLFSSL_DTLS
- /* cookie */
- if (ssl->options.dtls) {
- if ((i - begin) + OPAQUE8_LEN > helloSz)
- return BUFFER_ERROR;
- peerCookieSz = input[i++];
- if (peerCookieSz) {
- if (peerCookieSz > MAX_COOKIE_LEN)
- return BUFFER_ERROR;
- if ((i - begin) + peerCookieSz > helloSz)
- return BUFFER_ERROR;
- XMEMCPY(peerCookie, input + i, peerCookieSz);
- i += peerCookieSz;
- }
- }
- #endif
- /* suites */
- if ((i - begin) + OPAQUE16_LEN > helloSz)
- return BUFFER_ERROR;
- ato16(&input[i], &clSuites.suiteSz);
- i += OPAQUE16_LEN;
- /* suites and compression length check */
- if ((i - begin) + clSuites.suiteSz + OPAQUE8_LEN > helloSz)
- return BUFFER_ERROR;
- if (clSuites.suiteSz > WOLFSSL_MAX_SUITE_SZ)
- return BUFFER_ERROR;
- XMEMCPY(clSuites.suites, input + i, clSuites.suiteSz);
- #ifdef HAVE_SERVER_RENEGOTIATION_INFO
- /* check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV suite */
- if (FindSuite(&clSuites, 0, TLS_EMPTY_RENEGOTIATION_INFO_SCSV) >= 0) {
- TLSX* extension;
- /* check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV suite */
- ret = TLSX_AddEmptyRenegotiationInfo(&ssl->extensions, ssl->heap);
- if (ret != WOLFSSL_SUCCESS)
- return ret;
- extension = TLSX_Find(ssl->extensions, TLSX_RENEGOTIATION_INFO);
- if (extension) {
- ssl->secure_renegotiation =
- (SecureRenegotiation*)extension->data;
- ssl->secure_renegotiation->enabled = 1;
- }
- }
- #endif /* HAVE_SERVER_RENEGOTIATION_INFO */
- #if defined(HAVE_FALLBACK_SCSV) || defined(OPENSSL_ALL)
- /* check for TLS_FALLBACK_SCSV suite */
- if (FindSuite(&clSuites, TLS_FALLBACK_SCSV, 0) >= 0) {
- WOLFSSL_MSG("Found Fallback SCSV");
- if (ssl->ctx->method->version.minor > pv.minor) {
- WOLFSSL_MSG("Client trying to connect with lesser version");
- SendAlert(ssl, alert_fatal, inappropriate_fallback);
- return VERSION_ERROR;
- }
- }
- #endif
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- ret = wc_HmacUpdate(&cookieHmac,
- input + i - OPAQUE16_LEN,
- clSuites.suiteSz + OPAQUE16_LEN);
- if (ret != 0) return ret;
- }
- #endif /* WOLFSSL_DTLS */
- i += clSuites.suiteSz;
- clSuites.hashSigAlgoSz = 0;
- /* compression length */
- b = input[i++];
- if ((i - begin) + b > helloSz)
- return BUFFER_ERROR;
- if (b == 0) {
- WOLFSSL_MSG("No compression types in list");
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, decode_error);
- #endif
- return COMPRESSION_ERROR;
- }
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- byte newCookie[MAX_COOKIE_LEN];
- ret = wc_HmacUpdate(&cookieHmac, input + i - 1, b + 1);
- if (ret != 0) return ret;
- ret = wc_HmacFinal(&cookieHmac, newCookie);
- if (ret != 0) return ret;
- /* If a cookie callback is set, call it to overwrite the cookie.
- * This should be deprecated. The code now calculates the cookie
- * using an HMAC as expected. */
- if (ssl->ctx->CBIOCookie != NULL &&
- ssl->ctx->CBIOCookie(ssl, newCookie, cookieSz,
- ssl->IOCB_CookieCtx) != cookieSz) {
- return COOKIE_ERROR;
- }
- /* Check the cookie, see if we progress the state machine. */
- if (peerCookieSz != cookieSz ||
- XMEMCMP(peerCookie, newCookie, cookieSz) != 0) {
- /* Send newCookie to client in a HelloVerifyRequest message
- * and let the state machine alone. */
- ssl->msgsReceived.got_client_hello = 0;
- ssl->keys.dtls_handshake_number = 0;
- ssl->keys.dtls_expected_peer_handshake_number = 0;
- *inOutIdx += helloSz;
- return SendHelloVerifyRequest(ssl, newCookie, cookieSz);
- }
- /* This was skipped in the DTLS case so we could handle the hello
- * verify request. */
- ret = HashInput(ssl, input + *inOutIdx, helloSz);
- if (ret != 0) return ret;
- }
- #endif /* WOLFSSL_DTLS */
- {
- /* compression match types */
- int matchNo = 0;
- int matchZlib = 0;
- while (b--) {
- byte comp = input[i++];
- if (comp == NO_COMPRESSION) {
- matchNo = 1;
- }
- if (comp == ZLIB_COMPRESSION) {
- matchZlib = 1;
- }
- }
- if (ssl->options.usingCompression == 0 && matchNo) {
- WOLFSSL_MSG("Matched No Compression");
- } else if (ssl->options.usingCompression && matchZlib) {
- WOLFSSL_MSG("Matched zlib Compression");
- } else if (ssl->options.usingCompression && matchNo) {
- WOLFSSL_MSG("Could only match no compression, turning off");
- ssl->options.usingCompression = 0; /* turn off */
- } else {
- WOLFSSL_MSG("Could not match compression");
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, illegal_parameter);
- #endif
- return COMPRESSION_ERROR;
- }
- }
- *inOutIdx = i;
- /* tls extensions */
- if ((i - begin) < helloSz) {
- #ifdef HAVE_TLS_EXTENSIONS
- #ifdef HAVE_QSH
- QSH_Init(ssl);
- #endif
- if (TLSX_SupportExtensions(ssl))
- #else
- if (IsAtLeastTLSv1_2(ssl))
- #endif
- {
- /* Process the hello extension. Skip unsupported. */
- word16 totalExtSz;
- #ifdef HAVE_TLS_EXTENSIONS
- /* auto populate extensions supported unless user defined */
- if ((ret = TLSX_PopulateExtensions(ssl, 1)) != 0)
- return ret;
- #endif
- if ((i - begin) + OPAQUE16_LEN > helloSz)
- return BUFFER_ERROR;
- ato16(&input[i], &totalExtSz);
- i += OPAQUE16_LEN;
- if ((i - begin) + totalExtSz > helloSz)
- return BUFFER_ERROR;
- #ifdef HAVE_TLS_EXTENSIONS
- /* tls extensions */
- if ((ret = TLSX_Parse(ssl, (byte *) input + i, totalExtSz,
- client_hello, &clSuites)))
- return ret;
- #ifdef WOLFSSL_TLS13
- if (TLSX_Find(ssl->extensions,
- TLSX_SUPPORTED_VERSIONS) != NULL) {
- WOLFSSL_MSG(
- "Client attempting to connect with higher version");
- return VERSION_ERROR;
- }
- #endif
- #if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
- if((ret=SNI_Callback(ssl)))
- return ret;
- ssl->options.side = WOLFSSL_SERVER_END;
- #endif
- i += totalExtSz;
- #else
- while (totalExtSz) {
- word16 extId, extSz;
- if (OPAQUE16_LEN + OPAQUE16_LEN > totalExtSz)
- return BUFFER_ERROR;
- ato16(&input[i], &extId);
- i += OPAQUE16_LEN;
- ato16(&input[i], &extSz);
- i += OPAQUE16_LEN;
- if (OPAQUE16_LEN + OPAQUE16_LEN + extSz > totalExtSz)
- return BUFFER_ERROR;
- if (extId == HELLO_EXT_SIG_ALGO) {
- word16 hashSigAlgoSz;
- ato16(&input[i], &hashSigAlgoSz);
- i += OPAQUE16_LEN;
- if (OPAQUE16_LEN + hashSigAlgoSz > extSz)
- return BUFFER_ERROR;
- clSuites.hashSigAlgoSz = hashSigAlgoSz;
- if (clSuites.hashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
- WOLFSSL_MSG("ClientHello SigAlgo list exceeds max, "
- "truncating");
- clSuites.hashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
- }
- XMEMCPY(clSuites.hashSigAlgo, &input[i],
- clSuites.hashSigAlgoSz);
- i += hashSigAlgoSz;
- }
- #ifdef HAVE_EXTENDED_MASTER
- else if (extId == HELLO_EXT_EXTMS)
- ssl->options.haveEMS = 1;
- #endif
- else
- i += extSz;
- totalExtSz -= OPAQUE16_LEN + OPAQUE16_LEN + extSz;
- }
- #endif
- *inOutIdx = i;
- }
- else
- *inOutIdx = begin + helloSz; /* skip extensions */
- }
- ssl->options.clientState = CLIENT_HELLO_COMPLETE;
- ssl->options.haveSessionId = 1;
- /* ProcessOld uses same resume code */
- if (ssl->options.resuming) {
- ret = HandleTlsResumption(ssl, bogusID, &clSuites);
- if (ret != 0)
- return ret;
- #ifdef HAVE_SECURE_RENEGOTIATION
- if (ssl->secure_renegotiation &&
- ssl->secure_renegotiation->enabled &&
- IsEncryptionOn(ssl, 0))
- ssl->secure_renegotiation->startScr = 1;
- #endif
- if (ssl->options.clientState == CLIENT_KEYEXCHANGE_COMPLETE) {
- WOLFSSL_LEAVE("DoClientHello", ret);
- WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
- return ret;
- }
- }
- #if defined(HAVE_TLS_EXTENSIONS) && defined(HAVE_DH_DEFAULT_PARAMS)
- #if defined(HAVE_FFDHE) && defined(HAVE_SUPPORTED_CURVES)
- if (TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS) != NULL) {
- /* Set FFDHE parameters or clear DHE parameters if FFDH parameters
- * present and no matches in the server's list. */
- ret = TLSX_SupportedFFDHE_Set(ssl);
- if (ret != 0)
- return ret;
- }
- #endif
- #endif
- ret = MatchSuite(ssl, &clSuites);
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (ret == BUFFER_ERROR)
- SendAlert(ssl, alert_fatal, decode_error);
- else if (ret < 0)
- SendAlert(ssl, alert_fatal, handshake_failure);
- #endif
- #ifdef HAVE_SECURE_RENEGOTIATION
- if (ssl->secure_renegotiation && ssl->secure_renegotiation->enabled &&
- IsEncryptionOn(ssl, 0)) {
- ssl->secure_renegotiation->startScr = 1;
- }
- #endif
- WOLFSSL_LEAVE("DoClientHello", ret);
- WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
- return ret;
- }
- #if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
- defined(HAVE_ED448)) && !defined(WOLFSSL_NO_CLIENT_AUTH)
- typedef struct DcvArgs {
- byte* output; /* not allocated */
- word32 sendSz;
- word16 sz;
- word32 sigSz;
- word32 idx;
- word32 begin;
- byte hashAlgo;
- byte sigAlgo;
- } DcvArgs;
- static void FreeDcvArgs(WOLFSSL* ssl, void* pArgs)
- {
- DcvArgs* args = (DcvArgs*)pArgs;
- (void)ssl;
- (void)args;
- }
- /* handle processing of certificate_verify (15) */
- static int DoCertificateVerify(WOLFSSL* ssl, byte* input,
- word32* inOutIdx, word32 size)
- {
- int ret = 0;
- #ifdef WOLFSSL_ASYNC_CRYPT
- DcvArgs* args = (DcvArgs*)ssl->async.args;
- typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
- (void)sizeof(args_test);
- #else
- DcvArgs args[1];
- #endif
- WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_DO);
- WOLFSSL_ENTER("DoCertificateVerify");
- #ifdef WOLFSSL_ASYNC_CRYPT
- ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
- if (ret != WC_NOT_PENDING_E) {
- /* Check for error */
- if (ret < 0)
- goto exit_dcv;
- }
- else
- #endif
- {
- /* Reset state */
- ret = 0;
- ssl->options.asyncState = TLS_ASYNC_BEGIN;
- XMEMSET(args, 0, sizeof(DcvArgs));
- args->hashAlgo = sha_mac;
- args->sigAlgo = anonymous_sa_algo;
- args->idx = *inOutIdx;
- args->begin = *inOutIdx;
- #ifdef WOLFSSL_ASYNC_CRYPT
- ssl->async.freeArgs = FreeDcvArgs;
- #endif
- }
- switch(ssl->options.asyncState)
- {
- case TLS_ASYNC_BEGIN:
- {
- #ifdef WOLFSSL_CALLBACKS
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "CertificateVerify");
- if (ssl->toInfoOn)
- AddLateName("CertificateVerify", &ssl->timeoutInfo);
- #endif
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_BUILD;
- } /* case TLS_ASYNC_BEGIN */
- FALL_THROUGH;
- case TLS_ASYNC_BUILD:
- {
- if (IsAtLeastTLSv1_2(ssl)) {
- if ((args->idx - args->begin) + ENUM_LEN + ENUM_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcv);
- }
- DecodeSigAlg(&input[args->idx], &args->hashAlgo,
- &args->sigAlgo);
- args->idx += 2;
- }
- #ifndef NO_RSA
- else if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0)
- args->sigAlgo = rsa_sa_algo;
- #endif
- #ifdef HAVE_ECC
- else if (ssl->peerEccDsaKeyPresent)
- args->sigAlgo = ecc_dsa_sa_algo;
- #endif
- #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
- else if (ssl->peerEd25519KeyPresent)
- args->sigAlgo = ed25519_sa_algo;
- #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
- #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
- else if (ssl->peerEd448KeyPresent)
- args->sigAlgo = ed448_sa_algo;
- #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcv);
- }
- ato16(input + args->idx, &args->sz);
- args->idx += OPAQUE16_LEN;
- if ((args->idx - args->begin) + args->sz > size ||
- args->sz > ENCRYPT_LEN) {
- ERROR_OUT(BUFFER_ERROR, exit_dcv);
- }
- #ifdef HAVE_ECC
- if (ssl->peerEccDsaKeyPresent) {
- WOLFSSL_MSG("Doing ECC peer cert verify");
- /* make sure a default is defined */
- #if !defined(NO_SHA)
- SetDigest(ssl, sha_mac);
- #elif !defined(NO_SHA256)
- SetDigest(ssl, sha256_mac);
- #elif defined(WOLFSSL_SHA384)
- SetDigest(ssl, sha384_mac);
- #elif defined(WOLFSSL_SHA512)
- SetDigest(ssl, sha512_mac);
- #else
- #error No digest enabled for ECC sig verify
- #endif
- if (IsAtLeastTLSv1_2(ssl)) {
- if (args->sigAlgo != ecc_dsa_sa_algo) {
- WOLFSSL_MSG("Oops, peer sent ECC key but not in verify");
- }
- SetDigest(ssl, args->hashAlgo);
- }
- }
- #endif /* HAVE_ECC */
- #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
- if (ssl->peerEd25519KeyPresent) {
- WOLFSSL_MSG("Doing ED25519 peer cert verify");
- if (IsAtLeastTLSv1_2(ssl) &&
- args->sigAlgo != ed25519_sa_algo) {
- WOLFSSL_MSG(
- "Oops, peer sent ED25519 key but not in verify");
- }
- }
- #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
- #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
- if (ssl->peerEd448KeyPresent) {
- WOLFSSL_MSG("Doing ED448 peer cert verify");
- if (IsAtLeastTLSv1_2(ssl) &&
- args->sigAlgo != ed448_sa_algo) {
- WOLFSSL_MSG(
- "Oops, peer sent ED448 key but not in verify");
- }
- }
- #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_DO;
- } /* case TLS_ASYNC_BUILD */
- FALL_THROUGH;
- case TLS_ASYNC_DO:
- {
- #ifndef NO_RSA
- if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
- WOLFSSL_MSG("Doing RSA peer cert verify");
- ret = RsaVerify(ssl,
- input + args->idx,
- args->sz,
- &args->output,
- args->sigAlgo, args->hashAlgo,
- ssl->peerRsaKey,
- #ifdef HAVE_PK_CALLBACKS
- &ssl->buffers.peerRsaKey
- #else
- NULL
- #endif
- );
- if (ret >= 0) {
- if (args->sigAlgo == rsa_sa_algo)
- args->sendSz = ret;
- else {
- args->sigSz = ret;
- args->sendSz = ssl->buffers.digest.length;
- }
- ret = 0;
- }
- }
- #endif /* !NO_RSA */
- #ifdef HAVE_ECC
- if (ssl->peerEccDsaKeyPresent) {
- WOLFSSL_MSG("Doing ECC peer cert verify");
- ret = EccVerify(ssl,
- input + args->idx, args->sz,
- ssl->buffers.digest.buffer, ssl->buffers.digest.length,
- ssl->peerEccDsaKey,
- #ifdef HAVE_PK_CALLBACKS
- &ssl->buffers.peerEccDsaKey
- #else
- NULL
- #endif
- );
- }
- #endif /* HAVE_ECC */
- #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
- if (ssl->peerEd25519KeyPresent) {
- WOLFSSL_MSG("Doing Ed25519 peer cert verify");
- ret = Ed25519Verify(ssl,
- input + args->idx, args->sz,
- ssl->hsHashes->messages, ssl->hsHashes->prevLen,
- ssl->peerEd25519Key,
- #ifdef HAVE_PK_CALLBACKS
- &ssl->buffers.peerEd25519Key
- #else
- NULL
- #endif
- );
- }
- #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
- #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
- if (ssl->peerEd448KeyPresent) {
- WOLFSSL_MSG("Doing Ed448 peer cert verify");
- ret = Ed448Verify(ssl,
- input + args->idx, args->sz,
- ssl->hsHashes->messages, ssl->hsHashes->prevLen,
- ssl->peerEd448Key,
- #ifdef HAVE_PK_CALLBACKS
- &ssl->buffers.peerEd448Key
- #else
- NULL
- #endif
- );
- }
- #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* handle async pending */
- if (ret == WC_PENDING_E)
- goto exit_dcv;
- #endif
- /* Check for error */
- if (ret != 0) {
- ret = SIG_VERIFY_E;
- goto exit_dcv;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_VERIFY;
- } /* case TLS_ASYNC_DO */
- FALL_THROUGH;
- case TLS_ASYNC_VERIFY:
- {
- #ifndef NO_RSA
- if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
- if (IsAtLeastTLSv1_2(ssl)) {
- #ifdef WC_RSA_PSS
- if (args->sigAlgo == rsa_pss_sa_algo) {
- SetDigest(ssl, args->hashAlgo);
- #ifdef HAVE_SELFTEST
- ret = wc_RsaPSS_CheckPadding(
- ssl->buffers.digest.buffer,
- ssl->buffers.digest.length,
- args->output, args->sigSz,
- HashAlgoToType(args->hashAlgo));
- #else
- ret = wc_RsaPSS_CheckPadding_ex(
- ssl->buffers.digest.buffer,
- ssl->buffers.digest.length,
- args->output, args->sigSz,
- HashAlgoToType(args->hashAlgo), -1,
- mp_count_bits(&ssl->peerRsaKey->n));
- #endif
- if (ret != 0) {
- ret = SIG_VERIFY_E;
- goto exit_dcv;
- }
- }
- else
- #endif
- {
- #ifdef WOLFSSL_SMALL_STACK
- byte* encodedSig;
- #else
- byte encodedSig[MAX_ENCODED_SIG_SZ];
- #endif
- #ifdef WOLFSSL_SMALL_STACK
- encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
- ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- if (encodedSig == NULL) {
- ERROR_OUT(MEMORY_E, exit_dcv);
- }
- #endif
- if (args->sigAlgo != rsa_sa_algo) {
- WOLFSSL_MSG("Oops, peer sent RSA key but not "
- "in verify");
- }
- SetDigest(ssl, args->hashAlgo);
- args->sigSz = wc_EncodeSignature(encodedSig,
- ssl->buffers.digest.buffer,
- ssl->buffers.digest.length,
- TypeHash(args->hashAlgo));
- if (args->sendSz != args->sigSz || !args->output ||
- XMEMCMP(args->output, encodedSig,
- min(args->sigSz, MAX_ENCODED_SIG_SZ)) != 0) {
- ret = VERIFY_CERT_ERROR;
- }
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(encodedSig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
- #endif
- }
- }
- else {
- if (args->sendSz != FINISHED_SZ || !args->output ||
- XMEMCMP(args->output,
- &ssl->hsHashes->certHashes, FINISHED_SZ) != 0) {
- ret = VERIFY_CERT_ERROR;
- }
- }
- }
- #endif /* !NO_RSA */
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_FINALIZE;
- } /* case TLS_ASYNC_VERIFY */
- FALL_THROUGH;
- case TLS_ASYNC_FINALIZE:
- {
- if (IsEncryptionOn(ssl, 0)) {
- args->idx += ssl->keys.padSz;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead)
- args->idx += MacSize(ssl);
- #endif
- }
- ssl->options.havePeerVerify = 1;
- /* Set final index */
- args->idx += args->sz;
- *inOutIdx = args->idx;
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_END;
- } /* case TLS_ASYNC_FINALIZE */
- case TLS_ASYNC_END:
- {
- break;
- }
- default:
- ret = INPUT_CASE_ERROR;
- } /* switch(ssl->options.asyncState) */
- exit_dcv:
- WOLFSSL_LEAVE("DoCertificateVerify", ret);
- WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_DO);
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* Handle async operation */
- if (ret == WC_PENDING_E) {
- /* Mark message as not received so it can process again */
- ssl->msgsReceived.got_certificate_verify = 0;
- return ret;
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (ret == BUFFER_ERROR)
- SendAlert(ssl, alert_fatal, decode_error);
- else if (ret == SIG_VERIFY_E)
- SendAlert(ssl, alert_fatal, decrypt_error);
- else if (ret != 0)
- SendAlert(ssl, alert_fatal, bad_certificate);
- #endif
- /* Digest is not allocated, so do this to prevent free */
- ssl->buffers.digest.buffer = NULL;
- ssl->buffers.digest.length = 0;
- /* Final cleanup */
- FreeDcvArgs(ssl, args);
- FreeKeyExchange(ssl);
- return ret;
- }
- #endif /* (!NO_RSA || ECC || ED25519 || ED448) && !WOLFSSL_NO_CLIENT_AUTH */
- /* handle generation of server_hello_done (14) */
- int SendServerHelloDone(WOLFSSL* ssl)
- {
- byte* output;
- int sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
- int ret;
- WOLFSSL_START(WC_FUNC_SERVER_HELLO_DONE_SEND);
- WOLFSSL_ENTER("SendServerHelloDone");
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls)
- sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- #endif
- if (IsEncryptionOn(ssl, 1))
- sendSz += MAX_MSG_EXTRA;
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
- return ret;
- /* get output buffer */
- output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- AddHeaders(output, 0, server_hello_done, ssl);
- if (IsEncryptionOn(ssl, 1)) {
- byte* input;
- int inputSz = HANDSHAKE_HEADER_SZ; /* build msg adds rec hdr */
- input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (input == NULL)
- return MEMORY_E;
- XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
- sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
- handshake, 1, 0, 0);
- XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (sendSz < 0)
- return sendSz;
- } else {
- #ifdef WOLFSSL_DTLS
- if (IsDtlsNotSctpMode(ssl)) {
- if ((ret = DtlsMsgPoolSave(ssl, output, sendSz)) != 0)
- return ret;
- }
- if (ssl->options.dtls)
- DtlsSEQIncrement(ssl, CUR_ORDER);
- #endif
- ret = HashOutput(ssl, output, sendSz, 0);
- if (ret != 0)
- return ret;
- }
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "ServerHelloDone");
- if (ssl->toInfoOn)
- AddPacketInfo(ssl, "ServerHelloDone", handshake, output, sendSz,
- WRITE_PROTO, ssl->heap);
- #endif
- ssl->options.serverState = SERVER_HELLODONE_COMPLETE;
- ssl->buffers.outputBuffer.length += sendSz;
- ret = SendBuffered(ssl);
- WOLFSSL_LEAVE("SendServerHelloDone", ret);
- WOLFSSL_END(WC_FUNC_SERVER_HELLO_DONE_SEND);
- return ret;
- }
- #endif /* !WOLFSSL_NO_TLS12 */
- #ifdef HAVE_SESSION_TICKET
- #define WOLFSSL_TICKET_FIXED_SZ (WOLFSSL_TICKET_NAME_SZ + \
- WOLFSSL_TICKET_IV_SZ + WOLFSSL_TICKET_MAC_SZ + LENGTH_SZ)
- #define WOLFSSL_TICKET_ENC_SZ (SESSION_TICKET_LEN - WOLFSSL_TICKET_FIXED_SZ)
- /* our ticket format */
- typedef struct InternalTicket {
- ProtocolVersion pv; /* version when ticket created */
- byte suite[SUITE_LEN]; /* cipher suite when created */
- byte msecret[SECRET_LEN]; /* master secret */
- word32 timestamp; /* born on */
- word16 haveEMS; /* have extended master secret */
- #ifdef WOLFSSL_TLS13
- word32 ageAdd; /* Obfuscation of age */
- word16 namedGroup; /* Named group used */
- #ifndef WOLFSSL_TLS13_DRAFT_18
- TicketNonce ticketNonce; /* Ticket nonce */
- #endif
- #ifdef WOLFSSL_EARLY_DATA
- word32 maxEarlyDataSz; /* Max size of early data */
- #endif
- #endif
- } InternalTicket;
- /* fit within SESSION_TICKET_LEN */
- typedef struct ExternalTicket {
- byte key_name[WOLFSSL_TICKET_NAME_SZ]; /* key context name */
- byte iv[WOLFSSL_TICKET_IV_SZ]; /* this ticket's iv */
- byte enc_len[LENGTH_SZ]; /* encrypted length */
- byte enc_ticket[WOLFSSL_TICKET_ENC_SZ]; /* encrypted internal ticket */
- byte mac[WOLFSSL_TICKET_MAC_SZ]; /* total mac */
- /* !! if add to structure, add to TICKET_FIXED_SZ !! */
- } ExternalTicket;
- /* create a new session ticket, 0 on success */
- int CreateTicket(WOLFSSL* ssl)
- {
- InternalTicket it;
- ExternalTicket* et = (ExternalTicket*)ssl->session.ticket;
- int encLen;
- int ret;
- byte zeros[WOLFSSL_TICKET_MAC_SZ]; /* biggest cmp size */
- XMEMSET(&it, 0, sizeof(it));
- /* build internal */
- it.pv.major = ssl->version.major;
- it.pv.minor = ssl->version.minor;
- it.suite[0] = ssl->options.cipherSuite0;
- it.suite[1] = ssl->options.cipherSuite;
- #ifdef WOLFSSL_EARLY_DATA
- it.maxEarlyDataSz = ssl->options.maxEarlyDataSz;
- #endif
- if (!ssl->options.tls1_3) {
- XMEMCPY(it.msecret, ssl->arrays->masterSecret, SECRET_LEN);
- c32toa(LowResTimer(), (byte*)&it.timestamp);
- it.haveEMS = ssl->options.haveEMS;
- }
- else {
- #ifdef WOLFSSL_TLS13
- /* Client adds to ticket age to obfuscate. */
- ret = wc_RNG_GenerateBlock(ssl->rng, (byte*)&it.ageAdd,
- sizeof(it.ageAdd));
- if (ret != 0)
- return BAD_TICKET_ENCRYPT;
- ssl->session.ticketAdd = it.ageAdd;
- it.namedGroup = ssl->session.namedGroup;
- it.timestamp = TimeNowInMilliseconds();
- /* Resumption master secret. */
- XMEMCPY(it.msecret, ssl->session.masterSecret, SECRET_LEN);
- #ifndef WOLFSSL_TLS13_DRAFT_18
- XMEMCPY(&it.ticketNonce, &ssl->session.ticketNonce,
- sizeof(TicketNonce));
- #endif
- #endif
- }
- /* build external */
- XMEMCPY(et->enc_ticket, &it, sizeof(InternalTicket));
- /* encrypt */
- encLen = WOLFSSL_TICKET_ENC_SZ; /* max size user can use */
- if (ssl->ctx->ticketEncCb == NULL) {
- ret = WOLFSSL_TICKET_RET_FATAL;
- }
- else {
- ret = ssl->ctx->ticketEncCb(ssl, et->key_name, et->iv, et->mac, 1,
- et->enc_ticket, sizeof(InternalTicket),
- &encLen, ssl->ctx->ticketEncCtx);
- }
- if (ret == WOLFSSL_TICKET_RET_OK) {
- if (encLen < (int)sizeof(InternalTicket) ||
- encLen > WOLFSSL_TICKET_ENC_SZ) {
- WOLFSSL_MSG("Bad user ticket encrypt size");
- return BAD_TICKET_KEY_CB_SZ;
- }
- /* sanity checks on encrypt callback */
- /* internal ticket can't be the same if encrypted */
- if (XMEMCMP(et->enc_ticket, &it, sizeof(InternalTicket)) == 0) {
- WOLFSSL_MSG("User ticket encrypt didn't encrypt");
- return BAD_TICKET_ENCRYPT;
- }
- XMEMSET(zeros, 0, sizeof(zeros));
- /* name */
- if (XMEMCMP(et->key_name, zeros, WOLFSSL_TICKET_NAME_SZ) == 0) {
- WOLFSSL_MSG("User ticket encrypt didn't set name");
- return BAD_TICKET_ENCRYPT;
- }
- /* iv */
- if (XMEMCMP(et->iv, zeros, WOLFSSL_TICKET_IV_SZ) == 0) {
- WOLFSSL_MSG("User ticket encrypt didn't set iv");
- return BAD_TICKET_ENCRYPT;
- }
- /* mac */
- if (XMEMCMP(et->mac, zeros, WOLFSSL_TICKET_MAC_SZ) == 0) {
- WOLFSSL_MSG("User ticket encrypt didn't set mac");
- return BAD_TICKET_ENCRYPT;
- }
- /* set size */
- c16toa((word16)encLen, et->enc_len);
- ssl->session.ticketLen = (word16)(encLen + WOLFSSL_TICKET_FIXED_SZ);
- if (encLen < WOLFSSL_TICKET_ENC_SZ) {
- /* move mac up since whole enc buffer not used */
- XMEMMOVE(et->enc_ticket +encLen, et->mac,WOLFSSL_TICKET_MAC_SZ);
- }
- }
- return ret;
- }
- /* Parse ticket sent by client, returns callback return value */
- int DoClientTicket(WOLFSSL* ssl, const byte* input, word32 len)
- {
- ExternalTicket* et;
- InternalTicket* it;
- int ret;
- int outLen;
- word16 inLen;
- WOLFSSL_START(WC_FUNC_TICKET_DO);
- WOLFSSL_ENTER("DoClientTicket");
- if (len > SESSION_TICKET_LEN ||
- len < (word32)(sizeof(InternalTicket) + WOLFSSL_TICKET_FIXED_SZ)) {
- return BAD_TICKET_MSG_SZ;
- }
- et = (ExternalTicket*)input;
- it = (InternalTicket*)et->enc_ticket;
- /* decrypt */
- ato16(et->enc_len, &inLen);
- if (inLen > (word16)(len - WOLFSSL_TICKET_FIXED_SZ)) {
- return BAD_TICKET_MSG_SZ;
- }
- outLen = inLen; /* may be reduced by user padding */
- if (ssl->ctx->ticketEncCb == NULL) {
- ret = WOLFSSL_TICKET_RET_FATAL;
- }
- else {
- ret = ssl->ctx->ticketEncCb(ssl, et->key_name, et->iv,
- et->enc_ticket + inLen, 0,
- et->enc_ticket, inLen, &outLen,
- ssl->ctx->ticketEncCtx);
- }
- if (ret == WOLFSSL_TICKET_RET_FATAL || ret < 0) return ret;
- if (outLen > (int)inLen || outLen < (int)sizeof(InternalTicket)) {
- WOLFSSL_MSG("Bad user ticket decrypt len");
- return BAD_TICKET_KEY_CB_SZ;
- }
- /* get master secret */
- if (ret == WOLFSSL_TICKET_RET_OK || ret == WOLFSSL_TICKET_RET_CREATE) {
- if (ssl->version.minor < it->pv.minor) {
- WOLFSSL_MSG("Ticket has greater version");
- return VERSION_ERROR;
- }
- else if (ssl->version.minor > it->pv.minor) {
- if (!ssl->options.downgrade) {
- WOLFSSL_MSG("Ticket has lesser version");
- return VERSION_ERROR;
- }
- WOLFSSL_MSG("Downgrading protocol due to ticket");
- if (it->pv.minor < ssl->options.minDowngrade)
- return VERSION_ERROR;
- ssl->version.minor = it->pv.minor;
- }
- if (!IsAtLeastTLSv1_3(ssl->version)) {
- XMEMCPY(ssl->arrays->masterSecret, it->msecret, SECRET_LEN);
- /* Copy the haveExtendedMasterSecret property from the ticket to
- * the saved session, so the property may be checked later. */
- ssl->session.haveEMS = it->haveEMS;
- #ifndef NO_RESUME_SUITE_CHECK
- ssl->session.cipherSuite0 = it->suite[0];
- ssl->session.cipherSuite = it->suite[1];
- #endif
- }
- else {
- #ifdef WOLFSSL_TLS13
- /* Restore information to renegotiate. */
- ssl->session.ticketSeen = it->timestamp;
- ssl->session.ticketAdd = it->ageAdd;
- ssl->session.cipherSuite0 = it->suite[0];
- ssl->session.cipherSuite = it->suite[1];
- #ifdef WOLFSSL_EARLY_DATA
- ssl->session.maxEarlyDataSz = it->maxEarlyDataSz;
- #endif
- /* Resumption master secret. */
- XMEMCPY(ssl->session.masterSecret, it->msecret, SECRET_LEN);
- #ifndef WOLFSSL_TLS13_DRAFT_18
- XMEMCPY(&ssl->session.ticketNonce, &it->ticketNonce,
- sizeof(TicketNonce));
- #endif
- ssl->session.namedGroup = it->namedGroup;
- #endif
- }
- }
- WOLFSSL_LEAVE("DoClientTicket", ret);
- WOLFSSL_END(WC_FUNC_TICKET_DO);
- return ret;
- }
- /* send Session Ticket */
- int SendTicket(WOLFSSL* ssl)
- {
- byte* output;
- int ret;
- int sendSz;
- word32 length = SESSION_HINT_SZ + LENGTH_SZ;
- word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
- WOLFSSL_START(WC_FUNC_TICKET_SEND);
- WOLFSSL_ENTER("SendTicket");
- if (ssl->options.createTicket) {
- ret = CreateTicket(ssl);
- if (ret != 0) return ret;
- }
- length += ssl->session.ticketLen;
- sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
- if (!ssl->options.dtls) {
- if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone)
- sendSz += MAX_MSG_EXTRA;
- }
- else {
- #ifdef WOLFSSL_DTLS
- sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
- #endif
- }
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
- return ret;
- /* get output buffer */
- output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- AddHeaders(output, length, session_ticket, ssl);
- /* hint */
- c32toa(ssl->ctx->ticketHint, output + idx);
- idx += SESSION_HINT_SZ;
- /* length */
- c16toa(ssl->session.ticketLen, output + idx);
- idx += LENGTH_SZ;
- /* ticket */
- XMEMCPY(output + idx, ssl->session.ticket, ssl->session.ticketLen);
- idx += ssl->session.ticketLen;
- if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone) {
- byte* input;
- int inputSz = idx - RECORD_HEADER_SZ; /* build msg adds rec hdr */
- input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (input == NULL)
- return MEMORY_E;
- XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
- sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
- handshake, 1, 0, 0);
- XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (sendSz < 0)
- return sendSz;
- }
- else {
- #ifdef WOLFSSL_DTLS
- if (ssl->options.dtls) {
- if ((ret = DtlsMsgPoolSave(ssl, output, sendSz)) != 0)
- return ret;
- DtlsSEQIncrement(ssl, CUR_ORDER);
- }
- #endif
- ret = HashOutput(ssl, output, sendSz, 0);
- if (ret != 0)
- return ret;
- }
- ssl->buffers.outputBuffer.length += sendSz;
- ret = SendBuffered(ssl);
- WOLFSSL_LEAVE("SendTicket", ret);
- WOLFSSL_END(WC_FUNC_TICKET_SEND);
- return ret;
- }
- #endif /* HAVE_SESSION_TICKET */
- #ifndef WOLFSSL_NO_TLS12
- #if defined(HAVE_SECURE_RENEGOTIATION) && \
- defined(HAVE_SERVER_RENEGOTIATION_INFO) && \
- !defined(WOLFSSL_NO_SERVER)
- /* handle generation of server's hello_request (0) */
- int SendHelloRequest(WOLFSSL* ssl)
- {
- byte* output;
- int sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
- int ret;
- WOLFSSL_START(WC_FUNC_HELLO_REQUEST_SEND);
- WOLFSSL_ENTER("SendHelloRequest");
- if (IsEncryptionOn(ssl, 1))
- sendSz += MAX_MSG_EXTRA;
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
- return ret;
- /* get output buffer */
- output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- AddHeaders(output, 0, hello_request, ssl);
- if (IsEncryptionOn(ssl, 1)) {
- byte* input;
- int inputSz = HANDSHAKE_HEADER_SZ; /* build msg adds rec hdr */
- input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (input == NULL)
- return MEMORY_E;
- XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
- sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
- handshake, 0, 0, 0);
- XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
- if (sendSz < 0)
- return sendSz;
- }
- ssl->buffers.outputBuffer.length += sendSz;
- ret = SendBuffered(ssl);
- WOLFSSL_LEAVE("SendHelloRequest", ret);
- WOLFSSL_END(WC_FUNC_HELLO_REQUEST_SEND);
- return ret;
- }
- #endif /* HAVE_SECURE_RENEGOTIATION && HAVE_SERVER_RENEGOTIATION_INFO */
- #ifdef WOLFSSL_DTLS
- /* handle generation of DTLS hello_verify_request (3) */
- static int SendHelloVerifyRequest(WOLFSSL* ssl,
- const byte* cookie, byte cookieSz)
- {
- byte* output;
- int length = VERSION_SZ + ENUM_LEN + cookieSz;
- int idx = DTLS_RECORD_HEADER_SZ + DTLS_HANDSHAKE_HEADER_SZ;
- int sendSz = length + idx;
- int ret;
- /* check for available size */
- if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
- return ret;
- /* get output buffer */
- output = ssl->buffers.outputBuffer.buffer +
- ssl->buffers.outputBuffer.length;
- /* Hello Verify Request should use the same sequence number as the
- * Client Hello. */
- ssl->keys.dtls_sequence_number_hi = ssl->keys.curSeq_hi;
- ssl->keys.dtls_sequence_number_lo = ssl->keys.curSeq_lo;
- AddHeaders(output, length, hello_verify_request, ssl);
- #ifdef OPENSSL_EXTRA
- output[idx++] = DTLS_MAJOR;
- output[idx++] = DTLS_MINOR;
- #else
- output[idx++] = ssl->version.major;
- output[idx++] = ssl->version.minor;
- #endif
- output[idx++] = cookieSz;
- if (cookie == NULL || cookieSz == 0)
- return COOKIE_ERROR;
- XMEMCPY(output + idx, cookie, cookieSz);
- #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
- if (ssl->hsInfoOn)
- AddPacketName(ssl, "HelloVerifyRequest");
- if (ssl->toInfoOn)
- AddPacketInfo(ssl, "HelloVerifyRequest", handshake, output,
- sendSz, WRITE_PROTO, ssl->heap);
- #endif
- ssl->buffers.outputBuffer.length += sendSz;
- return SendBuffered(ssl);
- }
- #endif /* WOLFSSL_DTLS */
- typedef struct DckeArgs {
- byte* output; /* not allocated */
- word32 length;
- word32 idx;
- word32 begin;
- word32 sigSz;
- #ifndef NO_RSA
- int lastErr;
- #endif
- } DckeArgs;
- static void FreeDckeArgs(WOLFSSL* ssl, void* pArgs)
- {
- DckeArgs* args = (DckeArgs*)pArgs;
- (void)ssl;
- (void)args;
- }
- /* handle processing client_key_exchange (16) */
- static int DoClientKeyExchange(WOLFSSL* ssl, byte* input, word32* inOutIdx,
- word32 size)
- {
- int ret;
- #ifdef WOLFSSL_ASYNC_CRYPT
- DckeArgs* args = (DckeArgs*)ssl->async.args;
- typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
- (void)sizeof(args_test);
- #else
- DckeArgs args[1];
- #endif
- (void)size;
- (void)input;
- WOLFSSL_START(WC_FUNC_CLIENT_KEY_EXCHANGE_DO);
- WOLFSSL_ENTER("DoClientKeyExchange");
- #ifdef WOLFSSL_ASYNC_CRYPT
- ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
- if (ret != WC_NOT_PENDING_E) {
- /* Check for error */
- if (ret < 0)
- goto exit_dcke;
- }
- else
- #endif /* WOLFSSL_ASYNC_CRYPT */
- {
- /* Reset state */
- ret = 0;
- ssl->options.asyncState = TLS_ASYNC_BEGIN;
- XMEMSET(args, 0, sizeof(DckeArgs));
- args->idx = *inOutIdx;
- args->begin = *inOutIdx;
- #ifdef WOLFSSL_ASYNC_CRYPT
- ssl->async.freeArgs = FreeDckeArgs;
- #endif
- }
- /* Do Client Key Exchange State Machine */
- switch(ssl->options.asyncState)
- {
- case TLS_ASYNC_BEGIN:
- {
- /* Sanity checks */
- if (ssl->options.side != WOLFSSL_SERVER_END) {
- WOLFSSL_MSG("Client received client keyexchange, attack?");
- WOLFSSL_ERROR(ssl->error = SIDE_ERROR);
- ERROR_OUT(WOLFSSL_FATAL_ERROR, exit_dcke);
- }
- if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
- WOLFSSL_MSG("Client sending keyexchange at wrong time");
- SendAlert(ssl, alert_fatal, unexpected_message);
- ERROR_OUT(OUT_OF_ORDER_E, exit_dcke);
- }
- #ifndef NO_CERTS
- if (ssl->options.verifyPeer && ssl->options.failNoCert) {
- if (!ssl->options.havePeerCert) {
- WOLFSSL_MSG("client didn't present peer cert");
- ERROR_OUT(NO_PEER_CERT, exit_dcke);
- }
- }
- if (ssl->options.verifyPeer && ssl->options.failNoCertxPSK) {
- if (!ssl->options.havePeerCert &&
- !ssl->options.usingPSK_cipher) {
- WOLFSSL_MSG("client didn't present peer cert");
- return NO_PEER_CERT;
- }
- }
- #endif /* !NO_CERTS */
- #if defined(WOLFSSL_CALLBACKS)
- if (ssl->hsInfoOn) {
- AddPacketName(ssl, "ClientKeyExchange");
- }
- if (ssl->toInfoOn) {
- AddLateName("ClientKeyExchange", &ssl->timeoutInfo);
- }
- #endif
- if (ssl->arrays->preMasterSecret == NULL) {
- ssl->arrays->preMasterSz = ENCRYPT_LEN;
- ssl->arrays->preMasterSecret = (byte*)XMALLOC(ENCRYPT_LEN,
- ssl->heap, DYNAMIC_TYPE_SECRET);
- if (ssl->arrays->preMasterSecret == NULL) {
- ERROR_OUT(MEMORY_E, exit_dcke);
- }
- XMEMSET(ssl->arrays->preMasterSecret, 0, ENCRYPT_LEN);
- }
- switch (ssl->specs.kea) {
- #ifndef NO_RSA
- case rsa_kea:
- {
- break;
- } /* rsa_kea */
- #endif /* !NO_RSA */
- #ifndef NO_PSK
- case psk_kea:
- {
- /* sanity check that PSK server callback has been set */
- if (ssl->options.server_psk_cb == NULL) {
- WOLFSSL_MSG("No server PSK callback set");
- ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
- }
- break;
- }
- #endif /* !NO_PSK */
- #ifdef HAVE_NTRU
- case ntru_kea:
- {
- /* make sure private key exists */
- if (ssl->buffers.key == NULL ||
- ssl->buffers.key->buffer == NULL) {
- ERROR_OUT(NO_PRIVATE_KEY, exit_dcke);
- }
- break;
- }
- #endif /* HAVE_NTRU */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)
- case ecc_diffie_hellman_kea:
- {
- break;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #ifndef NO_DH
- case diffie_hellman_kea:
- {
- break;
- }
- #endif /* !NO_DH */
- #if !defined(NO_DH) && !defined(NO_PSK)
- case dhe_psk_kea:
- {
- /* sanity check that PSK server callback has been set */
- if (ssl->options.server_psk_cb == NULL) {
- WOLFSSL_MSG("No server PSK callback set");
- ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
- }
- break;
- }
- #endif /* !NO_DH && !NO_PSK */
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && !defined(NO_PSK)
- case ecdhe_psk_kea:
- {
- /* sanity check that PSK server callback has been set */
- if (ssl->options.server_psk_cb == NULL) {
- WOLFSSL_MSG("No server PSK callback set");
- ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
- }
- break;
- }
- #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
- default:
- WOLFSSL_MSG("Bad kea type");
- ret = BAD_KEA_TYPE_E;
- } /* switch (ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_dcke;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_BUILD;
- } /* TLS_ASYNC_BEGIN */
- FALL_THROUGH;
- case TLS_ASYNC_BUILD:
- {
- switch (ssl->specs.kea) {
- #ifndef NO_RSA
- case rsa_kea:
- {
- word16 keySz;
- ssl->buffers.keyType = rsa_sa_algo;
- ret = DecodePrivateKey(ssl, &keySz);
- if (ret != 0) {
- goto exit_dcke;
- }
- args->length = (word32)keySz;
- ssl->arrays->preMasterSz = SECRET_LEN;
- if (ssl->options.tls) {
- word16 check;
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- ato16(input + args->idx, &check);
- args->idx += OPAQUE16_LEN;
- if ((word32)check != args->length) {
- WOLFSSL_MSG("RSA explicit size doesn't match");
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, bad_record_mac);
- #endif
- ERROR_OUT(RSA_PRIVATE_ERROR, exit_dcke);
- }
- }
- if ((args->idx - args->begin) + args->length > size) {
- WOLFSSL_MSG("RSA message too big");
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- /* pre-load PreMasterSecret with RNG data */
- ret = wc_RNG_GenerateBlock(ssl->rng,
- &ssl->arrays->preMasterSecret[VERSION_SZ],
- SECRET_LEN - VERSION_SZ);
- if (ret != 0) {
- goto exit_dcke;
- }
- args->output = NULL;
- break;
- } /* rsa_kea */
- #endif /* !NO_RSA */
- #ifndef NO_PSK
- case psk_kea:
- {
- byte* pms = ssl->arrays->preMasterSecret;
- word16 ci_sz;
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- ato16(input + args->idx, &ci_sz);
- args->idx += OPAQUE16_LEN;
- if (ci_sz > MAX_PSK_ID_LEN) {
- ERROR_OUT(CLIENT_ID_ERROR, exit_dcke);
- }
- if ((args->idx - args->begin) + ci_sz > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- XMEMCPY(ssl->arrays->client_identity,
- input + args->idx, ci_sz);
- args->idx += ci_sz;
- ssl->arrays->client_identity[ci_sz] = '\0'; /* null term */
- ssl->arrays->psk_keySz = ssl->options.server_psk_cb(ssl,
- ssl->arrays->client_identity, ssl->arrays->psk_key,
- MAX_PSK_KEY_LEN);
- if (ssl->arrays->psk_keySz == 0 ||
- ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
- ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
- }
- /* make psk pre master secret */
- /* length of key + length 0s + length of key + key */
- c16toa((word16) ssl->arrays->psk_keySz, pms);
- pms += OPAQUE16_LEN;
- XMEMSET(pms, 0, ssl->arrays->psk_keySz);
- pms += ssl->arrays->psk_keySz;
- c16toa((word16) ssl->arrays->psk_keySz, pms);
- pms += OPAQUE16_LEN;
- XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
- ssl->arrays->preMasterSz =
- (ssl->arrays->psk_keySz * 2) + (OPAQUE16_LEN * 2);
- break;
- }
- #endif /* !NO_PSK */
- #ifdef HAVE_NTRU
- case ntru_kea:
- {
- word16 cipherLen;
- word16 plainLen = ENCRYPT_LEN;
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- ato16(input + args->idx, &cipherLen);
- args->idx += OPAQUE16_LEN;
- if (cipherLen > MAX_NTRU_ENCRYPT_SZ) {
- ERROR_OUT(NTRU_KEY_ERROR, exit_dcke);
- }
- if ((args->idx - args->begin) + cipherLen > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- if (NTRU_OK != ntru_crypto_ntru_decrypt(
- (word16) ssl->buffers.key->length,
- ssl->buffers.key->buffer, cipherLen,
- input + args->idx, &plainLen,
- ssl->arrays->preMasterSecret)) {
- ERROR_OUT(NTRU_DECRYPT_ERROR, exit_dcke);
- }
- if (plainLen != SECRET_LEN) {
- ERROR_OUT(NTRU_DECRYPT_ERROR, exit_dcke);
- }
- args->idx += cipherLen;
- ssl->arrays->preMasterSz = plainLen;
- break;
- }
- #endif /* HAVE_NTRU */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)
- case ecc_diffie_hellman_kea:
- {
- #ifdef HAVE_ECC
- ecc_key* private_key = ssl->eccTempKey;
- /* handle static private key */
- if (ssl->specs.static_ecdh &&
- ssl->ecdhCurveOID != ECC_X25519_OID &&
- ssl->ecdhCurveOID != ECC_X448_OID) {
- word16 keySz;
- ssl->buffers.keyType = ecc_dsa_sa_algo;
- ret = DecodePrivateKey(ssl, &keySz);
- if (ret != 0) {
- goto exit_dcke;
- }
- private_key = (ecc_key*)ssl->hsKey;
- }
- #endif
- /* import peer ECC key */
- if ((args->idx - args->begin) + OPAQUE8_LEN > size) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, decode_error);
- #endif
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- args->length = input[args->idx++];
- if ((args->idx - args->begin) + args->length > size) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, decode_error);
- #endif
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- #ifdef HAVE_CURVE25519
- if (ssl->ecdhCurveOID == ECC_X25519_OID) {
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->X25519SharedSecretCb != NULL) {
- break;
- }
- #endif
- if (ssl->peerX25519Key == NULL) {
- /* alloc/init on demand */
- ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
- (void**)&ssl->peerX25519Key);
- if (ret != 0) {
- goto exit_dcke;
- }
- } else if (ssl->peerX25519KeyPresent) {
- ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE25519,
- ssl->peerX25519Key);
- ssl->peerX25519KeyPresent = 0;
- if (ret != 0) {
- goto exit_dcke;
- }
- }
- if ((ret = wc_curve25519_check_public(
- input + args->idx, args->length,
- EC25519_LITTLE_ENDIAN)) != 0) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (ret == BUFFER_E)
- SendAlert(ssl, alert_fatal, decode_error);
- else if (ret == ECC_OUT_OF_RANGE_E)
- SendAlert(ssl, alert_fatal, bad_record_mac);
- else {
- SendAlert(ssl, alert_fatal,
- illegal_parameter);
- }
- #endif
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
- }
- if (wc_curve25519_import_public_ex(
- input + args->idx, args->length,
- ssl->peerX25519Key,
- EC25519_LITTLE_ENDIAN)) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, illegal_parameter);
- #endif
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
- }
- ssl->arrays->preMasterSz = CURVE25519_KEYSIZE;
- ssl->peerX25519KeyPresent = 1;
- break;
- }
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->ecdhCurveOID == ECC_X448_OID) {
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->X448SharedSecretCb != NULL) {
- break;
- }
- #endif
- if (ssl->peerX448Key == NULL) {
- /* alloc/init on demand */
- ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
- (void**)&ssl->peerX448Key);
- if (ret != 0) {
- goto exit_dcke;
- }
- } else if (ssl->peerX448KeyPresent) {
- ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE448,
- ssl->peerX448Key);
- ssl->peerX448KeyPresent = 0;
- if (ret != 0) {
- goto exit_dcke;
- }
- }
- if ((ret = wc_curve448_check_public(
- input + args->idx, args->length,
- EC448_LITTLE_ENDIAN)) != 0) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (ret == BUFFER_E)
- SendAlert(ssl, alert_fatal, decode_error);
- else if (ret == ECC_OUT_OF_RANGE_E)
- SendAlert(ssl, alert_fatal, bad_record_mac);
- else {
- SendAlert(ssl, alert_fatal,
- illegal_parameter);
- }
- #endif
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
- }
- if (wc_curve448_import_public_ex(
- input + args->idx, args->length,
- ssl->peerX448Key,
- EC448_LITTLE_ENDIAN)) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, illegal_parameter);
- #endif
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
- }
- ssl->arrays->preMasterSz = CURVE448_KEY_SIZE;
- ssl->peerX448KeyPresent = 1;
- break;
- }
- #endif
- #ifdef HAVE_ECC
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->EccSharedSecretCb != NULL) {
- break;
- }
- #endif
- if (!ssl->specs.static_ecdh &&
- ssl->eccTempKeyPresent == 0) {
- WOLFSSL_MSG("Ecc ephemeral key not made correctly");
- ERROR_OUT(ECC_MAKEKEY_ERROR, exit_dcke);
- }
- if (ssl->peerEccKey == NULL) {
- /* alloc/init on demand */
- ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
- (void**)&ssl->peerEccKey);
- if (ret != 0) {
- goto exit_dcke;
- }
- } else if (ssl->peerEccKeyPresent) {
- ret = ReuseKey(ssl, DYNAMIC_TYPE_ECC,
- ssl->peerEccKey);
- ssl->peerEccKeyPresent = 0;
- if (ret != 0) {
- goto exit_dcke;
- }
- }
- if (wc_ecc_import_x963_ex(input + args->idx,
- args->length, ssl->peerEccKey,
- private_key->dp->id)) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, illegal_parameter);
- #endif
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
- }
- ssl->arrays->preMasterSz = private_key->dp->size;
- ssl->peerEccKeyPresent = 1;
- #endif /* HAVE_ECC */
- break;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #ifndef NO_DH
- case diffie_hellman_kea:
- {
- word16 clientPubSz;
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- ato16(input + args->idx, &clientPubSz);
- args->idx += OPAQUE16_LEN;
- if ((args->idx - args->begin) + clientPubSz > size) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- SendAlert(ssl, alert_fatal, decode_error);
- #endif
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- args->sigSz = clientPubSz;
- ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
- (void**)&ssl->buffers.serverDH_Key);
- if (ret != 0) {
- goto exit_dcke;
- }
- ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
- ssl->buffers.serverDH_P.buffer,
- ssl->buffers.serverDH_P.length,
- ssl->buffers.serverDH_G.buffer,
- ssl->buffers.serverDH_G.length);
- /* set the max agree result size */
- ssl->arrays->preMasterSz = ENCRYPT_LEN;
- break;
- }
- #endif /* !NO_DH */
- #if !defined(NO_DH) && !defined(NO_PSK)
- case dhe_psk_kea:
- {
- word16 clientSz;
- /* Read in the PSK hint */
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- ato16(input + args->idx, &clientSz);
- args->idx += OPAQUE16_LEN;
- if (clientSz > MAX_PSK_ID_LEN) {
- ERROR_OUT(CLIENT_ID_ERROR, exit_dcke);
- }
- if ((args->idx - args->begin) + clientSz > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- XMEMCPY(ssl->arrays->client_identity, input + args->idx,
- clientSz);
- args->idx += clientSz;
- ssl->arrays->client_identity[clientSz] = '\0'; /* null term */
- /* Read in the DHE business */
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- ato16(input + args->idx, &clientSz);
- args->idx += OPAQUE16_LEN;
- if ((args->idx - args->begin) + clientSz > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- args->sigSz = clientSz;
- ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
- (void**)&ssl->buffers.serverDH_Key);
- if (ret != 0) {
- goto exit_dcke;
- }
- ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
- ssl->buffers.serverDH_P.buffer,
- ssl->buffers.serverDH_P.length,
- ssl->buffers.serverDH_G.buffer,
- ssl->buffers.serverDH_G.length);
- break;
- }
- #endif /* !NO_DH && !NO_PSK */
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && !defined(NO_PSK)
- case ecdhe_psk_kea:
- {
- word16 clientSz;
- /* Read in the PSK hint */
- if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- ato16(input + args->idx, &clientSz);
- args->idx += OPAQUE16_LEN;
- if (clientSz > MAX_PSK_ID_LEN) {
- ERROR_OUT(CLIENT_ID_ERROR, exit_dcke);
- }
- if ((args->idx - args->begin) + clientSz > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- XMEMCPY(ssl->arrays->client_identity,
- input + args->idx, clientSz);
- args->idx += clientSz;
- ssl->arrays->client_identity[clientSz] = '\0'; /* null term */
- /* import peer ECC key */
- if ((args->idx - args->begin) + OPAQUE8_LEN > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- args->length = input[args->idx++];
- if ((args->idx - args->begin) + args->length > size) {
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- args->sigSz = ENCRYPT_LEN - OPAQUE16_LEN;
- #ifdef HAVE_CURVE25519
- if (ssl->ecdhCurveOID == ECC_X25519_OID) {
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->X25519SharedSecretCb != NULL) {
- break;
- }
- #endif
- if (ssl->eccTempKeyPresent == 0) {
- WOLFSSL_MSG(
- "X25519 ephemeral key not made correctly");
- ERROR_OUT(ECC_MAKEKEY_ERROR, exit_dcke);
- }
- if (ssl->peerX25519Key == NULL) {
- /* alloc/init on demand */
- ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
- (void**)&ssl->peerX25519Key);
- if (ret != 0) {
- goto exit_dcke;
- }
- } else if (ssl->peerX25519KeyPresent) {
- ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE25519,
- ssl->peerX25519Key);
- ssl->peerX25519KeyPresent = 0;
- if (ret != 0) {
- goto exit_dcke;
- }
- }
- if ((ret = wc_curve25519_check_public(
- input + args->idx, args->length,
- EC25519_LITTLE_ENDIAN)) != 0) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (ret == BUFFER_E)
- SendAlert(ssl, alert_fatal, decode_error);
- else if (ret == ECC_OUT_OF_RANGE_E)
- SendAlert(ssl, alert_fatal, bad_record_mac);
- else {
- SendAlert(ssl, alert_fatal,
- illegal_parameter);
- }
- #endif
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
- }
- if (wc_curve25519_import_public_ex(
- input + args->idx, args->length,
- ssl->peerX25519Key,
- EC25519_LITTLE_ENDIAN)) {
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
- }
- ssl->peerX25519KeyPresent = 1;
- break;
- }
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->ecdhCurveOID == ECC_X448_OID) {
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->X448SharedSecretCb != NULL) {
- break;
- }
- #endif
- if (ssl->eccTempKeyPresent == 0) {
- WOLFSSL_MSG(
- "X448 ephemeral key not made correctly");
- ERROR_OUT(ECC_MAKEKEY_ERROR, exit_dcke);
- }
- if (ssl->peerX448Key == NULL) {
- /* alloc/init on demand */
- ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
- (void**)&ssl->peerX448Key);
- if (ret != 0) {
- goto exit_dcke;
- }
- } else if (ssl->peerX448KeyPresent) {
- ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE448,
- ssl->peerX448Key);
- ssl->peerX448KeyPresent = 0;
- if (ret != 0) {
- goto exit_dcke;
- }
- }
- if ((ret = wc_curve448_check_public(
- input + args->idx, args->length,
- EC448_LITTLE_ENDIAN)) != 0) {
- #ifdef WOLFSSL_EXTRA_ALERTS
- if (ret == BUFFER_E)
- SendAlert(ssl, alert_fatal, decode_error);
- else if (ret == ECC_OUT_OF_RANGE_E)
- SendAlert(ssl, alert_fatal, bad_record_mac);
- else {
- SendAlert(ssl, alert_fatal,
- illegal_parameter);
- }
- #endif
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
- }
- if (wc_curve448_import_public_ex(
- input + args->idx, args->length,
- ssl->peerX448Key,
- EC448_LITTLE_ENDIAN)) {
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
- }
- ssl->peerX448KeyPresent = 1;
- break;
- }
- #endif
- #ifdef HAVE_PK_CALLBACKS
- /* if callback then use it for shared secret */
- if (ssl->ctx->EccSharedSecretCb != NULL) {
- break;
- }
- #endif
- if (ssl->eccTempKeyPresent == 0) {
- WOLFSSL_MSG("Ecc ephemeral key not made correctly");
- ERROR_OUT(ECC_MAKEKEY_ERROR, exit_dcke);
- }
- if (ssl->peerEccKey == NULL) {
- /* alloc/init on demand */
- ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
- (void**)&ssl->peerEccKey);
- if (ret != 0) {
- goto exit_dcke;
- }
- }
- else if (ssl->peerEccKeyPresent) {
- ret = ReuseKey(ssl, DYNAMIC_TYPE_ECC,
- ssl->peerEccKey);
- ssl->peerEccKeyPresent = 0;
- if (ret != 0) {
- goto exit_dcke;
- }
- }
- if (wc_ecc_import_x963_ex(input + args->idx,
- args->length, ssl->peerEccKey,
- ssl->eccTempKey->dp->id)) {
- ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
- }
- ssl->peerEccKeyPresent = 1;
- break;
- }
- #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
- default:
- ret = BAD_KEA_TYPE_E;
- } /* switch (ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_dcke;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_DO;
- } /* TLS_ASYNC_BUILD */
- FALL_THROUGH;
- case TLS_ASYNC_DO:
- {
- switch (ssl->specs.kea) {
- #ifndef NO_RSA
- case rsa_kea:
- {
- RsaKey* key = (RsaKey*)ssl->hsKey;
- ret = RsaDec(ssl,
- input + args->idx,
- args->length,
- &args->output,
- &args->sigSz,
- key,
- #ifdef HAVE_PK_CALLBACKS
- ssl->buffers.key
- #else
- NULL
- #endif
- );
- /* Errors that can occur here that should be
- * indistinguishable:
- * RSA_BUFFER_E, RSA_PAD_E and RSA_PRIVATE_ERROR
- */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E)
- goto exit_dcke;
- #endif
- if (ret == BAD_FUNC_ARG)
- goto exit_dcke;
- args->lastErr = ret - (SECRET_LEN - args->sigSz);
- ret = 0;
- break;
- } /* rsa_kea */
- #endif /* !NO_RSA */
- #ifndef NO_PSK
- case psk_kea:
- {
- break;
- }
- #endif /* !NO_PSK */
- #ifdef HAVE_NTRU
- case ntru_kea:
- {
- break;
- }
- #endif /* HAVE_NTRU */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)
- case ecc_diffie_hellman_kea:
- {
- void* private_key = ssl->eccTempKey;
- (void)private_key;
- #ifdef HAVE_CURVE25519
- if (ssl->ecdhCurveOID == ECC_X25519_OID) {
- ret = X25519SharedSecret(ssl,
- (curve25519_key*)private_key,
- ssl->peerX25519Key,
- input + args->idx, &args->length,
- ssl->arrays->preMasterSecret,
- &ssl->arrays->preMasterSz,
- WOLFSSL_SERVER_END
- );
- break;
- }
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->ecdhCurveOID == ECC_X448_OID) {
- ret = X448SharedSecret(ssl,
- (curve448_key*)private_key,
- ssl->peerX448Key,
- input + args->idx, &args->length,
- ssl->arrays->preMasterSecret,
- &ssl->arrays->preMasterSz,
- WOLFSSL_SERVER_END
- );
- break;
- }
- #endif
- #ifdef HAVE_ECC
- if (ssl->specs.static_ecdh) {
- private_key = ssl->hsKey;
- }
- /* Generate shared secret */
- ret = EccSharedSecret(ssl,
- (ecc_key*)private_key, ssl->peerEccKey,
- input + args->idx, &args->length,
- ssl->arrays->preMasterSecret,
- &ssl->arrays->preMasterSz,
- WOLFSSL_SERVER_END
- );
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret != WC_PENDING_E)
- #endif
- {
- FreeKey(ssl, DYNAMIC_TYPE_ECC,
- (void**)&ssl->peerEccKey);
- ssl->peerEccKeyPresent = 0;
- }
- #endif
- break;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #ifndef NO_DH
- case diffie_hellman_kea:
- {
- ret = DhAgree(ssl, ssl->buffers.serverDH_Key,
- ssl->buffers.serverDH_Priv.buffer,
- ssl->buffers.serverDH_Priv.length,
- input + args->idx,
- (word16)args->sigSz,
- ssl->arrays->preMasterSecret,
- &ssl->arrays->preMasterSz);
- break;
- }
- #endif /* !NO_DH */
- #if !defined(NO_DH) && !defined(NO_PSK)
- case dhe_psk_kea:
- {
- ret = DhAgree(ssl, ssl->buffers.serverDH_Key,
- ssl->buffers.serverDH_Priv.buffer,
- ssl->buffers.serverDH_Priv.length,
- input + args->idx,
- (word16)args->sigSz,
- ssl->arrays->preMasterSecret + OPAQUE16_LEN,
- &ssl->arrays->preMasterSz);
- break;
- }
- #endif /* !NO_DH && !NO_PSK */
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && !defined(NO_PSK)
- case ecdhe_psk_kea:
- {
- #ifdef HAVE_CURVE25519
- if (ssl->ecdhCurveOID == ECC_X25519_OID) {
- ret = X25519SharedSecret(ssl,
- (curve25519_key*)ssl->eccTempKey,
- ssl->peerX25519Key,
- input + args->idx, &args->length,
- ssl->arrays->preMasterSecret + OPAQUE16_LEN,
- &args->sigSz,
- WOLFSSL_SERVER_END
- );
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret != WC_PENDING_E)
- #endif
- {
- FreeKey(ssl, DYNAMIC_TYPE_CURVE25519,
- (void**)&ssl->peerX25519Key);
- ssl->peerX25519KeyPresent = 0;
- }
- break;
- }
- #endif
- #ifdef HAVE_CURVE448
- if (ssl->ecdhCurveOID == ECC_X448_OID) {
- ret = X448SharedSecret(ssl,
- (curve448_key*)ssl->eccTempKey,
- ssl->peerX448Key,
- input + args->idx, &args->length,
- ssl->arrays->preMasterSecret + OPAQUE16_LEN,
- &args->sigSz,
- WOLFSSL_SERVER_END
- );
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret != WC_PENDING_E)
- #endif
- {
- FreeKey(ssl, DYNAMIC_TYPE_CURVE448,
- (void**)&ssl->peerX448Key);
- ssl->peerX448KeyPresent = 0;
- }
- break;
- }
- #endif
- /* Generate shared secret */
- ret = EccSharedSecret(ssl,
- ssl->eccTempKey, ssl->peerEccKey,
- input + args->idx, &args->length,
- ssl->arrays->preMasterSecret + OPAQUE16_LEN,
- &args->sigSz,
- WOLFSSL_SERVER_END
- );
- if (!ssl->specs.static_ecdh
- #ifdef WOLFSSL_ASYNC_CRYPT
- && ret != WC_PENDING_E
- #endif
- ) {
- FreeKey(ssl, DYNAMIC_TYPE_ECC,
- (void**)&ssl->peerEccKey);
- ssl->peerEccKeyPresent = 0;
- }
- break;
- }
- #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
- default:
- ret = BAD_KEA_TYPE_E;
- } /* switch (ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_dcke;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_VERIFY;
- } /* TLS_ASYNC_DO */
- FALL_THROUGH;
- case TLS_ASYNC_VERIFY:
- {
- switch (ssl->specs.kea) {
- #ifndef NO_RSA
- case rsa_kea:
- {
- byte mask;
- int i;
- /* Add the signature length to idx */
- args->idx += args->length;
- #ifdef DEBUG_WOLFSSL
- /* check version (debug warning message only) */
- if (args->output != NULL) {
- if (args->output[0] != ssl->chVersion.major ||
- args->output[1] != ssl->chVersion.minor) {
- WOLFSSL_MSG("preMasterSecret version mismatch");
- }
- }
- #endif
- /* RFC5246 7.4.7.1:
- * Treat incorrectly formatted message blocks and/or
- * mismatched version numbers in a manner
- * indistinguishable from correctly formatted RSA blocks
- */
- ret = args->lastErr;
- args->lastErr = 0; /* reset */
- /* On error 'ret' will be negative - top bit set */
- mask = ((unsigned int)ret >>
- ((sizeof(ret) * 8) - 1)) - 1;
- /* build PreMasterSecret */
- ssl->arrays->preMasterSecret[0] = ssl->chVersion.major;
- ssl->arrays->preMasterSecret[1] = ssl->chVersion.minor;
- if (args->output != NULL) {
- /* Use random secret on error */
- for (i = VERSION_SZ; i < SECRET_LEN; i++) {
- ssl->arrays->preMasterSecret[i] =
- ctMaskSel(mask, args->output[i],
- ssl->arrays->preMasterSecret[i]);
- }
- }
- /* preMasterSecret has RNG and version set
- * return proper length and ignore error
- * error will be caught as decryption error
- */
- args->sigSz = SECRET_LEN;
- ret = 0;
- break;
- } /* rsa_kea */
- #endif /* !NO_RSA */
- #ifndef NO_PSK
- case psk_kea:
- {
- break;
- }
- #endif /* !NO_PSK */
- #ifdef HAVE_NTRU
- case ntru_kea:
- {
- break;
- }
- #endif /* HAVE_NTRU */
- #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)
- case ecc_diffie_hellman_kea:
- {
- /* skip past the imported peer key */
- args->idx += args->length;
- break;
- }
- #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
- #ifndef NO_DH
- case diffie_hellman_kea:
- {
- args->idx += (word16)args->sigSz;
- break;
- }
- #endif /* !NO_DH */
- #if !defined(NO_DH) && !defined(NO_PSK)
- case dhe_psk_kea:
- {
- byte* pms = ssl->arrays->preMasterSecret;
- word16 clientSz = (word16)args->sigSz;
- args->idx += clientSz;
- c16toa((word16)ssl->arrays->preMasterSz, pms);
- ssl->arrays->preMasterSz += OPAQUE16_LEN;
- pms += ssl->arrays->preMasterSz;
- /* Use the PSK hint to look up the PSK and add it to the
- * preMasterSecret here. */
- ssl->arrays->psk_keySz = ssl->options.server_psk_cb(ssl,
- ssl->arrays->client_identity, ssl->arrays->psk_key,
- MAX_PSK_KEY_LEN);
- if (ssl->arrays->psk_keySz == 0 ||
- ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
- ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
- }
- c16toa((word16) ssl->arrays->psk_keySz, pms);
- pms += OPAQUE16_LEN;
- XMEMCPY(pms, ssl->arrays->psk_key,
- ssl->arrays->psk_keySz);
- ssl->arrays->preMasterSz += ssl->arrays->psk_keySz +
- OPAQUE16_LEN;
- break;
- }
- #endif /* !NO_DH && !NO_PSK */
- #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
- defined(HAVE_CURVE448)) && !defined(NO_PSK)
- case ecdhe_psk_kea:
- {
- byte* pms = ssl->arrays->preMasterSecret;
- word16 clientSz = (word16)args->sigSz;
- /* skip past the imported peer key */
- args->idx += args->length;
- /* Add preMasterSecret */
- c16toa(clientSz, pms);
- ssl->arrays->preMasterSz = OPAQUE16_LEN + clientSz;
- pms += ssl->arrays->preMasterSz;
- /* Use the PSK hint to look up the PSK and add it to the
- * preMasterSecret here. */
- ssl->arrays->psk_keySz = ssl->options.server_psk_cb(ssl,
- ssl->arrays->client_identity, ssl->arrays->psk_key,
- MAX_PSK_KEY_LEN);
- if (ssl->arrays->psk_keySz == 0 ||
- ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
- ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
- }
- c16toa((word16) ssl->arrays->psk_keySz, pms);
- pms += OPAQUE16_LEN;
- XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
- ssl->arrays->preMasterSz +=
- ssl->arrays->psk_keySz + OPAQUE16_LEN;
- break;
- }
- #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
- default:
- ret = BAD_KEA_TYPE_E;
- } /* switch (ssl->specs.kea) */
- /* Check for error */
- if (ret != 0) {
- goto exit_dcke;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_FINALIZE;
- } /* TLS_ASYNC_VERIFY */
- FALL_THROUGH;
- case TLS_ASYNC_FINALIZE:
- {
- if (IsEncryptionOn(ssl, 0)) {
- args->idx += ssl->keys.padSz;
- #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
- if (ssl->options.startedETMRead)
- args->idx += MacSize(ssl);
- #endif
- }
- #ifdef HAVE_QSH
- word16 name;
- if (ssl->options.haveQSH) {
- /* extension name */
- ato16(input + args->idx, &name);
- args->idx += OPAQUE16_LEN;
- if (name == TLSX_QUANTUM_SAFE_HYBRID) {
- int qshSz;
- /* if qshSz is larger than 0 it is the
- length of buffer used */
- if ((qshSz = TLSX_QSHCipher_Parse(ssl,
- input + args->idx,
- size - args->idx + args->begin, 1)) < 0) {
- ERROR_OUT(qshSz, exit_dcke);
- }
- args->idx += qshSz;
- }
- else {
- /* unknown extension sent client ignored handshake */
- ERROR_OUT(BUFFER_ERROR, exit_dcke);
- }
- }
- #endif /* HAVE_QSH */
- ret = MakeMasterSecret(ssl);
- /* Check for error */
- if (ret != 0) {
- goto exit_dcke;
- }
- /* Advance state and proceed */
- ssl->options.asyncState = TLS_ASYNC_END;
- } /* TLS_ASYNC_FINALIZE */
- FALL_THROUGH;
- case TLS_ASYNC_END:
- {
- /* Set final index */
- *inOutIdx = args->idx;
- ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
- #ifndef NO_CERTS
- if (ssl->options.verifyPeer) {
- ret = BuildCertHashes(ssl, &ssl->hsHashes->certHashes);
- }
- #endif
- break;
- } /* TLS_ASYNC_END */
- default:
- ret = INPUT_CASE_ERROR;
- } /* switch(ssl->options.asyncState) */
- exit_dcke:
- WOLFSSL_LEAVE("DoClientKeyExchange", ret);
- WOLFSSL_END(WC_FUNC_CLIENT_KEY_EXCHANGE_DO);
- #ifdef WOLFSSL_ASYNC_CRYPT
- /* Handle async operation */
- if (ret == WC_PENDING_E) {
- /* Mark message as not received so it can process again */
- ssl->msgsReceived.got_client_key_exchange = 0;
- return ret;
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- /* Cleanup PMS */
- if (ssl->arrays->preMasterSecret != NULL) {
- ForceZero(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
- }
- ssl->arrays->preMasterSz = 0;
- /* Final cleanup */
- FreeDckeArgs(ssl, args);
- FreeKeyExchange(ssl);
- return ret;
- }
- #endif /* !WOLFSSL_NO_TLS12 */
- #if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
- defined(WOLFSSL_HAPROXY)
- int SNI_Callback(WOLFSSL* ssl)
- {
- /* Stunnel supports a custom sni callback to switch an SSL's ctx
- * when SNI is received. Call it now if exists */
- if(ssl && ssl->ctx && ssl->ctx->sniRecvCb) {
- WOLFSSL_MSG("Calling custom sni callback");
- if(ssl->ctx->sniRecvCb(ssl, NULL, ssl->ctx->sniRecvCbArg)
- == alert_fatal) {
- WOLFSSL_MSG("Error in custom sni callback. Fatal alert");
- SendAlert(ssl, alert_fatal, unrecognized_name);
- return FATAL_ERROR;
- }
- }
- return 0;
- }
- #endif /* OPENSSL_ALL || HAVE_STUNNEL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
- #endif /* NO_WOLFSSL_SERVER */
- #ifdef WOLFSSL_ASYNC_CRYPT
- int wolfSSL_AsyncPop(WOLFSSL* ssl, byte* state)
- {
- int ret = 0;
- WC_ASYNC_DEV* asyncDev;
- WOLF_EVENT* event;
- if (ssl == NULL) {
- return BAD_FUNC_ARG;
- }
- /* check for pending async */
- asyncDev = ssl->async.dev;
- if (asyncDev) {
- /* grab event pointer */
- event = &asyncDev->event;
- ret = wolfAsync_EventPop(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL);
- if (ret != WC_NOT_PENDING_E && ret != WC_PENDING_E) {
- /* advance key share state if doesn't need called again */
- if (state && (asyncDev->event.flags & WC_ASYNC_FLAG_CALL_AGAIN) == 0) {
- (*state)++;
- }
- /* clear event */
- XMEMSET(&asyncDev->event, 0, sizeof(WOLF_EVENT));
- /* clear async dev */
- ssl->async.dev = NULL;
- }
- }
- else {
- ret = WC_NOT_PENDING_E;
- }
- WOLFSSL_LEAVE("wolfSSL_AsyncPop", ret);
- return ret;
- }
- int wolfSSL_AsyncInit(WOLFSSL* ssl, WC_ASYNC_DEV* asyncDev, word32 flags)
- {
- int ret;
- WOLF_EVENT* event;
- if (ssl == NULL || asyncDev == NULL) {
- return BAD_FUNC_ARG;
- }
- /* grab event pointer */
- event = &asyncDev->event;
- /* init event */
- ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL, ssl, flags);
- WOLFSSL_LEAVE("wolfSSL_AsyncInit", ret);
- return ret;
- }
- int wolfSSL_AsyncPush(WOLFSSL* ssl, WC_ASYNC_DEV* asyncDev)
- {
- int ret;
- WOLF_EVENT* event;
- if (ssl == NULL || asyncDev == NULL) {
- return BAD_FUNC_ARG;
- }
- /* grab event pointer */
- event = &asyncDev->event;
- /* store reference to active async operation */
- ssl->async.dev = asyncDev;
- /* place event into queue */
- ret = wolfAsync_EventQueuePush(&ssl->ctx->event_queue, event);
- /* success means return WC_PENDING_E */
- if (ret == 0) {
- ret = WC_PENDING_E;
- }
- WOLFSSL_LEAVE("wolfSSL_AsyncPush", ret);
- return ret;
- }
- #endif /* WOLFSSL_ASYNC_CRYPT */
- /* return the max record size */
- int wolfSSL_GetMaxRecordSize(WOLFSSL* ssl, int maxFragment)
- {
- (void) ssl; /* Avoid compiler warnings */
- if (maxFragment > MAX_RECORD_SIZE) {
- maxFragment = MAX_RECORD_SIZE;
- }
- #ifdef HAVE_MAX_FRAGMENT
- if ((ssl->max_fragment != 0) && ((word16)maxFragment > ssl->max_fragment)) {
- maxFragment = ssl->max_fragment;
- }
- #endif /* HAVE_MAX_FRAGMENT */
- #ifdef WOLFSSL_DTLS
- if ((ssl->options.dtls) && (maxFragment > MAX_UDP_SIZE)) {
- maxFragment = MAX_UDP_SIZE;
- }
- #endif
- return maxFragment;
- }
- #undef ERROR_OUT
- #endif /* WOLFCRYPT_ONLY */
|