libwinutils.c 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with this
  4. * work for additional information regarding copyright ownership. The ASF
  5. * licenses this file to you under the Apache License, Version 2.0 (the
  6. * "License"); you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. * License for the specific language governing permissions and limitations under
  15. * the License.
  16. */
  17. #pragma comment(lib, "authz.lib")
  18. #pragma comment(lib, "netapi32.lib")
  19. #pragma comment(lib, "Secur32.lib")
  20. #pragma comment(lib, "Userenv.lib")
  21. #pragma comment(lib, "Ntdsapi.lib")
  22. #include "winutils.h"
  23. #include <ctype.h>
  24. #include <Winsvc.h>
  25. #include <authz.h>
  26. #include <sddl.h>
  27. #include <Ntdsapi.h>
  28. #include <malloc.h>
  29. #define WIDEN_STRING(x) WIDEN_STRING_(x)
  30. #define WIDEN_STRING_(x) L ## x
  31. #define STRINGIFY(x) STRINGIFY_(x)
  32. #define STRINGIFY_(x) #x
  33. #pragma message("WSCE config is " STRINGIFY(WSCE_CONFIG_DIR) "\\" STRINGIFY(WSCE_CONFIG_FILE))
  34. const WCHAR* wsceConfigRelativePath = WIDEN_STRING(STRINGIFY(WSCE_CONFIG_DIR)) L"\\" WIDEN_STRING(STRINGIFY(WSCE_CONFIG_FILE));
  35. /*
  36. * The array of 12 months' three-letter abbreviations
  37. */
  38. const LPCWSTR MONTHS[] = { L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun",
  39. L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec" };
  40. /*
  41. * The WindowsAclMask and WinMasks contain the definitions used to establish
  42. * the mapping between Unix and Windows.
  43. * We set up the mapping with the following rules.
  44. * 1. Everyone will have WIN_ALL permissions;
  45. * 2. Owner will always have WIN_OWNER_SE permissions in addition;
  46. * 2. When Unix read/write/excute permission is set on the file, the
  47. * corresponding Windows allow ACE will be added to the file.
  48. * More details and explaination can be found in the following white paper:
  49. * http://technet.microsoft.com/en-us/library/bb463216.aspx
  50. */
  51. const ACCESS_MASK WinMasks[WIN_MASKS_TOTAL] =
  52. {
  53. /* WIN_READ */
  54. FILE_READ_DATA,
  55. /* WIN_WRITE */
  56. FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_APPEND_DATA | FILE_WRITE_EA |
  57. FILE_DELETE_CHILD,
  58. /* WIN_EXECUTE */
  59. FILE_EXECUTE,
  60. /* WIN_OWNER_SE */
  61. DELETE | WRITE_DAC | WRITE_OWNER | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES,
  62. /* WIN_ALL */
  63. READ_CONTROL | FILE_READ_EA | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
  64. };
  65. //----------------------------------------------------------------------------
  66. // Function: GetFileInformationByName
  67. //
  68. // Description:
  69. // To retrieve the by handle file information given the file name
  70. //
  71. // Returns:
  72. // ERROR_SUCCESS: on success
  73. // error code: otherwise
  74. //
  75. // Notes:
  76. // If followLink parameter is set to TRUE, we will follow the symbolic link
  77. // or junction point to get the target file information. Otherwise, the
  78. // information for the symbolic link or junction point is retrieved.
  79. //
  80. DWORD GetFileInformationByName(
  81. __in LPCWSTR pathName,
  82. __in BOOL followLink,
  83. __out LPBY_HANDLE_FILE_INFORMATION lpFileInformation)
  84. {
  85. HANDLE fileHandle = INVALID_HANDLE_VALUE;
  86. BOOL isSymlink = FALSE;
  87. BOOL isJunction = FALSE;
  88. DWORD dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS;
  89. DWORD dwErrorCode = ERROR_SUCCESS;
  90. assert(lpFileInformation != NULL);
  91. if (!followLink)
  92. {
  93. if ((dwErrorCode = SymbolicLinkCheck(pathName, &isSymlink)) != ERROR_SUCCESS)
  94. return dwErrorCode;
  95. if ((dwErrorCode = JunctionPointCheck(pathName, &isJunction)) != ERROR_SUCCESS)
  96. return dwErrorCode;
  97. if (isSymlink || isJunction)
  98. dwFlagsAndAttributes |= FILE_FLAG_OPEN_REPARSE_POINT;
  99. }
  100. fileHandle = CreateFileW(
  101. pathName,
  102. FILE_READ_ATTRIBUTES,
  103. FILE_SHARE_READ,
  104. NULL,
  105. OPEN_EXISTING,
  106. dwFlagsAndAttributes,
  107. NULL);
  108. if (fileHandle == INVALID_HANDLE_VALUE)
  109. {
  110. dwErrorCode = GetLastError();
  111. return dwErrorCode;
  112. }
  113. if (!GetFileInformationByHandle(fileHandle, lpFileInformation))
  114. {
  115. dwErrorCode = GetLastError();
  116. CloseHandle(fileHandle);
  117. return dwErrorCode;
  118. }
  119. CloseHandle(fileHandle);
  120. return dwErrorCode;
  121. }
  122. //----------------------------------------------------------------------------
  123. // Function: IsLongWindowsPath
  124. //
  125. // Description:
  126. // Checks if the path is longer than (MAX_PATH - 13) in which case it needs to
  127. // be prepended with \\?\ for Windows OS to understand it. The -13 is to
  128. // account for an additional constraint for directories that it must be possible
  129. // to append an additional path separator followed by an 8.3 file name.
  130. //
  131. // Returns:
  132. // TRUE long path
  133. // FALSE otherwise
  134. static BOOL IsLongWindowsPath(__in PCWSTR path)
  135. {
  136. return (wcslen(path) + 1) > (MAX_PATH - 13);
  137. }
  138. //----------------------------------------------------------------------------
  139. // Function: IsPrefixedAlready
  140. //
  141. // Description:
  142. // Checks if the given path is already prepended with \\?\.
  143. //
  144. // Returns:
  145. // TRUE if yes
  146. // FALSE otherwise
  147. static BOOL IsPrefixedAlready(__in PCWSTR path)
  148. {
  149. static const PCWSTR LongPathPrefix = L"\\\\?\\";
  150. size_t Prefixlen = wcslen(LongPathPrefix);
  151. size_t i = 0;
  152. if (path == NULL || wcslen(path) < Prefixlen)
  153. {
  154. return FALSE;
  155. }
  156. for (i = 0; i < Prefixlen; ++i)
  157. {
  158. if (path[i] != LongPathPrefix[i])
  159. {
  160. return FALSE;
  161. }
  162. }
  163. return TRUE;
  164. }
  165. //----------------------------------------------------------------------------
  166. // Function: ConvertToLongPath
  167. //
  168. // Description:
  169. // Prepends the path with the \\?\ prefix if the path is longer than MAX_PATH.
  170. // On success, newPath should be freed with LocalFree(). Given that relative
  171. // paths cannot be longer than MAX_PATH, we will never prepend the prefix
  172. // to relative paths.
  173. //
  174. // Returns:
  175. // ERROR_SUCCESS on success
  176. // error code on failure
  177. DWORD ConvertToLongPath(__in PCWSTR path, __deref_out PWSTR *newPath)
  178. {
  179. DWORD dwErrorCode = ERROR_SUCCESS;
  180. static const PCWSTR LongPathPrefix = L"\\\\?\\";
  181. BOOL bAppendPrefix = IsLongWindowsPath(path) && !IsPrefixedAlready(path);
  182. HRESULT hr = S_OK;
  183. size_t newPathLen = wcslen(path) + (bAppendPrefix ? wcslen(LongPathPrefix) : 0);
  184. // Allocate the buffer for the output path (+1 for terminating NULL char)
  185. //
  186. PWSTR newPathValue = (PWSTR)LocalAlloc(LPTR, (newPathLen + 1) * sizeof(WCHAR));
  187. if (newPathValue == NULL)
  188. {
  189. dwErrorCode = GetLastError();
  190. goto ConvertToLongPathExit;
  191. }
  192. if (bAppendPrefix)
  193. {
  194. // Append the prefix to the path
  195. //
  196. hr = StringCchPrintfW(newPathValue, newPathLen + 1, L"%s%s",
  197. LongPathPrefix, path);
  198. if (FAILED(hr))
  199. {
  200. dwErrorCode = HRESULT_CODE(hr);
  201. goto ConvertToLongPathExit;
  202. }
  203. }
  204. else
  205. {
  206. // Just copy the original value into the output path. In this scenario
  207. // we are doing extra buffer copy. We decided to trade code simplicity
  208. // on the call site for small performance impact (extra allocation and
  209. // buffer copy). As paths are short, the impact is generally small.
  210. //
  211. hr = StringCchPrintfW(newPathValue, newPathLen + 1, L"%s", path);
  212. if (FAILED(hr))
  213. {
  214. dwErrorCode = HRESULT_CODE(hr);
  215. goto ConvertToLongPathExit;
  216. }
  217. }
  218. *newPath = newPathValue;
  219. ConvertToLongPathExit:
  220. if (dwErrorCode != ERROR_SUCCESS)
  221. {
  222. LocalFree(newPathValue);
  223. }
  224. return dwErrorCode;
  225. }
  226. //----------------------------------------------------------------------------
  227. // Function: IsDirFileInfo
  228. //
  229. // Description:
  230. // Test if the given file information is a directory
  231. //
  232. // Returns:
  233. // TRUE if it is a directory
  234. // FALSE otherwise
  235. //
  236. // Notes:
  237. //
  238. BOOL IsDirFileInfo(const BY_HANDLE_FILE_INFORMATION *fileInformation)
  239. {
  240. if ((fileInformation->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  241. == FILE_ATTRIBUTE_DIRECTORY)
  242. return TRUE;
  243. return FALSE;
  244. }
  245. //----------------------------------------------------------------------------
  246. // Function: CheckFileAttributes
  247. //
  248. // Description:
  249. // Check if the given file has all the given attribute(s)
  250. //
  251. // Returns:
  252. // ERROR_SUCCESS on success
  253. // error code otherwise
  254. //
  255. // Notes:
  256. //
  257. static DWORD FileAttributesCheck(
  258. __in LPCWSTR path, __in DWORD attr, __out PBOOL res)
  259. {
  260. DWORD attrs = INVALID_FILE_ATTRIBUTES;
  261. *res = FALSE;
  262. if ((attrs = GetFileAttributes(path)) != INVALID_FILE_ATTRIBUTES)
  263. *res = ((attrs & attr) == attr);
  264. else
  265. return GetLastError();
  266. return ERROR_SUCCESS;
  267. }
  268. //----------------------------------------------------------------------------
  269. // Function: IsDirectory
  270. //
  271. // Description:
  272. // Check if the given file is a directory
  273. //
  274. // Returns:
  275. // ERROR_SUCCESS on success
  276. // error code otherwise
  277. //
  278. // Notes:
  279. //
  280. DWORD DirectoryCheck(__in LPCWSTR pathName, __out PBOOL res)
  281. {
  282. return FileAttributesCheck(pathName, FILE_ATTRIBUTE_DIRECTORY, res);
  283. }
  284. //----------------------------------------------------------------------------
  285. // Function: IsReparsePoint
  286. //
  287. // Description:
  288. // Check if the given file is a reparse point
  289. //
  290. // Returns:
  291. // ERROR_SUCCESS on success
  292. // error code otherwise
  293. //
  294. // Notes:
  295. //
  296. static DWORD ReparsePointCheck(__in LPCWSTR pathName, __out PBOOL res)
  297. {
  298. return FileAttributesCheck(pathName, FILE_ATTRIBUTE_REPARSE_POINT, res);
  299. }
  300. //----------------------------------------------------------------------------
  301. // Function: CheckReparseTag
  302. //
  303. // Description:
  304. // Check if the given file is a reparse point of the given tag.
  305. //
  306. // Returns:
  307. // ERROR_SUCCESS on success
  308. // error code otherwise
  309. //
  310. // Notes:
  311. //
  312. static DWORD ReparseTagCheck(__in LPCWSTR path, __in DWORD tag, __out PBOOL res)
  313. {
  314. BOOL isReparsePoint = FALSE;
  315. HANDLE hFind = INVALID_HANDLE_VALUE;
  316. WIN32_FIND_DATA findData;
  317. DWORD dwRtnCode;
  318. if ((dwRtnCode = ReparsePointCheck(path, &isReparsePoint)) != ERROR_SUCCESS)
  319. return dwRtnCode;
  320. if (!isReparsePoint)
  321. {
  322. *res = FALSE;
  323. }
  324. else
  325. {
  326. if ((hFind = FindFirstFile(path, &findData)) == INVALID_HANDLE_VALUE)
  327. {
  328. return GetLastError();
  329. }
  330. else
  331. {
  332. *res = (findData.dwReserved0 == tag);
  333. FindClose(hFind);
  334. }
  335. }
  336. return ERROR_SUCCESS;
  337. }
  338. //----------------------------------------------------------------------------
  339. // Function: IsSymbolicLink
  340. //
  341. // Description:
  342. // Check if the given file is a symbolic link.
  343. //
  344. // Returns:
  345. // ERROR_SUCCESS on success
  346. // error code otherwise
  347. //
  348. // Notes:
  349. //
  350. DWORD SymbolicLinkCheck(__in LPCWSTR pathName, __out PBOOL res)
  351. {
  352. return ReparseTagCheck(pathName, IO_REPARSE_TAG_SYMLINK, res);
  353. }
  354. //----------------------------------------------------------------------------
  355. // Function: IsJunctionPoint
  356. //
  357. // Description:
  358. // Check if the given file is a junction point.
  359. //
  360. // Returns:
  361. // ERROR_SUCCESS on success
  362. // error code otherwise
  363. //
  364. // Notes:
  365. //
  366. DWORD JunctionPointCheck(__in LPCWSTR pathName, __out PBOOL res)
  367. {
  368. return ReparseTagCheck(pathName, IO_REPARSE_TAG_MOUNT_POINT, res);
  369. }
  370. //----------------------------------------------------------------------------
  371. // Function: GetSidFromAcctNameW
  372. //
  373. // Description:
  374. // To retrieve the SID for a user account
  375. //
  376. // Returns:
  377. // ERROR_SUCCESS: on success
  378. // Other error code: otherwise
  379. //
  380. // Notes:
  381. // Caller needs to destroy the memory of Sid by calling LocalFree()
  382. //
  383. DWORD GetSidFromAcctNameW(__in PCWSTR acctName, __out PSID *ppSid)
  384. {
  385. DWORD dwSidSize = 0;
  386. DWORD cchDomainName = 0;
  387. DWORD dwDomainNameSize = 0;
  388. LPWSTR domainName = NULL;
  389. SID_NAME_USE eSidType;
  390. DWORD dwErrorCode = ERROR_SUCCESS;
  391. // Validate the input parameters.
  392. //
  393. assert (acctName != NULL && ppSid != NULL);
  394. // Empty name is invalid. However, LookupAccountName() function will return a
  395. // false Sid, i.e. Sid for 'BUILDIN', for an empty name instead failing. We
  396. // report the error before calling LookupAccountName() function for this
  397. // special case. The error code returned here is the same as the last error
  398. // code set by LookupAccountName() function for an invalid name.
  399. //
  400. if (wcslen(acctName) == 0)
  401. return ERROR_NONE_MAPPED;
  402. // First pass to retrieve the buffer size.
  403. //
  404. LookupAccountName(
  405. NULL, // Computer name. NULL for the local computer
  406. acctName,
  407. NULL, // pSid. NULL to retrieve buffer size
  408. &dwSidSize,
  409. NULL, // Domain Name. NULL to retrieve buffer size
  410. &cchDomainName,
  411. &eSidType);
  412. if((dwErrorCode = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
  413. {
  414. return dwErrorCode;
  415. }
  416. else
  417. {
  418. // Reallocate memory for the buffers.
  419. //
  420. *ppSid = (PSID)LocalAlloc(LPTR, dwSidSize);
  421. if (*ppSid == NULL)
  422. {
  423. return GetLastError();
  424. }
  425. dwDomainNameSize = (cchDomainName + 1) * sizeof(wchar_t);
  426. domainName = (LPWSTR)LocalAlloc(LPTR, dwDomainNameSize);
  427. if (domainName == NULL)
  428. {
  429. return GetLastError();
  430. }
  431. // Second pass to retrieve the SID and domain name.
  432. //
  433. if (!LookupAccountNameW(
  434. NULL, // Computer name. NULL for the local computer
  435. acctName,
  436. *ppSid,
  437. &dwSidSize,
  438. domainName,
  439. &cchDomainName,
  440. &eSidType))
  441. {
  442. LocalFree(domainName);
  443. return GetLastError();
  444. }
  445. assert(IsValidSid(*ppSid));
  446. }
  447. LocalFree(domainName);
  448. return ERROR_SUCCESS;
  449. }
  450. //----------------------------------------------------------------------------
  451. // Function: GetUnixAccessMask
  452. //
  453. // Description:
  454. // Compute the 3 bit Unix mask for the owner, group, or, others
  455. //
  456. // Returns:
  457. // The 3 bit Unix mask in INT
  458. //
  459. // Notes:
  460. //
  461. static INT GetUnixAccessMask(ACCESS_MASK Mask)
  462. {
  463. static const INT exe = 0x0001;
  464. static const INT write = 0x0002;
  465. static const INT read = 0x0004;
  466. INT mask = 0;
  467. if ((Mask & WinMasks[WIN_READ]) == WinMasks[WIN_READ])
  468. mask |= read;
  469. if ((Mask & WinMasks[WIN_WRITE]) == WinMasks[WIN_WRITE])
  470. mask |= write;
  471. if ((Mask & WinMasks[WIN_EXECUTE]) == WinMasks[WIN_EXECUTE])
  472. mask |= exe;
  473. return mask;
  474. }
  475. //----------------------------------------------------------------------------
  476. // Function: GetAccess
  477. //
  478. // Description:
  479. // Get Windows acces mask by AuthZ methods
  480. //
  481. // Returns:
  482. // ERROR_SUCCESS: on success
  483. //
  484. // Notes:
  485. //
  486. static DWORD GetAccess(AUTHZ_CLIENT_CONTEXT_HANDLE hAuthzClient,
  487. PSECURITY_DESCRIPTOR psd, PACCESS_MASK pAccessRights)
  488. {
  489. AUTHZ_ACCESS_REQUEST AccessRequest = {0};
  490. AUTHZ_ACCESS_REPLY AccessReply = {0};
  491. BYTE Buffer[1024];
  492. assert (pAccessRights != NULL);
  493. // Do AccessCheck
  494. AccessRequest.DesiredAccess = MAXIMUM_ALLOWED;
  495. AccessRequest.PrincipalSelfSid = NULL;
  496. AccessRequest.ObjectTypeList = NULL;
  497. AccessRequest.ObjectTypeListLength = 0;
  498. AccessRequest.OptionalArguments = NULL;
  499. RtlZeroMemory(Buffer, sizeof(Buffer));
  500. AccessReply.ResultListLength = 1;
  501. AccessReply.GrantedAccessMask = (PACCESS_MASK) (Buffer);
  502. AccessReply.Error = (PDWORD) (Buffer + sizeof(ACCESS_MASK));
  503. if (!AuthzAccessCheck(0,
  504. hAuthzClient,
  505. &AccessRequest,
  506. NULL,
  507. psd,
  508. NULL,
  509. 0,
  510. &AccessReply,
  511. NULL))
  512. {
  513. return GetLastError();
  514. }
  515. *pAccessRights = (*(const ACCESS_MASK *)(AccessReply.GrantedAccessMask));
  516. return ERROR_SUCCESS;
  517. }
  518. //----------------------------------------------------------------------------
  519. // Function: GetEffectiveRightsForSid
  520. //
  521. // Description:
  522. // Get Windows acces mask by AuthZ methods
  523. //
  524. // Returns:
  525. // ERROR_SUCCESS: on success
  526. //
  527. // Notes:
  528. // We run into problems for local user accounts when using the method
  529. // GetEffectiveRightsFromAcl(). We resort to using AuthZ methods as
  530. // an alternative way suggested on MSDN:
  531. // http://msdn.microsoft.com/en-us/library/windows/desktop/aa446637.aspx
  532. //
  533. static DWORD GetEffectiveRightsForSid(PSECURITY_DESCRIPTOR psd,
  534. PSID pSid,
  535. PACCESS_MASK pAccessRights)
  536. {
  537. AUTHZ_RESOURCE_MANAGER_HANDLE hManager = NULL;
  538. LUID unusedId = { 0 };
  539. AUTHZ_CLIENT_CONTEXT_HANDLE hAuthzClientContext = NULL;
  540. DWORD dwRtnCode = ERROR_SUCCESS;
  541. DWORD ret = ERROR_SUCCESS;
  542. assert (pAccessRights != NULL);
  543. if (!AuthzInitializeResourceManager(AUTHZ_RM_FLAG_NO_AUDIT,
  544. NULL, NULL, NULL, NULL, &hManager))
  545. {
  546. return GetLastError();
  547. }
  548. // Pass AUTHZ_SKIP_TOKEN_GROUPS to the function to avoid querying user group
  549. // information for access check. This allows us to model POSIX permissions
  550. // on Windows, where a user can have less permissions than a group it
  551. // belongs to.
  552. if(!AuthzInitializeContextFromSid(AUTHZ_SKIP_TOKEN_GROUPS,
  553. pSid, hManager, NULL, unusedId, NULL, &hAuthzClientContext))
  554. {
  555. ret = GetLastError();
  556. goto GetEffectiveRightsForSidEnd;
  557. }
  558. if ((dwRtnCode = GetAccess(hAuthzClientContext, psd, pAccessRights))
  559. != ERROR_SUCCESS)
  560. {
  561. ret = dwRtnCode;
  562. goto GetEffectiveRightsForSidEnd;
  563. }
  564. GetEffectiveRightsForSidEnd:
  565. if (hManager != NULL)
  566. {
  567. (void)AuthzFreeResourceManager(hManager);
  568. }
  569. if (hAuthzClientContext != NULL)
  570. {
  571. (void)AuthzFreeContext(hAuthzClientContext);
  572. }
  573. return ret;
  574. }
  575. //----------------------------------------------------------------------------
  576. // Function: CheckAccessForCurrentUser
  577. //
  578. // Description:
  579. // Checks if the current process has the requested access rights on the given
  580. // path. Based on the following MSDN article:
  581. // http://msdn.microsoft.com/en-us/library/windows/desktop/ff394771(v=vs.85).aspx
  582. //
  583. // Returns:
  584. // ERROR_SUCCESS: on success
  585. //
  586. DWORD CheckAccessForCurrentUser(
  587. __in PCWSTR pathName,
  588. __in ACCESS_MASK requestedAccess,
  589. __out BOOL *allowed)
  590. {
  591. DWORD dwRtnCode = ERROR_SUCCESS;
  592. LPWSTR longPathName = NULL;
  593. HANDLE hProcessToken = NULL;
  594. PSECURITY_DESCRIPTOR pSd = NULL;
  595. AUTHZ_RESOURCE_MANAGER_HANDLE hManager = NULL;
  596. AUTHZ_CLIENT_CONTEXT_HANDLE hAuthzClientContext = NULL;
  597. LUID Luid = {0, 0};
  598. ACCESS_MASK currentUserAccessRights = 0;
  599. // Prepend the long path prefix if needed
  600. dwRtnCode = ConvertToLongPath(pathName, &longPathName);
  601. if (dwRtnCode != ERROR_SUCCESS)
  602. {
  603. goto CheckAccessEnd;
  604. }
  605. // Get SD of the given path. OWNER and DACL security info must be
  606. // requested, otherwise, AuthzAccessCheck fails with invalid parameter
  607. // error.
  608. dwRtnCode = GetNamedSecurityInfo(longPathName, SE_FILE_OBJECT,
  609. OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
  610. DACL_SECURITY_INFORMATION,
  611. NULL, NULL, NULL, NULL, &pSd);
  612. if (dwRtnCode != ERROR_SUCCESS)
  613. {
  614. goto CheckAccessEnd;
  615. }
  616. // Get current process token
  617. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hProcessToken))
  618. {
  619. dwRtnCode = GetLastError();
  620. goto CheckAccessEnd;
  621. }
  622. if (!AuthzInitializeResourceManager(AUTHZ_RM_FLAG_NO_AUDIT, NULL, NULL,
  623. NULL, NULL, &hManager))
  624. {
  625. dwRtnCode = GetLastError();
  626. goto CheckAccessEnd;
  627. }
  628. if(!AuthzInitializeContextFromToken(0, hProcessToken, hManager, NULL,
  629. Luid, NULL, &hAuthzClientContext))
  630. {
  631. dwRtnCode = GetLastError();
  632. goto CheckAccessEnd;
  633. }
  634. dwRtnCode = GetAccess(hAuthzClientContext, pSd, &currentUserAccessRights);
  635. if (dwRtnCode != ERROR_SUCCESS)
  636. {
  637. goto CheckAccessEnd;
  638. }
  639. *allowed = ((currentUserAccessRights & requestedAccess) == requestedAccess);
  640. CheckAccessEnd:
  641. LocalFree(longPathName);
  642. LocalFree(pSd);
  643. if (hProcessToken != NULL)
  644. {
  645. CloseHandle(hProcessToken);
  646. }
  647. if (hManager != NULL)
  648. {
  649. (void)AuthzFreeResourceManager(hManager);
  650. }
  651. if (hAuthzClientContext != NULL)
  652. {
  653. (void)AuthzFreeContext(hAuthzClientContext);
  654. }
  655. return dwRtnCode;
  656. }
  657. //----------------------------------------------------------------------------
  658. // Function: FindFileOwnerAndPermissionByHandle
  659. //
  660. // Description:
  661. // Find the owner, primary group and permissions of a file object given the
  662. // the file object handle. The function will always follow symbolic links.
  663. //
  664. // Returns:
  665. // ERROR_SUCCESS: on success
  666. // Error code otherwise
  667. //
  668. // Notes:
  669. // - Caller needs to destroy the memeory of owner and group names by calling
  670. // LocalFree() function.
  671. //
  672. // - If the user or group name does not exist, the user or group SID will be
  673. // returned as the name.
  674. //
  675. DWORD FindFileOwnerAndPermissionByHandle(
  676. __in HANDLE fileHandle,
  677. __out_opt LPWSTR *pOwnerName,
  678. __out_opt LPWSTR *pGroupName,
  679. __out_opt PINT pMask)
  680. {
  681. LPWSTR path = NULL;
  682. DWORD cchPathLen = 0;
  683. DWORD dwRtnCode = ERROR_SUCCESS;
  684. DWORD ret = ERROR_SUCCESS;
  685. dwRtnCode = GetFinalPathNameByHandle(fileHandle, path, cchPathLen, 0);
  686. if (dwRtnCode == 0)
  687. {
  688. ret = GetLastError();
  689. goto FindFileOwnerAndPermissionByHandleEnd;
  690. }
  691. cchPathLen = dwRtnCode;
  692. path = (LPWSTR) LocalAlloc(LPTR, cchPathLen * sizeof(WCHAR));
  693. if (path == NULL)
  694. {
  695. ret = GetLastError();
  696. goto FindFileOwnerAndPermissionByHandleEnd;
  697. }
  698. dwRtnCode = GetFinalPathNameByHandle(fileHandle, path, cchPathLen, 0);
  699. if (dwRtnCode != cchPathLen - 1)
  700. {
  701. ret = GetLastError();
  702. goto FindFileOwnerAndPermissionByHandleEnd;
  703. }
  704. dwRtnCode = FindFileOwnerAndPermission(path, TRUE, pOwnerName, pGroupName, pMask);
  705. if (dwRtnCode != ERROR_SUCCESS)
  706. {
  707. ret = dwRtnCode;
  708. goto FindFileOwnerAndPermissionByHandleEnd;
  709. }
  710. FindFileOwnerAndPermissionByHandleEnd:
  711. LocalFree(path);
  712. return ret;
  713. }
  714. //----------------------------------------------------------------------------
  715. // Function: FindFileOwnerAndPermission
  716. //
  717. // Description:
  718. // Find the owner, primary group and permissions of a file object
  719. //
  720. // Returns:
  721. // ERROR_SUCCESS: on success
  722. // Error code otherwise
  723. //
  724. // Notes:
  725. // - Caller needs to destroy the memeory of owner and group names by calling
  726. // LocalFree() function.
  727. //
  728. // - If the user or group name does not exist, the user or group SID will be
  729. // returned as the name.
  730. //
  731. DWORD FindFileOwnerAndPermission(
  732. __in LPCWSTR pathName,
  733. __in BOOL followLink,
  734. __out_opt LPWSTR *pOwnerName,
  735. __out_opt LPWSTR *pGroupName,
  736. __out_opt PINT pMask)
  737. {
  738. DWORD dwRtnCode = 0;
  739. PSECURITY_DESCRIPTOR pSd = NULL;
  740. PSID psidOwner = NULL;
  741. PSID psidGroup = NULL;
  742. PSID psidEveryone = NULL;
  743. DWORD cbSid = SECURITY_MAX_SID_SIZE;
  744. PACL pDacl = NULL;
  745. BOOL isSymlink = FALSE;
  746. BY_HANDLE_FILE_INFORMATION fileInformation = {0};
  747. ACCESS_MASK ownerAccessRights = 0;
  748. ACCESS_MASK groupAccessRights = 0;
  749. ACCESS_MASK worldAccessRights = 0;
  750. DWORD ret = ERROR_SUCCESS;
  751. // Do nothing if the caller request nothing
  752. //
  753. if (pOwnerName == NULL && pGroupName == NULL && pMask == NULL)
  754. {
  755. return ret;
  756. }
  757. dwRtnCode = GetNamedSecurityInfo(pathName, SE_FILE_OBJECT,
  758. OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
  759. DACL_SECURITY_INFORMATION,
  760. &psidOwner, &psidGroup, &pDacl, NULL, &pSd);
  761. if (dwRtnCode != ERROR_SUCCESS)
  762. {
  763. ret = dwRtnCode;
  764. goto FindFileOwnerAndPermissionEnd;
  765. }
  766. if (pOwnerName != NULL)
  767. {
  768. dwRtnCode = GetAccntNameFromSid(psidOwner, pOwnerName);
  769. if (dwRtnCode == ERROR_NONE_MAPPED)
  770. {
  771. if (!ConvertSidToStringSid(psidOwner, pOwnerName))
  772. {
  773. ret = GetLastError();
  774. goto FindFileOwnerAndPermissionEnd;
  775. }
  776. }
  777. else if (dwRtnCode != ERROR_SUCCESS)
  778. {
  779. ret = dwRtnCode;
  780. goto FindFileOwnerAndPermissionEnd;
  781. }
  782. }
  783. if (pGroupName != NULL)
  784. {
  785. dwRtnCode = GetAccntNameFromSid(psidGroup, pGroupName);
  786. if (dwRtnCode == ERROR_NONE_MAPPED)
  787. {
  788. if (!ConvertSidToStringSid(psidGroup, pGroupName))
  789. {
  790. ret = GetLastError();
  791. goto FindFileOwnerAndPermissionEnd;
  792. }
  793. }
  794. else if (dwRtnCode != ERROR_SUCCESS)
  795. {
  796. ret = dwRtnCode;
  797. goto FindFileOwnerAndPermissionEnd;
  798. }
  799. }
  800. if (pMask == NULL) goto FindFileOwnerAndPermissionEnd;
  801. dwRtnCode = GetFileInformationByName(pathName,
  802. followLink, &fileInformation);
  803. if (dwRtnCode != ERROR_SUCCESS)
  804. {
  805. ret = dwRtnCode;
  806. goto FindFileOwnerAndPermissionEnd;
  807. }
  808. dwRtnCode = SymbolicLinkCheck(pathName, &isSymlink);
  809. if (dwRtnCode != ERROR_SUCCESS)
  810. {
  811. ret = dwRtnCode;
  812. goto FindFileOwnerAndPermissionEnd;
  813. }
  814. if (isSymlink)
  815. *pMask |= UX_SYMLINK;
  816. else if (IsDirFileInfo(&fileInformation))
  817. *pMask |= UX_DIRECTORY;
  818. else
  819. *pMask |= UX_REGULAR;
  820. if ((dwRtnCode = GetEffectiveRightsForSid(pSd,
  821. psidOwner, &ownerAccessRights)) != ERROR_SUCCESS)
  822. {
  823. ret = dwRtnCode;
  824. goto FindFileOwnerAndPermissionEnd;
  825. }
  826. if ((dwRtnCode = GetEffectiveRightsForSid(pSd,
  827. psidGroup, &groupAccessRights)) != ERROR_SUCCESS)
  828. {
  829. ret = dwRtnCode;
  830. goto FindFileOwnerAndPermissionEnd;
  831. }
  832. if ((psidEveryone = LocalAlloc(LPTR, cbSid)) == NULL)
  833. {
  834. ret = GetLastError();
  835. goto FindFileOwnerAndPermissionEnd;
  836. }
  837. if (!CreateWellKnownSid(WinWorldSid, NULL, psidEveryone, &cbSid))
  838. {
  839. ret = GetLastError();
  840. goto FindFileOwnerAndPermissionEnd;
  841. }
  842. if ((dwRtnCode = GetEffectiveRightsForSid(pSd,
  843. psidEveryone, &worldAccessRights)) != ERROR_SUCCESS)
  844. {
  845. ret = dwRtnCode;
  846. goto FindFileOwnerAndPermissionEnd;
  847. }
  848. *pMask |= GetUnixAccessMask(ownerAccessRights) << 6;
  849. *pMask |= GetUnixAccessMask(groupAccessRights) << 3;
  850. *pMask |= GetUnixAccessMask(worldAccessRights);
  851. FindFileOwnerAndPermissionEnd:
  852. LocalFree(psidEveryone);
  853. LocalFree(pSd);
  854. return ret;
  855. }
  856. //----------------------------------------------------------------------------
  857. // Function: GetWindowsAccessMask
  858. //
  859. // Description:
  860. // Get the Windows AccessMask for user, group and everyone based on the Unix
  861. // permission mask
  862. //
  863. // Returns:
  864. // none
  865. //
  866. // Notes:
  867. // none
  868. //
  869. static void GetWindowsAccessMask(INT unixMask,
  870. ACCESS_MASK *userAllow,
  871. ACCESS_MASK *userDeny,
  872. ACCESS_MASK *groupAllow,
  873. ACCESS_MASK *groupDeny,
  874. ACCESS_MASK *otherAllow)
  875. {
  876. assert (userAllow != NULL && userDeny != NULL &&
  877. groupAllow != NULL && groupDeny != NULL &&
  878. otherAllow != NULL);
  879. *userAllow = WinMasks[WIN_ALL] | WinMasks[WIN_OWNER_SE];
  880. if ((unixMask & UX_U_READ) == UX_U_READ)
  881. *userAllow |= WinMasks[WIN_READ];
  882. if ((unixMask & UX_U_WRITE) == UX_U_WRITE)
  883. *userAllow |= WinMasks[WIN_WRITE];
  884. if ((unixMask & UX_U_EXECUTE) == UX_U_EXECUTE)
  885. *userAllow |= WinMasks[WIN_EXECUTE];
  886. *userDeny = 0;
  887. if ((unixMask & UX_U_READ) != UX_U_READ &&
  888. ((unixMask & UX_G_READ) == UX_G_READ ||
  889. (unixMask & UX_O_READ) == UX_O_READ))
  890. *userDeny |= WinMasks[WIN_READ];
  891. if ((unixMask & UX_U_WRITE) != UX_U_WRITE &&
  892. ((unixMask & UX_G_WRITE) == UX_G_WRITE ||
  893. (unixMask & UX_O_WRITE) == UX_O_WRITE))
  894. *userDeny |= WinMasks[WIN_WRITE];
  895. if ((unixMask & UX_U_EXECUTE) != UX_U_EXECUTE &&
  896. ((unixMask & UX_G_EXECUTE) == UX_G_EXECUTE ||
  897. (unixMask & UX_O_EXECUTE) == UX_O_EXECUTE))
  898. *userDeny |= WinMasks[WIN_EXECUTE];
  899. *groupAllow = WinMasks[WIN_ALL];
  900. if ((unixMask & UX_G_READ) == UX_G_READ)
  901. *groupAllow |= FILE_GENERIC_READ;
  902. if ((unixMask & UX_G_WRITE) == UX_G_WRITE)
  903. *groupAllow |= WinMasks[WIN_WRITE];
  904. if ((unixMask & UX_G_EXECUTE) == UX_G_EXECUTE)
  905. *groupAllow |= WinMasks[WIN_EXECUTE];
  906. *groupDeny = 0;
  907. if ((unixMask & UX_G_READ) != UX_G_READ &&
  908. (unixMask & UX_O_READ) == UX_O_READ)
  909. *groupDeny |= WinMasks[WIN_READ];
  910. if ((unixMask & UX_G_WRITE) != UX_G_WRITE &&
  911. (unixMask & UX_O_WRITE) == UX_O_WRITE)
  912. *groupDeny |= WinMasks[WIN_WRITE];
  913. if ((unixMask & UX_G_EXECUTE) != UX_G_EXECUTE &&
  914. (unixMask & UX_O_EXECUTE) == UX_O_EXECUTE)
  915. *groupDeny |= WinMasks[WIN_EXECUTE];
  916. *otherAllow = WinMasks[WIN_ALL];
  917. if ((unixMask & UX_O_READ) == UX_O_READ)
  918. *otherAllow |= WinMasks[WIN_READ];
  919. if ((unixMask & UX_O_WRITE) == UX_O_WRITE)
  920. *otherAllow |= WinMasks[WIN_WRITE];
  921. if ((unixMask & UX_O_EXECUTE) == UX_O_EXECUTE)
  922. *otherAllow |= WinMasks[WIN_EXECUTE];
  923. }
  924. //----------------------------------------------------------------------------
  925. // Function: GetWindowsDACLs
  926. //
  927. // Description:
  928. // Get the Windows DACs based the Unix access mask
  929. //
  930. // Returns:
  931. // ERROR_SUCCESS: on success
  932. // Error code: otherwise
  933. //
  934. // Notes:
  935. // - Administrators and SYSTEM are always given full permission to the file,
  936. // unless Administrators or SYSTEM itself is the file owner and the user
  937. // explictly set the permission to something else. For example, file 'foo'
  938. // belongs to Administrators, 'chmod 000' on the file will not directly
  939. // assign Administrators full permission on the file.
  940. // - Only full permission for Administrators and SYSTEM are inheritable.
  941. // - CREATOR OWNER is always given full permission and the permission is
  942. // inheritable, more specifically OBJECT_INHERIT_ACE, CONTAINER_INHERIT_ACE
  943. // flags are set. The reason is to give the creator of child file full
  944. // permission, i.e., the child file will have permission mode 700 for
  945. // a user other than Administrator or SYSTEM.
  946. //
  947. static DWORD GetWindowsDACLs(__in INT unixMask,
  948. __in PSID pOwnerSid, __in PSID pGroupSid, __out PACL *ppNewDACL)
  949. {
  950. DWORD winUserAccessDenyMask;
  951. DWORD winUserAccessAllowMask;
  952. DWORD winGroupAccessDenyMask;
  953. DWORD winGroupAccessAllowMask;
  954. DWORD winOtherAccessAllowMask;
  955. PSID pEveryoneSid = NULL;
  956. DWORD cbEveryoneSidSize = SECURITY_MAX_SID_SIZE;
  957. PSID pSystemSid = NULL;
  958. DWORD cbSystemSidSize = SECURITY_MAX_SID_SIZE;
  959. BOOL bAddSystemAcls = FALSE;
  960. PSID pAdministratorsSid = NULL;
  961. DWORD cbAdministratorsSidSize = SECURITY_MAX_SID_SIZE;
  962. BOOL bAddAdministratorsAcls = FALSE;
  963. PSID pCreatorOwnerSid = NULL;
  964. DWORD cbCreatorOwnerSidSize = SECURITY_MAX_SID_SIZE;
  965. PACL pNewDACL = NULL;
  966. DWORD dwNewAclSize = 0;
  967. DWORD ret = ERROR_SUCCESS;
  968. GetWindowsAccessMask(unixMask,
  969. &winUserAccessAllowMask, &winUserAccessDenyMask,
  970. &winGroupAccessAllowMask, &winGroupAccessDenyMask,
  971. &winOtherAccessAllowMask);
  972. // Create a well-known SID for the Everyone group
  973. //
  974. if ((pEveryoneSid = LocalAlloc(LPTR, cbEveryoneSidSize)) == NULL)
  975. {
  976. ret = GetLastError();
  977. goto GetWindowsDACLsEnd;
  978. }
  979. if (!CreateWellKnownSid(WinWorldSid, NULL, pEveryoneSid, &cbEveryoneSidSize))
  980. {
  981. ret = GetLastError();
  982. goto GetWindowsDACLsEnd;
  983. }
  984. // Create a well-known SID for the Administrators group
  985. //
  986. if ((pAdministratorsSid = LocalAlloc(LPTR, cbAdministratorsSidSize)) == NULL)
  987. {
  988. ret = GetLastError();
  989. goto GetWindowsDACLsEnd;
  990. }
  991. if (!CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL,
  992. pAdministratorsSid, &cbAdministratorsSidSize))
  993. {
  994. ret = GetLastError();
  995. goto GetWindowsDACLsEnd;
  996. }
  997. if (!EqualSid(pAdministratorsSid, pOwnerSid)
  998. && !EqualSid(pAdministratorsSid, pGroupSid))
  999. bAddAdministratorsAcls = TRUE;
  1000. // Create a well-known SID for the SYSTEM
  1001. //
  1002. if ((pSystemSid = LocalAlloc(LPTR, cbSystemSidSize)) == NULL)
  1003. {
  1004. ret = GetLastError();
  1005. goto GetWindowsDACLsEnd;
  1006. }
  1007. if (!CreateWellKnownSid(WinLocalSystemSid, NULL,
  1008. pSystemSid, &cbSystemSidSize))
  1009. {
  1010. ret = GetLastError();
  1011. goto GetWindowsDACLsEnd;
  1012. }
  1013. if (!EqualSid(pSystemSid, pOwnerSid)
  1014. && !EqualSid(pSystemSid, pGroupSid))
  1015. bAddSystemAcls = TRUE;
  1016. // Create a well-known SID for the Creator Owner
  1017. //
  1018. if ((pCreatorOwnerSid = LocalAlloc(LPTR, cbCreatorOwnerSidSize)) == NULL)
  1019. {
  1020. ret = GetLastError();
  1021. goto GetWindowsDACLsEnd;
  1022. }
  1023. if (!CreateWellKnownSid(WinCreatorOwnerSid, NULL,
  1024. pCreatorOwnerSid, &cbCreatorOwnerSidSize))
  1025. {
  1026. ret = GetLastError();
  1027. goto GetWindowsDACLsEnd;
  1028. }
  1029. // Create the new DACL
  1030. //
  1031. dwNewAclSize = sizeof(ACL);
  1032. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  1033. GetLengthSid(pOwnerSid) - sizeof(DWORD);
  1034. if (winUserAccessDenyMask)
  1035. dwNewAclSize += sizeof(ACCESS_DENIED_ACE) +
  1036. GetLengthSid(pOwnerSid) - sizeof(DWORD);
  1037. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  1038. GetLengthSid(pGroupSid) - sizeof(DWORD);
  1039. if (winGroupAccessDenyMask)
  1040. dwNewAclSize += sizeof(ACCESS_DENIED_ACE) +
  1041. GetLengthSid(pGroupSid) - sizeof(DWORD);
  1042. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  1043. GetLengthSid(pEveryoneSid) - sizeof(DWORD);
  1044. if (bAddSystemAcls)
  1045. {
  1046. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  1047. cbSystemSidSize - sizeof(DWORD);
  1048. }
  1049. if (bAddAdministratorsAcls)
  1050. {
  1051. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  1052. cbAdministratorsSidSize - sizeof(DWORD);
  1053. }
  1054. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  1055. cbCreatorOwnerSidSize - sizeof(DWORD);
  1056. pNewDACL = (PACL)LocalAlloc(LPTR, dwNewAclSize);
  1057. if (pNewDACL == NULL)
  1058. {
  1059. ret = GetLastError();
  1060. goto GetWindowsDACLsEnd;
  1061. }
  1062. if (!InitializeAcl(pNewDACL, dwNewAclSize, ACL_REVISION))
  1063. {
  1064. ret = GetLastError();
  1065. goto GetWindowsDACLsEnd;
  1066. }
  1067. if (!AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  1068. CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
  1069. GENERIC_ALL, pCreatorOwnerSid))
  1070. {
  1071. ret = GetLastError();
  1072. goto GetWindowsDACLsEnd;
  1073. }
  1074. if (bAddSystemAcls &&
  1075. !AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  1076. CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
  1077. GENERIC_ALL, pSystemSid))
  1078. {
  1079. ret = GetLastError();
  1080. goto GetWindowsDACLsEnd;
  1081. }
  1082. if (bAddAdministratorsAcls &&
  1083. !AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  1084. CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
  1085. GENERIC_ALL, pAdministratorsSid))
  1086. {
  1087. ret = GetLastError();
  1088. goto GetWindowsDACLsEnd;
  1089. }
  1090. if (winUserAccessDenyMask &&
  1091. !AddAccessDeniedAceEx(pNewDACL, ACL_REVISION,
  1092. CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
  1093. winUserAccessDenyMask, pOwnerSid))
  1094. {
  1095. ret = GetLastError();
  1096. goto GetWindowsDACLsEnd;
  1097. }
  1098. if (!AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  1099. CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
  1100. winUserAccessAllowMask, pOwnerSid))
  1101. {
  1102. ret = GetLastError();
  1103. goto GetWindowsDACLsEnd;
  1104. }
  1105. if (winGroupAccessDenyMask &&
  1106. !AddAccessDeniedAceEx(pNewDACL, ACL_REVISION,
  1107. CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
  1108. winGroupAccessDenyMask, pGroupSid))
  1109. {
  1110. ret = GetLastError();
  1111. goto GetWindowsDACLsEnd;
  1112. }
  1113. if (!AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  1114. CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
  1115. winGroupAccessAllowMask, pGroupSid))
  1116. {
  1117. ret = GetLastError();
  1118. goto GetWindowsDACLsEnd;
  1119. }
  1120. if (!AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  1121. CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
  1122. winOtherAccessAllowMask, pEveryoneSid))
  1123. {
  1124. ret = GetLastError();
  1125. goto GetWindowsDACLsEnd;
  1126. }
  1127. *ppNewDACL = pNewDACL;
  1128. GetWindowsDACLsEnd:
  1129. LocalFree(pEveryoneSid);
  1130. LocalFree(pAdministratorsSid);
  1131. LocalFree(pSystemSid);
  1132. LocalFree(pCreatorOwnerSid);
  1133. if (ret != ERROR_SUCCESS) LocalFree(pNewDACL);
  1134. return ret;
  1135. }
  1136. //----------------------------------------------------------------------------
  1137. // Function: ChangeFileModeByMask
  1138. //
  1139. // Description:
  1140. // Change a file or direcotry at the path to Unix mode
  1141. //
  1142. // Returns:
  1143. // ERROR_SUCCESS: on success
  1144. // Error code: otherwise
  1145. //
  1146. // Notes:
  1147. // This function is long path safe, i.e. the path will be converted to long
  1148. // path format if not already converted. So the caller does not need to do
  1149. // the converstion before calling the method.
  1150. //
  1151. DWORD ChangeFileModeByMask(__in LPCWSTR path, INT mode)
  1152. {
  1153. LPWSTR longPathName = NULL;
  1154. PACL pNewDACL = NULL;
  1155. PSID pOwnerSid = NULL;
  1156. PSID pGroupSid = NULL;
  1157. PSECURITY_DESCRIPTOR pSD = NULL;
  1158. SECURITY_DESCRIPTOR_CONTROL control;
  1159. DWORD revision = 0;
  1160. PSECURITY_DESCRIPTOR pAbsSD = NULL;
  1161. PSECURITY_DESCRIPTOR pNonNullSD = NULL;
  1162. PACL pAbsDacl = NULL;
  1163. PACL pAbsSacl = NULL;
  1164. PSID pAbsOwner = NULL;
  1165. PSID pAbsGroup = NULL;
  1166. DWORD dwRtnCode = 0;
  1167. DWORD dwErrorCode = 0;
  1168. DWORD ret = ERROR_SUCCESS;
  1169. dwRtnCode = ConvertToLongPath(path, &longPathName);
  1170. if (dwRtnCode != ERROR_SUCCESS)
  1171. {
  1172. ret = dwRtnCode;
  1173. goto ChangeFileModeByMaskEnd;
  1174. }
  1175. // Get owner and group Sids
  1176. //
  1177. dwRtnCode = GetNamedSecurityInfoW(
  1178. longPathName,
  1179. SE_FILE_OBJECT,
  1180. OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION,
  1181. &pOwnerSid,
  1182. &pGroupSid,
  1183. NULL,
  1184. NULL,
  1185. &pSD);
  1186. if (ERROR_SUCCESS != dwRtnCode)
  1187. {
  1188. ret = dwRtnCode;
  1189. goto ChangeFileModeByMaskEnd;
  1190. }
  1191. // SetSecurityDescriptorDacl function used below only accepts security
  1192. // descriptor in absolute format, meaning that its members must be pointers to
  1193. // other structures, rather than offsets to contiguous data.
  1194. // To determine whether a security descriptor is self-relative or absolute,
  1195. // call the GetSecurityDescriptorControl function and check the
  1196. // SE_SELF_RELATIVE flag of the SECURITY_DESCRIPTOR_CONTROL parameter.
  1197. //
  1198. if (!GetSecurityDescriptorControl(pSD, &control, &revision))
  1199. {
  1200. ret = GetLastError();
  1201. goto ChangeFileModeByMaskEnd;
  1202. }
  1203. // If the security descriptor is self-relative, we use MakeAbsoluteSD function
  1204. // to convert it to absolute format.
  1205. //
  1206. if ((control & SE_SELF_RELATIVE) == SE_SELF_RELATIVE)
  1207. {
  1208. DWORD absSDSize = 0;
  1209. DWORD daclSize = 0;
  1210. DWORD saclSize = 0;
  1211. DWORD ownerSize = 0;
  1212. DWORD primaryGroupSize = 0;
  1213. MakeAbsoluteSD(pSD, NULL, &absSDSize, NULL, &daclSize, NULL,
  1214. &saclSize, NULL, &ownerSize, NULL, &primaryGroupSize);
  1215. if ((dwErrorCode = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
  1216. {
  1217. ret = dwErrorCode;
  1218. goto ChangeFileModeByMaskEnd;
  1219. }
  1220. if ((pAbsSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, absSDSize)) == NULL)
  1221. {
  1222. ret = GetLastError();
  1223. goto ChangeFileModeByMaskEnd;
  1224. }
  1225. if ((pAbsDacl = (PACL) LocalAlloc(LPTR, daclSize)) == NULL)
  1226. {
  1227. ret = GetLastError();
  1228. goto ChangeFileModeByMaskEnd;
  1229. }
  1230. if ((pAbsSacl = (PACL) LocalAlloc(LPTR, saclSize)) == NULL)
  1231. {
  1232. ret = GetLastError();
  1233. goto ChangeFileModeByMaskEnd;
  1234. }
  1235. if ((pAbsOwner = (PSID) LocalAlloc(LPTR, ownerSize)) == NULL)
  1236. {
  1237. ret = GetLastError();
  1238. goto ChangeFileModeByMaskEnd;
  1239. }
  1240. if ((pAbsGroup = (PSID) LocalAlloc(LPTR, primaryGroupSize)) == NULL)
  1241. {
  1242. ret = GetLastError();
  1243. goto ChangeFileModeByMaskEnd;
  1244. }
  1245. if (!MakeAbsoluteSD(pSD, pAbsSD, &absSDSize, pAbsDacl, &daclSize, pAbsSacl,
  1246. &saclSize, pAbsOwner, &ownerSize, pAbsGroup, &primaryGroupSize))
  1247. {
  1248. ret = GetLastError();
  1249. goto ChangeFileModeByMaskEnd;
  1250. }
  1251. }
  1252. // Get Windows DACLs based on Unix access mask
  1253. //
  1254. if ((dwRtnCode = GetWindowsDACLs(mode, pOwnerSid, pGroupSid, &pNewDACL))
  1255. != ERROR_SUCCESS)
  1256. {
  1257. ret = dwRtnCode;
  1258. goto ChangeFileModeByMaskEnd;
  1259. }
  1260. // Set the DACL information in the security descriptor; if a DACL is already
  1261. // present in the security descriptor, the DACL is replaced. The security
  1262. // descriptor is then used to set the security of a file or directory.
  1263. //
  1264. pNonNullSD = (pAbsSD != NULL) ? pAbsSD : pSD;
  1265. if (!SetSecurityDescriptorDacl(pNonNullSD, TRUE, pNewDACL, FALSE))
  1266. {
  1267. ret = GetLastError();
  1268. goto ChangeFileModeByMaskEnd;
  1269. }
  1270. // MSDN states "This function is obsolete. Use the SetNamedSecurityInfo
  1271. // function instead." However we have the following problem when using
  1272. // SetNamedSecurityInfo:
  1273. // - When PROTECTED_DACL_SECURITY_INFORMATION is not passed in as part of
  1274. // security information, the object will include inheritable permissions
  1275. // from its parent.
  1276. // - When PROTECTED_DACL_SECURITY_INFORMATION is passsed in to set
  1277. // permissions on a directory, the child object of the directory will lose
  1278. // inheritable permissions from their parent (the current directory).
  1279. // By using SetFileSecurity, we have the nice property that the new
  1280. // permissions of the object does not include the inheritable permissions from
  1281. // its parent, and the child objects will not lose their inherited permissions
  1282. // from the current object.
  1283. //
  1284. if (!SetFileSecurity(longPathName, DACL_SECURITY_INFORMATION, pNonNullSD))
  1285. {
  1286. ret = GetLastError();
  1287. goto ChangeFileModeByMaskEnd;
  1288. }
  1289. ChangeFileModeByMaskEnd:
  1290. pNonNullSD = NULL;
  1291. LocalFree(longPathName);
  1292. LocalFree(pSD);
  1293. LocalFree(pNewDACL);
  1294. LocalFree(pAbsDacl);
  1295. LocalFree(pAbsSacl);
  1296. LocalFree(pAbsOwner);
  1297. LocalFree(pAbsGroup);
  1298. LocalFree(pAbsSD);
  1299. return ret;
  1300. }
  1301. //----------------------------------------------------------------------------
  1302. // Function: GetTokenInformationByClass
  1303. //
  1304. // Description:
  1305. // Gets a class of information from a token. On success, this function has
  1306. // dynamically allocated memory and set the ppTokenInformation parameter to
  1307. // point to it. The caller owns this memory and is reponsible for releasing it
  1308. // by calling LocalFree.
  1309. //
  1310. // Returns:
  1311. // ERROR_SUCCESS: on success
  1312. // Error code: otherwise
  1313. //
  1314. static DWORD GetTokenInformationByClass(__in HANDLE hToken,
  1315. __in TOKEN_INFORMATION_CLASS class, __out_opt LPVOID *ppTokenInformation) {
  1316. DWORD dwRtnCode = ERROR_SUCCESS;
  1317. LPVOID pTokenInformation = NULL;
  1318. DWORD dwSize = 0;
  1319. // Call GetTokenInformation first time to get the required buffer size.
  1320. if (!GetTokenInformation(hToken, class, NULL, 0, &dwSize)) {
  1321. dwRtnCode = GetLastError();
  1322. if (dwRtnCode != ERROR_INSUFFICIENT_BUFFER) {
  1323. return dwRtnCode;
  1324. }
  1325. }
  1326. // Allocate memory.
  1327. pTokenInformation = LocalAlloc(LPTR, dwSize);
  1328. if (!pTokenInformation) {
  1329. return GetLastError();
  1330. }
  1331. // Call GetTokenInformation second time to fill our buffer with data.
  1332. if (!GetTokenInformation(hToken, class, pTokenInformation, dwSize, &dwSize)) {
  1333. LocalFree(pTokenInformation);
  1334. return GetLastError();
  1335. }
  1336. *ppTokenInformation = pTokenInformation;
  1337. return ERROR_SUCCESS;
  1338. }
  1339. //----------------------------------------------------------------------------
  1340. // Function: GetWindowsDACLsForCreate
  1341. //
  1342. // Description:
  1343. // Get the Windows discretionary access control list equivalent to the given
  1344. // mode, suitable for creating a new file or directory. Ownership is assumed
  1345. // to be the current process owner and primary group. On success, this function
  1346. // has dynamically allocated memory and set the ppDACL parameter to point to it.
  1347. // The caller owns this memory and is reponsible for releasing it by calling
  1348. // LocalFree.
  1349. //
  1350. // Returns:
  1351. // ERROR_SUCCESS: on success
  1352. // Error code: otherwise
  1353. //
  1354. static DWORD GetWindowsDACLsForCreate(__in INT mode, __out PACL *ppDACL) {
  1355. DWORD dwRtnCode = ERROR_SUCCESS;
  1356. HANDLE hToken = NULL;
  1357. DWORD dwSize = 0;
  1358. PTOKEN_OWNER pTokenOwner = NULL;
  1359. PTOKEN_PRIMARY_GROUP pTokenPrimaryGroup = NULL;
  1360. PSID pOwnerSid = NULL, pGroupSid = NULL;
  1361. PACL pDACL = NULL;
  1362. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {
  1363. dwRtnCode = GetLastError();
  1364. goto done;
  1365. }
  1366. dwRtnCode = GetTokenInformationByClass(hToken, TokenOwner, &pTokenOwner);
  1367. if (dwRtnCode != ERROR_SUCCESS) {
  1368. goto done;
  1369. }
  1370. pOwnerSid = pTokenOwner->Owner;
  1371. dwRtnCode = GetTokenInformationByClass(hToken, TokenPrimaryGroup,
  1372. &pTokenPrimaryGroup);
  1373. if (dwRtnCode != ERROR_SUCCESS) {
  1374. goto done;
  1375. }
  1376. pGroupSid = pTokenPrimaryGroup->PrimaryGroup;
  1377. dwRtnCode = GetWindowsDACLs(mode, pOwnerSid, pGroupSid, &pDACL);
  1378. if (dwRtnCode != ERROR_SUCCESS) {
  1379. goto done;
  1380. }
  1381. *ppDACL = pDACL;
  1382. done:
  1383. if (hToken) {
  1384. CloseHandle(hToken);
  1385. }
  1386. LocalFree(pTokenOwner);
  1387. LocalFree(pTokenPrimaryGroup);
  1388. return dwRtnCode;
  1389. }
  1390. //----------------------------------------------------------------------------
  1391. // Function: CreateSecurityDescriptorForCreate
  1392. //
  1393. // Description:
  1394. // Creates a security descriptor with the given DACL, suitable for creating a
  1395. // new file or directory. On success, this function has dynamically allocated
  1396. // memory and set the ppSD parameter to point to it. The caller owns this
  1397. // memory and is reponsible for releasing it by calling LocalFree.
  1398. //
  1399. // Returns:
  1400. // ERROR_SUCCESS: on success
  1401. // Error code: otherwise
  1402. //
  1403. static DWORD CreateSecurityDescriptorForCreate(__in PACL pDACL,
  1404. __out PSECURITY_DESCRIPTOR *ppSD) {
  1405. DWORD dwRtnCode = ERROR_SUCCESS;
  1406. PSECURITY_DESCRIPTOR pSD = NULL;
  1407. pSD = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  1408. if (!pSD) {
  1409. dwRtnCode = GetLastError();
  1410. goto done;
  1411. }
  1412. if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) {
  1413. dwRtnCode = GetLastError();
  1414. goto done;
  1415. }
  1416. if (!SetSecurityDescriptorDacl(pSD, TRUE, pDACL, FALSE)) {
  1417. dwRtnCode = GetLastError();
  1418. goto done;
  1419. }
  1420. *ppSD = pSD;
  1421. done:
  1422. if (dwRtnCode != ERROR_SUCCESS) {
  1423. LocalFree(pSD);
  1424. }
  1425. return dwRtnCode;
  1426. }
  1427. //----------------------------------------------------------------------------
  1428. // Function: CreateDirectoryWithMode
  1429. //
  1430. // Description:
  1431. // Create a directory with initial security descriptor containing a
  1432. // discretionary access control list equivalent to the given mode.
  1433. //
  1434. // Returns:
  1435. // ERROR_SUCCESS: on success
  1436. // Error code: otherwise
  1437. //
  1438. // Notes:
  1439. // This function is long path safe, i.e. the path will be converted to long
  1440. // path format if not already converted. So the caller does not need to do
  1441. // the conversion before calling the method.
  1442. //
  1443. DWORD CreateDirectoryWithMode(__in LPCWSTR lpPath, __in INT mode) {
  1444. DWORD dwRtnCode = ERROR_SUCCESS;
  1445. LPWSTR lpLongPath = NULL;
  1446. PACL pDACL = NULL;
  1447. PSECURITY_DESCRIPTOR pSD = NULL;
  1448. SECURITY_ATTRIBUTES sa;
  1449. dwRtnCode = ConvertToLongPath(lpPath, &lpLongPath);
  1450. if (dwRtnCode != ERROR_SUCCESS) {
  1451. goto done;
  1452. }
  1453. dwRtnCode = GetWindowsDACLsForCreate(mode, &pDACL);
  1454. if (dwRtnCode != ERROR_SUCCESS) {
  1455. goto done;
  1456. }
  1457. dwRtnCode = CreateSecurityDescriptorForCreate(pDACL, &pSD);
  1458. if (dwRtnCode != ERROR_SUCCESS) {
  1459. goto done;
  1460. }
  1461. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  1462. sa.lpSecurityDescriptor = pSD;
  1463. sa.bInheritHandle = FALSE;
  1464. if (!CreateDirectoryW(lpLongPath, &sa)) {
  1465. dwRtnCode = GetLastError();
  1466. }
  1467. done:
  1468. LocalFree(lpLongPath);
  1469. LocalFree(pDACL);
  1470. LocalFree(pSD);
  1471. return dwRtnCode;
  1472. }
  1473. //----------------------------------------------------------------------------
  1474. // Function: CreateFileWithMode
  1475. //
  1476. // Description:
  1477. // Create a file with initial security descriptor containing a discretionary
  1478. // access control list equivalent to the given mode.
  1479. //
  1480. // Returns:
  1481. // ERROR_SUCCESS: on success
  1482. // Error code: otherwise
  1483. //
  1484. // Notes:
  1485. // This function is long path safe, i.e. the path will be converted to long
  1486. // path format if not already converted. So the caller does not need to do
  1487. // the conversion before calling the method.
  1488. //
  1489. DWORD CreateFileWithMode(__in LPCWSTR lpPath, __in DWORD dwDesiredAccess,
  1490. __in DWORD dwShareMode, __in DWORD dwCreationDisposition, __in INT mode,
  1491. __out PHANDLE pHFile) {
  1492. DWORD dwRtnCode = ERROR_SUCCESS;
  1493. LPWSTR lpLongPath = NULL;
  1494. PACL pDACL = NULL;
  1495. PSECURITY_DESCRIPTOR pSD = NULL;
  1496. SECURITY_ATTRIBUTES sa;
  1497. DWORD dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  1498. HANDLE hFile = INVALID_HANDLE_VALUE;
  1499. dwRtnCode = ConvertToLongPath(lpPath, &lpLongPath);
  1500. if (dwRtnCode != ERROR_SUCCESS) {
  1501. goto done;
  1502. }
  1503. dwRtnCode = GetWindowsDACLsForCreate(mode, &pDACL);
  1504. if (dwRtnCode != ERROR_SUCCESS) {
  1505. goto done;
  1506. }
  1507. dwRtnCode = CreateSecurityDescriptorForCreate(pDACL, &pSD);
  1508. if (dwRtnCode != ERROR_SUCCESS) {
  1509. goto done;
  1510. }
  1511. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  1512. sa.lpSecurityDescriptor = pSD;
  1513. sa.bInheritHandle = FALSE;
  1514. hFile = CreateFileW(lpLongPath, dwDesiredAccess, dwShareMode, &sa,
  1515. dwCreationDisposition, dwFlagsAndAttributes, NULL);
  1516. if (hFile == INVALID_HANDLE_VALUE) {
  1517. dwRtnCode = GetLastError();
  1518. goto done;
  1519. }
  1520. *pHFile = hFile;
  1521. done:
  1522. LocalFree(lpLongPath);
  1523. LocalFree(pDACL);
  1524. LocalFree(pSD);
  1525. return dwRtnCode;
  1526. }
  1527. //----------------------------------------------------------------------------
  1528. // Function: GetAccntNameFromSid
  1529. //
  1530. // Description:
  1531. // To retrieve an account name given the SID
  1532. //
  1533. // Returns:
  1534. // ERROR_SUCCESS: on success
  1535. // Other error code: otherwise
  1536. //
  1537. // Notes:
  1538. // Caller needs to destroy the memory of account name by calling LocalFree()
  1539. //
  1540. DWORD GetAccntNameFromSid(__in PSID pSid, __out PWSTR *ppAcctName)
  1541. {
  1542. LPWSTR lpName = NULL;
  1543. DWORD cchName = 0;
  1544. LPWSTR lpDomainName = NULL;
  1545. DWORD cchDomainName = 0;
  1546. SID_NAME_USE eUse = SidTypeUnknown;
  1547. DWORD cchAcctName = 0;
  1548. DWORD dwErrorCode = ERROR_SUCCESS;
  1549. HRESULT hr = S_OK;
  1550. DWORD ret = ERROR_SUCCESS;
  1551. assert(ppAcctName != NULL);
  1552. // NOTE:
  1553. // MSDN says the length returned for the buffer size including the terminating
  1554. // null character. However we found it is not true during debuging.
  1555. //
  1556. LookupAccountSid(NULL, pSid, NULL, &cchName, NULL, &cchDomainName, &eUse);
  1557. if ((dwErrorCode = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
  1558. return dwErrorCode;
  1559. lpName = (LPWSTR) LocalAlloc(LPTR, (cchName + 1) * sizeof(WCHAR));
  1560. if (lpName == NULL)
  1561. {
  1562. ret = GetLastError();
  1563. goto GetAccntNameFromSidEnd;
  1564. }
  1565. lpDomainName = (LPWSTR) LocalAlloc(LPTR, (cchDomainName + 1) * sizeof(WCHAR));
  1566. if (lpDomainName == NULL)
  1567. {
  1568. ret = GetLastError();
  1569. goto GetAccntNameFromSidEnd;
  1570. }
  1571. if (!LookupAccountSid(NULL, pSid,
  1572. lpName, &cchName, lpDomainName, &cchDomainName, &eUse))
  1573. {
  1574. ret = GetLastError();
  1575. goto GetAccntNameFromSidEnd;
  1576. }
  1577. // Buffer size = name length + 1 for '\' + domain length + 1 for NULL
  1578. cchAcctName = cchName + cchDomainName + 2;
  1579. *ppAcctName = (LPWSTR) LocalAlloc(LPTR, cchAcctName * sizeof(WCHAR));
  1580. if (*ppAcctName == NULL)
  1581. {
  1582. ret = GetLastError();
  1583. goto GetAccntNameFromSidEnd;
  1584. }
  1585. hr = StringCchCopyW(*ppAcctName, cchAcctName, lpDomainName);
  1586. if (FAILED(hr))
  1587. {
  1588. ret = HRESULT_CODE(hr);
  1589. goto GetAccntNameFromSidEnd;
  1590. }
  1591. hr = StringCchCatW(*ppAcctName, cchAcctName, L"\\");
  1592. if (FAILED(hr))
  1593. {
  1594. ret = HRESULT_CODE(hr);
  1595. goto GetAccntNameFromSidEnd;
  1596. }
  1597. hr = StringCchCatW(*ppAcctName, cchAcctName, lpName);
  1598. if (FAILED(hr))
  1599. {
  1600. ret = HRESULT_CODE(hr);
  1601. goto GetAccntNameFromSidEnd;
  1602. }
  1603. GetAccntNameFromSidEnd:
  1604. LocalFree(lpName);
  1605. LocalFree(lpDomainName);
  1606. if (ret != ERROR_SUCCESS)
  1607. {
  1608. LocalFree(*ppAcctName);
  1609. *ppAcctName = NULL;
  1610. }
  1611. return ret;
  1612. }
  1613. //----------------------------------------------------------------------------
  1614. // Function: GetLocalGroupsForUser
  1615. //
  1616. // Description:
  1617. // Get an array of groups for the given user.
  1618. //
  1619. // Returns:
  1620. // ERROR_SUCCESS on success
  1621. // Other error code on failure
  1622. //
  1623. // Notes:
  1624. // - NetUserGetLocalGroups() function only accepts full user name in the format
  1625. // [domain name]\[username]. The user input to this function can be only the
  1626. // username. In this case, NetUserGetLocalGroups() will fail on the first try,
  1627. // and we will try to find full user name using LookupAccountNameW() method,
  1628. // and call NetUserGetLocalGroups() function again with full user name.
  1629. // However, it is not always possible to find full user name given only user
  1630. // name. For example, a computer named 'win1' joined domain 'redmond' can have
  1631. // two different users, 'win1\alex' and 'redmond\alex'. Given only 'alex', we
  1632. // cannot tell which one is correct.
  1633. //
  1634. // - Caller needs to destroy the memory of groups by using the
  1635. // NetApiBufferFree() function
  1636. //
  1637. DWORD GetLocalGroupsForUser(
  1638. __in LPCWSTR user,
  1639. __out LPLOCALGROUP_USERS_INFO_0 *groups,
  1640. __out LPDWORD entries)
  1641. {
  1642. DWORD dwEntriesRead = 0;
  1643. DWORD dwTotalEntries = 0;
  1644. NET_API_STATUS nStatus = NERR_Success;
  1645. PSID pUserSid = NULL;
  1646. LPWSTR fullName = NULL;
  1647. DWORD dwRtnCode = ERROR_SUCCESS;
  1648. DWORD ret = ERROR_SUCCESS;
  1649. *groups = NULL;
  1650. *entries = 0;
  1651. nStatus = NetUserGetLocalGroups(NULL,
  1652. user,
  1653. 0,
  1654. 0,
  1655. (LPBYTE *) groups,
  1656. MAX_PREFERRED_LENGTH,
  1657. &dwEntriesRead,
  1658. &dwTotalEntries);
  1659. if (nStatus == NERR_Success)
  1660. {
  1661. *entries = dwEntriesRead;
  1662. return ERROR_SUCCESS;
  1663. }
  1664. else if (nStatus != NERR_UserNotFound)
  1665. {
  1666. return nStatus;
  1667. }
  1668. if ((dwRtnCode = GetSidFromAcctNameW(user, &pUserSid)) != ERROR_SUCCESS)
  1669. {
  1670. ret = dwRtnCode;
  1671. goto GetLocalGroupsForUserEnd;
  1672. }
  1673. if ((dwRtnCode = GetAccntNameFromSid(pUserSid, &fullName)) != ERROR_SUCCESS)
  1674. {
  1675. ret = dwRtnCode;
  1676. goto GetLocalGroupsForUserEnd;
  1677. }
  1678. nStatus = NetUserGetLocalGroups(NULL,
  1679. fullName,
  1680. 0,
  1681. 0,
  1682. (LPBYTE *) groups,
  1683. MAX_PREFERRED_LENGTH,
  1684. &dwEntriesRead,
  1685. &dwTotalEntries);
  1686. if (nStatus != NERR_Success)
  1687. {
  1688. // NERR_DCNotFound (2453) and NERR_UserNotFound (2221) are not published
  1689. // Windows System Error Code. All other error codes returned by
  1690. // NetUserGetLocalGroups() are valid System Error Codes according to MSDN.
  1691. ret = nStatus;
  1692. goto GetLocalGroupsForUserEnd;
  1693. }
  1694. *entries = dwEntriesRead;
  1695. GetLocalGroupsForUserEnd:
  1696. LocalFree(pUserSid);
  1697. LocalFree(fullName);
  1698. return ret;
  1699. }
  1700. //----------------------------------------------------------------------------
  1701. // Function: EnablePrivilege
  1702. //
  1703. // Description:
  1704. // Check if the process has the given privilege. If yes, enable the privilege
  1705. // to the process's access token.
  1706. //
  1707. // Returns:
  1708. // ERROR_SUCCESS on success
  1709. // GetLastError() on error
  1710. //
  1711. // Notes:
  1712. //
  1713. DWORD EnablePrivilege(__in LPCWSTR privilegeName)
  1714. {
  1715. HANDLE hToken = INVALID_HANDLE_VALUE;
  1716. TOKEN_PRIVILEGES tp = { 0 };
  1717. DWORD dwErrCode = ERROR_SUCCESS;
  1718. if (!OpenProcessToken(GetCurrentProcess(),
  1719. TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
  1720. {
  1721. dwErrCode = GetLastError();
  1722. ReportErrorCode(L"OpenProcessToken", dwErrCode);
  1723. return dwErrCode;
  1724. }
  1725. tp.PrivilegeCount = 1;
  1726. if (!LookupPrivilegeValueW(NULL,
  1727. privilegeName, &(tp.Privileges[0].Luid)))
  1728. {
  1729. dwErrCode = GetLastError();
  1730. ReportErrorCode(L"LookupPrivilegeValue", dwErrCode);
  1731. CloseHandle(hToken);
  1732. return dwErrCode;
  1733. }
  1734. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1735. // As stated on MSDN, we need to use GetLastError() to check if
  1736. // AdjustTokenPrivileges() adjusted all of the specified privileges.
  1737. //
  1738. if (!AdjustTokenPrivileges(hToken, FALSE, &tp, 0, NULL, NULL)) {
  1739. dwErrCode = GetLastError();
  1740. }
  1741. CloseHandle(hToken);
  1742. return dwErrCode;
  1743. }
  1744. //----------------------------------------------------------------------------
  1745. // Function: ReportErrorCode
  1746. //
  1747. // Description:
  1748. // Report an error. Use FormatMessage function to get the system error message.
  1749. //
  1750. // Returns:
  1751. // None
  1752. //
  1753. // Notes:
  1754. //
  1755. //
  1756. void ReportErrorCode(LPCWSTR func, DWORD err)
  1757. {
  1758. DWORD len = 0;
  1759. LPWSTR msg = NULL;
  1760. assert(func != NULL);
  1761. len = FormatMessageW(
  1762. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  1763. NULL, err,
  1764. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1765. (LPWSTR)&msg, 0, NULL);
  1766. if (len > 0)
  1767. {
  1768. LogDebugMessage(L"%s error (%d): %s\n", func, err, msg);
  1769. fwprintf(stderr, L"%s error (%d): %s\n", func, err, msg);
  1770. }
  1771. else
  1772. {
  1773. LogDebugMessage(L"%s error code: %d.\n", func, err);
  1774. fwprintf(stderr, L"%s error code: %d.\n", func, err);
  1775. }
  1776. if (msg != NULL) LocalFree(msg);
  1777. }
  1778. //----------------------------------------------------------------------------
  1779. // Function: GetLibraryName
  1780. //
  1781. // Description:
  1782. // Given an address, get the file name of the library from which it was loaded.
  1783. //
  1784. // Notes:
  1785. // - The function allocates heap memory and points the filename out parameter to
  1786. // the newly allocated memory, which will contain the name of the file.
  1787. //
  1788. // - If there is any failure, then the function frees the heap memory it
  1789. // allocated and sets the filename out parameter to NULL.
  1790. //
  1791. void GetLibraryName(LPCVOID lpAddress, LPWSTR *filename)
  1792. {
  1793. SIZE_T ret = 0;
  1794. DWORD size = MAX_PATH;
  1795. HMODULE mod = NULL;
  1796. DWORD err = ERROR_SUCCESS;
  1797. MEMORY_BASIC_INFORMATION mbi;
  1798. ret = VirtualQuery(lpAddress, &mbi, sizeof(mbi));
  1799. if (ret == 0) goto cleanup;
  1800. mod = mbi.AllocationBase;
  1801. do {
  1802. *filename = (LPWSTR) realloc(*filename, size * sizeof(WCHAR));
  1803. if (*filename == NULL) goto cleanup;
  1804. GetModuleFileName(mod, *filename, size);
  1805. size <<= 1;
  1806. err = GetLastError();
  1807. } while (err == ERROR_INSUFFICIENT_BUFFER);
  1808. if (err != ERROR_SUCCESS) goto cleanup;
  1809. return;
  1810. cleanup:
  1811. if (*filename != NULL)
  1812. {
  1813. free(*filename);
  1814. *filename = NULL;
  1815. }
  1816. }
  1817. // Function: AssignLsaString
  1818. //
  1819. // Description:
  1820. // fills in values of LSA_STRING struct to point to a string buffer
  1821. //
  1822. // Returns:
  1823. // None
  1824. //
  1825. // IMPORTANT*** strBuf is not copied. It must be globally immutable
  1826. //
  1827. void AssignLsaString(__inout LSA_STRING * target, __in const char *strBuf)
  1828. {
  1829. target->Length = (USHORT)(sizeof(char)*strlen(strBuf));
  1830. target->MaximumLength = target->Length;
  1831. target->Buffer = (char *)(strBuf);
  1832. }
  1833. //----------------------------------------------------------------------------
  1834. // Function: RegisterWithLsa
  1835. //
  1836. // Description:
  1837. // Registers with local security authority and sets handle for use in later LSA
  1838. // operations
  1839. //
  1840. // Returns:
  1841. // ERROR_SUCCESS on success
  1842. // Other error code on failure
  1843. //
  1844. // Notes:
  1845. //
  1846. DWORD RegisterWithLsa(__in const char *logonProcessName, __out HANDLE * lsaHandle)
  1847. {
  1848. LSA_STRING processName;
  1849. LSA_OPERATIONAL_MODE o_mode; // never useful as per msdn docs
  1850. NTSTATUS registerStatus;
  1851. *lsaHandle = 0;
  1852. AssignLsaString(&processName, logonProcessName);
  1853. registerStatus = LsaRegisterLogonProcess(&processName, lsaHandle, &o_mode);
  1854. return LsaNtStatusToWinError( registerStatus );
  1855. }
  1856. //----------------------------------------------------------------------------
  1857. // Function: UnregisterWithLsa
  1858. //
  1859. // Description:
  1860. // Closes LSA handle allocated by RegisterWithLsa()
  1861. //
  1862. // Returns:
  1863. // None
  1864. //
  1865. // Notes:
  1866. //
  1867. void UnregisterWithLsa(__in HANDLE lsaHandle)
  1868. {
  1869. LsaClose(lsaHandle);
  1870. }
  1871. //----------------------------------------------------------------------------
  1872. // Function: LookupKerberosAuthenticationPackageId
  1873. //
  1874. // Description:
  1875. // Looks of the current id (integer index) of the Kerberos authentication package on the local
  1876. // machine.
  1877. //
  1878. // Returns:
  1879. // ERROR_SUCCESS on success
  1880. // Other error code on failure
  1881. //
  1882. // Notes:
  1883. //
  1884. DWORD LookupKerberosAuthenticationPackageId(__in HANDLE lsaHandle, __out ULONG * packageId)
  1885. {
  1886. NTSTATUS lookupStatus;
  1887. LSA_STRING pkgName;
  1888. AssignLsaString(&pkgName, MICROSOFT_KERBEROS_NAME_A);
  1889. lookupStatus = LsaLookupAuthenticationPackage(lsaHandle, &pkgName, packageId);
  1890. return LsaNtStatusToWinError( lookupStatus );
  1891. }
  1892. //----------------------------------------------------------------------------
  1893. // Function: CreateLogonTokenForUser
  1894. //
  1895. // Description:
  1896. // Contacts the local LSA and performs a logon without credential for the
  1897. // given principal. This logon token will be local machine only and have no
  1898. // network credentials attached.
  1899. //
  1900. // Returns:
  1901. // ERROR_SUCCESS on success
  1902. // Other error code on failure
  1903. //
  1904. // Notes:
  1905. // This call assumes that all required privileges have already been enabled (TCB etc).
  1906. // IMPORTANT **** tokenOriginName must be immutable!
  1907. //
  1908. DWORD CreateLogonTokenForUser(__in HANDLE lsaHandle,
  1909. __in const char * tokenSourceName,
  1910. __in const char * tokenOriginName, // must be immutable, will not be copied!
  1911. __in ULONG authnPkgId,
  1912. __in const wchar_t* principalName,
  1913. __out HANDLE *tokenHandle)
  1914. {
  1915. DWORD logonStatus = ERROR_ASSERTION_FAILURE; // Failure to set status should trigger error
  1916. TOKEN_SOURCE tokenSource;
  1917. LSA_STRING originName;
  1918. void * profile = NULL;
  1919. // from MSDN:
  1920. // The ClientUpn and ClientRealm members of the KERB_S4U_LOGON
  1921. // structure must point to buffers in memory that are contiguous
  1922. // to the structure itself. The value of the
  1923. // AuthenticationInformationLength parameter must take into
  1924. // account the length of these buffers.
  1925. const int principalNameBufLen = lstrlen(principalName)*sizeof(*principalName);
  1926. const int totalAuthInfoLen = sizeof(KERB_S4U_LOGON) + principalNameBufLen;
  1927. KERB_S4U_LOGON* s4uLogonAuthInfo = (KERB_S4U_LOGON*)calloc(totalAuthInfoLen, 1);
  1928. if (s4uLogonAuthInfo == NULL ) {
  1929. logonStatus = ERROR_NOT_ENOUGH_MEMORY;
  1930. goto done;
  1931. }
  1932. s4uLogonAuthInfo->MessageType = KerbS4ULogon;
  1933. s4uLogonAuthInfo->ClientUpn.Buffer = (wchar_t*)((char*)s4uLogonAuthInfo + sizeof *s4uLogonAuthInfo);
  1934. CopyMemory(s4uLogonAuthInfo->ClientUpn.Buffer, principalName, principalNameBufLen);
  1935. s4uLogonAuthInfo->ClientUpn.Length = (USHORT)principalNameBufLen;
  1936. s4uLogonAuthInfo->ClientUpn.MaximumLength = (USHORT)principalNameBufLen;
  1937. AllocateLocallyUniqueId(&tokenSource.SourceIdentifier);
  1938. StringCchCopyA(tokenSource.SourceName, TOKEN_SOURCE_LENGTH, tokenSourceName );
  1939. AssignLsaString(&originName, tokenOriginName);
  1940. {
  1941. DWORD cbProfile = 0;
  1942. LUID logonId;
  1943. QUOTA_LIMITS quotaLimits;
  1944. NTSTATUS subStatus;
  1945. NTSTATUS logonNtStatus = LsaLogonUser(lsaHandle,
  1946. &originName,
  1947. Batch, // SECURITY_LOGON_TYPE
  1948. authnPkgId,
  1949. s4uLogonAuthInfo,
  1950. totalAuthInfoLen,
  1951. 0,
  1952. &tokenSource,
  1953. &profile,
  1954. &cbProfile,
  1955. &logonId,
  1956. tokenHandle,
  1957. &quotaLimits,
  1958. &subStatus);
  1959. logonStatus = LsaNtStatusToWinError( logonNtStatus );
  1960. }
  1961. done:
  1962. // clean up
  1963. if (s4uLogonAuthInfo != NULL) {
  1964. free(s4uLogonAuthInfo);
  1965. }
  1966. if (profile != NULL) {
  1967. LsaFreeReturnBuffer(profile);
  1968. }
  1969. return logonStatus;
  1970. }
  1971. // NOTE: must free allocatedName
  1972. DWORD GetNameFromLogonToken(__in HANDLE logonToken, __out wchar_t **allocatedName)
  1973. {
  1974. DWORD userInfoSize = 0;
  1975. PTOKEN_USER user = NULL;
  1976. DWORD userNameSize = 0;
  1977. wchar_t * userName = NULL;
  1978. DWORD domainNameSize = 0;
  1979. wchar_t * domainName = NULL;
  1980. SID_NAME_USE sidUse = SidTypeUnknown;
  1981. DWORD getNameStatus = ERROR_ASSERTION_FAILURE; // Failure to set status should trigger error
  1982. BOOL tokenInformation = FALSE;
  1983. // call for sid size then alloc and call for sid
  1984. tokenInformation = GetTokenInformation(logonToken, TokenUser, NULL, 0, &userInfoSize);
  1985. assert (FALSE == tokenInformation);
  1986. // last call should have failed and filled in allocation size
  1987. if ((getNameStatus = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
  1988. {
  1989. goto done;
  1990. }
  1991. user = (PTOKEN_USER)calloc(userInfoSize,1);
  1992. if (user == NULL)
  1993. {
  1994. getNameStatus = ERROR_NOT_ENOUGH_MEMORY;
  1995. goto done;
  1996. }
  1997. if (!GetTokenInformation(logonToken, TokenUser, user, userInfoSize, &userInfoSize)) {
  1998. getNameStatus = GetLastError();
  1999. goto done;
  2000. }
  2001. LookupAccountSid( NULL, user->User.Sid, NULL, &userNameSize, NULL, &domainNameSize, &sidUse );
  2002. // last call should have failed and filled in allocation size
  2003. if ((getNameStatus = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
  2004. {
  2005. goto done;
  2006. }
  2007. userName = (wchar_t *)calloc(userNameSize, sizeof(wchar_t));
  2008. if (userName == NULL) {
  2009. getNameStatus = ERROR_NOT_ENOUGH_MEMORY;
  2010. goto done;
  2011. }
  2012. domainName = (wchar_t *)calloc(domainNameSize, sizeof(wchar_t));
  2013. if (domainName == NULL) {
  2014. getNameStatus = ERROR_NOT_ENOUGH_MEMORY;
  2015. goto done;
  2016. }
  2017. if (!LookupAccountSid( NULL, user->User.Sid, userName, &userNameSize, domainName, &domainNameSize, &sidUse )) {
  2018. getNameStatus = GetLastError();
  2019. goto done;
  2020. }
  2021. getNameStatus = ERROR_SUCCESS;
  2022. *allocatedName = userName;
  2023. userName = NULL;
  2024. done:
  2025. if (user != NULL) {
  2026. free( user );
  2027. user = NULL;
  2028. }
  2029. if (userName != NULL) {
  2030. free( userName );
  2031. userName = NULL;
  2032. }
  2033. if (domainName != NULL) {
  2034. free( domainName );
  2035. domainName = NULL;
  2036. }
  2037. return getNameStatus;
  2038. }
  2039. DWORD LoadUserProfileForLogon(__in HANDLE logonHandle, __out PROFILEINFO * pi)
  2040. {
  2041. wchar_t *userName = NULL;
  2042. DWORD loadProfileStatus = ERROR_ASSERTION_FAILURE; // Failure to set status should trigger error
  2043. loadProfileStatus = GetNameFromLogonToken( logonHandle, &userName );
  2044. if (loadProfileStatus != ERROR_SUCCESS) {
  2045. goto done;
  2046. }
  2047. assert(pi);
  2048. ZeroMemory( pi, sizeof(*pi) );
  2049. pi->dwSize = sizeof(*pi);
  2050. pi->lpUserName = userName;
  2051. pi->dwFlags = PI_NOUI;
  2052. // if the profile does not exist it will be created
  2053. if ( !LoadUserProfile( logonHandle, pi ) ) {
  2054. loadProfileStatus = GetLastError();
  2055. goto done;
  2056. }
  2057. loadProfileStatus = ERROR_SUCCESS;
  2058. done:
  2059. return loadProfileStatus;
  2060. }
  2061. DWORD UnloadProfileForLogon(__in HANDLE logonHandle, __in PROFILEINFO * pi)
  2062. {
  2063. DWORD touchProfileStatus = ERROR_ASSERTION_FAILURE; // Failure to set status should trigger error
  2064. assert(pi);
  2065. if ( !UnloadUserProfile(logonHandle, pi->hProfile ) ) {
  2066. touchProfileStatus = GetLastError();
  2067. goto done;
  2068. }
  2069. if (pi->lpUserName != NULL) {
  2070. free(pi->lpUserName);
  2071. pi->lpUserName = NULL;
  2072. }
  2073. ZeroMemory( pi, sizeof(*pi) );
  2074. touchProfileStatus = ERROR_SUCCESS;
  2075. done:
  2076. return touchProfileStatus;
  2077. }
  2078. //----------------------------------------------------------------------------
  2079. // Function: ChangeFileOwnerBySid
  2080. //
  2081. // Description:
  2082. // Change a file or directory ownership by giving new owner and group SIDs
  2083. //
  2084. // Returns:
  2085. // ERROR_SUCCESS: on success
  2086. // Error code: otherwise
  2087. //
  2088. // Notes:
  2089. // This function is long path safe, i.e. the path will be converted to long
  2090. // path format if not already converted. So the caller does not need to do
  2091. // the converstion before calling the method.
  2092. //
  2093. DWORD ChangeFileOwnerBySid(__in LPCWSTR path,
  2094. __in_opt PSID pNewOwnerSid, __in_opt PSID pNewGroupSid)
  2095. {
  2096. LPWSTR longPathName = NULL;
  2097. INT oldMode = 0;
  2098. SECURITY_INFORMATION securityInformation = 0;
  2099. DWORD dwRtnCode = ERROR_SUCCESS;
  2100. // Convert the path the the long path
  2101. //
  2102. dwRtnCode = ConvertToLongPath(path, &longPathName);
  2103. if (dwRtnCode != ERROR_SUCCESS)
  2104. {
  2105. goto ChangeFileOwnerByNameEnd;
  2106. }
  2107. // Get a pointer to the existing owner information and DACL
  2108. //
  2109. dwRtnCode = FindFileOwnerAndPermission(longPathName, FALSE, NULL, NULL, &oldMode);
  2110. if (dwRtnCode != ERROR_SUCCESS)
  2111. {
  2112. goto ChangeFileOwnerByNameEnd;
  2113. }
  2114. // We need SeTakeOwnershipPrivilege to set the owner if the caller does not
  2115. // have WRITE_OWNER access to the object; we need SeRestorePrivilege if the
  2116. // SID is not contained in the caller's token, and have the SE_GROUP_OWNER
  2117. // permission enabled.
  2118. //
  2119. if (EnablePrivilege(L"SeTakeOwnershipPrivilege") != ERROR_SUCCESS)
  2120. {
  2121. fwprintf(stdout, L"INFO: The user does not have SeTakeOwnershipPrivilege.\n");
  2122. }
  2123. if (EnablePrivilege(L"SeRestorePrivilege") != ERROR_SUCCESS)
  2124. {
  2125. fwprintf(stdout, L"INFO: The user does not have SeRestorePrivilege.\n");
  2126. }
  2127. assert(pNewOwnerSid != NULL || pNewGroupSid != NULL);
  2128. // Set the owners of the file.
  2129. //
  2130. if (pNewOwnerSid != NULL) securityInformation |= OWNER_SECURITY_INFORMATION;
  2131. if (pNewGroupSid != NULL) securityInformation |= GROUP_SECURITY_INFORMATION;
  2132. dwRtnCode = SetNamedSecurityInfoW(
  2133. longPathName,
  2134. SE_FILE_OBJECT,
  2135. securityInformation,
  2136. pNewOwnerSid,
  2137. pNewGroupSid,
  2138. NULL,
  2139. NULL);
  2140. if (dwRtnCode != ERROR_SUCCESS)
  2141. {
  2142. goto ChangeFileOwnerByNameEnd;
  2143. }
  2144. // Set the permission on the file for the new owner.
  2145. //
  2146. dwRtnCode = ChangeFileModeByMask(longPathName, oldMode);
  2147. if (dwRtnCode != ERROR_SUCCESS)
  2148. {
  2149. goto ChangeFileOwnerByNameEnd;
  2150. }
  2151. ChangeFileOwnerByNameEnd:
  2152. LocalFree(longPathName);
  2153. return dwRtnCode;
  2154. }
  2155. //-----------------------------------------------------------------------------
  2156. // Function: GetSecureJobObjectName
  2157. //
  2158. // Description:
  2159. // Creates a job object name usable in a secure environment: adds the Golbal\
  2160. //
  2161. DWORD GetSecureJobObjectName(
  2162. __in LPCWSTR jobName,
  2163. __in size_t cchSecureJobName,
  2164. __out_ecount(cchSecureJobName) LPWSTR secureJobName) {
  2165. HRESULT hr = StringCchPrintf(secureJobName, cchSecureJobName,
  2166. L"Global\\%s", jobName);
  2167. if (FAILED(hr)) {
  2168. return HRESULT_CODE(hr);
  2169. }
  2170. return ERROR_SUCCESS;
  2171. }
  2172. //-----------------------------------------------------------------------------
  2173. // Function: EnableImpersonatePrivileges
  2174. //
  2175. // Description:
  2176. // Enables the required privileges for S4U impersonation
  2177. //
  2178. // Returns:
  2179. // ERROR_SUCCESS: On success
  2180. //
  2181. DWORD EnableImpersonatePrivileges() {
  2182. DWORD dwError = ERROR_SUCCESS;
  2183. LPCWSTR privilege = NULL;
  2184. int crt = 0;
  2185. LPCWSTR privileges[] = {
  2186. SE_IMPERSONATE_NAME,
  2187. SE_TCB_NAME,
  2188. SE_ASSIGNPRIMARYTOKEN_NAME,
  2189. SE_INCREASE_QUOTA_NAME,
  2190. SE_RESTORE_NAME,
  2191. SE_DEBUG_NAME,
  2192. SE_SECURITY_NAME,
  2193. };
  2194. for (crt = 0; crt < sizeof(privileges)/sizeof(LPCWSTR); ++crt) {
  2195. LPCWSTR privilege = privileges[crt];
  2196. dwError = EnablePrivilege(privilege);
  2197. if( dwError != ERROR_SUCCESS ) {
  2198. LogDebugMessage(L"Failed to enable privilege: %s\n", privilege);
  2199. ReportErrorCode(L"EnablePrivilege", dwError);
  2200. goto done;
  2201. }
  2202. }
  2203. done:
  2204. return dwError;
  2205. }
  2206. //-----------------------------------------------------------------------------
  2207. // Function: KillTask
  2208. //
  2209. // Description:
  2210. // Kills a task via a jobobject. Outputs the
  2211. // appropriate information to stdout on success, or stderr on failure.
  2212. //
  2213. // Returns:
  2214. // ERROR_SUCCESS: On success
  2215. // GetLastError: otherwise
  2216. DWORD KillTask(PCWSTR jobObjName)
  2217. {
  2218. DWORD dwError = ERROR_SUCCESS;
  2219. HANDLE jobObject = OpenJobObject(JOB_OBJECT_TERMINATE, FALSE, jobObjName);
  2220. if(jobObject == NULL)
  2221. {
  2222. dwError = GetLastError();
  2223. if(dwError == ERROR_FILE_NOT_FOUND)
  2224. {
  2225. // job object does not exist. assume its not alive
  2226. dwError = ERROR_SUCCESS;
  2227. }
  2228. goto done;
  2229. }
  2230. if(TerminateJobObject(jobObject, KILLED_PROCESS_EXIT_CODE) == 0)
  2231. {
  2232. dwError = GetLastError();
  2233. }
  2234. done:
  2235. CloseHandle(jobObject);
  2236. return dwError;
  2237. }
  2238. DWORD ChownImpl(
  2239. __in_opt LPCWSTR userName,
  2240. __in_opt LPCWSTR groupName,
  2241. __in LPCWSTR pathName) {
  2242. DWORD dwError;
  2243. PSID pNewOwnerSid = NULL;
  2244. PSID pNewGroupSid = NULL;
  2245. if (userName != NULL)
  2246. {
  2247. dwError = GetSidFromAcctNameW(userName, &pNewOwnerSid);
  2248. if (dwError != ERROR_SUCCESS)
  2249. {
  2250. ReportErrorCode(L"GetSidFromAcctName", dwError);
  2251. fwprintf(stderr, L"Invalid user name: %s\n", userName);
  2252. goto done;
  2253. }
  2254. }
  2255. if (groupName != NULL)
  2256. {
  2257. dwError = GetSidFromAcctNameW(groupName, &pNewGroupSid);
  2258. if (dwError != ERROR_SUCCESS)
  2259. {
  2260. ReportErrorCode(L"GetSidFromAcctName", dwError);
  2261. fwprintf(stderr, L"Invalid group name: %s\n", groupName);
  2262. goto done;
  2263. }
  2264. }
  2265. if (wcslen(pathName) == 0 || wcsspn(pathName, L"/?|><:*\"") != 0)
  2266. {
  2267. fwprintf(stderr, L"Incorrect file name format: %s\n", pathName);
  2268. goto done;
  2269. }
  2270. dwError = ChangeFileOwnerBySid(pathName, pNewOwnerSid, pNewGroupSid);
  2271. if (dwError != ERROR_SUCCESS)
  2272. {
  2273. ReportErrorCode(L"ChangeFileOwnerBySid", dwError);
  2274. goto done;
  2275. }
  2276. done:
  2277. LocalFree(pNewOwnerSid);
  2278. LocalFree(pNewGroupSid);
  2279. return dwError;
  2280. }
  2281. LPCWSTR GetSystemTimeString() {
  2282. __declspec(thread) static WCHAR buffer[1024];
  2283. DWORD dwError;
  2284. FILETIME ftime;
  2285. SYSTEMTIME systime;
  2286. LARGE_INTEGER counter, frequency;
  2287. int subSec;
  2288. double qpc;
  2289. HRESULT hr;
  2290. buffer[0] = L'\0';
  2291. // GetSystemTimePreciseAsFileTime is only available in Win8+ and our libs do not link against it
  2292. GetSystemTimeAsFileTime(&ftime);
  2293. if (!FileTimeToSystemTime(&ftime, &systime)) {
  2294. dwError = GetLastError();
  2295. LogDebugMessage(L"FileTimeToSystemTime error:%d\n", dwError);
  2296. goto done;
  2297. }
  2298. // Get the ms from QPC. GetSystemTimeAdjustment is ignored...
  2299. QueryPerformanceCounter(&counter);
  2300. QueryPerformanceFrequency(&frequency);
  2301. qpc = (double) counter.QuadPart / (double) frequency.QuadPart;
  2302. subSec = ((qpc - (long)qpc) * 1000000);
  2303. hr = StringCbPrintf(buffer, sizeof(buffer), L"%02d:%02d:%02d.%06d",
  2304. (int)systime.wHour, (int)systime.wMinute, (int)systime.wSecond, (int)subSec);
  2305. if (FAILED(hr)) {
  2306. LogDebugMessage(L"StringCbPrintf error:%d\n", hr);
  2307. }
  2308. done:
  2309. return buffer;
  2310. }
  2311. //----------------------------------------------------------------------------
  2312. // Function: LogDebugMessage
  2313. //
  2314. // Description:
  2315. // Sends a message to the debugger console, if one is attached
  2316. //
  2317. // Notes:
  2318. // Native debugger: windbg, ntsd, cdb, visual studio
  2319. //
  2320. VOID LogDebugMessage(LPCWSTR format, ...) {
  2321. LPWSTR buffer[8192];
  2322. va_list args;
  2323. HRESULT hr;
  2324. if (!IsDebuggerPresent()) return;
  2325. va_start(args, format);
  2326. hr = StringCbVPrintf(buffer, sizeof(buffer), format, args);
  2327. if (SUCCEEDED(hr)) {
  2328. OutputDebugString(buffer);
  2329. }
  2330. va_end(args);
  2331. }
  2332. //----------------------------------------------------------------------------
  2333. // Function: SplitStringIgnoreSpaceW
  2334. //
  2335. // Description:
  2336. // splits a null-terminated string based on a delimiter
  2337. //
  2338. // Returns:
  2339. // ERROR_SUCCESS: on success
  2340. // error code: otherwise
  2341. //
  2342. // Notes:
  2343. // The tokes are also null-terminated
  2344. // Caller should use LocalFree to clear outTokens
  2345. //
  2346. DWORD SplitStringIgnoreSpaceW(
  2347. __in size_t len,
  2348. __in_ecount(len) LPCWSTR source,
  2349. __in WCHAR deli,
  2350. __out size_t* count,
  2351. __out_ecount(count) WCHAR*** outTokens) {
  2352. size_t tokenCount = 0;
  2353. size_t crtSource;
  2354. size_t crtToken = 0;
  2355. WCHAR* lpwszTokenStart = NULL;
  2356. WCHAR* lpwszTokenEnd = NULL;
  2357. WCHAR* lpwszBuffer = NULL;
  2358. size_t tokenLength = 0;
  2359. size_t cchBufferLength = 0;
  2360. WCHAR crt;
  2361. WCHAR** tokens = NULL;
  2362. enum {BLANK, TOKEN, DELIMITER} State = BLANK;
  2363. for(crtSource = 0; crtSource < len; ++crtSource) {
  2364. crt = source[crtSource];
  2365. switch(State) {
  2366. case BLANK: // intentional fallthrough
  2367. case DELIMITER:
  2368. if (crt == deli) {
  2369. State = DELIMITER;
  2370. }
  2371. else if (!iswspace(crt)) {
  2372. ++tokenCount;
  2373. lpwszTokenEnd = lpwszTokenStart = source + crtSource;
  2374. State = TOKEN;
  2375. }
  2376. else {
  2377. State = BLANK;
  2378. }
  2379. break;
  2380. case TOKEN:
  2381. if (crt == deli) {
  2382. State = DELIMITER;
  2383. cchBufferLength += lpwszTokenEnd - lpwszTokenStart + 2;
  2384. }
  2385. else if (!iswspace(crt)) {
  2386. lpwszTokenEnd = source + crtSource;
  2387. }
  2388. break;
  2389. }
  2390. }
  2391. if (State == TOKEN) {
  2392. cchBufferLength += lpwszTokenEnd - lpwszTokenStart + 2;
  2393. }
  2394. LogDebugMessage(L"counted %d [buffer:%d] tokens in %s\n", tokenCount, cchBufferLength, source);
  2395. #define COPY_CURRENT_TOKEN \
  2396. tokenLength = lpwszTokenEnd - lpwszTokenStart + 1; \
  2397. tokens[crtToken] = lpwszBuffer; \
  2398. memcpy(tokens[crtToken], lpwszTokenStart, tokenLength*sizeof(WCHAR)); \
  2399. tokens[crtToken][tokenLength] = L'\0'; \
  2400. lpwszBuffer += (tokenLength+1); \
  2401. ++crtToken;
  2402. if (tokenCount) {
  2403. // We use one contigous memory for both the pointer arrays and the data copy buffers
  2404. // We cannot use in-place references (zero-copy) because the function users
  2405. // need null-terminated strings for the tokens
  2406. tokens = (WCHAR**) LocalAlloc(LPTR,
  2407. sizeof(WCHAR*) * tokenCount + // for the pointers
  2408. sizeof(WCHAR) * cchBufferLength); // for the data
  2409. // Data will be copied after the array
  2410. lpwszBuffer = (WCHAR*)(((BYTE*)tokens) + (sizeof(WCHAR*) * tokenCount));
  2411. State = BLANK;
  2412. for(crtSource = 0; crtSource < len; ++crtSource) {
  2413. crt = source[crtSource];
  2414. switch(State) {
  2415. case DELIMITER: // intentional fallthrough
  2416. case BLANK:
  2417. if (crt == deli) {
  2418. State = DELIMITER;
  2419. }
  2420. else if (!iswspace(crt)) {
  2421. lpwszTokenEnd = lpwszTokenStart = source + crtSource;
  2422. State = TOKEN;
  2423. }
  2424. else {
  2425. State = BLANK;
  2426. }
  2427. break;
  2428. case TOKEN:
  2429. if (crt == deli) {
  2430. COPY_CURRENT_TOKEN;
  2431. State = DELIMITER;
  2432. }
  2433. else if (!iswspace(crt)) {
  2434. lpwszTokenEnd = source + crtSource;
  2435. }
  2436. break;
  2437. }
  2438. }
  2439. // Copy out last token, if any
  2440. if (TOKEN == State) {
  2441. COPY_CURRENT_TOKEN;
  2442. }
  2443. }
  2444. *count = tokenCount;
  2445. *outTokens = tokens;
  2446. return ERROR_SUCCESS;
  2447. }
  2448. //----------------------------------------------------------------------------
  2449. // Function: BuildServiceSecurityDescriptor
  2450. //
  2451. // Description:
  2452. // Builds a security descriptor for an arbitrary object
  2453. //
  2454. // Returns:
  2455. // ERROR_SUCCESS: on success
  2456. // error code: otherwise
  2457. //
  2458. // Notes:
  2459. // The SD is a of the self-contained flavor (offsets, not pointers)
  2460. // Caller should use LocalFree to clear allocated pSD
  2461. //
  2462. DWORD BuildServiceSecurityDescriptor(
  2463. __in ACCESS_MASK accessMask,
  2464. __in size_t grantSidCount,
  2465. __in_ecount(grantSidCount) PSID* pGrantSids,
  2466. __in size_t denySidCount,
  2467. __in_ecount(denySidCount) PSID* pDenySids,
  2468. __in_opt PSID pOwner,
  2469. __out PSECURITY_DESCRIPTOR* pSD) {
  2470. DWORD dwError = ERROR_SUCCESS;
  2471. unsigned int crt = 0;
  2472. int len = 0;
  2473. EXPLICIT_ACCESS* eas = NULL;
  2474. LPWSTR lpszSD = NULL;
  2475. ULONG cchSD = 0;
  2476. HANDLE hToken = INVALID_HANDLE_VALUE;
  2477. DWORD dwBufferSize = 0;
  2478. PTOKEN_USER pTokenUser = NULL;
  2479. PTOKEN_PRIMARY_GROUP pTokenGroup = NULL;
  2480. PSECURITY_DESCRIPTOR pTempSD = NULL;
  2481. ULONG cbSD = 0;
  2482. TRUSTEE owner, group;
  2483. ZeroMemory(&owner, sizeof(owner));
  2484. // We'll need our own SID to add as SD owner
  2485. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {
  2486. dwError = GetLastError();
  2487. LogDebugMessage(L"OpenProcessToken: %d\n", dwError);
  2488. goto done;
  2489. }
  2490. if (NULL == pOwner) {
  2491. if (!GetTokenInformation(hToken, TokenUser, NULL, 0, &dwBufferSize)) {
  2492. dwError = GetLastError();
  2493. if (ERROR_INSUFFICIENT_BUFFER != dwError) {
  2494. LogDebugMessage(L"GetTokenInformation: %d\n", dwError);
  2495. goto done;
  2496. }
  2497. }
  2498. pTokenUser = (PTOKEN_USER) LocalAlloc(LPTR, dwBufferSize);
  2499. if (NULL == pTokenUser) {
  2500. dwError = GetLastError();
  2501. LogDebugMessage(L"LocalAlloc:pTokenUser: %d\n", dwError);
  2502. goto done;
  2503. }
  2504. if (!GetTokenInformation(hToken, TokenUser, pTokenUser, dwBufferSize, &dwBufferSize)) {
  2505. dwError = GetLastError();
  2506. LogDebugMessage(L"GetTokenInformation: %d\n", dwError);
  2507. goto done;
  2508. }
  2509. if (!IsValidSid(pTokenUser->User.Sid)) {
  2510. dwError = ERROR_INVALID_PARAMETER;
  2511. LogDebugMessage(L"IsValidSid: %d\n", dwError);
  2512. goto done;
  2513. }
  2514. pOwner = pTokenUser->User.Sid;
  2515. }
  2516. dwBufferSize = 0;
  2517. if (!GetTokenInformation(hToken, TokenPrimaryGroup, NULL, 0, &dwBufferSize)) {
  2518. dwError = GetLastError();
  2519. if (ERROR_INSUFFICIENT_BUFFER != dwError) {
  2520. LogDebugMessage(L"GetTokenInformation: %d\n", dwError);
  2521. goto done;
  2522. }
  2523. }
  2524. pTokenGroup = (PTOKEN_USER) LocalAlloc(LPTR, dwBufferSize);
  2525. if (NULL == pTokenGroup) {
  2526. dwError = GetLastError();
  2527. LogDebugMessage(L"LocalAlloc:pTokenGroup: %d\n", dwError);
  2528. goto done;
  2529. }
  2530. if (!GetTokenInformation(hToken, TokenPrimaryGroup, pTokenGroup, dwBufferSize, &dwBufferSize)) {
  2531. dwError = GetLastError();
  2532. LogDebugMessage(L"GetTokenInformation: %d\n", dwError);
  2533. goto done;
  2534. }
  2535. if (!IsValidSid(pTokenGroup->PrimaryGroup)) {
  2536. dwError = ERROR_INVALID_PARAMETER;
  2537. LogDebugMessage(L"IsValidSid: %d\n", dwError);
  2538. goto done;
  2539. }
  2540. owner.TrusteeForm = TRUSTEE_IS_SID;
  2541. owner.TrusteeType = TRUSTEE_IS_UNKNOWN;
  2542. owner.ptstrName = (LPCWSTR) pOwner;
  2543. group.TrusteeForm = TRUSTEE_IS_SID;
  2544. group.TrusteeType = TRUSTEE_IS_UNKNOWN;
  2545. group.ptstrName = (LPCWSTR) pTokenGroup->PrimaryGroup;
  2546. eas = (EXPLICIT_ACCESS*) LocalAlloc(LPTR, sizeof(EXPLICIT_ACCESS) * (grantSidCount + denySidCount));
  2547. if (NULL == eas) {
  2548. dwError = ERROR_OUTOFMEMORY;
  2549. LogDebugMessage(L"LocalAlloc: %d\n", dwError);
  2550. goto done;
  2551. }
  2552. // Build the granted list
  2553. for (crt = 0; crt < grantSidCount; ++crt) {
  2554. eas[crt].grfAccessPermissions = accessMask;
  2555. eas[crt].grfAccessMode = GRANT_ACCESS;
  2556. eas[crt].grfInheritance = NO_INHERITANCE;
  2557. eas[crt].Trustee.TrusteeForm = TRUSTEE_IS_SID;
  2558. eas[crt].Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
  2559. eas[crt].Trustee.ptstrName = (LPCWSTR) pGrantSids[crt];
  2560. eas[crt].Trustee.pMultipleTrustee = NULL;
  2561. eas[crt].Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
  2562. }
  2563. // Build the deny list
  2564. for (; crt < grantSidCount + denySidCount; ++crt) {
  2565. eas[crt].grfAccessPermissions = accessMask;
  2566. eas[crt].grfAccessMode = DENY_ACCESS;
  2567. eas[crt].grfInheritance = NO_INHERITANCE;
  2568. eas[crt].Trustee.TrusteeForm = TRUSTEE_IS_SID;
  2569. eas[crt].Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
  2570. eas[crt].Trustee.ptstrName = (LPCWSTR) pDenySids[crt - grantSidCount];
  2571. eas[crt].Trustee.pMultipleTrustee = NULL;
  2572. eas[crt].Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
  2573. }
  2574. dwError = BuildSecurityDescriptor(
  2575. &owner,
  2576. &group,
  2577. crt,
  2578. eas,
  2579. 0, // cCountOfAuditEntries
  2580. NULL, // pListOfAuditEntries
  2581. NULL, // pOldSD
  2582. &cbSD,
  2583. &pTempSD);
  2584. if (ERROR_SUCCESS != dwError) {
  2585. LogDebugMessage(L"BuildSecurityDescriptor: %d\n", dwError);
  2586. goto done;
  2587. }
  2588. *pSD = pTempSD;
  2589. pTempSD = NULL;
  2590. if (IsDebuggerPresent()) {
  2591. ConvertSecurityDescriptorToStringSecurityDescriptor(*pSD,
  2592. SDDL_REVISION_1,
  2593. DACL_SECURITY_INFORMATION,
  2594. &lpszSD,
  2595. &cchSD);
  2596. LogDebugMessage(L"pSD: %.*s\n", cchSD, lpszSD);
  2597. }
  2598. done:
  2599. if (eas) LocalFree(eas);
  2600. if (pTokenUser) LocalFree(pTokenUser);
  2601. if (INVALID_HANDLE_VALUE != hToken) CloseHandle(hToken);
  2602. if (lpszSD) LocalFree(lpszSD);
  2603. if (pTempSD) LocalFree(pTempSD);
  2604. return dwError;
  2605. }
  2606. //----------------------------------------------------------------------------
  2607. // Function: MIDL_user_allocate
  2608. //
  2609. // Description:
  2610. // Hard-coded function name used by RPC midl code for allocations
  2611. //
  2612. // Notes:
  2613. // Must match the de-allocation mechanism used in MIDL_user_free
  2614. //
  2615. void __RPC_FAR * __RPC_USER MIDL_user_allocate(size_t len)
  2616. {
  2617. return LocalAlloc(LPTR, len);
  2618. }
  2619. //----------------------------------------------------------------------------
  2620. // Function: MIDL_user_free
  2621. //
  2622. // Description:
  2623. // Hard-coded function name used by RPC midl code for deallocations
  2624. //
  2625. // NoteS:
  2626. // Must match the allocation mechanism used in MIDL_user_allocate
  2627. //
  2628. void __RPC_USER MIDL_user_free(void __RPC_FAR * ptr)
  2629. {
  2630. LocalFree(ptr);
  2631. }