vlmcsd_all.c 181 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009
  1. #ifndef CONFIG
  2. #define CONFIG "config.h"
  3. #endif // CONFIG
  4. #include CONFIG
  5. #if defined(USE_MSRPC) && !defined(_WIN32) && !defined(__CYGWIN__)
  6. #error Microsoft RPC is only available on Windows and Cygwin
  7. #endif
  8. #if defined(NO_SOCKETS) && defined(USE_MSRPC)
  9. #error Cannot use inetd mode with Microsoft RPC
  10. #endif
  11. #ifndef _GNU_SOURCE
  12. #define _GNU_SOURCE
  13. #endif
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <errno.h>
  18. #include <stdint.h>
  19. #ifndef _WIN32
  20. #include <pwd.h>
  21. #include <grp.h>
  22. #include <sys/types.h>
  23. #if !defined(NO_LIMIT) && !__minix__
  24. #include <sys/ipc.h>
  25. #if !__ANDROID__
  26. #include <sys/shm.h>
  27. #else // __ANDROID__
  28. #include <sys/syscall.h>
  29. #endif // __ANDROID__
  30. #endif // !defined(NO_LIMIT) && !__minix__
  31. #include <sys/wait.h>
  32. #include <unistd.h>
  33. #include <fcntl.h>
  34. #include <sys/stat.h>
  35. #include <semaphore.h>
  36. #endif // !_WIN32
  37. #if __APPLE__
  38. #include <mach-o/dyld.h>
  39. #endif // __APPLE__
  40. #if __linux__ && defined(USE_AUXV)
  41. #include <sys/auxv.h>
  42. #endif
  43. #if __FreeBSD__
  44. #include <sys/sysctl.h>
  45. #endif
  46. #include "vlmcsd.h"
  47. #include "endian.h"
  48. #include "shared_globals.h"
  49. #include "output.h"
  50. #ifndef USE_MSRPC
  51. #include "network.h"
  52. #else // USE_MSRPC
  53. #include "msrpc-server.h"
  54. #endif // USE_MSRPC
  55. #include "ntservice.h"
  56. #include "helpers.h"
  57. static const char* const optstring = "N:B:m:t:w:0:3:H:A:R:u:g:L:p:i:P:l:r:U:W:C:SsfeDd46VvIdqkZ";
  58. #if !defined(NO_SOCKETS)
  59. #if !defined(USE_MSRPC)
  60. static uint_fast8_t maxsockets = 0;
  61. static int_fast8_t haveIPv6Stack = 0;
  62. static int_fast8_t haveIPv4Stack = 0;
  63. static int_fast8_t v6required = 0;
  64. static int_fast8_t v4required = 0;
  65. #endif // !defined(USE_MSRPC)
  66. #endif // !defined(NO_SOCKETS)
  67. #ifdef _NTSERVICE
  68. static int_fast8_t installService = 0;
  69. static const char *restrict ServiceUser = NULL;
  70. static const char *restrict ServicePassword = "";
  71. #endif
  72. #ifndef NO_PID_FILE
  73. static const char *fn_pid = NULL;
  74. #endif
  75. #ifndef NO_INI_FILE
  76. #ifdef INI_FILE
  77. static const char *fn_ini = INI_FILE;
  78. #else // !INI_FILE
  79. static const char *fn_ini = NULL;
  80. #endif // !INI_FILE
  81. static const char* IniFileErrorMessage = "";
  82. char* IniFileErrorBuffer = NULL;
  83. #define INIFILE_ERROR_BUFFERSIZE 256
  84. static IniFileParameter_t IniFileParameterList[] =
  85. {
  86. # ifndef NO_RANDOM_EPID
  87. { "RandomizationLevel", INI_PARAM_RANDOMIZATION_LEVEL },
  88. { "LCID", INI_PARAM_LCID },
  89. # endif // NO_RANDOM_EPID
  90. # ifdef USE_MSRPC
  91. { "Port", INI_PARAM_PORT },
  92. # endif // USE_MSRPC
  93. # if !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  94. { "Listen", INI_PARAM_LISTEN },
  95. # if !defined(NO_LIMIT) && !__minix__
  96. { "MaxWorkers", INI_PARAM_MAX_WORKERS },
  97. # endif // !defined(NO_LIMIT) && !__minix__
  98. # endif // !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  99. # if !defined(NO_TIMEOUT) && !__minix__ && !defined(USE_MSRPC) & !defined(USE_MSRPC)
  100. { "ConnectionTimeout", INI_PARAM_CONNECTION_TIMEOUT },
  101. # endif // !defined(NO_TIMEOUT) && !__minix__ && !defined(USE_MSRPC) & !defined(USE_MSRPC)
  102. # ifndef USE_MSRPC
  103. { "DisconnectClientsImmediately", INI_PARAM_DISCONNECT_IMMEDIATELY },
  104. { "UseNDR64", INI_PARAM_RPC_NDR64 },
  105. { "UseBTFN", INI_PARAM_RPC_BTFN },
  106. # endif // USE_MSRPC
  107. # ifndef NO_PID_FILE
  108. { "PIDFile", INI_PARAM_PID_FILE },
  109. # endif // NO_PID_FILE
  110. # ifndef NO_LOG
  111. { "LogFile", INI_PARAM_LOG_FILE },
  112. # ifndef NO_VERBOSE_LOG
  113. { "LogVerbose", INI_PARAM_LOG_VERBOSE },
  114. # endif // NO_VERBOSE_LOG
  115. # endif // NO_LOG
  116. # ifndef NO_CUSTOM_INTERVALS
  117. {"ActivationInterval", INI_PARAM_ACTIVATION_INTERVAL },
  118. {"RenewalInterval", INI_PARAM_RENEWAL_INTERVAL },
  119. # endif // NO_CUSTOM_INTERVALS
  120. # if !defined(NO_USER_SWITCH) && !defined(_WIN32)
  121. { "user", INI_PARAM_UID },
  122. { "group", INI_PARAM_GID},
  123. # endif // !defined(NO_USER_SWITCH) && !defined(_WIN32)
  124. };
  125. #endif // NO_INI_FILE
  126. #if !defined(NO_LIMIT) && !defined (NO_SOCKETS) && !__minix__
  127. #if !defined(USE_THREADS) && !defined(CYGWIN) && !defined(USE_MSRPC)
  128. static int shmid = -1;
  129. #endif
  130. #if __ANDROID__ && !defined(USE_THREADS) // Bionic does not wrap these syscalls (willingly because Google fears, developers don't know how to use it)
  131. #ifdef __NR_shmget
  132. static int shmget(key_t key, size_t size, int shmflg)
  133. {
  134. return syscall(__NR_shmget, key, size, shmflg);
  135. }
  136. #endif // __NR_shmget
  137. #ifdef __NR_shmat
  138. static void *shmat(int shmid, const void *shmaddr, int shmflg)
  139. {
  140. return (void *)syscall(__NR_shmat, shmid, shmaddr, shmflg);
  141. }
  142. #endif // __NR_shmat
  143. #ifdef __NR_shmdt
  144. static int shmdt(const void *shmaddr)
  145. {
  146. return syscall(__NR_shmdt, shmaddr);
  147. }
  148. #endif // __NR_shmdt
  149. #ifdef __NR_shmctl
  150. static int shmctl(int shmid, int cmd, /*struct shmid_ds*/void *buf)
  151. {
  152. return syscall(__NR_shmctl, shmid, cmd, buf);
  153. }
  154. #endif // __NR_shmctl
  155. #endif // __ANDROID__ && !defined(USE_THREADS)
  156. #endif // !defined(NO_LIMIT) && !defined (NO_SOCKETS) && !__minix__
  157. #ifndef NO_USER_SWITCH
  158. #ifndef _WIN32
  159. static const char *uname = NULL, *gname = NULL;
  160. static gid_t gid = INVALID_GID;
  161. static uid_t uid = INVALID_UID;
  162. // Get Numeric id of user/group
  163. static char GetNumericId(gid_t *restrict id, const char *const c)
  164. {
  165. char* endptr;
  166. gid_t temp;
  167. temp = (gid_t)strtoll(c, &endptr, 10);
  168. if (!*endptr) *id = temp;
  169. return *endptr;
  170. }
  171. // Get group id from option argument
  172. static char GetGid()
  173. {
  174. struct group *g;
  175. if ((g = getgrnam(optarg)))
  176. gid = g->gr_gid;
  177. else
  178. return GetNumericId(&gid, optarg);
  179. return 0;
  180. }
  181. // Get user id from option argument
  182. static char GetUid()
  183. {
  184. struct passwd *u;
  185. ////PORTABILITY: Assumes uid_t and gid_t are of same size (shouldn't be a problem)
  186. if ((u = getpwnam(optarg)))
  187. uid = u->pw_uid;
  188. else
  189. return GetNumericId((gid_t*)&uid, optarg);
  190. return 0;
  191. }
  192. #endif // _WIN32
  193. #endif //NO_USER_SWITCH
  194. #ifdef NO_HELP
  195. static __noreturn void usage()
  196. {
  197. printerrorf("Incorrect parameters\n\n");
  198. exit(!0);
  199. }
  200. #else // HELP
  201. static __noreturn void usage()
  202. {
  203. printerrorf("vlmcsd %s\n"
  204. "\nUsage:\n"
  205. " %s [ options ]\n\n"
  206. "Where:\n"
  207. #ifndef NO_CL_PIDS
  208. " -w <ePID> always use <ePID> for Windows\n"
  209. " -0 <ePID> always use <ePID> for Office2010\n"
  210. " -3 <ePID> always use <ePID> for Office2013\n"
  211. " -H <HwId> always use hardware Id <HwId>\n"
  212. #endif // NO_CL_PIDS
  213. #if !defined(_WIN32) && !defined(NO_USER_SWITCH)
  214. " -u <user> set uid to <user>\n"
  215. " -g <group> set gid to <group>\n"
  216. #endif // !defined(_WIN32) && !defined(NO_USER_SWITCH)
  217. #ifndef NO_RANDOM_EPID
  218. " -r 0|1|2\t\tset ePID randomization level (default 1)\n"
  219. " -C <LCID>\t\tuse fixed <LCID> in random ePIDs\n"
  220. #endif // NO_RANDOM_EPID
  221. #ifndef NO_SOCKETS
  222. #ifndef USE_MSRPC
  223. " -4\t\t\tuse IPv4\n"
  224. " -6\t\t\tuse IPv6\n"
  225. " -L <address>[:<port>]\tlisten on IP address <address> with optional <port>\n"
  226. " -P <port>\t\tset TCP port <port> for subsequent -L statements (default 1688)\n"
  227. #else // USE_MSRPC
  228. " -P <port>\t\tuse TCP port <port> (default 1688)\n"
  229. #endif // USE_MSRPC
  230. #if !defined(NO_LIMIT) && !__minix__
  231. " -m <clients>\t\tHandle max. <clients> simultaneously (default no limit)\n"
  232. #endif // !defined(NO_LIMIT) && !__minix__
  233. #ifdef _NTSERVICE
  234. " -s install vlmcsd as an NT service. Ignores -e"
  235. #ifndef _WIN32
  236. ", -f and -D"
  237. #endif // _WIN32
  238. "\n"
  239. " -S remove vlmcsd service. Ignores all other options\n"
  240. " -U <username> run NT service as <username>. Must be used with -s\n"
  241. " -W <password> optional <password> for -U. Must be used with -s\n"
  242. #endif // _NTSERVICE
  243. #ifndef NO_LOG
  244. " -e log to stdout\n"
  245. #endif // NO_LOG
  246. #ifndef _WIN32 //
  247. " -D run in foreground\n"
  248. " -f run in foreground"
  249. #ifndef NO_LOG
  250. " and log to stdout"
  251. #endif // NO_LOG
  252. "\n"
  253. #endif // _WIN32
  254. #endif // NO_SOCKETS
  255. #ifndef USE_MSRPC
  256. #if !defined(NO_TIMEOUT) && !__minix__
  257. " -t <seconds>\t\tdisconnect clients after <seconds> of inactivity (default 30)\n"
  258. #endif // !defined(NO_TIMEOUT) && !__minix__
  259. " -d\t\t\tdisconnect clients after each request\n"
  260. " -k\t\t\tdon't disconnect clients after each request (default)\n"
  261. " -N0, -N1\t\tdisable/enable NDR64\n"
  262. " -B0, -B1\t\tdisable/enable bind time feature negotiation\n"
  263. #endif // USE_MSRPC
  264. #ifndef NO_PID_FILE
  265. " -p <file> write pid to <file>\n"
  266. #endif // NO_PID_FILE
  267. #ifndef NO_INI_FILE
  268. " -i <file>\t\tuse config file <file>\n"
  269. #endif // NO_INI_FILE
  270. #ifndef NO_CUSTOM_INTERVALS
  271. " -R <interval> renew activation every <interval> (default 1w)\n"
  272. " -A <interval> retry activation every <interval> (default 2h)\n"
  273. #endif // NO_CUSTOM_INTERVALS
  274. #ifndef NO_LOG
  275. #ifndef _WIN32
  276. " -l syslog log to syslog\n"
  277. #endif // _WIN32
  278. " -l <file> log to <file>\n"
  279. #ifndef NO_VERBOSE_LOG
  280. " -v\t\t\tlog verbose\n"
  281. " -q\t\t\tdon't log verbose (default)\n"
  282. #endif // NO_VERBOSE_LOG
  283. #endif // NO_LOG
  284. " -V display version information and exit"
  285. "\n",
  286. Version, global_argv[0]);
  287. exit(!0);
  288. }
  289. #endif // HELP
  290. #ifndef NO_CUSTOM_INTERVALS
  291. // Convert time span strings (e.g. "2h", "5w") to minutes
  292. __pure static DWORD timeSpanString2Minutes(const char *const restrict argument)
  293. {
  294. char *unitId;
  295. long long val = strtoll(argument, &unitId, 10);
  296. switch(toupper((int)*unitId))
  297. {
  298. case 0:
  299. case 'M':
  300. break;
  301. case 'H':
  302. val *= 60;
  303. break;
  304. case 'D':
  305. val *= 60 * 24;
  306. break;
  307. case 'W':
  308. val *= 60 * 24 * 7;
  309. break;
  310. case 'S':
  311. val /= 60;
  312. break;
  313. default:
  314. return 0;
  315. }
  316. if (val < 1) val = 1;
  317. if (val > UINT_MAX) val = UINT_MAX;
  318. return (DWORD)val;
  319. }
  320. #ifndef NO_INI_FILE
  321. __pure static BOOL getTimeSpanFromIniFile(DWORD* result, const char *const restrict argument)
  322. {
  323. DWORD val = timeSpanString2Minutes(argument);
  324. if (!val)
  325. {
  326. IniFileErrorMessage = "Incorrect time span.";
  327. return FALSE;
  328. }
  329. *result = val;
  330. return TRUE;
  331. }
  332. #endif // NO_INI_FILE
  333. __pure static DWORD getTimeSpanFromCommandLine(const char *const restrict optarg, const char optchar)
  334. {
  335. long long val = timeSpanString2Minutes(optarg);
  336. if (!val)
  337. {
  338. printerrorf("Fatal: No valid time span specified in option -%c.\n", optchar);
  339. exit (!0);
  340. }
  341. return (DWORD)val;
  342. }
  343. #endif // NO_CUSTOM_INTERVALS
  344. #ifndef NO_INI_FILE
  345. static void ignoreIniFileParameter(uint_fast8_t iniFileParameterId)
  346. {
  347. uint_fast8_t i;
  348. for (i = 0; i < _countof(IniFileParameterList); i++)
  349. {
  350. if (IniFileParameterList[i].Id != iniFileParameterId) continue;
  351. IniFileParameterList[i].Id = 0;
  352. break;
  353. }
  354. }
  355. #else // NO_INI_FILE
  356. #define ignoreIniFileParameter(x)
  357. #endif // NO_INI_FILE
  358. #ifndef NO_INI_FILE
  359. static BOOL getIniFileArgumentBool(int_fast8_t *result, const char *const argument)
  360. {
  361. IniFileErrorMessage = "Argument must be true/on/yes/1 or false/off/no/0";
  362. return getArgumentBool(result, argument);
  363. }
  364. static BOOL getIniFileArgumentInt(unsigned int *result, const char *const argument, const unsigned int min, const unsigned int max)
  365. {
  366. unsigned int tempResult;
  367. if (!stringToInt(argument, min, max, &tempResult))
  368. {
  369. snprintf(IniFileErrorBuffer, INIFILE_ERROR_BUFFERSIZE, "Must be integer between %u and %u", min, max);
  370. IniFileErrorMessage = IniFileErrorBuffer;
  371. return FALSE;
  372. }
  373. *result = tempResult;
  374. return TRUE;
  375. }
  376. static char* allocateStringArgument(const char *const argument)
  377. {
  378. char* result = (char*)vlmcsd_malloc(strlen(argument) + 1);
  379. strcpy(result, argument);
  380. return result;
  381. }
  382. static BOOL setIniFileParameter(uint_fast8_t id, const char *const iniarg)
  383. {
  384. unsigned int result;
  385. BOOL success = TRUE;
  386. switch(id)
  387. {
  388. # if !defined(NO_USER_SWITCH) && !defined(_WIN32)
  389. case INI_PARAM_GID:
  390. {
  391. struct group *g;
  392. IniFileErrorMessage = "Invalid group id or name";
  393. if (!(gname = allocateStringArgument(iniarg))) return FALSE;
  394. if ((g = getgrnam(iniarg)))
  395. gid = g->gr_gid;
  396. else
  397. success = !GetNumericId(&gid, iniarg);
  398. break;
  399. }
  400. case INI_PARAM_UID:
  401. {
  402. struct passwd *p;
  403. IniFileErrorMessage = "Invalid user id or name";
  404. if (!(uname = allocateStringArgument(iniarg))) return FALSE;
  405. if ((p = getpwnam(iniarg)))
  406. uid = p->pw_uid;
  407. else
  408. success = !GetNumericId(&uid, iniarg);
  409. break;
  410. }
  411. # endif // !defined(NO_USER_SWITCH) && !defined(_WIN32)
  412. # ifndef NO_RANDOM_EPID
  413. case INI_PARAM_LCID:
  414. success = getIniFileArgumentInt(&result, iniarg, 0, 32767);
  415. if (success) Lcid = (uint16_t)result;
  416. break;
  417. case INI_PARAM_RANDOMIZATION_LEVEL:
  418. success = getIniFileArgumentInt(&result, iniarg, 0, 2);
  419. if (success) RandomizationLevel = (int_fast8_t)result;
  420. break;
  421. # endif // NO_RANDOM_EPID
  422. # ifdef USE_MSRPC
  423. case INI_PARAM_PORT:
  424. defaultport = allocateStringArgument(iniarg);
  425. break;
  426. # endif // USE_MSRPC
  427. # if !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  428. case INI_PARAM_LISTEN:
  429. maxsockets++;
  430. return TRUE;
  431. # if !defined(NO_LIMIT) && !__minix__
  432. case INI_PARAM_MAX_WORKERS:
  433. # ifdef USE_MSRPC
  434. success = getIniFileArgumentInt(&MaxTasks, iniarg, 1, RPC_C_LISTEN_MAX_CALLS_DEFAULT);
  435. # else // !USE_MSRPC
  436. success = getIniFileArgumentInt(&MaxTasks, iniarg, 1, SEM_VALUE_MAX);
  437. # endif // !USE_MSRPC
  438. break;
  439. # endif // !defined(NO_LIMIT) && !__minix__
  440. # endif // NO_SOCKETS
  441. # ifndef NO_PID_FILE
  442. case INI_PARAM_PID_FILE:
  443. fn_pid = allocateStringArgument(iniarg);
  444. break;
  445. # endif // NO_PID_FILE
  446. # ifndef NO_LOG
  447. case INI_PARAM_LOG_FILE:
  448. fn_log = allocateStringArgument(iniarg);
  449. break;
  450. # ifndef NO_VERBOSE_LOG
  451. case INI_PARAM_LOG_VERBOSE:
  452. success = getIniFileArgumentBool(&logverbose, iniarg);
  453. break;
  454. # endif // NO_VERBOSE_LOG
  455. # endif // NO_LOG
  456. # ifndef NO_CUSTOM_INTERVALS
  457. case INI_PARAM_ACTIVATION_INTERVAL:
  458. success = getTimeSpanFromIniFile(&VLActivationInterval, iniarg);
  459. break;
  460. case INI_PARAM_RENEWAL_INTERVAL:
  461. success = getTimeSpanFromIniFile(&VLRenewalInterval, iniarg);
  462. break;
  463. # endif // NO_CUSTOM_INTERVALS
  464. # ifndef USE_MSRPC
  465. # if !defined(NO_TIMEOUT) && !__minix__
  466. case INI_PARAM_CONNECTION_TIMEOUT:
  467. success = getIniFileArgumentInt(&result, iniarg, 1, 600);
  468. if (success) ServerTimeout = (DWORD)result;
  469. break;
  470. # endif // !defined(NO_TIMEOUT) && !__minix__
  471. case INI_PARAM_DISCONNECT_IMMEDIATELY:
  472. success = getIniFileArgumentBool(&DisconnectImmediately, iniarg);
  473. break;
  474. case INI_PARAM_RPC_NDR64:
  475. success = getIniFileArgumentBool(&UseRpcNDR64, iniarg);
  476. break;
  477. case INI_PARAM_RPC_BTFN:
  478. success = getIniFileArgumentBool(&UseRpcBTFN, iniarg);
  479. break;
  480. # endif // USE_MSRPC
  481. default:
  482. return FALSE;
  483. }
  484. return success;
  485. }
  486. static __pure int isControlCharOrSlash(const char c)
  487. {
  488. if ((unsigned char)c < '!') return !0;
  489. if (c == '/') return !0;
  490. return 0;
  491. }
  492. static void iniFileLineNextWord(const char **s)
  493. {
  494. while ( **s && isspace((int)**s) ) (*s)++;
  495. }
  496. static BOOL setHwIdFromIniFileLine(const char **s, const ProdListIndex_t index)
  497. {
  498. iniFileLineNextWord(s);
  499. if (**s == '/')
  500. {
  501. if (KmsResponseParameters[index].HwId) return TRUE;
  502. BYTE* HwId = (BYTE*)vlmcsd_malloc(sizeof(((RESPONSE_V6 *)0)->HwId));
  503. hex2bin(HwId, *s + 1, sizeof(((RESPONSE_V6 *)0)->HwId));
  504. KmsResponseParameters[index].HwId = HwId;
  505. }
  506. return TRUE;
  507. }
  508. static BOOL checkGuidInIniFileLine(const char **s, ProdListIndex_t *const index)
  509. {
  510. GUID AppGuid;
  511. if (!string2Uuid(*s, &AppGuid)) return FALSE;
  512. (*s) += GUID_STRING_LENGTH;
  513. getProductNameHE(&AppGuid, AppList, index);
  514. if (*index > getAppListSize() - 2)
  515. {
  516. IniFileErrorMessage = "Unknown App Guid.";
  517. return FALSE;
  518. }
  519. iniFileLineNextWord(s);
  520. if ( *(*s)++ != '=' ) return FALSE;
  521. return TRUE;
  522. }
  523. static BOOL setEpidFromIniFileLine(const char **s, const ProdListIndex_t index)
  524. {
  525. iniFileLineNextWord(s);
  526. const char *savedPosition = *s;
  527. uint_fast16_t i;
  528. for (i = 0; !isControlCharOrSlash(**s); i++)
  529. {
  530. if (utf8_to_ucs2_char((const unsigned char*)*s, (const unsigned char**)s) == (WCHAR)~0)
  531. {
  532. return FALSE;
  533. }
  534. }
  535. if (i < 1 || i >= PID_BUFFER_SIZE) return FALSE;
  536. if (KmsResponseParameters[index].Epid) return TRUE;
  537. size_t size = *s - savedPosition + 1;
  538. char* epidbuffer = (char*)vlmcsd_malloc(size);
  539. memcpy(epidbuffer, savedPosition, size - 1);
  540. epidbuffer[size - 1] = 0;
  541. KmsResponseParameters[index].Epid = epidbuffer;
  542. #ifndef NO_LOG
  543. KmsResponseParameters[index].EpidSource = fn_ini;
  544. #endif //NO_LOG
  545. return TRUE;
  546. }
  547. static BOOL getIniFileArgument(const char **s)
  548. {
  549. while (!isspace((int)**s) && **s != '=' && **s) (*s)++;
  550. iniFileLineNextWord(s);
  551. if (*((*s)++) != '=')
  552. {
  553. IniFileErrorMessage = "'=' required after keyword.";
  554. return FALSE;
  555. }
  556. iniFileLineNextWord(s);
  557. if (!**s)
  558. {
  559. IniFileErrorMessage = "missing argument after '='.";
  560. return FALSE;
  561. }
  562. return TRUE;
  563. }
  564. static BOOL handleIniFileParameter(const char *s)
  565. {
  566. uint_fast8_t i;
  567. for (i = 0; i < _countof(IniFileParameterList); i++)
  568. {
  569. if (strncasecmp(IniFileParameterList[i].Name, s, strlen(IniFileParameterList[i].Name))) continue;
  570. if (!IniFileParameterList[i].Id) return TRUE;
  571. if (!getIniFileArgument(&s)) return FALSE;
  572. return setIniFileParameter(IniFileParameterList[i].Id, s);
  573. }
  574. IniFileErrorMessage = "Unknown keyword.";
  575. return FALSE;
  576. }
  577. #if !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  578. static BOOL setupListeningSocketsFromIniFile(const char *s)
  579. {
  580. if (!maxsockets) return TRUE;
  581. if (strncasecmp("Listen", s, 6)) return TRUE;
  582. if (!getIniFileArgument(&s)) return TRUE;
  583. snprintf(IniFileErrorBuffer, INIFILE_ERROR_BUFFERSIZE, "Cannot listen on %s.", s);
  584. IniFileErrorMessage = IniFileErrorBuffer;
  585. return addListeningSocket(s);
  586. }
  587. #endif // !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  588. static BOOL readIniFile(const uint_fast8_t pass)
  589. {
  590. char line[256];
  591. const char *s;
  592. ProdListIndex_t appIndex;
  593. unsigned int lineNumber;
  594. uint_fast8_t lineParseError;
  595. FILE *restrict f;
  596. BOOL result = TRUE;
  597. IniFileErrorBuffer = (char*)vlmcsd_malloc(INIFILE_ERROR_BUFFERSIZE);
  598. if ( !(f = fopen(fn_ini, "r") )) return FALSE;
  599. for (lineNumber = 1; (s = fgets(line, sizeof(line), f)); lineNumber++)
  600. {
  601. line[strlen(line) - 1] = 0;
  602. iniFileLineNextWord(&s);
  603. if (*s == ';' || *s == '#' || !*s) continue;
  604. # ifndef NO_SOCKETS
  605. if (pass == INI_FILE_PASS_1)
  606. # endif // NO_SOCKETS
  607. {
  608. if (handleIniFileParameter(s)) continue;
  609. lineParseError = !checkGuidInIniFileLine(&s, &appIndex) ||
  610. !setEpidFromIniFileLine(&s, appIndex) ||
  611. !setHwIdFromIniFileLine(&s, appIndex);
  612. }
  613. # if !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  614. else if (pass == INI_FILE_PASS_2)
  615. {
  616. lineParseError = !setupListeningSocketsFromIniFile(s);
  617. }
  618. else
  619. {
  620. return FALSE;
  621. }
  622. # endif // NO_SOCKETS
  623. if (lineParseError)
  624. {
  625. printerrorf("Warning: %s line %u: \"%s\". %s\n", fn_ini, lineNumber, line, IniFileErrorMessage);
  626. continue;
  627. }
  628. }
  629. if (ferror(f)) result = FALSE;
  630. free(IniFileErrorBuffer);
  631. fclose(f);
  632. # if !defined(NO_SOCKETS) && !defined(NO_LOG)
  633. if (pass == INI_FILE_PASS_1 && !InetdMode && result)
  634. {
  635. # ifdef _NTSERVICE
  636. if (!installService)
  637. # endif // _NTSERVICE
  638. logger("Read ini file %s\n", fn_ini);
  639. }
  640. # endif // !defined(NO_SOCKETS) && !defined(NO_LOG)
  641. return result;
  642. }
  643. #endif // NO_INI_FILE
  644. #if !defined(NO_SOCKETS)
  645. #if !defined(_WIN32)
  646. #if !defined(NO_SIGHUP)
  647. static void exec_self(char** argv)
  648. {
  649. # if __linux__ && defined(USE_AUXV)
  650. char *execname_ptr = (char*)getauxval(AT_EXECFN);
  651. if (execname_ptr) execv(execname_ptr, argv);
  652. # elif (__linux__ || __CYGWIN__) && !defined(NO_PROCFS)
  653. execv(realpath("/proc/self/exe", NULL), argv);
  654. # elif (__FreeBSD__) && !defined(NO_PROCFS)
  655. int mib[4];
  656. mib[0] = CTL_KERN;
  657. mib[1] = KERN_PROC;
  658. mib[2] = KERN_PROC_PATHNAME;
  659. mib[3] = -1;
  660. char path[PATH_MAX + 1];
  661. size_t cb = sizeof(path);
  662. if (!sysctl(mib, 4, path, &cb, NULL, 0)) execv(path, argv);
  663. # elif (__DragonFly__) && !defined(NO_PROCFS)
  664. execv(realpath("/proc/curproc/file", NULL), argv);
  665. # elif __NetBSD__ && !defined(NO_PROCFS)
  666. execv(realpath("/proc/curproc/exe", NULL), argv);
  667. # elif __sun__
  668. const char* exename = getexecname();
  669. if (exename) execv(exename, argv);
  670. # elif __APPLE__
  671. char path[PATH_MAX + 1];
  672. uint32_t size = sizeof(path);
  673. if (_NSGetExecutablePath(path, &size) == 0) execv(path, argv);
  674. # else
  675. execvp(argv[0], argv);
  676. # endif
  677. }
  678. static void HangupHandler(const int signal_unused)
  679. {
  680. int i;
  681. int_fast8_t daemonize_protection = TRUE;
  682. CARGV argv_in = multi_argv == NULL ? global_argv : multi_argv;
  683. int argc_in = multi_argc == 0 ? global_argc : multi_argc;
  684. const char** argv_out = (const char**)vlmcsd_malloc((argc_in + 2) * sizeof(char**));
  685. for (i = 0; i < argc_in; i++)
  686. {
  687. if (!strcmp(argv_in[i], "-Z")) daemonize_protection = FALSE;
  688. argv_out[i] = argv_in[i];
  689. }
  690. argv_out[argc_in] = argv_out[argc_in + 1] = NULL;
  691. if (daemonize_protection) argv_out[argc_in] = (char*) "-Z";
  692. exec_self((char**)argv_out);
  693. # ifndef NO_LOG
  694. logger("Fatal: Unable to restart on SIGHUP: %s\n", strerror(errno));
  695. # endif
  696. # ifndef NO_PID_FILE
  697. if (fn_pid) unlink(fn_pid);
  698. # endif // NO_PID_FILE
  699. exit(errno);
  700. }
  701. #endif // NO_SIGHUP
  702. static void terminationHandler(const int signal_unused)
  703. {
  704. cleanup();
  705. exit(0);
  706. }
  707. #if defined(CHILD_HANDLER) || __minix__
  708. static void childHandler(const int signal)
  709. {
  710. waitpid(-1, NULL, WNOHANG);
  711. }
  712. #endif // defined(CHILD_HANDLER) || __minix__
  713. static int daemonizeAndSetSignalAction()
  714. {
  715. struct sigaction sa;
  716. sigemptyset(&sa.sa_mask);
  717. # ifndef NO_LOG
  718. if ( !nodaemon) if (daemon(!0, logstdout))
  719. # else // NO_LOG
  720. if ( !nodaemon) if (daemon(!0, 0))
  721. # endif // NO_LOG
  722. {
  723. printerrorf("Fatal: Could not daemonize to background.\n");
  724. return(errno);
  725. }
  726. if (!InetdMode)
  727. {
  728. # ifndef USE_THREADS
  729. # if defined(CHILD_HANDLER) || __minix__
  730. sa.sa_handler = childHandler;
  731. # else // !(defined(CHILD_HANDLER) || __minix__)
  732. sa.sa_handler = SIG_IGN;
  733. # endif // !(defined(CHILD_HANDLER) || __minix__)
  734. sa.sa_flags = SA_NOCLDWAIT;
  735. if (sigaction(SIGCHLD, &sa, NULL))
  736. return(errno);
  737. # endif // !USE_THREADS
  738. sa.sa_handler = terminationHandler;
  739. sa.sa_flags = 0;
  740. sigaction(SIGINT, &sa, NULL);
  741. sigaction(SIGTERM, &sa, NULL);
  742. # ifndef NO_SIGHUP
  743. sa.sa_handler = HangupHandler;
  744. sa.sa_flags = SA_NODEFER;
  745. sigaction(SIGHUP, &sa, NULL);
  746. # endif // NO_SIGHUP
  747. }
  748. return 0;
  749. }
  750. #else // _WIN32
  751. static BOOL terminationHandler(const DWORD fdwCtrlType)
  752. {
  753. // What a lame substitute for Unix signal handling
  754. switch(fdwCtrlType)
  755. {
  756. case CTRL_C_EVENT:
  757. case CTRL_CLOSE_EVENT:
  758. case CTRL_BREAK_EVENT:
  759. case CTRL_LOGOFF_EVENT:
  760. case CTRL_SHUTDOWN_EVENT:
  761. cleanup();
  762. exit(0);
  763. default:
  764. return FALSE;
  765. }
  766. }
  767. static DWORD daemonizeAndSetSignalAction()
  768. {
  769. if(!SetConsoleCtrlHandler( (PHANDLER_ROUTINE) terminationHandler, TRUE ))
  770. {
  771. #ifndef NO_LOG
  772. DWORD rc = GetLastError();
  773. logger("Warning: Could not register Windows signal handler: Error %u\n", rc);
  774. #endif // NO_LOG
  775. }
  776. return ERROR_SUCCESS;
  777. }
  778. #endif // _WIN32
  779. #endif // !defined(NO_SOCKETS)
  780. // Workaround for Cygwin fork bug (only affects cygwin processes that are Windows services)
  781. // Best is to compile for Cygwin with threads. fork() is slow and unreliable on Cygwin
  782. #if !defined(NO_INI_FILE) || !defined(NO_LOG) || !defined(NO_CL_PIDS)
  783. __pure static char* getCommandLineArg(char *const restrict optarg)
  784. {
  785. #if !defined (__CYGWIN__) || defined(USE_THREADS) || defined(NO_SOCKETS)
  786. return optarg;
  787. #else
  788. if (!IsNTService) return optarg;
  789. return allocateStringArgument(optarg);
  790. #endif
  791. }
  792. #endif // !defined(NO_INI_FILE) || !defined(NO_LOG) || !defined(NO_CL_PIDS)
  793. static void parseGeneralArguments() {
  794. int o;
  795. #ifndef NO_CL_PIDS
  796. BYTE* HwId;
  797. #endif // NO_CL_PIDS
  798. for (opterr = 0; ( o = getopt(global_argc, (char* const*)global_argv, optstring) ) > 0; ) switch (o)
  799. {
  800. #if !defined(NO_SOCKETS) && !defined(NO_SIGHUP) && !defined(_WIN32)
  801. case 'Z':
  802. IsRestarted = TRUE;
  803. nodaemon = TRUE;
  804. break;
  805. #endif // !defined(NO_SOCKETS) && !defined(NO_SIGHUP) && !defined(_WIN32)
  806. #ifndef NO_CL_PIDS
  807. case 'w':
  808. KmsResponseParameters[APP_ID_WINDOWS].Epid = getCommandLineArg(optarg);
  809. #ifndef NO_LOG
  810. KmsResponseParameters[APP_ID_WINDOWS].EpidSource = "command line";
  811. #endif // NO_LOG
  812. break;
  813. case '0':
  814. KmsResponseParameters[APP_ID_OFFICE2010].Epid = getCommandLineArg(optarg);
  815. #ifndef NO_LOG
  816. KmsResponseParameters[APP_ID_OFFICE2010].EpidSource = "command line";
  817. #endif // NO_LOG
  818. break;
  819. case '3':
  820. KmsResponseParameters[APP_ID_OFFICE2013].Epid = getCommandLineArg(optarg);
  821. #ifndef NO_LOG
  822. KmsResponseParameters[APP_ID_OFFICE2013].EpidSource = "command line";
  823. #endif // NO_LOG
  824. break;
  825. case 'H':
  826. HwId = (BYTE*)vlmcsd_malloc(sizeof(((RESPONSE_V6 *)0)->HwId));
  827. hex2bin(HwId, optarg, sizeof(((RESPONSE_V6 *)0)->HwId));
  828. KmsResponseParameters[APP_ID_WINDOWS].HwId = HwId;
  829. KmsResponseParameters[APP_ID_OFFICE2010].HwId = HwId;
  830. KmsResponseParameters[APP_ID_OFFICE2013].HwId = HwId;
  831. break;
  832. #endif // NO_CL_PIDS
  833. #ifndef NO_SOCKETS
  834. #ifndef USE_MSRPC
  835. case '4':
  836. case '6':
  837. case 'P':
  838. ignoreIniFileParameter(INI_PARAM_LISTEN);
  839. break;
  840. #else // USE_MSRPC
  841. case 'P':
  842. defaultport = optarg;
  843. ignoreIniFileParameter(INI_PARAM_PORT);
  844. break;
  845. #endif // USE_MSRPC
  846. #if !defined(NO_LIMIT) && !__minix__
  847. case 'm':
  848. #ifdef USE_MSRPC
  849. MaxTasks = getOptionArgumentInt(o, 1, RPC_C_LISTEN_MAX_CALLS_DEFAULT);
  850. #else // !USE_MSRPC
  851. MaxTasks = getOptionArgumentInt(o, 1, SEM_VALUE_MAX);
  852. #endif // !USE_MSRPC
  853. ignoreIniFileParameter(INI_PARAM_MAX_WORKERS);
  854. break;
  855. #endif // !defined(NO_LIMIT) && !__minix__
  856. #endif // NO_SOCKETS
  857. #if !defined(NO_TIMEOUT) && !__minix__ && !defined(USE_MSRPC)
  858. case 't':
  859. ServerTimeout = getOptionArgumentInt(o, 1, 600);
  860. ignoreIniFileParameter(INI_PARAM_CONNECTION_TIMEOUT);
  861. break;
  862. #endif // !defined(NO_TIMEOUT) && !__minix__ && !defined(USE_MSRPC)
  863. #ifndef NO_PID_FILE
  864. case 'p':
  865. fn_pid = getCommandLineArg(optarg);
  866. ignoreIniFileParameter(INI_PARAM_PID_FILE);
  867. break;
  868. #endif
  869. #ifndef NO_INI_FILE
  870. case 'i':
  871. fn_ini = getCommandLineArg(optarg);
  872. if (!strcmp(fn_ini, "-")) fn_ini = NULL;
  873. break;
  874. #endif
  875. #ifndef NO_LOG
  876. case 'l':
  877. fn_log = getCommandLineArg(optarg);
  878. ignoreIniFileParameter(INI_PARAM_LOG_FILE);
  879. break;
  880. #ifndef NO_VERBOSE_LOG
  881. case 'v':
  882. case 'q':
  883. logverbose = o == 'v';
  884. ignoreIniFileParameter(INI_PARAM_LOG_VERBOSE);
  885. break;
  886. #endif // NO_VERBOSE_LOG
  887. #endif // NO_LOG
  888. #ifndef NO_SOCKETS
  889. #ifndef USE_MSRPC
  890. case 'L':
  891. maxsockets++;
  892. ignoreIniFileParameter(INI_PARAM_LISTEN);
  893. break;
  894. #endif // USE_MSRPC
  895. case 'f':
  896. nodaemon = 1;
  897. #ifndef NO_LOG
  898. logstdout = 1;
  899. #endif
  900. break;
  901. #ifdef _NTSERVICE
  902. case 'U':
  903. ServiceUser = optarg;
  904. break;
  905. case 'W':
  906. ServicePassword = optarg;
  907. break;
  908. case 's':
  909. #ifndef USE_MSRPC
  910. if (InetdMode) usage();
  911. #endif // USE_MSRPC
  912. if (!IsNTService) installService = 1; // Install
  913. break;
  914. case 'S':
  915. if (!IsNTService) installService = 2; // Remove
  916. break;
  917. #endif // _NTSERVICE
  918. case 'D':
  919. nodaemon = 1;
  920. break;
  921. #ifndef NO_LOG
  922. case 'e':
  923. logstdout = 1;
  924. break;
  925. #endif // NO_LOG
  926. #endif // NO_SOCKETS
  927. #ifndef _WIN32
  928. case 'I': // Backward compatibility with svn681 and earlier
  929. break;
  930. #endif // _WIN32
  931. #ifndef NO_RANDOM_EPID
  932. case 'r':
  933. RandomizationLevel = (int_fast8_t)getOptionArgumentInt(o, 0, 2);
  934. ignoreIniFileParameter(INI_PARAM_RANDOMIZATION_LEVEL);
  935. break;
  936. case 'C':
  937. Lcid = (uint16_t)getOptionArgumentInt(o, 0, 32767);
  938. ignoreIniFileParameter(INI_PARAM_LCID);
  939. #ifdef _PEDANTIC
  940. if (!IsValidLcid(Lcid))
  941. {
  942. printerrorf("Warning: %s is not a valid LCID.\n", optarg);
  943. }
  944. #endif // _PEDANTIC
  945. break;
  946. #endif // NO_RANDOM_PID
  947. #if !defined(NO_USER_SWITCH) && !defined(_WIN32)
  948. case 'g':
  949. gname = optarg;
  950. ignoreIniFileParameter(INI_PARAM_GID);
  951. #ifndef NO_SIGHUP
  952. if (!IsRestarted)
  953. #endif // NO_SIGHUP
  954. if (GetGid())
  955. {
  956. printerrorf("Fatal: setgid for %s failed.\n", optarg);
  957. exit(!0);
  958. }
  959. break;
  960. case 'u':
  961. uname = optarg;
  962. ignoreIniFileParameter(INI_PARAM_UID);
  963. #ifndef NO_SIGHUP
  964. if (!IsRestarted)
  965. #endif // NO_SIGHUP
  966. if (GetUid())
  967. {
  968. printerrorf("Fatal: setuid for %s failed.\n", optarg);
  969. exit(!0);
  970. }
  971. break;
  972. #endif // NO_USER_SWITCH && !_WIN32
  973. #ifndef NO_CUSTOM_INTERVALS
  974. case 'R':
  975. VLRenewalInterval = getTimeSpanFromCommandLine(optarg, o);
  976. ignoreIniFileParameter(INI_PARAM_RENEWAL_INTERVAL);
  977. break;
  978. case 'A':
  979. VLActivationInterval = getTimeSpanFromCommandLine(optarg, o);
  980. ignoreIniFileParameter(INI_PARAM_ACTIVATION_INTERVAL);
  981. break;
  982. #endif
  983. #ifndef USE_MSRPC
  984. case 'd':
  985. case 'k':
  986. DisconnectImmediately = o == 'd';
  987. ignoreIniFileParameter(INI_PARAM_DISCONNECT_IMMEDIATELY);
  988. break;
  989. case 'N':
  990. if (!getArgumentBool(&UseRpcNDR64, optarg)) usage();
  991. ignoreIniFileParameter(INI_PARAM_RPC_NDR64);
  992. break;
  993. case 'B':
  994. if (!getArgumentBool(&UseRpcBTFN, optarg)) usage();
  995. ignoreIniFileParameter(INI_PARAM_RPC_BTFN);
  996. break;
  997. #endif // !USE_MSRPC
  998. case 'V':
  999. #ifdef _NTSERVICE
  1000. if (IsNTService) break;
  1001. #endif
  1002. printf("vlmcsd %s\n", Version);
  1003. exit(0);
  1004. default:
  1005. usage();
  1006. }
  1007. // Do not allow non-option arguments
  1008. if (optind != global_argc)
  1009. usage();
  1010. #ifdef _NTSERVICE
  1011. // -U and -W must be used with -s
  1012. if ((ServiceUser || *ServicePassword) && installService != 1) usage();
  1013. #endif // _NTSERVICE
  1014. }
  1015. #ifndef NO_PID_FILE
  1016. static void writePidFile()
  1017. {
  1018. # ifndef NO_SIGHUP
  1019. if (IsRestarted) return;
  1020. # endif // NO_SIGHUP
  1021. if (fn_pid && !InetdMode)
  1022. {
  1023. FILE *_f = fopen(fn_pid, "w");
  1024. if ( _f )
  1025. {
  1026. fprintf(_f, "%u", (uint32_t)getpid());
  1027. fclose(_f);
  1028. }
  1029. #ifndef NO_LOG
  1030. else
  1031. {
  1032. logger("Warning: Cannot write pid file '%s'. %s.\n", fn_pid, strerror(errno));
  1033. }
  1034. #endif // NO_LOG
  1035. }
  1036. }
  1037. #else
  1038. #define writePidFile(x)
  1039. #endif // NO_PID_FILE
  1040. #if !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1041. void cleanup()
  1042. {
  1043. if (!InetdMode)
  1044. {
  1045. #ifndef NO_PID_FILE
  1046. if (fn_pid) unlink(fn_pid);
  1047. #endif // NO_PID_FILE
  1048. closeAllListeningSockets();
  1049. #if !defined(NO_LIMIT) && !defined(NO_SOCKETS) && !defined(_WIN32) && !__minix__
  1050. sem_unlink("/vlmcsd");
  1051. #if !defined(USE_THREADS) && !defined(CYGWIN)
  1052. if (shmid >= 0)
  1053. {
  1054. if (Semaphore != (sem_t*)-1) shmdt(Semaphore);
  1055. shmctl(shmid, IPC_RMID, NULL);
  1056. }
  1057. #endif // !defined(USE_THREADS) && !defined(CYGWIN)
  1058. #endif // !defined(NO_LIMIT) && !defined(NO_SOCKETS) && !defined(_WIN32) && !__minix__
  1059. #ifndef NO_LOG
  1060. logger("vlmcsd %s was shutdown\n", Version);
  1061. #endif // NO_LOG
  1062. }
  1063. }
  1064. #elif defined(USE_MSRPC)
  1065. void cleanup()
  1066. {
  1067. # ifndef NO_PID_FILE
  1068. if (fn_pid) unlink(fn_pid);
  1069. # endif // NO_PID_FILE
  1070. # ifndef NO_LOG
  1071. logger("vlmcsd %s was shutdown\n", Version);
  1072. # endif // NO_LOG
  1073. }
  1074. #else // Neither Sockets nor RPC
  1075. __pure void cleanup() {}
  1076. #endif // Neither Sockets nor RPC
  1077. #if !defined(USE_MSRPC) && !defined(NO_LIMIT) && !defined(NO_SOCKETS) && !__minix__
  1078. // Get a semaphore for limiting the maximum concurrent tasks
  1079. static void allocateSemaphore(void)
  1080. {
  1081. #ifdef USE_THREADS
  1082. #define sharemode 0
  1083. #else
  1084. #define sharemode 1
  1085. #endif
  1086. #ifndef _WIN32
  1087. sem_unlink("/vlmcsd");
  1088. #endif
  1089. if(MaxTasks < SEM_VALUE_MAX && !InetdMode)
  1090. {
  1091. #ifndef _WIN32
  1092. #if !defined(USE_THREADS) && !defined(CYGWIN)
  1093. if ((Semaphore = sem_open("/vlmcsd", O_CREAT /*| O_EXCL*/, 0700, MaxTasks)) == SEM_FAILED) // fails on many systems
  1094. {
  1095. // We didn't get a named Semaphore (/dev/shm on Linux) so let's try our own shared page
  1096. if (
  1097. ( shmid = shmget(IPC_PRIVATE, sizeof(sem_t), IPC_CREAT | 0600) ) < 0 ||
  1098. ( Semaphore = (sem_t*)shmat(shmid, NULL, 0) ) == (sem_t*)-1 ||
  1099. sem_init(Semaphore, 1, MaxTasks) < 0
  1100. )
  1101. {
  1102. int errno_save = errno;
  1103. if (Semaphore != (sem_t*)-1) shmdt(Semaphore);
  1104. if (shmid >= 0) shmctl(shmid, IPC_RMID, NULL);
  1105. printerrorf("Warning: Could not create semaphore: %s\n", vlmcsd_strerror(errno_save));
  1106. MaxTasks = SEM_VALUE_MAX;
  1107. }
  1108. }
  1109. #else // THREADS or CYGWIN
  1110. Semaphore = (sem_t*)vlmcsd_malloc(sizeof(sem_t));
  1111. if (sem_init(Semaphore, sharemode, MaxTasks) < 0) // sem_init is not implemented on Darwin (returns ENOSYS)
  1112. {
  1113. free(Semaphore);
  1114. if ((Semaphore = sem_open("/vlmcsd", O_CREAT /*| O_EXCL*/, 0700, MaxTasks)) == SEM_FAILED)
  1115. {
  1116. printerrorf("Warning: Could not create semaphore: %s\n", vlmcsd_strerror(errno));
  1117. MaxTasks = SEM_VALUE_MAX;
  1118. }
  1119. }
  1120. #endif // THREADS or CYGWIN
  1121. #else // _WIN32
  1122. if (!(Semaphore = CreateSemaphoreA(NULL, MaxTasks, MaxTasks, NULL)))
  1123. {
  1124. printerrorf("Warning: Could not create semaphore: %s\n", vlmcsd_strerror(GetLastError()));
  1125. MaxTasks = SEM_VALUE_MAX;
  1126. }
  1127. #endif // _WIN32
  1128. }
  1129. }
  1130. #endif // !defined(NO_LIMIT) && !defined(NO_SOCKETS) && !__minix__
  1131. #if !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1132. int setupListeningSockets()
  1133. {
  1134. int o;
  1135. uint_fast8_t allocsockets = maxsockets ? maxsockets : 2;
  1136. SocketList = (SOCKET*)vlmcsd_malloc((size_t)allocsockets * sizeof(SOCKET));
  1137. haveIPv4Stack = checkProtocolStack(AF_INET);
  1138. haveIPv6Stack = checkProtocolStack(AF_INET6);
  1139. // Reset getopt since we've alread used it
  1140. optReset();
  1141. for (opterr = 0; ( o = getopt(global_argc, (char* const*)global_argv, optstring) ) > 0; ) switch (o)
  1142. {
  1143. case '4':
  1144. if (!haveIPv4Stack)
  1145. {
  1146. printerrorf("Fatal: Your system does not support %s.\n", cIPv4);
  1147. return !0;
  1148. }
  1149. v4required = 1;
  1150. break;
  1151. case '6':
  1152. if (!haveIPv6Stack)
  1153. {
  1154. printerrorf("Fatal: Your system does not support %s.\n", cIPv6);
  1155. return !0;
  1156. }
  1157. v6required = 1;
  1158. break;
  1159. case 'L':
  1160. addListeningSocket(optarg);
  1161. break;
  1162. case 'P':
  1163. defaultport = optarg;
  1164. break;
  1165. default:
  1166. break;
  1167. }
  1168. # ifndef NO_INI_FILE
  1169. if (maxsockets && !numsockets)
  1170. {
  1171. if (fn_ini && !readIniFile(INI_FILE_PASS_2))
  1172. {
  1173. #ifdef INI_FILE
  1174. if (strcmp(fn_ini, INI_FILE))
  1175. #endif // INI_FILE
  1176. printerrorf("Warning: Can't read %s: %s\n", fn_ini, strerror(errno));
  1177. }
  1178. }
  1179. # endif
  1180. // if -L hasn't been specified on the command line, use default sockets (all IP addresses)
  1181. // maxsocket results from first pass parsing the arguments
  1182. if (!maxsockets)
  1183. {
  1184. if (haveIPv6Stack && (v6required || !v4required)) addListeningSocket("::");
  1185. if (haveIPv4Stack && (v4required || !v6required)) addListeningSocket("0.0.0.0");
  1186. }
  1187. if (!numsockets)
  1188. {
  1189. printerrorf("Fatal: Could not listen on any socket.\n");
  1190. return(!0);
  1191. }
  1192. return 0;
  1193. }
  1194. #endif // !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1195. int server_main(int argc, CARGV argv)
  1196. {
  1197. #if !defined(_NTSERVICE) && !defined(NO_SOCKETS)
  1198. int error;
  1199. #endif // !defined(_NTSERVICE) && !defined(NO_SOCKETS)
  1200. // Initialize ePID / HwId parameters
  1201. memset(KmsResponseParameters, 0, sizeof(KmsResponseParameters));
  1202. global_argc = argc;
  1203. global_argv = argv;
  1204. #ifdef _NTSERVICE // #endif is in newmain()
  1205. DWORD lasterror = ERROR_SUCCESS;
  1206. if (!StartServiceCtrlDispatcher(NTServiceDispatchTable) && (lasterror = GetLastError()) == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
  1207. {
  1208. IsNTService = FALSE;
  1209. return newmain();
  1210. }
  1211. return lasterror;
  1212. }
  1213. int newmain()
  1214. {
  1215. int error;
  1216. // Initialize thread synchronization objects for Windows and Cygwin
  1217. #ifdef USE_THREADS
  1218. #ifndef NO_LOG
  1219. // Initialize the Critical Section for proper logging
  1220. InitializeCriticalSection(&logmutex);
  1221. #endif // NO_LOG
  1222. #endif // USE_THREADS
  1223. #ifdef _WIN32
  1224. #ifndef USE_MSRPC
  1225. // Windows Sockets must be initialized
  1226. WSADATA wsadata;
  1227. if ((error = WSAStartup(0x0202, &wsadata)))
  1228. {
  1229. printerrorf("Fatal: Could not initialize Windows sockets (Error: %d).\n", error);
  1230. return error;
  1231. }
  1232. #endif // USE_MSRPC
  1233. // Windows can never daemonize
  1234. nodaemon = 1;
  1235. #else // __CYGWIN__
  1236. // Do not daemonize if we are a Windows service
  1237. if (IsNTService) nodaemon = 1;
  1238. #endif // _WIN32 / __CYGWIN__
  1239. #endif // _NTSERVICE ( #ifdef is main(int argc, CARGV argv) )
  1240. parseGeneralArguments(); // Does not return if an error occurs
  1241. #if !defined(_WIN32) && !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1242. struct stat statbuf;
  1243. fstat(STDIN_FILENO, &statbuf);
  1244. if (S_ISSOCK(statbuf.st_mode))
  1245. {
  1246. InetdMode = 1;
  1247. nodaemon = 1;
  1248. maxsockets = 0;
  1249. #ifndef NO_LOG
  1250. logstdout = 0;
  1251. #endif // NO_LOG
  1252. }
  1253. #endif // !defined(_WIN32) && !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1254. #ifndef NO_INI_FILE
  1255. if (fn_ini && !readIniFile(INI_FILE_PASS_1))
  1256. {
  1257. #ifdef INI_FILE
  1258. if (strcmp(fn_ini, INI_FILE))
  1259. #endif // INI_FILE
  1260. printerrorf("Warning: Can't read %s: %s\n", fn_ini, strerror(errno));
  1261. }
  1262. #endif // NO_INI_FILE
  1263. #if !defined(NO_LIMIT) && !defined(NO_SOCKETS) && !__minix__ && !defined(USE_MSRPC)
  1264. allocateSemaphore();
  1265. #endif // !defined(NO_LIMIT) && !defined(NO_SOCKETS) && __minix__
  1266. #ifdef _NTSERVICE
  1267. if (installService)
  1268. return NtServiceInstallation(installService, ServiceUser, ServicePassword);
  1269. #endif // _NTSERVICE
  1270. #if !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1271. if (!InetdMode)
  1272. {
  1273. if ((error = setupListeningSockets())) return error;
  1274. }
  1275. #endif // NO_SOCKETS
  1276. // After sockets have been set up, we may switch to a lower privileged user
  1277. #if !defined(_WIN32) && !defined(NO_USER_SWITCH)
  1278. #ifndef NO_SIGHUP
  1279. if (!IsRestarted)
  1280. {
  1281. #endif // NO_SIGHUP
  1282. if (gid != INVALID_GID && setgid(gid))
  1283. {
  1284. printerrorf("Fatal: setgid for %s failed.\n", gname);
  1285. return !0;
  1286. }
  1287. if (uid != INVALID_UID && setuid(uid))
  1288. {
  1289. printerrorf("Fatal: setuid for %s failed.\n", uname);
  1290. return !0;
  1291. }
  1292. #ifndef NO_SIGHUP
  1293. }
  1294. #endif // NO_SIGHUP
  1295. #endif // !defined(_WIN32) && !defined(NO_USER_SWITCH)
  1296. randomNumberInit();
  1297. // Randomization Level 1 means generate ePIDs at startup and use them during
  1298. // the lifetime of the process. So we generate them now
  1299. #ifndef NO_RANDOM_EPID
  1300. if (RandomizationLevel == 1) randomPidInit();
  1301. #endif
  1302. #if !defined(NO_SOCKETS)
  1303. #ifdef _WIN32
  1304. if (!IsNTService)
  1305. #endif // _WIN32
  1306. if ((error = daemonizeAndSetSignalAction())) return error;
  1307. #endif // !defined(NO_SOCKETS)
  1308. writePidFile();
  1309. #if !defined(NO_LOG) && !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1310. if (!InetdMode)
  1311. logger("vlmcsd %s started successfully\n", Version);
  1312. #endif // !defined(NO_LOG) && !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1313. #if defined(_NTSERVICE) && !defined(USE_MSRPC)
  1314. if (IsNTService) ReportServiceStatus(SERVICE_RUNNING, NO_ERROR, 200);
  1315. #endif // defined(_NTSERVICE) && !defined(USE_MSRPC)
  1316. int rc;
  1317. rc = runServer();
  1318. // Clean up things and exit
  1319. #ifdef _NTSERVICE
  1320. if (!ServiceShutdown)
  1321. #endif
  1322. cleanup();
  1323. #ifdef _NTSERVICE
  1324. else
  1325. ReportServiceStatus(SERVICE_STOPPED, NO_ERROR, 0);
  1326. #endif
  1327. return rc;
  1328. }
  1329. #ifndef CONFIG
  1330. #define CONFIG "config.h"
  1331. #endif // CONFIG
  1332. #include CONFIG
  1333. #include "crypto.h"
  1334. #include "endian.h"
  1335. #include <stdint.h>
  1336. const BYTE AesKeyV4[] = {
  1337. 0x05, 0x3D, 0x83, 0x07, 0xF9, 0xE5, 0xF0, 0x88, 0xEB, 0x5E, 0xA6, 0x68, 0x6C, 0xF0, 0x37, 0xC7, 0xE4, 0xEF, 0xD2, 0xD6};
  1338. const BYTE AesKeyV5[] = {
  1339. 0xCD, 0x7E, 0x79, 0x6F, 0x2A, 0xB2, 0x5D, 0xCB, 0x55, 0xFF, 0xC8, 0xEF, 0x83, 0x64, 0xC4, 0x70 };
  1340. const BYTE AesKeyV6[] = {
  1341. 0xA9, 0x4A, 0x41, 0x95, 0xE2, 0x01, 0x43, 0x2D, 0x9B, 0xCB, 0x46, 0x04, 0x05, 0xD8, 0x4A, 0x21 };
  1342. static const BYTE SBox[] = {
  1343. 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B,
  1344. 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0,
  1345. 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26,
  1346. 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
  1347. 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2,
  1348. 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0,
  1349. 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED,
  1350. 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
  1351. 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F,
  1352. 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5,
  1353. 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC,
  1354. 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
  1355. 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14,
  1356. 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C,
  1357. 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D,
  1358. 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
  1359. 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F,
  1360. 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E,
  1361. 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11,
  1362. 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
  1363. 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F,
  1364. 0xB0, 0x54, 0xBB, 0x16
  1365. };
  1366. void XorBlock(const BYTE *const in, const BYTE *out) // Ensure that this is always 32 bit aligned
  1367. {
  1368. /*UAA64( out, 0 ) ^= UAA64( in, 0 );
  1369. UAA64( out, 1 ) ^= UAA64( in, 1 );*/
  1370. uint_fast8_t i;
  1371. for (i = 0; i < AES_BLOCK_WORDS; i++)
  1372. {
  1373. ((DWORD*)out)[i] ^= ((DWORD*)in)[i];
  1374. }
  1375. }
  1376. #define AddRoundKey(d, rk) XorBlock((const BYTE *)rk, (const BYTE *)d)
  1377. #define Mul2(word) (((word & 0x7f7f7f7f) << 1) ^ (((word & 0x80808080) >> 7) * 0x1b))
  1378. #define Mul3(word) (Mul2(word) ^ word)
  1379. #define Mul4(word) (Mul2(Mul2(word)))
  1380. #define Mul8(word) (Mul2(Mul2(Mul2(word))))
  1381. #define Mul9(word) (Mul8(word) ^ word)
  1382. #define MulB(word) (Mul8(word) ^ Mul3(word))
  1383. #define MulD(word) (Mul8(word) ^ Mul4(word) ^ word)
  1384. #define MulE(word) (Mul8(word) ^ Mul4(word) ^ Mul2(word))
  1385. //32 bit Galois Multiplication (generates bigger code than Macros)
  1386. /*static DWORD Mul(DWORD x, DWORD y)
  1387. {
  1388. DWORD result = x, yTemp = y, log2;
  1389. if (!y) return 0;
  1390. for (log2 = 0; yTemp >>= 1; log2++ )
  1391. {
  1392. result = Mul2(result);
  1393. }
  1394. return result ^ Mul(x, y - (1 << log2));
  1395. }*/
  1396. void MixColumnsR(BYTE *restrict state)
  1397. {
  1398. uint_fast8_t i = 0;
  1399. for (; i < AES_BLOCK_WORDS; i++)
  1400. {
  1401. #if defined(_CRYPTO_OPENSSL) && defined(_OPENSSL_SOFTWARE) && defined(_USE_AES_FROM_OPENSSL) //Always byte swap regardless of endianess
  1402. DWORD word = BS32(((DWORD *) state)[i]);
  1403. ((DWORD *) state)[i] = BS32(MulE(word) ^ ROR32(MulB(word), 8) ^ ROR32(MulD(word), 16) ^ ROR32(Mul9(word), 24));
  1404. #else
  1405. DWORD word = LE32(((DWORD *) state)[i]);
  1406. ((DWORD *) state)[i] = LE32(MulE(word) ^ ROR32(MulB(word), 8) ^ ROR32(MulD(word), 16) ^ ROR32(Mul9(word), 24));
  1407. #endif
  1408. }
  1409. }
  1410. static DWORD SubDword(DWORD v)
  1411. {
  1412. BYTE *b = (BYTE *)&v;
  1413. uint_fast8_t i = 0;
  1414. for (; i < sizeof(DWORD); i++) b[i] = SBox[b[i]];
  1415. return v;
  1416. }
  1417. void AesInitKey(AesCtx *Ctx, const BYTE *Key, int_fast8_t IsV6, int RijndaelKeyBytes)
  1418. {
  1419. int RijndaelKeyDwords = RijndaelKeyBytes / sizeof(DWORD);
  1420. Ctx->rounds = (uint_fast8_t)(RijndaelKeyDwords + 6);
  1421. static const DWORD RCon[] = {
  1422. 0x00000000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000,
  1423. 0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000 };
  1424. uint_fast8_t i;
  1425. DWORD temp;
  1426. memcpy(Ctx->Key, Key, RijndaelKeyBytes);
  1427. for ( i = RijndaelKeyDwords; i < ( Ctx->rounds + 1 ) << 2; i++ )
  1428. {
  1429. temp = Ctx->Key[ i - 1 ];
  1430. if ( ( i % RijndaelKeyDwords ) == 0 )
  1431. temp = BE32( SubDword( ROR32( BE32(temp), 24) ) ^ RCon[ i / RijndaelKeyDwords ] );
  1432. Ctx->Key[ i ] = Ctx->Key[ i - RijndaelKeyDwords ] ^ temp;
  1433. }
  1434. if ( IsV6 )
  1435. {
  1436. BYTE *_p = (BYTE *)Ctx->Key;
  1437. _p[ 4 * 16 ] ^= 0x73;
  1438. _p[ 6 * 16 ] ^= 0x09;
  1439. _p[ 8 * 16 ] ^= 0xE4;
  1440. }
  1441. }
  1442. #if !defined(_CRYPTO_OPENSSL) || !defined(_USE_AES_FROM_OPENSSL) || defined(_OPENSSL_SOFTWARE)
  1443. static void SubBytes(BYTE *block)
  1444. {
  1445. uint_fast8_t i;
  1446. for (i = 0; i < AES_BLOCK_BYTES; i++)
  1447. block[i] = SBox[ block[i] ];
  1448. }
  1449. static void ShiftRows(BYTE *state)
  1450. {
  1451. BYTE bIn[AES_BLOCK_BYTES];
  1452. uint_fast8_t i;
  1453. memcpy(bIn, state, AES_BLOCK_BYTES);
  1454. for (i = 0; i < AES_BLOCK_BYTES; i++)
  1455. {
  1456. state[i] = bIn[(i + ((i & 3) << 2)) & 0xf];
  1457. }
  1458. };
  1459. static void MixColumns(BYTE *state)
  1460. {
  1461. uint_fast8_t i = 0;
  1462. for (; i < AES_BLOCK_WORDS; i++)
  1463. {
  1464. DWORD word = LE32(((DWORD *) state)[i]);
  1465. ((DWORD *) state)[i] = LE32(Mul2(word) ^ ROR32(Mul3(word), 8) ^ ROR32(word, 16) ^ ROR32(word, 24));
  1466. }
  1467. }
  1468. void AesEncryptBlock(const AesCtx *const Ctx, BYTE *block)
  1469. {
  1470. uint_fast8_t i;
  1471. for ( i = 0 ;; i += 4 )
  1472. {
  1473. AddRoundKey(block, &Ctx->Key[ i ]);
  1474. SubBytes(block);
  1475. ShiftRows(block);
  1476. if ( i >= ( Ctx->rounds - 1 ) << 2 ) break;
  1477. MixColumns(block);
  1478. }
  1479. AddRoundKey(block, &Ctx->Key[ Ctx->rounds << 2 ]);
  1480. }
  1481. void AesCmacV4(BYTE *Message, size_t MessageSize, BYTE *MacOut)
  1482. {
  1483. size_t i;
  1484. BYTE mac[AES_BLOCK_BYTES];
  1485. AesCtx Ctx;
  1486. AesInitKey(&Ctx, AesKeyV4, FALSE, V4_KEY_BYTES);
  1487. memset(mac, 0, sizeof(mac));
  1488. memset(Message + MessageSize, 0, AES_BLOCK_BYTES);
  1489. Message[MessageSize] = 0x80;
  1490. for (i = 0; i <= MessageSize; i += AES_BLOCK_BYTES)
  1491. {
  1492. XorBlock(Message + i, mac);
  1493. AesEncryptBlock(&Ctx, mac);
  1494. }
  1495. memcpy(MacOut, mac, AES_BLOCK_BYTES);
  1496. }
  1497. #endif
  1498. #if !defined(_CRYPTO_OPENSSL) || !defined(_USE_AES_FROM_OPENSSL)
  1499. static const BYTE SBoxR[] = {
  1500. 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E,
  1501. 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87,
  1502. 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32,
  1503. 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
  1504. 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49,
  1505. 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16,
  1506. 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50,
  1507. 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
  1508. 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05,
  1509. 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02,
  1510. 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41,
  1511. 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
  1512. 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8,
  1513. 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89,
  1514. 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B,
  1515. 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
  1516. 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59,
  1517. 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D,
  1518. 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D,
  1519. 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
  1520. 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63,
  1521. 0x55, 0x21, 0x0C, 0x7D
  1522. };
  1523. static void ShiftRowsR(BYTE *state)
  1524. {
  1525. BYTE b[AES_BLOCK_BYTES];
  1526. uint_fast8_t i;
  1527. memcpy(b, state, AES_BLOCK_BYTES);
  1528. for (i = 0; i < AES_BLOCK_BYTES; i++)
  1529. state[i] = b[(i - ((i & 0x3) << 2)) & 0xf];
  1530. }
  1531. static void SubBytesR(BYTE *block)
  1532. {
  1533. uint_fast8_t i;
  1534. for (i = 0; i < AES_BLOCK_BYTES; i++)
  1535. block[i] = SBoxR[ block[i] ];
  1536. }
  1537. void AesEncryptCbc(const AesCtx *const Ctx, BYTE *restrict iv, BYTE *restrict data, size_t *restrict len)
  1538. {
  1539. // Pad up to blocksize inclusive
  1540. size_t i;
  1541. uint_fast8_t pad = (~*len & (AES_BLOCK_BYTES - 1)) + 1;
  1542. #if defined(__GNUC__) && (__GNUC__ == 4 && __GNUC_MINOR__ == 8) // gcc 4.8 memset bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56977
  1543. for (i = 0; i < pad; i++) data[*len + i] = pad;
  1544. #else
  1545. memset(data + *len, pad, pad);
  1546. #endif
  1547. *len += pad;
  1548. if ( iv ) XorBlock(iv, data);
  1549. AesEncryptBlock(Ctx, data);
  1550. for (i = *len - AES_BLOCK_BYTES; i; i -= AES_BLOCK_BYTES)
  1551. {
  1552. XorBlock(data, data + AES_BLOCK_BYTES);
  1553. data += AES_BLOCK_BYTES;
  1554. AesEncryptBlock(Ctx, data);
  1555. }
  1556. }
  1557. void AesDecryptBlock(const AesCtx *const Ctx, BYTE *block)
  1558. {
  1559. uint_fast8_t i;
  1560. AddRoundKey(block, &Ctx->Key[ Ctx->rounds << 2 ]);
  1561. for ( i = ( Ctx->rounds - 1 ) << 2 ;; i -= 4 )
  1562. {
  1563. ShiftRowsR(block);
  1564. SubBytesR(block);
  1565. AddRoundKey(block, &Ctx->Key[ i ]);
  1566. if ( i == 0 ) break;
  1567. MixColumnsR(block);
  1568. }
  1569. }
  1570. void AesDecryptCbc(const AesCtx *const Ctx, BYTE *iv, BYTE *data, size_t len)
  1571. {
  1572. BYTE *cc;
  1573. for (cc = data + len - AES_BLOCK_BYTES; cc > data; cc -= AES_BLOCK_BYTES)
  1574. {
  1575. AesDecryptBlock(Ctx, cc);
  1576. XorBlock(cc - AES_BLOCK_BYTES, cc);
  1577. }
  1578. AesDecryptBlock(Ctx, cc);
  1579. if ( iv ) XorBlock(iv, cc);
  1580. }
  1581. #endif // _CRYPTO_OPENSSL || OPENSSL_VERSION_NUMBER < 0x10000000L
  1582. #ifndef CONFIG
  1583. #define CONFIG "config.h"
  1584. #endif // CONFIG
  1585. #include CONFIG
  1586. #include <stdio.h>
  1587. #include <string.h>
  1588. #include <stdint.h>
  1589. #include <ctype.h>
  1590. #include <time.h>
  1591. #if !defined(_WIN32)
  1592. #include <sys/socket.h>
  1593. #endif
  1594. #include "output.h"
  1595. #include "crypto.h"
  1596. #include "endian.h"
  1597. #include "kms.h"
  1598. #include "shared_globals.h"
  1599. #include "helpers.h"
  1600. #define FRIENDLY_NAME_WINDOWS "Windows"
  1601. #define FRIENDLY_NAME_OFFICE2010 "Office 2010"
  1602. #define FRIENDLY_NAME_OFFICE2013 "Office"
  1603. #ifndef NO_BASIC_PRODUCT_LIST
  1604. // Do not change the order of this list. Append items as necessary
  1605. const KmsIdList ProductList[] = {
  1606. /* 000 */ { { 0x212a64dc, 0x43b1, 0x4d3d, { 0xa3, 0x0c, 0x2f, 0xc6, 0x9d, 0x20, 0x95, 0xc6 } } /*"212a64dc-43b1-4d3d-a30c-2fc69d2095c6"*/, "Vista", EPID_WINDOWS, 4, 25 },
  1607. /* 001 */ { { 0x7fde5219, 0xfbfa, 0x484a, { 0x82, 0xc9, 0x34, 0xd1, 0xad, 0x53, 0xe8, 0x56 } } /*"7fde5219-fbfa-484a-82c9-34d1ad53e856"*/, "Windows 7", EPID_WINDOWS, 4, 25 },
  1608. /* 002 */ { { 0x3c40b358, 0x5948, 0x45af, { 0x92, 0x3b, 0x53, 0xd2, 0x1f, 0xcc, 0x7e, 0x79 } } /*"3c40b358-5948-45af-923b-53d21fcc7e79"*/, "Windows 8 VL", EPID_WINDOWS, 5, 25 },
  1609. /* 003 */ { { 0x5f94a0bb, 0xd5a0, 0x4081, { 0xa6, 0x85, 0x58, 0x19, 0x41, 0x8b, 0x2f, 0xe0 } } /*"5f94a0bb-d5a0-4081-a685-5819418b2fe0"*/, "Windows Preview", EPID_WINDOWS, 6, 25 },
  1610. /* 004 */ { { 0xbbb97b3b, 0x8ca4, 0x4a28, { 0x97, 0x17, 0x89, 0xfa, 0xbd, 0x42, 0xc4, 0xac } } /*"bbb97b3b-8ca4-4a28-9717-89fabd42c4ac"*/, "Windows 8 Retail", EPID_WINDOWS, 5, 25 },
  1611. /* 005 */ { { 0xcb8fc780, 0x2c05, 0x495a, { 0x97, 0x10, 0x85, 0xaf, 0xff, 0xc9, 0x04, 0xd7 } } /*"cb8fc780-2c05-495a-9710-85afffc904d7"*/, "Windows 8.1 VL", EPID_WINDOWS, 6, 25 },
  1612. /* 006 */ { { 0x6d646890, 0x3606, 0x461a, { 0x86, 0xab, 0x59, 0x8b, 0xb8, 0x4a, 0xce, 0x82 } } /*"6d646890-3606-461a-86ab-598bb84ace82"*/, "Windows 8.1 Retail", EPID_WINDOWS, 6, 25 },
  1613. /* 007 */ { { 0x33e156e4, 0xb76f, 0x4a52, { 0x9f, 0x91, 0xf6, 0x41, 0xdd, 0x95, 0xac, 0x48 } } /*"33e156e4-b76f-4a52-9f91-f641dd95ac48"*/, "Windows 2008 A", EPID_WINDOWS, 4, 5 },
  1614. /* 008 */ { { 0x8fe53387, 0x3087, 0x4447, { 0x89, 0x85, 0xf7, 0x51, 0x32, 0x21, 0x5a, 0xc9 } } /*"8fe53387-3087-4447-8985-f75132215ac9"*/, "Windows 2008 B", EPID_WINDOWS, 4, 5 },
  1615. /* 009 */ { { 0x8a21fdf3, 0xcbc5, 0x44eb, { 0x83, 0xf3, 0xfe, 0x28, 0x4e, 0x66, 0x80, 0xa7 } } /*"8a21fdf3-cbc5-44eb-83f3-fe284e6680a7"*/, "Windows 2008 C", EPID_WINDOWS, 4, 5 },
  1616. /* 010 */ { { 0x0fc6ccaf, 0xff0e, 0x4fae, { 0x9d, 0x08, 0x43, 0x70, 0x78, 0x5b, 0xf7, 0xed } } /*"0fc6ccaf-ff0e-4fae-9d08-4370785bf7ed"*/, "Windows 2008 R2 A", EPID_WINDOWS, 4, 5 },
  1617. /* 011 */ { { 0xca87f5b6, 0xcd46, 0x40c0, { 0xb0, 0x6d, 0x8e, 0xcd, 0x57, 0xa4, 0x37, 0x3f } } /*"ca87f5b6-cd46-40c0-b06d-8ecd57a4373f"*/, "Windows 2008 R2 B", EPID_WINDOWS, 4, 5 },
  1618. /* 012 */ { { 0xb2ca2689, 0xa9a8, 0x42d7, { 0x93, 0x8d, 0xcf, 0x8e, 0x9f, 0x20, 0x19, 0x58 } } /*"b2ca2689-a9a8-42d7-938d-cf8e9f201958"*/, "Windows 2008 R2 C", EPID_WINDOWS, 4, 5 },
  1619. /* 013 */ { { 0x8665cb71, 0x468c, 0x4aa3, { 0xa3, 0x37, 0xcb, 0x9b, 0xc9, 0xd5, 0xea, 0xac } } /*"8665cb71-468c-4aa3-a337-cb9bc9d5eaac"*/, "Windows 2012", EPID_WINDOWS, 5, 5 },
  1620. /* 014 */ { { 0x8456EFD3, 0x0C04, 0x4089, { 0x87, 0x40, 0x5b, 0x72, 0x38, 0x53, 0x5a, 0x65 } } /*"8456EFD3-0C04-4089-8740-5B7238535A65"*/, "Windows 2012 R2", EPID_WINDOWS, 6, 5 },
  1621. /* 015 */ { { 0xe85af946, 0x2e25, 0x47b7, { 0x83, 0xe1, 0xbe, 0xbc, 0xeb, 0xea, 0xc6, 0x11 } } /*"e85af946-2e25-47b7-83e1-bebcebeac611"*/, "Office 2010", EPID_OFFICE2010, 4, 5 },
  1622. /* 016 */ { { 0xe6a6f1bf, 0x9d40, 0x40c3, { 0xaa, 0x9f, 0xc7, 0x7b, 0xa2, 0x15, 0x78, 0xc0 } } /*"e6a6f1bf-9d40-40c3-aa9f-c77ba21578c0"*/, "Office 2013", EPID_OFFICE2013, 6, 5 },
  1623. /* 017 */ { { 0x6d5f5270, 0x31ac, 0x433e, { 0xb9, 0x0a, 0x39, 0x89, 0x29, 0x23, 0xc6, 0x57 } } /*"6d5f5270-31ac-433e-b90a-39892923c657"*/, "Windows Server Preview", EPID_WINDOWS, 6, 5 },
  1624. /* 018 */ { { 0x85b5f61b, 0x320b, 0x4be3, { 0x81, 0x4a, 0xb7, 0x6b, 0x2b, 0xfa, 0xfc, 0x82 } } /*"85b5f61b-320b-4be3-814a-b76b2bfafc82"*/, "Office 2016", EPID_OFFICE2013, 6, 5 },
  1625. /* 019 */ { { 0x58e2134f, 0x8e11, 0x4d17, { 0x9c, 0xb2, 0x91, 0x06, 0x9c, 0x15, 0x11, 0x48 } } /*"58e2134f-8e11-4d17-9cb2-91069c151148"*/, "Windows 10 VL", EPID_WINDOWS, 6, 25 },
  1626. /* 020 */ { { 0xe1c51358, 0xfe3e, 0x4203, { 0xa4, 0xa2, 0x3b, 0x6b, 0x20, 0xc9, 0x73, 0x4e } } /*"e1c51358-fe3e-4203-a4a2-3b6b20c9734e"*/, "Windows 10 Retail", EPID_WINDOWS, 6, 25 },
  1627. /* 021 */ { { 0x00000000, 0x0000, 0x0000, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }, NULL, NULL, 0, 0 }
  1628. };
  1629. #endif
  1630. // Application ID is used by KMS server to count KeyManagementServiceCurrentCount
  1631. // Do not change the order of this list. Append items as necessary
  1632. const KmsIdList AppList[] = {
  1633. /* 000 */ { { 0x55c92734, 0xd682, 0x4d71, { 0x98, 0x3e, 0xd6, 0xec, 0x3f, 0x16, 0x05, 0x9f } } /*"55C92734-D682-4D71-983E-D6EC3F16059F"*/, FRIENDLY_NAME_WINDOWS, EPID_WINDOWS, 0, 0},
  1634. /* 001 */ { { 0x59A52881, 0xa989, 0x479d, { 0xaf, 0x46, 0xf2, 0x75, 0xc6, 0x37, 0x06, 0x63 } } /*"59A52881-A989-479D-AF46-F275C6370663"*/, FRIENDLY_NAME_OFFICE2010, EPID_OFFICE2010, 0, 0},
  1635. /* 002 */ { { 0x0FF1CE15, 0xA989, 0x479D, { 0xaf, 0x46, 0xf2, 0x75, 0xc6, 0x37, 0x06, 0x63 } } /*"0FF1CE15-A989-479D-AF46-F275C6370663"*/, FRIENDLY_NAME_OFFICE2013, EPID_OFFICE2013, 0, 0},
  1636. /* 003 */ { { 0x00000000, 0x0000, 0x0000, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }, NULL, NULL, 0, 0 }
  1637. };
  1638. #ifndef NO_EXTENDED_PRODUCT_LIST
  1639. const KmsIdList ExtendedProductList [] = {
  1640. // Windows Server
  1641. { { 0xad2542d4, 0x9154, 0x4c6d, { 0x8a, 0x44, 0x30, 0xf1, 0x1e, 0xe9, 0x69, 0x89, } } /*ad2542d4-9154-4c6d-8a44-30f11ee96989*/, "Windows Server 2008 Standard", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2008A },
  1642. { { 0x2401e3d0, 0xc50a, 0x4b58, { 0x87, 0xb2, 0x7e, 0x79, 0x4b, 0x7d, 0x26, 0x07, } } /*2401e3d0-c50a-4b58-87b2-7e794b7d2607*/, "Windows Server 2008 Standard V", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2008A },
  1643. { { 0x68b6e220, 0xcf09, 0x466b, { 0x92, 0xd3, 0x45, 0xcd, 0x96, 0x4b, 0x95, 0x09, } } /*68b6e220-cf09-466b-92d3-45cd964b9509*/, "Windows Server 2008 Datacenter", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2008C },
  1644. { { 0xfd09ef77, 0x5647, 0x4eff, { 0x80, 0x9c, 0xaf, 0x2b, 0x64, 0x65, 0x9a, 0x45, } } /*fd09ef77-5647-4eff-809c-af2b64659a45*/, "Windows Server 2008 Datacenter V", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2008C },
  1645. { { 0xc1af4d90, 0xd1bc, 0x44ca, { 0x85, 0xd4, 0x00, 0x3b, 0xa3, 0x3d, 0xb3, 0xb9, } } /*c1af4d90-d1bc-44ca-85d4-003ba33db3b9*/, "Windows Server 2008 Enterprise", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2008B },
  1646. { { 0x8198490a, 0xadd0, 0x47b2, { 0xb3, 0xba, 0x31, 0x6b, 0x12, 0xd6, 0x47, 0xb4, } } /*8198490a-add0-47b2-b3ba-316b12d647b4*/, "Windows Server 2008 Enterprise V", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2008B },
  1647. { { 0xddfa9f7c, 0xf09e, 0x40b9, { 0x8c, 0x1a, 0xbe, 0x87, 0x7a, 0x9a, 0x7f, 0x4b, } } /*ddfa9f7c-f09e-40b9-8c1a-be877a9a7f4b*/, "Windows Server 2008 Web", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2008A },
  1648. { { 0x7afb1156, 0x2c1d, 0x40fc, { 0xb2, 0x60, 0xaa, 0xb7, 0x44, 0x2b, 0x62, 0xfe, } } /*7afb1156-2c1d-40fc-b260-aab7442b62fe*/, "Windows Server 2008 Compute Cluster", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2008C },
  1649. { { 0x68531fb9, 0x5511, 0x4989, { 0x97, 0xbe, 0xd1, 0x1a, 0x0f, 0x55, 0x63, 0x3f, } } /*68531fb9-5511-4989-97be-d11a0f55633f*/, "Windows Server 2008 R2 Standard", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2008R2A },
  1650. { { 0x7482e61b, 0xc589, 0x4b7f, { 0x8e, 0xcc, 0x46, 0xd4, 0x55, 0xac, 0x3b, 0x87, } } /*7482e61b-c589-4b7f-8ecc-46d455ac3b87*/, "Windows Server 2008 R2 Datacenter", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2008R2C },
  1651. { { 0x620e2b3d, 0x09e7, 0x42fd, { 0x80, 0x2a, 0x17, 0xa1, 0x36, 0x52, 0xfe, 0x7a, } } /*620e2b3d-09e7-42fd-802a-17a13652fe7a*/, "Windows Server 2008 R2 Enterprise", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2008R2B },
  1652. { { 0xa78b8bd9, 0x8017, 0x4df5, { 0xb8, 0x6a, 0x09, 0xf7, 0x56, 0xaf, 0xfa, 0x7c, } } /*a78b8bd9-8017-4df5-b86a-09f756affa7c*/, "Windows Server 2008 R2 Web", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2008R2A },
  1653. { { 0xcda18cf3, 0xc196, 0x46ad, { 0xb2, 0x89, 0x60, 0xc0, 0x72, 0x86, 0x99, 0x94, } } /*cda18cf3-c196-46ad-b289-60c072869994*/, "Windows Server 2008 R2 Compute Cluster", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2008R2C },
  1654. { { 0xd3643d60, 0x0c42, 0x412d, { 0xa7, 0xd6, 0x52, 0xe6, 0x63, 0x53, 0x27, 0xf6, } } /*d3643d60-0c42-412d-a7d6-52e6635327f6*/, "Windows Server 2012 Datacenter", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2012 },
  1655. { { 0xf0f5ec41, 0x0d55, 0x4732, { 0xaf, 0x02, 0x44, 0x0a, 0x44, 0xa3, 0xcf, 0x0f, } } /*f0f5ec41-0d55-4732-af02-440a44a3cf0f*/, "Windows Server 2012 Standard", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2012 },
  1656. { { 0x95fd1c83, 0x7df5, 0x494a, { 0xbe, 0x8b, 0x13, 0x00, 0xe1, 0xc9, 0xd1, 0xcd, } } /*95fd1c83-7df5-494a-be8b-1300e1c9d1cd*/, "Windows Server 2012 MultiPoint Premium", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2012 },
  1657. { { 0x7d5486c7, 0xe120, 0x4771, { 0xb7, 0xf1, 0x7b, 0x56, 0xc6, 0xd3, 0x17, 0x0c, } } /*7d5486c7-e120-4771-b7f1-7b56c6d3170c*/, "Windows Server 2012 MultiPoint Standard", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2012 },
  1658. { { 0x00091344, 0x1ea4, 0x4f37, { 0xb7, 0x89, 0x01, 0x75, 0x0b, 0xa6, 0x98, 0x8c, } } /*00091344-1ea4-4f37-b789-01750ba6988c*/, "Windows Server 2012 R2 Datacenter", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2012R2 },
  1659. { { 0xb3ca044e, 0xa358, 0x4d68, { 0x98, 0x83, 0xaa, 0xa2, 0x94, 0x1a, 0xca, 0x99, } } /*b3ca044e-a358-4d68-9883-aaa2941aca99*/, "Windows Server 2012 R2 Standard", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2012R2 },
  1660. { { 0xb743a2be, 0x68d4, 0x4dd3, { 0xaf, 0x32, 0x92, 0x42, 0x5b, 0x7b, 0xb6, 0x23, } } /*b743a2be-68d4-4dd3-af32-92425b7bb623*/, "Windows Server 2012 R2 Cloud Storage", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2012R2 },
  1661. { { 0x21db6ba4, 0x9a7b, 0x4a14, { 0x9e, 0x29, 0x64, 0xa6, 0x0c, 0x59, 0x30, 0x1d, } } /*21db6ba4-9a7b-4a14-9e29-64a60c59301d*/, "Windows Server 2012 R2 Essentials", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN2012R2 },
  1662. { { 0xba947c44, 0xd19d, 0x4786, { 0xb6, 0xae, 0x22, 0x77, 0x0b, 0xc9, 0x4c, 0x54, } } /*ba947c44-d19d-4786-b6ae-22770bc94c54*/, "Windows Server 2016 Datacenter Preview", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN_SRV_BETA },
  1663. // Windows 10 Preview
  1664. # ifdef INCLUDE_BETAS
  1665. { { 0x6496e59d, 0x89dc, 0x49eb, { 0xa3, 0x53, 0x09, 0xce, 0xb9, 0x40, 0x48, 0x45, } } /*6496e59d-89dc-49eb-a353-09ceb9404845*/, "Windows 10 Core Preview", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN_BETA },
  1666. { { 0xa4383e6b, 0xdada, 0x423d, { 0xa4, 0x3d, 0xf2, 0x56, 0x78, 0x42, 0x96, 0x76, } } /*a4383e6b-dada-423d-a43d-f25678429676*/, "Windows 10 Professional Preview", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN_BETA },
  1667. { { 0xcf59a07b, 0x1a2a, 0x4be0, { 0xbf, 0xe0, 0x42, 0x3b, 0x58, 0x23, 0xe6, 0x63, } } /*cf59a07b-1a2a-4be0-bfe0-423b5823e663*/, "Windows 10 Professional WMC Preview", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN_BETA },
  1668. { { 0xcde952c7, 0x2f96, 0x4d9d, { 0x8f, 0x2b, 0x2d, 0x34, 0x9f, 0x64, 0xfc, 0x51, } } /*cde952c7-2f96-4d9d-8f2b-2d349f64fc51*/, "Windows 10 Enterprise Preview", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN_BETA },
  1669. # endif
  1670. // Windows 10
  1671. { { 0x73111121, 0x5638, 0x40f6, { 0xbc, 0x11, 0xf1, 0xd7, 0xb0, 0xd6, 0x43, 0x00, } } /*73111121-5638-40f6-bc11-f1d7b0d64300*/, "Windows 10 Enterprise", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN10_VL },
  1672. { { 0xe272e3e2, 0x732f, 0x4c65, { 0xa8, 0xf0, 0x48, 0x47, 0x47, 0xd0, 0xd9, 0x47, } } /*e272e3e2-732f-4c65-a8f0-484747d0d947*/, "Windows 10 Enterprise N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN10_VL},
  1673. { { 0x7b51a46c, 0x0c04, 0x4e8f, { 0x9a, 0xf4, 0x84, 0x96, 0xcc, 0xa9, 0x0d, 0x5e, } } /*7b51a46c-0c04-4e8f-9af4-8496cca90d5e*/, "Windows 10 Enterprise LTSB", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN10_VL},
  1674. { { 0x87b838b7, 0x41b6, 0x4590, { 0x83, 0x18, 0x57, 0x97, 0x95, 0x1d, 0x85, 0x29, } } /*87b838b7-41b6-4590-8318-5797951d8529*/, "Windows 10 Enterprise LTSB N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN10_VL},
  1675. { { 0xe0c42288, 0x980c, 0x4788, { 0xa0, 0x14, 0xc0, 0x80, 0xd2, 0xe1, 0x92, 0x6e, } } /*e0c42288-980c-4788-a014-c080d2e1926e*/, "Windows 10 Education", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN10_VL},
  1676. { { 0x3c102355, 0xd027, 0x42c6, { 0xad, 0x23, 0x2e, 0x7e, 0xf8, 0xa0, 0x25, 0x85, } } /*3c102355-d027-42c6-ad23-2e7ef8a02585*/, "Windows 10 Education N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN10_VL},
  1677. { { 0x2de67392, 0xb7a7, 0x462a, { 0xb1, 0xca, 0x10, 0x8d, 0xd1, 0x89, 0xf5, 0x88, } } /*2de67392-b7a7-462a-b1ca-108dd189f588*/, "Windows 10 Professional", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN10_VL },
  1678. { { 0xa80b5abf, 0x75ad, 0x428b, { 0xb0, 0x5d, 0xa4, 0x7d, 0x2d, 0xff, 0xee, 0xbf, } } /*a80b5abf-76ad-428b-b05d-a47d2dffeebf*/, "Windows 10 Professional N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN10_VL},
  1679. { { 0x58e97c99, 0xf377, 0x4ef1, { 0x81, 0xd5, 0x4a, 0xd5, 0x52, 0x2b, 0x5f, 0xd8, } } /*58e97c99-f377-4ef1-81d5-4ad5522b5fd8*/, "Windows 10 Home", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN10_RETAIL},
  1680. { { 0x7b9e1751, 0xa8da, 0x4f75, { 0x95, 0x60, 0x5f, 0xad, 0xfe, 0x3d, 0x8e, 0x38, } } /*7b9e1751-a8da-4f75-9560-5fadfe3d8e38*/, "Windows 10 Home N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN10_RETAIL},
  1681. { { 0xcd918a57, 0xa41b, 0x4c82, { 0x8d, 0xce, 0x1a, 0x53, 0x8e, 0x22, 0x1a, 0x83, } } /*cd918a57-a41b-4c82-8dce-1a538e221a83*/, "Windows 10 Home Single Language", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN10_RETAIL},
  1682. { { 0xa9107544, 0xf4a0, 0x4053, { 0xa9, 0x6a, 0x14, 0x79, 0xab, 0xde, 0xf9, 0x12, } } /*a9107544-f4a0-4053-a96a-1479abdef912*/, "Windows 10 Home Country Specific", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN10_RETAIL},
  1683. // Windows 8.x
  1684. # ifdef INCLUDE_BETAS
  1685. { { 0x2B9C337F, 0x7A1D, 0x4271, { 0x90, 0xA3, 0xC6, 0x85, 0x5A, 0x2B, 0x8A, 0x1C, } } /*2B9C337F-7A1D-4271-90A3-C6855A2B8A1C*/, "Windows 8.x Preview", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN_BETA },
  1686. { { 0x631EAD72, 0xA8AB, 0x4DF8, { 0xBB, 0xDF, 0x37, 0x20, 0x29, 0x98, 0x9B, 0xDD, } } /*631EAD72-A8AB-4DF8-BBDF-372029989BDD*/, "Windows 8.x Preview ARM", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN_BETA },
  1687. # endif
  1688. { { 0x81671aaf, 0x79d1, 0x4eb1, { 0xb0, 0x04, 0x8c, 0xbb, 0xe1, 0x73, 0xaf, 0xea, } } /*81671aaf-79d1-4eb1-b004-8cbbe173afea*/, "Windows 8.1 Enterprise", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_VL },
  1689. { { 0x113e705c, 0xfa49, 0x48a4, { 0xbe, 0xea, 0x7d, 0xd8, 0x79, 0xb4, 0x6b, 0x14, } } /*113e705c-fa49-48a4-beea-7dd879b46b14*/, "Windows 8.1 Enterprise N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_VL },
  1690. { { 0x096ce63d, 0x4fac, 0x48a9, { 0x82, 0xa9, 0x61, 0xae, 0x9e, 0x80, 0x0e, 0x5f, } } /*096ce63d-4fac-48a9-82a9-61ae9e800e5f*/, "Windows 8.1 Professional WMC", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_RETAIL },
  1691. { { 0xc06b6981, 0xd7fd, 0x4a35, { 0xb7, 0xb4, 0x05, 0x47, 0x42, 0xb7, 0xaf, 0x67, } } /*c06b6981-d7fd-4a35-b7b4-054742b7af67*/, "Windows 8.1 Professional", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_VL },
  1692. { { 0x7476d79f, 0x8e48, 0x49b4, { 0xab, 0x63, 0x4d, 0x0b, 0x81, 0x3a, 0x16, 0xe4, } } /*7476d79f-8e48-49b4-ab63-4d0b813a16e4*/, "Windows 8.1 Professional N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_VL },
  1693. { { 0xfe1c3238, 0x432a, 0x43a1, { 0x8e, 0x25, 0x97, 0xe7, 0xd1, 0xef, 0x10, 0xf3, } } /*fe1c3238-432a-43a1-8e25-97e7d1ef10f3*/, "Windows 8.1 Core", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_RETAIL },
  1694. { { 0x78558a64, 0xdc19, 0x43fe, { 0xa0, 0xd0, 0x80, 0x75, 0xb2, 0xa3, 0x70, 0xa3, } } /*78558a64-dc19-43fe-a0d0-8075b2a370a3*/, "Windows 8.1 Core N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_RETAIL },
  1695. { { 0xffee456a, 0xcd87, 0x4390, { 0x8e, 0x07, 0x16, 0x14, 0x6c, 0x67, 0x2f, 0xd0, } } /*ffee456a-cd87-4390-8e07-16146c672fd0*/, "Windows 8.1 Core ARM", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_RETAIL },
  1696. { { 0xc72c6a1d, 0xf252, 0x4e7e, { 0xbd, 0xd1, 0x3f, 0xca, 0x34, 0x2a, 0xcb, 0x35, } } /*c72c6a1d-f252-4e7e-bdd1-3fca342acb35*/, "Windows 8.1 Core Single Language", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_RETAIL },
  1697. { { 0xdb78b74f, 0xef1c, 0x4892, { 0xab, 0xfe, 0x1e, 0x66, 0xb8, 0x23, 0x1d, 0xf6, } } /*db78b74f-ef1c-4892-abfe-1e66b8231df6*/, "Windows 8.1 Core Country Specific", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_RETAIL },
  1698. { { 0xe9942b32, 0x2e55, 0x4197, { 0xb0, 0xbd, 0x5f, 0xf5, 0x8c, 0xba, 0x88, 0x60, } } /*e9942b32-2e55-4197-b0bd-5ff58cba8860*/, "Windows 8.1 Core Connected", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_VL },
  1699. { { 0xc6ddecd6, 0x2354, 0x4c19, { 0x90, 0x9b, 0x30, 0x6a, 0x30, 0x58, 0x48, 0x4e, } } /*c6ddecd6-2354-4c19-909b-306a3058484e*/, "Windows 8.1 Core Connected N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_VL },
  1700. { { 0xb8f5e3a3, 0xed33, 0x4608, { 0x81, 0xe1, 0x37, 0xd6, 0xc9, 0xdc, 0xfd, 0x9c, } } /*b8f5e3a3-ed33-4608-81e1-37d6c9dcfd9c*/, "Windows 8.1 Core Connected Single Language", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_VL },
  1701. { { 0xba998212, 0x460a, 0x44db, { 0xbf, 0xb5, 0x71, 0xbf, 0x09, 0xd1, 0xc6, 0x8b, } } /*ba998212-460a-44db-bfb5-71bf09d1c68b*/, "Windows 8.1 Core Connected Country Specific", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_VL },
  1702. { { 0xe58d87b5, 0x8126, 0x4580, { 0x80, 0xfb, 0x86, 0x1b, 0x22, 0xf7, 0x92, 0x96, } } /*e58d87b5-8126-4580-80fb-861b22f79296*/, "Windows 8.1 Professional Student", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_RETAIL },
  1703. { { 0xcab491c7, 0xa918, 0x4f60, { 0xb5, 0x02, 0xda, 0xb7, 0x5e, 0x33, 0x4f, 0x40, } } /*cab491c7-a918-4f60-b502-dab75e334f40*/, "Windows 8.1 Professional Student N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_RETAIL },
  1704. { { 0xa00018a3, 0xf20f, 0x4632, { 0xbf, 0x7c, 0x8d, 0xaa, 0x53, 0x51, 0xc9, 0x14, } } /*a00018a3-f20f-4632-bf7c-8daa5351c914*/, "Windows 8 Professional WMC", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN8_RETAIL },
  1705. { { 0xa98bcd6d, 0x5343, 0x4603, { 0x8a, 0xfe, 0x59, 0x08, 0xe4, 0x61, 0x11, 0x12, } } /*a98bcd6d-5343-4603-8afe-5908e4611112*/, "Windows 8 Professional", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN8_VL },
  1706. { { 0xebf245c1, 0x29a8, 0x4daf, { 0x9c, 0xb1, 0x38, 0xdf, 0xc6, 0x08, 0xa8, 0xc8, } } /*ebf245c1-29a8-4daf-9cb1-38dfc608a8c8*/, "Windows 8 Professional N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN8_VL },
  1707. { { 0x458e1bec, 0x837a, 0x45f6, { 0xb9, 0xd5, 0x92, 0x5e, 0xd5, 0xd2, 0x99, 0xde, } } /*458e1bec-837a-45f6-b9d5-925ed5d299de*/, "Windows 8 Enterprise", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN8_VL },
  1708. { { 0xe14997e7, 0x800a, 0x4cf7, { 0xad, 0x10, 0xde, 0x4b, 0x45, 0xb5, 0x78, 0xdb, } } /*e14997e7-800a-4cf7-ad10-de4b45b578db*/, "Windows 8 Enterprise N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN8_VL },
  1709. { { 0xc04ed6bf, 0x55c8, 0x4b47, { 0x9f, 0x8e, 0x5a, 0x1f, 0x31, 0xce, 0xee, 0x60, } } /*c04ed6bf-55c8-4b47-9f8e-5a1f31ceee60*/, "Windows 8 Core", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN8_RETAIL },
  1710. { { 0x197390a0, 0x65f6, 0x4a95, { 0xbd, 0xc4, 0x55, 0xd5, 0x8a, 0x3b, 0x02, 0x53, } } /*197390a0-65f6-4a95-bdc4-55d58a3b0253*/, "Windows 8 Core N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN8_RETAIL },
  1711. { { 0x9d5584a2, 0x2d85, 0x419a, { 0x98, 0x2c, 0xa0, 0x08, 0x88, 0xbb, 0x9d, 0xdf, } } /*9d5584a2-2d85-419a-982c-a00888bb9ddf*/, "Windows 8 Core Country Specific", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN8_RETAIL },
  1712. { { 0x8860fcd4, 0xa77b, 0x4a20, { 0x90, 0x45, 0xa1, 0x50, 0xff, 0x11, 0xd6, 0x09, } } /*8860fcd4-a77b-4a20-9045-a150ff11d609*/, "Windows 8 Core Single Language", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN8_RETAIL },
  1713. // Windows 7
  1714. { { 0xae2ee509, 0x1b34, 0x41c0, { 0xac, 0xb7, 0x6d, 0x46, 0x50, 0x16, 0x89, 0x15, } } /*ae2ee509-1b34-41c0-acb7-6d4650168915*/, "Windows 7 Enterprise", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN7 },
  1715. { { 0x1cb6d605, 0x11b3, 0x4e14, { 0xbb, 0x30, 0xda, 0x91, 0xc8, 0xe3, 0x98, 0x3a, } } /*1cb6d605-11b3-4e14-bb30-da91c8e3983a*/, "Windows 7 Enterprise N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN7 },
  1716. { { 0xb92e9980, 0xb9d5, 0x4821, { 0x9c, 0x94, 0x14, 0x0f, 0x63, 0x2f, 0x63, 0x12, } } /*b92e9980-b9d5-4821-9c94-140f632f6312*/, "Windows 7 Professional", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN7 },
  1717. { { 0x54a09a0d, 0xd57b, 0x4c10, { 0x8b, 0x69, 0xa8, 0x42, 0xd6, 0x59, 0x0a, 0xd5, } } /*54a09a0d-d57b-4c10-8b69-a842d6590ad5*/, "Windows 7 Professional N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN7 },
  1718. // Windows Vista
  1719. { { 0xcfd8ff08, 0xc0d7, 0x452b, { 0x9f, 0x60, 0xef, 0x5c, 0x70, 0xc3, 0x20, 0x94, } } /*cfd8ff08-c0d7-452b-9f60-ef5c70c32094*/, "Windows Vista Enterprise", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_VISTA },
  1720. { { 0xd4f54950, 0x26f2, 0x4fb4, { 0xba, 0x21, 0xff, 0xab, 0x16, 0xaf, 0xca, 0xde, } } /*d4f54950-26f2-4fb4-ba21-ffab16afcade*/, "Windows Vista Enterprise N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_VISTA },
  1721. { { 0x4f3d1606, 0x3fea, 0x4c01, { 0xbe, 0x3c, 0x8d, 0x67, 0x1c, 0x40, 0x1e, 0x3b, } } /*4f3d1606-3fea-4c01-be3c-8d671c401e3b*/, "Windows Vista Business", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_VISTA },
  1722. { { 0x2c682dc2, 0x8b68, 0x4f63, { 0xa1, 0x65, 0xae, 0x29, 0x1d, 0x4c, 0xf1, 0x38, } } /*2c682dc2-8b68-4f63-a165-ae291d4cf138*/, "Windows Vista Business N", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_VISTA },
  1723. // Windows Embedded
  1724. { { 0xaa6dd3aa, 0xc2b4, 0x40e2, { 0xa5, 0x44, 0xa6, 0xbb, 0xb3, 0xf5, 0xc3, 0x95, } } /*aa6dd3aa-c2b4-40e2-a544-a6bbb3f5c395*/, "Windows ThinPC", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN7 },
  1725. { { 0xdb537896, 0x376f, 0x48ae, { 0xa4, 0x92, 0x53, 0xd0, 0x54, 0x77, 0x73, 0xd0, } } /*db537896-376f-48ae-a492-53d0547773d0*/, "Windows Embedded POSReady 7", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN7 },
  1726. { { 0x0ab82d54, 0x47f4, 0x4acb, { 0x81, 0x8c, 0xcc, 0x5b, 0xf0, 0xec, 0xb6, 0x49, } } /*0ab82d54-47f4-4acb-818c-cc5bf0ecb649*/, "Windows Embedded Industry 8.1", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_VL },
  1727. { { 0xcd4e2d9f, 0x5059, 0x4a50, { 0xa9, 0x2d, 0x05, 0xd5, 0xbb, 0x12, 0x67, 0xc7, } } /*cd4e2d9f-5059-4a50-a92d-05d5bb1267c7*/, "Windows Embedded Industry E 8.1", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_VL },
  1728. { { 0xf7e88590, 0xdfc7, 0x4c78, { 0xbc, 0xcb, 0x6f, 0x38, 0x65, 0xb9, 0x9d, 0x1a, } } /*f7e88590-dfc7-4c78-bccb-6f3865b99d1a*/, "Windows Embedded Industry A 8.1", EPID_WINDOWS, APP_ID_WINDOWS, KMS_ID_WIN81_VL },
  1729. // Office 2010
  1730. { { 0x8ce7e872, 0x188c, 0x4b98, { 0x9d, 0x90, 0xf8, 0xf9, 0x0b, 0x7a, 0xad, 0x02, } } /*8ce7e872-188c-4b98-9d90-f8f90b7aad02*/, "Office Access 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1731. { { 0xcee5d470, 0x6e3b, 0x4fcc, { 0x8c, 0x2b, 0xd1, 0x74, 0x28, 0x56, 0x8a, 0x9f, } } /*cee5d470-6e3b-4fcc-8c2b-d17428568a9f*/, "Office Excel 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1732. { { 0x8947d0b8, 0xc33b, 0x43e1, { 0x8c, 0x56, 0x9b, 0x67, 0x4c, 0x05, 0x28, 0x32, } } /*8947d0b8-c33b-43e1-8c56-9b674c052832*/, "Office Groove 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1733. { { 0xca6b6639, 0x4ad6, 0x40ae, { 0xa5, 0x75, 0x14, 0xde, 0xe0, 0x7f, 0x64, 0x30, } } /*ca6b6639-4ad6-40ae-a575-14dee07f6430*/, "Office InfoPath 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1734. { { 0x09ed9640, 0xf020, 0x400a, { 0xac, 0xd8, 0xd7, 0xd8, 0x67, 0xdf, 0xd9, 0xc2, } } /*09ed9640-f020-400a-acd8-d7d867dfd9c2*/, "Office Mondo 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1735. { { 0xef3d4e49, 0xa53d, 0x4d81, { 0xa2, 0xb1, 0x2c, 0xa6, 0xc2, 0x55, 0x6b, 0x2c, } } /*ef3d4e49-a53d-4d81-a2b1-2ca6c2556b2c*/, "Office Mondo 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1736. { { 0xab586f5c, 0x5256, 0x4632, { 0x96, 0x2f, 0xfe, 0xfd, 0x8b, 0x49, 0xe6, 0xf4, } } /*ab586f5c-5256-4632-962f-fefd8b49e6f4*/, "Office OneNote 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1737. { { 0xecb7c192, 0x73ab, 0x4ded, { 0xac, 0xf4, 0x23, 0x99, 0xb0, 0x95, 0xd0, 0xcc, } } /*ecb7c192-73ab-4ded-acf4-2399b095d0cc*/, "Office OutLook 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1738. { { 0x45593b1d, 0xdfb1, 0x4e91, { 0xbb, 0xfb, 0x2d, 0x5d, 0x0c, 0xe2, 0x22, 0x7a, } } /*45593b1d-dfb1-4e91-bbfb-2d5d0ce2227a*/, "Office PowerPoint 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1739. { { 0xdf133ff7, 0xbf14, 0x4f95, { 0xaf, 0xe3, 0x7b, 0x48, 0xe7, 0xe3, 0x31, 0xef, } } /*df133ff7-bf14-4f95-afe3-7b48e7e331ef*/, "Office Project Pro 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1740. { { 0x5dc7bf61, 0x5ec9, 0x4996, { 0x9c, 0xcb, 0xdf, 0x80, 0x6a, 0x2d, 0x0e, 0xfe, } } /*5dc7bf61-5ec9-4996-9ccb-df806a2d0efe*/, "Office Project Standard 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1741. { { 0xb50c4f75, 0x599b, 0x43e8, { 0x8d, 0xcd, 0x10, 0x81, 0xa7, 0x96, 0x72, 0x41, } } /*b50c4f75-599b-43e8-8dcd-1081a7967241*/, "Office Publisher 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1742. { { 0x92236105, 0xbb67, 0x494f, { 0x94, 0xc7, 0x7f, 0x7a, 0x60, 0x79, 0x29, 0xbd, } } /*92236105-bb67-494f-94c7-7f7a607929bd*/, "Office Visio Premium 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1743. { { 0xe558389c, 0x83c3, 0x4b29, { 0xad, 0xfe, 0x5e, 0x4d, 0x7f, 0x46, 0xc3, 0x58, } } /*e558389c-83c3-4b29-adfe-5e4d7f46c358*/, "Office Visio Pro 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1744. { { 0x9ed833ff, 0x4f92, 0x4f36, { 0xb3, 0x70, 0x86, 0x83, 0xa4, 0xf1, 0x32, 0x75, } } /*9ed833ff-4f92-4f36-b370-8683a4f13275*/, "Office Visio Standard 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1745. { { 0x2d0882e7, 0xa4e7, 0x423b, { 0x8c, 0xcc, 0x70, 0xd9, 0x1e, 0x01, 0x58, 0xb1, } } /*2d0882e7-a4e7-423b-8ccc-70d91e0158b1*/, "Office Word 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1746. { { 0x6f327760, 0x8c5c, 0x417c, { 0x9b, 0x61, 0x83, 0x6a, 0x98, 0x28, 0x7e, 0x0c, } } /*6f327760-8c5c-417c-9b61-836a98287e0c*/, "Office Professional Plus 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1747. { { 0x9da2a678, 0xfb6b, 0x4e67, { 0xab, 0x84, 0x60, 0xdd, 0x6a, 0x9c, 0x81, 0x9a, } } /*9da2a678-fb6b-4e67-ab84-60dd6a9c819a*/, "Office Standard 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1748. { { 0xea509e87, 0x07a1, 0x4a45, { 0x9e, 0xdc, 0xeb, 0xa5, 0xa3, 0x9f, 0x36, 0xaf, } } /*ea509e87-07a1-4a45-9edc-eba5a39f36af*/, "Office Small Business Basics 2010", EPID_OFFICE2010, APP_ID_OFFICE2010, KMS_ID_OFFICE2010 },
  1749. // Office 2013
  1750. { { 0x6ee7622c, 0x18d8, 0x4005, { 0x9f, 0xb7, 0x92, 0xdb, 0x64, 0x4a, 0x27, 0x9b, } } /*6ee7622c-18d8-4005-9fb7-92db644a279b*/, "Office Access 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1751. { { 0xf7461d52, 0x7c2b, 0x43b2, { 0x87, 0x44, 0xea, 0x95, 0x8e, 0x0b, 0xd0, 0x9a, } } /*f7461d52-7c2b-43b2-8744-ea958e0bd09a*/, "Office Excel 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1752. { { 0xa30b8040, 0xd68a, 0x423f, { 0xb0, 0xb5, 0x9c, 0xe2, 0x92, 0xea, 0x5a, 0x8f, } } /*a30b8040-d68a-423f-b0b5-9ce292ea5a8f*/, "Office InfoPath 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1753. { { 0x1b9f11e3, 0xc85c, 0x4e1b, { 0xbb, 0x29, 0x87, 0x9a, 0xd2, 0xc9, 0x09, 0xe3, } } /*1b9f11e3-c85c-4e1b-bb29-879ad2c909e3*/, "Office Lync 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1754. { { 0xdc981c6b, 0xfc8e, 0x420f, { 0xaa, 0x43, 0xf8, 0xf3, 0x3e, 0x5c, 0x09, 0x23, } } /*dc981c6b-fc8e-420f-aa43-f8f33e5c0923*/, "Office Mondo 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1755. { { 0xefe1f3e6, 0xaea2, 0x4144, { 0xa2, 0x08, 0x32, 0xaa, 0x87, 0x2b, 0x65, 0x45, } } /*efe1f3e6-aea2-4144-a208-32aa872b6545*/, "Office OneNote 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1756. { { 0x771c3afa, 0x50c5, 0x443f, { 0xb1, 0x51, 0xff, 0x25, 0x46, 0xd8, 0x63, 0xa0, } } /*771c3afa-50c5-443f-b151-ff2546d863a0*/, "Office OutLook 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1757. { { 0x8c762649, 0x97d1, 0x4953, { 0xad, 0x27, 0xb7, 0xe2, 0xc2, 0x5b, 0x97, 0x2e, } } /*8c762649-97d1-4953-ad27-b7e2c25b972e*/, "Office PowerPoint 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1758. { { 0x4a5d124a, 0xe620, 0x44ba, { 0xb6, 0xff, 0x65, 0x89, 0x61, 0xb3, 0x3b, 0x9a, } } /*4a5d124a-e620-44ba-b6ff-658961b33b9a*/, "Office Project Pro 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1759. { { 0x427a28d1, 0xd17c, 0x4abf, { 0xb7, 0x17, 0x32, 0xc7, 0x80, 0xba, 0x6f, 0x07, } } /*427a28d1-d17c-4abf-b717-32c780ba6f07*/, "Office Project Standard 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1760. { { 0x00c79ff1, 0x6850, 0x443d, { 0xbf, 0x61, 0x71, 0xcd, 0xe0, 0xde, 0x30, 0x5f, } } /*00c79ff1-6850-443d-bf61-71cde0de305f*/, "Office Publisher 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1761. { { 0xac4efaf0, 0xf81f, 0x4f61, { 0xbd, 0xf7, 0xea, 0x32, 0xb0, 0x2a, 0xb1, 0x17, } } /*ac4efaf0-f81f-4f61-bdf7-ea32b02ab117*/, "Office Visio Standard 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1762. { { 0xe13ac10e, 0x75d0, 0x4aff, { 0xa0, 0xcd, 0x76, 0x49, 0x82, 0xcf, 0x54, 0x1c, } } /*e13ac10e-75d0-4aff-a0cd-764982cf541c*/, "Office Visio Pro 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1763. { { 0xd9f5b1c6, 0x5386, 0x495a, { 0x88, 0xf9, 0x9a, 0xd6, 0xb4, 0x1a, 0xc9, 0xb3, } } /*d9f5b1c6-5386-495a-88f9-9ad6b41ac9b3*/, "Office Word 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1764. { { 0xb322da9c, 0xa2e2, 0x4058, { 0x9e, 0x4e, 0xf5, 0x9a, 0x69, 0x70, 0xbd, 0x69, } } /*b322da9c-a2e2-4058-9e4e-f59a6970bd69*/, "Office Professional Plus 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1765. { { 0xb13afb38, 0xcd79, 0x4ae5, { 0x9f, 0x7f, 0xee, 0xd0, 0x58, 0xd7, 0x50, 0xca, } } /*b13afb38-cd79-4ae5-9f7f-eed058d750ca*/, "Office Standard 2013", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2013 },
  1766. // Office 2016
  1767. { { 0xd450596f, 0x894d, 0x49e0, { 0x96, 0x6a, 0xfd, 0x39, 0xed, 0x4c, 0x4c, 0x64, } } /*d450596f-894d-49e0-966a-fd39ed4c4c64*/, "Office Professional Plus 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1768. { { 0x4f414197, 0x0fc2, 0x4c01, { 0xb6, 0x8a, 0x86, 0xcb, 0xb9, 0xac, 0x25, 0x4c, } } /*4f414197-0fc2-4c01-b68a-86cbb9ac254c*/, "Office Project Pro 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1769. { { 0x6bf301c1, 0xb94a, 0x43e9, { 0xba, 0x31, 0xd4, 0x94, 0x59, 0x8c, 0x47, 0xfb, } } /*6bf301c1-b94a-43e9-ba31-d494598c47fb*/, "Office Visio Pro 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1770. { { 0x041a06cb, 0xc5b8, 0x4772, { 0x80, 0x9f, 0x41, 0x6d, 0x03, 0xd1, 0x66, 0x54, } } /*041a06cb-c5b8-4772-809f-416d03d16654*/, "Office Publisher 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1771. { { 0x67c0fc0c, 0xdeba, 0x401b, { 0xbf, 0x8b, 0x9c, 0x8a, 0xd8, 0x39, 0x58, 0x04, } } /*67c0fc0c-deba-401b-bf8b-9c8ad8395804*/, "Office Access 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1772. { { 0x83e04ee1, 0xfa8d, 0x436d, { 0x89, 0x94, 0xd3, 0x1a, 0x86, 0x2c, 0xab, 0x77, } } /*83e04ee1-fa8d-436d-8994-d31a862cab77*/, "Office Skype for Business 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1773. { { 0x9caabccb, 0x61b1, 0x4b4b, { 0x8b, 0xec, 0xd1, 0x0a, 0x3c, 0x3a, 0xc2, 0xce, } } /*9caabccb-61b1-4b4b-8bec-d10a3c3ac2ce*/, "Office Mondo 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1774. { { 0xaa2a7821, 0x1827, 0x4c2c, { 0x8f, 0x1d, 0x45, 0x13, 0xa3, 0x4d, 0xda, 0x97, } } /*aa2a7821-1827-4c2c-8f1d-4513a34dda97*/, "Office Visio Standard 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1775. { { 0xbb11badf, 0xd8aa, 0x470e, { 0x93, 0x11, 0x20, 0xea, 0xf8, 0x0f, 0xe5, 0xcc, } } /*bb11badf-d8aa-470e-9311-20eaf80fe5cc*/, "Office Word 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1776. { { 0xc3e65d36, 0x141f, 0x4d2f, { 0xa3, 0x03, 0xa8, 0x42, 0xee, 0x75, 0x6a, 0x29, } } /*c3e65d36-141f-4d2f-a303-a842ee756a29*/, "Office Excel 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1777. { { 0xd70b1bba, 0xb893, 0x4544, { 0x96, 0xe2, 0xb7, 0xa3, 0x18, 0x09, 0x1c, 0x33, } } /*d70b1bba-b893-4544-96e2-b7a318091c33*/, "Office Powerpoint 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1778. { { 0xd8cace59, 0x33d2, 0x4ac7, { 0x9b, 0x1b, 0x9b, 0x72, 0x33, 0x9c, 0x51, 0xc8, } } /*d8cace59-33d2-4ac7-9b1b-9b72339c51c8*/, "Office OneNote 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1779. { { 0xda7ddabc, 0x3fbe, 0x4447, { 0x9e, 0x01, 0x6a, 0xb7, 0x44, 0x0b, 0x4c, 0xd4, } } /*da7ddabc-3fbe-4447-9e01-6ab7440b4cd4*/, "Office Project Standard 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1780. { { 0xdedfa23d, 0x6ed1, 0x45a6, { 0x85, 0xdc, 0x63, 0xca, 0xe0, 0x54, 0x6d, 0xe6, } } /*dedfa23d-6ed1-45a6-85dc-63cae0546de6*/, "Office Standard 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1781. { { 0xe914ea6e, 0xa5fa, 0x4439, { 0xa3, 0x94, 0xa9, 0xbb, 0x32, 0x93, 0xca, 0x09, } } /*e914ea6e-a5fa-4439-a394-a9bb3293ca09*/, "Office Mondo R 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1782. { { 0xec9d9265, 0x9d1e, 0x4ed0, { 0x83, 0x8a, 0xcd, 0xc2, 0x0f, 0x25, 0x51, 0xa1, } } /*ec9d9265-9d1e-4ed0-838a-cdc20f2551a1*/, "Office Outlook 2016", EPID_OFFICE2013, APP_ID_OFFICE2013, KMS_ID_OFFICE2016 },
  1783. // End marker (necessity should be removed when time permits)
  1784. { { 0x00000000, 0x0000, 0x0000, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }, NULL, NULL, 0, 0 }
  1785. };
  1786. // necessary because other .c files cannot access _countof()
  1787. __pure ProdListIndex_t getExtendedProductListSize(void)
  1788. {
  1789. return _countof(ExtendedProductList) - 1;
  1790. }
  1791. __pure ProdListIndex_t getAppListSize(void)
  1792. {
  1793. return _countof(AppList);
  1794. }
  1795. #endif
  1796. #ifndef NO_RANDOM_EPID
  1797. // HostType and OSBuild
  1798. static const struct KMSHostOS { uint16_t Type; uint16_t Build; } HostOS[] =
  1799. {
  1800. { 55041, 6002 }, // Windows Server 2008 SP2
  1801. { 55041, 7601 }, // Windows Server 2008 R2 SP1
  1802. { 5426, 9200 }, // Windows Server 2012
  1803. { 6401, 9600 }, // Windows Server 2012 R2
  1804. { 3612, 10240}, // Windows Server 2016
  1805. };
  1806. // GroupID and PIDRange
  1807. static const struct PKEYCONFIG { uint16_t GroupID; uint32_t RangeMin; uint32_t RangeMax; } pkeyconfig[] = {
  1808. { 206, 152000000, 191999999 }, // Windows Server 2012 KMS Host pkeyconfig
  1809. { 206, 271000000, 310999999 }, // Windows Server 2012 R2 KMS Host pkeyconfig
  1810. { 96, 199000000, 217999999 }, // Office2010 KMS Host pkeyconfig
  1811. { 206, 234000000, 255999999 }, // Office2013 KMS Host pkeyconfig
  1812. };
  1813. // Valid language identifiers to be used in the ePID
  1814. static const uint16_t LcidList[] = {
  1815. 1078, 1052, 1025, 2049, 3073, 4097, 5121, 6145, 7169, 8193, 9217, 10241, 11265, 12289, 13313, 14337, 15361, 16385,
  1816. 1067, 1068, 2092, 1069, 1059, 1093, 5146, 1026, 1027, 1028, 2052, 3076, 4100, 5124, 1050, 4122, 1029, 1030, 1125, 1043, 2067,
  1817. 1033, 2057, 3081, 4105, 5129, 6153, 7177, 8201, 9225, 10249, 11273, 12297, 13321, 1061, 1080, 1065, 1035, 1036, 2060,
  1818. 3084, 4108, 5132, 6156, 1079, 1110, 1031, 2055, 3079, 4103, 5127, 1032, 1095, 1037, 1081, 1038, 1039, 1057, 1040, 2064, 1041, 1099,
  1819. 1087, 1111, 1042, 1088, 1062, 1063, 1071, 1086, 2110, 1100, 1082, 1153, 1102, 1104, 1044, 2068, 1045, 1046, 2070,
  1820. 1094, 1131, 2155, 3179, 1048, 1049, 9275, 4155, 5179, 3131, 1083, 2107, 8251, 6203, 7227, 1103, 2074, 6170, 3098,
  1821. 7194, 1051, 1060, 1034, 2058, 3082, 4106, 5130, 6154, 7178, 8202, 9226, 10250, 11274, 12298, 13322, 14346, 15370, 16394,
  1822. 17418, 18442, 19466, 20490, 1089, 1053, 2077, 1114, 1097, 1092, 1098, 1054, 1074, 1058, 1056, 1091, 2115, 1066, 1106, 1076, 1077
  1823. };
  1824. #ifdef _PEDANTIC
  1825. uint16_t IsValidLcid(const uint16_t Lcid)
  1826. {
  1827. uint16_t i;
  1828. for (i = 0; i < _countof(LcidList); i++)
  1829. {
  1830. if (Lcid == LcidList[i]) return Lcid;
  1831. }
  1832. return 0;
  1833. }
  1834. #endif // _PEDANTIC
  1835. #endif // NO_RANDOM_EPID
  1836. // Unix time is seconds from 1970-01-01. Should be 64 bits to avoid Year 2035 overflow bug.
  1837. // FILETIME is 100 nanoseconds from 1601-01-01. Must be 64 bits.
  1838. void getUnixTimeAsFileTime(FILETIME *const ts)
  1839. {
  1840. int64_t unixtime = (int64_t)time(NULL);
  1841. int64_t *filetime = (int64_t*)ts;
  1842. *filetime = LE64( (unixtime + 11644473600LL) * 10000000LL );
  1843. }
  1844. __pure int64_t fileTimeToUnixTime(const FILETIME *const ts)
  1845. {
  1846. return LE64( *((const int64_t *const)ts) ) / 10000000LL - 11644473600LL;
  1847. }
  1848. /*
  1849. * Get's a product name with a GUID in host-endian order.
  1850. * List can be any list defined above.
  1851. */
  1852. const char* getProductNameHE(const GUID *const guid, const KmsIdList *const List, ProdListIndex_t *const i)
  1853. {
  1854. for (*i = 0; List[*i].name != NULL; (*i)++)
  1855. {
  1856. if (IsEqualGUID(guid, &List[*i].guid))
  1857. return List[*i].name;
  1858. }
  1859. return "Unknown";
  1860. }
  1861. /*
  1862. * same as getProductnameHE except GUID is in little-endian (network) order
  1863. */
  1864. const char* getProductNameLE(const GUID *const guid, const KmsIdList *const List, ProdListIndex_t *const i)
  1865. {
  1866. #if __BYTE_ORDER != __LITTLE_ENDIAN
  1867. GUID HeGUID;
  1868. LEGUID(&HeGUID, guid);
  1869. return getProductNameHE(&HeGUID, List, i);
  1870. #else
  1871. return getProductNameHE(guid, List, i);
  1872. #endif
  1873. }
  1874. #ifndef NO_RANDOM_EPID
  1875. // formats an int with a fixed number of digits with leading zeros (helper for ePID generation)
  1876. static char* itoc(char *const c, const int i, uint_fast8_t digits)
  1877. {
  1878. char formatString[8];
  1879. if (digits > 9) digits = 0;
  1880. strcpy(formatString,"%");
  1881. if (digits)
  1882. {
  1883. formatString[1] = '0';
  1884. formatString[2] = digits | 0x30;
  1885. formatString[3] = 0;
  1886. }
  1887. strcat(formatString, "u");
  1888. sprintf(c, formatString, i);
  1889. return c;
  1890. }
  1891. static int getRandomServerType()
  1892. {
  1893. # ifndef USE_MSRPC
  1894. if (!UseRpcBTFN)
  1895. # endif // USE_MSRPC
  1896. {
  1897. // This isn't possible at all, e.g. KMS host on XP
  1898. return rand() % (int)_countof(HostOS);
  1899. }
  1900. # ifndef USE_MSRPC
  1901. else
  1902. {
  1903. // return 9200/9600/10240 if NDR64 is in use, otherwise 6002/7601
  1904. if (UseRpcNDR64) return (rand() % 3) + 2;
  1905. return (rand() % 2);
  1906. }
  1907. # endif // USE_MSRPC
  1908. }
  1909. /*
  1910. * Generates a random ePID
  1911. */
  1912. static void generateRandomPid(const int index, char *const szPid, int serverType, int16_t lang)
  1913. {
  1914. int clientApp;
  1915. char numberBuffer[12];
  1916. if (serverType < 0 || serverType >= (int)_countof(HostOS))
  1917. {
  1918. serverType = getRandomServerType();
  1919. }
  1920. strcpy(szPid, itoc(numberBuffer, HostOS[serverType].Type, 5));
  1921. strcat(szPid, "-");
  1922. if (index == 2)
  1923. clientApp = 3;
  1924. else if (index == 1)
  1925. clientApp = 2;
  1926. else
  1927. clientApp = serverType == 3 /*change if HostOS changes*/ ? 1 : 0;
  1928. strcat(szPid, itoc(numberBuffer, pkeyconfig[clientApp].GroupID, 5));
  1929. strcat(szPid, "-");
  1930. int keyId = (rand32() % (pkeyconfig[clientApp].RangeMax - pkeyconfig[clientApp].RangeMin)) + pkeyconfig[clientApp].RangeMin;
  1931. strcat(szPid, itoc(numberBuffer, keyId / 1000000, 3));
  1932. strcat(szPid, "-");
  1933. strcat(szPid, itoc(numberBuffer, keyId % 1000000, 6));
  1934. strcat(szPid, "-03-");
  1935. if (lang < 0) lang = LcidList[rand() % _countof(LcidList)];
  1936. strcat(szPid, itoc(numberBuffer, lang, 0));
  1937. strcat(szPid, "-");
  1938. strcat(szPid, itoc(numberBuffer, HostOS[serverType].Build, 0));
  1939. strcat(szPid, ".0000-");
  1940. # define minTime ((time_t)1436958000) // Release Date Windows 10 RTM Escrow
  1941. time_t maxTime, kmsTime;
  1942. time(&maxTime);
  1943. if (maxTime < minTime) // Just in case the system time is < 07/15/2015 1:00 pm
  1944. maxTime = (time_t)BUILD_TIME;
  1945. kmsTime = (rand32() % (maxTime - minTime)) + minTime;
  1946. # undef minTime
  1947. struct tm *pidTime;
  1948. pidTime = gmtime(&kmsTime);
  1949. strcat(szPid, itoc(numberBuffer, pidTime->tm_yday, 3));
  1950. strcat(szPid, itoc(numberBuffer, pidTime->tm_year + 1900, 4));
  1951. }
  1952. /*
  1953. * Generates random ePIDs and stores them if not already read from ini file.
  1954. * For use with randomization level 1
  1955. */
  1956. void randomPidInit()
  1957. {
  1958. ProdListIndex_t i;
  1959. int serverType = getRandomServerType();
  1960. int16_t lang = Lcid ? Lcid : LcidList[rand() % _countof(LcidList)];
  1961. for (i = 0; i < _countof(AppList) - 1; i++)
  1962. {
  1963. if (KmsResponseParameters[i].Epid) continue;
  1964. char Epid[PID_BUFFER_SIZE];
  1965. generateRandomPid(i, Epid, serverType, lang);
  1966. KmsResponseParameters[i].Epid = (const char*)vlmcsd_malloc(strlen(Epid) + 1);
  1967. strcpy((char*)KmsResponseParameters[i].Epid, Epid);
  1968. #ifndef NO_LOG
  1969. KmsResponseParameters[i].EpidSource = "randomized at program start";
  1970. #endif // NO_LOG
  1971. }
  1972. }
  1973. #endif // NO_RANDOM_EPID
  1974. #ifndef NO_LOG
  1975. /*
  1976. * Logs a Request
  1977. */
  1978. static void logRequest(const REQUEST *const baseRequest)
  1979. {
  1980. const char *productName;
  1981. char clientname[64];
  1982. ProdListIndex_t index;
  1983. #ifndef NO_EXTENDED_PRODUCT_LIST
  1984. productName = getProductNameLE(&baseRequest->ActID, ExtendedProductList, &index);
  1985. if (++index >= (int)_countof(ExtendedProductList))
  1986. #endif // NO_EXTENDED_PRODUCT_LIST
  1987. {
  1988. #ifndef NO_BASIC_PRODUCT_LIST
  1989. productName = getProductNameLE(&baseRequest->KMSID, ProductList, &index);
  1990. if (++index >= (int)_countof(ProductList))
  1991. #endif // NO_BASIC_PRODUCT_LIST
  1992. {
  1993. productName = getProductNameLE(&baseRequest->AppID, AppList, &index);
  1994. }
  1995. }
  1996. #ifndef NO_VERBOSE_LOG
  1997. if (logverbose)
  1998. {
  1999. logger("<<< Incoming KMS request\n");
  2000. logRequestVerbose(baseRequest, &logger);
  2001. }
  2002. else
  2003. {
  2004. #endif // NO_VERBOSE_LOG
  2005. ucs2_to_utf8(baseRequest->WorkstationName, clientname, 64, 64);
  2006. logger("KMS v%i.%i request from %s for %s\n", LE16(baseRequest->MajorVer), LE16(baseRequest->MinorVer), clientname, productName);
  2007. #ifndef NO_VERBOSE_LOG
  2008. }
  2009. #endif // NO_VERBOSE_LOG
  2010. }
  2011. #endif // NO_LOG
  2012. /*
  2013. * Converts a utf-8 ePID string to UCS-2 and writes it to a RESPONSE struct
  2014. */
  2015. static void getEpidFromString(RESPONSE *const Response, const char *const pid)
  2016. {
  2017. size_t length = utf8_to_ucs2(Response->KmsPID, pid, PID_BUFFER_SIZE, PID_BUFFER_SIZE * 3);
  2018. Response->PIDSize = LE32(((unsigned int )length + 1) << 1);
  2019. }
  2020. /*
  2021. * get ePID from appropriate source
  2022. */
  2023. static void getEpid(RESPONSE *const baseResponse, const char** EpidSource, const ProdListIndex_t index, BYTE *const HwId)
  2024. {
  2025. const char* pid;
  2026. if (KmsResponseParameters[index].Epid == NULL)
  2027. {
  2028. #ifndef NO_RANDOM_EPID
  2029. if (RandomizationLevel == 2)
  2030. {
  2031. char szPid[PID_BUFFER_SIZE];
  2032. generateRandomPid(index, szPid, -1, Lcid ? Lcid : -1);
  2033. pid = szPid;
  2034. #ifndef NO_LOG
  2035. *EpidSource = "randomized on every request";
  2036. #endif // NO_LOG
  2037. }
  2038. else
  2039. #endif // NO_RANDOM_EPID
  2040. {
  2041. pid = AppList[index].pid;
  2042. #ifndef NO_LOG
  2043. *EpidSource = "vlmcsd default";
  2044. #endif // NO_LOG
  2045. }
  2046. }
  2047. else
  2048. {
  2049. pid = KmsResponseParameters[index].Epid;
  2050. if (HwId && KmsResponseParameters[index].HwId != NULL)
  2051. memcpy(HwId, KmsResponseParameters[index].HwId, sizeof(((RESPONSE_V6 *)0)->HwId));
  2052. #ifndef NO_LOG
  2053. *EpidSource = KmsResponseParameters[index].EpidSource;
  2054. #endif // NO_LOG
  2055. }
  2056. getEpidFromString(baseResponse, pid);
  2057. }
  2058. #if !defined(NO_LOG) && defined(_PEDANTIC)
  2059. static BOOL CheckVersion4Uuid(const GUID *const guid, const char *const szGuidName)
  2060. {
  2061. if (LE16(guid->Data3) >> 12 != 4 || guid->Data4[0] >> 6 != 2)
  2062. {
  2063. logger("Warning: %s does not conform to version 4 UUID according to RFC 4122\n", szGuidName);
  2064. return FALSE;
  2065. }
  2066. return TRUE;
  2067. }
  2068. static void CheckRequest(const REQUEST *const Request)
  2069. {
  2070. CheckVersion4Uuid(&Request->CMID, "Client machine ID");
  2071. CheckVersion4Uuid(&Request->AppID, "Application ID");
  2072. CheckVersion4Uuid(&Request->KMSID, "Server SKU ID");
  2073. CheckVersion4Uuid(&Request->ActID, "Client SKU ID");
  2074. if (LE32(Request->IsClientVM) > 1)
  2075. logger("Warning: Virtual Machine field in request must be 0 or 1 but is %u\n", LE32(Request->IsClientVM));
  2076. if (LE32(Request->LicenseStatus) > 6 )
  2077. logger("Warning: License status must be between 0 and 6 but is %u\n", LE32(Request->LicenseStatus));
  2078. }
  2079. #endif // !defined(NO_LOG) && defined(_PEDANTIC)
  2080. #ifndef NO_LOG
  2081. /*
  2082. * Logs the Response
  2083. */
  2084. static void logResponse(const RESPONSE *const baseResponse, const BYTE *const hwId, const char *const EpidSource)
  2085. {
  2086. char utf8pid[PID_BUFFER_SIZE * 3];
  2087. ucs2_to_utf8(baseResponse->KmsPID, utf8pid, PID_BUFFER_SIZE, PID_BUFFER_SIZE * 3);
  2088. #ifndef NO_VERBOSE_LOG
  2089. if (!logverbose)
  2090. {
  2091. #endif // NO_VERBOSE_LOG
  2092. logger("Sending ePID (%s): %s\n", EpidSource, utf8pid);
  2093. #ifndef NO_VERBOSE_LOG
  2094. }
  2095. else
  2096. {
  2097. logger(">>> Sending response, ePID source = %s\n", EpidSource);
  2098. logResponseVerbose(utf8pid, hwId, baseResponse, &logger);
  2099. }
  2100. #endif // NO_VERBOSE_LOG
  2101. }
  2102. #endif
  2103. /*
  2104. * Creates the unencrypted base response
  2105. */
  2106. static BOOL __stdcall CreateResponseBaseCallback(const REQUEST *const baseRequest, RESPONSE *const baseResponse, BYTE *const hwId, const char* const ipstr)
  2107. {
  2108. const char* EpidSource;
  2109. #ifndef NO_LOG
  2110. logRequest(baseRequest);
  2111. #ifdef _PEDANTIC
  2112. CheckRequest(baseRequest);
  2113. #endif // _PEDANTIC
  2114. #endif // NO_LOG
  2115. ProdListIndex_t index;
  2116. getProductNameLE(&baseRequest->AppID, AppList, &index);
  2117. if (index >= _countof(AppList) - 1) index = 0; //default to Windows
  2118. getEpid(baseResponse, &EpidSource, index, hwId);
  2119. baseResponse->Version = baseRequest->Version;
  2120. memcpy(&baseResponse->CMID, &baseRequest->CMID, sizeof(GUID));
  2121. memcpy(&baseResponse->ClientTime, &baseRequest->ClientTime, sizeof(FILETIME));
  2122. baseResponse->Count = LE32(LE32(baseRequest->N_Policy) << 1);
  2123. baseResponse->VLActivationInterval = LE32(VLActivationInterval);
  2124. baseResponse->VLRenewalInterval = LE32(VLRenewalInterval);
  2125. #ifndef NO_LOG
  2126. logResponse(baseResponse, hwId, EpidSource);
  2127. #endif // NO_LOG
  2128. return !0;
  2129. }
  2130. RequestCallback_t CreateResponseBase = &CreateResponseBaseCallback;
  2131. ////TODO: Move to helpers.c
  2132. void get16RandomBytes(void* ptr)
  2133. {
  2134. int i;
  2135. for (i = 0; i < 4; i++) ((DWORD*)ptr)[i] = rand32();
  2136. }
  2137. /*
  2138. * Creates v4 response
  2139. */
  2140. size_t CreateResponseV4(REQUEST_V4 *const request_v4, BYTE *const responseBuffer, const char* const ipstr)
  2141. {
  2142. RESPONSE_V4* Response = (RESPONSE_V4*)responseBuffer;
  2143. if ( !CreateResponseBase(&request_v4->RequestBase, &Response->ResponseBase, NULL, ipstr) ) return 0;
  2144. DWORD pidSize = LE32(Response->ResponseBase.PIDSize);
  2145. BYTE* postEpidPtr = responseBuffer + V4_PRE_EPID_SIZE + pidSize;
  2146. memmove(postEpidPtr, &Response->ResponseBase.CMID, V4_POST_EPID_SIZE);
  2147. size_t encryptSize = V4_PRE_EPID_SIZE + V4_POST_EPID_SIZE + pidSize;
  2148. AesCmacV4(responseBuffer, encryptSize, responseBuffer + encryptSize);
  2149. return encryptSize + sizeof(Response->MAC);
  2150. }
  2151. /*
  2152. // Workaround for buggy GCC 4.2/4.3
  2153. #if defined(__GNUC__) && (__GNUC__ == 4 && __GNUC_MINOR__ < 4)
  2154. __attribute__((noinline))
  2155. #endif
  2156. __pure static uint64_t TimestampInterval(void *ts)
  2157. {
  2158. return ( GET_UA64LE(ts) / TIME_C1 ) * TIME_C2 + TIME_C3;
  2159. }*/
  2160. /*
  2161. * Creates the HMAC for v6
  2162. */
  2163. static int_fast8_t CreateV6Hmac(BYTE *const encrypt_start, const size_t encryptSize, int_fast8_t tolerance)
  2164. {
  2165. BYTE hash[32];
  2166. # define halfHashSize (sizeof(hash) >> 1)
  2167. uint64_t timeSlot;
  2168. BYTE *responseEnd = encrypt_start + encryptSize;
  2169. // This is the time from the response
  2170. FILETIME* ft = (FILETIME*)(responseEnd - V6_POST_EPID_SIZE + sizeof(((RESPONSE*)0)->CMID));
  2171. // Generate a time slot that changes every 4.11 hours.
  2172. // Request and repsonse time must match +/- 1 slot.
  2173. // When generating a response tolerance must be 0.
  2174. // If verifying the hash, try tolerance -1, 0 and +1. One of them must match.
  2175. timeSlot = LE64( (GET_UA64LE(ft) / TIME_C1 * TIME_C2 + TIME_C3) + (tolerance * TIME_C1) );
  2176. // The time slot is hashed with SHA256 so it is not so obvious that it is time
  2177. Sha256((BYTE*) &timeSlot, sizeof(timeSlot), hash);
  2178. // The last 16 bytes of the hashed time slot are the actual HMAC key
  2179. if (!Sha256Hmac
  2180. (
  2181. hash + halfHashSize, // Use last 16 bytes of SHA256 as HMAC key
  2182. encrypt_start, // hash only the encrypted part of the v6 response
  2183. encryptSize - sizeof(((RESPONSE_V6*)0)->HMAC), // encryptSize minus the HMAC itself
  2184. hash // use same buffer for resulting hash where the key came from
  2185. ))
  2186. {
  2187. return FALSE;
  2188. }
  2189. memcpy(responseEnd - sizeof(((RESPONSE_V6*)0)->HMAC), hash + halfHashSize, halfHashSize);
  2190. return TRUE;
  2191. # undef halfHashSize
  2192. }
  2193. /*
  2194. * Creates v5 or v6 response
  2195. */
  2196. size_t CreateResponseV6(REQUEST_V6 *restrict request_v6, BYTE *const responseBuffer, const char* const ipstr)
  2197. {
  2198. // The response will be created in a fixed sized struct to
  2199. // avoid unaligned access macros and packed structs on RISC systems
  2200. // which largely increase code size.
  2201. //
  2202. // The fixed sized struct with 64 WCHARs for the ePID will be converted
  2203. // to a variable sized struct later and requires unaligned access macros.
  2204. RESPONSE_V6* Response = (RESPONSE_V6*)responseBuffer;
  2205. RESPONSE* baseResponse = &Response->ResponseBase;
  2206. #ifdef _DEBUG
  2207. RESPONSE_V6_DEBUG* xxx = (RESPONSE_V6_DEBUG*)responseBuffer;
  2208. #endif
  2209. static const BYTE DefaultHwid[8] = { HWID };
  2210. int_fast8_t v6 = LE16(request_v6->MajorVer) > 5;
  2211. AesCtx aesCtx;
  2212. AesInitKey(&aesCtx, v6 ? AesKeyV6 : AesKeyV5, v6, AES_KEY_BYTES);
  2213. AesDecryptCbc(&aesCtx, NULL, request_v6->IV, V6_DECRYPT_SIZE);
  2214. // get random salt and SHA256 it
  2215. get16RandomBytes(Response->RandomXoredIVs);
  2216. Sha256(Response->RandomXoredIVs, sizeof(Response->RandomXoredIVs), Response->Hash);
  2217. if (v6) // V6 specific stuff
  2218. {
  2219. // In v6 a random IV is generated
  2220. Response->Version = request_v6->Version;
  2221. get16RandomBytes(Response->IV);
  2222. // pre-fill with default HwId (not required for v5)
  2223. memcpy(Response->HwId, DefaultHwid, sizeof(Response->HwId));
  2224. // Just copy decrypted request IV (using Null IV) here. Note this is identical
  2225. // to XORing non-decrypted request and reponse IVs
  2226. memcpy(Response->XoredIVs, request_v6->IV, sizeof(Response->XoredIVs));
  2227. }
  2228. else // V5 specific stuff
  2229. {
  2230. // In v5 IVs of request and response must be identical (MS client checks this)
  2231. // The following memcpy copies Version and IVs at once
  2232. memcpy(Response, request_v6, V6_UNENCRYPTED_SIZE);
  2233. }
  2234. // Xor Random bytes with decrypted request IV
  2235. XorBlock(request_v6->IV, Response->RandomXoredIVs);
  2236. // Get the base response
  2237. if ( !CreateResponseBase(&request_v6->RequestBase, baseResponse, Response->HwId, ipstr) ) return 0;
  2238. // Convert the fixed sized struct into variable sized
  2239. DWORD pidSize = LE32(baseResponse->PIDSize);
  2240. BYTE* postEpidPtr = responseBuffer + V6_PRE_EPID_SIZE + pidSize;
  2241. size_t post_epid_size = v6 ? V6_POST_EPID_SIZE : V5_POST_EPID_SIZE;
  2242. memmove(postEpidPtr, &baseResponse->CMID, post_epid_size);
  2243. // number of bytes to encrypt
  2244. size_t encryptSize =
  2245. V6_PRE_EPID_SIZE
  2246. - sizeof(Response->Version)
  2247. + pidSize
  2248. + post_epid_size;
  2249. //AesDecryptBlock(&aesCtx, Response->IV);
  2250. if (v6 && !CreateV6Hmac(Response->IV, encryptSize, 0)) return 0;
  2251. // Padding auto handled by encryption func
  2252. AesEncryptCbc(&aesCtx, NULL, Response->IV, &encryptSize);
  2253. return encryptSize + sizeof(Response->Version);
  2254. }
  2255. // Create Hashed KMS Client Request Data for KMS Protocol Version 4
  2256. BYTE *CreateRequestV4(size_t *size, const REQUEST* requestBase)
  2257. {
  2258. *size = sizeof(REQUEST_V4);
  2259. // Build a proper KMS client request data
  2260. BYTE *request = (BYTE *)vlmcsd_malloc(sizeof(REQUEST_V4));
  2261. // Temporary Pointer for access to REQUEST_V4 structure
  2262. REQUEST_V4 *request_v4 = (REQUEST_V4 *)request;
  2263. // Set KMS Client Request Base
  2264. memcpy(&request_v4->RequestBase, requestBase, sizeof(REQUEST));
  2265. // Generate Hash Signature
  2266. AesCmacV4(request, sizeof(REQUEST), request_v4->MAC);
  2267. // Return Request Data
  2268. return request;
  2269. }
  2270. // Create Encrypted KMS Client Request Data for KMS Protocol Version 6
  2271. BYTE* CreateRequestV6(size_t *size, const REQUEST* requestBase)
  2272. {
  2273. *size = sizeof(REQUEST_V6);
  2274. // Temporary Pointer for access to REQUEST_V5 structure
  2275. REQUEST_V6 *request = (REQUEST_V6 *)vlmcsd_malloc(sizeof(REQUEST_V6));
  2276. // KMS Protocol Version
  2277. request->Version = requestBase->Version;
  2278. // Initialize the IV
  2279. get16RandomBytes(request->IV);
  2280. // Set KMS Client Request Base
  2281. memcpy(&request->RequestBase, requestBase, sizeof(REQUEST));
  2282. // Encrypt KMS Client Request
  2283. size_t encryptSize = sizeof(request->RequestBase);
  2284. AesCtx Ctx;
  2285. int_fast8_t v6 = LE16(request->MajorVer) > 5;
  2286. AesInitKey(&Ctx, v6 ? AesKeyV6 : AesKeyV5, v6, 16);
  2287. AesEncryptCbc(&Ctx, request->IV, (BYTE*)(&request->RequestBase), &encryptSize);
  2288. // Return Proper Request Data
  2289. return (BYTE*)request;
  2290. }
  2291. /*
  2292. * Checks whether Length of ePID is valid
  2293. */
  2294. static uint8_t checkPidLength(const RESPONSE *const responseBase)
  2295. {
  2296. unsigned int i;
  2297. if (LE32(responseBase->PIDSize) > (PID_BUFFER_SIZE << 1)) return FALSE;
  2298. if (responseBase->KmsPID[(LE32(responseBase->PIDSize) >> 1) - 1]) return FALSE;
  2299. for (i = 0; i < (LE32(responseBase->PIDSize) >> 1) - 2; i++)
  2300. {
  2301. if (!responseBase->KmsPID[i]) return FALSE;
  2302. }
  2303. return TRUE;
  2304. }
  2305. /*
  2306. * "Decrypts" a KMS v4 response. Actually just copies to a fixed size buffer
  2307. */
  2308. RESPONSE_RESULT DecryptResponseV4(RESPONSE_V4* response_v4, const int responseSize, BYTE* const rawResponse, const BYTE* const rawRequest)
  2309. {
  2310. int copySize =
  2311. V4_PRE_EPID_SIZE +
  2312. (LE32(((RESPONSE_V4*)rawResponse)->ResponseBase.PIDSize) <= PID_BUFFER_SIZE << 1 ?
  2313. LE32(((RESPONSE_V4*)rawResponse)->ResponseBase.PIDSize) :
  2314. PID_BUFFER_SIZE << 1);
  2315. int messageSize = copySize + V4_POST_EPID_SIZE;
  2316. memcpy(response_v4, rawResponse, copySize);
  2317. memcpy(&response_v4->ResponseBase.CMID, rawResponse + copySize, responseSize - copySize);
  2318. // ensure PID is null terminated
  2319. response_v4->ResponseBase.KmsPID[PID_BUFFER_SIZE-1] = 0;
  2320. uint8_t* mac = rawResponse + messageSize;
  2321. AesCmacV4(rawResponse, messageSize, mac);
  2322. REQUEST_V4* request_v4 = (REQUEST_V4*)rawRequest;
  2323. RESPONSE_RESULT result;
  2324. result.mask = (DWORD)~0;
  2325. result.PidLengthOK = checkPidLength((RESPONSE*)rawResponse);
  2326. result.VersionOK = response_v4->ResponseBase.Version == request_v4->RequestBase.Version;
  2327. result.HashOK = !memcmp(&response_v4->MAC, mac, sizeof(response_v4->MAC));
  2328. result.TimeStampOK = !memcmp(&response_v4->ResponseBase.ClientTime, &request_v4->RequestBase.ClientTime, sizeof(FILETIME));
  2329. result.ClientMachineIDOK = !memcmp(&response_v4->ResponseBase.CMID, &request_v4->RequestBase.CMID, sizeof(GUID));
  2330. result.effectiveResponseSize = responseSize;
  2331. result.correctResponseSize = sizeof(RESPONSE_V4) - sizeof(response_v4->ResponseBase.KmsPID) + LE32(response_v4->ResponseBase.PIDSize);
  2332. return result;
  2333. }
  2334. static RESPONSE_RESULT VerifyResponseV6(RESPONSE_RESULT result, const AesCtx* Ctx, RESPONSE_V6* response_v6, REQUEST_V6* request_v6, BYTE* const rawResponse)
  2335. {
  2336. // Check IVs
  2337. result.IVsOK = !memcmp // In V6 the XoredIV is actually the request IV
  2338. (
  2339. response_v6->XoredIVs,
  2340. request_v6->IV,
  2341. sizeof(response_v6->XoredIVs)
  2342. );
  2343. result.IVnotSuspicious = !!memcmp // If IVs are identical, it is obviously an emulator
  2344. (
  2345. request_v6->IV,
  2346. response_v6->IV,
  2347. sizeof(request_v6->IV)
  2348. );
  2349. // Check Hmac
  2350. int_fast8_t tolerance;
  2351. BYTE OldHmac[sizeof(response_v6->HMAC)];
  2352. result.HmacSha256OK = FALSE;
  2353. memcpy // Save received HMAC to compare with calculated HMAC later
  2354. (
  2355. OldHmac,
  2356. response_v6->HMAC,
  2357. sizeof(response_v6->HMAC)
  2358. );
  2359. //AesEncryptBlock(Ctx, Response_v6->IV); // CreateV6Hmac needs original IV as received over the network
  2360. for (tolerance = -1; tolerance < 2; tolerance++)
  2361. {
  2362. CreateV6Hmac
  2363. (
  2364. rawResponse + sizeof(response_v6->Version), // Pointer to start of the encrypted part of the response
  2365. (size_t)result.correctResponseSize - V6_UNENCRYPTED_SIZE, // size of the encrypted part
  2366. tolerance // tolerance -1, 0, or +1
  2367. );
  2368. if
  2369. ((
  2370. result.HmacSha256OK = !memcmp // Compare both HMACs
  2371. (
  2372. OldHmac,
  2373. rawResponse + (size_t)result.correctResponseSize - sizeof(response_v6->HMAC),
  2374. sizeof(OldHmac)
  2375. )
  2376. ))
  2377. {
  2378. break;
  2379. }
  2380. }
  2381. return result;
  2382. }
  2383. static RESPONSE_RESULT VerifyResponseV5(RESPONSE_RESULT result, REQUEST_V5* request_v5, RESPONSE_V5* response_v5)
  2384. {
  2385. // Check IVs: in V5 (and only v5) request and response IVs must match
  2386. result.IVsOK = !memcmp(request_v5->IV, response_v5->IV, sizeof(request_v5->IV));
  2387. // V5 has no Hmac, always set to TRUE
  2388. result.HmacSha256OK = TRUE;
  2389. return result;
  2390. }
  2391. /*
  2392. * Decrypts a KMS v5 or v6 response received from a server.
  2393. * hwid must supply a valid 16 byte buffer for v6. hwid is ignored in v5
  2394. */
  2395. RESPONSE_RESULT DecryptResponseV6(RESPONSE_V6* response_v6, int responseSize, BYTE* const response, const BYTE* const rawRequest, BYTE* hwid)
  2396. {
  2397. RESPONSE_RESULT result;
  2398. result.mask = ~0; // Set all bits in the results mask to 1. Assume success first.
  2399. result.effectiveResponseSize = responseSize;
  2400. int copySize1 =
  2401. sizeof(response_v6->Version);
  2402. // Decrypt KMS Server Response (encrypted part starts after RequestIV)
  2403. responseSize -= copySize1;
  2404. AesCtx Ctx;
  2405. int_fast8_t v6 = LE16(((RESPONSE_V6*)response)->MajorVer) > 5;
  2406. AesInitKey(&Ctx, v6 ? AesKeyV6 : AesKeyV5, v6, AES_KEY_BYTES);
  2407. AesDecryptCbc(&Ctx, NULL, response + copySize1, responseSize);
  2408. // Check padding
  2409. BYTE* lastPadByte = response + (size_t)result.effectiveResponseSize - 1;
  2410. // Must be from 1 to 16
  2411. if (!*lastPadByte || *lastPadByte > AES_BLOCK_BYTES)
  2412. {
  2413. result.DecryptSuccess = FALSE;
  2414. return result;
  2415. }
  2416. // Check if pad bytes are all the same
  2417. BYTE* padByte;
  2418. for (padByte = lastPadByte - *lastPadByte + 1; padByte < lastPadByte; padByte++)
  2419. if (*padByte != *lastPadByte)
  2420. {
  2421. result.DecryptSuccess = FALSE;
  2422. return result;
  2423. }
  2424. // Add size of Version, KmsPIDLen and variable size PID
  2425. DWORD pidSize = LE32(((RESPONSE_V6*) response)->ResponseBase.PIDSize);
  2426. copySize1 +=
  2427. V6_UNENCRYPTED_SIZE +
  2428. sizeof(response_v6->ResponseBase.PIDSize) +
  2429. (pidSize <= PID_BUFFER_SIZE << 1 ? pidSize : PID_BUFFER_SIZE << 1);
  2430. // Copy part 1 of response up to variable sized PID
  2431. memcpy(response_v6, response, copySize1);
  2432. // ensure PID is null terminated
  2433. response_v6->ResponseBase.KmsPID[PID_BUFFER_SIZE - 1] = 0;
  2434. // Copy part 2
  2435. size_t copySize2 = v6 ? V6_POST_EPID_SIZE : V5_POST_EPID_SIZE;
  2436. memcpy(&response_v6->ResponseBase.CMID, response + copySize1, copySize2);
  2437. // Decrypting the response is finished here. Now we check the results for validity
  2438. // A basic client doesn't need the stuff below this comment but we want to use vlmcs
  2439. // as a debug tool for KMS emulators.
  2440. REQUEST_V6* request_v6 = (REQUEST_V6*) rawRequest;
  2441. DWORD decryptSize = sizeof(request_v6->IV) + sizeof(request_v6->RequestBase) + sizeof(request_v6->Pad);
  2442. AesDecryptCbc(&Ctx, NULL, request_v6->IV, decryptSize);
  2443. // Check that all version informations are the same
  2444. result.VersionOK =
  2445. request_v6->Version == response_v6->ResponseBase.Version &&
  2446. request_v6->Version == response_v6->Version &&
  2447. request_v6->Version == request_v6->RequestBase.Version;
  2448. // Check Base Request
  2449. result.PidLengthOK = checkPidLength(&((RESPONSE_V6*) response)->ResponseBase);
  2450. result.TimeStampOK = !memcmp(&response_v6->ResponseBase.ClientTime, &request_v6->RequestBase.ClientTime, sizeof(FILETIME));
  2451. result.ClientMachineIDOK = IsEqualGUID(&response_v6->ResponseBase.CMID, &request_v6->RequestBase.CMID);
  2452. // Rebuild Random Key and Sha256 Hash
  2453. BYTE HashVerify[sizeof(response_v6->Hash)];
  2454. BYTE RandomKey[sizeof(response_v6->RandomXoredIVs)];
  2455. memcpy(RandomKey, request_v6->IV, sizeof(RandomKey));
  2456. XorBlock(response_v6->RandomXoredIVs, RandomKey);
  2457. Sha256(RandomKey, sizeof(RandomKey), HashVerify);
  2458. result.HashOK = !memcmp(response_v6->Hash, HashVerify, sizeof(HashVerify));
  2459. // size before encryption (padding not included)
  2460. result.correctResponseSize =
  2461. (v6 ? sizeof(RESPONSE_V6) : sizeof(RESPONSE_V5))
  2462. - sizeof(response_v6->ResponseBase.KmsPID)
  2463. + LE32(response_v6->ResponseBase.PIDSize);
  2464. // Version specific stuff
  2465. if (v6)
  2466. {
  2467. // Copy the HwId
  2468. memcpy(hwid, response_v6->HwId, sizeof(response_v6->HwId));
  2469. // Verify the V6 specific part of the response
  2470. result = VerifyResponseV6(result, &Ctx, response_v6, request_v6, response);
  2471. }
  2472. else // V5
  2473. {
  2474. // Verify the V5 specific part of the response
  2475. result = VerifyResponseV5(result, request_v6, (RESPONSE_V5*)response_v6);
  2476. }
  2477. // padded size after encryption
  2478. result.correctResponseSize += (~(result.correctResponseSize - sizeof(response_v6->ResponseBase.Version)) & 0xf) + 1;
  2479. return result;
  2480. }
  2481. #ifndef CONFIG
  2482. #define CONFIG "config.h"
  2483. #endif // CONFIG
  2484. #include CONFIG
  2485. #include "endian.h"
  2486. #if defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && defined(__LITTLE_ENDIAN) \
  2487. && defined(BS16) && defined(BS32) && defined(BS64)
  2488. #else // ! defined(__BYTE_ORDER)
  2489. void PUT_UAA64BE(void *p, unsigned long long v, unsigned int i)
  2490. {
  2491. unsigned char *_p = (unsigned char *)&((unsigned long long *)p)[i];
  2492. _p[ 0 ] = v >> 56;
  2493. _p[ 1 ] = v >> 48;
  2494. _p[ 2 ] = v >> 40;
  2495. _p[ 3 ] = v >> 32;
  2496. _p[ 4 ] = v >> 24;
  2497. _p[ 5 ] = v >> 16;
  2498. _p[ 6 ] = v >> 8;
  2499. _p[ 7 ] = v;
  2500. }
  2501. void PUT_UAA32BE(void *p, unsigned int v, unsigned int i)
  2502. {
  2503. unsigned char *_p = (unsigned char *)&((unsigned int *)p)[i];
  2504. _p[ 0 ] = v >> 24;
  2505. _p[ 1 ] = v >> 16;
  2506. _p[ 2 ] = v >> 8;
  2507. _p[ 3 ] = v;
  2508. }
  2509. void PUT_UAA16BE(void *p, unsigned short v, unsigned int i)
  2510. {
  2511. unsigned char *_p = (unsigned char *)&((unsigned short *)p)[i];
  2512. _p[ 0 ] = v >> 8;
  2513. _p[ 1 ] = v;
  2514. }
  2515. void PUT_UAA64LE(void *p, unsigned long long v, unsigned int i)
  2516. {
  2517. unsigned char *_p = (unsigned char *)&((unsigned long long *)p)[i];
  2518. _p[ 0 ] = v;
  2519. _p[ 1 ] = v >> 8;
  2520. _p[ 2 ] = v >> 16;
  2521. _p[ 3 ] = v >> 24;
  2522. _p[ 4 ] = v >> 32;
  2523. _p[ 5 ] = v >> 40;
  2524. _p[ 6 ] = v >> 48;
  2525. _p[ 7 ] = v >> 56;
  2526. }
  2527. void PUT_UAA32LE(void *p, unsigned int v, unsigned int i)
  2528. {
  2529. unsigned char *_p = (unsigned char *)&((unsigned int *)p)[i];
  2530. _p[ 0 ] = v;
  2531. _p[ 1 ] = v >> 8;
  2532. _p[ 2 ] = v >> 16;
  2533. _p[ 3 ] = v >> 24;
  2534. }
  2535. void PUT_UAA16LE(void *p, unsigned short v, unsigned int i)
  2536. {
  2537. unsigned char *_p = (unsigned char *)&((unsigned short *)p)[i];
  2538. _p[ 0 ] = v;
  2539. _p[ 1 ] = v >> 8;
  2540. }
  2541. unsigned long long GET_UAA64BE(void *p, unsigned int i)
  2542. {
  2543. unsigned char *_p = (unsigned char *)&((unsigned long long *)p)[i];
  2544. return
  2545. (unsigned long long)_p[ 0 ] << 56 |
  2546. (unsigned long long)_p[ 1 ] << 48 |
  2547. (unsigned long long)_p[ 2 ] << 40 |
  2548. (unsigned long long)_p[ 3 ] << 32 |
  2549. (unsigned long long)_p[ 4 ] << 24 |
  2550. (unsigned long long)_p[ 5 ] << 16 |
  2551. (unsigned long long)_p[ 6 ] << 8 |
  2552. (unsigned long long)_p[ 7 ];
  2553. }
  2554. unsigned int GET_UAA32BE(void *p, unsigned int i)
  2555. {
  2556. unsigned char *_p = (unsigned char *)&((unsigned int *)p)[i];
  2557. return
  2558. (unsigned int)_p[ 0 ] << 24 |
  2559. (unsigned int)_p[ 1 ] << 16 |
  2560. (unsigned int)_p[ 2 ] << 8 |
  2561. (unsigned int)_p[ 3 ];
  2562. }
  2563. unsigned short GET_UAA16BE(void *p, unsigned int i)
  2564. {
  2565. unsigned char *_p = (unsigned char *)&((unsigned short *)p)[i];
  2566. return
  2567. (unsigned short)_p[ 0 ] << 8 |
  2568. (unsigned short)_p[ 1 ];
  2569. }
  2570. unsigned long long GET_UAA64LE(void *p, unsigned int i)
  2571. {
  2572. unsigned char *_p = (unsigned char *)&((unsigned long long *)p)[i];
  2573. return
  2574. (unsigned long long)_p[ 0 ] |
  2575. (unsigned long long)_p[ 1 ] << 8 |
  2576. (unsigned long long)_p[ 2 ] << 16 |
  2577. (unsigned long long)_p[ 3 ] << 24 |
  2578. (unsigned long long)_p[ 4 ] << 32 |
  2579. (unsigned long long)_p[ 5 ] << 40 |
  2580. (unsigned long long)_p[ 6 ] << 48 |
  2581. (unsigned long long)_p[ 7 ] << 56;
  2582. }
  2583. unsigned int GET_UAA32LE(void *p, unsigned int i)
  2584. {
  2585. unsigned char *_p = (unsigned char *)&((unsigned int *)p)[i];
  2586. return
  2587. (unsigned int)_p[ 0 ] |
  2588. (unsigned int)_p[ 1 ] << 8 |
  2589. (unsigned int)_p[ 2 ] << 16 |
  2590. (unsigned int)_p[ 3 ] << 24;
  2591. }
  2592. unsigned short GET_UAA16LE(void *p, unsigned int i)
  2593. {
  2594. unsigned char *_p = (unsigned char *)&((unsigned short *)p)[i];
  2595. return
  2596. (unsigned short)_p[ 0 ] |
  2597. (unsigned short)_p[ 1 ] << 8;
  2598. }
  2599. unsigned short BE16(unsigned short x)
  2600. {
  2601. return GET_UAA16BE(&x, 0);
  2602. }
  2603. unsigned short LE16(unsigned short x)
  2604. {
  2605. return GET_UAA16LE(&x, 0);
  2606. }
  2607. unsigned int BE32(unsigned int x)
  2608. {
  2609. return GET_UAA32BE(&x, 0);
  2610. }
  2611. unsigned int LE32(unsigned int x)
  2612. {
  2613. return GET_UAA32LE(&x, 0);
  2614. }
  2615. unsigned long long BE64(unsigned long long x)
  2616. {
  2617. return GET_UAA64BE(&x, 0);
  2618. }
  2619. inline unsigned long long LE64(unsigned long long x)
  2620. {
  2621. return GET_UAA64LE(&x, 0);
  2622. }
  2623. #endif // defined(__BYTE_ORDER)
  2624. #ifndef _DEFAULT_SOURCE
  2625. #define _DEFAULT_SOURCE
  2626. #endif // _DEFAULT_SOURCE
  2627. #ifndef CONFIG
  2628. #define CONFIG "config.h"
  2629. #endif // CONFIG
  2630. #include CONFIG
  2631. #include "output.h"
  2632. #include "shared_globals.h"
  2633. #include "endian.h"
  2634. #include "helpers.h"
  2635. #ifndef NO_LOG
  2636. static void vlogger(const char *message, va_list args)
  2637. {
  2638. FILE *log;
  2639. #ifdef _NTSERVICE
  2640. if (!IsNTService && logstdout) log = stdout;
  2641. #else
  2642. if (logstdout) log = stdout;
  2643. #endif
  2644. else
  2645. {
  2646. if (fn_log == NULL) return;
  2647. #ifndef _WIN32
  2648. if (!strcmp(fn_log, "syslog"))
  2649. {
  2650. openlog("vlmcsd", LOG_CONS | LOG_PID, LOG_USER);
  2651. ////PORTABILITY: vsyslog is not in Posix but virtually all Unixes have it
  2652. vsyslog(LOG_INFO, message, args);
  2653. closelog();
  2654. return;
  2655. }
  2656. #endif // _WIN32
  2657. log = fopen(fn_log, "a");
  2658. if ( !log ) return;
  2659. }
  2660. time_t now = time(0);
  2661. #ifdef USE_THREADS
  2662. char mbstr[2048];
  2663. #else
  2664. char mbstr[24];
  2665. #endif
  2666. strftime(mbstr, sizeof(mbstr), "%Y-%m-%d %X", localtime(&now));
  2667. #ifndef USE_THREADS
  2668. fprintf(log, "%s: ", mbstr);
  2669. vfprintf(log, message, args);
  2670. fflush(log);
  2671. #else // USE_THREADS
  2672. // We write everything to a string before we really log inside the critical section
  2673. // so formatting the output can be concurrent
  2674. strcat(mbstr, ": ");
  2675. int len = strlen(mbstr);
  2676. vsnprintf(mbstr + len, sizeof(mbstr) - len, message, args);
  2677. lock_mutex(&logmutex);
  2678. fputs(mbstr, log);
  2679. fflush(log);
  2680. unlock_mutex(&logmutex);
  2681. #endif // USE_THREADS
  2682. if (log != stdout) fclose(log);
  2683. }
  2684. // Always sends to log output
  2685. int logger(const char *const fmt, ...)
  2686. {
  2687. va_list args;
  2688. va_start(args, fmt);
  2689. vlogger(fmt, args);
  2690. va_end(args);
  2691. return 0;
  2692. }
  2693. #endif //NO_LOG
  2694. // Output to stderr if it is available or to log otherwise (e.g. if running as daemon/service)
  2695. void printerrorf(const char *const fmt, ...)
  2696. {
  2697. va_list arglist;
  2698. va_start(arglist, fmt);
  2699. #ifndef NO_LOG
  2700. #ifdef _NTSERVICE
  2701. if (InetdMode || IsNTService)
  2702. #else // !_NTSERVICE
  2703. if (InetdMode)
  2704. #endif // NTSERVIICE
  2705. vlogger(fmt, arglist);
  2706. else
  2707. #endif //NO_LOG
  2708. {
  2709. vfprintf(stderr, fmt, arglist);
  2710. fflush(stderr);
  2711. }
  2712. va_end(arglist);
  2713. }
  2714. // Always output to stderr
  2715. int errorout(const char* fmt, ...)
  2716. {
  2717. va_list args;
  2718. va_start(args, fmt);
  2719. int i = vfprintf(stderr, fmt, args);
  2720. va_end(args);
  2721. fflush(stderr);
  2722. return i;
  2723. }
  2724. static const char *LicenseStatusText[] =
  2725. {
  2726. "Unlicensed", "Licensed", "OOB grace", "OOT grace", "Non-Genuine", "Notification", "Extended grace"
  2727. };
  2728. void uuid2StringLE(const GUID *const guid, char *const string)
  2729. {
  2730. sprintf(string,
  2731. #ifdef _WIN32
  2732. "%08x-%04x-%04x-%04x-%012I64x",
  2733. #else
  2734. "%08x-%04x-%04x-%04x-%012llx",
  2735. #endif
  2736. (unsigned int)LE32( guid->Data1 ),
  2737. (unsigned int)LE16( guid->Data2 ),
  2738. (unsigned int)LE16( guid->Data3 ),
  2739. (unsigned int)BE16( *(uint16_t*)guid->Data4 ),
  2740. (unsigned long long)BE64(*(uint64_t*)(guid->Data4)) & 0xffffffffffffLL
  2741. );
  2742. }
  2743. void logRequestVerbose(const REQUEST *const Request, const PRINTFUNC p)
  2744. {
  2745. char guidBuffer[GUID_STRING_LENGTH + 1];
  2746. char WorkstationBuffer[3 * WORKSTATION_NAME_BUFFER];
  2747. const char *productName;
  2748. ProdListIndex_t index;
  2749. p("Protocol version : %u.%u\n", LE16(Request->MajorVer), LE16(Request->MinorVer));
  2750. p("Client is a virtual machine : %s\n", LE32(Request->VMInfo) ? "Yes" : "No");
  2751. p("Licensing status : %u (%s)\n", (uint32_t)LE32(Request->LicenseStatus), LE32(Request->LicenseStatus) < _countof(LicenseStatusText) ? LicenseStatusText[LE32(Request->LicenseStatus)] : "Unknown");
  2752. p("Remaining time (0 = forever) : %i minutes\n", (uint32_t)LE32(Request->BindingExpiration));
  2753. uuid2StringLE(&Request->AppID, guidBuffer);
  2754. productName = getProductNameLE(&Request->AppID, AppList, &index);
  2755. p("Application ID : %s (%s)\n", guidBuffer, productName);
  2756. uuid2StringLE(&Request->ActID, guidBuffer);
  2757. #ifndef NO_EXTENDED_PRODUCT_LIST
  2758. productName = getProductNameLE(&Request->ActID, ExtendedProductList, &index);
  2759. #else
  2760. productName = "Unknown";
  2761. #endif
  2762. p("Activation ID (Product) : %s (%s)\n", guidBuffer, productName);
  2763. uuid2StringLE(&Request->KMSID, guidBuffer);
  2764. #ifndef NO_BASIC_PRODUCT_LIST
  2765. productName = getProductNameLE(&Request->KMSID, ProductList, &index);
  2766. #else
  2767. productName = "Unknown";
  2768. #endif
  2769. p("Key Management Service ID : %s (%s)\n", guidBuffer, productName);
  2770. uuid2StringLE(&Request->CMID, guidBuffer);
  2771. p("Client machine ID : %s\n", guidBuffer);
  2772. uuid2StringLE(&Request->CMID_prev, guidBuffer);
  2773. p("Previous client machine ID : %s\n", guidBuffer);
  2774. char mbstr[64];
  2775. time_t st;
  2776. st = fileTimeToUnixTime(&Request->ClientTime);
  2777. strftime(mbstr, sizeof(mbstr), "%Y-%m-%d %X", gmtime(&st));
  2778. p("Client request timestamp (UTC) : %s\n", mbstr);
  2779. ucs2_to_utf8(Request->WorkstationName, WorkstationBuffer, WORKSTATION_NAME_BUFFER, sizeof(WorkstationBuffer));
  2780. p("Workstation name : %s\n", WorkstationBuffer);
  2781. p("N count policy (minimum clients): %u\n", (uint32_t)LE32(Request->N_Policy));
  2782. }
  2783. void logResponseVerbose(const char *const ePID, const BYTE *const hwid, const RESPONSE *const response, const PRINTFUNC p)
  2784. {
  2785. char guidBuffer[GUID_STRING_LENGTH + 1];
  2786. //SYSTEMTIME st;
  2787. p("Protocol version : %u.%u\n", (uint32_t)LE16(response->MajorVer), (uint32_t)LE16(response->MinorVer));
  2788. p("KMS host extended PID : %s\n", ePID);
  2789. if (LE16(response->MajorVer) > 5)
  2790. # ifndef _WIN32
  2791. p("KMS host Hardware ID : %016llX\n", (unsigned long long)BE64(*(uint64_t*)hwid));
  2792. # else // _WIN32
  2793. p("KMS host Hardware ID : %016I64X\n", (unsigned long long)BE64(*(uint64_t*)hwid));
  2794. # endif // WIN32
  2795. uuid2StringLE(&response->CMID, guidBuffer);
  2796. p("Client machine ID : %s\n", guidBuffer);
  2797. char mbstr[64];
  2798. time_t st;
  2799. st = fileTimeToUnixTime(&response->ClientTime);
  2800. strftime(mbstr, sizeof(mbstr), "%Y-%m-%d %X", gmtime(&st));
  2801. p("Client request timestamp (UTC) : %s\n", mbstr);
  2802. p("KMS host current active clients : %u\n", (uint32_t)LE32(response->Count));
  2803. p("Renewal interval policy : %u\n", (uint32_t)LE32(response->VLRenewalInterval));
  2804. p("Activation interval policy : %u\n", (uint32_t)LE32(response->VLActivationInterval));
  2805. }
  2806. #ifndef CONFIG
  2807. #define CONFIG "config.h"
  2808. #endif // CONFIG
  2809. #include CONFIG
  2810. #include "shared_globals.h"
  2811. int global_argc, multi_argc = 0;
  2812. CARGV global_argv, multi_argv = NULL;
  2813. const char *const Version = VERSION;
  2814. DWORD VLActivationInterval = 60 * 2; // 2 hours
  2815. DWORD VLRenewalInterval = 60 * 24 * 7; // 7 days
  2816. int_fast8_t DisconnectImmediately = FALSE;
  2817. const char *const cIPv4 = "IPv4";
  2818. const char *const cIPv6 = "IPv6";
  2819. #ifndef USE_MSRPC
  2820. int_fast8_t UseMultiplexedRpc = TRUE;
  2821. int_fast8_t UseRpcNDR64 = TRUE;
  2822. int_fast8_t UseRpcBTFN = TRUE;
  2823. #endif // USE_MSRPC
  2824. #ifndef NO_SOCKETS
  2825. const char *defaultport = "1688";
  2826. #endif // NO_SOCKETS
  2827. KmsResponseParam_t KmsResponseParameters[MAX_KMSAPPS];
  2828. #if !defined(NO_SOCKETS) && !defined(NO_SIGHUP) && !defined(_WIN32)
  2829. int_fast8_t IsRestarted = FALSE;
  2830. #endif // !defined(NO_SOCKETS) && !defined(NO_SIGHUP) && !defined(_WIN32)
  2831. #if !defined(NO_TIMEOUT) && !__minix__
  2832. DWORD ServerTimeout = 30;
  2833. #endif // !defined(NO_TIMEOUT) && !__minix__
  2834. #if !defined(NO_LIMIT) && !defined (NO_SOCKETS) && !__minix__
  2835. #ifdef USE_MSRPC
  2836. uint32_t MaxTasks = RPC_C_LISTEN_MAX_CALLS_DEFAULT;
  2837. #else // !USE_MSRPC
  2838. uint32_t MaxTasks = SEM_VALUE_MAX;
  2839. #endif // !USE_MSRPC
  2840. #endif // !defined(NO_LIMIT) && !defined (NO_SOCKETS) && !__minix__
  2841. #ifndef NO_LOG
  2842. char *fn_log = NULL;
  2843. int_fast8_t logstdout = 0;
  2844. #ifndef NO_VERBOSE_LOG
  2845. int_fast8_t logverbose = 0;
  2846. #endif // NO_VERBOSE_LOG
  2847. #endif // NO_LOG
  2848. #ifndef NO_SOCKETS
  2849. int_fast8_t nodaemon = 0;
  2850. int_fast8_t InetdMode = 0;
  2851. #else
  2852. int_fast8_t nodaemon = 1;
  2853. int_fast8_t InetdMode = 1;
  2854. #endif
  2855. #ifndef NO_RANDOM_EPID
  2856. int_fast8_t RandomizationLevel = 1;
  2857. uint16_t Lcid = 0;
  2858. #endif
  2859. #ifndef NO_SOCKETS
  2860. SOCKET *SocketList;
  2861. int numsockets = 0;
  2862. #if !defined(NO_LIMIT) && !__minix__
  2863. #ifndef _WIN32 // Posix
  2864. sem_t *Semaphore;
  2865. #else // _WIN32
  2866. HANDLE Semaphore;
  2867. #endif // _WIN32
  2868. #endif // !defined(NO_LIMIT) && !__minix__
  2869. #endif // NO_SOCKETS
  2870. #ifdef _NTSERVICE
  2871. int_fast8_t IsNTService = TRUE;
  2872. int_fast8_t ServiceShutdown = FALSE;
  2873. #endif // _NTSERVICE
  2874. #ifndef NO_LOG
  2875. #ifdef USE_THREADS
  2876. #if !defined(_WIN32) && !defined(__CYGWIN__)
  2877. pthread_mutex_t logmutex = PTHREAD_MUTEX_INITIALIZER;
  2878. #else
  2879. CRITICAL_SECTION logmutex;
  2880. #endif // !defined(_WIN32) && !defined(__CYGWIN__)
  2881. #endif // USE_THREADS
  2882. #endif // NO_LOG
  2883. /*
  2884. * Helper functions used by other modules
  2885. */
  2886. #ifndef CONFIG
  2887. #define CONFIG "config.h"
  2888. #endif // CONFIG
  2889. #include CONFIG
  2890. #ifndef _WIN32
  2891. #include <errno.h>
  2892. #endif // _WIN32
  2893. #include <getopt.h>
  2894. #include <string.h>
  2895. #include <stdlib.h>
  2896. #include <ctype.h>
  2897. #include "helpers.h"
  2898. #include "output.h"
  2899. #include "endian.h"
  2900. #include "shared_globals.h"
  2901. /*
  2902. * UCS2 <-> UTF-8 functions
  2903. * All functions use little endian UCS2 since we only need it to communicate with Windows via RPC
  2904. */
  2905. // Convert one character from UTF-8 to UCS2
  2906. // Returns 0xffff, if utf-8 evaluates to > 0xfffe (outside basic multilingual pane)
  2907. WCHAR utf8_to_ucs2_char (const unsigned char *input, const unsigned char **end_ptr)
  2908. {
  2909. *end_ptr = input;
  2910. if (input[0] == 0)
  2911. return ~0;
  2912. if (input[0] < 0x80) {
  2913. *end_ptr = input + 1;
  2914. return LE16(input[0]);
  2915. }
  2916. if ((input[0] & 0xE0) == 0xE0) {
  2917. if (input[1] == 0 || input[2] == 0)
  2918. return ~0;
  2919. *end_ptr = input + 3;
  2920. return
  2921. LE16((input[0] & 0x0F)<<12 |
  2922. (input[1] & 0x3F)<<6 |
  2923. (input[2] & 0x3F));
  2924. }
  2925. if ((input[0] & 0xC0) == 0xC0) {
  2926. if (input[1] == 0)
  2927. return ~0;
  2928. *end_ptr = input + 2;
  2929. return
  2930. LE16((input[0] & 0x1F)<<6 |
  2931. (input[1] & 0x3F));
  2932. }
  2933. return ~0;
  2934. }
  2935. // Convert one character from UCS2 to UTF-8
  2936. // Returns length of UTF-8 char (1, 2 or 3) or -1 on error (UTF-16 outside UCS2)
  2937. // char *utf8 must be large enough to hold 3 bytes
  2938. int ucs2_to_utf8_char (const WCHAR ucs2_le, char *utf8)
  2939. {
  2940. const WCHAR ucs2 = LE16(ucs2_le);
  2941. if (ucs2 < 0x80) {
  2942. utf8[0] = ucs2;
  2943. utf8[1] = '\0';
  2944. return 1;
  2945. }
  2946. if (ucs2 >= 0x80 && ucs2 < 0x800) {
  2947. utf8[0] = (ucs2 >> 6) | 0xC0;
  2948. utf8[1] = (ucs2 & 0x3F) | 0x80;
  2949. utf8[2] = '\0';
  2950. return 2;
  2951. }
  2952. if (ucs2 >= 0x800 && ucs2 < 0xFFFF) {
  2953. if (ucs2 >= 0xD800 && ucs2 <= 0xDFFF) {
  2954. /* Ill-formed (UTF-16 ouside of BMP) */
  2955. return -1;
  2956. }
  2957. utf8[0] = ((ucs2 >> 12) ) | 0xE0;
  2958. utf8[1] = ((ucs2 >> 6 ) & 0x3F) | 0x80;
  2959. utf8[2] = ((ucs2 ) & 0x3F) | 0x80;
  2960. utf8[3] = '\0';
  2961. return 3;
  2962. }
  2963. return -1;
  2964. }
  2965. // Converts UTF8 to UCS2. Returns size in bytes of the converted string or -1 on error
  2966. size_t utf8_to_ucs2(WCHAR* const ucs2_le, const char* const utf8, const size_t maxucs2, const size_t maxutf8)
  2967. {
  2968. const unsigned char* current_utf8 = (unsigned char*)utf8;
  2969. WCHAR* current_ucs2_le = ucs2_le;
  2970. for (; *current_utf8; current_ucs2_le++)
  2971. {
  2972. size_t size = (char*)current_utf8 - utf8;
  2973. if (size >= maxutf8) return (size_t)-1;
  2974. if (((*current_utf8 & 0xc0) == 0xc0) && (size >= maxutf8 - 1)) return (size_t)-1;
  2975. if (((*current_utf8 & 0xe0) == 0xe0) && (size >= maxutf8 - 2)) return (size_t)-1;
  2976. if (current_ucs2_le - ucs2_le >= (intptr_t)maxucs2 - 1) return (size_t)-1;
  2977. *current_ucs2_le = utf8_to_ucs2_char(current_utf8, &current_utf8);
  2978. current_ucs2_le[1] = 0;
  2979. if (*current_ucs2_le == (WCHAR)-1) return (size_t)-1;
  2980. }
  2981. return current_ucs2_le - ucs2_le;
  2982. }
  2983. // Converts UCS2 to UTF-8. Return TRUE or FALSE
  2984. BOOL ucs2_to_utf8(const WCHAR* const ucs2_le, char* utf8, size_t maxucs2, size_t maxutf8)
  2985. {
  2986. char utf8_char[4];
  2987. const WCHAR* current_ucs2 = ucs2_le;
  2988. unsigned int index_utf8 = 0;
  2989. for(*utf8 = 0; *current_ucs2; current_ucs2++)
  2990. {
  2991. if (current_ucs2 - ucs2_le > (intptr_t)maxucs2) return FALSE;
  2992. int len = ucs2_to_utf8_char(*current_ucs2, utf8_char);
  2993. if (index_utf8 + len > maxutf8) return FALSE;
  2994. strncat(utf8, utf8_char, len);
  2995. index_utf8+=len;
  2996. }
  2997. return TRUE;
  2998. }
  2999. /* End of UTF-8 <-> UCS2 conversion */
  3000. // Checks, whether a string is a valid integer number between min and max. Returns TRUE or FALSE. Puts int value in *value
  3001. BOOL stringToInt(const char *const szValue, const unsigned int min, const unsigned int max, unsigned int *const value)
  3002. {
  3003. char *nextchar;
  3004. errno = 0;
  3005. long long result = strtoll(szValue, &nextchar, 10);
  3006. if (errno || result < (long long)min || result > (long long)max || *nextchar)
  3007. {
  3008. return FALSE;
  3009. }
  3010. *value = (unsigned int)result;
  3011. return TRUE;
  3012. }
  3013. //Converts a String Guid to a host binary guid in host endianess
  3014. int_fast8_t string2Uuid(const char *const restrict input, GUID *const restrict guid)
  3015. {
  3016. int i;
  3017. if (strlen(input) < GUID_STRING_LENGTH) return FALSE;
  3018. if (input[8] != '-' || input[13] != '-' || input[18] != '-' || input[23] != '-') return FALSE;
  3019. for (i = 0; i < GUID_STRING_LENGTH; i++)
  3020. {
  3021. if (i == 8 || i == 13 || i == 18 || i == 23) continue;
  3022. const char c = toupper((int)input[i]);
  3023. if (c < '0' || c > 'F' || (c > '9' && c < 'A')) return FALSE;
  3024. }
  3025. char inputCopy[GUID_STRING_LENGTH + 1];
  3026. strncpy(inputCopy, input, GUID_STRING_LENGTH + 1);
  3027. inputCopy[8] = inputCopy[13] = inputCopy[18] = 0;
  3028. hex2bin((BYTE*)&guid->Data1, inputCopy, 8);
  3029. hex2bin((BYTE*)&guid->Data2, inputCopy + 9, 4);
  3030. hex2bin((BYTE*)&guid->Data3, inputCopy + 14, 4);
  3031. hex2bin(guid->Data4, input + 19, 16);
  3032. guid->Data1 = BE32(guid->Data1);
  3033. guid->Data2 = BE16(guid->Data2);
  3034. guid->Data3 = BE16(guid->Data3);
  3035. return TRUE;
  3036. }
  3037. // convert GUID to little-endian
  3038. void LEGUID(GUID *const restrict out, const GUID* const restrict in)
  3039. {
  3040. #if __BYTE_ORDER != __LITTLE_ENDIAN
  3041. out->Data1 = LE32(in->Data1);
  3042. out->Data2 = LE16(in->Data2);
  3043. out->Data3 = LE16(in->Data3);
  3044. memcpy(out->Data4, in->Data4, sizeof(out->Data4));
  3045. #else
  3046. memcpy(out, in, sizeof(GUID));
  3047. #endif
  3048. }
  3049. //Checks a command line argument if it is numeric and between min and max. Returns the numeric value or exits on error
  3050. __pure unsigned int getOptionArgumentInt(const char o, const unsigned int min, const unsigned int max)
  3051. {
  3052. unsigned int result;
  3053. if (!stringToInt(optarg, min, max, &result))
  3054. {
  3055. printerrorf("Fatal: Option \"-%c\" must be numeric between %u and %u.\n", o, min, max);
  3056. exit(!0);
  3057. }
  3058. return result;
  3059. }
  3060. // Resets getopt() to start parsing from the beginning
  3061. void optReset(void)
  3062. {
  3063. #if __minix__ || defined(__BSD__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__)
  3064. optind = 1;
  3065. optreset = 1; // Makes newer BSD getopt happy
  3066. #elif defined(__UCLIBC__) // uClibc headers also define __GLIBC__ so be careful here
  3067. optind = 0; // uClibc seeks compatibility with GLIBC
  3068. #elif defined(__GLIBC__)
  3069. optind = 0; // Makes GLIBC getopt happy
  3070. #else // Standard for most systems
  3071. optind = 1;
  3072. #endif
  3073. }
  3074. #if defined(_WIN32) || defined(USE_MSRPC)
  3075. // Returns a static message buffer containing text for a given Win32 error. Not thread safe (same as strerror)
  3076. char* win_strerror(const int message)
  3077. {
  3078. #define STRERROR_BUFFER_SIZE 256
  3079. static char buffer[STRERROR_BUFFER_SIZE];
  3080. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, NULL, message, 0, buffer, STRERROR_BUFFER_SIZE, NULL);
  3081. return buffer;
  3082. }
  3083. #endif // defined(_WIN32) || defined(USE_MSRPC)
  3084. /*
  3085. * parses an address in the form host:[port] in addr
  3086. * returns host and port in seperate strings
  3087. */
  3088. void parseAddress(char *const addr, char** szHost, char** szPort)
  3089. {
  3090. *szHost = addr;
  3091. # ifndef NO_SOCKETS
  3092. *szPort = (char*)defaultport;
  3093. # else // NO_SOCKETS
  3094. *szPort = "1688";
  3095. # endif // NO_SOCKETS
  3096. char *lastcolon = strrchr(addr, ':');
  3097. char *firstcolon = strchr(addr, ':');
  3098. char *closingbracket = strrchr(addr, ']');
  3099. if (*addr == '[' && closingbracket) //Address in brackets
  3100. {
  3101. *closingbracket = 0;
  3102. (*szHost)++;
  3103. if (closingbracket[1] == ':')
  3104. *szPort = closingbracket + 2;
  3105. }
  3106. else if (firstcolon && firstcolon == lastcolon) //IPv4 address or hostname with port
  3107. {
  3108. *firstcolon = 0;
  3109. *szPort = firstcolon + 1;
  3110. }
  3111. }
  3112. // Initialize random generator (needs to be done in each thread)
  3113. void randomNumberInit()
  3114. {
  3115. struct timeval tv;
  3116. gettimeofday(&tv, NULL);
  3117. srand((unsigned int)(tv.tv_sec ^ tv.tv_usec));
  3118. }
  3119. // We always exit immediately if any OOM condition occurs
  3120. __noreturn void OutOfMemory(void)
  3121. {
  3122. errorout("Fatal: Out of memory");
  3123. exit(!0);
  3124. }
  3125. void* vlmcsd_malloc(size_t len)
  3126. {
  3127. void* buf = malloc(len);
  3128. if (!buf) OutOfMemory();
  3129. return buf;
  3130. }
  3131. /*
  3132. * Converts hex digits to bytes in big-endian order.
  3133. * Ignores any non-hex characters
  3134. */
  3135. void hex2bin(BYTE *const bin, const char *hex, const size_t maxbin)
  3136. {
  3137. static const char *const hexdigits = "0123456789ABCDEF";
  3138. char* nextchar;
  3139. size_t i;
  3140. for (i = 0; (i < 16) && utf8_to_ucs2_char((const unsigned char*)hex, (const unsigned char**)&nextchar) != (WCHAR)-1; hex = nextchar)
  3141. {
  3142. const char* pos = strchr(hexdigits, toupper((int)*hex));
  3143. if (!pos) continue;
  3144. if (!(i & 1)) bin[i >> 1] = 0;
  3145. bin[i >> 1] |= (char)(pos - hexdigits);
  3146. if (!(i & 1)) bin[i >> 1] <<= 4;
  3147. i++;
  3148. if (i >> 1 > maxbin) break;
  3149. }
  3150. }
  3151. __pure BOOL getArgumentBool(int_fast8_t *result, const char *const argument)
  3152. {
  3153. if (
  3154. !strncasecmp(argument, "true", 4) ||
  3155. !strncasecmp(argument, "on", 4) ||
  3156. !strncasecmp(argument, "yes", 3) ||
  3157. !strncasecmp(argument, "1", 1)
  3158. )
  3159. {
  3160. *result = TRUE;
  3161. return TRUE;
  3162. }
  3163. else if (
  3164. !strncasecmp(argument, "false", 5) ||
  3165. !strncasecmp(argument, "off", 3) ||
  3166. !strncasecmp(argument, "no", 2) ||
  3167. !strncasecmp(argument, "0", 1)
  3168. )
  3169. {
  3170. *result = FALSE;
  3171. return TRUE;
  3172. }
  3173. return FALSE;
  3174. }
  3175. #ifndef CONFIG
  3176. #define CONFIG "config.h"
  3177. #endif // CONFIG
  3178. #include CONFIG
  3179. #ifndef USE_MSRPC
  3180. #ifndef _GNU_SOURCE
  3181. #define _GNU_SOURCE
  3182. #endif
  3183. #include <string.h>
  3184. #ifndef _WIN32
  3185. #include <signal.h>
  3186. #include <unistd.h>
  3187. #include <fcntl.h>
  3188. #include <errno.h>
  3189. #include <netinet/in.h>
  3190. #endif // WIN32
  3191. #include "network.h"
  3192. #include "endian.h"
  3193. #include "output.h"
  3194. #include "helpers.h"
  3195. #include "shared_globals.h"
  3196. #include "rpc.h"
  3197. #ifndef _WIN32
  3198. typedef ssize_t (*sendrecv_t)(int, void*, size_t, int);
  3199. #else
  3200. typedef int (WINAPI *sendrecv_t)(SOCKET, void*, int, int);
  3201. #endif
  3202. // Send or receive a fixed number of bytes regardless if received in one or more chunks
  3203. int_fast8_t sendrecv(SOCKET sock, BYTE *data, int len, int_fast8_t do_send)
  3204. {
  3205. int n;
  3206. sendrecv_t f = do_send
  3207. ? (sendrecv_t) send
  3208. : (sendrecv_t) recv;
  3209. do
  3210. {
  3211. n = f(sock, data, len, 0);
  3212. }
  3213. while (
  3214. ( n < 0 && socket_errno == VLMCSD_EINTR ) || ( n > 0 && ( data += n, (len -= n) > 0 ) ));
  3215. return ! len;
  3216. }
  3217. static int_fast8_t ip2str(char *restrict result, const size_t resultLength, const struct sockaddr *const restrict socketAddress, const socklen_t socketLength)
  3218. {
  3219. static const char *const fIPv4 = "%s:%s";
  3220. static const char *const fIPv6 = "[%s]:%s";
  3221. char ipAddress[64], portNumber[8];
  3222. if (getnameinfo
  3223. (
  3224. socketAddress,
  3225. socketLength,
  3226. ipAddress,
  3227. sizeof(ipAddress),
  3228. portNumber,
  3229. sizeof(portNumber),
  3230. NI_NUMERICHOST | NI_NUMERICSERV
  3231. ))
  3232. {
  3233. return FALSE;
  3234. }
  3235. if ((unsigned int)snprintf(result, resultLength, socketAddress->sa_family == AF_INET6 ? fIPv6 : fIPv4, ipAddress, portNumber) > resultLength) return FALSE;
  3236. return TRUE;
  3237. }
  3238. static int_fast8_t getSocketList(struct addrinfo **saList, const char *const addr, const int flags, const int AddressFamily)
  3239. {
  3240. int status;
  3241. char *szHost, *szPort;
  3242. size_t len = strlen(addr) + 1;
  3243. // Don't alloca too much
  3244. if (len > 264) return FALSE;
  3245. char *addrcopy = (char*)alloca(len);
  3246. memcpy(addrcopy, addr, len);
  3247. parseAddress(addrcopy, &szHost, &szPort);
  3248. struct addrinfo hints;
  3249. memset(&hints, 0, sizeof(struct addrinfo));
  3250. hints.ai_family = AddressFamily;
  3251. hints.ai_socktype = SOCK_STREAM;
  3252. hints.ai_protocol = IPPROTO_TCP;
  3253. hints.ai_flags = flags;
  3254. if ((status = getaddrinfo(szHost, szPort, &hints, saList)))
  3255. {
  3256. printerrorf("Warning: %s: %s\n", addr, gai_strerror(status));
  3257. return FALSE;
  3258. }
  3259. return TRUE;
  3260. }
  3261. static int_fast8_t setBlockingEnabled(SOCKET fd, int_fast8_t blocking)
  3262. {
  3263. if (fd == INVALID_SOCKET) return FALSE;
  3264. #ifdef _WIN32
  3265. unsigned long mode = blocking ? 0 : 1;
  3266. return (ioctlsocket(fd, FIONBIO, &mode) == 0) ? TRUE : FALSE;
  3267. #else // POSIX
  3268. int flags = fcntl(fd, F_GETFL, 0);
  3269. if (flags < 0) return FALSE;
  3270. flags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
  3271. return (fcntl(fd, F_SETFL, flags) == 0) ? TRUE : FALSE;
  3272. #endif // POSIX
  3273. }
  3274. int_fast8_t isDisconnected(const SOCKET s)
  3275. {
  3276. char buffer[1];
  3277. if (!setBlockingEnabled(s, FALSE)) return TRUE;
  3278. int n = recv(s, buffer, 1, MSG_PEEK);
  3279. if (!setBlockingEnabled(s, TRUE)) return TRUE;
  3280. if (n == 0) return TRUE;
  3281. return FALSE;
  3282. }
  3283. // Connect to TCP address addr (e.g. "kms.example.com:1688") and return an
  3284. // open socket for the connection if successful or INVALID_SOCKET otherwise
  3285. SOCKET connectToAddress(const char *const addr, const int AddressFamily, int_fast8_t showHostName)
  3286. {
  3287. struct addrinfo *saList, *sa;
  3288. SOCKET s = INVALID_SOCKET;
  3289. char szAddr[128];
  3290. if (!getSocketList(&saList, addr, 0, AddressFamily)) return INVALID_SOCKET;
  3291. for (sa = saList; sa; sa = sa->ai_next)
  3292. {
  3293. // struct sockaddr_in* addr4 = (struct sockaddr_in*)sa->ai_addr;
  3294. // struct sockaddr_in6* addr6 = (struct sockaddr_in6*)sa->ai_addr;
  3295. if (ip2str(szAddr, sizeof(szAddr), sa->ai_addr, sa->ai_addrlen))
  3296. {
  3297. if (showHostName)
  3298. printf("Connecting to %s (%s) ... ", addr, szAddr);
  3299. else
  3300. printf("Connecting to %s ... ", szAddr);
  3301. fflush(stdout);
  3302. }
  3303. s = socket(sa->ai_family, SOCK_STREAM, IPPROTO_TCP);
  3304. # if !defined(NO_TIMEOUT) && !__minix__
  3305. # ifndef _WIN32 // Standard Posix timeout structure
  3306. struct timeval to;
  3307. to.tv_sec = 10;
  3308. to.tv_usec = 0;
  3309. # else // Windows requires a DWORD with milliseconds
  3310. DWORD to = 10000;
  3311. # endif // _WIN32
  3312. setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (sockopt_t)&to, sizeof(to));
  3313. setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (sockopt_t)&to, sizeof(to));
  3314. # endif // !defined(NO_TIMEOUT) && !__minix__
  3315. if (!connect(s, sa->ai_addr, sa->ai_addrlen))
  3316. {
  3317. printf("successful\n");
  3318. break;
  3319. }
  3320. errorout("%s\n", socket_errno == VLMCSD_EINPROGRESS ? "Timed out" : vlmcsd_strerror(socket_errno));
  3321. socketclose(s);
  3322. s = INVALID_SOCKET;
  3323. }
  3324. freeaddrinfo(saList);
  3325. return s;
  3326. }
  3327. #ifndef NO_SOCKETS
  3328. // Create a Listening socket for addrinfo sa and return socket s
  3329. // szHost and szPort are for logging only
  3330. static int listenOnAddress(const struct addrinfo *const ai, SOCKET *s)
  3331. {
  3332. int error;
  3333. char ipstr[64];
  3334. ip2str(ipstr, sizeof(ipstr), ai->ai_addr, ai->ai_addrlen);
  3335. //*s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  3336. *s = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
  3337. if (*s == INVALID_SOCKET)
  3338. {
  3339. error = socket_errno;
  3340. printerrorf("Warning: %s error. %s\n", ai->ai_family == AF_INET6 ? cIPv6 : cIPv4, vlmcsd_strerror(error));
  3341. return error;
  3342. }
  3343. # if !defined(_WIN32) && !defined(NO_SIGHUP)
  3344. int flags = fcntl(*s, F_GETFD, 0);
  3345. if (flags != -1)
  3346. {
  3347. flags |= FD_CLOEXEC;
  3348. fcntl(*s, F_SETFD, flags);
  3349. }
  3350. # ifdef _PEDANTIC
  3351. else
  3352. {
  3353. printerrorf("Warning: Could not set FD_CLOEXEC flag on %s: %s\n", ipstr, vlmcsd_strerror(errno));
  3354. }
  3355. # endif // _PEDANTIC
  3356. # endif // !defined(_WIN32) && !defined(NO_SIGHUP)
  3357. BOOL socketOption = TRUE;
  3358. // fix for lame tomato toolchain
  3359. # ifndef IPV6_V6ONLY
  3360. # ifdef __linux__
  3361. # define IPV6_V6ONLY (26)
  3362. # endif // __linux__
  3363. # endif // IPV6_V6ONLY
  3364. # ifdef IPV6_V6ONLY
  3365. if (ai->ai_family == AF_INET6) setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY, (sockopt_t)&socketOption, sizeof(socketOption));
  3366. # endif
  3367. # ifndef _WIN32
  3368. setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, (sockopt_t)&socketOption, sizeof(socketOption));
  3369. # endif
  3370. if (bind(*s, ai->ai_addr, ai->ai_addrlen) || listen(*s, SOMAXCONN))
  3371. {
  3372. error = socket_errno;
  3373. printerrorf("Warning: %s: %s\n", ipstr, vlmcsd_strerror(error));
  3374. socketclose(*s);
  3375. return error;
  3376. }
  3377. # ifndef NO_LOG
  3378. logger("Listening on %s\n", ipstr);
  3379. # endif
  3380. return 0;
  3381. }
  3382. // Adds a listening socket for an address string,
  3383. // e.g. 127.0.0.1:1688 or [2001:db8:dead:beef::1]:1688
  3384. BOOL addListeningSocket(const char *const addr)
  3385. {
  3386. struct addrinfo *aiList, *ai;
  3387. int result = FALSE;
  3388. SOCKET *s = SocketList + numsockets;
  3389. if (getSocketList(&aiList, addr, AI_PASSIVE | AI_NUMERICHOST, AF_UNSPEC))
  3390. {
  3391. for (ai = aiList; ai; ai = ai->ai_next)
  3392. {
  3393. // struct sockaddr_in* addr4 = (struct sockaddr_in*)sa->ai_addr;
  3394. // struct sockaddr_in6* addr6 = (struct sockaddr_in6*)sa->ai_addr;
  3395. if (numsockets >= FD_SETSIZE)
  3396. {
  3397. #ifdef _PEDANTIC // Do not report this error in normal builds to keep file size low
  3398. printerrorf("Warning: Cannot listen on %s. Your OS only supports %u listening sockets in an FD_SET.\n", addr, FD_SETSIZE);
  3399. #endif
  3400. break;
  3401. }
  3402. if (!listenOnAddress(ai, s))
  3403. {
  3404. numsockets++;
  3405. result = TRUE;
  3406. }
  3407. }
  3408. freeaddrinfo(aiList);
  3409. }
  3410. return result;
  3411. }
  3412. // Just create some dummy sockets to see if we have a specific protocol (IPv4 or IPv6)
  3413. __pure int_fast8_t checkProtocolStack(const int addressfamily)
  3414. {
  3415. SOCKET s; // = INVALID_SOCKET;
  3416. s = socket(addressfamily, SOCK_STREAM, 0);
  3417. int_fast8_t success = (s != INVALID_SOCKET);
  3418. socketclose(s);
  3419. return success;
  3420. }
  3421. // Build an fd_set of all listening socket then use select to wait for an incoming connection
  3422. static SOCKET network_accept_any()
  3423. {
  3424. fd_set ListeningSocketsList;
  3425. SOCKET maxSocket, sock;
  3426. int i;
  3427. int status;
  3428. FD_ZERO(&ListeningSocketsList);
  3429. maxSocket = 0;
  3430. for (i = 0; i < numsockets; i++)
  3431. {
  3432. FD_SET(SocketList[i], &ListeningSocketsList);
  3433. if (SocketList[i] > maxSocket) maxSocket = SocketList[i];
  3434. }
  3435. status = select(maxSocket + 1, &ListeningSocketsList, NULL, NULL, NULL);
  3436. if (status < 0) return INVALID_SOCKET;
  3437. sock = INVALID_SOCKET;
  3438. for (i = 0; i < numsockets; i++)
  3439. {
  3440. if (FD_ISSET(SocketList[i], &ListeningSocketsList))
  3441. {
  3442. sock = SocketList[i];
  3443. break;
  3444. }
  3445. }
  3446. if (sock == INVALID_SOCKET)
  3447. return INVALID_SOCKET;
  3448. else
  3449. return accept(sock, NULL, NULL);
  3450. }
  3451. void closeAllListeningSockets()
  3452. {
  3453. int i;
  3454. for (i = 0; i < numsockets; i++)
  3455. {
  3456. shutdown(SocketList[i], VLMCSD_SHUT_RDWR);
  3457. socketclose(SocketList[i]);
  3458. }
  3459. }
  3460. #endif // NO_SOCKETS
  3461. static void serveClient(const SOCKET s_client, const DWORD RpcAssocGroup)
  3462. {
  3463. # if !defined(NO_TIMEOUT) && !__minix__
  3464. # ifndef _WIN32 // Standard Posix timeout structure
  3465. struct timeval to;
  3466. to.tv_sec = ServerTimeout;
  3467. to.tv_usec = 0;
  3468. #else // Windows requires a DWORD with milliseconds
  3469. DWORD to = ServerTimeout * 1000;
  3470. # endif // _WIN32
  3471. # if !defined(NO_LOG) && defined(_PEDANTIC)
  3472. int result =
  3473. setsockopt(s_client, SOL_SOCKET, SO_RCVTIMEO, (sockopt_t)&to, sizeof(to)) ||
  3474. setsockopt(s_client, SOL_SOCKET, SO_SNDTIMEO, (sockopt_t)&to, sizeof(to));
  3475. if (result) logger("Warning: Set timeout failed: %s\n", vlmcsd_strerror(socket_errno));
  3476. # else // !(!defined(NO_LOG) && defined(_PEDANTIC))
  3477. setsockopt(s_client, SOL_SOCKET, SO_RCVTIMEO, (sockopt_t)&to, sizeof(to));
  3478. setsockopt(s_client, SOL_SOCKET, SO_SNDTIMEO, (sockopt_t)&to, sizeof(to));
  3479. # endif // !(!defined(NO_LOG) && defined(_PEDANTIC))
  3480. # endif // !defined(NO_TIMEOUT) && !__minix__
  3481. char ipstr[64];
  3482. socklen_t len;
  3483. struct sockaddr_storage addr;
  3484. len = sizeof addr;
  3485. if (getpeername(s_client, (struct sockaddr*)&addr, &len) ||
  3486. !ip2str(ipstr, sizeof(ipstr), (struct sockaddr*)&addr, len))
  3487. {
  3488. # if !defined(NO_LOG) && defined(_PEDANTIC)
  3489. logger("Fatal: Cannot determine client's IP address: %s\n", vlmcsd_strerror(errno));
  3490. # endif // !defined(NO_LOG) && defined(_PEDANTIC)
  3491. socketclose(s_client);
  3492. return;
  3493. }
  3494. # ifndef NO_LOG
  3495. const char *const connection_type = addr.ss_family == AF_INET6 ? cIPv6 : cIPv4;
  3496. static const char *const cAccepted = "accepted";
  3497. static const char *const cClosed = "closed";
  3498. static const char *const fIP = "%s connection %s: %s.\n";
  3499. logger(fIP, connection_type, cAccepted, ipstr);
  3500. #endif // NO_LOG
  3501. rpcServer(s_client, RpcAssocGroup, ipstr);
  3502. # ifndef NO_LOG
  3503. logger(fIP, connection_type, cClosed, ipstr);
  3504. # endif // NO_LOG
  3505. socketclose(s_client);
  3506. }
  3507. #ifndef NO_SOCKETS
  3508. static void post_sem(void)
  3509. {
  3510. #if !defined(NO_LIMIT) && !__minix__
  3511. if (!InetdMode && MaxTasks != SEM_VALUE_MAX)
  3512. {
  3513. semaphore_post(Semaphore);
  3514. }
  3515. #endif // !defined(NO_LIMIT) && !__minix__
  3516. }
  3517. static void wait_sem(void)
  3518. {
  3519. #if !defined(NO_LIMIT) && !__minix__
  3520. if (!InetdMode && MaxTasks != SEM_VALUE_MAX)
  3521. {
  3522. semaphore_wait(Semaphore);
  3523. }
  3524. #endif // !defined(NO_LIMIT) && !__minix__
  3525. }
  3526. #endif // NO_SOCKETS
  3527. #if defined(USE_THREADS) && !defined(NO_SOCKETS)
  3528. #if defined(_WIN32) || defined(__CYGWIN__) // Win32 Threads
  3529. static DWORD WINAPI serveClientThreadProc(PCLDATA clData)
  3530. #else // Posix threads
  3531. static void *serveClientThreadProc (PCLDATA clData)
  3532. #endif // Thread proc is identical in WIN32 and Posix threads
  3533. {
  3534. serveClient(clData->socket, clData->RpcAssocGroup);
  3535. free(clData);
  3536. post_sem();
  3537. return 0;
  3538. }
  3539. #endif // USE_THREADS
  3540. #ifndef NO_SOCKETS
  3541. #if defined(USE_THREADS) && (defined(_WIN32) || defined(__CYGWIN__)) // Windows Threads
  3542. static int serveClientAsyncWinThreads(const PCLDATA thr_CLData)
  3543. {
  3544. wait_sem();
  3545. HANDLE h = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)serveClientThreadProc, thr_CLData, 0, NULL);
  3546. if (h)
  3547. CloseHandle(h);
  3548. else
  3549. {
  3550. socketclose(thr_CLData->socket);
  3551. free(thr_CLData);
  3552. post_sem();
  3553. return GetLastError();
  3554. }
  3555. return NO_ERROR;
  3556. }
  3557. #endif // defined(USE_THREADS) && defined(_WIN32) // Windows Threads
  3558. #if defined(USE_THREADS) && !defined(_WIN32) && !defined(__CYGWIN__) // Posix Threads
  3559. static int ServeClientAsyncPosixThreads(const PCLDATA thr_CLData)
  3560. {
  3561. pthread_t p_thr;
  3562. pthread_attr_t attr;
  3563. wait_sem();
  3564. // Must set detached state to avoid memory leak
  3565. if (pthread_attr_init(&attr) ||
  3566. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) ||
  3567. pthread_create(&p_thr, &attr, (void * (*)(void *))serveClientThreadProc, thr_CLData))
  3568. {
  3569. socketclose(thr_CLData->socket);
  3570. free(thr_CLData);
  3571. post_sem();
  3572. return !0;
  3573. }
  3574. return 0;
  3575. }
  3576. #endif // defined(USE_THREADS) && !defined(_WIN32) // Posix Threads
  3577. #ifndef USE_THREADS // fork() implementation
  3578. static void ChildSignalHandler(const int signal)
  3579. {
  3580. if (signal == SIGHUP) return;
  3581. post_sem();
  3582. #ifndef NO_LOG
  3583. logger("Warning: Child killed/crashed by %s\n", strsignal(signal));
  3584. #endif // NO_LOG
  3585. exit(!0);
  3586. }
  3587. static int ServeClientAsyncFork(const SOCKET s_client, const DWORD RpcAssocGroup)
  3588. {
  3589. int pid;
  3590. wait_sem();
  3591. if ((pid = fork()) < 0)
  3592. {
  3593. return errno;
  3594. }
  3595. else if ( pid )
  3596. {
  3597. // Parent process
  3598. socketclose(s_client);
  3599. return 0;
  3600. }
  3601. else
  3602. {
  3603. // Child process
  3604. // Setup a Child Handler for most common termination signals
  3605. struct sigaction sa;
  3606. sa.sa_flags = 0;
  3607. sa.sa_handler = ChildSignalHandler;
  3608. static int signallist[] = { SIGHUP, SIGINT, SIGTERM, SIGSEGV, SIGILL, SIGFPE, SIGBUS };
  3609. if (!sigemptyset(&sa.sa_mask))
  3610. {
  3611. uint_fast8_t i;
  3612. for (i = 0; i < _countof(signallist); i++)
  3613. {
  3614. sigaction(signallist[i], &sa, NULL);
  3615. }
  3616. }
  3617. serveClient(s_client, RpcAssocGroup);
  3618. post_sem();
  3619. exit(0);
  3620. }
  3621. }
  3622. #endif
  3623. int serveClientAsync(const SOCKET s_client, const DWORD RpcAssocGroup)
  3624. {
  3625. #ifndef USE_THREADS // fork() implementation
  3626. return ServeClientAsyncFork(s_client, RpcAssocGroup);
  3627. #else // threads implementation
  3628. PCLDATA thr_CLData = (PCLDATA)vlmcsd_malloc(sizeof(CLDATA));
  3629. thr_CLData->socket = s_client;
  3630. thr_CLData->RpcAssocGroup = RpcAssocGroup;
  3631. #if defined(_WIN32) || defined (__CYGWIN__) // Windows threads
  3632. return serveClientAsyncWinThreads(thr_CLData);
  3633. #else // Posix Threads
  3634. return ServeClientAsyncPosixThreads(thr_CLData);
  3635. #endif // Posix Threads
  3636. #endif // USE_THREADS
  3637. }
  3638. #endif // NO_SOCKETS
  3639. int runServer()
  3640. {
  3641. DWORD RpcAssocGroup = rand32();
  3642. // If compiled for inetd-only mode just serve the stdin socket
  3643. #ifdef NO_SOCKETS
  3644. serveClient(STDIN_FILENO, RpcAssocGroup);
  3645. return 0;
  3646. #else
  3647. // In inetd mode just handle the stdin socket
  3648. if (InetdMode)
  3649. {
  3650. serveClient(STDIN_FILENO, RpcAssocGroup);
  3651. return 0;
  3652. }
  3653. // Standalone mode
  3654. for (;;)
  3655. {
  3656. int error;
  3657. SOCKET s_client;
  3658. if ( (s_client = network_accept_any()) == INVALID_SOCKET )
  3659. {
  3660. error = socket_errno;
  3661. if (error == VLMCSD_EINTR || error == VLMCSD_ECONNABORTED) continue;
  3662. #ifdef _NTSERVICE
  3663. if (ServiceShutdown) return 0;
  3664. #endif
  3665. #ifndef NO_LOG
  3666. logger("Fatal: %s\n",vlmcsd_strerror(error));
  3667. #endif
  3668. return error;
  3669. }
  3670. RpcAssocGroup++;
  3671. serveClientAsync(s_client, RpcAssocGroup);
  3672. }
  3673. #endif // NO_SOCKETS
  3674. return 0;
  3675. }
  3676. #endif // USE_MSRPC
  3677. #ifndef _DEFAULT_SOURCE
  3678. #define _DEFAULT_SOURCE
  3679. #endif // _DEFAULT_SOURCE
  3680. #ifndef CONFIG
  3681. #define CONFIG "config.h"
  3682. #endif // CONFIG
  3683. #include CONFIG
  3684. #ifndef USE_MSRPC
  3685. #include <stdlib.h>
  3686. #include <stdio.h>
  3687. #include <string.h>
  3688. #include <stdint.h>
  3689. #include <ctype.h>
  3690. #include <time.h>
  3691. #if !defined(_WIN32)
  3692. #include <sys/socket.h>
  3693. #include <netdb.h>
  3694. #endif
  3695. #include "rpc.h"
  3696. #include "output.h"
  3697. #include "crypto.h"
  3698. #include "endian.h"
  3699. #include "helpers.h"
  3700. #include "network.h"
  3701. #include "shared_globals.h"
  3702. /* Forwards */
  3703. static int checkRpcHeader(const RPC_HEADER *const Header, const BYTE desiredPacketType, const PRINTFUNC p);
  3704. /* Data definitions */
  3705. // All GUIDs are defined as BYTE[16] here. No big-endian/little-endian byteswapping required.
  3706. static const BYTE TransferSyntaxNDR32[] = {
  3707. 0x04, 0x5D, 0x88, 0x8A, 0xEB, 0x1C, 0xC9, 0x11, 0x9F, 0xE8, 0x08, 0x00, 0x2B, 0x10, 0x48, 0x60
  3708. };
  3709. static const BYTE InterfaceUuid[] = {
  3710. 0x75, 0x21, 0xc8, 0x51, 0x4e, 0x84, 0x50, 0x47, 0xB0, 0xD8, 0xEC, 0x25, 0x55, 0x55, 0xBC, 0x06
  3711. };
  3712. static const BYTE TransferSyntaxNDR64[] = {
  3713. 0x33, 0x05, 0x71, 0x71, 0xba, 0xbe, 0x37, 0x49, 0x83, 0x19, 0xb5, 0xdb, 0xef, 0x9c, 0xcc, 0x36
  3714. };
  3715. static const BYTE BindTimeFeatureNegotiation[] = {
  3716. 0x2c, 0x1c, 0xb7, 0x6c, 0x12, 0x98, 0x40, 0x45, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  3717. };
  3718. //
  3719. // Dispatch RPC payload to kms.c
  3720. //
  3721. typedef int (*CreateResponse_t)(const void *const, void *const, const char* const);
  3722. static const struct {
  3723. unsigned int RequestSize;
  3724. CreateResponse_t CreateResponse;
  3725. } _Versions[] = {
  3726. { sizeof(REQUEST_V4), (CreateResponse_t) CreateResponseV4 },
  3727. { sizeof(REQUEST_V6), (CreateResponse_t) CreateResponseV6 },
  3728. { sizeof(REQUEST_V6), (CreateResponse_t) CreateResponseV6 }
  3729. };
  3730. RPC_FLAGS RpcFlags;
  3731. static int_fast8_t firstPacketSent;
  3732. //
  3733. // RPC request (server)
  3734. //
  3735. #if defined(_PEDANTIC) && !defined(NO_LOG)
  3736. static void CheckRpcRequest(const RPC_REQUEST64 *const Request, const unsigned int len, WORD* NdrCtx, WORD* Ndr64Ctx, WORD Ctx)
  3737. {
  3738. uint_fast8_t kmsMajorVersion;
  3739. uint32_t requestSize = Ctx != *Ndr64Ctx ? sizeof(RPC_REQUEST) : sizeof(RPC_REQUEST64);
  3740. if (len < requestSize)
  3741. {
  3742. logger("Fatal: RPC request (including header) must be at least %i bytes but is only %i bytes.\n",
  3743. (int)(sizeof(RPC_HEADER) + requestSize),
  3744. (int)(len + sizeof(RPC_HEADER))
  3745. );
  3746. return;
  3747. }
  3748. if (len < requestSize + sizeof(DWORD))
  3749. {
  3750. logger("Fatal: KMS Request too small to contain version info (less than 4 bytes).\n");
  3751. return;
  3752. }
  3753. if (Ctx != *Ndr64Ctx)
  3754. kmsMajorVersion = LE16(((WORD*)Request->Ndr.Data)[1]);
  3755. else
  3756. kmsMajorVersion = LE16(((WORD*)Request->Ndr64.Data)[1]);
  3757. if (kmsMajorVersion > 6)
  3758. {
  3759. logger("Fatal: KMSv%u is not supported.\n", (unsigned int)kmsMajorVersion);
  3760. }
  3761. else
  3762. {
  3763. if (len >_Versions[kmsMajorVersion].RequestSize + requestSize)
  3764. logger("Warning: %u excess bytes in RPC request.\n",
  3765. len - _Versions[kmsMajorVersion].RequestSize
  3766. );
  3767. }
  3768. if (Ctx != *Ndr64Ctx && Ctx != *NdrCtx)
  3769. logger("Warning: Context id should be %u (NDR32) or %u (NDR64) but is %u.\n",
  3770. (unsigned int)*NdrCtx,
  3771. (unsigned int)*Ndr64Ctx,
  3772. Ctx
  3773. );
  3774. if (Request->Opnum)
  3775. logger("Warning: OpNum should be 0 but is %u.\n",
  3776. (unsigned int)LE16(Request->Opnum)
  3777. );
  3778. if (LE32(Request->AllocHint) != len - sizeof(RPC_REQUEST) + sizeof(Request->Ndr))
  3779. logger("Warning: Allocation hint should be %u but is %u.\n",
  3780. len + sizeof(Request->Ndr),
  3781. LE32(Request->AllocHint)
  3782. );
  3783. if (Ctx != *Ndr64Ctx)
  3784. {
  3785. if (LE32(Request->Ndr.DataLength) != len - sizeof(RPC_REQUEST))
  3786. logger("Warning: NDR32 data length field should be %u but is %u.\n",
  3787. len - sizeof(RPC_REQUEST),
  3788. LE32(Request->Ndr.DataLength)
  3789. );
  3790. if (LE32(Request->Ndr.DataSizeIs) != len - sizeof(RPC_REQUEST))
  3791. logger("Warning: NDR32 data size field should be %u but is %u.\n",
  3792. len - sizeof(RPC_REQUEST),
  3793. LE32(Request->Ndr.DataSizeIs)
  3794. );
  3795. }
  3796. else
  3797. {
  3798. if (LE64(Request->Ndr64.DataLength) != len - sizeof(RPC_REQUEST64))
  3799. logger("Warning: NDR32 data length field should be %u but is %u.\n",
  3800. len - sizeof(RPC_REQUEST) + sizeof(Request->Ndr),
  3801. LE64(Request->Ndr64.DataLength)
  3802. );
  3803. if (LE64(Request->Ndr64.DataSizeIs) != len - sizeof(RPC_REQUEST64))
  3804. logger("Warning: NDR32 data size field should be %u but is %u.\n",
  3805. len - sizeof(RPC_REQUEST64),
  3806. LE64(Request->Ndr64.DataSizeIs)
  3807. );
  3808. }
  3809. }
  3810. #endif // defined(_PEDANTIC) && !defined(NO_LOG)
  3811. /*
  3812. * check RPC request for (somewhat) correct size
  3813. * allow any size that does not cause CreateResponse to fail badly
  3814. */
  3815. static unsigned int checkRpcRequestSize(const RPC_REQUEST64 *const Request, const unsigned int requestSize, WORD* NdrCtx, WORD* Ndr64Ctx)
  3816. {
  3817. WORD Ctx = LE16(Request->ContextId);
  3818. # if defined(_PEDANTIC) && !defined(NO_LOG)
  3819. CheckRpcRequest(Request, requestSize, NdrCtx, Ndr64Ctx, Ctx);
  3820. # endif // defined(_PEDANTIC) && !defined(NO_LOG)
  3821. // Anything that is smaller than a v4 request is illegal
  3822. if (requestSize < sizeof(REQUEST_V4) + (Ctx != *Ndr64Ctx ? sizeof(RPC_REQUEST) : sizeof(RPC_REQUEST64))) return 0;
  3823. // Get KMS major version
  3824. uint_fast16_t _v;
  3825. if (Ctx != *Ndr64Ctx)
  3826. _v = LE16(((WORD*)Request->Ndr.Data)[1]) - 4;
  3827. else
  3828. _v = LE16(((WORD*)Request->Ndr64.Data)[1]) - 4;
  3829. // Only KMS v4, v5 and v6 are supported
  3830. if (_v >= vlmcsd_countof(_Versions))
  3831. {
  3832. # ifndef NO_LOG
  3833. logger("Fatal: KMSv%i unsupported\n", _v + 4);
  3834. # endif // NO_LOG
  3835. return 0;
  3836. }
  3837. // Could check for equality but allow bigger requests to support buggy RPC clients (e.g. wine)
  3838. // Buffer overrun is check by caller.
  3839. return (requestSize >= _Versions[_v].RequestSize);
  3840. }
  3841. /*
  3842. * Handles the actual KMS request from the client.
  3843. * Calls KMS functions (CreateResponseV4 or CreateResponseV6) in kms.c
  3844. * Returns size of the KMS response packet or 0 on failure.
  3845. *
  3846. * The RPC packet size (excluding header) is actually in Response->AllocHint
  3847. */
  3848. static int rpcRequest(const RPC_REQUEST64 *const Request, RPC_RESPONSE64 *const Response, const DWORD RpcAssocGroup_unused, const SOCKET sock_unused, WORD* NdrCtx, WORD* Ndr64Ctx, BYTE packetType, const char* const ipstr)
  3849. {
  3850. uint_fast16_t _v;
  3851. int ResponseSize;
  3852. WORD Ctx = LE16(Request->ContextId);
  3853. BYTE* requestData;
  3854. BYTE* responseData;
  3855. BYTE* pRpcReturnCode;
  3856. int len;
  3857. if (Ctx != *Ndr64Ctx)
  3858. {
  3859. requestData = (BYTE*)&Request->Ndr.Data;
  3860. responseData = (BYTE*)&Response->Ndr.Data;
  3861. }
  3862. else
  3863. {
  3864. requestData = (BYTE*)&Request->Ndr64.Data;
  3865. responseData = (BYTE*)&Response->Ndr64.Data;
  3866. }
  3867. _v = LE16(((WORD*)requestData)[1]) - 4;
  3868. if (!(ResponseSize = _Versions[_v].CreateResponse(requestData, responseData, ipstr)))
  3869. {
  3870. return 0;
  3871. }
  3872. if (Ctx != *Ndr64Ctx)
  3873. {
  3874. Response->Ndr.DataSizeMax = LE32(0x00020000);
  3875. Response->Ndr.DataLength = Response->Ndr.DataSizeIs = LE32(ResponseSize);
  3876. len = ResponseSize + sizeof(Response->Ndr);
  3877. }
  3878. else
  3879. {
  3880. Response->Ndr64.DataSizeMax = LE64(0x00020000ULL);
  3881. Response->Ndr64.DataLength = Response->Ndr64.DataSizeIs = LE64((uint64_t)ResponseSize);
  3882. len = ResponseSize + sizeof(Response->Ndr64);
  3883. }
  3884. pRpcReturnCode = ((BYTE*)&Response->Ndr) + len;
  3885. UA32(pRpcReturnCode) = 0; //LE32 not needed for 0
  3886. len += sizeof(DWORD);
  3887. // Pad zeros to 32-bit align (seems not neccassary but Windows RPC does it this way)
  3888. int pad = ((~len & 3) + 1) & 3;
  3889. memset(pRpcReturnCode + sizeof(DWORD), 0, pad);
  3890. len += pad;
  3891. Response->AllocHint = LE32(len);
  3892. Response->ContextId = Request->ContextId;
  3893. *((WORD*)&Response->CancelCount) = 0; // CancelCount + Pad1
  3894. return len + 8;
  3895. }
  3896. #if defined(_PEDANTIC) && !defined(NO_LOG)
  3897. static void CheckRpcBindRequest(const RPC_BIND_REQUEST *const Request, const unsigned int len)
  3898. {
  3899. uint_fast8_t i, HasTransferSyntaxNDR32 = FALSE;
  3900. char guidBuffer1[GUID_STRING_LENGTH + 1], guidBuffer2[GUID_STRING_LENGTH + 1];
  3901. uint32_t CapCtxItems = (len - sizeof(*Request) + sizeof(Request->CtxItems)) / sizeof(Request->CtxItems);
  3902. DWORD NumCtxItems = LE32(Request->NumCtxItems);
  3903. if (NumCtxItems < CapCtxItems) // Can't be too small because already handled by RpcBindSize
  3904. logger("Warning: Excess bytes in RPC bind request.\n");
  3905. for (i = 0; i < NumCtxItems; i++)
  3906. {
  3907. if (!IsEqualGUID(&Request->CtxItems[i].InterfaceUUID, InterfaceUuid))
  3908. {
  3909. uuid2StringLE((GUID*)&Request->CtxItems[i].InterfaceUUID, guidBuffer1);
  3910. uuid2StringLE((GUID*)InterfaceUuid, guidBuffer2);
  3911. logger("Warning: Interface UUID is %s but should be %s in Ctx item %u.\n", guidBuffer1, guidBuffer2, (unsigned int)i);
  3912. }
  3913. if (Request->CtxItems[i].NumTransItems != LE16(1))
  3914. logger("Fatal: %u NDR32 transfer items detected in Ctx item %u, but only one is supported.\n",
  3915. (unsigned int)LE16(Request->CtxItems[i].NumTransItems), (unsigned int)i
  3916. );
  3917. if (Request->CtxItems[i].InterfaceVerMajor != LE16(1) || Request->CtxItems[i].InterfaceVerMinor != 0)
  3918. logger("Warning: NDR32 Interface version is %u.%u but should be 1.0.\n",
  3919. (unsigned int)LE16(Request->CtxItems[i].InterfaceVerMajor),
  3920. (unsigned int)LE16(Request->CtxItems[i].InterfaceVerMinor)
  3921. );
  3922. if (Request->CtxItems[i].ContextId != LE16((WORD)i))
  3923. logger("Warning: context id of Ctx item %u is %u.\n", (unsigned int)i, (unsigned int)Request->CtxItems[i].ContextId);
  3924. if ( IsEqualGUID((GUID*)TransferSyntaxNDR32, &Request->CtxItems[i].TransferSyntax) )
  3925. {
  3926. HasTransferSyntaxNDR32 = TRUE;
  3927. if (Request->CtxItems[i].SyntaxVersion != LE32(2))
  3928. logger("NDR32 transfer syntax version is %u but should be 2.\n", LE32(Request->CtxItems[i].SyntaxVersion));
  3929. }
  3930. else if ( IsEqualGUID((GUID*)TransferSyntaxNDR64, &Request->CtxItems[i].TransferSyntax) )
  3931. {
  3932. if (Request->CtxItems[i].SyntaxVersion != LE32(1))
  3933. logger("NDR64 transfer syntax version is %u but should be 1.\n", LE32(Request->CtxItems[i].SyntaxVersion));
  3934. }
  3935. else if (!memcmp(BindTimeFeatureNegotiation, (BYTE*)(&Request->CtxItems[i].TransferSyntax), 8))
  3936. {
  3937. if (Request->CtxItems[i].SyntaxVersion != LE32(1))
  3938. logger("BTFN syntax version is %u but should be 1.\n", LE32(Request->CtxItems[i].SyntaxVersion));
  3939. }
  3940. }
  3941. if (!HasTransferSyntaxNDR32)
  3942. logger("Warning: RPC bind request has no NDR32 CtxItem.\n");
  3943. }
  3944. #endif // defined(_PEDANTIC) && !defined(NO_LOG)
  3945. /*
  3946. * Check, if we receive enough bytes to return a valid RPC bind response
  3947. */
  3948. static unsigned int checkRpcBindSize(const RPC_BIND_REQUEST *const Request, const unsigned int RequestSize, WORD* NdrCtx, WORD* Ndr64Ctx)
  3949. {
  3950. if ( RequestSize < sizeof(RPC_BIND_REQUEST) ) return FALSE;
  3951. unsigned int _NumCtxItems = LE32(Request->NumCtxItems);
  3952. if ( RequestSize < sizeof(RPC_BIND_REQUEST) - sizeof(Request->CtxItems[0]) + _NumCtxItems * sizeof(Request->CtxItems[0]) ) return FALSE;
  3953. #if defined(_PEDANTIC) && !defined(NO_LOG)
  3954. CheckRpcBindRequest(Request, RequestSize);
  3955. #endif // defined(_PEDANTIC) && !defined(NO_LOG)
  3956. return TRUE;
  3957. }
  3958. /*
  3959. * Accepts a bind or alter context request from the client and composes the bind response.
  3960. * Needs the socket because the tcp port number is part of the response.
  3961. * len is not used here.
  3962. *
  3963. * Returns TRUE on success.
  3964. */
  3965. static int rpcBind(const RPC_BIND_REQUEST *const Request, RPC_BIND_RESPONSE* Response, const DWORD RpcAssocGroup, const SOCKET sock, WORD* NdrCtx, WORD* Ndr64Ctx, BYTE packetType, const char* const ipstr_unused)
  3966. {
  3967. unsigned int i, _st = FALSE;
  3968. DWORD numCtxItems = LE32(Request->NumCtxItems);
  3969. int_fast8_t IsNDR64possible = FALSE;
  3970. uint_fast8_t portNumberSize;
  3971. socklen_t socklen;
  3972. struct sockaddr_storage addr;
  3973. // M$ RPC does not do this. Pad bytes contain apparently random data
  3974. // memset(Response->SecondaryAddress, 0, sizeof(Response->SecondaryAddress));
  3975. socklen = sizeof addr;
  3976. if (
  3977. packetType == RPC_PT_ALTERCONTEXT_REQ ||
  3978. getsockname(sock, (struct sockaddr*)&addr, &socklen) ||
  3979. getnameinfo((struct sockaddr*)&addr, socklen, NULL, 0, (char*)Response->SecondaryAddress, sizeof(Response->SecondaryAddress), NI_NUMERICSERV))
  3980. {
  3981. portNumberSize = Response->SecondaryAddressLength = 0;
  3982. }
  3983. else
  3984. {
  3985. portNumberSize = strlen((char*)Response->SecondaryAddress) + 1;
  3986. Response->SecondaryAddressLength = LE16(portNumberSize);
  3987. }
  3988. Response->MaxXmitFrag = Request->MaxXmitFrag;
  3989. Response->MaxRecvFrag = Request->MaxRecvFrag;
  3990. Response->AssocGroup = LE32(RpcAssocGroup);
  3991. // This is really ugly (but efficient) code to support padding after the secondary address field
  3992. if (portNumberSize < 3)
  3993. {
  3994. Response = (RPC_BIND_RESPONSE*)((BYTE*)Response - 4);
  3995. }
  3996. Response->NumResults = Request->NumCtxItems;
  3997. if (UseRpcNDR64)
  3998. {
  3999. for (i = 0; i < numCtxItems; i++)
  4000. {
  4001. if ( IsEqualGUID((GUID*)TransferSyntaxNDR32, &Request->CtxItems[i].TransferSyntax) )
  4002. {
  4003. /*if (packetType == RPC_PT_BIND_REQ)*/
  4004. *NdrCtx = LE16(Request->CtxItems[i].ContextId);
  4005. }
  4006. if ( IsEqualGUID((GUID*)TransferSyntaxNDR64, &Request->CtxItems[i].TransferSyntax) )
  4007. {
  4008. IsNDR64possible = TRUE;
  4009. /*if (packetType == RPC_PT_BIND_REQ)*/
  4010. *Ndr64Ctx = LE16(Request->CtxItems[i].ContextId);
  4011. }
  4012. }
  4013. }
  4014. for (i = 0; i < numCtxItems; i++)
  4015. {
  4016. memset(&Response->Results[i].TransferSyntax, 0, sizeof(GUID));
  4017. if ( !IsNDR64possible && IsEqualGUID((GUID*)TransferSyntaxNDR32, &Request->CtxItems[i].TransferSyntax) )
  4018. {
  4019. Response->Results[i].SyntaxVersion = LE32(2);
  4020. Response->Results[i].AckResult =
  4021. Response->Results[i].AckReason = RPC_BIND_ACCEPT;
  4022. memcpy(&Response->Results[i].TransferSyntax, TransferSyntaxNDR32, sizeof(GUID));
  4023. _st = TRUE;
  4024. }
  4025. else if ( IsNDR64possible && IsEqualGUID((GUID*)TransferSyntaxNDR64, &Request->CtxItems[i].TransferSyntax) )
  4026. {
  4027. Response->Results[i].SyntaxVersion = LE32(1);
  4028. Response->Results[i].AckResult =
  4029. Response->Results[i].AckReason = RPC_BIND_ACCEPT;
  4030. memcpy(&Response->Results[i].TransferSyntax, TransferSyntaxNDR64, sizeof(GUID));
  4031. _st = TRUE;
  4032. }
  4033. else if ( UseRpcBTFN && !memcmp(BindTimeFeatureNegotiation, (BYTE*)(&Request->CtxItems[i].TransferSyntax), 8) )
  4034. {
  4035. Response->Results[i].SyntaxVersion = 0;
  4036. Response->Results[i].AckResult = RPC_BIND_ACK;
  4037. // Features requested are actually encoded in the GUID
  4038. Response->Results[i].AckReason =
  4039. ((WORD*)(&Request->CtxItems[i].TransferSyntax))[4] &
  4040. (RPC_BTFN_SEC_CONTEXT_MULTIPLEX | RPC_BTFN_KEEP_ORPHAN);
  4041. }
  4042. else
  4043. {
  4044. Response->Results[i].SyntaxVersion = 0;
  4045. Response->Results[i].AckResult =
  4046. Response->Results[i].AckReason = RPC_BIND_NACK; // Unsupported
  4047. }
  4048. }
  4049. if ( !_st ) return 0;
  4050. return sizeof(RPC_BIND_RESPONSE) + numCtxItems * sizeof(((RPC_BIND_RESPONSE *)0)->Results[0]) - (portNumberSize < 3 ? 4 : 0);
  4051. }
  4052. //
  4053. // Main RPC handling routine
  4054. //
  4055. typedef unsigned int (*GetResponseSize_t)(const void *const request, const unsigned int requestSize, WORD* NdrCtx, WORD* Ndr64Ctx);
  4056. typedef int (*GetResponse_t)(const void* const request, void* response, const DWORD rpcAssocGroup, const SOCKET socket, WORD* NdrCtx, WORD* Ndr64Ctx, BYTE packetType, const char* const ipstr);
  4057. static const struct {
  4058. BYTE ResponsePacketType;
  4059. GetResponseSize_t CheckRequestSize;
  4060. GetResponse_t GetResponse;
  4061. }
  4062. _Actions[] = {
  4063. { RPC_PT_BIND_ACK, (GetResponseSize_t)checkRpcBindSize, (GetResponse_t) rpcBind },
  4064. { RPC_PT_RESPONSE, (GetResponseSize_t)checkRpcRequestSize, (GetResponse_t) rpcRequest },
  4065. { RPC_PT_ALTERCONTEXT_ACK, (GetResponseSize_t)checkRpcBindSize, (GetResponse_t) rpcBind },
  4066. };
  4067. /*
  4068. * This is the main RPC server loop. Returns after KMS request has been serviced
  4069. * or a timeout has occured.
  4070. */
  4071. void rpcServer(const SOCKET sock, const DWORD RpcAssocGroup, const char* const ipstr)
  4072. {
  4073. RPC_HEADER rpcRequestHeader;
  4074. WORD NdrCtx = INVALID_NDR_CTX, Ndr64Ctx = INVALID_NDR_CTX;
  4075. randomNumberInit();
  4076. while (_recv(sock, &rpcRequestHeader, sizeof(rpcRequestHeader)))
  4077. {
  4078. //int_fast8_t _st;
  4079. unsigned int request_len, response_len;
  4080. uint_fast8_t _a;
  4081. #if defined(_PEDANTIC) && !defined(NO_LOG)
  4082. checkRpcHeader(&rpcRequestHeader, rpcRequestHeader.PacketType, &logger);
  4083. #endif // defined(_PEDANTIC) && !defined(NO_LOG)
  4084. switch (rpcRequestHeader.PacketType)
  4085. {
  4086. case RPC_PT_BIND_REQ: _a = 0; break;
  4087. case RPC_PT_REQUEST: _a = 1; break;
  4088. case RPC_PT_ALTERCONTEXT_REQ: _a = 2; break;
  4089. default: return;
  4090. }
  4091. request_len = LE16(rpcRequestHeader.FragLength) - sizeof(rpcRequestHeader);
  4092. BYTE requestBuffer[MAX_REQUEST_SIZE + sizeof(RPC_RESPONSE64)];
  4093. BYTE responseBuffer[MAX_RESPONSE_SIZE + sizeof(RPC_HEADER) + sizeof(RPC_RESPONSE64)];
  4094. RPC_HEADER *rpcResponseHeader = (RPC_HEADER *)responseBuffer;
  4095. RPC_RESPONSE* rpcResponse = (RPC_RESPONSE*)(responseBuffer + sizeof(rpcRequestHeader));
  4096. // The request is larger than the buffer size
  4097. if (request_len > MAX_REQUEST_SIZE + sizeof(RPC_REQUEST64)) return;
  4098. // Unable to receive the complete request
  4099. if (!_recv(sock, requestBuffer, request_len)) return;
  4100. // Request is invalid
  4101. if (!_Actions[_a].CheckRequestSize(requestBuffer, request_len, &NdrCtx, &Ndr64Ctx)) return;
  4102. // Unable to create a valid response from request
  4103. if (!(response_len = _Actions[_a].GetResponse(requestBuffer, rpcResponse, RpcAssocGroup, sock, &NdrCtx, &Ndr64Ctx, rpcRequestHeader.PacketType, ipstr))) return;
  4104. response_len += sizeof(RPC_HEADER);
  4105. memcpy(rpcResponseHeader, &rpcRequestHeader, sizeof(RPC_HEADER));
  4106. rpcResponseHeader->FragLength = LE16(response_len);
  4107. rpcResponseHeader->PacketType = _Actions[_a].ResponsePacketType;
  4108. if (rpcResponseHeader->PacketType == RPC_PT_ALTERCONTEXT_ACK)
  4109. rpcResponseHeader->PacketFlags = RPC_PF_FIRST | RPC_PF_LAST;
  4110. if (!_send(sock, responseBuffer, response_len)) return;
  4111. if (DisconnectImmediately && rpcResponseHeader->PacketType == RPC_PT_RESPONSE)
  4112. shutdown(sock, VLMCSD_SHUT_RDWR);
  4113. }
  4114. }
  4115. /* RPC client functions */
  4116. static DWORD CallId = 2; // M$ starts with CallId 2. So we do the same.
  4117. /*
  4118. * Checks RPC header. Returns 0 on success.
  4119. * This is mainly for debugging a non Microsoft KMS server that uses its own RPC code.
  4120. */
  4121. static int checkRpcHeader(const RPC_HEADER *const Header, const BYTE desiredPacketType, const PRINTFUNC p)
  4122. {
  4123. int status = 0;
  4124. if (Header->PacketType != desiredPacketType)
  4125. {
  4126. p("Fatal: Received wrong RPC packet type. Expected %u but got %u\n",
  4127. (uint32_t)desiredPacketType,
  4128. Header->PacketType
  4129. );
  4130. status = !0;
  4131. }
  4132. if (Header->DataRepresentation != BE32(0x10000000))
  4133. {
  4134. p("Fatal: RPC response does not conform to Microsoft's limited support of DCE RPC\n");
  4135. status = !0;
  4136. }
  4137. if (Header->AuthLength != 0)
  4138. {
  4139. p("Fatal: RPC response requests authentication\n");
  4140. status = !0;
  4141. }
  4142. // vlmcsd does not support fragmented packets (not yet neccassary)
  4143. if ( (Header->PacketFlags & (RPC_PF_FIRST | RPC_PF_LAST)) != (RPC_PF_FIRST | RPC_PF_LAST) )
  4144. {
  4145. p("Fatal: RPC packet flags RPC_PF_FIRST and RPC_PF_LAST are not both set.\n");
  4146. status = !0;
  4147. }
  4148. if (Header->PacketFlags & RPC_PF_CANCEL_PENDING) p("Warning: %s should not be set\n", "RPC_PF_CANCEL_PENDING");
  4149. if (Header->PacketFlags & RPC_PF_RESERVED) p("Warning: %s should not be set\n", "RPC_PF_RESERVED");
  4150. if (Header->PacketFlags & RPC_PF_NOT_EXEC) p("Warning: %s should not be set\n", "RPC_PF_NOT_EXEC");
  4151. if (Header->PacketFlags & RPC_PF_MAYBE) p("Warning: %s should not be set\n", "RPC_PF_MAYBE");
  4152. if (Header->PacketFlags & RPC_PF_OBJECT) p("Warning: %s should not be set\n", "RPC_PF_OBJECT");
  4153. if (Header->VersionMajor != 5 || Header->VersionMinor != 0)
  4154. {
  4155. p("Fatal: Expected RPC version 5.0 and got %u.%u\n", Header->VersionMajor, Header->VersionMinor);
  4156. status = !0;
  4157. }
  4158. return status;
  4159. }
  4160. /*
  4161. * Checks an RPC response header. Does basic header checks by calling checkRpcHeader()
  4162. * and then does additional checks if response header complies with the respective request header.
  4163. * PRINTFUNC p can be anything that has the same prototype as printf.
  4164. * Returns 0 on success.
  4165. */
  4166. static int checkRpcResponseHeader(const RPC_HEADER *const ResponseHeader, const RPC_HEADER *const RequestHeader, const BYTE desiredPacketType, const PRINTFUNC p)
  4167. {
  4168. static int_fast8_t WineBugDetected = FALSE;
  4169. int status = checkRpcHeader(ResponseHeader, desiredPacketType, p);
  4170. if (desiredPacketType == RPC_PT_BIND_ACK)
  4171. {
  4172. if ((ResponseHeader->PacketFlags & RPC_PF_MULTIPLEX) != (RequestHeader->PacketFlags & RPC_PF_MULTIPLEX))
  4173. {
  4174. p("Warning: RPC_PF_MULTIPLEX of RPC request and response should match\n");
  4175. }
  4176. }
  4177. else
  4178. {
  4179. if (ResponseHeader->PacketFlags & RPC_PF_MULTIPLEX)
  4180. {
  4181. p("Warning: %s should not be set\n", "RPC_PF_MULTIPLEX");
  4182. }
  4183. }
  4184. if (!status && ResponseHeader->CallId == LE32(1))
  4185. {
  4186. if (!WineBugDetected)
  4187. {
  4188. p("Warning: Buggy RPC of Wine detected. Call Id of Response is always 1\n");
  4189. WineBugDetected = TRUE;
  4190. }
  4191. }
  4192. else if (ResponseHeader->CallId != RequestHeader->CallId)
  4193. {
  4194. p("Fatal: Sent Call Id %u but received answer for Call Id %u\n",
  4195. (uint32_t)LE32(RequestHeader->CallId),
  4196. (uint32_t)LE32(ResponseHeader->CallId)
  4197. );
  4198. status = !0;
  4199. }
  4200. return status;
  4201. }
  4202. /*
  4203. * Initializes an RPC request header as needed for KMS, i.e. packet always fits in one fragment.
  4204. * size cannot be greater than fragment length negotiated during RPC bind.
  4205. */
  4206. static void createRpcRequestHeader(RPC_HEADER* RequestHeader, BYTE packetType, WORD size)
  4207. {
  4208. RequestHeader->PacketType = packetType;
  4209. RequestHeader->PacketFlags = RPC_PF_FIRST | RPC_PF_LAST;
  4210. RequestHeader->VersionMajor = 5;
  4211. RequestHeader->VersionMinor = 0;
  4212. RequestHeader->AuthLength = 0;
  4213. RequestHeader->DataRepresentation = BE32(0x10000000); // Little endian, ASCII charset, IEEE floating point
  4214. RequestHeader->CallId = LE32(CallId);
  4215. RequestHeader->FragLength = LE16(size);
  4216. }
  4217. /*
  4218. * Sends a KMS request via RPC and receives a response.
  4219. * Parameters are raw (encrypted) reqeuests / responses.
  4220. * Returns 0 on success.
  4221. */
  4222. RpcStatus rpcSendRequest(const RpcCtx sock, const BYTE *const KmsRequest, const size_t requestSize, BYTE **KmsResponse, size_t *const responseSize)
  4223. {
  4224. #define MAX_EXCESS_BYTES 16
  4225. RPC_HEADER *RequestHeader, ResponseHeader;
  4226. RPC_REQUEST64 *RpcRequest;
  4227. RPC_RESPONSE64 _Response;
  4228. int status = 0;
  4229. int_fast8_t useNdr64 = UseRpcNDR64 && firstPacketSent;
  4230. size_t size = sizeof(RPC_HEADER) + (useNdr64 ? sizeof(RPC_REQUEST64) : sizeof(RPC_REQUEST)) + requestSize;
  4231. size_t responseSize2;
  4232. *KmsResponse = NULL;
  4233. BYTE *_Request = (BYTE*)vlmcsd_malloc(size);
  4234. RequestHeader = (RPC_HEADER*)_Request;
  4235. RpcRequest = (RPC_REQUEST64*)(_Request + sizeof(RPC_HEADER));
  4236. createRpcRequestHeader(RequestHeader, RPC_PT_REQUEST, size);
  4237. // Increment CallId for next Request
  4238. CallId++;
  4239. RpcRequest->Opnum = 0;
  4240. if (useNdr64)
  4241. {
  4242. RpcRequest->ContextId = LE16(1); // We negotiate NDR64 always as context 1
  4243. RpcRequest->AllocHint = LE32(requestSize + sizeof(RpcRequest->Ndr64));
  4244. RpcRequest->Ndr64.DataLength = LE64((uint64_t)requestSize);
  4245. RpcRequest->Ndr64.DataSizeIs = LE64((uint64_t)requestSize);
  4246. memcpy(RpcRequest->Ndr64.Data, KmsRequest, requestSize);
  4247. }
  4248. else
  4249. {
  4250. RpcRequest->ContextId = 0; // We negotiate NDR32 always as context 0
  4251. RpcRequest->AllocHint = LE32(requestSize + sizeof(RpcRequest->Ndr));
  4252. RpcRequest->Ndr.DataLength = LE32(requestSize);
  4253. RpcRequest->Ndr.DataSizeIs = LE32(requestSize);
  4254. memcpy(RpcRequest->Ndr.Data, KmsRequest, requestSize);
  4255. }
  4256. for(;;)
  4257. {
  4258. int bytesread;
  4259. if (!_send(sock, _Request, size))
  4260. {
  4261. errorout("\nFatal: Could not send RPC request\n");
  4262. status = !0;
  4263. break;
  4264. }
  4265. if (!_recv(sock, &ResponseHeader, sizeof(RPC_HEADER)))
  4266. {
  4267. errorout("\nFatal: No RPC response received from server\n");
  4268. status = !0;
  4269. break;
  4270. }
  4271. if ((status = checkRpcResponseHeader(&ResponseHeader, RequestHeader, RPC_PT_RESPONSE, &errorout))) break;
  4272. size = useNdr64 ? sizeof(RPC_RESPONSE64) : sizeof(RPC_RESPONSE);
  4273. if (size > LE16(ResponseHeader.FragLength) - sizeof(ResponseHeader))
  4274. size = LE16(ResponseHeader.FragLength) - sizeof(ResponseHeader);
  4275. if (!_recv(sock, &_Response, size))
  4276. {
  4277. errorout("\nFatal: RPC response is incomplete\n");
  4278. status = !0;
  4279. break;
  4280. }
  4281. if (_Response.CancelCount != 0)
  4282. {
  4283. errorout("\nFatal: RPC response cancel count is not 0\n");
  4284. status = !0;
  4285. }
  4286. if (_Response.ContextId != (useNdr64 ? LE16(1) : 0))
  4287. {
  4288. errorout("\nFatal: RPC response context id %u is not bound\n", (unsigned int)LE16(_Response.ContextId));
  4289. status = !0;
  4290. }
  4291. int_fast8_t sizesMatch;
  4292. if (useNdr64)
  4293. {
  4294. *responseSize = (size_t)LE64(_Response.Ndr64.DataLength);
  4295. responseSize2 = (size_t)LE64(_Response.Ndr64.DataSizeIs);
  4296. if (!*responseSize || !_Response.Ndr64.DataSizeMax)
  4297. {
  4298. status = (int)LE32(_Response.Ndr64.status);
  4299. break;
  4300. }
  4301. sizesMatch = (size_t)LE64(_Response.Ndr64.DataLength) == responseSize2;
  4302. }
  4303. else
  4304. {
  4305. *responseSize = (size_t)LE32(_Response.Ndr.DataLength);
  4306. responseSize2 = (size_t)LE32(_Response.Ndr.DataSizeIs);
  4307. if (!*responseSize || !_Response.Ndr.DataSizeMax)
  4308. {
  4309. status = (int)LE32(_Response.Ndr.status);
  4310. break;
  4311. }
  4312. sizesMatch = (size_t)LE32(_Response.Ndr.DataLength) == responseSize2;
  4313. }
  4314. if (!sizesMatch)
  4315. {
  4316. errorout("\nFatal: NDR data length (%u) does not match NDR data size (%u)\n",
  4317. (uint32_t)*responseSize,
  4318. (uint32_t)LE32(_Response.Ndr.DataSizeIs)
  4319. );
  4320. status = !0;
  4321. }
  4322. *KmsResponse = (BYTE*)vlmcsd_malloc(*responseSize + MAX_EXCESS_BYTES);
  4323. // If RPC stub is too short, assume missing bytes are zero (same ill behavior as MS RPC)
  4324. memset(*KmsResponse, 0, *responseSize + MAX_EXCESS_BYTES);
  4325. // Read up to 16 bytes more than bytes expected to detect faulty KMS emulators
  4326. if ((bytesread = recv(sock, (char*)*KmsResponse, *responseSize + MAX_EXCESS_BYTES, 0)) < (int)*responseSize)
  4327. {
  4328. errorout("\nFatal: No or incomplete KMS response received. Required %u bytes but only got %i\n",
  4329. (uint32_t)*responseSize,
  4330. (int32_t)(bytesread < 0 ? 0 : bytesread)
  4331. );
  4332. status = !0;
  4333. break;
  4334. }
  4335. DWORD *pReturnCode;
  4336. size_t len = *responseSize + (useNdr64 ? sizeof(_Response.Ndr64) : sizeof(_Response.Ndr)) + sizeof(*pReturnCode);
  4337. size_t pad = ((~len & 3) + 1) & 3;
  4338. if (len + pad != LE32(_Response.AllocHint))
  4339. {
  4340. errorout("\nWarning: RPC stub size is %u, should be %u (probably incorrect padding)\n", (uint32_t)LE32(_Response.AllocHint), (uint32_t)(len + pad));
  4341. }
  4342. else
  4343. {
  4344. size_t i;
  4345. for (i = 0; i < pad; i++)
  4346. {
  4347. if (*(*KmsResponse + *responseSize + sizeof(*pReturnCode) + i))
  4348. {
  4349. errorout("\nWarning: RPC stub data not padded to zeros according to Microsoft standard\n");
  4350. break;
  4351. }
  4352. }
  4353. }
  4354. pReturnCode = (DWORD*)(*KmsResponse + *responseSize + pad);
  4355. status = LE32(UA32(pReturnCode));
  4356. if (status) errorout("\nWarning: RPC stub data reported Error %u\n", (uint32_t)status);
  4357. break;
  4358. }
  4359. free(_Request);
  4360. firstPacketSent = TRUE;
  4361. return status;
  4362. #undef MAX_EXCESS_BYTES
  4363. }
  4364. static int_fast8_t IsNullGuid(BYTE* guidPtr)
  4365. {
  4366. int_fast8_t i;
  4367. for (i = 0; i < 16; i++)
  4368. {
  4369. if (guidPtr[i]) return FALSE;
  4370. }
  4371. return TRUE;
  4372. }
  4373. /*
  4374. * Perform RPC client bind. Accepts a connected client socket.
  4375. * Returns 0 on success. RPC binding is required before any payload can be
  4376. * exchanged. It negotiates about protocol details.
  4377. */
  4378. RpcStatus rpcBindOrAlterClientContext(const RpcCtx sock, BYTE packetType, const int_fast8_t verbose)
  4379. {
  4380. RPC_HEADER *RequestHeader, ResponseHeader;
  4381. RPC_BIND_REQUEST *bindRequest;
  4382. RPC_BIND_RESPONSE *bindResponse;
  4383. int status;
  4384. WORD ctxItems = 1 + (packetType == RPC_PT_BIND_REQ ? UseRpcNDR64 + UseRpcBTFN : 0);
  4385. size_t rpcBindSize = (sizeof(RPC_HEADER) + sizeof(RPC_BIND_REQUEST) + (ctxItems - 1) * sizeof(bindRequest->CtxItems[0]));
  4386. WORD ctxIndex = 0;
  4387. WORD i;
  4388. WORD CtxBTFN = (WORD)~0, CtxNDR64 = (WORD)~0;
  4389. BYTE _Request[rpcBindSize];
  4390. RequestHeader = (RPC_HEADER*)_Request;
  4391. bindRequest = (RPC_BIND_REQUEST* )(_Request + sizeof(RPC_HEADER));
  4392. createRpcRequestHeader(RequestHeader, packetType, rpcBindSize);
  4393. RequestHeader->PacketFlags |= UseMultiplexedRpc ? RPC_PF_MULTIPLEX : 0;
  4394. bindRequest->AssocGroup = 0;
  4395. bindRequest->MaxRecvFrag = bindRequest->MaxXmitFrag = LE16(5840);
  4396. bindRequest->NumCtxItems = LE32(ctxItems);
  4397. // data that is identical in all Ctx items
  4398. for (i = 0; i < ctxItems; i++)
  4399. {
  4400. bindRequest->CtxItems[i].ContextId = LE16(i);
  4401. bindRequest->CtxItems[i].InterfaceVerMajor = LE16(1);
  4402. bindRequest->CtxItems[i].InterfaceVerMinor = 0;
  4403. bindRequest->CtxItems[i].NumTransItems = LE16(1);
  4404. bindRequest->CtxItems[i].SyntaxVersion = i ? LE32(1) : LE32(2);
  4405. memcpy(&bindRequest->CtxItems[i].InterfaceUUID, InterfaceUuid, sizeof(GUID));
  4406. }
  4407. memcpy(&bindRequest->CtxItems[0].TransferSyntax, TransferSyntaxNDR32, sizeof(GUID));
  4408. if (UseRpcNDR64 && packetType == RPC_PT_BIND_REQ)
  4409. {
  4410. memcpy(&bindRequest->CtxItems[++ctxIndex].TransferSyntax, TransferSyntaxNDR64, sizeof(GUID));
  4411. CtxNDR64 = ctxIndex;
  4412. }
  4413. if (UseRpcBTFN && packetType == RPC_PT_BIND_REQ)
  4414. {
  4415. memcpy(&bindRequest->CtxItems[++ctxIndex].TransferSyntax, BindTimeFeatureNegotiation, sizeof(GUID));
  4416. CtxBTFN = ctxIndex;
  4417. }
  4418. if (!_send(sock, _Request, rpcBindSize))
  4419. {
  4420. errorout("\nFatal: Sending RPC bind request failed\n");
  4421. return !0;
  4422. }
  4423. if (!_recv(sock, &ResponseHeader, sizeof(RPC_HEADER)))
  4424. {
  4425. errorout("\nFatal: Did not receive a response from server\n");
  4426. return !0;
  4427. }
  4428. if ((status = checkRpcResponseHeader
  4429. (
  4430. &ResponseHeader,
  4431. RequestHeader,
  4432. packetType == RPC_PT_BIND_REQ ? RPC_PT_BIND_ACK : RPC_PT_ALTERCONTEXT_ACK,
  4433. &errorout
  4434. )))
  4435. {
  4436. return status;
  4437. }
  4438. bindResponse = (RPC_BIND_RESPONSE*)vlmcsd_malloc(LE16(ResponseHeader.FragLength) - sizeof(RPC_HEADER));
  4439. BYTE* bindResponseBytePtr = (BYTE*)bindResponse;
  4440. if (!_recv(sock, bindResponse, LE16(ResponseHeader.FragLength) - sizeof(RPC_HEADER)))
  4441. {
  4442. errorout("\nFatal: Incomplete RPC bind acknowledgement received\n");
  4443. free(bindResponseBytePtr);
  4444. return !0;
  4445. }
  4446. else
  4447. {
  4448. /*
  4449. * checking, whether a bind or alter context response is as expected.
  4450. * This check is very strict and checks whether a KMS emulator behaves exactly the same way
  4451. * as Microsoft's RPC does.
  4452. */
  4453. status = 0;
  4454. if (bindResponse->SecondaryAddressLength < LE16(3))
  4455. bindResponse = (RPC_BIND_RESPONSE*)(bindResponseBytePtr - 4);
  4456. if (bindResponse->NumResults != bindRequest->NumCtxItems)
  4457. {
  4458. errorout("\nFatal: Expected %u CTX items but got %u\n",
  4459. (uint32_t)LE32(bindRequest->NumCtxItems),
  4460. (uint32_t)LE32(bindResponse->NumResults)
  4461. );
  4462. status = !0;
  4463. }
  4464. for (i = 0; i < ctxItems; i++)
  4465. {
  4466. const char* transferSyntaxName =
  4467. i == CtxBTFN ? "BTFN" : i == CtxNDR64 ? "NDR64" : "NDR32";
  4468. if (bindResponse->Results[i].AckResult == RPC_BIND_NACK) // transfer syntax was declined
  4469. {
  4470. if (!IsNullGuid((BYTE*)&bindResponse->Results[i].TransferSyntax))
  4471. {
  4472. errorout(
  4473. "\nWarning: Rejected transfer syntax %s did not return NULL Guid\n",
  4474. transferSyntaxName
  4475. );
  4476. }
  4477. if (bindResponse->Results[i].SyntaxVersion)
  4478. {
  4479. errorout(
  4480. "\nWarning: Rejected transfer syntax %s did not return syntax version 0 but %u\n",
  4481. transferSyntaxName,
  4482. LE32(bindResponse->Results[i].SyntaxVersion)
  4483. );
  4484. }
  4485. if (bindResponse->Results[i].AckReason == RPC_ABSTRACTSYNTAX_UNSUPPORTED)
  4486. {
  4487. errorout(
  4488. "\nWarning: Transfer syntax %s does not support KMS activation\n",
  4489. transferSyntaxName
  4490. );
  4491. }
  4492. else if (bindResponse->Results[i].AckReason != RPC_SYNTAX_UNSUPPORTED)
  4493. {
  4494. errorout(
  4495. "\nWarning: Rejected transfer syntax %s did not return ack reason RPC_SYNTAX_UNSUPPORTED\n",
  4496. transferSyntaxName
  4497. );
  4498. }
  4499. continue;
  4500. }
  4501. if (i == CtxBTFN) // BTFN
  4502. {
  4503. if (bindResponse->Results[i].AckResult != RPC_BIND_ACK)
  4504. {
  4505. errorout("\nWarning: BTFN did not respond with RPC_BIND_ACK or RPC_BIND_NACK\n");
  4506. }
  4507. if (bindResponse->Results[i].AckReason != LE16(3))
  4508. {
  4509. errorout("\nWarning: BTFN did not return expected feature mask 0x3 but 0x%X\n", (unsigned int)LE16(bindResponse->Results[i].AckReason));
  4510. }
  4511. if (verbose) printf("... BTFN ");
  4512. RpcFlags.HasBTFN = TRUE;
  4513. continue;
  4514. }
  4515. // NDR32 or NDR64 Ctx
  4516. if (bindResponse->Results[i].AckResult != RPC_BIND_ACCEPT)
  4517. {
  4518. errorout(
  4519. "\nFatal: transfer syntax %s returned an invalid status, neither RPC_BIND_ACCEPT nor RPC_BIND_NACK\n",
  4520. transferSyntaxName
  4521. );
  4522. status = !0;
  4523. }
  4524. if (!IsEqualGUID(&bindResponse->Results[i].TransferSyntax, &bindRequest->CtxItems[i].TransferSyntax))
  4525. {
  4526. errorout(
  4527. "\nFatal: Transfer syntax of RPC bind request and response does not match\n"
  4528. );
  4529. status = !0;
  4530. }
  4531. if (bindResponse->Results[i].SyntaxVersion != bindRequest->CtxItems[i].SyntaxVersion)
  4532. {
  4533. errorout("\nFatal: Expected transfer syntax version %u for %s but got %u\n",
  4534. (uint32_t)LE32(bindRequest->CtxItems[0].SyntaxVersion),
  4535. transferSyntaxName,
  4536. (uint32_t)LE32(bindResponse->Results[0].SyntaxVersion)
  4537. );
  4538. status = !0;
  4539. }
  4540. // The ack reason field is actually undefined here but Microsoft sets this to 0
  4541. if (bindResponse->Results[i].AckReason != 0)
  4542. {
  4543. errorout(
  4544. "\nWarning: Ack reason should be 0 but is %u\n",
  4545. LE16(bindResponse->Results[i].AckReason)
  4546. );
  4547. }
  4548. if (!status)
  4549. {
  4550. if (i == CtxNDR64)
  4551. {
  4552. RpcFlags.HasNDR64 = TRUE;
  4553. if (verbose) printf("... NDR64 ");
  4554. }
  4555. if (!i)
  4556. {
  4557. RpcFlags.HasNDR32 = TRUE;
  4558. if (verbose) printf("... NDR32 ");
  4559. }
  4560. }
  4561. }
  4562. }
  4563. free(bindResponseBytePtr);
  4564. if (!RpcFlags.HasNDR64 && !RpcFlags.HasNDR32)
  4565. {
  4566. errorout("\nFatal: Could neither negotiate NDR32 nor NDR64 with the RPC server\n");
  4567. status = !0;
  4568. }
  4569. return status;
  4570. }
  4571. RpcStatus rpcBindClient(const RpcCtx sock, const int_fast8_t verbose)
  4572. {
  4573. firstPacketSent = FALSE;
  4574. RpcFlags.mask = 0;
  4575. RpcStatus status =
  4576. rpcBindOrAlterClientContext(sock, RPC_PT_BIND_REQ, verbose);
  4577. if (status) return status;
  4578. if (!RpcFlags.HasNDR32)
  4579. status = rpcBindOrAlterClientContext(sock, RPC_PT_ALTERCONTEXT_REQ, verbose);
  4580. return status;
  4581. }
  4582. #endif // USE_MSRPC
  4583. #ifndef CONFIG
  4584. #define CONFIG "config.h"
  4585. #endif // CONFIG
  4586. #include CONFIG
  4587. #if !defined(_CRYPTO_OPENSSL) && !defined(_CRYPTO_POLARSSL) && !defined(_CRYPTO_WINDOWS)
  4588. #include "crypto_internal.h"
  4589. #include "endian.h"
  4590. #define F0(x, y, z) ( ((x) & (y)) | (~(x) & (z)) )
  4591. #define F1(x, y, z) ( ((x) & (y)) | ((x) & (z)) | ((y) & (z)) )
  4592. #define SI1(x) ( ROR32(x, 2 ) ^ ROR32(x, 13) ^ ROR32(x, 22) )
  4593. #define SI2(x) ( ROR32(x, 6 ) ^ ROR32(x, 11) ^ ROR32(x, 25) )
  4594. #define SI3(x) ( ROR32(x, 7 ) ^ ROR32(x, 18) ^ ((x) >> 3 ) )
  4595. #define SI4(x) ( ROR32(x, 17) ^ ROR32(x, 19) ^ ((x) >> 10) )
  4596. static const DWORD k[] = {
  4597. 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1,
  4598. 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
  4599. 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786,
  4600. 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
  4601. 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147,
  4602. 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
  4603. 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B,
  4604. 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
  4605. 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A,
  4606. 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
  4607. 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
  4608. };
  4609. static void Sha256Init(Sha256Ctx *Ctx)
  4610. {
  4611. Ctx->State[0] = 0x6A09E667;
  4612. Ctx->State[1] = 0xBB67AE85;
  4613. Ctx->State[2] = 0x3C6EF372;
  4614. Ctx->State[3] = 0xA54FF53A;
  4615. Ctx->State[4] = 0x510E527F;
  4616. Ctx->State[5] = 0x9B05688C;
  4617. Ctx->State[6] = 0x1F83D9AB;
  4618. Ctx->State[7] = 0x5BE0CD19;
  4619. Ctx->Len = 0;
  4620. }
  4621. static void Sha256ProcessBlock(Sha256Ctx *Ctx, BYTE *block)
  4622. {
  4623. unsigned int i;
  4624. DWORD w[64], temp1, temp2;
  4625. DWORD a = Ctx->State[0];
  4626. DWORD b = Ctx->State[1];
  4627. DWORD c = Ctx->State[2];
  4628. DWORD d = Ctx->State[3];
  4629. DWORD e = Ctx->State[4];
  4630. DWORD f = Ctx->State[5];
  4631. DWORD g = Ctx->State[6];
  4632. DWORD h = Ctx->State[7];
  4633. for (i = 0; i < 16; i++)
  4634. //w[ i ] = GET_UAA32BE(block, i);
  4635. w[i] = BE32(((DWORD*)block)[i]);
  4636. for (i = 16; i < 64; i++)
  4637. w[ i ] = SI4(w[ i - 2 ]) + w[ i - 7 ] + SI3(w[ i - 15 ]) + w[ i - 16 ];
  4638. for (i = 0; i < 64; i++)
  4639. {
  4640. temp1 = h + SI2(e) + F0(e, f, g) + k[ i ] + w[ i ];
  4641. temp2 = SI1(a) + F1(a, b, c);
  4642. h = g;
  4643. g = f;
  4644. f = e;
  4645. e = d + temp1;
  4646. d = c;
  4647. c = b;
  4648. b = a;
  4649. a = temp1 + temp2;
  4650. }
  4651. Ctx->State[0] += a;
  4652. Ctx->State[1] += b;
  4653. Ctx->State[2] += c;
  4654. Ctx->State[3] += d;
  4655. Ctx->State[4] += e;
  4656. Ctx->State[5] += f;
  4657. Ctx->State[6] += g;
  4658. Ctx->State[7] += h;
  4659. }
  4660. static void Sha256Update(Sha256Ctx *Ctx, BYTE *data, size_t len)
  4661. {
  4662. unsigned int b_len = Ctx->Len & 63,
  4663. r_len = (b_len ^ 63) + 1;
  4664. Ctx->Len += len;
  4665. if ( len < r_len )
  4666. {
  4667. memcpy(Ctx->Buffer + b_len, data, len);
  4668. return;
  4669. }
  4670. if ( r_len < 64 )
  4671. {
  4672. memcpy(Ctx->Buffer + b_len, data, r_len);
  4673. len -= r_len;
  4674. data += r_len;
  4675. Sha256ProcessBlock(Ctx, Ctx->Buffer);
  4676. }
  4677. for (; len >= 64; len -= 64, data += 64)
  4678. Sha256ProcessBlock(Ctx, data);
  4679. if ( len ) memcpy(Ctx->Buffer, data, len);
  4680. }
  4681. static void Sha256Finish(Sha256Ctx *Ctx, BYTE *hash)
  4682. {
  4683. unsigned int i, b_len = Ctx->Len & 63;
  4684. Ctx->Buffer[ b_len ] = 0x80;
  4685. if ( b_len ^ 63 ) memset(Ctx->Buffer + b_len + 1, 0, b_len ^ 63);
  4686. if ( b_len >= 56 )
  4687. {
  4688. Sha256ProcessBlock(Ctx, Ctx->Buffer);
  4689. memset(Ctx->Buffer, 0, 56);
  4690. }
  4691. //PUT_UAA64BE(Ctx->Buffer, (unsigned long long)(Ctx->Len * 8), 7);
  4692. ((uint64_t*)Ctx->Buffer)[7] = BE64((uint64_t)Ctx->Len << 3);
  4693. Sha256ProcessBlock(Ctx, Ctx->Buffer);
  4694. for (i = 0; i < 8; i++)
  4695. //PUT_UAA32BE(hash, Ctx->State[i], i);
  4696. ((DWORD*)hash)[i] = BE32(Ctx->State[i]);
  4697. }
  4698. void Sha256(BYTE *data, size_t len, BYTE *hash)
  4699. {
  4700. Sha256Ctx Ctx;
  4701. Sha256Init(&Ctx);
  4702. Sha256Update(&Ctx, data, len);
  4703. Sha256Finish(&Ctx, hash);
  4704. }
  4705. static void _Sha256HmacInit(Sha256HmacCtx *Ctx, BYTE *key, size_t klen)
  4706. {
  4707. BYTE IPad[64];
  4708. unsigned int i;
  4709. memset(IPad, 0x36, sizeof(IPad));
  4710. memset(Ctx->OPad, 0x5C, sizeof(Ctx->OPad));
  4711. if ( klen > 64 )
  4712. {
  4713. BYTE *temp = (BYTE*)alloca(32);
  4714. Sha256(key, klen, temp);
  4715. klen = 32;
  4716. key = temp;
  4717. }
  4718. for (i = 0; i < klen; i++)
  4719. {
  4720. IPad[ i ] ^= key[ i ];
  4721. Ctx->OPad[ i ] ^= key[ i ];
  4722. }
  4723. Sha256Init(&Ctx->ShaCtx);
  4724. Sha256Update(&Ctx->ShaCtx, IPad, sizeof(IPad));
  4725. }
  4726. static void _Sha256HmacUpdate(Sha256HmacCtx *Ctx, BYTE *data, size_t len)
  4727. {
  4728. Sha256Update(&Ctx->ShaCtx, data, len);
  4729. }
  4730. static void _Sha256HmacFinish(Sha256HmacCtx *Ctx, BYTE *hmac)
  4731. {
  4732. BYTE temp[32];
  4733. Sha256Finish(&Ctx->ShaCtx, temp);
  4734. Sha256Init(&Ctx->ShaCtx);
  4735. Sha256Update(&Ctx->ShaCtx, Ctx->OPad, sizeof(Ctx->OPad));
  4736. Sha256Update(&Ctx->ShaCtx, temp, sizeof(temp));
  4737. Sha256Finish(&Ctx->ShaCtx, hmac);
  4738. }
  4739. int_fast8_t Sha256Hmac(BYTE* key, BYTE* restrict data, DWORD len, BYTE* restrict hmac)
  4740. {
  4741. Sha256HmacCtx Ctx;
  4742. _Sha256HmacInit(&Ctx, key, 16);
  4743. _Sha256HmacUpdate(&Ctx, data, len);
  4744. _Sha256HmacFinish(&Ctx, hmac);
  4745. return TRUE;
  4746. }
  4747. #endif // No external Crypto