Protocol.c 173 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345
  1. // SoftEther VPN Source Code
  2. // Cedar Communication Module
  3. //
  4. // SoftEther VPN Server, Client and Bridge are free software under GPLv2.
  5. //
  6. // Copyright (c) 2012-2016 Daiyuu Nobori.
  7. // Copyright (c) 2012-2016 SoftEther VPN Project, University of Tsukuba, Japan.
  8. // Copyright (c) 2012-2016 SoftEther Corporation.
  9. //
  10. // All Rights Reserved.
  11. //
  12. // http://www.softether.org/
  13. //
  14. // Author: Daiyuu Nobori
  15. // Comments: Tetsuo Sugiyama, Ph.D.
  16. //
  17. // This program is free software; you can redistribute it and/or
  18. // modify it under the terms of the GNU General Public License
  19. // version 2 as published by the Free Software Foundation.
  20. //
  21. // This program is distributed in the hope that it will be useful,
  22. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. // GNU General Public License for more details.
  25. //
  26. // You should have received a copy of the GNU General Public License version 2
  27. // along with this program; if not, write to the Free Software
  28. // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  29. //
  30. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  31. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  32. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  33. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  34. // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  35. // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  36. // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  37. //
  38. // THE LICENSE AGREEMENT IS ATTACHED ON THE SOURCE-CODE PACKAGE
  39. // AS "LICENSE.TXT" FILE. READ THE TEXT FILE IN ADVANCE TO USE THE SOFTWARE.
  40. //
  41. //
  42. // THIS SOFTWARE IS DEVELOPED IN JAPAN, AND DISTRIBUTED FROM JAPAN,
  43. // UNDER JAPANESE LAWS. YOU MUST AGREE IN ADVANCE TO USE, COPY, MODIFY,
  44. // MERGE, PUBLISH, DISTRIBUTE, SUBLICENSE, AND/OR SELL COPIES OF THIS
  45. // SOFTWARE, THAT ANY JURIDICAL DISPUTES WHICH ARE CONCERNED TO THIS
  46. // SOFTWARE OR ITS CONTENTS, AGAINST US (SOFTETHER PROJECT, SOFTETHER
  47. // CORPORATION, DAIYUU NOBORI OR OTHER SUPPLIERS), OR ANY JURIDICAL
  48. // DISPUTES AGAINST US WHICH ARE CAUSED BY ANY KIND OF USING, COPYING,
  49. // MODIFYING, MERGING, PUBLISHING, DISTRIBUTING, SUBLICENSING, AND/OR
  50. // SELLING COPIES OF THIS SOFTWARE SHALL BE REGARDED AS BE CONSTRUED AND
  51. // CONTROLLED BY JAPANESE LAWS, AND YOU MUST FURTHER CONSENT TO
  52. // EXCLUSIVE JURISDICTION AND VENUE IN THE COURTS SITTING IN TOKYO,
  53. // JAPAN. YOU MUST WAIVE ALL DEFENSES OF LACK OF PERSONAL JURISDICTION
  54. // AND FORUM NON CONVENIENS. PROCESS MAY BE SERVED ON EITHER PARTY IN
  55. // THE MANNER AUTHORIZED BY APPLICABLE LAW OR COURT RULE.
  56. //
  57. // USE ONLY IN JAPAN. DO NOT USE THIS SOFTWARE IN ANOTHER COUNTRY UNLESS
  58. // YOU HAVE A CONFIRMATION THAT THIS SOFTWARE DOES NOT VIOLATE ANY
  59. // CRIMINAL LAWS OR CIVIL RIGHTS IN THAT PARTICULAR COUNTRY. USING THIS
  60. // SOFTWARE IN OTHER COUNTRIES IS COMPLETELY AT YOUR OWN RISK. THE
  61. // SOFTETHER VPN PROJECT HAS DEVELOPED AND DISTRIBUTED THIS SOFTWARE TO
  62. // COMPLY ONLY WITH THE JAPANESE LAWS AND EXISTING CIVIL RIGHTS INCLUDING
  63. // PATENTS WHICH ARE SUBJECTS APPLY IN JAPAN. OTHER COUNTRIES' LAWS OR
  64. // CIVIL RIGHTS ARE NONE OF OUR CONCERNS NOR RESPONSIBILITIES. WE HAVE
  65. // NEVER INVESTIGATED ANY CRIMINAL REGULATIONS, CIVIL LAWS OR
  66. // INTELLECTUAL PROPERTY RIGHTS INCLUDING PATENTS IN ANY OF OTHER 200+
  67. // COUNTRIES AND TERRITORIES. BY NATURE, THERE ARE 200+ REGIONS IN THE
  68. // WORLD, WITH DIFFERENT LAWS. IT IS IMPOSSIBLE TO VERIFY EVERY
  69. // COUNTRIES' LAWS, REGULATIONS AND CIVIL RIGHTS TO MAKE THE SOFTWARE
  70. // COMPLY WITH ALL COUNTRIES' LAWS BY THE PROJECT. EVEN IF YOU WILL BE
  71. // SUED BY A PRIVATE ENTITY OR BE DAMAGED BY A PUBLIC SERVANT IN YOUR
  72. // COUNTRY, THE DEVELOPERS OF THIS SOFTWARE WILL NEVER BE LIABLE TO
  73. // RECOVER OR COMPENSATE SUCH DAMAGES, CRIMINAL OR CIVIL
  74. // RESPONSIBILITIES. NOTE THAT THIS LINE IS NOT LICENSE RESTRICTION BUT
  75. // JUST A STATEMENT FOR WARNING AND DISCLAIMER.
  76. //
  77. //
  78. // SOURCE CODE CONTRIBUTION
  79. // ------------------------
  80. //
  81. // Your contribution to SoftEther VPN Project is much appreciated.
  82. // Please send patches to us through GitHub.
  83. // Read the SoftEther VPN Patch Acceptance Policy in advance:
  84. // http://www.softether.org/5-download/src/9.patch
  85. //
  86. //
  87. // DEAR SECURITY EXPERTS
  88. // ---------------------
  89. //
  90. // If you find a bug or a security vulnerability please kindly inform us
  91. // about the problem immediately so that we can fix the security problem
  92. // to protect a lot of users around the world as soon as possible.
  93. //
  94. // Our e-mail address for security reports is:
  95. // softether-vpn-security [at] softether.org
  96. //
  97. // Please note that the above e-mail address is not a technical support
  98. // inquiry address. If you need technical assistance, please visit
  99. // http://www.softether.org/ and ask your question on the users forum.
  100. //
  101. // Thank you for your cooperation.
  102. //
  103. //
  104. // NO MEMORY OR RESOURCE LEAKS
  105. // ---------------------------
  106. //
  107. // The memory-leaks and resource-leaks verification under the stress
  108. // test has been passed before release this source code.
  109. // Protocol.c
  110. // SoftEther protocol related routines
  111. #include "CedarPch.h"
  112. static UCHAR ssl_packet_start[3] = {0x17, 0x03, 0x00};
  113. // Download and save intermediate certificates if necessary
  114. bool DownloadAndSaveIntermediateCertificatesIfNecessary(X *x)
  115. {
  116. LIST *o;
  117. bool ret = false;
  118. // Validate arguments
  119. if (x == NULL)
  120. {
  121. return false;
  122. }
  123. if (x->root_cert)
  124. {
  125. return true;
  126. }
  127. o = NewCertList(true);
  128. ret = TryGetRootCertChain(o, x, true, NULL);
  129. FreeCertList(o);
  130. return ret;
  131. }
  132. // Attempt to fetch the full chain of the specified cert
  133. bool TryGetRootCertChain(LIST *o, X *x, bool auto_save, X **found_root_x)
  134. {
  135. bool ret = false;
  136. LIST *chain = NULL;
  137. LIST *current_chain_dir = NULL;
  138. // Validate arguments
  139. if (o == NULL || x == NULL)
  140. {
  141. return false;
  142. }
  143. chain = NewCertList(false);
  144. ret = TryGetParentCertFromCertList(o, x, chain);
  145. if (ret)
  146. {
  147. UINT i;
  148. DIRLIST *dir;
  149. wchar_t dirname[MAX_SIZE];
  150. wchar_t exedir[MAX_SIZE];
  151. GetExeDirW(exedir, sizeof(exedir));
  152. CombinePathW(dirname, sizeof(dirname), exedir, L"chain_certs");
  153. MakeDirExW(dirname);
  154. if (auto_save)
  155. {
  156. // delete the current auto_save files
  157. dir = EnumDirW(dirname);
  158. if (dir != NULL)
  159. {
  160. for (i = 0;i < dir->NumFiles;i++)
  161. {
  162. DIRENT *e = dir->File[i];
  163. if (e->Folder == false)
  164. {
  165. if (UniStartWith(e->FileNameW, AUTO_DOWNLOAD_CERTS_PREFIX))
  166. {
  167. wchar_t tmp[MAX_SIZE];
  168. CombinePathW(tmp, sizeof(tmp), dirname, e->FileNameW);
  169. FileDeleteW(tmp);
  170. }
  171. }
  172. }
  173. FreeDir(dir);
  174. }
  175. }
  176. current_chain_dir = NewCertList(false);
  177. AddAllChainCertsToCertList(current_chain_dir);
  178. for (i = 0;i < LIST_NUM(chain);i++)
  179. {
  180. wchar_t tmp[MAX_SIZE];
  181. X *xx = LIST_DATA(chain, i);
  182. GetAllNameFromName(tmp, sizeof(tmp), xx->subject_name);
  183. Debug("depth = %u, subject = %S\n", i, tmp);
  184. if (auto_save && CompareX(x, xx) == false && IsXInCertList(current_chain_dir, xx) == false)
  185. {
  186. wchar_t fn[MAX_PATH];
  187. char hex_a[128];
  188. wchar_t hex[128];
  189. UCHAR hash[SHA1_SIZE];
  190. wchar_t tmp[MAX_SIZE];
  191. BUF *b;
  192. GetXDigest(xx, hash, true);
  193. BinToStr(hex_a, sizeof(hex_a), hash, SHA1_SIZE);
  194. StrToUni(hex, sizeof(hex), hex_a);
  195. UniStrCpy(fn, sizeof(fn), AUTO_DOWNLOAD_CERTS_PREFIX);
  196. UniStrCat(fn, sizeof(fn), hex);
  197. UniStrCat(fn, sizeof(fn), L".cer");
  198. CombinePathW(tmp, sizeof(tmp), dirname, fn);
  199. b = XToBuf(xx, true);
  200. DumpBufW(b, tmp);
  201. FreeBuf(b);
  202. }
  203. if (xx->root_cert)
  204. {
  205. if (found_root_x != NULL)
  206. {
  207. *found_root_x = CloneX(xx);
  208. }
  209. }
  210. }
  211. }
  212. FreeCertList(chain);
  213. FreeCertList(current_chain_dir);
  214. return ret;
  215. }
  216. // Try get the parent cert
  217. bool TryGetParentCertFromCertList(LIST *o, X *x, LIST *found_chain)
  218. {
  219. bool ret = false;
  220. X *r;
  221. bool do_free = false;
  222. // Validate arguments
  223. if (o == NULL || x == NULL || found_chain == NULL)
  224. {
  225. return false;
  226. }
  227. if (LIST_NUM(found_chain) >= FIND_CERT_CHAIN_MAX_DEPTH)
  228. {
  229. return false;
  230. }
  231. Add(found_chain, CloneX(x));
  232. if (x->root_cert)
  233. {
  234. return true;
  235. }
  236. r = FindCertIssuerFromCertList(o, x);
  237. if (r == NULL)
  238. {
  239. if (IsEmptyStr(x->issuer_url) == false)
  240. {
  241. r = DownloadCert(x->issuer_url);
  242. if (CheckXEx(x, r, true, true) && CompareX(x, r) == false)
  243. {
  244. // found
  245. do_free = true;
  246. }
  247. else
  248. {
  249. // invalid
  250. FreeX(r);
  251. r = NULL;
  252. }
  253. }
  254. }
  255. if (r != NULL)
  256. {
  257. ret = TryGetParentCertFromCertList(o, r, found_chain);
  258. }
  259. if (do_free)
  260. {
  261. FreeX(r);
  262. }
  263. return ret;
  264. }
  265. // Find the issuer of the cert from the cert list
  266. X *FindCertIssuerFromCertList(LIST *o, X *x)
  267. {
  268. UINT i;
  269. // Validate arguments
  270. if (o == NULL || x == NULL)
  271. {
  272. return NULL;
  273. }
  274. if (x->root_cert)
  275. {
  276. return NULL;
  277. }
  278. for (i = 0;i < LIST_NUM(o);i++)
  279. {
  280. X *xx = LIST_DATA(o, i);
  281. if (CheckXEx(x, xx, true, true))
  282. {
  283. if (CompareX(x, xx) == false)
  284. {
  285. return xx;
  286. }
  287. }
  288. }
  289. return NULL;
  290. }
  291. // Download a cert by using HTTP
  292. X *DownloadCert(char *url)
  293. {
  294. BUF *b;
  295. URL_DATA url_data;
  296. X *ret = NULL;
  297. // Validate arguments
  298. if (IsEmptyStr(url))
  299. {
  300. return NULL;
  301. }
  302. Debug("Trying to download a cert from %s ...\n", url);
  303. if (ParseUrl(&url_data, url, false, NULL) == false)
  304. {
  305. Debug("Download failed.\n");
  306. return NULL;
  307. }
  308. b = HttpRequestEx(&url_data, NULL, CERT_HTTP_DOWNLOAD_TIMEOUT, CERT_HTTP_DOWNLOAD_TIMEOUT,
  309. NULL, false, NULL, NULL, NULL, NULL, NULL, CERT_HTTP_DOWNLOAD_MAXSIZE);
  310. if (b == NULL)
  311. {
  312. Debug("Download failed.\n");
  313. return NULL;
  314. }
  315. ret = BufToX(b, IsBase64(b));
  316. FreeBuf(b);
  317. Debug("Download ok.\n");
  318. return ret;
  319. }
  320. // New cert list
  321. LIST *NewCertList(bool load_root_and_chain)
  322. {
  323. LIST *o;
  324. o = NewList(NULL);
  325. if (load_root_and_chain)
  326. {
  327. AddAllRootCertsToCertList(o);
  328. AddAllChainCertsToCertList(o);
  329. }
  330. return o;
  331. }
  332. // Free cert list
  333. void FreeCertList(LIST *o)
  334. {
  335. UINT i;
  336. // Validate arguments
  337. if (o == NULL)
  338. {
  339. return;
  340. }
  341. for (i = 0;i < LIST_NUM(o);i++)
  342. {
  343. X *x = LIST_DATA(o, i);
  344. FreeX(x);
  345. }
  346. ReleaseList(o);
  347. }
  348. // Check whether the cert is in the cert list
  349. bool IsXInCertList(LIST *o, X *x)
  350. {
  351. UINT i;
  352. // Validate arguments
  353. if (o == NULL || x == NULL)
  354. {
  355. return false;
  356. }
  357. for (i = 0;i < LIST_NUM(o);i++)
  358. {
  359. X *xx = LIST_DATA(o, i);
  360. if (CompareX(x, xx))
  361. {
  362. return true;
  363. }
  364. }
  365. return false;
  366. }
  367. // Add a cert to the cert list
  368. void AddXToCertList(LIST *o, X *x)
  369. {
  370. // Validate arguments
  371. if (o == NULL || x == NULL)
  372. {
  373. return;
  374. }
  375. if (IsXInCertList(o, x))
  376. {
  377. return;
  378. }
  379. if (CheckXDateNow(x) == false)
  380. {
  381. return;
  382. }
  383. Add(o, CloneX(x));
  384. }
  385. // Add all chain certs to the cert list
  386. void AddAllChainCertsToCertList(LIST *o)
  387. {
  388. wchar_t dirname[MAX_SIZE];
  389. wchar_t exedir[MAX_SIZE];
  390. DIRLIST *dir;
  391. // Validate arguments
  392. if (o == NULL)
  393. {
  394. return;
  395. }
  396. GetExeDirW(exedir, sizeof(exedir));
  397. CombinePathW(dirname, sizeof(dirname), exedir, L"chain_certs");
  398. MakeDirExW(dirname);
  399. dir = EnumDirW(dirname);
  400. if (dir != NULL)
  401. {
  402. UINT i;
  403. for (i = 0;i < dir->NumFiles;i++)
  404. {
  405. DIRENT *e = dir->File[i];
  406. if (e->Folder == false)
  407. {
  408. wchar_t tmp[MAX_SIZE];
  409. X *x;
  410. CombinePathW(tmp, sizeof(tmp), dirname, e->FileNameW);
  411. x = FileToXW(tmp);
  412. if (x != NULL)
  413. {
  414. AddXToCertList(o, x);
  415. FreeX(x);
  416. }
  417. }
  418. }
  419. FreeDir(dir);
  420. }
  421. }
  422. // Add all root certs to the cert list
  423. void AddAllRootCertsToCertList(LIST *o)
  424. {
  425. BUF *buf;
  426. PACK *p;
  427. UINT num_ok = 0, num_error = 0;
  428. // Validate arguments
  429. if (o == NULL)
  430. {
  431. return;
  432. }
  433. buf = ReadDump(ROOT_CERTS_FILENAME);
  434. if (buf == NULL)
  435. {
  436. return;
  437. }
  438. p = BufToPack(buf);
  439. if (p != NULL)
  440. {
  441. UINT num = PackGetIndexCount(p, "cert");
  442. UINT i;
  443. for (i = 0;i < num;i++)
  444. {
  445. bool ok = false;
  446. BUF *b = PackGetBufEx(p, "cert", i);
  447. if (b != NULL)
  448. {
  449. X *x = BufToX(b, false);
  450. if (x != NULL)
  451. {
  452. AddXToCertList(o, x);
  453. ok = true;
  454. FreeX(x);
  455. }
  456. FreeBuf(b);
  457. }
  458. if (ok)
  459. {
  460. num_ok++;
  461. }
  462. else
  463. {
  464. num_error++;
  465. }
  466. }
  467. FreePack(p);
  468. }
  469. FreeBuf(buf);
  470. Debug("AddAllRootCertsToCertList: ok=%u error=%u total_list_len=%u\n", num_ok, num_error, LIST_NUM(o));
  471. }
  472. // Convert the date of YYYYMMDD format to a number
  473. UINT64 ShortStrToDate64(char *str)
  474. {
  475. UINT v;
  476. SYSTEMTIME st;
  477. // Validate arguments
  478. if (str == NULL)
  479. {
  480. return 0;
  481. }
  482. v = ToInt(str);
  483. Zero(&st, sizeof(st));
  484. st.wYear = (v % 100000000) / 10000;
  485. st.wMonth = (v % 10000) / 100;
  486. st.wDay = v % 100;
  487. return SystemToUINT64(&st);
  488. }
  489. // Handle the response that is returned from the server in the update client
  490. void UpdateClientThreadProcessResults(UPDATE_CLIENT *c, BUF *b)
  491. {
  492. bool exit = false;
  493. // Validate arguments
  494. if (c == NULL || b == NULL)
  495. {
  496. return;
  497. }
  498. SeekBufToBegin(b);
  499. while (true)
  500. {
  501. char *line = CfgReadNextLine(b);
  502. if (line == NULL)
  503. {
  504. break;
  505. }
  506. Trim(line);
  507. if (StartWith(line, "#") == false && IsEmptyStr(line) == false)
  508. {
  509. TOKEN_LIST *t = ParseTokenWithNullStr(line, " \t");
  510. if (t != NULL)
  511. {
  512. if (t->NumTokens >= 5)
  513. {
  514. if (StrCmpi(t->Token[0], c->FamilyName) == 0)
  515. {
  516. // Match
  517. UINT64 date = ShortStrToDate64(t->Token[1]);
  518. if (date != 0)
  519. {
  520. UINT build = ToInt(t->Token[2]);
  521. if (build != 0)
  522. {
  523. if (build > c->MyBuild && build > c->LatestBuild && build > c->Setting.LatestIgnoreBuild)
  524. {
  525. c->Callback(c, build, date, t->Token[3], t->Token[4], &c->HaltFlag, c->Param);
  526. c->LatestBuild = build;
  527. exit = true;
  528. }
  529. }
  530. }
  531. }
  532. }
  533. FreeToken(t);
  534. }
  535. }
  536. Free(line);
  537. if (exit)
  538. {
  539. break;
  540. }
  541. }
  542. }
  543. // Update client main process
  544. void UpdateClientThreadMain(UPDATE_CLIENT *c)
  545. {
  546. char url[MAX_SIZE];
  547. char id[MAX_SIZE];
  548. URL_DATA data;
  549. BUF *cert_hash;
  550. UINT ret = 0;
  551. BUF *recv;
  552. // Validate arguments
  553. if (c == NULL)
  554. {
  555. return;
  556. }
  557. // Generate the URL
  558. Format(url, sizeof(url), IsUseAlternativeHostname() ? UPDATE_SERVER_URL_CHINA : UPDATE_SERVER_URL_GLOBAL, c->FamilyName, c->SoftwareName, c->MyBuild, c->MyLanguage);
  559. if (IsEmptyStr(c->ClientId) == false)
  560. {
  561. Format(id, sizeof(id), "&id=%s", c->ClientId);
  562. StrCat(url, sizeof(url), id);
  563. }
  564. // Get a text file at this URL
  565. if (ParseUrl(&data, url, false, NULL) == false)
  566. {
  567. return;
  568. }
  569. cert_hash = StrToBin(UPDATE_SERVER_CERT_HASH);
  570. recv = HttpRequestEx2(&data, NULL, UPDATE_CONNECT_TIMEOUT, UPDATE_COMM_TIMEOUT, &ret, false, NULL, NULL,
  571. NULL, ((cert_hash != NULL && cert_hash->Size == SHA1_SIZE) ? cert_hash->Buf : NULL),
  572. (bool *)&c->HaltFlag, 0, NULL, NULL);
  573. FreeBuf(cert_hash);
  574. if (recv != NULL)
  575. {
  576. UpdateClientThreadProcessResults(c, recv);
  577. FreeBuf(recv);
  578. }
  579. }
  580. // Update client main thread
  581. void UpdateClientThreadProc(THREAD *thread, void *param)
  582. {
  583. UPDATE_CLIENT *c = (UPDATE_CLIENT *)param;
  584. bool first_loop = true;
  585. // Validate arguments
  586. if (thread == NULL || param == NULL)
  587. {
  588. return;
  589. }
  590. while (true)
  591. {
  592. // Termination check
  593. if (c->HaltFlag)
  594. {
  595. break;
  596. }
  597. if (first_loop == false)
  598. {
  599. // Wait for the foreground
  600. if (c->IsForegroundCb != NULL)
  601. {
  602. while (true)
  603. {
  604. if (c->HaltFlag)
  605. {
  606. break;
  607. }
  608. if (c->IsForegroundCb(c, c->Param))
  609. {
  610. break;
  611. }
  612. Wait(c->HaltEvent, 1000);
  613. }
  614. }
  615. }
  616. first_loop = false;
  617. if (c->HaltFlag)
  618. {
  619. break;
  620. }
  621. if (c->Setting.DisableCheck == false)
  622. {
  623. UpdateClientThreadMain(c);
  624. }
  625. // Wait until the next attempt
  626. Wait(c->HaltEvent, GenRandInterval(UPDATE_CHECK_INTERVAL_MIN, UPDATE_CHECK_INTERVAL_MAX));
  627. }
  628. }
  629. // Update the configuration of the update client
  630. void SetUpdateClientSetting(UPDATE_CLIENT *c, UPDATE_CLIENT_SETTING *s)
  631. {
  632. bool old_disable;
  633. // Validate arguments
  634. if (c == NULL || s == NULL)
  635. {
  636. return;
  637. }
  638. old_disable = c->Setting.DisableCheck;
  639. Copy(&c->Setting, s, sizeof(UPDATE_CLIENT_SETTING));
  640. Set(c->HaltEvent);
  641. }
  642. // Start the update client
  643. UPDATE_CLIENT *NewUpdateClient(UPDATE_NOTIFY_PROC *cb, UPDATE_ISFOREGROUND_PROC *isforeground_cb, void *param, char *family_name, char *software_name, wchar_t *software_title, UINT my_build, UINT64 my_date, char *my_lang, UPDATE_CLIENT_SETTING *current_setting, char *client_id)
  644. {
  645. UPDATE_CLIENT *c;
  646. // Validate arguments
  647. if (family_name == NULL || software_title == NULL || software_name == NULL || my_build == 0 ||
  648. my_lang == NULL || current_setting == NULL || cb == NULL)
  649. {
  650. return NULL;
  651. }
  652. c = ZeroMalloc(sizeof(UPDATE_CLIENT));
  653. c->Callback = cb;
  654. c->IsForegroundCb = isforeground_cb;
  655. StrCpy(c->ClientId, sizeof(c->ClientId), client_id);
  656. StrCpy(c->FamilyName, sizeof(c->FamilyName), family_name);
  657. StrCpy(c->SoftwareName, sizeof(c->SoftwareName), software_name);
  658. UniStrCpy(c->SoftwareTitle, sizeof(c->SoftwareTitle), software_title);
  659. c->MyBuild = my_build;
  660. c->MyDate = my_date;
  661. StrCpy(c->MyLanguage, sizeof(c->MyLanguage), my_lang);
  662. Copy(&c->Setting, current_setting, sizeof(c->Setting));
  663. c->Param = param;
  664. c->HaltEvent = NewEvent();
  665. // Create a thread
  666. c->Thread = NewThread(UpdateClientThreadProc, c);
  667. return c;
  668. }
  669. // Terminate the update client
  670. void FreeUpdateClient(UPDATE_CLIENT *c)
  671. {
  672. // Validate arguments
  673. if (c == NULL)
  674. {
  675. return;
  676. }
  677. // Thread stop
  678. c->HaltFlag = true;
  679. Set(c->HaltEvent);
  680. // Wait for thread termination
  681. WaitThread(c->Thread, INFINITE);
  682. ReleaseThread(c->Thread);
  683. ReleaseEvent(c->HaltEvent);
  684. Free(c);
  685. }
  686. // Generate unique IDs for each machine
  687. void GenerateMachineUniqueHash(void *data)
  688. {
  689. BUF *b;
  690. char name[64];
  691. OS_INFO *osinfo;
  692. UINT64 iphash = 0;
  693. // Validate arguments
  694. if (data == NULL)
  695. {
  696. return;
  697. }
  698. iphash = GetHostIPAddressListHash();
  699. b = NewBuf();
  700. GetMachineName(name, sizeof(name));
  701. osinfo = GetOsInfo();
  702. WriteBuf(b, name, StrLen(name));
  703. WriteBufInt64(b, iphash);
  704. WriteBuf(b, &osinfo->OsType, sizeof(osinfo->OsType));
  705. WriteBuf(b, osinfo->KernelName, StrLen(osinfo->KernelName));
  706. WriteBuf(b, osinfo->KernelVersion, StrLen(osinfo->KernelVersion));
  707. WriteBuf(b, osinfo->OsProductName, StrLen(osinfo->OsProductName));
  708. WriteBuf(b, &osinfo->OsServicePack, sizeof(osinfo->OsServicePack));
  709. WriteBuf(b, osinfo->OsSystemName, StrLen(osinfo->OsSystemName));
  710. WriteBuf(b, osinfo->OsVendorName, StrLen(osinfo->OsVendorName));
  711. WriteBuf(b, osinfo->OsVersion, StrLen(osinfo->OsVersion));
  712. Hash(data, b->Buf, b->Size, true);
  713. FreeBuf(b);
  714. }
  715. // Convert a node information to a string
  716. void NodeInfoToStr(wchar_t *str, UINT size, NODE_INFO *info)
  717. {
  718. char client_ip[128], server_ip[128], proxy_ip[128], unique_id[128];
  719. // Validate arguments
  720. if (str == NULL || info == NULL)
  721. {
  722. return;
  723. }
  724. IPToStr4or6(client_ip, sizeof(client_ip), info->ClientIpAddress, info->ClientIpAddress6);
  725. IPToStr4or6(server_ip, sizeof(server_ip), info->ServerIpAddress, info->ServerIpAddress6);
  726. IPToStr4or6(proxy_ip, sizeof(proxy_ip), info->ProxyIpAddress, info->ProxyIpAddress6);
  727. BinToStr(unique_id, sizeof(unique_id), info->UniqueId, sizeof(info->UniqueId));
  728. UniFormat(str, size, _UU("LS_NODE_INFO_TAG"), info->ClientProductName,
  729. Endian32(info->ClientProductVer), Endian32(info->ClientProductBuild),
  730. info->ServerProductName, Endian32(info->ServerProductVer), Endian32(info->ServerProductBuild),
  731. info->ClientOsName, info->ClientOsVer, info->ClientOsProductId,
  732. info->ClientHostname, client_ip, Endian32(info->ClientPort),
  733. info->ServerHostname, server_ip, Endian32(info->ServerPort),
  734. info->ProxyHostname, proxy_ip, Endian32(info->ProxyPort),
  735. info->HubName, unique_id);
  736. }
  737. // Comparison of node information
  738. bool CompareNodeInfo(NODE_INFO *a, NODE_INFO *b)
  739. {
  740. // Validate arguments
  741. if (a == NULL || b == NULL)
  742. {
  743. return false;
  744. }
  745. if (StrCmp(a->ClientProductName, b->ClientProductName) != 0)
  746. {
  747. return false;
  748. }
  749. if (a->ClientProductVer != b->ClientProductVer)
  750. {
  751. return false;
  752. }
  753. if (a->ClientProductBuild != b->ClientProductBuild)
  754. {
  755. return false;
  756. }
  757. if (StrCmp(a->ServerProductName, b->ServerProductName) != 0)
  758. {
  759. return false;
  760. }
  761. if (a->ServerProductVer != b->ServerProductVer)
  762. {
  763. return false;
  764. }
  765. if (a->ServerProductBuild != b->ServerProductBuild)
  766. {
  767. return false;
  768. }
  769. if (StrCmp(a->ClientOsName, b->ClientOsName) != 0)
  770. {
  771. return false;
  772. }
  773. if (StrCmp(a->ClientOsVer, b->ClientOsVer) != 0)
  774. {
  775. return false;
  776. }
  777. if (StrCmp(a->ClientOsProductId, b->ClientOsProductId) != 0)
  778. {
  779. return false;
  780. }
  781. if (StrCmp(a->ClientHostname, b->ClientHostname) != 0)
  782. {
  783. return false;
  784. }
  785. if (a->ClientIpAddress != b->ClientIpAddress)
  786. {
  787. return false;
  788. }
  789. if (StrCmp(a->ServerHostname, b->ServerHostname) != 0)
  790. {
  791. return false;
  792. }
  793. if (a->ServerIpAddress != b->ServerIpAddress)
  794. {
  795. return false;
  796. }
  797. if (a->ServerPort != b->ServerPort)
  798. {
  799. return false;
  800. }
  801. if (StrCmp(a->ProxyHostname, b->ProxyHostname) != 0)
  802. {
  803. return false;
  804. }
  805. if (a->ProxyIpAddress != b->ProxyIpAddress)
  806. {
  807. return false;
  808. }
  809. if (a->ProxyPort != b->ProxyPort)
  810. {
  811. return false;
  812. }
  813. if (StrCmp(a->HubName, b->HubName) != 0)
  814. {
  815. return false;
  816. }
  817. if (Cmp(a->UniqueId, b->UniqueId, 16) != 0)
  818. {
  819. return false;
  820. }
  821. return true;
  822. }
  823. // Accept the password change
  824. UINT ChangePasswordAccept(CONNECTION *c, PACK *p)
  825. {
  826. CEDAR *cedar;
  827. UCHAR random[SHA1_SIZE];
  828. char hubname[MAX_HUBNAME_LEN + 1];
  829. char username[MAX_USERNAME_LEN + 1];
  830. UCHAR secure_old_password[SHA1_SIZE];
  831. UCHAR new_password[SHA1_SIZE];
  832. UCHAR new_password_ntlm[SHA1_SIZE];
  833. UCHAR check_secure_old_password[SHA1_SIZE];
  834. UINT ret = ERR_NO_ERROR;
  835. HUB *hub;
  836. bool save = false;
  837. // Validate arguments
  838. if (c == NULL || p == NULL)
  839. {
  840. return ERR_INTERNAL_ERROR;
  841. }
  842. Copy(random, c->Random, SHA1_SIZE);
  843. if (PackGetStr(p, "hubname", hubname, sizeof(hubname)) == false ||
  844. PackGetStr(p, "username", username, sizeof(username)) == false ||
  845. PackGetData2(p, "secure_old_password", secure_old_password, sizeof(secure_old_password)) == false ||
  846. PackGetData2(p, "new_password", new_password, sizeof(new_password)) == false)
  847. {
  848. return ERR_PROTOCOL_ERROR;
  849. }
  850. if (PackGetData2(p, "new_password_ntlm", new_password_ntlm, MD5_SIZE) == false)
  851. {
  852. Zero(new_password_ntlm, sizeof(new_password_ntlm));
  853. }
  854. cedar = c->Cedar;
  855. LockHubList(cedar);
  856. {
  857. hub = GetHub(cedar, hubname);
  858. }
  859. UnlockHubList(cedar);
  860. if (hub == NULL)
  861. {
  862. ret = ERR_HUB_NOT_FOUND;
  863. }
  864. else
  865. {
  866. char tmp[MAX_SIZE];
  867. if (GetHubAdminOption(hub, "deny_change_user_password") != 0)
  868. {
  869. ReleaseHub(hub);
  870. return ERR_NOT_ENOUGH_RIGHT;
  871. }
  872. IPToStr(tmp, sizeof(tmp), &c->FirstSock->RemoteIP);
  873. HLog(hub, "LH_CHANGE_PASSWORD_1", c->Name, tmp);
  874. AcLock(hub);
  875. {
  876. USER *u = AcGetUser(hub, username);
  877. if (u == NULL)
  878. {
  879. HLog(hub, "LH_CHANGE_PASSWORD_2", c->Name, username);
  880. ret = ERR_OLD_PASSWORD_WRONG;
  881. }
  882. else
  883. {
  884. Lock(u->lock);
  885. {
  886. if (u->AuthType != AUTHTYPE_PASSWORD)
  887. {
  888. // Not a password authentication
  889. HLog(hub, "LH_CHANGE_PASSWORD_3", c->Name, username);
  890. ret = ERR_USER_AUTHTYPE_NOT_PASSWORD;
  891. }
  892. else
  893. {
  894. bool fix_password = false;
  895. if (u->Policy != NULL)
  896. {
  897. fix_password = u->Policy->FixPassword;
  898. }
  899. else
  900. {
  901. if (u->Group != NULL)
  902. {
  903. if (u->Group->Policy != NULL)
  904. {
  905. fix_password = u->Group->Policy->FixPassword;
  906. }
  907. }
  908. }
  909. if (fix_password == false)
  910. {
  911. // Confirmation of the old password
  912. AUTHPASSWORD *pw = (AUTHPASSWORD *)u->AuthData;
  913. SecurePassword(check_secure_old_password, pw->HashedKey, random);
  914. if (Cmp(check_secure_old_password, secure_old_password, SHA1_SIZE) != 0)
  915. {
  916. // Old password is incorrect
  917. ret = ERR_OLD_PASSWORD_WRONG;
  918. HLog(hub, "LH_CHANGE_PASSWORD_4", c->Name, username);
  919. }
  920. else
  921. {
  922. // Write a new password
  923. if (Cmp(pw->HashedKey, new_password, SHA1_SIZE) != 0 || IsZero(pw->NtLmSecureHash, MD5_SIZE))
  924. {
  925. Copy(pw->HashedKey, new_password, SHA1_SIZE);
  926. Copy(pw->NtLmSecureHash, new_password_ntlm, MD5_SIZE);
  927. }
  928. HLog(hub, "LH_CHANGE_PASSWORD_5", c->Name, username);
  929. save = true;
  930. }
  931. }
  932. else
  933. {
  934. // Password change is prohibited
  935. ret = ERR_NOT_ENOUGH_RIGHT;
  936. }
  937. }
  938. }
  939. Unlock(u->lock);
  940. ReleaseUser(u);
  941. }
  942. }
  943. AcUnlock(hub);
  944. ReleaseHub(hub);
  945. }
  946. return ret;
  947. }
  948. // Change the password
  949. UINT ChangePassword(CEDAR *cedar, CLIENT_OPTION *o, char *hubname, char *username, char *old_pass, char *new_pass)
  950. {
  951. UINT ret = ERR_NO_ERROR;
  952. UCHAR old_password[SHA1_SIZE];
  953. UCHAR secure_old_password[SHA1_SIZE];
  954. UCHAR new_password[SHA1_SIZE];
  955. UCHAR new_password_ntlm[MD5_SIZE];
  956. SOCK *sock;
  957. SESSION *s;
  958. // Validate arguments
  959. if (cedar == NULL || o == NULL || hubname == NULL || username == NULL || old_pass == NULL || new_pass == NULL)
  960. {
  961. return ERR_INTERNAL_ERROR;
  962. }
  963. // Create a session
  964. s = NewRpcSessionEx(cedar, o, &ret, NULL);
  965. if (s != NULL)
  966. {
  967. PACK *p = NewPack();
  968. sock = s->Connection->FirstSock;
  969. HashPassword(old_password, username, old_pass);
  970. SecurePassword(secure_old_password, old_password, s->Connection->Random);
  971. HashPassword(new_password, username, new_pass);
  972. GenerateNtPasswordHash(new_password_ntlm, new_pass);
  973. PackAddClientVersion(p, s->Connection);
  974. PackAddStr(p, "method", "password");
  975. PackAddStr(p, "hubname", hubname);
  976. PackAddStr(p, "username", username);
  977. PackAddData(p, "secure_old_password", secure_old_password, SHA1_SIZE);
  978. PackAddData(p, "new_password", new_password, SHA1_SIZE);
  979. PackAddData(p, "new_password_ntlm", new_password_ntlm, MD5_SIZE);
  980. if (HttpClientSend(sock, p))
  981. {
  982. PACK *p = HttpClientRecv(sock);
  983. if (p == NULL)
  984. {
  985. ret = ERR_DISCONNECTED;
  986. }
  987. else
  988. {
  989. ret = GetErrorFromPack(p);
  990. }
  991. FreePack(p);
  992. }
  993. else
  994. {
  995. ret = ERR_DISCONNECTED;
  996. }
  997. FreePack(p);
  998. ReleaseSession(s);
  999. }
  1000. return ret;
  1001. }
  1002. // Enumerate HUBs
  1003. TOKEN_LIST *EnumHub(SESSION *s)
  1004. {
  1005. SOCK *sock;
  1006. TOKEN_LIST *ret;
  1007. PACK *p;
  1008. UINT num;
  1009. UINT i;
  1010. // Validate arguments
  1011. if (s == NULL || s->Connection == NULL)
  1012. {
  1013. return NULL;
  1014. }
  1015. sock = s->Connection->FirstSock;
  1016. if (sock == NULL)
  1017. {
  1018. return NULL;
  1019. }
  1020. // Set the Timeout
  1021. SetTimeout(sock, 10000);
  1022. p = NewPack();
  1023. PackAddStr(p, "method", "enum_hub");
  1024. PackAddClientVersion(p, s->Connection);
  1025. if (HttpClientSend(sock, p) == false)
  1026. {
  1027. FreePack(p);
  1028. return NULL;
  1029. }
  1030. FreePack(p);
  1031. p = HttpClientRecv(sock);
  1032. if (p == NULL)
  1033. {
  1034. return NULL;
  1035. }
  1036. num = PackGetInt(p, "NumHub");
  1037. ret = ZeroMalloc(sizeof(TOKEN_LIST));
  1038. ret->NumTokens = num;
  1039. ret->Token = ZeroMalloc(sizeof(char *) * num);
  1040. for (i = 0;i < num;i++)
  1041. {
  1042. char tmp[MAX_SIZE];
  1043. if (PackGetStrEx(p, "HubName", tmp, sizeof(tmp), i))
  1044. {
  1045. ret->Token[i] = CopyStr(tmp);
  1046. }
  1047. }
  1048. FreePack(p);
  1049. return ret;
  1050. }
  1051. // Server accepts a connection from client
  1052. bool ServerAccept(CONNECTION *c)
  1053. {
  1054. bool ret = false;
  1055. UINT err;
  1056. PACK *p;
  1057. char username_real[MAX_SIZE];
  1058. char method[MAX_SIZE];
  1059. char hubname[MAX_SIZE];
  1060. char username[MAX_SIZE];
  1061. char groupname[MAX_SIZE];
  1062. UCHAR session_key[SHA1_SIZE];
  1063. UCHAR ticket[SHA1_SIZE];
  1064. RC4_KEY_PAIR key_pair;
  1065. UINT authtype;
  1066. POLICY *policy;
  1067. UINT assigned_vlan_id = 0;
  1068. HUB *hub;
  1069. SESSION *s = NULL;
  1070. UINT64 user_expires = 0;
  1071. bool use_encrypt;
  1072. bool use_compress;
  1073. bool half_connection;
  1074. UINT adjust_mss;
  1075. bool use_udp_acceleration_client;
  1076. bool support_hmac_on_udp_acceleration_client = false;
  1077. bool support_udp_accel_fast_disconnect_detect;
  1078. bool use_hmac_on_udp_acceleration = false;
  1079. bool supress_return_pack_error = false;
  1080. IP udp_acceleration_client_ip;
  1081. UCHAR udp_acceleration_client_key[UDP_ACCELERATION_COMMON_KEY_SIZE];
  1082. UINT udp_acceleration_client_port;
  1083. bool use_fast_rc4;
  1084. bool admin_mode = false;
  1085. UINT direction;
  1086. UINT max_connection;
  1087. UINT timeout;
  1088. bool no_reconnect_to_session = false;
  1089. bool farm_controller = false;
  1090. bool farm_member = false;
  1091. bool farm_mode = false;
  1092. bool require_bridge_routing_mode;
  1093. bool require_monitor_mode;
  1094. bool support_bulk_on_rudp = false;
  1095. bool support_hmac_on_bulk_of_rudp = false;
  1096. bool support_udp_recovery = false;
  1097. bool enable_bulk_on_rudp = false;
  1098. bool enable_udp_recovery = false;
  1099. bool enable_hmac_on_bulk_of_rudp = false;
  1100. bool use_client_license = false, use_bridge_license = false;
  1101. bool local_host_session = false;
  1102. char sessionname[MAX_SESSION_NAME_LEN + 1];
  1103. bool is_server_or_bridge = false;
  1104. bool qos = false;
  1105. bool cluster_dynamic_secure_nat = false;
  1106. bool no_save_password = false;
  1107. NODE_INFO node;
  1108. wchar_t *msg = NULL;
  1109. bool suppress_client_update_notification = false;
  1110. USER *loggedin_user_object = NULL;
  1111. FARM_MEMBER *f = NULL;
  1112. SERVER *server = NULL;
  1113. POLICY ticketed_policy;
  1114. UINT64 timestamp;
  1115. UCHAR unique[SHA1_SIZE], unique2[SHA1_SIZE];
  1116. CEDAR *cedar;
  1117. RPC_WINVER winver;
  1118. UINT client_id;
  1119. bool no_more_users_in_server = false;
  1120. UCHAR mschap_v2_server_response_20[20];
  1121. UINT ms_chap_error = 0;
  1122. bool is_empty_password = false;
  1123. char *error_detail = NULL;
  1124. char *error_detail_2 = NULL;
  1125. char ctoken_hash_str[64];
  1126. EAP_CLIENT *release_me_eap_client = NULL;
  1127. // Validate arguments
  1128. if (c == NULL)
  1129. {
  1130. return false;
  1131. }
  1132. GenerateMachineUniqueHash(unique2);
  1133. Zero(ctoken_hash_str, sizeof(ctoken_hash_str));
  1134. Zero(mschap_v2_server_response_20, sizeof(mschap_v2_server_response_20));
  1135. Zero(&udp_acceleration_client_ip, sizeof(udp_acceleration_client_ip));
  1136. udp_acceleration_client_port = 0;
  1137. Zero(udp_acceleration_client_key, sizeof(udp_acceleration_client_key));
  1138. Zero(&winver, sizeof(winver));
  1139. StrCpy(groupname, sizeof(groupname), "");
  1140. StrCpy(sessionname, sizeof(sessionname), "");
  1141. if (IsZero(c->CToken_Hash, SHA1_SIZE) == false)
  1142. {
  1143. BinToStr(ctoken_hash_str, sizeof(ctoken_hash_str), c->CToken_Hash, SHA1_SIZE);
  1144. }
  1145. cedar = c->Cedar;
  1146. // Get the license status
  1147. no_more_users_in_server = SiTooManyUserObjectsInServer(cedar->Server, true);
  1148. c->Status = CONNECTION_STATUS_NEGOTIATION;
  1149. if (c->Cedar->Server != NULL)
  1150. {
  1151. SERVER *s = c->Cedar->Server;
  1152. server = s;
  1153. if (s->ServerType == SERVER_TYPE_FARM_MEMBER)
  1154. {
  1155. farm_member = true;
  1156. farm_mode = true;
  1157. }
  1158. if (s->ServerType == SERVER_TYPE_FARM_CONTROLLER)
  1159. {
  1160. farm_controller = true;
  1161. farm_mode = true;
  1162. }
  1163. }
  1164. // Receive the signature
  1165. Debug("Downloading Signature...\n");
  1166. error_detail_2 = NULL;
  1167. if (ServerDownloadSignature(c, &error_detail_2) == false)
  1168. {
  1169. if (error_detail_2 == NULL)
  1170. {
  1171. error_detail = "ServerDownloadSignature";
  1172. }
  1173. else
  1174. {
  1175. error_detail = error_detail_2;
  1176. }
  1177. supress_return_pack_error = true;
  1178. goto CLEANUP;
  1179. }
  1180. // Send a Hello packet
  1181. Debug("Uploading Hello...\n");
  1182. if (ServerUploadHello(c) == false)
  1183. {
  1184. error_detail = "ServerUploadHello";
  1185. goto CLEANUP;
  1186. }
  1187. // Receive the authentication data
  1188. Debug("Auth...\n");
  1189. p = HttpServerRecv(c->FirstSock);
  1190. if (p == NULL)
  1191. {
  1192. // The connection disconnected
  1193. c->Err = ERR_DISCONNECTED;
  1194. error_detail = "RecvAuth1";
  1195. goto CLEANUP;
  1196. }
  1197. if (err = GetErrorFromPack(p))
  1198. {
  1199. // An error has occured
  1200. FreePack(p);
  1201. c->Err = err;
  1202. error_detail = "RecvAuth2";
  1203. goto CLEANUP;
  1204. }
  1205. // Get the method
  1206. if (GetMethodFromPack(p, method, sizeof(method)) == false)
  1207. {
  1208. // Protocol error
  1209. FreePack(p);
  1210. c->Err = ERR_PROTOCOL_ERROR;
  1211. error_detail = "GetMethodFromPack";
  1212. goto CLEANUP;
  1213. }
  1214. // Brand string for the connection limit
  1215. {
  1216. char tmp[20];
  1217. char *branded_ctos = _SS("BRANDED_C_TO_S");
  1218. PackGetStr(p, "branded_ctos", tmp, sizeof(tmp));
  1219. if(StrCmpi(method, "login") == 0 && StrLen(branded_ctos) > 0 && StrCmpi(branded_ctos, tmp) != 0)
  1220. {
  1221. FreePack(p);
  1222. c->Err = ERR_BRANDED_C_TO_S;
  1223. goto CLEANUP;
  1224. }
  1225. }
  1226. // Time inspection
  1227. timestamp = PackGetInt64(p, "timestamp");
  1228. if (timestamp != 0)
  1229. {
  1230. UINT64 now = SystemTime64();
  1231. UINT64 abs;
  1232. if (now >= timestamp)
  1233. {
  1234. abs = now - timestamp;
  1235. }
  1236. else
  1237. {
  1238. abs = timestamp - now;
  1239. }
  1240. if (abs > ALLOW_TIMESTAMP_DIFF)
  1241. {
  1242. // Time difference is too large
  1243. FreePack(p);
  1244. c->Err = ERR_BAD_CLOCK;
  1245. error_detail = "ERR_BAD_CLOCK";
  1246. goto CLEANUP;
  1247. }
  1248. }
  1249. // Get the client version
  1250. PackGetStr(p, "client_str", c->ClientStr, sizeof(c->ClientStr));
  1251. c->ClientVer = PackGetInt(p, "client_ver");
  1252. c->ClientBuild = PackGetInt(p, "client_build");
  1253. if (SearchStrEx(c->ClientStr, "server", 0, false) != INFINITE ||
  1254. SearchStrEx(c->ClientStr, "bridge", 0, false) != INFINITE)
  1255. {
  1256. is_server_or_bridge = true;
  1257. }
  1258. // Get the client Windows version
  1259. InRpcWinVer(&winver, p);
  1260. DecrementNoSsl(c->Cedar, &c->FirstSock->RemoteIP, 2);
  1261. if (StrCmpi(method, "login") == 0)
  1262. {
  1263. bool auth_ret = false;
  1264. Debug("Login...\n");
  1265. c->Status = CONNECTION_STATUS_USERAUTH;
  1266. c->Type = CONNECTION_TYPE_LOGIN;
  1267. if (no_more_users_in_server)
  1268. {
  1269. // There are many users than are allowed in the VPN Server
  1270. FreePack(p);
  1271. c->Err = ERR_TOO_MANY_USER;
  1272. error_detail = "ERR_TOO_MANY_USER";
  1273. goto CLEANUP;
  1274. }
  1275. // Such as the client name
  1276. if (PackGetStr(p, "hello", c->ClientStr, sizeof(c->ClientStr)) == false)
  1277. {
  1278. StrCpy(c->ClientStr, sizeof(c->ClientStr), "Unknown");
  1279. }
  1280. c->ServerVer = CEDAR_VER;
  1281. c->ServerBuild = CEDAR_BUILD;
  1282. // Get the NODE_INFO
  1283. Zero(&node, sizeof(node));
  1284. InRpcNodeInfo(&node, p);
  1285. // Protocol
  1286. c->Protocol = GetProtocolFromPack(p);
  1287. if (c->Protocol == CONNECTION_UDP)
  1288. {
  1289. // Release the structure of the TCP connection
  1290. if (c->Tcp)
  1291. {
  1292. ReleaseList(c->Tcp->TcpSockList);
  1293. Free(c->Tcp);
  1294. }
  1295. }
  1296. if (GetServerCapsBool(c->Cedar->Server, "b_vpn_client_connect") == false)
  1297. {
  1298. // VPN client is unable to connect
  1299. FreePack(p);
  1300. c->Err = ERR_NOT_SUPPORTED;
  1301. goto CLEANUP;
  1302. }
  1303. // Login
  1304. if (GetHubnameAndUsernameFromPack(p, username, sizeof(username), hubname, sizeof(hubname)) == false)
  1305. {
  1306. // Protocol error
  1307. FreePack(p);
  1308. c->Err = ERR_PROTOCOL_ERROR;
  1309. error_detail = "GetHubnameAndUsernameFromPack";
  1310. goto CLEANUP;
  1311. }
  1312. if (farm_member)
  1313. {
  1314. bool ok = false;
  1315. UINT authtype;
  1316. authtype = GetAuthTypeFromPack(p);
  1317. if (StrCmpi(username, ADMINISTRATOR_USERNAME) == 0 &&
  1318. authtype == AUTHTYPE_PASSWORD)
  1319. {
  1320. ok = true;
  1321. }
  1322. if (authtype == AUTHTYPE_TICKET)
  1323. {
  1324. ok = true;
  1325. }
  1326. if (ok == false)
  1327. {
  1328. // Logging on directly to server farm members by
  1329. // non-Administrators are prohibited
  1330. FreePack(p);
  1331. SLog(c->Cedar, "LS_FARMMEMBER_NOT_ADMIN", c->Name, hubname, ADMINISTRATOR_USERNAME, username);
  1332. c->Err = ERR_ACCESS_DENIED;
  1333. goto CLEANUP;
  1334. }
  1335. }
  1336. Debug("Username = %s, HubName = %s\n", username, hubname);
  1337. LockHubList(c->Cedar);
  1338. {
  1339. hub = GetHub(c->Cedar, hubname);
  1340. }
  1341. UnlockHubList(c->Cedar);
  1342. if (hub == NULL)
  1343. {
  1344. // The HUB does not exist
  1345. FreePack(p);
  1346. c->Err = ERR_HUB_NOT_FOUND;
  1347. SLog(c->Cedar, "LS_HUB_NOT_FOUND", c->Name, hubname);
  1348. error_detail = "ERR_HUB_NOT_FOUND";
  1349. goto CLEANUP;
  1350. }
  1351. if (hub->ForceDisableComm)
  1352. {
  1353. // Commnunication function is disabled
  1354. FreePack(p);
  1355. c->Err = ERR_SERVER_CANT_ACCEPT;
  1356. error_detail = "ERR_COMM_DISABLED";
  1357. ReleaseHub(hub);
  1358. goto CLEANUP;
  1359. }
  1360. if (GetGlobalServerFlag(GSF_DISABLE_AC) == 0)
  1361. {
  1362. if (hub->HubDb != NULL && c->FirstSock != NULL)
  1363. {
  1364. IP ip;
  1365. Copy(&ip, &c->FirstSock->RemoteIP, sizeof(IP));
  1366. if (IsIpDeniedByAcList(&ip, hub->HubDb->AcList))
  1367. {
  1368. char ip_str[64];
  1369. // Access denied
  1370. ReleaseHub(hub);
  1371. hub = NULL;
  1372. FreePack(p);
  1373. c->Err = ERR_IP_ADDRESS_DENIED;
  1374. IPToStr(ip_str, sizeof(ip_str), &ip);
  1375. SLog(c->Cedar, "LS_IP_DENIED", c->Name, ip_str);
  1376. goto CLEANUP;
  1377. }
  1378. }
  1379. }
  1380. Lock(hub->lock);
  1381. {
  1382. UINT cert_size = 0;
  1383. void *cert_buf = NULL;
  1384. USER *user;
  1385. USERGROUP *group;
  1386. char plain_password[MAX_PASSWORD_LEN + 1];
  1387. RADIUS_LOGIN_OPTION radius_login_opt;
  1388. if (hub->Halt || hub->Offline)
  1389. {
  1390. // HUB is off-line
  1391. FreePack(p);
  1392. Unlock(hub->lock);
  1393. ReleaseHub(hub);
  1394. c->Err = ERR_HUB_STOPPING;
  1395. goto CLEANUP;
  1396. }
  1397. Zero(&radius_login_opt, sizeof(radius_login_opt));
  1398. if (hub->Option != NULL)
  1399. {
  1400. radius_login_opt.In_CheckVLanId = hub->Option->AssignVLanIdByRadiusAttribute;
  1401. radius_login_opt.In_DenyNoVlanId = hub->Option->DenyAllRadiusLoginWithNoVlanAssign;
  1402. }
  1403. // Get the various flags
  1404. use_encrypt = PackGetInt(p, "use_encrypt") == 0 ? false : true;
  1405. use_compress = PackGetInt(p, "use_compress") == 0 ? false : true;
  1406. max_connection = PackGetInt(p, "max_connection");
  1407. half_connection = PackGetInt(p, "half_connection") == 0 ? false : true;
  1408. use_fast_rc4 = PackGetInt(p, "use_fast_rc4") == 0 ? false : true;
  1409. qos = PackGetInt(p, "qos") ? true : false;
  1410. client_id = PackGetInt(p, "client_id");
  1411. adjust_mss = PackGetInt(p, "adjust_mss");
  1412. use_udp_acceleration_client = PackGetBool(p, "use_udp_acceleration");
  1413. support_hmac_on_udp_acceleration_client = PackGetBool(p, "support_hmac_on_udp_acceleration");
  1414. support_udp_accel_fast_disconnect_detect = PackGetBool(p, "support_udp_accel_fast_disconnect_detect");
  1415. support_bulk_on_rudp = PackGetBool(p, "support_bulk_on_rudp");
  1416. support_hmac_on_bulk_of_rudp = PackGetBool(p, "support_hmac_on_bulk_of_rudp");
  1417. support_udp_recovery = PackGetBool(p, "support_udp_recovery");
  1418. if (c->IsInProc)
  1419. {
  1420. char tmp[MAX_SIZE];
  1421. UINT64 ptr;
  1422. ptr = PackGetInt64(p, "release_me_eap_client");
  1423. if (ptr != 0)
  1424. {
  1425. release_me_eap_client = (EAP_CLIENT *)ptr;
  1426. }
  1427. PackGetStr(p, "inproc_postfix", c->InProcPrefix, sizeof(c->InProcPrefix));
  1428. Zero(tmp, sizeof(tmp));
  1429. PackGetStr(p, "inproc_cryptname", tmp, sizeof(tmp));
  1430. if (c->FirstSock != NULL)
  1431. {
  1432. if (IsEmptyStr(c->InProcPrefix) == false)
  1433. {
  1434. Format(c->FirstSock->UnderlayProtocol, sizeof(c->FirstSock->UnderlayProtocol),
  1435. SOCK_UNDERLAY_INPROC_EX, c->InProcPrefix);
  1436. }
  1437. }
  1438. if (c->CipherName != NULL)
  1439. {
  1440. Free(c->CipherName);
  1441. }
  1442. c->CipherName = NULL;
  1443. if (IsEmptyStr(tmp) == false)
  1444. {
  1445. c->CipherName = CopyStr(tmp);
  1446. use_encrypt = true;
  1447. }
  1448. use_udp_acceleration_client = false;
  1449. }
  1450. else
  1451. {
  1452. if (c->CipherName != NULL)
  1453. {
  1454. Free(c->CipherName);
  1455. }
  1456. c->CipherName = NULL;
  1457. if (c->FirstSock != NULL && IsEmptyStr(c->FirstSock->CipherName) == false)
  1458. {
  1459. c->CipherName = CopyStr(c->FirstSock->CipherName);
  1460. }
  1461. }
  1462. if (support_bulk_on_rudp && c->FirstSock != NULL && c->FirstSock->IsRUDPSocket &&
  1463. c->FirstSock->BulkRecvKey != NULL && c->FirstSock->BulkSendKey != NULL)
  1464. {
  1465. // RAllow UDP bulk transfer if the client side supports
  1466. // in the case of using R-UDP Socket
  1467. enable_bulk_on_rudp = true;
  1468. enable_hmac_on_bulk_of_rudp = support_hmac_on_bulk_of_rudp;
  1469. }
  1470. if (support_udp_recovery && c->FirstSock != NULL && c->FirstSock->IsRUDPSocket)
  1471. {
  1472. // Allow UDP recovery
  1473. enable_udp_recovery = true;
  1474. }
  1475. if (use_udp_acceleration_client)
  1476. {
  1477. // Get the parameters for the UDP acceleration function
  1478. if (PackGetIp(p, "udp_acceleration_client_ip", &udp_acceleration_client_ip) == false ||
  1479. PackGetData2(p, "udp_acceleration_client_key", udp_acceleration_client_key, UDP_ACCELERATION_COMMON_KEY_SIZE) == false)
  1480. {
  1481. use_udp_acceleration_client = false;
  1482. }
  1483. else
  1484. {
  1485. if (IsZeroIp(&udp_acceleration_client_ip))
  1486. {
  1487. Copy(&udp_acceleration_client_ip, &c->FirstSock->RemoteIP, sizeof(IP));
  1488. }
  1489. udp_acceleration_client_port = PackGetInt(p, "udp_acceleration_client_port");
  1490. if (udp_acceleration_client_port == 0)
  1491. {
  1492. use_udp_acceleration_client = false;
  1493. }
  1494. }
  1495. use_hmac_on_udp_acceleration = support_hmac_on_udp_acceleration_client;
  1496. }
  1497. Debug("use_udp_acceleration_client = %u\n", use_udp_acceleration_client);
  1498. Debug("use_hmac_on_udp_acceleration = %u\n", use_hmac_on_udp_acceleration);
  1499. // Request mode
  1500. require_bridge_routing_mode = PackGetBool(p, "require_bridge_routing_mode");
  1501. require_monitor_mode = PackGetBool(p, "require_monitor_mode");
  1502. if (require_monitor_mode)
  1503. {
  1504. qos = false;
  1505. }
  1506. if (is_server_or_bridge)
  1507. {
  1508. require_bridge_routing_mode = true;
  1509. }
  1510. // Client unique ID
  1511. Zero(unique, sizeof(unique));
  1512. if (PackGetDataSize(p, "unique_id") == SHA1_SIZE)
  1513. {
  1514. PackGetData(p, "unique_id", unique);
  1515. }
  1516. // Get the authentication method
  1517. authtype = GetAuthTypeFromPack(p);
  1518. if (1)
  1519. {
  1520. // Log
  1521. char ip1[64], ip2[64], verstr[64];
  1522. wchar_t *authtype_str = _UU("LH_AUTH_UNKNOWN");
  1523. switch (authtype)
  1524. {
  1525. case CLIENT_AUTHTYPE_ANONYMOUS:
  1526. authtype_str = _UU("LH_AUTH_ANONYMOUS");
  1527. break;
  1528. case CLIENT_AUTHTYPE_PASSWORD:
  1529. authtype_str = _UU("LH_AUTH_PASSWORD");
  1530. break;
  1531. case CLIENT_AUTHTYPE_PLAIN_PASSWORD:
  1532. authtype_str = _UU("LH_AUTH_PLAIN_PASSWORD");
  1533. break;
  1534. case CLIENT_AUTHTYPE_CERT:
  1535. authtype_str = _UU("LH_AUTH_CERT");
  1536. break;
  1537. case AUTHTYPE_TICKET:
  1538. authtype_str = _UU("LH_AUTH_TICKET");
  1539. break;
  1540. }
  1541. IPToStr(ip1, sizeof(ip1), &c->FirstSock->RemoteIP);
  1542. IPToStr(ip2, sizeof(ip2), &c->FirstSock->LocalIP);
  1543. Format(verstr, sizeof(verstr), "%u.%02u", c->ClientVer / 100, c->ClientVer % 100);
  1544. HLog(hub, "LH_CONNECT_CLIENT", c->Name, ip1, c->FirstSock->RemoteHostname, c->FirstSock->RemotePort,
  1545. c->ClientStr, verstr, c->ClientBuild, authtype_str, username);
  1546. }
  1547. // Attempt an anonymous authentication first
  1548. auth_ret = SamAuthUserByAnonymous(hub, username);
  1549. if (auth_ret)
  1550. {
  1551. if (c->IsInProc)
  1552. {
  1553. IPC_MSCHAP_V2_AUTHINFO mschap;
  1554. char password_tmp[MAX_SIZE];
  1555. Zero(&mschap, sizeof(mschap));
  1556. Zero(password_tmp, sizeof(password_tmp));
  1557. PackGetStr(p, "plain_password", password_tmp, sizeof(password_tmp));
  1558. if (ParseAndExtractMsChapV2InfoFromPassword(&mschap, password_tmp))
  1559. {
  1560. // Because the server don't know the NTLM hashed password, the bet to the possibility of
  1561. // the same character to the user name and empty, search a password of different
  1562. // versions of the upper and lower case characters in the case of anonymous authentication.
  1563. // Returns the MS-CHAPv2 response by using the password if there is a match.
  1564. // Fail the authentication if no match is found.
  1565. // (Because, if return a false MS-CHAPv2 Response, PPP client cause an error)
  1566. LIST *o = NewListFast(NULL);
  1567. char tmp1[MAX_SIZE];
  1568. char tmp2[MAX_SIZE];
  1569. char tmp3[MAX_SIZE];
  1570. char tmp4[MAX_SIZE];
  1571. char *response_pw;
  1572. char psk[MAX_SIZE];
  1573. ParseNtUsername(mschap.MsChapV2_PPPUsername, tmp1, sizeof(tmp1), tmp2, sizeof(tmp2), false);
  1574. ParseNtUsername(mschap.MsChapV2_PPPUsername, tmp3, sizeof(tmp3), tmp4, sizeof(tmp4), true);
  1575. Add(o, "");
  1576. Add(o, "-");
  1577. Add(o, ".");
  1578. Add(o, "*");
  1579. Add(o, "?");
  1580. Add(o, " ");
  1581. Add(o, "p");
  1582. Add(o, "guest");
  1583. Add(o, "anony");
  1584. Add(o, "anonymouse");
  1585. Add(o, "password");
  1586. Add(o, "passwd");
  1587. Add(o, "pass");
  1588. Add(o, "pw");
  1589. Add(o, mschap.MsChapV2_PPPUsername);
  1590. Add(o, tmp1);
  1591. Add(o, tmp2);
  1592. Add(o, tmp3);
  1593. Add(o, tmp4);
  1594. Zero(psk, sizeof(psk));
  1595. if (c->Cedar->Server != NULL)
  1596. {
  1597. SERVER *s = c->Cedar->Server;
  1598. if (s->IPsecServer != NULL)
  1599. {
  1600. StrCpy(psk, sizeof(psk), s->IPsecServer->Services.IPsec_Secret);
  1601. Add(o, psk);
  1602. }
  1603. }
  1604. response_pw = MsChapV2DoBruteForce(&mschap, o);
  1605. ReleaseList(o);
  1606. if (response_pw != NULL)
  1607. {
  1608. UCHAR challenge8[8];
  1609. UCHAR nt_hash[16];
  1610. UCHAR nt_hash_hash[16];
  1611. GenerateNtPasswordHash(nt_hash, response_pw);
  1612. GenerateNtPasswordHashHash(nt_hash_hash, nt_hash);
  1613. MsChapV2_GenerateChallenge8(challenge8, mschap.MsChapV2_ClientChallenge, mschap.MsChapV2_ServerChallenge,
  1614. mschap.MsChapV2_PPPUsername);
  1615. MsChapV2Server_GenerateResponse(mschap_v2_server_response_20, nt_hash_hash,
  1616. mschap.MsChapV2_ClientResponse, challenge8);
  1617. Free(response_pw);
  1618. }
  1619. else
  1620. {
  1621. auth_ret = false;
  1622. }
  1623. }
  1624. }
  1625. if (auth_ret)
  1626. {
  1627. // User authentication success by anonymous authentication
  1628. HLog(hub, "LH_AUTH_OK", c->Name, username);
  1629. is_empty_password = true;
  1630. }
  1631. }
  1632. if (auth_ret == false)
  1633. {
  1634. // Attempt other authentication methods if anonymous authentication fails
  1635. switch (authtype)
  1636. {
  1637. case CLIENT_AUTHTYPE_ANONYMOUS:
  1638. // Anonymous authentication (this have been already attempted)
  1639. break;
  1640. case AUTHTYPE_TICKET:
  1641. // Ticket authentication
  1642. if (PackGetDataSize(p, "ticket") == SHA1_SIZE)
  1643. {
  1644. PackGetData(p, "ticket", ticket);
  1645. auth_ret = SiCheckTicket(hub, ticket, username, sizeof(username), username_real, sizeof(username_real),
  1646. &ticketed_policy, sessionname, sizeof(sessionname), groupname, sizeof(groupname));
  1647. }
  1648. break;
  1649. case CLIENT_AUTHTYPE_PASSWORD:
  1650. // Password authentication
  1651. if (PackGetDataSize(p, "secure_password") == SHA1_SIZE)
  1652. {
  1653. POLICY *pol = NULL;
  1654. UCHAR secure_password[SHA1_SIZE];
  1655. Zero(secure_password, sizeof(secure_password));
  1656. if (PackGetDataSize(p, "secure_password") == SHA1_SIZE)
  1657. {
  1658. PackGetData(p, "secure_password", secure_password);
  1659. }
  1660. auth_ret = SamAuthUserByPassword(hub, username, c->Random, secure_password, NULL, NULL, NULL);
  1661. pol = SamGetUserPolicy(hub, username);
  1662. if (pol != NULL)
  1663. {
  1664. no_save_password = pol->NoSavePassword;
  1665. Free(pol);
  1666. }
  1667. if(auth_ret){
  1668. // Check whether the password was empty
  1669. UCHAR hashed_empty_password[SHA1_SIZE];
  1670. UCHAR secure_empty_password[SHA1_SIZE];
  1671. HashPassword(hashed_empty_password, username, "");
  1672. SecurePassword(secure_empty_password, hashed_empty_password, c->Random);
  1673. if(Cmp(secure_password, secure_empty_password, SHA1_SIZE)==0){
  1674. is_empty_password = true;
  1675. }
  1676. }
  1677. }
  1678. break;
  1679. case CLIENT_AUTHTYPE_PLAIN_PASSWORD:
  1680. {
  1681. POLICY *pol = NULL;
  1682. // Plaintext password authentication
  1683. Zero(plain_password, sizeof(plain_password));
  1684. PackGetStr(p, "plain_password", plain_password, sizeof(plain_password));
  1685. if (c->IsInProc == false && StartWith(plain_password, IPC_PASSWORD_MSCHAPV2_TAG))
  1686. {
  1687. // Do not allow the MS-CHAPv2 authentication other than IPC sessions
  1688. Zero(plain_password, sizeof(plain_password));
  1689. }
  1690. if (auth_ret == false)
  1691. {
  1692. // Attempt a password authentication of normal user
  1693. UCHAR secure_password[SHA1_SIZE];
  1694. UCHAR hash_password[SHA1_SIZE];
  1695. bool is_mschap = StartWith(plain_password, IPC_PASSWORD_MSCHAPV2_TAG);
  1696. HashPassword(hash_password, username, plain_password);
  1697. SecurePassword(secure_password, hash_password, c->Random);
  1698. if (is_mschap == false)
  1699. {
  1700. auth_ret = SamAuthUserByPassword(hub, username, c->Random, secure_password, NULL, NULL, NULL);
  1701. }
  1702. else
  1703. {
  1704. auth_ret = SamAuthUserByPassword(hub, username, c->Random, secure_password,
  1705. plain_password, mschap_v2_server_response_20, &ms_chap_error);
  1706. }
  1707. if (auth_ret && pol == NULL)
  1708. {
  1709. pol = SamGetUserPolicy(hub, username);
  1710. }
  1711. }
  1712. if (auth_ret == false)
  1713. {
  1714. // Attempt external authentication registered users
  1715. bool fail_ext_user_auth = false;
  1716. if (GetGlobalServerFlag(GSF_DISABLE_RADIUS_AUTH) != 0)
  1717. {
  1718. fail_ext_user_auth = true;
  1719. }
  1720. if (fail_ext_user_auth == false)
  1721. {
  1722. auth_ret = SamAuthUserByPlainPassword(c, hub, username, plain_password, false, mschap_v2_server_response_20, &radius_login_opt);
  1723. }
  1724. if (auth_ret && pol == NULL)
  1725. {
  1726. pol = SamGetUserPolicy(hub, username);
  1727. }
  1728. }
  1729. if (auth_ret == false)
  1730. {
  1731. // Attempt external authentication asterisk user
  1732. bool b = false;
  1733. bool fail_ext_user_auth = false;
  1734. if (GetGlobalServerFlag(GSF_DISABLE_RADIUS_AUTH) != 0)
  1735. {
  1736. fail_ext_user_auth = true;
  1737. }
  1738. if (fail_ext_user_auth == false)
  1739. {
  1740. AcLock(hub);
  1741. {
  1742. b = AcIsUser(hub, "*");
  1743. }
  1744. AcUnlock(hub);
  1745. // If there is asterisk user, log on as the user
  1746. if (b)
  1747. {
  1748. auth_ret = SamAuthUserByPlainPassword(c, hub, username, plain_password, true, mschap_v2_server_response_20, &radius_login_opt);
  1749. if (auth_ret && pol == NULL)
  1750. {
  1751. pol = SamGetUserPolicy(hub, "*");
  1752. }
  1753. }
  1754. }
  1755. }
  1756. if (pol != NULL)
  1757. {
  1758. no_save_password = pol->NoSavePassword;
  1759. Free(pol);
  1760. }
  1761. if(auth_ret){
  1762. // Check whether the password was empty
  1763. if(IsEmptyStr(plain_password)){
  1764. is_empty_password = true;
  1765. }
  1766. }
  1767. }
  1768. break;
  1769. case CLIENT_AUTHTYPE_CERT:
  1770. if (GetGlobalServerFlag(GSF_DISABLE_CERT_AUTH) == 0)
  1771. {
  1772. // Certificate authentication
  1773. cert_size = PackGetDataSize(p, "cert");
  1774. if (cert_size >= 1 && cert_size <= 100000)
  1775. {
  1776. cert_buf = ZeroMalloc(cert_size);
  1777. if (PackGetData(p, "cert", cert_buf))
  1778. {
  1779. UCHAR sign[4096 / 8];
  1780. UINT sign_size = PackGetDataSize(p, "sign");
  1781. if (sign_size <= sizeof(sign) && sign_size >= 1)
  1782. {
  1783. if (PackGetData(p, "sign", sign))
  1784. {
  1785. BUF *b = NewBuf();
  1786. X *x;
  1787. WriteBuf(b, cert_buf, cert_size);
  1788. x = BufToX(b, false);
  1789. if (x != NULL && x->is_compatible_bit &&
  1790. sign_size == (x->bits / 8))
  1791. {
  1792. K *k = GetKFromX(x);
  1793. // Verify the signature received from the client
  1794. if (RsaVerifyEx(c->Random, SHA1_SIZE, sign, k, x->bits))
  1795. {
  1796. // Confirmed that the client has had this certificate
  1797. // certainly because the signature matched.
  1798. // Check whether the certificate is valid.
  1799. auth_ret = SamAuthUserByCert(hub, username, x);
  1800. if (auth_ret)
  1801. {
  1802. // Copy the certificate
  1803. c->ClientX = CloneX(x);
  1804. }
  1805. }
  1806. else
  1807. {
  1808. // Authentication failure
  1809. }
  1810. FreeK(k);
  1811. }
  1812. FreeX(x);
  1813. FreeBuf(b);
  1814. }
  1815. }
  1816. }
  1817. Free(cert_buf);
  1818. }
  1819. }
  1820. else
  1821. {
  1822. // Certificate authentication is not supported in the open source version
  1823. HLog(hub, "LH_AUTH_CERT_NOT_SUPPORT_ON_OPEN_SOURCE", c->Name, username);
  1824. Unlock(hub->lock);
  1825. ReleaseHub(hub);
  1826. FreePack(p);
  1827. c->Err = ERR_AUTHTYPE_NOT_SUPPORTED;
  1828. goto CLEANUP;
  1829. }
  1830. break;
  1831. default:
  1832. // Unknown authentication method
  1833. Unlock(hub->lock);
  1834. ReleaseHub(hub);
  1835. FreePack(p);
  1836. c->Err = ERR_AUTHTYPE_NOT_SUPPORTED;
  1837. error_detail = "ERR_AUTHTYPE_NOT_SUPPORTED";
  1838. goto CLEANUP;
  1839. }
  1840. if (auth_ret == false)
  1841. {
  1842. // Authentication failure
  1843. HLog(hub, "LH_AUTH_NG", c->Name, username);
  1844. }
  1845. else
  1846. {
  1847. // Authentication success
  1848. HLog(hub, "LH_AUTH_OK", c->Name, username);
  1849. }
  1850. }
  1851. if (auth_ret == false)
  1852. {
  1853. // Authentication failure
  1854. Unlock(hub->lock);
  1855. ReleaseHub(hub);
  1856. FreePack(p);
  1857. c->Err = ERR_AUTH_FAILED;
  1858. if (ms_chap_error != 0)
  1859. {
  1860. c->Err = ms_chap_error;
  1861. }
  1862. error_detail = "ERR_AUTH_FAILED";
  1863. goto CLEANUP;
  1864. }
  1865. else
  1866. {
  1867. if(is_empty_password)
  1868. {
  1869. SOCK *s = c->FirstSock;
  1870. if (s != NULL && s->RemoteIP.addr[0] != 127)
  1871. {
  1872. if(StrCmpi(username, ADMINISTRATOR_USERNAME) == 0 ||
  1873. GetHubAdminOption(hub, "deny_empty_password") != 0)
  1874. {
  1875. // When the password is empty, remote connection is not acceptable
  1876. HLog(hub, "LH_LOCAL_ONLY", c->Name, username);
  1877. Unlock(hub->lock);
  1878. ReleaseHub(hub);
  1879. FreePack(p);
  1880. c->Err = ERR_NULL_PASSWORD_LOCAL_ONLY;
  1881. error_detail = "ERR_NULL_PASSWORD_LOCAL_ONLY";
  1882. goto CLEANUP;
  1883. }
  1884. }
  1885. }
  1886. }
  1887. policy = NULL;
  1888. // Authentication success
  1889. FreePack(p);
  1890. // Check the assigned VLAN ID
  1891. if (radius_login_opt.Out_IsRadiusLogin)
  1892. {
  1893. if (radius_login_opt.In_CheckVLanId)
  1894. {
  1895. if (radius_login_opt.Out_VLanId != 0)
  1896. {
  1897. assigned_vlan_id = radius_login_opt.Out_VLanId;
  1898. }
  1899. if (radius_login_opt.In_DenyNoVlanId && assigned_vlan_id == 0 || assigned_vlan_id >= 4096)
  1900. {
  1901. // Deny this session
  1902. Unlock(hub->lock);
  1903. ReleaseHub(hub);
  1904. c->Err = ERR_ACCESS_DENIED;
  1905. error_detail = "In_DenyNoVlanId";
  1906. goto CLEANUP;
  1907. }
  1908. }
  1909. }
  1910. if (StrCmpi(username, ADMINISTRATOR_USERNAME) != 0)
  1911. {
  1912. // Get the policy
  1913. if (farm_member == false)
  1914. {
  1915. // In the case of not a farm member
  1916. user = AcGetUser(hub, username);
  1917. if (user == NULL)
  1918. {
  1919. user = AcGetUser(hub, "*");
  1920. if (user == NULL)
  1921. {
  1922. // User acquisition failure
  1923. Unlock(hub->lock);
  1924. ReleaseHub(hub);
  1925. c->Err = ERR_ACCESS_DENIED;
  1926. error_detail = "AcGetUser";
  1927. goto CLEANUP;
  1928. }
  1929. }
  1930. policy = NULL;
  1931. Lock(user->lock);
  1932. {
  1933. // Get the expiration date
  1934. user_expires = user->ExpireTime;
  1935. StrCpy(username_real, sizeof(username_real), user->Name);
  1936. group = user->Group;
  1937. if (group != NULL)
  1938. {
  1939. AddRef(group->ref);
  1940. Lock(group->lock);
  1941. {
  1942. // Get the group name
  1943. StrCpy(groupname, sizeof(groupname), group->Name);
  1944. }
  1945. Unlock(group->lock);
  1946. }
  1947. if (user->Policy != NULL)
  1948. {
  1949. policy = ClonePolicy(user->Policy);
  1950. }
  1951. else
  1952. {
  1953. if (group)
  1954. {
  1955. Lock(group->lock);
  1956. {
  1957. if (group->Policy != NULL)
  1958. {
  1959. policy = ClonePolicy(group->Policy);
  1960. }
  1961. }
  1962. Unlock(group->lock);
  1963. }
  1964. }
  1965. if (group != NULL)
  1966. {
  1967. ReleaseGroup(group);
  1968. }
  1969. }
  1970. Unlock(user->lock);
  1971. loggedin_user_object = user;
  1972. }
  1973. else
  1974. {
  1975. // In the case of farm member
  1976. policy = ClonePolicy(&ticketed_policy);
  1977. }
  1978. }
  1979. else
  1980. {
  1981. // Administrator mode
  1982. admin_mode = true;
  1983. StrCpy(username_real, sizeof(username_real), ADMINISTRATOR_USERNAME);
  1984. policy = ClonePolicy(GetDefaultPolicy());
  1985. policy->NoBroadcastLimiter = true;
  1986. policy->MonitorPort = true;
  1987. }
  1988. if (policy == NULL)
  1989. {
  1990. // Use the default policy
  1991. policy = ClonePolicy(GetDefaultPolicy());
  1992. }
  1993. if (policy->MaxConnection == 0)
  1994. {
  1995. policy->MaxConnection = MAX_TCP_CONNECTION;
  1996. }
  1997. if (policy->TimeOut == 0)
  1998. {
  1999. policy->TimeOut = 20;
  2000. }
  2001. if (qos)
  2002. {
  2003. // VoIP / QoS
  2004. if (policy->NoQoS)
  2005. {
  2006. // Policy does not allow QoS
  2007. qos = false;
  2008. }
  2009. if (GetServerCapsBool(c->Cedar->Server, "b_support_qos") == false)
  2010. {
  2011. // Server does not support QoS
  2012. qos = false;
  2013. policy->NoQoS = true;
  2014. }
  2015. if (GetHubAdminOption(hub, "deny_qos") != 0)
  2016. {
  2017. // It is prohibited in the management options
  2018. qos = false;
  2019. policy->NoQoS = true;
  2020. }
  2021. }
  2022. if (GetHubAdminOption(hub, "max_bitrates_download") != 0)
  2023. {
  2024. if (policy->MaxDownload == 0)
  2025. {
  2026. policy->MaxDownload = GetHubAdminOption(hub, "max_bitrates_download");
  2027. }
  2028. else
  2029. {
  2030. UINT r = GetHubAdminOption(hub, "max_bitrates_download");
  2031. policy->MaxDownload = MIN(policy->MaxDownload, r);
  2032. }
  2033. }
  2034. if (GetHubAdminOption(hub, "max_bitrates_upload") != 0)
  2035. {
  2036. if (policy->MaxUpload == 0)
  2037. {
  2038. policy->MaxUpload = GetHubAdminOption(hub, "max_bitrates_upload");
  2039. }
  2040. else
  2041. {
  2042. UINT r = GetHubAdminOption(hub, "max_bitrates_upload");
  2043. policy->MaxUpload = MIN(policy->MaxUpload, r);
  2044. }
  2045. }
  2046. if (GetHubAdminOption(hub, "deny_bridge") != 0)
  2047. {
  2048. policy->NoBridge = true;
  2049. }
  2050. if (GetHubAdminOption(hub, "deny_routing") != 0)
  2051. {
  2052. policy->NoRouting = true;
  2053. }
  2054. if (c->IsInProc)
  2055. {
  2056. policy->NoBridge = false;
  2057. policy->NoRouting = false;
  2058. }
  2059. if (hub->Option->ClientMinimumRequiredBuild > c->ClientBuild &&
  2060. InStrEx(c->ClientStr, "client", false))
  2061. {
  2062. // Build number of the client is too small
  2063. HLog(hub, "LH_CLIENT_VERSION_OLD", c->Name, c->ClientBuild, hub->Option->ClientMinimumRequiredBuild);
  2064. Unlock(hub->lock);
  2065. ReleaseHub(hub);
  2066. c->Err = ERR_VERSION_INVALID;
  2067. Free(policy);
  2068. error_detail = "ERR_VERSION_INVALID";
  2069. goto CLEANUP;
  2070. }
  2071. if (hub->Option->RequiredClientId != 0 &&
  2072. hub->Option->RequiredClientId != client_id &&
  2073. InStrEx(c->ClientStr, "client", false))
  2074. {
  2075. // Build number of the client is too small
  2076. HLog(hub, "LH_CLIENT_ID_REQUIRED", c->Name, client_id, hub->Option->RequiredClientId);
  2077. Unlock(hub->lock);
  2078. ReleaseHub(hub);
  2079. c->Err = ERR_CLIENT_ID_REQUIRED;
  2080. error_detail = "ERR_CLIENT_ID_REQUIRED";
  2081. Free(policy);
  2082. goto CLEANUP;
  2083. }
  2084. if ((policy->NoSavePassword) || (policy->AutoDisconnect != 0))
  2085. {
  2086. if (c->ClientBuild < 6560 && InStrEx(c->ClientStr, "client", false))
  2087. {
  2088. // If NoSavePassword policy is specified,
  2089. // only supported client can connect
  2090. HLog(hub, "LH_CLIENT_VERSION_OLD", c->Name, c->ClientBuild, 6560);
  2091. Unlock(hub->lock);
  2092. ReleaseHub(hub);
  2093. c->Err = ERR_VERSION_INVALID;
  2094. error_detail = "ERR_VERSION_INVALID";
  2095. Free(policy);
  2096. goto CLEANUP;
  2097. }
  2098. }
  2099. if (user_expires != 0 && user_expires <= SystemTime64())
  2100. {
  2101. // User expired
  2102. HLog(hub, "LH_USER_EXPIRES", c->Name, username);
  2103. Unlock(hub->lock);
  2104. ReleaseHub(hub);
  2105. c->Err = ERR_ACCESS_DENIED;
  2106. error_detail = "LH_USER_EXPIRES";
  2107. Free(policy);
  2108. goto CLEANUP;
  2109. }
  2110. if (policy->Access == false)
  2111. {
  2112. // Access is denied
  2113. HLog(hub, "LH_POLICY_ACCESS_NG", c->Name, username);
  2114. Unlock(hub->lock);
  2115. ReleaseHub(hub);
  2116. error_detail = "LH_POLICY_ACCESS_NG";
  2117. c->Err = ERR_ACCESS_DENIED;
  2118. Free(policy);
  2119. goto CLEANUP;
  2120. }
  2121. // Determine the contents of the policy by comparing to
  2122. // option presented by client or deny the connection.
  2123. // Confirm the connectivity in the monitor-mode first
  2124. if (require_monitor_mode && policy->MonitorPort == false)
  2125. {
  2126. // Can not connect in the monitor port mode
  2127. HLog(hub, "LH_POLICY_MONITOR_MODE", c->Name);
  2128. Unlock(hub->lock);
  2129. ReleaseHub(hub);
  2130. c->Err = ERR_MONITOR_MODE_DENIED;
  2131. Free(policy);
  2132. error_detail = "ERR_MONITOR_MODE_DENIED";
  2133. goto CLEANUP;
  2134. }
  2135. if (policy->MonitorPort)
  2136. {
  2137. if (require_monitor_mode == false)
  2138. {
  2139. policy->MonitorPort = false;
  2140. }
  2141. }
  2142. if (policy->MonitorPort)
  2143. {
  2144. qos = false;
  2145. }
  2146. // Determine whether it can be connected by a bridge / routing mode next
  2147. if (require_bridge_routing_mode &&
  2148. (policy->NoBridge && policy->NoRouting))
  2149. {
  2150. // Can not be connected by a bridge / routing mode
  2151. HLog(hub, "LH_POLICY_BRIDGE_MODE", c->Name);
  2152. Unlock(hub->lock);
  2153. ReleaseHub(hub);
  2154. c->Err = ERR_BRIDGE_MODE_DENIED;
  2155. error_detail = "ERR_BRIDGE_MODE_DENIED";
  2156. Free(policy);
  2157. goto CLEANUP;
  2158. }
  2159. if (require_bridge_routing_mode == false)
  2160. {
  2161. policy->NoBridge = true;
  2162. policy->NoRouting = true;
  2163. }
  2164. if (Cmp(unique, unique2, SHA1_SIZE) == 0)
  2165. {
  2166. // It's a localhost session
  2167. local_host_session = true;
  2168. }
  2169. if (local_host_session == false)
  2170. {
  2171. // Make further judgment whether localhost session
  2172. SOCK *s = c->FirstSock;
  2173. if (s != NULL)
  2174. {
  2175. if (IsIPMyHost(&s->RemoteIP))
  2176. {
  2177. // It's a localhost session
  2178. local_host_session = true;
  2179. }
  2180. }
  2181. }
  2182. if (local_host_session)
  2183. {
  2184. // Permit routing or bridging in the case of localhost session
  2185. policy->NoBridge = false;
  2186. policy->NoRouting = false;
  2187. }
  2188. if (local_host_session == false)
  2189. {
  2190. if (policy->NoBridge == false || policy->NoRouting == false)
  2191. {
  2192. use_bridge_license = true;
  2193. }
  2194. else
  2195. {
  2196. use_client_license = true;
  2197. }
  2198. }
  2199. if (server != NULL && server->ServerType != SERVER_TYPE_FARM_MEMBER &&
  2200. policy != NULL)
  2201. {
  2202. if (GetServerCapsBool(hub->Cedar->Server, "b_support_limit_multilogin"))
  2203. {
  2204. // Check if the number of concurrent multiple logins limit is specified in the policy
  2205. RPC_ENUM_SESSION t;
  2206. UINT i, num;
  2207. UINT max_logins = policy->MultiLogins;
  2208. UINT ao = GetHubAdminOption(hub, "max_multilogins_per_user");
  2209. if (ao != 0)
  2210. {
  2211. if (max_logins != 0)
  2212. {
  2213. max_logins = MIN(max_logins, ao);
  2214. }
  2215. else
  2216. {
  2217. max_logins = ao;
  2218. }
  2219. }
  2220. if (max_logins != 0)
  2221. {
  2222. Zero(&t, sizeof(t));
  2223. StrCpy(t.HubName, sizeof(t.HubName), hub->Name);
  2224. Unlock(hub->lock);
  2225. SiEnumSessionMain(server, &t);
  2226. Lock(hub->lock);
  2227. num = 0;
  2228. for (i = 0;i < t.NumSession;i++)
  2229. {
  2230. RPC_ENUM_SESSION_ITEM *e = &t.Sessions[i];
  2231. if (e->BridgeMode == false && e->Layer3Mode == false && e->LinkMode == false && e->CurrentNumTcp != 0)
  2232. {
  2233. if (StrCmpi(e->Username, username) == 0 &&
  2234. (IsZero(e->UniqueId, 16) || Cmp(e->UniqueId, node.UniqueId, 16) != 0))
  2235. {
  2236. num++;
  2237. }
  2238. }
  2239. }
  2240. FreeRpcEnumSession(&t);
  2241. if (num >= max_logins)
  2242. {
  2243. // Can not connect any more
  2244. Unlock(hub->lock);
  2245. // Dump a detailed error log
  2246. HLog(hub, "LH_TOO_MANY_MULTILOGINS",
  2247. c->Name,
  2248. username, max_logins, num);
  2249. ReleaseHub(hub);
  2250. c->Err = ERR_TOO_MANY_USER_SESSION;
  2251. Free(policy);
  2252. goto CLEANUP;
  2253. }
  2254. }
  2255. }
  2256. }
  2257. if (loggedin_user_object != NULL)
  2258. {
  2259. // Update the user information
  2260. Lock(loggedin_user_object->lock);
  2261. {
  2262. loggedin_user_object->LastLoginTime = SystemTime64();
  2263. }
  2264. Unlock(loggedin_user_object->lock);
  2265. }
  2266. // Update the number of log-ins
  2267. hub->LastCommTime = hub->LastLoginTime = SystemTime64();
  2268. if (farm_controller)
  2269. {
  2270. wchar_t *msg = GetHubMsg(hub);
  2271. Unlock(hub->lock);
  2272. Lock(cedar->CedarSuperLock);
  2273. // In the case of farm controller, choose a farm members to host this HUB
  2274. LockList(server->FarmMemberList);
  2275. {
  2276. HLog(hub, "LH_FARM_SELECT_1", c->Name);
  2277. f = SiGetHubHostingMember(server, hub, admin_mode, c);
  2278. if (f == NULL)
  2279. {
  2280. // Failed in the selection
  2281. HLog(hub, "LH_FARM_SELECT_2", c->Name);
  2282. UnlockList(server->FarmMemberList);
  2283. Unlock(cedar->CedarSuperLock);
  2284. ReleaseHub(hub);
  2285. c->Err = ERR_COULD_NOT_HOST_HUB_ON_FARM;
  2286. Free(policy);
  2287. Free(msg);
  2288. goto CLEANUP;
  2289. }
  2290. else
  2291. {
  2292. if (f->Me == false)
  2293. {
  2294. UCHAR ticket[SHA1_SIZE];
  2295. PACK *p;
  2296. BUF *b;
  2297. UINT i;
  2298. SLog(c->Cedar, "LH_FARM_SELECT_4", c->Name, f->hostname);
  2299. // Create a session on the selected server farm member
  2300. Rand(ticket, sizeof(ticket));
  2301. SiCallCreateTicket(server, f, hub->Name,
  2302. username, username_real, policy, ticket, Inc(hub->SessionCounter), groupname);
  2303. p = NewPack();
  2304. PackAddInt(p, "Redirect", 1);
  2305. PackAddIp32(p, "Ip", f->Ip);
  2306. for (i = 0;i < f->NumPort;i++)
  2307. {
  2308. PackAddIntEx(p, "Port", f->Ports[i], i, f->NumPort);
  2309. }
  2310. PackAddData(p, "Ticket", ticket, sizeof(ticket));
  2311. if (true)
  2312. {
  2313. char *utf = CopyUniToUtf(msg);
  2314. PackAddData(p, "Msg", utf, StrLen(utf));
  2315. Free(utf);
  2316. }
  2317. b = XToBuf(f->ServerCert, false);
  2318. PackAddBuf(p, "Cert", b);
  2319. FreeBuf(b);
  2320. UnlockList(server->FarmMemberList);
  2321. Unlock(cedar->CedarSuperLock);
  2322. ReleaseHub(hub);
  2323. HttpServerSend(c->FirstSock, p);
  2324. FreePack(p);
  2325. c->Err = 0;
  2326. Free(policy);
  2327. FreePack(HttpServerRecv(c->FirstSock));
  2328. Free(msg);
  2329. goto CLEANUP;
  2330. }
  2331. else
  2332. {
  2333. HLog(hub, "LH_FARM_SELECT_3", c->Name);
  2334. // Continue the process because myself was selected
  2335. UnlockList(server->FarmMemberList);
  2336. Unlock(cedar->CedarSuperLock);
  2337. f->Point = SiGetPoint(server);
  2338. Lock(hub->lock);
  2339. Free(msg);
  2340. }
  2341. }
  2342. }
  2343. }
  2344. if (admin_mode == false)
  2345. {
  2346. // Check the maximum number of connections of the HUB
  2347. if (hub->Option->MaxSession != 0 &&
  2348. hub->Option->MaxSession <= Count(hub->NumSessions))
  2349. {
  2350. // Can not connect any more
  2351. Unlock(hub->lock);
  2352. HLog(hub, "LH_MAX_SESSION", c->Name, hub->Option->MaxSession);
  2353. ReleaseHub(hub);
  2354. c->Err = ERR_HUB_IS_BUSY;
  2355. Free(policy);
  2356. error_detail = "ERR_HUB_IS_BUSY";
  2357. goto CLEANUP;
  2358. }
  2359. }
  2360. if (use_encrypt == false && c->FirstSock->IsReverseAcceptedSocket)
  2361. {
  2362. // On VPN Azure, SSL encryption is mandated.
  2363. use_encrypt = true;
  2364. }
  2365. if (use_client_license || use_bridge_license)
  2366. {
  2367. // Examine whether not to conflict with the limit of simultaneous connections
  2368. // number of sessions defined by the Virtual HUB management options
  2369. if (
  2370. (GetHubAdminOption(hub, "max_sessions") != 0 &&
  2371. (Count(hub->NumSessionsClient) + Count(hub->NumSessionsBridge)) >= GetHubAdminOption(hub, "max_sessions"))
  2372. ||
  2373. (hub->Option->MaxSession != 0 &&
  2374. (Count(hub->NumSessionsClient) + Count(hub->NumSessionsBridge)) >= hub->Option->MaxSession))
  2375. {
  2376. // Can not connect any more
  2377. Unlock(hub->lock);
  2378. HLog(hub, "LH_MAX_SESSION", c->Name, GetHubAdminOption(hub, "max_sessions"));
  2379. ReleaseHub(hub);
  2380. c->Err = ERR_HUB_IS_BUSY;
  2381. Free(policy);
  2382. goto CLEANUP;
  2383. }
  2384. }
  2385. if (use_client_license)
  2386. {
  2387. // Examine whether not to conflict with the limit of simultaneous connections
  2388. // number of sessions(client) defined by the Virtual HUB management options
  2389. if (((GetHubAdminOption(hub, "max_sessions_client_bridge_apply") != 0
  2390. ) &&
  2391. Count(hub->NumSessionsClient) >= GetHubAdminOption(hub, "max_sessions_client") && hub->Cedar->Server != NULL && hub->Cedar->Server->ServerType != SERVER_TYPE_FARM_MEMBER)
  2392. ||
  2393. (hub->FarmMember_MaxSessionClientBridgeApply &&
  2394. Count(hub->NumSessionsClient) >= hub->FarmMember_MaxSessionClient))
  2395. {
  2396. // Can not connect any more
  2397. Unlock(hub->lock);
  2398. HLog(hub, "LH_MAX_SESSION_CLIENT", c->Name, GetHubAdminOption(hub, "max_sessions_client"));
  2399. ReleaseHub(hub);
  2400. c->Err = ERR_HUB_IS_BUSY;
  2401. Free(policy);
  2402. goto CLEANUP;
  2403. }
  2404. }
  2405. if (use_bridge_license)
  2406. {
  2407. // Examine whether not to conflict with the limit of simultaneous connections
  2408. // number of sessions(bridge) defined by the Virtual HUB management options
  2409. if (((GetHubAdminOption(hub, "max_sessions_client_bridge_apply") != 0
  2410. ) &&
  2411. Count(hub->NumSessionsBridge) >= GetHubAdminOption(hub, "max_sessions_bridge") && hub->Cedar->Server != NULL && hub->Cedar->Server->ServerType != SERVER_TYPE_FARM_MEMBER)
  2412. ||
  2413. (hub->FarmMember_MaxSessionClientBridgeApply &&
  2414. Count(hub->NumSessionsBridge) >= hub->FarmMember_MaxSessionBridge))
  2415. {
  2416. // Can not connect any more
  2417. Unlock(hub->lock);
  2418. HLog(hub, "LH_MAX_SESSION_BRIDGE", c->Name, GetHubAdminOption(hub, "max_sessions_bridge"));
  2419. ReleaseHub(hub);
  2420. c->Err = ERR_HUB_IS_BUSY;
  2421. Free(policy);
  2422. goto CLEANUP;
  2423. }
  2424. }
  2425. if (Count(hub->Cedar->CurrentSessions) >= GetServerCapsInt(hub->Cedar->Server, "i_max_sessions"))
  2426. {
  2427. // Can not connect any more
  2428. Unlock(hub->lock);
  2429. HLog(hub, "LH_MAX_SESSION_2", c->Name, GetServerCapsInt(hub->Cedar->Server, "i_max_sessions"));
  2430. ReleaseHub(hub);
  2431. c->Err = ERR_HUB_IS_BUSY;
  2432. Free(policy);
  2433. goto CLEANUP;
  2434. }
  2435. // Increment the current number of connections
  2436. Inc(hub->NumSessions);
  2437. if (use_bridge_license)
  2438. {
  2439. Inc(hub->NumSessionsBridge);
  2440. }
  2441. if (use_client_license)
  2442. {
  2443. Inc(hub->NumSessionsClient);
  2444. }
  2445. Inc(hub->Cedar->CurrentSessions);
  2446. // Calculate the time-out period
  2447. timeout = policy->TimeOut * 1000; // Convert milliseconds to seconds
  2448. if (timeout == 0)
  2449. {
  2450. timeout = TIMEOUT_DEFAULT;
  2451. }
  2452. timeout = MIN(timeout, TIMEOUT_MAX);
  2453. timeout = MAX(timeout, TIMEOUT_MIN);
  2454. // Update the max_connection according to the policy
  2455. max_connection = MIN(max_connection, policy->MaxConnection);
  2456. max_connection = MIN(max_connection, MAX_TCP_CONNECTION);
  2457. max_connection = MAX(max_connection, 1);
  2458. if (c->FirstSock->IsRUDPSocket)
  2459. {
  2460. // In the case of TCP-over-UDP
  2461. half_connection = false;
  2462. // Disable the QoS
  2463. qos = false;
  2464. if (enable_udp_recovery == false)
  2465. {
  2466. // Disable the session reconnection feature
  2467. no_reconnect_to_session = true;
  2468. max_connection = 1;
  2469. }
  2470. else
  2471. {
  2472. // If the UDP recovery is enabled, permit the session re-connection feature (for 2)
  2473. no_reconnect_to_session = false;
  2474. max_connection = NUM_TCP_CONNECTION_FOR_UDP_RECOVERY;
  2475. }
  2476. }
  2477. if (half_connection)
  2478. {
  2479. // Number of connections should be more than 2 in the case of Half Connection
  2480. max_connection = MAX(max_connection, 2);
  2481. }
  2482. if (qos)
  2483. {
  2484. // Number of connections is set to 2 or more when using the VoIP / QoS
  2485. max_connection = MAX(max_connection, 2);
  2486. if (half_connection)
  2487. {
  2488. max_connection = MAX(max_connection, 4);
  2489. }
  2490. }
  2491. c->Status = CONNECTION_STATUS_ESTABLISHED;
  2492. // Remove the connection from Cedar
  2493. DelConnection(c->Cedar, c);
  2494. // VLAN ID
  2495. if (assigned_vlan_id != 0)
  2496. {
  2497. if (policy != NULL)
  2498. {
  2499. if (policy->VLanId == 0)
  2500. {
  2501. policy->VLanId = assigned_vlan_id;
  2502. }
  2503. }
  2504. }
  2505. // Create a Session
  2506. StrLower(username);
  2507. s = NewServerSessionEx(c->Cedar, c, hub, username, policy, c->IsInProc);
  2508. s->EnableUdpRecovery = enable_udp_recovery;
  2509. s->LocalHostSession = local_host_session;
  2510. s->NormalClient = true;
  2511. IPToStr(s->ClientIP, sizeof(s->ClientIP), &c->ClientIp);
  2512. if (c->FirstSock->IsRUDPSocket)
  2513. {
  2514. // R-UDP session
  2515. s->IsRUDPSession = true;
  2516. s->RUdpMss = c->FirstSock->RUDP_OptimizedMss;
  2517. Debug("Optimized MSS Value for R-UDP: %u\n", s->RUdpMss);
  2518. }
  2519. if (enable_bulk_on_rudp)
  2520. {
  2521. // Allow bulk transfer on R-UDP
  2522. s->EnableBulkOnRUDP = true;
  2523. s->EnableHMacOnBulkOfRUDP = enable_hmac_on_bulk_of_rudp;
  2524. }
  2525. s->IsAzureSession = c->FirstSock->IsReverseAcceptedSocket;
  2526. StrCpy(s->UnderlayProtocol, sizeof(s->UnderlayProtocol), c->FirstSock->UnderlayProtocol);
  2527. if (server != NULL)
  2528. {
  2529. s->NoSendSignature = server->NoSendSignature;
  2530. }
  2531. if (c->IsInProc)
  2532. {
  2533. s->NoSendSignature = true;
  2534. }
  2535. if (c->IsInProc && StrCmpi(c->InProcPrefix, OPENVPN_IPC_POSTFIX_L3) == 0)
  2536. {
  2537. // OpenVPN L3 session
  2538. s->IsOpenVPNL3Session = true;
  2539. }
  2540. if (c->IsInProc && StrCmpi(c->InProcPrefix, OPENVPN_IPC_POSTFIX_L2) == 0)
  2541. {
  2542. // OpenVPN L2 session
  2543. s->IsOpenVPNL2Session = true;
  2544. }
  2545. // Determine whether the use of UDP acceleration mode
  2546. if (use_udp_acceleration_client)
  2547. {
  2548. s->UseUdpAcceleration = true;
  2549. s->UdpAccelFastDisconnectDetect = support_udp_accel_fast_disconnect_detect;
  2550. }
  2551. if (hub->Option != NULL && hub->Option->DisableUdpAcceleration)
  2552. {
  2553. s->UseUdpAcceleration = false;
  2554. }
  2555. if (IsZeroIP(&c->FirstSock->Reverse_MyServerGlobalIp) == false &&
  2556. CmpIpAddr(&c->FirstSock->Reverse_MyServerGlobalIp, &c->FirstSock->RemoteIP) == 0)
  2557. {
  2558. // Disable forcibly the UDP acceleration mode if VPN Server and VPN Client
  2559. // are in same LAN in the case of using VPN Azure.
  2560. // (Or this may cause infinite loop of packet)
  2561. s->UseUdpAcceleration = false;
  2562. }
  2563. if (s->UseUdpAcceleration)
  2564. {
  2565. s->UseHMacOnUdpAcceleration = use_hmac_on_udp_acceleration;
  2566. }
  2567. Debug("UseUdpAcceleration = %u\n", s->UseUdpAcceleration);
  2568. Debug("UseHMacOnUdpAcceleration = %u\n", s->UseHMacOnUdpAcceleration);
  2569. if (s->UseUdpAcceleration)
  2570. {
  2571. bool no_nat_t = false;
  2572. // Initialize the UDP acceleration function
  2573. s->UdpAccel = NewUdpAccel(c->Cedar, (c->FirstSock->IsRUDPSocket ? NULL : &c->FirstSock->LocalIP), false, c->FirstSock->IsRUDPSocket, no_nat_t);
  2574. if (s->UdpAccel == NULL)
  2575. {
  2576. s->UseUdpAcceleration = false;
  2577. Debug("NewUdpAccel Failed.\n");
  2578. }
  2579. else
  2580. {
  2581. if (UdpAccelInitServer(s->UdpAccel, udp_acceleration_client_key, &udp_acceleration_client_ip, udp_acceleration_client_port,
  2582. &c->FirstSock->RemoteIP) == false)
  2583. {
  2584. Debug("UdpAccelInitServer Failed.\n");
  2585. s->UseUdpAcceleration = false;
  2586. }
  2587. s->UdpAccel->FastDetect = s->UdpAccelFastDisconnectDetect;
  2588. if (use_encrypt == false)
  2589. {
  2590. s->UdpAccel->PlainTextMode = true;
  2591. }
  2592. s->UdpAccel->UseHMac = s->UseHMacOnUdpAcceleration;
  2593. }
  2594. }
  2595. s->UseClientLicense = use_client_license;
  2596. s->UseBridgeLicense = use_bridge_license;
  2597. s->AdjustMss = adjust_mss;
  2598. if (s->AdjustMss != 0)
  2599. {
  2600. Debug("AdjustMSS: %u\n", s->AdjustMss);
  2601. }
  2602. s->IsBridgeMode = (policy->NoBridge == false) || (policy->NoRouting == false);
  2603. s->IsMonitorMode = policy->MonitorPort;
  2604. // Decide whether IPv6 session
  2605. s->IPv6Session = false;
  2606. if (node.ClientIpAddress == 0)
  2607. {
  2608. s->IPv6Session = true;
  2609. }
  2610. if (use_bridge_license)
  2611. {
  2612. Inc(s->Cedar->AssignedBridgeLicense);
  2613. }
  2614. if (use_client_license)
  2615. {
  2616. Inc(s->Cedar->AssignedClientLicense);
  2617. }
  2618. if (server != NULL)
  2619. {
  2620. // Update the total allocation of the number of licenses for Server structure
  2621. if (server->ServerType == SERVER_TYPE_STANDALONE)
  2622. {
  2623. // Update only stand-alone mode
  2624. // (Periodically poll in the cluster controller mode)
  2625. server->CurrentAssignedClientLicense = Count(s->Cedar->AssignedClientLicense);
  2626. server->CurrentAssignedBridgeLicense = Count(s->Cedar->AssignedBridgeLicense);
  2627. }
  2628. }
  2629. if (StrLen(sessionname) != 0)
  2630. {
  2631. // Specify the session name
  2632. Free(s->Name);
  2633. s->Name = CopyStr(sessionname);
  2634. }
  2635. {
  2636. char ip[128];
  2637. IPToStr(ip, sizeof(ip), &c->FirstSock->RemoteIP);
  2638. HLog(hub, "LH_NEW_SESSION", c->Name, s->Name, ip, c->FirstSock->RemotePort,
  2639. c->FirstSock->UnderlayProtocol);
  2640. }
  2641. c->Session = s;
  2642. s->AdministratorMode = admin_mode;
  2643. StrCpy(s->UserNameReal, sizeof(s->UserNameReal), username_real);
  2644. StrCpy(s->GroupName, sizeof(s->GroupName), groupname);
  2645. // Get the session key
  2646. Copy(session_key, s->SessionKey, SHA1_SIZE);
  2647. // Set the parameters
  2648. s->MaxConnection = max_connection;
  2649. s->UseEncrypt = use_encrypt;
  2650. if (s->UseEncrypt && use_fast_rc4)
  2651. {
  2652. s->UseFastRC4 = use_fast_rc4;
  2653. }
  2654. s->UseCompress = use_compress;
  2655. s->HalfConnection = half_connection;
  2656. s->Timeout = timeout;
  2657. s->QoS = qos;
  2658. s->NoReconnectToSession = no_reconnect_to_session;
  2659. if (policy != NULL)
  2660. {
  2661. s->VLanId = policy->VLanId;
  2662. }
  2663. // User name
  2664. s->Username = CopyStr(username);
  2665. HLog(hub, "LH_SET_SESSION", s->Name, s->MaxConnection,
  2666. s->UseEncrypt ? _UU("L_YES") : _UU("L_NO"),
  2667. s->UseCompress ? _UU("L_YES") : _UU("L_NO"),
  2668. s->HalfConnection ? _UU("L_YES") : _UU("L_NO"),
  2669. s->Timeout / 1000);
  2670. msg = GetHubMsg(hub);
  2671. // Suppress client update notification flag
  2672. if (hub->Option != NULL)
  2673. {
  2674. suppress_client_update_notification = hub->Option->SuppressClientUpdateNotification;
  2675. }
  2676. }
  2677. Unlock(hub->lock);
  2678. // Send a Welcome packet to the client
  2679. p = PackWelcome(s);
  2680. PackAddBool(p, "suppress_client_update_notification", suppress_client_update_notification);
  2681. if (s->InProcMode)
  2682. {
  2683. if (IsZero(mschap_v2_server_response_20, sizeof(mschap_v2_server_response_20)) == false)
  2684. {
  2685. // MS-CHAPv2 Response
  2686. PackAddData(p, "IpcMsChapV2ServerResponse", mschap_v2_server_response_20, sizeof(mschap_v2_server_response_20));
  2687. }
  2688. }
  2689. if (true)
  2690. {
  2691. // A message to be displayed in the VPN Client (Will not be displayed if the VPN Gate Virtual HUB)
  2692. char *utf;
  2693. wchar_t winver_msg_client[3800];
  2694. wchar_t winver_msg_server[3800];
  2695. UINT tmpsize;
  2696. wchar_t *tmp;
  2697. RPC_WINVER server_winver;
  2698. GetWinVer(&server_winver);
  2699. Zero(winver_msg_client, sizeof(winver_msg_client));
  2700. Zero(winver_msg_server, sizeof(winver_msg_server));
  2701. if (IsSupportedWinVer(&winver) == false)
  2702. {
  2703. SYSTEMTIME st;
  2704. LocalTime(&st);
  2705. UniFormat(winver_msg_client, sizeof(winver_msg_client), _UU("WINVER_ERROR_FORMAT"),
  2706. _UU("WINVER_ERROR_PC_LOCAL"),
  2707. winver.Title,
  2708. _UU("WINVER_ERROR_VPNSERVER"),
  2709. SUPPORTED_WINDOWS_LIST,
  2710. _UU("WINVER_ERROR_PC_LOCAL"),
  2711. _UU("WINVER_ERROR_VPNSERVER"),
  2712. _UU("WINVER_ERROR_VPNSERVER"),
  2713. _UU("WINVER_ERROR_VPNSERVER"),
  2714. st.wYear, st.wMonth);
  2715. }
  2716. if (IsSupportedWinVer(&server_winver) == false)
  2717. {
  2718. SYSTEMTIME st;
  2719. LocalTime(&st);
  2720. UniFormat(winver_msg_server, sizeof(winver_msg_server), _UU("WINVER_ERROR_FORMAT"),
  2721. _UU("WINVER_ERROR_PC_REMOTE"),
  2722. server_winver.Title,
  2723. _UU("WINVER_ERROR_VPNSERVER"),
  2724. SUPPORTED_WINDOWS_LIST,
  2725. _UU("WINVER_ERROR_PC_REMOTE"),
  2726. _UU("WINVER_ERROR_VPNSERVER"),
  2727. _UU("WINVER_ERROR_VPNSERVER"),
  2728. _UU("WINVER_ERROR_VPNSERVER"),
  2729. st.wYear, st.wMonth);
  2730. }
  2731. tmpsize = UniStrSize(winver_msg_client) + UniStrSize(winver_msg_server) + UniStrSize(msg) + (16000 + 3000) * sizeof(wchar_t);
  2732. tmp = ZeroMalloc(tmpsize);
  2733. if (IsURLMsg(msg, NULL, 0) == false)
  2734. {
  2735. if (s != NULL && s->IsRUDPSession && c != NULL && StrCmpi(hub->Name, VG_HUBNAME) != 0)
  2736. {
  2737. // Show the warning message if the connection is made by NAT-T
  2738. wchar_t *tmp2;
  2739. UINT tmp2_size = 2400 * sizeof(wchar_t);
  2740. char local_name[128];
  2741. wchar_t local_name_2[128];
  2742. char local_name_3[128];
  2743. Zero(local_name, sizeof(local_name));
  2744. Zero(local_name_2, sizeof(local_name_2));
  2745. Zero(local_name_3, sizeof(local_name_3));
  2746. GetMachineName(local_name, sizeof(local_name));
  2747. #ifdef OS_WIN32
  2748. MsGetComputerNameFullEx(local_name_2, sizeof(local_name_2), true);
  2749. UniToStr(local_name_3, sizeof(local_name_3), local_name_2);
  2750. if (IsEmptyStr(local_name_3) == false)
  2751. {
  2752. StrCpy(local_name, sizeof(local_name), local_name_3);
  2753. }
  2754. #endif // OS_WIN32
  2755. tmp2 = ZeroMalloc(tmp2_size);
  2756. UniFormat(tmp2, tmp2_size, _UU(c->ClientBuild >= 9428 ? "NATT_MSG" : "NATT_MSG2"), local_name);
  2757. UniStrCat(tmp, tmpsize, tmp2);
  2758. Free(tmp2);
  2759. }
  2760. {
  2761. if (GetGlobalServerFlag(GSF_SHOW_OSS_MSG) != 0)
  2762. {
  2763. UniStrCat(tmp, tmpsize, _UU("OSS_MSG"));
  2764. }
  2765. }
  2766. {
  2767. UniStrCat(tmp, tmpsize, winver_msg_client);
  2768. UniStrCat(tmp, tmpsize, winver_msg_server);
  2769. }
  2770. }
  2771. UniStrCat(tmp, tmpsize, msg);
  2772. utf = CopyUniToUtf(tmp);
  2773. PackAddData(p, "Msg", utf, StrLen(utf));
  2774. Free(tmp);
  2775. Free(utf);
  2776. }
  2777. Free(msg);
  2778. if (s->UseFastRC4)
  2779. {
  2780. // Generate a RC4 key pair
  2781. GenerateRC4KeyPair(&key_pair);
  2782. // Add to Welcome packet
  2783. PackAddData(p, "rc4_key_client_to_server", key_pair.ClientToServerKey, sizeof(key_pair.ClientToServerKey));
  2784. PackAddData(p, "rc4_key_server_to_client", key_pair.ServerToClientKey, sizeof(key_pair.ServerToClientKey));
  2785. {
  2786. char key1[64], key2[64];
  2787. BinToStr(key1, sizeof(key1), key_pair.ClientToServerKey, 16);
  2788. BinToStr(key2, sizeof(key2), key_pair.ServerToClientKey, 16);
  2789. Debug(
  2790. "Client to Server Key: %s\n"
  2791. "Server to Client Key: %s\n",
  2792. key1, key2);
  2793. }
  2794. }
  2795. // Brand string for the connection limit
  2796. {
  2797. char *branded_cfroms = _SS("BRANDED_C_FROM_S");
  2798. if(StrLen(branded_cfroms) > 0)
  2799. {
  2800. PackAddStr(p, "branded_cfroms", branded_cfroms);
  2801. }
  2802. }
  2803. HttpServerSend(c->FirstSock, p);
  2804. FreePack(p);
  2805. // Receive a signature
  2806. Copy(&c->Session->NodeInfo, &node, sizeof(NODE_INFO));
  2807. {
  2808. wchar_t tmp[MAX_SIZE * 2];
  2809. NodeInfoToStr(tmp, sizeof(tmp), &s->NodeInfo);
  2810. HLog(hub, "LH_NODE_INFO", s->Name, tmp);
  2811. if (s->VLanId != 0)
  2812. {
  2813. HLog(hub, "LH_VLAN_ID", s->Name, s->VLanId);
  2814. }
  2815. }
  2816. // Shift the connection to the tunneling mode
  2817. StartTunnelingMode(c);
  2818. // Processing of half-connection mode
  2819. if (s->HalfConnection)
  2820. {
  2821. // The direction of the first socket is client to server
  2822. TCPSOCK *ts = (TCPSOCK *)LIST_DATA(c->Tcp->TcpSockList, 0);
  2823. ts->Direction = TCP_CLIENT_TO_SERVER;
  2824. }
  2825. if (s->UseFastRC4)
  2826. {
  2827. // Set the RC4 key information to the first TCP connection
  2828. TCPSOCK *ts = (TCPSOCK *)LIST_DATA(c->Tcp->TcpSockList, 0);
  2829. Copy(&ts->Rc4KeyPair, &key_pair, sizeof(RC4_KEY_PAIR));
  2830. InitTcpSockRc4Key(ts, true);
  2831. }
  2832. if (s->UseEncrypt && s->UseFastRC4 == false)
  2833. {
  2834. s->UseSSLDataEncryption = true;
  2835. }
  2836. else
  2837. {
  2838. s->UseSSLDataEncryption = false;
  2839. }
  2840. if (s->Hub->Type == HUB_TYPE_FARM_DYNAMIC && s->Cedar->Server != NULL && s->Cedar->Server->ServerType == SERVER_TYPE_FARM_CONTROLLER)
  2841. {
  2842. if (s->Hub->BeingOffline == false)
  2843. {
  2844. // Start the SecureNAT on the dynamic Virtual HUB
  2845. EnableSecureNATEx(s->Hub, false, true);
  2846. cluster_dynamic_secure_nat = true;
  2847. }
  2848. }
  2849. if (s->LocalHostSession)
  2850. {
  2851. // Update the local MAC address list
  2852. RefreshLocalMacAddressList();
  2853. }
  2854. // Discard the user list cache
  2855. DeleteAllUserListCache(hub->UserList);
  2856. // Main routine of the session
  2857. Debug("SessionMain()\n");
  2858. s->NumLoginIncrementUserObject = loggedin_user_object;
  2859. s->NumLoginIncrementHubObject = s->Hub;
  2860. s->NumLoginIncrementTick = Tick64() + (UINT64)NUM_LOGIN_INCREMENT_INTERVAL;
  2861. SessionMain(s);
  2862. // Discard the user list cache
  2863. DeleteAllUserListCache(hub->UserList);
  2864. // Decrement the current number of connections
  2865. Lock(s->Hub->lock);
  2866. {
  2867. if (use_bridge_license)
  2868. {
  2869. Dec(hub->NumSessionsBridge);
  2870. }
  2871. if (use_client_license)
  2872. {
  2873. Dec(hub->NumSessionsClient);
  2874. }
  2875. Dec(s->Hub->NumSessions);
  2876. Dec(s->Hub->Cedar->CurrentSessions);
  2877. // Decrement the number of licenses
  2878. if (use_bridge_license)
  2879. {
  2880. Dec(s->Cedar->AssignedBridgeLicense);
  2881. }
  2882. if (use_client_license)
  2883. {
  2884. Dec(s->Cedar->AssignedClientLicense);
  2885. }
  2886. if (server != NULL)
  2887. {
  2888. // Update the total allocation of the number of licenses for Server structure
  2889. if (server->ServerType == SERVER_TYPE_STANDALONE)
  2890. {
  2891. // Update only stand-alone mode
  2892. // (Periodically polled in the cluster controller mode)
  2893. server->CurrentAssignedClientLicense = Count(s->Cedar->AssignedClientLicense);
  2894. server->CurrentAssignedBridgeLicense = Count(s->Cedar->AssignedBridgeLicense);
  2895. }
  2896. }
  2897. }
  2898. Unlock(s->Hub->lock);
  2899. PrintSessionTotalDataSize(s);
  2900. HLog(s->Hub, "LH_END_SESSION", s->Name, s->TotalSendSizeReal, s->TotalRecvSizeReal);
  2901. if (cluster_dynamic_secure_nat && s->Hub->BeingOffline == false)
  2902. {
  2903. // Stop the SecureNAT on the dynamic Virtual HUB
  2904. EnableSecureNATEx(s->Hub, false, true);
  2905. }
  2906. if (s->UdpAccel != NULL)
  2907. {
  2908. // Release the UDP acceleration
  2909. FreeUdpAccel(s->UdpAccel);
  2910. s->UdpAccel = NULL;
  2911. }
  2912. ReleaseSession(s);
  2913. ret = true;
  2914. c->Err = ERR_SESSION_REMOVED;
  2915. ReleaseHub(hub);
  2916. goto CLEANUP;
  2917. }
  2918. else if (StrCmpi(method, "additional_connect") == 0)
  2919. {
  2920. SOCK *sock;
  2921. TCPSOCK *ts;
  2922. UINT dummy;
  2923. c->Type = CONNECTION_TYPE_ADDITIONAL;
  2924. // Additional connection
  2925. // Read the session key
  2926. if (GetSessionKeyFromPack(p, session_key, &dummy) == false)
  2927. {
  2928. FreePack(p);
  2929. c->Err = ERR_PROTOCOL_ERROR;
  2930. goto CLEANUP;
  2931. }
  2932. FreePack(p);
  2933. // Get the session from the session key
  2934. s = GetSessionFromKey(c->Cedar, session_key);
  2935. if (s == NULL || s->Halt || s->NoReconnectToSession)
  2936. {
  2937. // Session can not be found, or re-connection is prohibited
  2938. Debug("Session Not Found.\n");
  2939. c->Err = ERR_SESSION_TIMEOUT;
  2940. goto CLEANUP;
  2941. }
  2942. // Session is found
  2943. Debug("Session Found: %s\n", s->Name);
  2944. // Check the protocol of session
  2945. c->Err = 0;
  2946. Lock(s->lock);
  2947. {
  2948. if (s->Connection->Protocol != CONNECTION_TCP)
  2949. {
  2950. c->Err = ERR_INVALID_PROTOCOL;
  2951. }
  2952. }
  2953. Unlock(s->lock);
  2954. // Check the current number of connections of the session
  2955. Lock(s->Connection->lock);
  2956. if (c->Err == 0)
  2957. {
  2958. if (Count(s->Connection->CurrentNumConnection) > s->MaxConnection)
  2959. {
  2960. c->Err = ERR_TOO_MANY_CONNECTION;
  2961. }
  2962. }
  2963. if (c->Err != 0)
  2964. {
  2965. Unlock(s->Connection->lock);
  2966. if (c->Err == ERR_TOO_MANY_CONNECTION)
  2967. {
  2968. Debug("Session TOO MANY CONNECTIONS !!: %u\n",
  2969. Count(s->Connection->CurrentNumConnection));
  2970. }
  2971. else
  2972. {
  2973. Debug("Session Invalid Protocol.\n");
  2974. }
  2975. ReleaseSession(s);
  2976. goto CLEANUP;
  2977. }
  2978. // Generate a high-speed RC4 encryption key
  2979. if (s->UseFastRC4)
  2980. {
  2981. GenerateRC4KeyPair(&key_pair);
  2982. }
  2983. // Add the socket of this connection to the connection list of the session (TCP)
  2984. sock = c->FirstSock;
  2985. ts = NewTcpSock(sock);
  2986. SetTimeout(sock, CONNECTING_TIMEOUT);
  2987. direction = TCP_BOTH;
  2988. LockList(s->Connection->Tcp->TcpSockList);
  2989. {
  2990. if (s->HalfConnection)
  2991. {
  2992. // In half-connection, directions of the TCP connections are automatically
  2993. // adjusted by examining all current direction of the TCP connections
  2994. UINT i, c2s, s2c;
  2995. c2s = s2c = 0;
  2996. for (i = 0;i < LIST_NUM(s->Connection->Tcp->TcpSockList);i++)
  2997. {
  2998. TCPSOCK *ts = (TCPSOCK *)LIST_DATA(s->Connection->Tcp->TcpSockList, i);
  2999. if (ts->Direction == TCP_SERVER_TO_CLIENT)
  3000. {
  3001. s2c++;
  3002. }
  3003. else
  3004. {
  3005. c2s++;
  3006. }
  3007. }
  3008. if (s2c > c2s)
  3009. {
  3010. direction = TCP_CLIENT_TO_SERVER;
  3011. }
  3012. else
  3013. {
  3014. direction = TCP_SERVER_TO_CLIENT;
  3015. }
  3016. Debug("%u/%u\n", s2c, c2s);
  3017. ts->Direction = direction;
  3018. }
  3019. }
  3020. UnlockList(s->Connection->Tcp->TcpSockList);
  3021. if (s->UseFastRC4)
  3022. {
  3023. // Set the RC4 key information
  3024. Copy(&ts->Rc4KeyPair, &key_pair, sizeof(RC4_KEY_PAIR));
  3025. InitTcpSockRc4Key(ts, true);
  3026. }
  3027. // Return a success result
  3028. p = PackError(ERR_NO_ERROR);
  3029. PackAddInt(p, "direction", direction);
  3030. if (s->UseFastRC4)
  3031. {
  3032. // Add a RC4 key information
  3033. PackAddData(p, "rc4_key_client_to_server", key_pair.ClientToServerKey, sizeof(key_pair.ClientToServerKey));
  3034. PackAddData(p, "rc4_key_server_to_client", key_pair.ServerToClientKey, sizeof(key_pair.ServerToClientKey));
  3035. {
  3036. char key1[64], key2[64];
  3037. BinToStr(key1, sizeof(key1), key_pair.ClientToServerKey, 16);
  3038. BinToStr(key2, sizeof(key2), key_pair.ServerToClientKey, 16);
  3039. Debug(
  3040. "Client to Server Key: %s\n"
  3041. "Server to Client Key: %s\n",
  3042. key1, key2);
  3043. }
  3044. }
  3045. HttpServerSend(c->FirstSock, p);
  3046. FreePack(p);
  3047. SetTimeout(sock, INFINITE);
  3048. LockList(s->Connection->Tcp->TcpSockList);
  3049. {
  3050. Add(s->Connection->Tcp->TcpSockList, ts);
  3051. }
  3052. UnlockList(s->Connection->Tcp->TcpSockList);
  3053. // Increment the number of connections
  3054. Inc(s->Connection->CurrentNumConnection);
  3055. Debug("TCP Connection Incremented: %u\n", Count(s->Connection->CurrentNumConnection));
  3056. // Issue the Cancel of session
  3057. Cancel(s->Cancel1);
  3058. Unlock(s->Connection->lock);
  3059. c->flag1 = true;
  3060. ReleaseSession(s);
  3061. return true;
  3062. }
  3063. else if (StrCmpi(method, "enum_hub") == 0)
  3064. {
  3065. // Enumerate the Virtual HUB
  3066. UINT i, num;
  3067. LIST *o;
  3068. o = NewListFast(NULL);
  3069. c->Type = CONNECTION_TYPE_ENUM_HUB;
  3070. FreePack(p);
  3071. p = NewPack();
  3072. LockList(c->Cedar->HubList);
  3073. {
  3074. num = LIST_NUM(c->Cedar->HubList);
  3075. for (i = 0;i < num;i++)
  3076. {
  3077. HUB *h = LIST_DATA(c->Cedar->HubList, i);
  3078. if (h->Option != NULL && h->Option->NoEnum == false)
  3079. {
  3080. Insert(o, CopyStr(h->Name));
  3081. }
  3082. }
  3083. }
  3084. UnlockList(c->Cedar->HubList);
  3085. num = LIST_NUM(o);
  3086. for (i = 0;i < num;i++)
  3087. {
  3088. char *name = LIST_DATA(o, i);
  3089. PackAddStrEx(p, "HubName", name, i, num);
  3090. Free(name);
  3091. }
  3092. ReleaseList(o);
  3093. PackAddInt(p, "NumHub", num);
  3094. HttpServerSend(c->FirstSock, p);
  3095. FreePack(p);
  3096. FreePack(HttpServerRecv(c->FirstSock));
  3097. c->Err = 0;
  3098. SLog(c->Cedar, "LS_ENUM_HUB", c->Name, num);
  3099. error_detail = "enum_hub";
  3100. goto CLEANUP;
  3101. }
  3102. else if (StrCmpi(method, "farm_connect") == 0)
  3103. {
  3104. // Server farm connection request
  3105. CEDAR *cedar = c->Cedar;
  3106. c->Type = CONNECTION_TYPE_FARM_RPC;
  3107. c->Err = 0;
  3108. if (c->Cedar->Server == NULL)
  3109. {
  3110. // Unsupported
  3111. c->Err = ERR_NOT_FARM_CONTROLLER;
  3112. }
  3113. else
  3114. {
  3115. SERVER *s = c->Cedar->Server;
  3116. if (s->ServerType != SERVER_TYPE_FARM_CONTROLLER || s->FarmControllerInited == false)
  3117. {
  3118. // Not a farm controller
  3119. SLog(c->Cedar, "LS_FARM_ACCEPT_1", c->Name);
  3120. c->Err = ERR_NOT_FARM_CONTROLLER;
  3121. }
  3122. else
  3123. {
  3124. UCHAR check_secure_password[SHA1_SIZE];
  3125. UCHAR secure_password[SHA1_SIZE];
  3126. // User authentication
  3127. SecurePassword(check_secure_password, s->HashedPassword, c->Random);
  3128. if (PackGetDataSize(p, "SecurePassword") == sizeof(secure_password))
  3129. {
  3130. PackGetData(p, "SecurePassword", secure_password);
  3131. }
  3132. else
  3133. {
  3134. Zero(secure_password, sizeof(secure_password));
  3135. }
  3136. if (Cmp(secure_password, check_secure_password, SHA1_SIZE) != 0)
  3137. {
  3138. // Password is different
  3139. SLog(c->Cedar, "LS_FARM_ACCEPT_2", c->Name);
  3140. c->Err = ERR_ACCESS_DENIED;
  3141. }
  3142. else
  3143. {
  3144. // Get the certificate
  3145. BUF *b;
  3146. X *server_x;
  3147. SLog(c->Cedar, "LS_FARM_ACCEPT_3", c->Name);
  3148. b = PackGetBuf(p, "ServerCert");
  3149. if (b == NULL)
  3150. {
  3151. c->Err = ERR_PROTOCOL_ERROR;
  3152. }
  3153. else
  3154. {
  3155. server_x = BufToX(b, false);
  3156. FreeBuf(b);
  3157. if (server_x == NULL)
  3158. {
  3159. c->Err = ERR_PROTOCOL_ERROR;
  3160. }
  3161. else
  3162. {
  3163. UINT ip;
  3164. UINT point;
  3165. char hostname[MAX_SIZE];
  3166. #ifdef OS_WIN32
  3167. MsSetThreadPriorityRealtime();
  3168. #endif // OS_WIN32
  3169. SetTimeout(c->FirstSock, SERVER_CONTROL_TCP_TIMEOUT);
  3170. ip = PackGetIp32(p, "PublicIp");
  3171. point = PackGetInt(p, "Point");
  3172. if (PackGetStr(p, "HostName", hostname, sizeof(hostname)))
  3173. {
  3174. UINT num_port = PackGetIndexCount(p, "PublicPort");
  3175. if (num_port >= 1 && num_port <= MAX_PUBLIC_PORT_NUM)
  3176. {
  3177. UINT *ports = ZeroMalloc(sizeof(UINT) * num_port);
  3178. UINT i;
  3179. for (i = 0;i < num_port;i++)
  3180. {
  3181. ports[i] = PackGetIntEx(p, "PublicPort", i);
  3182. }
  3183. SiFarmServ(s, c->FirstSock, server_x, ip, num_port, ports, hostname, point,
  3184. PackGetInt(p, "Weight"), PackGetInt(p, "MaxSessions"));
  3185. Free(ports);
  3186. }
  3187. }
  3188. FreeX(server_x);
  3189. }
  3190. }
  3191. }
  3192. }
  3193. }
  3194. FreePack(p);
  3195. goto CLEANUP;
  3196. }
  3197. else if (StrCmpi(method, "admin") == 0 && c->Cedar->Server != NULL)
  3198. {
  3199. UINT err;
  3200. // Administrative RPC connection request
  3201. c->Type = CONNECTION_TYPE_ADMIN_RPC;
  3202. err = AdminAccept(c, p);
  3203. FreePack(p);
  3204. if (err != ERR_NO_ERROR)
  3205. {
  3206. PACK *p = PackError(err);
  3207. HttpServerSend(c->FirstSock, p);
  3208. FreePack(p);
  3209. }
  3210. error_detail = "admin_rpc";
  3211. goto CLEANUP;
  3212. }
  3213. else if (StrCmpi(method, "password") == 0)
  3214. {
  3215. UINT err;
  3216. // Password change request
  3217. c->Type = CONNECTION_TYPE_PASSWORD;
  3218. err = ChangePasswordAccept(c, p);
  3219. FreePack(p);
  3220. p = PackError(err);
  3221. HttpServerSend(c->FirstSock, p);
  3222. FreePack(p);
  3223. error_detail = "change_password";
  3224. goto CLEANUP;
  3225. }
  3226. else
  3227. {
  3228. // Unknown method
  3229. FreePack(p);
  3230. c->Err = ERR_PROTOCOL_ERROR;
  3231. error_detail = "unknown_method";
  3232. goto CLEANUP;
  3233. }
  3234. CLEANUP:
  3235. // Release the user object
  3236. if (loggedin_user_object != NULL)
  3237. {
  3238. ReleaseUser(loggedin_user_object);
  3239. }
  3240. // Error packet transmission
  3241. if (supress_return_pack_error == false)
  3242. {
  3243. p = PackError(c->Err);
  3244. PackAddBool(p, "no_save_password", no_save_password);
  3245. HttpServerSend(c->FirstSock, p);
  3246. FreePack(p);
  3247. }
  3248. FreePack(HttpServerRecv(c->FirstSock));
  3249. SleepThread(25);
  3250. SLog(c->Cedar, "LS_CONNECTION_ERROR", c->Name, GetUniErrorStr(c->Err), c->Err);
  3251. if (release_me_eap_client != NULL)
  3252. {
  3253. ReleaseEapClient(release_me_eap_client);
  3254. }
  3255. return ret;
  3256. }
  3257. // Create a Node information
  3258. void CreateNodeInfo(NODE_INFO *info, CONNECTION *c)
  3259. {
  3260. SESSION *s;
  3261. OS_INFO *os;
  3262. char *product_id;
  3263. IP ip;
  3264. bool is_vgc = false;
  3265. // Validate arguments
  3266. if (c == NULL)
  3267. {
  3268. return;
  3269. }
  3270. s = c->Session;
  3271. os = GetOsInfo();
  3272. Zero(info, sizeof(NODE_INFO));
  3273. // Client product name
  3274. StrCpy(info->ClientProductName, sizeof(info->ClientProductName), c->ClientStr);
  3275. // Client version
  3276. info->ClientProductVer = Endian32(c->ClientVer);
  3277. // Client build number
  3278. info->ClientProductBuild = Endian32(c->ClientBuild);
  3279. // Server product name
  3280. StrCpy(info->ServerProductName, sizeof(info->ServerProductName), c->ServerStr);
  3281. // Server version
  3282. info->ServerProductVer = Endian32(c->ServerVer);
  3283. // Server build number
  3284. info->ServerProductBuild = Endian32(c->ServerBuild);
  3285. // Client OS name
  3286. StrCpy(info->ClientOsName, sizeof(info->ClientOsName), os->OsProductName);
  3287. // Client OS version
  3288. StrCpy(info->ClientOsVer, sizeof(info->ClientOsVer), os->OsVersion);
  3289. // Client OS Product ID
  3290. product_id = OSGetProductId();
  3291. StrCpy(info->ClientOsProductId, sizeof(info->ClientOsProductId), product_id);
  3292. Free(product_id);
  3293. // Client host name
  3294. #ifndef OS_WIN32
  3295. GetMachineName(info->ClientHostname, sizeof(info->ClientHostname));
  3296. #else // OS_WIN32
  3297. if (true)
  3298. {
  3299. wchar_t namew[256];
  3300. char namea[256];
  3301. Zero(namew, sizeof(namew));
  3302. MsGetComputerNameFullEx(namew, sizeof(namew), true);
  3303. Zero(namea, sizeof(namea));
  3304. UniToStr(namea, sizeof(namea), namew);
  3305. if (IsEmptyStr(namea))
  3306. {
  3307. GetMachineName(namea, sizeof(namea));
  3308. }
  3309. StrCpy(info->ClientHostname, sizeof(info->ClientHostname), namea);
  3310. }
  3311. #endif // OS_WIN32
  3312. // Client IP address
  3313. if (IsIP6(&c->FirstSock->LocalIP) == false)
  3314. {
  3315. info->ClientIpAddress = IPToUINT(&c->FirstSock->LocalIP);
  3316. }
  3317. else
  3318. {
  3319. Copy(info->ClientIpAddress6, c->FirstSock->LocalIP.ipv6_addr, sizeof(info->ClientIpAddress6));
  3320. }
  3321. // Client port number
  3322. info->ClientPort = Endian32(c->FirstSock->LocalPort);
  3323. // Server host name
  3324. StrCpy(info->ServerHostname, sizeof(info->ServerHostname), c->ServerName);
  3325. // Server IP address
  3326. if (GetIP(&ip, info->ServerHostname))
  3327. {
  3328. if (IsIP6(&ip) == false)
  3329. {
  3330. info->ServerIpAddress = IPToUINT(&ip);
  3331. }
  3332. else
  3333. {
  3334. Copy(info->ServerIpAddress6, ip.ipv6_addr, sizeof(info->ServerIpAddress6));
  3335. }
  3336. }
  3337. // Server port number
  3338. info->ServerPort = Endian32(c->ServerPort);
  3339. if (s->ClientOption->ProxyType == PROXY_SOCKS || s->ClientOption->ProxyType == PROXY_HTTP)
  3340. {
  3341. // Proxy host name
  3342. StrCpy(info->ProxyHostname, sizeof(info->ProxyHostname), s->ClientOption->ProxyName);
  3343. // Proxy Server IP Address
  3344. if (IsIP6(&c->FirstSock->RemoteIP) == false)
  3345. {
  3346. info->ProxyIpAddress = IPToUINT(&c->FirstSock->RemoteIP);
  3347. }
  3348. else
  3349. {
  3350. Copy(&info->ProxyIpAddress6, c->FirstSock->RemoteIP.ipv6_addr, sizeof(info->ProxyIpAddress6));
  3351. }
  3352. info->ProxyPort = Endian32(c->FirstSock->RemotePort);
  3353. }
  3354. // HUB name
  3355. StrCpy(info->HubName, sizeof(info->HubName), s->ClientOption->HubName);
  3356. // Unique ID
  3357. Copy(info->UniqueId, c->Cedar->UniqueId, sizeof(info->UniqueId));
  3358. }
  3359. // Connect a socket additionally
  3360. SOCK *ClientAdditionalConnectToServer(CONNECTION *c)
  3361. {
  3362. SOCK *s;
  3363. // Validate arguments
  3364. if (c == NULL)
  3365. {
  3366. return NULL;
  3367. }
  3368. // Socket connection
  3369. s = ClientConnectGetSocket(c, true, (c->DontUseTls1 ? false : true));
  3370. if (s == NULL)
  3371. {
  3372. // Connection failure
  3373. return NULL;
  3374. }
  3375. // Add the socket to the list
  3376. LockList(c->ConnectingSocks);
  3377. {
  3378. Add(c->ConnectingSocks, s);
  3379. AddRef(s->ref);
  3380. }
  3381. UnlockList(c->ConnectingSocks);
  3382. if (c->Session->Halt)
  3383. {
  3384. // Stop
  3385. Disconnect(s);
  3386. LockList(c->ConnectingSocks);
  3387. {
  3388. if (Delete(c->ConnectingSocks, s))
  3389. {
  3390. ReleaseSock(s);
  3391. }
  3392. }
  3393. UnlockList(c->ConnectingSocks);
  3394. ReleaseSock(s);
  3395. return NULL;
  3396. }
  3397. // Time-out
  3398. SetTimeout(s, CONNECTING_TIMEOUT);
  3399. // Start the SSL communication
  3400. if (StartSSLEx(s, NULL, NULL, (c->DontUseTls1 ? false : true), 0, c->ServerName) == false)
  3401. {
  3402. // SSL communication failure
  3403. Disconnect(s);
  3404. LockList(c->ConnectingSocks);
  3405. {
  3406. if (Delete(c->ConnectingSocks, s))
  3407. {
  3408. ReleaseSock(s);
  3409. }
  3410. }
  3411. UnlockList(c->ConnectingSocks);
  3412. ReleaseSock(s);
  3413. return NULL;
  3414. }
  3415. // Check the certificate
  3416. if (CompareX(s->RemoteX, c->ServerX) == false)
  3417. {
  3418. // The certificate is invalid
  3419. Disconnect(s);
  3420. c->Session->SessionTimeOuted = true;
  3421. }
  3422. return s;
  3423. }
  3424. // Remove the key and certificate in the secure device
  3425. UINT SecureDelete(UINT device_id, char *pin, char *cert_name, char *key_name)
  3426. {
  3427. SECURE *sec;
  3428. // Validate arguments
  3429. if (pin == NULL || device_id == 0)
  3430. {
  3431. return ERR_INTERNAL_ERROR;
  3432. }
  3433. // Open the device
  3434. sec = OpenSec(device_id);
  3435. if (sec == NULL)
  3436. {
  3437. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3438. }
  3439. // Open the session
  3440. if (OpenSecSession(sec, 0) == false)
  3441. {
  3442. CloseSec(sec);
  3443. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3444. }
  3445. // Login
  3446. if (LoginSec(sec, pin) == false)
  3447. {
  3448. CloseSecSession(sec);
  3449. CloseSec(sec);
  3450. return ERR_SECURE_PIN_LOGIN_FAILED;
  3451. }
  3452. // Delete the certificate
  3453. if (cert_name != NULL)
  3454. {
  3455. DeleteSecCert(sec, cert_name);
  3456. }
  3457. // Delete the Private key
  3458. if (key_name != NULL)
  3459. {
  3460. DeleteSecKey(sec, key_name);
  3461. }
  3462. // Log out
  3463. LogoutSec(sec);
  3464. // Close the session
  3465. CloseSecSession(sec);
  3466. // Close the device
  3467. CloseSec(sec);
  3468. return ERR_NO_ERROR;
  3469. }
  3470. // Enumerate certificates and keys in the secure device
  3471. UINT SecureEnum(UINT device_id, char *pin, TOKEN_LIST **cert_list, TOKEN_LIST **key_list)
  3472. {
  3473. SECURE *sec;
  3474. LIST *o;
  3475. LIST *cert_name_list, *key_name_list;
  3476. // Validate arguments
  3477. if (pin == NULL || device_id == 0 || cert_list == NULL || key_list == NULL)
  3478. {
  3479. return ERR_INTERNAL_ERROR;
  3480. }
  3481. // Open the device
  3482. sec = OpenSec(device_id);
  3483. if (sec == NULL)
  3484. {
  3485. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3486. }
  3487. // Open the session
  3488. if (OpenSecSession(sec, 0) == false)
  3489. {
  3490. CloseSec(sec);
  3491. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3492. }
  3493. // Login
  3494. if (LoginSec(sec, pin) == false)
  3495. {
  3496. CloseSecSession(sec);
  3497. CloseSec(sec);
  3498. return ERR_SECURE_PIN_LOGIN_FAILED;
  3499. }
  3500. // Enumerate objects
  3501. if ((o = EnumSecObject(sec)) != NULL)
  3502. {
  3503. UINT i;
  3504. cert_name_list = NewList(CompareStr);
  3505. key_name_list = NewList(CompareStr);
  3506. for (i = 0;i < LIST_NUM(o);i++)
  3507. {
  3508. SEC_OBJ *obj = LIST_DATA(o, i);
  3509. if (obj->Type == SEC_X)
  3510. {
  3511. Add(cert_name_list, CopyStr(obj->Name));
  3512. }
  3513. else if (obj->Type == SEC_K)
  3514. {
  3515. Add(key_name_list, CopyStr(obj->Name));
  3516. }
  3517. }
  3518. Sort(cert_name_list);
  3519. Sort(key_name_list);
  3520. *cert_list = ListToTokenList(cert_name_list);
  3521. *key_list = ListToTokenList(key_name_list);
  3522. // Release the memory
  3523. FreeStrList(cert_name_list);
  3524. FreeStrList(key_name_list);
  3525. FreeEnumSecObject(o);
  3526. }
  3527. else
  3528. {
  3529. *cert_list = NullToken();
  3530. *key_list = NullToken();
  3531. }
  3532. // Log out
  3533. LogoutSec(sec);
  3534. // Close the session
  3535. CloseSecSession(sec);
  3536. // Close the device
  3537. CloseSec(sec);
  3538. return ERR_NO_ERROR;
  3539. }
  3540. // Record the certificate and key to secure device
  3541. UINT SecureWrite(UINT device_id, char *cert_name, X *x, char *key_name, K *k, char *pin)
  3542. {
  3543. SECURE *sec;
  3544. bool failed;
  3545. // Validate arguments
  3546. if (pin == NULL || device_id == 0 || cert_name == NULL || x == NULL || key_name == NULL || k == NULL)
  3547. {
  3548. return ERR_INTERNAL_ERROR;
  3549. }
  3550. // Open the device
  3551. sec = OpenSec(device_id);
  3552. if (sec == NULL)
  3553. {
  3554. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3555. }
  3556. // Open the session
  3557. if (OpenSecSession(sec, 0) == false)
  3558. {
  3559. CloseSec(sec);
  3560. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3561. }
  3562. // Login
  3563. if (LoginSec(sec, pin) == false)
  3564. {
  3565. CloseSecSession(sec);
  3566. CloseSec(sec);
  3567. return ERR_SECURE_PIN_LOGIN_FAILED;
  3568. }
  3569. // Registration
  3570. failed = false;
  3571. // Register the certificate
  3572. if (WriteSecCert(sec, true, cert_name, x) == false)
  3573. {
  3574. failed = true;
  3575. }
  3576. // Register the private key
  3577. if (WriteSecKey(sec, true, key_name, k) == false)
  3578. {
  3579. failed = true;
  3580. }
  3581. // Log out
  3582. LogoutSec(sec);
  3583. // Close the session
  3584. CloseSecSession(sec);
  3585. // Close the device
  3586. CloseSec(sec);
  3587. if (failed == false)
  3588. {
  3589. // Success
  3590. return ERR_NO_ERROR;
  3591. }
  3592. else
  3593. {
  3594. // Failure
  3595. return ERR_SECURE_CANT_WRITE;
  3596. }
  3597. }
  3598. // Attempt to sign by the secure device
  3599. UINT SecureSign(SECURE_SIGN *sign, UINT device_id, char *pin)
  3600. {
  3601. SECURE *sec;
  3602. X *x;
  3603. // Validate arguments
  3604. if (sign == false || pin == NULL || device_id == 0)
  3605. {
  3606. return ERR_INTERNAL_ERROR;
  3607. }
  3608. // Open the device
  3609. sec = OpenSec(device_id);
  3610. if (sec == NULL)
  3611. {
  3612. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3613. }
  3614. // Open the session
  3615. if (OpenSecSession(sec, 0) == false)
  3616. {
  3617. CloseSec(sec);
  3618. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3619. }
  3620. // Login
  3621. if (LoginSec(sec, pin) == false)
  3622. {
  3623. CloseSecSession(sec);
  3624. CloseSec(sec);
  3625. return ERR_SECURE_PIN_LOGIN_FAILED;
  3626. }
  3627. // Read the certificate
  3628. x = ReadSecCert(sec, sign->SecurePublicCertName);
  3629. if (x == NULL)
  3630. {
  3631. LogoutSec(sec);
  3632. CloseSecSession(sec);
  3633. CloseSec(sec);
  3634. return ERR_SECURE_NO_CERT;
  3635. }
  3636. // Sign by the private key
  3637. if (SignSec(sec, sign->SecurePrivateKeyName, sign->Signature, sign->Random, SHA1_SIZE) == false)
  3638. {
  3639. // Signing failure
  3640. FreeX(x);
  3641. LogoutSec(sec);
  3642. CloseSecSession(sec);
  3643. CloseSec(sec);
  3644. return ERR_SECURE_NO_PRIVATE_KEY;
  3645. }
  3646. // Convert the certificate to buffer
  3647. sign->ClientCert = x;
  3648. // Log out
  3649. LogoutSec(sec);
  3650. // Close the session
  3651. CloseSecSession(sec);
  3652. // Close the device
  3653. CloseSec(sec);
  3654. // Success
  3655. return ERR_NO_ERROR;
  3656. }
  3657. // Client connects to the server additionally
  3658. bool ClientAdditionalConnect(CONNECTION *c, THREAD *t)
  3659. {
  3660. SOCK *s;
  3661. PACK *p;
  3662. TCPSOCK *ts;
  3663. UINT err;
  3664. UINT direction;
  3665. RC4_KEY_PAIR key_pair;
  3666. // Validate arguments
  3667. if (c == NULL)
  3668. {
  3669. return false;
  3670. }
  3671. // Socket connection to the server
  3672. s = ClientAdditionalConnectToServer(c);
  3673. if (s == NULL)
  3674. {
  3675. // Failed to connect socket
  3676. return false;
  3677. }
  3678. if (c->Halt)
  3679. {
  3680. goto CLEANUP;
  3681. }
  3682. // Send a signature
  3683. Debug("Uploading Signature...\n");
  3684. if (ClientUploadSignature(s) == false)
  3685. {
  3686. goto CLEANUP;
  3687. }
  3688. if (c->Halt)
  3689. {
  3690. // Stop
  3691. goto CLEANUP;
  3692. }
  3693. // Receive a Hello packet
  3694. Debug("Downloading Hello...\n");
  3695. if (ClientDownloadHello(c, s) == false)
  3696. {
  3697. goto CLEANUP;
  3698. }
  3699. if (c->Halt)
  3700. {
  3701. // Stop
  3702. goto CLEANUP;
  3703. }
  3704. // Send a authentication data for the additional connection
  3705. if (ClientUploadAuth2(c, s) == false)
  3706. {
  3707. // Disconnected
  3708. goto CLEANUP;
  3709. }
  3710. // Receive a response
  3711. p = HttpClientRecv(s);
  3712. if (p == NULL)
  3713. {
  3714. // Disconnected
  3715. goto CLEANUP;
  3716. }
  3717. err = GetErrorFromPack(p);
  3718. direction = PackGetInt(p, "direction");
  3719. if (c->Session->UseFastRC4)
  3720. {
  3721. // Get the RC4 key information
  3722. if (PackGetDataSize(p, "rc4_key_client_to_server") == 16)
  3723. {
  3724. PackGetData(p, "rc4_key_client_to_server", key_pair.ClientToServerKey);
  3725. }
  3726. if (PackGetDataSize(p, "rc4_key_server_to_client") == 16)
  3727. {
  3728. PackGetData(p, "rc4_key_server_to_client", key_pair.ServerToClientKey);
  3729. }
  3730. {
  3731. char key1[64], key2[64];
  3732. BinToStr(key1, sizeof(key1), key_pair.ClientToServerKey, 16);
  3733. BinToStr(key2, sizeof(key2), key_pair.ServerToClientKey, 16);
  3734. Debug(
  3735. "Client to Server Key: %s\n"
  3736. "Server to Client Key: %s\n",
  3737. key1, key2);
  3738. }
  3739. }
  3740. FreePack(p);
  3741. p = NULL;
  3742. if (err != 0)
  3743. {
  3744. // Error has occurred
  3745. Debug("Additional Connect Error: %u\n", err);
  3746. if (err == ERR_SESSION_TIMEOUT || err == ERR_INVALID_PROTOCOL)
  3747. {
  3748. // We shall re-connection because it is a fatal error
  3749. c->Session->SessionTimeOuted = true;
  3750. }
  3751. goto CLEANUP;
  3752. }
  3753. Debug("Additional Connect Succeed!\n");
  3754. // Success the additional connection
  3755. // Add to the TcpSockList of the connection
  3756. ts = NewTcpSock(s);
  3757. if (c->ServerMode == false)
  3758. {
  3759. if (c->Session->ClientOption->ConnectionDisconnectSpan != 0)
  3760. {
  3761. ts->DisconnectTick = Tick64() + c->Session->ClientOption->ConnectionDisconnectSpan * (UINT64)1000;
  3762. }
  3763. }
  3764. LockList(c->Tcp->TcpSockList);
  3765. {
  3766. ts->Direction = direction;
  3767. Add(c->Tcp->TcpSockList, ts);
  3768. }
  3769. UnlockList(c->Tcp->TcpSockList);
  3770. Debug("TCP Connection Incremented: %u\n", Count(c->CurrentNumConnection));
  3771. if (c->Session->HalfConnection)
  3772. {
  3773. Debug("New Half Connection: %s\n",
  3774. direction == TCP_SERVER_TO_CLIENT ? "TCP_SERVER_TO_CLIENT" : "TCP_CLIENT_TO_SERVER"
  3775. );
  3776. }
  3777. if (c->Session->UseFastRC4)
  3778. {
  3779. // Set the RC4 encryption key
  3780. Copy(&ts->Rc4KeyPair, &key_pair, sizeof(RC4_KEY_PAIR));
  3781. InitTcpSockRc4Key(ts, false);
  3782. }
  3783. // Issue the Cancel to the session
  3784. Cancel(c->Session->Cancel1);
  3785. // Remove the socket from the socket list of connected
  3786. LockList(c->ConnectingSocks);
  3787. {
  3788. if (Delete(c->ConnectingSocks, s))
  3789. {
  3790. ReleaseSock(s);
  3791. }
  3792. }
  3793. UnlockList(c->ConnectingSocks);
  3794. ReleaseSock(s);
  3795. return true;
  3796. CLEANUP:
  3797. // Disconnection process
  3798. Disconnect(s);
  3799. LockList(c->ConnectingSocks);
  3800. {
  3801. if (Delete(c->ConnectingSocks, s))
  3802. {
  3803. ReleaseSock(s);
  3804. }
  3805. }
  3806. UnlockList(c->ConnectingSocks);
  3807. ReleaseSock(s);
  3808. return false;
  3809. }
  3810. // Secure device signing thread
  3811. void ClientSecureSignThread(THREAD *thread, void *param)
  3812. {
  3813. SECURE_SIGN_THREAD_PROC *p = (SECURE_SIGN_THREAD_PROC *)param;
  3814. // Validate arguments
  3815. if (thread == NULL || param == NULL)
  3816. {
  3817. return;
  3818. }
  3819. NoticeThreadInit(thread);
  3820. p->Ok = p->SecureSignProc(p->Connection->Session, p->Connection, p->SecureSign);
  3821. p->UserFinished = true;
  3822. }
  3823. // Signing with the secure device
  3824. bool ClientSecureSign(CONNECTION *c, UCHAR *sign, UCHAR *random, X **x)
  3825. {
  3826. SECURE_SIGN_THREAD_PROC *p;
  3827. SECURE_SIGN *ss;
  3828. SESSION *s;
  3829. CLIENT_OPTION *o;
  3830. CLIENT_AUTH *a;
  3831. THREAD *thread;
  3832. UINT64 start;
  3833. bool ret;
  3834. // Validate arguments
  3835. if (c == NULL || sign == NULL || random == NULL || x == NULL)
  3836. {
  3837. return false;
  3838. }
  3839. s = c->Session;
  3840. o = s->ClientOption;
  3841. a = s->ClientAuth;
  3842. p = ZeroMalloc(sizeof(SECURE_SIGN_THREAD_PROC));
  3843. p->Connection = c;
  3844. ss = p->SecureSign = ZeroMallocEx(sizeof(SECURE_SIGN), true);
  3845. StrCpy(ss->SecurePrivateKeyName, sizeof(ss->SecurePrivateKeyName),
  3846. a->SecurePrivateKeyName);
  3847. StrCpy(ss->SecurePublicCertName, sizeof(ss->SecurePublicCertName),
  3848. a->SecurePublicCertName);
  3849. ss->UseSecureDeviceId = c->Cedar->Client->UseSecureDeviceId;
  3850. Copy(ss->Random, random, SHA1_SIZE);
  3851. #ifdef OS_WIN32
  3852. ss->BitmapId = CmGetSecureBitmapId(c->ServerName);
  3853. #endif // OS_WIN32
  3854. p->SecureSignProc = a->SecureSignProc;
  3855. // Create a thread
  3856. thread = NewThread(ClientSecureSignThread, p);
  3857. WaitThreadInit(thread);
  3858. // Poll every 0.5 seconds until signing is completed or canceled
  3859. start = Tick64();
  3860. while (true)
  3861. {
  3862. if ((Tick64() - start) > CONNECTING_POOLING_SPAN)
  3863. {
  3864. // Send a NOOP periodically for disconnection prevention
  3865. start = Tick64();
  3866. ClientUploadNoop(c);
  3867. }
  3868. if (p->UserFinished)
  3869. {
  3870. // User selected
  3871. break;
  3872. }
  3873. WaitThread(thread, 500);
  3874. }
  3875. ReleaseThread(thread);
  3876. ret = p->Ok;
  3877. if (ret)
  3878. {
  3879. Copy(sign, ss->Signature, 128);
  3880. *x = ss->ClientCert;
  3881. }
  3882. Free(p->SecureSign);
  3883. Free(p);
  3884. return ret;
  3885. }
  3886. // Server certificate confirmation thread
  3887. void ClientCheckServerCertThread(THREAD *thread, void *param)
  3888. {
  3889. CHECK_CERT_THREAD_PROC *p = (CHECK_CERT_THREAD_PROC *)param;
  3890. // Validate arguments
  3891. if (thread == NULL || param == NULL)
  3892. {
  3893. return;
  3894. }
  3895. // Notify the completion of initialization
  3896. NoticeThreadInit(thread);
  3897. // Query for the selection to the user
  3898. p->Ok = p->CheckCertProc(p->Connection->Session, p->Connection, p->ServerX, &p->Exipred);
  3899. p->UserSelected = true;
  3900. }
  3901. // Client verify the certificate of the server
  3902. bool ClientCheckServerCert(CONNECTION *c, bool *expired)
  3903. {
  3904. CLIENT_AUTH *auth;
  3905. X *x;
  3906. CHECK_CERT_THREAD_PROC *p;
  3907. THREAD *thread;
  3908. CEDAR *cedar;
  3909. bool ret;
  3910. UINT64 start;
  3911. // Validate arguments
  3912. if (c == NULL)
  3913. {
  3914. return false;
  3915. }
  3916. if (expired != NULL)
  3917. {
  3918. *expired = false;
  3919. }
  3920. auth = c->Session->ClientAuth;
  3921. cedar = c->Cedar;
  3922. if (auth->CheckCertProc == NULL && c->Session->LinkModeClient == false)
  3923. {
  3924. // No checking function
  3925. return true;
  3926. }
  3927. if (c->Session->LinkModeClient && c->Session->Link->CheckServerCert == false)
  3928. {
  3929. // It's in cascade connection mode, but do not check the server certificate
  3930. return true;
  3931. }
  3932. if (c->UseTicket)
  3933. {
  3934. // Check the certificate of the redirected VPN server
  3935. if (CompareX(c->FirstSock->RemoteX, c->ServerX) == false)
  3936. {
  3937. return false;
  3938. }
  3939. else
  3940. {
  3941. return true;
  3942. }
  3943. }
  3944. x = CloneX(c->FirstSock->RemoteX);
  3945. if (x == NULL)
  3946. {
  3947. // Strange error occurs
  3948. return false;
  3949. }
  3950. if (CheckXDateNow(x))
  3951. {
  3952. // Check whether it is signed by the root certificate to trust
  3953. if (c->Session->LinkModeClient == false)
  3954. {
  3955. // Normal VPN Client mode
  3956. if (CheckSignatureByCa(cedar, x))
  3957. {
  3958. // This certificate can be trusted because it is signed
  3959. FreeX(x);
  3960. return true;
  3961. }
  3962. }
  3963. else
  3964. {
  3965. // Cascade connection mode
  3966. if (CheckSignatureByCaLinkMode(c->Session, x))
  3967. {
  3968. // This certificate can be trusted because it is signed
  3969. FreeX(x);
  3970. return true;
  3971. }
  3972. }
  3973. }
  3974. if (c->Session->LinkModeClient)
  3975. {
  3976. if (CheckXDateNow(x))
  3977. {
  3978. Lock(c->Session->Link->lock);
  3979. {
  3980. if (c->Session->Link->ServerCert != NULL)
  3981. {
  3982. if (CompareX(c->Session->Link->ServerCert, x))
  3983. {
  3984. Unlock(c->Session->Link->lock);
  3985. // Exactly match the certificate that is registered in the cascade configuration
  3986. FreeX(x);
  3987. return true;
  3988. }
  3989. }
  3990. }
  3991. Unlock(c->Session->Link->lock);
  3992. }
  3993. else
  3994. {
  3995. if (expired != NULL)
  3996. {
  3997. *expired = true;
  3998. }
  3999. }
  4000. // Verification failure at this point in the case of cascade connection mode
  4001. FreeX(x);
  4002. return false;
  4003. }
  4004. p = ZeroMalloc(sizeof(CHECK_CERT_THREAD_PROC));
  4005. p->ServerX = x;
  4006. p->CheckCertProc = auth->CheckCertProc;
  4007. p->Connection = c;
  4008. // Create a thread
  4009. thread = NewThread(ClientCheckServerCertThread, p);
  4010. WaitThreadInit(thread);
  4011. // Poll at 0.5-second intervals until the user selects whether the connection
  4012. start = Tick64();
  4013. while (true)
  4014. {
  4015. if ((Tick64() - start) > CONNECTING_POOLING_SPAN)
  4016. {
  4017. // Send a NOOP periodically for disconnection prevention
  4018. start = Tick64();
  4019. ClientUploadNoop(c);
  4020. }
  4021. if (p->UserSelected)
  4022. {
  4023. // User-selected
  4024. break;
  4025. }
  4026. WaitThread(thread, 500);
  4027. }
  4028. if (expired != NULL)
  4029. {
  4030. *expired = p->Exipred;
  4031. }
  4032. ret = p->Ok;
  4033. FreeX(p->ServerX);
  4034. Free(p);
  4035. ReleaseThread(thread);
  4036. return ret;
  4037. }
  4038. // Client connects to the server
  4039. bool ClientConnect(CONNECTION *c)
  4040. {
  4041. bool ret = false;
  4042. bool ok = false;
  4043. UINT err;
  4044. SOCK *s;
  4045. PACK *p = NULL;
  4046. UINT session_key_32;
  4047. SESSION *sess;
  4048. char session_name[MAX_SESSION_NAME_LEN + 1];
  4049. char connection_name[MAX_CONNECTION_NAME_LEN + 1];
  4050. UCHAR session_key[SHA1_SIZE];
  4051. RC4_KEY_PAIR key_pair;
  4052. POLICY *policy;
  4053. bool expired = false;
  4054. IP server_ip;
  4055. // Validate arguments
  4056. if (c == NULL)
  4057. {
  4058. return false;
  4059. }
  4060. sess = c->Session;
  4061. PrintStatus(sess, L"init");
  4062. PrintStatus(sess, _UU("STATUS_1"));
  4063. REDIRECTED:
  4064. // [Connecting]
  4065. c->Status = CONNECTION_STATUS_CONNECTING;
  4066. c->Session->ClientStatus = CLIENT_STATUS_CONNECTING;
  4067. s = ClientConnectToServer(c);
  4068. if (s == NULL)
  4069. {
  4070. PrintStatus(sess, L"free");
  4071. return false;
  4072. }
  4073. Copy(&server_ip, &s->RemoteIP, sizeof(IP));
  4074. if (c->Halt)
  4075. {
  4076. // Stop
  4077. c->Err = ERR_USER_CANCEL;
  4078. goto CLEANUP;
  4079. }
  4080. // [Negotiating]
  4081. c->Session->ClientStatus = CLIENT_STATUS_NEGOTIATION;
  4082. // Initialize the UDP acceleration function
  4083. if (sess->ClientOption != NULL && sess->ClientOption->NoUdpAcceleration == false)
  4084. {
  4085. if (sess->ClientOption->ProxyType == PROXY_DIRECT)
  4086. {
  4087. if (s->Type == SOCK_TCP)
  4088. {
  4089. if (sess->UdpAccel == NULL)
  4090. {
  4091. bool no_nat_t = false;
  4092. if (sess->ClientOption->PortUDP != 0)
  4093. {
  4094. // There is no need for NAT-T treatment on my part if the UDP port on the other end is known beforehand
  4095. no_nat_t = true;
  4096. }
  4097. sess->UdpAccel = NewUdpAccel(c->Cedar, &s->LocalIP, true, true, no_nat_t);
  4098. }
  4099. }
  4100. }
  4101. }
  4102. // Send a signature
  4103. Debug("Uploading Signature...\n");
  4104. if (ClientUploadSignature(s) == false)
  4105. {
  4106. c->Err = ERR_DISCONNECTED;
  4107. goto CLEANUP;
  4108. }
  4109. if (c->Halt)
  4110. {
  4111. // Stop
  4112. c->Err = ERR_USER_CANCEL;
  4113. goto CLEANUP;
  4114. }
  4115. PrintStatus(sess, _UU("STATUS_5"));
  4116. // Receive a Hello packet
  4117. Debug("Downloading Hello...\n");
  4118. if (ClientDownloadHello(c, s) == false)
  4119. {
  4120. goto CLEANUP;
  4121. }
  4122. if (c->Session->ClientOption != NULL && c->Session->ClientOption->FromAdminPack)
  4123. {
  4124. if (IsAdminPackSupportedServerProduct(c->ServerStr) == false)
  4125. {
  4126. c->Err = ERR_NOT_ADMINPACK_SERVER;
  4127. goto CLEANUP;
  4128. }
  4129. }
  4130. if (c->Halt)
  4131. {
  4132. // Stop
  4133. c->Err = ERR_USER_CANCEL;
  4134. goto CLEANUP;
  4135. }
  4136. Debug("Server Version : %u\n"
  4137. "Server String : %s\n"
  4138. "Server Build : %u\n"
  4139. "Client Version : %u\n"
  4140. "Client String : %s\n"
  4141. "Client Build : %u\n",
  4142. c->ServerVer, c->ServerStr, c->ServerBuild,
  4143. c->ClientVer, c->ClientStr, c->ClientBuild);
  4144. // During user authentication
  4145. c->Session->ClientStatus = CLIENT_STATUS_AUTH;
  4146. // Verify the server certificate by the client
  4147. if (ClientCheckServerCert(c, &expired) == false)
  4148. {
  4149. if (expired == false)
  4150. {
  4151. c->Err = ERR_CERT_NOT_TRUSTED;
  4152. }
  4153. else
  4154. {
  4155. c->Err = ERR_SERVER_CERT_EXPIRES;
  4156. }
  4157. if (c->Session->LinkModeClient == false && c->Err == ERR_CERT_NOT_TRUSTED)
  4158. {
  4159. c->Session->ForceStopFlag = true;
  4160. }
  4161. goto CLEANUP;
  4162. }
  4163. PrintStatus(sess, _UU("STATUS_6"));
  4164. // Send the authentication data
  4165. if (ClientUploadAuth(c) == false)
  4166. {
  4167. goto CLEANUP;
  4168. }
  4169. if (c->Halt)
  4170. {
  4171. // Stop
  4172. c->Err = ERR_USER_CANCEL;
  4173. goto CLEANUP;
  4174. }
  4175. // Receive a Welcome packet
  4176. p = HttpClientRecv(s);
  4177. if (p == NULL)
  4178. {
  4179. c->Err = ERR_DISCONNECTED;
  4180. goto CLEANUP;
  4181. }
  4182. // Error checking
  4183. err = GetErrorFromPack(p);
  4184. if (err != 0)
  4185. {
  4186. // An error has occured
  4187. c->Err = err;
  4188. c->ClientConnectError_NoSavePassword = PackGetBool(p, "no_save_password");
  4189. goto CLEANUP;
  4190. }
  4191. // Branding string check for the connection limit
  4192. {
  4193. char tmp[20];
  4194. char *branded_cfroms = _SS("BRANDED_C_FROM_S");
  4195. PackGetStr(p, "branded_cfroms", tmp, sizeof(tmp));
  4196. if(StrLen(branded_cfroms) > 0 && StrCmpi(branded_cfroms, tmp) != 0)
  4197. {
  4198. c->Err = ERR_BRANDED_C_FROM_S;
  4199. goto CLEANUP;
  4200. }
  4201. }
  4202. if (c->Cedar->Server == NULL)
  4203. {
  4204. // Suppress client notification flag
  4205. if (PackIsValueExists(p, "suppress_client_update_notification"))
  4206. {
  4207. bool suppress_client_update_notification = PackGetBool(p, "suppress_client_update_notification");
  4208. #ifdef OS_WIN32
  4209. MsRegWriteIntEx2(REG_LOCAL_MACHINE, PROTO_SUPPRESS_CLIENT_UPDATE_NOTIFICATION_REGKEY, PROTO_SUPPRESS_CLIENT_UPDATE_NOTIFICATION_REGVALUE,
  4210. (suppress_client_update_notification ? 1 : 0), false, true);
  4211. #endif // OS_WIN32
  4212. }
  4213. }
  4214. if (true)
  4215. {
  4216. // Message retrieval
  4217. UINT utf_size;
  4218. char *utf;
  4219. wchar_t *msg;
  4220. utf_size = PackGetDataSize(p, "Msg");
  4221. utf = ZeroMalloc(utf_size + 8);
  4222. PackGetData(p, "Msg", utf);
  4223. msg = CopyUtfToUni(utf);
  4224. if (IsEmptyUniStr(msg) == false)
  4225. {
  4226. if (c->Session->Client_Message != NULL)
  4227. {
  4228. Free(c->Session->Client_Message);
  4229. }
  4230. c->Session->Client_Message = msg;
  4231. }
  4232. else
  4233. {
  4234. Free(msg);
  4235. }
  4236. Free(utf);
  4237. }
  4238. if (PackGetInt(p, "Redirect") != 0)
  4239. {
  4240. UINT i;
  4241. UINT ip;
  4242. UINT num_port;
  4243. UINT *ports;
  4244. UINT use_port = 0;
  4245. UINT current_port = c->ServerPort;
  4246. UCHAR ticket[SHA1_SIZE];
  4247. X *server_cert;
  4248. BUF *b;
  4249. // Redirect mode
  4250. PrintStatus(sess, _UU("STATUS_8"));
  4251. ip = PackGetIp32(p, "Ip");
  4252. num_port = MAX(MIN(PackGetIndexCount(p, "Port"), MAX_PUBLIC_PORT_NUM), 1);
  4253. ports = ZeroMalloc(sizeof(UINT) * num_port);
  4254. for (i = 0;i < num_port;i++)
  4255. {
  4256. ports[i] = PackGetIntEx(p, "Port", i);
  4257. }
  4258. // Select a port number
  4259. for (i = 0;i < num_port;i++)
  4260. {
  4261. if (ports[i] == current_port)
  4262. {
  4263. use_port = current_port;
  4264. }
  4265. }
  4266. if (use_port == 0)
  4267. {
  4268. use_port = ports[0];
  4269. }
  4270. Free(ports);
  4271. if (PackGetDataSize(p, "Ticket") == SHA1_SIZE)
  4272. {
  4273. PackGetData(p, "Ticket", ticket);
  4274. }
  4275. b = PackGetBuf(p, "Cert");
  4276. if (b != NULL)
  4277. {
  4278. server_cert = BufToX(b, false);
  4279. FreeBuf(b);
  4280. }
  4281. if (c->ServerX != NULL)
  4282. {
  4283. FreeX(c->ServerX);
  4284. }
  4285. c->ServerX = server_cert;
  4286. IPToStr32(c->ServerName, sizeof(c->ServerName), ip);
  4287. c->ServerPort = use_port;
  4288. c->UseTicket = true;
  4289. Copy(c->Ticket, ticket, SHA1_SIZE);
  4290. FreePack(p);
  4291. p = NewPack();
  4292. HttpClientSend(s, p);
  4293. FreePack(p);
  4294. p = NULL;
  4295. c->FirstSock = NULL;
  4296. Disconnect(s);
  4297. ReleaseSock(s);
  4298. s = NULL;
  4299. goto REDIRECTED;
  4300. }
  4301. PrintStatus(sess, _UU("STATUS_7"));
  4302. // Parse the Welcome packet
  4303. if (ParseWelcomeFromPack(p, session_name, sizeof(session_name),
  4304. connection_name, sizeof(connection_name), &policy) == false)
  4305. {
  4306. // Parsing failure
  4307. c->Err = ERR_PROTOCOL_ERROR;
  4308. goto CLEANUP;
  4309. }
  4310. // Get the session key
  4311. if (GetSessionKeyFromPack(p, session_key, &session_key_32) == false)
  4312. {
  4313. // Acquisition failure
  4314. Free(policy);
  4315. policy = NULL;
  4316. c->Err = ERR_PROTOCOL_ERROR;
  4317. goto CLEANUP;
  4318. }
  4319. Copy(c->Session->SessionKey, session_key, SHA1_SIZE);
  4320. c->Session->SessionKey32 = session_key_32;
  4321. // Save the contents of the Welcome packet
  4322. Debug("session_name: %s, connection_name: %s\n",
  4323. session_name, connection_name);
  4324. Lock(c->Session->lock);
  4325. {
  4326. // Deploy and update connection parameters
  4327. sess->EnableUdpRecovery = PackGetBool(p, "enable_udp_recovery");
  4328. c->Session->MaxConnection = PackGetInt(p, "max_connection");
  4329. if (sess->EnableUdpRecovery == false)
  4330. {
  4331. c->Session->MaxConnection = MIN(c->Session->MaxConnection, c->Session->ClientOption->MaxConnection);
  4332. }
  4333. c->Session->MaxConnection = MIN(c->Session->MaxConnection, MAX_TCP_CONNECTION);
  4334. c->Session->MaxConnection = MAX(c->Session->MaxConnection, 1);
  4335. c->Session->UseCompress = PackGetInt(p, "use_compress") == 0 ? false : true;
  4336. c->Session->UseEncrypt = PackGetInt(p, "use_encrypt") == 0 ? false : true;
  4337. c->Session->NoSendSignature = PackGetBool(p, "no_send_signature");
  4338. if (c->Session->UseEncrypt)
  4339. {
  4340. c->Session->UseFastRC4 = PackGetInt(p, "use_fast_rc4") == 0 ? false : true;
  4341. }
  4342. c->Session->HalfConnection = PackGetInt(p, "half_connection") == 0 ? false : true;
  4343. c->Session->IsAzureSession = PackGetInt(p, "is_azure_session") == 0 ? false : true;
  4344. c->Session->Timeout = PackGetInt(p, "timeout");
  4345. c->Session->QoS = PackGetInt(p, "qos") == 0 ? false : true;
  4346. if (c->Session->QoS)
  4347. {
  4348. c->Session->MaxConnection = MAX(c->Session->MaxConnection, (UINT)(c->Session->HalfConnection ? 4 : 2));
  4349. }
  4350. c->Session->VLanId = PackGetInt(p, "vlan_id");
  4351. // R-UDP Session ?
  4352. c->Session->IsRUDPSession = s->IsRUDPSocket;
  4353. ZeroIP4(&c->Session->AzureRealServerGlobalIp);
  4354. if (c->Session->IsAzureSession)
  4355. {
  4356. // Disable the life parameter of the connection in the case of VPN Azure relayed session
  4357. c->Session->ClientOption->ConnectionDisconnectSpan = 0;
  4358. // Get the AzureRealServerGlobalIp the case of VPN Azure relayed
  4359. PackGetIp(p, "azure_real_server_global_ip", &c->Session->AzureRealServerGlobalIp);
  4360. }
  4361. if (c->Session->IsRUDPSession)
  4362. {
  4363. // Disable the life parameter of the connection in the case of R-UDP session
  4364. c->Session->ClientOption->ConnectionDisconnectSpan = 0;
  4365. // Disable QoS, etc. in the case of R-UDP session
  4366. c->Session->QoS = false;
  4367. c->Session->HalfConnection = false;
  4368. if (c->Session->EnableUdpRecovery == false)
  4369. {
  4370. // Set the number of connection to 1 if UDP recovery is not supported
  4371. c->Session->MaxConnection = 1;
  4372. }
  4373. }
  4374. // Physical communication protocol
  4375. StrCpy(c->Session->UnderlayProtocol, sizeof(c->Session->UnderlayProtocol), s->UnderlayProtocol);
  4376. if (c->Session->IsAzureSession)
  4377. {
  4378. StrCpy(c->Session->UnderlayProtocol, sizeof(c->Session->UnderlayProtocol), SOCK_UNDERLAY_AZURE);
  4379. }
  4380. if (c->Protocol == CONNECTION_UDP)
  4381. {
  4382. // In the case of UDP protocol, receive the key from the server
  4383. if (PackGetDataSize(p, "udp_send_key") == sizeof(c->Session->UdpSendKey))
  4384. {
  4385. PackGetData(p, "udp_send_key", c->Session->UdpSendKey);
  4386. }
  4387. if (PackGetDataSize(p, "udp_recv_key") == sizeof(c->Session->UdpRecvKey))
  4388. {
  4389. PackGetData(p, "udp_recv_key", c->Session->UdpRecvKey);
  4390. }
  4391. }
  4392. if (c->Session->UseFastRC4)
  4393. {
  4394. // Get the RC4 key information
  4395. if (PackGetDataSize(p, "rc4_key_client_to_server") == 16)
  4396. {
  4397. PackGetData(p, "rc4_key_client_to_server", key_pair.ClientToServerKey);
  4398. }
  4399. if (PackGetDataSize(p, "rc4_key_server_to_client") == 16)
  4400. {
  4401. PackGetData(p, "rc4_key_server_to_client", key_pair.ServerToClientKey);
  4402. }
  4403. {
  4404. char key1[64], key2[64];
  4405. BinToStr(key1, sizeof(key1), key_pair.ClientToServerKey, 16);
  4406. BinToStr(key2, sizeof(key2), key_pair.ServerToClientKey, 16);
  4407. Debug(
  4408. "Client to Server Key: %s\n"
  4409. "Server to Client Key: %s\n",
  4410. key1, key2);
  4411. }
  4412. }
  4413. sess->EnableBulkOnRUDP = false;
  4414. sess->EnableHMacOnBulkOfRUDP = false;
  4415. if (s != NULL && s->IsRUDPSocket && s->BulkRecvKey != NULL && s->BulkSendKey != NULL)
  4416. {
  4417. // Bulk transfer on R-UDP
  4418. if (PackGetBool(p, "enable_bulk_on_rudp"))
  4419. {
  4420. // Receive the key
  4421. UCHAR key_send[SHA1_SIZE];
  4422. UCHAR key_recv[SHA1_SIZE];
  4423. if (PackGetData2(p, "bulk_on_rudp_send_key", key_send, SHA1_SIZE) &&
  4424. PackGetData2(p, "bulk_on_rudp_recv_key", key_recv, SHA1_SIZE))
  4425. {
  4426. sess->EnableBulkOnRUDP = true;
  4427. Copy(s->BulkSendKey->Data, key_send, SHA1_SIZE);
  4428. Copy(s->BulkRecvKey->Data, key_recv, SHA1_SIZE);
  4429. }
  4430. }
  4431. sess->EnableHMacOnBulkOfRUDP = PackGetBool(p, "enable_hmac_on_bulk_of_rudp");
  4432. }
  4433. Debug("EnableBulkOnRUDP = %u\n", sess->EnableBulkOnRUDP);
  4434. Debug("EnableHMacOnBulkOfRUDP = %u\n", sess->EnableHMacOnBulkOfRUDP);
  4435. Debug("EnableUdpRecovery = %u\n", sess->EnableUdpRecovery);
  4436. sess->UseUdpAcceleration = false;
  4437. sess->IsUsingUdpAcceleration = false;
  4438. sess->UseHMacOnUdpAcceleration = false;
  4439. if (sess->UdpAccel != NULL)
  4440. {
  4441. sess->UdpAccel->UseHMac = false;
  4442. sess->UdpAccelFastDisconnectDetect = false;
  4443. if (PackGetBool(p, "use_udp_acceleration"))
  4444. {
  4445. IP udp_acceleration_server_ip;
  4446. sess->UdpAccelFastDisconnectDetect = PackGetBool(p, "udp_accel_fast_disconnect_detect");
  4447. if (PackGetIp(p, "udp_acceleration_server_ip", &udp_acceleration_server_ip))
  4448. {
  4449. UINT udp_acceleration_server_port = PackGetInt(p, "udp_acceleration_server_port");
  4450. if (IsZeroIp(&udp_acceleration_server_ip))
  4451. {
  4452. Copy(&udp_acceleration_server_ip, &s->RemoteIP, sizeof(IP));
  4453. }
  4454. if (udp_acceleration_server_port != 0)
  4455. {
  4456. UCHAR udp_acceleration_server_key[UDP_ACCELERATION_COMMON_KEY_SIZE];
  4457. if (PackGetData2(p, "udp_acceleration_server_key", udp_acceleration_server_key, UDP_ACCELERATION_COMMON_KEY_SIZE))
  4458. {
  4459. UINT server_cookie = PackGetInt(p, "udp_acceleration_server_cookie");
  4460. UINT client_cookie = PackGetInt(p, "udp_acceleration_client_cookie");
  4461. bool encryption = PackGetBool(p, "udp_acceleration_use_encryption");
  4462. if (server_cookie != 0 && client_cookie != 0)
  4463. {
  4464. IP remote_ip;
  4465. Copy(&remote_ip, &s->RemoteIP, sizeof(IP));
  4466. if (IsZeroIp(&c->Session->AzureRealServerGlobalIp) == false)
  4467. {
  4468. Copy(&remote_ip, &c->Session->AzureRealServerGlobalIp, sizeof(IP));
  4469. }
  4470. if (UdpAccelInitClient(sess->UdpAccel, udp_acceleration_server_key,
  4471. &udp_acceleration_server_ip, udp_acceleration_server_port,
  4472. server_cookie, client_cookie, &remote_ip) == false)
  4473. {
  4474. Debug("UdpAccelInitClient failed.\n");
  4475. }
  4476. else
  4477. {
  4478. sess->UseUdpAcceleration = true;
  4479. sess->UdpAccel->FastDetect = sess->UdpAccelFastDisconnectDetect;
  4480. sess->UdpAccel->PlainTextMode = !encryption;
  4481. sess->UseHMacOnUdpAcceleration = PackGetBool(p, "use_hmac_on_udp_acceleration");
  4482. if (sess->UseHMacOnUdpAcceleration)
  4483. {
  4484. sess->UdpAccel->UseHMac = true;
  4485. }
  4486. }
  4487. }
  4488. }
  4489. }
  4490. }
  4491. }
  4492. }
  4493. }
  4494. Unlock(c->Session->lock);
  4495. Debug("UseUdpAcceleration = %u\n", sess->UseUdpAcceleration);
  4496. if (sess->UseUdpAcceleration == false)
  4497. {
  4498. if (sess->UdpAccel != NULL)
  4499. {
  4500. FreeUdpAccel(sess->UdpAccel);
  4501. sess->UdpAccel = NULL;
  4502. }
  4503. }
  4504. Lock(c->lock);
  4505. {
  4506. if (c->Name != NULL)
  4507. {
  4508. Free(c->Name);
  4509. }
  4510. c->Name = CopyStr(connection_name);
  4511. // Save the name of a cryptographic algorithm
  4512. if (c->CipherName != NULL)
  4513. {
  4514. Free(c->CipherName);
  4515. }
  4516. c->CipherName = CopyStr(c->FirstSock->CipherName);
  4517. }
  4518. Unlock(c->lock);
  4519. Lock(c->Session->lock);
  4520. {
  4521. if (c->Session->Name != NULL)
  4522. {
  4523. Free(c->Session->Name);
  4524. }
  4525. c->Session->Name = CopyStr(session_name);
  4526. c->Session->Policy = policy;
  4527. }
  4528. Unlock(c->Session->lock);
  4529. // Discard the Welcome packet
  4530. FreePack(p);
  4531. p = NULL;
  4532. // Connection establishment
  4533. c->Session->ClientStatus = CLIENT_STATUS_ESTABLISHED;
  4534. // Save the server certificate
  4535. if (c->ServerX == NULL)
  4536. {
  4537. c->ServerX = CloneX(c->FirstSock->RemoteX);
  4538. }
  4539. PrintStatus(sess, _UU("STATUS_9"));
  4540. // Shift the connection to the tunneling mode
  4541. StartTunnelingMode(c);
  4542. s = NULL;
  4543. if (c->Session->HalfConnection)
  4544. {
  4545. // Processing in the case of half-connection
  4546. TCPSOCK *ts = (TCPSOCK *)LIST_DATA(c->Tcp->TcpSockList, 0);
  4547. ts->Direction = TCP_CLIENT_TO_SERVER;
  4548. }
  4549. if (c->Session->UseFastRC4)
  4550. {
  4551. // Set the high-speed RC4 encryption key
  4552. TCPSOCK *ts = (TCPSOCK *)LIST_DATA(c->Tcp->TcpSockList, 0);
  4553. Copy(&ts->Rc4KeyPair, &key_pair, sizeof(key_pair));
  4554. InitTcpSockRc4Key(ts, false);
  4555. }
  4556. // SSL encryption flag
  4557. if (c->Session->UseEncrypt && c->Session->UseFastRC4 == false)
  4558. {
  4559. c->Session->UseSSLDataEncryption = true;
  4560. }
  4561. else
  4562. {
  4563. c->Session->UseSSLDataEncryption = false;
  4564. }
  4565. PrintStatus(sess, L"free");
  4566. CLog(c->Cedar->Client, "LC_CONNECT_2", c->Session->ClientOption->AccountName,
  4567. session_name);
  4568. if (c->Session->LinkModeClient && c->Session->Link != NULL)
  4569. {
  4570. HLog(c->Session->Link->Hub, "LH_CONNECT_2", c->Session->ClientOption->AccountName, session_name);
  4571. }
  4572. // Main routine of the session
  4573. SessionMain(c->Session);
  4574. ok = true;
  4575. if (c->Err == ERR_USER_CANCEL)
  4576. {
  4577. ret = true;
  4578. }
  4579. CLEANUP:
  4580. c->FirstSock = NULL;
  4581. if (sess->UdpAccel != NULL)
  4582. {
  4583. FreeUdpAccel(sess->UdpAccel);
  4584. sess->UdpAccel = NULL;
  4585. }
  4586. if (p != NULL)
  4587. {
  4588. FreePack(p);
  4589. }
  4590. Disconnect(s);
  4591. ReleaseSock(s);
  4592. Debug("Error: %u\n", c->Err);
  4593. if (ok == false)
  4594. {
  4595. PrintStatus(sess, L"free");
  4596. }
  4597. return ret;
  4598. }
  4599. // Parse the Welcome packet
  4600. bool ParseWelcomeFromPack(PACK *p, char *session_name, UINT session_name_size,
  4601. char *connection_name, UINT connection_name_size,
  4602. POLICY **policy)
  4603. {
  4604. // Validate arguments
  4605. if (p == NULL || session_name == NULL || connection_name == NULL || policy == NULL)
  4606. {
  4607. return false;
  4608. }
  4609. // Session name
  4610. if (PackGetStr(p, "session_name", session_name, session_name_size) == false)
  4611. {
  4612. return false;
  4613. }
  4614. // Connection name
  4615. if (PackGetStr(p, "connection_name", connection_name, connection_name_size) == false)
  4616. {
  4617. return false;
  4618. }
  4619. // Policy
  4620. *policy = PackGetPolicy(p);
  4621. if (*policy == NULL)
  4622. {
  4623. return false;
  4624. }
  4625. return true;
  4626. }
  4627. // Generate the Welcome packet
  4628. PACK *PackWelcome(SESSION *s)
  4629. {
  4630. PACK *p;
  4631. // Validate arguments
  4632. if (s == NULL)
  4633. {
  4634. return NULL;
  4635. }
  4636. p = NewPack();
  4637. // Session name
  4638. PackAddStr(p, "session_name", s->Name);
  4639. // Connection name
  4640. PackAddStr(p, "connection_name", s->Connection->Name);
  4641. // Parameters
  4642. PackAddInt(p, "max_connection", s->MaxConnection);
  4643. PackAddInt(p, "use_encrypt", s->UseEncrypt == false ? 0 : 1);
  4644. PackAddInt(p, "use_fast_rc4", s->UseFastRC4 == false ? 0 : 1);
  4645. PackAddInt(p, "use_compress", s->UseCompress == false ? 0 : 1);
  4646. PackAddInt(p, "half_connection", s->HalfConnection == false ? 0 : 1);
  4647. PackAddInt(p, "timeout", s->Timeout);
  4648. PackAddInt(p, "qos", s->QoS ? 1 : 0);
  4649. PackAddInt(p, "is_azure_session", s->IsAzureSession);
  4650. // Session key
  4651. PackAddData(p, "session_key", s->SessionKey, SHA1_SIZE);
  4652. PackAddInt(p, "session_key_32", s->SessionKey32);
  4653. // Policy
  4654. PackAddPolicy(p, s->Policy);
  4655. // VLAN ID
  4656. PackAddInt(p, "vlan_id", s->VLanId);
  4657. if (s->Connection->Protocol == CONNECTION_UDP)
  4658. {
  4659. // In the case of UDP protocol, generate 2 pairs of key
  4660. Rand(s->UdpSendKey, sizeof(s->UdpSendKey));
  4661. Rand(s->UdpRecvKey, sizeof(s->UdpRecvKey));
  4662. // Send to client by exchanging 2 keys
  4663. PackAddData(p, "udp_send_key", s->UdpRecvKey, sizeof(s->UdpRecvKey));
  4664. PackAddData(p, "udp_recv_key", s->UdpSendKey, sizeof(s->UdpSendKey));
  4665. }
  4666. // no_send_signature
  4667. if (s->NoSendSignature)
  4668. {
  4669. PackAddBool(p, "no_send_signature", true);
  4670. }
  4671. if (s->InProcMode)
  4672. {
  4673. // MAC address for IPC
  4674. PackAddData(p, "IpcMacAddress", s->IpcMacAddress, 6);
  4675. // Virtual HUB name
  4676. PackAddStr(p, "IpcHubName", s->Hub->Name);
  4677. }
  4678. if (s->UdpAccel != NULL)
  4679. {
  4680. // UDP acceleration function
  4681. PackAddBool(p, "use_udp_acceleration", true);
  4682. PackAddIp(p, "udp_acceleration_server_ip", &s->UdpAccel->MyIp);
  4683. PackAddInt(p, "udp_acceleration_server_port", s->UdpAccel->MyPort);
  4684. PackAddData(p, "udp_acceleration_server_key", s->UdpAccel->MyKey, UDP_ACCELERATION_COMMON_KEY_SIZE);
  4685. PackAddInt(p, "udp_acceleration_server_cookie", s->UdpAccel->MyCookie);
  4686. PackAddInt(p, "udp_acceleration_client_cookie", s->UdpAccel->YourCookie);
  4687. PackAddBool(p, "udp_acceleration_use_encryption", !s->UdpAccel->PlainTextMode);
  4688. PackAddBool(p, "use_hmac_on_udp_acceleration", s->UdpAccel->UseHMac);
  4689. PackAddBool(p, "udp_accel_fast_disconnect_detect", s->UdpAccelFastDisconnectDetect);
  4690. }
  4691. if (s->EnableBulkOnRUDP)
  4692. {
  4693. // Allow bulk transfer on R-UDP
  4694. PackAddBool(p, "enable_bulk_on_rudp", true);
  4695. PackAddBool(p, "enable_hmac_on_bulk_of_rudp", s->EnableHMacOnBulkOfRUDP);
  4696. PackAddData(p, "bulk_on_rudp_send_key", s->Connection->FirstSock->BulkRecvKey->Data, SHA1_SIZE);
  4697. PackAddData(p, "bulk_on_rudp_recv_key", s->Connection->FirstSock->BulkSendKey->Data, SHA1_SIZE);
  4698. }
  4699. if (s->IsAzureSession)
  4700. {
  4701. if (s->Connection != NULL && s->Connection->FirstSock != NULL)
  4702. {
  4703. SOCK *sock = s->Connection->FirstSock;
  4704. PackAddIp(p, "azure_real_server_global_ip", &sock->Reverse_MyServerGlobalIp);
  4705. }
  4706. }
  4707. PackAddBool(p, "enable_udp_recovery", s->EnableUdpRecovery);
  4708. return p;
  4709. }
  4710. #define PACK_ADD_POLICY_BOOL(name, value) \
  4711. PackAddInt(p, "policy:" name, y->value == false ? 0 : 1)
  4712. #define PACK_ADD_POLICY_UINT(name, value) \
  4713. PackAddInt(p, "policy:" name, y->value)
  4714. #define PACK_GET_POLICY_BOOL(name, value) \
  4715. y->value = (PackGetInt(p, "policy:" name) == 0 ? false : true)
  4716. #define PACK_GET_POLICY_UINT(name, value) \
  4717. y->value = PackGetInt(p, "policy:" name)
  4718. // Get a PACK from the session key
  4719. bool GetSessionKeyFromPack(PACK *p, UCHAR *session_key, UINT *session_key_32)
  4720. {
  4721. // Validate arguments
  4722. if (p == NULL || session_key == NULL || session_key_32 == NULL)
  4723. {
  4724. return false;
  4725. }
  4726. if (PackGetDataSize(p, "session_key") != SHA1_SIZE)
  4727. {
  4728. return false;
  4729. }
  4730. if (PackGetData(p, "session_key", session_key) == false)
  4731. {
  4732. return false;
  4733. }
  4734. *session_key_32 = PackGetInt(p, "session_key_32");
  4735. return true;
  4736. }
  4737. // Get the policy from the PACK
  4738. POLICY *PackGetPolicy(PACK *p)
  4739. {
  4740. POLICY *y;
  4741. // Validate arguments
  4742. if (p == NULL)
  4743. {
  4744. return NULL;
  4745. }
  4746. y = ZeroMalloc(sizeof(POLICY));
  4747. // Bool value
  4748. // Ver 2
  4749. PACK_GET_POLICY_BOOL("Access", Access);
  4750. PACK_GET_POLICY_BOOL("DHCPFilter", DHCPFilter);
  4751. PACK_GET_POLICY_BOOL("DHCPNoServer", DHCPNoServer);
  4752. PACK_GET_POLICY_BOOL("DHCPForce", DHCPForce);
  4753. PACK_GET_POLICY_BOOL("NoBridge", NoBridge);
  4754. PACK_GET_POLICY_BOOL("NoRouting", NoRouting);
  4755. PACK_GET_POLICY_BOOL("PrivacyFilter", PrivacyFilter);
  4756. PACK_GET_POLICY_BOOL("NoServer", NoServer);
  4757. PACK_GET_POLICY_BOOL("CheckMac", CheckMac);
  4758. PACK_GET_POLICY_BOOL("CheckIP", CheckIP);
  4759. PACK_GET_POLICY_BOOL("ArpDhcpOnly", ArpDhcpOnly);
  4760. PACK_GET_POLICY_BOOL("MonitorPort", MonitorPort);
  4761. PACK_GET_POLICY_BOOL("NoBroadcastLimiter", NoBroadcastLimiter);
  4762. PACK_GET_POLICY_BOOL("FixPassword", FixPassword);
  4763. PACK_GET_POLICY_BOOL("NoQoS", NoQoS);
  4764. // Ver 3
  4765. PACK_GET_POLICY_BOOL("RSandRAFilter", RSandRAFilter);
  4766. PACK_GET_POLICY_BOOL("RAFilter", RAFilter);
  4767. PACK_GET_POLICY_BOOL("DHCPv6Filter", DHCPv6Filter);
  4768. PACK_GET_POLICY_BOOL("DHCPv6NoServer", DHCPv6NoServer);
  4769. PACK_GET_POLICY_BOOL("NoRoutingV6", NoRoutingV6);
  4770. PACK_GET_POLICY_BOOL("CheckIPv6", CheckIPv6);
  4771. PACK_GET_POLICY_BOOL("NoServerV6", NoServerV6);
  4772. PACK_GET_POLICY_BOOL("NoSavePassword", NoSavePassword);
  4773. PACK_GET_POLICY_BOOL("FilterIPv4", FilterIPv4);
  4774. PACK_GET_POLICY_BOOL("FilterIPv6", FilterIPv6);
  4775. PACK_GET_POLICY_BOOL("FilterNonIP", FilterNonIP);
  4776. PACK_GET_POLICY_BOOL("NoIPv6DefaultRouterInRA", NoIPv6DefaultRouterInRA);
  4777. PACK_GET_POLICY_BOOL("NoIPv6DefaultRouterInRAWhenIPv6", NoIPv6DefaultRouterInRAWhenIPv6);
  4778. // UINT value
  4779. // Ver 2
  4780. PACK_GET_POLICY_UINT("MaxConnection", MaxConnection);
  4781. PACK_GET_POLICY_UINT("TimeOut", TimeOut);
  4782. PACK_GET_POLICY_UINT("MaxMac", MaxMac);
  4783. PACK_GET_POLICY_UINT("MaxIP", MaxIP);
  4784. PACK_GET_POLICY_UINT("MaxUpload", MaxUpload);
  4785. PACK_GET_POLICY_UINT("MaxDownload", MaxDownload);
  4786. PACK_GET_POLICY_UINT("MultiLogins", MultiLogins);
  4787. // Ver 3
  4788. PACK_GET_POLICY_UINT("MaxIPv6", MaxIPv6);
  4789. PACK_GET_POLICY_UINT("AutoDisconnect", AutoDisconnect);
  4790. PACK_GET_POLICY_UINT("VLanId", VLanId);
  4791. // Ver 3 flag
  4792. PACK_GET_POLICY_BOOL("Ver3", Ver3);
  4793. return y;
  4794. }
  4795. // Insert the policy into the PACK
  4796. void PackAddPolicy(PACK *p, POLICY *y)
  4797. {
  4798. // Validate arguments
  4799. if (p == NULL || y == NULL)
  4800. {
  4801. return;
  4802. }
  4803. // Bool value
  4804. // Ver 2
  4805. PACK_ADD_POLICY_BOOL("Access", Access);
  4806. PACK_ADD_POLICY_BOOL("DHCPFilter", DHCPFilter);
  4807. PACK_ADD_POLICY_BOOL("DHCPNoServer", DHCPNoServer);
  4808. PACK_ADD_POLICY_BOOL("DHCPForce", DHCPForce);
  4809. PACK_ADD_POLICY_BOOL("NoBridge", NoBridge);
  4810. PACK_ADD_POLICY_BOOL("NoRouting", NoRouting);
  4811. PACK_ADD_POLICY_BOOL("PrivacyFilter", PrivacyFilter);
  4812. PACK_ADD_POLICY_BOOL("NoServer", NoServer);
  4813. PACK_ADD_POLICY_BOOL("CheckMac", CheckMac);
  4814. PACK_ADD_POLICY_BOOL("CheckIP", CheckIP);
  4815. PACK_ADD_POLICY_BOOL("ArpDhcpOnly", ArpDhcpOnly);
  4816. PACK_ADD_POLICY_BOOL("MonitorPort", MonitorPort);
  4817. PACK_ADD_POLICY_BOOL("NoBroadcastLimiter", NoBroadcastLimiter);
  4818. PACK_ADD_POLICY_BOOL("FixPassword", FixPassword);
  4819. PACK_ADD_POLICY_BOOL("NoQoS", NoQoS);
  4820. // Ver 3
  4821. PACK_ADD_POLICY_BOOL("RSandRAFilter", RSandRAFilter);
  4822. PACK_ADD_POLICY_BOOL("RAFilter", RAFilter);
  4823. PACK_ADD_POLICY_BOOL("DHCPv6Filter", DHCPv6Filter);
  4824. PACK_ADD_POLICY_BOOL("DHCPv6NoServer", DHCPv6NoServer);
  4825. PACK_ADD_POLICY_BOOL("NoRoutingV6", NoRoutingV6);
  4826. PACK_ADD_POLICY_BOOL("CheckIPv6", CheckIPv6);
  4827. PACK_ADD_POLICY_BOOL("NoServerV6", NoServerV6);
  4828. PACK_ADD_POLICY_BOOL("NoSavePassword", NoSavePassword);
  4829. PACK_ADD_POLICY_BOOL("FilterIPv4", FilterIPv4);
  4830. PACK_ADD_POLICY_BOOL("FilterIPv6", FilterIPv6);
  4831. PACK_ADD_POLICY_BOOL("FilterNonIP", FilterNonIP);
  4832. PACK_ADD_POLICY_BOOL("NoIPv6DefaultRouterInRA", NoIPv6DefaultRouterInRA);
  4833. PACK_ADD_POLICY_BOOL("NoIPv6DefaultRouterInRAWhenIPv6", NoIPv6DefaultRouterInRAWhenIPv6);
  4834. // UINT value
  4835. // Ver 2
  4836. PACK_ADD_POLICY_UINT("MaxConnection", MaxConnection);
  4837. PACK_ADD_POLICY_UINT("TimeOut", TimeOut);
  4838. PACK_ADD_POLICY_UINT("MaxMac", MaxMac);
  4839. PACK_ADD_POLICY_UINT("MaxIP", MaxIP);
  4840. PACK_ADD_POLICY_UINT("MaxUpload", MaxUpload);
  4841. PACK_ADD_POLICY_UINT("MaxDownload", MaxDownload);
  4842. PACK_ADD_POLICY_UINT("MultiLogins", MultiLogins);
  4843. // Ver 3
  4844. PACK_ADD_POLICY_UINT("MaxIPv6", MaxIPv6);
  4845. PACK_ADD_POLICY_UINT("AutoDisconnect", AutoDisconnect);
  4846. PACK_ADD_POLICY_UINT("VLanId", VLanId);
  4847. // Ver 3 flag
  4848. PackAddBool(p, "policy:Ver3", true);
  4849. }
  4850. // Upload the authentication data for the additional connection
  4851. bool ClientUploadAuth2(CONNECTION *c, SOCK *s)
  4852. {
  4853. PACK *p = NULL;
  4854. // Validate arguments
  4855. if (c == NULL)
  4856. {
  4857. return false;
  4858. }
  4859. p = PackAdditionalConnect(c->Session->SessionKey);
  4860. PackAddClientVersion(p, c);
  4861. if (HttpClientSend(s, p) == false)
  4862. {
  4863. FreePack(p);
  4864. return false;
  4865. }
  4866. FreePack(p);
  4867. return true;
  4868. }
  4869. // Send a NOOP
  4870. void ClientUploadNoop(CONNECTION *c)
  4871. {
  4872. PACK *p;
  4873. // Validate arguments
  4874. if (c == NULL)
  4875. {
  4876. return;
  4877. }
  4878. p = PackError(0);
  4879. PackAddInt(p, "noop", 1);
  4880. HttpClientSend(c->FirstSock, p);
  4881. FreePack(p);
  4882. p = HttpClientRecv(c->FirstSock);
  4883. if (p != NULL)
  4884. {
  4885. FreePack(p);
  4886. }
  4887. }
  4888. // Add client version information to the PACK
  4889. void PackAddClientVersion(PACK *p, CONNECTION *c)
  4890. {
  4891. // Validate arguments
  4892. if (p == NULL || c == NULL)
  4893. {
  4894. return;
  4895. }
  4896. PackAddStr(p, "client_str", c->ClientStr);
  4897. PackAddInt(p, "client_ver", c->ClientVer);
  4898. PackAddInt(p, "client_build", c->ClientBuild);
  4899. }
  4900. // Upload the certificate data for the new connection
  4901. bool ClientUploadAuth(CONNECTION *c)
  4902. {
  4903. PACK *p = NULL;
  4904. CLIENT_AUTH *a;
  4905. CLIENT_OPTION *o;
  4906. X *x;
  4907. bool ret;
  4908. NODE_INFO info;
  4909. UCHAR secure_password[SHA1_SIZE];
  4910. UCHAR sign[4096 / 8];
  4911. UCHAR unique[SHA1_SIZE];
  4912. RPC_WINVER v;
  4913. // Validate arguments
  4914. if (c == NULL)
  4915. {
  4916. return false;
  4917. }
  4918. Zero(sign, sizeof(sign));
  4919. a = c->Session->ClientAuth;
  4920. o = c->Session->ClientOption;
  4921. if (c->UseTicket == false)
  4922. {
  4923. switch (a->AuthType)
  4924. {
  4925. case CLIENT_AUTHTYPE_ANONYMOUS:
  4926. // Anonymous authentication
  4927. p = PackLoginWithAnonymous(o->HubName, a->Username);
  4928. break;
  4929. case CLIENT_AUTHTYPE_PASSWORD:
  4930. // Password authentication
  4931. SecurePassword(secure_password, a->HashedPassword, c->Random);
  4932. p = PackLoginWithPassword(o->HubName, a->Username, secure_password);
  4933. break;
  4934. case CLIENT_AUTHTYPE_PLAIN_PASSWORD:
  4935. // Plaintext password authentication
  4936. p = PackLoginWithPlainPassword(o->HubName, a->Username, a->PlainPassword);
  4937. break;
  4938. case CLIENT_AUTHTYPE_CERT:
  4939. // Certificate authentication
  4940. if (a->ClientX != NULL && a->ClientX->is_compatible_bit &&
  4941. a->ClientX->bits != 0 && (a->ClientX->bits / 8) <= sizeof(sign))
  4942. {
  4943. if (RsaSignEx(sign, c->Random, SHA1_SIZE, a->ClientK, a->ClientX->bits))
  4944. {
  4945. p = PackLoginWithCert(o->HubName, a->Username, a->ClientX, sign, a->ClientX->bits / 8);
  4946. c->ClientX = CloneX(a->ClientX);
  4947. }
  4948. }
  4949. break;
  4950. case CLIENT_AUTHTYPE_SECURE:
  4951. // Authentication by secure device
  4952. if (ClientSecureSign(c, sign, c->Random, &x))
  4953. {
  4954. p = PackLoginWithCert(o->HubName, a->Username, x, sign, 128);
  4955. c->ClientX = CloneX(x);
  4956. FreeX(x);
  4957. }
  4958. else
  4959. {
  4960. c->Err = ERR_SECURE_DEVICE_OPEN_FAILED;
  4961. c->Session->ForceStopFlag = true;
  4962. }
  4963. break;
  4964. }
  4965. }
  4966. else
  4967. {
  4968. // Ticket
  4969. p = NewPack();
  4970. PackAddStr(p, "method", "login");
  4971. PackAddStr(p, "hubname", o->HubName);
  4972. PackAddStr(p, "username", a->Username);
  4973. PackAddInt(p, "authtype", AUTHTYPE_TICKET);
  4974. PackAddData(p, "ticket", c->Ticket, SHA1_SIZE);
  4975. }
  4976. // Current time
  4977. PackAddInt64(p, "timestamp", SystemTime64());
  4978. if (p == NULL)
  4979. {
  4980. // Error
  4981. if (c->Err != ERR_SECURE_DEVICE_OPEN_FAILED)
  4982. {
  4983. c->Err = ERR_PROTOCOL_ERROR;
  4984. }
  4985. return false;
  4986. }
  4987. PackAddClientVersion(p, c);
  4988. // Protocol
  4989. PackAddInt(p, "protocol", c->Protocol);
  4990. // Version, etc.
  4991. PackAddStr(p, "hello", c->ClientStr);
  4992. PackAddInt(p, "version", c->ClientVer);
  4993. PackAddInt(p, "build", c->ClientBuild);
  4994. PackAddInt(p, "client_id", c->Cedar->ClientId);
  4995. // The maximum number of connections
  4996. PackAddInt(p, "max_connection", o->MaxConnection);
  4997. // Flag to use of cryptography
  4998. PackAddInt(p, "use_encrypt", o->UseEncrypt == false ? 0 : 1);
  4999. // Fast encryption using flag
  5000. // PackAddInt(p, "use_fast_rc4", o->UseFastRC4 == false ? 0 : 1);
  5001. // Data compression flag
  5002. PackAddInt(p, "use_compress", o->UseCompress == false ? 0 : 1);
  5003. // Half connection flag
  5004. PackAddInt(p, "half_connection", o->HalfConnection == false ? 0 : 1);
  5005. // Bridge / routing mode flag
  5006. PackAddBool(p, "require_bridge_routing_mode", o->RequireBridgeRoutingMode);
  5007. // Monitor mode flag
  5008. PackAddBool(p, "require_monitor_mode", o->RequireMonitorMode);
  5009. // VoIP / QoS flag
  5010. PackAddBool(p, "qos", o->DisableQoS ? false : true);
  5011. // Bulk transfer support
  5012. PackAddBool(p, "support_bulk_on_rudp", true);
  5013. PackAddBool(p, "support_hmac_on_bulk_of_rudp", true);
  5014. // UDP recovery support
  5015. PackAddBool(p, "support_udp_recovery", true);
  5016. // Unique ID
  5017. GenerateMachineUniqueHash(unique);
  5018. PackAddData(p, "unique_id", unique, SHA1_SIZE);
  5019. // UDP acceleration function using flag
  5020. if (o->NoUdpAcceleration == false && c->Session->UdpAccel != NULL)
  5021. {
  5022. IP my_ip;
  5023. Zero(&my_ip, sizeof(my_ip));
  5024. PackAddBool(p, "use_udp_acceleration", true);
  5025. Copy(&my_ip, &c->Session->UdpAccel->MyIp, sizeof(IP));
  5026. if (IsLocalHostIP(&my_ip))
  5027. {
  5028. if (IsIP4(&my_ip))
  5029. {
  5030. ZeroIP4(&my_ip);
  5031. }
  5032. else
  5033. {
  5034. ZeroIP6(&my_ip);
  5035. }
  5036. }
  5037. PackAddIp(p, "udp_acceleration_client_ip", &my_ip);
  5038. PackAddInt(p, "udp_acceleration_client_port", c->Session->UdpAccel->MyPort);
  5039. PackAddData(p, "udp_acceleration_client_key", c->Session->UdpAccel->MyKey, UDP_ACCELERATION_COMMON_KEY_SIZE);
  5040. PackAddBool(p, "support_hmac_on_udp_acceleration", true);
  5041. PackAddBool(p, "support_udp_accel_fast_disconnect_detect", true);
  5042. }
  5043. // Brand string for the connection limit
  5044. {
  5045. char *branded_ctos = _SS("BRANDED_C_TO_S");
  5046. if(StrLen(branded_ctos) > 0)
  5047. {
  5048. PackAddStr(p, "branded_ctos", branded_ctos);
  5049. }
  5050. }
  5051. // Node information
  5052. CreateNodeInfo(&info, c);
  5053. OutRpcNodeInfo(p, &info);
  5054. // OS information
  5055. GetWinVer(&v);
  5056. OutRpcWinVer(p, &v);
  5057. ret = HttpClientSend(c->FirstSock, p);
  5058. if (ret == false)
  5059. {
  5060. c->Err = ERR_DISCONNECTED;
  5061. }
  5062. FreePack(p);
  5063. return ret;
  5064. }
  5065. // Upload the Hello packet
  5066. bool ServerUploadHello(CONNECTION *c)
  5067. {
  5068. PACK *p;
  5069. // Validate arguments
  5070. if (c == NULL)
  5071. {
  5072. return false;
  5073. }
  5074. // Random number generation
  5075. Rand(c->Random, SHA1_SIZE);
  5076. p = PackHello(c->Random, c->ServerVer, c->ServerBuild, c->ServerStr);
  5077. if (HttpServerSend(c->FirstSock, p) == false)
  5078. {
  5079. FreePack(p);
  5080. c->Err = ERR_DISCONNECTED;
  5081. return false;
  5082. }
  5083. FreePack(p);
  5084. return true;
  5085. }
  5086. // Download the Hello packet
  5087. bool ClientDownloadHello(CONNECTION *c, SOCK *s)
  5088. {
  5089. PACK *p;
  5090. UINT err;
  5091. UCHAR random[SHA1_SIZE];
  5092. // Validate arguments
  5093. if (c == NULL)
  5094. {
  5095. return false;
  5096. }
  5097. // Data reception
  5098. p = HttpClientRecv(s);
  5099. if (p == NULL)
  5100. {
  5101. c->Err = ERR_SERVER_IS_NOT_VPN;
  5102. return false;
  5103. }
  5104. if (err = GetErrorFromPack(p))
  5105. {
  5106. // An error has occured
  5107. c->Err = err;
  5108. FreePack(p);
  5109. return false;
  5110. }
  5111. // Packet interpretation
  5112. if (GetHello(p, random, &c->ServerVer, &c->ServerBuild, c->ServerStr, sizeof(c->ServerStr)) == false)
  5113. {
  5114. c->Err = ERR_SERVER_IS_NOT_VPN;
  5115. FreePack(p);
  5116. return false;
  5117. }
  5118. if (c->FirstSock == s)
  5119. {
  5120. Copy(c->Random, random, SHA1_SIZE);
  5121. }
  5122. FreePack(p);
  5123. return true;
  5124. }
  5125. // Download the signature
  5126. bool ServerDownloadSignature(CONNECTION *c, char **error_detail_str)
  5127. {
  5128. HTTP_HEADER *h;
  5129. UCHAR *data;
  5130. UINT data_size;
  5131. SOCK *s;
  5132. UINT num = 0, max = 19;
  5133. SERVER *server;
  5134. char hostname[64];
  5135. char *vpn_http_target = HTTP_VPN_TARGET2;
  5136. bool check_hostname = true;
  5137. // Validate arguments
  5138. if (c == NULL)
  5139. {
  5140. return false;
  5141. }
  5142. strcpy(hostname, "");
  5143. server = c->Cedar->Server;
  5144. s = c->FirstSock;
  5145. while (true)
  5146. {
  5147. bool not_found_error = false;
  5148. num++;
  5149. if (num > max)
  5150. {
  5151. // Disconnect
  5152. Disconnect(s);
  5153. c->Err = ERR_CLIENT_IS_NOT_VPN;
  5154. *error_detail_str = "HTTP_TOO_MANY_REQUEST";
  5155. return false;
  5156. }
  5157. // Receive a header
  5158. h = RecvHttpHeader(s);
  5159. if (h == NULL)
  5160. {
  5161. c->Err = ERR_CLIENT_IS_NOT_VPN;
  5162. return false;
  5163. }
  5164. if (check_hostname && (StrCmpi(h->Version, "HTTP/1.1") == 0 || StrCmpi(h->Version, "HTTP/1.2") == 0))
  5165. {
  5166. HTTP_VALUE *v;
  5167. Zero(hostname, sizeof(hostname));
  5168. v = GetHttpValue(h, "Host");
  5169. if (v != NULL)
  5170. {
  5171. StrCpy(hostname, sizeof(hostname), v->Data);
  5172. }
  5173. if (IsEmptyStr(hostname))
  5174. {
  5175. // Invalid hostname
  5176. HttpSendInvalidHostname(s, h->Target);
  5177. FreeHttpHeader(h);
  5178. c->Err = ERR_CLIENT_IS_NOT_VPN;
  5179. *error_detail_str = "Invalid_hostname";
  5180. return false;
  5181. }
  5182. }
  5183. // Interpret
  5184. if (StrCmpi(h->Method, "POST") == 0)
  5185. {
  5186. // Receive the data since it's POST
  5187. data_size = GetContentLength(h);
  5188. if ((data_size > MAX_WATERMARK_SIZE || data_size < SizeOfWaterMark()) && (data_size != StrLen(HTTP_VPN_TARGET_POSTDATA)))
  5189. {
  5190. // Data is too large
  5191. HttpSendForbidden(s, h->Target, NULL);
  5192. FreeHttpHeader(h);
  5193. c->Err = ERR_CLIENT_IS_NOT_VPN;
  5194. *error_detail_str = "POST_Recv_TooLong";
  5195. return false;
  5196. }
  5197. data = Malloc(data_size);
  5198. if (RecvAll(s, data, data_size, s->SecureMode) == false)
  5199. {
  5200. // Data reception failure
  5201. Free(data);
  5202. FreeHttpHeader(h);
  5203. c->Err = ERR_DISCONNECTED;
  5204. *error_detail_str = "POST_Recv_Failed";
  5205. return false;
  5206. }
  5207. // Check the Target
  5208. if ((StrCmpi(h->Target, vpn_http_target) != 0) || not_found_error)
  5209. {
  5210. // Target is invalid
  5211. HttpSendNotFound(s, h->Target);
  5212. Free(data);
  5213. FreeHttpHeader(h);
  5214. *error_detail_str = "POST_Target_Wrong";
  5215. }
  5216. else
  5217. {
  5218. // Compare posted data with the WaterMark
  5219. if ((data_size == StrLen(HTTP_VPN_TARGET_POSTDATA) && (Cmp(data, HTTP_VPN_TARGET_POSTDATA, data_size) == 0))
  5220. || (Cmp(data, WaterMark, SizeOfWaterMark()) == 0))
  5221. {
  5222. // Check the WaterMark
  5223. Free(data);
  5224. FreeHttpHeader(h);
  5225. return true;
  5226. }
  5227. else
  5228. {
  5229. // WaterMark is incorrect
  5230. HttpSendForbidden(s, h->Target, NULL);
  5231. FreeHttpHeader(h);
  5232. *error_detail_str = "POST_WaterMark_Error";
  5233. }
  5234. }
  5235. }
  5236. else if (StrCmpi(h->Method, "SSTP_DUPLEX_POST") == 0 && (server->DisableSSTPServer == false || s->IsReverseAcceptedSocket
  5237. ) &&
  5238. GetServerCapsBool(server, "b_support_sstp") && GetNoSstp() == false)
  5239. {
  5240. // SSTP client is connected
  5241. c->WasSstp = true;
  5242. if (StrCmpi(h->Target, SSTP_URI) == 0)
  5243. {
  5244. bool sstp_ret;
  5245. // Accept the SSTP connection
  5246. c->Type = CONNECTION_TYPE_SSTP;
  5247. sstp_ret = AcceptSstp(c);
  5248. c->Err = ERR_DISCONNECTED;
  5249. FreeHttpHeader(h);
  5250. if (sstp_ret)
  5251. {
  5252. *error_detail_str = "";
  5253. }
  5254. else
  5255. {
  5256. *error_detail_str = "SSTP_ABORT";
  5257. }
  5258. return false;
  5259. }
  5260. else
  5261. {
  5262. // URI is invalid
  5263. HttpSendNotFound(s, h->Target);
  5264. *error_detail_str = "SSTP_URL_WRONG";
  5265. }
  5266. FreeHttpHeader(h);
  5267. }
  5268. else
  5269. {
  5270. // This should not be a VPN client, but interpret a bit more
  5271. if (StrCmpi(h->Method, "GET") != 0 && StrCmpi(h->Method, "HEAD") != 0
  5272. && StrCmpi(h->Method, "POST") != 0)
  5273. {
  5274. // Unsupported method calls
  5275. HttpSendNotImplemented(s, h->Method, h->Target, h->Version);
  5276. *error_detail_str = "HTTP_BAD_METHOD";
  5277. }
  5278. else
  5279. {
  5280. if (StrCmpi(h->Target, "/") == 0)
  5281. {
  5282. // Root directory
  5283. SERVER *s = c->Cedar->Server;
  5284. bool is_free = false;
  5285. *error_detail_str = "HTTP_ROOT";
  5286. {
  5287. if (is_free == false)
  5288. {
  5289. // Other than free version
  5290. HttpSendForbidden(c->FirstSock, h->Target, "");
  5291. }
  5292. else
  5293. {
  5294. // Free version
  5295. BUF *b = ReadDump("|free.htm");
  5296. if (b != NULL)
  5297. {
  5298. char *src = ZeroMalloc(b->Size + 1);
  5299. UINT dst_size = b->Size * 2 + 64;
  5300. char *dst = ZeroMalloc(dst_size);
  5301. char host[MAX_PATH];
  5302. char portstr[64];
  5303. GetMachineName(host, sizeof(host));
  5304. ToStr(portstr, c->FirstSock->LocalPort);
  5305. Copy(src, b->Buf, b->Size);
  5306. ReplaceStrEx(dst, dst_size, src,
  5307. "$HOST$", host, false);
  5308. ReplaceStrEx(dst, dst_size, dst,
  5309. "$PORT$", portstr, false);
  5310. FreeHttpHeader(h);
  5311. h = NewHttpHeader("HTTP/1.1", "202", "OK");
  5312. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE4));
  5313. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  5314. AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
  5315. PostHttp(c->FirstSock, h, dst, StrLen(dst));
  5316. Free(src);
  5317. Free(dst);
  5318. FreeBuf(b);
  5319. }
  5320. }
  5321. }
  5322. }
  5323. else
  5324. {
  5325. bool b = false;
  5326. // Show the WebUI if the configuration allow to use the WebUI
  5327. if (c->Cedar->Server != NULL && c->Cedar->Server->UseWebUI)
  5328. {
  5329. WU_WEBPAGE *page;
  5330. // Show the WebUI
  5331. page = WuGetPage(h->Target, c->Cedar->WebUI);
  5332. if (page != NULL)
  5333. {
  5334. PostHttp(s, page->header, page->data, page->size);
  5335. b = true;
  5336. WuFreeWebPage(page);
  5337. }
  5338. }
  5339. if (c->FirstSock->RemoteIP.addr[0] == 127)
  5340. {
  5341. if (StrCmpi(h->Target, HTTP_SAITAMA) == 0)
  5342. {
  5343. // Saitama (joke)
  5344. FreeHttpHeader(h);
  5345. h = NewHttpHeader("HTTP/1.1", "202", "OK");
  5346. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE3));
  5347. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  5348. AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
  5349. PostHttp(s, h, Saitama, SizeOfSaitama());
  5350. b = true;
  5351. }
  5352. else if (StartWith(h->Target, HTTP_PICTURES))
  5353. {
  5354. BUF *buf;
  5355. // Lots of photos
  5356. buf = ReadDump("|Pictures.mht");
  5357. if (buf != NULL)
  5358. {
  5359. FreeHttpHeader(h);
  5360. h = NewHttpHeader("HTTP/1.1", "202", "OK");
  5361. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE5));
  5362. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  5363. AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
  5364. PostHttp(s, h, buf->Buf, buf->Size);
  5365. b = true;
  5366. FreeBuf(buf);
  5367. }
  5368. }
  5369. }
  5370. if ((b == false) && (StartWith(h->Target, "/wiki")))
  5371. {
  5372. HttpSendRedirect(s, h->Target, hostname);
  5373. b = true;
  5374. }
  5375. if (b == false)
  5376. {
  5377. // Not Found
  5378. HttpSendNotFound(s, h->Target);
  5379. *error_detail_str = "HTTP_NOT_FOUND";
  5380. }
  5381. }
  5382. }
  5383. FreeHttpHeader(h);
  5384. }
  5385. }
  5386. }
  5387. // Upload a signature
  5388. bool ClientUploadSignature(SOCK *s)
  5389. {
  5390. HTTP_HEADER *h;
  5391. UINT water_size, rand_size;
  5392. UCHAR *water;
  5393. char ip_str[128];
  5394. // Validate arguments
  5395. if (s == NULL)
  5396. {
  5397. return false;
  5398. }
  5399. IPToStr(ip_str, sizeof(ip_str), &s->RemoteIP);
  5400. h = NewHttpHeader("POST", HTTP_VPN_TARGET2, "HTTP/1.1");
  5401. AddHttpValue(h, NewHttpValue("Host", ip_str));
  5402. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE3));
  5403. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  5404. // Generate a watermark
  5405. rand_size = Rand32() % (HTTP_PACK_RAND_SIZE_MAX * 2);
  5406. water_size = SizeOfWaterMark() + rand_size;
  5407. water = Malloc(water_size);
  5408. Copy(water, WaterMark, SizeOfWaterMark());
  5409. Rand(&water[SizeOfWaterMark()], rand_size);
  5410. // Upload the watermark data
  5411. if (PostHttp(s, h, water, water_size) == false)
  5412. {
  5413. Free(water);
  5414. FreeHttpHeader(h);
  5415. return false;
  5416. }
  5417. Free(water);
  5418. FreeHttpHeader(h);
  5419. return true;
  5420. }
  5421. // Establish a connection to the server
  5422. SOCK *ClientConnectToServer(CONNECTION *c)
  5423. {
  5424. SOCK *s = NULL;
  5425. X *x = NULL;
  5426. K *k = NULL;
  5427. // Validate arguments
  5428. if (c == NULL)
  5429. {
  5430. return NULL;
  5431. }
  5432. if (c->Halt)
  5433. {
  5434. c->Err = ERR_USER_CANCEL;
  5435. return NULL;
  5436. }
  5437. // Get the socket by connecting
  5438. s = ClientConnectGetSocket(c, false, (c->DontUseTls1 ? false : true));
  5439. if (s == NULL)
  5440. {
  5441. // Connection failure
  5442. return NULL;
  5443. }
  5444. c->FirstSock = s;
  5445. if (c->Halt)
  5446. {
  5447. c->Err = ERR_USER_CANCEL;
  5448. ReleaseSock(s);
  5449. c->FirstSock = NULL;
  5450. return NULL;
  5451. }
  5452. // Time-out
  5453. SetTimeout(s, CONNECTING_TIMEOUT);
  5454. // Start the SSL communication
  5455. if (StartSSLEx(s, x, k, (c->DontUseTls1 ? false : true), 0, c->ServerName) == false)
  5456. {
  5457. // SSL communication start failure
  5458. Disconnect(s);
  5459. ReleaseSock(s);
  5460. c->FirstSock = NULL;
  5461. c->Err = ERR_SERVER_IS_NOT_VPN;
  5462. return NULL;
  5463. }
  5464. if (s->RemoteX == NULL)
  5465. {
  5466. // SSL communication start failure
  5467. Disconnect(s);
  5468. ReleaseSock(s);
  5469. c->FirstSock = NULL;
  5470. c->Err = ERR_SERVER_IS_NOT_VPN;
  5471. return NULL;
  5472. }
  5473. return s;
  5474. }
  5475. // Return a socket by connecting to the server
  5476. SOCK *ClientConnectGetSocket(CONNECTION *c, bool additional_connect, bool no_tls)
  5477. {
  5478. SOCK *s = NULL;
  5479. CLIENT_OPTION *o;
  5480. char *host_for_direct_connection;
  5481. UINT port_for_direct_connection;
  5482. wchar_t tmp[MAX_SIZE];
  5483. SESSION *sess;
  5484. volatile bool *cancel_flag = NULL;
  5485. void *hWnd;
  5486. UINT nat_t_err = 0;
  5487. bool is_additonal_rudp_session = false;
  5488. UCHAR uc = 0;
  5489. IP ret_ip;
  5490. // Validate arguments
  5491. if (c == NULL)
  5492. {
  5493. return NULL;
  5494. }
  5495. Zero(&ret_ip, sizeof(IP));
  5496. sess = c->Session;
  5497. if (sess != NULL)
  5498. {
  5499. cancel_flag = &sess->CancelConnect;
  5500. is_additonal_rudp_session = sess->IsRUDPSession;
  5501. }
  5502. hWnd = c->hWndForUI;
  5503. o = c->Session->ClientOption;
  5504. if (additional_connect)
  5505. {
  5506. if (sess != NULL)
  5507. {
  5508. Copy(&ret_ip, &sess->ServerIP_CacheForNextConnect, sizeof(IP));
  5509. }
  5510. }
  5511. if (c->RestoreServerNameAndPort && additional_connect)
  5512. {
  5513. // Restore to the original server name and port number
  5514. c->RestoreServerNameAndPort = false;
  5515. if (StrCmpi(c->ServerName, o->Hostname) != 0)
  5516. {
  5517. StrCpy(c->ServerName, sizeof(c->ServerName), o->Hostname);
  5518. Zero(&ret_ip, sizeof(IP));
  5519. }
  5520. c->ServerPort = o->Port;
  5521. }
  5522. host_for_direct_connection = c->ServerName;
  5523. port_for_direct_connection = c->ServerPort;
  5524. switch (o->ProxyType)
  5525. {
  5526. case PROXY_DIRECT: // TCP/IP
  5527. UniFormat(tmp, sizeof(tmp), _UU("STATUS_4"), c->ServerName);
  5528. PrintStatus(sess, tmp);
  5529. // Production job
  5530. if (o->PortUDP == 0)
  5531. {
  5532. {
  5533. // If additional_connect == false, enable trying to NAT-T connection
  5534. // If additional_connect == true, follow the IsRUDPSession setting in this session
  5535. s = TcpIpConnectEx(host_for_direct_connection, port_for_direct_connection,
  5536. (bool *)cancel_flag, hWnd, &nat_t_err, (additional_connect ? (!is_additonal_rudp_session) : false),
  5537. true, no_tls, &ret_ip);
  5538. }
  5539. }
  5540. else
  5541. {
  5542. // Mode to connect with R-UDP directly without using NAT-T server when using UDP
  5543. IP ip;
  5544. Zero(&ip, sizeof(ip));
  5545. StrToIP(&ip, o->Hostname);
  5546. s = NewRUDPClientDirect(VPN_RUDP_SVC_NAME, &ip, o->PortUDP, &nat_t_err,
  5547. TIMEOUT_TCP_PORT_CHECK, (bool *)cancel_flag, NULL, NULL, 0, false);
  5548. if (s != NULL)
  5549. {
  5550. StrCpy(s->UnderlayProtocol, sizeof(s->UnderlayProtocol), SOCK_UNDERLAY_NAT_T);
  5551. }
  5552. }
  5553. if (s == NULL)
  5554. {
  5555. // Connection failure
  5556. if (nat_t_err != RUDP_ERROR_NAT_T_TWO_OR_MORE)
  5557. {
  5558. c->Err = ERR_CONNECT_FAILED;
  5559. }
  5560. else
  5561. {
  5562. c->Err = ERR_NAT_T_TWO_OR_MORE;
  5563. }
  5564. return NULL;
  5565. }
  5566. break;
  5567. case PROXY_HTTP: // HTTP Proxy
  5568. host_for_direct_connection = o->ProxyName;
  5569. port_for_direct_connection = o->ProxyPort;
  5570. UniFormat(tmp, sizeof(tmp), _UU("STATUS_2"), c->ServerName, o->ProxyName);
  5571. PrintStatus(sess, tmp);
  5572. // Proxy connection
  5573. s = ProxyConnectEx(c, host_for_direct_connection, port_for_direct_connection,
  5574. c->ServerName, c->ServerPort, o->ProxyUsername, o->ProxyPassword,
  5575. additional_connect, (bool *)cancel_flag, hWnd);
  5576. if (s == NULL)
  5577. {
  5578. // Connection failure
  5579. return NULL;
  5580. }
  5581. break;
  5582. case PROXY_SOCKS: // SOCKS Proxy
  5583. host_for_direct_connection = o->ProxyName;
  5584. port_for_direct_connection = o->ProxyPort;
  5585. UniFormat(tmp, sizeof(tmp), _UU("STATUS_2"), c->ServerName, o->ProxyName);
  5586. PrintStatus(sess, tmp);
  5587. // SOCKS connection
  5588. s = SocksConnectEx2(c, host_for_direct_connection, port_for_direct_connection,
  5589. c->ServerName, c->ServerPort, o->ProxyUsername,
  5590. additional_connect, (bool *)cancel_flag, hWnd, 0, &ret_ip);
  5591. if (s == NULL)
  5592. {
  5593. // Connection failure
  5594. return NULL;
  5595. }
  5596. break;
  5597. }
  5598. if (s == NULL)
  5599. {
  5600. // Connection failure
  5601. c->Err = ERR_CONNECT_FAILED;
  5602. }
  5603. else
  5604. {
  5605. // Success to connect
  5606. // Keep a note of the IP address
  5607. if (additional_connect == false || IsZeroIP(&s->RemoteIP))
  5608. {
  5609. if (((s->IsRUDPSocket || s->IPv6) && IsZeroIP(&s->RemoteIP) == false && o->ProxyType == PROXY_DIRECT) || GetIP(&c->Session->ServerIP, host_for_direct_connection) == false)
  5610. {
  5611. Copy(&c->Session->ServerIP, &s->RemoteIP, sizeof(IP));
  5612. }
  5613. }
  5614. if (IsZeroIP(&ret_ip) == false)
  5615. {
  5616. if (c->Session != NULL)
  5617. {
  5618. if (additional_connect == false)
  5619. {
  5620. Copy(&c->Session->ServerIP_CacheForNextConnect, &ret_ip, sizeof(IP));
  5621. Debug("Saved ServerIP_CacheForNextConnect: %s = %r\n", c->ServerName, &ret_ip);
  5622. }
  5623. }
  5624. }
  5625. }
  5626. return s;
  5627. }
  5628. // Connect via SOCKS
  5629. SOCK *SocksConnect(CONNECTION *c, char *proxy_host_name, UINT proxy_port,
  5630. char *server_host_name, UINT server_port,
  5631. char *username, bool additional_connect)
  5632. {
  5633. return SocksConnectEx(c, proxy_host_name, proxy_port,
  5634. server_host_name, server_port, username, additional_connect, NULL, NULL);
  5635. }
  5636. SOCK *SocksConnectEx(CONNECTION *c, char *proxy_host_name, UINT proxy_port,
  5637. char *server_host_name, UINT server_port,
  5638. char *username, bool additional_connect,
  5639. bool *cancel_flag, void *hWnd)
  5640. {
  5641. return SocksConnectEx2(c, proxy_host_name, proxy_port,
  5642. server_host_name, server_port, username, additional_connect, cancel_flag,
  5643. hWnd, 0, NULL);
  5644. }
  5645. SOCK *SocksConnectEx2(CONNECTION *c, char *proxy_host_name, UINT proxy_port,
  5646. char *server_host_name, UINT server_port,
  5647. char *username, bool additional_connect,
  5648. bool *cancel_flag, void *hWnd, UINT timeout, IP *ret_ip)
  5649. {
  5650. SOCK *s = NULL;
  5651. IP ip;
  5652. // Validate arguments
  5653. if (c == NULL || proxy_host_name == NULL || proxy_port == 0 || server_host_name == NULL
  5654. || server_port == 0)
  5655. {
  5656. c->Err = ERR_PROXY_CONNECT_FAILED;
  5657. return NULL;
  5658. }
  5659. // Get the IP address of the destination server
  5660. if (GetIP(&ip, server_host_name) == false)
  5661. {
  5662. // Failure
  5663. c->Err = ERR_CONNECT_FAILED;
  5664. return NULL;
  5665. }
  5666. if (c->Halt)
  5667. {
  5668. // Stop
  5669. c->Err = ERR_USER_CANCEL;
  5670. return NULL;
  5671. }
  5672. // Connection
  5673. s = TcpConnectEx3(proxy_host_name, proxy_port, timeout, cancel_flag, hWnd, true, NULL, false, false, ret_ip);
  5674. if (s == NULL)
  5675. {
  5676. // Failure
  5677. c->Err = ERR_PROXY_CONNECT_FAILED;
  5678. return NULL;
  5679. }
  5680. // Timeout setting
  5681. SetTimeout(s, MIN(CONNECTING_TIMEOUT_PROXY, (timeout == 0 ? INFINITE : timeout)));
  5682. if (additional_connect == false)
  5683. {
  5684. c->FirstSock = s;
  5685. }
  5686. // Request packet transmission
  5687. if (SocksSendRequestPacket(c, s, server_port, &ip, username) == false)
  5688. {
  5689. // Failure
  5690. if (additional_connect == false)
  5691. {
  5692. c->FirstSock = NULL;
  5693. }
  5694. Disconnect(s);
  5695. ReleaseSock(s);
  5696. return NULL;
  5697. }
  5698. // Receive a response packet
  5699. if (SocksRecvResponsePacket(c, s) == false)
  5700. {
  5701. // Failure
  5702. if (additional_connect == false)
  5703. {
  5704. c->FirstSock = NULL;
  5705. }
  5706. Disconnect(s);
  5707. ReleaseSock(s);
  5708. return NULL;
  5709. }
  5710. SetTimeout(s, INFINITE);
  5711. return s;
  5712. }
  5713. // Receive a SOCKS response packet
  5714. bool SocksRecvResponsePacket(CONNECTION *c, SOCK *s)
  5715. {
  5716. BUF *b;
  5717. UINT size = 8;
  5718. UCHAR tmp[8];
  5719. UCHAR vn, cd;
  5720. // Validate arguments
  5721. if (c == NULL || s == NULL)
  5722. {
  5723. return false;
  5724. }
  5725. if (RecvAll(s, tmp, sizeof(tmp), false) == false)
  5726. {
  5727. c->Err = ERR_DISCONNECTED;
  5728. return false;
  5729. }
  5730. b = NewBuf();
  5731. WriteBuf(b, tmp, sizeof(tmp));
  5732. SeekBuf(b, 0, 0);
  5733. ReadBuf(b, &vn, 1);
  5734. ReadBuf(b, &cd, 1);
  5735. FreeBuf(b);
  5736. if (vn != 0)
  5737. {
  5738. c->Err = ERR_PROXY_ERROR;
  5739. return false;
  5740. }
  5741. switch (cd)
  5742. {
  5743. case 90:
  5744. // Success
  5745. return true;
  5746. case 93:
  5747. // Authentication failure
  5748. c->Err = ERR_PROXY_AUTH_FAILED;
  5749. return false;
  5750. default:
  5751. // Connection to the server failure
  5752. c->Err = ERR_CONNECT_FAILED;
  5753. return false;
  5754. }
  5755. }
  5756. // Send a SOCKS request packet
  5757. bool SocksSendRequestPacket(CONNECTION *c, SOCK *s, UINT dest_port, IP *dest_ip, char *userid)
  5758. {
  5759. BUF *b;
  5760. UCHAR vn, cd;
  5761. USHORT port;
  5762. UINT ip;
  5763. bool ret;
  5764. // Validate arguments
  5765. if (s == NULL || dest_port == 0 || dest_ip == NULL || c == NULL)
  5766. {
  5767. return false;
  5768. }
  5769. if (userid == NULL)
  5770. {
  5771. userid = "";
  5772. }
  5773. b = NewBuf();
  5774. vn = 4;
  5775. cd = 1;
  5776. WriteBuf(b, &vn, 1);
  5777. WriteBuf(b, &cd, 1);
  5778. port = Endian16((USHORT)dest_port);
  5779. ip = IPToUINT(dest_ip);
  5780. WriteBuf(b, &port, 2);
  5781. WriteBuf(b, &ip, 4);
  5782. WriteBuf(b, userid, StrLen(userid) + 1);
  5783. ret = SendAll(s, b->Buf, b->Size, false);
  5784. if (ret == false)
  5785. {
  5786. c->Err = ERR_DISCONNECTED;
  5787. }
  5788. FreeBuf(b);
  5789. return ret;
  5790. }
  5791. // Connect through a proxy
  5792. SOCK *ProxyConnect(CONNECTION *c, char *proxy_host_name, UINT proxy_port,
  5793. char *server_host_name, UINT server_port,
  5794. char *username, char *password, bool additional_connect)
  5795. {
  5796. return ProxyConnectEx(c, proxy_host_name, proxy_port,
  5797. server_host_name, server_port, username, password, additional_connect, NULL, NULL);
  5798. }
  5799. SOCK *ProxyConnectEx(CONNECTION *c, char *proxy_host_name, UINT proxy_port,
  5800. char *server_host_name, UINT server_port,
  5801. char *username, char *password, bool additional_connect,
  5802. bool *cancel_flag, void *hWnd)
  5803. {
  5804. return ProxyConnectEx2(c, proxy_host_name, proxy_port,
  5805. server_host_name, server_port, username, password, additional_connect,
  5806. cancel_flag, hWnd, 0);
  5807. }
  5808. SOCK *ProxyConnectEx2(CONNECTION *c, char *proxy_host_name, UINT proxy_port,
  5809. char *server_host_name, UINT server_port,
  5810. char *username, char *password, bool additional_connect,
  5811. bool *cancel_flag, void *hWnd, UINT timeout)
  5812. {
  5813. SOCK *s = NULL;
  5814. bool use_auth = false;
  5815. char tmp[MAX_SIZE];
  5816. char auth_tmp_str[MAX_SIZE], auth_b64_str[MAX_SIZE * 2];
  5817. char basic_str[MAX_SIZE * 2];
  5818. UINT http_error_code;
  5819. HTTP_HEADER *h;
  5820. char server_host_name_tmp[256];
  5821. UINT i, len;
  5822. // Validate arguments
  5823. if (c == NULL || proxy_host_name == NULL || proxy_port == 0 || server_host_name == NULL ||
  5824. server_port == 0)
  5825. {
  5826. c->Err = ERR_PROXY_CONNECT_FAILED;
  5827. return NULL;
  5828. }
  5829. if (username != NULL && password != NULL &&
  5830. (StrLen(username) != 0 || StrLen(password) != 0))
  5831. {
  5832. use_auth = true;
  5833. }
  5834. if (c->Halt)
  5835. {
  5836. // Stop
  5837. c->Err = ERR_USER_CANCEL;
  5838. return NULL;
  5839. }
  5840. Zero(server_host_name_tmp, sizeof(server_host_name_tmp));
  5841. StrCpy(server_host_name_tmp, sizeof(server_host_name_tmp), server_host_name);
  5842. len = StrLen(server_host_name_tmp);
  5843. for (i = 0;i < len;i++)
  5844. {
  5845. if (server_host_name_tmp[i] == '/')
  5846. {
  5847. server_host_name_tmp[i] = 0;
  5848. }
  5849. }
  5850. // Connection
  5851. s = TcpConnectEx3(proxy_host_name, proxy_port, timeout, cancel_flag, hWnd, true, NULL, false, false, NULL);
  5852. if (s == NULL)
  5853. {
  5854. // Failure
  5855. c->Err = ERR_PROXY_CONNECT_FAILED;
  5856. return NULL;
  5857. }
  5858. // Timeout setting
  5859. SetTimeout(s, MIN(CONNECTING_TIMEOUT_PROXY, (timeout == 0 ? INFINITE : timeout)));
  5860. if (additional_connect == false)
  5861. {
  5862. c->FirstSock = s;
  5863. }
  5864. // HTTP header generation
  5865. if (IsStrIPv6Address(server_host_name_tmp))
  5866. {
  5867. IP ip;
  5868. char iptmp[MAX_PATH];
  5869. StrToIP(&ip, server_host_name_tmp);
  5870. IPToStr(iptmp, sizeof(iptmp), &ip);
  5871. Format(tmp, sizeof(tmp), "[%s]:%u", iptmp, server_port);
  5872. }
  5873. else
  5874. {
  5875. Format(tmp, sizeof(tmp), "%s:%u", server_host_name_tmp, server_port);
  5876. }
  5877. h = NewHttpHeader("CONNECT", tmp, "HTTP/1.0");
  5878. AddHttpValue(h, NewHttpValue("User-Agent", (c->Cedar == NULL ? DEFAULT_USER_AGENT : c->Cedar->HttpUserAgent)));
  5879. AddHttpValue(h, NewHttpValue("Host", server_host_name_tmp));
  5880. AddHttpValue(h, NewHttpValue("Content-Length", "0"));
  5881. AddHttpValue(h, NewHttpValue("Proxy-Connection", "Keep-Alive"));
  5882. AddHttpValue(h, NewHttpValue("Pragma", "no-cache"));
  5883. if (use_auth)
  5884. {
  5885. wchar_t tmp[MAX_SIZE];
  5886. UniFormat(tmp, sizeof(tmp), _UU("STATUS_3"), server_host_name_tmp);
  5887. // Generate the authentication string
  5888. Format(auth_tmp_str, sizeof(auth_tmp_str), "%s:%s",
  5889. username, password);
  5890. // Base64 encode
  5891. Zero(auth_b64_str, sizeof(auth_b64_str));
  5892. Encode64(auth_b64_str, auth_tmp_str);
  5893. Format(basic_str, sizeof(basic_str), "Basic %s", auth_b64_str);
  5894. AddHttpValue(h, NewHttpValue("Proxy-Authorization", basic_str));
  5895. }
  5896. // Transmission
  5897. if (SendHttpHeader(s, h) == false)
  5898. {
  5899. // Failure
  5900. if (additional_connect == false)
  5901. {
  5902. c->FirstSock = NULL;
  5903. }
  5904. FreeHttpHeader(h);
  5905. Disconnect(s);
  5906. ReleaseSock(s);
  5907. c->Err = ERR_PROXY_ERROR;
  5908. return NULL;
  5909. }
  5910. FreeHttpHeader(h);
  5911. if (c->Halt)
  5912. {
  5913. // Stop
  5914. if (additional_connect == false)
  5915. {
  5916. c->FirstSock = NULL;
  5917. }
  5918. Disconnect(s);
  5919. ReleaseSock(s);
  5920. c->Err = ERR_USER_CANCEL;
  5921. return NULL;
  5922. }
  5923. // Receive the results
  5924. h = RecvHttpHeader(s);
  5925. if (h == NULL)
  5926. {
  5927. // Failure
  5928. if (additional_connect == false)
  5929. {
  5930. c->FirstSock = NULL;
  5931. }
  5932. FreeHttpHeader(h);
  5933. Disconnect(s);
  5934. ReleaseSock(s);
  5935. c->Err = ERR_PROXY_ERROR;
  5936. return NULL;
  5937. }
  5938. http_error_code = 0;
  5939. if (StrLen(h->Method) == 8)
  5940. {
  5941. if (Cmp(h->Method, "HTTP/1.", 7) == 0)
  5942. {
  5943. http_error_code = ToInt(h->Target);
  5944. }
  5945. }
  5946. FreeHttpHeader(h);
  5947. // Check the code
  5948. switch (http_error_code)
  5949. {
  5950. case 401:
  5951. case 403:
  5952. case 407:
  5953. // Authentication failure
  5954. if (additional_connect == false)
  5955. {
  5956. c->FirstSock = NULL;
  5957. }
  5958. Disconnect(s);
  5959. ReleaseSock(s);
  5960. c->Err = ERR_PROXY_AUTH_FAILED;
  5961. return NULL;
  5962. default:
  5963. if ((http_error_code / 100) == 2)
  5964. {
  5965. // Success
  5966. SetTimeout(s, INFINITE);
  5967. return s;
  5968. }
  5969. else
  5970. {
  5971. // Receive an unknown result
  5972. if (additional_connect == false)
  5973. {
  5974. c->FirstSock = NULL;
  5975. }
  5976. Disconnect(s);
  5977. ReleaseSock(s);
  5978. c->Err = ERR_PROXY_ERROR;
  5979. return NULL;
  5980. }
  5981. }
  5982. }
  5983. // TCP connection function
  5984. SOCK *TcpConnectEx2(char *hostname, UINT port, UINT timeout, bool *cancel_flag, void *hWnd, bool try_start_ssl, bool ssl_no_tls)
  5985. {
  5986. return TcpConnectEx3(hostname, port, timeout, cancel_flag, hWnd, false, NULL, try_start_ssl, ssl_no_tls, NULL);
  5987. }
  5988. SOCK *TcpConnectEx3(char *hostname, UINT port, UINT timeout, bool *cancel_flag, void *hWnd, bool no_nat_t, UINT *nat_t_error_code, bool try_start_ssl, bool ssl_no_tls, IP *ret_ip)
  5989. {
  5990. #ifdef OS_WIN32
  5991. if (hWnd == NULL)
  5992. {
  5993. #endif // OS_WIN32
  5994. return ConnectEx4(hostname, port, timeout, cancel_flag, (no_nat_t ? NULL : VPN_RUDP_SVC_NAME), nat_t_error_code, try_start_ssl, ssl_no_tls, true, ret_ip);
  5995. #ifdef OS_WIN32
  5996. }
  5997. else
  5998. {
  5999. return WinConnectEx3((HWND)hWnd, hostname, port, timeout, 0, NULL, NULL, nat_t_error_code, (no_nat_t ? NULL : VPN_RUDP_SVC_NAME), try_start_ssl, ssl_no_tls);
  6000. }
  6001. #endif // OS_WIN32
  6002. }
  6003. // Connect with TCP/IP
  6004. SOCK *TcpIpConnect(char *hostname, UINT port, bool try_start_ssl, bool ssl_no_tls)
  6005. {
  6006. return TcpIpConnectEx(hostname, port, NULL, NULL, NULL, false, try_start_ssl, ssl_no_tls, NULL);
  6007. }
  6008. SOCK *TcpIpConnectEx(char *hostname, UINT port, bool *cancel_flag, void *hWnd, UINT *nat_t_error_code, bool no_nat_t, bool try_start_ssl, bool ssl_no_tls, IP *ret_ip)
  6009. {
  6010. SOCK *s = NULL;
  6011. UINT dummy_int = 0;
  6012. // Validate arguments
  6013. if (nat_t_error_code == NULL)
  6014. {
  6015. nat_t_error_code = &dummy_int;
  6016. }
  6017. *nat_t_error_code = 0;
  6018. if (hostname == NULL || port == 0)
  6019. {
  6020. return NULL;
  6021. }
  6022. s = TcpConnectEx3(hostname, port, 0, cancel_flag, hWnd, no_nat_t, nat_t_error_code, try_start_ssl, ssl_no_tls, ret_ip);
  6023. if (s == NULL)
  6024. {
  6025. return NULL;
  6026. }
  6027. return s;
  6028. }
  6029. // Protocol routine initialization
  6030. void InitProtocol()
  6031. {
  6032. }
  6033. // Release the protocol routine
  6034. void FreeProtocol()
  6035. {
  6036. }
  6037. // Create a Hello packet
  6038. PACK *PackHello(void *random, UINT ver, UINT build, char *server_str)
  6039. {
  6040. PACK *p;
  6041. // Validate arguments
  6042. if (random == NULL || server_str == NULL)
  6043. {
  6044. return NULL;
  6045. }
  6046. p = NewPack();
  6047. PackAddStr(p, "hello", server_str);
  6048. PackAddInt(p, "version", ver);
  6049. PackAddInt(p, "build", build);
  6050. PackAddData(p, "random", random, SHA1_SIZE);
  6051. return p;
  6052. }
  6053. // Interpret the Hello packet
  6054. bool GetHello(PACK *p, void *random, UINT *ver, UINT *build, char *server_str, UINT server_str_size)
  6055. {
  6056. // Validate arguments
  6057. if (p == NULL || random == NULL || ver == NULL || server_str == NULL)
  6058. {
  6059. return false;
  6060. }
  6061. if (PackGetStr(p, "hello", server_str, server_str_size) == false)
  6062. {
  6063. return false;
  6064. }
  6065. *ver = PackGetInt(p, "version");
  6066. *build = PackGetInt(p, "build");
  6067. if (PackGetDataSize(p, "random") != SHA1_SIZE)
  6068. {
  6069. return false;
  6070. }
  6071. if (PackGetData(p, "random", random) == false)
  6072. {
  6073. return false;
  6074. }
  6075. return true;
  6076. }
  6077. // Get the authentication method from PACK
  6078. UINT GetAuthTypeFromPack(PACK *p)
  6079. {
  6080. // Validate arguments
  6081. if (p == NULL)
  6082. {
  6083. return 0;
  6084. }
  6085. return PackGetInt(p, "authtype");
  6086. }
  6087. // Get the HUB name and the user name from the PACK
  6088. bool GetHubnameAndUsernameFromPack(PACK *p, char *username, UINT username_size,
  6089. char *hubname, UINT hubname_size)
  6090. {
  6091. // Validate arguments
  6092. if (p == NULL || username == NULL || hubname == NULL)
  6093. {
  6094. return false;
  6095. }
  6096. if (PackGetStr(p, "username", username, username_size) == false)
  6097. {
  6098. return false;
  6099. }
  6100. if (PackGetStr(p, "hubname", hubname, hubname_size) == false)
  6101. {
  6102. return false;
  6103. }
  6104. return true;
  6105. }
  6106. // Get the protocol from PACK
  6107. UINT GetProtocolFromPack(PACK *p)
  6108. {
  6109. // Validate arguments
  6110. if (p == NULL)
  6111. {
  6112. return 0;
  6113. }
  6114. #if 0
  6115. return PackGetInt(p, "protocol");
  6116. #else
  6117. // Limit to the TCP protocol in the current version
  6118. return CONNECTION_TCP;
  6119. #endif
  6120. }
  6121. // Get the method from the PACK
  6122. bool GetMethodFromPack(PACK *p, char *method, UINT size)
  6123. {
  6124. // Validate arguments
  6125. if (p == NULL || method == NULL || size == 0)
  6126. {
  6127. return false;
  6128. }
  6129. return PackGetStr(p, "method", method, size);
  6130. }
  6131. // Generate a packet of certificate authentication login
  6132. PACK *PackLoginWithCert(char *hubname, char *username, X *x, void *sign, UINT sign_size)
  6133. {
  6134. PACK *p;
  6135. BUF *b;
  6136. // Validate arguments
  6137. if (hubname == NULL || username == NULL)
  6138. {
  6139. return NULL;
  6140. }
  6141. p = NewPack();
  6142. PackAddStr(p, "method", "login");
  6143. PackAddStr(p, "hubname", hubname);
  6144. PackAddStr(p, "username", username);
  6145. PackAddInt(p, "authtype", CLIENT_AUTHTYPE_CERT);
  6146. // Certificate
  6147. b = XToBuf(x, false);
  6148. PackAddData(p, "cert", b->Buf, b->Size);
  6149. FreeBuf(b);
  6150. // Signature data
  6151. PackAddData(p, "sign", sign, sign_size);
  6152. return p;
  6153. }
  6154. // Generate a packet of plain text password authentication login
  6155. PACK *PackLoginWithPlainPassword(char *hubname, char *username, void *plain_password)
  6156. {
  6157. PACK *p;
  6158. // Validate arguments
  6159. if (hubname == NULL || username == NULL)
  6160. {
  6161. return NULL;
  6162. }
  6163. p = NewPack();
  6164. PackAddStr(p, "method", "login");
  6165. PackAddStr(p, "hubname", hubname);
  6166. PackAddStr(p, "username", username);
  6167. PackAddInt(p, "authtype", CLIENT_AUTHTYPE_PLAIN_PASSWORD);
  6168. PackAddStr(p, "plain_password", plain_password);
  6169. return p;
  6170. }
  6171. // Create a packet of password authentication login
  6172. PACK *PackLoginWithPassword(char *hubname, char *username, void *secure_password)
  6173. {
  6174. PACK *p;
  6175. // Validate arguments
  6176. if (hubname == NULL || username == NULL)
  6177. {
  6178. return NULL;
  6179. }
  6180. p = NewPack();
  6181. PackAddStr(p, "method", "login");
  6182. PackAddStr(p, "hubname", hubname);
  6183. PackAddStr(p, "username", username);
  6184. PackAddInt(p, "authtype", CLIENT_AUTHTYPE_PASSWORD);
  6185. PackAddData(p, "secure_password", secure_password, SHA1_SIZE);
  6186. return p;
  6187. }
  6188. // Create a packet for anonymous login
  6189. PACK *PackLoginWithAnonymous(char *hubname, char *username)
  6190. {
  6191. PACK *p;
  6192. // Validate arguments
  6193. if (hubname == NULL || username == NULL)
  6194. {
  6195. return NULL;
  6196. }
  6197. p = NewPack();
  6198. PackAddStr(p, "method", "login");
  6199. PackAddStr(p, "hubname", hubname);
  6200. PackAddStr(p, "username", username);
  6201. PackAddInt(p, "authtype", CLIENT_AUTHTYPE_ANONYMOUS);
  6202. return p;
  6203. }
  6204. // Create a packet for the additional connection
  6205. PACK *PackAdditionalConnect(UCHAR *session_key)
  6206. {
  6207. PACK *p;
  6208. // Validate arguments
  6209. if (session_key == NULL)
  6210. {
  6211. return NULL;
  6212. }
  6213. p = NewPack();
  6214. PackAddStr(p, "method", "additional_connect");
  6215. PackAddData(p, "session_key", session_key, SHA1_SIZE);
  6216. return p;
  6217. }
  6218. // Generate a RC4 key pair
  6219. void GenerateRC4KeyPair(RC4_KEY_PAIR *k)
  6220. {
  6221. // Validate arguments
  6222. if (k == NULL)
  6223. {
  6224. return;
  6225. }
  6226. Rand(k->ClientToServerKey, sizeof(k->ClientToServerKey));
  6227. Rand(k->ServerToClientKey, sizeof(k->ServerToClientKey));
  6228. }
  6229. // Developed by SoftEther VPN Project at University of Tsukuba in Japan.
  6230. // Department of Computer Science has dozens of overly-enthusiastic geeks.
  6231. // Join us: http://www.tsukuba.ac.jp/english/admission/