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.

4118 lines
116 KiB

  1. //+---------------------------------------------------------------------------
  2. //
  3. // Microsoft Windows
  4. // Copyright (C) Microsoft Corporation, 1992 - 1993.
  5. //
  6. // File: logon32.c
  7. //
  8. // Contents:
  9. //
  10. // Classes:
  11. //
  12. // Functions:
  13. //
  14. // History: 9-30-94 RichardW Created
  15. //
  16. //----------------------------------------------------------------------------
  17. #include "advapi.h"
  18. #include <crypt.h>
  19. #include <mpr.h>
  20. #include <ntlsa.h>
  21. #include <ntmsv1_0.h>
  22. #include <wchar.h>
  23. #include <stdlib.h>
  24. #include <lmcons.h>
  25. #define SECURITY_WIN32
  26. #include <security.h>
  27. #include <windows.h>
  28. #include <winbase.h>
  29. #include <winbasep.h>
  30. #include <execsrv.h>
  31. #include <winsta.h>
  32. //
  33. // We dynamically load mpr.dll (no big surprise there), in order to call
  34. // WNetLogonNotify, as defined in private\inc\mpr.h. This prototype matches
  35. // it -- consult the header file for all the parameters.
  36. //
  37. typedef (* LOGONNOTIFYFN)(LPCWSTR, PLUID, LPCWSTR, LPVOID,
  38. LPCWSTR, LPVOID, LPWSTR, LPVOID, LPWSTR *);
  39. //
  40. // The QuotaLimits are global, because the defaults
  41. // are always used for accounts, based on server/wksta, and no one ever
  42. // calls lsasetaccountquota
  43. //
  44. HANDLE Logon32LsaHandle = NULL;
  45. ULONG Logon32MsvHandle = 0xFFFFFFFF;
  46. ULONG Logon32NegoHandle = 0xFFFFFFFF;
  47. WCHAR Logon32DomainName[DNLEN+1] = L"";
  48. QUOTA_LIMITS Logon32QuotaLimits;
  49. HINSTANCE Logon32MprHandle = NULL;
  50. LOGONNOTIFYFN Logon32LogonNotify = NULL;
  51. RTL_CRITICAL_SECTION Logon32Lock;
  52. #define LockLogon() RtlEnterCriticalSection( &Logon32Lock )
  53. #define UnlockLogon() RtlLeaveCriticalSection( &Logon32Lock )
  54. SID_IDENTIFIER_AUTHORITY L32SystemSidAuthority = SECURITY_NT_AUTHORITY;
  55. SID_IDENTIFIER_AUTHORITY L32LocalSidAuthority = SECURITY_LOCAL_SID_AUTHORITY;
  56. #define COMMON_CREATE_SUSPENDED 0x00000001 // Suspended, do not Resume()
  57. #define COMMON_CREATE_PROCESSSD 0x00000002 // Whack the process SD
  58. #define COMMON_CREATE_THREADSD 0x00000004 // Whack the thread SD
  59. BOOL
  60. WINAPI
  61. LogonUserCommonA(
  62. LPCSTR lpszUsername,
  63. LPCSTR lpszDomain,
  64. LPCSTR lpszPassword,
  65. DWORD dwLogonType,
  66. DWORD dwLogonProvider,
  67. BOOL fExVersion,
  68. HANDLE * phToken,
  69. PSID * ppLogonSid,
  70. PVOID * ppProfileBuffer,
  71. DWORD * pdwProfileLength,
  72. PQUOTA_LIMITS pQuotaLimits
  73. );
  74. BOOL
  75. WINAPI
  76. LogonUserCommonW(
  77. PCWSTR lpszUsername,
  78. PCWSTR lpszDomain,
  79. PCWSTR lpszPassword,
  80. DWORD dwLogonType,
  81. DWORD dwLogonProvider,
  82. BOOL fExVersion,
  83. HANDLE * phToken,
  84. PSID * ppLogonSid,
  85. PVOID * ppProfileBuffer,
  86. DWORD * pdwProfileLength,
  87. PQUOTA_LIMITS pQuotaLimits
  88. );
  89. //+---------------------------------------------------------------------------
  90. //
  91. // Function: Logon32Initialize
  92. //
  93. // Synopsis: Initializes the critical section
  94. //
  95. // Arguments: [hMod] --
  96. // [Reason] --
  97. // [Context] --
  98. //
  99. //----------------------------------------------------------------------------
  100. BOOL
  101. Logon32Initialize(
  102. IN PVOID hMod,
  103. IN ULONG Reason,
  104. IN PCONTEXT Context)
  105. {
  106. NTSTATUS Status;
  107. if (Reason == DLL_PROCESS_ATTACH)
  108. {
  109. Status = RtlInitializeCriticalSection( &Logon32Lock );
  110. return( Status == STATUS_SUCCESS );
  111. }
  112. return( TRUE );
  113. }
  114. /***************************************************************************\
  115. * FindLogonSid
  116. *
  117. * Finds logon sid for a new logon from the access token.
  118. *
  119. \***************************************************************************/
  120. PSID
  121. L32FindLogonSid(
  122. IN HANDLE hToken
  123. )
  124. {
  125. PTOKEN_GROUPS pGroups = NULL;
  126. DWORD cbGroups;
  127. PVOID FastBuffer[ 512 / sizeof(PVOID) ];
  128. PTOKEN_GROUPS pSlowBuffer = NULL;
  129. UINT i;
  130. PSID Sid = NULL;
  131. pGroups = (PTOKEN_GROUPS)FastBuffer;
  132. cbGroups = sizeof(FastBuffer);
  133. if(!GetTokenInformation(
  134. hToken,
  135. TokenGroups,
  136. pGroups,
  137. cbGroups,
  138. &cbGroups
  139. ))
  140. {
  141. if( GetLastError() != ERROR_INSUFFICIENT_BUFFER ) {
  142. return NULL;
  143. }
  144. pSlowBuffer = (PTOKEN_GROUPS)LocalAlloc(LMEM_FIXED, cbGroups);
  145. if( pSlowBuffer == NULL ) {
  146. return NULL;
  147. }
  148. pGroups = pSlowBuffer;
  149. if(!GetTokenInformation(
  150. hToken,
  151. TokenGroups,
  152. pGroups,
  153. cbGroups,
  154. &cbGroups
  155. )) {
  156. goto Cleanup;
  157. }
  158. }
  159. //
  160. // Get the logon Sid by looping through the Sids in the token
  161. //
  162. for(i = 0 ; i < pGroups->GroupCount ; i++) {
  163. if(pGroups->Groups[i].Attributes & SE_GROUP_LOGON_ID) {
  164. DWORD dwSidLength;
  165. //
  166. // insure we are dealing with a valid Sid
  167. //
  168. if(!IsValidSid(pGroups->Groups[i].Sid)) {
  169. goto Cleanup;
  170. }
  171. //
  172. // get required allocation size to copy the Sid
  173. //
  174. dwSidLength = GetLengthSid(pGroups->Groups[i].Sid);
  175. Sid = (PSID)LocalAlloc( LMEM_FIXED, dwSidLength );
  176. if( Sid == NULL ) {
  177. goto Cleanup;
  178. }
  179. CopySid(dwSidLength, Sid, pGroups->Groups[i].Sid);
  180. break;
  181. }
  182. }
  183. Cleanup:
  184. if( pSlowBuffer )
  185. {
  186. LocalFree( pSlowBuffer );
  187. }
  188. return Sid;
  189. }
  190. /*******************************************************************
  191. NAME: GetDefaultDomainName
  192. SYNOPSIS: Fills in the given array with the name of the default
  193. domain to use for logon validation.
  194. ENTRY: pszDomainName - Pointer to a buffer that will receive
  195. the default domain name.
  196. cchDomainName - The size (in charactesr) of the domain
  197. name buffer.
  198. RETURNS: TRUE if successful, FALSE if not.
  199. HISTORY:
  200. KeithMo 05-Dec-1994 Created.
  201. RichardW 10-Jan-95 Liberated from sockets and stuck in base
  202. ********************************************************************/
  203. BOOL
  204. L32GetDefaultDomainName(
  205. PUNICODE_STRING pDomainName
  206. )
  207. {
  208. OBJECT_ATTRIBUTES ObjectAttributes;
  209. NTSTATUS NtStatus;
  210. INT Result;
  211. DWORD err = 0;
  212. LSA_HANDLE LsaPolicyHandle = NULL;
  213. PPOLICY_ACCOUNT_DOMAIN_INFO DomainInfo = NULL;
  214. PUNICODE_STRING pDomain;
  215. if (Logon32DomainName[0] != L'\0')
  216. {
  217. RtlInitUnicodeString(pDomainName, Logon32DomainName);
  218. return(TRUE);
  219. }
  220. //
  221. // Open a handle to the local machine's LSA policy object.
  222. //
  223. InitializeObjectAttributes( &ObjectAttributes, // object attributes
  224. NULL, // name
  225. 0L, // attributes
  226. NULL, // root directory
  227. NULL ); // security descriptor
  228. NtStatus = LsaOpenPolicy( NULL, // system name
  229. &ObjectAttributes, // object attributes
  230. POLICY_EXECUTE, // access mask
  231. &LsaPolicyHandle ); // policy handle
  232. if( !NT_SUCCESS( NtStatus ) )
  233. {
  234. BaseSetLastNTError(NtStatus);
  235. return(FALSE);
  236. }
  237. //
  238. // Query the domain information from the policy object.
  239. //
  240. NtStatus = LsaQueryInformationPolicy( LsaPolicyHandle,
  241. PolicyAccountDomainInformation,
  242. (PVOID *) &DomainInfo );
  243. if (!NT_SUCCESS(NtStatus))
  244. {
  245. BaseSetLastNTError(NtStatus);
  246. LsaClose(LsaPolicyHandle);
  247. return(FALSE);
  248. }
  249. (void) LsaClose(LsaPolicyHandle);
  250. //
  251. // Copy the domain name into our cache, and
  252. //
  253. CopyMemory( Logon32DomainName,
  254. DomainInfo->DomainName.Buffer,
  255. DomainInfo->DomainName.Length );
  256. //
  257. // Null terminate it appropriately
  258. //
  259. Logon32DomainName[DomainInfo->DomainName.Length / sizeof(WCHAR)] = L'\0';
  260. //
  261. // Clean up
  262. //
  263. LsaFreeMemory( (PVOID)DomainInfo );
  264. //
  265. // And init the string
  266. //
  267. RtlInitUnicodeString(pDomainName, Logon32DomainName);
  268. return TRUE;
  269. } // GetDefaultDomainName
  270. //+---------------------------------------------------------------------------
  271. //
  272. // Function: L32pInitLsa
  273. //
  274. // Synopsis: Initialize connection with LSA
  275. //
  276. // Arguments: (none)
  277. //
  278. // History: 4-21-95 RichardW Created
  279. //
  280. // Notes:
  281. //
  282. //----------------------------------------------------------------------------
  283. BOOL
  284. L32pInitLsa(void)
  285. {
  286. STRING PackageName;
  287. ULONG MsvHandle;
  288. ULONG NegoHandle;
  289. NTSTATUS Status;
  290. //
  291. // Hookup to the LSA and locate our authentication package.
  292. //
  293. Status = LsaConnectUntrusted(
  294. &Logon32LsaHandle
  295. );
  296. if (!NT_SUCCESS(Status)) {
  297. Logon32LsaHandle = NULL;
  298. goto Cleanup;
  299. }
  300. //
  301. // Connect with the MSV1_0 authentication package
  302. //
  303. RtlInitString(&PackageName, "MICROSOFT_AUTHENTICATION_PACKAGE_V1_0");
  304. Status = LsaLookupAuthenticationPackage (
  305. Logon32LsaHandle,
  306. &PackageName,
  307. &MsvHandle
  308. );
  309. if (!NT_SUCCESS(Status)) {
  310. goto Cleanup;
  311. }
  312. //
  313. // Connect with the Negotiate authentication package
  314. //
  315. RtlInitString(&PackageName, NEGOSSP_NAME_A);
  316. Status = LsaLookupAuthenticationPackage (
  317. Logon32LsaHandle,
  318. &PackageName,
  319. &NegoHandle
  320. );
  321. if (!NT_SUCCESS(Status)) {
  322. goto Cleanup;
  323. }
  324. //
  325. // Wait until successful to update the 2 globals.
  326. //
  327. Logon32NegoHandle = NegoHandle;
  328. Logon32MsvHandle = MsvHandle;
  329. Cleanup:
  330. if( !NT_SUCCESS(Status) ) {
  331. if( Logon32LsaHandle ) {
  332. (VOID) LsaDeregisterLogonProcess( Logon32LsaHandle );
  333. Logon32LsaHandle = NULL;
  334. }
  335. BaseSetLastNTError( Status );
  336. return FALSE;
  337. }
  338. return TRUE;
  339. }
  340. //+---------------------------------------------------------------------------
  341. //
  342. // Function: L32pNotifyMpr
  343. //
  344. // Synopsis: Loads the MPR DLL and notifies the network providers (like
  345. // csnw) so they know about this logon session and the credentials
  346. //
  347. // Arguments: [NewLogon] -- New logon information
  348. // [LogonId] -- Logon ID
  349. //
  350. // History: 4-24-95 RichardW Created
  351. //
  352. // Notes:
  353. //
  354. //----------------------------------------------------------------------------
  355. BOOL
  356. L32pNotifyMpr(
  357. PMSV1_0_INTERACTIVE_LOGON NewLogon,
  358. PLUID LogonId
  359. )
  360. {
  361. MSV1_0_INTERACTIVE_LOGON OldLogon;
  362. LPWSTR LogonScripts;
  363. DWORD status;
  364. LUID LocalServiceLuid = LOCALSERVICE_LUID;
  365. LUID NetworkServiceLuid = NETWORKSERVICE_LUID;
  366. if (RtlEqualLuid(LogonId, &LocalServiceLuid)
  367. ||
  368. RtlEqualLuid(LogonId, &NetworkServiceLuid))
  369. {
  370. //
  371. // Don't notify providers for LocalService/NetworkService logons
  372. //
  373. return( TRUE );
  374. }
  375. if ( Logon32MprHandle == NULL )
  376. {
  377. LockLogon();
  378. if ( Logon32MprHandle == NULL)
  379. {
  380. Logon32MprHandle = LoadLibrary("mpr.dll");
  381. if (Logon32MprHandle != NULL) {
  382. Logon32LogonNotify = (LOGONNOTIFYFN) GetProcAddress(
  383. Logon32MprHandle,
  384. "WNetLogonNotify");
  385. }
  386. }
  387. UnlockLogon();
  388. }
  389. if ( Logon32LogonNotify != NULL )
  390. {
  391. CopyMemory(&OldLogon, NewLogon, sizeof(OldLogon));
  392. status = Logon32LogonNotify(
  393. L"Windows NT Network Provider",
  394. LogonId,
  395. L"MSV1_0:Interactive",
  396. (LPVOID)NewLogon,
  397. L"MSV1_0:Interactive",
  398. (LPVOID)&OldLogon,
  399. L"SvcCtl", // StationName
  400. NULL, // StationHandle
  401. &LogonScripts); // LogonScripts
  402. if (status == NO_ERROR) {
  403. if (LogonScripts != NULL ) {
  404. (void) LocalFree(LogonScripts);
  405. }
  406. }
  407. return( TRUE );
  408. }
  409. return( FALSE );
  410. }
  411. //+---------------------------------------------------------------------------
  412. //
  413. // Function: L32pLogonUser
  414. //
  415. // Synopsis: Wraps up the call to LsaLogonUser
  416. //
  417. // Arguments: [LsaHandle] --
  418. // [AuthenticationPackage] --
  419. // [LogonType] --
  420. // [UserName] --
  421. // [Domain] --
  422. // [Password] --
  423. // [LogonId] --
  424. // [LogonToken] --
  425. // [Quotas] --
  426. // [pProfileBuffer] --
  427. // [pProfileBufferLength] --
  428. // [pSubStatus] --
  429. //
  430. // History: 4-24-95 RichardW Created
  431. //
  432. // Notes:
  433. //
  434. //----------------------------------------------------------------------------
  435. NTSTATUS
  436. L32pLogonUser(
  437. IN HANDLE LsaHandle,
  438. IN ULONG AuthenticationPackage,
  439. IN SECURITY_LOGON_TYPE LogonType,
  440. IN PUNICODE_STRING UserName,
  441. IN PUNICODE_STRING Domain,
  442. IN PUNICODE_STRING Password,
  443. OUT PLUID LogonId,
  444. OUT PHANDLE LogonToken,
  445. OUT PQUOTA_LIMITS Quotas,
  446. OUT PVOID *pProfileBuffer,
  447. OUT PULONG pProfileBufferLength,
  448. OUT PNTSTATUS pSubStatus
  449. )
  450. {
  451. NTSTATUS Status;
  452. STRING OriginName;
  453. TOKEN_SOURCE SourceContext;
  454. PMSV1_0_INTERACTIVE_LOGON MsvAuthInfo;
  455. PMSV1_0_LM20_LOGON MsvNetAuthInfo;
  456. PVOID AuthInfoBuf;
  457. ULONG AuthInfoSize;
  458. WCHAR ComputerName[ MAX_COMPUTERNAME_LENGTH + 1 ];
  459. DWORD ComputerNameLength;
  460. //
  461. // Initialize source context structure
  462. //
  463. strncpy(SourceContext.SourceName, "Advapi ", sizeof(SourceContext.SourceName)); // LATER from res file
  464. Status = NtAllocateLocallyUniqueId(&SourceContext.SourceIdentifier);
  465. if (!NT_SUCCESS(Status)) {
  466. return(Status);
  467. }
  468. //
  469. // Set logon origin
  470. //
  471. RtlInitString(&OriginName, "LogonUser API");
  472. //
  473. // For network logons, do the magic.
  474. //
  475. if ( ( LogonType == Network ) )
  476. {
  477. ComputerNameLength = MAX_COMPUTERNAME_LENGTH + 1;
  478. if (!GetComputerNameW( ComputerName, &ComputerNameLength ) )
  479. {
  480. return(STATUS_INVALID_PARAMETER);
  481. }
  482. AuthInfoSize = sizeof( MSV1_0_LM20_LOGON ) +
  483. UserName->Length +
  484. Domain->Length +
  485. sizeof(WCHAR) * (ComputerNameLength + 1) +
  486. Password->Length + // NT password
  487. (LM20_PWLEN+1) ; // LM passsword (worst case)
  488. MsvNetAuthInfo = AuthInfoBuf = RtlAllocateHeap( RtlProcessHeap(),
  489. HEAP_ZERO_MEMORY,
  490. AuthInfoSize );
  491. if ( !MsvNetAuthInfo )
  492. {
  493. return( STATUS_NO_MEMORY );
  494. }
  495. //
  496. // Start packing in the string
  497. //
  498. MsvNetAuthInfo->MessageType = MsV1_0NetworkLogon;
  499. //
  500. // Copy the user name into the authentication buffer
  501. //
  502. MsvNetAuthInfo->UserName.Length =
  503. UserName->Length;
  504. MsvNetAuthInfo->UserName.MaximumLength =
  505. MsvNetAuthInfo->UserName.Length;
  506. MsvNetAuthInfo->UserName.Buffer = (PWSTR)(MsvNetAuthInfo+1);
  507. RtlCopyMemory(
  508. MsvNetAuthInfo->UserName.Buffer,
  509. UserName->Buffer,
  510. UserName->Length
  511. );
  512. //
  513. // Copy the domain name into the authentication buffer
  514. //
  515. MsvNetAuthInfo->LogonDomainName.Length = Domain->Length;
  516. MsvNetAuthInfo->LogonDomainName.MaximumLength = Domain->Length ;
  517. MsvNetAuthInfo->LogonDomainName.Buffer = (PWSTR)
  518. ((PBYTE)(MsvNetAuthInfo->UserName.Buffer) +
  519. MsvNetAuthInfo->UserName.MaximumLength);
  520. RtlCopyMemory(
  521. MsvNetAuthInfo->LogonDomainName.Buffer,
  522. Domain->Buffer,
  523. Domain->Length);
  524. //
  525. // Copy the workstation name into the buffer
  526. //
  527. MsvNetAuthInfo->Workstation.Length = (USHORT)
  528. (sizeof(WCHAR) * ComputerNameLength);
  529. MsvNetAuthInfo->Workstation.MaximumLength =
  530. MsvNetAuthInfo->Workstation.Length + sizeof(WCHAR);
  531. MsvNetAuthInfo->Workstation.Buffer = (PWSTR)
  532. ((PBYTE) (MsvNetAuthInfo->LogonDomainName.Buffer) +
  533. MsvNetAuthInfo->LogonDomainName.MaximumLength );
  534. wcscpy( MsvNetAuthInfo->Workstation.Buffer, ComputerName );
  535. //
  536. // Set up space for Password (Unicode)
  537. //
  538. MsvNetAuthInfo->CaseSensitiveChallengeResponse.Buffer = (PUCHAR)
  539. ((PBYTE) (MsvNetAuthInfo->Workstation.Buffer) +
  540. MsvNetAuthInfo->Workstation.MaximumLength );
  541. MsvNetAuthInfo->CaseSensitiveChallengeResponse.Length =
  542. MsvNetAuthInfo->CaseSensitiveChallengeResponse.MaximumLength =
  543. Password->Length;
  544. RtlCopyMemory(
  545. MsvNetAuthInfo->CaseSensitiveChallengeResponse.Buffer,
  546. Password->Buffer,
  547. Password->Length);
  548. //
  549. // handle passing in the case-insensitive version.
  550. //
  551. if( (Password->Length/sizeof(WCHAR)) > LM20_PWLEN )
  552. {
  553. Status = STATUS_INVALID_PARAMETER;
  554. } else {
  555. MsvNetAuthInfo->CaseInsensitiveChallengeResponse.Buffer = (PUCHAR)
  556. ((PBYTE) (MsvNetAuthInfo->CaseSensitiveChallengeResponse.Buffer) +
  557. MsvNetAuthInfo->CaseSensitiveChallengeResponse.MaximumLength );
  558. MsvNetAuthInfo->CaseInsensitiveChallengeResponse.Length = LM20_PWLEN;
  559. MsvNetAuthInfo->CaseInsensitiveChallengeResponse.MaximumLength = LM20_PWLEN+1;
  560. Status = RtlUpcaseUnicodeStringToOemString(
  561. &MsvNetAuthInfo->CaseInsensitiveChallengeResponse,
  562. Password,
  563. FALSE
  564. );
  565. }
  566. if ( !NT_SUCCESS(Status) )
  567. {
  568. Status = STATUS_SUCCESS;
  569. //
  570. // If we're here, the NT (supplied) password is longer than the
  571. // limit allowed for LM passwords. NULL out the field, so that
  572. // MSV knows not to worry about it.
  573. //
  574. RtlZeroMemory( &MsvNetAuthInfo->CaseInsensitiveChallengeResponse,
  575. sizeof(MsvNetAuthInfo->CaseInsensitiveChallengeResponse) );
  576. }
  577. //
  578. // to be consistent with Negotiate/Kerberos for _WINNT50 cases,
  579. // allow machine accounts to be logged on.
  580. //
  581. MsvNetAuthInfo->ParameterControl = MSV1_0_CLEARTEXT_PASSWORD_ALLOWED |
  582. MSV1_0_CLEARTEXT_PASSWORD_SUPPLIED |
  583. MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT |
  584. MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT;
  585. }
  586. else
  587. {
  588. //
  589. // Build logon structure for non-network logons - service,
  590. // batch, interactive, unlock, new credentials, networkcleartext
  591. //
  592. AuthInfoSize = sizeof(MSV1_0_INTERACTIVE_LOGON) +
  593. UserName->Length +
  594. Domain->Length +
  595. Password->Length;
  596. MsvAuthInfo = AuthInfoBuf = RtlAllocateHeap(RtlProcessHeap(),
  597. HEAP_ZERO_MEMORY,
  598. AuthInfoSize);
  599. if (MsvAuthInfo == NULL) {
  600. return(STATUS_NO_MEMORY);
  601. }
  602. //
  603. // This authentication buffer will be used for a logon attempt
  604. //
  605. MsvAuthInfo->MessageType = MsV1_0InteractiveLogon;
  606. //
  607. // Copy the user name into the authentication buffer
  608. //
  609. MsvAuthInfo->UserName.Length = UserName->Length;
  610. MsvAuthInfo->UserName.MaximumLength =
  611. MsvAuthInfo->UserName.Length;
  612. MsvAuthInfo->UserName.Buffer = (PWSTR)(MsvAuthInfo+1);
  613. RtlCopyMemory(
  614. MsvAuthInfo->UserName.Buffer,
  615. UserName->Buffer,
  616. UserName->Length
  617. );
  618. //
  619. // Copy the domain name into the authentication buffer
  620. //
  621. MsvAuthInfo->LogonDomainName.Length = Domain->Length;
  622. MsvAuthInfo->LogonDomainName.MaximumLength =
  623. MsvAuthInfo->LogonDomainName.Length;
  624. MsvAuthInfo->LogonDomainName.Buffer = (PWSTR)
  625. ((PBYTE)(MsvAuthInfo->UserName.Buffer) +
  626. MsvAuthInfo->UserName.MaximumLength);
  627. RtlCopyMemory(
  628. MsvAuthInfo->LogonDomainName.Buffer,
  629. Domain->Buffer,
  630. Domain->Length
  631. );
  632. //
  633. // Copy the password into the authentication buffer
  634. // Hide it once we have copied it. Use the same seed value
  635. // that we used for the original password in pGlobals.
  636. //
  637. MsvAuthInfo->Password.Length = Password->Length;
  638. MsvAuthInfo->Password.MaximumLength =
  639. MsvAuthInfo->Password.Length;
  640. MsvAuthInfo->Password.Buffer = (PWSTR)
  641. ((PBYTE)(MsvAuthInfo->LogonDomainName.Buffer) +
  642. MsvAuthInfo->LogonDomainName.MaximumLength);
  643. RtlCopyMemory(
  644. MsvAuthInfo->Password.Buffer,
  645. Password->Buffer,
  646. Password->Length
  647. );
  648. }
  649. //
  650. // Now try to log this sucker on
  651. //
  652. Status = LsaLogonUser (
  653. LsaHandle,
  654. &OriginName,
  655. LogonType,
  656. AuthenticationPackage,
  657. AuthInfoBuf,
  658. AuthInfoSize,
  659. NULL,
  660. &SourceContext,
  661. pProfileBuffer,
  662. pProfileBufferLength,
  663. LogonId,
  664. LogonToken,
  665. Quotas,
  666. pSubStatus
  667. );
  668. //
  669. // Notify all the network providers, if this is a NON network logon. Also
  670. // skip service logons since the LSA will call WNetLogonNotify for those.
  671. //
  672. if ( NT_SUCCESS( Status ) &&
  673. (LogonType != Network) &&
  674. (LogonType != Service) )
  675. {
  676. L32pNotifyMpr(AuthInfoBuf, LogonId);
  677. }
  678. //
  679. // Discard authentication buffer
  680. //
  681. RtlZeroMemory( AuthInfoBuf, AuthInfoSize );
  682. RtlFreeHeap(RtlProcessHeap(), 0, AuthInfoBuf);
  683. return(Status);
  684. }
  685. //+---------------------------------------------------------------------------
  686. //
  687. // Function: LogonUserCommonA
  688. //
  689. // Synopsis: ANSI wrapper for LogonUserCommonW. See description below
  690. //
  691. // Arguments: [lpszUsername] --
  692. // [lpszDomain] --
  693. // [lpszPassword] --
  694. // [dwLogonType] --
  695. // [dwLogonProvider] --
  696. // [fExVersion] --
  697. // [phToken] --
  698. // [ppLogonSid] --
  699. // [ppProfileBuffer] --
  700. // [pdwProfileLength] --
  701. // [pQuotaLimits] --
  702. //
  703. // History: 2-15-2000 JSchwart Created from RichardW's LogonUserA
  704. //
  705. // Notes:
  706. //
  707. //----------------------------------------------------------------------------
  708. BOOL
  709. WINAPI
  710. LogonUserCommonA(
  711. LPCSTR lpszUsername,
  712. LPCSTR lpszDomain,
  713. LPCSTR lpszPassword,
  714. DWORD dwLogonType,
  715. DWORD dwLogonProvider,
  716. BOOL fExVersion,
  717. HANDLE * phToken,
  718. PSID * ppLogonSid,
  719. PVOID * ppProfileBuffer,
  720. DWORD * pdwProfileLength,
  721. PQUOTA_LIMITS pQuotaLimits
  722. )
  723. {
  724. UNICODE_STRING Username;
  725. UNICODE_STRING Domain;
  726. UNICODE_STRING Password;
  727. ANSI_STRING Temp ;
  728. NTSTATUS Status;
  729. BOOL bRet;
  730. Username.Buffer = NULL;
  731. Domain.Buffer = NULL;
  732. Password.Buffer = NULL;
  733. RtlInitAnsiString( &Temp, lpszUsername );
  734. Status = RtlAnsiStringToUnicodeString( &Username, &Temp, TRUE );
  735. if (!NT_SUCCESS( Status ) )
  736. {
  737. BaseSetLastNTError(Status);
  738. bRet = FALSE;
  739. goto Cleanup;
  740. }
  741. RtlInitAnsiString( &Temp, lpszDomain );
  742. Status = RtlAnsiStringToUnicodeString(&Domain, &Temp, TRUE );
  743. if (!NT_SUCCESS(Status))
  744. {
  745. BaseSetLastNTError(Status);
  746. bRet = FALSE;
  747. goto Cleanup;
  748. }
  749. RtlInitAnsiString( &Temp, lpszPassword );
  750. Status = RtlAnsiStringToUnicodeString( &Password, &Temp, TRUE );
  751. if (!NT_SUCCESS(Status))
  752. {
  753. BaseSetLastNTError(Status);
  754. bRet = FALSE;
  755. goto Cleanup;
  756. }
  757. bRet = LogonUserCommonW( Username.Buffer,
  758. Domain.Buffer,
  759. Password.Buffer,
  760. dwLogonType,
  761. dwLogonProvider,
  762. fExVersion,
  763. phToken,
  764. ppLogonSid,
  765. ppProfileBuffer,
  766. pdwProfileLength,
  767. pQuotaLimits );
  768. Cleanup:
  769. if (Username.Buffer)
  770. {
  771. RtlFreeUnicodeString(&Username);
  772. }
  773. if (Domain.Buffer)
  774. {
  775. RtlFreeUnicodeString(&Domain);
  776. }
  777. if (Password.Buffer)
  778. {
  779. RtlZeroMemory(Password.Buffer, Password.Length);
  780. RtlFreeUnicodeString(&Password);
  781. }
  782. return(bRet);
  783. }
  784. //+---------------------------------------------------------------------------
  785. //
  786. // Function: LogonUserA
  787. //
  788. // Synopsis: ANSI wrapper for LogonUserW. See description below
  789. //
  790. // Arguments: [lpszUsername] --
  791. // [lpszDomain] --
  792. // [lpszPassword] --
  793. // [dwLogonType] --
  794. // [dwLogonProvider] --
  795. // [phToken] --
  796. //
  797. // History: 4-25-95 RichardW Created
  798. //
  799. // Notes:
  800. //
  801. //----------------------------------------------------------------------------
  802. BOOL
  803. WINAPI
  804. LogonUserA(
  805. LPCSTR lpszUsername,
  806. LPCSTR lpszDomain,
  807. LPCSTR lpszPassword,
  808. DWORD dwLogonType,
  809. DWORD dwLogonProvider,
  810. HANDLE * phToken
  811. )
  812. {
  813. return LogonUserCommonA(lpszUsername,
  814. lpszDomain,
  815. lpszPassword,
  816. dwLogonType,
  817. dwLogonProvider,
  818. FALSE, // LogonUserA
  819. phToken,
  820. NULL, // ppLogonSid
  821. NULL, // ppProfileBuffer
  822. NULL, // pdwProfileLength
  823. NULL); // pQuotaLimits
  824. }
  825. //+---------------------------------------------------------------------------
  826. //
  827. // Function: LogonUserExA
  828. //
  829. // Synopsis: ANSI wrapper for LogonUserExW. See description below
  830. //
  831. // Arguments: [lpszUsername] --
  832. // [lpszDomain] --
  833. // [lpszPassword] --
  834. // [dwLogonType] --
  835. // [dwLogonProvider] --
  836. // [phToken] --
  837. // [ppLogonSid] --
  838. // [ppProfileBuffer] --
  839. // [pdwProfileLength] --
  840. // [pQuotaLimits] --
  841. //
  842. // History: 2-15-2000 JSchwart Created from RichardW's LogonUserW
  843. //
  844. // Notes:
  845. //
  846. //----------------------------------------------------------------------------
  847. BOOL
  848. WINAPI
  849. LogonUserExA(
  850. LPCSTR lpszUsername,
  851. LPCSTR lpszDomain,
  852. LPCSTR lpszPassword,
  853. DWORD dwLogonType,
  854. DWORD dwLogonProvider,
  855. HANDLE * phToken,
  856. PSID * ppLogonSid,
  857. PVOID * ppProfileBuffer,
  858. DWORD * pdwProfileLength,
  859. PQUOTA_LIMITS pQuotaLimits
  860. )
  861. {
  862. return LogonUserCommonA(lpszUsername,
  863. lpszDomain,
  864. lpszPassword,
  865. dwLogonType,
  866. dwLogonProvider,
  867. TRUE, // LogonUserExA
  868. phToken,
  869. ppLogonSid,
  870. ppProfileBuffer,
  871. pdwProfileLength,
  872. pQuotaLimits);
  873. }
  874. //+---------------------------------------------------------------------------
  875. //
  876. // Function: LogonUserCommonW
  877. //
  878. // Synopsis: Common code for LogonUserW and LogonUserExW. Logs a user on
  879. // via plaintext password, username and domain name via the LSA.
  880. //
  881. // Arguments: [lpszUsername] -- User name
  882. // [lpszDomain] -- Domain name
  883. // [lpszPassword] -- Password
  884. // [dwLogonType] -- Logon type
  885. // [dwLogonProvider] -- Provider
  886. // [fExVersion] -- LogonUserExW or LogonUserW
  887. // [phToken] -- Returned handle to primary token
  888. // [ppLogonSid] -- Returned logon sid
  889. // [ppProfileBuffer] -- Returned user profile buffer
  890. // [pdwProfileLength] -- Returned profile length
  891. //
  892. // History: 2-15-2000 JSchwart Created from RichardW's LogonUserW
  893. //
  894. // Notes: Requires SeTcbPrivilege, and will enable it if not already
  895. // present.
  896. //
  897. //----------------------------------------------------------------------------
  898. BOOL
  899. WINAPI
  900. LogonUserCommonW(
  901. PCWSTR lpszUsername,
  902. PCWSTR lpszDomain,
  903. PCWSTR lpszPassword,
  904. DWORD dwLogonType,
  905. DWORD dwLogonProvider,
  906. BOOL fExVersion,
  907. HANDLE * phToken,
  908. PSID * ppLogonSid,
  909. PVOID * ppProfileBuffer,
  910. DWORD * pdwProfileLength,
  911. PQUOTA_LIMITS pQuotaLimits
  912. )
  913. {
  914. NTSTATUS Status;
  915. ULONG PackageId;
  916. UNICODE_STRING Username;
  917. UNICODE_STRING Domain;
  918. UNICODE_STRING Password;
  919. HANDLE hTempToken;
  920. HANDLE * phTempToken;
  921. LUID LogonId;
  922. PVOID Profile;
  923. ULONG ProfileLength;
  924. NTSTATUS SubStatus = STATUS_SUCCESS;
  925. SECURITY_LOGON_TYPE LogonType;
  926. //
  927. // Validate the provider
  928. //
  929. if (dwLogonProvider == LOGON32_PROVIDER_DEFAULT)
  930. {
  931. dwLogonProvider = LOGON32_PROVIDER_WINNT50;
  932. //
  933. // if domain was not supplied, and username is not a UPN, use
  934. // _WINNT40 to be compatible.
  935. //
  936. if((lpszUsername != NULL) &&
  937. (lpszDomain == NULL || lpszDomain[ 0 ] == L'\0'))
  938. {
  939. if( wcschr( lpszUsername, L'@' ) == NULL )
  940. {
  941. dwLogonProvider = LOGON32_PROVIDER_WINNT40;
  942. }
  943. }
  944. }
  945. if (dwLogonProvider > LOGON32_PROVIDER_WINNT50)
  946. {
  947. BaseSetLastNTError(STATUS_INVALID_PARAMETER);
  948. return(FALSE);
  949. }
  950. switch (dwLogonType)
  951. {
  952. case LOGON32_LOGON_INTERACTIVE:
  953. LogonType = Interactive;
  954. break;
  955. case LOGON32_LOGON_BATCH:
  956. LogonType = Batch;
  957. break;
  958. case LOGON32_LOGON_SERVICE:
  959. LogonType = Service;
  960. break;
  961. case LOGON32_LOGON_NETWORK:
  962. LogonType = Network;
  963. break;
  964. case LOGON32_LOGON_UNLOCK:
  965. LogonType = Unlock ;
  966. break;
  967. case LOGON32_LOGON_NETWORK_CLEARTEXT:
  968. LogonType = NetworkCleartext ;
  969. break;
  970. case LOGON32_LOGON_NEW_CREDENTIALS:
  971. LogonType = NewCredentials;
  972. break;
  973. default:
  974. BaseSetLastNTError(STATUS_INVALID_PARAMETER);
  975. return(FALSE);
  976. break;
  977. }
  978. //
  979. // If the MSV handle is -1, grab the lock, and try again:
  980. //
  981. if (Logon32MsvHandle == 0xFFFFFFFF || Logon32NegoHandle == 0xFFFFFFFF)
  982. {
  983. LockLogon();
  984. //
  985. // If the MSV handle is still -1, init our connection to lsa. We
  986. // have the lock, so no other threads can't be trying this right now.
  987. //
  988. if (Logon32MsvHandle == 0xFFFFFFFF || Logon32NegoHandle == 0xFFFFFFFF)
  989. {
  990. if (!L32pInitLsa())
  991. {
  992. UnlockLogon();
  993. return( FALSE );
  994. }
  995. }
  996. UnlockLogon();
  997. }
  998. //
  999. // Validate the parameters. NULL or empty domain or NULL or empty
  1000. // user name is invalid.
  1001. //
  1002. RtlInitUnicodeString(&Username, lpszUsername);
  1003. if (Username.Length == 0)
  1004. {
  1005. BaseSetLastNTError(STATUS_INVALID_PARAMETER);
  1006. return(FALSE);
  1007. }
  1008. //
  1009. // Initialize/check parameters based on which API we're servicing.
  1010. //
  1011. if (!fExVersion)
  1012. {
  1013. //
  1014. // LogonUserW -- phToken is required. Initialize the token handle,
  1015. // if the pointer is invalid, then catch the exception now.
  1016. //
  1017. *phToken = NULL;
  1018. phTempToken = phToken;
  1019. }
  1020. else
  1021. {
  1022. //
  1023. // LogonUserExW -- phToken, ppLogonSid, ppProfileBuffer, and
  1024. // pdwProfileLength are optional. Initialize as appropriate.
  1025. //
  1026. if (ARGUMENT_PRESENT(phToken))
  1027. {
  1028. *phToken = NULL;
  1029. phTempToken = phToken;
  1030. }
  1031. else
  1032. {
  1033. //
  1034. // Dummy token handle to use in the LsaLogonUser call
  1035. //
  1036. phTempToken = &hTempToken;
  1037. }
  1038. if (ARGUMENT_PRESENT(ppLogonSid))
  1039. {
  1040. *ppLogonSid = NULL;
  1041. }
  1042. if (!!ppProfileBuffer ^ !!pdwProfileLength)
  1043. {
  1044. //
  1045. // Can't have one without the other...
  1046. //
  1047. BaseSetLastNTError(STATUS_INVALID_PARAMETER);
  1048. return(FALSE);
  1049. }
  1050. if (ARGUMENT_PRESENT(ppProfileBuffer))
  1051. {
  1052. *ppProfileBuffer = NULL;
  1053. *pdwProfileLength = 0;
  1054. }
  1055. if (ARGUMENT_PRESENT(pQuotaLimits))
  1056. {
  1057. RtlZeroMemory(pQuotaLimits, sizeof(QUOTA_LIMITS));
  1058. }
  1059. }
  1060. //
  1061. // Parse that domain. Note, if the special token . is passed in for
  1062. // domain, we will use the right value from the LSA, meaning AccountDomain.
  1063. // If the domain is null, the lsa will talk to the local domain, the
  1064. // primary domain, and then on from there...
  1065. //
  1066. if (lpszDomain && *lpszDomain)
  1067. {
  1068. if ((lpszDomain[0] == L'.') &&
  1069. (lpszDomain[1] == L'\0') )
  1070. {
  1071. if (!L32GetDefaultDomainName(&Domain))
  1072. {
  1073. return(FALSE);
  1074. }
  1075. }
  1076. else
  1077. {
  1078. RtlInitUnicodeString(&Domain, lpszDomain);
  1079. }
  1080. }
  1081. else
  1082. {
  1083. RtlInitUnicodeString(&Domain, lpszDomain);
  1084. }
  1085. //
  1086. // Finally, init the password
  1087. //
  1088. RtlInitUnicodeString(&Password, lpszPassword);
  1089. //
  1090. // Attempt the logon
  1091. //
  1092. Status = L32pLogonUser(
  1093. Logon32LsaHandle,
  1094. (dwLogonProvider == LOGON32_PROVIDER_WINNT50) ?
  1095. Logon32NegoHandle : Logon32MsvHandle,
  1096. LogonType,
  1097. &Username,
  1098. &Domain,
  1099. &Password,
  1100. &LogonId,
  1101. phTempToken,
  1102. pQuotaLimits ? pQuotaLimits : &Logon32QuotaLimits,
  1103. &Profile,
  1104. &ProfileLength,
  1105. &SubStatus);
  1106. //
  1107. // Set output parameters based on which API we're servicing
  1108. //
  1109. // TODO: review cleanup code if something fails mid-stream.
  1110. //
  1111. if (!fExVersion)
  1112. {
  1113. if (!NT_SUCCESS(Status))
  1114. {
  1115. if (Status == STATUS_ACCOUNT_RESTRICTION)
  1116. {
  1117. BaseSetLastNTError(SubStatus);
  1118. }
  1119. else
  1120. {
  1121. BaseSetLastNTError(Status);
  1122. }
  1123. return(FALSE);
  1124. }
  1125. if (Profile != NULL)
  1126. {
  1127. LsaFreeReturnBuffer(Profile);
  1128. }
  1129. }
  1130. else
  1131. {
  1132. //
  1133. // We may need the allocated buffers if all went well, so
  1134. // check the return status first.
  1135. //
  1136. if (!NT_SUCCESS(Status))
  1137. {
  1138. if (Status == STATUS_ACCOUNT_RESTRICTION)
  1139. {
  1140. BaseSetLastNTError(SubStatus);
  1141. }
  1142. else
  1143. {
  1144. BaseSetLastNTError(Status);
  1145. }
  1146. return(FALSE);
  1147. }
  1148. //
  1149. // The logon succeeded -- fill in the requested output parameters.
  1150. //
  1151. if (ARGUMENT_PRESENT(ppLogonSid))
  1152. {
  1153. *ppLogonSid = L32FindLogonSid( *phTempToken );
  1154. if (*ppLogonSid == NULL)
  1155. {
  1156. if (Profile != NULL)
  1157. {
  1158. LsaFreeReturnBuffer(Profile);
  1159. }
  1160. CloseHandle(*phTempToken);
  1161. *phTempToken = NULL;
  1162. BaseSetLastNTError(STATUS_NO_MEMORY);
  1163. return(FALSE);
  1164. }
  1165. }
  1166. if (ARGUMENT_PRESENT(ppProfileBuffer))
  1167. {
  1168. if (Profile != NULL)
  1169. {
  1170. ASSERT(ProfileLength != 0);
  1171. *ppProfileBuffer = Profile;
  1172. *pdwProfileLength = ProfileLength;
  1173. }
  1174. }
  1175. else
  1176. {
  1177. if (Profile != NULL)
  1178. {
  1179. LsaFreeReturnBuffer(Profile);
  1180. }
  1181. }
  1182. if (!ARGUMENT_PRESENT(phToken))
  1183. {
  1184. //
  1185. // Close the dummy token handle
  1186. //
  1187. CloseHandle(*phTempToken);
  1188. }
  1189. }
  1190. return(TRUE);
  1191. }
  1192. //+---------------------------------------------------------------------------
  1193. //
  1194. // Function: LogonUserW
  1195. //
  1196. // Synopsis: Logs a user on via plaintext password, username and domain
  1197. // name via the LSA.
  1198. //
  1199. // Arguments: [lpszUsername] -- User name
  1200. // [lpszDomain] -- Domain name
  1201. // [lpszPassword] -- Password
  1202. // [dwLogonType] -- Logon type
  1203. // [dwLogonProvider] -- Provider
  1204. // [phToken] -- Returned handle to primary token
  1205. //
  1206. // History: 4-25-95 RichardW Created
  1207. //
  1208. // Notes: Requires SeTcbPrivilege, and will enable it if not already
  1209. // present.
  1210. //
  1211. //----------------------------------------------------------------------------
  1212. BOOL
  1213. WINAPI
  1214. LogonUserW(
  1215. PCWSTR lpszUsername,
  1216. PCWSTR lpszDomain,
  1217. PCWSTR lpszPassword,
  1218. DWORD dwLogonType,
  1219. DWORD dwLogonProvider,
  1220. HANDLE * phToken
  1221. )
  1222. {
  1223. return LogonUserCommonW(lpszUsername,
  1224. lpszDomain,
  1225. lpszPassword,
  1226. dwLogonType,
  1227. dwLogonProvider,
  1228. FALSE, // LogonUserW
  1229. phToken,
  1230. NULL, // ppLogonSid
  1231. NULL, // ppProfileBuffer
  1232. NULL, // pdwProfileLength
  1233. NULL); // pQuotaLimits
  1234. }
  1235. //+---------------------------------------------------------------------------
  1236. //
  1237. // Function: LogonUserExW
  1238. //
  1239. // Synopsis: Logs a user on via plaintext password, username and domain
  1240. // name via the LSA.
  1241. //
  1242. // Arguments: [lpszUsername] -- User name
  1243. // [lpszDomain] -- Domain name
  1244. // [lpszPassword] -- Password
  1245. // [dwLogonType] -- Logon type
  1246. // [dwLogonProvider] -- Provider
  1247. // [phToken] -- Returned handle to primary token
  1248. // [ppLogonSid] -- Returned logon sid
  1249. // [ppProfileBuffer] -- Returned user profile buffer
  1250. // [pdwProfileLength] -- Returned profile length
  1251. // [pQuotaLimits] -- Returned quota limits
  1252. //
  1253. // History: 2-15-2000 JSchwart Created from RichardW's LogonUserW
  1254. //
  1255. // Notes: Requires SeTcbPrivilege, and will enable it if not already
  1256. // present.
  1257. //
  1258. //----------------------------------------------------------------------------
  1259. BOOL
  1260. WINAPI
  1261. LogonUserExW(
  1262. PCWSTR lpszUsername,
  1263. PCWSTR lpszDomain,
  1264. PCWSTR lpszPassword,
  1265. DWORD dwLogonType,
  1266. DWORD dwLogonProvider,
  1267. HANDLE * phToken,
  1268. PSID * ppLogonSid,
  1269. PVOID * ppProfileBuffer,
  1270. DWORD * pdwProfileLength,
  1271. PQUOTA_LIMITS pQuotaLimits
  1272. )
  1273. {
  1274. return LogonUserCommonW(lpszUsername,
  1275. lpszDomain,
  1276. lpszPassword,
  1277. dwLogonType,
  1278. dwLogonProvider,
  1279. TRUE, // LogonUserExW
  1280. phToken,
  1281. ppLogonSid,
  1282. ppProfileBuffer,
  1283. pdwProfileLength,
  1284. pQuotaLimits);
  1285. }
  1286. //+---------------------------------------------------------------------------
  1287. //
  1288. // Function: ImpersonateLoggedOnUser
  1289. //
  1290. // Synopsis: Duplicates the token passed in if it is primary, and assigns
  1291. // it to the thread that called.
  1292. //
  1293. // Arguments: [hToken] --
  1294. //
  1295. // History: 1-10-95 RichardW Created
  1296. //
  1297. // Notes:
  1298. //
  1299. //----------------------------------------------------------------------------
  1300. BOOL
  1301. WINAPI
  1302. ImpersonateLoggedOnUser(
  1303. HANDLE hToken
  1304. )
  1305. {
  1306. TOKEN_TYPE Type;
  1307. ULONG cbType;
  1308. HANDLE hImpToken;
  1309. NTSTATUS Status;
  1310. SECURITY_QUALITY_OF_SERVICE SecurityQualityOfService;
  1311. OBJECT_ATTRIBUTES ObjectAttributes;
  1312. BOOL fCloseImp;
  1313. Status = NtQueryInformationToken(
  1314. hToken,
  1315. TokenType,
  1316. &Type,
  1317. sizeof(TOKEN_TYPE),
  1318. &cbType);
  1319. if (!NT_SUCCESS(Status))
  1320. {
  1321. BaseSetLastNTError(Status);
  1322. return(FALSE);
  1323. }
  1324. if (Type == TokenPrimary)
  1325. {
  1326. InitializeObjectAttributes(
  1327. &ObjectAttributes,
  1328. NULL,
  1329. 0L,
  1330. NULL,
  1331. NULL);
  1332. SecurityQualityOfService.Length = sizeof(SECURITY_QUALITY_OF_SERVICE);
  1333. SecurityQualityOfService.ImpersonationLevel = SecurityImpersonation;
  1334. SecurityQualityOfService.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
  1335. SecurityQualityOfService.EffectiveOnly = FALSE;
  1336. ObjectAttributes.SecurityQualityOfService = &SecurityQualityOfService;
  1337. Status = NtDuplicateToken( hToken,
  1338. TOKEN_IMPERSONATE | TOKEN_QUERY,
  1339. &ObjectAttributes,
  1340. FALSE,
  1341. TokenImpersonation,
  1342. &hImpToken
  1343. );
  1344. if (!NT_SUCCESS(Status))
  1345. {
  1346. BaseSetLastNTError(Status);
  1347. return(FALSE);
  1348. }
  1349. fCloseImp = TRUE;
  1350. }
  1351. else
  1352. {
  1353. hImpToken = hToken;
  1354. fCloseImp = FALSE;
  1355. }
  1356. Status = NtSetInformationThread(
  1357. NtCurrentThread(),
  1358. ThreadImpersonationToken,
  1359. (PVOID) &hImpToken,
  1360. sizeof(hImpToken)
  1361. );
  1362. if (fCloseImp)
  1363. {
  1364. (void) NtClose(hImpToken);
  1365. }
  1366. if (!NT_SUCCESS(Status))
  1367. {
  1368. BaseSetLastNTError(Status);
  1369. return(FALSE);
  1370. }
  1371. return(TRUE);
  1372. }
  1373. //+---------------------------------------------------------------------------
  1374. //
  1375. // Function: L32SetProcessToken
  1376. //
  1377. // Synopsis: Sets the primary token for the new process.
  1378. //
  1379. // Arguments: [psd] --
  1380. // [hProcess] --
  1381. // [hThread] --
  1382. // [hToken] --
  1383. //
  1384. // History: 4-25-95 RichardW Created
  1385. //
  1386. // Notes:
  1387. //
  1388. //----------------------------------------------------------------------------
  1389. BOOL
  1390. L32SetProcessToken(
  1391. HANDLE hProcess,
  1392. HANDLE hThread,
  1393. HANDLE hTokenToAssign,
  1394. BOOL AlreadyImpersonating
  1395. )
  1396. {
  1397. NTSTATUS Status, AdjustStatus;
  1398. PROCESS_ACCESS_TOKEN PrimaryTokenInfo;
  1399. BOOLEAN WasEnabled;
  1400. HANDLE NullHandle;
  1401. //
  1402. // Set the process's primary token. This is actually much more complex
  1403. // to implement in a single API, but we'll live with it. This MUST be
  1404. // called when we are not impersonating! The client generally does *not*
  1405. // have the SeAssignPrimary privilege
  1406. //
  1407. //
  1408. // Enable the required privilege
  1409. //
  1410. if ( !AlreadyImpersonating )
  1411. {
  1412. Status = RtlImpersonateSelf( SecurityImpersonation );
  1413. }
  1414. else
  1415. {
  1416. Status = STATUS_SUCCESS ;
  1417. }
  1418. if ( NT_SUCCESS( Status ) )
  1419. {
  1420. //
  1421. // We now allow restricted tokens to passed in, so we don't
  1422. // fail if the privilege isn't held. Let the kernel deal with
  1423. // the possibilities.
  1424. //
  1425. Status = RtlAdjustPrivilege(SE_ASSIGNPRIMARYTOKEN_PRIVILEGE, TRUE,
  1426. TRUE, &WasEnabled);
  1427. if ( !NT_SUCCESS( Status ) )
  1428. {
  1429. WasEnabled = TRUE ; // Don't try to restore it.
  1430. }
  1431. PrimaryTokenInfo.Token = hTokenToAssign;
  1432. PrimaryTokenInfo.Thread = hThread;
  1433. Status = NtSetInformationProcess(
  1434. hProcess,
  1435. ProcessAccessToken,
  1436. (PVOID)&PrimaryTokenInfo,
  1437. (ULONG)sizeof(PROCESS_ACCESS_TOKEN)
  1438. );
  1439. //
  1440. // Restore the privilege to its previous state
  1441. //
  1442. if (!WasEnabled)
  1443. {
  1444. AdjustStatus = RtlAdjustPrivilege(SE_ASSIGNPRIMARYTOKEN_PRIVILEGE,
  1445. WasEnabled, TRUE, &WasEnabled);
  1446. if (NT_SUCCESS(Status)) {
  1447. Status = AdjustStatus;
  1448. }
  1449. }
  1450. //
  1451. // Revert back to process.
  1452. //
  1453. if ( !AlreadyImpersonating )
  1454. {
  1455. NullHandle = NULL;
  1456. AdjustStatus = NtSetInformationThread(
  1457. NtCurrentThread(),
  1458. ThreadImpersonationToken,
  1459. (PVOID) &NullHandle,
  1460. sizeof( HANDLE ) );
  1461. if ( NT_SUCCESS( Status ) )
  1462. {
  1463. Status = AdjustStatus;
  1464. }
  1465. }
  1466. } else {
  1467. NOTHING;
  1468. }
  1469. if (!NT_SUCCESS(Status)) {
  1470. BaseSetLastNTError(Status);
  1471. }
  1472. return (NT_SUCCESS(Status));
  1473. }
  1474. //+---------------------------------------------------------------------------
  1475. //
  1476. // Function: L32SetProcessQuotas
  1477. //
  1478. // Synopsis: Updates the quotas for the process
  1479. //
  1480. // Arguments: [hProcess] --
  1481. //
  1482. // History: 4-25-95 RichardW Created
  1483. //
  1484. // Notes:
  1485. //
  1486. //----------------------------------------------------------------------------
  1487. BOOL
  1488. L32SetProcessQuotas(
  1489. HANDLE hProcess,
  1490. BOOL AlreadyImpersonating )
  1491. {
  1492. NTSTATUS Status = STATUS_SUCCESS;
  1493. NTSTATUS AdjustStatus = STATUS_SUCCESS;
  1494. QUOTA_LIMITS RequestedLimits;
  1495. BOOLEAN WasEnabled;
  1496. HANDLE NullHandle;
  1497. RequestedLimits = Logon32QuotaLimits;
  1498. RequestedLimits.MinimumWorkingSetSize = 0;
  1499. RequestedLimits.MaximumWorkingSetSize = 0;
  1500. //
  1501. // Set the process's quota. This MUST be
  1502. // called when we are not impersonating! The client generally does *not*
  1503. // have the SeIncreaseQuota privilege.
  1504. //
  1505. if ( !AlreadyImpersonating )
  1506. {
  1507. Status = RtlImpersonateSelf( SecurityImpersonation );
  1508. }
  1509. if ( NT_SUCCESS( Status ) )
  1510. {
  1511. if (RequestedLimits.PagedPoolLimit != 0) {
  1512. Status = RtlAdjustPrivilege(SE_INCREASE_QUOTA_PRIVILEGE, TRUE,
  1513. TRUE, &WasEnabled);
  1514. if ( NT_SUCCESS( Status ) )
  1515. {
  1516. Status = NtSetInformationProcess(
  1517. hProcess,
  1518. ProcessQuotaLimits,
  1519. (PVOID)&RequestedLimits,
  1520. (ULONG)sizeof(QUOTA_LIMITS)
  1521. );
  1522. if (!WasEnabled)
  1523. {
  1524. AdjustStatus = RtlAdjustPrivilege(SE_INCREASE_QUOTA_PRIVILEGE,
  1525. WasEnabled, FALSE, &WasEnabled);
  1526. if (NT_SUCCESS(Status)) {
  1527. Status = AdjustStatus;
  1528. }
  1529. }
  1530. }
  1531. }
  1532. if ( !AlreadyImpersonating )
  1533. {
  1534. NullHandle = NULL;
  1535. AdjustStatus = NtSetInformationThread(
  1536. NtCurrentThread(),
  1537. ThreadImpersonationToken,
  1538. (PVOID) &NullHandle,
  1539. sizeof( HANDLE ) );
  1540. if ( NT_SUCCESS( Status ) )
  1541. {
  1542. Status = AdjustStatus;
  1543. }
  1544. }
  1545. }
  1546. if (!NT_SUCCESS(Status))
  1547. {
  1548. BaseSetLastNTError(Status);
  1549. return(FALSE);
  1550. }
  1551. return(TRUE);
  1552. }
  1553. BOOL
  1554. L32CreateTokenForNewProcess(
  1555. PSECURITY_DESCRIPTOR psd,
  1556. HANDLE hToken,
  1557. PHANDLE phTokenToAssign
  1558. )
  1559. {
  1560. OBJECT_ATTRIBUTES ObjectAttributes;
  1561. NTSTATUS Status;
  1562. //
  1563. // Check for a NULL token. (No need to do anything)
  1564. // The process will run in the parent process's context and inherit
  1565. // the default ACL from the parent process's token.
  1566. //
  1567. if (hToken == NULL)
  1568. {
  1569. *phTokenToAssign = NULL;
  1570. return TRUE;
  1571. }
  1572. //
  1573. // A primary token can only be assigned to one process.
  1574. // Duplicate the logon token so we can assign one to the new
  1575. // process.
  1576. //
  1577. InitializeObjectAttributes(
  1578. &ObjectAttributes,
  1579. NULL,
  1580. 0,
  1581. NULL,
  1582. psd
  1583. );
  1584. Status = NtDuplicateToken(
  1585. hToken, // Duplicate this token
  1586. 0, // Same desired access
  1587. &ObjectAttributes,
  1588. FALSE, // EffectiveOnly
  1589. TokenPrimary, // TokenType
  1590. phTokenToAssign // Duplicate token handle stored here
  1591. );
  1592. if (!NT_SUCCESS(Status)) {
  1593. BaseSetLastNTError(Status);
  1594. return FALSE;
  1595. }
  1596. return TRUE;
  1597. }
  1598. HANDLE
  1599. L32RevertOpenProcess(
  1600. DWORD dwDesiredAccess,
  1601. BOOL bInheritHandle,
  1602. DWORD dwProcessId
  1603. )
  1604. /*+
  1605. A revert to self wrapper around OpenProcess
  1606. -*/
  1607. {
  1608. HANDLE hThreadToken = NULL;
  1609. HANDLE hRevertToken = NULL;
  1610. HANDLE hProcess = NULL;
  1611. BOOL bImp = FALSE;
  1612. NTSTATUS Status = STATUS_SUCCESS;
  1613. //
  1614. // If we are impersonating we must revert.
  1615. //
  1616. Status = NtOpenThreadToken(
  1617. NtCurrentThread(),
  1618. TOKEN_QUERY | TOKEN_IMPERSONATE,
  1619. TRUE,
  1620. &hThreadToken
  1621. );
  1622. if (NT_SUCCESS(Status))
  1623. {
  1624. bImp = TRUE;
  1625. //
  1626. // Stop impersonating.
  1627. //
  1628. Status = NtSetInformationThread(
  1629. NtCurrentThread(),
  1630. ThreadImpersonationToken,
  1631. &hRevertToken,
  1632. sizeof(HANDLE)
  1633. );
  1634. if (!NT_SUCCESS(Status))
  1635. {
  1636. BaseSetLastNTError(Status);
  1637. goto Cleanup;
  1638. }
  1639. else
  1640. {
  1641. bImp = FALSE;
  1642. }
  1643. }
  1644. else if (Status == STATUS_NO_TOKEN)
  1645. {
  1646. hThreadToken = NULL;
  1647. bImp = FALSE;
  1648. }
  1649. else
  1650. {
  1651. //
  1652. // Why couldn't we open the thread token?
  1653. //
  1654. BaseSetLastNTError(Status);
  1655. ASSERT(NT_SUCCESS(Status));
  1656. goto Cleanup;
  1657. }
  1658. //
  1659. // OpenProcess without impersonating.
  1660. //
  1661. hProcess = OpenProcess(
  1662. dwDesiredAccess,
  1663. bInheritHandle,
  1664. dwProcessId
  1665. );
  1666. if (hThreadToken)
  1667. {
  1668. //
  1669. // Continue to impersonate.
  1670. //
  1671. Status = NtSetInformationThread(
  1672. NtCurrentThread(),
  1673. ThreadImpersonationToken,
  1674. &hThreadToken,
  1675. sizeof(HANDLE)
  1676. );
  1677. if (!NT_SUCCESS(Status))
  1678. {
  1679. BaseSetLastNTError(Status);
  1680. goto Cleanup;
  1681. }
  1682. else
  1683. {
  1684. bImp = TRUE;
  1685. }
  1686. }
  1687. Cleanup:
  1688. if (hThreadToken)
  1689. {
  1690. if (!bImp)
  1691. {
  1692. //
  1693. // Continue to impersonate.
  1694. //
  1695. Status = NtSetInformationThread(
  1696. NtCurrentThread(),
  1697. ThreadImpersonationToken,
  1698. &hThreadToken,
  1699. sizeof(HANDLE)
  1700. );
  1701. ASSERT(NT_SUCCESS(Status));
  1702. }
  1703. NtClose(hThreadToken);
  1704. }
  1705. return hProcess;
  1706. }
  1707. BOOL
  1708. L32CommonCreate(
  1709. DWORD CreateFlags,
  1710. HANDLE hToken,
  1711. LPPROCESS_INFORMATION lpProcessInfo,
  1712. LPSECURITY_ATTRIBUTES lpProcessAttributes,
  1713. LPSECURITY_ATTRIBUTES lpThreadAttributes
  1714. )
  1715. /*+
  1716. This will do several tasks.
  1717. 1 create new security descriptors for the process / thread / token.
  1718. 2 create a new token for the new process
  1719. 3 assign security to that token
  1720. 4 put this new token on the new process
  1721. 5 assign security to the process and thread
  1722. 6 adjust quotas on the new process
  1723. -*/
  1724. {
  1725. NTSTATUS Status = STATUS_SUCCESS;
  1726. BOOL b = TRUE;
  1727. PISECURITY_DESCRIPTOR pProcessSd = NULL;
  1728. PISECURITY_DESCRIPTOR pThreadSd = NULL;
  1729. PISECURITY_DESCRIPTOR pTokenSd = NULL;
  1730. TOKEN_TYPE Type;
  1731. DWORD dwLength;
  1732. BOOL bUsingThreadToken = FALSE;
  1733. BOOL bUsingImpToken = FALSE;
  1734. HANDLE hThreadToken = NULL; // the initial thread token, if any
  1735. HANDLE hNull = NULL; // token handle for reverting
  1736. HANDLE hTokenToAssign = NULL; // primary token to place on new process
  1737. HANDLE hImpToken = NULL; // impersonation version of hTokenToAssign
  1738. OBJECT_ATTRIBUTES ObjectAttributes = {0};
  1739. //
  1740. // Please forgive me.
  1741. //
  1742. GENERIC_MAPPING ProcessMapping = {
  1743. STANDARD_RIGHTS_READ |PROCESS_VM_READ | PROCESS_QUERY_INFORMATION,
  1744. STANDARD_RIGHTS_WRITE |PROCESS_CREATE_PROCESS | PROCESS_CREATE_THREAD |PROCESS_VM_OPERATION |
  1745. PROCESS_VM_WRITE | PROCESS_DUP_HANDLE |PROCESS_TERMINATE | PROCESS_SET_QUOTA |
  1746. PROCESS_SET_INFORMATION | PROCESS_SET_PORT,
  1747. STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
  1748. PROCESS_ALL_ACCESS
  1749. };
  1750. GENERIC_MAPPING ThreadMapping = {
  1751. STANDARD_RIGHTS_READ |THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
  1752. STANDARD_RIGHTS_WRITE |THREAD_TERMINATE | THREAD_SUSPEND_RESUME | THREAD_ALERT |THREAD_SET_INFORMATION | THREAD_SET_CONTEXT,
  1753. STANDARD_RIGHTS_EXECUTE |SYNCHRONIZE,
  1754. THREAD_ALL_ACCESS
  1755. };
  1756. GENERIC_MAPPING TokenMapping = {
  1757. TOKEN_READ,
  1758. TOKEN_WRITE,
  1759. TOKEN_EXECUTE,
  1760. TOKEN_ALL_ACCESS
  1761. };
  1762. //
  1763. // Sanity.
  1764. //
  1765. if (lpProcessInfo->hProcess == NULL)
  1766. {
  1767. b = FALSE;
  1768. BaseSetLastNTError(STATUS_INVALID_HANDLE);
  1769. goto Cleanup;
  1770. }
  1771. #ifdef ALLOW_IMPERSONATION_TOKENS
  1772. HANDLE hTempToken = NULL;
  1773. #endif
  1774. //
  1775. // Determine type of token, since a non primary token will not work
  1776. // on a process. Now, we could duplicate it into a primary token,
  1777. // and whack it into the process, but that leaves the process possibly
  1778. // without credentials.
  1779. //
  1780. Status = NtQueryInformationToken(
  1781. hToken,
  1782. TokenType,
  1783. (PUCHAR) &Type,
  1784. sizeof(Type),
  1785. &dwLength
  1786. );
  1787. if (!NT_SUCCESS(Status))
  1788. {
  1789. b = FALSE;
  1790. BaseSetLastNTError(Status);
  1791. goto Cleanup;
  1792. }
  1793. if (Type != TokenPrimary)
  1794. {
  1795. #ifdef ALLOW_IMPERSONATION_TOKENS
  1796. //
  1797. // Make this a primary token.
  1798. //
  1799. InitializeObjectAttributes(
  1800. &ObjectAttributes,
  1801. NULL,
  1802. 0L,
  1803. NULL,
  1804. NULL);
  1805. SecurityQualityOfService.Length = sizeof(SECURITY_QUALITY_OF_SERVICE);
  1806. SecurityQualityOfService.ImpersonationLevel = SecurityImpersonation;
  1807. SecurityQualityOfService.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
  1808. SecurityQualityOfService.EffectiveOnly = FALSE;
  1809. ObjectAttributes.SecurityQualityOfService = &SecurityQualityOfService;
  1810. Status = NtDuplicateToken(
  1811. hToken,
  1812. TOKEN_IMPERSONATE | TOKEN_QUERY,
  1813. &ObjectAttributes,
  1814. FALSE,
  1815. TokenPrimary,
  1816. &hTempToken
  1817. );
  1818. if (!NT_SUCCESS(Status))
  1819. {
  1820. b = FALSE;
  1821. BaseSetLastNTError(Status);
  1822. goto Cleanup;
  1823. }
  1824. hToken = hTempToken;
  1825. #else // !ALLOW_IMPERSONATION_TOKENS
  1826. b = FALSE;
  1827. Status = STATUS_BAD_TOKEN_TYPE;
  1828. BaseSetLastNTError(Status);
  1829. goto Cleanup;
  1830. #endif
  1831. }
  1832. //
  1833. // Make our security descriptors grant ownership and permissions to the principal
  1834. // represented by hToken. We need a SD for the process, thread, and the token
  1835. // that is getting placed on the new process.
  1836. //
  1837. //
  1838. // If we are impersonating we must revert because CreatePrivateObjectSecurityEx will
  1839. // call RtlpGetDefaultsSubjectContext, which will try to open the process token.
  1840. // The thread token (if it exists) will most likely not have this access.
  1841. //
  1842. Status = NtOpenThreadToken(
  1843. NtCurrentThread(),
  1844. TOKEN_QUERY | TOKEN_IMPERSONATE,
  1845. TRUE,
  1846. &hThreadToken
  1847. );
  1848. if (NT_SUCCESS(Status))
  1849. {
  1850. //
  1851. // Stop impersonating.
  1852. //
  1853. Status = NtSetInformationThread(
  1854. NtCurrentThread(),
  1855. ThreadImpersonationToken,
  1856. &hNull,
  1857. sizeof(HANDLE)
  1858. );
  1859. if (!NT_SUCCESS(Status))
  1860. {
  1861. b = FALSE;
  1862. BaseSetLastNTError(Status);
  1863. goto Cleanup;
  1864. }
  1865. bUsingThreadToken = FALSE;
  1866. }
  1867. else if (Status == STATUS_NO_TOKEN)
  1868. {
  1869. hThreadToken = NULL;
  1870. bUsingThreadToken = FALSE;
  1871. }
  1872. else
  1873. {
  1874. //
  1875. // Why couldn't we open the thread token?
  1876. //
  1877. ASSERT(NT_SUCCESS(Status));
  1878. b = FALSE;
  1879. BaseSetLastNTError(Status);
  1880. goto Cleanup;
  1881. }
  1882. //
  1883. // We should not be impersonating.
  1884. //
  1885. ASSERT(!bUsingThreadToken && !bUsingImpToken);
  1886. //
  1887. // Ignore the owner check as the owner in the passed SD may not be assignable as an owner
  1888. // given our current security context.
  1889. //
  1890. b = CreatePrivateObjectSecurityEx(
  1891. NULL,
  1892. lpProcessAttributes ? lpProcessAttributes->lpSecurityDescriptor : NULL,
  1893. &pProcessSd,
  1894. NULL,
  1895. FALSE,
  1896. SEF_AVOID_OWNER_CHECK,
  1897. hToken,
  1898. &ProcessMapping
  1899. );
  1900. if (!b)
  1901. {
  1902. goto Cleanup;
  1903. }
  1904. b = CreatePrivateObjectSecurityEx(
  1905. NULL,
  1906. lpThreadAttributes ? lpThreadAttributes->lpSecurityDescriptor : NULL,
  1907. &pThreadSd,
  1908. NULL,
  1909. FALSE,
  1910. SEF_AVOID_OWNER_CHECK,
  1911. hToken,
  1912. &ThreadMapping
  1913. );
  1914. if (!b)
  1915. {
  1916. goto Cleanup;
  1917. }
  1918. b = CreatePrivateObjectSecurityEx(
  1919. NULL,
  1920. NULL,
  1921. &pTokenSd,
  1922. NULL,
  1923. FALSE,
  1924. SEF_AVOID_OWNER_CHECK,
  1925. hToken,
  1926. &TokenMapping
  1927. );
  1928. if (!b)
  1929. {
  1930. goto Cleanup;
  1931. }
  1932. //
  1933. // We need an impersonation version of hToken so that we can later assign
  1934. // these SDs to the process and threads. The SDs we created specify hToken
  1935. // as the owner (assuming no passed SDs with owners), so only a thread
  1936. // impersonating as hToken can assign them to objects successfully
  1937. // (else we fail with INVALID_OWNER).
  1938. //
  1939. b = DuplicateTokenEx(
  1940. hToken,
  1941. TOKEN_QUERY | TOKEN_IMPERSONATE,
  1942. NULL,
  1943. SecurityImpersonation,
  1944. TokenImpersonation,
  1945. &hImpToken
  1946. );
  1947. if (!b)
  1948. {
  1949. goto Cleanup;
  1950. }
  1951. //
  1952. // Create a new token to put on the process. Make this a duplicate of
  1953. // the passed hToken. We are not impersonating here.
  1954. //
  1955. ASSERT(!bUsingThreadToken && !bUsingImpToken);
  1956. b = L32CreateTokenForNewProcess(
  1957. pTokenSd,
  1958. hToken,
  1959. &hTokenToAssign
  1960. );
  1961. if (!b)
  1962. {
  1963. //
  1964. // Try again under impersonation: if the Owner in pTokenSd isn't assignable
  1965. // when we run as the process, it will work with the new impersonation
  1966. // version of hToken (since pTokenSd states that the hToken principal is to
  1967. // be assigned as the Owner of hTokenToAssign).
  1968. //
  1969. Status = NtSetInformationThread(
  1970. NtCurrentThread(),
  1971. ThreadImpersonationToken,
  1972. &hImpToken,
  1973. sizeof(HANDLE)
  1974. );
  1975. if (!NT_SUCCESS(Status))
  1976. {
  1977. b = FALSE;
  1978. BaseSetLastNTError(Status);
  1979. goto Cleanup;
  1980. }
  1981. bUsingImpToken = TRUE;
  1982. b = L32CreateTokenForNewProcess(
  1983. pTokenSd,
  1984. hToken,
  1985. &hTokenToAssign
  1986. );
  1987. if (!b)
  1988. {
  1989. goto Cleanup;
  1990. }
  1991. //
  1992. // Revert.
  1993. //
  1994. Status = NtSetInformationThread(
  1995. NtCurrentThread(),
  1996. ThreadImpersonationToken,
  1997. &hNull,
  1998. sizeof(HANDLE)
  1999. );
  2000. if (!NT_SUCCESS(Status))
  2001. {
  2002. b = FALSE;
  2003. BaseSetLastNTError(Status);
  2004. goto Cleanup;
  2005. }
  2006. bUsingImpToken = FALSE;
  2007. }
  2008. //
  2009. // Now hTokenToAssign exists as a duplicate of hToken and it has proper security
  2010. // which grants access and ownership to the hToken principal. Set the primary token
  2011. // of the new process to be hTokenToAssign. Try this first without impersonating,
  2012. // since the current process currently owns this new process.
  2013. //
  2014. ASSERT(!bUsingThreadToken && !bUsingImpToken);
  2015. b = L32SetProcessToken(
  2016. lpProcessInfo->hProcess,
  2017. lpProcessInfo->hThread,
  2018. hTokenToAssign,
  2019. FALSE
  2020. );
  2021. if (!b)
  2022. {
  2023. if (hThreadToken)
  2024. {
  2025. //
  2026. // Try again as the original thread principal. We aren't trying as the
  2027. // hToken principal because that would allow anyone to create a process
  2028. // as any user with the correct privileges (assuming that they could get
  2029. // ahold of said user's token). If the thread token had the assign primary
  2030. // privilege then we will succeed.
  2031. //
  2032. Status = NtSetInformationThread(
  2033. NtCurrentThread(),
  2034. ThreadImpersonationToken,
  2035. &hThreadToken,
  2036. sizeof(HANDLE)
  2037. );
  2038. if (!NT_SUCCESS(Status))
  2039. {
  2040. b = FALSE;
  2041. BaseSetLastNTError(Status);
  2042. goto Cleanup;
  2043. }
  2044. bUsingThreadToken = TRUE;
  2045. b = L32SetProcessToken(
  2046. lpProcessInfo->hProcess,
  2047. lpProcessInfo->hThread,
  2048. hTokenToAssign,
  2049. TRUE
  2050. );
  2051. if (!b)
  2052. {
  2053. goto Cleanup;
  2054. }
  2055. //
  2056. // Revert.
  2057. //
  2058. Status = NtSetInformationThread(
  2059. NtCurrentThread(),
  2060. ThreadImpersonationToken,
  2061. &hNull,
  2062. sizeof(HANDLE)
  2063. );
  2064. if (!NT_SUCCESS(Status))
  2065. {
  2066. b = FALSE;
  2067. BaseSetLastNTError(Status);
  2068. goto Cleanup;
  2069. }
  2070. bUsingThreadToken = FALSE;
  2071. }
  2072. else
  2073. {
  2074. //
  2075. // The process doesn't have rights to assign the new process
  2076. // a primary token, and we weren't called with an impersonation
  2077. // context. We must give up.
  2078. //
  2079. goto Cleanup;
  2080. }
  2081. }
  2082. //
  2083. // Adjust the quota to something reasonable.
  2084. //
  2085. ASSERT(!bUsingThreadToken && !bUsingImpToken);
  2086. b = L32SetProcessQuotas(
  2087. lpProcessInfo->hProcess,
  2088. FALSE
  2089. );
  2090. if (!b)
  2091. {
  2092. if (hThreadToken)
  2093. {
  2094. //
  2095. // If we failed to adjust quota as the process then try
  2096. // while impersonating as the original thread token.
  2097. //
  2098. Status = NtSetInformationThread(
  2099. NtCurrentThread(),
  2100. ThreadImpersonationToken,
  2101. &hThreadToken,
  2102. sizeof(HANDLE)
  2103. );
  2104. if (!NT_SUCCESS(Status))
  2105. {
  2106. b = FALSE;
  2107. BaseSetLastNTError(Status);
  2108. goto Cleanup;
  2109. }
  2110. bUsingThreadToken = TRUE;
  2111. b = L32SetProcessQuotas(
  2112. lpProcessInfo->hProcess,
  2113. TRUE
  2114. );
  2115. if (!b)
  2116. {
  2117. goto Cleanup;
  2118. }
  2119. //
  2120. // Revert.
  2121. //
  2122. Status = NtSetInformationThread(
  2123. NtCurrentThread(),
  2124. ThreadImpersonationToken,
  2125. &hNull,
  2126. sizeof(HANDLE)
  2127. );
  2128. if (!NT_SUCCESS(Status))
  2129. {
  2130. b = FALSE;
  2131. BaseSetLastNTError(Status);
  2132. goto Cleanup;
  2133. }
  2134. bUsingThreadToken = FALSE;
  2135. }
  2136. else
  2137. {
  2138. //
  2139. // We cannot adjust the quota as the process, and we were
  2140. // not called while impersonating. Fail.
  2141. //
  2142. goto Cleanup;
  2143. }
  2144. }
  2145. //
  2146. // We should not be impersonating here.
  2147. //
  2148. ASSERT(!bUsingThreadToken && !bUsingImpToken);
  2149. //
  2150. // Now put the correct SD on the process / thread.
  2151. //
  2152. b = SetKernelObjectSecurity(
  2153. lpProcessInfo->hProcess,
  2154. GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
  2155. pProcessSd
  2156. );
  2157. if (!b)
  2158. {
  2159. //
  2160. // If we failed above the cause was most likely because the owner ID in
  2161. // the SD does not exist as an assignable owner ID in the current process token.
  2162. // Impersonating as hImpToken will take care of this.
  2163. //
  2164. Status = NtSetInformationThread(
  2165. NtCurrentThread(),
  2166. ThreadImpersonationToken,
  2167. &hImpToken,
  2168. sizeof(HANDLE)
  2169. );
  2170. if (!NT_SUCCESS(Status))
  2171. {
  2172. b = FALSE;
  2173. BaseSetLastNTError(Status);
  2174. goto Cleanup;
  2175. }
  2176. bUsingImpToken = TRUE;
  2177. //
  2178. // Try again as hImpToken.
  2179. //
  2180. b = SetKernelObjectSecurity(
  2181. lpProcessInfo->hProcess,
  2182. GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
  2183. pProcessSd
  2184. );
  2185. if (!b)
  2186. {
  2187. goto Cleanup;
  2188. }
  2189. //
  2190. // Revert.
  2191. //
  2192. Status = NtSetInformationThread(
  2193. NtCurrentThread(),
  2194. ThreadImpersonationToken,
  2195. &hNull,
  2196. sizeof(HANDLE)
  2197. );
  2198. if (!NT_SUCCESS(Status))
  2199. {
  2200. b = FALSE;
  2201. BaseSetLastNTError(Status);
  2202. goto Cleanup;
  2203. }
  2204. bUsingImpToken = FALSE;
  2205. }
  2206. //
  2207. // Now put it on the thread.
  2208. //
  2209. b = SetKernelObjectSecurity(
  2210. lpProcessInfo->hThread,
  2211. GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
  2212. pThreadSd
  2213. );
  2214. if (!b)
  2215. {
  2216. //
  2217. // If we failed above the cause was most likely because the owner ID in
  2218. // the SD does not exist as an assignable owner ID in the current process token.
  2219. // Impersonating as hImpToken will take care of this.
  2220. //
  2221. Status = NtSetInformationThread(
  2222. NtCurrentThread(),
  2223. ThreadImpersonationToken,
  2224. &hImpToken,
  2225. sizeof(HANDLE)
  2226. );
  2227. if (!NT_SUCCESS(Status))
  2228. {
  2229. b = FALSE;
  2230. BaseSetLastNTError(Status);
  2231. goto Cleanup;
  2232. }
  2233. bUsingImpToken = TRUE;
  2234. //
  2235. // Try again as hImpToken.
  2236. //
  2237. b = SetKernelObjectSecurity(
  2238. lpProcessInfo->hThread,
  2239. GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
  2240. pThreadSd
  2241. );
  2242. if (!b)
  2243. {
  2244. goto Cleanup;
  2245. }
  2246. //
  2247. // Revert.
  2248. //
  2249. Status = NtSetInformationThread(
  2250. NtCurrentThread(),
  2251. ThreadImpersonationToken,
  2252. &hNull,
  2253. sizeof(HANDLE)
  2254. );
  2255. if (!NT_SUCCESS(Status))
  2256. {
  2257. b = FALSE;
  2258. BaseSetLastNTError(Status);
  2259. goto Cleanup;
  2260. }
  2261. bUsingImpToken = FALSE;
  2262. }
  2263. //
  2264. // If we're not supposed to leave it suspended then resume the
  2265. // thread and let it run.
  2266. //
  2267. if ((CreateFlags & COMMON_CREATE_SUSPENDED) == 0)
  2268. {
  2269. ResumeThread(lpProcessInfo->hThread);
  2270. }
  2271. //
  2272. // That's it!
  2273. //
  2274. goto Cleanup;
  2275. Cleanup:
  2276. #ifdef ALLOW_IMPERSONATION_TOKENS
  2277. if (hTempToken)
  2278. {
  2279. NtClose(hTempToken);
  2280. }
  2281. #endif
  2282. //
  2283. // Free our new security descriptors.
  2284. //
  2285. if (pTokenSd)
  2286. {
  2287. DestroyPrivateObjectSecurity(&pTokenSd);
  2288. }
  2289. if (pProcessSd)
  2290. {
  2291. DestroyPrivateObjectSecurity(&pProcessSd);
  2292. }
  2293. if (pThreadSd)
  2294. {
  2295. DestroyPrivateObjectSecurity(&pThreadSd);
  2296. }
  2297. if (hTokenToAssign)
  2298. {
  2299. NtClose(hTokenToAssign);
  2300. }
  2301. //
  2302. // If we are using the newly created impersonation token
  2303. // then revert.
  2304. //
  2305. if (hImpToken)
  2306. {
  2307. if (bUsingImpToken)
  2308. {
  2309. Status = NtSetInformationThread(
  2310. NtCurrentThread(),
  2311. ThreadImpersonationToken,
  2312. &hNull,
  2313. sizeof(HANDLE)
  2314. );
  2315. //
  2316. // We should only ASSERT here because we don't want to
  2317. // overwrite our real error codes.
  2318. //
  2319. ASSERT(NT_SUCCESS(Status));
  2320. }
  2321. NtClose(hImpToken);
  2322. }
  2323. //
  2324. // Resume original impersonation if that is how we were called.
  2325. //
  2326. if (hThreadToken)
  2327. {
  2328. if (!bUsingThreadToken)
  2329. {
  2330. Status = NtSetInformationThread(
  2331. NtCurrentThread(),
  2332. ThreadImpersonationToken,
  2333. &hThreadToken,
  2334. sizeof(HANDLE)
  2335. );
  2336. //
  2337. // We should only ASSERT here because we don't want to
  2338. // overwrite our real error codes.
  2339. //
  2340. ASSERT(NT_SUCCESS(Status));
  2341. }
  2342. NtClose(hThreadToken);
  2343. }
  2344. if (!b)
  2345. {
  2346. if (lpProcessInfo->hProcess)
  2347. {
  2348. NtTerminateProcess(
  2349. lpProcessInfo->hProcess,
  2350. ERROR_ACCESS_DENIED
  2351. );
  2352. NtClose(lpProcessInfo->hProcess);
  2353. }
  2354. if (lpProcessInfo->hThread)
  2355. {
  2356. NtClose(lpProcessInfo->hThread);
  2357. }
  2358. RtlZeroMemory(
  2359. lpProcessInfo,
  2360. sizeof(PROCESS_INFORMATION)
  2361. );
  2362. }
  2363. return b;
  2364. }
  2365. //+---------------------------------------------------------------------------
  2366. //
  2367. // Function: SaferiReplaceProcessThreadTokens
  2368. //
  2369. // Synopsis:
  2370. // Provides a privately exported function to replace the access token
  2371. // of a process and its primary thread of a new process before its
  2372. // execution has begun. The process is left in a suspended state
  2373. // after the token modification has been performed.
  2374. //
  2375. // Effects:
  2376. //
  2377. // Arguments: [NewTokenHandle] -- Primary token to use
  2378. // [ProcessHandle] -- Process handle
  2379. // [ThreadHandle] -- Handle of process's primary Thread
  2380. //
  2381. // History: 8-25-2000 JLawson Created
  2382. //
  2383. // Notes:
  2384. // This is merely a wrapper function that calls L32CommonCreate.
  2385. //
  2386. //----------------------------------------------------------------------------
  2387. BOOL
  2388. WINAPI
  2389. SaferiReplaceProcessThreadTokens(
  2390. IN HANDLE NewTokenHandle,
  2391. IN HANDLE ProcessHandle,
  2392. IN HANDLE ThreadHandle
  2393. )
  2394. {
  2395. PROCESS_INFORMATION TempProcessInfo;
  2396. RtlZeroMemory( &TempProcessInfo, sizeof( PROCESS_INFORMATION ) );
  2397. TempProcessInfo.hProcess = ProcessHandle;
  2398. TempProcessInfo.hThread = ThreadHandle;
  2399. return (L32CommonCreate(
  2400. COMMON_CREATE_PROCESSSD | COMMON_CREATE_THREADSD | COMMON_CREATE_SUSPENDED,
  2401. NewTokenHandle,
  2402. &TempProcessInfo,
  2403. NULL,
  2404. NULL));
  2405. }
  2406. //+---------------------------------------------------------------------------
  2407. //
  2408. // MarshallString
  2409. //
  2410. // Marshall in a UNICODE_NULL terminated WCHAR string
  2411. //
  2412. // ENTRY:
  2413. // pSource (input)
  2414. // Pointer to source string
  2415. //
  2416. // pBase (input)
  2417. // Base buffer pointer for normalizing the string pointer
  2418. //
  2419. // MaxSize (input)
  2420. // Maximum buffer size available
  2421. //
  2422. // ppPtr (input/output)
  2423. // Pointer to the current context pointer in the marshall buffer.
  2424. // This is updated as data is marshalled into the buffer
  2425. //
  2426. // pCount (input/output)
  2427. // Current count of data in the marshall buffer.
  2428. // This is updated as data is marshalled into the buffer
  2429. //
  2430. // EXIT:
  2431. // NULL - Error
  2432. // !=NULL "normalized" pointer to the string in reference to pBase
  2433. //
  2434. //+---------------------------------------------------------------------------
  2435. PWCHAR
  2436. MarshallString(
  2437. PCWSTR pSource,
  2438. PCHAR pBase,
  2439. ULONG MaxSize,
  2440. PCHAR *ppPtr,
  2441. PULONG pCount
  2442. )
  2443. {
  2444. ULONG Len;
  2445. PCHAR ptr;
  2446. Len = wcslen( pSource );
  2447. Len++; // include the NULL;
  2448. Len *= sizeof(WCHAR); // convert to bytes
  2449. if( (*pCount + Len) > MaxSize ) {
  2450. return( NULL );
  2451. }
  2452. RtlMoveMemory( *ppPtr, pSource, Len );
  2453. //
  2454. // the normalized ptr is the current count
  2455. //
  2456. // Sundown note: ptr is a zero-extension of *pCount.
  2457. ptr = (PCHAR)ULongToPtr(*pCount);
  2458. *ppPtr += Len;
  2459. *pCount += Len;
  2460. return((PWCHAR)ptr);
  2461. }
  2462. #if DBG
  2463. void DumpOutLastErrorString()
  2464. {
  2465. LPVOID lpMsgBuf;
  2466. FormatMessage(
  2467. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  2468. FORMAT_MESSAGE_FROM_SYSTEM |
  2469. FORMAT_MESSAGE_IGNORE_INSERTS,
  2470. NULL,
  2471. GetLastError(),
  2472. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  2473. (LPTSTR) &lpMsgBuf,
  2474. 0,
  2475. NULL
  2476. );
  2477. //
  2478. // Process any inserts in lpMsgBuf.
  2479. // ...
  2480. // Display the string.
  2481. //
  2482. KdPrint(("%s\n", (LPCTSTR)lpMsgBuf ));
  2483. //
  2484. // Free the buffer.
  2485. //
  2486. LocalFree( lpMsgBuf );
  2487. }
  2488. #endif
  2489. #ifdef DBG
  2490. #define DBG_DumpOutLastError DumpOutLastErrorString();
  2491. #else
  2492. #define DBG_DumpOutLastError
  2493. #endif
  2494. //+---------------------------------------------------------------------------
  2495. //
  2496. // This function was originally defined in \nt\private\ole32\dcomss\olescm\execclt.cxx
  2497. //
  2498. // CreateRemoteSessionProcessW()
  2499. //
  2500. // Create a process on the given Terminal Server Session. This is in UNICODE
  2501. //
  2502. // ENTRY:
  2503. // SessionId (input)
  2504. // SessionId of Session to create process on
  2505. //
  2506. // Param1 (input/output)
  2507. // Comments
  2508. //
  2509. // Comments
  2510. // The security attribs are not used by the session, they are set to NULL
  2511. // We may consider to extend this feature in the future, assuming there is a
  2512. // need for it.
  2513. //
  2514. // EXIT:
  2515. // STATUS_SUCCESS - no error
  2516. //+---------------------------------------------------------------------------
  2517. BOOL
  2518. CreateRemoteSessionProcessW(
  2519. ULONG SessionId,
  2520. BOOL System,
  2521. HANDLE hToken,
  2522. PCWSTR lpszImageName,
  2523. PCWSTR lpszCommandLine,
  2524. PSECURITY_ATTRIBUTES psaProcess, // these are ignored on the session side, set to NULL
  2525. PSECURITY_ATTRIBUTES psaThread, // these are ignored on the session side, set to NULL
  2526. BOOL fInheritHandles,
  2527. DWORD fdwCreate,
  2528. LPVOID lpvEnvionment,
  2529. LPCWSTR lpszCurDir,
  2530. LPSTARTUPINFOW pStartInfo,
  2531. LPPROCESS_INFORMATION pProcInfo
  2532. )
  2533. {
  2534. BOOL Result = TRUE;
  2535. HANDLE hPipe = NULL;
  2536. WCHAR szPipeName[EXECSRVPIPENAMELEN];
  2537. PCHAR ptr;
  2538. ULONG Count, AmountWrote, AmountRead;
  2539. DWORD MyProcId;
  2540. PEXECSRV_REQUEST pReq;
  2541. EXECSRV_REPLY Rep;
  2542. CHAR Buf[EXECSRV_BUFFER_SIZE];
  2543. ULONG MaxSize = EXECSRV_BUFFER_SIZE;
  2544. DWORD rc;
  2545. LPVOID lpMsgBuf;
  2546. ULONG envSize=0; // size of the lpEnvironemt, if any
  2547. PWCHAR lpEnv;
  2548. ULONG ReturnLen;
  2549. #if DBG
  2550. if( lpszImageName )
  2551. KdPrint(("logon32.c: CreateRemoteSessionProcessW: lpszImageName %ws\n",lpszImageName));
  2552. if( lpszCommandLine )
  2553. KdPrint(("logon32.c: CreateRemoteSessionProcessW: lpszCommandLine %ws\n",lpszCommandLine));
  2554. #endif
  2555. //
  2556. // Winlogon handles all now. System flag tells it what to do
  2557. //
  2558. Result = WinStationQueryInformation( NULL, SessionId, WinStationExecSrvSystemPipe, szPipeName, sizeof(szPipeName), &ReturnLen );
  2559. if ( !Result ) {
  2560. KdPrint(("logon32.c: WinStationQueryInformation for the EXECSRV pipe name failed\n"));
  2561. return(FALSE);
  2562. }
  2563. while ( TRUE )
  2564. {
  2565. hPipe = CreateFileW(
  2566. szPipeName,
  2567. GENERIC_READ|GENERIC_WRITE,
  2568. 0, // File share mode
  2569. NULL, // default security
  2570. OPEN_EXISTING,
  2571. 0, // Attrs and flags
  2572. NULL // template file handle
  2573. );
  2574. if( hPipe == INVALID_HANDLE_VALUE )
  2575. {
  2576. if (GetLastError() == ERROR_PIPE_BUSY)
  2577. {
  2578. if (!WaitNamedPipeW( szPipeName, 30000 ))
  2579. { // 30 sec
  2580. KdPrint(("logon32.c: Waited too long for pipe name %ws\n", szPipeName));
  2581. return(FALSE);
  2582. }
  2583. }
  2584. else
  2585. {
  2586. DBG_DumpOutLastError;
  2587. KdPrint(("logon32.c: Could not create pipe name %ws\n", szPipeName));
  2588. return(FALSE);
  2589. }
  2590. }
  2591. else
  2592. {
  2593. break;
  2594. }
  2595. }
  2596. //
  2597. // Get the handle to the current process
  2598. //
  2599. MyProcId = GetCurrentProcessId();
  2600. //
  2601. // setup the marshalling
  2602. //
  2603. ptr = Buf;
  2604. Count = 0;
  2605. pReq = (PEXECSRV_REQUEST)ptr;
  2606. ptr += sizeof(EXECSRV_REQUEST);
  2607. Count += sizeof(EXECSRV_REQUEST);
  2608. //
  2609. // set the basic parameters
  2610. //
  2611. pReq->System = System;
  2612. pReq->hToken = hToken;
  2613. pReq->RequestingProcessId = MyProcId;
  2614. pReq->fInheritHandles = fInheritHandles;
  2615. pReq->fdwCreate = fdwCreate;
  2616. //
  2617. // marshall the ImageName string
  2618. //
  2619. if( lpszImageName ) {
  2620. pReq->lpszImageName = MarshallString( lpszImageName, Buf, MaxSize, &ptr, &Count );
  2621. if (! pReq->lpszImageName)
  2622. {
  2623. Result = FALSE;
  2624. goto Cleanup;
  2625. }
  2626. }
  2627. else {
  2628. pReq->lpszImageName = NULL;
  2629. }
  2630. //
  2631. // marshall in the CommandLine string
  2632. //
  2633. if( lpszCommandLine ) {
  2634. pReq->lpszCommandLine = MarshallString( lpszCommandLine, Buf, MaxSize, &ptr, &Count );
  2635. if ( ! pReq->lpszCommandLine )
  2636. {
  2637. Result = FALSE;
  2638. goto Cleanup;
  2639. }
  2640. }
  2641. else {
  2642. pReq->lpszCommandLine = NULL;
  2643. }
  2644. //
  2645. // marshall in the CurDir string
  2646. //
  2647. if( lpszCurDir ) {
  2648. pReq->lpszCurDir = MarshallString( lpszCurDir, Buf, MaxSize, &ptr, &Count );
  2649. if ( ! pReq->lpszCurDir )
  2650. {
  2651. Result = FALSE;
  2652. goto Cleanup;
  2653. }
  2654. }
  2655. else {
  2656. pReq->lpszCurDir = NULL;
  2657. }
  2658. //
  2659. // marshall in the StartupInfo structure
  2660. //
  2661. RtlMoveMemory( &pReq->StartInfo, pStartInfo, sizeof(STARTUPINFO) );
  2662. //
  2663. // Now marshall the strings in STARTUPINFO
  2664. //
  2665. if( pStartInfo->lpDesktop ) {
  2666. pReq->StartInfo.lpDesktop = MarshallString( pStartInfo->lpDesktop, Buf, MaxSize, &ptr, &Count );
  2667. if (! pReq->StartInfo.lpDesktop )
  2668. {
  2669. Result = FALSE;
  2670. goto Cleanup;
  2671. }
  2672. }
  2673. else {
  2674. pReq->StartInfo.lpDesktop = NULL;
  2675. }
  2676. if( pStartInfo->lpTitle ) {
  2677. pReq->StartInfo.lpTitle = MarshallString( pStartInfo->lpTitle, Buf, MaxSize, &ptr, &Count );
  2678. if ( !pReq->StartInfo.lpTitle )
  2679. {
  2680. Result = FALSE;
  2681. goto Cleanup;
  2682. }
  2683. }
  2684. else {
  2685. pReq->StartInfo.lpTitle = NULL;
  2686. }
  2687. //
  2688. // WARNING: This version does not pass the following:
  2689. //
  2690. // Also saProcess and saThread are ignored right now and use
  2691. // the users default security on the remote WinStation
  2692. //
  2693. // Set things that are always NULL
  2694. //
  2695. pReq->StartInfo.lpReserved = NULL; // always NULL
  2696. if ( lpvEnvionment)
  2697. {
  2698. for ( lpEnv = (PWCHAR) lpvEnvionment;
  2699. (*lpEnv ) && (envSize + Count < MaxSize ) ; lpEnv++)
  2700. {
  2701. while( *lpEnv )
  2702. {
  2703. lpEnv++;
  2704. envSize += 2; // we are dealing with wide chars
  2705. if ( envSize+Count >= MaxSize )
  2706. {
  2707. // we have too many
  2708. // vars in the user's profile.
  2709. KdPrint(("\tEnv length too big = %d \n", envSize));
  2710. break;
  2711. }
  2712. }
  2713. // this is the null which marked the end of the last env var.
  2714. envSize +=2;
  2715. }
  2716. envSize += 2; // this is the final NULL
  2717. if ( Count + envSize < MaxSize )
  2718. {
  2719. RtlMoveMemory( (PCHAR)&Buf[Count] ,lpvEnvionment, envSize );
  2720. // SUNDOWN: Count is zero-extended and store in lpvEnvironment.
  2721. // This zero-extension is valid. The consuming code [see tsext\notify\execsrv.c]
  2722. // considers lpvEnvironment as an offset (<2GB).
  2723. pReq->lpvEnvironment = (PCHAR)ULongToPtr(Count);
  2724. ptr += envSize; // for the next guy
  2725. Count += envSize; // the count used so far
  2726. }
  2727. else // no room left to make a complete copy
  2728. {
  2729. pReq->lpvEnvironment = NULL;
  2730. }
  2731. }
  2732. else
  2733. {
  2734. pReq->lpvEnvironment = NULL;
  2735. }
  2736. //
  2737. // now fill in the total count
  2738. //
  2739. pReq->Size = Count;
  2740. #if DBG
  2741. KdPrint(("pReq->Size = %d, envSize = %d \n", pReq->Size , envSize ));
  2742. #endif
  2743. //
  2744. // Now send the buffer out to the server
  2745. //
  2746. Result = WriteFile(
  2747. hPipe,
  2748. Buf,
  2749. Count,
  2750. &AmountWrote,
  2751. NULL
  2752. );
  2753. if( !Result ) {
  2754. KdPrint(("logon32.c: Error %d sending request\n",GetLastError() ));
  2755. goto Cleanup;
  2756. }
  2757. //
  2758. // Now read the reply
  2759. //
  2760. Result = ReadFile(
  2761. hPipe,
  2762. &Rep,
  2763. sizeof(Rep),
  2764. &AmountRead,
  2765. NULL
  2766. );
  2767. if( !Result ) {
  2768. KdPrint(("logon32.c: Error %d reading reply\n",GetLastError()));
  2769. goto Cleanup;
  2770. }
  2771. //
  2772. // Check the result
  2773. //
  2774. if( !Rep.Result ) {
  2775. KdPrint(("logon32.c: Error %d in reply\n",Rep.LastError));
  2776. //
  2777. // set the error in the current thread to the returned error
  2778. //
  2779. Result = Rep.Result;
  2780. SetLastError( Rep.LastError );
  2781. goto Cleanup;
  2782. }
  2783. //
  2784. // We copy the PROCESS_INFO structure from the reply
  2785. // to the caller.
  2786. //
  2787. // The remote site has duplicated the handles into our
  2788. // process space for hProcess and hThread so that they will
  2789. // behave like CreateProcessW()
  2790. //
  2791. RtlMoveMemory( pProcInfo, &Rep.ProcInfo, sizeof( PROCESS_INFORMATION ) );
  2792. Cleanup:
  2793. CloseHandle(hPipe);
  2794. KdPrint(("logon32.c:: Result 0x%x\n", Result));
  2795. return(Result);
  2796. }
  2797. //+---------------------------------------------------------------------------
  2798. //
  2799. // Function: CreateProcessAsUserW
  2800. //
  2801. // Synopsis: Creates a process running as the user in hToken.
  2802. //
  2803. // Arguments: [hToken] -- Handle to a Primary Token to use
  2804. // [lpApplicationName] -- as CreateProcess() q.v.
  2805. // [lpCommandLine] --
  2806. // [lpProcessAttributes] --
  2807. // [lpThreadAttributes] --
  2808. // [bInheritHandles] --
  2809. // [dwCreationFlags] --
  2810. // [lpEnvironment] --
  2811. // [lpCurrentDirectory] --
  2812. // [lpStartupInfo] --
  2813. // [lpProcessInformation] --
  2814. //
  2815. // Return Values
  2816. // If the function succeeds, the return value is nonzero.
  2817. // If the function fails, the return value is zero. To get extended error information, call GetLastError.
  2818. //
  2819. // History: 4-25-95 RichardW Created
  2820. // 1-14-98 AraBern add changes for Hydra
  2821. // Notes:
  2822. //
  2823. //
  2824. //----------------------------------------------------------------------------
  2825. BOOL
  2826. WINAPI
  2827. CreateProcessAsUserW(
  2828. HANDLE hToken,
  2829. LPCWSTR lpApplicationName,
  2830. LPWSTR lpCommandLine,
  2831. LPSECURITY_ATTRIBUTES lpProcessAttributes,
  2832. LPSECURITY_ATTRIBUTES lpThreadAttributes,
  2833. BOOL bInheritHandles,
  2834. DWORD dwCreationFlags,
  2835. LPVOID lpEnvironment,
  2836. LPCWSTR lpCurrentDirectory,
  2837. LPSTARTUPINFOW lpStartupInfo,
  2838. LPPROCESS_INFORMATION lpProcessInformation
  2839. )
  2840. {
  2841. DWORD CreateFlags;
  2842. DWORD clientSessionID=0;
  2843. DWORD currentSessionID=0;
  2844. DWORD resultLength;
  2845. HANDLE hTmpToken;
  2846. DWORD curProcId ;
  2847. NTSTATUS Status ;
  2848. CreateFlags = (dwCreationFlags & CREATE_SUSPENDED ? COMMON_CREATE_SUSPENDED : 0);
  2849. //
  2850. // get the sessionID (if zero then it means that we are on the console).
  2851. //
  2852. currentSessionID = NtCurrentPeb()->SessionId;
  2853. if ( !GetTokenInformation ( hToken, TokenSessionId , &clientSessionID,sizeof( DWORD), &resultLength ) )
  2854. {
  2855. //
  2856. // get the access token for the client of this call
  2857. // get token instead of process since the client might have only
  2858. // impersonated the thread, not the process
  2859. //
  2860. DBG_DumpOutLastError;
  2861. ASSERT( FALSE );
  2862. currentSessionID = 0;
  2863. //
  2864. // We should probably return FALSE here, but at this time we don't want to alter the
  2865. // non-Hydra code-execution-flow at all.
  2866. //
  2867. }
  2868. // KdPrint(("logon32.c: CreateProcessAsUserW(): clientSessionID = %d, currentSessionID = %d \n",
  2869. // clientSessionID, currentSessionID ));
  2870. if ( clientSessionID != currentSessionID )
  2871. {
  2872. //
  2873. // If the client session ID is not the same as the current session ID, then, we are attempting
  2874. // to create a process on a remote session from the current session.
  2875. // This block of code is used to accomplish such process creation, it is Terminal-Server specific
  2876. //
  2877. BOOL bHaveImpersonated;
  2878. HANDLE hCurrentThread;
  2879. HANDLE hPrevToken = NULL;
  2880. DWORD rc;
  2881. TOKEN_TYPE tokenType;
  2882. //
  2883. // We must send the request to the remote session
  2884. // of the requestor
  2885. //
  2886. // NOTE: The current WinStationCreateProcessW() does not use
  2887. // the supplied security descriptor, but creates the
  2888. // process under the account of the logged on user.
  2889. //
  2890. //
  2891. // Stop impersonating before doing the WinStationCreateProcess.
  2892. // The remote winstation exec thread will launch the app under
  2893. // the users context. We must not be impersonating because this
  2894. // call only lets SYSTEM request the remote execute.
  2895. //
  2896. //
  2897. // Handle Inheritance is not allowed for cross session process creation
  2898. //
  2899. if (bInheritHandles) {
  2900. SetLastError(ERROR_INVALID_PARAMETER);
  2901. return FALSE;
  2902. }
  2903. hCurrentThread = GetCurrentThread();
  2904. //
  2905. // Init bHaveImpersonated to the FALSE state
  2906. //
  2907. bHaveImpersonated = FALSE;
  2908. //
  2909. // Since the caller of this function (runas-> SecLogon service ) has already
  2910. // impersonated the new (target) user, we do the OpenThreadToken with
  2911. // OpenAsSelf = TRUE
  2912. //
  2913. if ( OpenThreadToken( hCurrentThread, TOKEN_QUERY | TOKEN_IMPERSONATE , TRUE, &hPrevToken ) )
  2914. {
  2915. bHaveImpersonated = TRUE;
  2916. if ( !RevertToSelf() )
  2917. {
  2918. return FALSE;
  2919. }
  2920. }
  2921. //
  2922. // else, we are not impersonating, as reflected by the init value of bHaveImpersonated
  2923. //
  2924. rc = CreateRemoteSessionProcessW(
  2925. clientSessionID,
  2926. FALSE, // not creating a process for System
  2927. hToken,
  2928. lpApplicationName,
  2929. lpCommandLine,
  2930. lpProcessAttributes,
  2931. lpThreadAttributes,
  2932. bInheritHandles,
  2933. dwCreationFlags,
  2934. lpEnvironment,
  2935. lpCurrentDirectory,
  2936. lpStartupInfo,
  2937. lpProcessInformation) ;
  2938. //
  2939. // Undo the effect of RevertToSelf() if we had impersoanted
  2940. //
  2941. if ( bHaveImpersonated )
  2942. {
  2943. Status = NtSetInformationThread(
  2944. NtCurrentThread(),
  2945. ThreadImpersonationToken,
  2946. &hPrevToken,
  2947. sizeof( hPrevToken ) );
  2948. ASSERT( NT_SUCCESS(Status ) );
  2949. NtClose( hPrevToken );
  2950. }
  2951. if ( rc )
  2952. {
  2953. return TRUE;
  2954. }
  2955. else
  2956. {
  2957. return FALSE;
  2958. }
  2959. }
  2960. else
  2961. //
  2962. // this is the standard non-Hydra related call block
  2963. //
  2964. {
  2965. HANDLE hRestrictedToken = NULL;
  2966. BOOL b = FALSE;
  2967. if (!CreateProcessInternalW(hToken,
  2968. lpApplicationName,
  2969. lpCommandLine,
  2970. lpProcessAttributes,
  2971. lpThreadAttributes,
  2972. bInheritHandles,
  2973. dwCreationFlags | CREATE_SUSPENDED ,
  2974. lpEnvironment,
  2975. lpCurrentDirectory,
  2976. lpStartupInfo,
  2977. lpProcessInformation,
  2978. &hRestrictedToken))
  2979. {
  2980. //
  2981. // The internal routine might return a token even in the failure case
  2982. // since it uses try-finally. Free the token if needed.
  2983. //
  2984. if (hRestrictedToken != NULL)
  2985. {
  2986. NtClose(hRestrictedToken);
  2987. }
  2988. return(FALSE);
  2989. }
  2990. CreateFlags |= (lpProcessAttributes ? 0 : COMMON_CREATE_PROCESSSD);
  2991. CreateFlags |= (lpThreadAttributes ? 0 : COMMON_CREATE_THREADSD);
  2992. if(lpProcessInformation->dwProcessId != 0) {
  2993. HANDLE VdmWaitHandle = NULL;
  2994. //
  2995. // Check if it is a shared wow being started
  2996. //
  2997. if((ULONG_PTR)lpProcessInformation->hProcess & 0x2) {
  2998. VdmWaitHandle = lpProcessInformation->hProcess;
  2999. lpProcessInformation->hProcess = OpenProcess(PROCESS_ALL_ACCESS,
  3000. FALSE,
  3001. lpProcessInformation->dwProcessId);
  3002. if (lpProcessInformation->hProcess == NULL)
  3003. {
  3004. //
  3005. // Couldn't open it. Try reverting since the new process gets security
  3006. // from the process token.
  3007. //
  3008. lpProcessInformation->hProcess = L32RevertOpenProcess(PROCESS_ALL_ACCESS,
  3009. FALSE,
  3010. lpProcessInformation->dwProcessId);
  3011. ASSERT(lpProcessInformation->hProcess);
  3012. }
  3013. }
  3014. //
  3015. // If a restricted token was returned, set it on the process.
  3016. // Else use the token provided by the caller.
  3017. //
  3018. if (hRestrictedToken == NULL)
  3019. {
  3020. b = (L32CommonCreate(CreateFlags, hToken, lpProcessInformation, lpProcessAttributes, lpThreadAttributes));
  3021. }
  3022. else
  3023. {
  3024. b = (L32CommonCreate(CreateFlags, hRestrictedToken, lpProcessInformation, lpProcessAttributes, lpThreadAttributes));
  3025. }
  3026. //
  3027. // if L32CommonCreate didn't succeed, it closes lpProcessInformation->hProcess and
  3028. // zeros out lpProcessInformation, so we shouldn't be closing it again if it didn't
  3029. // succeed.
  3030. if(b && VdmWaitHandle) {
  3031. if(lpProcessInformation->hProcess) {
  3032. NtClose(lpProcessInformation->hProcess);
  3033. }
  3034. lpProcessInformation->hProcess = VdmWaitHandle;
  3035. }
  3036. }
  3037. else {
  3038. b = TRUE;
  3039. }
  3040. if (hRestrictedToken) {
  3041. NtClose(hRestrictedToken);
  3042. }
  3043. return b;
  3044. }
  3045. }
  3046. /***************************************************************************\
  3047. * OemToCharW
  3048. *
  3049. * OemToCharW(pSrc, pDst) - Translates the OEM string at pSrc into
  3050. * the Unicode string at pDst. pSrc == pDst is not legal.
  3051. *
  3052. * History:
  3053. * This function was copied from NT\windows\Core\ntuser\client\oemxlate.c
  3054. *
  3055. \***************************************************************************/
  3056. BOOL WINAPI ConvertOemToCharW(
  3057. LPCSTR pSrc,
  3058. LPWSTR pDst)
  3059. {
  3060. int cch;
  3061. if (pSrc == NULL || pDst == NULL) {
  3062. return FALSE;
  3063. } else if (pSrc == (LPCSTR)pDst) {
  3064. /*
  3065. * MultiByteToWideChar() requires pSrc != pDst: fail this call.
  3066. * LATER: Is this really true?
  3067. */
  3068. return FALSE;
  3069. }
  3070. cch = strlen(pSrc) + 1;
  3071. MultiByteToWideChar(
  3072. CP_OEMCP, // Unicode -> OEM
  3073. MB_PRECOMPOSED | MB_USEGLYPHCHARS, // visual map to precomposed
  3074. (LPSTR)pSrc, cch, // source & length
  3075. pDst, // destination
  3076. cch); // max poss. precomposed length
  3077. return TRUE;
  3078. }
  3079. //----------------------------------------------------------------------------
  3080. //
  3081. // Function: OemToCharW_WithAllocation()
  3082. //
  3083. // Synopsis: This func will allocated memory for the string ppDst which
  3084. // must be then deallocatd thru a call to LocalFree().
  3085. // If the passed in ansi string is NULL, then no memory
  3086. // is allocated, and a NULL is returned
  3087. //
  3088. // Arguments:
  3089. // LPCSTR [in] ansi string for which we want the wide version
  3090. // *LPWSTR [out] the wide version of ansi string
  3091. // Return:
  3092. // BOOL : TRUE if no errors.
  3093. // BOOL : FALSE if unable to allocated memory.
  3094. //
  3095. //----------------------------------------------------------------------------
  3096. BOOL WINAPI OemToCharW_WithAllocation( LPCSTR pSrc,
  3097. LPWSTR *ppDst)
  3098. {
  3099. DWORD size;
  3100. if (pSrc)
  3101. {
  3102. size = strlen( pSrc );
  3103. *ppDst = ( WCHAR *) LocalAlloc(LMEM_FIXED, ( size + 1 ) * sizeof( WCHAR ) );
  3104. if ( ppDst )
  3105. {
  3106. ConvertOemToCharW( pSrc, *ppDst );
  3107. return TRUE;
  3108. }
  3109. else
  3110. return FALSE;
  3111. }
  3112. else
  3113. {
  3114. *ppDst = NULL;
  3115. return TRUE;
  3116. }
  3117. }
  3118. // ANSI wrapper for CreateRemoteSessionProcessW()
  3119. //
  3120. BOOL
  3121. CreateRemoteSessionProcessA(
  3122. ULONG SessionId,
  3123. BOOL System,
  3124. HANDLE hToken,
  3125. LPCSTR lpApplicationName,
  3126. LPSTR lpCommandLine,
  3127. LPSECURITY_ATTRIBUTES lpProcessAttributes,
  3128. LPSECURITY_ATTRIBUTES lpThreadAttributes,
  3129. BOOL bInheritHandles,
  3130. DWORD dwCreationFlags,
  3131. LPVOID lpEnvironment,
  3132. LPCSTR lpCurrentDirectory,
  3133. LPSTARTUPINFOA lpStartupInfo,
  3134. LPPROCESS_INFORMATION lpProcessInformation
  3135. )
  3136. {
  3137. NTSTATUS st;
  3138. BOOL rc,rc2;
  3139. STARTUPINFOW WCHAR_StartupInfo;
  3140. PWCHAR pWCHAR_AppName, pWCHAR_CommandLine, pWCHAR_CurDir, pWCHAR_Title, pWCHAR_Desktop;
  3141. pWCHAR_AppName = pWCHAR_CommandLine = pWCHAR_CurDir = pWCHAR_Title = pWCHAR_Desktop = NULL;
  3142. // in case there is a premature return from this function.
  3143. rc2 = FALSE;
  3144. if ( !( rc = OemToCharW_WithAllocation( lpApplicationName , &pWCHAR_AppName ) ))
  3145. {
  3146. goto Cleanup;
  3147. }
  3148. if ( !( rc = OemToCharW_WithAllocation( lpCommandLine , &pWCHAR_CommandLine ) ))
  3149. {
  3150. goto Cleanup;
  3151. }
  3152. if ( !( rc = OemToCharW_WithAllocation( lpCurrentDirectory , &pWCHAR_CurDir ) ))
  3153. {
  3154. goto Cleanup;
  3155. }
  3156. if ( !( rc = OemToCharW_WithAllocation( lpStartupInfo->lpTitle , &pWCHAR_Title ) ))
  3157. {
  3158. goto Cleanup;
  3159. }
  3160. if ( !( rc = OemToCharW_WithAllocation( lpStartupInfo->lpDesktop , &pWCHAR_Desktop ) ))
  3161. {
  3162. goto Cleanup;
  3163. }
  3164. WCHAR_StartupInfo.cb = lpStartupInfo->cb ;
  3165. WCHAR_StartupInfo.cbReserved2 = lpStartupInfo->cbReserved2;
  3166. WCHAR_StartupInfo.dwFillAttribute = lpStartupInfo->dwFillAttribute;
  3167. WCHAR_StartupInfo.dwFlags = lpStartupInfo->dwFlags;
  3168. WCHAR_StartupInfo.dwX = lpStartupInfo->dwX;
  3169. WCHAR_StartupInfo.dwXCountChars = lpStartupInfo->dwXCountChars;
  3170. WCHAR_StartupInfo.dwXSize = lpStartupInfo->dwXSize;
  3171. WCHAR_StartupInfo.dwY = lpStartupInfo->dwY;
  3172. WCHAR_StartupInfo.dwYCountChars = lpStartupInfo->dwYCountChars;
  3173. WCHAR_StartupInfo.dwYSize = lpStartupInfo->dwYSize;
  3174. WCHAR_StartupInfo.hStdError = lpStartupInfo->hStdError;
  3175. WCHAR_StartupInfo.hStdInput = lpStartupInfo->hStdInput;
  3176. WCHAR_StartupInfo.hStdOutput = lpStartupInfo->hStdOutput;
  3177. WCHAR_StartupInfo.lpReserved2 = lpStartupInfo->lpReserved2;
  3178. WCHAR_StartupInfo.wShowWindow = lpStartupInfo->wShowWindow;
  3179. WCHAR_StartupInfo.lpDesktop = pWCHAR_Desktop;
  3180. WCHAR_StartupInfo.lpReserved = NULL;
  3181. WCHAR_StartupInfo.lpTitle = pWCHAR_Title;
  3182. rc2 = CreateRemoteSessionProcessW(
  3183. SessionId,
  3184. System,
  3185. hToken,
  3186. pWCHAR_AppName ,
  3187. pWCHAR_CommandLine,
  3188. lpProcessAttributes,
  3189. lpThreadAttributes ,
  3190. bInheritHandles,
  3191. dwCreationFlags,
  3192. lpEnvironment,
  3193. pWCHAR_CurDir,
  3194. &WCHAR_StartupInfo,
  3195. lpProcessInformation
  3196. );
  3197. Cleanup:
  3198. if ( !rc ) // rc is set to FALSE if an attempted memory allocation has failed.
  3199. {
  3200. BaseSetLastNTError(STATUS_NO_MEMORY);
  3201. }
  3202. if (pWCHAR_AppName)
  3203. {
  3204. LocalFree( pWCHAR_AppName );
  3205. }
  3206. if (pWCHAR_CommandLine)
  3207. {
  3208. LocalFree( pWCHAR_CommandLine );
  3209. }
  3210. if (pWCHAR_CurDir)
  3211. {
  3212. LocalFree( pWCHAR_CurDir );
  3213. }
  3214. if (pWCHAR_Title)
  3215. {
  3216. LocalFree( pWCHAR_Title );
  3217. }
  3218. if (pWCHAR_Desktop)
  3219. {
  3220. LocalFree( pWCHAR_Desktop );
  3221. }
  3222. return rc2;
  3223. }
  3224. //+---------------------------------------------------------------------------
  3225. //
  3226. // Function: CreateProcessAsUserA
  3227. //
  3228. // Synopsis: ANSI wrapper for CreateProcessAsUserW
  3229. //
  3230. // Arguments: [hToken] --
  3231. // [lpApplicationName] --
  3232. // [lpCommandLine] --
  3233. // [lpProcessAttributes] --
  3234. // [lpThreadAttributes] --
  3235. // [bInheritHandles] --
  3236. // [dwCreationFlags] --
  3237. // [lpEnvironment] --
  3238. // [lpCurrentDirectory] --
  3239. // [lpStartupInfo] --
  3240. // [lpProcessInformation] --
  3241. //
  3242. // Return Values
  3243. // If the function succeeds, the return value is nonzero.
  3244. // If the function fails, the return value is zero. To get extended error information, call GetLastError.
  3245. //
  3246. // History: 4-25-95 RichardW Created
  3247. // 1-14-98 AraBern add changes for Hydra
  3248. //
  3249. // Notes:
  3250. //
  3251. //----------------------------------------------------------------------------
  3252. BOOL
  3253. WINAPI
  3254. CreateProcessAsUserA(
  3255. HANDLE hToken,
  3256. LPCSTR lpApplicationName,
  3257. LPSTR lpCommandLine,
  3258. LPSECURITY_ATTRIBUTES lpProcessAttributes,
  3259. LPSECURITY_ATTRIBUTES lpThreadAttributes,
  3260. BOOL bInheritHandles,
  3261. DWORD dwCreationFlags,
  3262. LPVOID lpEnvironment,
  3263. LPCSTR lpCurrentDirectory,
  3264. LPSTARTUPINFOA lpStartupInfo,
  3265. LPPROCESS_INFORMATION lpProcessInformation
  3266. )
  3267. {
  3268. DWORD CreateFlags;
  3269. DWORD clientSessionID=0;
  3270. DWORD currentSessionID=0;
  3271. DWORD resultLength;
  3272. HANDLE hTmpToken;
  3273. DWORD curProcId ;
  3274. NTSTATUS Status ;
  3275. CreateFlags = (dwCreationFlags & CREATE_SUSPENDED ? COMMON_CREATE_SUSPENDED : 0);
  3276. //
  3277. // get the session if (zero means console).
  3278. //
  3279. currentSessionID = NtCurrentPeb()->SessionId;
  3280. if ( !GetTokenInformation ( hToken, TokenSessionId , &clientSessionID,sizeof( DWORD), &resultLength ) )
  3281. {
  3282. //
  3283. // get the access token for the client of this call
  3284. // use get token instead of process since the client might have only
  3285. // impersonated the thread, not the process
  3286. //
  3287. DBG_DumpOutLastError;
  3288. ASSERT( FALSE );
  3289. currentSessionID = 0;
  3290. //
  3291. // We should probably return FALSE here, but at this time we don't want to alter the
  3292. // non-Hydra code-execution-flow at all.
  3293. //
  3294. }
  3295. KdPrint(("logon32.c: CreateProcessAsUserA(): clientSessionID = %d, currentSessionID = %d \n",
  3296. clientSessionID, currentSessionID ));
  3297. if ( ( clientSessionID != currentSessionID ))
  3298. {
  3299. //
  3300. // If the client session ID is not the same as the current session ID, then, we are attempting
  3301. // to create a process on a remote session from the current session.
  3302. // This block of code is used to accomplish such process creation, it is Terminal-Server specific
  3303. //
  3304. BOOL bHaveImpersonated;
  3305. HANDLE hCurrentThread;
  3306. HANDLE hPrevToken = NULL;
  3307. DWORD rc;
  3308. TOKEN_TYPE tokenType;
  3309. //
  3310. // We must send the request to the remote WinStation
  3311. // of the requestor
  3312. //
  3313. // NOTE: The current WinStationCreateProcessW() does not use
  3314. // the supplied security descriptor, but creates the
  3315. // process under the account of the logged on user.
  3316. //
  3317. //
  3318. // Stop impersonating before doing the WinStationCreateProcess.
  3319. // The remote winstation exec thread will launch the app under
  3320. // the users context. We must not be impersonating because this
  3321. // call only lets SYSTEM request the remote execute.
  3322. //
  3323. hCurrentThread = GetCurrentThread();
  3324. //
  3325. // Init bHaveImpersonated to the FALSE state
  3326. //
  3327. bHaveImpersonated = FALSE;
  3328. //
  3329. // Since the caller of this function (runas-> SecLogon service ) has already
  3330. // impersonated the new (target) user, we do the OpenThreadToken with
  3331. // OpenAsSelf = TRUE
  3332. //
  3333. if ( OpenThreadToken( hCurrentThread, TOKEN_QUERY | TOKEN_IMPERSONATE, TRUE, &hPrevToken ) )
  3334. {
  3335. bHaveImpersonated = TRUE;
  3336. if ( !RevertToSelf() )
  3337. {
  3338. return FALSE;
  3339. }
  3340. }
  3341. //
  3342. // else, we are not impersonating, as reflected by the init value of bHaveImpersonated
  3343. //
  3344. rc = CreateRemoteSessionProcessA(
  3345. clientSessionID,
  3346. FALSE, // not creating a process for System
  3347. hToken,
  3348. lpApplicationName,
  3349. lpCommandLine,
  3350. lpProcessAttributes,
  3351. lpThreadAttributes,
  3352. bInheritHandles,
  3353. dwCreationFlags,
  3354. lpEnvironment,
  3355. lpCurrentDirectory,
  3356. lpStartupInfo,
  3357. lpProcessInformation) ;
  3358. //
  3359. // Undo the effect of RevertToSelf() if we had impersoanted
  3360. //
  3361. if ( bHaveImpersonated )
  3362. {
  3363. Status = NtSetInformationThread(
  3364. NtCurrentThread(),
  3365. ThreadImpersonationToken,
  3366. &hPrevToken,
  3367. sizeof( hPrevToken ) );
  3368. ASSERT( NT_SUCCESS(Status ) );
  3369. NtClose( hPrevToken );
  3370. }
  3371. if ( rc )
  3372. {
  3373. return TRUE;
  3374. }
  3375. else
  3376. {
  3377. return FALSE;
  3378. }
  3379. }
  3380. else
  3381. //
  3382. // this is the standard non-Hydra related call block
  3383. //
  3384. {
  3385. HANDLE hRestrictedToken = NULL;
  3386. BOOL b = FALSE;
  3387. if (!CreateProcessInternalA(hToken,
  3388. lpApplicationName,
  3389. lpCommandLine,
  3390. lpProcessAttributes,
  3391. lpThreadAttributes,
  3392. bInheritHandles,
  3393. dwCreationFlags | CREATE_SUSPENDED,
  3394. lpEnvironment,
  3395. lpCurrentDirectory,
  3396. lpStartupInfo,
  3397. lpProcessInformation,
  3398. &hRestrictedToken))
  3399. {
  3400. //
  3401. // The internal routine might return a token even in the failure case
  3402. // since it uses try-finally. Free the token if needed.
  3403. //
  3404. if (hRestrictedToken != NULL)
  3405. {
  3406. NtClose(hRestrictedToken);
  3407. }
  3408. return(FALSE);
  3409. }
  3410. CreateFlags |= (lpProcessAttributes ? 0 : COMMON_CREATE_PROCESSSD);
  3411. CreateFlags |= (lpThreadAttributes ? 0 : COMMON_CREATE_THREADSD);
  3412. if(lpProcessInformation->dwProcessId != 0) {
  3413. HANDLE VdmWaitHandle = NULL;
  3414. //
  3415. // Check if it is a shared wow being started
  3416. //
  3417. if((ULONG_PTR)lpProcessInformation->hProcess & 0x2) {
  3418. VdmWaitHandle = lpProcessInformation->hProcess;
  3419. lpProcessInformation->hProcess = OpenProcess(PROCESS_ALL_ACCESS,
  3420. FALSE,
  3421. lpProcessInformation->dwProcessId);
  3422. if (lpProcessInformation->hProcess == NULL)
  3423. {
  3424. //
  3425. // Couldn't open it. Try reverting since the new process gets security
  3426. // from the process token.
  3427. //
  3428. lpProcessInformation->hProcess = L32RevertOpenProcess(PROCESS_ALL_ACCESS,
  3429. FALSE,
  3430. lpProcessInformation->dwProcessId);
  3431. ASSERT(lpProcessInformation->hProcess);
  3432. }
  3433. }
  3434. //
  3435. // If a restricted token was returned, set it on the process.
  3436. // Else use the token provided by the caller.
  3437. //
  3438. if (hRestrictedToken == NULL)
  3439. {
  3440. b = (L32CommonCreate(CreateFlags, hToken, lpProcessInformation, lpProcessAttributes, lpThreadAttributes));
  3441. }
  3442. else
  3443. {
  3444. b = (L32CommonCreate(CreateFlags, hRestrictedToken, lpProcessInformation, lpProcessAttributes, lpThreadAttributes));
  3445. }
  3446. //
  3447. // if L32CommonCreate didn't succeed, it closes lpProcessInformation->hProcess and
  3448. // zeros out lpProcessInformation, so we shouldn't be closing it again if it didn't
  3449. // succeed.
  3450. if(b && VdmWaitHandle) {
  3451. if(lpProcessInformation->hProcess) {
  3452. NtClose(lpProcessInformation->hProcess);
  3453. }
  3454. lpProcessInformation->hProcess = VdmWaitHandle;
  3455. }
  3456. }
  3457. else {
  3458. b = TRUE;
  3459. }
  3460. if (hRestrictedToken) {
  3461. NtClose(hRestrictedToken);
  3462. }
  3463. return b;
  3464. }
  3465. }