Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

939 lines
26 KiB

  1. /*++
  2. Copyright (c) 1991-1994 Microsoft Corporation
  3. Module Name:
  4. logclear.c
  5. Abstract:
  6. Contains functions used to log an event indicating who cleared the log.
  7. This is only called after the security log has been cleared.
  8. Author:
  9. Dan Lafferty (danl) 01-July-1994
  10. Environment:
  11. User Mode -Win32
  12. Revision History:
  13. 01-July-1994 danl & robertre
  14. Created - Rob supplied the code which I fitted into the eventlog.
  15. --*/
  16. #include <nt.h>
  17. #include <ntrtl.h>
  18. #include <nturtl.h>
  19. #include <windows.h>
  20. #include <stdio.h>
  21. #include <msaudite.h>
  22. #include <eventp.h>
  23. #include <tstr.h>
  24. #include <winsock2.h>
  25. #include <strsafe.h>
  26. #define NUM_STRINGS 6
  27. //
  28. // LOCAL FUNCTION PROTOTYPES
  29. //
  30. BOOL
  31. GetUserInfo(
  32. IN HANDLE Token,
  33. OUT LPWSTR *UserName,
  34. OUT LPWSTR *DomainName,
  35. OUT LPWSTR *AuthenticationId,
  36. OUT PSID *UserSid
  37. );
  38. LPWSTR
  39. GetNameFromIPAddress(
  40. LPWSTR pszComputerNameFromBinding);
  41. BOOL
  42. IsLocal(
  43. VOID
  44. );
  45. VOID
  46. ElfpGenerateLogClearedEvent(
  47. IELF_HANDLE LogHandle,
  48. LPWSTR pwsClientSidString,
  49. LPWSTR pwsComputerName,
  50. PTOKEN_USER pToken
  51. )
  52. /*++
  53. Routine Description:
  54. This function generates an event indicating that the log was cleared.
  55. Arguments:
  56. LogHandle -- This is a handle to the log that the event is to be placed in.
  57. It is intended that this function only be called when the SecurityLog
  58. has been cleared. So it is expected the LogHandle will always be
  59. a handle to the security log.
  60. Return Value:
  61. None -- Either it works or it doesn't. If it doesn't, there isn't much
  62. we can do about it.
  63. --*/
  64. {
  65. LPWSTR UserName = L"-";
  66. LPWSTR DomainName = L"-";
  67. LPWSTR AuthenticationId = L"-";
  68. LPWSTR ClientUserName = pwsClientSidString;
  69. LPWSTR ClientDomainName = L"-";
  70. LPWSTR ClientAuthenticationId = L"-";
  71. PSID UserSid = NULL;
  72. DWORD i;
  73. BOOL Result;
  74. HANDLE Token;
  75. PUNICODE_STRING StringPtrArray[NUM_STRINGS];
  76. UNICODE_STRING StringArray[NUM_STRINGS];
  77. NTSTATUS Status;
  78. LARGE_INTEGER Time;
  79. ULONG EventTime;
  80. ULONG LogHandleGrantedAccess;
  81. UNICODE_STRING ComputerNameU;
  82. DWORD dwStatus;
  83. BOOL bUserNameSet = FALSE;
  84. BOOL bClientInfoSet = FALSE;
  85. //
  86. // Get information about the Eventlog service (i.e., LocalSystem)
  87. //
  88. Result = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &Token);
  89. if (!Result)
  90. {
  91. ELF_LOG1(ERROR,
  92. "ElfpGenerateLogClearedEvent: OpenProcessToken failed %d\n",
  93. GetLastError());
  94. }
  95. else
  96. {
  97. Result = GetUserInfo(Token,
  98. &UserName,
  99. &DomainName,
  100. &AuthenticationId,
  101. &UserSid);
  102. CloseHandle(Token);
  103. if (!Result)
  104. {
  105. ELF_LOG1(ERROR,
  106. "ElfpGenerateLogClearedEvent: GetUserInfo failed %d\n",
  107. GetLastError());
  108. }
  109. else
  110. bUserNameSet = TRUE;
  111. }
  112. if(!bUserNameSet)
  113. {
  114. UserName = L"-";
  115. DomainName = L"-";
  116. AuthenticationId = L"-";
  117. UserSid = pToken->User.Sid;
  118. }
  119. ELF_LOG3(TRACE,
  120. "ElfpGenerateLogClearedEvent: GetUserInfo returned: \n"
  121. "\tUserName = %ws,\n"
  122. "\tDomainName = %ws,\n"
  123. "\tAuthenticationId = %ws\n",
  124. UserName,
  125. DomainName,
  126. AuthenticationId);
  127. //
  128. // Now impersonate in order to get the client's information.
  129. // This call should never fail.
  130. //
  131. dwStatus = RpcImpersonateClient(NULL);
  132. if (dwStatus != RPC_S_OK)
  133. {
  134. ELF_LOG1(ERROR,
  135. "ElfpGenerateLogClearedEvent: RpcImpersonateClient failed %d\n",
  136. dwStatus);
  137. }
  138. else
  139. {
  140. Result = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &Token);
  141. if (!Result)
  142. {
  143. ELF_LOG1(ERROR,
  144. "ElfpGenerateLogClearedEvent: OpenThreadToken failed %d\n",
  145. GetLastError());
  146. ASSERT(FALSE);
  147. }
  148. else
  149. {
  150. Result = GetUserInfo(Token,
  151. &ClientUserName,
  152. &ClientDomainName,
  153. &ClientAuthenticationId,
  154. NULL);
  155. CloseHandle(Token);
  156. if (!Result)
  157. {
  158. ELF_LOG1(ERROR,
  159. "ElfpGenerateLogClearedEvent: GetUserInfo (call 2) failed %d\n",
  160. GetLastError());
  161. }
  162. else
  163. bClientInfoSet = TRUE;
  164. }
  165. }
  166. if(!bClientInfoSet)
  167. {
  168. ClientUserName = pwsClientSidString;
  169. ClientDomainName = L"-";
  170. ClientAuthenticationId = L"-";
  171. }
  172. ELF_LOG3(TRACE,
  173. "ElfpGenerateLogClearedEvent: GetUserInfo (call 2) returned: \n"
  174. "\tUserName = %ws,\n"
  175. "\tDomainName = %ws,\n"
  176. "\tAuthenticationId = %ws\n",
  177. ClientUserName,
  178. ClientDomainName,
  179. ClientAuthenticationId);
  180. RtlInitUnicodeString(&StringArray[0], UserName);
  181. RtlInitUnicodeString(&StringArray[1], DomainName);
  182. RtlInitUnicodeString(&StringArray[2], AuthenticationId);
  183. RtlInitUnicodeString(&StringArray[3], ClientUserName);
  184. RtlInitUnicodeString(&StringArray[4], ClientDomainName);
  185. RtlInitUnicodeString(&StringArray[5], ClientAuthenticationId);
  186. //
  187. // Create an array of pointers to UNICODE_STRINGs.
  188. //
  189. for (i = 0; i < NUM_STRINGS; i++)
  190. {
  191. StringPtrArray[i] = &StringArray[i];
  192. }
  193. //
  194. // Generate the time of the event. This is done on the client side
  195. // since that is where the event occurred.
  196. //
  197. NtQuerySystemTime(&Time);
  198. RtlTimeToSecondsSince1970(&Time, &EventTime);
  199. RtlInitUnicodeString(&ComputerNameU, pwsComputerName);
  200. //
  201. // Since all processes other than LSA are given read-only access
  202. // to the security log, we have to explicitly give the current
  203. // process the right to write the "Log cleared" event
  204. //
  205. LogHandleGrantedAccess = LogHandle->GrantedAccess;
  206. LogHandle->GrantedAccess |= ELF_LOGFILE_WRITE;
  207. Status = ElfrReportEventW (
  208. LogHandle, // Log Handle
  209. EventTime, // Time
  210. EVENTLOG_AUDIT_SUCCESS, // Event Type
  211. (USHORT)SE_CATEGID_SYSTEM, // Event Category
  212. SE_AUDITID_AUDIT_LOG_CLEARED, // EventID
  213. NUM_STRINGS, // NumStrings
  214. 0, // DataSize
  215. &ComputerNameU, // ComputerNameU
  216. UserSid, // UserSid
  217. StringPtrArray, // *Strings
  218. NULL, // Data
  219. 0, // Flags
  220. NULL, // RecordNumber
  221. NULL); // TimeWritten
  222. LogHandle->GrantedAccess = LogHandleGrantedAccess;
  223. //
  224. // We only come down this path if we know for sure that these
  225. // first three have been allocated.
  226. //
  227. if(bUserNameSet)
  228. {
  229. ElfpFreeBuffer(UserName);
  230. ElfpFreeBuffer(DomainName);
  231. ElfpFreeBuffer(AuthenticationId);
  232. ElfpFreeBuffer(UserSid);
  233. }
  234. if(bClientInfoSet)
  235. {
  236. ElfpFreeBuffer(ClientUserName);
  237. ElfpFreeBuffer(ClientDomainName);
  238. ElfpFreeBuffer(ClientAuthenticationId);
  239. }
  240. //
  241. // Stop impersonating
  242. //
  243. dwStatus = RpcRevertToSelf();
  244. if (dwStatus != RPC_S_OK)
  245. {
  246. ELF_LOG1(ERROR,
  247. "ElfpGenerateLogClearedEvent: RpcRevertToSelf failed %d\n",
  248. GetLastError());
  249. }
  250. }
  251. BOOL
  252. GetUserInfo(
  253. IN HANDLE Token,
  254. OUT LPWSTR *UserName,
  255. OUT LPWSTR *DomainName,
  256. OUT LPWSTR *AuthenticationId,
  257. OUT PSID *UserSid
  258. )
  259. /*++
  260. Routine Description:
  261. This function gathers information about the user identified with the
  262. token.
  263. Arguments:
  264. Token - This token identifies the entity for which we are gathering
  265. information.
  266. UserName - This is the entity's user name.
  267. DomainName - This is the entity's domain name.
  268. AuthenticationId - This is the entity's Authentication ID.
  269. UserSid - This is the entity's SID.
  270. NOTE:
  271. Memory is allocated by this routine for UserName, DomainName,
  272. AuthenticationId, and UserSid. It is the caller's responsibility to
  273. free this memory.
  274. Return Value:
  275. TRUE - If the operation was successful. It is possible that
  276. UserSid did not get allocated in the successful case. Therefore,
  277. the caller should test prior to freeing.
  278. FALSE - If unsuccessful. No memory is allocated in this case.
  279. --*/
  280. {
  281. PTOKEN_USER Buffer = NULL;
  282. LPWSTR Domain = NULL;
  283. LPWSTR AccountName = NULL;
  284. SID_NAME_USE Use;
  285. BOOL Result;
  286. DWORD RequiredLength;
  287. DWORD AccountNameSize;
  288. DWORD DomainNameSize;
  289. TOKEN_STATISTICS Statistics;
  290. WCHAR LogonIdString[256];
  291. DWORD Status = ERROR_SUCCESS;
  292. if(UserSid)
  293. *UserSid = NULL;
  294. Result = GetTokenInformation(Token, TokenUser, NULL, 0, &RequiredLength);
  295. if (!Result)
  296. {
  297. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
  298. {
  299. ELF_LOG1(TRACE,
  300. "GetUserInfo: GetTokenInformation needs %d bytes\n",
  301. RequiredLength);
  302. Buffer = ElfpAllocateBuffer(RequiredLength);
  303. if (Buffer == NULL)
  304. {
  305. ELF_LOG0(ERROR,
  306. "GetUserInfo: Unable to allocate memory for token\n");
  307. return FALSE;
  308. }
  309. Result = GetTokenInformation(Token,
  310. TokenUser,
  311. Buffer,
  312. RequiredLength,
  313. &RequiredLength);
  314. if (!Result)
  315. {
  316. ELF_LOG1(ERROR,
  317. "GetUserInfo: GetTokenInformation (call 2) failed %d\n",
  318. GetLastError());
  319. ElfpFreeBuffer(Buffer);
  320. return FALSE;
  321. }
  322. }
  323. else
  324. {
  325. ELF_LOG1(ERROR,
  326. "GetUserInfo: GetTokenInformation (call 1) failed %d\n",
  327. GetLastError());
  328. return FALSE;
  329. }
  330. }
  331. AccountNameSize = 0;
  332. DomainNameSize = 0;
  333. Result = LookupAccountSidW(L"",
  334. Buffer->User.Sid,
  335. NULL,
  336. &AccountNameSize,
  337. NULL,
  338. &DomainNameSize,
  339. &Use);
  340. if (!Result)
  341. {
  342. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
  343. {
  344. AccountName = ElfpAllocateBuffer((AccountNameSize + 1) * sizeof(WCHAR));
  345. Domain = ElfpAllocateBuffer((DomainNameSize + 1) * sizeof(WCHAR));
  346. if (AccountName == NULL)
  347. {
  348. ELF_LOG1(ERROR,
  349. "GetUserInfo: Unable to allocate %d bytes for AccountName\n",
  350. AccountNameSize);
  351. goto ErrorCleanup;
  352. }
  353. if (Domain == NULL)
  354. {
  355. ELF_LOG1(ERROR,
  356. "GetUserInfo: Unable to allocate %d bytes for Domain\n",
  357. DomainNameSize);
  358. goto ErrorCleanup;
  359. }
  360. Result = LookupAccountSidW(L"",
  361. Buffer->User.Sid,
  362. AccountName,
  363. &AccountNameSize,
  364. Domain,
  365. &DomainNameSize,
  366. &Use
  367. );
  368. if (!Result)
  369. {
  370. ELF_LOG1(ERROR,
  371. "GetUserInfo: LookupAccountSid (call 2) failed %d\n",
  372. GetLastError());
  373. goto ErrorCleanup;
  374. }
  375. }
  376. else
  377. {
  378. ELF_LOG1(ERROR,
  379. "GetUserInfo: LookupAccountsid (call 1) failed %d\n",
  380. GetLastError());
  381. goto ErrorCleanup;
  382. }
  383. }
  384. else
  385. {
  386. ELF_LOG0(ERROR,
  387. "GetUserInfo: LookupAccountSid succeeded unexpectedly\n");
  388. goto ErrorCleanup;
  389. }
  390. ELF_LOG2(TRACE,
  391. "GetUserInfo: Name = %ws\\%ws\n",
  392. Domain,
  393. AccountName);
  394. Result = GetTokenInformation(Token,
  395. TokenStatistics,
  396. &Statistics,
  397. sizeof(Statistics),
  398. &RequiredLength);
  399. if (!Result)
  400. {
  401. ELF_LOG1(ERROR,
  402. "GetUserInfo: GetTokenInformation (call 3) failed %d\n",
  403. GetLastError());
  404. goto ErrorCleanup;
  405. }
  406. StringCchPrintfW(LogonIdString, 256,
  407. L"(0x%X,0x%X)",
  408. Statistics.AuthenticationId.HighPart,
  409. Statistics.AuthenticationId.LowPart);
  410. ELF_LOG1(TRACE,
  411. "GetUserInfo: LogonIdString = %ws\n",
  412. LogonIdString);
  413. *AuthenticationId = ElfpAllocateBuffer(WCSSIZE(LogonIdString));
  414. if (*AuthenticationId == NULL)
  415. {
  416. ELF_LOG0(ERROR,
  417. "GetUserInfo: Unable to allocate memory for AuthenticationId\n");
  418. goto ErrorCleanup;
  419. }
  420. StringCchCopyW(*AuthenticationId, wcslen(LogonIdString) +1, LogonIdString);
  421. //
  422. // Return accumulated information
  423. //
  424. if(UserSid)
  425. {
  426. *UserSid = ElfpAllocateBuffer(GetLengthSid(Buffer->User.Sid));
  427. if (*UserSid == NULL)
  428. {
  429. ELF_LOG0(ERROR,
  430. "GetUserInfo: Unable to allocate memory for UserSid\n");
  431. goto ErrorCleanup;
  432. }
  433. Result = CopySid(GetLengthSid(Buffer->User.Sid),
  434. *UserSid,
  435. Buffer->User.Sid);
  436. }
  437. ElfpFreeBuffer(Buffer);
  438. *DomainName = Domain;
  439. *UserName = AccountName;
  440. return TRUE;
  441. ErrorCleanup:
  442. ElfpFreeBuffer(Buffer);
  443. ElfpFreeBuffer(Domain);
  444. ElfpFreeBuffer(AccountName);
  445. if(UserSid)
  446. ElfpFreeBuffer(*UserSid);
  447. ElfpFreeBuffer(*AuthenticationId);
  448. return FALSE;
  449. }
  450. LPWSTR
  451. GetNameFromIPAddress(
  452. LPWSTR pszComputerNameFromBinding)
  453. /*++
  454. Routine Description:
  455. Examines a string and determines if it looks like an ip address. If it
  456. does, then it converts it to a fqdn
  457. Arguments:
  458. Machine name: Could be xxx.xxx.xxx.xxx or anything else!
  459. Return Value:
  460. If successful, returns a fully qualified domain name which the caller
  461. will free. Returns NULL if there are any problems.
  462. --*/
  463. {
  464. LPWSTR pComputerName = NULL;
  465. DWORD dwAddr;
  466. char cName[17]; // should be plenty of room
  467. size_t NumConv;
  468. HOSTENT FAR * pEnt;
  469. DWORD dwSize;
  470. WORD wVersionRequested;
  471. WSADATA wsaData;
  472. int error;
  473. NumConv = wcstombs(cName, pszComputerNameFromBinding, 16);
  474. if(NumConv == -1 || NumConv == 0)
  475. return NULL;
  476. // convert the string into a network order dword representation
  477. dwAddr = inet_addr(cName);
  478. if(dwAddr == INADDR_NONE)
  479. return NULL;
  480. // initialize sockets.
  481. wVersionRequested = MAKEWORD( 2, 2 );
  482. error = WSAStartup( wVersionRequested, &wsaData );
  483. if(error != 0)
  484. {
  485. ELF_LOG1(TRACE,
  486. "GetNameFromIPAddress: failed to initialize sockets, error = 0x%x\n", error);
  487. return NULL;
  488. }
  489. pEnt = gethostbyaddr((char FAR *)&dwAddr, 4, PF_INET);
  490. if(pEnt == NULL || pEnt->h_name == NULL)
  491. {
  492. ELF_LOG1(TRACE,
  493. "GetNameFromIPAddress: failed gethostbyaddr, error = 0x%x\n",
  494. WSAGetLastError());
  495. WSACleanup();
  496. return NULL;
  497. }
  498. dwSize = strlen(pEnt->h_name) + 1 ;
  499. pComputerName = ElfpAllocateBuffer(2*dwSize);
  500. if(pComputerName == NULL)
  501. {
  502. ELF_LOG0(ERROR,
  503. "GetNameFromIPAddress: failed trying to allocate memory\n");
  504. WSACleanup();
  505. return NULL;
  506. }
  507. pComputerName[0] = 0;
  508. mbstowcs(pComputerName, pEnt->h_name, dwSize);
  509. WSACleanup();
  510. return pComputerName;
  511. }
  512. BOOL
  513. IsLocal(
  514. VOID
  515. )
  516. /*++
  517. Routine Description:
  518. Determines if the caller is local.
  519. Arguments:
  520. NONE
  521. Return Value:
  522. TRUE if definately local.
  523. --*/
  524. {
  525. UINT LocalFlag;
  526. RPC_STATUS RpcStatus;
  527. RpcStatus = I_RpcBindingIsClientLocal(0, &LocalFlag);
  528. if( RpcStatus != RPC_S_OK )
  529. {
  530. ELF_LOG1(ERROR,
  531. "IsLocal: I_RpcBindingIsClientLocal failed %d\n",
  532. RpcStatus);
  533. return FALSE;
  534. }
  535. if(LocalFlag == 0)
  536. return FALSE;
  537. else
  538. return TRUE;
  539. }
  540. LPWSTR
  541. ElfpGetComputerName(
  542. VOID
  543. )
  544. /*++
  545. Routine Description:
  546. This routine gets the LPWSTR name of the computer.
  547. Arguments:
  548. NONE
  549. Return Value:
  550. Returns a pointer to the computer name, or a NULL. Note that the caller
  551. is expected to free this via
  552. --*/
  553. {
  554. RPC_STATUS RpcStatus;
  555. handle_t hServerBinding = NULL;
  556. LPWSTR pszBinding = NULL;
  557. LPWSTR pszComputerNameFromBinding = NULL;
  558. LPWSTR pszComputerName = NULL;
  559. DWORD dwSize;
  560. BOOL bOK;
  561. // Check if the connection is local. If it is, then just
  562. // call GetComputerName
  563. if(IsLocal())
  564. {
  565. dwSize = MAX_COMPUTERNAME_LENGTH + 1 ;
  566. pszComputerName = ElfpAllocateBuffer(2*dwSize);
  567. if(pszComputerName == NULL)
  568. {
  569. ELF_LOG0(ERROR,
  570. "ElfpGetComputerName: failed trying to allocate memory\n");
  571. return NULL;
  572. }
  573. bOK = GetComputerNameW(pszComputerName, &dwSize);
  574. if(bOK == FALSE)
  575. {
  576. ElfpFreeBuffer(pszComputerName);
  577. ELF_LOG1(ERROR,
  578. "ElfpGetComputerName: failed calling GetComputerNameW, last error 0x%x\n",
  579. GetLastError());
  580. return NULL;
  581. }
  582. else
  583. return pszComputerName;
  584. }
  585. RpcStatus = RpcBindingServerFromClient( NULL, &hServerBinding );
  586. if( RpcStatus != RPC_S_OK )
  587. {
  588. ELF_LOG1(ERROR,
  589. "ElfpGetComputerName: RpcBindingServerFromClient failed %d\n",
  590. RpcStatus);
  591. return NULL;
  592. }
  593. // This gets us something like "ncacn_np:xxx.xxx.xxx.xxx" or
  594. // "ncacn_np:localMachine"
  595. RpcStatus = RpcBindingToStringBinding( hServerBinding, &pszBinding );
  596. if( RpcStatus != RPC_S_OK )
  597. {
  598. ELF_LOG1(ERROR,
  599. "ElfpGetComputerName: RpcBindingToStringBinding failed %d\n",
  600. RpcStatus);
  601. goto CleanExitGetCompName;
  602. }
  603. // Acquire just the network address. That will be something like
  604. // "xxx.xxx.xxx.xxx" or "mymachine"
  605. RpcStatus = RpcStringBindingParse( pszBinding,
  606. NULL,
  607. NULL,
  608. &pszComputerNameFromBinding,
  609. NULL,
  610. NULL );
  611. if( RpcStatus != RPC_S_OK || pszComputerNameFromBinding == NULL)
  612. {
  613. ELF_LOG1(ERROR,
  614. "ElfpGetComputerName: RpcStringBindingParse failed %d\n",
  615. RpcStatus);
  616. goto CleanExitGetCompName;
  617. }
  618. // sometimes the name is an ip address. If it is, then the following determines
  619. // that and returns the right string.
  620. pszComputerName = GetNameFromIPAddress(pszComputerNameFromBinding);
  621. if(pszComputerName == NULL)
  622. {
  623. dwSize = wcslen(pszComputerNameFromBinding) + 1;
  624. pszComputerName = ElfpAllocateBuffer(2*dwSize);
  625. if(pszComputerName == NULL)
  626. {
  627. ELF_LOG0(ERROR,
  628. "ElfpGetComputerName: failed trying to allocate memory\n");
  629. }
  630. else
  631. StringCchCopyW(pszComputerName, dwSize, pszComputerNameFromBinding);
  632. }
  633. CleanExitGetCompName:
  634. if(hServerBinding)
  635. RpcStatus = RpcBindingFree(&hServerBinding);
  636. if(pszBinding)
  637. RpcStatus = RpcStringFree(&pszBinding);
  638. if(pszComputerNameFromBinding)
  639. RpcStatus = RpcStringFree(&pszComputerNameFromBinding);
  640. return pszComputerName;
  641. }
  642. NTSTATUS
  643. ElfpGetClientSidString(
  644. LPWSTR * ppwsClientSidString,
  645. PTOKEN_USER * ppToken
  646. )
  647. /*++
  648. Routine Description:
  649. This routine gets the LPWSTR version of the RPC callers SID. Note that
  650. upon success, the calling routine should free this via ElfpFreeBuffer
  651. Arguments:
  652. ppwsClientSidString - upon succes, this will have a fail safe version
  653. of the client info which the caller must free
  654. Return Value:
  655. NTSTATUS value
  656. --*/
  657. {
  658. NTSTATUS Status, RevertStatus;
  659. BOOL bImpersonating = FALSE;
  660. HANDLE hToken;
  661. BOOL bGotToken = FALSE;
  662. DWORD RequiredLength;
  663. UNICODE_STRING UnicodeStringSid;
  664. BOOL bNeedToFreeUnicodeStr = FALSE;
  665. DWORD dwRetStringSize = 0;
  666. *ppwsClientSidString = NULL;
  667. *ppToken = NULL;
  668. // impersonate the client
  669. Status = I_RpcMapWin32Status( RpcImpersonateClient( NULL ) );
  670. if ( !NT_SUCCESS( Status ) )
  671. {
  672. ELF_LOG1(ERROR, "ElfpGetClientSidString: RpcImpersonateClient failed %#x\n", Status);
  673. goto ExitElfpGetClientSidString;
  674. }
  675. bImpersonating = TRUE;
  676. // Get the thread token
  677. Status = NtOpenThreadToken (GetCurrentThread(), TOKEN_QUERY, TRUE, &hToken);
  678. if ( !NT_SUCCESS( Status ) )
  679. {
  680. ELF_LOG1(ERROR, "ElfpGetClientSidString: NtOpenThreadToken failed %#x\n", Status);
  681. goto ExitElfpGetClientSidString;
  682. }
  683. bGotToken = TRUE;
  684. // first find out how much memory is needed
  685. Status = NtQueryInformationToken (hToken, TokenUser, NULL, 0, &RequiredLength);
  686. if (Status != STATUS_BUFFER_TOO_SMALL)
  687. {
  688. ELF_LOG1(ERROR, "ElfpGetClientSidString: 1stNtQueryInformationToken isnt too small %#x\n", Status);
  689. if(NT_SUCCESS( Status ))
  690. {
  691. // weird case, should never happen, but we dont want caller to think this worked by
  692. // accident
  693. Status = STATUS_UNSUCCESSFUL;
  694. }
  695. goto ExitElfpGetClientSidString;
  696. }
  697. // get the memory and actually read the data
  698. *ppToken = ElfpAllocateBuffer(RequiredLength);
  699. if (*ppToken == NULL)
  700. {
  701. ELF_LOG0(ERROR,
  702. "ElfpGetClientSidString: Unable to allocate memory for token\n");
  703. Status = STATUS_NO_MEMORY;
  704. goto ExitElfpGetClientSidString;
  705. }
  706. Status = NtQueryInformationToken (hToken,
  707. TokenUser,
  708. *ppToken,
  709. RequiredLength,
  710. &RequiredLength);
  711. if ( !NT_SUCCESS( Status ) )
  712. {
  713. ELF_LOG1(ERROR, "ElfpGetClientSidString: 2nNtQueryInformationToken failed %#x\n", Status);
  714. goto ExitElfpGetClientSidString;
  715. }
  716. // Convert using the Rtl functions
  717. Status = RtlConvertSidToUnicodeString( &UnicodeStringSid, (*ppToken)->User.Sid, TRUE );
  718. if ( !NT_SUCCESS( Status ) ) {
  719. ELF_LOG1(ERROR, "ElfpGetClientSidString: RtlConvertSidToUnicodeString failed %#x\n", Status);
  720. goto ExitElfpGetClientSidString;
  721. }
  722. bNeedToFreeUnicodeStr = TRUE;
  723. // allocate and convert
  724. dwRetStringSize = UnicodeStringSid.Length + sizeof(WCHAR);
  725. *ppwsClientSidString = ElfpAllocateBuffer(dwRetStringSize);
  726. if (*ppwsClientSidString == NULL)
  727. {
  728. ELF_LOG0(ERROR,
  729. "ElfpGetClientSidString: Unable to allocate memory for returned string\n");
  730. Status = STATUS_NO_MEMORY;
  731. goto ExitElfpGetClientSidString;
  732. }
  733. StringCbCopyW( *ppwsClientSidString, dwRetStringSize, UnicodeStringSid.Buffer);
  734. Status = STATUS_SUCCESS;
  735. ExitElfpGetClientSidString:
  736. if(bImpersonating)
  737. {
  738. RevertStatus = I_RpcMapWin32Status( RpcRevertToSelf() );
  739. if ( !NT_SUCCESS( RevertStatus ) )
  740. {
  741. ELF_LOG1(ERROR, "ElfpGetClientSidString: RpcRevertToSelf failed %#x\n", Status);
  742. if(NT_SUCCESS( Status ))
  743. Status = RevertStatus;
  744. }
  745. }
  746. if(!NT_SUCCESS( Status ) && *ppwsClientSidString)
  747. {
  748. ElfpFreeBuffer(*ppwsClientSidString);
  749. *ppwsClientSidString = NULL;
  750. }
  751. if(!NT_SUCCESS( Status ) && *ppToken)
  752. {
  753. ElfpFreeBuffer(*ppToken);
  754. *ppToken = NULL;
  755. }
  756. if(bGotToken)
  757. NtClose(hToken);
  758. if(bNeedToFreeUnicodeStr)
  759. RtlFreeUnicodeString( &UnicodeStringSid );
  760. return Status;
  761. }