Source code of Windows XP (NT5)
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.

3818 lines
105 KiB

  1. //+-----------------------------------------------------------------------
  2. //
  3. // Microsoft Windows
  4. //
  5. // Copyright (c) Microsoft Corporation 1992 - 1999
  6. //
  7. // File: userapi.cxx
  8. //
  9. // Contents: User-mode APIs to the NtLm security package
  10. //
  11. // Main user mode entry points into this dll:
  12. // SpUserModeInitialize
  13. // SpInstanceInit
  14. // SpDeleteUserModeContext
  15. // SpInitUserModeContext
  16. // SpMakeSignature
  17. // SpVerifySignature
  18. // SpSealMessage
  19. // SpUnsealMessage
  20. // SpGetContextToken
  21. // SpQueryContextAttributes
  22. // SpCompleteAuthToken
  23. // SpFormatCredentials
  24. // SpMarshallSupplementalCreds
  25. // SpExportSecurityContext
  26. // SpImportSecurityContext
  27. //
  28. // Helper functions:
  29. // ReferenceUserContext
  30. // FreeUserContext
  31. // DereferenceUserContext
  32. // SspGenCheckSum
  33. // SspEncryptBuffer
  34. // NtLmMakePackedContext(this is called in the client's process)
  35. // NtLmCreateUserModeContext
  36. // SspGetTokenUser
  37. // SspCreateTokenDacl
  38. // SspMapContext (this is called in Lsa mode)
  39. //
  40. // History: ChandanS 26-Jul-1996 Stolen from kerberos\client2\userapi.cxx
  41. //
  42. //------------------------------------------------------------------------
  43. #include <global.h> // Globals!
  44. #include "crc32.h" // How to use crc32
  45. extern "C"
  46. {
  47. #include <nlp.h>
  48. }
  49. // Keep this is sync with NTLM_KERNEL_CONTEXT defined in
  50. // security\msv_sspi\kernel\krnlapi.cxx
  51. typedef struct _NTLM_CLIENT_CONTEXT{
  52. union {
  53. LIST_ENTRY Next;
  54. KSEC_LIST_ENTRY KernelNext;
  55. };
  56. ULONG_PTR LsaContext;
  57. ULONG NegotiateFlags;
  58. HANDLE ClientTokenHandle;
  59. PACCESS_TOKEN AccessToken;
  60. PULONG pSendNonce; // ptr to nonce to use for send
  61. PULONG pRecvNonce; // ptr to nonce to use for receive
  62. struct RC4_KEYSTRUCT * pSealRc4Sched; // ptr to key sched used for Seal
  63. struct RC4_KEYSTRUCT * pUnsealRc4Sched; // ptr to key sched used to Unseal
  64. ULONG SendNonce;
  65. ULONG RecvNonce;
  66. LPWSTR ContextNames;
  67. PUCHAR pbMarshalledTargetInfo;
  68. ULONG cbMarshalledTargetInfo;
  69. UCHAR SessionKey[MSV1_0_USER_SESSION_KEY_LENGTH];
  70. ULONG ContextSignature;
  71. ULONG References ;
  72. TimeStamp PasswordExpiry;
  73. ULONG UserFlags;
  74. UCHAR SignSessionKey[MSV1_0_USER_SESSION_KEY_LENGTH];
  75. UCHAR VerifySessionKey[MSV1_0_USER_SESSION_KEY_LENGTH];
  76. UCHAR SealSessionKey[MSV1_0_USER_SESSION_KEY_LENGTH];
  77. UCHAR UnsealSessionKey[MSV1_0_USER_SESSION_KEY_LENGTH];
  78. ULONG64 Pad1; // pad keystructs to 64.
  79. struct RC4_KEYSTRUCT SealRc4Sched; // key struct used for Seal
  80. ULONG64 Pad2; // pad keystructs to 64.
  81. struct RC4_KEYSTRUCT UnsealRc4Sched; // key struct used to Unseal
  82. } NTLM_CLIENT_CONTEXT, * PNTLM_CLIENT_CONTEXT;
  83. typedef struct _NTLM_PACKED_CONTEXT {
  84. ULONG Tag ;
  85. ULONG NegotiateFlags ;
  86. ULONG ClientTokenHandle ;
  87. ULONG SendNonce ;
  88. ULONG RecvNonce ;
  89. UCHAR SessionKey[ MSV1_0_USER_SESSION_KEY_LENGTH ];
  90. ULONG ContextSignature ;
  91. TimeStamp PasswordExpiry ;
  92. ULONG UserFlags ;
  93. ULONG ContextNames ;
  94. ULONG ContextNameLength ;
  95. ULONG MarshalledTargetInfo; // offset
  96. ULONG MarshalledTargetInfoLength;
  97. UCHAR SignSessionKey[ MSV1_0_USER_SESSION_KEY_LENGTH ];
  98. UCHAR VerifySessionKey[ MSV1_0_USER_SESSION_KEY_LENGTH ];
  99. UCHAR SealSessionKey[ MSV1_0_USER_SESSION_KEY_LENGTH ];
  100. UCHAR UnsealSessionKey[ MSV1_0_USER_SESSION_KEY_LENGTH ];
  101. struct RC4_KEYSTRUCT SealRc4Sched;
  102. struct RC4_KEYSTRUCT UnsealRc4Sched;
  103. } NTLM_PACKED_CONTEXT, * PNTLM_PACKED_CONTEXT ;
  104. #define NTLM_PACKED_CONTEXT_MAP 0
  105. #define NTLM_PACKED_CONTEXT_EXPORT 1
  106. #define CSSEALMAGIC "session key to client-to-server sealing key magic constant"
  107. #define SCSEALMAGIC "session key to server-to-client sealing key magic constant"
  108. #define CSSIGNMAGIC "session key to client-to-server signing key magic constant"
  109. #define SCSIGNMAGIC "session key to server-to-client signing key magic constant"
  110. #define NTLM_USERLIST_COUNT (16) // count of lists
  111. #define NTLM_USERLIST_LOCK_COUNT (2) // count of locks
  112. LIST_ENTRY NtLmUserContextList[ NTLM_USERLIST_COUNT ]; // list array.
  113. ULONG NtLmUserContextCount[ NTLM_USERLIST_COUNT ]; // count of active contexts
  114. RTL_RESOURCE NtLmUserContextLock[ NTLM_USERLIST_LOCK_COUNT ]; // lock array
  115. // Counter for exported handles;never de-refed
  116. // Should probably do a GetSystemInfo and get a space of handles that cannot
  117. // be valid in the Lsa process
  118. ULONG_PTR ExportedContext = 0;
  119. NTSTATUS
  120. SspCreateTokenDacl(
  121. HANDLE Token
  122. );
  123. ULONG
  124. HandleToListIndex(
  125. ULONG_PTR ContextHandle
  126. );
  127. ULONG
  128. __inline
  129. ListIndexToLockIndex(
  130. ULONG ListIndex
  131. );
  132. //+-------------------------------------------------------------------------
  133. //
  134. // Function: SpUserModeInitialize
  135. //
  136. // Synopsis: Initialize an the MSV1_0 DLL in a client's
  137. // address space
  138. //
  139. // Effects:
  140. //
  141. // Arguments: LsaVersion - Version of the security dll loading the package
  142. // PackageVersion - Version of the MSV1_0 package
  143. // UserFunctionTable - Receives a copy of Kerberos's user mode
  144. // function table
  145. // pcTables - Receives count of tables returned.
  146. //
  147. // Requires:
  148. //
  149. // Returns: STATUS_SUCCESS
  150. //
  151. // Notes: we do what was done in SspInitLocalContexts()
  152. // from net\svcdlls\ntlmssp\client\sign.c and more.
  153. //
  154. //
  155. //--------------------------------------------------------------------------
  156. NTSTATUS
  157. SEC_ENTRY
  158. SpUserModeInitialize(
  159. IN ULONG LsaVersion,
  160. OUT PULONG PackageVersion,
  161. OUT PSECPKG_USER_FUNCTION_TABLE * UserFunctionTable,
  162. OUT PULONG pcTables
  163. )
  164. {
  165. NTSTATUS Status = STATUS_SUCCESS;
  166. #if DBG
  167. SspGlobalDbflag = SSP_CRITICAL;
  168. if( NtLmState != NtLmLsaMode )
  169. {
  170. InitializeCriticalSection(&SspGlobalLogFileCritSect);
  171. }
  172. #endif
  173. if (LsaVersion != SECPKG_INTERFACE_VERSION)
  174. {
  175. Status = STATUS_INVALID_PARAMETER;
  176. goto Cleanup;
  177. }
  178. *PackageVersion = SECPKG_INTERFACE_VERSION;
  179. NtLmUserFunctionTable.InstanceInit = SpInstanceInit;
  180. NtLmUserFunctionTable.MakeSignature = SpMakeSignature;
  181. NtLmUserFunctionTable.VerifySignature = SpVerifySignature;
  182. NtLmUserFunctionTable.SealMessage = SpSealMessage;
  183. NtLmUserFunctionTable.UnsealMessage = SpUnsealMessage;
  184. NtLmUserFunctionTable.GetContextToken = SpGetContextToken;
  185. NtLmUserFunctionTable.QueryContextAttributes = SpQueryContextAttributes;
  186. NtLmUserFunctionTable.CompleteAuthToken = SpCompleteAuthToken;
  187. NtLmUserFunctionTable.InitUserModeContext = SpInitUserModeContext;
  188. NtLmUserFunctionTable.DeleteUserModeContext = SpDeleteUserModeContext;
  189. NtLmUserFunctionTable.FormatCredentials = SpFormatCredentials;
  190. NtLmUserFunctionTable.MarshallSupplementalCreds = SpMarshallSupplementalCreds;
  191. NtLmUserFunctionTable.ExportContext = SpExportSecurityContext;
  192. NtLmUserFunctionTable.ImportContext = SpImportSecurityContext;
  193. *UserFunctionTable = &NtLmUserFunctionTable;
  194. *pcTables = 1;
  195. if ( NtLmState != NtLmLsaMode)
  196. {
  197. //
  198. // SafeAllocaInitialize was already called in SpLsaModeInitialize
  199. //
  200. SafeAllocaInitialize(SAFEALLOCA_USE_DEFAULT,
  201. SAFEALLOCA_USE_DEFAULT,
  202. NtLmAllocate,
  203. NtLmFree);
  204. }
  205. Cleanup:
  206. return(SspNtStatusToSecStatus(Status, SEC_E_INTERNAL_ERROR));
  207. }
  208. //+-------------------------------------------------------------------------
  209. //
  210. // Function: ReferenceUserContext
  211. //
  212. // Synopsis: locates a user context in the list, refrences it
  213. //
  214. // Effects:
  215. //
  216. // Arguments:
  217. //
  218. // Requires:
  219. //
  220. // Returns: the context, if it is found, else NULL
  221. //
  222. // Notes: This was SspContextReferenceContext() in
  223. // net\svcdlls\ntlmssp\common\context.c
  224. //
  225. //
  226. //--------------------------------------------------------------------------
  227. PNTLM_CLIENT_CONTEXT
  228. ReferenceUserContext(
  229. IN ULONG_PTR ContextHandle,
  230. IN BOOLEAN RemoveContext )
  231. {
  232. SspPrint(( SSP_API_MORE, "Entering ReferenceUserContext for 0x%x\n", ContextHandle ));
  233. PLIST_ENTRY ListEntry;
  234. PNTLM_CLIENT_CONTEXT pContext = NULL;
  235. ULONG ListIndex;
  236. ULONG LockIndex;
  237. ListIndex = HandleToListIndex( ContextHandle );
  238. LockIndex = ListIndexToLockIndex( ListIndex );
  239. RtlAcquireResourceShared(&NtLmUserContextLock[LockIndex], TRUE);
  240. //
  241. // Look for a match for the LsaContext, not user context
  242. //
  243. for (ListEntry = NtLmUserContextList[ListIndex].Flink;
  244. ListEntry != &NtLmUserContextList[ListIndex];
  245. ListEntry = ListEntry->Flink ) {
  246. pContext = CONTAINING_RECORD(ListEntry, NTLM_CLIENT_CONTEXT, Next );
  247. if (pContext->LsaContext != ContextHandle)
  248. {
  249. continue;
  250. }
  251. //
  252. // Found it!
  253. //
  254. if (!RemoveContext)
  255. {
  256. InterlockedIncrement( (PLONG)&pContext->References );
  257. RtlReleaseResource(&NtLmUserContextLock[LockIndex]);
  258. }
  259. else
  260. {
  261. RtlConvertSharedToExclusive(&NtLmUserContextLock[LockIndex]);
  262. RemoveEntryList (&pContext->Next);
  263. NtLmUserContextCount[ListIndex]--;
  264. RtlReleaseResource(&NtLmUserContextLock[LockIndex]);
  265. SspPrint(( SSP_API_MORE, "Delinked Context 0x%lx\n", pContext ));
  266. }
  267. SspPrint(( SSP_API_MORE, "Leaving ReferenceUserContext for 0x%x\n", ContextHandle));
  268. return pContext;
  269. }
  270. // No match found
  271. RtlReleaseResource(&NtLmUserContextLock[LockIndex]);
  272. SspPrint(( SSP_API_MORE, "Leaving ReferenceUserContext for 0x%x\n", ContextHandle ));
  273. return NULL;
  274. }
  275. //+-------------------------------------------------------------------------
  276. //
  277. // Function: FreeUserContext
  278. //
  279. // Synopsis: frees alloced pointers in this context and
  280. // then frees the context
  281. //
  282. // Arguments: lContext - the unlinked user context
  283. //
  284. // Returns: STATUS_SUCCESS on success
  285. //
  286. // Notes:
  287. //
  288. //--------------------------------------------------------------------------
  289. NTSTATUS
  290. FreeUserContext (
  291. PNTLM_CLIENT_CONTEXT UserContext
  292. )
  293. {
  294. SspPrint(( SSP_API_MORE, "Entering FreeUserContext for context 0x%x\n", UserContext ));
  295. NTSTATUS Status = STATUS_SUCCESS;
  296. if (UserContext->ContextNames != NULL)
  297. {
  298. NtLmFree (UserContext->ContextNames);
  299. }
  300. if (UserContext->ClientTokenHandle != NULL)
  301. {
  302. NTSTATUS IgnoreStatus;
  303. IgnoreStatus = NtClose(UserContext->ClientTokenHandle);
  304. ASSERT (NT_SUCCESS (IgnoreStatus));
  305. }
  306. SspPrint(( SSP_API_MORE, "Deleting Context 0x%x\n", UserContext));
  307. ZeroMemory( UserContext, sizeof(*UserContext) );
  308. NtLmFree (UserContext);
  309. SspPrint(( SSP_API_MORE, "Leaving FreeUserContext for context 0x%x, status = 0x%x\n", Status ));
  310. return Status;
  311. }
  312. //+-------------------------------------------------------------------------
  313. //
  314. // Function: DereferenceUserContext
  315. //
  316. // Synopsis: frees alloced elements in the context, frees context
  317. //
  318. // Effects:
  319. //
  320. // Arguments:
  321. //
  322. // Requires:
  323. //
  324. // Returns: None
  325. //
  326. // Notes: This was SspContextDereferenceContext() in
  327. // net\svcdlls\ntlmssp\common\context.c
  328. //
  329. //
  330. //--------------------------------------------------------------------------
  331. NTSTATUS
  332. DereferenceUserContext (
  333. PNTLM_CLIENT_CONTEXT pContext
  334. )
  335. {
  336. SspPrint(( SSP_API_MORE, "Entering DereferenceUserContext 0x%lx\n", pContext ));
  337. NTSTATUS Status = STATUS_SUCCESS;
  338. LONG References;
  339. //
  340. // Decrement the reference count
  341. //
  342. /// RtlAcquireResourceShared(&NtLmUserContextLock, TRUE);
  343. //// ASSERT (pContext->References >= 1);
  344. //// References = -- pContext->References;
  345. References = InterlockedDecrement( (PLONG)&pContext->References );
  346. ASSERT( References >= 0 );
  347. //// RtlReleaseResource(&NtLmUserContextLock);
  348. //
  349. // If the count has dropped to zero, then free all alloced stuff
  350. //
  351. if (References == 0)
  352. {
  353. Status = FreeUserContext(pContext);
  354. }
  355. SspPrint(( SSP_API_MORE, "Leaving DereferenceUserContext\n" ));
  356. return Status;
  357. }
  358. //+-------------------------------------------------------------------------
  359. //
  360. // Function: SpInstanceInit
  361. //
  362. // Synopsis: Initialize an instance of the NtLm package in a client's
  363. // address space
  364. //
  365. // Effects:
  366. //
  367. // Arguments: Version - Version of the security dll loading the package
  368. // FunctionTable - Contains helper routines for use by NtLm
  369. // UserFunctions - Receives a copy of NtLm's user mode
  370. // function table
  371. //
  372. // Requires:
  373. //
  374. // Returns: STATUS_SUCCESS
  375. //
  376. // Notes: we do what was done in SspInitLocalContexts()
  377. // from net\svcdlls\ntlmssp\client\sign.c and more.
  378. //
  379. //
  380. //--------------------------------------------------------------------------
  381. NTSTATUS NTAPI
  382. SpInstanceInit(
  383. IN ULONG Version,
  384. IN PSECPKG_DLL_FUNCTIONS DllFunctionTable,
  385. OUT PVOID * UserFunctionTable
  386. )
  387. {
  388. SspPrint(( SSP_API, "Entering SpInstanceInit\n" ));
  389. NTSTATUS Status = STATUS_SUCCESS;
  390. ULONG Index;
  391. // Save the Alloc/Free functions
  392. if( NtLmState != NtLmLsaMode )
  393. {
  394. NtLmState = NtLmUserMode;
  395. }
  396. UserFunctions = DllFunctionTable;
  397. for( Index=0 ; Index < NTLM_USERLIST_COUNT ; Index++ )
  398. {
  399. InitializeListHead (&NtLmUserContextList[Index]);
  400. }
  401. for( Index=0 ; Index < NTLM_USERLIST_LOCK_COUNT ; Index++ )
  402. {
  403. __try {
  404. RtlInitializeResource (&NtLmUserContextLock[Index]);
  405. } __except(EXCEPTION_EXECUTE_HANDLER)
  406. {
  407. Status = STATUS_INSUFFICIENT_RESOURCES;
  408. break;
  409. }
  410. }
  411. SspPrint(( SSP_API, "Leaving SpInstanceInit: 0x%lx\n", Status ));
  412. return(SspNtStatusToSecStatus(Status, SEC_E_INTERNAL_ERROR));
  413. }
  414. //+-------------------------------------------------------------------------
  415. //
  416. // Function: SpDeleteUserModeContext
  417. //
  418. // Synopsis: Deletes a user mode context by unlinking it and then
  419. // dereferencing it.
  420. //
  421. // Effects:
  422. //
  423. // Arguments: ContextHandle - Lsa context handle of the context to delete
  424. //
  425. // Requires:
  426. //
  427. // Returns: STATUS_SUCCESS on success, STATUS_INVALID_HANDLE if the
  428. // context can't be located
  429. //
  430. // Notes:
  431. // If this is an exported context, send a flag back to the LSA so that
  432. // Lsa does not call the SecpDeleteSecurityContext in the lsa process
  433. //
  434. //
  435. //--------------------------------------------------------------------------
  436. NTSTATUS NTAPI
  437. SpDeleteUserModeContext(
  438. IN ULONG_PTR ContextHandle
  439. )
  440. {
  441. SspPrint(( SSP_API, "Entering SpDeleteUserModeContext 0x%lx\n", ContextHandle ));
  442. PNTLM_CLIENT_CONTEXT pContext = NULL;
  443. NTSTATUS Status = STATUS_SUCCESS, SaveStatus = STATUS_SUCCESS;
  444. //
  445. // Find the currently existing user context and delink it
  446. // so that another context cannot Reference it before we
  447. // Dereference this one.
  448. //
  449. pContext = ReferenceUserContext(ContextHandle, TRUE);
  450. if (pContext == NULL)
  451. {
  452. //
  453. // pContext is legally NULL when we are dealing with an incomplete
  454. // context. This can often be the case when the second call to
  455. // InitializeSecurityContext() fails.
  456. //
  457. /// Status = STATUS_INVALID_HANDLE;
  458. Status = STATUS_SUCCESS;
  459. SspPrint(( SSP_API_MORE, "SpDeleteUserModeContext, local pContext is NULL\n" ));
  460. goto CleanUp;
  461. }
  462. if ((pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_EXPORTED_CONTEXT) != 0)
  463. {
  464. // Ignore all other errors and pass back
  465. SaveStatus = SEC_I_NO_LSA_CONTEXT;
  466. }
  467. CleanUp:
  468. if (pContext != NULL)
  469. {
  470. Status = DereferenceUserContext(pContext);
  471. }
  472. if (SaveStatus == SEC_I_NO_LSA_CONTEXT)
  473. {
  474. Status = SaveStatus;
  475. }
  476. SspPrint(( SSP_API, "Leaving SpDeleteUserModeContext: 0x%lx\n", Status ));
  477. return(SspNtStatusToSecStatus(Status, SEC_E_INTERNAL_ERROR));
  478. }
  479. VOID
  480. SspRc4Key(
  481. IN ULONG NegotiateFlags,
  482. OUT struct RC4_KEYSTRUCT *pRc4Key,
  483. IN PUCHAR pSessionKey
  484. )
  485. /*++
  486. RoutineDescription:
  487. Create an RC4 key schedule, making sure key length is OK for export
  488. Arguments:
  489. NegotiateFlags negotiate feature flags; NTLM2 bit is only one looked at
  490. pRc4Key pointer to RC4 key schedule structure; filled in by this routine
  491. pSessionKey pointer to session key -- must be full 16 bytes
  492. Return Value:
  493. --*/
  494. {
  495. //
  496. // For NTLM2, effective length was already cut down
  497. //
  498. if ((NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM2) != 0) {
  499. rc4_key(pRc4Key, MSV1_0_USER_SESSION_KEY_LENGTH, pSessionKey);
  500. } else if( NegotiateFlags & NTLMSSP_NEGOTIATE_LM_KEY ) {
  501. UCHAR Key[MSV1_0_LANMAN_SESSION_KEY_LENGTH];
  502. ULONG KeyLen;
  503. ASSERT(MSV1_0_LANMAN_SESSION_KEY_LENGTH == 8);
  504. // prior to Win2k, negotiated key strength had no bearing on
  505. // key size. So, to allow proper interop to NT4, we don't
  506. // worry about 128bit. 56bit and 40bit are the only supported options.
  507. // 56bit is enabled because this was introduced in Win2k, and
  508. // Win2k -> Win2k interops correctly.
  509. //
  510. #if 0
  511. if( NegotiateFlags & NTLMSSP_NEGOTIATE_128 ) {
  512. KeyLen = 8;
  513. } else
  514. #endif
  515. if( NegotiateFlags & NTLMSSP_NEGOTIATE_56 ) {
  516. KeyLen = 7;
  517. //
  518. // Put a well-known salt at the end of the key to
  519. // limit the changing part to 56 bits.
  520. //
  521. Key[7] = 0xa0;
  522. } else {
  523. KeyLen = 5;
  524. //
  525. // Put a well-known salt at the end of the key to
  526. // limit the changing part to 40 bits.
  527. //
  528. Key[5] = 0xe5;
  529. Key[6] = 0x38;
  530. Key[7] = 0xb0;
  531. }
  532. RtlCopyMemory(Key,pSessionKey,KeyLen);
  533. SspPrint(( SSP_SESSION_KEYS, "Non NTLMv2 LM_KEY session key size: %lu key=%lx%lx\n",
  534. KeyLen,
  535. ((DWORD*)Key)[0],
  536. ((DWORD*)Key)[1]
  537. ));
  538. rc4_key(pRc4Key, MSV1_0_LANMAN_SESSION_KEY_LENGTH, Key);
  539. } else {
  540. SspPrint(( SSP_SESSION_KEYS, "Non NTLMv2 (not LM_KEY) session key size: %lu\n", 16));
  541. rc4_key(pRc4Key, MSV1_0_USER_SESSION_KEY_LENGTH, pSessionKey);
  542. }
  543. }
  544. //+-------------------------------------------------------------------------
  545. //
  546. // Function: SpInitUserModeContext
  547. //
  548. // Synopsis: Creates a user-mode context from a packed LSA mode context
  549. //
  550. // Effects:
  551. //
  552. // Arguments: ContextHandle - Lsa mode context handle for the context
  553. // PackedContext - A marshalled buffer containing the LSA
  554. // mode context.
  555. //
  556. // Requires:
  557. //
  558. // Returns: STATUS_SUCCESS or STATUS_INSUFFICIENT_RESOURCES
  559. //
  560. // Notes:
  561. //
  562. //
  563. //--------------------------------------------------------------------------
  564. NTSTATUS NTAPI
  565. SpInitUserModeContext(
  566. IN ULONG_PTR ContextHandle,
  567. IN PSecBuffer PackedContext
  568. )
  569. {
  570. ASSERT(PackedContext);
  571. SspPrint(( SSP_API, "Entering SpInitUserModeContext 0x%lx\n", ContextHandle ));
  572. NTSTATUS Status = STATUS_SUCCESS;
  573. PNTLM_CLIENT_CONTEXT pContext = NULL;
  574. UINT Length = 0;
  575. PNTLM_PACKED_CONTEXT pTmpContext = (PNTLM_PACKED_CONTEXT) PackedContext->pvBuffer;
  576. ULONG ListIndex;
  577. ULONG LockIndex;
  578. if (PackedContext->cbBuffer < sizeof(NTLM_PACKED_CONTEXT))
  579. {
  580. Status = STATUS_INVALID_PARAMETER;
  581. SspPrint(( SSP_CRITICAL, "SpInitUserModeContext, ContextData size < NTLM_CLIENT_CONTEXT\n" ));
  582. goto Cleanup;
  583. }
  584. pContext = (PNTLM_CLIENT_CONTEXT) NtLmAllocate( sizeof(NTLM_CLIENT_CONTEXT) );
  585. if (!pContext)
  586. {
  587. Status = STATUS_INSUFFICIENT_RESOURCES;
  588. SspPrint(( SSP_CRITICAL, "SpInitUserModeContext, NtLmAllocate returns NULL\n" ));
  589. goto Cleanup;
  590. }
  591. //
  592. // If ClientTokenHandle is NULL, we are being called as
  593. // as an effect of InitializeSecurityContext, else we are
  594. // being called because of AcceptSecurityContext
  595. //
  596. if (pTmpContext->ClientTokenHandle != NULL )
  597. {
  598. pContext->ClientTokenHandle = (HANDLE) ULongToPtr(pTmpContext->ClientTokenHandle);
  599. if (FAILED(SspCreateTokenDacl(pContext->ClientTokenHandle)))
  600. {
  601. Status = STATUS_INVALID_HANDLE;
  602. SspPrint(( SSP_CRITICAL, "SpInitUserModeContext, SspCreateTokenDacl failed\n" ));
  603. goto Cleanup;
  604. }
  605. }
  606. // Copy contents of PackedContext->pvBuffer to pContext
  607. pContext->LsaContext = ContextHandle;
  608. pContext->NegotiateFlags = pTmpContext->NegotiateFlags;
  609. SspPrint((SSP_NEGOTIATE_FLAGS, "SpInitUserModeContext NegotiateFlags: %lx\n", pContext->NegotiateFlags));
  610. pContext->References = 1;
  611. //
  612. // keep all 128 bits here, so signing can be strong even if encrypt can't be
  613. //
  614. RtlCopyMemory( pContext->SessionKey,
  615. pTmpContext->SessionKey,
  616. MSV1_0_USER_SESSION_KEY_LENGTH);
  617. //
  618. // if doing full duplex as part of NTLM2, generate different sign
  619. // and seal keys for each direction
  620. // all we do is MD5 the base session key with a different magic constant
  621. //
  622. if ( pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM2 ) {
  623. MD5_CTX Md5Context;
  624. ULONG KeyLen;
  625. ASSERT(MD5DIGESTLEN == MSV1_0_USER_SESSION_KEY_LENGTH);
  626. if( pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_128 )
  627. KeyLen = 16;
  628. else if( pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_56 )
  629. KeyLen = 7;
  630. else
  631. KeyLen = 5;
  632. SspPrint(( SSP_SESSION_KEYS, "NTLMv2 session key size: %lu\n", KeyLen));
  633. //
  634. // make client to server encryption key
  635. //
  636. MD5Init(&Md5Context);
  637. MD5Update(&Md5Context, pContext->SessionKey, KeyLen);
  638. MD5Update(&Md5Context, (unsigned char*)CSSEALMAGIC, sizeof(CSSEALMAGIC));
  639. MD5Final(&Md5Context);
  640. //
  641. // if TokenHandle == NULL, this is the client side
  642. // put key in the right place: for client it's seal, for server it's unseal
  643. //
  644. if (pContext->ClientTokenHandle == NULL)
  645. RtlCopyMemory(pContext->SealSessionKey, Md5Context.digest, MSV1_0_USER_SESSION_KEY_LENGTH);
  646. else
  647. RtlCopyMemory(pContext->UnsealSessionKey, Md5Context.digest, MSV1_0_USER_SESSION_KEY_LENGTH);
  648. //
  649. // make server to client encryption key
  650. //
  651. MD5Init(&Md5Context);
  652. MD5Update(&Md5Context, pContext->SessionKey, KeyLen);
  653. MD5Update(&Md5Context, (unsigned char*)SCSEALMAGIC, sizeof(SCSEALMAGIC));
  654. MD5Final(&Md5Context);
  655. ASSERT(MD5DIGESTLEN == MSV1_0_USER_SESSION_KEY_LENGTH);
  656. if (pContext->ClientTokenHandle == NULL)
  657. RtlCopyMemory(pContext->UnsealSessionKey, Md5Context.digest, MSV1_0_USER_SESSION_KEY_LENGTH);
  658. else
  659. RtlCopyMemory(pContext->SealSessionKey, Md5Context.digest, MSV1_0_USER_SESSION_KEY_LENGTH);
  660. //
  661. // make client to server signing key -- always 128 bits!
  662. //
  663. MD5Init(&Md5Context);
  664. MD5Update(&Md5Context, pContext->SessionKey, MSV1_0_USER_SESSION_KEY_LENGTH);
  665. MD5Update(&Md5Context, (unsigned char*)CSSIGNMAGIC, sizeof(CSSIGNMAGIC));
  666. MD5Final(&Md5Context);
  667. if (pContext->ClientTokenHandle == NULL)
  668. RtlCopyMemory(pContext->SignSessionKey, Md5Context.digest, MSV1_0_USER_SESSION_KEY_LENGTH);
  669. else
  670. RtlCopyMemory(pContext->VerifySessionKey, Md5Context.digest, MSV1_0_USER_SESSION_KEY_LENGTH);
  671. //
  672. // make server to client signing key
  673. //
  674. MD5Init(&Md5Context);
  675. MD5Update(&Md5Context, pContext->SessionKey, MSV1_0_USER_SESSION_KEY_LENGTH);
  676. MD5Update(&Md5Context, (unsigned char*)SCSIGNMAGIC, sizeof(SCSIGNMAGIC));
  677. MD5Final(&Md5Context);
  678. if (pContext->ClientTokenHandle == NULL)
  679. RtlCopyMemory(pContext->VerifySessionKey, Md5Context.digest, MSV1_0_USER_SESSION_KEY_LENGTH);
  680. else
  681. RtlCopyMemory(pContext->SignSessionKey, Md5Context.digest, MSV1_0_USER_SESSION_KEY_LENGTH);
  682. //
  683. // set pointers to different key schedule and nonce for each direction
  684. // key schedule will be filled in later...
  685. //
  686. pContext->pSealRc4Sched = &pContext->SealRc4Sched;
  687. pContext->pUnsealRc4Sched = &pContext->UnsealRc4Sched;
  688. pContext->pSendNonce = &pContext->SendNonce;
  689. pContext->pRecvNonce = &pContext->RecvNonce;
  690. } else {
  691. //
  692. // just copy session key to all four keys
  693. // leave them 128 bits -- they get cut to 40 bits later
  694. //
  695. RtlCopyMemory( pContext->SealSessionKey,
  696. pContext->SessionKey,
  697. MSV1_0_USER_SESSION_KEY_LENGTH);
  698. RtlCopyMemory( pContext->UnsealSessionKey,
  699. pContext->SessionKey,
  700. MSV1_0_USER_SESSION_KEY_LENGTH);
  701. RtlCopyMemory( pContext->SignSessionKey,
  702. pContext->SessionKey,
  703. MSV1_0_USER_SESSION_KEY_LENGTH);
  704. RtlCopyMemory( pContext->VerifySessionKey,
  705. pContext->SessionKey,
  706. MSV1_0_USER_SESSION_KEY_LENGTH);
  707. //
  708. // set pointers to share a key schedule and nonce for each direction
  709. // (OK because half duplex!)
  710. //
  711. pContext->pSealRc4Sched = &pContext->SealRc4Sched;
  712. pContext->pUnsealRc4Sched = &pContext->SealRc4Sched;
  713. pContext->pSendNonce = &pContext->SendNonce;
  714. pContext->pRecvNonce = &pContext->SendNonce;
  715. }
  716. if ( pTmpContext->ContextNames )
  717. {
  718. pContext->ContextNames = (PWSTR) NtLmAllocate( pTmpContext->ContextNameLength );
  719. if ( pContext->ContextNames == NULL )
  720. {
  721. Status = STATUS_INSUFFICIENT_RESOURCES ;
  722. goto Cleanup ;
  723. }
  724. RtlCopyMemory(
  725. pContext->ContextNames,
  726. ((PUCHAR) pTmpContext) + pTmpContext->ContextNames,
  727. pTmpContext->ContextNameLength );
  728. }
  729. else
  730. {
  731. pContext->ContextNames = NULL ;
  732. }
  733. pContext->SendNonce = pTmpContext->SendNonce;
  734. pContext->RecvNonce = pTmpContext->RecvNonce;
  735. SspRc4Key(pContext->NegotiateFlags, &pContext->SealRc4Sched, pContext->SealSessionKey);
  736. SspRc4Key(pContext->NegotiateFlags, &pContext->UnsealRc4Sched, pContext->UnsealSessionKey);
  737. pContext->PasswordExpiry = pTmpContext->PasswordExpiry;
  738. pContext->UserFlags = pTmpContext->UserFlags;
  739. ListIndex = HandleToListIndex( pContext->LsaContext );
  740. LockIndex = ListIndexToLockIndex( ListIndex );
  741. RtlAcquireResourceExclusive(&NtLmUserContextLock[LockIndex], TRUE);
  742. InsertHeadList ( &NtLmUserContextList[ListIndex], &pContext->Next );
  743. NtLmUserContextCount[ListIndex]++;
  744. RtlReleaseResource(&NtLmUserContextLock[LockIndex]);
  745. Cleanup:
  746. if (!NT_SUCCESS(Status))
  747. {
  748. if (pContext != NULL)
  749. {
  750. FreeUserContext(pContext);
  751. }
  752. }
  753. // Let FreeContextBuffer handle freeing the virtual allocs
  754. if (PackedContext->pvBuffer != NULL)
  755. {
  756. FreeContextBuffer(PackedContext->pvBuffer);
  757. PackedContext->pvBuffer = NULL;
  758. }
  759. SspPrint(( SSP_API, "Leaving SpInitUserModeContext: 0x%lx\n", Status ));
  760. return(SspNtStatusToSecStatus(Status, SEC_E_INTERNAL_ERROR));
  761. }
  762. //
  763. // Bogus add-shift check sum
  764. //
  765. void
  766. SspGenCheckSum(
  767. IN PSecBuffer pMessage,
  768. OUT PNTLMSSP_MESSAGE_SIGNATURE pSig
  769. )
  770. /*++
  771. RoutineDescription:
  772. Generate a crc-32 checksum for a buffer
  773. Arguments:
  774. Return Value:
  775. Notes: This was stolen from net\svcdlls\ntlmssp\client\sign.c ,
  776. routine SspGenCheckSum. It's possible that
  777. bugs got copied too
  778. --*/
  779. {
  780. Crc32(pSig->CheckSum,pMessage->cbBuffer,pMessage->pvBuffer,&pSig->CheckSum);
  781. }
  782. VOID
  783. SspEncryptBuffer(
  784. IN PNTLM_CLIENT_CONTEXT pContext,
  785. IN struct RC4_KEYSTRUCT * pRc4Key,
  786. IN ULONG BufferSize,
  787. IN OUT PVOID Buffer
  788. )
  789. /*++
  790. RoutineDescription:
  791. Encrypts a buffer with the RC4 key in the context. If the context
  792. is for a datagram session, then the key is copied before being used
  793. to encrypt the buffer.
  794. Arguments:
  795. pContext - Context containing the key to encrypt the data
  796. BufferSize - Length of buffer in bytes
  797. Buffer - Buffer to encrypt.
  798. Notes: This was stolen from net\svcdlls\ntlmssp\client\sign.c ,
  799. routine SspEncryptBuffer. It's possible that
  800. bugs got copied too
  801. Return Value:
  802. --*/
  803. {
  804. struct RC4_KEYSTRUCT TemporaryKey;
  805. /// struct RC4_KEYSTRUCT * EncryptionKey = &pContext->Rc4Key;
  806. struct RC4_KEYSTRUCT * EncryptionKey = pRc4Key;
  807. if (BufferSize == 0)
  808. {
  809. return;
  810. }
  811. //
  812. // For datagram (application supplied sequence numbers) before NTLM2
  813. // we used to copy the key before encrypting so we don't
  814. // have a changing key; but that reused the key stream. Now we only
  815. // do that when backwards compatibility is explicitly called for.
  816. //
  817. if (((pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_DATAGRAM) != 0) &&
  818. ((pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM2) == 0) ) {
  819. RtlCopyMemory(
  820. &TemporaryKey,
  821. EncryptionKey,
  822. sizeof(struct RC4_KEYSTRUCT)
  823. );
  824. EncryptionKey = &TemporaryKey;
  825. }
  826. rc4(
  827. EncryptionKey,
  828. BufferSize,
  829. (PUCHAR) Buffer
  830. );
  831. }
  832. typedef enum _eSignSealOp {
  833. eSign, // MakeSignature is calling
  834. eVerify, // VerifySignature is calling
  835. eSeal, // SealMessage is calling
  836. eUnseal // UnsealMessage is calling
  837. } eSignSealOp;
  838. SECURITY_STATUS
  839. SspSignSealHelper(
  840. IN PNTLM_CLIENT_CONTEXT pContext,
  841. IN eSignSealOp Op,
  842. IN OUT PSecBufferDesc pMessage,
  843. IN ULONG MessageSeqNo,
  844. OUT PNTLMSSP_MESSAGE_SIGNATURE pSig,
  845. OUT PNTLMSSP_MESSAGE_SIGNATURE * ppSig
  846. )
  847. /*++
  848. RoutineDescription:
  849. Handle signing a message
  850. Arguments:
  851. Return Value:
  852. --*/
  853. {
  854. HMACMD5_CTX HMACMD5Context;
  855. UCHAR TempSig[MD5DIGESTLEN];
  856. NTLMSSP_MESSAGE_SIGNATURE Sig;
  857. int Signature;
  858. ULONG i;
  859. PUCHAR pKey; // ptr to key to use for encryption
  860. PUCHAR pSignKey; // ptr to key to use for signing
  861. PULONG pNonce; // ptr to nonce to use
  862. struct RC4_KEYSTRUCT * pRc4Sched; // ptr to key schedule to use
  863. NTLMSSP_MESSAGE_SIGNATURE AlignedSig; // aligned copy of input sig data
  864. Signature = -1;
  865. for (i = 0; i < pMessage->cBuffers; i++)
  866. {
  867. if ((pMessage->pBuffers[i].BufferType & 0xFF) == SECBUFFER_TOKEN)
  868. {
  869. Signature = i;
  870. break;
  871. }
  872. }
  873. if (Signature == -1)
  874. {
  875. return(SEC_E_INVALID_TOKEN);
  876. }
  877. if (pMessage->pBuffers[Signature].cbBuffer < NTLMSSP_MESSAGE_SIGNATURE_SIZE)
  878. {
  879. return(SEC_E_INVALID_TOKEN);
  880. }
  881. *ppSig = (NTLMSSP_MESSAGE_SIGNATURE*)pMessage->pBuffers[Signature].pvBuffer;
  882. RtlCopyMemory( &AlignedSig, *ppSig, sizeof(AlignedSig) );
  883. //
  884. // If sequence detect wasn't requested, put on an empty
  885. // security token . Don't do the check if Seal/Unseal is called.
  886. //
  887. if (!(pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_SIGN) &&
  888. (Op == eSign || Op == eVerify))
  889. {
  890. RtlZeroMemory(pSig,NTLMSSP_MESSAGE_SIGNATURE_SIZE);
  891. pSig->Version = NTLM_SIGN_VERSION;
  892. return(SEC_E_OK);
  893. }
  894. // figure out which key, key schedule, and nonce to use
  895. // depends on the op. SspAddLocalContext set up so that code on client
  896. // and server just (un)seals with (un)seal key or key schedule, etc.
  897. // and also sets pointers to share sending/receiving key schedule/nonce
  898. // when in half duplex mode. Hence, this code gets to act as if it were
  899. // always in full duplex mode.
  900. switch (Op) {
  901. case eSeal:
  902. pSignKey = pContext->SignSessionKey; // if NTLM2
  903. pKey = pContext->SealSessionKey;
  904. pRc4Sched = pContext->pSealRc4Sched;
  905. pNonce = pContext->pSendNonce;
  906. break;
  907. case eUnseal:
  908. pSignKey = pContext->VerifySessionKey; // if NTLM2
  909. pKey = pContext->UnsealSessionKey;
  910. pRc4Sched = pContext->pUnsealRc4Sched;
  911. pNonce = pContext->pRecvNonce;
  912. break;
  913. case eSign:
  914. pSignKey = pContext->SignSessionKey; // if NTLM2
  915. pKey = pContext->SealSessionKey; // might be used to encrypt the signature
  916. pRc4Sched = pContext->pSealRc4Sched;
  917. pNonce = pContext->pSendNonce;
  918. break;
  919. case eVerify:
  920. pSignKey = pContext->VerifySessionKey; // if NTLM2
  921. pKey = pContext->UnsealSessionKey; // might be used to decrypt the signature
  922. pRc4Sched = pContext->pUnsealRc4Sched;
  923. pNonce = pContext->pRecvNonce;
  924. break;
  925. }
  926. //
  927. // Either we can supply the sequence number, or
  928. // the application can supply the message sequence number.
  929. //
  930. Sig.Version = NTLM_SIGN_VERSION;
  931. // if we're doing the new NTLM2 version:
  932. if (pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM2) {
  933. if ((pContext->NegotiateFlags & NTLMSSP_APP_SEQ) == 0)
  934. {
  935. Sig.Nonce = *pNonce; // use our sequence number
  936. (*pNonce) += 1;
  937. }
  938. else {
  939. if (Op == eSeal || Op == eSign || MessageSeqNo != 0)
  940. Sig.Nonce = MessageSeqNo;
  941. else
  942. Sig.Nonce = AlignedSig.Nonce;
  943. // if using RC4, must rekey for each packet
  944. // RC4 is used for seal, unseal; and for encrypting the HMAC hash if
  945. // key exchange was negotiated (we use just HMAC if no key exchange,
  946. // so that a good signing option exists with no RC4 encryption needed)
  947. if (Op == eSeal || Op == eUnseal || pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
  948. {
  949. MD5_CTX Md5ContextReKey;
  950. MD5Init(&Md5ContextReKey);
  951. MD5Update(&Md5ContextReKey, pKey, MSV1_0_USER_SESSION_KEY_LENGTH);
  952. MD5Update(&Md5ContextReKey, (unsigned char*)&Sig.Nonce, sizeof(Sig.Nonce));
  953. MD5Final(&Md5ContextReKey);
  954. ASSERT(MD5DIGESTLEN == MSV1_0_USER_SESSION_KEY_LENGTH);
  955. SspRc4Key(pContext->NegotiateFlags, pRc4Sched, Md5ContextReKey.digest);
  956. }
  957. }
  958. //
  959. // using HMAC hash, init it with the key
  960. //
  961. HMACMD5Init(&HMACMD5Context, pSignKey, MSV1_0_USER_SESSION_KEY_LENGTH);
  962. //
  963. // include the message sequence number
  964. //
  965. HMACMD5Update(&HMACMD5Context, (unsigned char*)&Sig.Nonce, sizeof(Sig.Nonce));
  966. for (i = 0; i < pMessage->cBuffers ; i++ )
  967. {
  968. if (((pMessage->pBuffers[i].BufferType & 0xFF) == SECBUFFER_DATA) &&
  969. (pMessage->pBuffers[i].cbBuffer != 0))
  970. {
  971. // decrypt (before checksum...) if it's not READ_ONLY
  972. if ((Op==eUnseal)
  973. && !(pMessage->pBuffers[i].BufferType & SECBUFFER_READONLY)
  974. )
  975. {
  976. SspEncryptBuffer(
  977. pContext,
  978. pRc4Sched,
  979. pMessage->pBuffers[i].cbBuffer,
  980. pMessage->pBuffers[i].pvBuffer
  981. );
  982. }
  983. HMACMD5Update(
  984. &HMACMD5Context,
  985. (unsigned char*)pMessage->pBuffers[i].pvBuffer,
  986. pMessage->pBuffers[i].cbBuffer);
  987. //
  988. // Encrypt if its not READ_ONLY
  989. //
  990. if ((Op==eSeal)
  991. && !(pMessage->pBuffers[i].BufferType & SECBUFFER_READONLY)
  992. )
  993. {
  994. SspEncryptBuffer(
  995. pContext,
  996. pRc4Sched,
  997. pMessage->pBuffers[i].cbBuffer,
  998. pMessage->pBuffers[i].pvBuffer
  999. );
  1000. }
  1001. }
  1002. }
  1003. HMACMD5Final(&HMACMD5Context, TempSig);
  1004. //
  1005. // use RandomPad and Checksum fields for 8 bytes of MD5 hash
  1006. //
  1007. RtlCopyMemory(&Sig.RandomPad, TempSig, 8);
  1008. //
  1009. // if we're using crypto for KEY_EXCH, may as well use it for signing too...
  1010. //
  1011. if (pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
  1012. SspEncryptBuffer(
  1013. pContext,
  1014. pRc4Sched,
  1015. 8,
  1016. &Sig.RandomPad
  1017. );
  1018. }
  1019. //
  1020. // pre-NTLM2 methods
  1021. //
  1022. else {
  1023. //
  1024. // required by CRC-32 algorithm
  1025. //
  1026. Sig.CheckSum = 0xffffffff;
  1027. for (i = 0; i < pMessage->cBuffers ; i++ )
  1028. {
  1029. if (((pMessage->pBuffers[i].BufferType & 0xFF) == SECBUFFER_DATA) &&
  1030. !(pMessage->pBuffers[i].BufferType & SECBUFFER_READONLY) &&
  1031. (pMessage->pBuffers[i].cbBuffer != 0))
  1032. {
  1033. // decrypt (before checksum...)
  1034. if (Op==eUnseal)
  1035. {
  1036. SspEncryptBuffer(
  1037. pContext,
  1038. pRc4Sched,
  1039. pMessage->pBuffers[i].cbBuffer,
  1040. pMessage->pBuffers[i].pvBuffer
  1041. );
  1042. }
  1043. SspGenCheckSum(&pMessage->pBuffers[i], &Sig);
  1044. // Encrypt
  1045. if (Op==eSeal)
  1046. {
  1047. SspEncryptBuffer(
  1048. pContext,
  1049. pRc4Sched,
  1050. pMessage->pBuffers[i].cbBuffer,
  1051. pMessage->pBuffers[i].pvBuffer
  1052. );
  1053. }
  1054. }
  1055. }
  1056. //
  1057. // Required by CRC-32 algorithm
  1058. //
  1059. Sig.CheckSum ^= 0xffffffff;
  1060. // when we encrypt 0, we will get the cipher stream for the nonce!
  1061. Sig.Nonce = 0;
  1062. SspEncryptBuffer(
  1063. pContext,
  1064. pRc4Sched,
  1065. sizeof(NTLMSSP_MESSAGE_SIGNATURE) - sizeof(ULONG),
  1066. &Sig.RandomPad
  1067. );
  1068. if ((pContext->NegotiateFlags & NTLMSSP_APP_SEQ) == 0)
  1069. {
  1070. Sig.Nonce ^= *pNonce; // use our sequence number and encrypt it
  1071. (*pNonce) += 1;
  1072. }
  1073. else if (Op == eSeal || Op == eSign || MessageSeqNo != 0)
  1074. Sig.Nonce ^= MessageSeqNo; // use caller's sequence number and encrypt it
  1075. else
  1076. Sig.Nonce = AlignedSig.Nonce; // use sender's sequence number
  1077. //
  1078. // for SignMessage calling, does nothing (copies garbage)
  1079. // For VerifyMessage calling, allows it to compare sig block
  1080. // upon return to Verify without knowing whether its MD5 or CRC32
  1081. //
  1082. Sig.RandomPad = AlignedSig.RandomPad;
  1083. }
  1084. pMessage->pBuffers[Signature].cbBuffer = sizeof(NTLMSSP_MESSAGE_SIGNATURE);
  1085. RtlCopyMemory(
  1086. pSig,
  1087. &Sig,
  1088. NTLMSSP_MESSAGE_SIGNATURE_SIZE
  1089. );
  1090. return(SEC_E_OK);
  1091. }
  1092. //+-------------------------------------------------------------------------
  1093. //
  1094. // Function: SpMakeSignature
  1095. //
  1096. // Synopsis: Signs a message buffer by calculatinga checksum over all
  1097. // the non-read only data buffers and encrypting the checksum
  1098. // along with a nonce.
  1099. //
  1100. // Effects:
  1101. //
  1102. // Arguments: ContextHandle - Handle of the context to use to sign the
  1103. // message.
  1104. // QualityOfProtection - Unused flags.
  1105. // MessageBuffers - Contains an array of buffers to sign and
  1106. // to store the signature.
  1107. // MessageSequenceNumber - Sequence number for this message,
  1108. // only used in datagram cases.
  1109. //
  1110. // Requires: STATUS_INVALID_HANDLE - the context could not be found or
  1111. // was not configured for message integrity.
  1112. // STATUS_INVALID_PARAMETER - the signature buffer could not
  1113. // be found.
  1114. // STATUS_BUFFER_TOO_SMALL - the signature buffer is too small
  1115. // to hold the signature
  1116. //
  1117. // Returns:
  1118. //
  1119. // Notes: This was stolen from net\svcdlls\ntlmssp\client\sign.c ,
  1120. // routine SspHandleSignMessage. It's possible that
  1121. // bugs got copied too
  1122. //
  1123. //
  1124. //--------------------------------------------------------------------------
  1125. NTSTATUS NTAPI
  1126. SpMakeSignature(
  1127. IN ULONG_PTR ContextHandle,
  1128. IN ULONG fQOP,
  1129. IN PSecBufferDesc pMessage,
  1130. IN ULONG MessageSeqNo
  1131. )
  1132. {
  1133. SspPrint(( SSP_API, "Entering SpMakeSignature\n" ));
  1134. NTSTATUS Status = S_OK;
  1135. NTSTATUS SubStatus = S_OK;
  1136. PNTLM_CLIENT_CONTEXT pContext;
  1137. NTLMSSP_MESSAGE_SIGNATURE Sig;
  1138. NTLMSSP_MESSAGE_SIGNATURE *pSig;
  1139. UNREFERENCED_PARAMETER(fQOP);
  1140. pContext = ReferenceUserContext(ContextHandle, FALSE);
  1141. if (pContext == NULL)
  1142. {
  1143. Status = STATUS_INVALID_HANDLE;
  1144. SspPrint(( SSP_CRITICAL, "SpMakeSignature, ReferenceUserContext returns NULL\n" ));
  1145. goto CleanUp;
  1146. }
  1147. Status = SspSignSealHelper(
  1148. pContext,
  1149. eSign,
  1150. pMessage,
  1151. MessageSeqNo,
  1152. &Sig,
  1153. &pSig
  1154. );
  1155. if( !NT_SUCCESS(Status) ) {
  1156. SspPrint(( SSP_CRITICAL, "SpMakeSignature, SspSignSealHelper returns %lx\n", Status ));
  1157. goto CleanUp;
  1158. }
  1159. RtlCopyMemory(
  1160. pSig,
  1161. &Sig,
  1162. NTLMSSP_MESSAGE_SIGNATURE_SIZE
  1163. );
  1164. CleanUp:
  1165. if (pContext != NULL)
  1166. {
  1167. SubStatus = DereferenceUserContext(pContext);
  1168. // Don't destroy real status
  1169. if (NT_SUCCESS(Status))
  1170. {
  1171. Status = SubStatus;
  1172. }
  1173. }
  1174. SspPrint(( SSP_API, "Leaving SpMakeSignature: 0x%lx\n", Status ));
  1175. return(SspNtStatusToSecStatus(Status, SEC_E_INTERNAL_ERROR));
  1176. }
  1177. //+-------------------------------------------------------------------------
  1178. //
  1179. // Function: SpVerifySignature
  1180. //
  1181. // Synopsis: Verifies a signed message buffer by calculating a checksum over all
  1182. // the non-read only data buffers and encrypting the checksum
  1183. // along with a nonce.
  1184. //
  1185. // Effects:
  1186. //
  1187. // Arguments: ContextHandle - Handle of the context to use to sign the
  1188. // message.
  1189. // MessageBuffers - Contains an array of signed buffers and
  1190. // a signature buffer.
  1191. // MessageSequenceNumber - Sequence number for this message,
  1192. // only used in datagram cases.
  1193. // QualityOfProtection - Unused flags.
  1194. //
  1195. // Requires: STATUS_INVALID_HANDLE - the context could not be found or
  1196. // was not configured for message integrity.
  1197. // STATUS_INVALID_PARAMETER - the signature buffer could not
  1198. // be found or was too small.
  1199. //
  1200. // Returns:
  1201. //
  1202. // Notes: This was stolen from net\svcdlls\ntlmssp\client\sign.c ,
  1203. // routine SspHandleVerifyMessage. It's possible that
  1204. // bugs got copied too
  1205. //
  1206. //
  1207. //--------------------------------------------------------------------------
  1208. NTSTATUS NTAPI
  1209. SpVerifySignature(
  1210. IN ULONG_PTR ContextHandle,
  1211. IN PSecBufferDesc pMessage,
  1212. IN ULONG MessageSeqNo,
  1213. OUT PULONG pfQOP
  1214. )
  1215. {
  1216. SspPrint(( SSP_API, "Entering SpVerifySignature\n" ));
  1217. NTSTATUS Status = S_OK;
  1218. NTSTATUS SubStatus = S_OK;
  1219. PNTLM_CLIENT_CONTEXT pContext;
  1220. NTLMSSP_MESSAGE_SIGNATURE Sig;
  1221. PNTLMSSP_MESSAGE_SIGNATURE pSig; // pointer to buffer with sig in it
  1222. NTLMSSP_MESSAGE_SIGNATURE AlignedSig; // Aligned sig buffer.
  1223. UNREFERENCED_PARAMETER(pfQOP);
  1224. pContext = ReferenceUserContext(ContextHandle, FALSE);
  1225. if (!pContext)
  1226. {
  1227. Status = STATUS_INVALID_HANDLE;
  1228. SspPrint(( SSP_CRITICAL, "SpVerifySignature, ReferenceUserContext returns NULL\n" ));
  1229. goto CleanUp;
  1230. }
  1231. Status = SspSignSealHelper(
  1232. pContext,
  1233. eVerify,
  1234. pMessage,
  1235. MessageSeqNo,
  1236. &Sig,
  1237. &pSig
  1238. );
  1239. if (!NT_SUCCESS(Status))
  1240. {
  1241. SspPrint(( SSP_CRITICAL, "SpVerifySignature, SspSignSealHelper returns %lx\n", Status ));
  1242. goto CleanUp;
  1243. }
  1244. RtlCopyMemory( &AlignedSig, pSig, sizeof( AlignedSig ) );
  1245. if (AlignedSig.Version != NTLM_SIGN_VERSION) {
  1246. SspPrint(( SSP_CRITICAL, "SpVerifySignature, unknown Version wanted=%lx got=%lx\n",
  1247. NTLM_SIGN_VERSION,
  1248. AlignedSig.Version
  1249. ));
  1250. Status = SEC_E_INVALID_TOKEN;
  1251. goto CleanUp;
  1252. }
  1253. // validate the signature...
  1254. if (AlignedSig.CheckSum != Sig.CheckSum)
  1255. {
  1256. SspPrint(( SSP_CRITICAL, "SpVerifySignature, CheckSum mis-match wanted=%lx got=%lx\n",
  1257. Sig.CheckSum,
  1258. AlignedSig.CheckSum
  1259. ));
  1260. Status = SEC_E_MESSAGE_ALTERED;
  1261. goto CleanUp;
  1262. }
  1263. // with MD5 sig, this now matters!
  1264. if (AlignedSig.RandomPad != Sig.RandomPad)
  1265. {
  1266. SspPrint(( SSP_CRITICAL, "SpVerifySignature, RandomPad mis-match wanted=%lx got=%lx\n",
  1267. Sig.RandomPad,
  1268. AlignedSig.RandomPad
  1269. ));
  1270. Status = SEC_E_MESSAGE_ALTERED;
  1271. goto CleanUp;
  1272. }
  1273. if (AlignedSig.Nonce != Sig.Nonce)
  1274. {
  1275. SspPrint(( SSP_CRITICAL, "SpVerifySignature, Nonce mis-match wanted=%lx got=%lx\n",
  1276. Sig.Nonce,
  1277. AlignedSig.Nonce
  1278. ));
  1279. Status = SEC_E_OUT_OF_SEQUENCE;
  1280. goto CleanUp;
  1281. }
  1282. CleanUp:
  1283. if (pContext != NULL)
  1284. {
  1285. SubStatus = DereferenceUserContext(pContext);
  1286. // Don't destroy real status
  1287. if (NT_SUCCESS(Status))
  1288. {
  1289. Status = SubStatus;
  1290. }
  1291. }
  1292. SspPrint(( SSP_API, "Leaving SpVerifySignature: 0x%lx\n", Status ));
  1293. return(SspNtStatusToSecStatus(Status, SEC_E_INTERNAL_ERROR));
  1294. }
  1295. //+-------------------------------------------------------------------------
  1296. //
  1297. // Function: SpSealMessage
  1298. //
  1299. // Synopsis: Verifies a signed message buffer by calculating a checksum over all
  1300. // the non-read only data buffers and encrypting the checksum
  1301. // along with a nonce.
  1302. //
  1303. // Effects:
  1304. //
  1305. // Arguments: ContextHandle - Handle of the context to use to sign the
  1306. // message.
  1307. // MessageBuffers - Contains an array of signed buffers and
  1308. // a signature buffer.
  1309. // MessageSequenceNumber - Sequence number for this message,
  1310. // only used in datagram cases.
  1311. // QualityOfProtection - Unused flags.
  1312. //
  1313. // Requires: STATUS_INVALID_HANDLE - the context could not be found or
  1314. // was not configured for message integrity.
  1315. // STATUS_INVALID_PARAMETER - the signature buffer could not
  1316. // be found or was too small.
  1317. //
  1318. // Returns:
  1319. //
  1320. // Notes: This was stolen from net\svcdlls\ntlmssp\client\sign.c ,
  1321. // routine SspHandleSealMessage. It's possible that
  1322. // bugs got copied too
  1323. //
  1324. //
  1325. //--------------------------------------------------------------------------
  1326. NTSTATUS NTAPI
  1327. SpSealMessage(
  1328. IN ULONG_PTR ContextHandle,
  1329. IN ULONG fQOP,
  1330. IN PSecBufferDesc pMessage,
  1331. IN ULONG MessageSeqNo
  1332. )
  1333. {
  1334. SspPrint(( SSP_API, "Entering SpSealMessage\n" ));
  1335. NTSTATUS Status = S_OK;
  1336. NTSTATUS SubStatus = S_OK;
  1337. PNTLM_CLIENT_CONTEXT pContext;
  1338. NTLMSSP_MESSAGE_SIGNATURE Sig;
  1339. PNTLMSSP_MESSAGE_SIGNATURE pSig; // pointer to buffer where sig goes
  1340. ULONG i;
  1341. UNREFERENCED_PARAMETER(fQOP);
  1342. pContext = ReferenceUserContext(ContextHandle, FALSE);
  1343. if (!pContext)
  1344. {
  1345. Status = STATUS_INVALID_HANDLE;
  1346. SspPrint(( SSP_CRITICAL, "SpSealMessage, ReferenceUserContext returns NULL\n" ));
  1347. goto CleanUp;
  1348. }
  1349. Status = SspSignSealHelper(
  1350. pContext,
  1351. eSeal,
  1352. pMessage,
  1353. MessageSeqNo,
  1354. &Sig,
  1355. &pSig
  1356. );
  1357. if (!NT_SUCCESS(Status))
  1358. {
  1359. SspPrint(( SSP_CRITICAL, "SpVerifySignature, SspSignSealHelper returns %lx\n", Status ));
  1360. goto CleanUp;
  1361. }
  1362. RtlCopyMemory(
  1363. pSig,
  1364. &Sig,
  1365. NTLMSSP_MESSAGE_SIGNATURE_SIZE
  1366. );
  1367. //
  1368. // for gss style sign/seal, strip the padding as RC4 requires none.
  1369. // (in fact, we rely on this to simplify the size computation in DecryptMessage).
  1370. // if we support some other block cipher, need to rev the NTLM_ token version to make blocksize
  1371. //
  1372. for (i = 0; i < pMessage->cBuffers; i++)
  1373. {
  1374. if ((pMessage->pBuffers[i].BufferType & 0xFF) == SECBUFFER_PADDING)
  1375. {
  1376. //
  1377. // no padding required!
  1378. //
  1379. pMessage->pBuffers[i].cbBuffer = 0;
  1380. break;
  1381. }
  1382. }
  1383. CleanUp:
  1384. if (pContext != NULL)
  1385. {
  1386. SubStatus = DereferenceUserContext(pContext);
  1387. // Don't destroy real status
  1388. if (NT_SUCCESS(Status))
  1389. {
  1390. Status = SubStatus;
  1391. }
  1392. }
  1393. SspPrint(( SSP_API, "Leaving SpSealMessage: 0x%lx\n", Status ));
  1394. return(SspNtStatusToSecStatus(Status, SEC_E_INTERNAL_ERROR));
  1395. }
  1396. //+-------------------------------------------------------------------------
  1397. //
  1398. // Function: SpUnsealMessage
  1399. //
  1400. // Synopsis: Verifies a signed message buffer by calculating a checksum over all
  1401. // the non-read only data buffers and encrypting the checksum
  1402. // along with a nonce.
  1403. //
  1404. // Effects:
  1405. //
  1406. // Arguments: ContextHandle - Handle of the context to use to sign the
  1407. // message.
  1408. // MessageBuffers - Contains an array of signed buffers and
  1409. // a signature buffer.
  1410. // MessageSequenceNumber - Sequence number for this message,
  1411. // only used in datagram cases.
  1412. // QualityOfProtection - Unused flags.
  1413. //
  1414. // Requires: STATUS_INVALID_HANDLE - the context could not be found or
  1415. // was not configured for message integrity.
  1416. // STATUS_INVALID_PARAMETER - the signature buffer could not
  1417. // be found or was too small.
  1418. //
  1419. // Returns:
  1420. //
  1421. // Notes: This was stolen from net\svcdlls\ntlmssp\client\sign.c ,
  1422. // routine SspHandleUnsealMessage. It's possible that
  1423. // bugs got copied too
  1424. //
  1425. //
  1426. //--------------------------------------------------------------------------
  1427. NTSTATUS NTAPI
  1428. SpUnsealMessage(
  1429. IN ULONG_PTR ContextHandle,
  1430. IN PSecBufferDesc pMessage,
  1431. IN ULONG MessageSeqNo,
  1432. OUT PULONG pfQOP
  1433. )
  1434. {
  1435. SspPrint(( SSP_API, "Entering SpUnsealMessage\n" ));
  1436. NTSTATUS Status = S_OK;
  1437. NTSTATUS SubStatus = S_OK;
  1438. PNTLM_CLIENT_CONTEXT pContext;
  1439. NTLMSSP_MESSAGE_SIGNATURE Sig;
  1440. PNTLMSSP_MESSAGE_SIGNATURE pSig; // pointer to buffer where sig goes
  1441. NTLMSSP_MESSAGE_SIGNATURE AlignedSig; // aligned buffer.
  1442. PSecBufferDesc MessageBuffers = pMessage;
  1443. ULONG Index;
  1444. PSecBuffer SignatureBuffer = NULL;
  1445. PSecBuffer StreamBuffer = NULL;
  1446. PSecBuffer DataBuffer = NULL;
  1447. SecBufferDesc ProcessBuffers;
  1448. SecBuffer wrap_bufs[2];
  1449. UNREFERENCED_PARAMETER(pfQOP);
  1450. pContext = ReferenceUserContext(ContextHandle, FALSE);
  1451. if (!pContext)
  1452. {
  1453. Status = STATUS_INVALID_HANDLE;
  1454. SspPrint(( SSP_CRITICAL, "SpUnsealMessage, ReferenceUserContext returns NULL\n" ));
  1455. goto CleanUp;
  1456. }
  1457. //
  1458. // Find the body and signature SecBuffers from pMessage
  1459. //
  1460. for (Index = 0; Index < MessageBuffers->cBuffers ; Index++ )
  1461. {
  1462. if ((MessageBuffers->pBuffers[Index].BufferType & ~SECBUFFER_ATTRMASK) == SECBUFFER_TOKEN)
  1463. {
  1464. SignatureBuffer = &MessageBuffers->pBuffers[Index];
  1465. }
  1466. else if ((MessageBuffers->pBuffers[Index].BufferType & ~SECBUFFER_ATTRMASK) == SECBUFFER_STREAM)
  1467. {
  1468. StreamBuffer = &MessageBuffers->pBuffers[Index];
  1469. }
  1470. else if ((MessageBuffers->pBuffers[Index].BufferType & ~SECBUFFER_ATTRMASK) == SECBUFFER_DATA)
  1471. {
  1472. DataBuffer = &MessageBuffers->pBuffers[Index];
  1473. }
  1474. }
  1475. if( StreamBuffer != NULL )
  1476. {
  1477. if( SignatureBuffer != NULL )
  1478. {
  1479. Status = SEC_E_INVALID_TOKEN;
  1480. SspPrint(( SSP_CRITICAL, "SpUnsealMessage, Both stream and signature buffer present.\n"));
  1481. goto CleanUp;
  1482. }
  1483. //
  1484. // for version 1 NTLM blobs, padding is never present, since RC4 is stream cipher.
  1485. //
  1486. wrap_bufs[0].cbBuffer = NTLMSSP_MESSAGE_SIGNATURE_SIZE;
  1487. wrap_bufs[1].cbBuffer = StreamBuffer->cbBuffer - NTLMSSP_MESSAGE_SIGNATURE_SIZE;
  1488. if( StreamBuffer->cbBuffer < wrap_bufs[0].cbBuffer )
  1489. {
  1490. Status = SEC_E_INVALID_TOKEN;
  1491. SspPrint(( SSP_CRITICAL, "SpUnsealMessage, invalid buffer present in STREAM.\n"));
  1492. goto CleanUp;
  1493. }
  1494. wrap_bufs[0].BufferType = SECBUFFER_TOKEN;
  1495. wrap_bufs[0].pvBuffer = StreamBuffer->pvBuffer;
  1496. wrap_bufs[1].BufferType = SECBUFFER_DATA;
  1497. wrap_bufs[1].pvBuffer = (PBYTE)wrap_bufs[0].pvBuffer + wrap_bufs[0].cbBuffer;
  1498. if( DataBuffer == NULL )
  1499. {
  1500. Status = SEC_E_INVALID_TOKEN;
  1501. SspPrint(( SSP_CRITICAL, "SpUnsealMessage, gss missing SECBUFFER_DATA.\n"));
  1502. goto CleanUp;
  1503. }
  1504. DataBuffer->cbBuffer = wrap_bufs[1].cbBuffer;
  1505. DataBuffer->pvBuffer = wrap_bufs[1].pvBuffer;
  1506. ProcessBuffers.cBuffers = 2;
  1507. ProcessBuffers.pBuffers = wrap_bufs;
  1508. ProcessBuffers.ulVersion = SECBUFFER_VERSION;
  1509. } else {
  1510. ProcessBuffers = *MessageBuffers;
  1511. }
  1512. Status = SspSignSealHelper(
  1513. pContext,
  1514. eUnseal,
  1515. &ProcessBuffers,
  1516. MessageSeqNo,
  1517. &Sig,
  1518. &pSig
  1519. );
  1520. if (!NT_SUCCESS(Status))
  1521. {
  1522. SspPrint(( SSP_CRITICAL, "SpUnsealMessage, SspSignSealHelper returns %lx\n", Status ));
  1523. goto CleanUp;
  1524. }
  1525. RtlCopyMemory( &AlignedSig, pSig, sizeof(AlignedSig) );
  1526. if (AlignedSig.Version != NTLM_SIGN_VERSION) {
  1527. SspPrint(( SSP_CRITICAL, "SpUnsealMessage, unknown Version wanted=%lx got=%lx\n",
  1528. NTLM_SIGN_VERSION,
  1529. AlignedSig.Version
  1530. ));
  1531. Status = SEC_E_INVALID_TOKEN;
  1532. goto CleanUp;
  1533. }
  1534. // validate the signature...
  1535. if (AlignedSig.CheckSum != Sig.CheckSum)
  1536. {
  1537. SspPrint(( SSP_CRITICAL, "SpUnsealMessage, CheckSum mis-match wanted=%lx got=%lx\n",
  1538. Sig.CheckSum,
  1539. AlignedSig.CheckSum
  1540. ));
  1541. Status = SEC_E_MESSAGE_ALTERED;
  1542. goto CleanUp;
  1543. }
  1544. if (AlignedSig.RandomPad != Sig.RandomPad)
  1545. {
  1546. SspPrint(( SSP_CRITICAL, "SpUnsealMessage, RandomPad mis-match wanted=%lx got=%lx\n",
  1547. Sig.RandomPad,
  1548. AlignedSig.RandomPad
  1549. ));
  1550. Status = SEC_E_MESSAGE_ALTERED;
  1551. goto CleanUp;
  1552. }
  1553. if (AlignedSig.Nonce != Sig.Nonce)
  1554. {
  1555. SspPrint(( SSP_CRITICAL, "SpUnsealMessage, Nonce mis-match wanted=%lx got=%lx\n",
  1556. Sig.Nonce,
  1557. AlignedSig.Nonce
  1558. ));
  1559. Status = SEC_E_OUT_OF_SEQUENCE;
  1560. goto CleanUp;
  1561. }
  1562. CleanUp:
  1563. if (pContext != NULL)
  1564. {
  1565. SubStatus = DereferenceUserContext(pContext);
  1566. // Don't destroy real status
  1567. if (NT_SUCCESS(Status))
  1568. {
  1569. Status = SubStatus;
  1570. }
  1571. }
  1572. SspPrint(( SSP_API, "Leaving SpUnsealMessage: 0x%lx\n", Status ));
  1573. return(SspNtStatusToSecStatus(Status, SEC_E_INTERNAL_ERROR));
  1574. }
  1575. //+-------------------------------------------------------------------------
  1576. //
  1577. // Function: SpGetContextToken
  1578. //
  1579. // Synopsis: returns a pointer to the token for a server-side context
  1580. //
  1581. // Effects:
  1582. //
  1583. // Arguments:
  1584. //
  1585. // Requires:
  1586. //
  1587. // Returns:
  1588. //
  1589. // Notes:
  1590. //
  1591. //
  1592. //--------------------------------------------------------------------------
  1593. NTSTATUS NTAPI
  1594. SpGetContextToken(
  1595. IN ULONG_PTR ContextHandle,
  1596. OUT PHANDLE ImpersonationToken
  1597. )
  1598. {
  1599. SspPrint(( SSP_API, "Entering SpGetContextToken\n" ));
  1600. NTSTATUS Status = S_OK;
  1601. PNTLM_CLIENT_CONTEXT pContext;
  1602. pContext = ReferenceUserContext(ContextHandle, FALSE);
  1603. if (pContext && pContext->ClientTokenHandle)
  1604. {
  1605. *ImpersonationToken = pContext->ClientTokenHandle;
  1606. Status= S_OK;
  1607. goto CleanUp;
  1608. }
  1609. Status = STATUS_INVALID_HANDLE;
  1610. SspPrint(( SSP_CRITICAL, "SpGetContextToken, no token handle\n" ));
  1611. CleanUp:
  1612. if (pContext != NULL)
  1613. {
  1614. Status = DereferenceUserContext(pContext);
  1615. }
  1616. SspPrint(( SSP_API, "Leaving SpGetContextToken: 0x%lx\n", Status ));
  1617. return(SspNtStatusToSecStatus(Status, SEC_E_INTERNAL_ERROR));
  1618. }
  1619. //+-------------------------------------------------------------------------
  1620. //
  1621. // Function: SpQueryContextAttributes
  1622. //
  1623. // Synopsis: Querys attributes of the specified context
  1624. // This API allows a customer of the security
  1625. // services to determine certain attributes of
  1626. // the context. These are: sizes, names, and lifespan.
  1627. //
  1628. // Effects:
  1629. //
  1630. // Arguments:
  1631. //
  1632. // ContextHandle - Handle to the context to query.
  1633. //
  1634. // Attribute - Attribute to query.
  1635. //
  1636. // #define SECPKG_ATTR_SIZES 0
  1637. // #define SECPKG_ATTR_NAMES 1
  1638. // #define SECPKG_ATTR_LIFESPAN 2
  1639. //
  1640. // Buffer - Buffer to copy the data into. The buffer must
  1641. // be large enough to fit the queried attribute.
  1642. //
  1643. //
  1644. // Requires:
  1645. //
  1646. // Returns:
  1647. //
  1648. // STATUS_SUCCESS - Call completed successfully
  1649. //
  1650. // STATUS_INVALID_HANDLE -- Credential/Context Handle is invalid
  1651. // STATUS_NOT_SUPPORTED -- Function code is not supported
  1652. //
  1653. // Notes:
  1654. //
  1655. //--------------------------------------------------------------------------
  1656. NTSTATUS NTAPI
  1657. SpQueryContextAttributes(
  1658. IN ULONG_PTR ContextHandle,
  1659. IN ULONG Attribute,
  1660. IN OUT PVOID Buffer
  1661. )
  1662. {
  1663. NTSTATUS Status = STATUS_SUCCESS;
  1664. PNTLM_CLIENT_CONTEXT pContext = NULL;
  1665. PSecPkgContext_Sizes ContextSizes;
  1666. PSecPkgContext_Flags ContextFlags;
  1667. PSecPkgContext_DceInfo ContextDceInfo = NULL;
  1668. PSecPkgContext_Names ContextNames = NULL;
  1669. PSecPkgContext_PackageInfo PackageInfo;
  1670. PSecPkgContext_NegotiationInfo NegInfo ;
  1671. PSecPkgContext_PasswordExpiry PasswordExpires;
  1672. PSecPkgContext_UserFlags UserFlags;
  1673. PSecPkgContext_SessionKey SessionKeyInfo;
  1674. PSecPkgContext_AccessToken AccessToken;
  1675. ULONG PackageInfoSize = 0;
  1676. SspPrint(( SSP_API, "Entering SpQueryContextAttributes\n" ));
  1677. pContext = ReferenceUserContext(ContextHandle, FALSE);
  1678. if (pContext == NULL) {
  1679. Status = STATUS_INVALID_HANDLE;
  1680. SspPrint(( SSP_API_MORE, "SpQueryContextAttributes, ReferenceUserContext returns NULL (possible incomplete context)\n" ));
  1681. goto Cleanup;
  1682. }
  1683. //
  1684. // Handle each of the various queried attributes
  1685. //
  1686. SspPrint(( SSP_API_MORE, "SpQueryContextAttributes : 0x%lx\n", Attribute ));
  1687. switch ( Attribute) {
  1688. case SECPKG_ATTR_SIZES:
  1689. ContextSizes = (PSecPkgContext_Sizes) Buffer;
  1690. ContextSizes->cbMaxToken = NTLMSP_MAX_TOKEN_SIZE;
  1691. if (pContext->NegotiateFlags & (NTLMSSP_NEGOTIATE_ALWAYS_SIGN |
  1692. NTLMSSP_NEGOTIATE_SIGN |
  1693. NTLMSSP_NEGOTIATE_SEAL) ) {
  1694. ContextSizes->cbMaxSignature = NTLMSSP_MESSAGE_SIGNATURE_SIZE;
  1695. } else {
  1696. ContextSizes->cbMaxSignature = 0;
  1697. }
  1698. if (pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_SEAL) {
  1699. ContextSizes->cbBlockSize = 1;
  1700. ContextSizes->cbSecurityTrailer = NTLMSSP_MESSAGE_SIGNATURE_SIZE;
  1701. }
  1702. else
  1703. {
  1704. ContextSizes->cbBlockSize = 0;
  1705. if((pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_SIGN) ||
  1706. (pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN))
  1707. {
  1708. ContextSizes->cbSecurityTrailer = NTLMSSP_MESSAGE_SIGNATURE_SIZE;
  1709. } else {
  1710. ContextSizes->cbSecurityTrailer = 0;
  1711. }
  1712. }
  1713. break;
  1714. case SECPKG_ATTR_DCE_INFO:
  1715. ContextDceInfo = (PSecPkgContext_DceInfo) Buffer;
  1716. if (pContext->ContextNames)
  1717. {
  1718. UINT Length = wcslen(pContext->ContextNames);
  1719. ContextDceInfo->pPac = (LPWSTR)UserFunctions->AllocateHeap((Length + 1) * sizeof(WCHAR));
  1720. if (ContextDceInfo->pPac == NULL) {
  1721. Status = STATUS_NO_MEMORY;
  1722. SspPrint(( SSP_CRITICAL, "SpQueryContextAttributes, NtLmAllocate returns NULL\n" ));
  1723. goto Cleanup;
  1724. }
  1725. RtlCopyMemory(
  1726. (LPWSTR) ContextDceInfo->pPac,
  1727. pContext->ContextNames,
  1728. Length * sizeof(WCHAR)
  1729. );
  1730. *((LPWSTR)(ContextDceInfo->pPac) + Length) = L'\0';
  1731. }
  1732. else
  1733. {
  1734. SspPrint(( SSP_API_MORE, "SpQueryContextAttributes no ContextNames\n" ));
  1735. ContextDceInfo->pPac = (LPWSTR) UserFunctions->AllocateHeap(sizeof(WCHAR));
  1736. *((LPWSTR)(ContextDceInfo->pPac)) = L'\0';
  1737. }
  1738. ContextDceInfo->AuthzSvc = 0;
  1739. break;
  1740. case SECPKG_ATTR_SESSION_KEY:
  1741. {
  1742. if (NtLmState != NtLmLsaMode)
  1743. {
  1744. Status = STATUS_INVALID_PARAMETER;
  1745. break;
  1746. }
  1747. SessionKeyInfo = (PSecPkgContext_SessionKey) Buffer;
  1748. SessionKeyInfo->SessionKeyLength = sizeof(pContext->SessionKey);
  1749. SessionKeyInfo->SessionKey = (PUCHAR) UserFunctions->AllocateHeap(
  1750. SessionKeyInfo->SessionKeyLength
  1751. );
  1752. if (SessionKeyInfo->SessionKey != NULL)
  1753. {
  1754. RtlCopyMemory(
  1755. SessionKeyInfo->SessionKey,
  1756. pContext->SessionKey,
  1757. SessionKeyInfo->SessionKeyLength
  1758. );
  1759. }
  1760. else
  1761. {
  1762. Status = STATUS_INSUFFICIENT_RESOURCES;
  1763. }
  1764. break;
  1765. }
  1766. case SECPKG_ATTR_NAMES:
  1767. ContextNames = (PSecPkgContext_Names) Buffer;
  1768. if (pContext->ContextNames)
  1769. {
  1770. UINT Length = wcslen(pContext->ContextNames);
  1771. ContextNames->sUserName = (LPWSTR) UserFunctions->AllocateHeap((Length+1) * sizeof(WCHAR));
  1772. if (ContextNames->sUserName == NULL) {
  1773. Status = STATUS_NO_MEMORY;
  1774. SspPrint(( SSP_CRITICAL, "SpQueryContextAttributes, NtLmAllocate returns NULL\n" ));
  1775. goto Cleanup;
  1776. }
  1777. RtlCopyMemory(
  1778. ContextNames->sUserName,
  1779. pContext->ContextNames,
  1780. Length * sizeof(WCHAR)
  1781. );
  1782. *(ContextNames->sUserName + Length) = L'\0';
  1783. }
  1784. else
  1785. {
  1786. SspPrint(( SSP_API_MORE, "SpQueryContextAttributes no ContextNames\n" ));
  1787. ContextNames->sUserName = (LPWSTR) UserFunctions->AllocateHeap(sizeof(WCHAR));
  1788. *(ContextNames->sUserName) = L'\0';
  1789. }
  1790. break;
  1791. case SECPKG_ATTR_PACKAGE_INFO:
  1792. case SECPKG_ATTR_NEGOTIATION_INFO:
  1793. //
  1794. // Return the information about this package. This is useful for
  1795. // callers who used SPNEGO and don't know what package they got.
  1796. //
  1797. PackageInfo = (PSecPkgContext_PackageInfo) Buffer;
  1798. PackageInfoSize = sizeof(SecPkgInfoW) + sizeof(NTLMSP_NAME) + sizeof(NTLMSP_COMMENT);
  1799. PackageInfo->PackageInfo = (PSecPkgInfoW) UserFunctions->AllocateHeap(PackageInfoSize);
  1800. if (PackageInfo->PackageInfo == NULL)
  1801. {
  1802. Status = STATUS_INSUFFICIENT_RESOURCES;
  1803. goto Cleanup;
  1804. }
  1805. PackageInfo->PackageInfo->Name = (LPWSTR) (PackageInfo->PackageInfo + 1);
  1806. PackageInfo->PackageInfo->Comment = (LPWSTR) ((((PBYTE) PackageInfo->PackageInfo->Name)) + sizeof(NTLMSP_NAME));
  1807. wcscpy(
  1808. PackageInfo->PackageInfo->Name,
  1809. NTLMSP_NAME
  1810. );
  1811. wcscpy(
  1812. PackageInfo->PackageInfo->Comment,
  1813. NTLMSP_COMMENT
  1814. );
  1815. PackageInfo->PackageInfo->wVersion = SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION;
  1816. PackageInfo->PackageInfo->wRPCID = RPC_C_AUTHN_WINNT;
  1817. PackageInfo->PackageInfo->fCapabilities = NTLMSP_CAPS;
  1818. PackageInfo->PackageInfo->cbMaxToken = NTLMSP_MAX_TOKEN_SIZE;
  1819. if ( Attribute == SECPKG_ATTR_NEGOTIATION_INFO )
  1820. {
  1821. NegInfo = (PSecPkgContext_NegotiationInfo) PackageInfo ;
  1822. NegInfo->NegotiationState = SECPKG_NEGOTIATION_COMPLETE ;
  1823. }
  1824. break;
  1825. case SECPKG_ATTR_PASSWORD_EXPIRY:
  1826. PasswordExpires = (PSecPkgContext_PasswordExpiry) Buffer;
  1827. if(pContext->PasswordExpiry.QuadPart != 0) {
  1828. PasswordExpires->tsPasswordExpires = pContext->PasswordExpiry;
  1829. } else {
  1830. Status = SEC_E_UNSUPPORTED_FUNCTION;
  1831. }
  1832. break;
  1833. case SECPKG_ATTR_USER_FLAGS:
  1834. UserFlags = (PSecPkgContext_UserFlags) Buffer;
  1835. UserFlags->UserFlags = pContext->UserFlags;
  1836. break;
  1837. case SECPKG_ATTR_FLAGS:
  1838. {
  1839. BOOLEAN Client = (pContext->ClientTokenHandle == 0);
  1840. ULONG Flags = 0;
  1841. //
  1842. // note: doesn't return all flags; by design.
  1843. //
  1844. ContextFlags = (PSecPkgContext_Flags) Buffer;
  1845. ContextFlags->Flags = 0;
  1846. if (pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_SEAL) {
  1847. if( Client )
  1848. {
  1849. Flags |= ISC_RET_CONFIDENTIALITY;
  1850. } else {
  1851. Flags |= ASC_RET_CONFIDENTIALITY;
  1852. }
  1853. }
  1854. if (pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_SIGN) {
  1855. if( Client )
  1856. {
  1857. Flags |= ISC_RET_SEQUENCE_DETECT | ISC_RET_REPLAY_DETECT | ISC_RET_INTEGRITY;
  1858. } else {
  1859. Flags |= ASC_RET_SEQUENCE_DETECT | ASC_RET_REPLAY_DETECT | ASC_RET_INTEGRITY;
  1860. }
  1861. }
  1862. if (pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_NULL_SESSION) {
  1863. if( Client )
  1864. {
  1865. Flags |= ISC_RET_NULL_SESSION;
  1866. } else {
  1867. Flags |= ASC_RET_NULL_SESSION;
  1868. }
  1869. }
  1870. if (pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_DATAGRAM) {
  1871. if( Client )
  1872. {
  1873. Flags |= ISC_RET_DATAGRAM;
  1874. } else {
  1875. Flags |= ASC_RET_DATAGRAM;
  1876. }
  1877. }
  1878. if (pContext->NegotiateFlags & NTLMSSP_NEGOTIATE_IDENTIFY) {
  1879. if( Client )
  1880. {
  1881. Flags |= ISC_RET_IDENTIFY;
  1882. } else {
  1883. Flags |= ASC_RET_IDENTIFY;
  1884. }
  1885. }
  1886. ContextFlags->Flags |= Flags;
  1887. break;
  1888. }
  1889. case SECPKG_ATTR_ACCESS_TOKEN:
  1890. AccessToken = (PSecPkgContext_AccessToken) Buffer;
  1891. //
  1892. // ClientTokenHandle can be NULL, for instance:
  1893. // 1. client side context.
  1894. // 2. incomplete server context.
  1895. //
  1896. if(pContext->ClientTokenHandle)
  1897. AccessToken->AccessToken = pContext->ClientTokenHandle;
  1898. else
  1899. Status = SEC_E_NO_IMPERSONATION;
  1900. break;
  1901. case SECPKG_ATTR_LIFESPAN:
  1902. default:
  1903. Status = STATUS_NOT_SUPPORTED;
  1904. break;
  1905. }
  1906. Cleanup:
  1907. if (!NT_SUCCESS(Status))
  1908. {
  1909. switch (Attribute) {
  1910. case SECPKG_ATTR_NAMES:
  1911. if (ContextNames != NULL && ContextNames->sUserName )
  1912. {
  1913. NtLmFree(ContextNames->sUserName);
  1914. }
  1915. break;
  1916. case SECPKG_ATTR_DCE_INFO:
  1917. if (ContextDceInfo != NULL && ContextDceInfo->pPac)
  1918. {
  1919. NtLmFree(ContextDceInfo->pPac);
  1920. }
  1921. break;
  1922. }
  1923. }
  1924. if (pContext != NULL)
  1925. {
  1926. (VOID) DereferenceUserContext(pContext);
  1927. }
  1928. SspPrint(( SSP_API, "Leaving SpQueryContextAttributes: 0x%lx\n", Status ));
  1929. return(SspNtStatusToSecStatus(Status, SEC_E_INTERNAL_ERROR));
  1930. }
  1931. //+-------------------------------------------------------------------------
  1932. //
  1933. // Function: SpCompleteAuthToken
  1934. //
  1935. // Synopsis: Completes a context
  1936. //
  1937. // Effects:
  1938. //
  1939. // Arguments:
  1940. //
  1941. // Requires:
  1942. //
  1943. // Returns:
  1944. //
  1945. // Notes:
  1946. //
  1947. //
  1948. //--------------------------------------------------------------------------
  1949. NTSTATUS NTAPI
  1950. SpCompleteAuthToken(
  1951. IN ULONG_PTR ContextHandle,
  1952. IN PSecBufferDesc InputBuffer
  1953. )
  1954. {
  1955. UNREFERENCED_PARAMETER (ContextHandle);
  1956. UNREFERENCED_PARAMETER (InputBuffer);
  1957. SspPrint(( SSP_API, "Entering SpCompleteAuthToken\n" ));
  1958. SspPrint(( SSP_API, "Leaving SpCompleteAuthToken\n" ));
  1959. return(SEC_E_UNSUPPORTED_FUNCTION);
  1960. }
  1961. NTSTATUS NTAPI
  1962. SpFormatCredentials(
  1963. IN PSecBuffer Credentials,
  1964. OUT PSecBuffer FormattedCredentials
  1965. )
  1966. {
  1967. UNREFERENCED_PARAMETER (Credentials);
  1968. UNREFERENCED_PARAMETER (FormattedCredentials);
  1969. SspPrint(( SSP_API, "Entering SpFormatCredentials\n" ));
  1970. SspPrint(( SSP_API, "Leaving SpFormatCredentials\n" ));
  1971. return(SEC_E_UNSUPPORTED_FUNCTION);
  1972. }
  1973. NTSTATUS NTAPI
  1974. SpMarshallSupplementalCreds(
  1975. IN ULONG CredentialSize,
  1976. IN PUCHAR Credentials,
  1977. OUT PULONG MarshalledCredSize,
  1978. OUT PVOID * MarshalledCreds
  1979. )
  1980. {
  1981. UNREFERENCED_PARAMETER (CredentialSize);
  1982. UNREFERENCED_PARAMETER (Credentials);
  1983. UNREFERENCED_PARAMETER (MarshalledCredSize);
  1984. UNREFERENCED_PARAMETER (MarshalledCreds);
  1985. SspPrint(( SSP_API, "Entering SpMarshallSupplementalCreds\n" ));
  1986. SspPrint(( SSP_API, "Leaving SpMarshallSupplementalCreds\n" ));
  1987. return(SEC_E_UNSUPPORTED_FUNCTION);
  1988. }
  1989. //+-------------------------------------------------------------------------
  1990. //
  1991. // Function: NtLmMakePackedContext
  1992. //
  1993. // Synopsis: Maps a context to the caller's address space
  1994. //
  1995. // Effects:
  1996. //
  1997. // Arguments: Context - The context to map
  1998. // MappedContext - Set to TRUE on success
  1999. // ContextData - Receives a buffer in the caller's address space
  2000. // with the mapped context.
  2001. //
  2002. // Requires:
  2003. //
  2004. // Returns:
  2005. //
  2006. // Notes:
  2007. //
  2008. //
  2009. //--------------------------------------------------------------------------
  2010. NTSTATUS
  2011. NtLmMakePackedContext(
  2012. IN PNTLM_CLIENT_CONTEXT Context,
  2013. OUT PBOOLEAN MappedContext,
  2014. OUT PSecBuffer ContextData,
  2015. IN ULONG Flags
  2016. )
  2017. {
  2018. NTSTATUS Status = STATUS_SUCCESS;
  2019. PNTLM_PACKED_CONTEXT PackedContext = NULL;
  2020. ULONG ContextSize, ContextNameSize = 0;
  2021. if (Context->ContextNames)
  2022. {
  2023. ContextNameSize = wcslen(Context->ContextNames);
  2024. }
  2025. ContextSize = sizeof(NTLM_CLIENT_CONTEXT) +
  2026. ContextNameSize * sizeof(WCHAR) + sizeof( WCHAR );
  2027. PackedContext = (PNTLM_PACKED_CONTEXT) NtLmAllocateLsaHeap( ContextSize );
  2028. if (PackedContext == NULL)
  2029. {
  2030. Status = STATUS_INSUFFICIENT_RESOURCES;
  2031. goto Cleanup;
  2032. }
  2033. // Copy all fields of the old context
  2034. PackedContext->Tag = NTLM_PACKED_CONTEXT_MAP ;
  2035. PackedContext->NegotiateFlags = Context->NegotiateFlags ;
  2036. PackedContext->SendNonce = Context->SendNonce ;
  2037. PackedContext->RecvNonce = Context->RecvNonce ;
  2038. RtlCopyMemory(
  2039. PackedContext->SessionKey,
  2040. Context->SessionKey,
  2041. MSV1_0_USER_SESSION_KEY_LENGTH );
  2042. PackedContext->ContextSignature = Context->ContextSignature ;
  2043. PackedContext->PasswordExpiry = Context->PasswordExpiry ;
  2044. PackedContext->UserFlags = Context->UserFlags ;
  2045. if ( ContextNameSize )
  2046. {
  2047. PackedContext->ContextNames = sizeof( NTLM_PACKED_CONTEXT );
  2048. PackedContext->ContextNameLength = (ContextNameSize + 1) * sizeof( WCHAR ) ;
  2049. RtlCopyMemory(
  2050. (PackedContext + 1),
  2051. Context->ContextNames,
  2052. PackedContext->ContextNameLength );
  2053. }
  2054. else
  2055. {
  2056. PackedContext->ContextNames = 0 ;
  2057. }
  2058. RtlCopyMemory(
  2059. PackedContext->SignSessionKey,
  2060. Context->SignSessionKey,
  2061. MSV1_0_USER_SESSION_KEY_LENGTH );
  2062. RtlCopyMemory(
  2063. PackedContext->VerifySessionKey,
  2064. Context->VerifySessionKey,
  2065. MSV1_0_USER_SESSION_KEY_LENGTH );
  2066. RtlCopyMemory(
  2067. PackedContext->SealSessionKey,
  2068. Context->SealSessionKey,
  2069. MSV1_0_USER_SESSION_KEY_LENGTH );
  2070. RtlCopyMemory(
  2071. PackedContext->UnsealSessionKey,
  2072. Context->SealSessionKey,
  2073. MSV1_0_USER_SESSION_KEY_LENGTH );
  2074. RtlCopyMemory(
  2075. &PackedContext->SealRc4Sched,
  2076. &Context->SealRc4Sched,
  2077. sizeof( struct RC4_KEYSTRUCT ) );
  2078. RtlCopyMemory(
  2079. &PackedContext->UnsealRc4Sched,
  2080. &Context->UnsealRc4Sched,
  2081. sizeof( struct RC4_KEYSTRUCT ) );
  2082. // Replace some fields
  2083. //
  2084. // Token will be returned by the caller of this routine
  2085. //
  2086. PackedContext->ClientTokenHandle = 0 ;
  2087. // Save the fact that it's exported
  2088. PackedContext->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXPORTED_CONTEXT;
  2089. ContextData->pvBuffer = PackedContext;
  2090. ContextData->cbBuffer = ContextSize;
  2091. *MappedContext = TRUE;
  2092. Status = STATUS_SUCCESS;
  2093. Cleanup:
  2094. if (!NT_SUCCESS(Status))
  2095. {
  2096. if (PackedContext != NULL)
  2097. {
  2098. NtLmFreeLsaHeap(PackedContext);
  2099. }
  2100. }
  2101. return(Status);
  2102. }
  2103. //+-------------------------------------------------------------------------
  2104. //
  2105. // Function: SpExportSecurityContext
  2106. //
  2107. // Synopsis: Exports a security context to another process
  2108. //
  2109. // Effects: Allocates memory for output
  2110. //
  2111. // Arguments: ContextHandle - handle to context to export
  2112. // Flags - Flags concerning duplication. Allowable flags:
  2113. // SECPKG_CONTEXT_EXPORT_DELETE_OLD - causes old context
  2114. // to be deleted.
  2115. // PackedContext - Receives serialized context to be freed with
  2116. // FreeContextBuffer
  2117. // TokenHandle - Optionally receives handle to context's token.
  2118. //
  2119. // Requires:
  2120. //
  2121. // Returns:
  2122. //
  2123. // Notes:
  2124. //
  2125. //
  2126. //--------------------------------------------------------------------------
  2127. NTSTATUS
  2128. SpExportSecurityContext(
  2129. IN ULONG_PTR ContextHandle,
  2130. IN ULONG Flags,
  2131. OUT PSecBuffer PackedContext,
  2132. OUT PHANDLE TokenHandle
  2133. )
  2134. {
  2135. PNTLM_CLIENT_CONTEXT Context = NULL ;
  2136. PNTLM_PACKED_CONTEXT pvContext = NULL;
  2137. NTSTATUS Status = STATUS_SUCCESS;
  2138. NTSTATUS SubStatus = STATUS_SUCCESS;
  2139. ULONG ContextSize = 0;
  2140. BOOLEAN MappedContext = FALSE;
  2141. SspPrint(( SSP_API,"Entering SpExportSecurityContext for context 0x%x\n", ContextHandle ));
  2142. if (ARGUMENT_PRESENT(TokenHandle))
  2143. {
  2144. *TokenHandle = NULL;
  2145. }
  2146. PackedContext->pvBuffer = NULL;
  2147. PackedContext->cbBuffer = 0;
  2148. PackedContext->BufferType = 0;
  2149. Context = ReferenceUserContext(
  2150. ContextHandle,
  2151. FALSE // don't unlink
  2152. );
  2153. if (Context == NULL)
  2154. {
  2155. SspPrint((SSP_CRITICAL, "SpExportSecurityContext: Invalid handle supplied (0x%x)\n",
  2156. ContextHandle));
  2157. Status = STATUS_INVALID_HANDLE;
  2158. goto Cleanup;
  2159. }
  2160. Status = NtLmMakePackedContext(
  2161. Context,
  2162. &MappedContext,
  2163. PackedContext,
  2164. Flags
  2165. );
  2166. if (!NT_SUCCESS(Status))
  2167. {
  2168. goto Cleanup;
  2169. }
  2170. ASSERT(MappedContext);
  2171. //
  2172. // Now either duplicate the token or copy it.
  2173. //
  2174. if (ARGUMENT_PRESENT(TokenHandle))
  2175. {
  2176. ULONG LockIndex;
  2177. LockIndex = ListIndexToLockIndex( HandleToListIndex( ContextHandle ) );
  2178. RtlAcquireResourceShared( &NtLmUserContextLock[LockIndex], TRUE );
  2179. if ((Flags & SECPKG_CONTEXT_EXPORT_DELETE_OLD) != 0)
  2180. {
  2181. RtlConvertSharedToExclusive( &NtLmUserContextLock[LockIndex] );
  2182. *TokenHandle = Context->ClientTokenHandle;
  2183. Context->ClientTokenHandle = NULL;
  2184. }
  2185. else
  2186. {
  2187. Status = NtDuplicateObject(
  2188. NtCurrentProcess(),
  2189. Context->ClientTokenHandle,
  2190. NULL,
  2191. TokenHandle,
  2192. 0, // no new access
  2193. 0, // no handle attributes
  2194. DUPLICATE_SAME_ACCESS
  2195. );
  2196. }
  2197. RtlReleaseResource( &NtLmUserContextLock[LockIndex] );
  2198. if (!NT_SUCCESS(Status))
  2199. {
  2200. goto Cleanup;
  2201. }
  2202. }
  2203. pvContext = (PNTLM_PACKED_CONTEXT) PackedContext->pvBuffer;
  2204. // Semantics of this flag: Export from here, but reset the Nonce.
  2205. // We zero out the session key, since all we need is the rc4 key.
  2206. if ((Flags & SECPKG_CONTEXT_EXPORT_RESET_NEW) != 0)
  2207. {
  2208. pvContext->SendNonce = (ULONG) -1;
  2209. pvContext->RecvNonce = (ULONG) -1;
  2210. }
  2211. RtlZeroMemory(
  2212. &pvContext->SessionKey,
  2213. MSV1_0_USER_SESSION_KEY_LENGTH
  2214. );
  2215. Cleanup:
  2216. if (Context != NULL)
  2217. {
  2218. SubStatus = DereferenceUserContext(Context);
  2219. // Don't destroy real status
  2220. if (NT_SUCCESS(Status))
  2221. {
  2222. Status = SubStatus;
  2223. }
  2224. }
  2225. SspPrint(( SSP_API,"Leaving SpExportContext: 0x%lx\n", Status ));
  2226. return(SspNtStatusToSecStatus(Status, SEC_E_INTERNAL_ERROR));
  2227. }
  2228. //+-------------------------------------------------------------------------
  2229. //
  2230. // Function: NtLmCreateUserModeContext
  2231. //
  2232. // Synopsis: Creates a user-mode context to support impersonation and
  2233. // message integrity and privacy
  2234. //
  2235. // Effects:
  2236. //
  2237. // Arguments:
  2238. //
  2239. // Requires:
  2240. //
  2241. // Returns:
  2242. //
  2243. // Notes:
  2244. //
  2245. //
  2246. //--------------------------------------------------------------------------
  2247. NTSTATUS
  2248. NtLmCreateUserModeContext(
  2249. IN ULONG_PTR ContextHandle,
  2250. IN HANDLE Token,
  2251. IN PSecBuffer MarshalledContext,
  2252. OUT PNTLM_CLIENT_CONTEXT * NewContext
  2253. )
  2254. {
  2255. NTSTATUS Status = STATUS_SUCCESS;
  2256. PNTLM_CLIENT_CONTEXT Context = NULL;
  2257. PNTLM_PACKED_CONTEXT PackedContext;
  2258. UINT Length = 0;
  2259. ULONG ListIndex;
  2260. ULONG LockIndex;
  2261. if (MarshalledContext->cbBuffer < sizeof(NTLM_PACKED_CONTEXT))
  2262. {
  2263. SspPrint((SSP_CRITICAL,"NtLmCreateUserModeContext: Invalid buffer size for marshalled context: was 0x%x, needed 0x%x\n",
  2264. MarshalledContext->cbBuffer, sizeof(NTLM_PACKED_CONTEXT)));
  2265. return(STATUS_INVALID_PARAMETER);
  2266. }
  2267. PackedContext = (PNTLM_PACKED_CONTEXT) MarshalledContext->pvBuffer;
  2268. Context = (PNTLM_CLIENT_CONTEXT)NtLmAllocate ( sizeof(NTLM_CLIENT_CONTEXT));
  2269. if (Context == NULL)
  2270. {
  2271. Status = STATUS_INSUFFICIENT_RESOURCES;
  2272. goto Cleanup;
  2273. }
  2274. Context->NegotiateFlags = PackedContext->NegotiateFlags ;
  2275. Context->SendNonce = PackedContext->SendNonce ;
  2276. Context->RecvNonce = PackedContext->RecvNonce ;
  2277. RtlCopyMemory(
  2278. Context->SessionKey,
  2279. PackedContext->SessionKey,
  2280. MSV1_0_USER_SESSION_KEY_LENGTH );
  2281. Context->ContextSignature = PackedContext->ContextSignature ;
  2282. Context->PasswordExpiry = PackedContext->PasswordExpiry ;
  2283. Context->UserFlags = PackedContext->UserFlags ;
  2284. if ( PackedContext->ContextNames )
  2285. {
  2286. Context->ContextNames = (PWSTR) NtLmAllocate( PackedContext->ContextNameLength );
  2287. if ( Context->ContextNames == NULL )
  2288. {
  2289. Status = STATUS_INSUFFICIENT_RESOURCES ;
  2290. goto Cleanup ;
  2291. }
  2292. RtlCopyMemory(
  2293. Context->ContextNames,
  2294. ((PUCHAR) PackedContext) + PackedContext->ContextNames,
  2295. PackedContext->ContextNameLength );
  2296. }
  2297. else
  2298. {
  2299. Context->ContextNames = NULL ;
  2300. }
  2301. RtlCopyMemory(
  2302. Context->SignSessionKey,
  2303. PackedContext->SignSessionKey,
  2304. MSV1_0_USER_SESSION_KEY_LENGTH );
  2305. RtlCopyMemory(
  2306. Context->VerifySessionKey,
  2307. PackedContext->VerifySessionKey,
  2308. MSV1_0_USER_SESSION_KEY_LENGTH );
  2309. RtlCopyMemory(
  2310. Context->SealSessionKey,
  2311. PackedContext->SealSessionKey,
  2312. MSV1_0_USER_SESSION_KEY_LENGTH );
  2313. RtlCopyMemory(
  2314. Context->UnsealSessionKey,
  2315. PackedContext->UnsealSessionKey,
  2316. MSV1_0_USER_SESSION_KEY_LENGTH );
  2317. RtlCopyMemory(
  2318. &Context->SealRc4Sched,
  2319. &PackedContext->SealRc4Sched,
  2320. sizeof( struct RC4_KEYSTRUCT ) );
  2321. RtlCopyMemory(
  2322. &Context->UnsealRc4Sched,
  2323. &PackedContext->UnsealRc4Sched,
  2324. sizeof( struct RC4_KEYSTRUCT ) );
  2325. // These need to be changed
  2326. Context->ClientTokenHandle = Token;
  2327. if (Context->SendNonce == (ULONG) -1)
  2328. {
  2329. Context->SendNonce = 0;
  2330. }
  2331. if (Context->RecvNonce == (ULONG) -1)
  2332. {
  2333. Context->RecvNonce = 0;
  2334. }
  2335. if ( Context->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM2 )
  2336. {
  2337. Context->pSealRc4Sched = &Context->SealRc4Sched;
  2338. Context->pUnsealRc4Sched = &Context->UnsealRc4Sched;
  2339. Context->pSendNonce = &Context->SendNonce;
  2340. Context->pRecvNonce = &Context->RecvNonce;
  2341. } else {
  2342. Context->pSealRc4Sched = &Context->SealRc4Sched;
  2343. Context->pUnsealRc4Sched = &Context->SealRc4Sched;
  2344. Context->pSendNonce = &Context->SendNonce;
  2345. Context->pRecvNonce = &Context->SendNonce;
  2346. }
  2347. Context->References = 2;
  2348. //
  2349. // Modify the DACL on the token to grant access to the caller
  2350. //
  2351. if (Context->ClientTokenHandle != NULL)
  2352. {
  2353. Status = SspCreateTokenDacl(
  2354. Context->ClientTokenHandle
  2355. );
  2356. if (!NT_SUCCESS(Status))
  2357. {
  2358. goto Cleanup;
  2359. }
  2360. }
  2361. // Dummy up an lsa handle by incrementing a global variable. This
  2362. // will ensure that each imported context has a unique handle.
  2363. // Skip over values that could be interpreted as an aligned pointer,
  2364. // so that they won't get mixed up with real lsa handles.
  2365. Context->LsaContext = InterlockedIncrement((PLONG)&ExportedContext);
  2366. while(Context->LsaContext % MAX_NATURAL_ALIGNMENT == 0)
  2367. {
  2368. Context->LsaContext = InterlockedIncrement((PLONG)&ExportedContext);
  2369. }
  2370. ListIndex = HandleToListIndex( Context->LsaContext );
  2371. LockIndex = ListIndexToLockIndex( ListIndex );
  2372. RtlAcquireResourceExclusive(&NtLmUserContextLock[LockIndex], TRUE);
  2373. InsertHeadList ( &NtLmUserContextList[ListIndex], &Context->Next );
  2374. NtLmUserContextCount[ListIndex]++;
  2375. RtlReleaseResource(&NtLmUserContextLock[LockIndex]);
  2376. *NewContext = Context;
  2377. Cleanup:
  2378. if (!NT_SUCCESS(Status))
  2379. {
  2380. if (Context != NULL)
  2381. {
  2382. FreeUserContext(Context);
  2383. }
  2384. }
  2385. return(Status);
  2386. }
  2387. //+-------------------------------------------------------------------------
  2388. //
  2389. // Function: SpImportSecurityContext
  2390. //
  2391. // Synopsis:
  2392. //
  2393. // Effects:
  2394. //
  2395. // Arguments:
  2396. //
  2397. // Requires:
  2398. //
  2399. // Returns:
  2400. //
  2401. // Notes:
  2402. //
  2403. //
  2404. //--------------------------------------------------------------------------
  2405. NTSTATUS
  2406. SpImportSecurityContext(
  2407. IN PSecBuffer PackedContext,
  2408. IN HANDLE Token,
  2409. OUT PULONG_PTR ContextHandle
  2410. )
  2411. {
  2412. NTSTATUS Status = STATUS_SUCCESS;
  2413. NTSTATUS SubStatus = STATUS_SUCCESS;
  2414. PNTLM_CLIENT_CONTEXT Context = NULL;
  2415. SspPrint(( SSP_API,"Entering SpImportSecurityContext\n"));
  2416. Status = NtLmCreateUserModeContext(
  2417. 0, // no lsa context
  2418. Token,
  2419. PackedContext,
  2420. &Context
  2421. );
  2422. if (!NT_SUCCESS(Status))
  2423. {
  2424. SspPrint((SSP_CRITICAL,"SpImportSecurityContext: Failed to create user mode context: 0x%x\n",
  2425. Status));
  2426. goto Cleanup;
  2427. }
  2428. *ContextHandle = Context->LsaContext;
  2429. Cleanup:
  2430. if (Context != NULL)
  2431. {
  2432. SubStatus = DereferenceUserContext(Context);
  2433. // Don't destroy real status
  2434. if (NT_SUCCESS(Status))
  2435. {
  2436. Status = SubStatus;
  2437. }
  2438. }
  2439. SspPrint(( SSP_API,"Leaving SpImportSecurityContext: 0x%lx\n", Status));
  2440. return(SspNtStatusToSecStatus(Status, SEC_E_INTERNAL_ERROR));
  2441. }
  2442. NTSTATUS
  2443. SspGetTokenUser(
  2444. HANDLE Token,
  2445. PTOKEN_USER pTokenUser,
  2446. PULONG TokenUserSize
  2447. )
  2448. /*++
  2449. RoutineDescription:
  2450. Gets the TOKEN_USER from an open token
  2451. Arguments:
  2452. Token - Handle to a token open for TOKEN_QUERY access
  2453. Return Value:
  2454. STATUS_INSUFFICIENT_RESOURCES - not enough memory to complete the
  2455. function.
  2456. Errors from NtQueryInformationToken.
  2457. --*/
  2458. {
  2459. NTSTATUS Status;
  2460. Status = NtQueryInformationToken(
  2461. Token,
  2462. TokenUser,
  2463. pTokenUser,
  2464. *TokenUserSize,
  2465. TokenUserSize
  2466. );
  2467. return(Status);
  2468. }
  2469. NTSTATUS
  2470. SspCreateTokenDacl(
  2471. HANDLE Token
  2472. )
  2473. /*++
  2474. RoutineDescription:
  2475. Creates a new DACL for the token granting the server and client
  2476. all access to the token.
  2477. Arguments:
  2478. Token - Handle to an impersonation token open for TOKEN_QUERY and
  2479. WRITE_DAC
  2480. Return Value:
  2481. STATUS_INSUFFICIENT_RESOURCES - insufficient memory to complete
  2482. the function.
  2483. Errors from NtSetSecurityObject
  2484. --*/
  2485. {
  2486. NTSTATUS Status;
  2487. PTOKEN_USER ThreadTokenUser;
  2488. PTOKEN_USER ImpersonationTokenUser = NULL;
  2489. PTOKEN_USER SlowProcessTokenUser = NULL;
  2490. PTOKEN_USER SlowThreadTokenUser = NULL;
  2491. PTOKEN_USER SlowImpersonationTokenUser = NULL;
  2492. ULONG_PTR FastThreadTokenUser[ 128/sizeof(ULONG_PTR) ];
  2493. ULONG_PTR FastImpersonationTokenUser[ 128/sizeof(ULONG_PTR) ];
  2494. ULONG TokenUserSize;
  2495. HANDLE ProcessToken = NULL;
  2496. HANDLE ImpersonationToken = NULL;
  2497. BOOL fInsertImpersonatingUser = FALSE;
  2498. SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
  2499. ULONG AclLength;
  2500. PACL NewDacl;
  2501. PACL SlowNewDacl = NULL;
  2502. ULONG_PTR FastNewDacl[ 512/sizeof(ULONG_PTR) ];
  2503. SECURITY_DESCRIPTOR SecurityDescriptor;
  2504. //
  2505. // Build the two well known sids we need.
  2506. //
  2507. if (NtLmGlobalLocalSystemSid == NULL)
  2508. {
  2509. PSID pLocalSidSystem;
  2510. PSID pOldSid;
  2511. Status = RtlAllocateAndInitializeSid(
  2512. &NtAuthority,
  2513. 1,
  2514. SECURITY_LOCAL_SYSTEM_RID,
  2515. 0,0,0,0,0,0,0,
  2516. &pLocalSidSystem
  2517. );
  2518. if (!NT_SUCCESS(Status))
  2519. {
  2520. SspPrint(( SSP_CRITICAL, "SspCreateTokenDacl, RtlAllocateAndInitializeSid returns 0x%lx\n", Status ));
  2521. goto Cleanup;
  2522. }
  2523. pOldSid = InterlockedCompareExchangePointer(
  2524. &NtLmGlobalLocalSystemSid,
  2525. pLocalSidSystem,
  2526. NULL
  2527. );
  2528. if( pOldSid )
  2529. {
  2530. RtlFreeSid( pLocalSidSystem );
  2531. }
  2532. }
  2533. if (NtLmGlobalAliasAdminsSid == NULL)
  2534. {
  2535. PSID pLocalSidAdmins;
  2536. PSID pOldSid;
  2537. Status = RtlAllocateAndInitializeSid(
  2538. &NtAuthority,
  2539. 2,
  2540. SECURITY_BUILTIN_DOMAIN_RID,
  2541. DOMAIN_ALIAS_RID_ADMINS,
  2542. 0,0,0,0,0,0,
  2543. &pLocalSidAdmins
  2544. );
  2545. if (!NT_SUCCESS(Status))
  2546. {
  2547. SspPrint(( SSP_CRITICAL, "SspCreateTokenDacl, RtlAllocateAndInitializeSid returns 0x%lx\n", Status ));
  2548. goto Cleanup;
  2549. }
  2550. pOldSid = InterlockedCompareExchangePointer(
  2551. &NtLmGlobalAliasAdminsSid,
  2552. pLocalSidAdmins,
  2553. NULL
  2554. );
  2555. if( pOldSid )
  2556. {
  2557. RtlFreeSid( pLocalSidAdmins );
  2558. }
  2559. }
  2560. //
  2561. // it's possible that the current thread is impersonating a user.
  2562. // if that's the case, get it's token user, and revert to insure we
  2563. // can open the process token.
  2564. //
  2565. Status = NtOpenThreadToken(
  2566. NtCurrentThread(),
  2567. TOKEN_QUERY | TOKEN_IMPERSONATE,
  2568. TRUE,
  2569. &ImpersonationToken
  2570. );
  2571. if( NT_SUCCESS(Status) )
  2572. {
  2573. //
  2574. // stop impersonating.
  2575. //
  2576. RevertToSelf();
  2577. //
  2578. // get the token user for the impersonating user.
  2579. //
  2580. ImpersonationTokenUser = (PTOKEN_USER)FastImpersonationTokenUser;
  2581. TokenUserSize = sizeof(FastImpersonationTokenUser);
  2582. Status = SspGetTokenUser(
  2583. ImpersonationToken,
  2584. ImpersonationTokenUser,
  2585. &TokenUserSize
  2586. );
  2587. if( Status == STATUS_BUFFER_TOO_SMALL )
  2588. {
  2589. SlowImpersonationTokenUser = (PTOKEN_USER)NtLmAllocate( TokenUserSize );
  2590. if(SlowImpersonationTokenUser == NULL)
  2591. {
  2592. Status = STATUS_INSUFFICIENT_RESOURCES;
  2593. goto Cleanup;
  2594. }
  2595. ImpersonationTokenUser = SlowImpersonationTokenUser;
  2596. Status = SspGetTokenUser(
  2597. ImpersonationToken,
  2598. ImpersonationTokenUser,
  2599. &TokenUserSize
  2600. );
  2601. }
  2602. if (!NT_SUCCESS(Status))
  2603. {
  2604. SspPrint(( SSP_CRITICAL, "SspCreateTokenDacl, SspGetTokenUser returns 0x%lx\n", Status ));
  2605. goto Cleanup;
  2606. }
  2607. }
  2608. if( NtLmGlobalProcessUserSid == NULL )
  2609. {
  2610. PTOKEN_USER ProcessTokenUser;
  2611. ULONG_PTR FastProcessTokenUser[ 128/sizeof(ULONG_PTR) ];
  2612. PSID pOldSid;
  2613. PSID pNewSid;
  2614. ULONG cbNewSid;
  2615. //
  2616. // Open the process token to find out the user sid
  2617. //
  2618. Status = NtOpenProcessToken(
  2619. NtCurrentProcess(),
  2620. TOKEN_QUERY,
  2621. &ProcessToken
  2622. );
  2623. if(!NT_SUCCESS(Status))
  2624. {
  2625. SspPrint(( SSP_CRITICAL, "SspCreateTokenDacl, NtOpenProcessToken returns 0x%lx\n", Status ));
  2626. goto Cleanup;
  2627. }
  2628. //
  2629. // get the token user for the process token.
  2630. //
  2631. ProcessTokenUser = (PTOKEN_USER)FastProcessTokenUser;
  2632. TokenUserSize = sizeof(FastProcessTokenUser);
  2633. Status = SspGetTokenUser(
  2634. ProcessToken,
  2635. ProcessTokenUser,
  2636. &TokenUserSize
  2637. );
  2638. if( Status == STATUS_BUFFER_TOO_SMALL )
  2639. {
  2640. SlowProcessTokenUser = (PTOKEN_USER)NtLmAllocate( TokenUserSize );
  2641. if(SlowProcessTokenUser == NULL)
  2642. {
  2643. Status = STATUS_INSUFFICIENT_RESOURCES;
  2644. goto Cleanup;
  2645. }
  2646. ProcessTokenUser = SlowProcessTokenUser;
  2647. Status = SspGetTokenUser(
  2648. ProcessToken,
  2649. ProcessTokenUser,
  2650. &TokenUserSize
  2651. );
  2652. }
  2653. if (!NT_SUCCESS(Status))
  2654. {
  2655. SspPrint(( SSP_CRITICAL, "SspCreateTokenDacl, SspGetTokenUser returns 0x%lx\n", Status ));
  2656. goto Cleanup;
  2657. }
  2658. cbNewSid = RtlLengthSid( ProcessTokenUser->User.Sid );
  2659. pNewSid = NtLmAllocate( cbNewSid );
  2660. if( pNewSid == NULL )
  2661. {
  2662. Status = STATUS_INSUFFICIENT_RESOURCES;
  2663. goto Cleanup;
  2664. }
  2665. CopyMemory( pNewSid, ProcessTokenUser->User.Sid, cbNewSid );
  2666. pOldSid = InterlockedCompareExchangePointer(
  2667. &NtLmGlobalProcessUserSid,
  2668. pNewSid,
  2669. NULL
  2670. );
  2671. if( pOldSid )
  2672. {
  2673. NtLmFree( pNewSid );
  2674. }
  2675. }
  2676. //
  2677. // Now get the token user for the thread.
  2678. //
  2679. ThreadTokenUser = (PTOKEN_USER)FastThreadTokenUser;
  2680. TokenUserSize = sizeof(FastThreadTokenUser);
  2681. Status = SspGetTokenUser(
  2682. Token,
  2683. ThreadTokenUser,
  2684. &TokenUserSize
  2685. );
  2686. if( Status == STATUS_BUFFER_TOO_SMALL )
  2687. {
  2688. SlowThreadTokenUser = (PTOKEN_USER)NtLmAllocate( TokenUserSize );
  2689. if(SlowThreadTokenUser == NULL)
  2690. {
  2691. Status = STATUS_INSUFFICIENT_RESOURCES;
  2692. goto Cleanup;
  2693. }
  2694. ThreadTokenUser = SlowThreadTokenUser;
  2695. Status = SspGetTokenUser(
  2696. Token,
  2697. ThreadTokenUser,
  2698. &TokenUserSize
  2699. );
  2700. }
  2701. if (!NT_SUCCESS(Status))
  2702. {
  2703. SspPrint(( SSP_CRITICAL, "SspCreateTokenDacl, SspGetTokenUser returns 0x%lx\n", Status ));
  2704. goto Cleanup;
  2705. }
  2706. AclLength = 4 * sizeof( ACCESS_ALLOWED_ACE ) - 4 * sizeof( ULONG ) +
  2707. RtlLengthSid( NtLmGlobalProcessUserSid ) +
  2708. RtlLengthSid( ThreadTokenUser->User.Sid ) +
  2709. RtlLengthSid( NtLmGlobalLocalSystemSid ) +
  2710. RtlLengthSid( NtLmGlobalAliasAdminsSid ) +
  2711. sizeof( ACL );
  2712. //
  2713. // determine if we need to add impersonation token sid onto the token Dacl.
  2714. //
  2715. if( ImpersonationTokenUser &&
  2716. !RtlEqualSid( ImpersonationTokenUser->User.Sid, NtLmGlobalProcessUserSid ) &&
  2717. !RtlEqualSid( ImpersonationTokenUser->User.Sid, ThreadTokenUser->User.Sid )
  2718. )
  2719. {
  2720. AclLength += (sizeof(ACCESS_ALLOWED_ACE) - sizeof( ULONG )) +
  2721. RtlLengthSid( ImpersonationTokenUser->User.Sid );
  2722. fInsertImpersonatingUser = TRUE;
  2723. }
  2724. if( AclLength <= sizeof(FastNewDacl) )
  2725. {
  2726. NewDacl = (PACL)FastNewDacl;
  2727. } else {
  2728. SlowNewDacl = (PACL)NtLmAllocate(AclLength );
  2729. NewDacl = SlowNewDacl;
  2730. if (SlowNewDacl == NULL) {
  2731. Status = STATUS_INSUFFICIENT_RESOURCES;
  2732. SspPrint(( SSP_CRITICAL, "SspCreateTokenDacl, NtLmallocate returns 0x%lx\n", NewDacl));
  2733. goto Cleanup;
  2734. }
  2735. }
  2736. Status = RtlCreateAcl( NewDacl, AclLength, ACL_REVISION2 );
  2737. ASSERT(NT_SUCCESS( Status ));
  2738. Status = RtlAddAccessAllowedAce (
  2739. NewDacl,
  2740. ACL_REVISION2,
  2741. TOKEN_ALL_ACCESS,
  2742. NtLmGlobalProcessUserSid
  2743. );
  2744. ASSERT( NT_SUCCESS( Status ));
  2745. Status = RtlAddAccessAllowedAce (
  2746. NewDacl,
  2747. ACL_REVISION2,
  2748. TOKEN_ALL_ACCESS,
  2749. ThreadTokenUser->User.Sid
  2750. );
  2751. ASSERT( NT_SUCCESS( Status ));
  2752. if( fInsertImpersonatingUser )
  2753. {
  2754. Status = RtlAddAccessAllowedAce (
  2755. NewDacl,
  2756. ACL_REVISION2,
  2757. TOKEN_ALL_ACCESS,
  2758. ImpersonationTokenUser->User.Sid
  2759. );
  2760. ASSERT( NT_SUCCESS( Status ));
  2761. }
  2762. Status = RtlAddAccessAllowedAce (
  2763. NewDacl,
  2764. ACL_REVISION2,
  2765. TOKEN_ALL_ACCESS,
  2766. NtLmGlobalAliasAdminsSid
  2767. );
  2768. ASSERT( NT_SUCCESS( Status ));
  2769. Status = RtlAddAccessAllowedAce (
  2770. NewDacl,
  2771. ACL_REVISION2,
  2772. TOKEN_ALL_ACCESS,
  2773. NtLmGlobalLocalSystemSid
  2774. );
  2775. ASSERT( NT_SUCCESS( Status ));
  2776. Status = RtlCreateSecurityDescriptor (
  2777. &SecurityDescriptor,
  2778. SECURITY_DESCRIPTOR_REVISION
  2779. );
  2780. ASSERT( NT_SUCCESS( Status ));
  2781. Status = RtlSetDaclSecurityDescriptor(
  2782. &SecurityDescriptor,
  2783. TRUE,
  2784. NewDacl,
  2785. FALSE
  2786. );
  2787. ASSERT( NT_SUCCESS( Status ));
  2788. Status = NtSetSecurityObject(
  2789. Token,
  2790. DACL_SECURITY_INFORMATION,
  2791. &SecurityDescriptor
  2792. );
  2793. ASSERT( NT_SUCCESS( Status ));
  2794. Cleanup:
  2795. if (ImpersonationToken != NULL)
  2796. {
  2797. //
  2798. // put the thread token back if we were impersonating.
  2799. //
  2800. SetThreadToken( NULL, ImpersonationToken );
  2801. NtClose(ImpersonationToken);
  2802. }
  2803. if (SlowThreadTokenUser != NULL) {
  2804. NtLmFree( SlowThreadTokenUser );
  2805. }
  2806. if (SlowProcessTokenUser != NULL) {
  2807. NtLmFree( SlowProcessTokenUser );
  2808. }
  2809. if (SlowImpersonationTokenUser != NULL) {
  2810. NtLmFree( SlowImpersonationTokenUser );
  2811. }
  2812. if (SlowNewDacl != NULL) {
  2813. NtLmFree( SlowNewDacl );
  2814. }
  2815. if (ProcessToken != NULL)
  2816. {
  2817. NtClose(ProcessToken);
  2818. }
  2819. return( Status );
  2820. }
  2821. NTSTATUS
  2822. SspMapContext(
  2823. IN PULONG_PTR phContext,
  2824. IN PUCHAR pSessionKey,
  2825. IN ULONG NegotiateFlags,
  2826. IN HANDLE TokenHandle,
  2827. IN PTimeStamp PasswordExpiry OPTIONAL,
  2828. IN ULONG UserFlags,
  2829. OUT PSecBuffer ContextData
  2830. )
  2831. /*++
  2832. RoutineDescription:
  2833. Create a local context for a real context
  2834. Don't link it to out list of local contexts.
  2835. Arguments:
  2836. Return Value:
  2837. --*/
  2838. {
  2839. NTSTATUS Status = STATUS_SUCCESS;
  2840. PNTLM_PACKED_CONTEXT pContext = NULL;
  2841. ULONG cbContextData;
  2842. WCHAR ContextNames[(UNLEN + DNS_MAX_NAME_LENGTH + 2 + 1) *sizeof (WCHAR)];
  2843. PLUID pLogonId = NULL;
  2844. TOKEN_STATISTICS TokenStats;
  2845. PSSP_CONTEXT pTempContext = (PSSP_CONTEXT)*phContext;
  2846. PACTIVE_LOGON *ActiveLogon = NULL, Logon = NULL;
  2847. LPWSTR UserName = NULL;
  2848. UINT Length = 0;
  2849. BOOLEAN ActiveLogonsAreLocked = FALSE;
  2850. if (pTempContext == NULL)
  2851. {
  2852. Status = STATUS_INVALID_HANDLE;
  2853. SspPrint(( SSP_CRITICAL, "SspMapContext, pTempContext is 0x%lx\n", pTempContext));
  2854. goto Cleanup;
  2855. }
  2856. if( pTempContext->Credential != NULL ) {
  2857. pLogonId = &(pTempContext->Credential->LogonId);
  2858. } else {
  2859. //
  2860. // if it was a local call where the default creds were used, lookup
  2861. // the username and domain name based on the AuthenticationId of the
  2862. // access token. The local call gets a duplicated access token
  2863. // associated with the original client, so information on this logon
  2864. // should be found in the active logon list.
  2865. //
  2866. if( NegotiateFlags & NTLMSSP_NEGOTIATE_LOCAL_CALL &&
  2867. pTempContext->UserName.Length == 0 &&
  2868. pTempContext->UserName.Buffer == NULL &&
  2869. pTempContext->DomainName.Length == 0 &&
  2870. pTempContext->DomainName.Buffer == NULL &&
  2871. TokenHandle ) {
  2872. DWORD TokenInfoLength = sizeof( TokenStats );
  2873. if( GetTokenInformation(
  2874. TokenHandle,
  2875. TokenStatistics,
  2876. &TokenStats,
  2877. TokenInfoLength,
  2878. &TokenInfoLength
  2879. )) {
  2880. pLogonId = &(TokenStats.AuthenticationId);
  2881. }
  2882. }
  2883. }
  2884. if( pLogonId )
  2885. {
  2886. NlpLockActiveLogonsRead();
  2887. ActiveLogonsAreLocked = TRUE;
  2888. if (!NlpFindActiveLogon (
  2889. pLogonId,
  2890. &ActiveLogon))
  2891. {
  2892. // Status = STATUS_NO_SUCH_LOGON_SESSION;
  2893. SspPrint(( SSP_API_MORE, "SspMapContext, NlpFindActiveLogon returns FALSE\n"));
  2894. // SspPrint(( SSP_CRITICAL, "SspMapContext, NlpFindActiveLogon returns FALSE\n"));
  2895. // goto Cleanup;
  2896. }
  2897. }
  2898. if (ActiveLogon != NULL)
  2899. {
  2900. Logon = *ActiveLogon;
  2901. }
  2902. ContextNames[0] = L'\0';
  2903. if (Logon != NULL)
  2904. {
  2905. if ( (Logon->UserName.Length > 0) &&
  2906. (Logon->LogonDomainName.Length > 0))
  2907. {
  2908. RtlCopyMemory (ContextNames,
  2909. Logon->LogonDomainName.Buffer,
  2910. Logon->LogonDomainName.Length);
  2911. Length = (Logon->LogonDomainName.Length)/sizeof(WCHAR);
  2912. ContextNames[Length] = L'\\';
  2913. Length += 1;
  2914. UserName = &ContextNames[Length];
  2915. RtlCopyMemory (UserName,
  2916. Logon->UserName.Buffer,
  2917. Logon->UserName.Length);
  2918. Length += (Logon->UserName.Length)/sizeof(WCHAR);
  2919. ContextNames[Length] = L'\0';
  2920. }
  2921. }
  2922. else
  2923. {
  2924. // We don't store network logons, but in the case of server side
  2925. // mapping, the client has sent us the Context Names, so use that.
  2926. // Also, handle the case where we don't have domainnames, just usernames
  2927. // Must handle the valid case where both domainname & username are NULL (rdr)
  2928. if ((pTempContext->DomainName.Length > 0) &&
  2929. (pTempContext->UserName.Length > 0))
  2930. {
  2931. RtlCopyMemory (ContextNames,
  2932. pTempContext->DomainName.Buffer,
  2933. pTempContext->DomainName.Length);
  2934. Length = (pTempContext->DomainName.Length)/sizeof(WCHAR);
  2935. ContextNames[Length] = L'\\';
  2936. Length += 1;
  2937. UserName = &ContextNames[Length];
  2938. RtlCopyMemory (UserName,
  2939. pTempContext->UserName.Buffer,
  2940. pTempContext->UserName.Length);
  2941. Length += (pTempContext->UserName.Length)/sizeof(WCHAR);
  2942. ContextNames[Length] = L'\0';
  2943. }
  2944. else if ((pTempContext->DomainName.Length == 0) &&
  2945. (pTempContext->UserName.Length >0))
  2946. {
  2947. RtlCopyMemory (ContextNames + Length,
  2948. pTempContext->UserName.Buffer,
  2949. pTempContext->UserName.Length);
  2950. Length = (pTempContext->UserName.Length)/sizeof(WCHAR);
  2951. ContextNames[Length] = L'\0';
  2952. }
  2953. }
  2954. //
  2955. // when domain is present, don't supply domain\UPN, supply domain\user
  2956. //
  2957. if( UserName ) {
  2958. DWORD cchUserName = wcslen(UserName);
  2959. DWORD i;
  2960. for( i = 0 ; i < cchUserName ; i++ ) {
  2961. if( UserName[ i ] == L'@' ) {
  2962. UserName[ i ] = L'\0';
  2963. break;
  2964. }
  2965. }
  2966. }
  2967. Length = wcslen(ContextNames) * sizeof(WCHAR);
  2968. cbContextData =
  2969. sizeof(NTLM_PACKED_CONTEXT) +
  2970. Length +
  2971. sizeof(WCHAR);
  2972. cbContextData += pTempContext->cbMarshalledTargetInfo;
  2973. // the first sizeof (NTLM_CLIENT_CONTEXT) bytes can be
  2974. // casted to pContext anyway.
  2975. pContext = (PNTLM_PACKED_CONTEXT)NtLmAllocateLsaHeap( cbContextData );
  2976. if (!pContext)
  2977. {
  2978. SspPrint(( SSP_CRITICAL, "SspMapContext, NtLmAllocate returns NULL\n"));
  2979. Status = STATUS_INSUFFICIENT_RESOURCES;
  2980. goto Cleanup;
  2981. }
  2982. // ZeroMemory( pContext, cbContextData );
  2983. pContext->NegotiateFlags = NegotiateFlags;
  2984. RtlCopyMemory( pContext->SessionKey,
  2985. pSessionKey,
  2986. MSV1_0_USER_SESSION_KEY_LENGTH);
  2987. // Save away the LsaContextHandle
  2988. // pContext->LsaContext = *phContext;
  2989. // dup token if it exists
  2990. pContext->ClientTokenHandle = 0 ;
  2991. if (TokenHandle != NULL)
  2992. {
  2993. HANDLE Tmp ;
  2994. Status = LsaFunctions->DuplicateHandle(
  2995. TokenHandle,
  2996. &Tmp );
  2997. if (!NT_SUCCESS(Status))
  2998. {
  2999. if (pContext)
  3000. {
  3001. NtLmFreeLsaHeap(pContext);
  3002. }
  3003. SspPrint(( SSP_CRITICAL, "SspMapContext, DuplicateHandle returns 0x%lx\n", Status));
  3004. goto Cleanup;
  3005. }
  3006. pContext->ClientTokenHandle = (ULONG) ((ULONG_PTR) Tmp) ;
  3007. }
  3008. if (cbContextData > sizeof(NTLM_PACKED_CONTEXT) )
  3009. {
  3010. pContext->ContextNames = sizeof(NTLM_PACKED_CONTEXT);
  3011. pContext->ContextNameLength = Length;
  3012. RtlCopyMemory(pContext+1,
  3013. ContextNames,
  3014. pContext->ContextNameLength
  3015. );
  3016. pContext->ContextNameLength += sizeof(WCHAR);
  3017. }
  3018. else
  3019. {
  3020. pContext->ContextNames = 0;
  3021. pContext->ContextNameLength = 0;
  3022. }
  3023. if( pTempContext->pbMarshalledTargetInfo )
  3024. {
  3025. pContext->MarshalledTargetInfo = (ULONG)pContext->ContextNameLength + sizeof(NTLM_PACKED_CONTEXT) ;
  3026. pContext->MarshalledTargetInfoLength = pTempContext->cbMarshalledTargetInfo;
  3027. RtlCopyMemory( (PBYTE)pContext+pContext->MarshalledTargetInfo,
  3028. pTempContext->pbMarshalledTargetInfo,
  3029. pContext->MarshalledTargetInfoLength
  3030. );
  3031. }
  3032. pContext->SendNonce = 0;
  3033. pContext->RecvNonce = 0;
  3034. ContextData->pvBuffer = pContext;
  3035. ContextData->cbBuffer = cbContextData;
  3036. if(ARGUMENT_PRESENT(PasswordExpiry)) {
  3037. pContext->PasswordExpiry = *PasswordExpiry;
  3038. } else {
  3039. pContext->PasswordExpiry.QuadPart = 0;
  3040. }
  3041. pContext->UserFlags = UserFlags;
  3042. Cleanup:
  3043. if (ActiveLogonsAreLocked)
  3044. {
  3045. NlpUnlockActiveLogons();
  3046. }
  3047. return(Status);
  3048. }
  3049. ULONG
  3050. HandleToListIndex(
  3051. ULONG_PTR ContextHandle
  3052. )
  3053. {
  3054. ASSERT( (NTLM_USERLIST_COUNT != 0) );
  3055. ASSERT( (NTLM_USERLIST_COUNT & 1) == 0 );
  3056. ULONG Number ;
  3057. ULONG Hash;
  3058. ULONG HashFinal;
  3059. Number = (ULONG)ContextHandle;
  3060. Hash = Number;
  3061. Hash += Number >> 8;
  3062. Hash += Number >> 16;
  3063. Hash += Number >> 24;
  3064. HashFinal = Hash;
  3065. HashFinal += Hash >> 4;
  3066. //
  3067. // insure power of two if not one.
  3068. //
  3069. return ( HashFinal & (NTLM_USERLIST_COUNT-1) ) ;
  3070. }
  3071. ULONG
  3072. __inline
  3073. ListIndexToLockIndex(
  3074. ULONG ListIndex
  3075. )
  3076. {
  3077. ASSERT( (NTLM_USERLIST_LOCK_COUNT) != 0 );
  3078. ASSERT( (NTLM_USERLIST_LOCK_COUNT & 1) == 0 );
  3079. //
  3080. // insure power of two if not one.
  3081. //
  3082. return ( ListIndex & (NTLM_USERLIST_LOCK_COUNT-1) );
  3083. }