libwinutils.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711
  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. #include "winutils.h"
  20. #include <authz.h>
  21. #include <sddl.h>
  22. /*
  23. * The array of 12 months' three-letter abbreviations
  24. */
  25. const LPCWSTR MONTHS[] = { L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun",
  26. L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec" };
  27. /*
  28. * The WindowsAclMask and WinMasks contain the definitions used to establish
  29. * the mapping between Unix and Windows.
  30. * We set up the mapping with the following rules.
  31. * 1. Everyone will have WIN_ALL permissions;
  32. * 2. Owner will always have WIN_OWNER_SE permissions in addition;
  33. * 2. When Unix read/write/excute permission is set on the file, the
  34. * corresponding Windows allow ACE will be added to the file.
  35. * More details and explaination can be found in the following white paper:
  36. * http://technet.microsoft.com/en-us/library/bb463216.aspx
  37. */
  38. const ACCESS_MASK WinMasks[WIN_MASKS_TOTAL] =
  39. {
  40. /* WIN_READ */
  41. FILE_READ_DATA,
  42. /* WIN_WRITE */
  43. FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_APPEND_DATA | FILE_WRITE_EA |
  44. FILE_DELETE_CHILD,
  45. /* WIN_EXECUTE */
  46. FILE_EXECUTE,
  47. /* WIN_OWNER_SE */
  48. DELETE | WRITE_DAC | WRITE_OWNER | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES,
  49. /* WIN_ALL */
  50. READ_CONTROL | FILE_READ_EA | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
  51. };
  52. //----------------------------------------------------------------------------
  53. // Function: GetFileInformationByName
  54. //
  55. // Description:
  56. // To retrieve the by handle file information given the file name
  57. //
  58. // Returns:
  59. // ERROR_SUCCESS: on success
  60. // error code: otherwise
  61. //
  62. // Notes:
  63. // If followLink parameter is set to TRUE, we will follow the symbolic link
  64. // or junction point to get the target file information. Otherwise, the
  65. // information for the symbolic link or junction point is retrieved.
  66. //
  67. DWORD GetFileInformationByName(
  68. __in LPCWSTR pathName,
  69. __in BOOL followLink,
  70. __out LPBY_HANDLE_FILE_INFORMATION lpFileInformation)
  71. {
  72. HANDLE fileHandle = INVALID_HANDLE_VALUE;
  73. BOOL isSymlink = FALSE;
  74. BOOL isJunction = FALSE;
  75. DWORD dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS;
  76. DWORD dwErrorCode = ERROR_SUCCESS;
  77. assert(lpFileInformation != NULL);
  78. if (!followLink)
  79. {
  80. if ((dwErrorCode = SymbolicLinkCheck(pathName, &isSymlink)) != ERROR_SUCCESS)
  81. return dwErrorCode;
  82. if ((dwErrorCode = JunctionPointCheck(pathName, &isJunction)) != ERROR_SUCCESS)
  83. return dwErrorCode;
  84. if (isSymlink || isJunction)
  85. dwFlagsAndAttributes |= FILE_FLAG_OPEN_REPARSE_POINT;
  86. }
  87. fileHandle = CreateFileW(
  88. pathName,
  89. FILE_READ_ATTRIBUTES,
  90. FILE_SHARE_READ,
  91. NULL,
  92. OPEN_EXISTING,
  93. dwFlagsAndAttributes,
  94. NULL);
  95. if (fileHandle == INVALID_HANDLE_VALUE)
  96. {
  97. dwErrorCode = GetLastError();
  98. return dwErrorCode;
  99. }
  100. if (!GetFileInformationByHandle(fileHandle, lpFileInformation))
  101. {
  102. dwErrorCode = GetLastError();
  103. CloseHandle(fileHandle);
  104. return dwErrorCode;
  105. }
  106. CloseHandle(fileHandle);
  107. return dwErrorCode;
  108. }
  109. //----------------------------------------------------------------------------
  110. // Function: IsLongWindowsPath
  111. //
  112. // Description:
  113. // Checks if the path is longer than MAX_PATH in which case it needs to be
  114. // prepended with \\?\ for Windows OS to understand it.
  115. //
  116. // Returns:
  117. // TRUE long path
  118. // FALSE otherwise
  119. static BOOL IsLongWindowsPath(__in PCWSTR path)
  120. {
  121. return (wcslen(path) + 1) > MAX_PATH;
  122. }
  123. //----------------------------------------------------------------------------
  124. // Function: IsPrefixedAlready
  125. //
  126. // Description:
  127. // Checks if the given path is already prepended with \\?\.
  128. //
  129. // Returns:
  130. // TRUE if yes
  131. // FALSE otherwise
  132. static BOOL IsPrefixedAlready(__in PCWSTR path)
  133. {
  134. static const PCWSTR LongPathPrefix = L"\\\\?\\";
  135. size_t Prefixlen = wcslen(LongPathPrefix);
  136. size_t i = 0;
  137. if (path == NULL || wcslen(path) < Prefixlen)
  138. {
  139. return FALSE;
  140. }
  141. for (i = 0; i < Prefixlen; ++i)
  142. {
  143. if (path[i] != LongPathPrefix[i])
  144. {
  145. return FALSE;
  146. }
  147. }
  148. return TRUE;
  149. }
  150. //----------------------------------------------------------------------------
  151. // Function: ConvertToLongPath
  152. //
  153. // Description:
  154. // Prepends the path with the \\?\ prefix if the path is longer than MAX_PATH.
  155. // On success, newPath should be freed with LocalFree(). Given that relative
  156. // paths cannot be longer than MAX_PATH, we will never prepend the prefix
  157. // to relative paths.
  158. //
  159. // Returns:
  160. // ERROR_SUCCESS on success
  161. // error code on failure
  162. DWORD ConvertToLongPath(__in PCWSTR path, __deref_out PWSTR *newPath)
  163. {
  164. DWORD dwErrorCode = ERROR_SUCCESS;
  165. static const PCWSTR LongPathPrefix = L"\\\\?\\";
  166. BOOL bAppendPrefix = IsLongWindowsPath(path) && !IsPrefixedAlready(path);
  167. HRESULT hr = S_OK;
  168. size_t newPathLen = wcslen(path) + (bAppendPrefix ? wcslen(LongPathPrefix) : 0);
  169. // Allocate the buffer for the output path (+1 for terminating NULL char)
  170. //
  171. PWSTR newPathValue = (PWSTR)LocalAlloc(LPTR, (newPathLen + 1) * sizeof(WCHAR));
  172. if (newPathValue == NULL)
  173. {
  174. dwErrorCode = GetLastError();
  175. goto ConvertToLongPathExit;
  176. }
  177. if (bAppendPrefix)
  178. {
  179. // Append the prefix to the path
  180. //
  181. hr = StringCchPrintfW(newPathValue, newPathLen + 1, L"%s%s",
  182. LongPathPrefix, path);
  183. if (FAILED(hr))
  184. {
  185. dwErrorCode = HRESULT_CODE(hr);
  186. goto ConvertToLongPathExit;
  187. }
  188. }
  189. else
  190. {
  191. // Just copy the original value into the output path. In this scenario
  192. // we are doing extra buffer copy. We decided to trade code simplicity
  193. // on the call site for small performance impact (extra allocation and
  194. // buffer copy). As paths are short, the impact is generally small.
  195. //
  196. hr = StringCchPrintfW(newPathValue, newPathLen + 1, L"%s", path);
  197. if (FAILED(hr))
  198. {
  199. dwErrorCode = HRESULT_CODE(hr);
  200. goto ConvertToLongPathExit;
  201. }
  202. }
  203. *newPath = newPathValue;
  204. ConvertToLongPathExit:
  205. if (dwErrorCode != ERROR_SUCCESS)
  206. {
  207. LocalFree(newPathValue);
  208. }
  209. return dwErrorCode;
  210. }
  211. //----------------------------------------------------------------------------
  212. // Function: IsDirFileInfo
  213. //
  214. // Description:
  215. // Test if the given file information is a directory
  216. //
  217. // Returns:
  218. // TRUE if it is a directory
  219. // FALSE otherwise
  220. //
  221. // Notes:
  222. //
  223. BOOL IsDirFileInfo(const BY_HANDLE_FILE_INFORMATION *fileInformation)
  224. {
  225. if ((fileInformation->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  226. == FILE_ATTRIBUTE_DIRECTORY)
  227. return TRUE;
  228. return FALSE;
  229. }
  230. //----------------------------------------------------------------------------
  231. // Function: CheckFileAttributes
  232. //
  233. // Description:
  234. // Check if the given file has all the given attribute(s)
  235. //
  236. // Returns:
  237. // ERROR_SUCCESS on success
  238. // error code otherwise
  239. //
  240. // Notes:
  241. //
  242. static DWORD FileAttributesCheck(
  243. __in LPCWSTR path, __in DWORD attr, __out PBOOL res)
  244. {
  245. DWORD attrs = INVALID_FILE_ATTRIBUTES;
  246. *res = FALSE;
  247. if ((attrs = GetFileAttributes(path)) != INVALID_FILE_ATTRIBUTES)
  248. *res = ((attrs & attr) == attr);
  249. else
  250. return GetLastError();
  251. return ERROR_SUCCESS;
  252. }
  253. //----------------------------------------------------------------------------
  254. // Function: IsDirectory
  255. //
  256. // Description:
  257. // Check if the given file is a directory
  258. //
  259. // Returns:
  260. // ERROR_SUCCESS on success
  261. // error code otherwise
  262. //
  263. // Notes:
  264. //
  265. DWORD DirectoryCheck(__in LPCWSTR pathName, __out PBOOL res)
  266. {
  267. return FileAttributesCheck(pathName, FILE_ATTRIBUTE_DIRECTORY, res);
  268. }
  269. //----------------------------------------------------------------------------
  270. // Function: IsReparsePoint
  271. //
  272. // Description:
  273. // Check if the given file is a reparse point
  274. //
  275. // Returns:
  276. // ERROR_SUCCESS on success
  277. // error code otherwise
  278. //
  279. // Notes:
  280. //
  281. static DWORD ReparsePointCheck(__in LPCWSTR pathName, __out PBOOL res)
  282. {
  283. return FileAttributesCheck(pathName, FILE_ATTRIBUTE_REPARSE_POINT, res);
  284. }
  285. //----------------------------------------------------------------------------
  286. // Function: CheckReparseTag
  287. //
  288. // Description:
  289. // Check if the given file is a reparse point of the given tag.
  290. //
  291. // Returns:
  292. // ERROR_SUCCESS on success
  293. // error code otherwise
  294. //
  295. // Notes:
  296. //
  297. static DWORD ReparseTagCheck(__in LPCWSTR path, __in DWORD tag, __out PBOOL res)
  298. {
  299. BOOL isReparsePoint = FALSE;
  300. HANDLE hFind = INVALID_HANDLE_VALUE;
  301. WIN32_FIND_DATA findData;
  302. DWORD dwRtnCode;
  303. if ((dwRtnCode = ReparsePointCheck(path, &isReparsePoint)) != ERROR_SUCCESS)
  304. return dwRtnCode;
  305. if (!isReparsePoint)
  306. {
  307. *res = FALSE;
  308. }
  309. else
  310. {
  311. if ((hFind = FindFirstFile(path, &findData)) == INVALID_HANDLE_VALUE)
  312. {
  313. return GetLastError();
  314. }
  315. else
  316. {
  317. *res = (findData.dwReserved0 == tag);
  318. FindClose(hFind);
  319. }
  320. }
  321. return ERROR_SUCCESS;
  322. }
  323. //----------------------------------------------------------------------------
  324. // Function: IsSymbolicLink
  325. //
  326. // Description:
  327. // Check if the given file is a symbolic link.
  328. //
  329. // Returns:
  330. // ERROR_SUCCESS on success
  331. // error code otherwise
  332. //
  333. // Notes:
  334. //
  335. DWORD SymbolicLinkCheck(__in LPCWSTR pathName, __out PBOOL res)
  336. {
  337. return ReparseTagCheck(pathName, IO_REPARSE_TAG_SYMLINK, res);
  338. }
  339. //----------------------------------------------------------------------------
  340. // Function: IsJunctionPoint
  341. //
  342. // Description:
  343. // Check if the given file is a junction point.
  344. //
  345. // Returns:
  346. // ERROR_SUCCESS on success
  347. // error code otherwise
  348. //
  349. // Notes:
  350. //
  351. DWORD JunctionPointCheck(__in LPCWSTR pathName, __out PBOOL res)
  352. {
  353. return ReparseTagCheck(pathName, IO_REPARSE_TAG_MOUNT_POINT, res);
  354. }
  355. //----------------------------------------------------------------------------
  356. // Function: GetSidFromAcctNameW
  357. //
  358. // Description:
  359. // To retrieve the SID for a user account
  360. //
  361. // Returns:
  362. // ERROR_SUCCESS: on success
  363. // Other error code: otherwise
  364. //
  365. // Notes:
  366. // Caller needs to destroy the memory of Sid by calling LocalFree()
  367. //
  368. DWORD GetSidFromAcctNameW(__in PCWSTR acctName, __out PSID *ppSid)
  369. {
  370. DWORD dwSidSize = 0;
  371. DWORD cchDomainName = 0;
  372. DWORD dwDomainNameSize = 0;
  373. LPWSTR domainName = NULL;
  374. SID_NAME_USE eSidType;
  375. DWORD dwErrorCode = ERROR_SUCCESS;
  376. // Validate the input parameters.
  377. //
  378. assert (acctName != NULL && ppSid != NULL);
  379. // Empty name is invalid. However, LookupAccountName() function will return a
  380. // false Sid, i.e. Sid for 'BUILDIN', for an empty name instead failing. We
  381. // report the error before calling LookupAccountName() function for this
  382. // special case. The error code returned here is the same as the last error
  383. // code set by LookupAccountName() function for an invalid name.
  384. //
  385. if (wcslen(acctName) == 0)
  386. return ERROR_NONE_MAPPED;
  387. // First pass to retrieve the buffer size.
  388. //
  389. LookupAccountName(
  390. NULL, // Computer name. NULL for the local computer
  391. acctName,
  392. NULL, // pSid. NULL to retrieve buffer size
  393. &dwSidSize,
  394. NULL, // Domain Name. NULL to retrieve buffer size
  395. &cchDomainName,
  396. &eSidType);
  397. if((dwErrorCode = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
  398. {
  399. return dwErrorCode;
  400. }
  401. else
  402. {
  403. // Reallocate memory for the buffers.
  404. //
  405. *ppSid = (PSID)LocalAlloc(LPTR, dwSidSize);
  406. if (*ppSid == NULL)
  407. {
  408. return GetLastError();
  409. }
  410. dwDomainNameSize = (cchDomainName + 1) * sizeof(wchar_t);
  411. domainName = (LPWSTR)LocalAlloc(LPTR, dwDomainNameSize);
  412. if (domainName == NULL)
  413. {
  414. return GetLastError();
  415. }
  416. // Second pass to retrieve the SID and domain name.
  417. //
  418. if (!LookupAccountNameW(
  419. NULL, // Computer name. NULL for the local computer
  420. acctName,
  421. *ppSid,
  422. &dwSidSize,
  423. domainName,
  424. &cchDomainName,
  425. &eSidType))
  426. {
  427. LocalFree(domainName);
  428. return GetLastError();
  429. }
  430. assert(IsValidSid(*ppSid));
  431. }
  432. LocalFree(domainName);
  433. return ERROR_SUCCESS;
  434. }
  435. //----------------------------------------------------------------------------
  436. // Function: GetUnixAccessMask
  437. //
  438. // Description:
  439. // Compute the 3 bit Unix mask for the owner, group, or, others
  440. //
  441. // Returns:
  442. // The 3 bit Unix mask in INT
  443. //
  444. // Notes:
  445. //
  446. static INT GetUnixAccessMask(ACCESS_MASK Mask)
  447. {
  448. static const INT exe = 0x0001;
  449. static const INT write = 0x0002;
  450. static const INT read = 0x0004;
  451. INT mask = 0;
  452. if ((Mask & WinMasks[WIN_READ]) == WinMasks[WIN_READ])
  453. mask |= read;
  454. if ((Mask & WinMasks[WIN_WRITE]) == WinMasks[WIN_WRITE])
  455. mask |= write;
  456. if ((Mask & WinMasks[WIN_EXECUTE]) == WinMasks[WIN_EXECUTE])
  457. mask |= exe;
  458. return mask;
  459. }
  460. //----------------------------------------------------------------------------
  461. // Function: GetAccess
  462. //
  463. // Description:
  464. // Get Windows acces mask by AuthZ methods
  465. //
  466. // Returns:
  467. // ERROR_SUCCESS: on success
  468. //
  469. // Notes:
  470. //
  471. static DWORD GetAccess(AUTHZ_CLIENT_CONTEXT_HANDLE hAuthzClient,
  472. PSECURITY_DESCRIPTOR psd, PACCESS_MASK pAccessRights)
  473. {
  474. AUTHZ_ACCESS_REQUEST AccessRequest = {0};
  475. AUTHZ_ACCESS_REPLY AccessReply = {0};
  476. BYTE Buffer[1024];
  477. assert (pAccessRights != NULL);
  478. // Do AccessCheck
  479. AccessRequest.DesiredAccess = MAXIMUM_ALLOWED;
  480. AccessRequest.PrincipalSelfSid = NULL;
  481. AccessRequest.ObjectTypeList = NULL;
  482. AccessRequest.ObjectTypeListLength = 0;
  483. AccessRequest.OptionalArguments = NULL;
  484. RtlZeroMemory(Buffer, sizeof(Buffer));
  485. AccessReply.ResultListLength = 1;
  486. AccessReply.GrantedAccessMask = (PACCESS_MASK) (Buffer);
  487. AccessReply.Error = (PDWORD) (Buffer + sizeof(ACCESS_MASK));
  488. if (!AuthzAccessCheck(0,
  489. hAuthzClient,
  490. &AccessRequest,
  491. NULL,
  492. psd,
  493. NULL,
  494. 0,
  495. &AccessReply,
  496. NULL))
  497. {
  498. return GetLastError();
  499. }
  500. *pAccessRights = (*(const ACCESS_MASK *)(AccessReply.GrantedAccessMask));
  501. return ERROR_SUCCESS;
  502. }
  503. //----------------------------------------------------------------------------
  504. // Function: GetEffectiveRightsForSid
  505. //
  506. // Description:
  507. // Get Windows acces mask by AuthZ methods
  508. //
  509. // Returns:
  510. // ERROR_SUCCESS: on success
  511. //
  512. // Notes:
  513. // We run into problems for local user accounts when using the method
  514. // GetEffectiveRightsFromAcl(). We resort to using AuthZ methods as
  515. // an alternative way suggested on MSDN:
  516. // http://msdn.microsoft.com/en-us/library/windows/desktop/aa446637.aspx
  517. //
  518. static DWORD GetEffectiveRightsForSid(PSECURITY_DESCRIPTOR psd,
  519. PSID pSid,
  520. PACCESS_MASK pAccessRights)
  521. {
  522. AUTHZ_RESOURCE_MANAGER_HANDLE hManager = NULL;
  523. LUID unusedId = { 0 };
  524. AUTHZ_CLIENT_CONTEXT_HANDLE hAuthzClientContext = NULL;
  525. DWORD dwRtnCode = ERROR_SUCCESS;
  526. DWORD ret = ERROR_SUCCESS;
  527. assert (pAccessRights != NULL);
  528. if (!AuthzInitializeResourceManager(AUTHZ_RM_FLAG_NO_AUDIT,
  529. NULL, NULL, NULL, NULL, &hManager))
  530. {
  531. return GetLastError();
  532. }
  533. // Pass AUTHZ_SKIP_TOKEN_GROUPS to the function to avoid querying user group
  534. // information for access check. This allows us to model POSIX permissions
  535. // on Windows, where a user can have less permissions than a group it
  536. // belongs to.
  537. if(!AuthzInitializeContextFromSid(AUTHZ_SKIP_TOKEN_GROUPS,
  538. pSid, hManager, NULL, unusedId, NULL, &hAuthzClientContext))
  539. {
  540. ret = GetLastError();
  541. goto GetEffectiveRightsForSidEnd;
  542. }
  543. if ((dwRtnCode = GetAccess(hAuthzClientContext, psd, pAccessRights))
  544. != ERROR_SUCCESS)
  545. {
  546. ret = dwRtnCode;
  547. goto GetEffectiveRightsForSidEnd;
  548. }
  549. GetEffectiveRightsForSidEnd:
  550. if (hManager != NULL)
  551. {
  552. (void)AuthzFreeResourceManager(hManager);
  553. }
  554. if (hAuthzClientContext != NULL)
  555. {
  556. (void)AuthzFreeContext(hAuthzClientContext);
  557. }
  558. return ret;
  559. }
  560. //----------------------------------------------------------------------------
  561. // Function: CheckAccessForCurrentUser
  562. //
  563. // Description:
  564. // Checks if the current process has the requested access rights on the given
  565. // path. Based on the following MSDN article:
  566. // http://msdn.microsoft.com/en-us/library/windows/desktop/ff394771(v=vs.85).aspx
  567. //
  568. // Returns:
  569. // ERROR_SUCCESS: on success
  570. //
  571. DWORD CheckAccessForCurrentUser(
  572. __in PCWSTR pathName,
  573. __in ACCESS_MASK requestedAccess,
  574. __out BOOL *allowed)
  575. {
  576. DWORD dwRtnCode = ERROR_SUCCESS;
  577. LPWSTR longPathName = NULL;
  578. HANDLE hProcessToken = NULL;
  579. PSECURITY_DESCRIPTOR pSd = NULL;
  580. AUTHZ_RESOURCE_MANAGER_HANDLE hManager = NULL;
  581. AUTHZ_CLIENT_CONTEXT_HANDLE hAuthzClientContext = NULL;
  582. LUID Luid = {0, 0};
  583. ACCESS_MASK currentUserAccessRights = 0;
  584. // Prepend the long path prefix if needed
  585. dwRtnCode = ConvertToLongPath(pathName, &longPathName);
  586. if (dwRtnCode != ERROR_SUCCESS)
  587. {
  588. goto CheckAccessEnd;
  589. }
  590. // Get SD of the given path. OWNER and DACL security info must be
  591. // requested, otherwise, AuthzAccessCheck fails with invalid parameter
  592. // error.
  593. dwRtnCode = GetNamedSecurityInfo(longPathName, SE_FILE_OBJECT,
  594. OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
  595. DACL_SECURITY_INFORMATION,
  596. NULL, NULL, NULL, NULL, &pSd);
  597. if (dwRtnCode != ERROR_SUCCESS)
  598. {
  599. goto CheckAccessEnd;
  600. }
  601. // Get current process token
  602. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hProcessToken))
  603. {
  604. dwRtnCode = GetLastError();
  605. goto CheckAccessEnd;
  606. }
  607. if (!AuthzInitializeResourceManager(AUTHZ_RM_FLAG_NO_AUDIT, NULL, NULL,
  608. NULL, NULL, &hManager))
  609. {
  610. dwRtnCode = GetLastError();
  611. goto CheckAccessEnd;
  612. }
  613. if(!AuthzInitializeContextFromToken(0, hProcessToken, hManager, NULL,
  614. Luid, NULL, &hAuthzClientContext))
  615. {
  616. dwRtnCode = GetLastError();
  617. goto CheckAccessEnd;
  618. }
  619. dwRtnCode = GetAccess(hAuthzClientContext, pSd, &currentUserAccessRights);
  620. if (dwRtnCode != ERROR_SUCCESS)
  621. {
  622. goto CheckAccessEnd;
  623. }
  624. *allowed = ((currentUserAccessRights & requestedAccess) == requestedAccess);
  625. CheckAccessEnd:
  626. LocalFree(longPathName);
  627. LocalFree(pSd);
  628. if (hProcessToken != NULL)
  629. {
  630. CloseHandle(hProcessToken);
  631. }
  632. if (hManager != NULL)
  633. {
  634. (void)AuthzFreeResourceManager(hManager);
  635. }
  636. if (hAuthzClientContext != NULL)
  637. {
  638. (void)AuthzFreeContext(hAuthzClientContext);
  639. }
  640. return dwRtnCode;
  641. }
  642. //----------------------------------------------------------------------------
  643. // Function: FindFileOwnerAndPermissionByHandle
  644. //
  645. // Description:
  646. // Find the owner, primary group and permissions of a file object given the
  647. // the file object handle. The function will always follow symbolic links.
  648. //
  649. // Returns:
  650. // ERROR_SUCCESS: on success
  651. // Error code otherwise
  652. //
  653. // Notes:
  654. // - Caller needs to destroy the memeory of owner and group names by calling
  655. // LocalFree() function.
  656. //
  657. // - If the user or group name does not exist, the user or group SID will be
  658. // returned as the name.
  659. //
  660. DWORD FindFileOwnerAndPermissionByHandle(
  661. __in HANDLE fileHandle,
  662. __out_opt LPWSTR *pOwnerName,
  663. __out_opt LPWSTR *pGroupName,
  664. __out_opt PINT pMask)
  665. {
  666. LPWSTR path = NULL;
  667. DWORD cchPathLen = 0;
  668. DWORD dwRtnCode = ERROR_SUCCESS;
  669. DWORD ret = ERROR_SUCCESS;
  670. dwRtnCode = GetFinalPathNameByHandle(fileHandle, path, cchPathLen, 0);
  671. if (dwRtnCode == 0)
  672. {
  673. ret = GetLastError();
  674. goto FindFileOwnerAndPermissionByHandleEnd;
  675. }
  676. cchPathLen = dwRtnCode;
  677. path = (LPWSTR) LocalAlloc(LPTR, cchPathLen * sizeof(WCHAR));
  678. if (path == NULL)
  679. {
  680. ret = GetLastError();
  681. goto FindFileOwnerAndPermissionByHandleEnd;
  682. }
  683. dwRtnCode = GetFinalPathNameByHandle(fileHandle, path, cchPathLen, 0);
  684. if (dwRtnCode != cchPathLen - 1)
  685. {
  686. ret = GetLastError();
  687. goto FindFileOwnerAndPermissionByHandleEnd;
  688. }
  689. dwRtnCode = FindFileOwnerAndPermission(path, TRUE, pOwnerName, pGroupName, pMask);
  690. if (dwRtnCode != ERROR_SUCCESS)
  691. {
  692. ret = dwRtnCode;
  693. goto FindFileOwnerAndPermissionByHandleEnd;
  694. }
  695. FindFileOwnerAndPermissionByHandleEnd:
  696. LocalFree(path);
  697. return ret;
  698. }
  699. //----------------------------------------------------------------------------
  700. // Function: FindFileOwnerAndPermission
  701. //
  702. // Description:
  703. // Find the owner, primary group and permissions of a file object
  704. //
  705. // Returns:
  706. // ERROR_SUCCESS: on success
  707. // Error code otherwise
  708. //
  709. // Notes:
  710. // - Caller needs to destroy the memeory of owner and group names by calling
  711. // LocalFree() function.
  712. //
  713. // - If the user or group name does not exist, the user or group SID will be
  714. // returned as the name.
  715. //
  716. DWORD FindFileOwnerAndPermission(
  717. __in LPCWSTR pathName,
  718. __in BOOL followLink,
  719. __out_opt LPWSTR *pOwnerName,
  720. __out_opt LPWSTR *pGroupName,
  721. __out_opt PINT pMask)
  722. {
  723. DWORD dwRtnCode = 0;
  724. PSECURITY_DESCRIPTOR pSd = NULL;
  725. PSID psidOwner = NULL;
  726. PSID psidGroup = NULL;
  727. PSID psidEveryone = NULL;
  728. DWORD cbSid = SECURITY_MAX_SID_SIZE;
  729. PACL pDacl = NULL;
  730. BOOL isSymlink;
  731. BY_HANDLE_FILE_INFORMATION fileInformation;
  732. ACCESS_MASK ownerAccessRights = 0;
  733. ACCESS_MASK groupAccessRights = 0;
  734. ACCESS_MASK worldAccessRights = 0;
  735. DWORD ret = ERROR_SUCCESS;
  736. // Do nothing if the caller request nothing
  737. //
  738. if (pOwnerName == NULL && pGroupName == NULL && pMask == NULL)
  739. {
  740. return ret;
  741. }
  742. dwRtnCode = GetNamedSecurityInfo(pathName, SE_FILE_OBJECT,
  743. OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
  744. DACL_SECURITY_INFORMATION,
  745. &psidOwner, &psidGroup, &pDacl, NULL, &pSd);
  746. if (dwRtnCode != ERROR_SUCCESS)
  747. {
  748. ret = dwRtnCode;
  749. goto FindFileOwnerAndPermissionEnd;
  750. }
  751. if (pOwnerName != NULL)
  752. {
  753. dwRtnCode = GetAccntNameFromSid(psidOwner, pOwnerName);
  754. if (dwRtnCode == ERROR_NONE_MAPPED)
  755. {
  756. if (!ConvertSidToStringSid(psidOwner, pOwnerName))
  757. {
  758. ret = GetLastError();
  759. goto FindFileOwnerAndPermissionEnd;
  760. }
  761. }
  762. else if (dwRtnCode != ERROR_SUCCESS)
  763. {
  764. ret = dwRtnCode;
  765. goto FindFileOwnerAndPermissionEnd;
  766. }
  767. }
  768. if (pGroupName != NULL)
  769. {
  770. dwRtnCode = GetAccntNameFromSid(psidGroup, pGroupName);
  771. if (dwRtnCode == ERROR_NONE_MAPPED)
  772. {
  773. if (!ConvertSidToStringSid(psidGroup, pGroupName))
  774. {
  775. ret = GetLastError();
  776. goto FindFileOwnerAndPermissionEnd;
  777. }
  778. }
  779. else if (dwRtnCode != ERROR_SUCCESS)
  780. {
  781. ret = dwRtnCode;
  782. goto FindFileOwnerAndPermissionEnd;
  783. }
  784. }
  785. if (pMask == NULL) goto FindFileOwnerAndPermissionEnd;
  786. dwRtnCode = GetFileInformationByName(pathName,
  787. followLink, &fileInformation);
  788. if (dwRtnCode != ERROR_SUCCESS)
  789. {
  790. ret = dwRtnCode;
  791. goto FindFileOwnerAndPermissionEnd;
  792. }
  793. dwRtnCode = SymbolicLinkCheck(pathName, &isSymlink);
  794. if (dwRtnCode != ERROR_SUCCESS)
  795. {
  796. ret = dwRtnCode;
  797. goto FindFileOwnerAndPermissionEnd;
  798. }
  799. if (isSymlink)
  800. *pMask |= UX_SYMLINK;
  801. else if (IsDirFileInfo(&fileInformation))
  802. *pMask |= UX_DIRECTORY;
  803. else
  804. *pMask |= UX_REGULAR;
  805. if ((dwRtnCode = GetEffectiveRightsForSid(pSd,
  806. psidOwner, &ownerAccessRights)) != ERROR_SUCCESS)
  807. {
  808. ret = dwRtnCode;
  809. goto FindFileOwnerAndPermissionEnd;
  810. }
  811. if ((dwRtnCode = GetEffectiveRightsForSid(pSd,
  812. psidGroup, &groupAccessRights)) != ERROR_SUCCESS)
  813. {
  814. ret = dwRtnCode;
  815. goto FindFileOwnerAndPermissionEnd;
  816. }
  817. if ((psidEveryone = LocalAlloc(LPTR, cbSid)) == NULL)
  818. {
  819. ret = GetLastError();
  820. goto FindFileOwnerAndPermissionEnd;
  821. }
  822. if (!CreateWellKnownSid(WinWorldSid, NULL, psidEveryone, &cbSid))
  823. {
  824. ret = GetLastError();
  825. goto FindFileOwnerAndPermissionEnd;
  826. }
  827. if ((dwRtnCode = GetEffectiveRightsForSid(pSd,
  828. psidEveryone, &worldAccessRights)) != ERROR_SUCCESS)
  829. {
  830. ret = dwRtnCode;
  831. goto FindFileOwnerAndPermissionEnd;
  832. }
  833. *pMask |= GetUnixAccessMask(ownerAccessRights) << 6;
  834. *pMask |= GetUnixAccessMask(groupAccessRights) << 3;
  835. *pMask |= GetUnixAccessMask(worldAccessRights);
  836. FindFileOwnerAndPermissionEnd:
  837. LocalFree(psidEveryone);
  838. LocalFree(pSd);
  839. return ret;
  840. }
  841. //----------------------------------------------------------------------------
  842. // Function: GetWindowsAccessMask
  843. //
  844. // Description:
  845. // Get the Windows AccessMask for user, group and everyone based on the Unix
  846. // permission mask
  847. //
  848. // Returns:
  849. // none
  850. //
  851. // Notes:
  852. // none
  853. //
  854. static void GetWindowsAccessMask(INT unixMask,
  855. ACCESS_MASK *userAllow,
  856. ACCESS_MASK *userDeny,
  857. ACCESS_MASK *groupAllow,
  858. ACCESS_MASK *groupDeny,
  859. ACCESS_MASK *otherAllow)
  860. {
  861. assert (userAllow != NULL && userDeny != NULL &&
  862. groupAllow != NULL && groupDeny != NULL &&
  863. otherAllow != NULL);
  864. *userAllow = WinMasks[WIN_ALL] | WinMasks[WIN_OWNER_SE];
  865. if ((unixMask & UX_U_READ) == UX_U_READ)
  866. *userAllow |= WinMasks[WIN_READ];
  867. if ((unixMask & UX_U_WRITE) == UX_U_WRITE)
  868. *userAllow |= WinMasks[WIN_WRITE];
  869. if ((unixMask & UX_U_EXECUTE) == UX_U_EXECUTE)
  870. *userAllow |= WinMasks[WIN_EXECUTE];
  871. *userDeny = 0;
  872. if ((unixMask & UX_U_READ) != UX_U_READ &&
  873. ((unixMask & UX_G_READ) == UX_G_READ ||
  874. (unixMask & UX_O_READ) == UX_O_READ))
  875. *userDeny |= WinMasks[WIN_READ];
  876. if ((unixMask & UX_U_WRITE) != UX_U_WRITE &&
  877. ((unixMask & UX_G_WRITE) == UX_G_WRITE ||
  878. (unixMask & UX_O_WRITE) == UX_O_WRITE))
  879. *userDeny |= WinMasks[WIN_WRITE];
  880. if ((unixMask & UX_U_EXECUTE) != UX_U_EXECUTE &&
  881. ((unixMask & UX_G_EXECUTE) == UX_G_EXECUTE ||
  882. (unixMask & UX_O_EXECUTE) == UX_O_EXECUTE))
  883. *userDeny |= WinMasks[WIN_EXECUTE];
  884. *groupAllow = WinMasks[WIN_ALL];
  885. if ((unixMask & UX_G_READ) == UX_G_READ)
  886. *groupAllow |= FILE_GENERIC_READ;
  887. if ((unixMask & UX_G_WRITE) == UX_G_WRITE)
  888. *groupAllow |= WinMasks[WIN_WRITE];
  889. if ((unixMask & UX_G_EXECUTE) == UX_G_EXECUTE)
  890. *groupAllow |= WinMasks[WIN_EXECUTE];
  891. *groupDeny = 0;
  892. if ((unixMask & UX_G_READ) != UX_G_READ &&
  893. (unixMask & UX_O_READ) == UX_O_READ)
  894. *groupDeny |= WinMasks[WIN_READ];
  895. if ((unixMask & UX_G_WRITE) != UX_G_WRITE &&
  896. (unixMask & UX_O_WRITE) == UX_O_WRITE)
  897. *groupDeny |= WinMasks[WIN_WRITE];
  898. if ((unixMask & UX_G_EXECUTE) != UX_G_EXECUTE &&
  899. (unixMask & UX_O_EXECUTE) == UX_O_EXECUTE)
  900. *groupDeny |= WinMasks[WIN_EXECUTE];
  901. *otherAllow = WinMasks[WIN_ALL];
  902. if ((unixMask & UX_O_READ) == UX_O_READ)
  903. *otherAllow |= WinMasks[WIN_READ];
  904. if ((unixMask & UX_O_WRITE) == UX_O_WRITE)
  905. *otherAllow |= WinMasks[WIN_WRITE];
  906. if ((unixMask & UX_O_EXECUTE) == UX_O_EXECUTE)
  907. *otherAllow |= WinMasks[WIN_EXECUTE];
  908. }
  909. //----------------------------------------------------------------------------
  910. // Function: GetWindowsDACLs
  911. //
  912. // Description:
  913. // Get the Windows DACs based the Unix access mask
  914. //
  915. // Returns:
  916. // ERROR_SUCCESS: on success
  917. // Error code: otherwise
  918. //
  919. // Notes:
  920. // - Administrators and SYSTEM are always given full permission to the file,
  921. // unless Administrators or SYSTEM itself is the file owner and the user
  922. // explictly set the permission to something else. For example, file 'foo'
  923. // belongs to Administrators, 'chmod 000' on the file will not directly
  924. // assign Administrators full permission on the file.
  925. // - Only full permission for Administrators and SYSTEM are inheritable.
  926. // - CREATOR OWNER is always given full permission and the permission is
  927. // inheritable, more specifically OBJECT_INHERIT_ACE, CONTAINER_INHERIT_ACE
  928. // flags are set. The reason is to give the creator of child file full
  929. // permission, i.e., the child file will have permission mode 700 for
  930. // a user other than Administrator or SYSTEM.
  931. //
  932. static DWORD GetWindowsDACLs(__in INT unixMask,
  933. __in PSID pOwnerSid, __in PSID pGroupSid, __out PACL *ppNewDACL)
  934. {
  935. DWORD winUserAccessDenyMask;
  936. DWORD winUserAccessAllowMask;
  937. DWORD winGroupAccessDenyMask;
  938. DWORD winGroupAccessAllowMask;
  939. DWORD winOtherAccessAllowMask;
  940. PSID pEveryoneSid = NULL;
  941. DWORD cbEveryoneSidSize = SECURITY_MAX_SID_SIZE;
  942. PSID pSystemSid = NULL;
  943. DWORD cbSystemSidSize = SECURITY_MAX_SID_SIZE;
  944. BOOL bAddSystemAcls = FALSE;
  945. PSID pAdministratorsSid = NULL;
  946. DWORD cbAdministratorsSidSize = SECURITY_MAX_SID_SIZE;
  947. BOOL bAddAdministratorsAcls = FALSE;
  948. PSID pCreatorOwnerSid = NULL;
  949. DWORD cbCreatorOwnerSidSize = SECURITY_MAX_SID_SIZE;
  950. PACL pNewDACL = NULL;
  951. DWORD dwNewAclSize = 0;
  952. DWORD ret = ERROR_SUCCESS;
  953. GetWindowsAccessMask(unixMask,
  954. &winUserAccessAllowMask, &winUserAccessDenyMask,
  955. &winGroupAccessAllowMask, &winGroupAccessDenyMask,
  956. &winOtherAccessAllowMask);
  957. // Create a well-known SID for the Everyone group
  958. //
  959. if ((pEveryoneSid = LocalAlloc(LPTR, cbEveryoneSidSize)) == NULL)
  960. {
  961. ret = GetLastError();
  962. goto GetWindowsDACLsEnd;
  963. }
  964. if (!CreateWellKnownSid(WinWorldSid, NULL, pEveryoneSid, &cbEveryoneSidSize))
  965. {
  966. ret = GetLastError();
  967. goto GetWindowsDACLsEnd;
  968. }
  969. // Create a well-known SID for the Administrators group
  970. //
  971. if ((pAdministratorsSid = LocalAlloc(LPTR, cbAdministratorsSidSize)) == NULL)
  972. {
  973. ret = GetLastError();
  974. goto GetWindowsDACLsEnd;
  975. }
  976. if (!CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL,
  977. pAdministratorsSid, &cbAdministratorsSidSize))
  978. {
  979. ret = GetLastError();
  980. goto GetWindowsDACLsEnd;
  981. }
  982. if (!EqualSid(pAdministratorsSid, pOwnerSid)
  983. && !EqualSid(pAdministratorsSid, pGroupSid))
  984. bAddAdministratorsAcls = TRUE;
  985. // Create a well-known SID for the SYSTEM
  986. //
  987. if ((pSystemSid = LocalAlloc(LPTR, cbSystemSidSize)) == NULL)
  988. {
  989. ret = GetLastError();
  990. goto GetWindowsDACLsEnd;
  991. }
  992. if (!CreateWellKnownSid(WinLocalSystemSid, NULL,
  993. pSystemSid, &cbSystemSidSize))
  994. {
  995. ret = GetLastError();
  996. goto GetWindowsDACLsEnd;
  997. }
  998. if (!EqualSid(pSystemSid, pOwnerSid)
  999. && !EqualSid(pSystemSid, pGroupSid))
  1000. bAddSystemAcls = TRUE;
  1001. // Create a well-known SID for the Creator Owner
  1002. //
  1003. if ((pCreatorOwnerSid = LocalAlloc(LPTR, cbCreatorOwnerSidSize)) == NULL)
  1004. {
  1005. ret = GetLastError();
  1006. goto GetWindowsDACLsEnd;
  1007. }
  1008. if (!CreateWellKnownSid(WinCreatorOwnerSid, NULL,
  1009. pCreatorOwnerSid, &cbCreatorOwnerSidSize))
  1010. {
  1011. ret = GetLastError();
  1012. goto GetWindowsDACLsEnd;
  1013. }
  1014. // Create the new DACL
  1015. //
  1016. dwNewAclSize = sizeof(ACL);
  1017. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  1018. GetLengthSid(pOwnerSid) - sizeof(DWORD);
  1019. if (winUserAccessDenyMask)
  1020. dwNewAclSize += sizeof(ACCESS_DENIED_ACE) +
  1021. GetLengthSid(pOwnerSid) - sizeof(DWORD);
  1022. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  1023. GetLengthSid(pGroupSid) - sizeof(DWORD);
  1024. if (winGroupAccessDenyMask)
  1025. dwNewAclSize += sizeof(ACCESS_DENIED_ACE) +
  1026. GetLengthSid(pGroupSid) - sizeof(DWORD);
  1027. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  1028. GetLengthSid(pEveryoneSid) - sizeof(DWORD);
  1029. if (bAddSystemAcls)
  1030. {
  1031. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  1032. cbSystemSidSize - sizeof(DWORD);
  1033. }
  1034. if (bAddAdministratorsAcls)
  1035. {
  1036. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  1037. cbAdministratorsSidSize - sizeof(DWORD);
  1038. }
  1039. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  1040. cbCreatorOwnerSidSize - sizeof(DWORD);
  1041. pNewDACL = (PACL)LocalAlloc(LPTR, dwNewAclSize);
  1042. if (pNewDACL == NULL)
  1043. {
  1044. ret = GetLastError();
  1045. goto GetWindowsDACLsEnd;
  1046. }
  1047. if (!InitializeAcl(pNewDACL, dwNewAclSize, ACL_REVISION))
  1048. {
  1049. ret = GetLastError();
  1050. goto GetWindowsDACLsEnd;
  1051. }
  1052. if (!AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  1053. CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
  1054. GENERIC_ALL, pCreatorOwnerSid))
  1055. {
  1056. ret = GetLastError();
  1057. goto GetWindowsDACLsEnd;
  1058. }
  1059. if (bAddSystemAcls &&
  1060. !AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  1061. CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
  1062. GENERIC_ALL, pSystemSid))
  1063. {
  1064. ret = GetLastError();
  1065. goto GetWindowsDACLsEnd;
  1066. }
  1067. if (bAddAdministratorsAcls &&
  1068. !AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  1069. CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
  1070. GENERIC_ALL, pAdministratorsSid))
  1071. {
  1072. ret = GetLastError();
  1073. goto GetWindowsDACLsEnd;
  1074. }
  1075. if (winUserAccessDenyMask &&
  1076. !AddAccessDeniedAceEx(pNewDACL, ACL_REVISION,
  1077. NO_PROPAGATE_INHERIT_ACE,
  1078. winUserAccessDenyMask, pOwnerSid))
  1079. {
  1080. ret = GetLastError();
  1081. goto GetWindowsDACLsEnd;
  1082. }
  1083. if (!AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  1084. NO_PROPAGATE_INHERIT_ACE,
  1085. winUserAccessAllowMask, pOwnerSid))
  1086. {
  1087. ret = GetLastError();
  1088. goto GetWindowsDACLsEnd;
  1089. }
  1090. if (winGroupAccessDenyMask &&
  1091. !AddAccessDeniedAceEx(pNewDACL, ACL_REVISION,
  1092. NO_PROPAGATE_INHERIT_ACE,
  1093. winGroupAccessDenyMask, pGroupSid))
  1094. {
  1095. ret = GetLastError();
  1096. goto GetWindowsDACLsEnd;
  1097. }
  1098. if (!AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  1099. NO_PROPAGATE_INHERIT_ACE,
  1100. winGroupAccessAllowMask, pGroupSid))
  1101. {
  1102. ret = GetLastError();
  1103. goto GetWindowsDACLsEnd;
  1104. }
  1105. if (!AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  1106. NO_PROPAGATE_INHERIT_ACE,
  1107. winOtherAccessAllowMask, pEveryoneSid))
  1108. {
  1109. ret = GetLastError();
  1110. goto GetWindowsDACLsEnd;
  1111. }
  1112. *ppNewDACL = pNewDACL;
  1113. GetWindowsDACLsEnd:
  1114. LocalFree(pEveryoneSid);
  1115. LocalFree(pAdministratorsSid);
  1116. LocalFree(pSystemSid);
  1117. LocalFree(pCreatorOwnerSid);
  1118. if (ret != ERROR_SUCCESS) LocalFree(pNewDACL);
  1119. return ret;
  1120. }
  1121. //----------------------------------------------------------------------------
  1122. // Function: ChangeFileModeByMask
  1123. //
  1124. // Description:
  1125. // Change a file or direcotry at the path to Unix mode
  1126. //
  1127. // Returns:
  1128. // ERROR_SUCCESS: on success
  1129. // Error code: otherwise
  1130. //
  1131. // Notes:
  1132. // This function is long path safe, i.e. the path will be converted to long
  1133. // path format if not already converted. So the caller does not need to do
  1134. // the converstion before calling the method.
  1135. //
  1136. DWORD ChangeFileModeByMask(__in LPCWSTR path, INT mode)
  1137. {
  1138. LPWSTR longPathName = NULL;
  1139. PACL pNewDACL = NULL;
  1140. PSID pOwnerSid = NULL;
  1141. PSID pGroupSid = NULL;
  1142. PSECURITY_DESCRIPTOR pSD = NULL;
  1143. SECURITY_DESCRIPTOR_CONTROL control;
  1144. DWORD revision = 0;
  1145. PSECURITY_DESCRIPTOR pAbsSD = NULL;
  1146. PSECURITY_DESCRIPTOR pNonNullSD = NULL;
  1147. PACL pAbsDacl = NULL;
  1148. PACL pAbsSacl = NULL;
  1149. PSID pAbsOwner = NULL;
  1150. PSID pAbsGroup = NULL;
  1151. DWORD dwRtnCode = 0;
  1152. DWORD dwErrorCode = 0;
  1153. DWORD ret = ERROR_SUCCESS;
  1154. dwRtnCode = ConvertToLongPath(path, &longPathName);
  1155. if (dwRtnCode != ERROR_SUCCESS)
  1156. {
  1157. ret = dwRtnCode;
  1158. goto ChangeFileModeByMaskEnd;
  1159. }
  1160. // Get owner and group Sids
  1161. //
  1162. dwRtnCode = GetNamedSecurityInfoW(
  1163. longPathName,
  1164. SE_FILE_OBJECT,
  1165. OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION,
  1166. &pOwnerSid,
  1167. &pGroupSid,
  1168. NULL,
  1169. NULL,
  1170. &pSD);
  1171. if (ERROR_SUCCESS != dwRtnCode)
  1172. {
  1173. ret = dwRtnCode;
  1174. goto ChangeFileModeByMaskEnd;
  1175. }
  1176. // SetSecurityDescriptorDacl function used below only accepts security
  1177. // descriptor in absolute format, meaning that its members must be pointers to
  1178. // other structures, rather than offsets to contiguous data.
  1179. // To determine whether a security descriptor is self-relative or absolute,
  1180. // call the GetSecurityDescriptorControl function and check the
  1181. // SE_SELF_RELATIVE flag of the SECURITY_DESCRIPTOR_CONTROL parameter.
  1182. //
  1183. if (!GetSecurityDescriptorControl(pSD, &control, &revision))
  1184. {
  1185. ret = GetLastError();
  1186. goto ChangeFileModeByMaskEnd;
  1187. }
  1188. // If the security descriptor is self-relative, we use MakeAbsoluteSD function
  1189. // to convert it to absolute format.
  1190. //
  1191. if ((control & SE_SELF_RELATIVE) == SE_SELF_RELATIVE)
  1192. {
  1193. DWORD absSDSize = 0;
  1194. DWORD daclSize = 0;
  1195. DWORD saclSize = 0;
  1196. DWORD ownerSize = 0;
  1197. DWORD primaryGroupSize = 0;
  1198. MakeAbsoluteSD(pSD, NULL, &absSDSize, NULL, &daclSize, NULL,
  1199. &saclSize, NULL, &ownerSize, NULL, &primaryGroupSize);
  1200. if ((dwErrorCode = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
  1201. {
  1202. ret = dwErrorCode;
  1203. goto ChangeFileModeByMaskEnd;
  1204. }
  1205. if ((pAbsSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, absSDSize)) == NULL)
  1206. {
  1207. ret = GetLastError();
  1208. goto ChangeFileModeByMaskEnd;
  1209. }
  1210. if ((pAbsDacl = (PACL) LocalAlloc(LPTR, daclSize)) == NULL)
  1211. {
  1212. ret = GetLastError();
  1213. goto ChangeFileModeByMaskEnd;
  1214. }
  1215. if ((pAbsSacl = (PACL) LocalAlloc(LPTR, saclSize)) == NULL)
  1216. {
  1217. ret = GetLastError();
  1218. goto ChangeFileModeByMaskEnd;
  1219. }
  1220. if ((pAbsOwner = (PSID) LocalAlloc(LPTR, ownerSize)) == NULL)
  1221. {
  1222. ret = GetLastError();
  1223. goto ChangeFileModeByMaskEnd;
  1224. }
  1225. if ((pAbsGroup = (PSID) LocalAlloc(LPTR, primaryGroupSize)) == NULL)
  1226. {
  1227. ret = GetLastError();
  1228. goto ChangeFileModeByMaskEnd;
  1229. }
  1230. if (!MakeAbsoluteSD(pSD, pAbsSD, &absSDSize, pAbsDacl, &daclSize, pAbsSacl,
  1231. &saclSize, pAbsOwner, &ownerSize, pAbsGroup, &primaryGroupSize))
  1232. {
  1233. ret = GetLastError();
  1234. goto ChangeFileModeByMaskEnd;
  1235. }
  1236. }
  1237. // Get Windows DACLs based on Unix access mask
  1238. //
  1239. if ((dwRtnCode = GetWindowsDACLs(mode, pOwnerSid, pGroupSid, &pNewDACL))
  1240. != ERROR_SUCCESS)
  1241. {
  1242. ret = dwRtnCode;
  1243. goto ChangeFileModeByMaskEnd;
  1244. }
  1245. // Set the DACL information in the security descriptor; if a DACL is already
  1246. // present in the security descriptor, the DACL is replaced. The security
  1247. // descriptor is then used to set the security of a file or directory.
  1248. //
  1249. pNonNullSD = (pAbsSD != NULL) ? pAbsSD : pSD;
  1250. if (!SetSecurityDescriptorDacl(pNonNullSD, TRUE, pNewDACL, FALSE))
  1251. {
  1252. ret = GetLastError();
  1253. goto ChangeFileModeByMaskEnd;
  1254. }
  1255. // MSDN states "This function is obsolete. Use the SetNamedSecurityInfo
  1256. // function instead." However we have the following problem when using
  1257. // SetNamedSecurityInfo:
  1258. // - When PROTECTED_DACL_SECURITY_INFORMATION is not passed in as part of
  1259. // security information, the object will include inheritable permissions
  1260. // from its parent.
  1261. // - When PROTECTED_DACL_SECURITY_INFORMATION is passsed in to set
  1262. // permissions on a directory, the child object of the directory will lose
  1263. // inheritable permissions from their parent (the current directory).
  1264. // By using SetFileSecurity, we have the nice property that the new
  1265. // permissions of the object does not include the inheritable permissions from
  1266. // its parent, and the child objects will not lose their inherited permissions
  1267. // from the current object.
  1268. //
  1269. if (!SetFileSecurity(longPathName, DACL_SECURITY_INFORMATION, pNonNullSD))
  1270. {
  1271. ret = GetLastError();
  1272. goto ChangeFileModeByMaskEnd;
  1273. }
  1274. ChangeFileModeByMaskEnd:
  1275. pNonNullSD = NULL;
  1276. LocalFree(longPathName);
  1277. LocalFree(pSD);
  1278. LocalFree(pNewDACL);
  1279. LocalFree(pAbsDacl);
  1280. LocalFree(pAbsSacl);
  1281. LocalFree(pAbsOwner);
  1282. LocalFree(pAbsGroup);
  1283. LocalFree(pAbsSD);
  1284. return ret;
  1285. }
  1286. //----------------------------------------------------------------------------
  1287. // Function: GetAccntNameFromSid
  1288. //
  1289. // Description:
  1290. // To retrieve an account name given the SID
  1291. //
  1292. // Returns:
  1293. // ERROR_SUCCESS: on success
  1294. // Other error code: otherwise
  1295. //
  1296. // Notes:
  1297. // Caller needs to destroy the memory of account name by calling LocalFree()
  1298. //
  1299. DWORD GetAccntNameFromSid(__in PSID pSid, __out PWSTR *ppAcctName)
  1300. {
  1301. LPWSTR lpName = NULL;
  1302. DWORD cchName = 0;
  1303. LPWSTR lpDomainName = NULL;
  1304. DWORD cchDomainName = 0;
  1305. SID_NAME_USE eUse = SidTypeUnknown;
  1306. DWORD cchAcctName = 0;
  1307. DWORD dwErrorCode = ERROR_SUCCESS;
  1308. HRESULT hr = S_OK;
  1309. DWORD ret = ERROR_SUCCESS;
  1310. assert(ppAcctName != NULL);
  1311. // NOTE:
  1312. // MSDN says the length returned for the buffer size including the terminating
  1313. // null character. However we found it is not true during debuging.
  1314. //
  1315. LookupAccountSid(NULL, pSid, NULL, &cchName, NULL, &cchDomainName, &eUse);
  1316. if ((dwErrorCode = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
  1317. return dwErrorCode;
  1318. lpName = (LPWSTR) LocalAlloc(LPTR, (cchName + 1) * sizeof(WCHAR));
  1319. if (lpName == NULL)
  1320. {
  1321. ret = GetLastError();
  1322. goto GetAccntNameFromSidEnd;
  1323. }
  1324. lpDomainName = (LPWSTR) LocalAlloc(LPTR, (cchDomainName + 1) * sizeof(WCHAR));
  1325. if (lpDomainName == NULL)
  1326. {
  1327. ret = GetLastError();
  1328. goto GetAccntNameFromSidEnd;
  1329. }
  1330. if (!LookupAccountSid(NULL, pSid,
  1331. lpName, &cchName, lpDomainName, &cchDomainName, &eUse))
  1332. {
  1333. ret = GetLastError();
  1334. goto GetAccntNameFromSidEnd;
  1335. }
  1336. // Buffer size = name length + 1 for '\' + domain length + 1 for NULL
  1337. cchAcctName = cchName + cchDomainName + 2;
  1338. *ppAcctName = (LPWSTR) LocalAlloc(LPTR, cchAcctName * sizeof(WCHAR));
  1339. if (*ppAcctName == NULL)
  1340. {
  1341. ret = GetLastError();
  1342. goto GetAccntNameFromSidEnd;
  1343. }
  1344. hr = StringCchCopyW(*ppAcctName, cchAcctName, lpDomainName);
  1345. if (FAILED(hr))
  1346. {
  1347. ret = HRESULT_CODE(hr);
  1348. goto GetAccntNameFromSidEnd;
  1349. }
  1350. hr = StringCchCatW(*ppAcctName, cchAcctName, L"\\");
  1351. if (FAILED(hr))
  1352. {
  1353. ret = HRESULT_CODE(hr);
  1354. goto GetAccntNameFromSidEnd;
  1355. }
  1356. hr = StringCchCatW(*ppAcctName, cchAcctName, lpName);
  1357. if (FAILED(hr))
  1358. {
  1359. ret = HRESULT_CODE(hr);
  1360. goto GetAccntNameFromSidEnd;
  1361. }
  1362. GetAccntNameFromSidEnd:
  1363. LocalFree(lpName);
  1364. LocalFree(lpDomainName);
  1365. if (ret != ERROR_SUCCESS)
  1366. {
  1367. LocalFree(*ppAcctName);
  1368. *ppAcctName = NULL;
  1369. }
  1370. return ret;
  1371. }
  1372. //----------------------------------------------------------------------------
  1373. // Function: GetLocalGroupsForUser
  1374. //
  1375. // Description:
  1376. // Get an array of groups for the given user.
  1377. //
  1378. // Returns:
  1379. // ERROR_SUCCESS on success
  1380. // Other error code on failure
  1381. //
  1382. // Notes:
  1383. // - NetUserGetLocalGroups() function only accepts full user name in the format
  1384. // [domain name]\[username]. The user input to this function can be only the
  1385. // username. In this case, NetUserGetLocalGroups() will fail on the first try,
  1386. // and we will try to find full user name using LookupAccountNameW() method,
  1387. // and call NetUserGetLocalGroups() function again with full user name.
  1388. // However, it is not always possible to find full user name given only user
  1389. // name. For example, a computer named 'win1' joined domain 'redmond' can have
  1390. // two different users, 'win1\alex' and 'redmond\alex'. Given only 'alex', we
  1391. // cannot tell which one is correct.
  1392. //
  1393. // - Caller needs to destroy the memory of groups by using the
  1394. // NetApiBufferFree() function
  1395. //
  1396. DWORD GetLocalGroupsForUser(
  1397. __in LPCWSTR user,
  1398. __out LPLOCALGROUP_USERS_INFO_0 *groups,
  1399. __out LPDWORD entries)
  1400. {
  1401. DWORD dwEntriesRead = 0;
  1402. DWORD dwTotalEntries = 0;
  1403. NET_API_STATUS nStatus = NERR_Success;
  1404. PSID pUserSid = NULL;
  1405. LPWSTR fullName = NULL;
  1406. DWORD dwRtnCode = ERROR_SUCCESS;
  1407. DWORD ret = ERROR_SUCCESS;
  1408. *groups = NULL;
  1409. *entries = 0;
  1410. nStatus = NetUserGetLocalGroups(NULL,
  1411. user,
  1412. 0,
  1413. 0,
  1414. (LPBYTE *) groups,
  1415. MAX_PREFERRED_LENGTH,
  1416. &dwEntriesRead,
  1417. &dwTotalEntries);
  1418. if (nStatus == NERR_Success)
  1419. {
  1420. *entries = dwEntriesRead;
  1421. return ERROR_SUCCESS;
  1422. }
  1423. else if (nStatus != NERR_UserNotFound)
  1424. {
  1425. return nStatus;
  1426. }
  1427. if ((dwRtnCode = GetSidFromAcctNameW(user, &pUserSid)) != ERROR_SUCCESS)
  1428. {
  1429. ret = dwRtnCode;
  1430. goto GetLocalGroupsForUserEnd;
  1431. }
  1432. if ((dwRtnCode = GetAccntNameFromSid(pUserSid, &fullName)) != ERROR_SUCCESS)
  1433. {
  1434. ret = dwRtnCode;
  1435. goto GetLocalGroupsForUserEnd;
  1436. }
  1437. nStatus = NetUserGetLocalGroups(NULL,
  1438. fullName,
  1439. 0,
  1440. 0,
  1441. (LPBYTE *) groups,
  1442. MAX_PREFERRED_LENGTH,
  1443. &dwEntriesRead,
  1444. &dwTotalEntries);
  1445. if (nStatus != NERR_Success)
  1446. {
  1447. // NERR_DCNotFound (2453) and NERR_UserNotFound (2221) are not published
  1448. // Windows System Error Code. All other error codes returned by
  1449. // NetUserGetLocalGroups() are valid System Error Codes according to MSDN.
  1450. ret = nStatus;
  1451. goto GetLocalGroupsForUserEnd;
  1452. }
  1453. *entries = dwEntriesRead;
  1454. GetLocalGroupsForUserEnd:
  1455. LocalFree(pUserSid);
  1456. LocalFree(fullName);
  1457. return ret;
  1458. }
  1459. //----------------------------------------------------------------------------
  1460. // Function: EnablePrivilege
  1461. //
  1462. // Description:
  1463. // Check if the process has the given privilege. If yes, enable the privilege
  1464. // to the process's access token.
  1465. //
  1466. // Returns:
  1467. // TRUE: on success
  1468. //
  1469. // Notes:
  1470. //
  1471. BOOL EnablePrivilege(__in LPCWSTR privilegeName)
  1472. {
  1473. HANDLE hToken = INVALID_HANDLE_VALUE;
  1474. TOKEN_PRIVILEGES tp = { 0 };
  1475. DWORD dwErrCode = ERROR_SUCCESS;
  1476. if (!OpenProcessToken(GetCurrentProcess(),
  1477. TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
  1478. {
  1479. ReportErrorCode(L"OpenProcessToken", GetLastError());
  1480. return FALSE;
  1481. }
  1482. tp.PrivilegeCount = 1;
  1483. if (!LookupPrivilegeValueW(NULL,
  1484. privilegeName, &(tp.Privileges[0].Luid)))
  1485. {
  1486. ReportErrorCode(L"LookupPrivilegeValue", GetLastError());
  1487. CloseHandle(hToken);
  1488. return FALSE;
  1489. }
  1490. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1491. // As stated on MSDN, we need to use GetLastError() to check if
  1492. // AdjustTokenPrivileges() adjusted all of the specified privileges.
  1493. //
  1494. AdjustTokenPrivileges(hToken, FALSE, &tp, 0, NULL, NULL);
  1495. dwErrCode = GetLastError();
  1496. CloseHandle(hToken);
  1497. return dwErrCode == ERROR_SUCCESS;
  1498. }
  1499. //----------------------------------------------------------------------------
  1500. // Function: ReportErrorCode
  1501. //
  1502. // Description:
  1503. // Report an error. Use FormatMessage function to get the system error message.
  1504. //
  1505. // Returns:
  1506. // None
  1507. //
  1508. // Notes:
  1509. //
  1510. //
  1511. void ReportErrorCode(LPCWSTR func, DWORD err)
  1512. {
  1513. DWORD len = 0;
  1514. LPWSTR msg = NULL;
  1515. assert(func != NULL);
  1516. len = FormatMessageW(
  1517. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  1518. NULL, err,
  1519. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1520. (LPWSTR)&msg, 0, NULL);
  1521. if (len > 0)
  1522. {
  1523. fwprintf(stderr, L"%s error (%d): %s\n", func, err, msg);
  1524. }
  1525. else
  1526. {
  1527. fwprintf(stderr, L"%s error code: %d.\n", func, err);
  1528. }
  1529. if (msg != NULL) LocalFree(msg);
  1530. }