Protocol.c 173 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343
  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. if (hub->Option->UseHubNameAsRadiusNasId == true)
  1403. {
  1404. StrCpy(radius_login_opt.NasId, sizeof(radius_login_opt.NasId), hubname);
  1405. }
  1406. }
  1407. // Get the various flags
  1408. use_encrypt = PackGetInt(p, "use_encrypt") == 0 ? false : true;
  1409. use_compress = PackGetInt(p, "use_compress") == 0 ? false : true;
  1410. max_connection = PackGetInt(p, "max_connection");
  1411. half_connection = PackGetInt(p, "half_connection") == 0 ? false : true;
  1412. use_fast_rc4 = PackGetInt(p, "use_fast_rc4") == 0 ? false : true;
  1413. qos = PackGetInt(p, "qos") ? true : false;
  1414. client_id = PackGetInt(p, "client_id");
  1415. adjust_mss = PackGetInt(p, "adjust_mss");
  1416. use_udp_acceleration_client = PackGetBool(p, "use_udp_acceleration");
  1417. support_hmac_on_udp_acceleration_client = PackGetBool(p, "support_hmac_on_udp_acceleration");
  1418. support_udp_accel_fast_disconnect_detect = PackGetBool(p, "support_udp_accel_fast_disconnect_detect");
  1419. support_bulk_on_rudp = PackGetBool(p, "support_bulk_on_rudp");
  1420. support_hmac_on_bulk_of_rudp = PackGetBool(p, "support_hmac_on_bulk_of_rudp");
  1421. support_udp_recovery = PackGetBool(p, "support_udp_recovery");
  1422. if (c->IsInProc)
  1423. {
  1424. char tmp[MAX_SIZE];
  1425. UINT64 ptr;
  1426. ptr = PackGetInt64(p, "release_me_eap_client");
  1427. if (ptr != 0)
  1428. {
  1429. release_me_eap_client = (EAP_CLIENT *)ptr;
  1430. }
  1431. PackGetStr(p, "inproc_postfix", c->InProcPrefix, sizeof(c->InProcPrefix));
  1432. Zero(tmp, sizeof(tmp));
  1433. PackGetStr(p, "inproc_cryptname", tmp, sizeof(tmp));
  1434. if (c->FirstSock != NULL)
  1435. {
  1436. if (IsEmptyStr(c->InProcPrefix) == false)
  1437. {
  1438. Format(c->FirstSock->UnderlayProtocol, sizeof(c->FirstSock->UnderlayProtocol),
  1439. SOCK_UNDERLAY_INPROC_EX, c->InProcPrefix);
  1440. }
  1441. }
  1442. if (c->CipherName != NULL)
  1443. {
  1444. Free(c->CipherName);
  1445. }
  1446. c->CipherName = NULL;
  1447. if (IsEmptyStr(tmp) == false)
  1448. {
  1449. c->CipherName = CopyStr(tmp);
  1450. use_encrypt = true;
  1451. }
  1452. use_udp_acceleration_client = false;
  1453. }
  1454. else
  1455. {
  1456. if (c->CipherName != NULL)
  1457. {
  1458. Free(c->CipherName);
  1459. }
  1460. c->CipherName = NULL;
  1461. if (c->FirstSock != NULL && IsEmptyStr(c->FirstSock->CipherName) == false)
  1462. {
  1463. c->CipherName = CopyStr(c->FirstSock->CipherName);
  1464. }
  1465. }
  1466. if (support_bulk_on_rudp && c->FirstSock != NULL && c->FirstSock->IsRUDPSocket &&
  1467. c->FirstSock->BulkRecvKey != NULL && c->FirstSock->BulkSendKey != NULL)
  1468. {
  1469. // RAllow UDP bulk transfer if the client side supports
  1470. // in the case of using R-UDP Socket
  1471. enable_bulk_on_rudp = true;
  1472. enable_hmac_on_bulk_of_rudp = support_hmac_on_bulk_of_rudp;
  1473. }
  1474. if (support_udp_recovery && c->FirstSock != NULL && c->FirstSock->IsRUDPSocket)
  1475. {
  1476. // Allow UDP recovery
  1477. enable_udp_recovery = true;
  1478. }
  1479. if (use_udp_acceleration_client)
  1480. {
  1481. // Get the parameters for the UDP acceleration function
  1482. if (PackGetIp(p, "udp_acceleration_client_ip", &udp_acceleration_client_ip) == false ||
  1483. PackGetData2(p, "udp_acceleration_client_key", udp_acceleration_client_key, UDP_ACCELERATION_COMMON_KEY_SIZE) == false)
  1484. {
  1485. use_udp_acceleration_client = false;
  1486. }
  1487. else
  1488. {
  1489. if (IsZeroIp(&udp_acceleration_client_ip))
  1490. {
  1491. Copy(&udp_acceleration_client_ip, &c->FirstSock->RemoteIP, sizeof(IP));
  1492. }
  1493. udp_acceleration_client_port = PackGetInt(p, "udp_acceleration_client_port");
  1494. if (udp_acceleration_client_port == 0)
  1495. {
  1496. use_udp_acceleration_client = false;
  1497. }
  1498. }
  1499. use_hmac_on_udp_acceleration = support_hmac_on_udp_acceleration_client;
  1500. }
  1501. Debug("use_udp_acceleration_client = %u\n", use_udp_acceleration_client);
  1502. Debug("use_hmac_on_udp_acceleration = %u\n", use_hmac_on_udp_acceleration);
  1503. // Request mode
  1504. require_bridge_routing_mode = PackGetBool(p, "require_bridge_routing_mode");
  1505. require_monitor_mode = PackGetBool(p, "require_monitor_mode");
  1506. if (require_monitor_mode)
  1507. {
  1508. qos = false;
  1509. }
  1510. if (is_server_or_bridge)
  1511. {
  1512. require_bridge_routing_mode = true;
  1513. }
  1514. // Client unique ID
  1515. Zero(unique, sizeof(unique));
  1516. if (PackGetDataSize(p, "unique_id") == SHA1_SIZE)
  1517. {
  1518. PackGetData(p, "unique_id", unique);
  1519. }
  1520. // Get the authentication method
  1521. authtype = GetAuthTypeFromPack(p);
  1522. if (1)
  1523. {
  1524. // Log
  1525. char ip1[64], ip2[64], verstr[64];
  1526. wchar_t *authtype_str = _UU("LH_AUTH_UNKNOWN");
  1527. switch (authtype)
  1528. {
  1529. case CLIENT_AUTHTYPE_ANONYMOUS:
  1530. authtype_str = _UU("LH_AUTH_ANONYMOUS");
  1531. break;
  1532. case CLIENT_AUTHTYPE_PASSWORD:
  1533. authtype_str = _UU("LH_AUTH_PASSWORD");
  1534. break;
  1535. case CLIENT_AUTHTYPE_PLAIN_PASSWORD:
  1536. authtype_str = _UU("LH_AUTH_PLAIN_PASSWORD");
  1537. break;
  1538. case CLIENT_AUTHTYPE_CERT:
  1539. authtype_str = _UU("LH_AUTH_CERT");
  1540. break;
  1541. case AUTHTYPE_TICKET:
  1542. authtype_str = _UU("LH_AUTH_TICKET");
  1543. break;
  1544. }
  1545. IPToStr(ip1, sizeof(ip1), &c->FirstSock->RemoteIP);
  1546. IPToStr(ip2, sizeof(ip2), &c->FirstSock->LocalIP);
  1547. Format(verstr, sizeof(verstr), "%u.%02u", c->ClientVer / 100, c->ClientVer % 100);
  1548. HLog(hub, "LH_CONNECT_CLIENT", c->Name, ip1, c->FirstSock->RemoteHostname, c->FirstSock->RemotePort,
  1549. c->ClientStr, verstr, c->ClientBuild, authtype_str, username);
  1550. }
  1551. // Attempt an anonymous authentication first
  1552. auth_ret = SamAuthUserByAnonymous(hub, username);
  1553. if (auth_ret)
  1554. {
  1555. if (c->IsInProc)
  1556. {
  1557. IPC_MSCHAP_V2_AUTHINFO mschap;
  1558. char password_tmp[MAX_SIZE];
  1559. Zero(&mschap, sizeof(mschap));
  1560. Zero(password_tmp, sizeof(password_tmp));
  1561. PackGetStr(p, "plain_password", password_tmp, sizeof(password_tmp));
  1562. if (ParseAndExtractMsChapV2InfoFromPassword(&mschap, password_tmp))
  1563. {
  1564. // Because the server don't know the NTLM hashed password, the bet to the possibility of
  1565. // the same character to the user name and empty, search a password of different
  1566. // versions of the upper and lower case characters in the case of anonymous authentication.
  1567. // Returns the MS-CHAPv2 response by using the password if there is a match.
  1568. // Fail the authentication if no match is found.
  1569. // (Because, if return a false MS-CHAPv2 Response, PPP client cause an error)
  1570. LIST *o = NewListFast(NULL);
  1571. char tmp1[MAX_SIZE];
  1572. char tmp2[MAX_SIZE];
  1573. char tmp3[MAX_SIZE];
  1574. char tmp4[MAX_SIZE];
  1575. char *response_pw;
  1576. char psk[MAX_SIZE];
  1577. ParseNtUsername(mschap.MsChapV2_PPPUsername, tmp1, sizeof(tmp1), tmp2, sizeof(tmp2), false);
  1578. ParseNtUsername(mschap.MsChapV2_PPPUsername, tmp3, sizeof(tmp3), tmp4, sizeof(tmp4), true);
  1579. Add(o, "");
  1580. Add(o, "-");
  1581. Add(o, ".");
  1582. Add(o, "*");
  1583. Add(o, "?");
  1584. Add(o, " ");
  1585. Add(o, "p");
  1586. Add(o, "guest");
  1587. Add(o, "anony");
  1588. Add(o, "anonymouse");
  1589. Add(o, "password");
  1590. Add(o, "passwd");
  1591. Add(o, "pass");
  1592. Add(o, "pw");
  1593. Add(o, mschap.MsChapV2_PPPUsername);
  1594. Add(o, tmp1);
  1595. Add(o, tmp2);
  1596. Add(o, tmp3);
  1597. Add(o, tmp4);
  1598. Zero(psk, sizeof(psk));
  1599. if (c->Cedar->Server != NULL)
  1600. {
  1601. SERVER *s = c->Cedar->Server;
  1602. if (s->IPsecServer != NULL)
  1603. {
  1604. StrCpy(psk, sizeof(psk), s->IPsecServer->Services.IPsec_Secret);
  1605. Add(o, psk);
  1606. }
  1607. }
  1608. response_pw = MsChapV2DoBruteForce(&mschap, o);
  1609. ReleaseList(o);
  1610. if (response_pw != NULL)
  1611. {
  1612. UCHAR challenge8[8];
  1613. UCHAR nt_hash[16];
  1614. UCHAR nt_hash_hash[16];
  1615. GenerateNtPasswordHash(nt_hash, response_pw);
  1616. GenerateNtPasswordHashHash(nt_hash_hash, nt_hash);
  1617. MsChapV2_GenerateChallenge8(challenge8, mschap.MsChapV2_ClientChallenge, mschap.MsChapV2_ServerChallenge,
  1618. mschap.MsChapV2_PPPUsername);
  1619. MsChapV2Server_GenerateResponse(mschap_v2_server_response_20, nt_hash_hash,
  1620. mschap.MsChapV2_ClientResponse, challenge8);
  1621. Free(response_pw);
  1622. }
  1623. else
  1624. {
  1625. auth_ret = false;
  1626. }
  1627. }
  1628. }
  1629. if (auth_ret)
  1630. {
  1631. // User authentication success by anonymous authentication
  1632. HLog(hub, "LH_AUTH_OK", c->Name, username);
  1633. is_empty_password = true;
  1634. }
  1635. }
  1636. if (auth_ret == false)
  1637. {
  1638. // Attempt other authentication methods if anonymous authentication fails
  1639. switch (authtype)
  1640. {
  1641. case CLIENT_AUTHTYPE_ANONYMOUS:
  1642. // Anonymous authentication (this have been already attempted)
  1643. break;
  1644. case AUTHTYPE_TICKET:
  1645. // Ticket authentication
  1646. if (PackGetDataSize(p, "ticket") == SHA1_SIZE)
  1647. {
  1648. PackGetData(p, "ticket", ticket);
  1649. auth_ret = SiCheckTicket(hub, ticket, username, sizeof(username), username_real, sizeof(username_real),
  1650. &ticketed_policy, sessionname, sizeof(sessionname), groupname, sizeof(groupname));
  1651. }
  1652. break;
  1653. case CLIENT_AUTHTYPE_PASSWORD:
  1654. // Password authentication
  1655. if (PackGetDataSize(p, "secure_password") == SHA1_SIZE)
  1656. {
  1657. POLICY *pol = NULL;
  1658. UCHAR secure_password[SHA1_SIZE];
  1659. Zero(secure_password, sizeof(secure_password));
  1660. if (PackGetDataSize(p, "secure_password") == SHA1_SIZE)
  1661. {
  1662. PackGetData(p, "secure_password", secure_password);
  1663. }
  1664. auth_ret = SamAuthUserByPassword(hub, username, c->Random, secure_password, NULL, NULL, NULL);
  1665. pol = SamGetUserPolicy(hub, username);
  1666. if (pol != NULL)
  1667. {
  1668. no_save_password = pol->NoSavePassword;
  1669. Free(pol);
  1670. }
  1671. if(auth_ret){
  1672. // Check whether the password was empty
  1673. UCHAR hashed_empty_password[SHA1_SIZE];
  1674. UCHAR secure_empty_password[SHA1_SIZE];
  1675. HashPassword(hashed_empty_password, username, "");
  1676. SecurePassword(secure_empty_password, hashed_empty_password, c->Random);
  1677. if(Cmp(secure_password, secure_empty_password, SHA1_SIZE)==0){
  1678. is_empty_password = true;
  1679. }
  1680. }
  1681. }
  1682. break;
  1683. case CLIENT_AUTHTYPE_PLAIN_PASSWORD:
  1684. {
  1685. POLICY *pol = NULL;
  1686. // Plaintext password authentication
  1687. Zero(plain_password, sizeof(plain_password));
  1688. PackGetStr(p, "plain_password", plain_password, sizeof(plain_password));
  1689. if (c->IsInProc == false && StartWith(plain_password, IPC_PASSWORD_MSCHAPV2_TAG))
  1690. {
  1691. // Do not allow the MS-CHAPv2 authentication other than IPC sessions
  1692. Zero(plain_password, sizeof(plain_password));
  1693. }
  1694. if (auth_ret == false)
  1695. {
  1696. // Attempt a password authentication of normal user
  1697. UCHAR secure_password[SHA1_SIZE];
  1698. UCHAR hash_password[SHA1_SIZE];
  1699. bool is_mschap = StartWith(plain_password, IPC_PASSWORD_MSCHAPV2_TAG);
  1700. HashPassword(hash_password, username, plain_password);
  1701. SecurePassword(secure_password, hash_password, c->Random);
  1702. if (is_mschap == false)
  1703. {
  1704. auth_ret = SamAuthUserByPassword(hub, username, c->Random, secure_password, NULL, NULL, NULL);
  1705. }
  1706. else
  1707. {
  1708. auth_ret = SamAuthUserByPassword(hub, username, c->Random, secure_password,
  1709. plain_password, mschap_v2_server_response_20, &ms_chap_error);
  1710. }
  1711. if (auth_ret && pol == NULL)
  1712. {
  1713. pol = SamGetUserPolicy(hub, username);
  1714. }
  1715. }
  1716. if (auth_ret == false)
  1717. {
  1718. // Attempt external authentication registered users
  1719. bool fail_ext_user_auth = false;
  1720. if (GetGlobalServerFlag(GSF_DISABLE_RADIUS_AUTH) != 0)
  1721. {
  1722. fail_ext_user_auth = true;
  1723. }
  1724. if (fail_ext_user_auth == false)
  1725. {
  1726. auth_ret = SamAuthUserByPlainPassword(c, hub, username, plain_password, false, mschap_v2_server_response_20, &radius_login_opt);
  1727. }
  1728. if (auth_ret && pol == NULL)
  1729. {
  1730. pol = SamGetUserPolicy(hub, username);
  1731. }
  1732. }
  1733. if (auth_ret == false)
  1734. {
  1735. // Attempt external authentication asterisk user
  1736. bool b = false;
  1737. bool fail_ext_user_auth = false;
  1738. if (GetGlobalServerFlag(GSF_DISABLE_RADIUS_AUTH) != 0)
  1739. {
  1740. fail_ext_user_auth = true;
  1741. }
  1742. if (fail_ext_user_auth == false)
  1743. {
  1744. AcLock(hub);
  1745. {
  1746. b = AcIsUser(hub, "*");
  1747. }
  1748. AcUnlock(hub);
  1749. // If there is asterisk user, log on as the user
  1750. if (b)
  1751. {
  1752. auth_ret = SamAuthUserByPlainPassword(c, hub, username, plain_password, true, mschap_v2_server_response_20, &radius_login_opt);
  1753. if (auth_ret && pol == NULL)
  1754. {
  1755. pol = SamGetUserPolicy(hub, "*");
  1756. }
  1757. }
  1758. }
  1759. }
  1760. if (pol != NULL)
  1761. {
  1762. no_save_password = pol->NoSavePassword;
  1763. Free(pol);
  1764. }
  1765. if(auth_ret){
  1766. // Check whether the password was empty
  1767. if(IsEmptyStr(plain_password)){
  1768. is_empty_password = true;
  1769. }
  1770. }
  1771. }
  1772. break;
  1773. case CLIENT_AUTHTYPE_CERT:
  1774. if (GetGlobalServerFlag(GSF_DISABLE_CERT_AUTH) == 0)
  1775. {
  1776. // Certificate authentication
  1777. cert_size = PackGetDataSize(p, "cert");
  1778. if (cert_size >= 1 && cert_size <= 100000)
  1779. {
  1780. cert_buf = ZeroMalloc(cert_size);
  1781. if (PackGetData(p, "cert", cert_buf))
  1782. {
  1783. UCHAR sign[4096 / 8];
  1784. UINT sign_size = PackGetDataSize(p, "sign");
  1785. if (sign_size <= sizeof(sign) && sign_size >= 1)
  1786. {
  1787. if (PackGetData(p, "sign", sign))
  1788. {
  1789. BUF *b = NewBuf();
  1790. X *x;
  1791. WriteBuf(b, cert_buf, cert_size);
  1792. x = BufToX(b, false);
  1793. if (x != NULL && x->is_compatible_bit &&
  1794. sign_size == (x->bits / 8))
  1795. {
  1796. K *k = GetKFromX(x);
  1797. // Verify the signature received from the client
  1798. if (RsaVerifyEx(c->Random, SHA1_SIZE, sign, k, x->bits))
  1799. {
  1800. // Confirmed that the client has had this certificate
  1801. // certainly because the signature matched.
  1802. // Check whether the certificate is valid.
  1803. auth_ret = SamAuthUserByCert(hub, username, x);
  1804. if (auth_ret)
  1805. {
  1806. // Copy the certificate
  1807. c->ClientX = CloneX(x);
  1808. }
  1809. }
  1810. else
  1811. {
  1812. // Authentication failure
  1813. }
  1814. FreeK(k);
  1815. }
  1816. FreeX(x);
  1817. FreeBuf(b);
  1818. }
  1819. }
  1820. }
  1821. Free(cert_buf);
  1822. }
  1823. }
  1824. else
  1825. {
  1826. // Certificate authentication is not supported in the open source version
  1827. HLog(hub, "LH_AUTH_CERT_NOT_SUPPORT_ON_OPEN_SOURCE", c->Name, username);
  1828. Unlock(hub->lock);
  1829. ReleaseHub(hub);
  1830. FreePack(p);
  1831. c->Err = ERR_AUTHTYPE_NOT_SUPPORTED;
  1832. goto CLEANUP;
  1833. }
  1834. break;
  1835. default:
  1836. // Unknown authentication method
  1837. Unlock(hub->lock);
  1838. ReleaseHub(hub);
  1839. FreePack(p);
  1840. c->Err = ERR_AUTHTYPE_NOT_SUPPORTED;
  1841. error_detail = "ERR_AUTHTYPE_NOT_SUPPORTED";
  1842. goto CLEANUP;
  1843. }
  1844. if (auth_ret == false)
  1845. {
  1846. // Authentication failure
  1847. HLog(hub, "LH_AUTH_NG", c->Name, username);
  1848. }
  1849. else
  1850. {
  1851. // Authentication success
  1852. HLog(hub, "LH_AUTH_OK", c->Name, username);
  1853. }
  1854. }
  1855. if (auth_ret == false)
  1856. {
  1857. // Authentication failure
  1858. Unlock(hub->lock);
  1859. ReleaseHub(hub);
  1860. FreePack(p);
  1861. c->Err = ERR_AUTH_FAILED;
  1862. if (ms_chap_error != 0)
  1863. {
  1864. c->Err = ms_chap_error;
  1865. }
  1866. error_detail = "ERR_AUTH_FAILED";
  1867. goto CLEANUP;
  1868. }
  1869. else
  1870. {
  1871. if(is_empty_password)
  1872. {
  1873. SOCK *s = c->FirstSock;
  1874. if (s != NULL && s->RemoteIP.addr[0] != 127)
  1875. {
  1876. if(StrCmpi(username, ADMINISTRATOR_USERNAME) == 0 ||
  1877. GetHubAdminOption(hub, "deny_empty_password") != 0)
  1878. {
  1879. // When the password is empty, remote connection is not acceptable
  1880. HLog(hub, "LH_LOCAL_ONLY", c->Name, username);
  1881. Unlock(hub->lock);
  1882. ReleaseHub(hub);
  1883. FreePack(p);
  1884. c->Err = ERR_NULL_PASSWORD_LOCAL_ONLY;
  1885. error_detail = "ERR_NULL_PASSWORD_LOCAL_ONLY";
  1886. goto CLEANUP;
  1887. }
  1888. }
  1889. }
  1890. }
  1891. policy = NULL;
  1892. // Authentication success
  1893. FreePack(p);
  1894. // Check the assigned VLAN ID
  1895. if (radius_login_opt.Out_IsRadiusLogin)
  1896. {
  1897. if (radius_login_opt.In_CheckVLanId)
  1898. {
  1899. if (radius_login_opt.Out_VLanId != 0)
  1900. {
  1901. assigned_vlan_id = radius_login_opt.Out_VLanId;
  1902. }
  1903. if (radius_login_opt.In_DenyNoVlanId && assigned_vlan_id == 0 || assigned_vlan_id >= 4096)
  1904. {
  1905. // Deny this session
  1906. Unlock(hub->lock);
  1907. ReleaseHub(hub);
  1908. c->Err = ERR_ACCESS_DENIED;
  1909. error_detail = "In_DenyNoVlanId";
  1910. goto CLEANUP;
  1911. }
  1912. }
  1913. }
  1914. if (StrCmpi(username, ADMINISTRATOR_USERNAME) != 0)
  1915. {
  1916. // Get the policy
  1917. if (farm_member == false)
  1918. {
  1919. // In the case of not a farm member
  1920. user = AcGetUser(hub, username);
  1921. if (user == NULL)
  1922. {
  1923. user = AcGetUser(hub, "*");
  1924. if (user == NULL)
  1925. {
  1926. // User acquisition failure
  1927. Unlock(hub->lock);
  1928. ReleaseHub(hub);
  1929. c->Err = ERR_ACCESS_DENIED;
  1930. error_detail = "AcGetUser";
  1931. goto CLEANUP;
  1932. }
  1933. }
  1934. policy = NULL;
  1935. Lock(user->lock);
  1936. {
  1937. // Get the expiration date
  1938. user_expires = user->ExpireTime;
  1939. StrCpy(username_real, sizeof(username_real), user->Name);
  1940. group = user->Group;
  1941. if (group != NULL)
  1942. {
  1943. AddRef(group->ref);
  1944. Lock(group->lock);
  1945. {
  1946. // Get the group name
  1947. StrCpy(groupname, sizeof(groupname), group->Name);
  1948. }
  1949. Unlock(group->lock);
  1950. }
  1951. if (user->Policy != NULL)
  1952. {
  1953. policy = ClonePolicy(user->Policy);
  1954. }
  1955. else
  1956. {
  1957. if (group)
  1958. {
  1959. Lock(group->lock);
  1960. {
  1961. if (group->Policy != NULL)
  1962. {
  1963. policy = ClonePolicy(group->Policy);
  1964. }
  1965. }
  1966. Unlock(group->lock);
  1967. }
  1968. }
  1969. if (group != NULL)
  1970. {
  1971. ReleaseGroup(group);
  1972. }
  1973. }
  1974. Unlock(user->lock);
  1975. loggedin_user_object = user;
  1976. }
  1977. else
  1978. {
  1979. // In the case of farm member
  1980. policy = ClonePolicy(&ticketed_policy);
  1981. }
  1982. }
  1983. else
  1984. {
  1985. // Administrator mode
  1986. admin_mode = true;
  1987. StrCpy(username_real, sizeof(username_real), ADMINISTRATOR_USERNAME);
  1988. policy = ClonePolicy(GetDefaultPolicy());
  1989. policy->NoBroadcastLimiter = true;
  1990. policy->MonitorPort = true;
  1991. }
  1992. if (policy == NULL)
  1993. {
  1994. // Use the default policy
  1995. policy = ClonePolicy(GetDefaultPolicy());
  1996. }
  1997. if (policy->MaxConnection == 0)
  1998. {
  1999. policy->MaxConnection = MAX_TCP_CONNECTION;
  2000. }
  2001. if (policy->TimeOut == 0)
  2002. {
  2003. policy->TimeOut = 20;
  2004. }
  2005. if (qos)
  2006. {
  2007. // VoIP / QoS
  2008. if (policy->NoQoS)
  2009. {
  2010. // Policy does not allow QoS
  2011. qos = false;
  2012. }
  2013. if (GetServerCapsBool(c->Cedar->Server, "b_support_qos") == false)
  2014. {
  2015. // Server does not support QoS
  2016. qos = false;
  2017. policy->NoQoS = true;
  2018. }
  2019. if (GetHubAdminOption(hub, "deny_qos") != 0)
  2020. {
  2021. // It is prohibited in the management options
  2022. qos = false;
  2023. policy->NoQoS = true;
  2024. }
  2025. }
  2026. if (GetHubAdminOption(hub, "max_bitrates_download") != 0)
  2027. {
  2028. if (policy->MaxDownload == 0)
  2029. {
  2030. policy->MaxDownload = GetHubAdminOption(hub, "max_bitrates_download");
  2031. }
  2032. else
  2033. {
  2034. UINT r = GetHubAdminOption(hub, "max_bitrates_download");
  2035. policy->MaxDownload = MIN(policy->MaxDownload, r);
  2036. }
  2037. }
  2038. if (GetHubAdminOption(hub, "max_bitrates_upload") != 0)
  2039. {
  2040. if (policy->MaxUpload == 0)
  2041. {
  2042. policy->MaxUpload = GetHubAdminOption(hub, "max_bitrates_upload");
  2043. }
  2044. else
  2045. {
  2046. UINT r = GetHubAdminOption(hub, "max_bitrates_upload");
  2047. policy->MaxUpload = MIN(policy->MaxUpload, r);
  2048. }
  2049. }
  2050. if (GetHubAdminOption(hub, "deny_bridge") != 0)
  2051. {
  2052. policy->NoBridge = true;
  2053. }
  2054. if (GetHubAdminOption(hub, "deny_routing") != 0)
  2055. {
  2056. policy->NoRouting = true;
  2057. }
  2058. if (c->IsInProc)
  2059. {
  2060. policy->NoBridge = false;
  2061. policy->NoRouting = false;
  2062. }
  2063. if (hub->Option->ClientMinimumRequiredBuild > c->ClientBuild &&
  2064. InStrEx(c->ClientStr, "client", false))
  2065. {
  2066. // Build number of the client is too small
  2067. HLog(hub, "LH_CLIENT_VERSION_OLD", c->Name, c->ClientBuild, hub->Option->ClientMinimumRequiredBuild);
  2068. Unlock(hub->lock);
  2069. ReleaseHub(hub);
  2070. c->Err = ERR_VERSION_INVALID;
  2071. Free(policy);
  2072. error_detail = "ERR_VERSION_INVALID";
  2073. goto CLEANUP;
  2074. }
  2075. if (hub->Option->RequiredClientId != 0 &&
  2076. hub->Option->RequiredClientId != client_id &&
  2077. InStrEx(c->ClientStr, "client", false))
  2078. {
  2079. // Build number of the client is too small
  2080. HLog(hub, "LH_CLIENT_ID_REQUIRED", c->Name, client_id, hub->Option->RequiredClientId);
  2081. Unlock(hub->lock);
  2082. ReleaseHub(hub);
  2083. c->Err = ERR_CLIENT_ID_REQUIRED;
  2084. error_detail = "ERR_CLIENT_ID_REQUIRED";
  2085. Free(policy);
  2086. goto CLEANUP;
  2087. }
  2088. if ((policy->NoSavePassword) || (policy->AutoDisconnect != 0))
  2089. {
  2090. if (c->ClientBuild < 6560 && InStrEx(c->ClientStr, "client", false))
  2091. {
  2092. // If NoSavePassword policy is specified,
  2093. // only supported client can connect
  2094. HLog(hub, "LH_CLIENT_VERSION_OLD", c->Name, c->ClientBuild, 6560);
  2095. Unlock(hub->lock);
  2096. ReleaseHub(hub);
  2097. c->Err = ERR_VERSION_INVALID;
  2098. error_detail = "ERR_VERSION_INVALID";
  2099. Free(policy);
  2100. goto CLEANUP;
  2101. }
  2102. }
  2103. if (user_expires != 0 && user_expires <= SystemTime64())
  2104. {
  2105. // User expired
  2106. HLog(hub, "LH_USER_EXPIRES", c->Name, username);
  2107. Unlock(hub->lock);
  2108. ReleaseHub(hub);
  2109. c->Err = ERR_ACCESS_DENIED;
  2110. error_detail = "LH_USER_EXPIRES";
  2111. Free(policy);
  2112. goto CLEANUP;
  2113. }
  2114. if (policy->Access == false)
  2115. {
  2116. // Access is denied
  2117. HLog(hub, "LH_POLICY_ACCESS_NG", c->Name, username);
  2118. Unlock(hub->lock);
  2119. ReleaseHub(hub);
  2120. error_detail = "LH_POLICY_ACCESS_NG";
  2121. c->Err = ERR_ACCESS_DENIED;
  2122. Free(policy);
  2123. goto CLEANUP;
  2124. }
  2125. // Determine the contents of the policy by comparing to
  2126. // option presented by client or deny the connection.
  2127. // Confirm the connectivity in the monitor-mode first
  2128. if (require_monitor_mode && policy->MonitorPort == false)
  2129. {
  2130. // Can not connect in the monitor port mode
  2131. HLog(hub, "LH_POLICY_MONITOR_MODE", c->Name);
  2132. Unlock(hub->lock);
  2133. ReleaseHub(hub);
  2134. c->Err = ERR_MONITOR_MODE_DENIED;
  2135. Free(policy);
  2136. error_detail = "ERR_MONITOR_MODE_DENIED";
  2137. goto CLEANUP;
  2138. }
  2139. if (policy->MonitorPort)
  2140. {
  2141. if (require_monitor_mode == false)
  2142. {
  2143. policy->MonitorPort = false;
  2144. }
  2145. }
  2146. if (policy->MonitorPort)
  2147. {
  2148. qos = false;
  2149. }
  2150. // Determine whether it can be connected by a bridge / routing mode next
  2151. if (require_bridge_routing_mode &&
  2152. (policy->NoBridge && policy->NoRouting))
  2153. {
  2154. // Can not be connected by a bridge / routing mode
  2155. HLog(hub, "LH_POLICY_BRIDGE_MODE", c->Name);
  2156. Unlock(hub->lock);
  2157. ReleaseHub(hub);
  2158. c->Err = ERR_BRIDGE_MODE_DENIED;
  2159. error_detail = "ERR_BRIDGE_MODE_DENIED";
  2160. Free(policy);
  2161. goto CLEANUP;
  2162. }
  2163. if (require_bridge_routing_mode == false)
  2164. {
  2165. policy->NoBridge = true;
  2166. policy->NoRouting = true;
  2167. }
  2168. if (Cmp(unique, unique2, SHA1_SIZE) == 0)
  2169. {
  2170. // It's a localhost session
  2171. local_host_session = true;
  2172. }
  2173. if (local_host_session == false)
  2174. {
  2175. // Make further judgment whether localhost session
  2176. SOCK *s = c->FirstSock;
  2177. if (s != NULL)
  2178. {
  2179. if (IsIPMyHost(&s->RemoteIP))
  2180. {
  2181. // It's a localhost session
  2182. local_host_session = true;
  2183. }
  2184. }
  2185. }
  2186. if (local_host_session)
  2187. {
  2188. // Permit routing or bridging in the case of localhost session
  2189. policy->NoBridge = false;
  2190. policy->NoRouting = false;
  2191. }
  2192. if (local_host_session == false)
  2193. {
  2194. if (policy->NoBridge == false || policy->NoRouting == false)
  2195. {
  2196. use_bridge_license = true;
  2197. }
  2198. else
  2199. {
  2200. use_client_license = true;
  2201. }
  2202. }
  2203. if (server != NULL && server->ServerType != SERVER_TYPE_FARM_MEMBER &&
  2204. policy != NULL)
  2205. {
  2206. if (GetServerCapsBool(hub->Cedar->Server, "b_support_limit_multilogin"))
  2207. {
  2208. // Check if the number of concurrent multiple logins limit is specified in the policy
  2209. RPC_ENUM_SESSION t;
  2210. UINT i, num;
  2211. UINT max_logins = policy->MultiLogins;
  2212. UINT ao = GetHubAdminOption(hub, "max_multilogins_per_user");
  2213. if (ao != 0)
  2214. {
  2215. if (max_logins != 0)
  2216. {
  2217. max_logins = MIN(max_logins, ao);
  2218. }
  2219. else
  2220. {
  2221. max_logins = ao;
  2222. }
  2223. }
  2224. if (max_logins != 0)
  2225. {
  2226. Zero(&t, sizeof(t));
  2227. StrCpy(t.HubName, sizeof(t.HubName), hub->Name);
  2228. Unlock(hub->lock);
  2229. SiEnumSessionMain(server, &t);
  2230. Lock(hub->lock);
  2231. num = 0;
  2232. for (i = 0;i < t.NumSession;i++)
  2233. {
  2234. RPC_ENUM_SESSION_ITEM *e = &t.Sessions[i];
  2235. if (e->BridgeMode == false && e->Layer3Mode == false && e->LinkMode == false && e->CurrentNumTcp != 0)
  2236. {
  2237. if (StrCmpi(e->Username, username) == 0 &&
  2238. (IsZero(e->UniqueId, 16) || Cmp(e->UniqueId, node.UniqueId, 16) != 0))
  2239. {
  2240. num++;
  2241. }
  2242. }
  2243. }
  2244. FreeRpcEnumSession(&t);
  2245. if (num >= max_logins)
  2246. {
  2247. // Can not connect any more
  2248. Unlock(hub->lock);
  2249. // Dump a detailed error log
  2250. HLog(hub, "LH_TOO_MANY_MULTILOGINS",
  2251. c->Name,
  2252. username, max_logins, num);
  2253. ReleaseHub(hub);
  2254. c->Err = ERR_TOO_MANY_USER_SESSION;
  2255. Free(policy);
  2256. goto CLEANUP;
  2257. }
  2258. }
  2259. }
  2260. }
  2261. if (loggedin_user_object != NULL)
  2262. {
  2263. // Update the user information
  2264. Lock(loggedin_user_object->lock);
  2265. {
  2266. loggedin_user_object->LastLoginTime = SystemTime64();
  2267. }
  2268. Unlock(loggedin_user_object->lock);
  2269. }
  2270. // Update the number of log-ins
  2271. hub->LastCommTime = hub->LastLoginTime = SystemTime64();
  2272. if (farm_controller)
  2273. {
  2274. wchar_t *msg = GetHubMsg(hub);
  2275. Unlock(hub->lock);
  2276. Lock(cedar->CedarSuperLock);
  2277. // In the case of farm controller, choose a farm members to host this HUB
  2278. LockList(server->FarmMemberList);
  2279. {
  2280. HLog(hub, "LH_FARM_SELECT_1", c->Name);
  2281. f = SiGetHubHostingMember(server, hub, admin_mode, c);
  2282. if (f == NULL)
  2283. {
  2284. // Failed in the selection
  2285. HLog(hub, "LH_FARM_SELECT_2", c->Name);
  2286. UnlockList(server->FarmMemberList);
  2287. Unlock(cedar->CedarSuperLock);
  2288. ReleaseHub(hub);
  2289. c->Err = ERR_COULD_NOT_HOST_HUB_ON_FARM;
  2290. Free(policy);
  2291. Free(msg);
  2292. goto CLEANUP;
  2293. }
  2294. else
  2295. {
  2296. if (f->Me == false)
  2297. {
  2298. UCHAR ticket[SHA1_SIZE];
  2299. PACK *p;
  2300. BUF *b;
  2301. UINT i;
  2302. SLog(c->Cedar, "LH_FARM_SELECT_4", c->Name, f->hostname);
  2303. // Create a session on the selected server farm member
  2304. Rand(ticket, sizeof(ticket));
  2305. SiCallCreateTicket(server, f, hub->Name,
  2306. username, username_real, policy, ticket, Inc(hub->SessionCounter), groupname);
  2307. p = NewPack();
  2308. PackAddInt(p, "Redirect", 1);
  2309. PackAddIp32(p, "Ip", f->Ip);
  2310. for (i = 0;i < f->NumPort;i++)
  2311. {
  2312. PackAddIntEx(p, "Port", f->Ports[i], i, f->NumPort);
  2313. }
  2314. PackAddData(p, "Ticket", ticket, sizeof(ticket));
  2315. if (true)
  2316. {
  2317. char *utf = CopyUniToUtf(msg);
  2318. PackAddData(p, "Msg", utf, StrLen(utf));
  2319. Free(utf);
  2320. }
  2321. b = XToBuf(f->ServerCert, false);
  2322. PackAddBuf(p, "Cert", b);
  2323. FreeBuf(b);
  2324. UnlockList(server->FarmMemberList);
  2325. Unlock(cedar->CedarSuperLock);
  2326. ReleaseHub(hub);
  2327. HttpServerSend(c->FirstSock, p);
  2328. FreePack(p);
  2329. c->Err = 0;
  2330. Free(policy);
  2331. FreePack(HttpServerRecv(c->FirstSock));
  2332. Free(msg);
  2333. goto CLEANUP;
  2334. }
  2335. else
  2336. {
  2337. HLog(hub, "LH_FARM_SELECT_3", c->Name);
  2338. // Continue the process because myself was selected
  2339. UnlockList(server->FarmMemberList);
  2340. Unlock(cedar->CedarSuperLock);
  2341. f->Point = SiGetPoint(server);
  2342. Lock(hub->lock);
  2343. Free(msg);
  2344. }
  2345. }
  2346. }
  2347. }
  2348. if (admin_mode == false)
  2349. {
  2350. // Check the maximum number of connections of the HUB
  2351. if (hub->Option->MaxSession != 0 &&
  2352. hub->Option->MaxSession <= Count(hub->NumSessions))
  2353. {
  2354. // Can not connect any more
  2355. Unlock(hub->lock);
  2356. HLog(hub, "LH_MAX_SESSION", c->Name, hub->Option->MaxSession);
  2357. ReleaseHub(hub);
  2358. c->Err = ERR_HUB_IS_BUSY;
  2359. Free(policy);
  2360. error_detail = "ERR_HUB_IS_BUSY";
  2361. goto CLEANUP;
  2362. }
  2363. }
  2364. if (use_encrypt == false && c->FirstSock->IsReverseAcceptedSocket)
  2365. {
  2366. // On VPN Azure, SSL encryption is mandated.
  2367. use_encrypt = true;
  2368. }
  2369. if (use_client_license || use_bridge_license)
  2370. {
  2371. // Examine whether not to conflict with the limit of simultaneous connections
  2372. // number of sessions defined by the Virtual HUB management options
  2373. if (
  2374. (GetHubAdminOption(hub, "max_sessions") != 0 &&
  2375. (Count(hub->NumSessionsClient) + Count(hub->NumSessionsBridge)) >= GetHubAdminOption(hub, "max_sessions"))
  2376. ||
  2377. (hub->Option->MaxSession != 0 &&
  2378. (Count(hub->NumSessionsClient) + Count(hub->NumSessionsBridge)) >= hub->Option->MaxSession))
  2379. {
  2380. // Can not connect any more
  2381. Unlock(hub->lock);
  2382. HLog(hub, "LH_MAX_SESSION", c->Name, GetHubAdminOption(hub, "max_sessions"));
  2383. ReleaseHub(hub);
  2384. c->Err = ERR_HUB_IS_BUSY;
  2385. Free(policy);
  2386. goto CLEANUP;
  2387. }
  2388. }
  2389. if (use_client_license)
  2390. {
  2391. // Examine whether not to conflict with the limit of simultaneous connections
  2392. // number of sessions(client) defined by the Virtual HUB management options
  2393. if (((GetHubAdminOption(hub, "max_sessions_client_bridge_apply") != 0
  2394. ) &&
  2395. Count(hub->NumSessionsClient) >= GetHubAdminOption(hub, "max_sessions_client") && hub->Cedar->Server != NULL && hub->Cedar->Server->ServerType != SERVER_TYPE_FARM_MEMBER)
  2396. ||
  2397. (hub->FarmMember_MaxSessionClientBridgeApply &&
  2398. Count(hub->NumSessionsClient) >= hub->FarmMember_MaxSessionClient))
  2399. {
  2400. // Can not connect any more
  2401. Unlock(hub->lock);
  2402. HLog(hub, "LH_MAX_SESSION_CLIENT", c->Name, GetHubAdminOption(hub, "max_sessions_client"));
  2403. ReleaseHub(hub);
  2404. c->Err = ERR_HUB_IS_BUSY;
  2405. Free(policy);
  2406. goto CLEANUP;
  2407. }
  2408. }
  2409. if (use_bridge_license)
  2410. {
  2411. // Examine whether not to conflict with the limit of simultaneous connections
  2412. // number of sessions(bridge) defined by the Virtual HUB management options
  2413. if (((GetHubAdminOption(hub, "max_sessions_client_bridge_apply") != 0
  2414. ) &&
  2415. Count(hub->NumSessionsBridge) >= GetHubAdminOption(hub, "max_sessions_bridge") && hub->Cedar->Server != NULL && hub->Cedar->Server->ServerType != SERVER_TYPE_FARM_MEMBER)
  2416. ||
  2417. (hub->FarmMember_MaxSessionClientBridgeApply &&
  2418. Count(hub->NumSessionsBridge) >= hub->FarmMember_MaxSessionBridge))
  2419. {
  2420. // Can not connect any more
  2421. Unlock(hub->lock);
  2422. HLog(hub, "LH_MAX_SESSION_BRIDGE", c->Name, GetHubAdminOption(hub, "max_sessions_bridge"));
  2423. ReleaseHub(hub);
  2424. c->Err = ERR_HUB_IS_BUSY;
  2425. Free(policy);
  2426. goto CLEANUP;
  2427. }
  2428. }
  2429. if (Count(hub->Cedar->CurrentSessions) >= GetServerCapsInt(hub->Cedar->Server, "i_max_sessions"))
  2430. {
  2431. // Can not connect any more
  2432. Unlock(hub->lock);
  2433. HLog(hub, "LH_MAX_SESSION_2", c->Name, GetServerCapsInt(hub->Cedar->Server, "i_max_sessions"));
  2434. ReleaseHub(hub);
  2435. c->Err = ERR_HUB_IS_BUSY;
  2436. Free(policy);
  2437. goto CLEANUP;
  2438. }
  2439. // Increment the current number of connections
  2440. Inc(hub->NumSessions);
  2441. if (use_bridge_license)
  2442. {
  2443. Inc(hub->NumSessionsBridge);
  2444. }
  2445. if (use_client_license)
  2446. {
  2447. Inc(hub->NumSessionsClient);
  2448. }
  2449. Inc(hub->Cedar->CurrentSessions);
  2450. // Calculate the time-out period
  2451. timeout = policy->TimeOut * 1000; // Convert milliseconds to seconds
  2452. if (timeout == 0)
  2453. {
  2454. timeout = TIMEOUT_DEFAULT;
  2455. }
  2456. timeout = MIN(timeout, TIMEOUT_MAX);
  2457. timeout = MAX(timeout, TIMEOUT_MIN);
  2458. // Update the max_connection according to the policy
  2459. max_connection = MIN(max_connection, policy->MaxConnection);
  2460. max_connection = MIN(max_connection, MAX_TCP_CONNECTION);
  2461. max_connection = MAX(max_connection, 1);
  2462. if (c->FirstSock->IsRUDPSocket)
  2463. {
  2464. // In the case of TCP-over-UDP
  2465. half_connection = false;
  2466. // Disable the QoS
  2467. qos = false;
  2468. if (enable_udp_recovery == false)
  2469. {
  2470. // Disable the session reconnection feature
  2471. no_reconnect_to_session = true;
  2472. max_connection = 1;
  2473. }
  2474. else
  2475. {
  2476. // If the UDP recovery is enabled, permit the session re-connection feature (for 2)
  2477. no_reconnect_to_session = false;
  2478. max_connection = NUM_TCP_CONNECTION_FOR_UDP_RECOVERY;
  2479. }
  2480. }
  2481. if (half_connection)
  2482. {
  2483. // Number of connections should be more than 2 in the case of Half Connection
  2484. max_connection = MAX(max_connection, 2);
  2485. }
  2486. if (qos)
  2487. {
  2488. // Number of connections is set to 2 or more when using the VoIP / QoS
  2489. max_connection = MAX(max_connection, 2);
  2490. if (half_connection)
  2491. {
  2492. max_connection = MAX(max_connection, 4);
  2493. }
  2494. }
  2495. c->Status = CONNECTION_STATUS_ESTABLISHED;
  2496. // Remove the connection from Cedar
  2497. DelConnection(c->Cedar, c);
  2498. // VLAN ID
  2499. if (assigned_vlan_id != 0)
  2500. {
  2501. if (policy != NULL)
  2502. {
  2503. if (policy->VLanId == 0)
  2504. {
  2505. policy->VLanId = assigned_vlan_id;
  2506. }
  2507. }
  2508. }
  2509. // Create a Session
  2510. StrLower(username);
  2511. s = NewServerSessionEx(c->Cedar, c, hub, username, policy, c->IsInProc);
  2512. s->EnableUdpRecovery = enable_udp_recovery;
  2513. s->LocalHostSession = local_host_session;
  2514. s->NormalClient = true;
  2515. IPToStr(s->ClientIP, sizeof(s->ClientIP), &c->ClientIp);
  2516. if (c->FirstSock->IsRUDPSocket)
  2517. {
  2518. // R-UDP session
  2519. s->IsRUDPSession = true;
  2520. s->RUdpMss = c->FirstSock->RUDP_OptimizedMss;
  2521. Debug("Optimized MSS Value for R-UDP: %u\n", s->RUdpMss);
  2522. }
  2523. if (enable_bulk_on_rudp)
  2524. {
  2525. // Allow bulk transfer on R-UDP
  2526. s->EnableBulkOnRUDP = true;
  2527. s->EnableHMacOnBulkOfRUDP = enable_hmac_on_bulk_of_rudp;
  2528. }
  2529. s->IsAzureSession = c->FirstSock->IsReverseAcceptedSocket;
  2530. StrCpy(s->UnderlayProtocol, sizeof(s->UnderlayProtocol), c->FirstSock->UnderlayProtocol);
  2531. if (server != NULL)
  2532. {
  2533. s->NoSendSignature = server->NoSendSignature;
  2534. }
  2535. if (c->IsInProc)
  2536. {
  2537. s->NoSendSignature = true;
  2538. }
  2539. if (c->IsInProc && StrCmpi(c->InProcPrefix, OPENVPN_IPC_POSTFIX_L3) == 0)
  2540. {
  2541. // OpenVPN L3 session
  2542. s->IsOpenVPNL3Session = true;
  2543. }
  2544. if (c->IsInProc && StrCmpi(c->InProcPrefix, OPENVPN_IPC_POSTFIX_L2) == 0)
  2545. {
  2546. // OpenVPN L2 session
  2547. s->IsOpenVPNL2Session = true;
  2548. }
  2549. // Determine whether the use of UDP acceleration mode
  2550. if (use_udp_acceleration_client)
  2551. {
  2552. s->UseUdpAcceleration = true;
  2553. s->UdpAccelFastDisconnectDetect = support_udp_accel_fast_disconnect_detect;
  2554. }
  2555. if (hub->Option != NULL && hub->Option->DisableUdpAcceleration)
  2556. {
  2557. s->UseUdpAcceleration = false;
  2558. }
  2559. if (IsZeroIP(&c->FirstSock->Reverse_MyServerGlobalIp) == false &&
  2560. CmpIpAddr(&c->FirstSock->Reverse_MyServerGlobalIp, &c->FirstSock->RemoteIP) == 0)
  2561. {
  2562. // Disable forcibly the UDP acceleration mode if VPN Server and VPN Client
  2563. // are in same LAN in the case of using VPN Azure.
  2564. // (Or this may cause infinite loop of packet)
  2565. s->UseUdpAcceleration = false;
  2566. }
  2567. if (s->UseUdpAcceleration)
  2568. {
  2569. s->UseHMacOnUdpAcceleration = use_hmac_on_udp_acceleration;
  2570. }
  2571. Debug("UseUdpAcceleration = %u\n", s->UseUdpAcceleration);
  2572. Debug("UseHMacOnUdpAcceleration = %u\n", s->UseHMacOnUdpAcceleration);
  2573. if (s->UseUdpAcceleration)
  2574. {
  2575. bool no_nat_t = false;
  2576. // Initialize the UDP acceleration function
  2577. s->UdpAccel = NewUdpAccel(c->Cedar, (c->FirstSock->IsRUDPSocket ? NULL : &c->FirstSock->LocalIP), false, c->FirstSock->IsRUDPSocket, no_nat_t);
  2578. if (s->UdpAccel == NULL)
  2579. {
  2580. s->UseUdpAcceleration = false;
  2581. Debug("NewUdpAccel Failed.\n");
  2582. }
  2583. else
  2584. {
  2585. if (UdpAccelInitServer(s->UdpAccel, udp_acceleration_client_key, &udp_acceleration_client_ip, udp_acceleration_client_port,
  2586. &c->FirstSock->RemoteIP) == false)
  2587. {
  2588. Debug("UdpAccelInitServer Failed.\n");
  2589. s->UseUdpAcceleration = false;
  2590. }
  2591. s->UdpAccel->FastDetect = s->UdpAccelFastDisconnectDetect;
  2592. if (use_encrypt == false)
  2593. {
  2594. s->UdpAccel->PlainTextMode = true;
  2595. }
  2596. s->UdpAccel->UseHMac = s->UseHMacOnUdpAcceleration;
  2597. }
  2598. }
  2599. s->UseClientLicense = use_client_license;
  2600. s->UseBridgeLicense = use_bridge_license;
  2601. s->AdjustMss = adjust_mss;
  2602. if (s->AdjustMss != 0)
  2603. {
  2604. Debug("AdjustMSS: %u\n", s->AdjustMss);
  2605. }
  2606. s->IsBridgeMode = (policy->NoBridge == false) || (policy->NoRouting == false);
  2607. s->IsMonitorMode = policy->MonitorPort;
  2608. // Decide whether IPv6 session
  2609. s->IPv6Session = false;
  2610. if (node.ClientIpAddress == 0)
  2611. {
  2612. s->IPv6Session = true;
  2613. }
  2614. if (use_bridge_license)
  2615. {
  2616. Inc(s->Cedar->AssignedBridgeLicense);
  2617. }
  2618. if (use_client_license)
  2619. {
  2620. Inc(s->Cedar->AssignedClientLicense);
  2621. }
  2622. if (server != NULL)
  2623. {
  2624. // Update the total allocation of the number of licenses for Server structure
  2625. if (server->ServerType == SERVER_TYPE_STANDALONE)
  2626. {
  2627. // Update only stand-alone mode
  2628. // (Periodically poll in the cluster controller mode)
  2629. server->CurrentAssignedClientLicense = Count(s->Cedar->AssignedClientLicense);
  2630. server->CurrentAssignedBridgeLicense = Count(s->Cedar->AssignedBridgeLicense);
  2631. }
  2632. }
  2633. if (StrLen(sessionname) != 0)
  2634. {
  2635. // Specify the session name
  2636. Free(s->Name);
  2637. s->Name = CopyStr(sessionname);
  2638. }
  2639. {
  2640. char ip[128];
  2641. IPToStr(ip, sizeof(ip), &c->FirstSock->RemoteIP);
  2642. HLog(hub, "LH_NEW_SESSION", c->Name, s->Name, ip, c->FirstSock->RemotePort,
  2643. c->FirstSock->UnderlayProtocol);
  2644. }
  2645. c->Session = s;
  2646. s->AdministratorMode = admin_mode;
  2647. StrCpy(s->UserNameReal, sizeof(s->UserNameReal), username_real);
  2648. StrCpy(s->GroupName, sizeof(s->GroupName), groupname);
  2649. // Get the session key
  2650. Copy(session_key, s->SessionKey, SHA1_SIZE);
  2651. // Set the parameters
  2652. s->MaxConnection = max_connection;
  2653. s->UseEncrypt = use_encrypt;
  2654. if (s->UseEncrypt && use_fast_rc4)
  2655. {
  2656. s->UseFastRC4 = use_fast_rc4;
  2657. }
  2658. s->UseCompress = use_compress;
  2659. s->HalfConnection = half_connection;
  2660. s->Timeout = timeout;
  2661. s->QoS = qos;
  2662. s->NoReconnectToSession = no_reconnect_to_session;
  2663. if (policy != NULL)
  2664. {
  2665. s->VLanId = policy->VLanId;
  2666. }
  2667. // User name
  2668. s->Username = CopyStr(username);
  2669. HLog(hub, "LH_SET_SESSION", s->Name, s->MaxConnection,
  2670. s->UseEncrypt ? _UU("L_YES") : _UU("L_NO"),
  2671. s->UseCompress ? _UU("L_YES") : _UU("L_NO"),
  2672. s->HalfConnection ? _UU("L_YES") : _UU("L_NO"),
  2673. s->Timeout / 1000);
  2674. msg = GetHubMsg(hub);
  2675. // Suppress client update notification flag
  2676. if (hub->Option != NULL)
  2677. {
  2678. suppress_client_update_notification = hub->Option->SuppressClientUpdateNotification;
  2679. }
  2680. }
  2681. Unlock(hub->lock);
  2682. // Send a Welcome packet to the client
  2683. p = PackWelcome(s);
  2684. PackAddBool(p, "suppress_client_update_notification", suppress_client_update_notification);
  2685. if (s->InProcMode)
  2686. {
  2687. if (IsZero(mschap_v2_server_response_20, sizeof(mschap_v2_server_response_20)) == false)
  2688. {
  2689. // MS-CHAPv2 Response
  2690. PackAddData(p, "IpcMsChapV2ServerResponse", mschap_v2_server_response_20, sizeof(mschap_v2_server_response_20));
  2691. }
  2692. }
  2693. if (true)
  2694. {
  2695. // A message to be displayed in the VPN Client (Will not be displayed if the VPN Gate Virtual HUB)
  2696. char *utf;
  2697. wchar_t winver_msg_client[3800];
  2698. wchar_t winver_msg_server[3800];
  2699. UINT tmpsize;
  2700. wchar_t *tmp;
  2701. RPC_WINVER server_winver;
  2702. GetWinVer(&server_winver);
  2703. Zero(winver_msg_client, sizeof(winver_msg_client));
  2704. Zero(winver_msg_server, sizeof(winver_msg_server));
  2705. if (IsSupportedWinVer(&winver) == false)
  2706. {
  2707. SYSTEMTIME st;
  2708. LocalTime(&st);
  2709. UniFormat(winver_msg_client, sizeof(winver_msg_client), _UU("WINVER_ERROR_FORMAT"),
  2710. _UU("WINVER_ERROR_PC_LOCAL"),
  2711. winver.Title,
  2712. _UU("WINVER_ERROR_VPNSERVER"),
  2713. SUPPORTED_WINDOWS_LIST,
  2714. _UU("WINVER_ERROR_PC_LOCAL"),
  2715. _UU("WINVER_ERROR_VPNSERVER"),
  2716. _UU("WINVER_ERROR_VPNSERVER"),
  2717. _UU("WINVER_ERROR_VPNSERVER"),
  2718. st.wYear, st.wMonth);
  2719. }
  2720. if (IsSupportedWinVer(&server_winver) == false)
  2721. {
  2722. SYSTEMTIME st;
  2723. LocalTime(&st);
  2724. UniFormat(winver_msg_server, sizeof(winver_msg_server), _UU("WINVER_ERROR_FORMAT"),
  2725. _UU("WINVER_ERROR_PC_REMOTE"),
  2726. server_winver.Title,
  2727. _UU("WINVER_ERROR_VPNSERVER"),
  2728. SUPPORTED_WINDOWS_LIST,
  2729. _UU("WINVER_ERROR_PC_REMOTE"),
  2730. _UU("WINVER_ERROR_VPNSERVER"),
  2731. _UU("WINVER_ERROR_VPNSERVER"),
  2732. _UU("WINVER_ERROR_VPNSERVER"),
  2733. st.wYear, st.wMonth);
  2734. }
  2735. tmpsize = UniStrSize(winver_msg_client) + UniStrSize(winver_msg_server) + UniStrSize(msg) + (16000 + 3000) * sizeof(wchar_t);
  2736. tmp = ZeroMalloc(tmpsize);
  2737. if (IsURLMsg(msg, NULL, 0) == false)
  2738. {
  2739. if (s != NULL && s->IsRUDPSession && c != NULL && StrCmpi(hub->Name, VG_HUBNAME) != 0)
  2740. {
  2741. // Show the warning message if the connection is made by NAT-T
  2742. wchar_t *tmp2;
  2743. UINT tmp2_size = 2400 * sizeof(wchar_t);
  2744. char local_name[128];
  2745. wchar_t local_name_2[128];
  2746. char local_name_3[128];
  2747. Zero(local_name, sizeof(local_name));
  2748. Zero(local_name_2, sizeof(local_name_2));
  2749. Zero(local_name_3, sizeof(local_name_3));
  2750. GetMachineName(local_name, sizeof(local_name));
  2751. #ifdef OS_WIN32
  2752. MsGetComputerNameFullEx(local_name_2, sizeof(local_name_2), true);
  2753. UniToStr(local_name_3, sizeof(local_name_3), local_name_2);
  2754. if (IsEmptyStr(local_name_3) == false)
  2755. {
  2756. StrCpy(local_name, sizeof(local_name), local_name_3);
  2757. }
  2758. #endif // OS_WIN32
  2759. tmp2 = ZeroMalloc(tmp2_size);
  2760. UniFormat(tmp2, tmp2_size, _UU(c->ClientBuild >= 9428 ? "NATT_MSG" : "NATT_MSG2"), local_name);
  2761. UniStrCat(tmp, tmpsize, tmp2);
  2762. Free(tmp2);
  2763. }
  2764. {
  2765. if (GetGlobalServerFlag(GSF_SHOW_OSS_MSG) != 0)
  2766. {
  2767. UniStrCat(tmp, tmpsize, _UU("OSS_MSG"));
  2768. }
  2769. }
  2770. {
  2771. UniStrCat(tmp, tmpsize, winver_msg_client);
  2772. UniStrCat(tmp, tmpsize, winver_msg_server);
  2773. }
  2774. }
  2775. UniStrCat(tmp, tmpsize, msg);
  2776. utf = CopyUniToUtf(tmp);
  2777. PackAddData(p, "Msg", utf, StrLen(utf));
  2778. Free(tmp);
  2779. Free(utf);
  2780. }
  2781. Free(msg);
  2782. if (s->UseFastRC4)
  2783. {
  2784. // Generate a RC4 key pair
  2785. GenerateRC4KeyPair(&key_pair);
  2786. // Add to Welcome packet
  2787. PackAddData(p, "rc4_key_client_to_server", key_pair.ClientToServerKey, sizeof(key_pair.ClientToServerKey));
  2788. PackAddData(p, "rc4_key_server_to_client", key_pair.ServerToClientKey, sizeof(key_pair.ServerToClientKey));
  2789. {
  2790. char key1[64], key2[64];
  2791. BinToStr(key1, sizeof(key1), key_pair.ClientToServerKey, 16);
  2792. BinToStr(key2, sizeof(key2), key_pair.ServerToClientKey, 16);
  2793. Debug(
  2794. "Client to Server Key: %s\n"
  2795. "Server to Client Key: %s\n",
  2796. key1, key2);
  2797. }
  2798. }
  2799. // Brand string for the connection limit
  2800. {
  2801. char *branded_cfroms = _SS("BRANDED_C_FROM_S");
  2802. if(StrLen(branded_cfroms) > 0)
  2803. {
  2804. PackAddStr(p, "branded_cfroms", branded_cfroms);
  2805. }
  2806. }
  2807. HttpServerSend(c->FirstSock, p);
  2808. FreePack(p);
  2809. // Receive a signature
  2810. Copy(&c->Session->NodeInfo, &node, sizeof(NODE_INFO));
  2811. {
  2812. wchar_t tmp[MAX_SIZE * 2];
  2813. NodeInfoToStr(tmp, sizeof(tmp), &s->NodeInfo);
  2814. HLog(hub, "LH_NODE_INFO", s->Name, tmp);
  2815. if (s->VLanId != 0)
  2816. {
  2817. HLog(hub, "LH_VLAN_ID", s->Name, s->VLanId);
  2818. }
  2819. }
  2820. // Shift the connection to the tunneling mode
  2821. StartTunnelingMode(c);
  2822. // Processing of half-connection mode
  2823. if (s->HalfConnection)
  2824. {
  2825. // The direction of the first socket is client to server
  2826. TCPSOCK *ts = (TCPSOCK *)LIST_DATA(c->Tcp->TcpSockList, 0);
  2827. ts->Direction = TCP_CLIENT_TO_SERVER;
  2828. }
  2829. if (s->UseFastRC4)
  2830. {
  2831. // Set the RC4 key information to the first TCP connection
  2832. TCPSOCK *ts = (TCPSOCK *)LIST_DATA(c->Tcp->TcpSockList, 0);
  2833. Copy(&ts->Rc4KeyPair, &key_pair, sizeof(RC4_KEY_PAIR));
  2834. InitTcpSockRc4Key(ts, true);
  2835. }
  2836. if (s->UseEncrypt && s->UseFastRC4 == false)
  2837. {
  2838. s->UseSSLDataEncryption = true;
  2839. }
  2840. else
  2841. {
  2842. s->UseSSLDataEncryption = false;
  2843. }
  2844. if (s->Hub->Type == HUB_TYPE_FARM_DYNAMIC && s->Cedar->Server != NULL && s->Cedar->Server->ServerType == SERVER_TYPE_FARM_CONTROLLER)
  2845. {
  2846. if (s->Hub->BeingOffline == false)
  2847. {
  2848. // Start the SecureNAT on the dynamic Virtual HUB
  2849. EnableSecureNATEx(s->Hub, false, true);
  2850. cluster_dynamic_secure_nat = true;
  2851. }
  2852. }
  2853. if (s->LocalHostSession)
  2854. {
  2855. // Update the local MAC address list
  2856. RefreshLocalMacAddressList();
  2857. }
  2858. // Discard the user list cache
  2859. DeleteAllUserListCache(hub->UserList);
  2860. // Main routine of the session
  2861. Debug("SessionMain()\n");
  2862. s->NumLoginIncrementUserObject = loggedin_user_object;
  2863. s->NumLoginIncrementHubObject = s->Hub;
  2864. s->NumLoginIncrementTick = Tick64() + (UINT64)NUM_LOGIN_INCREMENT_INTERVAL;
  2865. SessionMain(s);
  2866. // Discard the user list cache
  2867. DeleteAllUserListCache(hub->UserList);
  2868. // Decrement the current number of connections
  2869. Lock(s->Hub->lock);
  2870. {
  2871. if (use_bridge_license)
  2872. {
  2873. Dec(hub->NumSessionsBridge);
  2874. }
  2875. if (use_client_license)
  2876. {
  2877. Dec(hub->NumSessionsClient);
  2878. }
  2879. Dec(s->Hub->NumSessions);
  2880. Dec(s->Hub->Cedar->CurrentSessions);
  2881. // Decrement the number of licenses
  2882. if (use_bridge_license)
  2883. {
  2884. Dec(s->Cedar->AssignedBridgeLicense);
  2885. }
  2886. if (use_client_license)
  2887. {
  2888. Dec(s->Cedar->AssignedClientLicense);
  2889. }
  2890. if (server != NULL)
  2891. {
  2892. // Update the total allocation of the number of licenses for Server structure
  2893. if (server->ServerType == SERVER_TYPE_STANDALONE)
  2894. {
  2895. // Update only stand-alone mode
  2896. // (Periodically polled in the cluster controller mode)
  2897. server->CurrentAssignedClientLicense = Count(s->Cedar->AssignedClientLicense);
  2898. server->CurrentAssignedBridgeLicense = Count(s->Cedar->AssignedBridgeLicense);
  2899. }
  2900. }
  2901. }
  2902. Unlock(s->Hub->lock);
  2903. PrintSessionTotalDataSize(s);
  2904. HLog(s->Hub, "LH_END_SESSION", s->Name, s->TotalSendSizeReal, s->TotalRecvSizeReal);
  2905. if (cluster_dynamic_secure_nat && s->Hub->BeingOffline == false)
  2906. {
  2907. // Stop the SecureNAT on the dynamic Virtual HUB
  2908. EnableSecureNATEx(s->Hub, false, true);
  2909. }
  2910. if (s->UdpAccel != NULL)
  2911. {
  2912. // Release the UDP acceleration
  2913. FreeUdpAccel(s->UdpAccel);
  2914. s->UdpAccel = NULL;
  2915. }
  2916. ReleaseSession(s);
  2917. ret = true;
  2918. c->Err = ERR_SESSION_REMOVED;
  2919. ReleaseHub(hub);
  2920. goto CLEANUP;
  2921. }
  2922. else if (StrCmpi(method, "additional_connect") == 0)
  2923. {
  2924. SOCK *sock;
  2925. TCPSOCK *ts;
  2926. UINT dummy;
  2927. c->Type = CONNECTION_TYPE_ADDITIONAL;
  2928. // Additional connection
  2929. // Read the session key
  2930. if (GetSessionKeyFromPack(p, session_key, &dummy) == false)
  2931. {
  2932. FreePack(p);
  2933. c->Err = ERR_PROTOCOL_ERROR;
  2934. goto CLEANUP;
  2935. }
  2936. FreePack(p);
  2937. // Get the session from the session key
  2938. s = GetSessionFromKey(c->Cedar, session_key);
  2939. if (s == NULL || s->Halt || s->NoReconnectToSession)
  2940. {
  2941. // Session can not be found, or re-connection is prohibited
  2942. Debug("Session Not Found.\n");
  2943. c->Err = ERR_SESSION_TIMEOUT;
  2944. goto CLEANUP;
  2945. }
  2946. // Session is found
  2947. Debug("Session Found: %s\n", s->Name);
  2948. // Check the protocol of session
  2949. c->Err = 0;
  2950. Lock(s->lock);
  2951. {
  2952. if (s->Connection->Protocol != CONNECTION_TCP)
  2953. {
  2954. c->Err = ERR_INVALID_PROTOCOL;
  2955. }
  2956. }
  2957. Unlock(s->lock);
  2958. // Check the current number of connections of the session
  2959. Lock(s->Connection->lock);
  2960. if (c->Err == 0)
  2961. {
  2962. if (Count(s->Connection->CurrentNumConnection) > s->MaxConnection)
  2963. {
  2964. c->Err = ERR_TOO_MANY_CONNECTION;
  2965. }
  2966. }
  2967. if (c->Err != 0)
  2968. {
  2969. Unlock(s->Connection->lock);
  2970. if (c->Err == ERR_TOO_MANY_CONNECTION)
  2971. {
  2972. Debug("Session TOO MANY CONNECTIONS !!: %u\n",
  2973. Count(s->Connection->CurrentNumConnection));
  2974. }
  2975. else
  2976. {
  2977. Debug("Session Invalid Protocol.\n");
  2978. }
  2979. ReleaseSession(s);
  2980. goto CLEANUP;
  2981. }
  2982. // Generate a high-speed RC4 encryption key
  2983. if (s->UseFastRC4)
  2984. {
  2985. GenerateRC4KeyPair(&key_pair);
  2986. }
  2987. // Add the socket of this connection to the connection list of the session (TCP)
  2988. sock = c->FirstSock;
  2989. ts = NewTcpSock(sock);
  2990. SetTimeout(sock, CONNECTING_TIMEOUT);
  2991. direction = TCP_BOTH;
  2992. LockList(s->Connection->Tcp->TcpSockList);
  2993. {
  2994. if (s->HalfConnection)
  2995. {
  2996. // In half-connection, directions of the TCP connections are automatically
  2997. // adjusted by examining all current direction of the TCP connections
  2998. UINT i, c2s, s2c;
  2999. c2s = s2c = 0;
  3000. for (i = 0;i < LIST_NUM(s->Connection->Tcp->TcpSockList);i++)
  3001. {
  3002. TCPSOCK *ts = (TCPSOCK *)LIST_DATA(s->Connection->Tcp->TcpSockList, i);
  3003. if (ts->Direction == TCP_SERVER_TO_CLIENT)
  3004. {
  3005. s2c++;
  3006. }
  3007. else
  3008. {
  3009. c2s++;
  3010. }
  3011. }
  3012. if (s2c > c2s)
  3013. {
  3014. direction = TCP_CLIENT_TO_SERVER;
  3015. }
  3016. else
  3017. {
  3018. direction = TCP_SERVER_TO_CLIENT;
  3019. }
  3020. Debug("%u/%u\n", s2c, c2s);
  3021. ts->Direction = direction;
  3022. }
  3023. }
  3024. UnlockList(s->Connection->Tcp->TcpSockList);
  3025. if (s->UseFastRC4)
  3026. {
  3027. // Set the RC4 key information
  3028. Copy(&ts->Rc4KeyPair, &key_pair, sizeof(RC4_KEY_PAIR));
  3029. InitTcpSockRc4Key(ts, true);
  3030. }
  3031. // Return a success result
  3032. p = PackError(ERR_NO_ERROR);
  3033. PackAddInt(p, "direction", direction);
  3034. if (s->UseFastRC4)
  3035. {
  3036. // Add a RC4 key information
  3037. PackAddData(p, "rc4_key_client_to_server", key_pair.ClientToServerKey, sizeof(key_pair.ClientToServerKey));
  3038. PackAddData(p, "rc4_key_server_to_client", key_pair.ServerToClientKey, sizeof(key_pair.ServerToClientKey));
  3039. {
  3040. char key1[64], key2[64];
  3041. BinToStr(key1, sizeof(key1), key_pair.ClientToServerKey, 16);
  3042. BinToStr(key2, sizeof(key2), key_pair.ServerToClientKey, 16);
  3043. Debug(
  3044. "Client to Server Key: %s\n"
  3045. "Server to Client Key: %s\n",
  3046. key1, key2);
  3047. }
  3048. }
  3049. HttpServerSend(c->FirstSock, p);
  3050. FreePack(p);
  3051. SetTimeout(sock, INFINITE);
  3052. LockList(s->Connection->Tcp->TcpSockList);
  3053. {
  3054. Add(s->Connection->Tcp->TcpSockList, ts);
  3055. }
  3056. UnlockList(s->Connection->Tcp->TcpSockList);
  3057. // Increment the number of connections
  3058. Inc(s->Connection->CurrentNumConnection);
  3059. Debug("TCP Connection Incremented: %u\n", Count(s->Connection->CurrentNumConnection));
  3060. // Issue the Cancel of session
  3061. Cancel(s->Cancel1);
  3062. Unlock(s->Connection->lock);
  3063. c->flag1 = true;
  3064. ReleaseSession(s);
  3065. return true;
  3066. }
  3067. else if (StrCmpi(method, "enum_hub") == 0)
  3068. {
  3069. // Enumerate the Virtual HUB
  3070. UINT i, num;
  3071. LIST *o;
  3072. o = NewListFast(NULL);
  3073. c->Type = CONNECTION_TYPE_ENUM_HUB;
  3074. FreePack(p);
  3075. p = NewPack();
  3076. LockList(c->Cedar->HubList);
  3077. {
  3078. num = LIST_NUM(c->Cedar->HubList);
  3079. for (i = 0;i < num;i++)
  3080. {
  3081. HUB *h = LIST_DATA(c->Cedar->HubList, i);
  3082. if (h->Option != NULL && h->Option->NoEnum == false)
  3083. {
  3084. Insert(o, CopyStr(h->Name));
  3085. }
  3086. }
  3087. }
  3088. UnlockList(c->Cedar->HubList);
  3089. num = LIST_NUM(o);
  3090. for (i = 0;i < num;i++)
  3091. {
  3092. char *name = LIST_DATA(o, i);
  3093. PackAddStrEx(p, "HubName", name, i, num);
  3094. Free(name);
  3095. }
  3096. ReleaseList(o);
  3097. PackAddInt(p, "NumHub", num);
  3098. HttpServerSend(c->FirstSock, p);
  3099. FreePack(p);
  3100. FreePack(HttpServerRecv(c->FirstSock));
  3101. c->Err = 0;
  3102. SLog(c->Cedar, "LS_ENUM_HUB", c->Name, num);
  3103. error_detail = "enum_hub";
  3104. goto CLEANUP;
  3105. }
  3106. else if (StrCmpi(method, "farm_connect") == 0)
  3107. {
  3108. // Server farm connection request
  3109. CEDAR *cedar = c->Cedar;
  3110. c->Type = CONNECTION_TYPE_FARM_RPC;
  3111. c->Err = 0;
  3112. if (c->Cedar->Server == NULL)
  3113. {
  3114. // Unsupported
  3115. c->Err = ERR_NOT_FARM_CONTROLLER;
  3116. }
  3117. else
  3118. {
  3119. SERVER *s = c->Cedar->Server;
  3120. if (s->ServerType != SERVER_TYPE_FARM_CONTROLLER || s->FarmControllerInited == false)
  3121. {
  3122. // Not a farm controller
  3123. SLog(c->Cedar, "LS_FARM_ACCEPT_1", c->Name);
  3124. c->Err = ERR_NOT_FARM_CONTROLLER;
  3125. }
  3126. else
  3127. {
  3128. UCHAR check_secure_password[SHA1_SIZE];
  3129. UCHAR secure_password[SHA1_SIZE];
  3130. // User authentication
  3131. SecurePassword(check_secure_password, s->HashedPassword, c->Random);
  3132. if (PackGetDataSize(p, "SecurePassword") == sizeof(secure_password))
  3133. {
  3134. PackGetData(p, "SecurePassword", secure_password);
  3135. }
  3136. else
  3137. {
  3138. Zero(secure_password, sizeof(secure_password));
  3139. }
  3140. if (Cmp(secure_password, check_secure_password, SHA1_SIZE) != 0)
  3141. {
  3142. // Password is different
  3143. SLog(c->Cedar, "LS_FARM_ACCEPT_2", c->Name);
  3144. c->Err = ERR_ACCESS_DENIED;
  3145. }
  3146. else
  3147. {
  3148. // Get the certificate
  3149. BUF *b;
  3150. X *server_x;
  3151. SLog(c->Cedar, "LS_FARM_ACCEPT_3", c->Name);
  3152. b = PackGetBuf(p, "ServerCert");
  3153. if (b == NULL)
  3154. {
  3155. c->Err = ERR_PROTOCOL_ERROR;
  3156. }
  3157. else
  3158. {
  3159. server_x = BufToX(b, false);
  3160. FreeBuf(b);
  3161. if (server_x == NULL)
  3162. {
  3163. c->Err = ERR_PROTOCOL_ERROR;
  3164. }
  3165. else
  3166. {
  3167. UINT ip;
  3168. UINT point;
  3169. char hostname[MAX_SIZE];
  3170. #ifdef OS_WIN32
  3171. MsSetThreadPriorityRealtime();
  3172. #endif // OS_WIN32
  3173. SetTimeout(c->FirstSock, SERVER_CONTROL_TCP_TIMEOUT);
  3174. ip = PackGetIp32(p, "PublicIp");
  3175. point = PackGetInt(p, "Point");
  3176. if (PackGetStr(p, "HostName", hostname, sizeof(hostname)))
  3177. {
  3178. UINT num_port = PackGetIndexCount(p, "PublicPort");
  3179. if (num_port >= 1 && num_port <= MAX_PUBLIC_PORT_NUM)
  3180. {
  3181. UINT *ports = ZeroMalloc(sizeof(UINT) * num_port);
  3182. UINT i;
  3183. for (i = 0;i < num_port;i++)
  3184. {
  3185. ports[i] = PackGetIntEx(p, "PublicPort", i);
  3186. }
  3187. SiFarmServ(s, c->FirstSock, server_x, ip, num_port, ports, hostname, point,
  3188. PackGetInt(p, "Weight"), PackGetInt(p, "MaxSessions"));
  3189. Free(ports);
  3190. }
  3191. }
  3192. FreeX(server_x);
  3193. }
  3194. }
  3195. }
  3196. }
  3197. }
  3198. FreePack(p);
  3199. goto CLEANUP;
  3200. }
  3201. else if (StrCmpi(method, "admin") == 0 && c->Cedar->Server != NULL)
  3202. {
  3203. UINT err;
  3204. // Administrative RPC connection request
  3205. c->Type = CONNECTION_TYPE_ADMIN_RPC;
  3206. err = AdminAccept(c, p);
  3207. FreePack(p);
  3208. if (err != ERR_NO_ERROR)
  3209. {
  3210. PACK *p = PackError(err);
  3211. HttpServerSend(c->FirstSock, p);
  3212. FreePack(p);
  3213. }
  3214. error_detail = "admin_rpc";
  3215. goto CLEANUP;
  3216. }
  3217. else if (StrCmpi(method, "password") == 0)
  3218. {
  3219. UINT err;
  3220. // Password change request
  3221. c->Type = CONNECTION_TYPE_PASSWORD;
  3222. err = ChangePasswordAccept(c, p);
  3223. FreePack(p);
  3224. p = PackError(err);
  3225. HttpServerSend(c->FirstSock, p);
  3226. FreePack(p);
  3227. error_detail = "change_password";
  3228. goto CLEANUP;
  3229. }
  3230. else
  3231. {
  3232. // Unknown method
  3233. FreePack(p);
  3234. c->Err = ERR_PROTOCOL_ERROR;
  3235. error_detail = "unknown_method";
  3236. goto CLEANUP;
  3237. }
  3238. CLEANUP:
  3239. // Release the user object
  3240. if (loggedin_user_object != NULL)
  3241. {
  3242. ReleaseUser(loggedin_user_object);
  3243. }
  3244. // Error packet transmission
  3245. if (supress_return_pack_error == false)
  3246. {
  3247. p = PackError(c->Err);
  3248. PackAddBool(p, "no_save_password", no_save_password);
  3249. HttpServerSend(c->FirstSock, p);
  3250. FreePack(p);
  3251. }
  3252. FreePack(HttpServerRecv(c->FirstSock));
  3253. SleepThread(25);
  3254. SLog(c->Cedar, "LS_CONNECTION_ERROR", c->Name, GetUniErrorStr(c->Err), c->Err);
  3255. if (release_me_eap_client != NULL)
  3256. {
  3257. ReleaseEapClient(release_me_eap_client);
  3258. }
  3259. return ret;
  3260. }
  3261. // Create a Node information
  3262. void CreateNodeInfo(NODE_INFO *info, CONNECTION *c)
  3263. {
  3264. SESSION *s;
  3265. OS_INFO *os;
  3266. char *product_id;
  3267. IP ip;
  3268. bool is_vgc = false;
  3269. // Validate arguments
  3270. if (c == NULL)
  3271. {
  3272. return;
  3273. }
  3274. s = c->Session;
  3275. os = GetOsInfo();
  3276. Zero(info, sizeof(NODE_INFO));
  3277. // Client product name
  3278. StrCpy(info->ClientProductName, sizeof(info->ClientProductName), c->ClientStr);
  3279. // Client version
  3280. info->ClientProductVer = Endian32(c->ClientVer);
  3281. // Client build number
  3282. info->ClientProductBuild = Endian32(c->ClientBuild);
  3283. // Server product name
  3284. StrCpy(info->ServerProductName, sizeof(info->ServerProductName), c->ServerStr);
  3285. // Server version
  3286. info->ServerProductVer = Endian32(c->ServerVer);
  3287. // Server build number
  3288. info->ServerProductBuild = Endian32(c->ServerBuild);
  3289. // Client OS name
  3290. StrCpy(info->ClientOsName, sizeof(info->ClientOsName), os->OsProductName);
  3291. // Client OS version
  3292. StrCpy(info->ClientOsVer, sizeof(info->ClientOsVer), os->OsVersion);
  3293. // Client OS Product ID
  3294. product_id = OSGetProductId();
  3295. StrCpy(info->ClientOsProductId, sizeof(info->ClientOsProductId), product_id);
  3296. Free(product_id);
  3297. // Client host name
  3298. #ifndef OS_WIN32
  3299. GetMachineName(info->ClientHostname, sizeof(info->ClientHostname));
  3300. #else // OS_WIN32
  3301. if (true)
  3302. {
  3303. wchar_t namew[256];
  3304. char namea[256];
  3305. Zero(namew, sizeof(namew));
  3306. MsGetComputerNameFullEx(namew, sizeof(namew), true);
  3307. Zero(namea, sizeof(namea));
  3308. UniToStr(namea, sizeof(namea), namew);
  3309. if (IsEmptyStr(namea))
  3310. {
  3311. GetMachineName(namea, sizeof(namea));
  3312. }
  3313. StrCpy(info->ClientHostname, sizeof(info->ClientHostname), namea);
  3314. }
  3315. #endif // OS_WIN32
  3316. // Client IP address
  3317. if (IsIP6(&c->FirstSock->LocalIP) == false)
  3318. {
  3319. info->ClientIpAddress = IPToUINT(&c->FirstSock->LocalIP);
  3320. }
  3321. else
  3322. {
  3323. Copy(info->ClientIpAddress6, c->FirstSock->LocalIP.ipv6_addr, sizeof(info->ClientIpAddress6));
  3324. }
  3325. // Client port number
  3326. info->ClientPort = Endian32(c->FirstSock->LocalPort);
  3327. // Server host name
  3328. StrCpy(info->ServerHostname, sizeof(info->ServerHostname), c->ServerName);
  3329. // Server IP address
  3330. if (GetIP(&ip, info->ServerHostname))
  3331. {
  3332. if (IsIP6(&ip) == false)
  3333. {
  3334. info->ServerIpAddress = IPToUINT(&ip);
  3335. }
  3336. else
  3337. {
  3338. Copy(info->ServerIpAddress6, ip.ipv6_addr, sizeof(info->ServerIpAddress6));
  3339. }
  3340. }
  3341. // Server port number
  3342. info->ServerPort = Endian32(c->ServerPort);
  3343. if (s->ClientOption->ProxyType == PROXY_SOCKS || s->ClientOption->ProxyType == PROXY_HTTP)
  3344. {
  3345. // Proxy host name
  3346. StrCpy(info->ProxyHostname, sizeof(info->ProxyHostname), s->ClientOption->ProxyName);
  3347. // Proxy Server IP Address
  3348. if (IsIP6(&c->FirstSock->RemoteIP) == false)
  3349. {
  3350. info->ProxyIpAddress = IPToUINT(&c->FirstSock->RemoteIP);
  3351. }
  3352. else
  3353. {
  3354. Copy(&info->ProxyIpAddress6, c->FirstSock->RemoteIP.ipv6_addr, sizeof(info->ProxyIpAddress6));
  3355. }
  3356. info->ProxyPort = Endian32(c->FirstSock->RemotePort);
  3357. }
  3358. // HUB name
  3359. StrCpy(info->HubName, sizeof(info->HubName), s->ClientOption->HubName);
  3360. // Unique ID
  3361. Copy(info->UniqueId, c->Cedar->UniqueId, sizeof(info->UniqueId));
  3362. }
  3363. // Connect a socket additionally
  3364. SOCK *ClientAdditionalConnectToServer(CONNECTION *c)
  3365. {
  3366. SOCK *s;
  3367. // Validate arguments
  3368. if (c == NULL)
  3369. {
  3370. return NULL;
  3371. }
  3372. // Socket connection
  3373. s = ClientConnectGetSocket(c, true, (c->DontUseTls1 ? false : true));
  3374. if (s == NULL)
  3375. {
  3376. // Connection failure
  3377. return NULL;
  3378. }
  3379. // Add the socket to the list
  3380. LockList(c->ConnectingSocks);
  3381. {
  3382. Add(c->ConnectingSocks, s);
  3383. AddRef(s->ref);
  3384. }
  3385. UnlockList(c->ConnectingSocks);
  3386. if (c->Session->Halt)
  3387. {
  3388. // Stop
  3389. Disconnect(s);
  3390. LockList(c->ConnectingSocks);
  3391. {
  3392. if (Delete(c->ConnectingSocks, s))
  3393. {
  3394. ReleaseSock(s);
  3395. }
  3396. }
  3397. UnlockList(c->ConnectingSocks);
  3398. ReleaseSock(s);
  3399. return NULL;
  3400. }
  3401. // Time-out
  3402. SetTimeout(s, CONNECTING_TIMEOUT);
  3403. // Start the SSL communication
  3404. if (StartSSLEx(s, NULL, NULL, (c->DontUseTls1 ? false : true), 0, c->ServerName) == false)
  3405. {
  3406. // SSL communication failure
  3407. Disconnect(s);
  3408. LockList(c->ConnectingSocks);
  3409. {
  3410. if (Delete(c->ConnectingSocks, s))
  3411. {
  3412. ReleaseSock(s);
  3413. }
  3414. }
  3415. UnlockList(c->ConnectingSocks);
  3416. ReleaseSock(s);
  3417. return NULL;
  3418. }
  3419. // Check the certificate
  3420. if (CompareX(s->RemoteX, c->ServerX) == false)
  3421. {
  3422. // The certificate is invalid
  3423. Disconnect(s);
  3424. c->Session->SessionTimeOuted = true;
  3425. }
  3426. return s;
  3427. }
  3428. // Remove the key and certificate in the secure device
  3429. UINT SecureDelete(UINT device_id, char *pin, char *cert_name, char *key_name)
  3430. {
  3431. SECURE *sec;
  3432. // Validate arguments
  3433. if (pin == NULL || device_id == 0)
  3434. {
  3435. return ERR_INTERNAL_ERROR;
  3436. }
  3437. // Open the device
  3438. sec = OpenSec(device_id);
  3439. if (sec == NULL)
  3440. {
  3441. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3442. }
  3443. // Open the session
  3444. if (OpenSecSession(sec, 0) == false)
  3445. {
  3446. CloseSec(sec);
  3447. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3448. }
  3449. // Login
  3450. if (LoginSec(sec, pin) == false)
  3451. {
  3452. CloseSecSession(sec);
  3453. CloseSec(sec);
  3454. return ERR_SECURE_PIN_LOGIN_FAILED;
  3455. }
  3456. // Delete the certificate
  3457. if (cert_name != NULL)
  3458. {
  3459. DeleteSecCert(sec, cert_name);
  3460. }
  3461. // Delete the Private key
  3462. if (key_name != NULL)
  3463. {
  3464. DeleteSecKey(sec, key_name);
  3465. }
  3466. // Log out
  3467. LogoutSec(sec);
  3468. // Close the session
  3469. CloseSecSession(sec);
  3470. // Close the device
  3471. CloseSec(sec);
  3472. return ERR_NO_ERROR;
  3473. }
  3474. // Enumerate certificates and keys in the secure device
  3475. UINT SecureEnum(UINT device_id, char *pin, TOKEN_LIST **cert_list, TOKEN_LIST **key_list)
  3476. {
  3477. SECURE *sec;
  3478. LIST *o;
  3479. LIST *cert_name_list, *key_name_list;
  3480. // Validate arguments
  3481. if (pin == NULL || device_id == 0 || cert_list == NULL || key_list == NULL)
  3482. {
  3483. return ERR_INTERNAL_ERROR;
  3484. }
  3485. // Open the device
  3486. sec = OpenSec(device_id);
  3487. if (sec == NULL)
  3488. {
  3489. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3490. }
  3491. // Open the session
  3492. if (OpenSecSession(sec, 0) == false)
  3493. {
  3494. CloseSec(sec);
  3495. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3496. }
  3497. // Login
  3498. if (LoginSec(sec, pin) == false)
  3499. {
  3500. CloseSecSession(sec);
  3501. CloseSec(sec);
  3502. return ERR_SECURE_PIN_LOGIN_FAILED;
  3503. }
  3504. // Enumerate objects
  3505. if ((o = EnumSecObject(sec)) != NULL)
  3506. {
  3507. UINT i;
  3508. cert_name_list = NewList(CompareStr);
  3509. key_name_list = NewList(CompareStr);
  3510. for (i = 0;i < LIST_NUM(o);i++)
  3511. {
  3512. SEC_OBJ *obj = LIST_DATA(o, i);
  3513. if (obj->Type == SEC_X)
  3514. {
  3515. Add(cert_name_list, CopyStr(obj->Name));
  3516. }
  3517. else if (obj->Type == SEC_K)
  3518. {
  3519. Add(key_name_list, CopyStr(obj->Name));
  3520. }
  3521. }
  3522. Sort(cert_name_list);
  3523. Sort(key_name_list);
  3524. *cert_list = ListToTokenList(cert_name_list);
  3525. *key_list = ListToTokenList(key_name_list);
  3526. // Release the memory
  3527. FreeStrList(cert_name_list);
  3528. FreeStrList(key_name_list);
  3529. FreeEnumSecObject(o);
  3530. }
  3531. else
  3532. {
  3533. *cert_list = NullToken();
  3534. *key_list = NullToken();
  3535. }
  3536. // Log out
  3537. LogoutSec(sec);
  3538. // Close the session
  3539. CloseSecSession(sec);
  3540. // Close the device
  3541. CloseSec(sec);
  3542. return ERR_NO_ERROR;
  3543. }
  3544. // Record the certificate and key to secure device
  3545. UINT SecureWrite(UINT device_id, char *cert_name, X *x, char *key_name, K *k, char *pin)
  3546. {
  3547. SECURE *sec;
  3548. bool failed;
  3549. // Validate arguments
  3550. if (pin == NULL || device_id == 0 || cert_name == NULL || x == NULL || key_name == NULL || k == NULL)
  3551. {
  3552. return ERR_INTERNAL_ERROR;
  3553. }
  3554. // Open the device
  3555. sec = OpenSec(device_id);
  3556. if (sec == NULL)
  3557. {
  3558. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3559. }
  3560. // Open the session
  3561. if (OpenSecSession(sec, 0) == false)
  3562. {
  3563. CloseSec(sec);
  3564. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3565. }
  3566. // Login
  3567. if (LoginSec(sec, pin) == false)
  3568. {
  3569. CloseSecSession(sec);
  3570. CloseSec(sec);
  3571. return ERR_SECURE_PIN_LOGIN_FAILED;
  3572. }
  3573. // Registration
  3574. failed = false;
  3575. // Register the certificate
  3576. if (WriteSecCert(sec, true, cert_name, x) == false)
  3577. {
  3578. failed = true;
  3579. }
  3580. // Register the private key
  3581. if (WriteSecKey(sec, true, key_name, k) == false)
  3582. {
  3583. failed = true;
  3584. }
  3585. // Log out
  3586. LogoutSec(sec);
  3587. // Close the session
  3588. CloseSecSession(sec);
  3589. // Close the device
  3590. CloseSec(sec);
  3591. if (failed == false)
  3592. {
  3593. // Success
  3594. return ERR_NO_ERROR;
  3595. }
  3596. else
  3597. {
  3598. // Failure
  3599. return ERR_SECURE_CANT_WRITE;
  3600. }
  3601. }
  3602. // Attempt to sign by the secure device
  3603. UINT SecureSign(SECURE_SIGN *sign, UINT device_id, char *pin)
  3604. {
  3605. SECURE *sec;
  3606. X *x;
  3607. // Validate arguments
  3608. if (sign == false || pin == NULL || device_id == 0)
  3609. {
  3610. return ERR_INTERNAL_ERROR;
  3611. }
  3612. // Open the device
  3613. sec = OpenSec(device_id);
  3614. if (sec == NULL)
  3615. {
  3616. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3617. }
  3618. // Open the session
  3619. if (OpenSecSession(sec, 0) == false)
  3620. {
  3621. CloseSec(sec);
  3622. return ERR_SECURE_DEVICE_OPEN_FAILED;
  3623. }
  3624. // Login
  3625. if (LoginSec(sec, pin) == false)
  3626. {
  3627. CloseSecSession(sec);
  3628. CloseSec(sec);
  3629. return ERR_SECURE_PIN_LOGIN_FAILED;
  3630. }
  3631. // Read the certificate
  3632. x = ReadSecCert(sec, sign->SecurePublicCertName);
  3633. if (x == NULL)
  3634. {
  3635. LogoutSec(sec);
  3636. CloseSecSession(sec);
  3637. CloseSec(sec);
  3638. return ERR_SECURE_NO_CERT;
  3639. }
  3640. // Sign by the private key
  3641. if (SignSec(sec, sign->SecurePrivateKeyName, sign->Signature, sign->Random, SHA1_SIZE) == false)
  3642. {
  3643. // Signing failure
  3644. FreeX(x);
  3645. LogoutSec(sec);
  3646. CloseSecSession(sec);
  3647. CloseSec(sec);
  3648. return ERR_SECURE_NO_PRIVATE_KEY;
  3649. }
  3650. // Convert the certificate to buffer
  3651. sign->ClientCert = x;
  3652. // Log out
  3653. LogoutSec(sec);
  3654. // Close the session
  3655. CloseSecSession(sec);
  3656. // Close the device
  3657. CloseSec(sec);
  3658. // Success
  3659. return ERR_NO_ERROR;
  3660. }
  3661. // Client connects to the server additionally
  3662. bool ClientAdditionalConnect(CONNECTION *c, THREAD *t)
  3663. {
  3664. SOCK *s;
  3665. PACK *p;
  3666. TCPSOCK *ts;
  3667. UINT err;
  3668. UINT direction;
  3669. RC4_KEY_PAIR key_pair;
  3670. // Validate arguments
  3671. if (c == NULL)
  3672. {
  3673. return false;
  3674. }
  3675. // Socket connection to the server
  3676. s = ClientAdditionalConnectToServer(c);
  3677. if (s == NULL)
  3678. {
  3679. // Failed to connect socket
  3680. return false;
  3681. }
  3682. if (c->Halt)
  3683. {
  3684. goto CLEANUP;
  3685. }
  3686. // Send a signature
  3687. Debug("Uploading Signature...\n");
  3688. if (ClientUploadSignature(s) == false)
  3689. {
  3690. goto CLEANUP;
  3691. }
  3692. if (c->Halt)
  3693. {
  3694. // Stop
  3695. goto CLEANUP;
  3696. }
  3697. // Receive a Hello packet
  3698. Debug("Downloading Hello...\n");
  3699. if (ClientDownloadHello(c, s) == false)
  3700. {
  3701. goto CLEANUP;
  3702. }
  3703. if (c->Halt)
  3704. {
  3705. // Stop
  3706. goto CLEANUP;
  3707. }
  3708. // Send a authentication data for the additional connection
  3709. if (ClientUploadAuth2(c, s) == false)
  3710. {
  3711. // Disconnected
  3712. goto CLEANUP;
  3713. }
  3714. // Receive a response
  3715. p = HttpClientRecv(s);
  3716. if (p == NULL)
  3717. {
  3718. // Disconnected
  3719. goto CLEANUP;
  3720. }
  3721. err = GetErrorFromPack(p);
  3722. direction = PackGetInt(p, "direction");
  3723. if (c->Session->UseFastRC4)
  3724. {
  3725. // Get the RC4 key information
  3726. if (PackGetDataSize(p, "rc4_key_client_to_server") == 16)
  3727. {
  3728. PackGetData(p, "rc4_key_client_to_server", key_pair.ClientToServerKey);
  3729. }
  3730. if (PackGetDataSize(p, "rc4_key_server_to_client") == 16)
  3731. {
  3732. PackGetData(p, "rc4_key_server_to_client", key_pair.ServerToClientKey);
  3733. }
  3734. {
  3735. char key1[64], key2[64];
  3736. BinToStr(key1, sizeof(key1), key_pair.ClientToServerKey, 16);
  3737. BinToStr(key2, sizeof(key2), key_pair.ServerToClientKey, 16);
  3738. Debug(
  3739. "Client to Server Key: %s\n"
  3740. "Server to Client Key: %s\n",
  3741. key1, key2);
  3742. }
  3743. }
  3744. FreePack(p);
  3745. p = NULL;
  3746. if (err != 0)
  3747. {
  3748. // Error has occurred
  3749. Debug("Additional Connect Error: %u\n", err);
  3750. if (err == ERR_SESSION_TIMEOUT || err == ERR_INVALID_PROTOCOL)
  3751. {
  3752. // We shall re-connection because it is a fatal error
  3753. c->Session->SessionTimeOuted = true;
  3754. }
  3755. goto CLEANUP;
  3756. }
  3757. Debug("Additional Connect Succeed!\n");
  3758. // Success the additional connection
  3759. // Add to the TcpSockList of the connection
  3760. ts = NewTcpSock(s);
  3761. if (c->ServerMode == false)
  3762. {
  3763. if (c->Session->ClientOption->ConnectionDisconnectSpan != 0)
  3764. {
  3765. ts->DisconnectTick = Tick64() + c->Session->ClientOption->ConnectionDisconnectSpan * (UINT64)1000;
  3766. }
  3767. }
  3768. LockList(c->Tcp->TcpSockList);
  3769. {
  3770. ts->Direction = direction;
  3771. Add(c->Tcp->TcpSockList, ts);
  3772. }
  3773. UnlockList(c->Tcp->TcpSockList);
  3774. Debug("TCP Connection Incremented: %u\n", Count(c->CurrentNumConnection));
  3775. if (c->Session->HalfConnection)
  3776. {
  3777. Debug("New Half Connection: %s\n",
  3778. direction == TCP_SERVER_TO_CLIENT ? "TCP_SERVER_TO_CLIENT" : "TCP_CLIENT_TO_SERVER"
  3779. );
  3780. }
  3781. if (c->Session->UseFastRC4)
  3782. {
  3783. // Set the RC4 encryption key
  3784. Copy(&ts->Rc4KeyPair, &key_pair, sizeof(RC4_KEY_PAIR));
  3785. InitTcpSockRc4Key(ts, false);
  3786. }
  3787. // Issue the Cancel to the session
  3788. Cancel(c->Session->Cancel1);
  3789. // Remove the socket from the socket list of connected
  3790. LockList(c->ConnectingSocks);
  3791. {
  3792. if (Delete(c->ConnectingSocks, s))
  3793. {
  3794. ReleaseSock(s);
  3795. }
  3796. }
  3797. UnlockList(c->ConnectingSocks);
  3798. ReleaseSock(s);
  3799. return true;
  3800. CLEANUP:
  3801. // Disconnection process
  3802. Disconnect(s);
  3803. LockList(c->ConnectingSocks);
  3804. {
  3805. if (Delete(c->ConnectingSocks, s))
  3806. {
  3807. ReleaseSock(s);
  3808. }
  3809. }
  3810. UnlockList(c->ConnectingSocks);
  3811. ReleaseSock(s);
  3812. return false;
  3813. }
  3814. // Secure device signing thread
  3815. void ClientSecureSignThread(THREAD *thread, void *param)
  3816. {
  3817. SECURE_SIGN_THREAD_PROC *p = (SECURE_SIGN_THREAD_PROC *)param;
  3818. // Validate arguments
  3819. if (thread == NULL || param == NULL)
  3820. {
  3821. return;
  3822. }
  3823. NoticeThreadInit(thread);
  3824. p->Ok = p->SecureSignProc(p->Connection->Session, p->Connection, p->SecureSign);
  3825. p->UserFinished = true;
  3826. }
  3827. // Signing with the secure device
  3828. bool ClientSecureSign(CONNECTION *c, UCHAR *sign, UCHAR *random, X **x)
  3829. {
  3830. SECURE_SIGN_THREAD_PROC *p;
  3831. SECURE_SIGN *ss;
  3832. SESSION *s;
  3833. CLIENT_OPTION *o;
  3834. CLIENT_AUTH *a;
  3835. THREAD *thread;
  3836. UINT64 start;
  3837. bool ret;
  3838. // Validate arguments
  3839. if (c == NULL || sign == NULL || random == NULL || x == NULL)
  3840. {
  3841. return false;
  3842. }
  3843. s = c->Session;
  3844. o = s->ClientOption;
  3845. a = s->ClientAuth;
  3846. p = ZeroMalloc(sizeof(SECURE_SIGN_THREAD_PROC));
  3847. p->Connection = c;
  3848. ss = p->SecureSign = ZeroMallocEx(sizeof(SECURE_SIGN), true);
  3849. StrCpy(ss->SecurePrivateKeyName, sizeof(ss->SecurePrivateKeyName),
  3850. a->SecurePrivateKeyName);
  3851. StrCpy(ss->SecurePublicCertName, sizeof(ss->SecurePublicCertName),
  3852. a->SecurePublicCertName);
  3853. ss->UseSecureDeviceId = c->Cedar->Client->UseSecureDeviceId;
  3854. Copy(ss->Random, random, SHA1_SIZE);
  3855. #ifdef OS_WIN32
  3856. ss->BitmapId = CmGetSecureBitmapId(c->ServerName);
  3857. #endif // OS_WIN32
  3858. p->SecureSignProc = a->SecureSignProc;
  3859. // Create a thread
  3860. thread = NewThread(ClientSecureSignThread, p);
  3861. WaitThreadInit(thread);
  3862. // Poll every 0.5 seconds until signing is completed or canceled
  3863. start = Tick64();
  3864. while (true)
  3865. {
  3866. if ((Tick64() - start) > CONNECTING_POOLING_SPAN)
  3867. {
  3868. // Send a NOOP periodically for disconnection prevention
  3869. start = Tick64();
  3870. ClientUploadNoop(c);
  3871. }
  3872. if (p->UserFinished)
  3873. {
  3874. // User selected
  3875. break;
  3876. }
  3877. WaitThread(thread, 500);
  3878. }
  3879. ReleaseThread(thread);
  3880. ret = p->Ok;
  3881. if (ret)
  3882. {
  3883. Copy(sign, ss->Signature, 128);
  3884. *x = ss->ClientCert;
  3885. }
  3886. Free(p->SecureSign);
  3887. Free(p);
  3888. return ret;
  3889. }
  3890. // Server certificate confirmation thread
  3891. void ClientCheckServerCertThread(THREAD *thread, void *param)
  3892. {
  3893. CHECK_CERT_THREAD_PROC *p = (CHECK_CERT_THREAD_PROC *)param;
  3894. // Validate arguments
  3895. if (thread == NULL || param == NULL)
  3896. {
  3897. return;
  3898. }
  3899. // Notify the completion of initialization
  3900. NoticeThreadInit(thread);
  3901. // Query for the selection to the user
  3902. p->Ok = p->CheckCertProc(p->Connection->Session, p->Connection, p->ServerX, &p->Exipred);
  3903. p->UserSelected = true;
  3904. }
  3905. // Client verify the certificate of the server
  3906. bool ClientCheckServerCert(CONNECTION *c, bool *expired)
  3907. {
  3908. CLIENT_AUTH *auth;
  3909. X *x;
  3910. CHECK_CERT_THREAD_PROC *p;
  3911. THREAD *thread;
  3912. CEDAR *cedar;
  3913. bool ret;
  3914. UINT64 start;
  3915. // Validate arguments
  3916. if (c == NULL)
  3917. {
  3918. return false;
  3919. }
  3920. if (expired != NULL)
  3921. {
  3922. *expired = false;
  3923. }
  3924. auth = c->Session->ClientAuth;
  3925. cedar = c->Cedar;
  3926. if (auth->CheckCertProc == NULL && c->Session->LinkModeClient == false)
  3927. {
  3928. // No checking function
  3929. return true;
  3930. }
  3931. if (c->Session->LinkModeClient && c->Session->Link->CheckServerCert == false)
  3932. {
  3933. // It's in cascade connection mode, but do not check the server certificate
  3934. return true;
  3935. }
  3936. if (c->UseTicket)
  3937. {
  3938. // Check the certificate of the redirected VPN server
  3939. if (CompareX(c->FirstSock->RemoteX, c->ServerX) == false)
  3940. {
  3941. return false;
  3942. }
  3943. else
  3944. {
  3945. return true;
  3946. }
  3947. }
  3948. x = CloneX(c->FirstSock->RemoteX);
  3949. if (x == NULL)
  3950. {
  3951. // Strange error occurs
  3952. return false;
  3953. }
  3954. if (CheckXDateNow(x))
  3955. {
  3956. // Check whether it is signed by the root certificate to trust
  3957. if (c->Session->LinkModeClient == false)
  3958. {
  3959. // Normal VPN Client mode
  3960. if (CheckSignatureByCa(cedar, x))
  3961. {
  3962. // This certificate can be trusted because it is signed
  3963. FreeX(x);
  3964. return true;
  3965. }
  3966. }
  3967. else
  3968. {
  3969. // Cascade connection mode
  3970. if (CheckSignatureByCaLinkMode(c->Session, x))
  3971. {
  3972. // This certificate can be trusted because it is signed
  3973. FreeX(x);
  3974. return true;
  3975. }
  3976. }
  3977. }
  3978. if (c->Session->LinkModeClient)
  3979. {
  3980. if (CheckXDateNow(x))
  3981. {
  3982. Lock(c->Session->Link->lock);
  3983. {
  3984. if (c->Session->Link->ServerCert != NULL)
  3985. {
  3986. if (CompareX(c->Session->Link->ServerCert, x))
  3987. {
  3988. Unlock(c->Session->Link->lock);
  3989. // Exactly match the certificate that is registered in the cascade configuration
  3990. FreeX(x);
  3991. return true;
  3992. }
  3993. }
  3994. }
  3995. Unlock(c->Session->Link->lock);
  3996. }
  3997. else
  3998. {
  3999. if (expired != NULL)
  4000. {
  4001. *expired = true;
  4002. }
  4003. }
  4004. // Verification failure at this point in the case of cascade connection mode
  4005. FreeX(x);
  4006. return false;
  4007. }
  4008. p = ZeroMalloc(sizeof(CHECK_CERT_THREAD_PROC));
  4009. p->ServerX = x;
  4010. p->CheckCertProc = auth->CheckCertProc;
  4011. p->Connection = c;
  4012. // Create a thread
  4013. thread = NewThread(ClientCheckServerCertThread, p);
  4014. WaitThreadInit(thread);
  4015. // Poll at 0.5-second intervals until the user selects whether the connection
  4016. start = Tick64();
  4017. while (true)
  4018. {
  4019. if ((Tick64() - start) > CONNECTING_POOLING_SPAN)
  4020. {
  4021. // Send a NOOP periodically for disconnection prevention
  4022. start = Tick64();
  4023. ClientUploadNoop(c);
  4024. }
  4025. if (p->UserSelected)
  4026. {
  4027. // User-selected
  4028. break;
  4029. }
  4030. WaitThread(thread, 500);
  4031. }
  4032. if (expired != NULL)
  4033. {
  4034. *expired = p->Exipred;
  4035. }
  4036. ret = p->Ok;
  4037. FreeX(p->ServerX);
  4038. Free(p);
  4039. ReleaseThread(thread);
  4040. return ret;
  4041. }
  4042. // Client connects to the server
  4043. bool ClientConnect(CONNECTION *c)
  4044. {
  4045. bool ret = false;
  4046. bool ok = false;
  4047. UINT err;
  4048. SOCK *s;
  4049. PACK *p = NULL;
  4050. UINT session_key_32;
  4051. SESSION *sess;
  4052. char session_name[MAX_SESSION_NAME_LEN + 1];
  4053. char connection_name[MAX_CONNECTION_NAME_LEN + 1];
  4054. UCHAR session_key[SHA1_SIZE];
  4055. RC4_KEY_PAIR key_pair;
  4056. POLICY *policy;
  4057. bool expired = false;
  4058. IP server_ip;
  4059. // Validate arguments
  4060. if (c == NULL)
  4061. {
  4062. return false;
  4063. }
  4064. sess = c->Session;
  4065. PrintStatus(sess, L"init");
  4066. PrintStatus(sess, _UU("STATUS_1"));
  4067. REDIRECTED:
  4068. // [Connecting]
  4069. c->Status = CONNECTION_STATUS_CONNECTING;
  4070. c->Session->ClientStatus = CLIENT_STATUS_CONNECTING;
  4071. s = ClientConnectToServer(c);
  4072. if (s == NULL)
  4073. {
  4074. PrintStatus(sess, L"free");
  4075. return false;
  4076. }
  4077. Copy(&server_ip, &s->RemoteIP, sizeof(IP));
  4078. if (c->Halt)
  4079. {
  4080. // Stop
  4081. c->Err = ERR_USER_CANCEL;
  4082. goto CLEANUP;
  4083. }
  4084. // [Negotiating]
  4085. c->Session->ClientStatus = CLIENT_STATUS_NEGOTIATION;
  4086. // Initialize the UDP acceleration function
  4087. if (sess->ClientOption != NULL && sess->ClientOption->NoUdpAcceleration == false)
  4088. {
  4089. if (sess->ClientOption->ProxyType == PROXY_DIRECT)
  4090. {
  4091. if (s->Type == SOCK_TCP)
  4092. {
  4093. if (sess->UdpAccel == NULL)
  4094. {
  4095. bool no_nat_t = false;
  4096. if (sess->ClientOption->PortUDP != 0)
  4097. {
  4098. // There is no need for NAT-T treatment on my part if the UDP port on the other end is known beforehand
  4099. no_nat_t = true;
  4100. }
  4101. sess->UdpAccel = NewUdpAccel(c->Cedar, &s->LocalIP, true, true, no_nat_t);
  4102. }
  4103. }
  4104. }
  4105. }
  4106. // Send a signature
  4107. Debug("Uploading Signature...\n");
  4108. if (ClientUploadSignature(s) == false)
  4109. {
  4110. c->Err = ERR_DISCONNECTED;
  4111. goto CLEANUP;
  4112. }
  4113. if (c->Halt)
  4114. {
  4115. // Stop
  4116. c->Err = ERR_USER_CANCEL;
  4117. goto CLEANUP;
  4118. }
  4119. PrintStatus(sess, _UU("STATUS_5"));
  4120. // Receive a Hello packet
  4121. Debug("Downloading Hello...\n");
  4122. if (ClientDownloadHello(c, s) == false)
  4123. {
  4124. goto CLEANUP;
  4125. }
  4126. if (c->Session->ClientOption != NULL && c->Session->ClientOption->FromAdminPack)
  4127. {
  4128. if (IsAdminPackSupportedServerProduct(c->ServerStr) == false)
  4129. {
  4130. c->Err = ERR_NOT_ADMINPACK_SERVER;
  4131. goto CLEANUP;
  4132. }
  4133. }
  4134. if (c->Halt)
  4135. {
  4136. // Stop
  4137. c->Err = ERR_USER_CANCEL;
  4138. goto CLEANUP;
  4139. }
  4140. Debug("Server Version : %u\n"
  4141. "Server String : %s\n"
  4142. "Server Build : %u\n"
  4143. "Client Version : %u\n"
  4144. "Client String : %s\n"
  4145. "Client Build : %u\n",
  4146. c->ServerVer, c->ServerStr, c->ServerBuild,
  4147. c->ClientVer, c->ClientStr, c->ClientBuild);
  4148. // During user authentication
  4149. c->Session->ClientStatus = CLIENT_STATUS_AUTH;
  4150. // Verify the server certificate by the client
  4151. if (ClientCheckServerCert(c, &expired) == false)
  4152. {
  4153. if (expired == false)
  4154. {
  4155. c->Err = ERR_CERT_NOT_TRUSTED;
  4156. }
  4157. else
  4158. {
  4159. c->Err = ERR_SERVER_CERT_EXPIRES;
  4160. }
  4161. if (c->Session->LinkModeClient == false && c->Err == ERR_CERT_NOT_TRUSTED)
  4162. {
  4163. c->Session->ForceStopFlag = true;
  4164. }
  4165. goto CLEANUP;
  4166. }
  4167. PrintStatus(sess, _UU("STATUS_6"));
  4168. // Send the authentication data
  4169. if (ClientUploadAuth(c) == false)
  4170. {
  4171. goto CLEANUP;
  4172. }
  4173. if (c->Halt)
  4174. {
  4175. // Stop
  4176. c->Err = ERR_USER_CANCEL;
  4177. goto CLEANUP;
  4178. }
  4179. // Receive a Welcome packet
  4180. p = HttpClientRecv(s);
  4181. if (p == NULL)
  4182. {
  4183. c->Err = ERR_DISCONNECTED;
  4184. goto CLEANUP;
  4185. }
  4186. // Error checking
  4187. err = GetErrorFromPack(p);
  4188. if (err != 0)
  4189. {
  4190. // An error has occured
  4191. c->Err = err;
  4192. c->ClientConnectError_NoSavePassword = PackGetBool(p, "no_save_password");
  4193. goto CLEANUP;
  4194. }
  4195. // Branding string check for the connection limit
  4196. {
  4197. char tmp[20];
  4198. char *branded_cfroms = _SS("BRANDED_C_FROM_S");
  4199. PackGetStr(p, "branded_cfroms", tmp, sizeof(tmp));
  4200. if(StrLen(branded_cfroms) > 0 && StrCmpi(branded_cfroms, tmp) != 0)
  4201. {
  4202. c->Err = ERR_BRANDED_C_FROM_S;
  4203. goto CLEANUP;
  4204. }
  4205. }
  4206. if (c->Cedar->Server == NULL)
  4207. {
  4208. // Suppress client notification flag
  4209. if (PackIsValueExists(p, "suppress_client_update_notification"))
  4210. {
  4211. bool suppress_client_update_notification = PackGetBool(p, "suppress_client_update_notification");
  4212. #ifdef OS_WIN32
  4213. MsRegWriteIntEx2(REG_LOCAL_MACHINE, PROTO_SUPPRESS_CLIENT_UPDATE_NOTIFICATION_REGKEY, PROTO_SUPPRESS_CLIENT_UPDATE_NOTIFICATION_REGVALUE,
  4214. (suppress_client_update_notification ? 1 : 0), false, true);
  4215. #endif // OS_WIN32
  4216. }
  4217. }
  4218. if (true)
  4219. {
  4220. // Message retrieval
  4221. UINT utf_size;
  4222. char *utf;
  4223. wchar_t *msg;
  4224. utf_size = PackGetDataSize(p, "Msg");
  4225. utf = ZeroMalloc(utf_size + 8);
  4226. PackGetData(p, "Msg", utf);
  4227. msg = CopyUtfToUni(utf);
  4228. if (IsEmptyUniStr(msg) == false)
  4229. {
  4230. if (c->Session->Client_Message != NULL)
  4231. {
  4232. Free(c->Session->Client_Message);
  4233. }
  4234. c->Session->Client_Message = msg;
  4235. }
  4236. else
  4237. {
  4238. Free(msg);
  4239. }
  4240. Free(utf);
  4241. }
  4242. if (PackGetInt(p, "Redirect") != 0)
  4243. {
  4244. UINT i;
  4245. UINT ip;
  4246. UINT num_port;
  4247. UINT *ports;
  4248. UINT use_port = 0;
  4249. UINT current_port = c->ServerPort;
  4250. UCHAR ticket[SHA1_SIZE];
  4251. X *server_cert;
  4252. BUF *b;
  4253. // Redirect mode
  4254. PrintStatus(sess, _UU("STATUS_8"));
  4255. ip = PackGetIp32(p, "Ip");
  4256. num_port = MAX(MIN(PackGetIndexCount(p, "Port"), MAX_PUBLIC_PORT_NUM), 1);
  4257. ports = ZeroMalloc(sizeof(UINT) * num_port);
  4258. for (i = 0;i < num_port;i++)
  4259. {
  4260. ports[i] = PackGetIntEx(p, "Port", i);
  4261. }
  4262. // Select a port number
  4263. for (i = 0;i < num_port;i++)
  4264. {
  4265. if (ports[i] == current_port)
  4266. {
  4267. use_port = current_port;
  4268. }
  4269. }
  4270. if (use_port == 0)
  4271. {
  4272. use_port = ports[0];
  4273. }
  4274. Free(ports);
  4275. if (PackGetDataSize(p, "Ticket") == SHA1_SIZE)
  4276. {
  4277. PackGetData(p, "Ticket", ticket);
  4278. }
  4279. b = PackGetBuf(p, "Cert");
  4280. if (b != NULL)
  4281. {
  4282. server_cert = BufToX(b, false);
  4283. FreeBuf(b);
  4284. }
  4285. if (c->ServerX != NULL)
  4286. {
  4287. FreeX(c->ServerX);
  4288. }
  4289. c->ServerX = server_cert;
  4290. IPToStr32(c->ServerName, sizeof(c->ServerName), ip);
  4291. c->ServerPort = use_port;
  4292. c->UseTicket = true;
  4293. Copy(c->Ticket, ticket, SHA1_SIZE);
  4294. FreePack(p);
  4295. p = NewPack();
  4296. HttpClientSend(s, p);
  4297. FreePack(p);
  4298. p = NULL;
  4299. c->FirstSock = NULL;
  4300. Disconnect(s);
  4301. ReleaseSock(s);
  4302. s = NULL;
  4303. goto REDIRECTED;
  4304. }
  4305. PrintStatus(sess, _UU("STATUS_7"));
  4306. // Parse the Welcome packet
  4307. if (ParseWelcomeFromPack(p, session_name, sizeof(session_name),
  4308. connection_name, sizeof(connection_name), &policy) == false)
  4309. {
  4310. // Parsing failure
  4311. c->Err = ERR_PROTOCOL_ERROR;
  4312. goto CLEANUP;
  4313. }
  4314. // Get the session key
  4315. if (GetSessionKeyFromPack(p, session_key, &session_key_32) == false)
  4316. {
  4317. // Acquisition failure
  4318. Free(policy);
  4319. policy = NULL;
  4320. c->Err = ERR_PROTOCOL_ERROR;
  4321. goto CLEANUP;
  4322. }
  4323. Copy(c->Session->SessionKey, session_key, SHA1_SIZE);
  4324. c->Session->SessionKey32 = session_key_32;
  4325. // Save the contents of the Welcome packet
  4326. Debug("session_name: %s, connection_name: %s\n",
  4327. session_name, connection_name);
  4328. Lock(c->Session->lock);
  4329. {
  4330. // Deploy and update connection parameters
  4331. sess->EnableUdpRecovery = PackGetBool(p, "enable_udp_recovery");
  4332. c->Session->MaxConnection = PackGetInt(p, "max_connection");
  4333. if (sess->EnableUdpRecovery == false)
  4334. {
  4335. c->Session->MaxConnection = MIN(c->Session->MaxConnection, c->Session->ClientOption->MaxConnection);
  4336. }
  4337. c->Session->MaxConnection = MIN(c->Session->MaxConnection, MAX_TCP_CONNECTION);
  4338. c->Session->MaxConnection = MAX(c->Session->MaxConnection, 1);
  4339. c->Session->UseCompress = PackGetInt(p, "use_compress") == 0 ? false : true;
  4340. c->Session->UseEncrypt = PackGetInt(p, "use_encrypt") == 0 ? false : true;
  4341. c->Session->NoSendSignature = PackGetBool(p, "no_send_signature");
  4342. if (c->Session->UseEncrypt)
  4343. {
  4344. c->Session->UseFastRC4 = PackGetInt(p, "use_fast_rc4") == 0 ? false : true;
  4345. }
  4346. c->Session->HalfConnection = PackGetInt(p, "half_connection") == 0 ? false : true;
  4347. c->Session->IsAzureSession = PackGetInt(p, "is_azure_session") == 0 ? false : true;
  4348. c->Session->Timeout = PackGetInt(p, "timeout");
  4349. c->Session->QoS = PackGetInt(p, "qos") == 0 ? false : true;
  4350. if (c->Session->QoS)
  4351. {
  4352. c->Session->MaxConnection = MAX(c->Session->MaxConnection, (UINT)(c->Session->HalfConnection ? 4 : 2));
  4353. }
  4354. c->Session->VLanId = PackGetInt(p, "vlan_id");
  4355. // R-UDP Session ?
  4356. c->Session->IsRUDPSession = s->IsRUDPSocket;
  4357. ZeroIP4(&c->Session->AzureRealServerGlobalIp);
  4358. if (c->Session->IsAzureSession)
  4359. {
  4360. // Disable the life parameter of the connection in the case of VPN Azure relayed session
  4361. c->Session->ClientOption->ConnectionDisconnectSpan = 0;
  4362. // Get the AzureRealServerGlobalIp the case of VPN Azure relayed
  4363. PackGetIp(p, "azure_real_server_global_ip", &c->Session->AzureRealServerGlobalIp);
  4364. }
  4365. if (c->Session->IsRUDPSession)
  4366. {
  4367. // Disable the life parameter of the connection in the case of R-UDP session
  4368. c->Session->ClientOption->ConnectionDisconnectSpan = 0;
  4369. // Disable QoS, etc. in the case of R-UDP session
  4370. c->Session->QoS = false;
  4371. c->Session->HalfConnection = false;
  4372. if (c->Session->EnableUdpRecovery == false)
  4373. {
  4374. // Set the number of connection to 1 if UDP recovery is not supported
  4375. c->Session->MaxConnection = 1;
  4376. }
  4377. }
  4378. // Physical communication protocol
  4379. StrCpy(c->Session->UnderlayProtocol, sizeof(c->Session->UnderlayProtocol), s->UnderlayProtocol);
  4380. if (c->Session->IsAzureSession)
  4381. {
  4382. StrCpy(c->Session->UnderlayProtocol, sizeof(c->Session->UnderlayProtocol), SOCK_UNDERLAY_AZURE);
  4383. }
  4384. if (c->Protocol == CONNECTION_UDP)
  4385. {
  4386. // In the case of UDP protocol, receive the key from the server
  4387. if (PackGetDataSize(p, "udp_send_key") == sizeof(c->Session->UdpSendKey))
  4388. {
  4389. PackGetData(p, "udp_send_key", c->Session->UdpSendKey);
  4390. }
  4391. if (PackGetDataSize(p, "udp_recv_key") == sizeof(c->Session->UdpRecvKey))
  4392. {
  4393. PackGetData(p, "udp_recv_key", c->Session->UdpRecvKey);
  4394. }
  4395. }
  4396. if (c->Session->UseFastRC4)
  4397. {
  4398. // Get the RC4 key information
  4399. if (PackGetDataSize(p, "rc4_key_client_to_server") == 16)
  4400. {
  4401. PackGetData(p, "rc4_key_client_to_server", key_pair.ClientToServerKey);
  4402. }
  4403. if (PackGetDataSize(p, "rc4_key_server_to_client") == 16)
  4404. {
  4405. PackGetData(p, "rc4_key_server_to_client", key_pair.ServerToClientKey);
  4406. }
  4407. {
  4408. char key1[64], key2[64];
  4409. BinToStr(key1, sizeof(key1), key_pair.ClientToServerKey, 16);
  4410. BinToStr(key2, sizeof(key2), key_pair.ServerToClientKey, 16);
  4411. Debug(
  4412. "Client to Server Key: %s\n"
  4413. "Server to Client Key: %s\n",
  4414. key1, key2);
  4415. }
  4416. }
  4417. sess->EnableBulkOnRUDP = false;
  4418. sess->EnableHMacOnBulkOfRUDP = false;
  4419. if (s != NULL && s->IsRUDPSocket && s->BulkRecvKey != NULL && s->BulkSendKey != NULL)
  4420. {
  4421. // Bulk transfer on R-UDP
  4422. if (PackGetBool(p, "enable_bulk_on_rudp"))
  4423. {
  4424. // Receive the key
  4425. UCHAR key_send[SHA1_SIZE];
  4426. UCHAR key_recv[SHA1_SIZE];
  4427. if (PackGetData2(p, "bulk_on_rudp_send_key", key_send, SHA1_SIZE) &&
  4428. PackGetData2(p, "bulk_on_rudp_recv_key", key_recv, SHA1_SIZE))
  4429. {
  4430. sess->EnableBulkOnRUDP = true;
  4431. Copy(s->BulkSendKey->Data, key_send, SHA1_SIZE);
  4432. Copy(s->BulkRecvKey->Data, key_recv, SHA1_SIZE);
  4433. }
  4434. }
  4435. sess->EnableHMacOnBulkOfRUDP = PackGetBool(p, "enable_hmac_on_bulk_of_rudp");
  4436. }
  4437. Debug("EnableBulkOnRUDP = %u\n", sess->EnableBulkOnRUDP);
  4438. Debug("EnableHMacOnBulkOfRUDP = %u\n", sess->EnableHMacOnBulkOfRUDP);
  4439. Debug("EnableUdpRecovery = %u\n", sess->EnableUdpRecovery);
  4440. sess->UseUdpAcceleration = false;
  4441. sess->IsUsingUdpAcceleration = false;
  4442. sess->UseHMacOnUdpAcceleration = false;
  4443. if (sess->UdpAccel != NULL)
  4444. {
  4445. sess->UdpAccel->UseHMac = false;
  4446. sess->UdpAccelFastDisconnectDetect = false;
  4447. if (PackGetBool(p, "use_udp_acceleration"))
  4448. {
  4449. IP udp_acceleration_server_ip;
  4450. sess->UdpAccelFastDisconnectDetect = PackGetBool(p, "udp_accel_fast_disconnect_detect");
  4451. if (PackGetIp(p, "udp_acceleration_server_ip", &udp_acceleration_server_ip))
  4452. {
  4453. UINT udp_acceleration_server_port = PackGetInt(p, "udp_acceleration_server_port");
  4454. if (IsZeroIp(&udp_acceleration_server_ip))
  4455. {
  4456. Copy(&udp_acceleration_server_ip, &s->RemoteIP, sizeof(IP));
  4457. }
  4458. if (udp_acceleration_server_port != 0)
  4459. {
  4460. UCHAR udp_acceleration_server_key[UDP_ACCELERATION_COMMON_KEY_SIZE];
  4461. if (PackGetData2(p, "udp_acceleration_server_key", udp_acceleration_server_key, UDP_ACCELERATION_COMMON_KEY_SIZE))
  4462. {
  4463. UINT server_cookie = PackGetInt(p, "udp_acceleration_server_cookie");
  4464. UINT client_cookie = PackGetInt(p, "udp_acceleration_client_cookie");
  4465. bool encryption = PackGetBool(p, "udp_acceleration_use_encryption");
  4466. if (server_cookie != 0 && client_cookie != 0)
  4467. {
  4468. IP remote_ip;
  4469. Copy(&remote_ip, &s->RemoteIP, sizeof(IP));
  4470. if (IsZeroIp(&c->Session->AzureRealServerGlobalIp) == false)
  4471. {
  4472. Copy(&remote_ip, &c->Session->AzureRealServerGlobalIp, sizeof(IP));
  4473. }
  4474. if (UdpAccelInitClient(sess->UdpAccel, udp_acceleration_server_key,
  4475. &udp_acceleration_server_ip, udp_acceleration_server_port,
  4476. server_cookie, client_cookie, &remote_ip) == false)
  4477. {
  4478. Debug("UdpAccelInitClient failed.\n");
  4479. }
  4480. else
  4481. {
  4482. sess->UseUdpAcceleration = true;
  4483. sess->UdpAccel->FastDetect = sess->UdpAccelFastDisconnectDetect;
  4484. sess->UdpAccel->PlainTextMode = !encryption;
  4485. sess->UseHMacOnUdpAcceleration = PackGetBool(p, "use_hmac_on_udp_acceleration");
  4486. if (sess->UseHMacOnUdpAcceleration)
  4487. {
  4488. sess->UdpAccel->UseHMac = true;
  4489. }
  4490. }
  4491. }
  4492. }
  4493. }
  4494. }
  4495. }
  4496. }
  4497. }
  4498. Unlock(c->Session->lock);
  4499. Debug("UseUdpAcceleration = %u\n", sess->UseUdpAcceleration);
  4500. if (sess->UseUdpAcceleration == false)
  4501. {
  4502. if (sess->UdpAccel != NULL)
  4503. {
  4504. FreeUdpAccel(sess->UdpAccel);
  4505. sess->UdpAccel = NULL;
  4506. }
  4507. }
  4508. Lock(c->lock);
  4509. {
  4510. if (c->Name != NULL)
  4511. {
  4512. Free(c->Name);
  4513. }
  4514. c->Name = CopyStr(connection_name);
  4515. // Save the name of a cryptographic algorithm
  4516. if (c->CipherName != NULL)
  4517. {
  4518. Free(c->CipherName);
  4519. }
  4520. c->CipherName = CopyStr(c->FirstSock->CipherName);
  4521. }
  4522. Unlock(c->lock);
  4523. Lock(c->Session->lock);
  4524. {
  4525. if (c->Session->Name != NULL)
  4526. {
  4527. Free(c->Session->Name);
  4528. }
  4529. c->Session->Name = CopyStr(session_name);
  4530. c->Session->Policy = policy;
  4531. }
  4532. Unlock(c->Session->lock);
  4533. // Discard the Welcome packet
  4534. FreePack(p);
  4535. p = NULL;
  4536. // Connection establishment
  4537. c->Session->ClientStatus = CLIENT_STATUS_ESTABLISHED;
  4538. // Save the server certificate
  4539. if (c->ServerX == NULL)
  4540. {
  4541. c->ServerX = CloneX(c->FirstSock->RemoteX);
  4542. }
  4543. PrintStatus(sess, _UU("STATUS_9"));
  4544. // Shift the connection to the tunneling mode
  4545. StartTunnelingMode(c);
  4546. s = NULL;
  4547. if (c->Session->HalfConnection)
  4548. {
  4549. // Processing in the case of half-connection
  4550. TCPSOCK *ts = (TCPSOCK *)LIST_DATA(c->Tcp->TcpSockList, 0);
  4551. ts->Direction = TCP_CLIENT_TO_SERVER;
  4552. }
  4553. if (c->Session->UseFastRC4)
  4554. {
  4555. // Set the high-speed RC4 encryption key
  4556. TCPSOCK *ts = (TCPSOCK *)LIST_DATA(c->Tcp->TcpSockList, 0);
  4557. Copy(&ts->Rc4KeyPair, &key_pair, sizeof(key_pair));
  4558. InitTcpSockRc4Key(ts, false);
  4559. }
  4560. // SSL encryption flag
  4561. if (c->Session->UseEncrypt && c->Session->UseFastRC4 == false)
  4562. {
  4563. c->Session->UseSSLDataEncryption = true;
  4564. }
  4565. else
  4566. {
  4567. c->Session->UseSSLDataEncryption = false;
  4568. }
  4569. PrintStatus(sess, L"free");
  4570. CLog(c->Cedar->Client, "LC_CONNECT_2", c->Session->ClientOption->AccountName,
  4571. session_name);
  4572. if (c->Session->LinkModeClient && c->Session->Link != NULL)
  4573. {
  4574. HLog(c->Session->Link->Hub, "LH_CONNECT_2", c->Session->ClientOption->AccountName, session_name);
  4575. }
  4576. // Main routine of the session
  4577. SessionMain(c->Session);
  4578. ok = true;
  4579. if (c->Err == ERR_USER_CANCEL)
  4580. {
  4581. ret = true;
  4582. }
  4583. CLEANUP:
  4584. c->FirstSock = NULL;
  4585. if (sess->UdpAccel != NULL)
  4586. {
  4587. FreeUdpAccel(sess->UdpAccel);
  4588. sess->UdpAccel = NULL;
  4589. }
  4590. if (p != NULL)
  4591. {
  4592. FreePack(p);
  4593. }
  4594. Disconnect(s);
  4595. ReleaseSock(s);
  4596. Debug("Error: %u\n", c->Err);
  4597. if (ok == false)
  4598. {
  4599. PrintStatus(sess, L"free");
  4600. }
  4601. return ret;
  4602. }
  4603. // Parse the Welcome packet
  4604. bool ParseWelcomeFromPack(PACK *p, char *session_name, UINT session_name_size,
  4605. char *connection_name, UINT connection_name_size,
  4606. POLICY **policy)
  4607. {
  4608. // Validate arguments
  4609. if (p == NULL || session_name == NULL || connection_name == NULL || policy == NULL)
  4610. {
  4611. return false;
  4612. }
  4613. // Session name
  4614. if (PackGetStr(p, "session_name", session_name, session_name_size) == false)
  4615. {
  4616. return false;
  4617. }
  4618. // Connection name
  4619. if (PackGetStr(p, "connection_name", connection_name, connection_name_size) == false)
  4620. {
  4621. return false;
  4622. }
  4623. // Policy
  4624. *policy = PackGetPolicy(p);
  4625. if (*policy == NULL)
  4626. {
  4627. return false;
  4628. }
  4629. return true;
  4630. }
  4631. // Generate the Welcome packet
  4632. PACK *PackWelcome(SESSION *s)
  4633. {
  4634. PACK *p;
  4635. // Validate arguments
  4636. if (s == NULL)
  4637. {
  4638. return NULL;
  4639. }
  4640. p = NewPack();
  4641. // Session name
  4642. PackAddStr(p, "session_name", s->Name);
  4643. // Connection name
  4644. PackAddStr(p, "connection_name", s->Connection->Name);
  4645. // Parameters
  4646. PackAddInt(p, "max_connection", s->MaxConnection);
  4647. PackAddInt(p, "use_encrypt", s->UseEncrypt == false ? 0 : 1);
  4648. PackAddInt(p, "use_fast_rc4", s->UseFastRC4 == false ? 0 : 1);
  4649. PackAddInt(p, "use_compress", s->UseCompress == false ? 0 : 1);
  4650. PackAddInt(p, "half_connection", s->HalfConnection == false ? 0 : 1);
  4651. PackAddInt(p, "timeout", s->Timeout);
  4652. PackAddInt(p, "qos", s->QoS ? 1 : 0);
  4653. PackAddInt(p, "is_azure_session", s->IsAzureSession);
  4654. // Session key
  4655. PackAddData(p, "session_key", s->SessionKey, SHA1_SIZE);
  4656. PackAddInt(p, "session_key_32", s->SessionKey32);
  4657. // Policy
  4658. PackAddPolicy(p, s->Policy);
  4659. // VLAN ID
  4660. PackAddInt(p, "vlan_id", s->VLanId);
  4661. if (s->Connection->Protocol == CONNECTION_UDP)
  4662. {
  4663. // In the case of UDP protocol, generate 2 pairs of key
  4664. Rand(s->UdpSendKey, sizeof(s->UdpSendKey));
  4665. Rand(s->UdpRecvKey, sizeof(s->UdpRecvKey));
  4666. // Send to client by exchanging 2 keys
  4667. PackAddData(p, "udp_send_key", s->UdpRecvKey, sizeof(s->UdpRecvKey));
  4668. PackAddData(p, "udp_recv_key", s->UdpSendKey, sizeof(s->UdpSendKey));
  4669. }
  4670. // no_send_signature
  4671. if (s->NoSendSignature)
  4672. {
  4673. PackAddBool(p, "no_send_signature", true);
  4674. }
  4675. if (s->InProcMode)
  4676. {
  4677. // MAC address for IPC
  4678. PackAddData(p, "IpcMacAddress", s->IpcMacAddress, 6);
  4679. // Virtual HUB name
  4680. PackAddStr(p, "IpcHubName", s->Hub->Name);
  4681. }
  4682. if (s->UdpAccel != NULL)
  4683. {
  4684. // UDP acceleration function
  4685. PackAddBool(p, "use_udp_acceleration", true);
  4686. PackAddIp(p, "udp_acceleration_server_ip", &s->UdpAccel->MyIp);
  4687. PackAddInt(p, "udp_acceleration_server_port", s->UdpAccel->MyPort);
  4688. PackAddData(p, "udp_acceleration_server_key", s->UdpAccel->MyKey, UDP_ACCELERATION_COMMON_KEY_SIZE);
  4689. PackAddInt(p, "udp_acceleration_server_cookie", s->UdpAccel->MyCookie);
  4690. PackAddInt(p, "udp_acceleration_client_cookie", s->UdpAccel->YourCookie);
  4691. PackAddBool(p, "udp_acceleration_use_encryption", !s->UdpAccel->PlainTextMode);
  4692. PackAddBool(p, "use_hmac_on_udp_acceleration", s->UdpAccel->UseHMac);
  4693. PackAddBool(p, "udp_accel_fast_disconnect_detect", s->UdpAccelFastDisconnectDetect);
  4694. }
  4695. if (s->EnableBulkOnRUDP)
  4696. {
  4697. // Allow bulk transfer on R-UDP
  4698. PackAddBool(p, "enable_bulk_on_rudp", true);
  4699. PackAddBool(p, "enable_hmac_on_bulk_of_rudp", s->EnableHMacOnBulkOfRUDP);
  4700. PackAddData(p, "bulk_on_rudp_send_key", s->Connection->FirstSock->BulkRecvKey->Data, SHA1_SIZE);
  4701. PackAddData(p, "bulk_on_rudp_recv_key", s->Connection->FirstSock->BulkSendKey->Data, SHA1_SIZE);
  4702. }
  4703. if (s->IsAzureSession)
  4704. {
  4705. if (s->Connection != NULL && s->Connection->FirstSock != NULL)
  4706. {
  4707. SOCK *sock = s->Connection->FirstSock;
  4708. PackAddIp(p, "azure_real_server_global_ip", &sock->Reverse_MyServerGlobalIp);
  4709. }
  4710. }
  4711. PackAddBool(p, "enable_udp_recovery", s->EnableUdpRecovery);
  4712. return p;
  4713. }
  4714. #define PACK_ADD_POLICY_BOOL(name, value) \
  4715. PackAddInt(p, "policy:" name, y->value == false ? 0 : 1)
  4716. #define PACK_ADD_POLICY_UINT(name, value) \
  4717. PackAddInt(p, "policy:" name, y->value)
  4718. #define PACK_GET_POLICY_BOOL(name, value) \
  4719. y->value = (PackGetInt(p, "policy:" name) == 0 ? false : true)
  4720. #define PACK_GET_POLICY_UINT(name, value) \
  4721. y->value = PackGetInt(p, "policy:" name)
  4722. // Get a PACK from the session key
  4723. bool GetSessionKeyFromPack(PACK *p, UCHAR *session_key, UINT *session_key_32)
  4724. {
  4725. // Validate arguments
  4726. if (p == NULL || session_key == NULL || session_key_32 == NULL)
  4727. {
  4728. return false;
  4729. }
  4730. if (PackGetDataSize(p, "session_key") != SHA1_SIZE)
  4731. {
  4732. return false;
  4733. }
  4734. if (PackGetData(p, "session_key", session_key) == false)
  4735. {
  4736. return false;
  4737. }
  4738. *session_key_32 = PackGetInt(p, "session_key_32");
  4739. return true;
  4740. }
  4741. // Get the policy from the PACK
  4742. POLICY *PackGetPolicy(PACK *p)
  4743. {
  4744. POLICY *y;
  4745. // Validate arguments
  4746. if (p == NULL)
  4747. {
  4748. return NULL;
  4749. }
  4750. y = ZeroMalloc(sizeof(POLICY));
  4751. // Bool value
  4752. // Ver 2
  4753. PACK_GET_POLICY_BOOL("Access", Access);
  4754. PACK_GET_POLICY_BOOL("DHCPFilter", DHCPFilter);
  4755. PACK_GET_POLICY_BOOL("DHCPNoServer", DHCPNoServer);
  4756. PACK_GET_POLICY_BOOL("DHCPForce", DHCPForce);
  4757. PACK_GET_POLICY_BOOL("NoBridge", NoBridge);
  4758. PACK_GET_POLICY_BOOL("NoRouting", NoRouting);
  4759. PACK_GET_POLICY_BOOL("PrivacyFilter", PrivacyFilter);
  4760. PACK_GET_POLICY_BOOL("NoServer", NoServer);
  4761. PACK_GET_POLICY_BOOL("CheckMac", CheckMac);
  4762. PACK_GET_POLICY_BOOL("CheckIP", CheckIP);
  4763. PACK_GET_POLICY_BOOL("ArpDhcpOnly", ArpDhcpOnly);
  4764. PACK_GET_POLICY_BOOL("MonitorPort", MonitorPort);
  4765. PACK_GET_POLICY_BOOL("NoBroadcastLimiter", NoBroadcastLimiter);
  4766. PACK_GET_POLICY_BOOL("FixPassword", FixPassword);
  4767. PACK_GET_POLICY_BOOL("NoQoS", NoQoS);
  4768. // Ver 3
  4769. PACK_GET_POLICY_BOOL("RSandRAFilter", RSandRAFilter);
  4770. PACK_GET_POLICY_BOOL("RAFilter", RAFilter);
  4771. PACK_GET_POLICY_BOOL("DHCPv6Filter", DHCPv6Filter);
  4772. PACK_GET_POLICY_BOOL("DHCPv6NoServer", DHCPv6NoServer);
  4773. PACK_GET_POLICY_BOOL("NoRoutingV6", NoRoutingV6);
  4774. PACK_GET_POLICY_BOOL("CheckIPv6", CheckIPv6);
  4775. PACK_GET_POLICY_BOOL("NoServerV6", NoServerV6);
  4776. PACK_GET_POLICY_BOOL("NoSavePassword", NoSavePassword);
  4777. PACK_GET_POLICY_BOOL("FilterIPv4", FilterIPv4);
  4778. PACK_GET_POLICY_BOOL("FilterIPv6", FilterIPv6);
  4779. PACK_GET_POLICY_BOOL("FilterNonIP", FilterNonIP);
  4780. PACK_GET_POLICY_BOOL("NoIPv6DefaultRouterInRA", NoIPv6DefaultRouterInRA);
  4781. PACK_GET_POLICY_BOOL("NoIPv6DefaultRouterInRAWhenIPv6", NoIPv6DefaultRouterInRAWhenIPv6);
  4782. // UINT value
  4783. // Ver 2
  4784. PACK_GET_POLICY_UINT("MaxConnection", MaxConnection);
  4785. PACK_GET_POLICY_UINT("TimeOut", TimeOut);
  4786. PACK_GET_POLICY_UINT("MaxMac", MaxMac);
  4787. PACK_GET_POLICY_UINT("MaxIP", MaxIP);
  4788. PACK_GET_POLICY_UINT("MaxUpload", MaxUpload);
  4789. PACK_GET_POLICY_UINT("MaxDownload", MaxDownload);
  4790. PACK_GET_POLICY_UINT("MultiLogins", MultiLogins);
  4791. // Ver 3
  4792. PACK_GET_POLICY_UINT("MaxIPv6", MaxIPv6);
  4793. PACK_GET_POLICY_UINT("AutoDisconnect", AutoDisconnect);
  4794. PACK_GET_POLICY_UINT("VLanId", VLanId);
  4795. // Ver 3 flag
  4796. PACK_GET_POLICY_BOOL("Ver3", Ver3);
  4797. return y;
  4798. }
  4799. // Insert the policy into the PACK
  4800. void PackAddPolicy(PACK *p, POLICY *y)
  4801. {
  4802. // Validate arguments
  4803. if (p == NULL || y == NULL)
  4804. {
  4805. return;
  4806. }
  4807. // Bool value
  4808. // Ver 2
  4809. PACK_ADD_POLICY_BOOL("Access", Access);
  4810. PACK_ADD_POLICY_BOOL("DHCPFilter", DHCPFilter);
  4811. PACK_ADD_POLICY_BOOL("DHCPNoServer", DHCPNoServer);
  4812. PACK_ADD_POLICY_BOOL("DHCPForce", DHCPForce);
  4813. PACK_ADD_POLICY_BOOL("NoBridge", NoBridge);
  4814. PACK_ADD_POLICY_BOOL("NoRouting", NoRouting);
  4815. PACK_ADD_POLICY_BOOL("PrivacyFilter", PrivacyFilter);
  4816. PACK_ADD_POLICY_BOOL("NoServer", NoServer);
  4817. PACK_ADD_POLICY_BOOL("CheckMac", CheckMac);
  4818. PACK_ADD_POLICY_BOOL("CheckIP", CheckIP);
  4819. PACK_ADD_POLICY_BOOL("ArpDhcpOnly", ArpDhcpOnly);
  4820. PACK_ADD_POLICY_BOOL("MonitorPort", MonitorPort);
  4821. PACK_ADD_POLICY_BOOL("NoBroadcastLimiter", NoBroadcastLimiter);
  4822. PACK_ADD_POLICY_BOOL("FixPassword", FixPassword);
  4823. PACK_ADD_POLICY_BOOL("NoQoS", NoQoS);
  4824. // Ver 3
  4825. PACK_ADD_POLICY_BOOL("RSandRAFilter", RSandRAFilter);
  4826. PACK_ADD_POLICY_BOOL("RAFilter", RAFilter);
  4827. PACK_ADD_POLICY_BOOL("DHCPv6Filter", DHCPv6Filter);
  4828. PACK_ADD_POLICY_BOOL("DHCPv6NoServer", DHCPv6NoServer);
  4829. PACK_ADD_POLICY_BOOL("NoRoutingV6", NoRoutingV6);
  4830. PACK_ADD_POLICY_BOOL("CheckIPv6", CheckIPv6);
  4831. PACK_ADD_POLICY_BOOL("NoServerV6", NoServerV6);
  4832. PACK_ADD_POLICY_BOOL("NoSavePassword", NoSavePassword);
  4833. PACK_ADD_POLICY_BOOL("FilterIPv4", FilterIPv4);
  4834. PACK_ADD_POLICY_BOOL("FilterIPv6", FilterIPv6);
  4835. PACK_ADD_POLICY_BOOL("FilterNonIP", FilterNonIP);
  4836. PACK_ADD_POLICY_BOOL("NoIPv6DefaultRouterInRA", NoIPv6DefaultRouterInRA);
  4837. PACK_ADD_POLICY_BOOL("NoIPv6DefaultRouterInRAWhenIPv6", NoIPv6DefaultRouterInRAWhenIPv6);
  4838. // UINT value
  4839. // Ver 2
  4840. PACK_ADD_POLICY_UINT("MaxConnection", MaxConnection);
  4841. PACK_ADD_POLICY_UINT("TimeOut", TimeOut);
  4842. PACK_ADD_POLICY_UINT("MaxMac", MaxMac);
  4843. PACK_ADD_POLICY_UINT("MaxIP", MaxIP);
  4844. PACK_ADD_POLICY_UINT("MaxUpload", MaxUpload);
  4845. PACK_ADD_POLICY_UINT("MaxDownload", MaxDownload);
  4846. PACK_ADD_POLICY_UINT("MultiLogins", MultiLogins);
  4847. // Ver 3
  4848. PACK_ADD_POLICY_UINT("MaxIPv6", MaxIPv6);
  4849. PACK_ADD_POLICY_UINT("AutoDisconnect", AutoDisconnect);
  4850. PACK_ADD_POLICY_UINT("VLanId", VLanId);
  4851. // Ver 3 flag
  4852. PackAddBool(p, "policy:Ver3", true);
  4853. }
  4854. // Upload the authentication data for the additional connection
  4855. bool ClientUploadAuth2(CONNECTION *c, SOCK *s)
  4856. {
  4857. PACK *p = NULL;
  4858. // Validate arguments
  4859. if (c == NULL)
  4860. {
  4861. return false;
  4862. }
  4863. p = PackAdditionalConnect(c->Session->SessionKey);
  4864. PackAddClientVersion(p, c);
  4865. if (HttpClientSend(s, p) == false)
  4866. {
  4867. FreePack(p);
  4868. return false;
  4869. }
  4870. FreePack(p);
  4871. return true;
  4872. }
  4873. // Send a NOOP
  4874. void ClientUploadNoop(CONNECTION *c)
  4875. {
  4876. PACK *p;
  4877. // Validate arguments
  4878. if (c == NULL)
  4879. {
  4880. return;
  4881. }
  4882. p = PackError(0);
  4883. PackAddInt(p, "noop", 1);
  4884. HttpClientSend(c->FirstSock, p);
  4885. FreePack(p);
  4886. p = HttpClientRecv(c->FirstSock);
  4887. if (p != NULL)
  4888. {
  4889. FreePack(p);
  4890. }
  4891. }
  4892. // Add client version information to the PACK
  4893. void PackAddClientVersion(PACK *p, CONNECTION *c)
  4894. {
  4895. // Validate arguments
  4896. if (p == NULL || c == NULL)
  4897. {
  4898. return;
  4899. }
  4900. PackAddStr(p, "client_str", c->ClientStr);
  4901. PackAddInt(p, "client_ver", c->ClientVer);
  4902. PackAddInt(p, "client_build", c->ClientBuild);
  4903. }
  4904. // Upload the certificate data for the new connection
  4905. bool ClientUploadAuth(CONNECTION *c)
  4906. {
  4907. PACK *p = NULL;
  4908. CLIENT_AUTH *a;
  4909. CLIENT_OPTION *o;
  4910. X *x;
  4911. bool ret;
  4912. NODE_INFO info;
  4913. UCHAR secure_password[SHA1_SIZE];
  4914. UCHAR sign[4096 / 8];
  4915. UCHAR unique[SHA1_SIZE];
  4916. RPC_WINVER v;
  4917. // Validate arguments
  4918. if (c == NULL)
  4919. {
  4920. return false;
  4921. }
  4922. Zero(sign, sizeof(sign));
  4923. a = c->Session->ClientAuth;
  4924. o = c->Session->ClientOption;
  4925. if (c->UseTicket == false)
  4926. {
  4927. switch (a->AuthType)
  4928. {
  4929. case CLIENT_AUTHTYPE_ANONYMOUS:
  4930. // Anonymous authentication
  4931. p = PackLoginWithAnonymous(o->HubName, a->Username);
  4932. break;
  4933. case CLIENT_AUTHTYPE_PASSWORD:
  4934. // Password authentication
  4935. SecurePassword(secure_password, a->HashedPassword, c->Random);
  4936. p = PackLoginWithPassword(o->HubName, a->Username, secure_password);
  4937. break;
  4938. case CLIENT_AUTHTYPE_PLAIN_PASSWORD:
  4939. // Plaintext password authentication
  4940. p = PackLoginWithPlainPassword(o->HubName, a->Username, a->PlainPassword);
  4941. break;
  4942. case CLIENT_AUTHTYPE_CERT:
  4943. // Certificate authentication
  4944. if (a->ClientX != NULL && a->ClientX->is_compatible_bit &&
  4945. a->ClientX->bits != 0 && (a->ClientX->bits / 8) <= sizeof(sign))
  4946. {
  4947. if (RsaSignEx(sign, c->Random, SHA1_SIZE, a->ClientK, a->ClientX->bits))
  4948. {
  4949. p = PackLoginWithCert(o->HubName, a->Username, a->ClientX, sign, a->ClientX->bits / 8);
  4950. c->ClientX = CloneX(a->ClientX);
  4951. }
  4952. }
  4953. break;
  4954. case CLIENT_AUTHTYPE_SECURE:
  4955. // Authentication by secure device
  4956. if (ClientSecureSign(c, sign, c->Random, &x))
  4957. {
  4958. p = PackLoginWithCert(o->HubName, a->Username, x, sign, 128);
  4959. c->ClientX = CloneX(x);
  4960. FreeX(x);
  4961. }
  4962. else
  4963. {
  4964. c->Err = ERR_SECURE_DEVICE_OPEN_FAILED;
  4965. c->Session->ForceStopFlag = true;
  4966. }
  4967. break;
  4968. }
  4969. }
  4970. else
  4971. {
  4972. // Ticket
  4973. p = NewPack();
  4974. PackAddStr(p, "method", "login");
  4975. PackAddStr(p, "hubname", o->HubName);
  4976. PackAddStr(p, "username", a->Username);
  4977. PackAddInt(p, "authtype", AUTHTYPE_TICKET);
  4978. PackAddData(p, "ticket", c->Ticket, SHA1_SIZE);
  4979. }
  4980. // Current time
  4981. PackAddInt64(p, "timestamp", SystemTime64());
  4982. if (p == NULL)
  4983. {
  4984. // Error
  4985. if (c->Err != ERR_SECURE_DEVICE_OPEN_FAILED)
  4986. {
  4987. c->Err = ERR_PROTOCOL_ERROR;
  4988. }
  4989. return false;
  4990. }
  4991. PackAddClientVersion(p, c);
  4992. // Protocol
  4993. PackAddInt(p, "protocol", c->Protocol);
  4994. // Version, etc.
  4995. PackAddStr(p, "hello", c->ClientStr);
  4996. PackAddInt(p, "version", c->ClientVer);
  4997. PackAddInt(p, "build", c->ClientBuild);
  4998. PackAddInt(p, "client_id", c->Cedar->ClientId);
  4999. // The maximum number of connections
  5000. PackAddInt(p, "max_connection", o->MaxConnection);
  5001. // Flag to use of cryptography
  5002. PackAddInt(p, "use_encrypt", o->UseEncrypt == false ? 0 : 1);
  5003. // Fast encryption using flag
  5004. // PackAddInt(p, "use_fast_rc4", o->UseFastRC4 == false ? 0 : 1);
  5005. // Data compression flag
  5006. PackAddInt(p, "use_compress", o->UseCompress == false ? 0 : 1);
  5007. // Half connection flag
  5008. PackAddInt(p, "half_connection", o->HalfConnection == false ? 0 : 1);
  5009. // Bridge / routing mode flag
  5010. PackAddBool(p, "require_bridge_routing_mode", o->RequireBridgeRoutingMode);
  5011. // Monitor mode flag
  5012. PackAddBool(p, "require_monitor_mode", o->RequireMonitorMode);
  5013. // VoIP / QoS flag
  5014. PackAddBool(p, "qos", o->DisableQoS ? false : true);
  5015. // Bulk transfer support
  5016. PackAddBool(p, "support_bulk_on_rudp", true);
  5017. PackAddBool(p, "support_hmac_on_bulk_of_rudp", true);
  5018. // UDP recovery support
  5019. PackAddBool(p, "support_udp_recovery", true);
  5020. // Unique ID
  5021. GenerateMachineUniqueHash(unique);
  5022. PackAddData(p, "unique_id", unique, SHA1_SIZE);
  5023. // UDP acceleration function using flag
  5024. if (o->NoUdpAcceleration == false && c->Session->UdpAccel != NULL)
  5025. {
  5026. IP my_ip;
  5027. Zero(&my_ip, sizeof(my_ip));
  5028. PackAddBool(p, "use_udp_acceleration", true);
  5029. Copy(&my_ip, &c->Session->UdpAccel->MyIp, sizeof(IP));
  5030. if (IsLocalHostIP(&my_ip))
  5031. {
  5032. if (IsIP4(&my_ip))
  5033. {
  5034. ZeroIP4(&my_ip);
  5035. }
  5036. else
  5037. {
  5038. ZeroIP6(&my_ip);
  5039. }
  5040. }
  5041. PackAddIp(p, "udp_acceleration_client_ip", &my_ip);
  5042. PackAddInt(p, "udp_acceleration_client_port", c->Session->UdpAccel->MyPort);
  5043. PackAddData(p, "udp_acceleration_client_key", c->Session->UdpAccel->MyKey, UDP_ACCELERATION_COMMON_KEY_SIZE);
  5044. PackAddBool(p, "support_hmac_on_udp_acceleration", true);
  5045. PackAddBool(p, "support_udp_accel_fast_disconnect_detect", true);
  5046. }
  5047. // Brand string for the connection limit
  5048. {
  5049. char *branded_ctos = _SS("BRANDED_C_TO_S");
  5050. if(StrLen(branded_ctos) > 0)
  5051. {
  5052. PackAddStr(p, "branded_ctos", branded_ctos);
  5053. }
  5054. }
  5055. // Node information
  5056. CreateNodeInfo(&info, c);
  5057. OutRpcNodeInfo(p, &info);
  5058. // OS information
  5059. GetWinVer(&v);
  5060. OutRpcWinVer(p, &v);
  5061. ret = HttpClientSend(c->FirstSock, p);
  5062. if (ret == false)
  5063. {
  5064. c->Err = ERR_DISCONNECTED;
  5065. }
  5066. FreePack(p);
  5067. return ret;
  5068. }
  5069. // Upload the Hello packet
  5070. bool ServerUploadHello(CONNECTION *c)
  5071. {
  5072. PACK *p;
  5073. // Validate arguments
  5074. if (c == NULL)
  5075. {
  5076. return false;
  5077. }
  5078. // Random number generation
  5079. Rand(c->Random, SHA1_SIZE);
  5080. p = PackHello(c->Random, c->ServerVer, c->ServerBuild, c->ServerStr);
  5081. if (HttpServerSend(c->FirstSock, p) == false)
  5082. {
  5083. FreePack(p);
  5084. c->Err = ERR_DISCONNECTED;
  5085. return false;
  5086. }
  5087. FreePack(p);
  5088. return true;
  5089. }
  5090. // Download the Hello packet
  5091. bool ClientDownloadHello(CONNECTION *c, SOCK *s)
  5092. {
  5093. PACK *p;
  5094. UINT err;
  5095. UCHAR random[SHA1_SIZE];
  5096. // Validate arguments
  5097. if (c == NULL)
  5098. {
  5099. return false;
  5100. }
  5101. // Data reception
  5102. p = HttpClientRecv(s);
  5103. if (p == NULL)
  5104. {
  5105. c->Err = ERR_SERVER_IS_NOT_VPN;
  5106. return false;
  5107. }
  5108. if (err = GetErrorFromPack(p))
  5109. {
  5110. // An error has occured
  5111. c->Err = err;
  5112. FreePack(p);
  5113. return false;
  5114. }
  5115. // Packet interpretation
  5116. if (GetHello(p, random, &c->ServerVer, &c->ServerBuild, c->ServerStr, sizeof(c->ServerStr)) == false)
  5117. {
  5118. c->Err = ERR_SERVER_IS_NOT_VPN;
  5119. FreePack(p);
  5120. return false;
  5121. }
  5122. if (c->FirstSock == s)
  5123. {
  5124. Copy(c->Random, random, SHA1_SIZE);
  5125. }
  5126. FreePack(p);
  5127. return true;
  5128. }
  5129. // Download the signature
  5130. bool ServerDownloadSignature(CONNECTION *c, char **error_detail_str)
  5131. {
  5132. HTTP_HEADER *h;
  5133. UCHAR *data;
  5134. UINT data_size;
  5135. SOCK *s;
  5136. UINT num = 0, max = 19;
  5137. SERVER *server;
  5138. char *vpn_http_target = HTTP_VPN_TARGET2;
  5139. bool check_hostname = false;
  5140. // Validate arguments
  5141. if (c == NULL)
  5142. {
  5143. return false;
  5144. }
  5145. server = c->Cedar->Server;
  5146. s = c->FirstSock;
  5147. while (true)
  5148. {
  5149. bool not_found_error = false;
  5150. num++;
  5151. if (num > max)
  5152. {
  5153. // Disconnect
  5154. Disconnect(s);
  5155. c->Err = ERR_CLIENT_IS_NOT_VPN;
  5156. *error_detail_str = "HTTP_TOO_MANY_REQUEST";
  5157. return false;
  5158. }
  5159. // Receive a header
  5160. h = RecvHttpHeader(s);
  5161. if (h == NULL)
  5162. {
  5163. c->Err = ERR_CLIENT_IS_NOT_VPN;
  5164. return false;
  5165. }
  5166. if (check_hostname && (StrCmpi(h->Version, "HTTP/1.1") == 0 || StrCmpi(h->Version, "HTTP/1.2") == 0))
  5167. {
  5168. HTTP_VALUE *v;
  5169. char hostname[64];
  5170. Zero(hostname, sizeof(hostname));
  5171. v = GetHttpValue(h, "Host");
  5172. if (v != NULL)
  5173. {
  5174. StrCpy(hostname, sizeof(hostname), v->Data);
  5175. }
  5176. if (IsEmptyStr(hostname))
  5177. {
  5178. // Invalid hostname
  5179. HttpSendInvalidHostname(s, h->Target);
  5180. FreeHttpHeader(h);
  5181. c->Err = ERR_CLIENT_IS_NOT_VPN;
  5182. *error_detail_str = "Invalid_hostname";
  5183. return false;
  5184. }
  5185. }
  5186. // Interpret
  5187. if (StrCmpi(h->Method, "POST") == 0)
  5188. {
  5189. // Receive the data since it's POST
  5190. data_size = GetContentLength(h);
  5191. if ((data_size > MAX_WATERMARK_SIZE || data_size < SizeOfWaterMark()) && (data_size != StrLen(HTTP_VPN_TARGET_POSTDATA)))
  5192. {
  5193. // Data is too large
  5194. HttpSendForbidden(s, h->Target, NULL);
  5195. FreeHttpHeader(h);
  5196. c->Err = ERR_CLIENT_IS_NOT_VPN;
  5197. *error_detail_str = "POST_Recv_TooLong";
  5198. return false;
  5199. }
  5200. data = Malloc(data_size);
  5201. if (RecvAll(s, data, data_size, s->SecureMode) == false)
  5202. {
  5203. // Data reception failure
  5204. Free(data);
  5205. FreeHttpHeader(h);
  5206. c->Err = ERR_DISCONNECTED;
  5207. *error_detail_str = "POST_Recv_Failed";
  5208. return false;
  5209. }
  5210. // Check the Target
  5211. if ((StrCmpi(h->Target, vpn_http_target) != 0) || not_found_error)
  5212. {
  5213. // Target is invalid
  5214. HttpSendNotFound(s, h->Target);
  5215. Free(data);
  5216. FreeHttpHeader(h);
  5217. *error_detail_str = "POST_Target_Wrong";
  5218. }
  5219. else
  5220. {
  5221. // Compare posted data with the WaterMark
  5222. if ((data_size == StrLen(HTTP_VPN_TARGET_POSTDATA) && (Cmp(data, HTTP_VPN_TARGET_POSTDATA, data_size) == 0))
  5223. || (Cmp(data, WaterMark, SizeOfWaterMark()) == 0))
  5224. {
  5225. // Check the WaterMark
  5226. Free(data);
  5227. FreeHttpHeader(h);
  5228. return true;
  5229. }
  5230. else
  5231. {
  5232. // WaterMark is incorrect
  5233. HttpSendForbidden(s, h->Target, NULL);
  5234. FreeHttpHeader(h);
  5235. *error_detail_str = "POST_WaterMark_Error";
  5236. }
  5237. }
  5238. }
  5239. else if (StrCmpi(h->Method, "SSTP_DUPLEX_POST") == 0 && (server->DisableSSTPServer == false || s->IsReverseAcceptedSocket
  5240. ) &&
  5241. GetServerCapsBool(server, "b_support_sstp") && GetNoSstp() == false)
  5242. {
  5243. // SSTP client is connected
  5244. c->WasSstp = true;
  5245. if (StrCmpi(h->Target, SSTP_URI) == 0)
  5246. {
  5247. bool sstp_ret;
  5248. // Accept the SSTP connection
  5249. c->Type = CONNECTION_TYPE_SSTP;
  5250. sstp_ret = AcceptSstp(c);
  5251. c->Err = ERR_DISCONNECTED;
  5252. FreeHttpHeader(h);
  5253. if (sstp_ret)
  5254. {
  5255. *error_detail_str = "";
  5256. }
  5257. else
  5258. {
  5259. *error_detail_str = "SSTP_ABORT";
  5260. }
  5261. return false;
  5262. }
  5263. else
  5264. {
  5265. // URI is invalid
  5266. HttpSendNotFound(s, h->Target);
  5267. *error_detail_str = "SSTP_URL_WRONG";
  5268. }
  5269. FreeHttpHeader(h);
  5270. }
  5271. else
  5272. {
  5273. // This should not be a VPN client, but interpret a bit more
  5274. if (StrCmpi(h->Method, "GET") != 0 && StrCmpi(h->Method, "HEAD") != 0
  5275. && StrCmpi(h->Method, "POST") != 0)
  5276. {
  5277. // Unsupported method calls
  5278. HttpSendNotImplemented(s, h->Method, h->Target, h->Version);
  5279. *error_detail_str = "HTTP_BAD_METHOD";
  5280. }
  5281. else
  5282. {
  5283. if (StrCmpi(h->Target, "/") == 0)
  5284. {
  5285. // Root directory
  5286. SERVER *s = c->Cedar->Server;
  5287. bool is_free = false;
  5288. *error_detail_str = "HTTP_ROOT";
  5289. {
  5290. if (is_free == false)
  5291. {
  5292. // Other than free version
  5293. HttpSendForbidden(c->FirstSock, h->Target, "");
  5294. }
  5295. else
  5296. {
  5297. // Free version
  5298. BUF *b = ReadDump("|free.htm");
  5299. if (b != NULL)
  5300. {
  5301. char *src = ZeroMalloc(b->Size + 1);
  5302. UINT dst_size = b->Size * 2 + 64;
  5303. char *dst = ZeroMalloc(dst_size);
  5304. char host[MAX_PATH];
  5305. char portstr[64];
  5306. GetMachineName(host, sizeof(host));
  5307. ToStr(portstr, c->FirstSock->LocalPort);
  5308. Copy(src, b->Buf, b->Size);
  5309. ReplaceStrEx(dst, dst_size, src,
  5310. "$HOST$", host, false);
  5311. ReplaceStrEx(dst, dst_size, dst,
  5312. "$PORT$", portstr, false);
  5313. FreeHttpHeader(h);
  5314. h = NewHttpHeader("HTTP/1.1", "202", "OK");
  5315. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE4));
  5316. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  5317. AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
  5318. PostHttp(c->FirstSock, h, dst, StrLen(dst));
  5319. Free(src);
  5320. Free(dst);
  5321. FreeBuf(b);
  5322. }
  5323. }
  5324. }
  5325. }
  5326. else
  5327. {
  5328. bool b = false;
  5329. // Show the WebUI if the configuration allow to use the WebUI
  5330. if (c->Cedar->Server != NULL && c->Cedar->Server->UseWebUI)
  5331. {
  5332. WU_WEBPAGE *page;
  5333. // Show the WebUI
  5334. page = WuGetPage(h->Target, c->Cedar->WebUI);
  5335. if (page != NULL)
  5336. {
  5337. PostHttp(s, page->header, page->data, page->size);
  5338. b = true;
  5339. WuFreeWebPage(page);
  5340. }
  5341. }
  5342. if (c->FirstSock->RemoteIP.addr[0] == 127)
  5343. {
  5344. if (StrCmpi(h->Target, HTTP_SAITAMA) == 0)
  5345. {
  5346. // Saitama (joke)
  5347. FreeHttpHeader(h);
  5348. h = NewHttpHeader("HTTP/1.1", "202", "OK");
  5349. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE3));
  5350. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  5351. AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
  5352. PostHttp(s, h, Saitama, SizeOfSaitama());
  5353. b = true;
  5354. }
  5355. else if (StartWith(h->Target, HTTP_PICTURES))
  5356. {
  5357. BUF *buf;
  5358. // Lots of photos
  5359. buf = ReadDump("|Pictures.mht");
  5360. if (buf != NULL)
  5361. {
  5362. FreeHttpHeader(h);
  5363. h = NewHttpHeader("HTTP/1.1", "202", "OK");
  5364. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE5));
  5365. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  5366. AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
  5367. PostHttp(s, h, buf->Buf, buf->Size);
  5368. b = true;
  5369. FreeBuf(buf);
  5370. }
  5371. }
  5372. }
  5373. if (b == false)
  5374. {
  5375. // Not Found
  5376. HttpSendNotFound(s, h->Target);
  5377. *error_detail_str = "HTTP_NOT_FOUND";
  5378. }
  5379. }
  5380. }
  5381. FreeHttpHeader(h);
  5382. }
  5383. }
  5384. }
  5385. // Upload a signature
  5386. bool ClientUploadSignature(SOCK *s)
  5387. {
  5388. HTTP_HEADER *h;
  5389. UINT water_size, rand_size;
  5390. UCHAR *water;
  5391. char ip_str[128];
  5392. // Validate arguments
  5393. if (s == NULL)
  5394. {
  5395. return false;
  5396. }
  5397. IPToStr(ip_str, sizeof(ip_str), &s->RemoteIP);
  5398. h = NewHttpHeader("POST", HTTP_VPN_TARGET2, "HTTP/1.1");
  5399. AddHttpValue(h, NewHttpValue("Host", ip_str));
  5400. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE3));
  5401. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  5402. // Generate a watermark
  5403. rand_size = Rand32() % (HTTP_PACK_RAND_SIZE_MAX * 2);
  5404. water_size = SizeOfWaterMark() + rand_size;
  5405. water = Malloc(water_size);
  5406. Copy(water, WaterMark, SizeOfWaterMark());
  5407. Rand(&water[SizeOfWaterMark()], rand_size);
  5408. // Upload the watermark data
  5409. if (PostHttp(s, h, water, water_size) == false)
  5410. {
  5411. Free(water);
  5412. FreeHttpHeader(h);
  5413. return false;
  5414. }
  5415. Free(water);
  5416. FreeHttpHeader(h);
  5417. return true;
  5418. }
  5419. // Establish a connection to the server
  5420. SOCK *ClientConnectToServer(CONNECTION *c)
  5421. {
  5422. SOCK *s = NULL;
  5423. X *x = NULL;
  5424. K *k = NULL;
  5425. // Validate arguments
  5426. if (c == NULL)
  5427. {
  5428. return NULL;
  5429. }
  5430. if (c->Halt)
  5431. {
  5432. c->Err = ERR_USER_CANCEL;
  5433. return NULL;
  5434. }
  5435. // Get the socket by connecting
  5436. s = ClientConnectGetSocket(c, false, (c->DontUseTls1 ? false : true));
  5437. if (s == NULL)
  5438. {
  5439. // Connection failure
  5440. return NULL;
  5441. }
  5442. c->FirstSock = s;
  5443. if (c->Halt)
  5444. {
  5445. c->Err = ERR_USER_CANCEL;
  5446. ReleaseSock(s);
  5447. c->FirstSock = NULL;
  5448. return NULL;
  5449. }
  5450. // Time-out
  5451. SetTimeout(s, CONNECTING_TIMEOUT);
  5452. // Start the SSL communication
  5453. if (StartSSLEx(s, x, k, (c->DontUseTls1 ? false : true), 0, c->ServerName) == false)
  5454. {
  5455. // SSL communication start failure
  5456. Disconnect(s);
  5457. ReleaseSock(s);
  5458. c->FirstSock = NULL;
  5459. c->Err = ERR_SERVER_IS_NOT_VPN;
  5460. return NULL;
  5461. }
  5462. if (s->RemoteX == NULL)
  5463. {
  5464. // SSL communication start failure
  5465. Disconnect(s);
  5466. ReleaseSock(s);
  5467. c->FirstSock = NULL;
  5468. c->Err = ERR_SERVER_IS_NOT_VPN;
  5469. return NULL;
  5470. }
  5471. return s;
  5472. }
  5473. // Return a socket by connecting to the server
  5474. SOCK *ClientConnectGetSocket(CONNECTION *c, bool additional_connect, bool no_tls)
  5475. {
  5476. SOCK *s = NULL;
  5477. CLIENT_OPTION *o;
  5478. char *host_for_direct_connection;
  5479. UINT port_for_direct_connection;
  5480. wchar_t tmp[MAX_SIZE];
  5481. SESSION *sess;
  5482. volatile bool *cancel_flag = NULL;
  5483. void *hWnd;
  5484. UINT nat_t_err = 0;
  5485. bool is_additonal_rudp_session = false;
  5486. UCHAR uc = 0;
  5487. IP ret_ip;
  5488. // Validate arguments
  5489. if (c == NULL)
  5490. {
  5491. return NULL;
  5492. }
  5493. Zero(&ret_ip, sizeof(IP));
  5494. sess = c->Session;
  5495. if (sess != NULL)
  5496. {
  5497. cancel_flag = &sess->CancelConnect;
  5498. is_additonal_rudp_session = sess->IsRUDPSession;
  5499. }
  5500. hWnd = c->hWndForUI;
  5501. o = c->Session->ClientOption;
  5502. if (additional_connect)
  5503. {
  5504. if (sess != NULL)
  5505. {
  5506. Copy(&ret_ip, &sess->ServerIP_CacheForNextConnect, sizeof(IP));
  5507. }
  5508. }
  5509. if (c->RestoreServerNameAndPort && additional_connect)
  5510. {
  5511. // Restore to the original server name and port number
  5512. c->RestoreServerNameAndPort = false;
  5513. if (StrCmpi(c->ServerName, o->Hostname) != 0)
  5514. {
  5515. StrCpy(c->ServerName, sizeof(c->ServerName), o->Hostname);
  5516. Zero(&ret_ip, sizeof(IP));
  5517. }
  5518. c->ServerPort = o->Port;
  5519. }
  5520. host_for_direct_connection = c->ServerName;
  5521. port_for_direct_connection = c->ServerPort;
  5522. switch (o->ProxyType)
  5523. {
  5524. case PROXY_DIRECT: // TCP/IP
  5525. UniFormat(tmp, sizeof(tmp), _UU("STATUS_4"), c->ServerName);
  5526. PrintStatus(sess, tmp);
  5527. // Production job
  5528. if (o->PortUDP == 0)
  5529. {
  5530. {
  5531. // If additional_connect == false, enable trying to NAT-T connection
  5532. // If additional_connect == true, follow the IsRUDPSession setting in this session
  5533. s = TcpIpConnectEx(host_for_direct_connection, port_for_direct_connection,
  5534. (bool *)cancel_flag, hWnd, &nat_t_err, (additional_connect ? (!is_additonal_rudp_session) : false),
  5535. true, no_tls, &ret_ip);
  5536. }
  5537. }
  5538. else
  5539. {
  5540. // Mode to connect with R-UDP directly without using NAT-T server when using UDP
  5541. IP ip;
  5542. Zero(&ip, sizeof(ip));
  5543. StrToIP(&ip, o->Hostname);
  5544. s = NewRUDPClientDirect(VPN_RUDP_SVC_NAME, &ip, o->PortUDP, &nat_t_err,
  5545. TIMEOUT_TCP_PORT_CHECK, (bool *)cancel_flag, NULL, NULL, 0, false);
  5546. if (s != NULL)
  5547. {
  5548. StrCpy(s->UnderlayProtocol, sizeof(s->UnderlayProtocol), SOCK_UNDERLAY_NAT_T);
  5549. }
  5550. }
  5551. if (s == NULL)
  5552. {
  5553. // Connection failure
  5554. if (nat_t_err != RUDP_ERROR_NAT_T_TWO_OR_MORE)
  5555. {
  5556. c->Err = ERR_CONNECT_FAILED;
  5557. }
  5558. else
  5559. {
  5560. c->Err = ERR_NAT_T_TWO_OR_MORE;
  5561. }
  5562. return NULL;
  5563. }
  5564. break;
  5565. case PROXY_HTTP: // HTTP Proxy
  5566. host_for_direct_connection = o->ProxyName;
  5567. port_for_direct_connection = o->ProxyPort;
  5568. UniFormat(tmp, sizeof(tmp), _UU("STATUS_2"), c->ServerName, o->ProxyName);
  5569. PrintStatus(sess, tmp);
  5570. // Proxy connection
  5571. s = ProxyConnectEx(c, host_for_direct_connection, port_for_direct_connection,
  5572. c->ServerName, c->ServerPort, o->ProxyUsername, o->ProxyPassword,
  5573. additional_connect, (bool *)cancel_flag, hWnd);
  5574. if (s == NULL)
  5575. {
  5576. // Connection failure
  5577. return NULL;
  5578. }
  5579. break;
  5580. case PROXY_SOCKS: // SOCKS Proxy
  5581. host_for_direct_connection = o->ProxyName;
  5582. port_for_direct_connection = o->ProxyPort;
  5583. UniFormat(tmp, sizeof(tmp), _UU("STATUS_2"), c->ServerName, o->ProxyName);
  5584. PrintStatus(sess, tmp);
  5585. // SOCKS connection
  5586. s = SocksConnectEx2(c, host_for_direct_connection, port_for_direct_connection,
  5587. c->ServerName, c->ServerPort, o->ProxyUsername,
  5588. additional_connect, (bool *)cancel_flag, hWnd, 0, &ret_ip);
  5589. if (s == NULL)
  5590. {
  5591. // Connection failure
  5592. return NULL;
  5593. }
  5594. break;
  5595. }
  5596. if (s == NULL)
  5597. {
  5598. // Connection failure
  5599. c->Err = ERR_CONNECT_FAILED;
  5600. }
  5601. else
  5602. {
  5603. // Success to connect
  5604. // Keep a note of the IP address
  5605. if (additional_connect == false || IsZeroIP(&s->RemoteIP))
  5606. {
  5607. if (((s->IsRUDPSocket || s->IPv6) && IsZeroIP(&s->RemoteIP) == false && o->ProxyType == PROXY_DIRECT) || GetIP(&c->Session->ServerIP, host_for_direct_connection) == false)
  5608. {
  5609. Copy(&c->Session->ServerIP, &s->RemoteIP, sizeof(IP));
  5610. }
  5611. }
  5612. if (IsZeroIP(&ret_ip) == false)
  5613. {
  5614. if (c->Session != NULL)
  5615. {
  5616. if (additional_connect == false)
  5617. {
  5618. Copy(&c->Session->ServerIP_CacheForNextConnect, &ret_ip, sizeof(IP));
  5619. Debug("Saved ServerIP_CacheForNextConnect: %s = %r\n", c->ServerName, &ret_ip);
  5620. }
  5621. }
  5622. }
  5623. }
  5624. return s;
  5625. }
  5626. // Connect via SOCKS
  5627. SOCK *SocksConnect(CONNECTION *c, char *proxy_host_name, UINT proxy_port,
  5628. char *server_host_name, UINT server_port,
  5629. char *username, bool additional_connect)
  5630. {
  5631. return SocksConnectEx(c, proxy_host_name, proxy_port,
  5632. server_host_name, server_port, username, additional_connect, NULL, NULL);
  5633. }
  5634. SOCK *SocksConnectEx(CONNECTION *c, char *proxy_host_name, UINT proxy_port,
  5635. char *server_host_name, UINT server_port,
  5636. char *username, bool additional_connect,
  5637. bool *cancel_flag, void *hWnd)
  5638. {
  5639. return SocksConnectEx2(c, proxy_host_name, proxy_port,
  5640. server_host_name, server_port, username, additional_connect, cancel_flag,
  5641. hWnd, 0, NULL);
  5642. }
  5643. SOCK *SocksConnectEx2(CONNECTION *c, char *proxy_host_name, UINT proxy_port,
  5644. char *server_host_name, UINT server_port,
  5645. char *username, bool additional_connect,
  5646. bool *cancel_flag, void *hWnd, UINT timeout, IP *ret_ip)
  5647. {
  5648. SOCK *s = NULL;
  5649. IP ip;
  5650. // Validate arguments
  5651. if (c == NULL || proxy_host_name == NULL || proxy_port == 0 || server_host_name == NULL
  5652. || server_port == 0)
  5653. {
  5654. c->Err = ERR_PROXY_CONNECT_FAILED;
  5655. return NULL;
  5656. }
  5657. // Get the IP address of the destination server
  5658. if (GetIP(&ip, server_host_name) == false)
  5659. {
  5660. // Failure
  5661. c->Err = ERR_CONNECT_FAILED;
  5662. return NULL;
  5663. }
  5664. if (c->Halt)
  5665. {
  5666. // Stop
  5667. c->Err = ERR_USER_CANCEL;
  5668. return NULL;
  5669. }
  5670. // Connection
  5671. s = TcpConnectEx3(proxy_host_name, proxy_port, timeout, cancel_flag, hWnd, true, NULL, false, false, ret_ip);
  5672. if (s == NULL)
  5673. {
  5674. // Failure
  5675. c->Err = ERR_PROXY_CONNECT_FAILED;
  5676. return NULL;
  5677. }
  5678. // Timeout setting
  5679. SetTimeout(s, MIN(CONNECTING_TIMEOUT_PROXY, (timeout == 0 ? INFINITE : timeout)));
  5680. if (additional_connect == false)
  5681. {
  5682. c->FirstSock = s;
  5683. }
  5684. // Request packet transmission
  5685. if (SocksSendRequestPacket(c, s, server_port, &ip, username) == false)
  5686. {
  5687. // Failure
  5688. if (additional_connect == false)
  5689. {
  5690. c->FirstSock = NULL;
  5691. }
  5692. Disconnect(s);
  5693. ReleaseSock(s);
  5694. return NULL;
  5695. }
  5696. // Receive a response packet
  5697. if (SocksRecvResponsePacket(c, s) == false)
  5698. {
  5699. // Failure
  5700. if (additional_connect == false)
  5701. {
  5702. c->FirstSock = NULL;
  5703. }
  5704. Disconnect(s);
  5705. ReleaseSock(s);
  5706. return NULL;
  5707. }
  5708. SetTimeout(s, INFINITE);
  5709. return s;
  5710. }
  5711. // Receive a SOCKS response packet
  5712. bool SocksRecvResponsePacket(CONNECTION *c, SOCK *s)
  5713. {
  5714. BUF *b;
  5715. UINT size = 8;
  5716. UCHAR tmp[8];
  5717. UCHAR vn, cd;
  5718. // Validate arguments
  5719. if (c == NULL || s == NULL)
  5720. {
  5721. return false;
  5722. }
  5723. if (RecvAll(s, tmp, sizeof(tmp), false) == false)
  5724. {
  5725. c->Err = ERR_DISCONNECTED;
  5726. return false;
  5727. }
  5728. b = NewBuf();
  5729. WriteBuf(b, tmp, sizeof(tmp));
  5730. SeekBuf(b, 0, 0);
  5731. ReadBuf(b, &vn, 1);
  5732. ReadBuf(b, &cd, 1);
  5733. FreeBuf(b);
  5734. if (vn != 0)
  5735. {
  5736. c->Err = ERR_PROXY_ERROR;
  5737. return false;
  5738. }
  5739. switch (cd)
  5740. {
  5741. case 90:
  5742. // Success
  5743. return true;
  5744. case 93:
  5745. // Authentication failure
  5746. c->Err = ERR_PROXY_AUTH_FAILED;
  5747. return false;
  5748. default:
  5749. // Connection to the server failure
  5750. c->Err = ERR_CONNECT_FAILED;
  5751. return false;
  5752. }
  5753. }
  5754. // Send a SOCKS request packet
  5755. bool SocksSendRequestPacket(CONNECTION *c, SOCK *s, UINT dest_port, IP *dest_ip, char *userid)
  5756. {
  5757. BUF *b;
  5758. UCHAR vn, cd;
  5759. USHORT port;
  5760. UINT ip;
  5761. bool ret;
  5762. // Validate arguments
  5763. if (s == NULL || dest_port == 0 || dest_ip == NULL || c == NULL)
  5764. {
  5765. return false;
  5766. }
  5767. if (userid == NULL)
  5768. {
  5769. userid = "";
  5770. }
  5771. b = NewBuf();
  5772. vn = 4;
  5773. cd = 1;
  5774. WriteBuf(b, &vn, 1);
  5775. WriteBuf(b, &cd, 1);
  5776. port = Endian16((USHORT)dest_port);
  5777. ip = IPToUINT(dest_ip);
  5778. WriteBuf(b, &port, 2);
  5779. WriteBuf(b, &ip, 4);
  5780. WriteBuf(b, userid, StrLen(userid) + 1);
  5781. ret = SendAll(s, b->Buf, b->Size, false);
  5782. if (ret == false)
  5783. {
  5784. c->Err = ERR_DISCONNECTED;
  5785. }
  5786. FreeBuf(b);
  5787. return ret;
  5788. }
  5789. // Connect through a proxy
  5790. SOCK *ProxyConnect(CONNECTION *c, char *proxy_host_name, UINT proxy_port,
  5791. char *server_host_name, UINT server_port,
  5792. char *username, char *password, bool additional_connect)
  5793. {
  5794. return ProxyConnectEx(c, proxy_host_name, proxy_port,
  5795. server_host_name, server_port, username, password, additional_connect, NULL, NULL);
  5796. }
  5797. SOCK *ProxyConnectEx(CONNECTION *c, char *proxy_host_name, UINT proxy_port,
  5798. char *server_host_name, UINT server_port,
  5799. char *username, char *password, bool additional_connect,
  5800. bool *cancel_flag, void *hWnd)
  5801. {
  5802. return ProxyConnectEx2(c, proxy_host_name, proxy_port,
  5803. server_host_name, server_port, username, password, additional_connect,
  5804. cancel_flag, hWnd, 0);
  5805. }
  5806. SOCK *ProxyConnectEx2(CONNECTION *c, char *proxy_host_name, UINT proxy_port,
  5807. char *server_host_name, UINT server_port,
  5808. char *username, char *password, bool additional_connect,
  5809. bool *cancel_flag, void *hWnd, UINT timeout)
  5810. {
  5811. SOCK *s = NULL;
  5812. bool use_auth = false;
  5813. char tmp[MAX_SIZE];
  5814. char auth_tmp_str[MAX_SIZE], auth_b64_str[MAX_SIZE * 2];
  5815. char basic_str[MAX_SIZE * 2];
  5816. UINT http_error_code;
  5817. HTTP_HEADER *h;
  5818. char server_host_name_tmp[256];
  5819. UINT i, len;
  5820. // Validate arguments
  5821. if (c == NULL || proxy_host_name == NULL || proxy_port == 0 || server_host_name == NULL ||
  5822. server_port == 0)
  5823. {
  5824. c->Err = ERR_PROXY_CONNECT_FAILED;
  5825. return NULL;
  5826. }
  5827. if (username != NULL && password != NULL &&
  5828. (StrLen(username) != 0 || StrLen(password) != 0))
  5829. {
  5830. use_auth = true;
  5831. }
  5832. if (c->Halt)
  5833. {
  5834. // Stop
  5835. c->Err = ERR_USER_CANCEL;
  5836. return NULL;
  5837. }
  5838. Zero(server_host_name_tmp, sizeof(server_host_name_tmp));
  5839. StrCpy(server_host_name_tmp, sizeof(server_host_name_tmp), server_host_name);
  5840. len = StrLen(server_host_name_tmp);
  5841. for (i = 0;i < len;i++)
  5842. {
  5843. if (server_host_name_tmp[i] == '/')
  5844. {
  5845. server_host_name_tmp[i] = 0;
  5846. }
  5847. }
  5848. // Connection
  5849. s = TcpConnectEx3(proxy_host_name, proxy_port, timeout, cancel_flag, hWnd, true, NULL, false, false, NULL);
  5850. if (s == NULL)
  5851. {
  5852. // Failure
  5853. c->Err = ERR_PROXY_CONNECT_FAILED;
  5854. return NULL;
  5855. }
  5856. // Timeout setting
  5857. SetTimeout(s, MIN(CONNECTING_TIMEOUT_PROXY, (timeout == 0 ? INFINITE : timeout)));
  5858. if (additional_connect == false)
  5859. {
  5860. c->FirstSock = s;
  5861. }
  5862. // HTTP header generation
  5863. if (IsStrIPv6Address(server_host_name_tmp))
  5864. {
  5865. IP ip;
  5866. char iptmp[MAX_PATH];
  5867. StrToIP(&ip, server_host_name_tmp);
  5868. IPToStr(iptmp, sizeof(iptmp), &ip);
  5869. Format(tmp, sizeof(tmp), "[%s]:%u", iptmp, server_port);
  5870. }
  5871. else
  5872. {
  5873. Format(tmp, sizeof(tmp), "%s:%u", server_host_name_tmp, server_port);
  5874. }
  5875. h = NewHttpHeader("CONNECT", tmp, "HTTP/1.0");
  5876. AddHttpValue(h, NewHttpValue("User-Agent", (c->Cedar == NULL ? DEFAULT_USER_AGENT : c->Cedar->HttpUserAgent)));
  5877. AddHttpValue(h, NewHttpValue("Host", server_host_name_tmp));
  5878. AddHttpValue(h, NewHttpValue("Content-Length", "0"));
  5879. AddHttpValue(h, NewHttpValue("Proxy-Connection", "Keep-Alive"));
  5880. AddHttpValue(h, NewHttpValue("Pragma", "no-cache"));
  5881. if (use_auth)
  5882. {
  5883. wchar_t tmp[MAX_SIZE];
  5884. UniFormat(tmp, sizeof(tmp), _UU("STATUS_3"), server_host_name_tmp);
  5885. // Generate the authentication string
  5886. Format(auth_tmp_str, sizeof(auth_tmp_str), "%s:%s",
  5887. username, password);
  5888. // Base64 encode
  5889. Zero(auth_b64_str, sizeof(auth_b64_str));
  5890. Encode64(auth_b64_str, auth_tmp_str);
  5891. Format(basic_str, sizeof(basic_str), "Basic %s", auth_b64_str);
  5892. AddHttpValue(h, NewHttpValue("Proxy-Authorization", basic_str));
  5893. }
  5894. // Transmission
  5895. if (SendHttpHeader(s, h) == false)
  5896. {
  5897. // Failure
  5898. if (additional_connect == false)
  5899. {
  5900. c->FirstSock = NULL;
  5901. }
  5902. FreeHttpHeader(h);
  5903. Disconnect(s);
  5904. ReleaseSock(s);
  5905. c->Err = ERR_PROXY_ERROR;
  5906. return NULL;
  5907. }
  5908. FreeHttpHeader(h);
  5909. if (c->Halt)
  5910. {
  5911. // Stop
  5912. if (additional_connect == false)
  5913. {
  5914. c->FirstSock = NULL;
  5915. }
  5916. Disconnect(s);
  5917. ReleaseSock(s);
  5918. c->Err = ERR_USER_CANCEL;
  5919. return NULL;
  5920. }
  5921. // Receive the results
  5922. h = RecvHttpHeader(s);
  5923. if (h == NULL)
  5924. {
  5925. // Failure
  5926. if (additional_connect == false)
  5927. {
  5928. c->FirstSock = NULL;
  5929. }
  5930. FreeHttpHeader(h);
  5931. Disconnect(s);
  5932. ReleaseSock(s);
  5933. c->Err = ERR_PROXY_ERROR;
  5934. return NULL;
  5935. }
  5936. http_error_code = 0;
  5937. if (StrLen(h->Method) == 8)
  5938. {
  5939. if (Cmp(h->Method, "HTTP/1.", 7) == 0)
  5940. {
  5941. http_error_code = ToInt(h->Target);
  5942. }
  5943. }
  5944. FreeHttpHeader(h);
  5945. // Check the code
  5946. switch (http_error_code)
  5947. {
  5948. case 401:
  5949. case 403:
  5950. case 407:
  5951. // Authentication failure
  5952. if (additional_connect == false)
  5953. {
  5954. c->FirstSock = NULL;
  5955. }
  5956. Disconnect(s);
  5957. ReleaseSock(s);
  5958. c->Err = ERR_PROXY_AUTH_FAILED;
  5959. return NULL;
  5960. default:
  5961. if ((http_error_code / 100) == 2)
  5962. {
  5963. // Success
  5964. SetTimeout(s, INFINITE);
  5965. return s;
  5966. }
  5967. else
  5968. {
  5969. // Receive an unknown result
  5970. if (additional_connect == false)
  5971. {
  5972. c->FirstSock = NULL;
  5973. }
  5974. Disconnect(s);
  5975. ReleaseSock(s);
  5976. c->Err = ERR_PROXY_ERROR;
  5977. return NULL;
  5978. }
  5979. }
  5980. }
  5981. // TCP connection function
  5982. SOCK *TcpConnectEx2(char *hostname, UINT port, UINT timeout, bool *cancel_flag, void *hWnd, bool try_start_ssl, bool ssl_no_tls)
  5983. {
  5984. return TcpConnectEx3(hostname, port, timeout, cancel_flag, hWnd, false, NULL, try_start_ssl, ssl_no_tls, NULL);
  5985. }
  5986. 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)
  5987. {
  5988. #ifdef OS_WIN32
  5989. if (hWnd == NULL)
  5990. {
  5991. #endif // OS_WIN32
  5992. 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);
  5993. #ifdef OS_WIN32
  5994. }
  5995. else
  5996. {
  5997. 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);
  5998. }
  5999. #endif // OS_WIN32
  6000. }
  6001. // Connect with TCP/IP
  6002. SOCK *TcpIpConnect(char *hostname, UINT port, bool try_start_ssl, bool ssl_no_tls)
  6003. {
  6004. return TcpIpConnectEx(hostname, port, NULL, NULL, NULL, false, try_start_ssl, ssl_no_tls, NULL);
  6005. }
  6006. 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)
  6007. {
  6008. SOCK *s = NULL;
  6009. UINT dummy_int = 0;
  6010. // Validate arguments
  6011. if (nat_t_error_code == NULL)
  6012. {
  6013. nat_t_error_code = &dummy_int;
  6014. }
  6015. *nat_t_error_code = 0;
  6016. if (hostname == NULL || port == 0)
  6017. {
  6018. return NULL;
  6019. }
  6020. s = TcpConnectEx3(hostname, port, 0, cancel_flag, hWnd, no_nat_t, nat_t_error_code, try_start_ssl, ssl_no_tls, ret_ip);
  6021. if (s == NULL)
  6022. {
  6023. return NULL;
  6024. }
  6025. return s;
  6026. }
  6027. // Protocol routine initialization
  6028. void InitProtocol()
  6029. {
  6030. }
  6031. // Release the protocol routine
  6032. void FreeProtocol()
  6033. {
  6034. }
  6035. // Create a Hello packet
  6036. PACK *PackHello(void *random, UINT ver, UINT build, char *server_str)
  6037. {
  6038. PACK *p;
  6039. // Validate arguments
  6040. if (random == NULL || server_str == NULL)
  6041. {
  6042. return NULL;
  6043. }
  6044. p = NewPack();
  6045. PackAddStr(p, "hello", server_str);
  6046. PackAddInt(p, "version", ver);
  6047. PackAddInt(p, "build", build);
  6048. PackAddData(p, "random", random, SHA1_SIZE);
  6049. return p;
  6050. }
  6051. // Interpret the Hello packet
  6052. bool GetHello(PACK *p, void *random, UINT *ver, UINT *build, char *server_str, UINT server_str_size)
  6053. {
  6054. // Validate arguments
  6055. if (p == NULL || random == NULL || ver == NULL || server_str == NULL)
  6056. {
  6057. return false;
  6058. }
  6059. if (PackGetStr(p, "hello", server_str, server_str_size) == false)
  6060. {
  6061. return false;
  6062. }
  6063. *ver = PackGetInt(p, "version");
  6064. *build = PackGetInt(p, "build");
  6065. if (PackGetDataSize(p, "random") != SHA1_SIZE)
  6066. {
  6067. return false;
  6068. }
  6069. if (PackGetData(p, "random", random) == false)
  6070. {
  6071. return false;
  6072. }
  6073. return true;
  6074. }
  6075. // Get the authentication method from PACK
  6076. UINT GetAuthTypeFromPack(PACK *p)
  6077. {
  6078. // Validate arguments
  6079. if (p == NULL)
  6080. {
  6081. return 0;
  6082. }
  6083. return PackGetInt(p, "authtype");
  6084. }
  6085. // Get the HUB name and the user name from the PACK
  6086. bool GetHubnameAndUsernameFromPack(PACK *p, char *username, UINT username_size,
  6087. char *hubname, UINT hubname_size)
  6088. {
  6089. // Validate arguments
  6090. if (p == NULL || username == NULL || hubname == NULL)
  6091. {
  6092. return false;
  6093. }
  6094. if (PackGetStr(p, "username", username, username_size) == false)
  6095. {
  6096. return false;
  6097. }
  6098. if (PackGetStr(p, "hubname", hubname, hubname_size) == false)
  6099. {
  6100. return false;
  6101. }
  6102. return true;
  6103. }
  6104. // Get the protocol from PACK
  6105. UINT GetProtocolFromPack(PACK *p)
  6106. {
  6107. // Validate arguments
  6108. if (p == NULL)
  6109. {
  6110. return 0;
  6111. }
  6112. #if 0
  6113. return PackGetInt(p, "protocol");
  6114. #else
  6115. // Limit to the TCP protocol in the current version
  6116. return CONNECTION_TCP;
  6117. #endif
  6118. }
  6119. // Get the method from the PACK
  6120. bool GetMethodFromPack(PACK *p, char *method, UINT size)
  6121. {
  6122. // Validate arguments
  6123. if (p == NULL || method == NULL || size == 0)
  6124. {
  6125. return false;
  6126. }
  6127. return PackGetStr(p, "method", method, size);
  6128. }
  6129. // Generate a packet of certificate authentication login
  6130. PACK *PackLoginWithCert(char *hubname, char *username, X *x, void *sign, UINT sign_size)
  6131. {
  6132. PACK *p;
  6133. BUF *b;
  6134. // Validate arguments
  6135. if (hubname == NULL || username == NULL)
  6136. {
  6137. return NULL;
  6138. }
  6139. p = NewPack();
  6140. PackAddStr(p, "method", "login");
  6141. PackAddStr(p, "hubname", hubname);
  6142. PackAddStr(p, "username", username);
  6143. PackAddInt(p, "authtype", CLIENT_AUTHTYPE_CERT);
  6144. // Certificate
  6145. b = XToBuf(x, false);
  6146. PackAddData(p, "cert", b->Buf, b->Size);
  6147. FreeBuf(b);
  6148. // Signature data
  6149. PackAddData(p, "sign", sign, sign_size);
  6150. return p;
  6151. }
  6152. // Generate a packet of plain text password authentication login
  6153. PACK *PackLoginWithPlainPassword(char *hubname, char *username, void *plain_password)
  6154. {
  6155. PACK *p;
  6156. // Validate arguments
  6157. if (hubname == NULL || username == NULL)
  6158. {
  6159. return NULL;
  6160. }
  6161. p = NewPack();
  6162. PackAddStr(p, "method", "login");
  6163. PackAddStr(p, "hubname", hubname);
  6164. PackAddStr(p, "username", username);
  6165. PackAddInt(p, "authtype", CLIENT_AUTHTYPE_PLAIN_PASSWORD);
  6166. PackAddStr(p, "plain_password", plain_password);
  6167. return p;
  6168. }
  6169. // Create a packet of password authentication login
  6170. PACK *PackLoginWithPassword(char *hubname, char *username, void *secure_password)
  6171. {
  6172. PACK *p;
  6173. // Validate arguments
  6174. if (hubname == NULL || username == NULL)
  6175. {
  6176. return NULL;
  6177. }
  6178. p = NewPack();
  6179. PackAddStr(p, "method", "login");
  6180. PackAddStr(p, "hubname", hubname);
  6181. PackAddStr(p, "username", username);
  6182. PackAddInt(p, "authtype", CLIENT_AUTHTYPE_PASSWORD);
  6183. PackAddData(p, "secure_password", secure_password, SHA1_SIZE);
  6184. return p;
  6185. }
  6186. // Create a packet for anonymous login
  6187. PACK *PackLoginWithAnonymous(char *hubname, char *username)
  6188. {
  6189. PACK *p;
  6190. // Validate arguments
  6191. if (hubname == NULL || username == NULL)
  6192. {
  6193. return NULL;
  6194. }
  6195. p = NewPack();
  6196. PackAddStr(p, "method", "login");
  6197. PackAddStr(p, "hubname", hubname);
  6198. PackAddStr(p, "username", username);
  6199. PackAddInt(p, "authtype", CLIENT_AUTHTYPE_ANONYMOUS);
  6200. return p;
  6201. }
  6202. // Create a packet for the additional connection
  6203. PACK *PackAdditionalConnect(UCHAR *session_key)
  6204. {
  6205. PACK *p;
  6206. // Validate arguments
  6207. if (session_key == NULL)
  6208. {
  6209. return NULL;
  6210. }
  6211. p = NewPack();
  6212. PackAddStr(p, "method", "additional_connect");
  6213. PackAddData(p, "session_key", session_key, SHA1_SIZE);
  6214. return p;
  6215. }
  6216. // Generate a RC4 key pair
  6217. void GenerateRC4KeyPair(RC4_KEY_PAIR *k)
  6218. {
  6219. // Validate arguments
  6220. if (k == NULL)
  6221. {
  6222. return;
  6223. }
  6224. Rand(k->ClientToServerKey, sizeof(k->ClientToServerKey));
  6225. Rand(k->ServerToClientKey, sizeof(k->ServerToClientKey));
  6226. }
  6227. // Developed by SoftEther VPN Project at University of Tsukuba in Japan.
  6228. // Department of Computer Science has dozens of overly-enthusiastic geeks.
  6229. // Join us: http://www.tsukuba.ac.jp/english/admission/