Proto_IKE.c 158 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904
  1. // SoftEther VPN Source Code - Developer Edition Master Branch
  2. // Cedar Communication Module
  3. // Proto_IKE.c
  4. // IKE (ISAKMP) and ESP protocol stack
  5. #include "Proto_IKE.h"
  6. #include "Cedar.h"
  7. #include "Connection.h"
  8. #include "Logging.h"
  9. #include "Proto_EtherIP.h"
  10. #include "Proto_IPsec.h"
  11. #include "Proto_L2TP.h"
  12. #include "Server.h"
  13. #include "Mayaqua/Memory.h"
  14. #include "Mayaqua/Object.h"
  15. #include "Mayaqua/Str.h"
  16. #include "Mayaqua/Table.h"
  17. #include "Mayaqua/TcpIp.h"
  18. #include "Mayaqua/Tick64.h"
  19. //#define RAW_DEBUG
  20. // Processing of IKE received packet
  21. void ProcIKEPacketRecv(IKE_SERVER *ike, UDPPACKET *p)
  22. {
  23. // Validate arguments
  24. if (ike == NULL || p == NULL)
  25. {
  26. return;
  27. }
  28. if (p->Type == IKE_UDP_TYPE_ISAKMP)
  29. {
  30. // ISAKMP (IKE) packet
  31. IKE_PACKET *header;
  32. header = ParseIKEPacketHeader(p);
  33. if (header == NULL)
  34. {
  35. return;
  36. }
  37. //Debug("InitiatorCookie: %I64u, ResponderCookie: %I64u\n", header->InitiatorCookie, header->ResponderCookie);
  38. switch (header->ExchangeType)
  39. {
  40. case IKE_EXCHANGE_TYPE_MAIN: // Main mode
  41. ProcIkeMainModePacketRecv(ike, p, header);
  42. break;
  43. case IKE_EXCHANGE_TYPE_AGGRESSIVE: // Aggressive mode
  44. if (ike->Cedar->Server->DisableIPsecAggressiveMode == false)
  45. {
  46. ProcIkeAggressiveModePacketRecv(ike, p, header);
  47. }
  48. break;
  49. case IKE_EXCHANGE_TYPE_QUICK: // Quick mode
  50. ProcIkeQuickModePacketRecv(ike, p, header);
  51. break;
  52. case IKE_EXCHANGE_TYPE_INFORMATION: // Information exchange
  53. ProcIkeInformationalExchangePacketRecv(ike, p, header);
  54. break;
  55. }
  56. IkeFree(header);
  57. }
  58. else if (p->Type == IKE_UDP_TYPE_ESP)
  59. {
  60. // ESP packet
  61. ProcIPsecEspPacketRecv(ike, p);
  62. }
  63. }
  64. // Send a packet via IPsec
  65. void IPsecSendPacketByIPsecSa(IKE_SERVER *ike, IPSECSA *sa, UCHAR *data, UINT data_size, UCHAR protocol_id)
  66. {
  67. bool is_tunnel_mode;
  68. IKE_CLIENT *c;
  69. // Validate arguments
  70. if (ike == NULL || sa == NULL || data == NULL || data_size == 0)
  71. {
  72. return;
  73. }
  74. is_tunnel_mode = IsIPsecSaTunnelMode(sa);
  75. c = sa->IkeClient;
  76. if (c == NULL)
  77. {
  78. return;
  79. }
  80. if (is_tunnel_mode)
  81. {
  82. // Add an IPv4 / IPv6 header in the case of tunnel mode
  83. if (IsZeroIP(&c->TunnelModeClientIP) == false || IsZeroIP(&c->TunnelModeServerIP) == false)
  84. {
  85. BUF *b;
  86. UCHAR esp_proto_id;
  87. b = NewBuf();
  88. if (IsIP4(&c->TunnelModeClientIP))
  89. {
  90. // IPv4 header
  91. IPV4_HEADER h;
  92. h.VersionAndHeaderLength = 0;
  93. h.TypeOfService = 0;
  94. IPV4_SET_VERSION(&h, 4);
  95. IPV4_SET_HEADER_LEN(&h, sizeof(IPV4_HEADER) / 4);
  96. h.TotalLength = Endian16((USHORT)(data_size + sizeof(IPV4_HEADER)));
  97. h.Identification = Endian16(c->TunnelSendIpId++);
  98. h.FlagsAndFragmentOffset[0] = h.FlagsAndFragmentOffset[1] = 0;
  99. h.TimeToLive = DEFAULT_IP_TTL;
  100. h.Protocol = protocol_id;
  101. h.SrcIP = IPToUINT(&c->TunnelModeServerIP);
  102. h.DstIP = IPToUINT(&c->TunnelModeClientIP);
  103. h.Checksum = 0;
  104. h.Checksum = IpChecksum(&h, sizeof(IPV4_HEADER));
  105. WriteBuf(b, &h, sizeof(IPV4_HEADER));
  106. esp_proto_id = IKE_PROTOCOL_ID_IPV4;
  107. }
  108. else
  109. {
  110. // IPv6 header
  111. IPV6_HEADER h;
  112. Zero(&h, sizeof(h));
  113. h.VersionAndTrafficClass1 = 0;
  114. IPV6_SET_VERSION(&h, 6);
  115. h.TrafficClass2AndFlowLabel1 = 0;
  116. h.FlowLabel2 = h.FlowLabel3 = 0;
  117. h.PayloadLength = Endian16(data_size);
  118. h.NextHeader = protocol_id;
  119. h.HopLimit = 64;
  120. Copy(h.SrcAddress.Value, c->TunnelModeServerIP.ipv6_addr, 16);
  121. Copy(h.DestAddress.Value, c->TunnelModeClientIP.ipv6_addr, 16);
  122. WriteBuf(b, &h, sizeof(IPV6_HEADER));
  123. esp_proto_id = IKE_PROTOCOL_ID_IPV6;
  124. }
  125. WriteBuf(b, data, data_size);
  126. IPsecSendPacketByIPsecSaInner(ike, sa, b->Buf, b->Size, esp_proto_id);
  127. FreeBuf(b);
  128. }
  129. }
  130. else
  131. {
  132. // Send as it is in the case of transport mode
  133. IPsecSendPacketByIPsecSaInner(ike, sa, data, data_size, protocol_id);
  134. }
  135. }
  136. void IPsecSendPacketByIPsecSaInner(IKE_SERVER *ike, IPSECSA *sa, UCHAR *data, UINT data_size, UCHAR protocol_id)
  137. {
  138. UINT esp_size;
  139. UINT encrypted_payload_size;
  140. UCHAR *esp;
  141. UINT i;
  142. UINT size_of_padding;
  143. IKE_CRYPTO_PARAM cp;
  144. BUF *enc;
  145. IKE_CLIENT *c;
  146. // Validate arguments
  147. if (ike == NULL || sa == NULL || data == NULL || data_size == 0)
  148. {
  149. return;
  150. }
  151. c = sa->IkeClient;
  152. if (c == NULL)
  153. {
  154. return;
  155. }
  156. // Calculate the payload size after encryption
  157. encrypted_payload_size = data_size + 2;
  158. if ((encrypted_payload_size % sa->TransformSetting.Crypto->BlockSize) != 0)
  159. {
  160. encrypted_payload_size = ((encrypted_payload_size / sa->TransformSetting.Crypto->BlockSize) + 1) * sa->TransformSetting.Crypto->BlockSize;
  161. }
  162. size_of_padding = encrypted_payload_size - data_size - 2;
  163. // Calculate the size of the ESP packet
  164. esp_size = sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + encrypted_payload_size + IKE_ESP_HASH_SIZE;
  165. // Build the ESP packet
  166. esp = Malloc(esp_size + IKE_MAX_HASH_SIZE);
  167. // SPI
  168. WRITE_UINT(esp, sa->Spi);
  169. // Sequence number
  170. sa->CurrentSeqNo++;
  171. WRITE_UINT(esp + sizeof(UINT), sa->CurrentSeqNo);
  172. // IV
  173. Copy(esp + sizeof(UINT) * 2, sa->EspIv, sa->TransformSetting.Crypto->BlockSize);
  174. // Payload data
  175. Copy(esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize, data, data_size);
  176. // Padding
  177. for (i = 0;i < size_of_padding;i++)
  178. {
  179. esp[sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + data_size + i] = (UCHAR)(i + 1);
  180. }
  181. // Padding length
  182. esp[sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + data_size + size_of_padding] = (UCHAR)size_of_padding;
  183. // Next header number
  184. esp[sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + data_size + size_of_padding + 1] = protocol_id;
  185. // Encryption
  186. Copy(cp.Iv, sa->EspIv, sa->TransformSetting.Crypto->BlockSize);
  187. cp.Key = sa->CryptoKey;
  188. enc = IkeEncrypt(esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize, encrypted_payload_size, &cp);
  189. if (enc != NULL)
  190. {
  191. bool start_qm = false;
  192. UINT server_port = c->ServerPort;
  193. UINT client_port = c->ClientPort;
  194. // Overwrite the encrypted result
  195. Copy(esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize, enc->Buf, encrypted_payload_size);
  196. FreeBuf(enc);
  197. // Calculate the HMAC
  198. IkeHMac(sa->TransformSetting.Hash,
  199. esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + encrypted_payload_size,
  200. sa->HashKey,
  201. sa->TransformSetting.Hash->HashSize,
  202. esp,
  203. sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + encrypted_payload_size);
  204. //*(UCHAR *)(esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + encrypted_payload_size) = 0xff;
  205. if (sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TRANSPORT ||
  206. sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TUNNEL)
  207. {
  208. server_port = client_port = IPSEC_PORT_IPSEC_ESP_RAW;
  209. }
  210. // Add the completed packet to the transmission list
  211. IkeSendUdpPacket(ike, IKE_UDP_TYPE_ESP, &c->ServerIP, server_port, &c->ClientIP, client_port,
  212. esp, esp_size);
  213. // Feedback the IV
  214. Copy(sa->EspIv, cp.NextIv, sa->TransformSetting.Crypto->BlockSize);
  215. sa->TotalSize += esp_size;
  216. if (sa->CurrentSeqNo >= 0xf0000000)
  217. {
  218. start_qm = true;
  219. }
  220. if (sa->TransformSetting.LifeKilobytes != 0)
  221. {
  222. UINT64 hard_size = (UINT64)sa->TransformSetting.LifeKilobytes * (UINT64)1000;
  223. UINT64 soft_size = hard_size * (UINT64)2 / (UINT64)3;
  224. if (sa->TotalSize >= soft_size)
  225. {
  226. start_qm = true;
  227. }
  228. }
  229. if (start_qm)
  230. {
  231. if (sa->StartQM_FlagSet == false)
  232. {
  233. sa->StartQM_FlagSet = true;
  234. c->StartQuickModeAsSoon = true;
  235. }
  236. }
  237. }
  238. else
  239. {
  240. // Encryption failure
  241. Free(esp);
  242. }
  243. }
  244. void IPsecSendPacketByIkeClient(IKE_SERVER *ike, IKE_CLIENT *c, UCHAR *data, UINT data_size, UCHAR protocol_id)
  245. {
  246. // Validate arguments
  247. if (ike == NULL || c == NULL || data == NULL || data_size == 0)
  248. {
  249. return;
  250. }
  251. if (c->CurrentIpSecSaSend == NULL)
  252. {
  253. return;
  254. }
  255. IPsecSendPacketByIPsecSa(ike, c->CurrentIpSecSaSend, data, data_size, protocol_id);
  256. }
  257. // Send an UDP packet via IPsec
  258. void IPsecSendUdpPacket(IKE_SERVER *ike, IKE_CLIENT *c, UINT src_port, UINT dst_port, UCHAR *data, UINT data_size)
  259. {
  260. UCHAR *udp;
  261. UINT udp_size;
  262. UDP_HEADER *u;
  263. UCHAR tmp1600[1600];
  264. bool no_free = false;
  265. // Validate arguments
  266. if (ike == NULL || c == NULL || data == NULL || data_size == 0)
  267. {
  268. return;
  269. }
  270. // Build an UDP packet
  271. udp_size = sizeof(UDP_HEADER) + data_size;
  272. if (udp_size > sizeof(tmp1600))
  273. {
  274. udp = Malloc(udp_size);
  275. }
  276. else
  277. {
  278. udp = tmp1600;
  279. no_free = true;
  280. }
  281. // UDP header
  282. u = (UDP_HEADER *)udp;
  283. u->SrcPort = Endian16(src_port);
  284. u->DstPort = Endian16(dst_port);
  285. u->PacketLength = Endian16(udp_size);
  286. u->Checksum = 0;
  287. //Debug("IPsec UDP Send: %u -> %u %u\n", src_port, dst_port, data_size);
  288. #ifdef RAW_DEBUG
  289. IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, data, data_size);
  290. #endif // RAW_DEBUG
  291. // Payload
  292. Copy(udp + sizeof(UDP_HEADER), data, data_size);
  293. if (IsIP6(&c->ClientIP))
  294. {
  295. if (IsIPsecSaTunnelMode(c->CurrentIpSecSaSend) == false)
  296. {
  297. u->Checksum = CalcChecksumForIPv6((IPV6_ADDR *)c->TransportModeServerIP.ipv6_addr,
  298. (IPV6_ADDR *)c->TransportModeClientIP.ipv6_addr,
  299. IP_PROTO_UDP,
  300. u,
  301. udp_size, 0);
  302. }
  303. else
  304. {
  305. u->Checksum = CalcChecksumForIPv6((IPV6_ADDR *)c->TunnelModeServerIP.ipv6_addr,
  306. (IPV6_ADDR *)c->TunnelModeClientIP.ipv6_addr,
  307. IP_PROTO_UDP,
  308. u,
  309. udp_size, 0);
  310. }
  311. }
  312. IPsecSendPacketByIkeClient(ike, c, udp, udp_size, IP_PROTO_UDP);
  313. if (no_free == false)
  314. {
  315. Free(udp);
  316. }
  317. }
  318. // Get whether the specified IPsec SA is in tunnel mode
  319. bool IsIPsecSaTunnelMode(IPSECSA *sa)
  320. {
  321. // Validate arguments
  322. if (sa == NULL)
  323. {
  324. return false;
  325. }
  326. if (sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TUNNEL ||
  327. sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_NAT_TUNNEL_1 ||
  328. sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_NAT_TUNNEL_2)
  329. {
  330. return true;
  331. }
  332. return false;
  333. }
  334. // Reception process of ESP packet
  335. void ProcIPsecEspPacketRecv(IKE_SERVER *ike, UDPPACKET *p)
  336. {
  337. UCHAR *src;
  338. UINT src_size;
  339. UINT spi;
  340. UINT seq;
  341. IPSECSA *ipsec_sa;
  342. IKE_CLIENT *c;
  343. UINT block_size;
  344. UINT hash_size;
  345. bool update_status = false;
  346. UCHAR *iv;
  347. UCHAR *hash;
  348. UCHAR *encrypted_payload_data;
  349. UINT size_of_payload_data;
  350. IKE_CRYPTO_PARAM cp;
  351. BUF *dec;
  352. UCHAR calced_hash[IKE_MAX_HASH_SIZE];
  353. bool is_tunnel_mode = false;
  354. // Validate arguments
  355. if (ike == NULL || p == NULL)
  356. {
  357. return;
  358. }
  359. src = (UCHAR *)p->Data;
  360. src_size = p->Size;
  361. if (p->DestPort == IPSEC_PORT_IPSEC_ESP_RAW)
  362. {
  363. if (IsIP4(&p->DstIP))
  364. {
  365. // Skip the IP header when received in Raw mode (only in the case of IPv4)
  366. UINT ip_header_size = GetIpHeaderSize(src, src_size);
  367. src += ip_header_size;
  368. src_size -= ip_header_size;
  369. }
  370. }
  371. // Get the SPI
  372. if (src_size < sizeof(UINT))
  373. {
  374. return;
  375. }
  376. spi = READ_UINT(src + 0);
  377. if (spi == 0)
  378. {
  379. return;
  380. }
  381. // Get the sequence number
  382. if (src_size < (sizeof(UINT) * 2))
  383. {
  384. return;
  385. }
  386. seq = READ_UINT(src + sizeof(UINT));
  387. // Search and retrieve the IPsec SA from SPI
  388. ipsec_sa = SearchClientToServerIPsecSaBySpi(ike, spi);
  389. if (ipsec_sa == NULL)
  390. {
  391. // Invalid SPI
  392. UINT64 init_cookie = Rand64();
  393. UINT64 resp_cookie = 0;
  394. IKE_CLIENT *c = NULL;
  395. IKE_CLIENT t;
  396. Copy(&t.ClientIP, &p->SrcIP, sizeof(IP));
  397. t.ClientPort = p->SrcPort;
  398. Copy(&t.ServerIP, &p->DstIP, sizeof(IP));
  399. t.ServerPort = p->DestPort;
  400. t.CurrentIkeSa = NULL;
  401. if (p->DestPort == IPSEC_PORT_IPSEC_ESP_RAW)
  402. {
  403. t.ClientPort = t.ServerPort = IPSEC_PORT_IPSEC_ISAKMP;
  404. }
  405. c = Search(ike->ClientList, &t);
  406. if (c != NULL && c->CurrentIkeSa != NULL)
  407. {
  408. init_cookie = c->CurrentIkeSa->InitiatorCookie;
  409. resp_cookie = c->CurrentIkeSa->ResponderCookie;
  410. }
  411. SendInformationalExchangePacketEx(ike, (c == NULL ? &t : c), IkeNewNoticeErrorInvalidSpiPayload(spi), false,
  412. init_cookie, resp_cookie);
  413. SendDeleteIPsecSaPacket(ike, (c == NULL ? &t : c), spi);
  414. return;
  415. }
  416. is_tunnel_mode = IsIPsecSaTunnelMode(ipsec_sa);
  417. c = ipsec_sa->IkeClient;
  418. if (c == NULL)
  419. {
  420. return;
  421. }
  422. block_size = ipsec_sa->TransformSetting.Crypto->BlockSize;
  423. hash_size = IKE_ESP_HASH_SIZE;
  424. // Get the IV
  425. if (src_size < (sizeof(UINT) * 2 + block_size + hash_size + block_size))
  426. {
  427. return;
  428. }
  429. iv = src + sizeof(UINT) * 2;
  430. // Get the hash
  431. hash = src + src_size - hash_size;
  432. // Inspect the HMAC
  433. IkeHMac(ipsec_sa->TransformSetting.Hash, calced_hash, ipsec_sa->HashKey,
  434. ipsec_sa->TransformSetting.Hash->HashSize, src, src_size - hash_size);
  435. if (Cmp(calced_hash, hash, hash_size) != 0)
  436. {
  437. //Debug("IPsec SA 0x%X: Invalid HMAC Value.\n", ipsec_sa->Spi);
  438. return;
  439. }
  440. // Get the payload data
  441. encrypted_payload_data = src + sizeof(UINT) * 2 + block_size;
  442. size_of_payload_data = src_size - hash_size - block_size - sizeof(UINT) * 2;
  443. if (size_of_payload_data == 0 || (size_of_payload_data % block_size) != 0)
  444. {
  445. // Payload data don't exist or is not a multiple of block size
  446. return;
  447. }
  448. // Decrypt the payload data
  449. cp.Key = ipsec_sa->CryptoKey;
  450. Copy(&cp.Iv, iv, block_size);
  451. dec = IkeDecrypt(encrypted_payload_data, size_of_payload_data, &cp);
  452. if (dec != NULL)
  453. {
  454. UCHAR *dec_data = dec->Buf;
  455. UINT dec_size = dec->Size;
  456. UCHAR size_of_padding = dec_data[dec_size - 2];
  457. UCHAR next_header = dec_data[dec_size - 1];
  458. if ((dec_size - 2) >= size_of_padding)
  459. {
  460. UINT orig_size = dec_size - 2 - size_of_padding;
  461. ipsec_sa->TotalSize += dec_size;
  462. if (is_tunnel_mode)
  463. {
  464. // Tunnel Mode
  465. if (next_header == IKE_PROTOCOL_ID_IPV4 || next_header == IKE_PROTOCOL_ID_IPV6)
  466. {
  467. // Check the contents by parsing the IPv4 / IPv6 header in the case of tunnel mode
  468. BUF *b = NewBuf();
  469. static UCHAR src_mac_dummy[6] = {0, 0, 0, 0, 0, 0, };
  470. static UCHAR dst_mac_dummy[6] = {0, 0, 0, 0, 0, 0, };
  471. USHORT tpid = Endian16(next_header == IKE_PROTOCOL_ID_IPV4 ? MAC_PROTO_IPV4 : MAC_PROTO_IPV6);
  472. PKT *pkt;
  473. WriteBuf(b, src_mac_dummy, sizeof(src_mac_dummy));
  474. WriteBuf(b, dst_mac_dummy, sizeof(dst_mac_dummy));
  475. WriteBuf(b, &tpid, sizeof(tpid));
  476. WriteBuf(b, dec_data, dec_size);
  477. // Parse
  478. pkt = ParsePacket(b->Buf, b->Size);
  479. #ifdef RAW_DEBUG
  480. IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, b->Buf, b->Size);
  481. #endif // RAW_DEBUG
  482. if (pkt == NULL)
  483. {
  484. // Parsing failure
  485. dec_data = NULL;
  486. dec_size = 0;
  487. }
  488. else
  489. {
  490. // Parsing success
  491. switch (pkt->TypeL3)
  492. {
  493. case L3_IPV4:
  494. // Save the internal IP address information
  495. UINTToIP(&c->TunnelModeServerIP, pkt->L3.IPv4Header->DstIP);
  496. UINTToIP(&c->TunnelModeClientIP, pkt->L3.IPv4Header->SrcIP);
  497. if (IPV4_GET_OFFSET(pkt->L3.IPv4Header) == 0)
  498. {
  499. if ((IPV4_GET_FLAGS(pkt->L3.IPv4Header) & 0x01) == 0)
  500. {
  501. if (pkt->L3.IPv4Header->Protocol == IPSEC_IP_PROTO_ETHERIP)
  502. {
  503. // EtherIP
  504. if (ike->IPsec->Services.EtherIP_IPsec)
  505. {
  506. // An EtherIP packet has been received
  507. ProcIPsecEtherIPPacketRecv(ike, c, pkt->IPv4PayloadData, pkt->IPv4PayloadSize, true);
  508. }
  509. }
  510. else if (pkt->L3.IPv4Header->Protocol == IPSEC_IP_PROTO_L2TPV3)
  511. {
  512. // L2TPv3
  513. if (ike->IPsec->Services.EtherIP_IPsec)
  514. {
  515. // A L2TPv3 packet has been received
  516. ProcL2TPv3PacketRecv(ike, c, pkt->IPv4PayloadData, pkt->IPv4PayloadSize, true);
  517. }
  518. }
  519. }
  520. }
  521. break;
  522. case L3_IPV6:
  523. // Save the internal IP address information
  524. SetIP6(&c->TunnelModeServerIP, pkt->IPv6HeaderPacketInfo.IPv6Header->DestAddress.Value);
  525. SetIP6(&c->TunnelModeClientIP, pkt->IPv6HeaderPacketInfo.IPv6Header->SrcAddress.Value);
  526. if (pkt->IPv6HeaderPacketInfo.IsFragment == false)
  527. {
  528. if (pkt->IPv6HeaderPacketInfo.FragmentHeader == NULL || (IPV6_GET_FLAGS(pkt->IPv6HeaderPacketInfo.FragmentHeader) & IPV6_FRAGMENT_HEADER_FLAG_MORE_FRAGMENTS) == 0)
  529. {
  530. if (pkt->IPv6HeaderPacketInfo.Protocol == IPSEC_IP_PROTO_ETHERIP)
  531. {
  532. // EtherIP
  533. if (ike->IPsec->Services.EtherIP_IPsec)
  534. {
  535. // An EtherIP packet has been received
  536. ProcIPsecEtherIPPacketRecv(ike, c, pkt->IPv6HeaderPacketInfo.Payload, pkt->IPv6HeaderPacketInfo.PayloadSize, true);
  537. }
  538. }
  539. else if (pkt->IPv6HeaderPacketInfo.Protocol == IPSEC_IP_PROTO_L2TPV3)
  540. {
  541. // L2TPv3
  542. if (ike->IPsec->Services.EtherIP_IPsec)
  543. {
  544. // A L2TPv3 packet has been received
  545. ProcL2TPv3PacketRecv(ike, c, pkt->IPv6HeaderPacketInfo.Payload, pkt->IPv6HeaderPacketInfo.PayloadSize, true);
  546. }
  547. }
  548. }
  549. }
  550. break;
  551. }
  552. FreePacket(pkt);
  553. }
  554. FreeBuf(b);
  555. }
  556. }
  557. else
  558. {
  559. // Transport mode
  560. if (next_header == IP_PROTO_UDP)
  561. {
  562. if (ike->IPsec->Services.L2TP_IPsec || ike->IPsec->Services.EtherIP_IPsec)
  563. {
  564. // An UDP packet has been received
  565. ProcIPsecUdpPacketRecv(ike, c, dec_data, dec_size);
  566. }
  567. }
  568. else if (next_header == IPSEC_IP_PROTO_ETHERIP)
  569. {
  570. if (ike->IPsec->Services.EtherIP_IPsec)
  571. {
  572. // An EtherIP packet has been received
  573. ProcIPsecEtherIPPacketRecv(ike, c, dec_data, dec_size, false);
  574. }
  575. }
  576. else if (next_header == IPSEC_IP_PROTO_L2TPV3)
  577. {
  578. if (ike->IPsec->Services.EtherIP_IPsec)
  579. {
  580. // A L2TPv3 packet has been received
  581. ProcL2TPv3PacketRecv(ike, c, dec_data, dec_size, false);
  582. }
  583. }
  584. }
  585. update_status = true;
  586. }
  587. FreeBuf(dec);
  588. }
  589. if (update_status)
  590. {
  591. bool start_qm = false;
  592. // Update the status of the client
  593. c->CurrentIpSecSaRecv = ipsec_sa;
  594. if (ipsec_sa->PairIPsecSa != NULL)
  595. {
  596. c->CurrentIpSecSaSend = ipsec_sa->PairIPsecSa;
  597. if (p->DestPort == IPSEC_PORT_IPSEC_ESP_UDP)
  598. {
  599. IPSECSA *send_sa = c->CurrentIpSecSaSend;
  600. if (send_sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TUNNEL)
  601. {
  602. send_sa->TransformSetting.CapsuleMode = IKE_P2_CAPSULE_NAT_TUNNEL_1;
  603. }
  604. else if (send_sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TRANSPORT)
  605. {
  606. send_sa->TransformSetting.CapsuleMode = IKE_P2_CAPSULE_NAT_TRANSPORT_1;
  607. }
  608. }
  609. }
  610. c->LastCommTick = ike->Now;
  611. ipsec_sa->LastCommTick = ike->Now;
  612. if (ipsec_sa->PairIPsecSa != NULL)
  613. {
  614. ipsec_sa->PairIPsecSa->LastCommTick = ike->Now;
  615. }
  616. SetIkeClientEndpoint(ike, c, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort);
  617. if (seq >= 0xf0000000)
  618. {
  619. // Execute a QuickMode forcibly since sequence number is going to exhaust
  620. start_qm = true;
  621. }
  622. if (ipsec_sa->TransformSetting.LifeKilobytes != 0)
  623. {
  624. UINT64 hard_size = (UINT64)ipsec_sa->TransformSetting.LifeKilobytes * (UINT64)1000;
  625. UINT64 soft_size = hard_size * (UINT64)2 / (UINT64)3;
  626. if (ipsec_sa->TotalSize >= soft_size)
  627. {
  628. // Execute a QuickMode forcibly because the capacity limit is going to exceed
  629. start_qm = true;
  630. }
  631. }
  632. if (start_qm)
  633. {
  634. if (ipsec_sa->StartQM_FlagSet == false)
  635. {
  636. c->StartQuickModeAsSoon = true;
  637. ipsec_sa->StartQM_FlagSet = true;
  638. }
  639. }
  640. }
  641. }
  642. // Received the L2TPv3 packet via the IPsec tunnel
  643. void ProcL2TPv3PacketRecv(IKE_SERVER *ike, IKE_CLIENT *c, UCHAR *data, UINT data_size, bool is_tunnel_mode)
  644. {
  645. UDPPACKET p;
  646. // Validate arguments
  647. if (ike == NULL || c == NULL || data == NULL || data_size == 0)
  648. {
  649. return;
  650. }
  651. c->IsL2TPOnIPsecTunnelMode = is_tunnel_mode;
  652. IPsecIkeClientManageL2TPServer(ike, c);
  653. // Pass the received packet to the L2TP server
  654. p.Type = 0;
  655. p.Data = data;
  656. p.DestPort = IPSEC_PORT_L2TPV3_VIRTUAL;
  657. p.Size = data_size;
  658. if (is_tunnel_mode)
  659. {
  660. Copy(&p.DstIP, &c->TunnelModeServerIP, sizeof(IP));
  661. Copy(&p.SrcIP, &c->TunnelModeClientIP, sizeof(IP));
  662. }
  663. else
  664. {
  665. Copy(&p.DstIP, &c->L2TPServerIP, sizeof(IP));
  666. Copy(&p.SrcIP, &c->L2TPClientIP, sizeof(IP));
  667. }
  668. p.SrcPort = IPSEC_PORT_L2TPV3_VIRTUAL;
  669. #ifdef RAW_DEBUG
  670. IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, ((UCHAR *)p.Data) + 4, p.Size - 4);
  671. #endif // RAW_DEBUG
  672. ProcL2TPPacketRecv(c->L2TP, &p);
  673. }
  674. // An EtherIP packet has been received via an IPsec tunnel
  675. void ProcIPsecEtherIPPacketRecv(IKE_SERVER *ike, IKE_CLIENT *c, UCHAR *data, UINT data_size, bool is_tunnel_mode)
  676. {
  677. BLOCK *b;
  678. // Validate arguments
  679. if (ike == NULL || c == NULL || data == NULL || data_size == 0)
  680. {
  681. return;
  682. }
  683. c->IsEtherIPOnIPsecTunnelMode = is_tunnel_mode;
  684. IPsecIkeClientManageEtherIPServer(ike, c);
  685. b = NewBlock(data, data_size, 0);
  686. EtherIPProcRecvPackets(c->EtherIP, b);
  687. Free(b);
  688. }
  689. // An UDP packet has been received via the IPsec tunnel
  690. void ProcIPsecUdpPacketRecv(IKE_SERVER *ike, IKE_CLIENT *c, UCHAR *data, UINT data_size)
  691. {
  692. UDP_HEADER *u;
  693. UINT payload_size;
  694. UINT src_port, dst_port;
  695. UINT packet_length;
  696. // Validate arguments
  697. if (ike == NULL || c == NULL || data == NULL || data_size == 0)
  698. {
  699. return;
  700. }
  701. if (data_size <= sizeof(UDP_HEADER))
  702. {
  703. // There is no UDP header or the data is 0 bytes
  704. return;
  705. }
  706. // UDP header
  707. u = (UDP_HEADER *)data;
  708. packet_length = Endian16(u->PacketLength);
  709. if (packet_length <= sizeof(UDP_HEADER))
  710. {
  711. return;
  712. }
  713. payload_size = packet_length - sizeof(UDP_HEADER);
  714. if (payload_size == 0)
  715. {
  716. // No data
  717. return;
  718. }
  719. if (data_size < (sizeof(UDP_HEADER) + payload_size))
  720. {
  721. // Data is not followed
  722. return;
  723. }
  724. src_port = Endian16(u->SrcPort);
  725. dst_port = Endian16(u->DstPort);
  726. if (dst_port == IPSEC_PORT_L2TP)
  727. {
  728. UDPPACKET p;
  729. // A L2TP packet has been received
  730. IPsecIkeClientManageL2TPServer(ike, c);
  731. // Update Port number
  732. c->L2TPClientPort = src_port;
  733. // Pass the received packet to the L2TP server
  734. p.Type = 0;
  735. p.Data = data + sizeof(UDP_HEADER);
  736. p.DestPort = IPSEC_PORT_L2TP;
  737. Copy(&p.DstIP, &c->L2TPServerIP, sizeof(IP));
  738. p.Size = payload_size;
  739. Copy(&p.SrcIP, &c->L2TPClientIP, sizeof(IP));
  740. p.SrcPort = IPSEC_PORT_L2TP;
  741. ProcL2TPPacketRecv(c->L2TP, &p);
  742. //Debug("IPsec UDP Recv: %u <= %u %u\n", dst_port, src_port, p.Size);
  743. #ifdef RAW_DEBUG
  744. IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, p.Data, p.Size);
  745. #endif // RAW_DEBUG
  746. }
  747. }
  748. // Send a raw packet for debugging
  749. void IPsecIkeSendUdpForDebug(UINT dst_port, UINT dst_ip, void *data, UINT size)
  750. {
  751. SOCK *s = NewUDP(0);
  752. IP d;
  753. SetIP(&d, dst_ip, dst_ip, dst_ip, dst_ip);
  754. SendTo(s, &d, dst_port, data, size);
  755. ReleaseSock(s);
  756. }
  757. // L2TP packet transmission (via IPsec SA tunnel)
  758. void IPsecIkeClientSendL2TPPackets(IKE_SERVER *ike, IKE_CLIENT *c, L2TP_SERVER *l2tp)
  759. {
  760. UINT i;
  761. // Validate arguments
  762. if (ike == NULL || c == NULL || l2tp == NULL)
  763. {
  764. return;
  765. }
  766. for (i = 0;i < LIST_NUM(l2tp->SendPacketList);i++)
  767. {
  768. UDPPACKET *u = LIST_DATA(l2tp->SendPacketList, i);
  769. if (u->SrcPort != IPSEC_PORT_L2TPV3_VIRTUAL)
  770. {
  771. // L2TP UDP packet transmission
  772. IPsecSendUdpPacket(ike, c, IPSEC_PORT_L2TP, c->L2TPClientPort,
  773. u->Data, u->Size);
  774. }
  775. else
  776. {
  777. // L2TPv3 special IP packet transmission
  778. IPsecSendPacketByIkeClient(ike, c, u->Data, u->Size, IPSEC_IP_PROTO_L2TPV3);
  779. #ifdef RAW_DEBUG
  780. IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, ((UCHAR *)u->Data) + 4, u->Size - 4);
  781. #endif // RAW_DEBUG
  782. }
  783. FreeUdpPacket(u);
  784. }
  785. DeleteAll(l2tp->SendPacketList);
  786. }
  787. // Manage the L2TP server that is associated with the IKE_CLIENT
  788. void IPsecIkeClientManageL2TPServer(IKE_SERVER *ike, IKE_CLIENT *c)
  789. {
  790. L2TP_SERVER *l2tp;
  791. // Validate arguments
  792. if (ike == NULL || c == NULL)
  793. {
  794. return;
  795. }
  796. if (c->L2TP == NULL)
  797. {
  798. UINT crypt_block_size = IKE_MAX_BLOCK_SIZE;
  799. if (c->CurrentIpSecSaRecv != NULL)
  800. {
  801. crypt_block_size = c->CurrentIpSecSaRecv->TransformSetting.Crypto->BlockSize;
  802. }
  803. c->L2TP = NewL2TPServerEx(ike->Cedar, ike, IsIP6(&c->ClientIP), crypt_block_size);
  804. c->L2TP->IkeClient = c;
  805. Copy(&c->L2TPServerIP, &c->ServerIP, sizeof(IP));
  806. Copy(&c->L2TPClientIP, &c->ClientIP, sizeof(IP));
  807. if (c->CurrentIpSecSaRecv != NULL)
  808. {
  809. Format(c->L2TP->CryptName, sizeof(c->L2TP->CryptName),
  810. "IPsec - %s (%u bits)",
  811. c->CurrentIpSecSaRecv->TransformSetting.Crypto->Name,
  812. c->CurrentIpSecSaRecv->TransformSetting.CryptoKeySize * 8);
  813. }
  814. Debug("IKE_CLIENT 0x%X: L2TP Server Started.\n", c);
  815. IPsecLog(ike, c, NULL, NULL, "LI_L2TP_SERVER_STARTED");
  816. }
  817. l2tp = c->L2TP;
  818. if (l2tp->Interrupts == NULL)
  819. {
  820. l2tp->Interrupts = ike->Interrupts;
  821. }
  822. if (l2tp->SockEvent == NULL)
  823. {
  824. SetL2TPServerSockEvent(l2tp, ike->SockEvent);
  825. }
  826. l2tp->Now = ike->Now;
  827. }
  828. // Manage the EtherIP server that is associated with the IKE_CLIENT
  829. void IPsecIkeClientManageEtherIPServer(IKE_SERVER *ike, IKE_CLIENT *c)
  830. {
  831. ETHERIP_SERVER *s;
  832. // Validate arguments
  833. if (ike == NULL || c == NULL)
  834. {
  835. return;
  836. }
  837. if (c->EtherIP == NULL)
  838. {
  839. char crypt_name[MAX_SIZE];
  840. UINT crypt_block_size = IKE_MAX_BLOCK_SIZE;
  841. Zero(crypt_name, sizeof(crypt_name));
  842. if (c->CurrentIpSecSaRecv != NULL)
  843. {
  844. Format(crypt_name, sizeof(crypt_name),
  845. "IPsec - %s (%u bits)",
  846. c->CurrentIpSecSaRecv->TransformSetting.Crypto->Name,
  847. c->CurrentIpSecSaRecv->TransformSetting.CryptoKeySize * 8);
  848. crypt_block_size = c->CurrentIpSecSaRecv->TransformSetting.Crypto->BlockSize;
  849. }
  850. c->EtherIP = NewEtherIPServer(ike->Cedar, ike->IPsec, ike,
  851. &c->ClientIP, c->ClientPort,
  852. &c->ServerIP, c->ServerPort, crypt_name,
  853. c->IsEtherIPOnIPsecTunnelMode, crypt_block_size, c->ClientId,
  854. ++ike->CurrentEtherId);
  855. Debug("IKE_CLIENT 0x%X: EtherIP Server Started.\n", c);
  856. IPsecLog(ike, c, NULL, NULL, NULL, "LI_ETHERIP_SERVER_STARTED", ike->CurrentEtherId);
  857. }
  858. else
  859. {
  860. StrCpy(c->EtherIP->ClientId, sizeof(c->EtherIP->ClientId), c->ClientId);
  861. }
  862. s = c->EtherIP;
  863. if (s->Interrupts == NULL)
  864. {
  865. s->Interrupts = ike->Interrupts;
  866. }
  867. if (s->SockEvent == NULL)
  868. {
  869. SetEtherIPServerSockEvent(s, ike->SockEvent);
  870. }
  871. s->Now = ike->Now;
  872. }
  873. // EtherIP packet transmission (via IPsec SA tunnel)
  874. void IPsecIkeClientSendEtherIPPackets(IKE_SERVER *ike, IKE_CLIENT *c, ETHERIP_SERVER *s)
  875. {
  876. UINT i;
  877. // Validate arguments
  878. if (ike == NULL || c == NULL || s == NULL)
  879. {
  880. return;
  881. }
  882. for (i = 0;i < LIST_NUM(s->SendPacketList);i++)
  883. {
  884. BLOCK *b = LIST_DATA(s->SendPacketList, i);
  885. // Packet transmission
  886. IPsecSendPacketByIkeClient(ike, c, b->Buf, b->Size, IPSEC_IP_PROTO_ETHERIP);
  887. FreeBlock(b);
  888. }
  889. DeleteAll(s->SendPacketList);
  890. }
  891. // Handle the deletion payload
  892. void ProcDeletePayload(IKE_SERVER *ike, IKE_CLIENT *c, IKE_PACKET_DELETE_PAYLOAD *d)
  893. {
  894. // Validate arguments
  895. if (ike == NULL || c == NULL || d == NULL)
  896. {
  897. return;
  898. }
  899. if (d->ProtocolId == IKE_PROTOCOL_ID_IPSEC_ESP)
  900. {
  901. UINT i;
  902. // Remove the IPsec SA
  903. for (i = 0;i < LIST_NUM(d->SpiList);i++)
  904. {
  905. BUF *b = LIST_DATA(d->SpiList, i);
  906. if (b->Size == 4)
  907. {
  908. UINT spi = READ_UINT(b->Buf);
  909. MarkIPsecSaAsDeleted(ike, SearchIPsecSaBySpi(ike, c, spi));
  910. }
  911. }
  912. }
  913. else if (d->ProtocolId == IKE_PROTOCOL_ID_IKE)
  914. {
  915. UINT i;
  916. // Remove the IKE SA
  917. for (i = 0;i < LIST_NUM(d->SpiList);i++)
  918. {
  919. BUF *b = LIST_DATA(d->SpiList, i);
  920. if (b->Size == 16)
  921. {
  922. UINT64 v1 = READ_UINT64(((UCHAR *)b->Buf) + 0);
  923. UINT64 v2 = READ_UINT64(((UCHAR *)b->Buf) + 8);
  924. IKE_SA *sa = FindIkeSaByResponderCookie(ike, v2);
  925. if (sa != NULL && sa->IkeClient == c)
  926. {
  927. MarkIkeSaAsDeleted(ike, sa);
  928. }
  929. }
  930. }
  931. }
  932. }
  933. // Mark the IKE_CLIENT for deletion
  934. void MarkIkeClientAsDeleted(IKE_SERVER *ike, IKE_CLIENT *c)
  935. {
  936. char client_ip_str[MAX_SIZE];
  937. char server_ip_str[MAX_SIZE];
  938. // Validate arguments
  939. if (ike == NULL || c == NULL)
  940. {
  941. return;
  942. }
  943. if (c->Deleting)
  944. {
  945. return;
  946. }
  947. ike->StateHasChanged = true;
  948. c->Deleting = true;
  949. IPToStr(client_ip_str, sizeof(client_ip_str), &c->ClientIP);
  950. IPToStr(server_ip_str, sizeof(server_ip_str), &c->ServerIP);
  951. Debug("Deleting IKE_CLIENT: %p: %s:%u -> %s:%u\n", c, client_ip_str, c->ClientPort, server_ip_str, c->ServerPort);
  952. IPsecLog(ike, c, NULL, NULL, "LI_DELETE_IKE_CLIENT");
  953. }
  954. // Mark the IKE SA for deletion
  955. void MarkIkeSaAsDeleted(IKE_SERVER *ike, IKE_SA *sa)
  956. {
  957. // Validate arguments
  958. if (ike == NULL || sa == NULL)
  959. {
  960. return;
  961. }
  962. if (sa->Deleting)
  963. {
  964. return;
  965. }
  966. ike->StateHasChanged = true;
  967. sa->Deleting = true;
  968. Debug("IKE SA %I64u - %I64u has been marked as being deleted.\n", sa->InitiatorCookie, sa->ResponderCookie);
  969. SendDeleteIkeSaPacket(ike, sa->IkeClient, sa->InitiatorCookie, sa->ResponderCookie);
  970. IPsecLog(ike, NULL, sa, NULL, "LI_DELETE_IKE_SA");
  971. }
  972. // Mark the IPsec SA for deletion
  973. void MarkIPsecSaAsDeleted(IKE_SERVER *ike, IPSECSA *sa)
  974. {
  975. // Validate arguments
  976. if (ike == NULL || sa == NULL)
  977. {
  978. return;
  979. }
  980. if (sa->Deleting)
  981. {
  982. return;
  983. }
  984. ike->StateHasChanged = true;
  985. sa->Deleting = true;
  986. Debug("IPsec SA 0x%X has been marked as being deleted.\n", sa->Spi);
  987. SendDeleteIPsecSaPacket(ike, sa->IkeClient, sa->Spi);
  988. IPsecLog(ike, NULL, NULL, sa, "LI_DELETE_IPSEC_SA");
  989. }
  990. // IPsec SA Deletion packet transmission process
  991. void SendDeleteIPsecSaPacket(IKE_SERVER *ike, IKE_CLIENT *c, UINT spi)
  992. {
  993. IKE_PACKET_PAYLOAD *payload;
  994. BUF *buf;
  995. // Validate arguments
  996. if (ike == NULL || c == NULL || spi == 0)
  997. {
  998. return;
  999. }
  1000. buf = NewBuf();
  1001. WriteBufInt(buf, spi);
  1002. payload = IkeNewDeletePayload(IKE_PROTOCOL_ID_IPSEC_ESP, NewListSingle(buf));
  1003. SendInformationalExchangePacket(ike, c, payload);
  1004. }
  1005. // IKE SA deletion packet transmission process
  1006. void SendDeleteIkeSaPacket(IKE_SERVER *ike, IKE_CLIENT *c, UINT64 init_cookie, UINT64 resp_cookie)
  1007. {
  1008. IKE_PACKET_PAYLOAD *payload;
  1009. BUF *buf;
  1010. // Validate arguments
  1011. if (ike == NULL || c == NULL)
  1012. {
  1013. return;
  1014. }
  1015. buf = NewBuf();
  1016. WriteBufInt64(buf, init_cookie);
  1017. WriteBufInt64(buf, resp_cookie);
  1018. payload = IkeNewDeletePayload(IKE_PROTOCOL_ID_IKE, NewListSingle(buf));
  1019. SendInformationalExchangePacket(ike, c, payload);
  1020. }
  1021. // Information exchange packet transmission process
  1022. void SendInformationalExchangePacket(IKE_SERVER *ike, IKE_CLIENT *c, IKE_PACKET_PAYLOAD *payload)
  1023. {
  1024. SendInformationalExchangePacketEx(ike, c, payload, false, 0, 0);
  1025. }
  1026. void SendInformationalExchangePacketEx(IKE_SERVER *ike, IKE_CLIENT *c, IKE_PACKET_PAYLOAD *payload, bool force_plain, UINT64 init_cookie, UINT64 resp_cookie)
  1027. {
  1028. IKE_SA *sa;
  1029. IKE_PACKET *ps;
  1030. LIST *payload_list;
  1031. UCHAR dummy_hash_data[IKE_MAX_HASH_SIZE];
  1032. IKE_PACKET_PAYLOAD *hash_payload;
  1033. BUF *ps_buf;
  1034. UINT after_hash_offset, after_hash_size;
  1035. BUF *ps_buf_after_hash;
  1036. BUF *tmp_buf;
  1037. UCHAR hash[IKE_MAX_HASH_SIZE];
  1038. IKE_CRYPTO_PARAM cp;
  1039. bool plain = false;
  1040. // Validate arguments
  1041. if (ike == NULL || c == NULL || payload == NULL)
  1042. {
  1043. IkeFreePayload(payload);
  1044. return;
  1045. }
  1046. sa = c->CurrentIkeSa;
  1047. if (sa == NULL)
  1048. {
  1049. plain = true;
  1050. }
  1051. if (force_plain)
  1052. {
  1053. plain = true;
  1054. }
  1055. if (plain && (init_cookie == 0 && resp_cookie == 0))
  1056. {
  1057. init_cookie = Rand64();
  1058. resp_cookie = 0;
  1059. }
  1060. payload_list = NewListFast(NULL);
  1061. Zero(dummy_hash_data, sizeof(dummy_hash_data));
  1062. // Hash payload
  1063. if (plain == false)
  1064. {
  1065. hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, dummy_hash_data, sa->HashSize);
  1066. Add(payload_list, hash_payload);
  1067. }
  1068. // Body
  1069. Add(payload_list, payload);
  1070. // Packet creation
  1071. ps = IkeNew((plain ? init_cookie : sa->InitiatorCookie), (plain ? resp_cookie : sa->ResponderCookie),
  1072. IKE_EXCHANGE_TYPE_INFORMATION, false, false, false,
  1073. GenerateNewMessageId(ike), payload_list);
  1074. if (plain == false)
  1075. {
  1076. // Build a temporary packet
  1077. ps_buf = IkeBuild(ps, NULL);
  1078. // Get the payload after the hash part
  1079. after_hash_offset = sizeof(IKE_HEADER) + hash_payload->BitArray->Size + sizeof(IKE_COMMON_HEADER);
  1080. after_hash_size = ((ps_buf->Size > after_hash_offset) ? (ps_buf->Size - after_hash_offset) : 0);
  1081. ps_buf_after_hash = MemToBuf(((UCHAR *)ps_buf->Buf) + after_hash_offset, after_hash_size);
  1082. FreeBuf(ps_buf);
  1083. // Calculate the hash
  1084. tmp_buf = NewBuf();
  1085. WriteBufInt(tmp_buf, ps->MessageId);
  1086. WriteBufBuf(tmp_buf, ps_buf_after_hash);
  1087. IkeHMac(sa->TransformSetting.Hash, hash, sa->SKEYID_a, sa->HashSize, tmp_buf->Buf, tmp_buf->Size);
  1088. FreeBuf(tmp_buf);
  1089. // Overwrite the hash
  1090. Copy(hash_payload->Payload.Hash.Data->Buf, hash, sa->HashSize);
  1091. ps->FlagEncrypted = true;
  1092. FreeBuf(ps_buf_after_hash);
  1093. }
  1094. // Packet reply
  1095. Zero(&cp, sizeof(cp));
  1096. if (plain == false)
  1097. {
  1098. cp.Key = sa->CryptoKey;
  1099. IkeCalcPhase2InitialIv(cp.Iv, sa, ps->MessageId);
  1100. }
  1101. ps_buf = IkeBuild(ps, &cp);
  1102. IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &c->ServerIP, c->ServerPort,
  1103. &c->ClientIP, c->ClientPort,
  1104. ps_buf->Buf, ps_buf->Size);
  1105. #ifdef RAW_DEBUG
  1106. IkeDebugUdpSendRawPacket(ps);
  1107. #endif // RAW_DEBUG
  1108. Free(ps_buf);
  1109. IkeFree(ps);
  1110. }
  1111. // Information exchange packet reception process
  1112. void ProcIkeInformationalExchangePacketRecv(IKE_SERVER *ike, UDPPACKET *p, IKE_PACKET *header)
  1113. {
  1114. IKE_CLIENT *c;
  1115. IKE_SA *ike_sa;
  1116. // Validate arguments
  1117. if (ike == NULL || p == NULL || header == NULL || header->InitiatorCookie == 0 || header->ResponderCookie == 0
  1118. || header->MessageId == 0 || header->FlagEncrypted == false)
  1119. {
  1120. return;
  1121. }
  1122. c = SearchOrCreateNewIkeClientForIkePacket(ike, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort, header);
  1123. if (c == NULL)
  1124. {
  1125. return;
  1126. }
  1127. ike_sa = FindIkeSaByResponderCookieAndClient(ike, header->ResponderCookie, c);
  1128. if (ike_sa != NULL && ike_sa->Established)
  1129. {
  1130. IKE_PACKET *pr;
  1131. IKE_CRYPTO_PARAM cp;
  1132. // Packet decoding
  1133. Zero(&cp, sizeof(cp));
  1134. cp.Key = ike_sa->CryptoKey;
  1135. IkeCalcPhase2InitialIv(cp.Iv, ike_sa, header->MessageId);
  1136. pr = IkeParse(p->Data, p->Size, &cp);
  1137. #ifdef RAW_DEBUG
  1138. IkeDebugUdpSendRawPacket(pr);
  1139. #endif // RAW_DEBUG
  1140. if (pr != NULL)
  1141. {
  1142. // Get the hash payload
  1143. IKE_PACKET_PAYLOAD *hash_payload;
  1144. hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
  1145. if (hash_payload != NULL)
  1146. {
  1147. // Get the payload after the hash
  1148. UINT header_and_hash_size = sizeof(IKE_COMMON_HEADER) + hash_payload->BitArray->Size;
  1149. void *after_hash_data = ((UCHAR *)pr->DecryptedPayload->Buf) + header_and_hash_size;
  1150. if (pr->DecryptedPayload->Size > header_and_hash_size)
  1151. {
  1152. UINT after_hash_size = pr->DecryptedPayload->Size - header_and_hash_size;
  1153. UCHAR hash1[IKE_MAX_HASH_SIZE];
  1154. BUF *hash1_buf;
  1155. hash1_buf = NewBuf();
  1156. WriteBufInt(hash1_buf, header->MessageId);
  1157. WriteBuf(hash1_buf, after_hash_data, after_hash_size);
  1158. IkeHMac(ike_sa->TransformSetting.Hash, hash1, ike_sa->SKEYID_a, ike_sa->HashSize,
  1159. hash1_buf->Buf, hash1_buf->Size);
  1160. // Compare the hash value
  1161. if (IkeCompareHash(hash_payload, hash1, ike_sa->HashSize))
  1162. {
  1163. UINT i, num;
  1164. // Handle the deletion payload
  1165. num = IkeGetPayloadNum(pr->PayloadList, IKE_PAYLOAD_DELETE);
  1166. for (i = 0;i < num;i++)
  1167. {
  1168. IKE_PACKET_PAYLOAD *payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_DELETE, i);
  1169. IKE_PACKET_DELETE_PAYLOAD *del = &payload->Payload.Delete;
  1170. ProcDeletePayload(ike, c, del);
  1171. }
  1172. num = IkeGetPayloadNum(pr->PayloadList, IKE_PAYLOAD_NOTICE);
  1173. // Handle the notification payload
  1174. for (i = 0;i < num;i++)
  1175. {
  1176. IKE_PACKET_PAYLOAD *payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NOTICE, i);
  1177. IKE_PACKET_NOTICE_PAYLOAD *n = &payload->Payload.Notice;
  1178. if (n->MessageType == IKE_NOTICE_DPD_REQUEST || n->MessageType == IKE_NOTICE_DPD_RESPONSE)
  1179. {
  1180. if (n->MessageData != NULL && n->MessageData->Size == sizeof(UINT))
  1181. {
  1182. UINT seq_no = READ_UINT(n->MessageData->Buf);
  1183. if (n->Spi->Size == (sizeof(UINT64) * 2))
  1184. {
  1185. UINT64 init_cookie = READ_UINT64(((UCHAR *)n->Spi->Buf));
  1186. UINT64 resp_cookie = READ_UINT64(((UCHAR *)n->Spi->Buf) + sizeof(UINT64));
  1187. if (init_cookie != 0 && resp_cookie != 0)
  1188. {
  1189. IKE_SA *found_ike_sa = SearchIkeSaByCookie(ike, init_cookie, resp_cookie);
  1190. if (found_ike_sa != NULL && found_ike_sa->IkeClient == c)
  1191. {
  1192. if (n->MessageType == IKE_NOTICE_DPD_REQUEST)
  1193. {
  1194. // Return the DPD Response (ACK) for the DPD Request
  1195. SendInformationalExchangePacket(ike, c,
  1196. IkeNewNoticeDpdPayload(true, init_cookie, resp_cookie,
  1197. seq_no));
  1198. }
  1199. // Update the status of the IKE SA
  1200. found_ike_sa->LastCommTick = ike->Now;
  1201. ike_sa->LastCommTick = ike->Now;
  1202. found_ike_sa->IkeClient->LastCommTick = ike->Now;
  1203. ike_sa->IkeClient->LastCommTick = ike->Now;
  1204. ike_sa->IkeClient->CurrentIkeSa = ike_sa;
  1205. }
  1206. }
  1207. }
  1208. }
  1209. }
  1210. }
  1211. }
  1212. FreeBuf(hash1_buf);
  1213. }
  1214. }
  1215. IkeFree(pr);
  1216. }
  1217. }
  1218. }
  1219. // Create a new message ID
  1220. UINT GenerateNewMessageId(IKE_SERVER *ike)
  1221. {
  1222. UINT ret;
  1223. // Validate arguments
  1224. if (ike == NULL)
  1225. {
  1226. return 0;
  1227. }
  1228. while (true)
  1229. {
  1230. ret = Rand32();
  1231. if (ret != 0 && ret != 0xffffffff)
  1232. {
  1233. UINT i;
  1234. bool ok = true;
  1235. for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
  1236. {
  1237. IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
  1238. if (sa->MessageId == ret)
  1239. {
  1240. ok = false;
  1241. break;
  1242. }
  1243. }
  1244. if (ok)
  1245. {
  1246. return ret;
  1247. }
  1248. }
  1249. }
  1250. }
  1251. // Start the quick mode
  1252. void StartQuickMode(IKE_SERVER *ike, IKE_CLIENT *c)
  1253. {
  1254. IPSEC_SA_TRANSFORM_SETTING setting;
  1255. IKE_SA *ike_sa;
  1256. UINT message_id;
  1257. UCHAR iv[IKE_MAX_BLOCK_SIZE];
  1258. // Validate arguments
  1259. if (ike == NULL || c == NULL)
  1260. {
  1261. return;
  1262. }
  1263. if (IsZero(&c->CachedTransformSetting, sizeof(IPSEC_SA_TRANSFORM_SETTING)))
  1264. {
  1265. // Cached transform setting does not exist
  1266. Debug("Error: c->CachedTransformSetting is not existing.\n");
  1267. return;
  1268. }
  1269. ike_sa = c->CurrentIkeSa;
  1270. if (ike_sa == NULL)
  1271. {
  1272. return;
  1273. }
  1274. IPsecLog(ike, NULL, ike_sa, NULL, "LI_START_QM_FROM_SERVER");
  1275. Copy(&setting, &c->CachedTransformSetting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
  1276. message_id = GenerateNewMessageId(ike);
  1277. IkeCalcPhase2InitialIv(iv, ike_sa, message_id);
  1278. #ifdef FORCE_LIFETIME_QM
  1279. setting.LifeSeconds = FORCE_LIFETIME_QM;
  1280. #endif // FORCE_LIFETIME_QM
  1281. if (true)
  1282. {
  1283. IKE_PACKET *ps;
  1284. LIST *payload_list;
  1285. IKE_PACKET_PAYLOAD *send_hash_payload;
  1286. IKE_PACKET_PAYLOAD *send_sa_payload;
  1287. IKE_PACKET_PAYLOAD *send_proposal_payload;
  1288. IKE_PACKET_PAYLOAD *send_transform_payload;
  1289. IKE_PACKET_PAYLOAD *send_rand_payload;
  1290. IKE_PACKET_PAYLOAD *send_key_payload = NULL;
  1291. IKE_PACKET_PAYLOAD *send_id_1 = NULL, *send_id_2 = NULL;
  1292. UINT shared_key_size = 0;
  1293. UCHAR *shared_key = NULL;
  1294. BUF *initiator_rand;
  1295. IPSECSA *ipsec_sa_s_c, *ipsec_sa_c_s;
  1296. BUF *ps_buf;
  1297. UINT after_hash_offset, after_hash_size;
  1298. BUF *ps_buf_after_hash;
  1299. BUF *tmp_buf;
  1300. UINT spi;
  1301. UINT spi_be;
  1302. UCHAR hash1[IKE_MAX_HASH_SIZE];
  1303. DH_CTX *dh = NULL;
  1304. UCHAR dummy_hash_data[IKE_MAX_HASH_SIZE];
  1305. initiator_rand = RandBuf(IKE_SA_RAND_SIZE);
  1306. if (setting.Dh != NULL)
  1307. {
  1308. // Generate DH
  1309. dh = IkeDhNewCtx(setting.Dh);
  1310. if (dh != NULL)
  1311. {
  1312. send_key_payload = IkeNewDataPayload(IKE_PAYLOAD_KEY_EXCHANGE,
  1313. dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
  1314. }
  1315. }
  1316. Zero(dummy_hash_data, sizeof(dummy_hash_data));
  1317. // Dummy hash value
  1318. payload_list = NewListFast(NULL);
  1319. send_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, dummy_hash_data, ike_sa->HashSize);
  1320. Add(payload_list, send_hash_payload);
  1321. // Determine the SPI
  1322. spi = GenerateNewIPsecSaSpi(ike, 0);
  1323. spi_be = Endian32(spi);
  1324. // SA
  1325. send_transform_payload = TransformSettingToTransformPayloadForIPsec(ike, &setting);
  1326. send_proposal_payload = IkeNewProposalPayload(1, IKE_PROTOCOL_ID_IPSEC_ESP, &spi_be, sizeof(spi_be),
  1327. NewListSingle(send_transform_payload));
  1328. send_sa_payload = IkeNewSaPayload(NewListSingle(send_proposal_payload));
  1329. Add(payload_list, send_sa_payload);
  1330. // Random number
  1331. send_rand_payload = IkeNewDataPayload(IKE_PAYLOAD_RAND, initiator_rand->Buf, initiator_rand->Size);
  1332. Add(payload_list, send_rand_payload);
  1333. // Key exchange
  1334. if (send_key_payload != NULL)
  1335. {
  1336. Add(payload_list, send_key_payload);
  1337. }
  1338. if (c->SendID1andID2)
  1339. {
  1340. // Add the ID payload
  1341. if (setting.CapsuleMode == IKE_P2_CAPSULE_NAT_TUNNEL_1 || setting.CapsuleMode == IKE_P2_CAPSULE_NAT_TUNNEL_2)
  1342. {
  1343. UCHAR zero[32];
  1344. Zero(zero, sizeof(zero));
  1345. // Tunnel Mode
  1346. send_id_1 = IkeNewIdPayload((IsIP4(&c->ServerIP) ? IKE_ID_IPV4_ADDR_SUBNET : IKE_ID_IPV6_ADDR_SUBNET),
  1347. 0, 0,
  1348. zero, (IsIP4(&c->ServerIP) ? 8 : 32));
  1349. send_id_2 = IkeNewIdPayload(c->SendID1_Type,
  1350. c->SendID1_Protocol, c->SendID1_Port,
  1351. c->SendID1_Buf->Buf, c->SendID1_Buf->Size);
  1352. }
  1353. else
  1354. {
  1355. // Transport mode
  1356. // Specify in the reverse order in which the client has been specified
  1357. send_id_2 = IkeNewIdPayload(c->SendID1_Type,
  1358. c->SendID1_Protocol, c->SendID1_Port,
  1359. c->SendID1_Buf->Buf, c->SendID1_Buf->Size);
  1360. send_id_1 = IkeNewIdPayload(c->SendID2_Type,
  1361. c->SendID2_Protocol, c->SendID2_Port,
  1362. c->SendID2_Buf->Buf, c->SendID2_Buf->Size);
  1363. }
  1364. Add(payload_list, send_id_1);
  1365. Add(payload_list, send_id_2);
  1366. }
  1367. if (true)
  1368. {
  1369. // NAT-OA payload
  1370. if (c->SendNatOaDraft1)
  1371. {
  1372. Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA_DRAFT, &c->ServerIP));
  1373. }
  1374. if (c->SendNatOaDraft2)
  1375. {
  1376. Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA_DRAFT_2, &c->ServerIP));
  1377. }
  1378. if (c->SendNatOaRfc)
  1379. {
  1380. Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA, &c->ClientIP));
  1381. Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA, &c->ServerIP));
  1382. }
  1383. }
  1384. // Build a packet
  1385. ps = IkeNew(ike_sa->InitiatorCookie, ike_sa->ResponderCookie, IKE_EXCHANGE_TYPE_QUICK,
  1386. false, false, false, message_id, payload_list);
  1387. // Build a temporary packet
  1388. ps_buf = IkeBuild(ps, NULL);
  1389. // Get the payload after the hash part
  1390. after_hash_offset = sizeof(IKE_HEADER) + send_hash_payload->BitArray->Size + sizeof(IKE_COMMON_HEADER);
  1391. after_hash_size = ((ps_buf->Size > after_hash_offset) ? (ps_buf->Size - after_hash_offset) : 0);
  1392. ps_buf_after_hash = MemToBuf(((UCHAR *)ps_buf->Buf) + after_hash_offset, after_hash_size);
  1393. FreeBuf(ps_buf);
  1394. // Calculate the hash #1
  1395. tmp_buf = NewBuf();
  1396. WriteBufInt(tmp_buf, message_id);
  1397. WriteBufBuf(tmp_buf, ps_buf_after_hash);
  1398. IkeHMac(ike_sa->TransformSetting.Hash, hash1, ike_sa->SKEYID_a, ike_sa->HashSize, tmp_buf->Buf, tmp_buf->Size);
  1399. FreeBuf(tmp_buf);
  1400. // Overwrite hash #1
  1401. Copy(send_hash_payload->Payload.Hash.Data->Buf, hash1, ike_sa->HashSize);
  1402. // Create an IPsec SA
  1403. ipsec_sa_c_s = NewIPsecSa(ike, c, ike_sa, true, message_id, false, iv, spi,
  1404. initiator_rand->Buf, initiator_rand->Size, NULL, 0,
  1405. &setting, shared_key, shared_key_size);
  1406. ipsec_sa_s_c = NewIPsecSa(ike, c, ike_sa, true, message_id, true, iv, 0,
  1407. initiator_rand->Buf, initiator_rand->Size, NULL, 0,
  1408. &setting, shared_key, shared_key_size);
  1409. ipsec_sa_c_s->PairIPsecSa = ipsec_sa_s_c;
  1410. ipsec_sa_s_c->PairIPsecSa = ipsec_sa_c_s;
  1411. ipsec_sa_s_c->Dh = dh;
  1412. Insert(ike->IPsecSaList, ipsec_sa_c_s);
  1413. Insert(ike->IPsecSaList, ipsec_sa_s_c);
  1414. // Packet transmission
  1415. ps->FlagEncrypted = true;
  1416. IPsecSaSendPacket(ike, ipsec_sa_s_c, ps);
  1417. ipsec_sa_s_c->NumResends = 3;
  1418. #ifdef RAW_DEBUG
  1419. IkeDebugUdpSendRawPacket(ps);
  1420. #endif // RAW_DEBUG
  1421. IkeFree(ps);
  1422. Free(shared_key);
  1423. FreeBuf(ps_buf_after_hash);
  1424. FreeBuf(initiator_rand);
  1425. }
  1426. }
  1427. // Process the quick mode received packet
  1428. void ProcIkeQuickModePacketRecv(IKE_SERVER *ike, UDPPACKET *p, IKE_PACKET *header)
  1429. {
  1430. IKE_CLIENT *c;
  1431. IKE_SA *ike_sa;
  1432. // Validate arguments
  1433. if (ike == NULL || p == NULL || header == NULL || header->InitiatorCookie == 0 || header->ResponderCookie == 0
  1434. || header->MessageId == 0 || header->FlagEncrypted == false)
  1435. {
  1436. return;
  1437. }
  1438. c = SearchOrCreateNewIkeClientForIkePacket(ike, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort, header);
  1439. if (c == NULL)
  1440. {
  1441. return;
  1442. }
  1443. ike_sa = FindIkeSaByResponderCookieAndClient(ike, header->ResponderCookie, c);
  1444. if (ike_sa == NULL)
  1445. {
  1446. // IKE SA does not exist
  1447. SendInformationalExchangePacketEx(ike, c, IkeNewNoticeErrorInvalidCookiePayload(header->InitiatorCookie,
  1448. header->ResponderCookie), true, header->InitiatorCookie, header->ResponderCookie);
  1449. }
  1450. if (ike_sa != NULL && ike_sa->Established)
  1451. {
  1452. // Update the status of the IKE SA
  1453. ike_sa->LastCommTick = ike->Now;
  1454. ike_sa->IkeClient->LastCommTick = ike->Now;
  1455. ike_sa->IkeClient->CurrentIkeSa = ike_sa;
  1456. // Search whether the Message ID is already in the database
  1457. if (SearchIPsecSaByMessageId(ike, c, header->MessageId) == NULL)
  1458. {
  1459. IKE_PACKET *pr;
  1460. IKE_CRYPTO_PARAM cp;
  1461. // Message ID does not exist. Start a new Quick Mode session
  1462. Zero(&cp, sizeof(cp));
  1463. cp.Key = ike_sa->CryptoKey;
  1464. IkeCalcPhase2InitialIv(cp.Iv, ike_sa, header->MessageId);
  1465. pr = IkeParse(p->Data, p->Size, &cp);
  1466. #ifdef RAW_DEBUG
  1467. IkeDebugUdpSendRawPacket(pr);
  1468. #endif // RAW_DEBUG
  1469. if (pr != NULL)
  1470. {
  1471. // Get the hash payload
  1472. IKE_PACKET_PAYLOAD *hash_payload;
  1473. hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
  1474. if (hash_payload != NULL)
  1475. {
  1476. // Get the payload after the hash
  1477. UINT header_and_hash_size = sizeof(IKE_COMMON_HEADER) + hash_payload->BitArray->Size;
  1478. void *after_hash_data = ((UCHAR *)pr->DecryptedPayload->Buf) + header_and_hash_size;
  1479. if (pr->DecryptedPayload->Size > header_and_hash_size)
  1480. {
  1481. UINT after_hash_size = pr->DecryptedPayload->Size - header_and_hash_size;
  1482. UCHAR hash1[IKE_MAX_HASH_SIZE];
  1483. BUF *hash1_buf;
  1484. hash1_buf = NewBuf();
  1485. WriteBufInt(hash1_buf, header->MessageId);
  1486. WriteBuf(hash1_buf, after_hash_data, after_hash_size);
  1487. IkeHMac(ike_sa->TransformSetting.Hash, hash1, ike_sa->SKEYID_a, ike_sa->HashSize,
  1488. hash1_buf->Buf, hash1_buf->Size);
  1489. // Compare the hash value
  1490. if (IkeCompareHash(hash_payload, hash1, ike_sa->HashSize))
  1491. {
  1492. IKE_PACKET_PAYLOAD *sa_payload, *rand_payload, *key_payload, *id_payload_1, *id_payload_2;
  1493. // Get the payload of other
  1494. sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
  1495. rand_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_RAND, 0);
  1496. key_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_KEY_EXCHANGE, 0);
  1497. id_payload_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 0);
  1498. id_payload_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 1);
  1499. if (sa_payload != NULL && rand_payload != NULL)
  1500. {
  1501. IPSEC_SA_TRANSFORM_SETTING setting;
  1502. Zero(&setting, sizeof(setting));
  1503. // Interpret the SA payload
  1504. if (GetBestTransformSettingForIPsecSa(ike, pr, &setting, &p->DstIP) && (GetNumberOfIPsecSaOfIkeClient(ike, c) <= IKE_QUOTA_MAX_SA_PER_CLIENT))
  1505. {
  1506. // Appropriate transform setting is selected
  1507. Debug("P2 Transform: %s %s %s(%u) %u %u\n",
  1508. (setting.Dh == NULL ? NULL : setting.Dh->Name), setting.Hash->Name, setting.Crypto->Name, setting.CryptoKeySize,
  1509. setting.LifeKilobytes, setting.LifeSeconds);
  1510. #ifdef FORCE_LIFETIME_QM
  1511. setting.LifeSeconds = FORCE_LIFETIME_QM;
  1512. #endif // FORCE_LIFETIME_QM
  1513. // Cache the transform attribute value
  1514. Copy(&c->CachedTransformSetting, &setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
  1515. // Check the key exchange payload if the PFS is specified
  1516. if (setting.Dh == NULL || (setting.Dh != NULL && key_payload != NULL &&
  1517. key_payload->Payload.KeyExchange.Data->Size <= setting.Dh->KeySize))
  1518. {
  1519. // Create a payload for response
  1520. IKE_PACKET *ps;
  1521. LIST *payload_list;
  1522. IKE_PACKET_PAYLOAD *send_hash_payload;
  1523. IKE_PACKET_PAYLOAD *send_sa_payload;
  1524. IKE_PACKET_PAYLOAD *send_proposal_payload;
  1525. IKE_PACKET_PAYLOAD *send_transform_payload;
  1526. IKE_PACKET_PAYLOAD *send_rand_payload;
  1527. IKE_PACKET_PAYLOAD *send_key_payload = NULL;
  1528. IKE_PACKET_PAYLOAD *send_id_1 = NULL, *send_id_2 = NULL;
  1529. UCHAR dummy_hash_data[IKE_MAX_HASH_SIZE];
  1530. DH_CTX *dh = NULL;
  1531. UINT shared_key_size = 0;
  1532. UCHAR *shared_key = NULL;
  1533. BUF *initiator_rand, *responder_rand;
  1534. IPSECSA *ipsec_sa_s_c, *ipsec_sa_c_s;
  1535. BUF *ps_buf;
  1536. UINT after_hash_offset, after_hash_size;
  1537. BUF *ps_buf_after_hash;
  1538. BUF *tmp_buf;
  1539. UINT spi;
  1540. UINT spi_be;
  1541. UCHAR hash2[IKE_MAX_HASH_SIZE];
  1542. UCHAR hash3[IKE_MAX_HASH_SIZE];
  1543. UCHAR zero = 0;
  1544. IPsecLog(ike, NULL, ike_sa, NULL, "LI_START_QM_FROM_CLIENT");
  1545. initiator_rand = CloneBuf(rand_payload->Payload.Rand.Data);
  1546. responder_rand = RandBuf(IKE_SA_RAND_SIZE);
  1547. if (setting.Dh != NULL)
  1548. {
  1549. // Calculate DH
  1550. dh = IkeDhNewCtx(setting.Dh);
  1551. shared_key_size = (dh == NULL ? 0 : dh->Size);
  1552. shared_key = ZeroMalloc(shared_key_size);
  1553. if (DhCompute(dh, shared_key, key_payload->Payload.KeyExchange.Data->Buf, key_payload->Payload.KeyExchange.Data->Size))
  1554. {
  1555. // DH calculation success
  1556. Debug("P2 DH Ok.\n");
  1557. send_key_payload = IkeNewDataPayload(IKE_PAYLOAD_KEY_EXCHANGE,
  1558. dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
  1559. IkeDhFreeCtx(dh);
  1560. }
  1561. else
  1562. {
  1563. // DH calculation failure
  1564. Debug("P2 DhCompute failed.\n");
  1565. shared_key = NULL;
  1566. Free(shared_key);
  1567. shared_key_size = 0;
  1568. IPsecLog(ike, NULL, ike_sa, NULL, "LI_QM_DH_ERROR");
  1569. }
  1570. }
  1571. Zero(dummy_hash_data, sizeof(dummy_hash_data));
  1572. // Dummy hash value
  1573. payload_list = NewListFast(NULL);
  1574. send_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, dummy_hash_data, ike_sa->HashSize);
  1575. Add(payload_list, send_hash_payload);
  1576. // Determine the SPI
  1577. spi = GenerateNewIPsecSaSpi(ike, setting.SpiServerToClient);
  1578. spi_be = Endian32(spi);
  1579. // SA
  1580. send_transform_payload = TransformSettingToTransformPayloadForIPsec(ike, &setting);
  1581. send_proposal_payload = IkeNewProposalPayload(1, IKE_PROTOCOL_ID_IPSEC_ESP, &spi_be, sizeof(spi_be),
  1582. NewListSingle(send_transform_payload));
  1583. send_sa_payload = IkeNewSaPayload(NewListSingle(send_proposal_payload));
  1584. Add(payload_list, send_sa_payload);
  1585. // Random number
  1586. send_rand_payload = IkeNewDataPayload(IKE_PAYLOAD_RAND, responder_rand->Buf, responder_rand->Size);
  1587. Add(payload_list, send_rand_payload);
  1588. // Key exchange
  1589. if (send_key_payload != NULL)
  1590. {
  1591. Add(payload_list, send_key_payload);
  1592. }
  1593. // ID
  1594. if (id_payload_1 != NULL && id_payload_2 != NULL)
  1595. {
  1596. send_id_1 = IkeNewIdPayload(id_payload_1->Payload.Id.Type,
  1597. id_payload_1->Payload.Id.ProtocolId, id_payload_1->Payload.Id.Port,
  1598. id_payload_1->Payload.Id.IdData->Buf, id_payload_1->Payload.Id.IdData->Size);
  1599. send_id_2 = IkeNewIdPayload(id_payload_2->Payload.Id.Type,
  1600. id_payload_2->Payload.Id.ProtocolId, id_payload_2->Payload.Id.Port,
  1601. id_payload_2->Payload.Id.IdData->Buf, id_payload_2->Payload.Id.IdData->Size);
  1602. Add(payload_list, send_id_1);
  1603. Add(payload_list, send_id_2);
  1604. if (c->SendID1_Buf != NULL)
  1605. {
  1606. FreeBuf(c->SendID1_Buf);
  1607. }
  1608. if (c->SendID2_Buf != NULL)
  1609. {
  1610. FreeBuf(c->SendID2_Buf);
  1611. }
  1612. c->SendID1_Type = id_payload_1->Payload.Id.Type;
  1613. c->SendID1_Protocol = id_payload_1->Payload.Id.ProtocolId;
  1614. c->SendID1_Port = id_payload_1->Payload.Id.Port;
  1615. c->SendID1_Buf = CloneBuf(id_payload_1->Payload.Id.IdData);
  1616. c->SendID2_Type = id_payload_2->Payload.Id.Type;
  1617. c->SendID2_Protocol = id_payload_2->Payload.Id.ProtocolId;
  1618. c->SendID2_Port = id_payload_2->Payload.Id.Port;
  1619. c->SendID2_Buf = CloneBuf(id_payload_2->Payload.Id.IdData);
  1620. c->SendID1andID2 = true;
  1621. }
  1622. else
  1623. {
  1624. c->SendID1andID2 = false;
  1625. }
  1626. if (true)
  1627. {
  1628. // Reply if NAT-OA payload is presented by the client
  1629. IKE_PACKET_PAYLOAD *nat_oa_draft1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_OA_DRAFT, 0);
  1630. IKE_PACKET_PAYLOAD *nat_oa_draft2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_OA_DRAFT_2, 0);
  1631. IKE_PACKET_PAYLOAD *nat_oa_rfc_0 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_OA, 0);
  1632. IKE_PACKET_PAYLOAD *nat_oa_rfc_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_OA, 1);
  1633. c->SendNatOaDraft1 = c->SendNatOaDraft2 = c->SendNatOaRfc = false;
  1634. c->ShouldCalcChecksumForUDP = false;
  1635. if (nat_oa_draft1 != NULL)
  1636. {
  1637. Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA_DRAFT, &c->ServerIP));
  1638. c->SendNatOaDraft1 = true;
  1639. if (IsIP4(&nat_oa_draft1->Payload.NatOa.IpAddress) == IsIP4(&c->ServerIP))
  1640. {
  1641. Copy(&c->TransportModeClientIP, &nat_oa_draft1->Payload.NatOa.IpAddress, sizeof(IP));
  1642. Copy(&c->TransportModeServerIP, &c->ServerIP, sizeof(IP));
  1643. c->ShouldCalcChecksumForUDP = true;
  1644. }
  1645. }
  1646. if (nat_oa_draft2 != NULL)
  1647. {
  1648. Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA_DRAFT_2, &c->ServerIP));
  1649. c->SendNatOaDraft2 = true;
  1650. if (IsIP4(&nat_oa_draft2->Payload.NatOa.IpAddress) == IsIP4(&c->ServerIP))
  1651. {
  1652. Copy(&c->TransportModeClientIP, &nat_oa_draft2->Payload.NatOa.IpAddress, sizeof(IP));
  1653. Copy(&c->TransportModeServerIP, &c->ServerIP, sizeof(IP));
  1654. c->ShouldCalcChecksumForUDP = true;
  1655. }
  1656. }
  1657. if (nat_oa_rfc_0 != NULL && nat_oa_rfc_1 != NULL)
  1658. {
  1659. Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA, &c->ClientIP));
  1660. Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA, &c->ServerIP));
  1661. c->SendNatOaRfc = true;
  1662. if (IsIP4(&nat_oa_rfc_0->Payload.NatOa.IpAddress) == IsIP4(&c->ServerIP))
  1663. {
  1664. Copy(&c->TransportModeClientIP, &nat_oa_rfc_0->Payload.NatOa.IpAddress, sizeof(IP));
  1665. Copy(&c->TransportModeServerIP, &c->ServerIP, sizeof(IP));
  1666. c->ShouldCalcChecksumForUDP = true;
  1667. }
  1668. }
  1669. }
  1670. // Build a packet
  1671. ps = IkeNew(ike_sa->InitiatorCookie, ike_sa->ResponderCookie, IKE_EXCHANGE_TYPE_QUICK,
  1672. false, false, false, header->MessageId, payload_list);
  1673. // Build a temporary packet
  1674. ps_buf = IkeBuild(ps, NULL);
  1675. // Get the payload after the hash part
  1676. after_hash_offset = sizeof(IKE_HEADER) + send_hash_payload->BitArray->Size + sizeof(IKE_COMMON_HEADER);
  1677. after_hash_size = ((ps_buf->Size > after_hash_offset) ? (ps_buf->Size - after_hash_offset) : 0);
  1678. ps_buf_after_hash = MemToBuf(((UCHAR *)ps_buf->Buf) + after_hash_offset, after_hash_size);
  1679. FreeBuf(ps_buf);
  1680. // Calculate the hash #2
  1681. tmp_buf = NewBuf();
  1682. WriteBufInt(tmp_buf, header->MessageId);
  1683. WriteBufBuf(tmp_buf, initiator_rand);
  1684. WriteBufBuf(tmp_buf, ps_buf_after_hash);
  1685. IkeHMac(ike_sa->TransformSetting.Hash, hash2, ike_sa->SKEYID_a, ike_sa->HashSize, tmp_buf->Buf, tmp_buf->Size);
  1686. FreeBuf(tmp_buf);
  1687. // Calculate the hash #3
  1688. tmp_buf = NewBuf();
  1689. WriteBuf(tmp_buf, &zero, 1);
  1690. WriteBufInt(tmp_buf, header->MessageId);
  1691. WriteBufBuf(tmp_buf, initiator_rand);
  1692. WriteBufBuf(tmp_buf, responder_rand);
  1693. IkeHMac(ike_sa->TransformSetting.Hash, hash3, ike_sa->SKEYID_a, ike_sa->HashSize, tmp_buf->Buf, tmp_buf->Size);
  1694. FreeBuf(tmp_buf);
  1695. // Create an IPsec SA
  1696. ipsec_sa_c_s = NewIPsecSa(ike, c, ike_sa, false, header->MessageId, false, cp.NextIv, spi,
  1697. initiator_rand->Buf, initiator_rand->Size, responder_rand->Buf, responder_rand->Size,
  1698. &setting, shared_key, shared_key_size);
  1699. ipsec_sa_s_c = NewIPsecSa(ike, c, ike_sa, false, header->MessageId, true, cp.NextIv, setting.SpiServerToClient,
  1700. initiator_rand->Buf, initiator_rand->Size, responder_rand->Buf, responder_rand->Size,
  1701. &setting, shared_key, shared_key_size);
  1702. ipsec_sa_c_s->PairIPsecSa = ipsec_sa_s_c;
  1703. ipsec_sa_s_c->PairIPsecSa = ipsec_sa_c_s;
  1704. Insert(ike->IPsecSaList, ipsec_sa_c_s);
  1705. Insert(ike->IPsecSaList, ipsec_sa_s_c);
  1706. Copy(ipsec_sa_c_s->Hash3, hash3, ike_sa->HashSize);
  1707. // Overwrite hash #2
  1708. Copy(send_hash_payload->Payload.Hash.Data->Buf, hash2, ike_sa->HashSize);
  1709. // Packet reply
  1710. ps->FlagEncrypted = true;
  1711. IPsecSaSendPacket(ike, ipsec_sa_s_c, ps);
  1712. IkeSaSendPacket(ike, ike_sa, NULL);
  1713. #ifdef RAW_DEBUG
  1714. IkeDebugUdpSendRawPacket(ps);
  1715. #endif // RAW_DEBUG
  1716. IkeFree(ps);
  1717. Free(shared_key);
  1718. FreeBuf(ps_buf_after_hash);
  1719. FreeBuf(initiator_rand);
  1720. FreeBuf(responder_rand);
  1721. }
  1722. }
  1723. else
  1724. {
  1725. // No appropriate transform setting
  1726. Debug("No Appropriate Transform was Found.\n");
  1727. IPsecLog(ike, NULL, ike_sa, NULL, "LI_IPSEC_NO_TRANSFORM");
  1728. SendInformationalExchangePacket(ike, c, IkeNewNoticeErrorNoProposalChosenPayload(true, header->InitiatorCookie, header->ResponderCookie));
  1729. }
  1730. }
  1731. }
  1732. else
  1733. {
  1734. Debug("QM-1: Hash 1 is invalid.\n");
  1735. }
  1736. FreeBuf(hash1_buf);
  1737. }
  1738. }
  1739. IkeFree(pr);
  1740. }
  1741. }
  1742. else
  1743. {
  1744. // Get the IPsec SA
  1745. IPSECSA *ipsec_sa_cs = SearchIPsecSaByMessageId(ike, c, header->MessageId);
  1746. if (ipsec_sa_cs != NULL)
  1747. {
  1748. IPSECSA *ipsec_sa_sc = ipsec_sa_cs->PairIPsecSa;
  1749. if (ipsec_sa_sc != NULL)
  1750. {
  1751. if (ipsec_sa_sc->Established == false && ipsec_sa_cs->Established == false)
  1752. {
  1753. IKE_PACKET *pr = IPsecSaRecvPacket(ike, ipsec_sa_cs, p->Data, p->Size);
  1754. #ifdef RAW_DEBUG
  1755. IkeDebugUdpSendRawPacket(pr);
  1756. #endif // RAW_DEBUG
  1757. if (pr != NULL)
  1758. {
  1759. if (ipsec_sa_cs->Initiated == false)
  1760. {
  1761. // Initiator is client-side
  1762. // Check hash3 payload
  1763. IKE_PACKET_PAYLOAD *hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
  1764. if (hash_payload != NULL)
  1765. {
  1766. BUF *hash_buf = hash_payload->Payload.Hash.Data;
  1767. if (hash_buf != NULL)
  1768. {
  1769. if (hash_buf->Size == ipsec_sa_cs->IkeSa->HashSize)
  1770. {
  1771. if (Cmp(hash_buf->Buf, ipsec_sa_cs->Hash3, hash_buf->Size) == 0)
  1772. {
  1773. ipsec_sa_cs->Established = ipsec_sa_sc->Established = true;
  1774. ipsec_sa_cs->EstablishedTick = ipsec_sa_sc->EstablishedTick = ike->Now;
  1775. ipsec_sa_cs->LastCommTick = ipsec_sa_sc->LastCommTick = ike->Now;
  1776. c->CurrentIpSecSaRecv = ipsec_sa_cs;
  1777. c->CurrentIpSecSaSend = ipsec_sa_sc;
  1778. Debug("IPsec SA 0x%X & 0x%X Established.\n",
  1779. ipsec_sa_cs->Spi,
  1780. ipsec_sa_sc->Spi);
  1781. IPsecLog(ike, NULL, NULL, ipsec_sa_sc, "LI_IPSEC_SA_ESTABLISHED");
  1782. IPsecSaSendPacket(ike, ipsec_sa_sc, NULL);
  1783. }
  1784. else
  1785. {
  1786. Debug("QM-3: Hash 3 is invalid.\n");
  1787. }
  1788. }
  1789. }
  1790. }
  1791. }
  1792. else
  1793. {
  1794. // Initiator is server-side
  1795. // Get hash payload
  1796. IKE_PACKET_PAYLOAD *hash_payload;
  1797. hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
  1798. if (hash_payload != NULL && ipsec_sa_sc->InitiatorRand != NULL)
  1799. {
  1800. // Get the payload after the hash
  1801. UINT header_and_hash_size = sizeof(IKE_COMMON_HEADER) + hash_payload->BitArray->Size;
  1802. void *after_hash_data = ((UCHAR *)pr->DecryptedPayload->Buf) + header_and_hash_size;
  1803. if (pr->DecryptedPayload->Size > header_and_hash_size)
  1804. {
  1805. UINT after_hash_size = pr->DecryptedPayload->Size - header_and_hash_size;
  1806. UCHAR hash2[IKE_MAX_HASH_SIZE];
  1807. BUF *hash2_buf;
  1808. hash2_buf = NewBuf();
  1809. WriteBufInt(hash2_buf, header->MessageId);
  1810. WriteBufBuf(hash2_buf, ipsec_sa_sc->InitiatorRand);
  1811. WriteBuf(hash2_buf, after_hash_data, after_hash_size);
  1812. IkeHMac(ipsec_sa_sc->SKEYID_Hash, hash2, ipsec_sa_sc->SKEYID_a, ipsec_sa_sc->SKEYID_Hash->HashSize,
  1813. hash2_buf->Buf, hash2_buf->Size);
  1814. FreeBuf(hash2_buf);
  1815. // Compare the hash value
  1816. if (IkeCompareHash(hash_payload, hash2, ike_sa->HashSize))
  1817. {
  1818. IKE_PACKET_PAYLOAD *sa_payload, *rand_payload, *key_payload, *id_payload_1, *id_payload_2;
  1819. // Get the payload of other
  1820. sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
  1821. rand_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_RAND, 0);
  1822. key_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_KEY_EXCHANGE, 0);
  1823. id_payload_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 0);
  1824. id_payload_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 1);
  1825. if (sa_payload != NULL && rand_payload != NULL)
  1826. {
  1827. IPSEC_SA_TRANSFORM_SETTING setting;
  1828. // Interpret the SA payload
  1829. if (GetBestTransformSettingForIPsecSa(ike, pr, &setting, &p->DstIP))
  1830. {
  1831. // Appropriate transform setting is selected
  1832. Debug("P2 Transform: %s %s %s(%u) %u %u\n",
  1833. (setting.Dh == NULL ? NULL : setting.Dh->Name), setting.Hash->Name, setting.Crypto->Name, setting.CryptoKeySize,
  1834. setting.LifeKilobytes, setting.LifeSeconds);
  1835. #ifdef FORCE_LIFETIME_QM
  1836. setting.LifeSeconds = FORCE_LIFETIME_QM;
  1837. #endif // FORCE_LIFETIME_QM
  1838. // Check the key exchange payload if the PFS is specified
  1839. if (setting.Dh == NULL || (setting.Dh != NULL && key_payload != NULL && ipsec_sa_sc->Dh != NULL &&
  1840. key_payload->Payload.KeyExchange.Data->Size <= setting.Dh->KeySize))
  1841. {
  1842. IKE_PACKET *ps;
  1843. LIST *payload_list;
  1844. IKE_PACKET_PAYLOAD *send_hash_payload;
  1845. IKE_PACKET_PAYLOAD *send_key_payload = NULL;
  1846. IKE_PACKET_PAYLOAD *send_id_1 = NULL, *send_id_2 = NULL;
  1847. DH_CTX *dh = NULL;
  1848. UINT shared_key_size = 0;
  1849. UCHAR *shared_key = NULL;
  1850. BUF *initiator_rand, *responder_rand;
  1851. BUF *tmp_buf;
  1852. UCHAR hash3[IKE_MAX_HASH_SIZE];
  1853. char tmp[MAX_SIZE];
  1854. UCHAR zero = 0;
  1855. initiator_rand = ipsec_sa_sc->InitiatorRand;
  1856. responder_rand = CloneBuf(rand_payload->Payload.Rand.Data);
  1857. if (setting.Dh != NULL)
  1858. {
  1859. // Calculate DH
  1860. DH_CTX *dh = ipsec_sa_sc->Dh;
  1861. shared_key_size = (dh == NULL ? 0 : dh->Size);
  1862. shared_key = ZeroMalloc(shared_key_size);
  1863. if (DhCompute(dh, shared_key, key_payload->Payload.KeyExchange.Data->Buf, key_payload->Payload.KeyExchange.Data->Size))
  1864. {
  1865. // DH calculation success
  1866. Debug("P2 DH Ok.\n");
  1867. }
  1868. else
  1869. {
  1870. // DH calculation failure
  1871. Debug("P2 DhCompute failed.\n");
  1872. shared_key = NULL;
  1873. Free(shared_key);
  1874. shared_key_size = 0;
  1875. IPsecLog(ike, NULL, ike_sa, NULL, "LI_QM_DH_ERROR");
  1876. }
  1877. }
  1878. // Update the information of IPsec SA
  1879. if (shared_key != NULL)
  1880. {
  1881. ipsec_sa_sc->SharedKey = NewBuf(shared_key, shared_key_size);
  1882. ipsec_sa_cs->SharedKey = NewBuf(shared_key, shared_key_size);
  1883. }
  1884. ipsec_sa_sc->Spi = setting.SpiServerToClient;
  1885. IPsecLog(ike, NULL, NULL, ipsec_sa_sc, "LI_IPSEC_SA_SPI_SET", ipsec_sa_sc->Spi);
  1886. ike->IPsecSaList->sorted = false;
  1887. ipsec_sa_sc->ResponderRand = CloneBuf(responder_rand);
  1888. ipsec_sa_cs->ResponderRand = CloneBuf(responder_rand);
  1889. Copy(&ipsec_sa_sc->TransformSetting, &setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
  1890. Copy(&ipsec_sa_cs->TransformSetting, &setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
  1891. ipsec_sa_sc->Established = true;
  1892. ipsec_sa_cs->Established = true;
  1893. IPsecLog(ike, NULL, NULL, ipsec_sa_sc, "LI_IPSEC_SA_ESTABLISHED");
  1894. ipsec_sa_sc->LastCommTick = ike->Now;
  1895. ipsec_sa_cs->LastCommTick = ike->Now;
  1896. c->CurrentIpSecSaRecv = ipsec_sa_cs;
  1897. c->CurrentIpSecSaSend = ipsec_sa_sc;
  1898. // Calculate the KEYMAT
  1899. IPsecCalcKeymat(ike, ipsec_sa_sc->SKEYID_Hash, ipsec_sa_sc->KeyMat, sizeof(ipsec_sa_sc->KeyMat),
  1900. ipsec_sa_sc->SKEYID_d, ipsec_sa_sc->SKEYID_Hash->HashSize, IKE_PROTOCOL_ID_IPSEC_ESP,
  1901. ipsec_sa_sc->Spi, initiator_rand->Buf, initiator_rand->Size,
  1902. responder_rand->Buf, responder_rand->Size,
  1903. shared_key, shared_key_size);
  1904. IPsecCalcKeymat(ike, ipsec_sa_cs->SKEYID_Hash, ipsec_sa_cs->KeyMat, sizeof(ipsec_sa_cs->KeyMat),
  1905. ipsec_sa_cs->SKEYID_d, ipsec_sa_cs->SKEYID_Hash->HashSize, IKE_PROTOCOL_ID_IPSEC_ESP,
  1906. ipsec_sa_cs->Spi, initiator_rand->Buf, initiator_rand->Size,
  1907. responder_rand->Buf, responder_rand->Size,
  1908. shared_key, shared_key_size);
  1909. IkeFreeKey(ipsec_sa_sc->CryptoKey);
  1910. IkeFreeKey(ipsec_sa_cs->CryptoKey);
  1911. ipsec_sa_sc->CryptoKey = IkeNewKey(setting.Crypto, ipsec_sa_sc->KeyMat, setting.CryptoKeySize);
  1912. ipsec_sa_cs->CryptoKey = IkeNewKey(setting.Crypto, ipsec_sa_cs->KeyMat, setting.CryptoKeySize);
  1913. Copy(ipsec_sa_sc->HashKey, ipsec_sa_sc->KeyMat + setting.CryptoKeySize, setting.Hash->HashSize);
  1914. Copy(ipsec_sa_cs->HashKey, ipsec_sa_cs->KeyMat + setting.CryptoKeySize, setting.Hash->HashSize);
  1915. BinToStrEx(tmp, sizeof(tmp), ipsec_sa_sc->KeyMat, ipsec_sa_sc->TransformSetting.CryptoKeySize);
  1916. Debug(" KEYMAT (SC): %s\n", tmp);
  1917. BinToStrEx(tmp, sizeof(tmp), ipsec_sa_cs->KeyMat, ipsec_sa_cs->TransformSetting.CryptoKeySize);
  1918. Debug(" KEYMAT (CS): %s\n", tmp);
  1919. Debug("IPsec SA 0x%X & 0x%X Established (Server is Initiator).\n",
  1920. ipsec_sa_cs->Spi,
  1921. ipsec_sa_sc->Spi);
  1922. // Calculate the hash #3
  1923. tmp_buf = NewBuf();
  1924. WriteBuf(tmp_buf, &zero, 1);
  1925. WriteBufInt(tmp_buf, header->MessageId);
  1926. WriteBufBuf(tmp_buf, initiator_rand);
  1927. WriteBufBuf(tmp_buf, responder_rand);
  1928. IkeHMac(ipsec_sa_cs->SKEYID_Hash, hash3, ipsec_sa_cs->SKEYID_a, ipsec_sa_cs->SKEYID_Hash->HashSize, tmp_buf->Buf, tmp_buf->Size);
  1929. FreeBuf(tmp_buf);
  1930. // Return the hash #3
  1931. send_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, hash3, ipsec_sa_cs->SKEYID_Hash->HashSize);
  1932. payload_list = NewListSingle(send_hash_payload);
  1933. ps = IkeNew(ike_sa->InitiatorCookie, ike_sa->ResponderCookie,
  1934. IKE_EXCHANGE_TYPE_QUICK, true, false, false, header->MessageId, payload_list);
  1935. IPsecSaSendPacket(ike, ipsec_sa_sc, ps);
  1936. #ifdef RAW_DEBUG
  1937. IkeDebugUdpSendRawPacket(ps);
  1938. #endif // RAW_DEBUG
  1939. ipsec_sa_sc->NumResends = 3;
  1940. if (false)
  1941. {
  1942. UINT i;
  1943. for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
  1944. {
  1945. IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
  1946. if (sa != ipsec_sa_sc && sa != ipsec_sa_cs)
  1947. {
  1948. MarkIPsecSaAsDeleted(ike, sa);
  1949. }
  1950. }
  1951. }
  1952. IkeFree(ps);
  1953. // Release the memory
  1954. FreeBuf(responder_rand);
  1955. }
  1956. }
  1957. else
  1958. {
  1959. // No appropriate transform setting
  1960. Debug("No Appropriate Transform was Found.\n");
  1961. IPsecLog(ike, NULL, ike_sa, NULL, "LI_IPSEC_NO_TRANSFORM");
  1962. SendInformationalExchangePacket(ike, c, IkeNewNoticeErrorNoProposalChosenPayload(true, header->InitiatorCookie, header->ResponderCookie));
  1963. }
  1964. }
  1965. }
  1966. }
  1967. }
  1968. }
  1969. IkeFree(pr);
  1970. }
  1971. }
  1972. }
  1973. }
  1974. }
  1975. }
  1976. }
  1977. // Calculate the KEYMAT
  1978. void IPsecCalcKeymat(IKE_SERVER *ike, IKE_HASH *h, void *dst, UINT dst_size, void *skeyid_d_data, UINT skeyid_d_size, UCHAR protocol, UINT spi, void *rand_init_data, UINT rand_init_size,
  1979. void *rand_resp_data, UINT rand_resp_size, void *df_key_data, UINT df_key_size)
  1980. {
  1981. BUF *k;
  1982. BUF *ret;
  1983. // Validate arguments
  1984. if (ike == NULL || dst == NULL || h == NULL || rand_init_data == NULL || rand_resp_data == NULL||
  1985. (df_key_size != 0 && df_key_data == NULL))
  1986. {
  1987. return;
  1988. }
  1989. ret = NewBuf();
  1990. k = NULL;
  1991. while (true)
  1992. {
  1993. BUF *tmp = NewBuf();
  1994. UCHAR hash[IKE_MAX_HASH_SIZE];
  1995. if (k != NULL)
  1996. {
  1997. WriteBufBuf(tmp, k);
  1998. }
  1999. if (df_key_data != NULL)
  2000. {
  2001. WriteBuf(tmp, df_key_data, df_key_size);
  2002. }
  2003. WriteBuf(tmp, &protocol, 1);
  2004. WriteBufInt(tmp, spi);
  2005. WriteBuf(tmp, rand_init_data, rand_init_size);
  2006. WriteBuf(tmp, rand_resp_data, rand_resp_size);
  2007. if (k != NULL)
  2008. {
  2009. FreeBuf(k);
  2010. }
  2011. IkeHMac(h, hash, skeyid_d_data, skeyid_d_size, tmp->Buf, tmp->Size);
  2012. FreeBuf(tmp);
  2013. k = MemToBuf(hash, h->HashSize);
  2014. WriteBufBuf(ret, k);
  2015. if (ret->Size >= dst_size)
  2016. {
  2017. break;
  2018. }
  2019. }
  2020. Copy(dst, ret->Buf, dst_size);
  2021. FreeBuf(ret);
  2022. FreeBuf(k);
  2023. }
  2024. // Search for IPsec SA from Message ID
  2025. IPSECSA *SearchIPsecSaByMessageId(IKE_SERVER *ike, IKE_CLIENT *c, UINT message_id)
  2026. {
  2027. UINT i;
  2028. // Validate arguments
  2029. if (ike == NULL || c == NULL || message_id == 0)
  2030. {
  2031. return NULL;
  2032. }
  2033. for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
  2034. {
  2035. IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
  2036. if (sa->IkeClient == c)
  2037. {
  2038. if (sa->MessageId == message_id)
  2039. {
  2040. if (sa->ServerToClient == false)
  2041. {
  2042. if (sa->Established == false)
  2043. {
  2044. return sa;
  2045. }
  2046. }
  2047. }
  2048. }
  2049. }
  2050. return NULL;
  2051. }
  2052. // Search for IPsec SA from SPI value
  2053. IPSECSA *SearchClientToServerIPsecSaBySpi(IKE_SERVER *ike, UINT spi)
  2054. {
  2055. IPSECSA t;
  2056. // Validate arguments
  2057. if (ike == NULL || spi == 0)
  2058. {
  2059. return NULL;
  2060. }
  2061. t.ServerToClient = false;
  2062. t.Spi = spi;
  2063. return Search(ike->IPsecSaList, &t);
  2064. }
  2065. IPSECSA *SearchIPsecSaBySpi(IKE_SERVER *ike, IKE_CLIENT *c, UINT spi)
  2066. {
  2067. UINT i;
  2068. // Validate arguments
  2069. if (ike == NULL || c == NULL || spi == 0)
  2070. {
  2071. return NULL;
  2072. }
  2073. for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
  2074. {
  2075. IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
  2076. if (sa->Spi == spi)
  2077. {
  2078. if (sa->IkeClient == c)
  2079. {
  2080. return sa;
  2081. }
  2082. }
  2083. }
  2084. return NULL;
  2085. }
  2086. // Search an IKE SA from the value of the Cookie
  2087. IKE_SA *SearchIkeSaByCookie(IKE_SERVER *ike, UINT64 init_cookie, UINT64 resp_cookie)
  2088. {
  2089. UINT i;
  2090. // Validate arguments
  2091. if (ike == NULL)
  2092. {
  2093. return NULL;
  2094. }
  2095. for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
  2096. {
  2097. IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
  2098. if (sa->InitiatorCookie == init_cookie && sa->ResponderCookie == resp_cookie)
  2099. {
  2100. return sa;
  2101. }
  2102. }
  2103. return NULL;
  2104. }
  2105. // Generate the SPI value of new IPsec SA
  2106. UINT GenerateNewIPsecSaSpi(IKE_SERVER *ike, UINT counterpart_spi)
  2107. {
  2108. UINT ret;
  2109. // Validate arguments
  2110. if (ike == NULL)
  2111. {
  2112. return 0;
  2113. }
  2114. while (true)
  2115. {
  2116. ret = Rand32();
  2117. if (ret != counterpart_spi)
  2118. {
  2119. if (ret >= 4096 && ret != INFINITE)
  2120. {
  2121. if (SearchClientToServerIPsecSaBySpi(ike, ret) == NULL)
  2122. {
  2123. return ret;
  2124. }
  2125. }
  2126. }
  2127. }
  2128. }
  2129. // Calculate the initial IV for Phase 2
  2130. void IkeCalcPhase2InitialIv(void *iv, IKE_SA *sa, UINT message_id)
  2131. {
  2132. BUF *b;
  2133. UCHAR hash[IKE_MAX_HASH_SIZE];
  2134. // Validate arguments
  2135. if (iv == NULL || sa == NULL)
  2136. {
  2137. return;
  2138. }
  2139. message_id = Endian32(message_id);
  2140. b = NewBuf();
  2141. WriteBuf(b, sa->Iv, sa->BlockSize);
  2142. WriteBuf(b, &message_id, sizeof(UINT));
  2143. IkeHash(sa->TransformSetting.Hash, hash, b->Buf, b->Size);
  2144. Copy(iv, hash, sa->TransformSetting.Crypto->BlockSize);
  2145. FreeBuf(b);
  2146. }
  2147. // Create a new IPsec SA
  2148. IPSECSA *NewIPsecSa(IKE_SERVER *ike, IKE_CLIENT *c, IKE_SA *ike_sa, bool initiate, UINT message_id, bool server_to_client, void *iv, UINT spi, void *init_rand_data, UINT init_rand_size, void *res_rand_data, UINT res_rand_size, IPSEC_SA_TRANSFORM_SETTING *setting, void *shared_key_data, UINT shared_key_size)
  2149. {
  2150. IPSECSA *sa;
  2151. char tmp[MAX_SIZE];
  2152. UINT total_key_size;
  2153. // Validate arguments
  2154. if (ike == NULL || c == NULL || ike_sa == NULL || message_id == 0 || iv == NULL || setting == NULL ||
  2155. (shared_key_data == NULL && shared_key_size != 0))
  2156. {
  2157. return NULL;
  2158. }
  2159. sa = ZeroMalloc(sizeof(IPSECSA));
  2160. if (server_to_client == false)
  2161. {
  2162. ike->CurrentIPsecSaId++;
  2163. }
  2164. sa->Id = ike->CurrentIPsecSaId;
  2165. sa->IkeClient = c;
  2166. sa->IkeSa = ike_sa;
  2167. sa->MessageId = message_id;
  2168. sa->FirstCommTick = ike->Now;
  2169. sa->LastCommTick = ike->Now;
  2170. sa->Initiated = initiate;
  2171. sa->ServerToClient = server_to_client;
  2172. sa->Spi = spi;
  2173. sa->SKEYID_Hash = ike_sa->TransformSetting.Hash;
  2174. Copy(sa->SKEYID_a, ike_sa->SKEYID_a, sa->SKEYID_Hash->HashSize);
  2175. Copy(sa->SKEYID_d, ike_sa->SKEYID_d, sa->SKEYID_Hash->HashSize);
  2176. sa->InitiatorRand = MemToBuf(init_rand_data, init_rand_size);
  2177. if (initiate == false)
  2178. {
  2179. sa->ResponderRand = MemToBuf(res_rand_data, res_rand_size);
  2180. }
  2181. Copy(sa->Iv, iv, ike_sa->BlockSize);
  2182. Copy(&sa->TransformSetting, setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
  2183. if (shared_key_data != NULL)
  2184. {
  2185. sa->SharedKey = MemToBuf(shared_key_data, shared_key_size);
  2186. }
  2187. total_key_size = sa->TransformSetting.CryptoKeySize + sa->TransformSetting.Hash->HashSize;
  2188. if (initiate == false)
  2189. {
  2190. IPsecCalcKeymat(ike, ike_sa->TransformSetting.Hash, sa->KeyMat, total_key_size,
  2191. ike_sa->SKEYID_d, ike_sa->HashSize, IKE_PROTOCOL_ID_IPSEC_ESP, spi, sa->InitiatorRand->Buf,
  2192. sa->InitiatorRand->Size, sa->ResponderRand->Buf, sa->ResponderRand->Size,
  2193. shared_key_data, shared_key_size);
  2194. sa->CryptoKey = IkeNewKey(sa->TransformSetting.Crypto, sa->KeyMat, sa->TransformSetting.CryptoKeySize);
  2195. Copy(sa->HashKey, sa->KeyMat + sa->TransformSetting.CryptoKeySize, sa->TransformSetting.Hash->HashSize);
  2196. }
  2197. Debug("New IPsec SA (StoC = %u): 0x%X 0x%X (%s %s %s(%u) %u %u)\n",
  2198. sa->ServerToClient,
  2199. sa->MessageId,
  2200. sa->Spi,
  2201. (setting->Dh == NULL ? NULL : setting->Dh->Name), setting->Hash->Name, setting->Crypto->Name, setting->CryptoKeySize,
  2202. setting->LifeKilobytes, setting->LifeSeconds);
  2203. IPsecLog(ike, c, NULL, sa, "LI_NEW_IPSEC_SA",
  2204. (sa->ServerToClient ? _UU("LI_TAG_SERVER_TO_CLIENT") : _UU("LI_TAG_CLIENT_TO_SERVER")),
  2205. sa->Spi,
  2206. (setting->Dh == NULL ? NULL : setting->Dh->Name), setting->Hash->Name, setting->Crypto->Name, setting->CryptoKeySize * 8,
  2207. setting->LifeKilobytes, setting->LifeSeconds);
  2208. Rand(sa->EspIv, sizeof(sa->EspIv));
  2209. if (initiate == false)
  2210. {
  2211. BinToStrEx(tmp, sizeof(tmp), sa->KeyMat, sa->TransformSetting.CryptoKeySize);
  2212. Debug(" KEYMAT: %s\n", tmp);
  2213. }
  2214. // Set the expiration time
  2215. if (setting->LifeSeconds != 0)
  2216. {
  2217. const UINT64 span = (UINT64)((UINT64)setting->LifeSeconds * (UINT64)1000) + (UINT64)IKE_SOFT_EXPIRES_MARGIN;
  2218. sa->ExpiresHardTick = ike->Now + span;
  2219. sa->ExpiresSoftTick = ike->Now + span;
  2220. //sa->ExpiresSoftTick = ike->Now + (UINT64)5000;
  2221. AddInterrupt(ike->Interrupts, sa->ExpiresSoftTick);
  2222. }
  2223. return sa;
  2224. }
  2225. // Treat aggressive mode packet reception
  2226. void ProcIkeAggressiveModePacketRecv(IKE_SERVER *ike, UDPPACKET *p, IKE_PACKET *header)
  2227. {
  2228. IKE_CLIENT *c;
  2229. char tmp[MAX_SIZE];
  2230. // Validate arguments
  2231. if (ike == NULL || p == NULL || header == NULL || header->InitiatorCookie == 0)
  2232. {
  2233. return;
  2234. }
  2235. c = SearchOrCreateNewIkeClientForIkePacket(ike, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort, header);
  2236. if (c == NULL)
  2237. {
  2238. return;
  2239. }
  2240. if (header->ResponderCookie == 0)
  2241. {
  2242. // Start process of the state 1
  2243. IKE_CAPS caps;
  2244. IKE_SA *sa;
  2245. IKE_PACKET *pr = IkeParse(p->Data, p->Size, NULL);
  2246. if (pr != NULL)
  2247. {
  2248. // Determine the CAPS
  2249. IkeCheckCaps(&caps, pr);
  2250. if (caps.MS_L2TPIPSecVPNClient || caps.MS_NT5_ISAKMP_OAKLEY || caps.MS_Vid_InitialContact)
  2251. {
  2252. c->IsMicrosoft = true;
  2253. }
  2254. if ((caps.NatTraversalDraftIetf || caps.NatTraversalRfc3947) || (IsUdpPortOpened(ike->IPsec->UdpListener, &p->DstIP, IPSEC_PORT_IPSEC_ESP_RAW)))
  2255. {
  2256. sa = FindIkeSaByEndPointAndInitiatorCookie(ike, &p->DstIP, p->DestPort, &p->SrcIP, p->SrcPort, header->InitiatorCookie, IKE_SA_AGGRESSIVE_MODE);
  2257. if (sa == NULL)
  2258. {
  2259. // Check whether there is acceptable SA parameters by analyzing proposed parameters
  2260. IKE_SA_TRANSFORM_SETTING setting;
  2261. if (GetBestTransformSettingForIkeSa(ike, pr, &setting) && (GetNumberOfIkeSaOfIkeClient(ike, c) <= IKE_QUOTA_MAX_SA_PER_CLIENT))
  2262. {
  2263. IKE_PACKET_PAYLOAD *tp;
  2264. IKE_PACKET_PAYLOAD *pp;
  2265. IKE_PACKET_PAYLOAD *sap;
  2266. IKE_PACKET_PAYLOAD *client_sa_payload;
  2267. IKE_PACKET_PAYLOAD *your_key_payload;
  2268. IKE_PACKET_PAYLOAD *your_rand_payload;
  2269. IKE_PACKET_PAYLOAD *your_id_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 0);
  2270. // Appropriate transform setting is selected
  2271. Debug("P1 Transform: %s %s %s(%u) %u %u\n",
  2272. setting.Dh->Name, setting.Hash->Name, setting.Crypto->Name, setting.CryptoKeySize,
  2273. setting.LifeKilobytes, setting.LifeSeconds);
  2274. // Receive a key exchange packet
  2275. your_key_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_KEY_EXCHANGE, 0);
  2276. your_rand_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_RAND, 0);
  2277. if (your_key_payload != NULL && your_rand_payload != NULL && your_id_payload != NULL)
  2278. {
  2279. // Check the key payload
  2280. BUF *your_key_buf = your_key_payload->Payload.KeyExchange.Data;
  2281. BUF *your_rand_buf = your_rand_payload->Payload.Rand.Data;
  2282. // DH generation
  2283. DH_CTX *dh = IkeDhNewCtx(setting.Dh);
  2284. UINT shared_key_size = (dh == NULL ? 0 : dh->Size);
  2285. UCHAR *shared_key = ZeroMalloc(shared_key_size);
  2286. // DH calculation
  2287. if (DhCompute(dh, shared_key, your_key_buf->Buf, your_key_buf->Size))
  2288. {
  2289. IKE_PACKET *ps;
  2290. LIST *payload_list;
  2291. IKE_PACKET_PAYLOAD *my_key_payload;
  2292. IKE_PACKET_PAYLOAD *my_rand_payload;
  2293. BUF *nat_buf1, *nat_buf2;
  2294. BUF *iv_buf;
  2295. UCHAR iv_hashed_data[IKE_MAX_HASH_SIZE];
  2296. UCHAR initiator_hash[IKE_MAX_HASH_SIZE];
  2297. BUF *b;
  2298. IKE_PACKET_PAYLOAD *my_id_payload, *my_hash_payload;
  2299. UCHAR responder_hash[IKE_MAX_HASH_SIZE];
  2300. BUF *idir_b;
  2301. IKE_PACKET_PAYLOAD *your_nat_d_1 = NULL;
  2302. IKE_PACKET_PAYLOAD *your_nat_d_2 = NULL;
  2303. // Create an IKE SA
  2304. sa = NewIkeSa(ike, c, header->InitiatorCookie, IKE_SA_AGGRESSIVE_MODE, &setting);
  2305. Copy(&sa->Caps, &caps, sizeof(IKE_CAPS));
  2306. sa->State= IKE_SA_AM_STATE_1_SA;
  2307. Insert(ike->IkeSaList, sa);
  2308. sa->HashSize = sa->TransformSetting.Hash->HashSize;
  2309. sa->KeySize = sa->TransformSetting.CryptoKeySize;
  2310. sa->BlockSize = sa->TransformSetting.Crypto->BlockSize;
  2311. // Get the Caps additionally
  2312. if (sa->Caps.NatTraversalRfc3947)
  2313. {
  2314. sa->Caps.UsingNatTraversalRfc3947 = true;
  2315. your_nat_d_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D, 0);
  2316. your_nat_d_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D, 1);
  2317. }
  2318. else if (sa->Caps.NatTraversalDraftIetf)
  2319. {
  2320. sa->Caps.UsingNatTraversalDraftIetf = true;
  2321. your_nat_d_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT, 0);
  2322. your_nat_d_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT, 1);
  2323. }
  2324. // Calculation success
  2325. sa->DhSharedKey = MemToBuf(shared_key, shared_key_size);
  2326. sa->InitiatorRand = RandBuf(IKE_SA_RAND_SIZE);
  2327. sa->ResponderRand = CloneBuf(your_rand_buf);
  2328. // Save a bit array of SA payload presented by the client
  2329. client_sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
  2330. sa->SAi_b = CloneBuf(client_sa_payload->BitArray);
  2331. // Save the ID payload presented by the client
  2332. sa->YourIDPayloadForAM = CloneBuf(your_id_payload->BitArray);
  2333. //// Assemble the SA payload
  2334. // Construct transform payload
  2335. tp = TransformSettingToTransformPayloadForIke(ike, &setting);
  2336. // Build a proposal payload
  2337. pp = IkeNewProposalPayload(1, IKE_PROTOCOL_ID_IKE, NULL, 0, NewListSingle(tp));
  2338. // Build the SA payload
  2339. sap = IkeNewSaPayload(NewListSingle(pp));
  2340. payload_list = NewListSingle(sap);
  2341. // Send a key exchange packet
  2342. my_key_payload = IkeNewDataPayload(IKE_PAYLOAD_KEY_EXCHANGE, dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
  2343. my_rand_payload = IkeNewDataPayload(IKE_PAYLOAD_RAND, sa->InitiatorRand->Buf, sa->InitiatorRand->Size);
  2344. Add(payload_list, my_key_payload);
  2345. Add(payload_list, my_rand_payload);
  2346. // NAT-D Packet
  2347. // Address of the opponent. Randomize in order to be forced to use NAT
  2348. nat_buf1 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash, Rand64(), Rand64(), &c->ClientIP, Rand16());
  2349. // My address
  2350. if (c->IsMicrosoft == false || (your_nat_d_1 == NULL || your_nat_d_2 == NULL || your_nat_d_1->BitArray == NULL))
  2351. {
  2352. // Calculate exactly
  2353. nat_buf2 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash,
  2354. sa->InitiatorCookie, sa->ResponderCookie, &c->ServerIP, c->ServerPort);
  2355. }
  2356. else
  2357. {
  2358. // Parrot the NAT_D payload indicating myself I got from
  2359. // the other if it has connected from a Microsoft VPN Client
  2360. nat_buf2 = CloneBuf(your_nat_d_1->BitArray);
  2361. }
  2362. // Save DH information
  2363. sa->GXi = CloneBuf(your_key_buf);
  2364. sa->GXr = CloneBuf(dh->MyPublicKey);
  2365. // Calculate the key set
  2366. IkeCalcSaKeySet(ike, sa, NULL);
  2367. // Calculate the initiator side hash value
  2368. b = NewBuf();
  2369. WriteBufBuf(b, sa->GXi);
  2370. WriteBufBuf(b, sa->GXr);
  2371. WriteBufInt64(b, sa->InitiatorCookie);
  2372. WriteBufInt64(b, sa->ResponderCookie);
  2373. WriteBufBuf(b, sa->SAi_b);
  2374. WriteBufBuf(b, sa->YourIDPayloadForAM);
  2375. IkeHMac(sa->TransformSetting.Hash, initiator_hash, sa->SKEYID, sa->HashSize,
  2376. b->Buf, b->Size);
  2377. FreeBuf(b);
  2378. Copy(sa->InitiatorHashForAM, initiator_hash, sa->HashSize);
  2379. // Prepare the response ID payload
  2380. // Generate the ID payload
  2381. if (IsIP6(&sa->IkeClient->ServerIP))
  2382. {
  2383. // IPv6 address
  2384. my_id_payload = IkeNewIdPayload(IKE_ID_IPV6_ADDR, 0, 0, sa->IkeClient->ServerIP.ipv6_addr, 16);
  2385. }
  2386. else
  2387. {
  2388. // IPv4 address
  2389. my_id_payload = IkeNewIdPayload(IKE_ID_IPV4_ADDR, 0, 0, sa->IkeClient->ServerIP.addr, 4);
  2390. }
  2391. // Build the ID payload tentatively
  2392. idir_b = IkeBuildIdPayload(&my_id_payload->Payload.Id);
  2393. b = NewBuf();
  2394. WriteBufBuf(b, sa->GXr);
  2395. WriteBufBuf(b, sa->GXi);
  2396. WriteBufInt64(b, sa->ResponderCookie);
  2397. WriteBufInt64(b, sa->InitiatorCookie);
  2398. WriteBufBuf(b, sa->SAi_b);
  2399. WriteBufBuf(b, idir_b);
  2400. IkeHMac(sa->TransformSetting.Hash, responder_hash, sa->SKEYID, sa->HashSize,
  2401. b->Buf, b->Size);
  2402. FreeBuf(b);
  2403. FreeBuf(idir_b);
  2404. my_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, responder_hash, sa->HashSize);
  2405. Add(payload_list, my_id_payload);
  2406. Add(payload_list, my_hash_payload);
  2407. ps = IkeNew(sa->InitiatorCookie, sa->ResponderCookie, IKE_EXCHANGE_TYPE_AGGRESSIVE,
  2408. false, false, false, 0, payload_list);
  2409. // Add the vendor ID
  2410. IkeAddVendorIdPayloads(ps);
  2411. // NAT-D related
  2412. if (sa->Caps.UsingNatTraversalRfc3947)
  2413. {
  2414. // RFC-compliant
  2415. Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D, nat_buf1->Buf, nat_buf1->Size));
  2416. Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D, nat_buf2->Buf, nat_buf2->Size));
  2417. }
  2418. if (sa->Caps.UsingNatTraversalDraftIetf)
  2419. {
  2420. // Draft compliant
  2421. Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D_DRAFT, nat_buf1->Buf, nat_buf1->Size));
  2422. Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D_DRAFT, nat_buf2->Buf, nat_buf2->Size));
  2423. }
  2424. FreeBuf(nat_buf1);
  2425. FreeBuf(nat_buf2);
  2426. StrCpy(c->ClientId, sizeof(c->ClientId), your_id_payload->Payload.Id.StrData);
  2427. Debug("Client ID = %s\n", c->ClientId);
  2428. IPsecLog(ike, c, NULL, NULL, NULL, "LI_SET_CLIENT_ID", c->ClientId);
  2429. // Initial IV setting
  2430. iv_buf = NewBuf();
  2431. WriteBuf(iv_buf, your_key_buf->Buf, your_key_buf->Size);
  2432. WriteBuf(iv_buf, dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
  2433. IkeHash(sa->TransformSetting.Hash, iv_hashed_data, iv_buf->Buf, iv_buf->Size);
  2434. BinToStrEx(tmp, sizeof(tmp), iv_hashed_data, sa->BlockSize);
  2435. Debug("Initial IV: %s\n", tmp);
  2436. IkeSaUpdateIv(sa, iv_hashed_data, sa->HashSize);
  2437. FreeBuf(iv_buf);
  2438. // Transmission
  2439. IkeSaSendPacket(ike, sa, ps);
  2440. IkeFree(ps);
  2441. }
  2442. else
  2443. {
  2444. // DH calculation failure
  2445. Debug("DhCompute failed.\n");
  2446. }
  2447. Free(shared_key);
  2448. DhFree(dh);
  2449. }
  2450. }
  2451. else
  2452. {
  2453. // No appropriate transform setting
  2454. Debug("No Appropriate Transform was Found.\n");
  2455. IPsecLog(ike, c, NULL, NULL, "LI_IKE_NO_TRANSFORM");
  2456. SendInformationalExchangePacket(ike, c, IkeNewNoticeErrorNoProposalChosenPayload(false, header->InitiatorCookie, header->ResponderCookie));
  2457. }
  2458. }
  2459. }
  2460. else
  2461. {
  2462. // Client does not support NAT Traversal
  2463. Debug("Client doesn't support NAT-T.\n");
  2464. IPsecLog(ike, c, NULL, NULL, "LI_IKE_NO_NAT_T");
  2465. }
  2466. IkeFree(pr);
  2467. }
  2468. }
  2469. else
  2470. {
  2471. // Process of state 2
  2472. IKE_SA *sa;
  2473. sa = FindIkeSaByResponderCookieAndClient(ike, header->ResponderCookie, c);
  2474. if (sa == NULL)
  2475. {
  2476. SendInformationalExchangePacketEx(ike, c, IkeNewNoticeErrorInvalidCookiePayload(header->InitiatorCookie,
  2477. header->ResponderCookie), true, header->InitiatorCookie, header->ResponderCookie);
  2478. }
  2479. if (sa != NULL && sa->Mode == IKE_SA_AGGRESSIVE_MODE)
  2480. {
  2481. IKE_PACKET *pr = NULL;
  2482. sa->LastCommTick = ike->Now;
  2483. switch (sa->State)
  2484. {
  2485. case IKE_SA_AM_STATE_1_SA:
  2486. pr = IkeSaRecvPacket(ike, sa, p->Data, p->Size);
  2487. if (pr != NULL)
  2488. {
  2489. IKE_PACKET_PAYLOAD *your_hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
  2490. if (your_hash_payload != NULL)
  2491. {
  2492. // Compare the hash
  2493. if (IkeCompareHash(your_hash_payload, sa->InitiatorHashForAM, sa->HashSize))
  2494. {
  2495. // Transit to the established state
  2496. Debug("IKE SA 0x%X Established.\n", sa);
  2497. sa->State = IKE_SA_AM_STATE_2_ESTABLISHED;
  2498. sa->EstablishedTick = ike->Now;
  2499. sa->Established = true;
  2500. c->CurrentIkeSa = sa;
  2501. c->NextDpdSendTick = ike->Now + (UINT64)IKE_INTERVAL_DPD_KEEPALIVE;
  2502. StrCpy(c->Secret, sizeof(c->Secret), sa->Secret);
  2503. IPsecLog(ike, NULL, sa, NULL, "LI_IKE_SA_ESTABLISHED");
  2504. IkeSaSendPacket(ike, sa, NULL);
  2505. }
  2506. else
  2507. {
  2508. Debug("IKE SA 0x%X Invalid Hash.\n", sa);
  2509. }
  2510. }
  2511. }
  2512. break;
  2513. }
  2514. if (pr != NULL)
  2515. {
  2516. IkeFree(pr);
  2517. }
  2518. }
  2519. }
  2520. }
  2521. // Process of the main mode packet reception
  2522. void ProcIkeMainModePacketRecv(IKE_SERVER *ike, UDPPACKET *p, IKE_PACKET *header)
  2523. {
  2524. IKE_CLIENT *c;
  2525. char tmp[MAX_SIZE];
  2526. // Validate arguments
  2527. if (ike == NULL || p == NULL || header == NULL || header->InitiatorCookie == 0)
  2528. {
  2529. return;
  2530. }
  2531. c = SearchOrCreateNewIkeClientForIkePacket(ike, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort, header);
  2532. if (c == NULL)
  2533. {
  2534. return;
  2535. }
  2536. if (header->ResponderCookie == 0)
  2537. {
  2538. // Start process of the state 1
  2539. IKE_CAPS caps;
  2540. IKE_SA *sa;
  2541. IKE_PACKET *pr = IkeParse(p->Data, p->Size, NULL);
  2542. if (pr != NULL)
  2543. {
  2544. // Determine the CAPS
  2545. IkeCheckCaps(&caps, pr);
  2546. if (caps.MS_L2TPIPSecVPNClient || caps.MS_NT5_ISAKMP_OAKLEY || caps.MS_Vid_InitialContact)
  2547. {
  2548. c->IsMicrosoft = true;
  2549. }
  2550. if ((caps.NatTraversalDraftIetf || caps.NatTraversalRfc3947) || (IsUdpPortOpened(ike->IPsec->UdpListener, &p->DstIP, IPSEC_PORT_IPSEC_ESP_RAW)))
  2551. {
  2552. sa = FindIkeSaByEndPointAndInitiatorCookie(ike, &p->DstIP, p->DestPort, &p->SrcIP, p->SrcPort, header->InitiatorCookie, IKE_SA_MAIN_MODE);
  2553. if (sa == NULL)
  2554. {
  2555. // Check whether there is acceptable SA parameters by analyzing proposed parameters
  2556. IKE_SA_TRANSFORM_SETTING setting;
  2557. if (GetBestTransformSettingForIkeSa(ike, pr, &setting) && (GetNumberOfIkeSaOfIkeClient(ike, c) <= IKE_QUOTA_MAX_SA_PER_CLIENT))
  2558. {
  2559. IKE_PACKET *ps;
  2560. IKE_PACKET_PAYLOAD *tp;
  2561. IKE_PACKET_PAYLOAD *pp;
  2562. IKE_PACKET_PAYLOAD *sap;
  2563. LIST *payload_list;
  2564. IKE_PACKET_PAYLOAD *client_sa_payload;
  2565. // Appropriate transform setting is selected
  2566. Debug("P1 Transform: %s %s %s(%u) %u %u\n",
  2567. setting.Dh->Name, setting.Hash->Name, setting.Crypto->Name, setting.CryptoKeySize,
  2568. setting.LifeKilobytes, setting.LifeSeconds);
  2569. #ifdef FORCE_LIFETIME_MM
  2570. setting.LifeSeconds = FORCE_LIFETIME_MM;
  2571. #endif // FORCE_LIFETIME_MM
  2572. // Create an IKE SA
  2573. sa = NewIkeSa(ike, c, header->InitiatorCookie, IKE_SA_MAIN_MODE, &setting);
  2574. Copy(&sa->Caps, &caps, sizeof(IKE_CAPS));
  2575. Insert(ike->IkeSaList, sa);
  2576. // Answer the SA parameter selection results
  2577. sa->State = IKE_SA_MM_STATE_1_SA;
  2578. // Save a bit array of SA payload presented by the client
  2579. client_sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
  2580. sa->SAi_b = CloneBuf(client_sa_payload->BitArray);
  2581. //// Assemble the SA payload
  2582. // Construct a transform payload
  2583. tp = TransformSettingToTransformPayloadForIke(ike, &setting);
  2584. // Build a proposal payload
  2585. pp = IkeNewProposalPayload(1, IKE_PROTOCOL_ID_IKE, NULL, 0, NewListSingle(tp));
  2586. // Build a SA payload
  2587. sap = IkeNewSaPayload(NewListSingle(pp));
  2588. payload_list = NewListSingle(sap);
  2589. ps = IkeNew(sa->InitiatorCookie, sa->ResponderCookie, IKE_EXCHANGE_TYPE_MAIN,
  2590. false, false, false, 0, payload_list);
  2591. // Add the vendor ID payload
  2592. IkeAddVendorIdPayloads(ps);
  2593. IkeSaSendPacket(ike, sa, ps);
  2594. sa->HashSize = sa->TransformSetting.Hash->HashSize;
  2595. sa->KeySize = sa->TransformSetting.CryptoKeySize;
  2596. sa->BlockSize = sa->TransformSetting.Crypto->BlockSize;
  2597. IkeFree(ps);
  2598. }
  2599. else
  2600. {
  2601. // No appropriate transform setting
  2602. Debug("No Appropriate Transform was Found.\n");
  2603. IPsecLog(ike, c, NULL, NULL, "LI_IKE_NO_TRANSFORM");
  2604. SendInformationalExchangePacket(ike, c, IkeNewNoticeErrorNoProposalChosenPayload(false, header->InitiatorCookie, header->ResponderCookie));
  2605. }
  2606. }
  2607. else
  2608. {
  2609. // Ignore for IKE SA which already exists (Because it's likely to be a re-transmission)
  2610. }
  2611. }
  2612. else
  2613. {
  2614. // It does not support NAT Traversal
  2615. Debug("Client doesn't support NAT-T.\n");
  2616. IPsecLog(ike, c, NULL, NULL, "LI_IKE_NO_NAT_T");
  2617. }
  2618. IkeFree(pr);
  2619. }
  2620. }
  2621. else
  2622. {
  2623. // Process of state 2 or later
  2624. IKE_SA *sa;
  2625. sa = FindIkeSaByResponderCookieAndClient(ike, header->ResponderCookie, c);
  2626. if (sa == NULL)
  2627. {
  2628. SendInformationalExchangePacketEx(ike, c, IkeNewNoticeErrorInvalidCookiePayload(header->InitiatorCookie,
  2629. header->ResponderCookie), true, header->InitiatorCookie, header->ResponderCookie);
  2630. }
  2631. if (sa != NULL && sa->Mode == IKE_SA_MAIN_MODE)
  2632. {
  2633. IKE_PACKET *pr = NULL;
  2634. sa->LastCommTick = ike->Now;
  2635. switch (sa->State)
  2636. {
  2637. case IKE_SA_MM_STATE_1_SA:
  2638. pr = IkeSaRecvPacket(ike, sa, p->Data, p->Size);
  2639. if (pr != NULL)
  2640. {
  2641. // Receive a key exchange packet
  2642. IKE_PACKET_PAYLOAD *your_key_payload;
  2643. IKE_PACKET_PAYLOAD *your_rand_payload;
  2644. IKE_PACKET_PAYLOAD *your_nat_d_1 = NULL;
  2645. IKE_PACKET_PAYLOAD *your_nat_d_2 = NULL;
  2646. your_key_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_KEY_EXCHANGE, 0);
  2647. your_rand_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_RAND, 0);
  2648. if (IkeGetPayloadNum(pr->PayloadList, IKE_PAYLOAD_NAT_D) != 0)
  2649. {
  2650. sa->Caps.UsingNatTraversalRfc3947 = true;
  2651. your_nat_d_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D, 0);
  2652. your_nat_d_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D, 1);
  2653. }
  2654. if (IkeGetPayloadNum(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT) != 0)
  2655. {
  2656. sa->Caps.UsingNatTraversalDraftIetf = true;
  2657. your_nat_d_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT, 0);
  2658. your_nat_d_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT, 1);
  2659. }
  2660. if (your_key_payload != NULL && your_rand_payload != NULL)
  2661. {
  2662. // Check the key payload
  2663. BUF *your_key_buf = your_key_payload->Payload.KeyExchange.Data;
  2664. BUF *your_rand_buf = your_rand_payload->Payload.Rand.Data;
  2665. // DH generation
  2666. DH_CTX *dh = IkeDhNewCtx(sa->TransformSetting.Dh);
  2667. UINT shared_key_size = (dh == NULL ? 0 : dh->Size);
  2668. UCHAR *shared_key = ZeroMalloc(shared_key_size);
  2669. // DH calculation
  2670. if (DhCompute(dh, shared_key, your_key_buf->Buf, your_key_buf->Size))
  2671. {
  2672. IKE_PACKET *ps;
  2673. LIST *payload_list;
  2674. IKE_PACKET_PAYLOAD *my_key_payload;
  2675. IKE_PACKET_PAYLOAD *my_rand_payload;
  2676. BUF *nat_buf1, *nat_buf2;
  2677. BUF *iv_buf;
  2678. UCHAR iv_hashed_data[IKE_MAX_HASH_SIZE];
  2679. // Calculation success
  2680. sa->DhSharedKey = MemToBuf(shared_key, shared_key_size);
  2681. sa->InitiatorRand = RandBuf(IKE_SA_RAND_SIZE);
  2682. sa->ResponderRand = CloneBuf(your_rand_buf);
  2683. // Send a key exchange packet
  2684. my_key_payload = IkeNewDataPayload(IKE_PAYLOAD_KEY_EXCHANGE, dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
  2685. my_rand_payload = IkeNewDataPayload(IKE_PAYLOAD_RAND, sa->InitiatorRand->Buf, sa->InitiatorRand->Size);
  2686. payload_list = NewListSingle(my_key_payload);
  2687. Add(payload_list, my_rand_payload);
  2688. // NAT-D packet
  2689. // Address of the opponent. Randomize in order to be forced to use NAT
  2690. nat_buf1 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash, Rand64(), Rand64(), &c->ClientIP, Rand16());
  2691. //nat_buf1 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash, sa->InitiatorCookie, sa->ResponderCookie, &c->ClientIP, c->ClientPort);
  2692. // My address
  2693. if (c->IsMicrosoft == false || (your_nat_d_1 == NULL || your_nat_d_2 == NULL || your_nat_d_1->BitArray == NULL))
  2694. {
  2695. // Calculate exactly
  2696. nat_buf2 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash,
  2697. sa->InitiatorCookie, sa->ResponderCookie, &c->ServerIP, c->ServerPort);
  2698. }
  2699. else
  2700. {
  2701. // Parrot the NAT_D payload indicating myself I got from
  2702. // the other if it has connected from a Microsoft VPN Client
  2703. nat_buf2 = CloneBuf(your_nat_d_1->BitArray);
  2704. }
  2705. if (sa->Caps.UsingNatTraversalRfc3947)
  2706. {
  2707. // RFC-compliant
  2708. Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D, nat_buf1->Buf, nat_buf1->Size));
  2709. Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D, nat_buf2->Buf, nat_buf2->Size));
  2710. }
  2711. if (sa->Caps.UsingNatTraversalDraftIetf)
  2712. {
  2713. // Draft compliant
  2714. Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D_DRAFT, nat_buf1->Buf, nat_buf1->Size));
  2715. Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D_DRAFT, nat_buf2->Buf, nat_buf2->Size));
  2716. }
  2717. FreeBuf(nat_buf1);
  2718. FreeBuf(nat_buf2);
  2719. ps = IkeNew(sa->InitiatorCookie, sa->ResponderCookie, IKE_EXCHANGE_TYPE_MAIN,
  2720. false, false, false, 0, payload_list);
  2721. // Initial IV setting
  2722. iv_buf = NewBuf();
  2723. WriteBuf(iv_buf, your_key_buf->Buf, your_key_buf->Size);
  2724. WriteBuf(iv_buf, dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
  2725. IkeHash(sa->TransformSetting.Hash, iv_hashed_data, iv_buf->Buf, iv_buf->Size);
  2726. BinToStrEx(tmp, sizeof(tmp), iv_hashed_data, sa->BlockSize);
  2727. Debug("Initial IV: %s\n", tmp);
  2728. IkeSaUpdateIv(sa, iv_hashed_data, sa->HashSize);
  2729. FreeBuf(iv_buf);
  2730. // Save the DH information
  2731. sa->GXi = CloneBuf(your_key_buf);
  2732. sa->GXr = CloneBuf(dh->MyPublicKey);
  2733. // Transmission
  2734. IkeSaSendPacket(ike, sa, ps);
  2735. IkeFree(ps);
  2736. // Calculate the key set
  2737. IkeCalcSaKeySet(ike, sa, NULL);
  2738. sa->State = IKE_SA_MM_STATE_2_KEY;
  2739. }
  2740. else
  2741. {
  2742. // DH calculation failure
  2743. Debug("DhCompute failed.\n");
  2744. }
  2745. Free(shared_key);
  2746. DhFree(dh);
  2747. }
  2748. }
  2749. break;
  2750. case IKE_SA_MM_STATE_2_KEY:
  2751. pr = IkeSaRecvPacket(ike, sa, p->Data, p->Size);
  2752. if (pr != NULL && pr->FlagEncrypted)
  2753. {
  2754. // Receive an ID exchange packet
  2755. IKE_PACKET_PAYLOAD *your_id_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 0);
  2756. IKE_PACKET_PAYLOAD *your_hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
  2757. if (your_id_payload && your_hash_payload)
  2758. {
  2759. UCHAR initiator_hash[IKE_MAX_HASH_SIZE];
  2760. BUF *b;
  2761. // Calculate the initiator side hash value
  2762. b = NewBuf();
  2763. WriteBufBuf(b, sa->GXi);
  2764. WriteBufBuf(b, sa->GXr);
  2765. WriteBufInt64(b, sa->InitiatorCookie);
  2766. WriteBufInt64(b, sa->ResponderCookie);
  2767. WriteBufBuf(b, sa->SAi_b);
  2768. WriteBufBuf(b, your_id_payload->BitArray);
  2769. StrCpy(c->ClientId, sizeof(c->ClientId), your_id_payload->Payload.Id.StrData);
  2770. Debug("Client ID = %s\n", c->ClientId);
  2771. IPsecLog(ike, c, NULL, NULL, NULL, "LI_SET_CLIENT_ID", c->ClientId);
  2772. IkeHMac(sa->TransformSetting.Hash, initiator_hash, sa->SKEYID, sa->HashSize,
  2773. b->Buf, b->Size);
  2774. FreeBuf(b);
  2775. // Hash comparison
  2776. if (IkeCompareHash(your_hash_payload, initiator_hash, sa->HashSize))
  2777. {
  2778. // Generate a response packet
  2779. IKE_PACKET *ps;
  2780. LIST *payload_list = NewListFast(NULL);
  2781. IKE_PACKET_PAYLOAD *my_id_payload, *my_hash_payload;
  2782. UCHAR responder_hash[IKE_MAX_HASH_SIZE];
  2783. BUF *idir_b;
  2784. // Generate an ID payload
  2785. if (IsIP6(&sa->IkeClient->ServerIP))
  2786. {
  2787. // IPv6 address
  2788. my_id_payload = IkeNewIdPayload(IKE_ID_IPV6_ADDR, 0, 0, sa->IkeClient->ServerIP.ipv6_addr, 16);
  2789. }
  2790. else
  2791. {
  2792. // IPv4 address
  2793. my_id_payload = IkeNewIdPayload(IKE_ID_IPV4_ADDR, 0, 0, sa->IkeClient->ServerIP.addr, 4);
  2794. }
  2795. // Build the ID payload tentatively
  2796. idir_b = IkeBuildIdPayload(&my_id_payload->Payload.Id);
  2797. // Generate the hash payload
  2798. b = NewBuf();
  2799. WriteBufBuf(b, sa->GXr);
  2800. WriteBufBuf(b, sa->GXi);
  2801. WriteBufInt64(b, sa->ResponderCookie);
  2802. WriteBufInt64(b, sa->InitiatorCookie);
  2803. WriteBufBuf(b, sa->SAi_b);
  2804. WriteBufBuf(b, idir_b);
  2805. IkeHMac(sa->TransformSetting.Hash, responder_hash, sa->SKEYID, sa->HashSize,
  2806. b->Buf, b->Size);
  2807. FreeBuf(b);
  2808. FreeBuf(idir_b);
  2809. my_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, responder_hash, sa->HashSize);
  2810. Add(payload_list, my_id_payload);
  2811. Add(payload_list, my_hash_payload);
  2812. ps = IkeNew(sa->InitiatorCookie, sa->ResponderCookie, IKE_EXCHANGE_TYPE_MAIN, true, false,
  2813. false, 0, payload_list);
  2814. // Transmission
  2815. IkeSaSendPacket(ike, sa, ps);
  2816. sa->NumResends = 3;
  2817. IkeFree(ps);
  2818. StrCpy(c->ClientId, sizeof(c->ClientId), your_id_payload->Payload.Id.StrData);
  2819. // Transit to the established state
  2820. Debug("IKE SA 0x%X Established. Client ID=%s\n", sa, c->ClientId);
  2821. sa->State = IKE_SA_MM_STATE_3_ESTABLISHED;
  2822. sa->EstablishedTick = ike->Now;
  2823. c->CurrentIkeSa = sa;
  2824. c->NextDpdSendTick = ike->Now + (UINT64)IKE_INTERVAL_DPD_KEEPALIVE;
  2825. StrCpy(c->Secret, sizeof(c->Secret), sa->Secret);
  2826. sa->Established = true;
  2827. IPsecLog(ike, NULL, sa, NULL, "LI_IKE_SA_ESTABLISHED");
  2828. }
  2829. else
  2830. {
  2831. Debug("IKE SA 0x%X Invalid Hash.\n", sa);
  2832. }
  2833. }
  2834. }
  2835. break;
  2836. }
  2837. if (pr != NULL)
  2838. {
  2839. IkeFree(pr);
  2840. }
  2841. }
  2842. }
  2843. }
  2844. // Update the IV of IPsec SA
  2845. void IPsecSaUpdateIv(IPSECSA *sa, void *iv, UINT iv_size)
  2846. {
  2847. // Validate arguments
  2848. if (sa == NULL || iv == NULL)
  2849. {
  2850. return;
  2851. }
  2852. Copy(sa->Iv, iv, MIN(sa->IkeSa->BlockSize, iv_size));
  2853. if (iv_size < sa->IkeSa->BlockSize)
  2854. {
  2855. Zero(sa->Iv + sa->IkeSa->BlockSize, sa->IkeSa->BlockSize - iv_size);
  2856. }
  2857. sa->IsIvExisting = true;
  2858. }
  2859. // Update the IV of the IKE SA
  2860. void IkeSaUpdateIv(IKE_SA *sa, void *iv, UINT iv_size)
  2861. {
  2862. // Validate arguments
  2863. if (sa == NULL || iv == NULL)
  2864. {
  2865. return;
  2866. }
  2867. Copy(sa->Iv, iv, MIN(sa->BlockSize, iv_size));
  2868. if (iv_size < sa->BlockSize)
  2869. {
  2870. Zero(sa->Iv + sa->BlockSize, sa->BlockSize - iv_size);
  2871. }
  2872. sa->IsIvExisting = true;
  2873. }
  2874. // Calculate the key set of the IKE SA
  2875. void IkeCalcSaKeySet(IKE_SERVER *ike, IKE_SA *sa, char *secret)
  2876. {
  2877. BUF *secret_buf;
  2878. BUF *rand_buf;
  2879. BUF *d_buf, *a_buf, *e_buf;
  2880. UCHAR u;
  2881. IKE_HASH *h;
  2882. char tmp[MAX_SIZE];
  2883. // Validate arguments
  2884. if (ike == NULL || sa == NULL)
  2885. {
  2886. return;
  2887. }
  2888. h = sa->TransformSetting.Hash;
  2889. // Calculation of SKEYID
  2890. StrCpy(sa->Secret, sizeof(sa->Secret), secret == NULL ? ike->Secret : secret);
  2891. secret_buf = IkeStrToPassword(sa->Secret);
  2892. rand_buf = CloneBuf(sa->ResponderRand);
  2893. SeekBufToEnd(rand_buf);
  2894. BinToStrEx(tmp, sizeof(tmp), rand_buf->Buf, rand_buf->Size);
  2895. Debug("ResponderRand: %s\n", tmp);
  2896. BinToStrEx(tmp, sizeof(tmp), sa->InitiatorRand->Buf, sa->InitiatorRand->Size);
  2897. Debug("InitiatorRand: %s\n", tmp);
  2898. WriteBufBuf(rand_buf, sa->InitiatorRand);
  2899. IkeHMacBuf(h, sa->SKEYID, secret_buf, rand_buf);
  2900. BinToStrEx(tmp, sizeof(tmp), sa->SKEYID, sa->HashSize);
  2901. Debug("SKEYID: %s\n", tmp);
  2902. // SKEYID_d
  2903. d_buf = CloneBuf(sa->DhSharedKey);
  2904. SeekBufToEnd(d_buf);
  2905. WriteBufInt64(d_buf, sa->InitiatorCookie);
  2906. WriteBufInt64(d_buf, sa->ResponderCookie);
  2907. u = 0;
  2908. WriteBuf(d_buf, &u, 1);
  2909. IkeHMac(h, sa->SKEYID_d, sa->SKEYID, sa->HashSize, d_buf->Buf, d_buf->Size);
  2910. BinToStrEx(tmp, sizeof(tmp), sa->SKEYID_d, sa->HashSize);
  2911. Debug("SKEYID_d: %s\n", tmp);
  2912. // SKEYID_a
  2913. a_buf = MemToBuf(sa->SKEYID_d, sa->HashSize);
  2914. SeekBufToEnd(a_buf);
  2915. WriteBufBuf(a_buf, sa->DhSharedKey);
  2916. WriteBufInt64(a_buf, sa->InitiatorCookie);
  2917. WriteBufInt64(a_buf, sa->ResponderCookie);
  2918. u = 1;
  2919. WriteBuf(a_buf, &u, 1);
  2920. IkeHMac(h, sa->SKEYID_a, sa->SKEYID, sa->HashSize, a_buf->Buf, a_buf->Size);
  2921. BinToStrEx(tmp, sizeof(tmp), sa->SKEYID_a, sa->HashSize);
  2922. Debug("SKEYID_a: %s\n", tmp);
  2923. // SKEYID_e
  2924. e_buf = MemToBuf(sa->SKEYID_a, sa->HashSize);
  2925. SeekBufToEnd(e_buf);
  2926. WriteBufBuf(e_buf, sa->DhSharedKey);
  2927. WriteBufInt64(e_buf, sa->InitiatorCookie);
  2928. WriteBufInt64(e_buf, sa->ResponderCookie);
  2929. u = 2;
  2930. WriteBuf(e_buf, &u, 1);
  2931. IkeHMac(h, sa->SKEYID_e, sa->SKEYID, sa->HashSize, e_buf->Buf, e_buf->Size);
  2932. BinToStrEx(tmp, sizeof(tmp), sa->SKEYID_e, sa->HashSize);
  2933. Debug("SKEYID_e: %s\n", tmp);
  2934. if (sa->CryptoKey != NULL)
  2935. {
  2936. IkeFreeKey(sa->CryptoKey);
  2937. }
  2938. sa->CryptoKey = IkeNewCryptoKeyFromK(ike, sa->SKEYID_e, sa->HashSize, sa->TransformSetting.Hash,
  2939. sa->TransformSetting.Crypto, sa->TransformSetting.CryptoKeySize);
  2940. // Release the memory
  2941. FreeBuf(secret_buf);
  2942. FreeBuf(rand_buf);
  2943. FreeBuf(d_buf);
  2944. FreeBuf(a_buf);
  2945. FreeBuf(e_buf);
  2946. }
  2947. // Extend the key size
  2948. BUF *IkeExpandKeySize(IKE_HASH *h, void *k, UINT k_size, UINT target_size)
  2949. {
  2950. BUF *b1, *b2;
  2951. UCHAR tmp[IKE_MAX_HASH_SIZE];
  2952. UINT tmp_size;
  2953. // Validate arguments
  2954. if (h == NULL || k == NULL || k_size == 0)
  2955. {
  2956. return NULL;
  2957. }
  2958. if (k_size >= target_size)
  2959. {
  2960. return MemToBuf(k, target_size);
  2961. }
  2962. tmp[0] = 0;
  2963. tmp_size = 1;
  2964. b1 = NewBuf();
  2965. do
  2966. {
  2967. IkeHMac(h, tmp, k, k_size, tmp, tmp_size);
  2968. WriteBuf(b1, tmp, h->HashSize);
  2969. tmp_size = h->HashSize;
  2970. }
  2971. while (b1->Size < target_size);
  2972. b2 = MemToBuf(b1->Buf, target_size);
  2973. FreeBuf(b1);
  2974. return b2;
  2975. }
  2976. // Generate a key from K
  2977. IKE_CRYPTO_KEY *IkeNewCryptoKeyFromK(IKE_SERVER *ike, void *k, UINT k_size, IKE_HASH *h, IKE_CRYPTO *c, UINT crypto_key_size)
  2978. {
  2979. BUF *key_buf;
  2980. IKE_CRYPTO_KEY *ret;
  2981. // Validate arguments
  2982. if (ike == NULL || k == NULL || k_size == 0 || h == NULL || c == NULL || crypto_key_size == 0)
  2983. {
  2984. return NULL;
  2985. }
  2986. key_buf = IkeExpandKeySize(h, k, k_size, crypto_key_size);
  2987. if (key_buf == NULL)
  2988. {
  2989. return NULL;
  2990. }
  2991. ret = IkeNewKey(c, key_buf->Buf, key_buf->Size);
  2992. FreeBuf(key_buf);
  2993. return ret;
  2994. }
  2995. // Generate a hash for NAT detection
  2996. BUF *IkeCalcNatDetectHash(IKE_SERVER *ike, IKE_HASH *hash, UINT64 initiator_cookie, UINT64 responder_cookie, IP *ip, UINT port)
  2997. {
  2998. BUF *b;
  2999. USHORT us;
  3000. USHORT hash_data[IKE_MAX_HASH_SIZE];
  3001. // Validate arguments
  3002. if (ike == NULL || ip == NULL || hash == NULL)
  3003. {
  3004. return NewBuf();
  3005. }
  3006. b = NewBuf();
  3007. WriteBufInt64(b, initiator_cookie);
  3008. WriteBufInt64(b, responder_cookie);
  3009. if (IsIP6(ip))
  3010. {
  3011. WriteBuf(b, ip->ipv6_addr, sizeof(ip->ipv6_addr));
  3012. }
  3013. else
  3014. {
  3015. WriteBuf(b, ip->addr, sizeof(ip->addr));
  3016. }
  3017. us = Endian16((USHORT)port);
  3018. WriteBuf(b, &us, sizeof(USHORT));
  3019. IkeHash(hash, hash_data, b->Buf, b->Size);
  3020. FreeBuf(b);
  3021. return MemToBuf(hash_data, hash->HashSize);
  3022. }
  3023. // Check the capacity of the opposite IPsec client
  3024. void IkeCheckCaps(IKE_CAPS *caps, IKE_PACKET *p)
  3025. {
  3026. // Validate arguments
  3027. if (caps == NULL || p == NULL)
  3028. {
  3029. Zero(caps, sizeof(IKE_CAPS));
  3030. return;
  3031. }
  3032. Zero(caps, sizeof(IKE_CAPS));
  3033. caps->NatTraversalRfc3947 = IkeIsVendorIdExists(p, IKE_VENDOR_ID_RFC3947_NAT_T);
  3034. caps->NatTraversalDraftIetf = IkeIsVendorIdExists(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_03) ||
  3035. IkeIsVendorIdExists(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_02) ||
  3036. IkeIsVendorIdExists(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_02_2) ||
  3037. IkeIsVendorIdExists(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_00);
  3038. caps->DpdRfc3706 = IkeIsVendorIdExists(p, IKE_VENDOR_ID_RFC3706_DPD);
  3039. caps->MS_L2TPIPSecVPNClient = IkeIsVendorIdExists(p, IKE_VENDOR_ID_MICROSOFT_L2TP);
  3040. caps->MS_NT5_ISAKMP_OAKLEY = IkeIsVendorIdExists(p, IKE_VENDOR_ID_MS_NT5_ISAKMPOAKLEY);
  3041. caps->MS_Vid_InitialContact = IkeIsVendorIdExists(p, IKE_VENDOR_ID_MS_VID_INITIALCONTACT);
  3042. }
  3043. // Check whether the specified vendor ID is contained in the packet
  3044. bool IkeIsVendorIdExists(IKE_PACKET *p, char *str)
  3045. {
  3046. BUF *buf;
  3047. UINT i, num;
  3048. bool ok = false;
  3049. // Validate arguments
  3050. if (p == NULL || str == NULL)
  3051. {
  3052. return false;
  3053. }
  3054. buf = IkeStrToVendorId(str);
  3055. if (buf == NULL)
  3056. {
  3057. return false;
  3058. }
  3059. num = IkeGetPayloadNum(p->PayloadList, IKE_PAYLOAD_VENDOR_ID);
  3060. for (i = 0;i < num;i++)
  3061. {
  3062. IKE_PACKET_PAYLOAD *payload = IkeGetPayload(p->PayloadList, IKE_PAYLOAD_VENDOR_ID, i);
  3063. if (payload == NULL)
  3064. {
  3065. break;
  3066. }
  3067. if (CompareBuf(payload->Payload.VendorId.Data, buf))
  3068. {
  3069. ok = true;
  3070. }
  3071. else
  3072. {
  3073. if (payload->Payload.VendorId.Data != NULL)
  3074. {
  3075. if (payload->Payload.VendorId.Data->Size >= buf->Size)
  3076. {
  3077. if (Cmp(payload->Payload.VendorId.Data->Buf, buf->Buf, buf->Size) == 0)
  3078. {
  3079. ok = true;
  3080. }
  3081. }
  3082. }
  3083. }
  3084. }
  3085. FreeBuf(buf);
  3086. return ok;
  3087. }
  3088. // Add the vendor ID payload list
  3089. void IkeAddVendorIdPayloads(IKE_PACKET *p)
  3090. {
  3091. // Validate arguments
  3092. if (p == NULL)
  3093. {
  3094. return;
  3095. }
  3096. IkeAddVendorId(p, IKE_VENDOR_ID_RFC3947_NAT_T);
  3097. IkeAddVendorId(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_03);
  3098. IkeAddVendorId(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_02);
  3099. IkeAddVendorId(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_02_2);
  3100. IkeAddVendorId(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_00);
  3101. IkeAddVendorId(p, IKE_VENDOR_ID_RFC3706_DPD);
  3102. }
  3103. // Add the vendor ID payload
  3104. void IkeAddVendorId(IKE_PACKET *p, char *str)
  3105. {
  3106. BUF *buf;
  3107. IKE_PACKET_PAYLOAD *payload;
  3108. // Validate arguments
  3109. if (p == NULL || str == NULL)
  3110. {
  3111. return;
  3112. }
  3113. buf = IkeStrToVendorId(str);
  3114. if (buf == NULL)
  3115. {
  3116. return;
  3117. }
  3118. payload = IkeNewDataPayload(IKE_PAYLOAD_VENDOR_ID, buf->Buf, buf->Size);
  3119. Add(p->PayloadList, payload);
  3120. FreeBuf(buf);
  3121. }
  3122. // Convert string to the vendor ID
  3123. BUF *IkeStrToVendorId(char *str)
  3124. {
  3125. // Validate arguments
  3126. if (IsEmptyStr(str))
  3127. {
  3128. return NULL;
  3129. }
  3130. if (StartWith(str, "0x"))
  3131. {
  3132. BUF *buf = StrToBin(str + 2);
  3133. if (buf == NULL || buf->Size == 0)
  3134. {
  3135. FreeBuf(buf);
  3136. return NULL;
  3137. }
  3138. return buf;
  3139. }
  3140. else
  3141. {
  3142. BUF *buf;
  3143. UCHAR hash[MD5_SIZE];
  3144. Md5(hash, str, StrLen(str));
  3145. buf = MemToBuf(hash, sizeof(hash));
  3146. return buf;
  3147. }
  3148. }
  3149. // Receive a packet using the IKE SA
  3150. IKE_PACKET *IkeSaRecvPacket(IKE_SERVER *ike, IKE_SA *sa, void *data, UINT size)
  3151. {
  3152. IKE_PACKET *ret;
  3153. // Validate arguments
  3154. if (ike == NULL || sa == NULL || (size != 0 && data == NULL))
  3155. {
  3156. return NULL;
  3157. }
  3158. if (sa->IsIvExisting == false || sa->CryptoKey == NULL)
  3159. {
  3160. ret = IkeParse(data, size, NULL);
  3161. }
  3162. else
  3163. {
  3164. IKE_CRYPTO_PARAM cp;
  3165. Copy(&cp.Iv, sa->Iv, sa->BlockSize);
  3166. cp.Key = sa->CryptoKey;
  3167. ret = IkeParse(data, size, &cp);
  3168. if (ret->FlagEncrypted)
  3169. {
  3170. IkeSaUpdateIv(sa, cp.NextIv, sa->BlockSize);
  3171. }
  3172. }
  3173. return ret;
  3174. }
  3175. // Receive a packet using IPsec SA (Quick Mode received)
  3176. IKE_PACKET *IPsecSaRecvPacket(IKE_SERVER *ike, IPSECSA *sa, void *data, UINT size)
  3177. {
  3178. IKE_PACKET *ret;
  3179. // Validate arguments
  3180. if (ike == NULL || sa == NULL || (size != 0 && data == NULL))
  3181. {
  3182. return NULL;
  3183. }
  3184. if (sa->IsIvExisting == false || sa->IkeSa->CryptoKey == NULL)
  3185. {
  3186. ret = IkeParse(data, size, NULL);
  3187. }
  3188. else
  3189. {
  3190. IKE_CRYPTO_PARAM cp;
  3191. Copy(&cp.Iv, sa->Iv, sa->IkeSa->BlockSize);
  3192. cp.Key = sa->IkeSa->CryptoKey;
  3193. ret = IkeParse(data, size, &cp);
  3194. if (ret->FlagEncrypted)
  3195. {
  3196. IPsecSaUpdateIv(sa, cp.NextIv, sa->IkeSa->BlockSize);
  3197. IPsecSaUpdateIv(sa->PairIPsecSa, cp.NextIv, sa->IkeSa->BlockSize);
  3198. }
  3199. }
  3200. return ret;
  3201. }
  3202. // Send a packet using IPsec SA (Quick Mode transmission)
  3203. void IPsecSaSendPacket(IKE_SERVER *ike, IPSECSA *sa, IKE_PACKET *p)
  3204. {
  3205. BUF *buf;
  3206. // Validate arguments
  3207. if (ike == NULL || sa == NULL)
  3208. {
  3209. return;
  3210. }
  3211. if (p == NULL)
  3212. {
  3213. FreeBuf(sa->SendBuffer);
  3214. sa->SendBuffer = NULL;
  3215. sa->NextSendTick = 0;
  3216. return;
  3217. }
  3218. // Build a packet
  3219. if (p->FlagEncrypted == false)
  3220. {
  3221. buf = IkeBuild(p, NULL);
  3222. }
  3223. else
  3224. {
  3225. IKE_CRYPTO_PARAM cp;
  3226. Copy(cp.Iv, sa->Iv, sa->IkeSa->BlockSize);
  3227. cp.Key = sa->IkeSa->CryptoKey;
  3228. buf = IkeBuild(p, &cp);
  3229. IPsecSaUpdateIv(sa, cp.NextIv, sa->IkeSa->BlockSize);
  3230. IPsecSaUpdateIv(sa->PairIPsecSa, cp.NextIv, sa->IkeSa->BlockSize);
  3231. }
  3232. if (buf == NULL)
  3233. {
  3234. return;
  3235. }
  3236. // Register the last packet to re-transmit
  3237. if (sa->SendBuffer != NULL)
  3238. {
  3239. FreeBuf(sa->SendBuffer);
  3240. }
  3241. sa->SendBuffer = CloneBuf(buf);
  3242. sa->NextSendTick = ike->Now + (UINT64)(IKE_SA_RESEND_INTERVAL);
  3243. AddInterrupt(ike->Interrupts, sa->NextSendTick);
  3244. IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &sa->IkeClient->ServerIP, sa->IkeClient->ServerPort,
  3245. &sa->IkeClient->ClientIP, sa->IkeClient->ClientPort,
  3246. buf->Buf, buf->Size);
  3247. Free(buf);
  3248. }
  3249. // Send a packet using the IKE SA
  3250. void IkeSaSendPacket(IKE_SERVER *ike, IKE_SA *sa, IKE_PACKET *p)
  3251. {
  3252. BUF *buf;
  3253. // Validate arguments
  3254. if (ike == NULL || sa == NULL)
  3255. {
  3256. return;
  3257. }
  3258. if (p == NULL)
  3259. {
  3260. FreeBuf(sa->SendBuffer);
  3261. sa->SendBuffer = NULL;
  3262. sa->NextSendTick = 0;
  3263. return;
  3264. }
  3265. // Build a packet
  3266. if (p->FlagEncrypted == false)
  3267. {
  3268. buf = IkeBuild(p, NULL);
  3269. }
  3270. else
  3271. {
  3272. IKE_CRYPTO_PARAM cp;
  3273. Copy(cp.Iv, sa->Iv, sa->BlockSize);
  3274. cp.Key = sa->CryptoKey;
  3275. buf = IkeBuild(p, &cp);
  3276. IkeSaUpdateIv(sa, cp.NextIv, sa->BlockSize);
  3277. }
  3278. if (buf == NULL)
  3279. {
  3280. return;
  3281. }
  3282. if (p->ExchangeType != IKE_EXCHANGE_TYPE_INFORMATION)
  3283. {
  3284. // Register the last packet to re-transmit
  3285. if (sa->SendBuffer != NULL)
  3286. {
  3287. FreeBuf(sa->SendBuffer);
  3288. }
  3289. sa->SendBuffer = CloneBuf(buf);
  3290. sa->NextSendTick = ike->Now + (UINT64)(IKE_SA_RESEND_INTERVAL);
  3291. AddInterrupt(ike->Interrupts, sa->NextSendTick);
  3292. }
  3293. IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &sa->IkeClient->ServerIP, sa->IkeClient->ServerPort,
  3294. &sa->IkeClient->ClientIP, sa->IkeClient->ClientPort,
  3295. buf->Buf, buf->Size);
  3296. Free(buf);
  3297. }
  3298. // Send an UDP packet
  3299. void IkeSendUdpPacket(IKE_SERVER *ike, UINT type, IP *server_ip, UINT server_port, IP *client_ip, UINT client_port, void *data, UINT size)
  3300. {
  3301. UDPPACKET *p;
  3302. // Validate arguments
  3303. if (ike == NULL || server_ip == NULL || client_ip == NULL || server_port == 0 || client_port == 0 || data == NULL || size == 0)
  3304. {
  3305. return;
  3306. }
  3307. p = NewUdpPacket(server_ip, server_port, client_ip, client_port, data, size);
  3308. p->Type = type;
  3309. Add(ike->SendPacketList, p);
  3310. }
  3311. // Create an IKE SA
  3312. IKE_SA *NewIkeSa(IKE_SERVER *ike, IKE_CLIENT *c, UINT64 init_cookie, UINT mode, IKE_SA_TRANSFORM_SETTING *setting)
  3313. {
  3314. IKE_SA *sa;
  3315. // Validate arguments
  3316. if (ike == NULL || c == NULL || init_cookie == 0 || setting == NULL)
  3317. {
  3318. return NULL;
  3319. }
  3320. sa = ZeroMalloc(sizeof(IKE_SA));
  3321. sa->Id = ++ike->CurrentIkeSaId;
  3322. sa->IkeClient = c;
  3323. sa->InitiatorCookie = init_cookie;
  3324. sa->ResponderCookie = GenerateNewResponserCookie(ike);
  3325. sa->Mode = mode;
  3326. sa->FirstCommTick = sa->LastCommTick = ike->Now;
  3327. Copy(&sa->TransformSetting, setting, sizeof(IKE_SA_TRANSFORM_SETTING));
  3328. Debug("New IKE SA (Mode = %u): %I64u <--> %I64u (%s %s %s(%u) %u %u)\n",
  3329. mode,
  3330. sa->InitiatorCookie,
  3331. sa->ResponderCookie,
  3332. setting->Dh->Name, setting->Hash->Name, setting->Crypto->Name, setting->CryptoKeySize,
  3333. setting->LifeKilobytes, setting->LifeSeconds);
  3334. IPsecLog(ike, NULL, sa, NULL, "LI_NEW_IKE_SA",
  3335. (mode == IKE_SA_MAIN_MODE ? _UU("LI_TAG_MAINMODE") : _UU("LI_TAG_AGGRESSIVE")),
  3336. sa->InitiatorCookie, sa->ResponderCookie,
  3337. setting->Dh->Name, setting->Hash->Name, setting->Crypto->Name, setting->CryptoKeySize * 8,
  3338. setting->LifeKilobytes, setting->LifeSeconds);
  3339. return sa;
  3340. }
  3341. // Search an IKE SA from the Responder Cookie
  3342. IKE_SA *FindIkeSaByResponderCookie(IKE_SERVER *ike, UINT64 responder_cookie)
  3343. {
  3344. IKE_SA t;
  3345. // Validate arguments
  3346. if (ike == NULL || responder_cookie == 0)
  3347. {
  3348. return NULL;
  3349. }
  3350. t.ResponderCookie = responder_cookie;
  3351. return Search(ike->IkeSaList, &t);
  3352. }
  3353. // Search an IKE SA from the Responder Cookie and the IKE_CLIENT
  3354. IKE_SA *FindIkeSaByResponderCookieAndClient(IKE_SERVER *ike, UINT64 responder_cookie, IKE_CLIENT *c)
  3355. {
  3356. IKE_SA *sa;
  3357. // Validate arguments
  3358. if (ike == NULL || responder_cookie == 0 || c == NULL)
  3359. {
  3360. return NULL;
  3361. }
  3362. sa = FindIkeSaByResponderCookie(ike, responder_cookie);
  3363. if (sa == NULL)
  3364. {
  3365. return NULL;
  3366. }
  3367. if (sa->IkeClient != c)
  3368. {
  3369. return NULL;
  3370. }
  3371. return sa;
  3372. }
  3373. // Search an IKE SA from the endpoint and the Initiator Cookie
  3374. IKE_SA *FindIkeSaByEndPointAndInitiatorCookie(IKE_SERVER *ike, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port, UINT64 init_cookie, UINT mode)
  3375. {
  3376. UINT i;
  3377. // Validate arguments
  3378. if (ike == NULL || client_ip == NULL || server_ip == NULL || client_port == 0 || server_port == 0 || init_cookie == 0)
  3379. {
  3380. return NULL;
  3381. }
  3382. for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
  3383. {
  3384. IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
  3385. IKE_CLIENT *c;
  3386. c = sa->IkeClient;
  3387. if (CmpIpAddr(&c->ClientIP, client_ip) == 0 &&
  3388. CmpIpAddr(&c->ServerIP, server_ip) == 0 &&
  3389. c->ClientPort == client_port &&
  3390. c->ServerPort == server_port &&
  3391. sa->InitiatorCookie == init_cookie &&
  3392. sa->Mode == mode)
  3393. {
  3394. return sa;
  3395. }
  3396. }
  3397. return NULL;
  3398. }
  3399. // Get the number of IPsec SA that is associated with the IKE_CLIENT
  3400. UINT GetNumberOfIPsecSaOfIkeClient(IKE_SERVER *ike, IKE_CLIENT *c)
  3401. {
  3402. UINT num = 0, i;
  3403. // Validate arguments
  3404. if (ike == NULL || c == NULL)
  3405. {
  3406. return 0;
  3407. }
  3408. for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
  3409. {
  3410. IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
  3411. if (sa->IkeClient == c)
  3412. {
  3413. num++;
  3414. }
  3415. }
  3416. return num;
  3417. }
  3418. // Get the number of IKE SA that is associated with the IKE_CLIENT
  3419. UINT GetNumberOfIkeSaOfIkeClient(IKE_SERVER *ike, IKE_CLIENT *c)
  3420. {
  3421. UINT num = 0, i;
  3422. // Validate arguments
  3423. if (ike == NULL || c == NULL)
  3424. {
  3425. return 0;
  3426. }
  3427. for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
  3428. {
  3429. IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
  3430. if (sa->IkeClient == c)
  3431. {
  3432. num++;
  3433. }
  3434. }
  3435. return num;
  3436. }
  3437. // Get the number of clients that are connected from the specified IP address
  3438. UINT GetNumberOfIkeClientsFromIP(IKE_SERVER *ike, IP *client_ip)
  3439. {
  3440. UINT i, num;
  3441. // Validate arguments
  3442. if (ike == NULL || client_ip == NULL)
  3443. {
  3444. return 0;
  3445. }
  3446. num = 0;
  3447. for (i = 0;i < LIST_NUM(ike->ClientList);i++)
  3448. {
  3449. IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
  3450. if (CmpIpAddr(&c->ClientIP, client_ip) == 0)
  3451. {
  3452. num++;
  3453. }
  3454. }
  3455. return num;
  3456. }
  3457. // Find the appropriate IKE client. Create if it is absent
  3458. IKE_CLIENT *SearchOrCreateNewIkeClientForIkePacket(IKE_SERVER *ike, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port, IKE_PACKET *pr)
  3459. {
  3460. IKE_CLIENT *c;
  3461. // Validate arguments
  3462. if (ike == NULL || pr == NULL || client_ip == NULL || server_ip == NULL || client_port == 0 || server_port == 0)
  3463. {
  3464. return NULL;
  3465. }
  3466. c = SearchIkeClientForIkePacket(ike, client_ip, client_port, server_ip, server_port, pr);
  3467. if (c == NULL)
  3468. {
  3469. if (GetNumberOfIkeClientsFromIP(ike, client_ip) > IKE_QUOTA_MAX_NUM_CLIENTS_PER_IP ||
  3470. LIST_NUM(ike->ClientList) > IKE_QUOTA_MAX_NUM_CLIENTS)
  3471. {
  3472. return NULL;
  3473. }
  3474. c = NewIkeClient(ike, client_ip, client_port, server_ip, server_port);
  3475. Insert(ike->ClientList, c);
  3476. }
  3477. return SetIkeClientEndpoint(ike, c, client_ip, client_port, server_ip, server_port);
  3478. }
  3479. // Create an IKE client
  3480. IKE_CLIENT *NewIkeClient(IKE_SERVER *ike, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port)
  3481. {
  3482. IKE_CLIENT *c;
  3483. char client_ip_str[MAX_SIZE];
  3484. char server_ip_str[MAX_SIZE];
  3485. // Validate arguments
  3486. if (ike == NULL || client_ip == NULL || server_ip == NULL || client_port == 0 || server_port == 0)
  3487. {
  3488. return NULL;
  3489. }
  3490. c = ZeroMalloc(sizeof(IKE_CLIENT));
  3491. c->Id = ++ike->CurrentIkeClientId;
  3492. Copy(&c->ClientIP, client_ip, sizeof(IP));
  3493. c->ClientPort = client_port;
  3494. Copy(&c->ServerIP, server_ip, sizeof(IP));
  3495. Copy(&c->TransportModeServerIP, server_ip, sizeof(IP));
  3496. Copy(&c->TransportModeClientIP, client_ip, sizeof(IP));
  3497. c->ServerPort = server_port;
  3498. c->LastCommTick = ike->Now;
  3499. c->FirstCommTick = ike->Now;
  3500. IPToStr(client_ip_str, sizeof(client_ip_str), client_ip);
  3501. IPToStr(server_ip_str, sizeof(server_ip_str), server_ip);
  3502. Debug("New IKE_CLIENT: %p: %s:%u -> %s:%u\n", c, client_ip_str, client_port, server_ip_str, server_port);
  3503. IPsecLog(ike, c, NULL, NULL, "LI_NEW_IKE_CLIENT");
  3504. return c;
  3505. }
  3506. // Search for the best associated IKE client when an IKE packet has been received
  3507. IKE_CLIENT *SearchIkeClientForIkePacket(IKE_SERVER *ike, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port, IKE_PACKET *pr)
  3508. {
  3509. IKE_CLIENT t;
  3510. IKE_CLIENT *c = NULL;
  3511. // Validate arguments
  3512. if (ike == NULL || pr == NULL || client_ip == NULL || server_ip == NULL || client_port == 0 || server_port == 0)
  3513. {
  3514. return NULL;
  3515. }
  3516. if (true)
  3517. {
  3518. UINT i;
  3519. if (pr->InitiatorCookie != 0 && pr->ResponderCookie != 0)
  3520. {
  3521. for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
  3522. {
  3523. IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
  3524. // Extract what Cookie matches exactly
  3525. if (sa->InitiatorCookie == pr->InitiatorCookie && sa->ResponderCookie == pr->ResponderCookie)
  3526. {
  3527. IKE_CLIENT *cc = sa->IkeClient;
  3528. if (CmpIpAddr(&cc->ServerIP, server_ip) == 0 &&
  3529. CmpIpAddr(&cc->ClientIP, client_ip) == 0)
  3530. {
  3531. c = cc;
  3532. break;
  3533. }
  3534. }
  3535. }
  3536. }
  3537. }
  3538. if (c == NULL)
  3539. {
  3540. // Search by a pair of IP address and port number
  3541. Copy(&t.ClientIP, client_ip, sizeof(IP));
  3542. t.ClientPort = client_port;
  3543. Copy(&t.ServerIP, server_ip, sizeof(IP));
  3544. t.ServerPort = server_port;
  3545. c = Search(ike->ClientList, &t);
  3546. if (c != NULL)// && server_port == IPSEC_PORT_IPSEC_ISAKMP)
  3547. {
  3548. // Search that the IKE_SA that points to this IKE_CLIENT exists and match the Cookie
  3549. bool ok = false;
  3550. UINT i;
  3551. if (server_port == IPSEC_PORT_IPSEC_ESP_UDP)
  3552. {
  3553. // Regard as OK if the port number exactly match in the case of connecting to a server-side 4500
  3554. ok = true;
  3555. }
  3556. else
  3557. {
  3558. if (c->CurrentIkeSa != NULL &&
  3559. c->CurrentIkeSa->InitiatorCookie == pr->InitiatorCookie &&
  3560. c->CurrentIkeSa->ResponderCookie == pr->ResponderCookie)
  3561. {
  3562. ok = true;
  3563. }
  3564. else
  3565. {
  3566. for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
  3567. {
  3568. IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
  3569. if (sa->IkeClient == c)
  3570. {
  3571. if (sa->InitiatorCookie == pr->InitiatorCookie &&
  3572. sa->ResponderCookie == pr->ResponderCookie)
  3573. {
  3574. ok = true;
  3575. break;
  3576. }
  3577. }
  3578. }
  3579. }
  3580. }
  3581. if (ok == false)
  3582. {
  3583. // Not found
  3584. c = NULL;
  3585. }
  3586. }
  3587. }
  3588. return c;
  3589. }
  3590. // Comparison of IPsec SA
  3591. int CmpIPsecSa(void *p1, void *p2)
  3592. {
  3593. IPSECSA *sa1, *sa2;
  3594. int r;
  3595. // Validate arguments
  3596. if (p1 == NULL || p2 == NULL)
  3597. {
  3598. return 0;
  3599. }
  3600. sa1 = *(IPSECSA **)p1;
  3601. sa2 = *(IPSECSA **)p2;
  3602. if (sa1 == NULL || sa2 == NULL)
  3603. {
  3604. return 0;
  3605. }
  3606. r = COMPARE_RET(sa1->ServerToClient, sa2->ServerToClient);
  3607. if (r != 0)
  3608. {
  3609. return r;
  3610. }
  3611. r = COMPARE_RET(sa1->Spi, sa2->Spi);
  3612. return r;
  3613. }
  3614. // Comparison of IKE_SA
  3615. int CmpIkeSa(void *p1, void *p2)
  3616. {
  3617. IKE_SA *sa1, *sa2;
  3618. int r;
  3619. // Validate arguments
  3620. if (p1 == NULL || p2 == NULL)
  3621. {
  3622. return 0;
  3623. }
  3624. sa1 = *(IKE_SA **)p1;
  3625. sa2 = *(IKE_SA **)p2;
  3626. if (sa1 == NULL || sa2 == NULL)
  3627. {
  3628. return 0;
  3629. }
  3630. r = COMPARE_RET(sa1->ResponderCookie, sa2->ResponderCookie);
  3631. return r;
  3632. }
  3633. // Comparison of IKE_CLIENT
  3634. int CmpIkeClient(void *p1, void *p2)
  3635. {
  3636. IKE_CLIENT *c1, *c2;
  3637. int r;
  3638. // Validate arguments
  3639. if (p1 == NULL || p2 == NULL)
  3640. {
  3641. return 0;
  3642. }
  3643. c1 = *(IKE_CLIENT **)p1;
  3644. c2 = *(IKE_CLIENT **)p2;
  3645. if (c1 == NULL || c2 == NULL)
  3646. {
  3647. return 0;
  3648. }
  3649. r = CmpIpAddr(&c1->ClientIP, &c2->ClientIP);
  3650. if (r != 0)
  3651. {
  3652. return r;
  3653. }
  3654. r = CmpIpAddr(&c1->ServerIP, &c2->ServerIP);
  3655. if (r != 0)
  3656. {
  3657. return r;
  3658. }
  3659. r = COMPARE_RET(c1->ClientPort, c2->ClientPort);
  3660. if (r != 0)
  3661. {
  3662. return r;
  3663. }
  3664. r = COMPARE_RET(c1->ServerPort, c2->ServerPort);
  3665. if (r != 0)
  3666. {
  3667. return r;
  3668. }
  3669. return 0;
  3670. }
  3671. // Update the endpoint information of IKE_CLIENT
  3672. IKE_CLIENT *SetIkeClientEndpoint(IKE_SERVER *ike, IKE_CLIENT *c, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port)
  3673. {
  3674. char client_ip_str[MAX_SIZE];
  3675. char server_ip_str[MAX_SIZE];
  3676. IKE_CLIENT *ret = c;
  3677. IKE_CLIENT *cc;
  3678. IKE_CLIENT t;
  3679. // Validate arguments
  3680. if (ike == NULL || c == NULL || client_ip == NULL || client_port == 0 || server_ip == NULL || server_port == 0)
  3681. {
  3682. return NULL;
  3683. }
  3684. if (CmpIpAddr(&c->ClientIP, client_ip) == 0 &&
  3685. CmpIpAddr(&c->ServerIP, server_ip) == 0 &&
  3686. c->ClientPort == client_port &&
  3687. c->ServerPort == server_port)
  3688. {
  3689. // No change
  3690. return ret;
  3691. }
  3692. if (IS_SPECIAL_PORT(client_port) || IS_SPECIAL_PORT(server_port))
  3693. {
  3694. // Don't change in the case of Raw socket
  3695. return ret;
  3696. }
  3697. // Search for an existing IKE_CLIENT which exactly matches to combination of the new IP address and the port number
  3698. Copy(&t.ClientIP, client_ip, sizeof(IP));
  3699. t.ClientPort = client_port;
  3700. Copy(&t.ServerIP, server_ip, sizeof(IP));
  3701. t.ServerPort = server_port;
  3702. cc = Search(ike->ClientList, &t);
  3703. if (cc != NULL && c != cc && cc->Deleting == false && c->L2TP == NULL)
  3704. {
  3705. UINT i;
  3706. // Merge into this existing IKE_CLIENT since it found
  3707. for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
  3708. {
  3709. IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
  3710. if (sa->IkeClient == c)
  3711. {
  3712. sa->IkeClient = cc;
  3713. }
  3714. }
  3715. for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
  3716. {
  3717. IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
  3718. if (sa->IkeClient == c)
  3719. {
  3720. sa->IkeClient = cc;
  3721. }
  3722. }
  3723. if (cc->LastCommTick < c->LastCommTick)
  3724. {
  3725. StrCpy(cc->ClientId, sizeof(cc->ClientId), c->ClientId);
  3726. }
  3727. cc->FirstCommTick = MIN(cc->FirstCommTick, c->FirstCommTick);
  3728. cc->LastCommTick = MAX(cc->LastCommTick, c->LastCommTick);
  3729. ret = cc;
  3730. IPToStr(client_ip_str, sizeof(client_ip_str), client_ip);
  3731. IPToStr(server_ip_str, sizeof(server_ip_str), server_ip);
  3732. Debug("Merge IKE_CLIENT: %p->%p: %s:%u -> %s:%u\n", c, cc, client_ip_str, client_port, server_ip_str, server_port);
  3733. IPsecLog(ike, c, NULL, NULL, "LI_CLIENT_MERGE", c->Id, cc->Id, cc->Id);
  3734. // Remove old IKE_CLIENT from the list and free
  3735. Delete(ike->ClientList, c);
  3736. FreeIkeClient(ike, c);
  3737. }
  3738. else
  3739. {
  3740. // Rewrite the end point information of this IKE_CLIENT because not found
  3741. Copy(&c->ClientIP, client_ip, sizeof(IP));
  3742. Copy(&c->ServerIP, server_ip, sizeof(IP));
  3743. c->ClientPort = client_port;
  3744. c->ServerPort = server_port;
  3745. IPToStr(client_ip_str, sizeof(client_ip_str), client_ip);
  3746. IPToStr(server_ip_str, sizeof(server_ip_str), server_ip);
  3747. Debug("Update IKE_CLIENT: %p: %s:%u -> %s:%u\n", c, client_ip_str, client_port, server_ip_str, server_port);
  3748. IPsecLog(ike, c, NULL, NULL, "LI_CLIENT_UPDATE");
  3749. ike->ClientList->sorted = false;
  3750. }
  3751. return ret;
  3752. }
  3753. // Select the optimal transform setting for IPsec SA
  3754. bool GetBestTransformSettingForIPsecSa(IKE_SERVER *ike, IKE_PACKET *pr, IPSEC_SA_TRANSFORM_SETTING *setting, IP *server_ip)
  3755. {
  3756. IKE_PACKET_PAYLOAD *sa_payload;
  3757. IKE_PACKET_SA_PAYLOAD *sa;
  3758. UINT i, num;
  3759. bool ocmii_flag = false;
  3760. // Validate arguments
  3761. if (ike == NULL || pr == NULL || setting == NULL || server_ip == NULL)
  3762. {
  3763. return false;
  3764. }
  3765. Zero(setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
  3766. // Get the SA payload
  3767. sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
  3768. if (sa_payload == NULL)
  3769. {
  3770. return false;
  3771. }
  3772. sa = &sa_payload->Payload.Sa;
  3773. // Scan all proposal payloads
  3774. num = IkeGetPayloadNum(sa->PayloadList, IKE_PAYLOAD_PROPOSAL);
  3775. for (i = 0;i < num;i++)
  3776. {
  3777. IKE_PACKET_PAYLOAD *proposal_payload = IkeGetPayload(sa->PayloadList, IKE_PAYLOAD_PROPOSAL, i);
  3778. if (proposal_payload != NULL)
  3779. {
  3780. IKE_PACKET_PROPOSAL_PAYLOAD *proposal = &proposal_payload->Payload.Proposal;
  3781. // Examine the contents of the proposal payload
  3782. if (proposal->ProtocolId == IKE_PROTOCOL_ID_IPSEC_ESP && proposal->Spi->Size == 4)
  3783. {
  3784. // Scan all transform payloads
  3785. UINT j, num2;
  3786. num2 = IkeGetPayloadNum(proposal->PayloadList, IKE_PAYLOAD_TRANSFORM);
  3787. for (j = 0;j < num2;j++)
  3788. {
  3789. IKE_PACKET_PAYLOAD *transform_payload = IkeGetPayload(proposal->PayloadList, IKE_PAYLOAD_TRANSFORM, j);
  3790. if (transform_payload != NULL)
  3791. {
  3792. IKE_PACKET_TRANSFORM_PAYLOAD *transform = &transform_payload->Payload.Transform;
  3793. IPSEC_SA_TRANSFORM_SETTING set;
  3794. Zero(&set, sizeof(set));
  3795. if (TransformPayloadToTransformSettingForIPsecSa(ike, transform, &set, server_ip))
  3796. {
  3797. Copy(setting, &set, sizeof(IPSEC_SA_TRANSFORM_SETTING));
  3798. setting->SpiServerToClient = READ_UINT(proposal->Spi->Buf);
  3799. return true;
  3800. }
  3801. else
  3802. {
  3803. if (set.OnlyCapsuleModeIsInvalid)
  3804. {
  3805. if (ocmii_flag == false)
  3806. {
  3807. Copy(setting, &set, sizeof(IPSEC_SA_TRANSFORM_SETTING));
  3808. ocmii_flag = true;
  3809. }
  3810. }
  3811. }
  3812. }
  3813. }
  3814. }
  3815. }
  3816. }
  3817. return false;
  3818. }
  3819. // Select the optimal transform settings for the IKE SA
  3820. bool GetBestTransformSettingForIkeSa(IKE_SERVER *ike, IKE_PACKET *pr, IKE_SA_TRANSFORM_SETTING *setting)
  3821. {
  3822. IKE_PACKET_PAYLOAD *sa_payload;
  3823. IKE_PACKET_SA_PAYLOAD *sa;
  3824. UINT i, num;
  3825. // Validate arguments
  3826. if (ike == NULL || pr == NULL || setting == NULL)
  3827. {
  3828. return false;
  3829. }
  3830. // Get the SA payload
  3831. sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
  3832. if (sa_payload == NULL)
  3833. {
  3834. return false;
  3835. }
  3836. sa = &sa_payload->Payload.Sa;
  3837. // Scan all proposal payloads
  3838. num = IkeGetPayloadNum(sa->PayloadList, IKE_PAYLOAD_PROPOSAL);
  3839. for (i = 0;i < num;i++)
  3840. {
  3841. IKE_PACKET_PAYLOAD *proposal_payload = IkeGetPayload(sa->PayloadList, IKE_PAYLOAD_PROPOSAL, i);
  3842. if (proposal_payload != NULL)
  3843. {
  3844. IKE_PACKET_PROPOSAL_PAYLOAD *proposal = &proposal_payload->Payload.Proposal;
  3845. // Examine the contents of the proposal payload
  3846. if (proposal->ProtocolId == IKE_PROTOCOL_ID_IKE)
  3847. {
  3848. // Scan all transform payloads
  3849. UINT j, num2;
  3850. num2 = IkeGetPayloadNum(proposal->PayloadList, IKE_PAYLOAD_TRANSFORM);
  3851. for (j = 0;j < num2;j++)
  3852. {
  3853. IKE_PACKET_PAYLOAD *transform_payload = IkeGetPayload(proposal->PayloadList, IKE_PAYLOAD_TRANSFORM, j);
  3854. if (transform_payload != NULL)
  3855. {
  3856. IKE_PACKET_TRANSFORM_PAYLOAD *transform = &transform_payload->Payload.Transform;
  3857. if (transform->TransformId == IKE_TRANSFORM_ID_P1_KEY_IKE)
  3858. {
  3859. IKE_SA_TRANSFORM_SETTING set;
  3860. if (TransformPayloadToTransformSettingForIkeSa(ike, transform, &set))
  3861. {
  3862. Copy(setting, &set, sizeof(IKE_SA_TRANSFORM_SETTING));
  3863. return true;
  3864. }
  3865. }
  3866. }
  3867. }
  3868. }
  3869. }
  3870. }
  3871. return false;
  3872. }
  3873. // Convert a structure to the transform payload (for IPsec SA)
  3874. IKE_PACKET_PAYLOAD *TransformSettingToTransformPayloadForIPsec(IKE_SERVER *ike, IPSEC_SA_TRANSFORM_SETTING *setting)
  3875. {
  3876. LIST *value_list;
  3877. // Validate arguments
  3878. if (ike == NULL || setting == NULL)
  3879. {
  3880. return NULL;
  3881. }
  3882. value_list = NewListFast(NULL);
  3883. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_HMAC, setting->HashId));
  3884. if (setting->Dh != NULL)
  3885. {
  3886. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_DH_GROUP, setting->DhId));
  3887. }
  3888. if (setting->LifeSeconds != INFINITE)
  3889. {
  3890. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_LIFE_TYPE, IKE_P2_LIFE_TYPE_SECONDS));
  3891. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_LIFE_VALUE, setting->LifeSeconds));
  3892. }
  3893. if (setting->LifeKilobytes != INFINITE)
  3894. {
  3895. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_LIFE_TYPE, IKE_P2_LIFE_TYPE_KILOBYTES));
  3896. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_LIFE_VALUE, setting->LifeKilobytes));
  3897. }
  3898. if (setting->Crypto->VariableKeySize)
  3899. {
  3900. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_KEY_SIZE, setting->CryptoKeySize * 8));
  3901. }
  3902. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_CAPSULE, setting->CapsuleMode));
  3903. return IkeNewTransformPayload(1, setting->CryptoId, value_list);
  3904. }
  3905. // Convert a structure to the transform payload (for IKE SA)
  3906. IKE_PACKET_PAYLOAD *TransformSettingToTransformPayloadForIke(IKE_SERVER *ike, IKE_SA_TRANSFORM_SETTING *setting)
  3907. {
  3908. LIST *value_list;
  3909. // Validate arguments
  3910. if (ike == NULL || setting == NULL)
  3911. {
  3912. return NULL;
  3913. }
  3914. value_list = NewListFast(NULL);
  3915. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_CRYPTO, setting->CryptoId));
  3916. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_HASH, setting->HashId));
  3917. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_AUTH_METHOD, IKE_P1_AUTH_METHOD_PRESHAREDKEY));
  3918. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_DH_GROUP, setting->DhId));
  3919. if (setting->LifeSeconds != INFINITE)
  3920. {
  3921. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_LIFE_TYPE, IKE_P1_LIFE_TYPE_SECONDS));
  3922. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_LIFE_VALUE, setting->LifeSeconds));
  3923. }
  3924. if (setting->LifeKilobytes != INFINITE)
  3925. {
  3926. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_LIFE_TYPE, IKE_P1_LIFE_TYPE_KILOBYTES));
  3927. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_LIFE_VALUE, setting->LifeKilobytes));
  3928. }
  3929. if (setting->Crypto->VariableKeySize)
  3930. {
  3931. Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_KET_SIZE, setting->CryptoKeySize * 8));
  3932. }
  3933. return IkeNewTransformPayload(1, IKE_TRANSFORM_ID_P1_KEY_IKE, value_list);
  3934. }
  3935. // Convert a transform payload to a structure (for IPsec SA)
  3936. bool TransformPayloadToTransformSettingForIPsecSa(IKE_SERVER *ike, IKE_PACKET_TRANSFORM_PAYLOAD *transform, IPSEC_SA_TRANSFORM_SETTING *setting, IP *server_ip)
  3937. {
  3938. UINT i;
  3939. UINT capsule_mode;
  3940. bool is_esp_supported;
  3941. // Validate arguments
  3942. if (ike == NULL || transform == NULL || setting == NULL || server_ip == NULL)
  3943. {
  3944. return false;
  3945. }
  3946. is_esp_supported = IsUdpPortOpened(ike->IPsec->UdpListener, server_ip, IPSEC_PORT_IPSEC_ESP_RAW);
  3947. Zero(setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
  3948. setting->CryptoId = transform->TransformId;
  3949. setting->HashId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_HMAC, 0);
  3950. setting->DhId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_DH_GROUP, 0);
  3951. setting->LifeKilobytes = INFINITE;
  3952. setting->LifeSeconds = INFINITE;
  3953. for (i = 0;i < IkeGetTransformValueNum(transform, IKE_TRANSFORM_VALUE_P2_LIFE_TYPE);i++)
  3954. {
  3955. UINT life_type = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_LIFE_TYPE, i);
  3956. switch (life_type)
  3957. {
  3958. case IKE_P2_LIFE_TYPE_SECONDS: // Number of seconds
  3959. setting->LifeSeconds = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_LIFE_VALUE, i);
  3960. break;
  3961. case IKE_P2_LIFE_TYPE_KILOBYTES: // Kilobytes
  3962. setting->LifeKilobytes = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_LIFE_VALUE, i);
  3963. break;
  3964. default:
  3965. // Unsupported expiration type
  3966. return false;
  3967. }
  3968. }
  3969. setting->Crypto = GetIkeCrypto(ike->Engine, true, setting->CryptoId);
  3970. setting->Hash = GetIkeHash(ike->Engine, true, setting->HashId);
  3971. setting->Dh = GetIkeDh(ike->Engine, true, setting->DhId);
  3972. if (setting->Crypto == NULL || setting->Hash == NULL)
  3973. {
  3974. // Unsupported algorithm
  3975. return false;
  3976. }
  3977. if (setting->Crypto->VariableKeySize)
  3978. {
  3979. // Get the actual key size in the case of variable key size
  3980. setting->CryptoKeySize = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_KEY_SIZE, 0);
  3981. // bits -> bytes
  3982. setting->CryptoKeySize = setting->CryptoKeySize / 8;
  3983. if (setting->CryptoKeySize == 0 || IkeCheckKeySize(setting->Crypto, setting->CryptoKeySize) == false)
  3984. {
  3985. // The key size is not specified or inappropriate
  3986. return false;
  3987. }
  3988. }
  3989. else
  3990. {
  3991. // Get a fixed key length for fixed key size
  3992. setting->CryptoKeySize = setting->Crypto->KeySizes[0];
  3993. }
  3994. capsule_mode = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_CAPSULE, 0);
  3995. if (capsule_mode != IKE_P2_CAPSULE_NAT_TUNNEL_1 && capsule_mode != IKE_P2_CAPSULE_NAT_TUNNEL_2 &&
  3996. capsule_mode != IKE_P2_CAPSULE_NAT_TRANSPORT_1 && capsule_mode != IKE_P2_CAPSULE_NAT_TRANSPORT_2)
  3997. {
  3998. // No support for UDP encapsulation mode except for the NAT-Traversal
  3999. if (capsule_mode == IKE_P2_CAPSULE_TRANSPORT || capsule_mode == IKE_P2_CAPSULE_TUNNEL)
  4000. {
  4001. if (is_esp_supported == false)
  4002. {
  4003. setting->OnlyCapsuleModeIsInvalid = true;
  4004. return false;
  4005. }
  4006. else
  4007. {
  4008. // It is an environment that can send and receive ESP packets
  4009. }
  4010. }
  4011. else
  4012. {
  4013. return false;
  4014. }
  4015. }
  4016. setting->CapsuleMode = capsule_mode;
  4017. return true;
  4018. }
  4019. // Convert a transform payload to a structure (for IKE SA)
  4020. bool TransformPayloadToTransformSettingForIkeSa(IKE_SERVER *ike, IKE_PACKET_TRANSFORM_PAYLOAD *transform, IKE_SA_TRANSFORM_SETTING *setting)
  4021. {
  4022. UINT i;
  4023. // Validate arguments
  4024. if (ike == NULL || transform == NULL || setting == NULL)
  4025. {
  4026. return false;
  4027. }
  4028. Zero(setting, sizeof(IKE_SA_TRANSFORM_SETTING));
  4029. setting->CryptoId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_CRYPTO, 0);
  4030. setting->HashId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_HASH, 0);
  4031. if (IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_AUTH_METHOD, 0) != IKE_P1_AUTH_METHOD_PRESHAREDKEY)
  4032. {
  4033. // Only PSK authentication method is supported
  4034. return false;
  4035. }
  4036. setting->DhId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_DH_GROUP, 0);
  4037. setting->LifeKilobytes = INFINITE;
  4038. setting->LifeSeconds = INFINITE;
  4039. for (i = 0;i < IkeGetTransformValueNum(transform, IKE_TRANSFORM_VALUE_P1_LIFE_TYPE);i++)
  4040. {
  4041. UINT life_type = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_LIFE_TYPE, i);
  4042. switch (life_type)
  4043. {
  4044. case IKE_P1_LIFE_TYPE_SECONDS: // Number of seconds
  4045. setting->LifeSeconds = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_LIFE_VALUE, i);
  4046. break;
  4047. case IKE_P1_LIFE_TYPE_KILOBYTES: // Kilobytes
  4048. setting->LifeKilobytes = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_LIFE_VALUE, i);
  4049. break;
  4050. default:
  4051. // Unsupported expiration type
  4052. return false;
  4053. }
  4054. }
  4055. setting->Crypto = GetIkeCrypto(ike->Engine, false, setting->CryptoId);
  4056. setting->Hash = GetIkeHash(ike->Engine, false, setting->HashId);
  4057. setting->Dh = GetIkeDh(ike->Engine, false, setting->DhId);
  4058. if (setting->Crypto == NULL || setting->Hash == NULL || setting->Dh == NULL)
  4059. {
  4060. // Unsupported algorithm
  4061. return false;
  4062. }
  4063. if (setting->Crypto->VariableKeySize)
  4064. {
  4065. // Get the actual key size in the case of variable key size
  4066. setting->CryptoKeySize = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_KET_SIZE, 0);
  4067. // bits -> bytes
  4068. setting->CryptoKeySize = setting->CryptoKeySize / 8;
  4069. if (setting->CryptoKeySize == 0 || IkeCheckKeySize(setting->Crypto, setting->CryptoKeySize) == false)
  4070. {
  4071. // The key size is not specified or inappropriate
  4072. return false;
  4073. }
  4074. }
  4075. else
  4076. {
  4077. // Get a fixed key length for fixed key size
  4078. setting->CryptoKeySize = setting->Crypto->KeySizes[0];
  4079. }
  4080. return true;
  4081. }
  4082. // Creating a new Responder Cookie
  4083. UINT64 GenerateNewResponserCookie(IKE_SERVER *ike)
  4084. {
  4085. UINT64 c;
  4086. // Validate arguments
  4087. if (ike == NULL)
  4088. {
  4089. return 0;
  4090. }
  4091. while (true)
  4092. {
  4093. bool b = false;
  4094. UINT i;
  4095. c = Rand64();
  4096. for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
  4097. {
  4098. IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
  4099. if (sa->ResponderCookie == c)
  4100. {
  4101. b = true;
  4102. break;
  4103. }
  4104. }
  4105. if (b == false)
  4106. {
  4107. return c;
  4108. }
  4109. }
  4110. }
  4111. // Parse the IKE packet header
  4112. IKE_PACKET *ParseIKEPacketHeader(UDPPACKET *p)
  4113. {
  4114. // Validate arguments
  4115. if (p == NULL)
  4116. {
  4117. return NULL;
  4118. }
  4119. return IkeParseHeader(p->Data, p->Size, NULL);
  4120. }
  4121. // Search for another IPsec SA belonging to the IKE_CLIENT which have same conditions to the specified IPsec SA
  4122. IPSECSA *GetOtherLatestIPsecSa(IKE_SERVER *ike, IPSECSA *sa)
  4123. {
  4124. UINT i;
  4125. UINT64 min_value = 0;
  4126. IPSECSA *max_sa = NULL;
  4127. // Validate arguments
  4128. if (ike == NULL || sa == NULL)
  4129. {
  4130. return NULL;
  4131. }
  4132. if (sa->IkeClient == NULL)
  4133. {
  4134. return NULL;
  4135. }
  4136. for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
  4137. {
  4138. IPSECSA *sa2 = LIST_DATA(ike->IPsecSaList, i);
  4139. if (sa2 != sa)
  4140. {
  4141. if (sa2->IkeClient == sa->IkeClient)
  4142. {
  4143. if (sa2->ServerToClient == sa->ServerToClient)
  4144. {
  4145. if (sa2->Deleting == false)
  4146. {
  4147. if (sa2->Established)
  4148. {
  4149. UINT64 last_comm_tick = sa2->LastCommTick;
  4150. if (sa2->ServerToClient)
  4151. {
  4152. if (sa2->PairIPsecSa != NULL)
  4153. {
  4154. last_comm_tick = sa2->PairIPsecSa->LastCommTick;
  4155. }
  4156. }
  4157. if (min_value < last_comm_tick)
  4158. {
  4159. min_value = last_comm_tick;
  4160. max_sa = sa2;
  4161. }
  4162. }
  4163. }
  4164. }
  4165. }
  4166. }
  4167. }
  4168. return max_sa;
  4169. }
  4170. // Search for another IKE_SA belonging to the IKE_CLIENT which have same conditions to the specified IKE_SA
  4171. IKE_SA *GetOtherLatestIkeSa(IKE_SERVER *ike, IKE_SA *sa)
  4172. {
  4173. UINT i;
  4174. UINT64 min_value = 0;
  4175. IKE_SA *max_sa = NULL;
  4176. // Validate arguments
  4177. if (ike == NULL || sa == NULL)
  4178. {
  4179. return NULL;
  4180. }
  4181. if (sa->IkeClient == NULL)
  4182. {
  4183. return NULL;
  4184. }
  4185. for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
  4186. {
  4187. IKE_SA *sa2 = LIST_DATA(ike->IkeSaList, i);
  4188. if (sa2 != sa)
  4189. {
  4190. if (sa2->IkeClient == sa->IkeClient)
  4191. {
  4192. if (sa2->Deleting == false)
  4193. {
  4194. if (sa2->Established)
  4195. {
  4196. if (min_value < sa2->LastCommTick)
  4197. {
  4198. min_value = sa2->LastCommTick;
  4199. max_sa = sa2;
  4200. }
  4201. }
  4202. }
  4203. }
  4204. }
  4205. }
  4206. return max_sa;
  4207. }
  4208. // Purge the IPsec SA
  4209. void PurgeIPsecSa(IKE_SERVER *ike, IPSECSA *sa)
  4210. {
  4211. UINT i;
  4212. IPSECSA *other_sa;
  4213. // Validate arguments
  4214. if (ike == NULL || sa == NULL)
  4215. {
  4216. return;
  4217. }
  4218. other_sa = GetOtherLatestIPsecSa(ike, sa);
  4219. // Rewrite the pairing partner by looking for IPsec SA that are paired
  4220. for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
  4221. {
  4222. IPSECSA *sa2 = LIST_DATA(ike->IPsecSaList, i);
  4223. if (sa2->PairIPsecSa == sa)
  4224. {
  4225. sa2->PairIPsecSa = other_sa;
  4226. }
  4227. }
  4228. // Rewrite the IKE_CLIENT using this IPsec SA to use alternate
  4229. for (i = 0;i < LIST_NUM(ike->ClientList);i++)
  4230. {
  4231. IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
  4232. if (c->CurrentIpSecSaRecv == sa)
  4233. {
  4234. c->CurrentIpSecSaRecv = other_sa;
  4235. }
  4236. if (c->CurrentIpSecSaSend == sa)
  4237. {
  4238. c->CurrentIpSecSaSend = other_sa;
  4239. }
  4240. }
  4241. Delete(ike->IPsecSaList, sa);
  4242. FreeIPsecSa(sa);
  4243. }
  4244. // Remove the IKE SA
  4245. void PurgeIkeSa(IKE_SERVER *ike, IKE_SA *sa)
  4246. {
  4247. IKE_SA *other_sa;
  4248. UINT i;
  4249. // Validate arguments
  4250. if (ike == NULL || sa == NULL)
  4251. {
  4252. return;
  4253. }
  4254. Debug("Purging IKE SA %I64u-%I64u\n", sa->InitiatorCookie, sa->ResponderCookie);
  4255. // Rewrite to alternative IKE_SA of all IPsec SA that are using this IKE_SA
  4256. other_sa = GetOtherLatestIkeSa(ike, sa);
  4257. for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
  4258. {
  4259. IPSECSA *ipsec_sa = LIST_DATA(ike->IPsecSaList, i);
  4260. if (ipsec_sa->IkeSa == sa)
  4261. {
  4262. if (other_sa == NULL)
  4263. {
  4264. // Remove this IPsec SA because there is no alternative IKE_SA
  4265. Debug(" Deleting IPsec SA 0x%X of this IKE SA (no alternatives)\n", ipsec_sa->Spi);
  4266. MarkIPsecSaAsDeleted(ike, ipsec_sa);
  4267. ipsec_sa->IkeSa = NULL;
  4268. }
  4269. else
  4270. {
  4271. // Replace to the alternative IKE_SA
  4272. Debug(" Replacing IKE SA of IPsec SA 0x%X from %I64u-%I64u to %I64u-%I64u\n", ipsec_sa->Spi,
  4273. sa->InitiatorCookie, sa->ResponderCookie,
  4274. other_sa->InitiatorCookie, other_sa->ResponderCookie);
  4275. ipsec_sa->IkeSa = other_sa;
  4276. }
  4277. }
  4278. }
  4279. // Substitute the IKE_SA of all IKE_CLIENT that are using this IKE_SA with alternative
  4280. for (i = 0;i < LIST_NUM(ike->ClientList);i++)
  4281. {
  4282. IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
  4283. if (c->CurrentIkeSa == sa)
  4284. {
  4285. c->CurrentIkeSa = other_sa;
  4286. }
  4287. }
  4288. Delete(ike->IkeSaList, sa);
  4289. FreeIkeSa(sa);
  4290. }
  4291. // Purge the IKE_CLIENT
  4292. void PurgeIkeClient(IKE_SERVER *ike, IKE_CLIENT *c)
  4293. {
  4294. UINT i;
  4295. // Validate arguments
  4296. if (ike == NULL || c == NULL)
  4297. {
  4298. return;
  4299. }
  4300. // Delete all of IPsec SA and IKE SA that belong to this IKE Client
  4301. for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
  4302. {
  4303. IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
  4304. if (sa->IkeClient == c)
  4305. {
  4306. MarkIkeSaAsDeleted(ike, sa);
  4307. }
  4308. }
  4309. for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
  4310. {
  4311. IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
  4312. if (sa->IkeClient == c)
  4313. {
  4314. MarkIPsecSaAsDeleted(ike, sa);
  4315. }
  4316. }
  4317. Delete(ike->ClientList, c);
  4318. FreeIkeClient(ike, c);
  4319. }
  4320. // Remove the SA that has been marked to delete
  4321. void PurgeDeletingSAsAndClients(IKE_SERVER *ike)
  4322. {
  4323. UINT i;
  4324. LIST *o = NULL;
  4325. // Validate arguments
  4326. if (ike == NULL)
  4327. {
  4328. return;
  4329. }
  4330. for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
  4331. {
  4332. IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
  4333. if (sa->Deleting)
  4334. {
  4335. if (o == NULL)
  4336. {
  4337. o = NewListFast(NULL);
  4338. }
  4339. Add(o, sa);
  4340. }
  4341. }
  4342. for (i = 0;i < LIST_NUM(o);i++)
  4343. {
  4344. IKE_SA *sa = LIST_DATA(o, i);
  4345. PurgeIkeSa(ike, sa);
  4346. }
  4347. ReleaseList(o);
  4348. o = NULL;
  4349. for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
  4350. {
  4351. IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
  4352. if (sa->Deleting)
  4353. {
  4354. if (o == NULL)
  4355. {
  4356. o = NewListFast(NULL);
  4357. }
  4358. Add(o, sa);
  4359. }
  4360. }
  4361. for (i = 0;i < LIST_NUM(o);i++)
  4362. {
  4363. IPSECSA *sa = LIST_DATA(o, i);
  4364. PurgeIPsecSa(ike, sa);
  4365. }
  4366. ReleaseList(o);
  4367. o = NULL;
  4368. for (i = 0;i < LIST_NUM(ike->ClientList);i++)
  4369. {
  4370. IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
  4371. if (c->Deleting)
  4372. {
  4373. if (o == NULL)
  4374. {
  4375. o = NewListFast(NULL);
  4376. }
  4377. Add(o, c);
  4378. }
  4379. }
  4380. for (i = 0;i < LIST_NUM(o);i++)
  4381. {
  4382. IKE_CLIENT *c = LIST_DATA(o, i);
  4383. PurgeIkeClient(ike, c);
  4384. }
  4385. ReleaseList(o);
  4386. }
  4387. // IKE interrupt process
  4388. void ProcessIKEInterrupts(IKE_SERVER *ike)
  4389. {
  4390. UINT i;
  4391. // Validate arguments
  4392. if (ike == NULL)
  4393. {
  4394. return;
  4395. }
  4396. for (i = 0;i < LIST_NUM(ike->ClientList);i++)
  4397. {
  4398. IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
  4399. c->CurrentExpiresSoftTick_CtoS = 0;
  4400. c->CurrentExpiresSoftTick_StoC = 0;
  4401. c->CurrentNumEstablishedIPsecSA_CtoS = 0;
  4402. c->CurrentNumEstablishedIPsecSA_StoC = 0;
  4403. c->CurrentNumHealtyIPsecSA_CtoS = 0;
  4404. c->CurrentNumHealtyIPsecSA_StoC = 0;
  4405. }
  4406. // Packet retransmission by scanning all IKE SA
  4407. for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
  4408. {
  4409. IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
  4410. if (sa->SendBuffer != NULL)
  4411. {
  4412. if (ike->Now >= sa->NextSendTick)
  4413. {
  4414. IKE_CLIENT *c = sa->IkeClient;
  4415. IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &c->ServerIP, c->ServerPort, &c->ClientIP, c->ClientPort,
  4416. Clone(sa->SendBuffer->Buf, sa->SendBuffer->Size), sa->SendBuffer->Size);
  4417. sa->NextSendTick += (UINT64)(IKE_SA_RESEND_INTERVAL);
  4418. AddInterrupt(ike->Interrupts, sa->NextSendTick);
  4419. if (sa->NumResends != 0)
  4420. {
  4421. sa->NumResends--;
  4422. if (sa->NumResends == 0)
  4423. {
  4424. sa->NextSendTick = 0;
  4425. FreeBuf(sa->SendBuffer);
  4426. sa->SendBuffer = NULL;
  4427. }
  4428. }
  4429. }
  4430. }
  4431. // Remove those of non-communication
  4432. if (sa->IkeClient == NULL || (sa->IkeClient->CurrentIkeSa != sa))
  4433. {
  4434. // When the IKE_CLIENT don't point this
  4435. if (sa->Established == false)
  4436. {
  4437. // Make time-out in a short time when it is not established
  4438. if ((sa->LastCommTick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT_FOR_NOT_ESTABLISHED) <= ike->Now)
  4439. {
  4440. WHERE;
  4441. MarkIkeSaAsDeleted(ike, sa);
  4442. }
  4443. }
  4444. else
  4445. {
  4446. // Timeout in a long time in the case of established
  4447. if ((sa->LastCommTick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT) <= ike->Now)
  4448. {
  4449. WHERE;
  4450. MarkIkeSaAsDeleted(ike, sa);
  4451. }
  4452. }
  4453. }
  4454. }
  4455. // Packet retransmission by scanning all IPsec SA
  4456. for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
  4457. {
  4458. IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
  4459. IKE_CLIENT *c = sa->IkeClient;
  4460. if (sa->SendBuffer != NULL)
  4461. {
  4462. if (ike->Now >= sa->NextSendTick)
  4463. {
  4464. IKE_CLIENT *c = sa->IkeClient;
  4465. IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &c->ServerIP, c->ServerPort, &c->ClientIP, c->ClientPort,
  4466. Clone(sa->SendBuffer->Buf, sa->SendBuffer->Size), sa->SendBuffer->Size);
  4467. sa->NextSendTick += (UINT64)(IKE_SA_RESEND_INTERVAL);
  4468. AddInterrupt(ike->Interrupts, sa->NextSendTick);
  4469. if (sa->NumResends != 0)
  4470. {
  4471. sa->NumResends--;
  4472. if (sa->NumResends == 0)
  4473. {
  4474. sa->NextSendTick = 0;
  4475. FreeBuf(sa->SendBuffer);
  4476. sa->SendBuffer = NULL;
  4477. }
  4478. }
  4479. }
  4480. }
  4481. if (sa->Established && sa->Deleting == false && c != NULL)
  4482. {
  4483. // Get the flexible expiration date of SA for each IKE_CLIENT
  4484. if (sa->ServerToClient)
  4485. {
  4486. c->CurrentExpiresSoftTick_StoC = MAX(c->CurrentExpiresSoftTick_StoC, sa->ExpiresSoftTick);
  4487. c->CurrentNumEstablishedIPsecSA_StoC++;
  4488. if (sa->ExpiresSoftTick == 0 || sa->ExpiresSoftTick > ike->Now)
  4489. {
  4490. c->CurrentNumHealtyIPsecSA_StoC++;
  4491. }
  4492. }
  4493. else
  4494. {
  4495. c->CurrentExpiresSoftTick_CtoS = MAX(c->CurrentExpiresSoftTick_CtoS, sa->ExpiresSoftTick);
  4496. c->CurrentNumEstablishedIPsecSA_CtoS++;
  4497. if (sa->ExpiresSoftTick == 0 || sa->ExpiresSoftTick > ike->Now)
  4498. {
  4499. c->CurrentNumHealtyIPsecSA_CtoS++;
  4500. }
  4501. }
  4502. }
  4503. // Remove those of non-communication
  4504. if (sa->IkeClient == NULL || (sa->IkeClient->CurrentIpSecSaRecv != sa && sa->IkeClient->CurrentIpSecSaSend != sa))
  4505. {
  4506. // When the IKE_CLIENT don't point this
  4507. UINT64 last_comm_tick = sa->LastCommTick;
  4508. if (sa->ServerToClient && sa->PairIPsecSa != NULL)
  4509. {
  4510. last_comm_tick = sa->PairIPsecSa->LastCommTick;
  4511. }
  4512. if (sa->Established == false)
  4513. {
  4514. // Make time-out in a short time when it is not established
  4515. if ((last_comm_tick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT_FOR_NOT_ESTABLISHED) <= ike->Now)
  4516. {
  4517. WHERE;
  4518. MarkIPsecSaAsDeleted(ike, sa);
  4519. }
  4520. }
  4521. else
  4522. {
  4523. // Timeout in a long time in the case of established
  4524. if ((last_comm_tick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT) <= ike->Now)
  4525. {
  4526. WHERE;
  4527. MarkIPsecSaAsDeleted(ike, sa);
  4528. }
  4529. }
  4530. }
  4531. }
  4532. // IKE_CLIENT scanning process
  4533. for (i = 0;i < LIST_NUM(ike->ClientList);i++)
  4534. {
  4535. IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
  4536. UINT64 tick;
  4537. UCHAR data[1];
  4538. bool need_qm = false;
  4539. bool need_qm_hard = false;
  4540. UINT64 qm_soft_tick = 0;
  4541. // Determine whether it is necessary to start a new Quick Mode
  4542. if (c->CurrentExpiresSoftTick_StoC != 0 && ike->Now >= c->CurrentExpiresSoftTick_StoC)
  4543. {
  4544. need_qm = true;
  4545. qm_soft_tick = MAX(qm_soft_tick, c->CurrentExpiresSoftTick_StoC);
  4546. }
  4547. if (c->CurrentExpiresSoftTick_CtoS != 0 && ike->Now >= c->CurrentExpiresSoftTick_CtoS)
  4548. {
  4549. need_qm = true;
  4550. qm_soft_tick = MAX(qm_soft_tick, c->CurrentExpiresSoftTick_StoC);
  4551. }
  4552. if (c->CurrentNumHealtyIPsecSA_CtoS == 0 || c->CurrentNumHealtyIPsecSA_StoC == 0)
  4553. {
  4554. need_qm = true;
  4555. need_qm_hard = true;
  4556. }
  4557. if (c->StartQuickModeAsSoon)
  4558. {
  4559. need_qm = true;
  4560. need_qm_hard = true;
  4561. }
  4562. if (c->Deleting || c->CurrentIkeSa == NULL || c->CurrentIkeSa->Deleting)
  4563. {
  4564. need_qm = false;
  4565. need_qm_hard = true;
  4566. }
  4567. if (need_qm)
  4568. {
  4569. if (c->StartQuickModeAsSoon || ((c->LastQuickModeStartTick + (UINT64)IKE_QUICKMODE_START_INTERVAL) <= ike->Now))
  4570. {
  4571. // Start the Quick Mode
  4572. Debug("IKE_CLIENT 0x%X: Begin QuickMode\n", c);
  4573. c->StartQuickModeAsSoon = false;
  4574. c->LastQuickModeStartTick = ike->Now;
  4575. AddInterrupt(ike->Interrupts, c->LastQuickModeStartTick + (UINT64)IKE_QUICKMODE_START_INTERVAL);
  4576. StartQuickMode(ike, c);
  4577. }
  4578. }
  4579. if (need_qm_hard)
  4580. {
  4581. if (c->NeedQmBeginTick == 0)
  4582. {
  4583. c->NeedQmBeginTick = ike->Now;
  4584. }
  4585. }
  4586. else
  4587. {
  4588. c->NeedQmBeginTick = 0;
  4589. }
  4590. if (((c->LastCommTick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT) <= ike->Now) ||
  4591. ((c->CurrentIkeSa == NULL && c->CurrentIpSecSaRecv == NULL && c->CurrentIpSecSaSend == NULL) && (c->LastCommTick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT_FOR_NOT_ESTABLISHED) <= ike->Now) ||
  4592. (c->NeedQmBeginTick != 0 && ((c->NeedQmBeginTick + (UINT64)IKE_QUICKMODE_FAILED_TIMEOUT) <= ike->Now)))
  4593. {
  4594. // Remove IKE_CLIENT not communicating for a certain period of time
  4595. WHERE;
  4596. MarkIkeClientAsDeleted(ike, c);
  4597. }
  4598. // L2TP processing
  4599. if (c->L2TP != NULL)
  4600. {
  4601. IPsecIkeClientManageL2TPServer(ike, c);
  4602. // Interrupt processing occurs
  4603. L2TPProcessInterrupts(c->L2TP);
  4604. // Packet transmission
  4605. IPsecIkeClientSendL2TPPackets(ike, c, c->L2TP);
  4606. }
  4607. // EtherIP processing
  4608. if (c->EtherIP != NULL)
  4609. {
  4610. IPsecIkeClientManageEtherIPServer(ike, c);
  4611. // Interrupt processing occurs
  4612. EtherIPProcInterrupts(c->EtherIP);
  4613. // Packet transmission
  4614. IPsecIkeClientSendEtherIPPackets(ike, c, c->EtherIP);
  4615. }
  4616. // KeepAlive transmission
  4617. tick = MAX(c->LastCommTick + (UINT64)IKE_INTERVAL_UDP_KEEPALIVE, c->NextKeepAliveSendTick);
  4618. if (tick <= ike->Now && c->ServerPort == IPSEC_PORT_IPSEC_ESP_UDP)
  4619. {
  4620. c->NextKeepAliveSendTick = ike->Now + (UINT64)IKE_INTERVAL_UDP_KEEPALIVE;
  4621. AddInterrupt(ike->Interrupts, c->NextKeepAliveSendTick);
  4622. Zero(data, sizeof(data));
  4623. data[0] = 0xff;
  4624. IkeSendUdpPacket(ike, IKE_UDP_KEEPALIVE, &c->ServerIP, c->ServerPort, &c->ClientIP, c->ClientPort, Clone(data, sizeof(data)), sizeof(data));
  4625. }
  4626. // DPD transmission
  4627. if (c->NextDpdSendTick == 0 || c->NextDpdSendTick <= ike->Now)
  4628. {
  4629. if (c->CurrentIkeSa != NULL && c->CurrentIkeSa->Established)
  4630. {
  4631. if (c->CurrentIkeSa->Caps.DpdRfc3706)
  4632. {
  4633. c->NextDpdSendTick = ike->Now + (UINT64)IKE_INTERVAL_DPD_KEEPALIVE;
  4634. AddInterrupt(ike->Interrupts, c->NextDpdSendTick);
  4635. SendInformationalExchangePacket(ike, c,
  4636. IkeNewNoticeDpdPayload(false, c->CurrentIkeSa->InitiatorCookie, c->CurrentIkeSa->ResponderCookie,
  4637. c->DpdSeqNo++));
  4638. }
  4639. }
  4640. }
  4641. }
  4642. do
  4643. {
  4644. ike->StateHasChanged = false;
  4645. // Deletion process
  4646. PurgeDeletingSAsAndClients(ike);
  4647. }
  4648. while (ike->StateHasChanged);
  4649. // Maintenance of the thread list
  4650. MaintainThreadList(ike->ThreadList);
  4651. /*Debug("ike->ThreadList: %u\n", LIST_NUM(ike->ThreadList));
  4652. {
  4653. UINT i;
  4654. for (i = 0;i < LIST_NUM(ike->ThreadList);i++)
  4655. {
  4656. THREAD *t = LIST_DATA(ike->ThreadList, i);
  4657. Debug(" Thread %u: 0x%p ID: %u Stop: %u Ref: %u\n", i, t, t->ThreadId, t->Stopped, t->ref->c->c);
  4658. }
  4659. }*/
  4660. }
  4661. // Stop the IKE server
  4662. void StopIKEServer(IKE_SERVER *ike)
  4663. {
  4664. // Validate arguments
  4665. if (ike == NULL)
  4666. {
  4667. return;
  4668. }
  4669. }
  4670. // Set the socket events in IKE server
  4671. void SetIKEServerSockEvent(IKE_SERVER *ike, SOCK_EVENT *e)
  4672. {
  4673. // Validate arguments
  4674. if (ike == NULL)
  4675. {
  4676. return;
  4677. }
  4678. if (e != NULL)
  4679. {
  4680. AddRef(e->ref);
  4681. }
  4682. if (ike->SockEvent != NULL)
  4683. {
  4684. ReleaseSockEvent(ike->SockEvent);
  4685. }
  4686. ike->SockEvent = e;
  4687. }
  4688. // Release the IKE client
  4689. void FreeIkeClient(IKE_SERVER *ike, IKE_CLIENT *c)
  4690. {
  4691. // Validate arguments
  4692. if (c == NULL || ike == NULL)
  4693. {
  4694. return;
  4695. }
  4696. if (c->L2TP != NULL)
  4697. {
  4698. StopL2TPServer(c->L2TP, true);
  4699. FreeL2TPServer(c->L2TP);
  4700. }
  4701. if (c->EtherIP != NULL)
  4702. {
  4703. ReleaseEtherIPServer(c->EtherIP);
  4704. }
  4705. FreeBuf(c->SendID1_Buf);
  4706. FreeBuf(c->SendID2_Buf);
  4707. Free(c);
  4708. }
  4709. // Release the IPsec SA
  4710. void FreeIPsecSa(IPSECSA *sa)
  4711. {
  4712. // Validate arguments
  4713. if (sa == NULL)
  4714. {
  4715. return;
  4716. }
  4717. IkeFreeKey(sa->CryptoKey);
  4718. FreeBuf(sa->SendBuffer);
  4719. FreeBuf(sa->InitiatorRand);
  4720. FreeBuf(sa->ResponderRand);
  4721. FreeBuf(sa->SharedKey);
  4722. IkeDhFreeCtx(sa->Dh);
  4723. Free(sa);
  4724. }
  4725. // Release the IKE SA
  4726. void FreeIkeSa(IKE_SA *sa)
  4727. {
  4728. // Validate arguments
  4729. if (sa == NULL)
  4730. {
  4731. return;
  4732. }
  4733. FreeBuf(sa->SendBuffer);
  4734. FreeBuf(sa->InitiatorRand);
  4735. FreeBuf(sa->ResponderRand);
  4736. FreeBuf(sa->DhSharedKey);
  4737. FreeBuf(sa->YourIDPayloadForAM);
  4738. FreeBuf(sa->GXi);
  4739. FreeBuf(sa->GXr);
  4740. FreeBuf(sa->SAi_b);
  4741. IkeFreeKey(sa->CryptoKey);
  4742. Free(sa);
  4743. }
  4744. // Release the IKE server
  4745. void FreeIKEServer(IKE_SERVER *ike)
  4746. {
  4747. UINT i;
  4748. // Validate arguments
  4749. if (ike == NULL)
  4750. {
  4751. return;
  4752. }
  4753. IPsecLog(ike, NULL, NULL, NULL, "LI_STOPPING");
  4754. for (i = 0;i < LIST_NUM(ike->SendPacketList);i++)
  4755. {
  4756. UDPPACKET *udp = LIST_DATA(ike->SendPacketList, i);
  4757. FreeUdpPacket(udp);
  4758. }
  4759. ReleaseList(ike->SendPacketList);
  4760. Debug("Num of IPsec SAs: %u\n", LIST_NUM(ike->IPsecSaList));
  4761. IPsecLog(ike, NULL, NULL, NULL, "LI_NUM_IPSEC_SA", LIST_NUM(ike->IPsecSaList));
  4762. for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
  4763. {
  4764. IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
  4765. FreeIPsecSa(sa);
  4766. }
  4767. ReleaseList(ike->IPsecSaList);
  4768. Debug("Num of IKE SAs: %u\n", LIST_NUM(ike->IkeSaList));
  4769. IPsecLog(ike, NULL, NULL, NULL, "LI_NUM_IKE_SA", LIST_NUM(ike->IkeSaList));
  4770. for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
  4771. {
  4772. IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
  4773. FreeIkeSa(sa);
  4774. }
  4775. ReleaseList(ike->IkeSaList);
  4776. Debug("Num of IKE_CLIENTs: %u\n", LIST_NUM(ike->ClientList));
  4777. IPsecLog(ike, NULL, NULL, NULL, "LI_NUM_IKE_CLIENTS", LIST_NUM(ike->ClientList));
  4778. for (i = 0;i < LIST_NUM(ike->ClientList);i++)
  4779. {
  4780. IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
  4781. FreeIkeClient(ike, c);
  4782. }
  4783. ReleaseList(ike->ClientList);
  4784. ReleaseSockEvent(ike->SockEvent);
  4785. IPsecLog(ike, NULL, NULL, NULL, "LI_STOP");
  4786. ReleaseCedar(ike->Cedar);
  4787. FreeIkeEngine(ike->Engine);
  4788. Debug("FreeThreadList()...\n");
  4789. FreeThreadList(ike->ThreadList);
  4790. Debug("FreeThreadList() Done.\n");
  4791. Free(ike);
  4792. }
  4793. // Create a new IKE server
  4794. IKE_SERVER *NewIKEServer(CEDAR *cedar, IPSEC_SERVER *ipsec)
  4795. {
  4796. IKE_SERVER *ike;
  4797. // Validate arguments
  4798. if (cedar == NULL)
  4799. {
  4800. return NULL;
  4801. }
  4802. ike = ZeroMalloc(sizeof(IKE_SERVER));
  4803. ike->Cedar = cedar;
  4804. AddRef(cedar->ref);
  4805. ike->IPsec = ipsec;
  4806. ike->Now = Tick64();
  4807. ike->SendPacketList = NewList(NULL);
  4808. ike->IkeSaList = NewList(CmpIkeSa);
  4809. ike->IPsecSaList = NewList(CmpIPsecSa);
  4810. ike->ClientList = NewList(CmpIkeClient);
  4811. ike->Engine = NewIkeEngine();
  4812. ike->ThreadList = NewThreadList();
  4813. IPsecLog(ike, NULL, NULL, NULL, "LI_START");
  4814. return ike;
  4815. }