libwinutils.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517
  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;
  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. if(!AuthzInitializeContextFromSid(AUTHZ_SKIP_TOKEN_GROUPS,
  534. pSid, hManager, NULL, unusedId, NULL, &hAuthzClientContext))
  535. {
  536. ret = GetLastError();
  537. goto GetEffectiveRightsForSidEnd;
  538. }
  539. if ((dwRtnCode = GetAccess(hAuthzClientContext, psd, pAccessRights))
  540. != ERROR_SUCCESS)
  541. {
  542. ret = dwRtnCode;
  543. goto GetEffectiveRightsForSidEnd;
  544. }
  545. if (!AuthzFreeContext(hAuthzClientContext))
  546. {
  547. ret = GetLastError();
  548. goto GetEffectiveRightsForSidEnd;
  549. }
  550. GetEffectiveRightsForSidEnd:
  551. return ret;
  552. }
  553. //----------------------------------------------------------------------------
  554. // Function: FindFileOwnerAndPermission
  555. //
  556. // Description:
  557. // Find the owner, primary group and permissions of a file object
  558. //
  559. // Returns:
  560. // ERROR_SUCCESS: on success
  561. // Error code otherwise
  562. //
  563. // Notes:
  564. // - Caller needs to destroy the memeory of owner and group names by calling
  565. // LocalFree() function.
  566. //
  567. // - If the user or group name does not exist, the user or group SID will be
  568. // returned as the name.
  569. //
  570. DWORD FindFileOwnerAndPermission(
  571. __in LPCWSTR pathName,
  572. __out_opt LPWSTR *pOwnerName,
  573. __out_opt LPWSTR *pGroupName,
  574. __out_opt PINT pMask)
  575. {
  576. DWORD dwRtnCode = 0;
  577. PSECURITY_DESCRIPTOR pSd = NULL;
  578. PSID psidOwner = NULL;
  579. PSID psidGroup = NULL;
  580. PSID psidEveryone = NULL;
  581. DWORD cbSid = SECURITY_MAX_SID_SIZE;
  582. PACL pDacl = NULL;
  583. ACCESS_MASK ownerAccessRights = 0;
  584. ACCESS_MASK groupAccessRights = 0;
  585. ACCESS_MASK worldAccessRights = 0;
  586. DWORD ret = ERROR_SUCCESS;
  587. // Do nothing if the caller request nothing
  588. //
  589. if (pOwnerName == NULL && pGroupName == NULL && pMask == NULL)
  590. {
  591. return ret;
  592. }
  593. dwRtnCode = GetNamedSecurityInfo(pathName, SE_FILE_OBJECT,
  594. OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
  595. DACL_SECURITY_INFORMATION,
  596. &psidOwner, &psidGroup, &pDacl, NULL, &pSd);
  597. if (dwRtnCode != ERROR_SUCCESS)
  598. {
  599. ret = dwRtnCode;
  600. goto FindFileOwnerAndPermissionEnd;
  601. }
  602. if (pOwnerName != NULL)
  603. {
  604. dwRtnCode = GetAccntNameFromSid(psidOwner, pOwnerName);
  605. if (dwRtnCode == ERROR_NONE_MAPPED)
  606. {
  607. if (!ConvertSidToStringSid(psidOwner, pOwnerName))
  608. {
  609. ret = GetLastError();
  610. goto FindFileOwnerAndPermissionEnd;
  611. }
  612. }
  613. else if (dwRtnCode != ERROR_SUCCESS)
  614. {
  615. ret = dwRtnCode;
  616. goto FindFileOwnerAndPermissionEnd;
  617. }
  618. }
  619. if (pGroupName != NULL)
  620. {
  621. dwRtnCode = GetAccntNameFromSid(psidGroup, pGroupName);
  622. if (dwRtnCode == ERROR_NONE_MAPPED)
  623. {
  624. if (!ConvertSidToStringSid(psidGroup, pGroupName))
  625. {
  626. ret = GetLastError();
  627. goto FindFileOwnerAndPermissionEnd;
  628. }
  629. }
  630. else if (dwRtnCode != ERROR_SUCCESS)
  631. {
  632. ret = dwRtnCode;
  633. goto FindFileOwnerAndPermissionEnd;
  634. }
  635. }
  636. if (pMask == NULL) goto FindFileOwnerAndPermissionEnd;
  637. if ((dwRtnCode = GetEffectiveRightsForSid(pSd,
  638. psidOwner, &ownerAccessRights)) != ERROR_SUCCESS)
  639. {
  640. ret = dwRtnCode;
  641. goto FindFileOwnerAndPermissionEnd;
  642. }
  643. if ((dwRtnCode = GetEffectiveRightsForSid(pSd,
  644. psidGroup, &groupAccessRights)) != ERROR_SUCCESS)
  645. {
  646. ret = dwRtnCode;
  647. goto FindFileOwnerAndPermissionEnd;
  648. }
  649. if ((psidEveryone = LocalAlloc(LPTR, cbSid)) == NULL)
  650. {
  651. ret = GetLastError();
  652. goto FindFileOwnerAndPermissionEnd;
  653. }
  654. if (!CreateWellKnownSid(WinWorldSid, NULL, psidEveryone, &cbSid))
  655. {
  656. ret = GetLastError();
  657. goto FindFileOwnerAndPermissionEnd;
  658. }
  659. if ((dwRtnCode = GetEffectiveRightsForSid(pSd,
  660. psidEveryone, &worldAccessRights)) != ERROR_SUCCESS)
  661. {
  662. ret = dwRtnCode;
  663. goto FindFileOwnerAndPermissionEnd;
  664. }
  665. *pMask |= GetUnixAccessMask(ownerAccessRights) << 6;
  666. *pMask |= GetUnixAccessMask(groupAccessRights) << 3;
  667. *pMask |= GetUnixAccessMask(worldAccessRights);
  668. FindFileOwnerAndPermissionEnd:
  669. LocalFree(psidEveryone);
  670. LocalFree(pSd);
  671. return ret;
  672. }
  673. //----------------------------------------------------------------------------
  674. // Function: GetWindowsAccessMask
  675. //
  676. // Description:
  677. // Get the Windows AccessMask for user, group and everyone based on the Unix
  678. // permission mask
  679. //
  680. // Returns:
  681. // none
  682. //
  683. // Notes:
  684. // none
  685. //
  686. static void GetWindowsAccessMask(INT unixMask,
  687. ACCESS_MASK *userAllow,
  688. ACCESS_MASK *userDeny,
  689. ACCESS_MASK *groupAllow,
  690. ACCESS_MASK *groupDeny,
  691. ACCESS_MASK *otherAllow)
  692. {
  693. assert (userAllow != NULL && userDeny != NULL &&
  694. groupAllow != NULL && groupDeny != NULL &&
  695. otherAllow != NULL);
  696. *userAllow = WinMasks[WIN_ALL] | WinMasks[WIN_OWNER_SE];
  697. if ((unixMask & UX_U_READ) == UX_U_READ)
  698. *userAllow |= WinMasks[WIN_READ];
  699. if ((unixMask & UX_U_WRITE) == UX_U_WRITE)
  700. *userAllow |= WinMasks[WIN_WRITE];
  701. if ((unixMask & UX_U_EXECUTE) == UX_U_EXECUTE)
  702. *userAllow |= WinMasks[WIN_EXECUTE];
  703. *userDeny = 0;
  704. if ((unixMask & UX_U_READ) != UX_U_READ &&
  705. ((unixMask & UX_G_READ) == UX_G_READ ||
  706. (unixMask & UX_O_READ) == UX_O_READ))
  707. *userDeny |= WinMasks[WIN_READ];
  708. if ((unixMask & UX_U_WRITE) != UX_U_WRITE &&
  709. ((unixMask & UX_G_WRITE) == UX_G_WRITE ||
  710. (unixMask & UX_O_WRITE) == UX_O_WRITE))
  711. *userDeny |= WinMasks[WIN_WRITE];
  712. if ((unixMask & UX_U_EXECUTE) != UX_U_EXECUTE &&
  713. ((unixMask & UX_G_EXECUTE) == UX_G_EXECUTE ||
  714. (unixMask & UX_O_EXECUTE) == UX_O_EXECUTE))
  715. *userDeny |= WinMasks[WIN_EXECUTE];
  716. *groupAllow = WinMasks[WIN_ALL];
  717. if ((unixMask & UX_G_READ) == UX_G_READ)
  718. *groupAllow |= FILE_GENERIC_READ;
  719. if ((unixMask & UX_G_WRITE) == UX_G_WRITE)
  720. *groupAllow |= WinMasks[WIN_WRITE];
  721. if ((unixMask & UX_G_EXECUTE) == UX_G_EXECUTE)
  722. *groupAllow |= WinMasks[WIN_EXECUTE];
  723. *groupDeny = 0;
  724. if ((unixMask & UX_G_READ) != UX_G_READ &&
  725. (unixMask & UX_O_READ) == UX_O_READ)
  726. *groupDeny |= WinMasks[WIN_READ];
  727. if ((unixMask & UX_G_WRITE) != UX_G_WRITE &&
  728. (unixMask & UX_O_WRITE) == UX_O_WRITE)
  729. *groupDeny |= WinMasks[WIN_WRITE];
  730. if ((unixMask & UX_G_EXECUTE) != UX_G_EXECUTE &&
  731. (unixMask & UX_O_EXECUTE) == UX_O_EXECUTE)
  732. *groupDeny |= WinMasks[WIN_EXECUTE];
  733. *otherAllow = WinMasks[WIN_ALL];
  734. if ((unixMask & UX_O_READ) == UX_O_READ)
  735. *otherAllow |= WinMasks[WIN_READ];
  736. if ((unixMask & UX_O_WRITE) == UX_O_WRITE)
  737. *otherAllow |= WinMasks[WIN_WRITE];
  738. if ((unixMask & UX_O_EXECUTE) == UX_O_EXECUTE)
  739. *otherAllow |= WinMasks[WIN_EXECUTE];
  740. }
  741. //----------------------------------------------------------------------------
  742. // Function: GetWindowsDACLs
  743. //
  744. // Description:
  745. // Get the Windows DACs based the Unix access mask
  746. //
  747. // Returns:
  748. // ERROR_SUCCESS: on success
  749. // Error code: otherwise
  750. //
  751. // Notes:
  752. // - Administrators and SYSTEM are always given full permission to the file,
  753. // unless Administrators or SYSTEM itself is the file owner and the user
  754. // explictly set the permission to something else. For example, file 'foo'
  755. // belongs to Administrators, 'chmod 000' on the file will not directly
  756. // assign Administrators full permission on the file.
  757. // - Only full permission for Administrators and SYSTEM are inheritable.
  758. // - CREATOR OWNER is always given full permission and the permission is
  759. // inheritable, more specifically OBJECT_INHERIT_ACE, CONTAINER_INHERIT_ACE
  760. // flags are set. The reason is to give the creator of child file full
  761. // permission, i.e., the child file will have permission mode 700 for
  762. // a user other than Administrator or SYSTEM.
  763. //
  764. static DWORD GetWindowsDACLs(__in INT unixMask,
  765. __in PSID pOwnerSid, __in PSID pGroupSid, __out PACL *ppNewDACL)
  766. {
  767. DWORD winUserAccessDenyMask;
  768. DWORD winUserAccessAllowMask;
  769. DWORD winGroupAccessDenyMask;
  770. DWORD winGroupAccessAllowMask;
  771. DWORD winOtherAccessAllowMask;
  772. PSID pEveryoneSid = NULL;
  773. DWORD cbEveryoneSidSize = SECURITY_MAX_SID_SIZE;
  774. PSID pSystemSid = NULL;
  775. DWORD cbSystemSidSize = SECURITY_MAX_SID_SIZE;
  776. BOOL bAddSystemAcls = FALSE;
  777. PSID pAdministratorsSid = NULL;
  778. DWORD cbAdministratorsSidSize = SECURITY_MAX_SID_SIZE;
  779. BOOL bAddAdministratorsAcls = FALSE;
  780. PSID pCreatorOwnerSid = NULL;
  781. DWORD cbCreatorOwnerSidSize = SECURITY_MAX_SID_SIZE;
  782. PACL pNewDACL = NULL;
  783. DWORD dwNewAclSize = 0;
  784. DWORD ret = ERROR_SUCCESS;
  785. GetWindowsAccessMask(unixMask,
  786. &winUserAccessAllowMask, &winUserAccessDenyMask,
  787. &winGroupAccessAllowMask, &winGroupAccessDenyMask,
  788. &winOtherAccessAllowMask);
  789. // Create a well-known SID for the Everyone group
  790. //
  791. if ((pEveryoneSid = LocalAlloc(LPTR, cbEveryoneSidSize)) == NULL)
  792. {
  793. ret = GetLastError();
  794. goto GetWindowsDACLsEnd;
  795. }
  796. if (!CreateWellKnownSid(WinWorldSid, NULL, pEveryoneSid, &cbEveryoneSidSize))
  797. {
  798. ret = GetLastError();
  799. goto GetWindowsDACLsEnd;
  800. }
  801. // Create a well-known SID for the Administrators group
  802. //
  803. if ((pAdministratorsSid = LocalAlloc(LPTR, cbAdministratorsSidSize)) == NULL)
  804. {
  805. ret = GetLastError();
  806. goto GetWindowsDACLsEnd;
  807. }
  808. if (!CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL,
  809. pAdministratorsSid, &cbAdministratorsSidSize))
  810. {
  811. ret = GetLastError();
  812. goto GetWindowsDACLsEnd;
  813. }
  814. if (!EqualSid(pAdministratorsSid, pOwnerSid)
  815. && !EqualSid(pAdministratorsSid, pGroupSid))
  816. bAddAdministratorsAcls = TRUE;
  817. // Create a well-known SID for the SYSTEM
  818. //
  819. if ((pSystemSid = LocalAlloc(LPTR, cbSystemSidSize)) == NULL)
  820. {
  821. ret = GetLastError();
  822. goto GetWindowsDACLsEnd;
  823. }
  824. if (!CreateWellKnownSid(WinLocalSystemSid, NULL,
  825. pSystemSid, &cbSystemSidSize))
  826. {
  827. ret = GetLastError();
  828. goto GetWindowsDACLsEnd;
  829. }
  830. if (!EqualSid(pSystemSid, pOwnerSid)
  831. && !EqualSid(pSystemSid, pGroupSid))
  832. bAddSystemAcls = TRUE;
  833. // Create a well-known SID for the Creator Owner
  834. //
  835. if ((pCreatorOwnerSid = LocalAlloc(LPTR, cbCreatorOwnerSidSize)) == NULL)
  836. {
  837. ret = GetLastError();
  838. goto GetWindowsDACLsEnd;
  839. }
  840. if (!CreateWellKnownSid(WinCreatorOwnerSid, NULL,
  841. pCreatorOwnerSid, &cbCreatorOwnerSidSize))
  842. {
  843. ret = GetLastError();
  844. goto GetWindowsDACLsEnd;
  845. }
  846. // Create the new DACL
  847. //
  848. dwNewAclSize = sizeof(ACL);
  849. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  850. GetLengthSid(pOwnerSid) - sizeof(DWORD);
  851. if (winUserAccessDenyMask)
  852. dwNewAclSize += sizeof(ACCESS_DENIED_ACE) +
  853. GetLengthSid(pOwnerSid) - sizeof(DWORD);
  854. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  855. GetLengthSid(pGroupSid) - sizeof(DWORD);
  856. if (winGroupAccessDenyMask)
  857. dwNewAclSize += sizeof(ACCESS_DENIED_ACE) +
  858. GetLengthSid(pGroupSid) - sizeof(DWORD);
  859. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  860. GetLengthSid(pEveryoneSid) - sizeof(DWORD);
  861. if (bAddSystemAcls)
  862. {
  863. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  864. cbSystemSidSize - sizeof(DWORD);
  865. }
  866. if (bAddAdministratorsAcls)
  867. {
  868. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  869. cbAdministratorsSidSize - sizeof(DWORD);
  870. }
  871. dwNewAclSize += sizeof(ACCESS_ALLOWED_ACE) +
  872. cbCreatorOwnerSidSize - sizeof(DWORD);
  873. pNewDACL = (PACL)LocalAlloc(LPTR, dwNewAclSize);
  874. if (pNewDACL == NULL)
  875. {
  876. ret = GetLastError();
  877. goto GetWindowsDACLsEnd;
  878. }
  879. if (!InitializeAcl(pNewDACL, dwNewAclSize, ACL_REVISION))
  880. {
  881. ret = GetLastError();
  882. goto GetWindowsDACLsEnd;
  883. }
  884. if (!AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  885. CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
  886. GENERIC_ALL, pCreatorOwnerSid))
  887. {
  888. ret = GetLastError();
  889. goto GetWindowsDACLsEnd;
  890. }
  891. if (bAddSystemAcls &&
  892. !AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  893. CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
  894. GENERIC_ALL, pSystemSid))
  895. {
  896. ret = GetLastError();
  897. goto GetWindowsDACLsEnd;
  898. }
  899. if (bAddAdministratorsAcls &&
  900. !AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  901. CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
  902. GENERIC_ALL, pAdministratorsSid))
  903. {
  904. ret = GetLastError();
  905. goto GetWindowsDACLsEnd;
  906. }
  907. if (winUserAccessDenyMask &&
  908. !AddAccessDeniedAceEx(pNewDACL, ACL_REVISION,
  909. NO_PROPAGATE_INHERIT_ACE,
  910. winUserAccessDenyMask, pOwnerSid))
  911. {
  912. ret = GetLastError();
  913. goto GetWindowsDACLsEnd;
  914. }
  915. if (!AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  916. NO_PROPAGATE_INHERIT_ACE,
  917. winUserAccessAllowMask, pOwnerSid))
  918. {
  919. ret = GetLastError();
  920. goto GetWindowsDACLsEnd;
  921. }
  922. if (winGroupAccessDenyMask &&
  923. !AddAccessDeniedAceEx(pNewDACL, ACL_REVISION,
  924. NO_PROPAGATE_INHERIT_ACE,
  925. winGroupAccessDenyMask, pGroupSid))
  926. {
  927. ret = GetLastError();
  928. goto GetWindowsDACLsEnd;
  929. }
  930. if (!AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  931. NO_PROPAGATE_INHERIT_ACE,
  932. winGroupAccessAllowMask, pGroupSid))
  933. {
  934. ret = GetLastError();
  935. goto GetWindowsDACLsEnd;
  936. }
  937. if (!AddAccessAllowedAceEx(pNewDACL, ACL_REVISION,
  938. NO_PROPAGATE_INHERIT_ACE,
  939. winOtherAccessAllowMask, pEveryoneSid))
  940. {
  941. ret = GetLastError();
  942. goto GetWindowsDACLsEnd;
  943. }
  944. *ppNewDACL = pNewDACL;
  945. GetWindowsDACLsEnd:
  946. LocalFree(pEveryoneSid);
  947. LocalFree(pAdministratorsSid);
  948. LocalFree(pSystemSid);
  949. LocalFree(pCreatorOwnerSid);
  950. if (ret != ERROR_SUCCESS) LocalFree(pNewDACL);
  951. return ret;
  952. }
  953. //----------------------------------------------------------------------------
  954. // Function: ChangeFileModeByMask
  955. //
  956. // Description:
  957. // Change a file or direcotry at the path to Unix mode
  958. //
  959. // Returns:
  960. // ERROR_SUCCESS: on success
  961. // Error code: otherwise
  962. //
  963. // Notes:
  964. // This function is long path safe, i.e. the path will be converted to long
  965. // path format if not already converted. So the caller does not need to do
  966. // the converstion before calling the method.
  967. //
  968. DWORD ChangeFileModeByMask(__in LPCWSTR path, INT mode)
  969. {
  970. LPWSTR longPathName = NULL;
  971. PACL pNewDACL = NULL;
  972. PSID pOwnerSid = NULL;
  973. PSID pGroupSid = NULL;
  974. PSECURITY_DESCRIPTOR pSD = NULL;
  975. SECURITY_DESCRIPTOR_CONTROL control;
  976. DWORD revision = 0;
  977. PSECURITY_DESCRIPTOR pAbsSD = NULL;
  978. PSECURITY_DESCRIPTOR pNonNullSD = NULL;
  979. PACL pAbsDacl = NULL;
  980. PACL pAbsSacl = NULL;
  981. PSID pAbsOwner = NULL;
  982. PSID pAbsGroup = NULL;
  983. DWORD dwRtnCode = 0;
  984. DWORD dwErrorCode = 0;
  985. DWORD ret = ERROR_SUCCESS;
  986. dwRtnCode = ConvertToLongPath(path, &longPathName);
  987. if (dwRtnCode != ERROR_SUCCESS)
  988. {
  989. ret = dwRtnCode;
  990. goto ChangeFileModeByMaskEnd;
  991. }
  992. // Get owner and group Sids
  993. //
  994. dwRtnCode = GetNamedSecurityInfoW(
  995. longPathName,
  996. SE_FILE_OBJECT,
  997. OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION,
  998. &pOwnerSid,
  999. &pGroupSid,
  1000. NULL,
  1001. NULL,
  1002. &pSD);
  1003. if (ERROR_SUCCESS != dwRtnCode)
  1004. {
  1005. ret = dwRtnCode;
  1006. goto ChangeFileModeByMaskEnd;
  1007. }
  1008. // SetSecurityDescriptorDacl function used below only accepts security
  1009. // descriptor in absolute format, meaning that its members must be pointers to
  1010. // other structures, rather than offsets to contiguous data.
  1011. // To determine whether a security descriptor is self-relative or absolute,
  1012. // call the GetSecurityDescriptorControl function and check the
  1013. // SE_SELF_RELATIVE flag of the SECURITY_DESCRIPTOR_CONTROL parameter.
  1014. //
  1015. if (!GetSecurityDescriptorControl(pSD, &control, &revision))
  1016. {
  1017. ret = GetLastError();
  1018. goto ChangeFileModeByMaskEnd;
  1019. }
  1020. // If the security descriptor is self-relative, we use MakeAbsoluteSD function
  1021. // to convert it to absolute format.
  1022. //
  1023. if ((control & SE_SELF_RELATIVE) == SE_SELF_RELATIVE)
  1024. {
  1025. DWORD absSDSize = 0;
  1026. DWORD daclSize = 0;
  1027. DWORD saclSize = 0;
  1028. DWORD ownerSize = 0;
  1029. DWORD primaryGroupSize = 0;
  1030. MakeAbsoluteSD(pSD, NULL, &absSDSize, NULL, &daclSize, NULL,
  1031. &saclSize, NULL, &ownerSize, NULL, &primaryGroupSize);
  1032. if ((dwErrorCode = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
  1033. {
  1034. ret = dwErrorCode;
  1035. goto ChangeFileModeByMaskEnd;
  1036. }
  1037. if ((pAbsSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, absSDSize)) == NULL)
  1038. {
  1039. ret = GetLastError();
  1040. goto ChangeFileModeByMaskEnd;
  1041. }
  1042. if ((pAbsDacl = (PACL) LocalAlloc(LPTR, daclSize)) == NULL)
  1043. {
  1044. ret = GetLastError();
  1045. goto ChangeFileModeByMaskEnd;
  1046. }
  1047. if ((pAbsSacl = (PACL) LocalAlloc(LPTR, saclSize)) == NULL)
  1048. {
  1049. ret = GetLastError();
  1050. goto ChangeFileModeByMaskEnd;
  1051. }
  1052. if ((pAbsOwner = (PSID) LocalAlloc(LPTR, ownerSize)) == NULL)
  1053. {
  1054. ret = GetLastError();
  1055. goto ChangeFileModeByMaskEnd;
  1056. }
  1057. if ((pAbsGroup = (PSID) LocalAlloc(LPTR, primaryGroupSize)) == NULL)
  1058. {
  1059. ret = GetLastError();
  1060. goto ChangeFileModeByMaskEnd;
  1061. }
  1062. if (!MakeAbsoluteSD(pSD, pAbsSD, &absSDSize, pAbsDacl, &daclSize, pAbsSacl,
  1063. &saclSize, pAbsOwner, &ownerSize, pAbsGroup, &primaryGroupSize))
  1064. {
  1065. ret = GetLastError();
  1066. goto ChangeFileModeByMaskEnd;
  1067. }
  1068. }
  1069. // Get Windows DACLs based on Unix access mask
  1070. //
  1071. if ((dwRtnCode = GetWindowsDACLs(mode, pOwnerSid, pGroupSid, &pNewDACL))
  1072. != ERROR_SUCCESS)
  1073. {
  1074. ret = dwRtnCode;
  1075. goto ChangeFileModeByMaskEnd;
  1076. }
  1077. // Set the DACL information in the security descriptor; if a DACL is already
  1078. // present in the security descriptor, the DACL is replaced. The security
  1079. // descriptor is then used to set the security of a file or directory.
  1080. //
  1081. pNonNullSD = (pAbsSD != NULL) ? pAbsSD : pSD;
  1082. if (!SetSecurityDescriptorDacl(pNonNullSD, TRUE, pNewDACL, FALSE))
  1083. {
  1084. ret = GetLastError();
  1085. goto ChangeFileModeByMaskEnd;
  1086. }
  1087. // MSDN states "This function is obsolete. Use the SetNamedSecurityInfo
  1088. // function instead." However we have the following problem when using
  1089. // SetNamedSecurityInfo:
  1090. // - When PROTECTED_DACL_SECURITY_INFORMATION is not passed in as part of
  1091. // security information, the object will include inheritable permissions
  1092. // from its parent.
  1093. // - When PROTECTED_DACL_SECURITY_INFORMATION is passsed in to set
  1094. // permissions on a directory, the child object of the directory will lose
  1095. // inheritable permissions from their parent (the current directory).
  1096. // By using SetFileSecurity, we have the nice property that the new
  1097. // permissions of the object does not include the inheritable permissions from
  1098. // its parent, and the child objects will not lose their inherited permissions
  1099. // from the current object.
  1100. //
  1101. if (!SetFileSecurity(longPathName, DACL_SECURITY_INFORMATION, pNonNullSD))
  1102. {
  1103. ret = GetLastError();
  1104. goto ChangeFileModeByMaskEnd;
  1105. }
  1106. ChangeFileModeByMaskEnd:
  1107. pNonNullSD = NULL;
  1108. LocalFree(longPathName);
  1109. LocalFree(pSD);
  1110. LocalFree(pNewDACL);
  1111. LocalFree(pAbsDacl);
  1112. LocalFree(pAbsSacl);
  1113. LocalFree(pAbsOwner);
  1114. LocalFree(pAbsGroup);
  1115. LocalFree(pAbsSD);
  1116. return ret;
  1117. }
  1118. //----------------------------------------------------------------------------
  1119. // Function: GetAccntNameFromSid
  1120. //
  1121. // Description:
  1122. // To retrieve an account name given the SID
  1123. //
  1124. // Returns:
  1125. // ERROR_SUCCESS: on success
  1126. // Other error code: otherwise
  1127. //
  1128. // Notes:
  1129. // Caller needs to destroy the memory of account name by calling LocalFree()
  1130. //
  1131. DWORD GetAccntNameFromSid(__in PSID pSid, __out PWSTR *ppAcctName)
  1132. {
  1133. LPWSTR lpName = NULL;
  1134. DWORD cchName = 0;
  1135. LPWSTR lpDomainName = NULL;
  1136. DWORD cchDomainName = 0;
  1137. SID_NAME_USE eUse = SidTypeUnknown;
  1138. DWORD cchAcctName = 0;
  1139. DWORD dwErrorCode = ERROR_SUCCESS;
  1140. HRESULT hr = S_OK;
  1141. DWORD ret = ERROR_SUCCESS;
  1142. assert(ppAcctName != NULL);
  1143. // NOTE:
  1144. // MSDN says the length returned for the buffer size including the terminating
  1145. // null character. However we found it is not true during debuging.
  1146. //
  1147. LookupAccountSid(NULL, pSid, NULL, &cchName, NULL, &cchDomainName, &eUse);
  1148. if ((dwErrorCode = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
  1149. return dwErrorCode;
  1150. lpName = (LPWSTR) LocalAlloc(LPTR, (cchName + 1) * sizeof(WCHAR));
  1151. if (lpName == NULL)
  1152. {
  1153. ret = GetLastError();
  1154. goto GetAccntNameFromSidEnd;
  1155. }
  1156. lpDomainName = (LPWSTR) LocalAlloc(LPTR, (cchDomainName + 1) * sizeof(WCHAR));
  1157. if (lpDomainName == NULL)
  1158. {
  1159. ret = GetLastError();
  1160. goto GetAccntNameFromSidEnd;
  1161. }
  1162. if (!LookupAccountSid(NULL, pSid,
  1163. lpName, &cchName, lpDomainName, &cchDomainName, &eUse))
  1164. {
  1165. ret = GetLastError();
  1166. goto GetAccntNameFromSidEnd;
  1167. }
  1168. // Buffer size = name length + 1 for '\' + domain length + 1 for NULL
  1169. cchAcctName = cchName + cchDomainName + 2;
  1170. *ppAcctName = (LPWSTR) LocalAlloc(LPTR, cchAcctName * sizeof(WCHAR));
  1171. if (*ppAcctName == NULL)
  1172. {
  1173. ret = GetLastError();
  1174. goto GetAccntNameFromSidEnd;
  1175. }
  1176. hr = StringCchCopyW(*ppAcctName, cchAcctName, lpDomainName);
  1177. if (FAILED(hr))
  1178. {
  1179. ret = HRESULT_CODE(hr);
  1180. goto GetAccntNameFromSidEnd;
  1181. }
  1182. hr = StringCchCatW(*ppAcctName, cchAcctName, L"\\");
  1183. if (FAILED(hr))
  1184. {
  1185. ret = HRESULT_CODE(hr);
  1186. goto GetAccntNameFromSidEnd;
  1187. }
  1188. hr = StringCchCatW(*ppAcctName, cchAcctName, lpName);
  1189. if (FAILED(hr))
  1190. {
  1191. ret = HRESULT_CODE(hr);
  1192. goto GetAccntNameFromSidEnd;
  1193. }
  1194. GetAccntNameFromSidEnd:
  1195. LocalFree(lpName);
  1196. LocalFree(lpDomainName);
  1197. if (ret != ERROR_SUCCESS)
  1198. {
  1199. LocalFree(*ppAcctName);
  1200. *ppAcctName = NULL;
  1201. }
  1202. return ret;
  1203. }
  1204. //----------------------------------------------------------------------------
  1205. // Function: GetLocalGroupsForUser
  1206. //
  1207. // Description:
  1208. // Get an array of groups for the given user.
  1209. //
  1210. // Returns:
  1211. // ERROR_SUCCESS on success
  1212. // Other error code on failure
  1213. //
  1214. // Notes:
  1215. // - NetUserGetLocalGroups() function only accepts full user name in the format
  1216. // [domain name]\[username]. The user input to this function can be only the
  1217. // username. In this case, NetUserGetLocalGroups() will fail on the first try,
  1218. // and we will try to find full user name using LookupAccountNameW() method,
  1219. // and call NetUserGetLocalGroups() function again with full user name.
  1220. // However, it is not always possible to find full user name given only user
  1221. // name. For example, a computer named 'win1' joined domain 'redmond' can have
  1222. // two different users, 'win1\alex' and 'redmond\alex'. Given only 'alex', we
  1223. // cannot tell which one is correct.
  1224. //
  1225. // - Caller needs to destroy the memory of groups by using the
  1226. // NetApiBufferFree() function
  1227. //
  1228. DWORD GetLocalGroupsForUser(
  1229. __in LPCWSTR user,
  1230. __out LPLOCALGROUP_USERS_INFO_0 *groups,
  1231. __out LPDWORD entries)
  1232. {
  1233. DWORD dwEntriesRead = 0;
  1234. DWORD dwTotalEntries = 0;
  1235. NET_API_STATUS nStatus = NERR_Success;
  1236. PSID pUserSid = NULL;
  1237. LPWSTR fullName = NULL;
  1238. DWORD dwRtnCode = ERROR_SUCCESS;
  1239. DWORD ret = ERROR_SUCCESS;
  1240. *groups = NULL;
  1241. *entries = 0;
  1242. nStatus = NetUserGetLocalGroups(NULL,
  1243. user,
  1244. 0,
  1245. 0,
  1246. (LPBYTE *) groups,
  1247. MAX_PREFERRED_LENGTH,
  1248. &dwEntriesRead,
  1249. &dwTotalEntries);
  1250. if (nStatus == NERR_Success)
  1251. {
  1252. *entries = dwEntriesRead;
  1253. return ERROR_SUCCESS;
  1254. }
  1255. else if (nStatus != NERR_UserNotFound)
  1256. {
  1257. return nStatus;
  1258. }
  1259. if ((dwRtnCode = GetSidFromAcctNameW(user, &pUserSid)) != ERROR_SUCCESS)
  1260. {
  1261. ret = dwRtnCode;
  1262. goto GetLocalGroupsForUserEnd;
  1263. }
  1264. if ((dwRtnCode = GetAccntNameFromSid(pUserSid, &fullName)) != ERROR_SUCCESS)
  1265. {
  1266. ret = dwRtnCode;
  1267. goto GetLocalGroupsForUserEnd;
  1268. }
  1269. nStatus = NetUserGetLocalGroups(NULL,
  1270. fullName,
  1271. 0,
  1272. 0,
  1273. (LPBYTE *) groups,
  1274. MAX_PREFERRED_LENGTH,
  1275. &dwEntriesRead,
  1276. &dwTotalEntries);
  1277. if (nStatus != NERR_Success)
  1278. {
  1279. // NERR_DCNotFound (2453) and NERR_UserNotFound (2221) are not published
  1280. // Windows System Error Code. All other error codes returned by
  1281. // NetUserGetLocalGroups() are valid System Error Codes according to MSDN.
  1282. ret = nStatus;
  1283. goto GetLocalGroupsForUserEnd;
  1284. }
  1285. *entries = dwEntriesRead;
  1286. GetLocalGroupsForUserEnd:
  1287. LocalFree(pUserSid);
  1288. LocalFree(fullName);
  1289. return ret;
  1290. }
  1291. //----------------------------------------------------------------------------
  1292. // Function: EnablePrivilege
  1293. //
  1294. // Description:
  1295. // Check if the process has the given privilege. If yes, enable the privilege
  1296. // to the process's access token.
  1297. //
  1298. // Returns:
  1299. // TRUE: on success
  1300. //
  1301. // Notes:
  1302. //
  1303. BOOL EnablePrivilege(__in LPCWSTR privilegeName)
  1304. {
  1305. HANDLE hToken = INVALID_HANDLE_VALUE;
  1306. TOKEN_PRIVILEGES tp = { 0 };
  1307. DWORD dwErrCode = ERROR_SUCCESS;
  1308. if (!OpenProcessToken(GetCurrentProcess(),
  1309. TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
  1310. {
  1311. ReportErrorCode(L"OpenProcessToken", GetLastError());
  1312. return FALSE;
  1313. }
  1314. tp.PrivilegeCount = 1;
  1315. if (!LookupPrivilegeValueW(NULL,
  1316. privilegeName, &(tp.Privileges[0].Luid)))
  1317. {
  1318. ReportErrorCode(L"LookupPrivilegeValue", GetLastError());
  1319. CloseHandle(hToken);
  1320. return FALSE;
  1321. }
  1322. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1323. // As stated on MSDN, we need to use GetLastError() to check if
  1324. // AdjustTokenPrivileges() adjusted all of the specified privileges.
  1325. //
  1326. AdjustTokenPrivileges(hToken, FALSE, &tp, 0, NULL, NULL);
  1327. dwErrCode = GetLastError();
  1328. CloseHandle(hToken);
  1329. return dwErrCode == ERROR_SUCCESS;
  1330. }
  1331. //----------------------------------------------------------------------------
  1332. // Function: ReportErrorCode
  1333. //
  1334. // Description:
  1335. // Report an error. Use FormatMessage function to get the system error message.
  1336. //
  1337. // Returns:
  1338. // None
  1339. //
  1340. // Notes:
  1341. //
  1342. //
  1343. void ReportErrorCode(LPCWSTR func, DWORD err)
  1344. {
  1345. DWORD len = 0;
  1346. LPWSTR msg = NULL;
  1347. assert(func != NULL);
  1348. len = FormatMessageW(
  1349. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  1350. NULL, err,
  1351. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1352. (LPWSTR)&msg, 0, NULL);
  1353. if (len > 0)
  1354. {
  1355. fwprintf(stderr, L"%s error (%d): %s\n", func, err, msg);
  1356. }
  1357. else
  1358. {
  1359. fwprintf(stderr, L"%s error code: %d.\n", func, err);
  1360. }
  1361. if (msg != NULL) LocalFree(msg);
  1362. }