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

4157 lines
103 KiB

  1. //+-----------------------------------------------------------------------
  2. //
  3. // Microsoft Windows
  4. //
  5. // Copyright (c) Microsoft Corporation 1992 - 1996
  6. //
  7. // File: kerbutil.cxx
  8. //
  9. // Contents: Utility functions for Kerberos package
  10. //
  11. //
  12. // History: 16-April-1996 Created MikeSw
  13. //
  14. //------------------------------------------------------------------------
  15. #include <kerb.hxx>
  16. #include <kerbp.h>
  17. #ifndef WIN32_CHICAGO
  18. #include <nb30.h>
  19. #else // WIN32_CHICAGO
  20. #define NCBNAMSZ 16
  21. #endif // WIN32_CHICAGO
  22. #include <userapi.h> // for gss support routines
  23. #ifdef RETAIL_LOG_SUPPORT
  24. static TCHAR THIS_FILE[]=TEXT(__FILE__);
  25. #endif
  26. GUID GUID_NULL = {0L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  27. //+-------------------------------------------------------------------------
  28. //
  29. // Function: KerbSplitFullServiceName
  30. //
  31. // Synopsis: Splits a full service name into a domain name and a
  32. // service name. The output strings point into the input
  33. // string's buffer and should not be freed
  34. //
  35. // Effects:
  36. //
  37. // Arguments: FullServiceName - The full service name in a domain\service
  38. // format
  39. // DomainName - Receives the domain portion of the full service
  40. // name in a 'domain' format
  41. // ServiceName - Receives the service name in a 'service' format
  42. //
  43. // Requires:
  44. //
  45. // Returns: STATUS_INVALID_PARAMETER if the service name does not
  46. // match the correct format.
  47. //
  48. // Notes:
  49. //
  50. //
  51. //--------------------------------------------------------------------------
  52. NTSTATUS
  53. KerbSplitFullServiceName(
  54. IN PUNICODE_STRING FullServiceName,
  55. OUT PUNICODE_STRING DomainName,
  56. OUT PUNICODE_STRING ServiceName
  57. )
  58. {
  59. UNICODE_STRING TempDomainName;
  60. UNICODE_STRING TempServiceName;
  61. TempDomainName = *FullServiceName;
  62. //
  63. // Find the split between domain and service name
  64. //
  65. TempDomainName.Length = 0;
  66. while ((TempDomainName.Length < FullServiceName->Length) &&
  67. (TempDomainName.Buffer[TempDomainName.Length/sizeof(WCHAR)] != L'\\') &&
  68. (TempDomainName.Buffer[TempDomainName.Length/sizeof(WCHAR)] != L'@') )
  69. {
  70. TempDomainName.Length += sizeof(WCHAR);
  71. }
  72. //
  73. // In this case, there is no separator
  74. //
  75. if (TempDomainName.Length == FullServiceName->Length)
  76. {
  77. *ServiceName = *FullServiceName;
  78. EMPTY_UNICODE_STRING( DomainName );
  79. return(STATUS_SUCCESS);
  80. }
  81. //
  82. // If the separator is an "@" switch the doman & service portion
  83. //
  84. if (TempDomainName.Buffer[TempDomainName.Length/sizeof(WCHAR)] == L'@')
  85. {
  86. TempServiceName = TempDomainName;
  87. TempDomainName.Buffer = TempServiceName.Buffer + TempServiceName.Length/sizeof(WCHAR) + 1;
  88. TempServiceName.MaximumLength = TempServiceName.Length;
  89. //
  90. // The Domain name is everything else
  91. //
  92. TempDomainName.Length = FullServiceName->Length - TempServiceName.Length - sizeof(WCHAR);
  93. TempDomainName.MaximumLength = TempDomainName.Length;
  94. }
  95. else
  96. {
  97. TempServiceName.Buffer = TempDomainName.Buffer + TempDomainName.Length/sizeof(WCHAR) + 1;
  98. TempDomainName.MaximumLength = TempDomainName.Length;
  99. //
  100. // The service name is everything else
  101. //
  102. TempServiceName.Length = FullServiceName->Length - TempDomainName.Length - sizeof(WCHAR);
  103. TempServiceName.MaximumLength = TempServiceName.Length;
  104. }
  105. //
  106. // We could be pointing at the end of the buffer. Set this to NULL
  107. //
  108. if (TempServiceName.Length == 0)
  109. {
  110. TempServiceName.Buffer = NULL;
  111. }
  112. if (TempDomainName.Length == 0)
  113. {
  114. TempDomainName.Buffer = NULL;
  115. }
  116. *ServiceName = TempServiceName;
  117. *DomainName = TempDomainName;
  118. return(STATUS_SUCCESS);
  119. }
  120. //+-------------------------------------------------------------------------
  121. //
  122. // Function: KerbAllocateNonce
  123. //
  124. // Synopsis: Allocates a locally unique number
  125. //
  126. // Effects:
  127. //
  128. // Arguments: none
  129. //
  130. // Requires:
  131. //
  132. // Returns: the nonce
  133. //
  134. // Notes:
  135. //
  136. //
  137. //--------------------------------------------------------------------------
  138. ULONG
  139. KerbAllocateNonce(
  140. VOID
  141. )
  142. {
  143. LUID TempLuid;
  144. TimeStamp CurrentTime;
  145. NtAllocateLocallyUniqueId(&TempLuid);
  146. GetSystemTimeAsFileTime((PFILETIME) &CurrentTime);
  147. #ifndef WIN32_CHICAGO
  148. return(0x7fffffff & (TempLuid.LowPart ^ TempLuid.HighPart ^ CurrentTime.LowPart ^ CurrentTime.HighPart));
  149. #else // WIN32_CHICAGO
  150. return(0x7fffffff & ((ULONG)(TempLuid.LowPart ^ TempLuid.HighPart ^ CurrentTime)));
  151. #endif // WIN32_CHICAGO
  152. }
  153. //+-------------------------------------------------------------------------
  154. //
  155. // Function: KerbAllocate
  156. //
  157. // Synopsis: Allocate memory in either lsa mode or user mode
  158. //
  159. // Effects:
  160. //
  161. // Arguments:
  162. //
  163. // Requires:
  164. //
  165. // Returns:
  166. //
  167. // Notes:
  168. //
  169. //
  170. //--------------------------------------------------------------------------
  171. PVOID
  172. KerbAllocate(
  173. IN SIZE_T BufferSize
  174. )
  175. {
  176. PVOID pBuffer = NULL;
  177. if (KerberosState == KerberosLsaMode)
  178. {
  179. pBuffer = LsaFunctions->AllocateLsaHeap((ULONG) BufferSize);
  180. // Lsa helper routine zeroes the memory.
  181. }
  182. else
  183. {
  184. DsysAssert(KerberosState == KerberosUserMode);
  185. pBuffer = LocalAlloc(0,BufferSize);
  186. if (pBuffer)
  187. {
  188. RtlZeroMemory (pBuffer, BufferSize);
  189. }
  190. }
  191. return pBuffer;
  192. }
  193. //+-------------------------------------------------------------------------
  194. //
  195. // Function: KerbFree
  196. //
  197. // Synopsis: Free memory in either lsa mode or user mode
  198. //
  199. // Effects:
  200. //
  201. // Arguments:
  202. //
  203. // Requires:
  204. //
  205. // Returns:
  206. //
  207. // Notes:
  208. //
  209. //
  210. //--------------------------------------------------------------------------
  211. VOID
  212. KerbFree(
  213. IN PVOID Buffer
  214. )
  215. {
  216. if (ARGUMENT_PRESENT(Buffer))
  217. {
  218. if (KerberosState == KerberosLsaMode)
  219. {
  220. LsaFunctions->FreeLsaHeap(Buffer);
  221. }
  222. else
  223. {
  224. DsysAssert(KerberosState == KerberosUserMode);
  225. LocalFree(Buffer);
  226. }
  227. }
  228. }
  229. //+-------------------------------------------------------------------------
  230. //
  231. // Function: KerbStringToUnicodeString()
  232. //
  233. // Synopsis: Takes a ansi string and (1) unicodes it, (2) copies it
  234. //
  235. // Effects:
  236. //
  237. // Arguments: pDest must be initialized unicode string
  238. //
  239. // Requires:
  240. //
  241. // Returns: Free .buffer using KerbFree()
  242. //
  243. // Notes:
  244. //
  245. //--------------------------------------------------------------------------
  246. BOOLEAN
  247. KerbMbStringToUnicodeString(PUNICODE_STRING pDest,
  248. char * pszString)
  249. {
  250. int cbNewString = 0;
  251. USHORT cbOriginalString;
  252. BOOLEAN fRet = FALSE;
  253. cbOriginalString = (USHORT) strlen(pszString) + 1;
  254. cbNewString = MultiByteToWideChar(
  255. CP_OEMCP,
  256. MB_PRECOMPOSED,
  257. pszString,
  258. cbOriginalString,
  259. NULL,
  260. 0
  261. );
  262. if ( cbNewString && ( cbNewString < KERB_MAX_UNICODE_STRING ))
  263. {
  264. pDest->Buffer = (PWSTR) KerbAllocate(cbNewString);
  265. if (NULL == pDest->Buffer)
  266. {
  267. return FALSE;
  268. }
  269. if (MultiByteToWideChar(CP_OEMCP, MB_PRECOMPOSED,
  270. pszString, cbOriginalString,
  271. pDest->Buffer, cbNewString))
  272. {
  273. pDest->Length = (USHORT) cbNewString;
  274. pDest->MaximumLength = (USHORT) cbNewString;
  275. fRet = TRUE;
  276. }
  277. }
  278. return fRet;
  279. }
  280. #ifndef WIN32_CHICAGO
  281. //+-------------------------------------------------------------------------
  282. //
  283. // Function: KerbWaitForEvent
  284. //
  285. // Synopsis: Wait up to Timeout seconds for EventName to be triggered.
  286. //
  287. // Effects:
  288. //
  289. // Arguments: EventName - Name of event to wait on
  290. // Timeout - Timeout for event (in seconds).
  291. //
  292. // Requires:
  293. //
  294. // Returns: STATUS_SUCCESS - Indicates Event was set.
  295. // STATUS_NETLOGON_NOT_STARTED - Timeout occurred.
  296. //
  297. //
  298. // Notes:
  299. //
  300. //
  301. //--------------------------------------------------------------------------
  302. NTSTATUS
  303. KerbWaitForEvent(
  304. IN LPWSTR EventName,
  305. IN ULONG Timeout
  306. )
  307. {
  308. NTSTATUS Status;
  309. HANDLE EventHandle;
  310. OBJECT_ATTRIBUTES EventAttributes;
  311. UNICODE_STRING EventNameString;
  312. LARGE_INTEGER LocalTimeout;
  313. //
  314. // Create an event for us to wait on.
  315. //
  316. RtlInitUnicodeString( &EventNameString, EventName);
  317. InitializeObjectAttributes( &EventAttributes, &EventNameString, 0, 0, NULL);
  318. Status = NtCreateEvent(
  319. &EventHandle,
  320. SYNCHRONIZE,
  321. &EventAttributes,
  322. NotificationEvent,
  323. (BOOLEAN) FALSE // The event is initially not signaled
  324. );
  325. if ( !NT_SUCCESS(Status)) {
  326. //
  327. // If the event already exists, the server beat us to creating it.
  328. // Just open it.
  329. //
  330. if( Status == STATUS_OBJECT_NAME_EXISTS ||
  331. Status == STATUS_OBJECT_NAME_COLLISION ) {
  332. Status = NtOpenEvent( &EventHandle,
  333. SYNCHRONIZE,
  334. &EventAttributes );
  335. }
  336. if ( !NT_SUCCESS(Status)) {
  337. KdPrint(("[MSV1_0] OpenEvent failed %lx\n", Status ));
  338. return Status;
  339. }
  340. }
  341. //
  342. // Wait for NETLOGON to initialize. Wait a maximum of Timeout seconds.
  343. //
  344. LocalTimeout.QuadPart = ((LONGLONG)(Timeout)) * (-10000000);
  345. Status = NtWaitForSingleObject( EventHandle, (BOOLEAN)FALSE, &LocalTimeout);
  346. (VOID) NtClose( EventHandle );
  347. if ( !NT_SUCCESS(Status) || Status == STATUS_TIMEOUT ) {
  348. if ( Status == STATUS_TIMEOUT ) {
  349. Status = STATUS_NETLOGON_NOT_STARTED; // Map to an error condition
  350. }
  351. return Status;
  352. }
  353. return STATUS_SUCCESS;
  354. }
  355. //+-------------------------------------------------------------------------
  356. //
  357. // Function: KerbWaitForKdc
  358. //
  359. // Synopsis: Wait up to Timeout seconds for the netlogon service to start.
  360. //
  361. // Effects:
  362. //
  363. // Arguments: Timeout - Timeout for netlogon (in seconds).
  364. //
  365. // Requires:
  366. //
  367. // Returns: STATUS_SUCCESS - Indicates NETLOGON successfully initialized.
  368. // STATUS_NETLOGON_NOT_STARTED - Timeout occurred.
  369. //
  370. // Notes:
  371. //
  372. //
  373. //--------------------------------------------------------------------------
  374. NTSTATUS
  375. KerbWaitForKdc(
  376. IN ULONG Timeout
  377. )
  378. {
  379. NTSTATUS Status;
  380. ULONG NetStatus;
  381. SC_HANDLE ScManagerHandle = NULL;
  382. SC_HANDLE ServiceHandle = NULL;
  383. SERVICE_STATUS ServiceStatus;
  384. LPQUERY_SERVICE_CONFIG ServiceConfig;
  385. LPQUERY_SERVICE_CONFIG AllocServiceConfig = NULL;
  386. QUERY_SERVICE_CONFIG DummyServiceConfig;
  387. DWORD ServiceConfigSize;
  388. BOOLEAN AutoStart = FALSE;
  389. //
  390. // If the KDC service is currently running,
  391. // skip the rest of the tests.
  392. //
  393. Status = KerbWaitForEvent( KDC_START_EVENT, 0 );
  394. if ( NT_SUCCESS(Status) ) {
  395. KerbKdcStarted = TRUE;
  396. return Status;
  397. }
  398. //
  399. // Open a handle to the KDC Service.
  400. //
  401. ScManagerHandle = OpenSCManager(
  402. NULL,
  403. NULL,
  404. SC_MANAGER_CONNECT );
  405. if (ScManagerHandle == NULL) {
  406. DebugLog((DEB_ERROR, " KerbWaitForKdc: OpenSCManager failed: "
  407. "%lu. %ws, line %d\n", GetLastError(), THIS_FILE, __LINE__));
  408. Status = STATUS_NETLOGON_NOT_STARTED;
  409. goto Cleanup;
  410. }
  411. ServiceHandle = OpenService(
  412. ScManagerHandle,
  413. SERVICE_KDC,
  414. SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG );
  415. if ( ServiceHandle == NULL ) {
  416. D_DebugLog((DEB_ERROR, "KerbWaitForKdc: OpenService failed: "
  417. "%lu. %ws, line %d\n", GetLastError(), THIS_FILE, __LINE__));
  418. Status = STATUS_NETLOGON_NOT_STARTED;
  419. goto Cleanup;
  420. }
  421. //
  422. // If the KDC service isn't configured to be automatically started
  423. // by the service controller, don't bother waiting for it to start -
  424. // just check to see if it is started.
  425. //
  426. // ?? Pass "DummyServiceConfig" and "sizeof(..)" since QueryService config
  427. // won't allow a null pointer, yet.
  428. if ( QueryServiceConfig(
  429. ServiceHandle,
  430. &DummyServiceConfig,
  431. sizeof(DummyServiceConfig),
  432. &ServiceConfigSize )) {
  433. ServiceConfig = &DummyServiceConfig;
  434. } else {
  435. NetStatus = GetLastError();
  436. if ( NetStatus != ERROR_INSUFFICIENT_BUFFER ) {
  437. D_DebugLog((DEB_ERROR,"KerbWaitForKdc: QueryServiceConfig failed: "
  438. "%lu. %ws, line %d\n", NetStatus, THIS_FILE, __LINE__));
  439. Status = STATUS_NETLOGON_NOT_STARTED;
  440. goto Cleanup;
  441. }
  442. SafeAllocaAllocate(AllocServiceConfig, ServiceConfigSize);
  443. ServiceConfig = AllocServiceConfig;
  444. if ( AllocServiceConfig == NULL ) {
  445. Status = STATUS_NO_MEMORY;
  446. goto Cleanup;
  447. }
  448. if ( !QueryServiceConfig(
  449. ServiceHandle,
  450. ServiceConfig,
  451. ServiceConfigSize,
  452. &ServiceConfigSize )) {
  453. D_DebugLog((DEB_ERROR, "KerbWaitForKdc: QueryServiceConfig "
  454. "failed again: %lu. %ws, line %d\n", GetLastError(), THIS_FILE, __LINE__));
  455. Status = STATUS_NETLOGON_NOT_STARTED;
  456. goto Cleanup;
  457. }
  458. }
  459. if ( ServiceConfig->dwStartType == SERVICE_AUTO_START ) {
  460. AutoStart = TRUE;
  461. }
  462. //
  463. // Loop waiting for the KDC service to start.
  464. //
  465. for (;;) {
  466. //
  467. // Query the status of the KDC service.
  468. //
  469. if (! QueryServiceStatus( ServiceHandle, &ServiceStatus )) {
  470. D_DebugLog((DEB_ERROR, "KerbWaitForKdc: QueryServiceStatus failed: "
  471. "%lu. %ws, line %d\n", GetLastError(), THIS_FILE, __LINE__ ));
  472. Status = STATUS_NETLOGON_NOT_STARTED;
  473. goto Cleanup;
  474. }
  475. //
  476. // Return or continue waiting depending on the state of
  477. // the KDC service.
  478. //
  479. switch( ServiceStatus.dwCurrentState) {
  480. case SERVICE_RUNNING:
  481. Status = STATUS_SUCCESS;
  482. goto Cleanup;
  483. case SERVICE_STOPPED:
  484. //
  485. // If KDC failed to start,
  486. // error out now. The caller has waited long enough to start.
  487. //
  488. if ( ServiceStatus.dwWin32ExitCode != ERROR_SERVICE_NEVER_STARTED ){
  489. #if DBG
  490. D_DebugLog((DEB_ERROR, "KerbWaitForKdc: "
  491. "KDC service couldn't start: %lu %lx. %ws, line %d\n",
  492. ServiceStatus.dwWin32ExitCode,
  493. ServiceStatus.dwWin32ExitCode, THIS_FILE, __LINE__ ));
  494. if ( ServiceStatus.dwWin32ExitCode == ERROR_SERVICE_SPECIFIC_ERROR ) {
  495. D_DebugLog((DEB_ERROR, " Service specific error code: %lu %lx. %ws, line %d\n",
  496. ServiceStatus.dwServiceSpecificExitCode,
  497. ServiceStatus.dwServiceSpecificExitCode,
  498. THIS_FILE, __LINE__ ));
  499. }
  500. #endif // DBG
  501. Status = STATUS_NETLOGON_NOT_STARTED;
  502. goto Cleanup;
  503. }
  504. //
  505. // If KDC has never been started on this boot,
  506. // continue waiting for it to start.
  507. //
  508. break;
  509. //
  510. // If KDC is trying to start up now,
  511. // continue waiting for it to start.
  512. //
  513. case SERVICE_START_PENDING:
  514. break;
  515. //
  516. // Any other state is bogus.
  517. //
  518. default:
  519. D_DebugLog((DEB_ERROR, "KerbWaitForKdc: "
  520. "Invalid service state: %lu. %ws, line %d\n",
  521. ServiceStatus.dwCurrentState, THIS_FILE, __LINE__ ));
  522. Status = STATUS_NETLOGON_NOT_STARTED;
  523. goto Cleanup;
  524. }
  525. //
  526. // If the service wasn't auto start, don't bother waiting and
  527. // retrying
  528. //
  529. if ((ServiceStatus.dwCurrentState) != SERVICE_START_PENDING && !AutoStart) {
  530. break;
  531. }
  532. //
  533. // Wait a second for the KDC service to start.
  534. // If it has successfully started, just return now.
  535. //
  536. Status = KerbWaitForEvent( KDC_START_EVENT, 1 );
  537. if ( Status != STATUS_NETLOGON_NOT_STARTED ) {
  538. goto Cleanup;
  539. }
  540. //
  541. // If we've waited long enough for KDC to start,
  542. // time out now.
  543. //
  544. if ( (--Timeout) == 0 ) {
  545. Status = STATUS_NETLOGON_NOT_STARTED;
  546. goto Cleanup;
  547. }
  548. }
  549. /* NOT REACHED */
  550. Cleanup:
  551. if ( ScManagerHandle != NULL ) {
  552. (VOID) CloseServiceHandle(ScManagerHandle);
  553. }
  554. if ( ServiceHandle != NULL ) {
  555. (VOID) CloseServiceHandle(ServiceHandle);
  556. }
  557. SafeAllocaFree( AllocServiceConfig );
  558. if (NT_SUCCESS(Status)) {
  559. KerbKdcStarted = TRUE;
  560. } else {
  561. KerbKdcStarted = FALSE;
  562. }
  563. return Status;
  564. }
  565. //+-------------------------------------------------------------------------
  566. //
  567. // Function: KerbWaitForService
  568. //
  569. // Synopsis: Wait up to Timeout seconds for the service to start.
  570. //
  571. // Effects:
  572. //
  573. // Arguments: ServiceName - Name of service to wait for
  574. // ServiceEvent - Optionally has event name signalling that
  575. // service is started
  576. // Timeout - Timeout for netlogon (in seconds).
  577. //
  578. // Requires:
  579. //
  580. // Returns: STATUS_SUCCESS - Indicates NETLOGON successfully initialized.
  581. // STATUS_NETLOGON_NOT_STARTED - Timeout occurred.
  582. //
  583. // Notes:
  584. //
  585. //
  586. //--------------------------------------------------------------------------
  587. NTSTATUS
  588. KerbWaitForService(
  589. IN LPWSTR ServiceName,
  590. IN OPTIONAL LPWSTR ServiceEvent,
  591. IN ULONG Timeout
  592. )
  593. {
  594. NTSTATUS Status = STATUS_SUCCESS;
  595. ULONG NetStatus;
  596. SC_HANDLE ScManagerHandle = NULL;
  597. SC_HANDLE ServiceHandle = NULL;
  598. SERVICE_STATUS ServiceStatus;
  599. LPQUERY_SERVICE_CONFIG ServiceConfig;
  600. LPQUERY_SERVICE_CONFIG AllocServiceConfig = NULL;
  601. QUERY_SERVICE_CONFIG DummyServiceConfig;
  602. DWORD ServiceConfigSize;
  603. BOOLEAN AutoStart = FALSE;
  604. if (ARGUMENT_PRESENT(ServiceEvent))
  605. {
  606. //
  607. // If the KDC service is currently running,
  608. // skip the rest of the tests.
  609. //
  610. Status = KerbWaitForEvent( ServiceEvent, 0 );
  611. if ( NT_SUCCESS(Status) ) {
  612. return Status;
  613. }
  614. }
  615. //
  616. // Open a handle to the Service.
  617. //
  618. ScManagerHandle = OpenSCManager(
  619. NULL,
  620. NULL,
  621. SC_MANAGER_CONNECT );
  622. if (ScManagerHandle == NULL) {
  623. D_DebugLog((DEB_ERROR, " KerbWaitForService: OpenSCManager failed: "
  624. "%lu. %ws, line %d\n", GetLastError(), THIS_FILE, __LINE__));
  625. Status = STATUS_NETLOGON_NOT_STARTED;
  626. goto Cleanup;
  627. }
  628. ServiceHandle = OpenService(
  629. ScManagerHandle,
  630. ServiceName,
  631. SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG );
  632. if ( ServiceHandle == NULL ) {
  633. D_DebugLog((DEB_ERROR, "KerbWaitForService: OpenService failed: "
  634. "%lu. %ws, line %d\n", GetLastError(), THIS_FILE, __LINE__));
  635. Status = STATUS_NETLOGON_NOT_STARTED;
  636. goto Cleanup;
  637. }
  638. //
  639. // If the KDC service isn't configured to be automatically started
  640. // by the service controller, don't bother waiting for it to start -
  641. // just check to see if it is started.
  642. //
  643. // ?? Pass "DummyServiceConfig" and "sizeof(..)" since QueryService config
  644. // won't allow a null pointer, yet.
  645. if ( QueryServiceConfig(
  646. ServiceHandle,
  647. &DummyServiceConfig,
  648. sizeof(DummyServiceConfig),
  649. &ServiceConfigSize )) {
  650. ServiceConfig = &DummyServiceConfig;
  651. } else {
  652. NetStatus = GetLastError();
  653. if ( NetStatus != ERROR_INSUFFICIENT_BUFFER ) {
  654. D_DebugLog((DEB_ERROR,"KerbWaitForService: QueryServiceConfig failed: "
  655. "%lu. %ws, line %d\n", NetStatus, THIS_FILE, __LINE__));
  656. Status = STATUS_NETLOGON_NOT_STARTED;
  657. goto Cleanup;
  658. }
  659. SafeAllocaAllocate(AllocServiceConfig, ServiceConfigSize);
  660. ServiceConfig = AllocServiceConfig;
  661. if ( AllocServiceConfig == NULL ) {
  662. Status = STATUS_NO_MEMORY;
  663. goto Cleanup;
  664. }
  665. if ( !QueryServiceConfig(
  666. ServiceHandle,
  667. ServiceConfig,
  668. ServiceConfigSize,
  669. &ServiceConfigSize )) {
  670. D_DebugLog((DEB_ERROR, "KerbWaitForService: QueryServiceConfig "
  671. "failed again: %lu. %ws, line %d\n", GetLastError(), THIS_FILE, __LINE__));
  672. Status = STATUS_NETLOGON_NOT_STARTED;
  673. goto Cleanup;
  674. }
  675. }
  676. if ( ServiceConfig->dwStartType == SERVICE_AUTO_START ) {
  677. AutoStart = TRUE;
  678. }
  679. //
  680. // Loop waiting for the KDC service to start.
  681. //
  682. for (;;) {
  683. //
  684. // Query the status of the KDC service.
  685. //
  686. if (! QueryServiceStatus( ServiceHandle, &ServiceStatus )) {
  687. D_DebugLog((DEB_ERROR, "KerbWaitForService: QueryServiceStatus failed: "
  688. "%lu. %ws, line %d\n", GetLastError(), THIS_FILE, __LINE__ ));
  689. Status = STATUS_NETLOGON_NOT_STARTED;
  690. goto Cleanup;
  691. }
  692. //
  693. // Return or continue waiting depending on the state of
  694. // the KDC service.
  695. //
  696. switch( ServiceStatus.dwCurrentState) {
  697. case SERVICE_RUNNING:
  698. Status = STATUS_SUCCESS;
  699. goto Cleanup;
  700. case SERVICE_STOPPED:
  701. //
  702. // If KDC failed to start,
  703. // error out now. The caller has waited long enough to start.
  704. //
  705. if ( ServiceStatus.dwWin32ExitCode != ERROR_SERVICE_NEVER_STARTED ){
  706. #if DBG
  707. D_DebugLog((DEB_ERROR, "KerbWaitForService: "
  708. "%ws service couldn't start: %lu %lx. %ws, line %d\n",
  709. ServiceName,
  710. ServiceStatus.dwWin32ExitCode,
  711. ServiceStatus.dwWin32ExitCode, THIS_FILE, __LINE__ ));
  712. if ( ServiceStatus.dwWin32ExitCode == ERROR_SERVICE_SPECIFIC_ERROR ) {
  713. D_DebugLog((DEB_ERROR, " Service specific error code: %lu %lx. %ws, line %d\n",
  714. ServiceStatus.dwServiceSpecificExitCode,
  715. ServiceStatus.dwServiceSpecificExitCode,
  716. THIS_FILE, __LINE__ ));
  717. }
  718. #endif // DBG
  719. Status = STATUS_NETLOGON_NOT_STARTED;
  720. goto Cleanup;
  721. }
  722. //
  723. // If service has never been started on this boot,
  724. // continue waiting for it to start.
  725. //
  726. break;
  727. //
  728. // If service is trying to start up now,
  729. // continue waiting for it to start.
  730. //
  731. case SERVICE_START_PENDING:
  732. break;
  733. //
  734. // Any other state is bogus.
  735. //
  736. default:
  737. D_DebugLog((DEB_ERROR, "KerbWaitForService: "
  738. "Invalid service state: %lu. %ws, line %d\n",
  739. ServiceStatus.dwCurrentState, THIS_FILE, __LINE__ ));
  740. Status = STATUS_NETLOGON_NOT_STARTED;
  741. goto Cleanup;
  742. }
  743. //
  744. // If the service wasn't auto start, don't bother waiting and
  745. // retrying
  746. //
  747. if (!AutoStart) {
  748. break;
  749. }
  750. //
  751. // Wait a second for the KDC service to start.
  752. // If it has successfully started, just return now.
  753. //
  754. if (ARGUMENT_PRESENT(ServiceEvent))
  755. {
  756. Status = KerbWaitForEvent( ServiceEvent, 1 );
  757. if ( Status != STATUS_NETLOGON_NOT_STARTED ) {
  758. goto Cleanup;
  759. }
  760. }
  761. else
  762. {
  763. Sleep(1000);
  764. }
  765. //
  766. // If we've waited long enough for KDC to start,
  767. // time out now.
  768. //
  769. if ( (--Timeout) == 0 ) {
  770. Status = STATUS_NETLOGON_NOT_STARTED;
  771. goto Cleanup;
  772. }
  773. }
  774. /* NOT REACHED */
  775. Cleanup:
  776. if ( ScManagerHandle != NULL ) {
  777. (VOID) CloseServiceHandle(ScManagerHandle);
  778. }
  779. if ( ServiceHandle != NULL ) {
  780. (VOID) CloseServiceHandle(ServiceHandle);
  781. }
  782. SafeAllocaFree(AllocServiceConfig);
  783. return Status;
  784. }
  785. #endif // WIN32_CHICAGO
  786. //+-------------------------------------------------------------------------
  787. //
  788. // Function: KerbMapContextFlags
  789. //
  790. // Synopsis: Maps the ISC_RET_xx flags to ASC_RET_xxx flags
  791. //
  792. // Effects:
  793. //
  794. // Arguments: ContextFlags - Flags to map
  795. //
  796. // Requires:
  797. //
  798. // Returns:
  799. //
  800. // Notes:
  801. //
  802. //
  803. //--------------------------------------------------------------------------
  804. struct _KERB_FLAG_MAPPING {
  805. ULONG InitFlag;
  806. ULONG AcceptFlag;
  807. } KerbContextFlagMappingTable[] = {
  808. {ISC_RET_EXTENDED_ERROR, ASC_RET_EXTENDED_ERROR},
  809. {ISC_RET_INTEGRITY , ASC_RET_INTEGRITY },
  810. {ISC_RET_IDENTIFY, ASC_RET_IDENTIFY },
  811. {ISC_RET_NULL_SESSION, ASC_RET_NULL_SESSION }
  812. };
  813. #define KERB_CONTEXT_FLAG_IDENTICAL 0xFFF & ~( ISC_RET_USED_COLLECTED_CREDS | ISC_RET_USED_SUPPLIED_CREDS)
  814. ULONG
  815. KerbMapContextFlags(
  816. IN ULONG ContextFlags
  817. )
  818. {
  819. ULONG OutputFlags;
  820. ULONG Index;
  821. //
  822. // First copy the identical flags
  823. //
  824. OutputFlags = ContextFlags & KERB_CONTEXT_FLAG_IDENTICAL;
  825. for (Index = 0; Index < sizeof(KerbContextFlagMappingTable) / (2 * sizeof(ULONG)) ;Index++ )
  826. {
  827. if ((ContextFlags & KerbContextFlagMappingTable[Index].InitFlag) != 0)
  828. {
  829. OutputFlags |= KerbContextFlagMappingTable[Index].AcceptFlag;
  830. }
  831. }
  832. return(OutputFlags);
  833. }
  834. //+-------------------------------------------------------------------------
  835. //
  836. // Function: KerbIsIpAddress
  837. //
  838. // Synopsis: Checks to see if a target name is an IP address
  839. //
  840. // Effects: none
  841. //
  842. // Arguments: TargetName - Name to check
  843. //
  844. // Requires:
  845. //
  846. // Returns: TRUE if the name is an ip address
  847. //
  848. // Notes: IP address consist of only digits and periods, possibly
  849. // with a terminating '$'.
  850. //
  851. //
  852. //--------------------------------------------------------------------------
  853. BOOLEAN
  854. KerbIsIpAddress(
  855. IN PUNICODE_STRING TargetName
  856. )
  857. {
  858. ULONG Index;
  859. ULONG PeriodCount = 0;
  860. //
  861. // Null names are not IP addresses.
  862. //
  863. if (!ARGUMENT_PRESENT(TargetName) || (TargetName->Length == 0))
  864. {
  865. return(FALSE);
  866. }
  867. for (Index = 0; Index < TargetName->Length/sizeof(WCHAR) ; Index++ )
  868. {
  869. switch(TargetName->Buffer[Index])
  870. {
  871. case L'0':
  872. case L'1':
  873. case L'2':
  874. case L'3':
  875. case L'4':
  876. case L'5':
  877. case L'6':
  878. case L'7':
  879. case L'8':
  880. case L'9':
  881. continue;
  882. case L'$':
  883. //
  884. // Only allow this at the end.
  885. //
  886. if (Index != (TargetName->Length/sizeof(WCHAR) -1) )
  887. {
  888. return(FALSE);
  889. }
  890. continue;
  891. case L'.':
  892. PeriodCount++;
  893. break;
  894. default:
  895. return(FALSE);
  896. }
  897. }
  898. //
  899. // We require a period in the name, so return the FoundPeriod flag
  900. //
  901. if (PeriodCount == 3)
  902. {
  903. return(TRUE);
  904. }
  905. else
  906. {
  907. return(FALSE);
  908. }
  909. }
  910. //+-------------------------------------------------------------------------
  911. //
  912. // Function: KerbHidePassword
  913. //
  914. // Synopsis: obscures a password in memory
  915. //
  916. // Effects:
  917. //
  918. // Arguments:
  919. //
  920. // Requires:
  921. //
  922. // Returns:
  923. //
  924. // Notes:
  925. //
  926. //
  927. //--------------------------------------------------------------------------
  928. VOID
  929. KerbHidePassword(
  930. IN OUT PUNICODE_STRING Password
  931. )
  932. {
  933. LsaFunctions->LsaProtectMemory(
  934. Password->Buffer,
  935. (ULONG)Password->MaximumLength
  936. );
  937. }
  938. //+-------------------------------------------------------------------------
  939. //
  940. // Function: KerbRevealPassword
  941. //
  942. // Synopsis: Reveals a password that has been hidden
  943. //
  944. // Effects:
  945. //
  946. // Arguments:
  947. //
  948. // Requires:
  949. //
  950. // Returns:
  951. //
  952. // Notes:
  953. //
  954. //
  955. //--------------------------------------------------------------------------
  956. VOID
  957. KerbRevealPassword(
  958. IN OUT PUNICODE_STRING HiddenPassword
  959. )
  960. {
  961. LsaFunctions->LsaUnprotectMemory(
  962. HiddenPassword->Buffer,
  963. (ULONG)HiddenPassword->MaximumLength
  964. );
  965. }
  966. //+-------------------------------------------------------------------------
  967. //
  968. // Function: KerbDuplicatePassword
  969. //
  970. // Synopsis: Duplicates a UNICODE_STRING. If the source string buffer is
  971. // NULL the destionation will be too. The MaximumLength contains
  972. // room for encryption padding data.
  973. //
  974. // Effects: allocates memory with LsaFunctions.AllocateLsaHeap
  975. //
  976. // Arguments: DestinationString - Receives a copy of the source string
  977. // SourceString - String to copy
  978. //
  979. // Requires:
  980. //
  981. // Notes:
  982. //
  983. //
  984. //--------------------------------------------------------------------------
  985. NTSTATUS
  986. KerbDuplicatePassword(
  987. OUT PUNICODE_STRING DestinationString,
  988. IN OPTIONAL PUNICODE_STRING SourceString
  989. )
  990. {
  991. NTSTATUS Status = STATUS_SUCCESS;
  992. DestinationString->Buffer = NULL;
  993. DestinationString->Length =
  994. DestinationString->MaximumLength =
  995. 0;
  996. if ((ARGUMENT_PRESENT(SourceString)) &&
  997. (SourceString->Buffer != NULL))
  998. {
  999. USHORT PaddingLength;
  1000. PaddingLength = RTL_ENCRYPT_MEMORY_SIZE - (SourceString->Length % RTL_ENCRYPT_MEMORY_SIZE);
  1001. if( PaddingLength == RTL_ENCRYPT_MEMORY_SIZE )
  1002. {
  1003. PaddingLength = 0;
  1004. }
  1005. //
  1006. // Make sure we don't overflow maximum length w/ pwd + max padding
  1007. // pwd won't be 65k long :)
  1008. //
  1009. if (SourceString->Length > (KERB_MAX_UNICODE_STRING - RTL_ENCRYPT_MEMORY_SIZE))
  1010. {
  1011. return STATUS_ILL_FORMED_PASSWORD;
  1012. }
  1013. DestinationString->Buffer = (LPWSTR) MIDL_user_allocate(
  1014. SourceString->Length +
  1015. PaddingLength
  1016. );
  1017. if (DestinationString->Buffer != NULL)
  1018. {
  1019. DestinationString->Length = SourceString->Length;
  1020. DestinationString->MaximumLength = SourceString->Length + PaddingLength;
  1021. if( DestinationString->MaximumLength == SourceString->MaximumLength )
  1022. {
  1023. //
  1024. // duplicating an already padded buffer -- pickup the original
  1025. // pad.
  1026. //
  1027. RtlCopyMemory(
  1028. DestinationString->Buffer,
  1029. SourceString->Buffer,
  1030. SourceString->MaximumLength
  1031. );
  1032. } else {
  1033. //
  1034. // duplicating an unpadded buffer -- pickup only the string
  1035. // and fill the rest with pad.
  1036. //
  1037. RtlCopyMemory(
  1038. DestinationString->Buffer,
  1039. SourceString->Buffer,
  1040. SourceString->Length
  1041. );
  1042. }
  1043. }
  1044. else
  1045. {
  1046. Status = STATUS_NO_MEMORY;
  1047. }
  1048. }
  1049. return Status;
  1050. }
  1051. #ifdef notdef
  1052. // use this if we ever need to map errors in kerb to something else.
  1053. //+-------------------------------------------------------------------------
  1054. //
  1055. // Function: KerbMapKerbNtStatusToNtStatus
  1056. //
  1057. // Synopsis: Maps an NT status code to a security status
  1058. // Here's the package's chance to send back generic NtStatus
  1059. // errors
  1060. //
  1061. // Effects:
  1062. //
  1063. // Arguments:
  1064. //
  1065. // Requires:
  1066. //
  1067. // Returns:
  1068. //
  1069. //
  1070. //
  1071. //--------------------------------------------------------------------------
  1072. NTSTATUS
  1073. KerbMapKerbNtStatusToNtStatus(
  1074. IN NTSTATUS Status
  1075. )
  1076. {
  1077. return(Status);
  1078. }
  1079. #endif
  1080. void * __cdecl
  1081. operator new(
  1082. size_t nSize
  1083. )
  1084. {
  1085. return((LPVOID)LocalAlloc(LPTR, nSize));
  1086. }
  1087. void __cdecl
  1088. operator delete(
  1089. void *pv
  1090. )
  1091. {
  1092. LocalFree((HLOCAL)pv);
  1093. }
  1094. //+-------------------------------------------------------------------------
  1095. //
  1096. // Function: KerbExtractDomainName
  1097. //
  1098. // Synopsis: Extracts the domain name from a principal name
  1099. //
  1100. // Effects: Allocates the destination string
  1101. //
  1102. // Arguments:
  1103. //
  1104. // Requires:
  1105. //
  1106. // Returns:
  1107. //
  1108. // Notes:
  1109. //
  1110. //
  1111. //--------------------------------------------------------------------------
  1112. NTSTATUS
  1113. KerbExtractDomainName(
  1114. OUT PUNICODE_STRING DomainName,
  1115. IN PKERB_INTERNAL_NAME PrincipalName,
  1116. IN PUNICODE_STRING TicketSourceDomain
  1117. )
  1118. {
  1119. NTSTATUS Status = STATUS_SUCCESS;
  1120. UNICODE_STRING TempPrincipal;
  1121. UNICODE_STRING TempDomain = NULL_UNICODE_STRING;
  1122. EMPTY_UNICODE_STRING( DomainName );
  1123. //
  1124. // We do different things depending on the name type:
  1125. // - for NT_MS_PRINCIPAL we call KerbSplitFullServiceName, then do the
  1126. // same as for other name types
  1127. // - For all other names, if the first portion is "krbtgt" then
  1128. // we use the second portion of the name, otherwise the
  1129. // TicketSourceRealm
  1130. //
  1131. if (PrincipalName->NameType == KRB_NT_MS_PRINCIPAL)
  1132. {
  1133. if (PrincipalName->NameCount != 1)
  1134. {
  1135. D_DebugLog((DEB_ERROR,"Principal name has more than one name. %ws, line %d\n", THIS_FILE, __LINE__ ));
  1136. Status = STATUS_TOO_MANY_PRINCIPALS;
  1137. return(Status);
  1138. }
  1139. else
  1140. {
  1141. Status = KerbSplitFullServiceName(
  1142. &PrincipalName->Names[0],
  1143. &TempDomain,
  1144. &TempPrincipal
  1145. );
  1146. if (!NT_SUCCESS(Status))
  1147. {
  1148. return(Status);
  1149. }
  1150. }
  1151. }
  1152. else
  1153. {
  1154. //
  1155. // The principal name is the first portion. If there are exactly
  1156. // two portions, the domain name is the second portion
  1157. //
  1158. TempPrincipal = PrincipalName->Names[0];
  1159. if (PrincipalName->NameCount == 2)
  1160. {
  1161. TempDomain = PrincipalName->Names[1];
  1162. }
  1163. else
  1164. {
  1165. TempDomain = *TicketSourceDomain;
  1166. }
  1167. }
  1168. //
  1169. // Check to see if the principal is "krbtgt" - if it is, the domain
  1170. // is TempDomain - otherwise it is TicketSourceDomain.
  1171. //
  1172. if (RtlEqualUnicodeString(
  1173. &TempPrincipal,
  1174. &KerbGlobalKdcServiceName,
  1175. TRUE // case insensitive
  1176. ))
  1177. {
  1178. Status = KerbDuplicateString(
  1179. DomainName,
  1180. &TempDomain
  1181. );
  1182. }
  1183. else
  1184. {
  1185. Status = KerbDuplicateString(
  1186. DomainName,
  1187. TicketSourceDomain
  1188. );
  1189. }
  1190. return(Status);
  1191. }
  1192. //+-------------------------------------------------------------------------
  1193. //
  1194. // Function: KerbUtcTimeToLocalTime
  1195. //
  1196. // Synopsis: Converts system time (used internally) to local time, which
  1197. // is returned to callers.
  1198. //
  1199. // Effects:
  1200. //
  1201. // Arguments:
  1202. //
  1203. // Requires:
  1204. //
  1205. // Returns:
  1206. //
  1207. // Notes:
  1208. //
  1209. //
  1210. //--------------------------------------------------------------------------
  1211. VOID
  1212. KerbUtcTimeToLocalTime(
  1213. OUT PTimeStamp LocalTime,
  1214. IN PTimeStamp SystemTime
  1215. )
  1216. {
  1217. #ifndef WIN32_CHICAGO
  1218. NTSTATUS Status;
  1219. Status = RtlSystemTimeToLocalTime(
  1220. SystemTime,
  1221. LocalTime
  1222. );
  1223. DsysAssert(NT_SUCCESS(Status));
  1224. #else
  1225. BOOL Result;
  1226. Result = FileTimeToLocalFileTime(
  1227. (PFILETIME) SystemTime,
  1228. (PFILETIME) LocalTime
  1229. );
  1230. DsysAssert(Result);
  1231. #endif
  1232. }
  1233. //+-------------------------------------------------------------------------
  1234. //
  1235. // Function: KerbConvertKdcOptionsToTicketFlags
  1236. //
  1237. // Synopsis:
  1238. //
  1239. // Effects:
  1240. //
  1241. // Arguments:
  1242. //
  1243. // Requires:
  1244. //
  1245. // Returns:
  1246. //
  1247. // Notes:
  1248. //
  1249. //
  1250. //--------------------------------------------------------------------------
  1251. ULONG
  1252. KerbConvertKdcOptionsToTicketFlags(
  1253. IN ULONG KdcOptions
  1254. )
  1255. {
  1256. ULONG TicketFlags = 0;
  1257. if ((KdcOptions & KERB_KDC_OPTIONS_forwardable) != 0)
  1258. {
  1259. TicketFlags |= KERB_TICKET_FLAGS_forwardable;
  1260. }
  1261. if ((KdcOptions & KERB_KDC_OPTIONS_forwarded) != 0)
  1262. {
  1263. TicketFlags |= KERB_TICKET_FLAGS_forwarded;
  1264. }
  1265. if ((KdcOptions & KERB_KDC_OPTIONS_proxiable) != 0)
  1266. {
  1267. TicketFlags |= KERB_TICKET_FLAGS_proxiable;
  1268. }
  1269. if ((KdcOptions & KERB_KDC_OPTIONS_proxy) != 0)
  1270. {
  1271. TicketFlags |= KERB_TICKET_FLAGS_proxy;
  1272. }
  1273. if ((KdcOptions & KERB_KDC_OPTIONS_postdated) != 0)
  1274. {
  1275. TicketFlags |= KERB_TICKET_FLAGS_postdated;
  1276. }
  1277. if ((KdcOptions & KERB_KDC_OPTIONS_allow_postdate) != 0)
  1278. {
  1279. TicketFlags |= KERB_TICKET_FLAGS_may_postdate;
  1280. }
  1281. if ((KdcOptions & KERB_KDC_OPTIONS_renewable) != 0)
  1282. {
  1283. TicketFlags |= KERB_TICKET_FLAGS_renewable;
  1284. }
  1285. return(TicketFlags);
  1286. }
  1287. //+-------------------------------------------------------------------------
  1288. //
  1289. // Function: KerbGetAddressListFromWinsock
  1290. //
  1291. // Synopsis: gets the list of addresses from a winsock ioctl
  1292. //
  1293. // Effects:
  1294. //
  1295. // Arguments:
  1296. //
  1297. // Requires:
  1298. //
  1299. // Returns:
  1300. //
  1301. // Notes:
  1302. //
  1303. //
  1304. //--------------------------------------------------------------------------
  1305. NTSTATUS
  1306. KerbGetAddressListFromWinsock(
  1307. OUT LPSOCKET_ADDRESS_LIST * SocketAddressList
  1308. )
  1309. {
  1310. ULONG BytesReturned = 150;
  1311. LPSOCKET_ADDRESS_LIST AddressList = NULL;
  1312. INT i,j;
  1313. ULONG NetStatus;
  1314. NTSTATUS Status = STATUS_SUCCESS;
  1315. SOCKET AddressSocket = INVALID_SOCKET;
  1316. #ifdef WIN32_CHICAGO
  1317. j = 0;
  1318. AddressList = (LPSOCKET_ADDRESS_LIST) MIDL_user_allocate(sizeof(SOCKET_ADDRESS_LIST));
  1319. if (AddressList == NULL)
  1320. {
  1321. Status = STATUS_INSUFFICIENT_RESOURCES;
  1322. goto Cleanup;
  1323. }
  1324. #else // WIN32_CHICAGO
  1325. AddressSocket = WSASocket( AF_INET,
  1326. SOCK_DGRAM,
  1327. 0, // PF_INET,
  1328. NULL,
  1329. 0,
  1330. 0 );
  1331. if ( AddressSocket == INVALID_SOCKET ) {
  1332. NetStatus = WSAGetLastError();
  1333. D_DebugLog((DEB_ERROR,"WSASocket failed with %ld. %ws, line %d\n", NetStatus, THIS_FILE, __LINE__ ));
  1334. Status = STATUS_UNSUCCESSFUL;
  1335. goto Cleanup;
  1336. }
  1337. for (;;) {
  1338. //
  1339. // Allocate a buffer that should be big enough.
  1340. //
  1341. if ( AddressList != NULL ) {
  1342. MIDL_user_free( AddressList );
  1343. }
  1344. AddressList = (LPSOCKET_ADDRESS_LIST) MIDL_user_allocate( BytesReturned );
  1345. if ( AddressList == NULL ) {
  1346. Status = STATUS_INSUFFICIENT_RESOURCES;
  1347. goto Cleanup;
  1348. }
  1349. //
  1350. // Get the list of IP addresses
  1351. //
  1352. NetStatus = WSAIoctl( AddressSocket,
  1353. SIO_ADDRESS_LIST_QUERY,
  1354. NULL, // No input buffer
  1355. 0, // No input buffer
  1356. (PVOID) AddressList,
  1357. BytesReturned,
  1358. &BytesReturned,
  1359. NULL, // No overlapped,
  1360. NULL ); // Not async
  1361. if ( NetStatus != 0 ) {
  1362. NetStatus = WSAGetLastError();
  1363. //
  1364. // If the buffer isn't big enough, try again.
  1365. //
  1366. if ( NetStatus == WSAEFAULT ) {
  1367. continue;
  1368. }
  1369. D_DebugLog((DEB_ERROR,"KerbGetAddressListFromWinsock: Cannot WSAIoctl SIO_ADDRESS_LIST_QUERY %ld %ld. %ws, line %d\n",
  1370. NetStatus, BytesReturned, THIS_FILE, __LINE__));
  1371. Status = STATUS_UNSUCCESSFUL;
  1372. goto Cleanup;
  1373. }
  1374. break;
  1375. }
  1376. //
  1377. // Weed out any zero IP addresses and other invalid addresses
  1378. //
  1379. for ( i = 0, j = 0; i < AddressList->iAddressCount; i++ ) {
  1380. PSOCKET_ADDRESS SocketAddress;
  1381. //
  1382. // Copy this address to the front of the list.
  1383. //
  1384. AddressList->Address[j] = AddressList->Address[i];
  1385. //
  1386. // If the address isn't valid,
  1387. // skip it.
  1388. //
  1389. SocketAddress = &AddressList->Address[j];
  1390. if ( SocketAddress->iSockaddrLength == 0 ||
  1391. SocketAddress->lpSockaddr == NULL ||
  1392. SocketAddress->lpSockaddr->sa_family != AF_INET ||
  1393. ((PSOCKADDR_IN)(SocketAddress->lpSockaddr))->sin_addr.s_addr == 0 ) {
  1394. } else {
  1395. //
  1396. // Otherwise keep it.
  1397. //
  1398. j++;
  1399. }
  1400. }
  1401. #endif // WIN32_CHICAGO
  1402. AddressList->iAddressCount = j;
  1403. *SocketAddressList = AddressList;
  1404. AddressList = NULL;
  1405. Cleanup:
  1406. if (AddressList != NULL)
  1407. {
  1408. MIDL_user_free(AddressList);
  1409. }
  1410. if ( AddressSocket != INVALID_SOCKET ) {
  1411. closesocket(AddressSocket);
  1412. }
  1413. return(Status);
  1414. }
  1415. //+-------------------------------------------------------------------------
  1416. //
  1417. // Function: KerbBuildHostAddresses
  1418. //
  1419. // Synopsis: Builds a list of host addresses to go in a KDC request
  1420. //
  1421. // Effects:
  1422. //
  1423. // Arguments:
  1424. //
  1425. // Requires:
  1426. //
  1427. // Returns:
  1428. //
  1429. // Notes:
  1430. //
  1431. //
  1432. //--------------------------------------------------------------------------
  1433. NTSTATUS
  1434. KerbBuildHostAddresses(
  1435. IN BOOLEAN IncludeIpAddresses,
  1436. IN BOOLEAN IncludeNetbiosAddresses,
  1437. OUT PKERB_HOST_ADDRESSES * HostAddresses
  1438. )
  1439. {
  1440. NTSTATUS Status = STATUS_SUCCESS;
  1441. PKERB_HOST_ADDRESSES Addresses = NULL;
  1442. PKERB_HOST_ADDRESSES TempAddress = NULL;
  1443. BOOLEAN LockHeld = FALSE;
  1444. #ifndef WIN32_CHICAGO
  1445. KerbGlobalReadLock();
  1446. LockHeld = TRUE;
  1447. //
  1448. // Check to see if we've gotten out addresses from Netlogon yet.
  1449. //
  1450. if ( IncludeIpAddresses &&
  1451. KerbGlobalIpAddressCount == 0)
  1452. {
  1453. LPSOCKET_ADDRESS_LIST SocketAddressList = NULL;
  1454. KerbGlobalReleaseLock();
  1455. LockHeld = FALSE;
  1456. //
  1457. // We haven't get them now
  1458. //
  1459. Status = KerbGetAddressListFromWinsock(
  1460. &SocketAddressList
  1461. );
  1462. if (NT_SUCCESS(Status))
  1463. {
  1464. Status = KerbUpdateGlobalAddresses(
  1465. SocketAddressList->Address,
  1466. SocketAddressList->iAddressCount
  1467. );
  1468. MIDL_user_free(SocketAddressList);
  1469. }
  1470. else
  1471. {
  1472. KerbGlobalWriteLock();
  1473. KerbGlobalIpAddressesInitialized = TRUE;
  1474. KerbGlobalReleaseLock();
  1475. }
  1476. KerbGlobalReadLock();
  1477. LockHeld = TRUE;
  1478. }
  1479. //
  1480. // On failure don't bother inserting the IP addresses
  1481. //
  1482. if ( Status == STATUS_SUCCESS &&
  1483. IncludeIpAddresses ) {
  1484. ULONG Index;
  1485. for (Index = 0; Index < KerbGlobalIpAddressCount ; Index++ )
  1486. {
  1487. TempAddress = (PKERB_HOST_ADDRESSES) KerbAllocate(sizeof(KERB_HOST_ADDRESSES));
  1488. if (TempAddress == NULL)
  1489. {
  1490. Status = STATUS_INSUFFICIENT_RESOURCES;
  1491. goto Cleanup;
  1492. }
  1493. TempAddress->value.address_type = KERB_ADDRTYPE_INET;
  1494. TempAddress->value.address.length = 4;
  1495. TempAddress->value.address.value = (PUCHAR) KerbAllocate(4);
  1496. if (TempAddress->value.address.value == NULL)
  1497. {
  1498. Status = STATUS_INSUFFICIENT_RESOURCES;
  1499. goto Cleanup;
  1500. }
  1501. RtlCopyMemory
  1502. (
  1503. TempAddress->value.address.value,
  1504. &KerbGlobalIpAddresses[Index].sin_addr.S_un.S_addr,
  1505. 4
  1506. );
  1507. TempAddress->next = Addresses;
  1508. Addresses = TempAddress;
  1509. TempAddress = NULL;
  1510. }
  1511. }
  1512. else
  1513. {
  1514. Status = STATUS_SUCCESS;
  1515. }
  1516. #endif // WIN32_CHICAGO
  1517. //
  1518. // Insert the netbios address (if it will fit)
  1519. //
  1520. if (IncludeNetbiosAddresses &&
  1521. KerbGlobalKerbMachineName.Length < NCBNAMSZ)
  1522. {
  1523. TempAddress = (PKERB_HOST_ADDRESSES) KerbAllocate(sizeof(KERB_HOST_ADDRESSES));
  1524. if (TempAddress == NULL)
  1525. {
  1526. Status = STATUS_INSUFFICIENT_RESOURCES;
  1527. goto Cleanup;
  1528. }
  1529. TempAddress->value.address_type = KERB_ADDRTYPE_NETBIOS;
  1530. TempAddress->value.address.length = NCBNAMSZ;
  1531. TempAddress->value.address.value = (PUCHAR) KerbAllocate(NCBNAMSZ);
  1532. if (TempAddress->value.address.value == NULL)
  1533. {
  1534. Status = STATUS_INSUFFICIENT_RESOURCES;
  1535. goto Cleanup;
  1536. }
  1537. RtlCopyMemory(
  1538. TempAddress->value.address.value,
  1539. KerbGlobalKerbMachineName.Buffer,
  1540. KerbGlobalKerbMachineName.Length
  1541. );
  1542. memset(
  1543. TempAddress->value.address.value + KerbGlobalKerbMachineName.Length,
  1544. ' ', // space
  1545. NCBNAMSZ - KerbGlobalKerbMachineName.Length
  1546. );
  1547. TempAddress->next = Addresses;
  1548. Addresses = TempAddress;
  1549. TempAddress = NULL;
  1550. }
  1551. *HostAddresses = Addresses;
  1552. Addresses = NULL;
  1553. Cleanup:
  1554. if (LockHeld)
  1555. {
  1556. KerbGlobalReleaseLock();
  1557. }
  1558. if (TempAddress != NULL)
  1559. {
  1560. if (TempAddress->value.address.value != NULL)
  1561. {
  1562. KerbFree(TempAddress->value.address.value);
  1563. }
  1564. KerbFree(TempAddress);
  1565. }
  1566. if (Addresses != NULL)
  1567. {
  1568. //KerbFreeHostAddresses(Addresses);
  1569. while (Addresses != NULL)
  1570. {
  1571. TempAddress = Addresses;
  1572. Addresses = Addresses->next;
  1573. if (TempAddress->value.address.value != NULL)
  1574. {
  1575. KerbFree(TempAddress->value.address.value);
  1576. }
  1577. KerbFree(TempAddress);
  1578. }
  1579. }
  1580. return(Status);
  1581. }
  1582. //+-------------------------------------------------------------------------
  1583. //
  1584. // Function: KerbBuildGssErrorMessage
  1585. //
  1586. // Synopsis: Builds an error message with GSS framing, if necessary
  1587. //
  1588. // Effects:
  1589. //
  1590. // Arguments:
  1591. //
  1592. // Requires:
  1593. //
  1594. // Returns:
  1595. //
  1596. // Notes:
  1597. //
  1598. //
  1599. //--------------------------------------------------------------------------
  1600. NTSTATUS
  1601. KerbBuildGssErrorMessage(
  1602. IN KERBERR Error,
  1603. IN PBYTE ErrorData,
  1604. IN ULONG ErrorDataSize,
  1605. IN PKERB_CONTEXT Context,
  1606. OUT PULONG ErrorMessageSize,
  1607. OUT PBYTE * ErrorMessage
  1608. )
  1609. {
  1610. KERBERR KerbErr = KDC_ERR_NONE;
  1611. NTSTATUS Status = STATUS_SUCCESS;
  1612. PUNICODE_STRING pDomain = NULL;
  1613. PBYTE RawErrorMessage = NULL;
  1614. ULONG RawErrorMessageSize = 0;
  1615. PBYTE EncodedErrorData = NULL;
  1616. ULONG EncodedErrorDataSize = 0;
  1617. PBYTE MessageStart = NULL;
  1618. KERB_ERROR_METHOD_DATA ApErrorData = {0};
  1619. PKERB_INTERNAL_NAME Spn = NULL;
  1620. gss_OID MechId;
  1621. //
  1622. // First, convert the error data to a specified type
  1623. //
  1624. if (Error == KRB_AP_ERR_SKEW)
  1625. {
  1626. ApErrorData.data_type = KERB_AP_ERR_TYPE_SKEW_RECOVERY;
  1627. ApErrorData.data_value.value = NULL;
  1628. ApErrorData.data_value.length = 0;
  1629. KerbErr = KerbPackData(
  1630. &ApErrorData,
  1631. KERB_ERROR_METHOD_DATA_PDU,
  1632. &EncodedErrorDataSize,
  1633. &EncodedErrorData
  1634. );
  1635. if (!KERB_SUCCESS(KerbErr))
  1636. {
  1637. Status = KerbMapKerbError(KerbErr);
  1638. goto Cleanup;
  1639. }
  1640. }
  1641. else if (ErrorDataSize != 0)
  1642. {
  1643. if (Error == KRB_AP_ERR_USER_TO_USER_REQUIRED)
  1644. {
  1645. EncodedErrorData = ErrorData;
  1646. EncodedErrorDataSize = ErrorDataSize;
  1647. }
  1648. else
  1649. {
  1650. ApErrorData.data_type = KERB_AP_ERR_TYPE_NTSTATUS;
  1651. ApErrorData.data_value.value = ErrorData;
  1652. ApErrorData.data_value.length = ErrorDataSize;
  1653. ApErrorData.bit_mask |= data_value_present;
  1654. KerbErr = KerbPackData(
  1655. &ApErrorData,
  1656. KERB_ERROR_METHOD_DATA_PDU,
  1657. &EncodedErrorDataSize,
  1658. &EncodedErrorData
  1659. );
  1660. if (!KERB_SUCCESS(KerbErr))
  1661. {
  1662. Status = KerbMapKerbError(KerbErr);
  1663. goto Cleanup;
  1664. }
  1665. }
  1666. }
  1667. //
  1668. // First build the error message
  1669. //
  1670. KerbGlobalReadLock();
  1671. if (Context->ServerPrincipalName.Buffer != NULL)
  1672. {
  1673. KerbErr = KerbConvertStringToKdcName(
  1674. &Spn,
  1675. &Context->ServerPrincipalName
  1676. );
  1677. if (!KERB_SUCCESS(KerbErr))
  1678. {
  1679. Status = KerbMapKerbError(KerbErr);
  1680. goto Cleanup;
  1681. }
  1682. }
  1683. else
  1684. {
  1685. Spn = KerbGlobalMitMachineServiceName;
  1686. }
  1687. if (KerbGlobalDnsDomainName.Buffer != NULL)
  1688. {
  1689. pDomain = &KerbGlobalDnsDomainName;
  1690. }
  1691. else if (KerbGlobalDomainName.Buffer != NULL)
  1692. {
  1693. pDomain = &KerbGlobalDomainName;
  1694. }
  1695. KerbErr = KerbBuildErrorMessageEx(
  1696. Error,
  1697. NULL, // no extended error
  1698. pDomain,
  1699. Spn,
  1700. NULL, // no client realm
  1701. EncodedErrorData,
  1702. EncodedErrorDataSize,
  1703. &RawErrorMessageSize,
  1704. &RawErrorMessage
  1705. );
  1706. KerbGlobalReleaseLock();
  1707. if (!KERB_SUCCESS(KerbErr))
  1708. {
  1709. Status = KerbMapKerbError(KerbErr);
  1710. goto Cleanup;
  1711. }
  1712. //
  1713. // Figure out what OID to use
  1714. //
  1715. KerbReadLockContexts();
  1716. //
  1717. // For DCE style we don't use an OID
  1718. //
  1719. if ((Context->ContextFlags & ISC_RET_USED_DCE_STYLE) != 0)
  1720. {
  1721. KerbUnlockContexts();
  1722. *ErrorMessage = RawErrorMessage;
  1723. *ErrorMessageSize = RawErrorMessageSize;
  1724. RawErrorMessage = NULL;
  1725. goto Cleanup;
  1726. }
  1727. if ((Context->ContextAttributes & KERB_CONTEXT_USER_TO_USER) != 0)
  1728. {
  1729. MechId = gss_mech_krb5_u2u;
  1730. }
  1731. else
  1732. {
  1733. MechId = gss_mech_krb5_new;
  1734. }
  1735. KerbUnlockContexts();
  1736. *ErrorMessageSize = g_token_size(MechId, RawErrorMessageSize);
  1737. *ErrorMessage = (PBYTE) KerbAllocate(*ErrorMessageSize);
  1738. if (*ErrorMessage == NULL)
  1739. {
  1740. Status = STATUS_INSUFFICIENT_RESOURCES;
  1741. goto Cleanup;
  1742. }
  1743. //
  1744. // the g_make_token_header will reset this to point to the end of the
  1745. // header
  1746. //
  1747. MessageStart = *ErrorMessage;
  1748. g_make_token_header(
  1749. MechId,
  1750. RawErrorMessageSize,
  1751. &MessageStart,
  1752. KG_TOK_CTX_ERROR
  1753. );
  1754. RtlCopyMemory(
  1755. MessageStart,
  1756. RawErrorMessage,
  1757. RawErrorMessageSize
  1758. );
  1759. Cleanup:
  1760. if (RawErrorMessage != NULL)
  1761. {
  1762. MIDL_user_free(RawErrorMessage);
  1763. }
  1764. if (EncodedErrorData != ErrorData)
  1765. {
  1766. MIDL_user_free(EncodedErrorData);
  1767. }
  1768. if (Spn != NULL && Context->ServerPrincipalName.Buffer != NULL)
  1769. {
  1770. MIDL_user_free(Spn);
  1771. }
  1772. return(Status);
  1773. }
  1774. //+-------------------------------------------------------------------------
  1775. //
  1776. // Function: KerbReceiveErrorMessage
  1777. //
  1778. // Synopsis: Unpacks an error message from a context request
  1779. //
  1780. // Effects:
  1781. //
  1782. // Arguments:
  1783. //
  1784. // Requires:
  1785. //
  1786. // Returns:
  1787. //
  1788. // Notes:
  1789. //
  1790. //
  1791. //--------------------------------------------------------------------------
  1792. NTSTATUS
  1793. KerbReceiveErrorMessage(
  1794. IN PBYTE ErrorMessage,
  1795. IN ULONG ErrorMessageSize,
  1796. IN PKERB_CONTEXT Context,
  1797. OUT PKERB_ERROR * DecodedErrorMessage,
  1798. OUT PKERB_ERROR_METHOD_DATA * ErrorData
  1799. )
  1800. {
  1801. NTSTATUS Status = STATUS_SUCCESS;
  1802. KERBERR KerbErr;
  1803. PBYTE MessageStart = NULL;
  1804. ULONG MessageSize = 0;
  1805. BOOLEAN VerifiedHeader = FALSE;
  1806. gss_OID MechId = NULL;
  1807. KerbReadLockContexts();
  1808. //
  1809. // For DCE style we don't use an OID
  1810. //
  1811. if ((Context->ContextAttributes & KERB_CONTEXT_USER_TO_USER) != 0)
  1812. {
  1813. MechId = gss_mech_krb5_u2u;
  1814. }
  1815. else
  1816. {
  1817. MechId = gss_mech_krb5_new;
  1818. }
  1819. KerbUnlockContexts();
  1820. //
  1821. // First try pull off the header
  1822. //
  1823. MessageSize = ErrorMessageSize;
  1824. MessageStart = ErrorMessage;
  1825. if (!g_verify_token_header(
  1826. MechId,
  1827. (INT *) &MessageSize,
  1828. &MessageStart,
  1829. KG_TOK_CTX_ERROR,
  1830. ErrorMessageSize
  1831. ))
  1832. {
  1833. //
  1834. // If we couldn't find the header, try it without
  1835. // a header
  1836. //
  1837. MessageSize = ErrorMessageSize;
  1838. MessageStart = ErrorMessage;
  1839. }
  1840. else
  1841. {
  1842. VerifiedHeader = TRUE;
  1843. }
  1844. KerbErr = KerbUnpackKerbError(
  1845. MessageStart,
  1846. MessageSize,
  1847. DecodedErrorMessage
  1848. );
  1849. if (!KERB_SUCCESS(KerbErr))
  1850. {
  1851. Status = STATUS_INVALID_PARAMETER;
  1852. goto Cleanup;
  1853. }
  1854. if (((*DecodedErrorMessage)->bit_mask & error_data_present) != 0)
  1855. {
  1856. KerbUnpackErrorMethodData(
  1857. *DecodedErrorMessage,
  1858. ErrorData
  1859. );
  1860. }
  1861. else
  1862. {
  1863. Status = KerbMapKerbError(KerbErr);
  1864. }
  1865. Cleanup:
  1866. return(Status);
  1867. }
  1868. #ifndef WIN32_CHICAGO
  1869. //+-------------------------------------------------------------------------
  1870. //
  1871. // Function: KerbUnpackErrorMethodData
  1872. //
  1873. // Synopsis: This routine unpacks extended error information from
  1874. // a KERB_ERROR message
  1875. //
  1876. // Effects:
  1877. //
  1878. // Arguments: Unpacked error message. Returns extended error to
  1879. // be freed using KerbFree
  1880. //
  1881. // Requires:
  1882. //
  1883. // Returns: NTSTATUS
  1884. //
  1885. // Notes:
  1886. //
  1887. //
  1888. //--------------------------------------------------------------------------
  1889. KERBERR
  1890. KerbUnpackErrorMethodData(
  1891. IN PKERB_ERROR ErrorMessage,
  1892. IN OUT OPTIONAL PKERB_ERROR_METHOD_DATA * ppErrorData
  1893. )
  1894. {
  1895. PKERB_ERROR_METHOD_DATA pErrorData = NULL;
  1896. KERBERR KerbErr = KDC_ERR_NONE;
  1897. if (ARGUMENT_PRESENT(ppErrorData))
  1898. {
  1899. *ppErrorData = NULL;
  1900. }
  1901. if ((ErrorMessage->bit_mask & error_data_present) == 0)
  1902. {
  1903. return (KRB_ERR_GENERIC);
  1904. }
  1905. KerbErr = KerbUnpackData(
  1906. ErrorMessage->error_data.value,
  1907. ErrorMessage->error_data.length,
  1908. KERB_ERROR_METHOD_DATA_PDU,
  1909. (void**) &pErrorData
  1910. );
  1911. if (KERB_SUCCESS(KerbErr) && ARGUMENT_PRESENT(ppErrorData) && (NULL != pErrorData))
  1912. {
  1913. *ppErrorData = pErrorData;
  1914. pErrorData = NULL;
  1915. }
  1916. if (pErrorData)
  1917. {
  1918. KerbFreeData(KERB_ERROR_METHOD_DATA_PDU, pErrorData);
  1919. }
  1920. return (KerbErr);
  1921. }
  1922. //+-------------------------------------------------------------------------
  1923. //
  1924. // Function: KerbGetDnsHostName
  1925. //
  1926. // Synopsis: This routine gets DnsHostName of this machine.
  1927. //
  1928. // Effects:
  1929. //
  1930. // Arguments: DnsHostName - Returns the DNS Host Name of the machine.
  1931. // Will return a NULL string if this machine has no DNS host name.
  1932. // Free this buffer using KerbFreeString.
  1933. //
  1934. // Requires:
  1935. //
  1936. // Returns:
  1937. //
  1938. // Notes:
  1939. //
  1940. //
  1941. //--------------------------------------------------------------------------
  1942. NTSTATUS
  1943. KerbGetDnsHostName(
  1944. OUT PUNICODE_STRING DnsHostName
  1945. )
  1946. {
  1947. NTSTATUS Status = STATUS_SUCCESS;
  1948. WCHAR LocalDnsUnicodeHostName[DNS_MAX_NAME_BUFFER_LENGTH+1];
  1949. ULONG LocalDnsUnicodeHostNameLen = DNS_MAX_NAME_BUFFER_LENGTH+1;
  1950. LPWSTR ConfiguredDnsName = LocalDnsUnicodeHostName;
  1951. UNICODE_STRING HostName;
  1952. RtlInitUnicodeString(
  1953. DnsHostName,
  1954. NULL
  1955. );
  1956. //
  1957. // Get the DNS host name.
  1958. //
  1959. if (!GetComputerNameEx(
  1960. ComputerNameDnsHostname,
  1961. ConfiguredDnsName,
  1962. &LocalDnsUnicodeHostNameLen))
  1963. {
  1964. goto Cleanup;
  1965. }
  1966. ConfiguredDnsName = &LocalDnsUnicodeHostName[LocalDnsUnicodeHostNameLen];
  1967. *ConfiguredDnsName = L'.';
  1968. ConfiguredDnsName++;
  1969. //
  1970. // Now get the DNS domain name
  1971. //
  1972. LocalDnsUnicodeHostNameLen = DNS_MAX_NAME_BUFFER_LENGTH - LocalDnsUnicodeHostNameLen;
  1973. if (!GetComputerNameEx(
  1974. ComputerNameDnsDomain,
  1975. ConfiguredDnsName,
  1976. &LocalDnsUnicodeHostNameLen
  1977. ))
  1978. {
  1979. goto Cleanup;
  1980. }
  1981. RtlInitUnicodeString(
  1982. &HostName,
  1983. LocalDnsUnicodeHostName
  1984. );
  1985. Status = RtlDowncaseUnicodeString(
  1986. &HostName,
  1987. &HostName,
  1988. FALSE // don't allocate destination
  1989. );
  1990. if (!NT_SUCCESS(Status))
  1991. {
  1992. goto Cleanup;
  1993. }
  1994. Status = KerbDuplicateString(
  1995. DnsHostName,
  1996. &HostName
  1997. );
  1998. Cleanup:
  1999. return Status;
  2000. }
  2001. #endif // WIN32_CHICAGO
  2002. //+-------------------------------------------------------------------------
  2003. //
  2004. // Function: KerbIsThisOurDomain
  2005. //
  2006. // Synopsis: Compares a domain name to the local domain anme
  2007. //
  2008. // Effects:
  2009. //
  2010. // Arguments:
  2011. //
  2012. // Requires:
  2013. //
  2014. // Returns:
  2015. //
  2016. // Notes:
  2017. //
  2018. //
  2019. //--------------------------------------------------------------------------
  2020. BOOLEAN
  2021. KerbIsThisOurDomain(
  2022. IN PUNICODE_STRING DomainName
  2023. )
  2024. {
  2025. BOOLEAN Result;
  2026. KerbGlobalReadLock();
  2027. Result = KerbCompareUnicodeRealmNames(
  2028. DomainName,
  2029. &KerbGlobalDnsDomainName
  2030. ) ||
  2031. RtlEqualUnicodeString(
  2032. DomainName,
  2033. &KerbGlobalDomainName,
  2034. TRUE
  2035. );
  2036. KerbGlobalReleaseLock();
  2037. return(Result);
  2038. }
  2039. //+-------------------------------------------------------------------------
  2040. //
  2041. // Function: KerbGetOurDomainName
  2042. //
  2043. // Synopsis: Copies the machines dns domain name, if available,
  2044. // netbios otherwise.
  2045. //
  2046. // Effects:
  2047. //
  2048. // Arguments:
  2049. //
  2050. // Requires:
  2051. //
  2052. // Returns:
  2053. //
  2054. // Notes:
  2055. //
  2056. //
  2057. //--------------------------------------------------------------------------
  2058. NTSTATUS
  2059. KerbGetOurDomainName(
  2060. OUT PUNICODE_STRING DomainName
  2061. )
  2062. {
  2063. NTSTATUS Status;
  2064. KerbGlobalReadLock();
  2065. if (KerbGlobalDnsDomainName.Length != 0)
  2066. {
  2067. Status = KerbDuplicateString(
  2068. DomainName,
  2069. &KerbGlobalDnsDomainName
  2070. );
  2071. }
  2072. else
  2073. {
  2074. Status = KerbDuplicateString(
  2075. DomainName,
  2076. &KerbGlobalDomainName
  2077. );
  2078. }
  2079. KerbGlobalReleaseLock();
  2080. return(Status);
  2081. }
  2082. //+-------------------------------------------------------------------------
  2083. //
  2084. // Function: KerbGetGlobalRole
  2085. //
  2086. // Synopsis: Returns the current role of the machine
  2087. //
  2088. // Effects:
  2089. //
  2090. // Arguments:
  2091. //
  2092. // Requires:
  2093. //
  2094. // Returns:
  2095. //
  2096. // Notes:
  2097. //
  2098. //
  2099. //--------------------------------------------------------------------------
  2100. KERBEROS_MACHINE_ROLE
  2101. KerbGetGlobalRole(
  2102. VOID
  2103. )
  2104. {
  2105. KERBEROS_MACHINE_ROLE Role;
  2106. KerbGlobalReadLock();
  2107. Role = KerbGlobalRole;
  2108. KerbGlobalReleaseLock();
  2109. return(Role);
  2110. }
  2111. //+-------------------------------------------------------------------------
  2112. //
  2113. // Function: KerbSetComputerName
  2114. //
  2115. // Synopsis: Sets all computer-name related global variables
  2116. //
  2117. // Effects:
  2118. //
  2119. // Arguments:
  2120. //
  2121. // Requires:
  2122. //
  2123. // Returns:
  2124. //
  2125. // Notes:
  2126. //
  2127. //
  2128. //--------------------------------------------------------------------------
  2129. NTSTATUS
  2130. KerbSetComputerName(
  2131. VOID
  2132. )
  2133. {
  2134. UNICODE_STRING LocalMachineName;
  2135. STRING LocalKerbMachineName;
  2136. UNICODE_STRING OldMachineName;
  2137. STRING OldKerbMachineName;
  2138. ULONG ComputerNameLength;
  2139. NTSTATUS Status;
  2140. BOOLEAN LockHeld = FALSE;
  2141. #ifdef WIN32_CHICAGO
  2142. CHAR TempAnsiBuffer[MAX_COMPUTERNAME_LENGTH + 1];
  2143. ComputerNameLength = sizeof(TempAnsiBuffer);
  2144. #endif
  2145. LocalMachineName.Buffer = NULL;
  2146. LocalKerbMachineName.Buffer = NULL;
  2147. #ifndef WIN32_CHICAGO
  2148. ComputerNameLength = 0;
  2149. if (GetComputerNameW(
  2150. NULL,
  2151. &ComputerNameLength
  2152. ))
  2153. {
  2154. D_DebugLog((DEB_ERROR,"Succeeded to get computer name when failure expected! %ws, line %d\n", THIS_FILE, __LINE__));
  2155. Status = STATUS_UNSUCCESSFUL;
  2156. goto Cleanup;
  2157. }
  2158. LocalMachineName.Buffer = (LPWSTR) KerbAllocate(
  2159. ((ComputerNameLength + 1) * sizeof(WCHAR))
  2160. );
  2161. if (LocalMachineName.Buffer == NULL)
  2162. {
  2163. Status = STATUS_INSUFFICIENT_RESOURCES;
  2164. goto Cleanup;
  2165. }
  2166. #endif // WIN32_CHICAGO
  2167. #ifndef WIN32_CHICAGO
  2168. if (!GetComputerNameW(
  2169. LocalMachineName.Buffer,
  2170. &ComputerNameLength
  2171. ))
  2172. #else // WIN32_CHICAGO
  2173. if (!GetComputerName(
  2174. TempAnsiBuffer,
  2175. &ComputerNameLength
  2176. ))
  2177. #endif // WIN32_CHICAGO
  2178. {
  2179. D_DebugLog((DEB_ERROR,"Failed to get computer name: %d. %ws, line %d\n",GetLastError(), THIS_FILE, __LINE__));
  2180. Status = STATUS_UNSUCCESSFUL;
  2181. goto Cleanup;
  2182. }
  2183. #ifndef WIN32_CHICAGO
  2184. LocalMachineName.Length = (USHORT)(ComputerNameLength * sizeof(WCHAR));
  2185. LocalMachineName.MaximumLength = LocalMachineName.Length + sizeof(WCHAR);
  2186. #else
  2187. RtlCreateUnicodeStringFromAsciiz (&LocalMachineName, TempAnsiBuffer);
  2188. // KerbFree (TempAnsiBuffer);
  2189. #endif // WIN32_CHICAGO
  2190. //
  2191. // Build the ansi format
  2192. //
  2193. if (!KERB_SUCCESS(KerbUnicodeStringToKerbString(
  2194. &LocalKerbMachineName,
  2195. &LocalMachineName
  2196. )))
  2197. {
  2198. Status = STATUS_INSUFFICIENT_RESOURCES;
  2199. goto Cleanup;
  2200. }
  2201. //
  2202. // free the current globals, and update to point at new values.
  2203. //
  2204. KerbGlobalWriteLock();
  2205. LockHeld = TRUE;
  2206. OldMachineName = KerbGlobalMachineName;
  2207. OldKerbMachineName = KerbGlobalKerbMachineName;
  2208. KerbGlobalMachineName = LocalMachineName;
  2209. KerbGlobalKerbMachineName = LocalKerbMachineName;
  2210. //
  2211. // now, see if the netbios machine name changed versus the prior
  2212. // value.
  2213. //
  2214. if( OldMachineName.Buffer != NULL )
  2215. {
  2216. if(!RtlEqualUnicodeString( &OldMachineName, &LocalMachineName, FALSE ))
  2217. {
  2218. D_DebugLog((DEB_WARN,"Netbios computer name change detected.\n"));
  2219. KerbGlobalMachineNameChanged = TRUE;
  2220. }
  2221. }
  2222. KerbGlobalReleaseLock();
  2223. LockHeld = FALSE;
  2224. LocalMachineName.Buffer = NULL;
  2225. LocalKerbMachineName.Buffer = NULL;
  2226. KerbFreeString( &OldMachineName );
  2227. KerbFreeString( (PUNICODE_STRING)&OldKerbMachineName );
  2228. Status = STATUS_SUCCESS;
  2229. Cleanup:
  2230. if( LockHeld )
  2231. {
  2232. KerbGlobalReleaseLock();
  2233. }
  2234. KerbFreeString( &LocalMachineName );
  2235. KerbFreeString( (PUNICODE_STRING)&LocalKerbMachineName );
  2236. return Status;
  2237. }
  2238. //
  2239. //
  2240. // Routine Description:
  2241. //
  2242. // This function checks the system to see if
  2243. // we are running on the personal version of
  2244. // the operating system.
  2245. //
  2246. // The personal version is denoted by the product
  2247. // id equal to WINNT, which is really workstation,
  2248. // and the product suite containing the personal
  2249. // suite string.
  2250. //
  2251. BOOLEAN
  2252. KerbRunningPersonal(
  2253. VOID
  2254. )
  2255. {
  2256. OSVERSIONINFOEXW OsVer = {0};
  2257. ULONGLONG ConditionMask = 0;
  2258. OsVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  2259. OsVer.wSuiteMask = VER_SUITE_PERSONAL;
  2260. OsVer.wProductType = VER_NT_WORKSTATION;
  2261. VER_SET_CONDITION( ConditionMask, VER_PRODUCT_TYPE, VER_EQUAL );
  2262. VER_SET_CONDITION( ConditionMask, VER_SUITENAME, VER_AND );
  2263. return RtlVerifyVersionInfo( &OsVer,
  2264. VER_PRODUCT_TYPE | VER_SUITENAME,
  2265. ConditionMask) == STATUS_SUCCESS;
  2266. }
  2267. BOOLEAN
  2268. KerbRunningServer(
  2269. VOID
  2270. )
  2271. {
  2272. OSVERSIONINFOEXW OsVer = {0};
  2273. ULONGLONG ConditionMask = 0;
  2274. OsVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  2275. OsVer.wProductType = VER_NT_DOMAIN_CONTROLLER;
  2276. VER_SET_CONDITION( ConditionMask, VER_PRODUCT_TYPE, VER_GREATER_EQUAL );
  2277. return RtlVerifyVersionInfo( &OsVer,
  2278. VER_PRODUCT_TYPE ,
  2279. ConditionMask) == STATUS_SUCCESS;
  2280. }
  2281. //+-------------------------------------------------------------------------
  2282. //
  2283. // Function: KerbSetDomainName
  2284. //
  2285. // Synopsis: Sets all domain-name related global variables
  2286. //
  2287. // Effects:
  2288. //
  2289. // Arguments:
  2290. //
  2291. // Requires:
  2292. //
  2293. // Returns:
  2294. //
  2295. // Notes:
  2296. //
  2297. //
  2298. //--------------------------------------------------------------------------
  2299. NTSTATUS
  2300. KerbSetDomainName(
  2301. IN PUNICODE_STRING DomainName,
  2302. IN PUNICODE_STRING DnsDomainName,
  2303. IN PSID DomainSid,
  2304. IN GUID DomainGuid
  2305. )
  2306. {
  2307. NTSTATUS Status = STATUS_SUCCESS;
  2308. BOOLEAN AcquiredLock = FALSE;
  2309. UNICODE_STRING TempDomainName = {0};
  2310. UNICODE_STRING TempDnsDomainName = {0};
  2311. UNICODE_STRING TempMachineServiceName = {0};
  2312. PKERB_INTERNAL_NAME TempMitMachineServiceName = NULL;
  2313. PSID TempDomainSid = NULL;
  2314. UNICODE_STRING TempString;
  2315. WCHAR MachineAccountName[CNLEN + 2]; // for null and '$'
  2316. UNICODE_STRING DnsString = {0};
  2317. #ifndef WIN32_CHICAGO
  2318. LUID SystemLogonId = SYSTEM_LUID;
  2319. LUID NetworkServiceLogonId = NETWORKSERVICE_LUID;
  2320. PKERB_LOGON_SESSION SystemLogonSession = NULL;
  2321. PKERB_LOGON_SESSION NetworkServiceLogonSession = NULL;
  2322. #endif
  2323. static TimeStamp KerbSetDomainNameTime = {0};
  2324. static ULONG NumOfUpdatedLuids = 0;
  2325. NtQuerySystemTime(&KerbSetDomainNameTime);
  2326. //
  2327. // Copy the domain name / sid
  2328. //
  2329. Status = KerbDuplicateString(
  2330. &TempDomainName,
  2331. DomainName
  2332. );
  2333. if (!NT_SUCCESS(Status))
  2334. {
  2335. goto Cleanup;
  2336. }
  2337. Status = KerbDuplicateString(
  2338. &TempDnsDomainName,
  2339. DnsDomainName
  2340. );
  2341. if (!NT_SUCCESS(Status))
  2342. {
  2343. goto Cleanup;
  2344. }
  2345. //
  2346. // If we are in an NT domain, uppercase the dns domain name
  2347. //
  2348. #ifndef WIN32_CHICAGO
  2349. if (DomainSid != NULL)
  2350. #endif
  2351. {
  2352. Status = RtlUpcaseUnicodeString(
  2353. &TempDnsDomainName,
  2354. &TempDnsDomainName,
  2355. FALSE // don't allocate
  2356. );
  2357. if (!NT_SUCCESS(Status))
  2358. {
  2359. goto Cleanup;
  2360. }
  2361. }
  2362. #ifndef WIN32_CHICAGO
  2363. if (DomainSid != NULL)
  2364. {
  2365. Status = KerbDuplicateSid(
  2366. &TempDomainSid,
  2367. DomainSid
  2368. );
  2369. if (!NT_SUCCESS(Status))
  2370. {
  2371. goto Cleanup;
  2372. }
  2373. }
  2374. #endif
  2375. //
  2376. // Create the new machine names
  2377. //
  2378. KerbGlobalReadLock();
  2379. ASSERT( (KerbGlobalMachineName.Length <= (CNLEN * sizeof(WCHAR)) ) );
  2380. RtlCopyMemory(
  2381. MachineAccountName,
  2382. KerbGlobalMachineName.Buffer,
  2383. KerbGlobalMachineName.Length
  2384. );
  2385. MachineAccountName[KerbGlobalMachineName.Length/sizeof(WCHAR)] = SSI_ACCOUNT_NAME_POSTFIX_CHAR;
  2386. MachineAccountName[1 + KerbGlobalMachineName.Length/sizeof(WCHAR)] = L'\0';
  2387. KerbGlobalReleaseLock();
  2388. RtlInitUnicodeString(
  2389. &TempString,
  2390. MachineAccountName
  2391. );
  2392. Status = KerbDuplicateString(
  2393. &TempMachineServiceName,
  2394. &TempString
  2395. );
  2396. if (!NT_SUCCESS(Status))
  2397. {
  2398. goto Cleanup;
  2399. }
  2400. #ifndef WIN32_CHICAGO
  2401. //
  2402. // Now build the MIT version of our machine service name
  2403. //
  2404. Status = KerbGetDnsHostName(
  2405. &DnsString
  2406. );
  2407. if (!NT_SUCCESS(Status))
  2408. {
  2409. goto Cleanup;
  2410. }
  2411. RtlInitUnicodeString(
  2412. &TempString,
  2413. KERB_HOST_STRING
  2414. );
  2415. if (!KERB_SUCCESS(KerbBuildFullServiceKdcName(
  2416. &DnsString,
  2417. &TempString,
  2418. KRB_NT_SRV_HST,
  2419. &TempMitMachineServiceName
  2420. )))
  2421. {
  2422. Status = STATUS_INSUFFICIENT_RESOURCES;
  2423. goto Cleanup;
  2424. }
  2425. //
  2426. // Acquire the global lock so we can update the data
  2427. //
  2428. if (!KerbGlobalWriteLock())
  2429. {
  2430. D_DebugLog((DEB_ERROR, "Failed to acquire global resource. Not changing domain. %ws, line %d\n", THIS_FILE, __LINE__));
  2431. goto Cleanup;
  2432. }
  2433. AcquiredLock = TRUE;
  2434. #endif // WIN32_CHICAGO
  2435. //
  2436. // Copy all the data to the global structures
  2437. //
  2438. // If we're NT4, we don't have a dns domain name
  2439. // If we're joined to an MIT domain, we don't have a domain GUID and we
  2440. // have a dns domain name
  2441. if ((DomainGuid == GUID_NULL) && (TempDnsDomainName.Length == 0))
  2442. {
  2443. KerbGlobalDomainIsPreNT5 = TRUE;
  2444. }
  2445. else
  2446. {
  2447. KerbGlobalDomainIsPreNT5 = FALSE;
  2448. }
  2449. KerbFreeString(&KerbGlobalDomainName);
  2450. KerbGlobalDomainName = TempDomainName;
  2451. TempDomainName.Buffer = NULL;
  2452. KerbFreeString(&KerbGlobalDnsDomainName);
  2453. KerbGlobalDnsDomainName = TempDnsDomainName;
  2454. TempDnsDomainName.Buffer = NULL;
  2455. KerbFreeString(&KerbGlobalMachineServiceName);
  2456. KerbGlobalMachineServiceName = TempMachineServiceName;
  2457. TempMachineServiceName.Buffer = NULL;
  2458. #ifndef WIN32_CHICAGO
  2459. KerbFreeKdcName(&KerbGlobalMitMachineServiceName);
  2460. KerbGlobalMitMachineServiceName = TempMitMachineServiceName;
  2461. TempMitMachineServiceName = NULL;
  2462. if (KerbGlobalDomainSid != NULL)
  2463. {
  2464. KerbFree(KerbGlobalDomainSid);
  2465. }
  2466. KerbGlobalDomainSid = TempDomainSid;
  2467. TempDomainSid = NULL;
  2468. //
  2469. // Update the role on non DCs. The role of a DC never changes.
  2470. // Demotion requires a reboot so that the domain controller role
  2471. // will not change.
  2472. //
  2473. if (KerbGlobalRole != KerbRoleDomainController)
  2474. {
  2475. if (KerbRunningPersonal())
  2476. {
  2477. KerbGlobalRole = KerbRoleRealmlessWksta;
  2478. }
  2479. else if (DomainSid == NULL )
  2480. {
  2481. // No machine account, nor associate w/ MIT realm
  2482. if (DnsDomainName->Length == 0 )
  2483. {
  2484. KerbGlobalRole = KerbRoleRealmlessWksta;
  2485. }
  2486. // Member of MIT realm, but not a domain
  2487. else
  2488. {
  2489. KerbGlobalRole = KerbRoleStandalone;
  2490. }
  2491. }
  2492. else
  2493. {
  2494. KerbGlobalRole = KerbRoleWorkstation;
  2495. }
  2496. }
  2497. KerbGlobalReleaseLock();
  2498. AcquiredLock = FALSE;
  2499. //
  2500. // Update the system/networkservice logon session, if there is one
  2501. //
  2502. SystemLogonSession = KerbReferenceLogonSession(
  2503. &SystemLogonId,
  2504. FALSE // don't unlink
  2505. );
  2506. if (SystemLogonSession)
  2507. {
  2508. KerbWriteLockLogonSessions(SystemLogonSession);
  2509. D_DebugLog((DEB_TRACE_CRED,
  2510. "KerbSetDomainName change localsystem domain name from %wZ to %wZ\n",
  2511. &SystemLogonSession->PrimaryCredentials.DomainName,
  2512. DnsDomainName));
  2513. //
  2514. // detect fake updates
  2515. //
  2516. if (!RtlEqualUnicodeString(
  2517. &SystemLogonSession->PrimaryCredentials.DomainName,
  2518. DnsDomainName,
  2519. TRUE
  2520. ))
  2521. {
  2522. KerbFreeString(&SystemLogonSession->PrimaryCredentials.DomainName);
  2523. Status = KerbDuplicateString(
  2524. &SystemLogonSession->PrimaryCredentials.DomainName ,
  2525. DnsDomainName
  2526. );
  2527. if (!NT_SUCCESS(Status))
  2528. {
  2529. goto Cleanup;
  2530. }
  2531. KerbPurgeTicketCache(&SystemLogonSession->PrimaryCredentials.ServerTicketCache);
  2532. KerbPurgeTicketCache(&SystemLogonSession->PrimaryCredentials.AuthenticationTicketCache);
  2533. KerbPurgeTicketCache(&SystemLogonSession->PrimaryCredentials.S4UTicketCache);
  2534. SystemLogonSession->LogonSessionFlags |= KERB_LOGON_DEFERRED;
  2535. NumOfUpdatedLuids++;
  2536. }
  2537. KerbUnlockLogonSessions(SystemLogonSession);
  2538. }
  2539. NetworkServiceLogonSession = KerbReferenceLogonSession(
  2540. &NetworkServiceLogonId,
  2541. FALSE // don't unlink
  2542. );
  2543. if (NetworkServiceLogonSession != NULL)
  2544. {
  2545. KerbWriteLockLogonSessions(NetworkServiceLogonSession);
  2546. D_DebugLog((DEB_TRACE_CRED,
  2547. "KerbSetDomainName change networkservice domain name from %wZ to %wZ\n",
  2548. &NetworkServiceLogonSession->PrimaryCredentials.DomainName,
  2549. DnsDomainName));
  2550. //
  2551. // detect fake updates
  2552. //
  2553. if (!RtlEqualUnicodeString(
  2554. &NetworkServiceLogonSession->PrimaryCredentials.DomainName,
  2555. DnsDomainName,
  2556. TRUE
  2557. ))
  2558. {
  2559. KerbFreeString(&NetworkServiceLogonSession->PrimaryCredentials.DomainName);
  2560. Status = KerbDuplicateString(
  2561. &NetworkServiceLogonSession->PrimaryCredentials.DomainName ,
  2562. DnsDomainName
  2563. );
  2564. if (!NT_SUCCESS(Status))
  2565. {
  2566. goto Cleanup;
  2567. }
  2568. KerbPurgeTicketCache(&NetworkServiceLogonSession->PrimaryCredentials.ServerTicketCache);
  2569. KerbPurgeTicketCache(&NetworkServiceLogonSession->PrimaryCredentials.AuthenticationTicketCache);
  2570. KerbPurgeTicketCache(&NetworkServiceLogonSession->PrimaryCredentials.S4UTicketCache);
  2571. NetworkServiceLogonSession->LogonSessionFlags |= KERB_LOGON_DEFERRED;
  2572. NumOfUpdatedLuids++;
  2573. }
  2574. KerbUnlockLogonSessions(NetworkServiceLogonSession);
  2575. }
  2576. #endif
  2577. Cleanup:
  2578. #ifndef WIN32_CHICAGO
  2579. if (AcquiredLock)
  2580. {
  2581. KerbGlobalReleaseLock();
  2582. }
  2583. #endif // WIN32_CHICAGO
  2584. KerbFreeString(
  2585. &DnsString
  2586. );
  2587. KerbFreeString(
  2588. &TempDomainName
  2589. );
  2590. KerbFreeString(
  2591. &TempDnsDomainName
  2592. );
  2593. KerbFreeString(
  2594. &TempMachineServiceName
  2595. );
  2596. #ifndef WIN32_CHICAGO
  2597. KerbFreeKdcName(
  2598. &TempMitMachineServiceName
  2599. );
  2600. if (TempDomainSid != NULL)
  2601. {
  2602. KerbFree(TempDomainSid);
  2603. }
  2604. if (SystemLogonSession != NULL)
  2605. {
  2606. KerbDereferenceLogonSession(SystemLogonSession);
  2607. }
  2608. if (NetworkServiceLogonSession != NULL)
  2609. {
  2610. KerbDereferenceLogonSession(NetworkServiceLogonSession);
  2611. }
  2612. #endif
  2613. return(Status);
  2614. }
  2615. #ifndef WIN32_CHICAGO
  2616. //+-------------------------------------------------------------------------
  2617. //
  2618. // Function: KerbLoadKdc
  2619. //
  2620. // Synopsis: Loads kdcsvc.dll and gets the address of important functions
  2621. //
  2622. // Effects:
  2623. //
  2624. // Arguments:
  2625. //
  2626. // Requires:
  2627. //
  2628. // Returns: STATUS_SUCCESS if kdcsvc.dll could be loaded and the
  2629. // necessary entrypoints found.
  2630. //
  2631. // Notes:
  2632. //
  2633. //
  2634. //--------------------------------------------------------------------------
  2635. NTSTATUS
  2636. KerbLoadKdc(
  2637. VOID
  2638. )
  2639. {
  2640. NTSTATUS Status = STATUS_SUCCESS;
  2641. KerbKdcHandle = LoadLibraryA("kdcsvc.dll");
  2642. if (KerbKdcHandle == NULL) {
  2643. D_DebugLog((DEB_WARN,"Failed to load kdcsvc.dll: %d\n",GetLastError()));
  2644. return(STATUS_DLL_NOT_FOUND);
  2645. }
  2646. KerbKdcVerifyPac = (PKDC_VERIFY_PAC_ROUTINE) GetProcAddress(
  2647. KerbKdcHandle,
  2648. KDC_VERIFY_PAC_NAME
  2649. );
  2650. if (KerbKdcVerifyPac == NULL)
  2651. {
  2652. D_DebugLog((DEB_WARN, "Failed to get proc address for KdcVerifyPac: %d\n",
  2653. GetLastError()));
  2654. Status = STATUS_PROCEDURE_NOT_FOUND;
  2655. goto Cleanup;
  2656. }
  2657. KerbKdcGetTicket = (PKDC_GET_TICKET_ROUTINE) GetProcAddress(
  2658. KerbKdcHandle,
  2659. KDC_GET_TICKET_NAME
  2660. );
  2661. if (KerbKdcGetTicket == NULL)
  2662. {
  2663. D_DebugLog((DEB_WARN,"Failed to get proc address for KdcGetTicket: %d\n",
  2664. GetLastError()));
  2665. Status = STATUS_PROCEDURE_NOT_FOUND;
  2666. goto Cleanup;
  2667. }
  2668. KerbKdcChangePassword = (PKDC_GET_TICKET_ROUTINE) GetProcAddress(
  2669. KerbKdcHandle,
  2670. KDC_CHANGE_PASSWORD_NAME
  2671. );
  2672. if (KerbKdcChangePassword == NULL)
  2673. {
  2674. D_DebugLog((DEB_WARN,"Failed to get proc address for KdcChangePassword: %d\n",
  2675. GetLastError()));
  2676. Status = STATUS_PROCEDURE_NOT_FOUND;
  2677. goto Cleanup;
  2678. }
  2679. KerbKdcFreeMemory = (PKDC_FREE_MEMORY_ROUTINE) GetProcAddress(
  2680. KerbKdcHandle,
  2681. KDC_FREE_MEMORY_NAME
  2682. );
  2683. if (KerbKdcFreeMemory == NULL)
  2684. {
  2685. D_DebugLog((DEB_WARN,"Failed to get proc address for KdcFreeMemory: %d\n",
  2686. GetLastError()));
  2687. Status = STATUS_PROCEDURE_NOT_FOUND;
  2688. goto Cleanup;
  2689. }
  2690. Cleanup:
  2691. if (!NT_SUCCESS(Status))
  2692. {
  2693. if (KerbKdcHandle != NULL)
  2694. {
  2695. FreeLibrary(KerbKdcHandle);
  2696. KerbKdcHandle = NULL;
  2697. }
  2698. }
  2699. return(Status);
  2700. }
  2701. //+-------------------------------------------------------------------------
  2702. //
  2703. // Function: KerbDomainChangeCallback
  2704. //
  2705. // Synopsis: Function to be called when domain changes
  2706. //
  2707. // Effects:
  2708. //
  2709. // Arguments:
  2710. //
  2711. // Requires:
  2712. //
  2713. // Returns:
  2714. //
  2715. // Notes:
  2716. //
  2717. //
  2718. //--------------------------------------------------------------------------
  2719. VOID NTAPI
  2720. KerbDomainChangeCallback(
  2721. IN POLICY_NOTIFICATION_INFORMATION_CLASS ChangedInfoClass
  2722. )
  2723. {
  2724. NTSTATUS Status = STATUS_SUCCESS;
  2725. PLSAPR_POLICY_INFORMATION Policy = NULL;
  2726. //
  2727. // We only care about domain dns information
  2728. //
  2729. if (ChangedInfoClass != PolicyNotifyDnsDomainInformation)
  2730. {
  2731. return;
  2732. }
  2733. //
  2734. // Get the new domain information
  2735. //
  2736. Status = I_LsaIQueryInformationPolicyTrusted(
  2737. PolicyDnsDomainInformation,
  2738. &Policy
  2739. );
  2740. if (!NT_SUCCESS(Status))
  2741. {
  2742. D_DebugLog((DEB_ERROR,"Failed to query domain dns information %x - not updating. %ws, line %d\n",
  2743. Status, THIS_FILE, __LINE__));
  2744. goto Cleanup;
  2745. }
  2746. //
  2747. // update computer name info.
  2748. //
  2749. Status = KerbSetComputerName();
  2750. if (!NT_SUCCESS(Status))
  2751. {
  2752. D_DebugLog((DEB_ERROR,"Failed to set computer name: 0x%x. %ws, line %d\n",Status, THIS_FILE, __LINE__));
  2753. goto Cleanup;
  2754. }
  2755. Status = KerbSetDomainName(
  2756. (PUNICODE_STRING) &Policy->PolicyDnsDomainInfo.Name,
  2757. (PUNICODE_STRING) &Policy->PolicyDnsDomainInfo.DnsDomainName,
  2758. (PSID) Policy->PolicyDnsDomainInfo.Sid,
  2759. (GUID) Policy->PolicyDnsDomainInfo.DomainGuid
  2760. );
  2761. if (!NT_SUCCESS(Status))
  2762. {
  2763. D_DebugLog((DEB_ERROR,"Failed to set domain name: 0x%x. %ws, line %d\n",Status, THIS_FILE, __LINE__));
  2764. goto Cleanup;
  2765. }
  2766. //
  2767. // Domain Name has changed. So, the cache in the registry will
  2768. // have changed too. And we haven't rebooted yet.
  2769. //
  2770. KerbSetKdcData(TRUE, FALSE);
  2771. Cleanup:
  2772. if (Policy != NULL)
  2773. {
  2774. I_LsaIFree_LSAPR_POLICY_INFORMATION(
  2775. PolicyDnsDomainInformation,
  2776. Policy
  2777. );
  2778. }
  2779. return;
  2780. }
  2781. //+-------------------------------------------------------------------------
  2782. //
  2783. // Function: KerbRegisterForDomainChange
  2784. //
  2785. // Synopsis: Register with the LSA to be notified of domain changes
  2786. //
  2787. // Effects:
  2788. //
  2789. // Arguments:
  2790. //
  2791. // Requires:
  2792. //
  2793. // Returns:
  2794. //
  2795. // Notes:
  2796. //
  2797. //
  2798. //--------------------------------------------------------------------------
  2799. NTSTATUS
  2800. KerbRegisterForDomainChange(
  2801. VOID
  2802. )
  2803. {
  2804. NTSTATUS Status = STATUS_SUCCESS;
  2805. Status = I_LsaIRegisterPolicyChangeNotificationCallback(
  2806. KerbDomainChangeCallback,
  2807. PolicyNotifyDnsDomainInformation
  2808. );
  2809. if (!NT_SUCCESS(Status))
  2810. {
  2811. D_DebugLog((DEB_ERROR,"Failed to register for domain change notification: 0x%x. %ws, line %d\n",Status, THIS_FILE, __LINE__));
  2812. }
  2813. return(Status);
  2814. }
  2815. //+-------------------------------------------------------------------------
  2816. //
  2817. // Function: KerbUnregisterForDomainChange
  2818. //
  2819. // Synopsis: Unregister for domain change notification
  2820. //
  2821. // Effects:
  2822. //
  2823. // Arguments:
  2824. //
  2825. // Requires:
  2826. //
  2827. // Returns:
  2828. //
  2829. // Notes:
  2830. //
  2831. //
  2832. //--------------------------------------------------------------------------
  2833. VOID
  2834. KerbUnregisterForDomainChange(
  2835. VOID
  2836. )
  2837. {
  2838. (VOID) I_LsaIUnregisterPolicyChangeNotificationCallback(
  2839. KerbDomainChangeCallback,
  2840. PolicyNotifyDnsDomainInformation
  2841. );
  2842. }
  2843. //+-------------------------------------------------------------------------
  2844. //
  2845. // Function: KerbUpdateGlobalAddresses
  2846. //
  2847. // Synopsis: Updates the global array of addresses with information from
  2848. // netlogon.
  2849. //
  2850. // Effects:
  2851. //
  2852. // Arguments:
  2853. //
  2854. // Requires:
  2855. //
  2856. // Returns:
  2857. //
  2858. // Notes: Ideally, we should also have called WSAProviderConfigChange to be
  2859. // notified of when tcp is added/removed. But, we can take advantage
  2860. // of the fact that netlogon is registered for changes in ipaddress
  2861. // so, even though, change of ipaddress & xports notifications are
  2862. // async, we will get to know of it, so, it suffices to rely on
  2863. // netlogon rather than register for a notification change.
  2864. //
  2865. //
  2866. //--------------------------------------------------------------------------
  2867. NTSTATUS
  2868. KerbUpdateGlobalAddresses(
  2869. IN PSOCKET_ADDRESS NewAddresses,
  2870. IN ULONG NewAddressCount
  2871. )
  2872. {
  2873. PSOCKADDR_IN GlobalIpAddresses = NULL;
  2874. ULONG Index;
  2875. ULONG AddressCount = 0;
  2876. WSAPROTOCOL_INFO *lpProtocolBuf = NULL;
  2877. DWORD dwBufLen = 0;
  2878. INT protocols[2];
  2879. int nRet = 0;
  2880. BOOLEAN NoTcpInstalled = FALSE;
  2881. GlobalIpAddresses = (PSOCKADDR_IN) KerbAllocate(sizeof(SOCKADDR_IN) * NewAddressCount);
  2882. if (GlobalIpAddresses == NULL)
  2883. {
  2884. return(STATUS_INSUFFICIENT_RESOURCES);
  2885. }
  2886. for (Index = 0; Index < NewAddressCount ; Index++ )
  2887. {
  2888. if ((NewAddresses[Index].iSockaddrLength == sizeof(SOCKADDR)) &&
  2889. (NewAddresses[Index].lpSockaddr->sa_family == AF_INET))
  2890. {
  2891. RtlCopyMemory(
  2892. &GlobalIpAddresses[AddressCount++],
  2893. NewAddresses[Index].lpSockaddr,
  2894. sizeof(SOCKADDR_IN)
  2895. );
  2896. }
  2897. else
  2898. {
  2899. D_DebugLog((DEB_ERROR,"Netlogon handed us a address of length or type %d, %d. %ws, line %d\n",
  2900. NewAddresses[Index].iSockaddrLength,
  2901. NewAddresses[Index].lpSockaddr->sa_family,
  2902. THIS_FILE, __LINE__ ));
  2903. }
  2904. }
  2905. //
  2906. // winsock is already initialized by now, or we would not have
  2907. // gotten so far. Check if TCP s an available xport
  2908. //
  2909. protocols[0] = IPPROTO_TCP;
  2910. protocols[1] = NULL;
  2911. nRet = WSAEnumProtocols(protocols, lpProtocolBuf, &dwBufLen);
  2912. if (nRet == 0)
  2913. {
  2914. //
  2915. // Tcp is not installed as a xport.
  2916. //
  2917. D_DebugLog((DEB_TRACE_SOCK,"WSAEnumProtocols returned 0x%x. %ws, line %d\n", nRet, THIS_FILE, __LINE__ ));
  2918. NoTcpInstalled = TRUE;
  2919. }
  2920. //
  2921. // Copy them into the global for others to use
  2922. //
  2923. KerbGlobalWriteLock();
  2924. if (KerbGlobalIpAddresses != NULL)
  2925. {
  2926. KerbFree(KerbGlobalIpAddresses);
  2927. }
  2928. KerbGlobalIpAddresses = GlobalIpAddresses;
  2929. KerbGlobalIpAddressCount = AddressCount;
  2930. KerbGlobalIpAddressesInitialized = TRUE;
  2931. KerbGlobalNoTcpUdp = NoTcpInstalled;
  2932. KerbGlobalReleaseLock();
  2933. return(STATUS_SUCCESS);
  2934. }
  2935. #ifdef RESTRICTED_TOKEN
  2936. //+-------------------------------------------------------------------------
  2937. //
  2938. // Function: KerbGetTokenInformation
  2939. //
  2940. // Synopsis: Allocates and returns token information
  2941. //
  2942. // Effects:
  2943. //
  2944. // Arguments:
  2945. //
  2946. // Requires:
  2947. //
  2948. // Returns:
  2949. //
  2950. // Notes:
  2951. //
  2952. //
  2953. //--------------------------------------------------------------------------
  2954. NTSTATUS
  2955. KerbGetTokenInformation(
  2956. IN HANDLE TokenHandle,
  2957. IN TOKEN_INFORMATION_CLASS InformationClass,
  2958. IN OUT PVOID * Buffer
  2959. )
  2960. {
  2961. NTSTATUS Status = STATUS_SUCCESS;
  2962. ULONG BufferSize = 0;
  2963. //
  2964. // First retrieve the restricted sids
  2965. //
  2966. Status = NtQueryInformationToken(
  2967. TokenHandle,
  2968. InformationClass,
  2969. NULL,
  2970. 0,
  2971. &BufferSize
  2972. );
  2973. if (Status != STATUS_BUFFER_TOO_SMALL)
  2974. {
  2975. goto Cleanup;
  2976. }
  2977. *Buffer = KerbAllocate(BufferSize);
  2978. if (*Buffer == NULL)
  2979. {
  2980. Status = STATUS_INSUFFICIENT_RESOURCES;
  2981. goto Cleanup;
  2982. }
  2983. Status = NtQueryInformationToken(
  2984. TokenHandle,
  2985. InformationClass,
  2986. *Buffer,
  2987. BufferSize,
  2988. &BufferSize
  2989. );
  2990. if (!NT_SUCCESS(Status))
  2991. {
  2992. goto Cleanup;
  2993. }
  2994. Cleanup:
  2995. return(Status);
  2996. }
  2997. //+-------------------------------------------------------------------------
  2998. //
  2999. // Function: KerbCaptureTokenRestrictions
  3000. //
  3001. // Synopsis: Captures the restrictions of a restricted token
  3002. //
  3003. // Effects:
  3004. //
  3005. // Arguments: TokenHandle - token handle open for TOKEN_QUERY access
  3006. //
  3007. // Requires:
  3008. //
  3009. // Returns:
  3010. //
  3011. // Notes:
  3012. //
  3013. //
  3014. //--------------------------------------------------------------------------
  3015. NTSTATUS
  3016. KerbCaptureTokenRestrictions(
  3017. IN HANDLE TokenHandle,
  3018. OUT PKERB_AUTHORIZATION_DATA Restrictions
  3019. )
  3020. {
  3021. PTOKEN_GROUPS Groups = NULL;
  3022. PTOKEN_GROUPS RestrictedSids = NULL;
  3023. PTOKEN_PRIVILEGES Privileges = NULL;
  3024. PTOKEN_PRIVILEGES DeletePrivileges = NULL;
  3025. NTSTATUS Status = STATUS_SUCCESS;
  3026. ULONG BufferSize = 0;
  3027. ULONG Index,Index2,LastIndex;
  3028. KERB_TOKEN_RESTRICTIONS TokenRestrictions = {0};
  3029. Status = KerbGetTokenInformation(
  3030. TokenHandle,
  3031. TokenRestrictedSids,
  3032. (PVOID *) &RestrictedSids
  3033. );
  3034. if (!NT_SUCCESS(Status))
  3035. {
  3036. goto Cleanup;
  3037. }
  3038. Status = KerbGetTokenInformation(
  3039. TokenHandle,
  3040. TokenGroups,
  3041. (PVOID *) &Groups
  3042. );
  3043. if (!NT_SUCCESS(Status))
  3044. {
  3045. goto Cleanup;
  3046. }
  3047. Status = KerbGetTokenInformation(
  3048. TokenHandle,
  3049. TokenPrivileges,
  3050. (PVOID *) &Privileges
  3051. );
  3052. if (!NT_SUCCESS(Status))
  3053. {
  3054. goto Cleanup;
  3055. }
  3056. //
  3057. // Now build the list of just the restricted privileges & groups
  3058. //
  3059. //
  3060. // First, find what groups are restricted.
  3061. //
  3062. LastIndex = 0;
  3063. for (Index = 0; Index < Groups->GroupCount ; Index++ )
  3064. {
  3065. if ((Groups->Groups[Index].Attributes & SE_GROUP_USE_FOR_DENY_ONLY) != 0)
  3066. {
  3067. if (LastIndex != Index)
  3068. {
  3069. Groups->Groups[LastIndex].Sid = Groups->Groups[Index].Sid;
  3070. Groups->Groups[LastIndex].Attributes = 0;
  3071. }
  3072. LastIndex++;
  3073. }
  3074. }
  3075. Groups->GroupCount = LastIndex;
  3076. if (LastIndex != 0)
  3077. {
  3078. TokenRestrictions.GroupsToDisable = (PPAC_TOKEN_GROUPS) Groups;
  3079. TokenRestrictions.Flags |= KERB_TOKEN_RESTRICTION_DISABLE_GROUPS;
  3080. }
  3081. //
  3082. // Add the restricted sids
  3083. //
  3084. if (RestrictedSids->GroupCount != 0)
  3085. {
  3086. for (Index = 0; Index < RestrictedSids->GroupCount ; Index++ )
  3087. {
  3088. RestrictedSids->Groups[Index].Attributes = 0;
  3089. }
  3090. TokenRestrictions.RestrictedSids = (PPAC_TOKEN_GROUPS) RestrictedSids;
  3091. TokenRestrictions.Flags |= KERB_TOKEN_RESTRICTION_RESTRICT_SIDS;
  3092. }
  3093. //
  3094. // Now make a list of all the privileges that _aren't_ enabled
  3095. //
  3096. SafeAllocaAllocate(DeletePrivileges,
  3097. sizeof(TOKEN_PRIVILEGES) +
  3098. sizeof(LUID_AND_ATTRIBUTES) *
  3099. (1 + SE_MAX_WELL_KNOWN_PRIVILEGE - SE_MIN_WELL_KNOWN_PRIVILEGE));
  3100. if (DeletePrivileges == NULL)
  3101. {
  3102. Status = STATUS_INSUFFICIENT_RESOURCES;
  3103. goto Cleanup;
  3104. }
  3105. DeletePrivileges->PrivilegeCount = 0;
  3106. //
  3107. // Find out what privileges haven't been enabled
  3108. //
  3109. LastIndex = 0;
  3110. for (Index = SE_MIN_WELL_KNOWN_PRIVILEGE; Index <= SE_MAX_WELL_KNOWN_PRIVILEGE ; Index++ )
  3111. {
  3112. LUID TempLuid;
  3113. BOOLEAN Found = FALSE;
  3114. TempLuid = RtlConvertUlongToLuid(Index);
  3115. for (Index2 = 0; Index2 < Privileges->PrivilegeCount ; Index2++ )
  3116. {
  3117. if (RtlEqualLuid(&Privileges->Privileges[Index2].Luid,&TempLuid) &&
  3118. ((Privileges->Privileges[Index2].Attributes & SE_PRIVILEGE_ENABLED) != 0))
  3119. {
  3120. Found = TRUE;
  3121. break;
  3122. }
  3123. }
  3124. if (!Found)
  3125. {
  3126. DeletePrivileges->Privileges[LastIndex].Luid = TempLuid;
  3127. DeletePrivileges->Privileges[LastIndex].Attributes = 0;
  3128. LastIndex++;
  3129. }
  3130. }
  3131. DeletePrivileges->PrivilegeCount = LastIndex;
  3132. if (LastIndex != 0)
  3133. {
  3134. TokenRestrictions.PrivilegesToDelete = (PPAC_TOKEN_PRIVILEGES) DeletePrivileges;
  3135. TokenRestrictions.Flags |= KERB_TOKEN_RESTRICTION_DELETE_PRIVS;
  3136. }
  3137. Restrictions->value.auth_data_type = KERB_AUTH_DATA_TOKEN_RESTRICTIONS;
  3138. Status = PAC_EncodeTokenRestrictions(
  3139. &TokenRestrictions,
  3140. &Restrictions->value.auth_data.value,
  3141. &Restrictions->value.auth_data.length
  3142. );
  3143. Cleanup:
  3144. if (Groups != NULL)
  3145. {
  3146. KerbFree(Groups);
  3147. }
  3148. if (RestrictedSids != NULL)
  3149. {
  3150. KerbFree(RestrictedSids);
  3151. }
  3152. if (Privileges != NULL)
  3153. {
  3154. KerbFree(Privileges);
  3155. }
  3156. SafeAllocaFree(DeletePrivileges);
  3157. return(Status);
  3158. }
  3159. //+-------------------------------------------------------------------------
  3160. //
  3161. // Function: KerbAddRestrictionsToCredential
  3162. //
  3163. // Synopsis: Captures client'st token restrictions and sticks them in
  3164. // the credential
  3165. //
  3166. // Effects:
  3167. //
  3168. // Arguments:
  3169. //
  3170. // Requires:
  3171. //
  3172. // Returns:
  3173. //
  3174. // Notes:
  3175. //
  3176. //
  3177. //--------------------------------------------------------------------------
  3178. NTSTATUS
  3179. KerbAddRestrictionsToCredential(
  3180. IN PKERB_LOGON_SESSION LogonSession,
  3181. IN PKERB_CREDENTIAL Credential
  3182. )
  3183. {
  3184. NTSTATUS Status = STATUS_SUCCESS;
  3185. PKERB_AUTHORIZATION_DATA AuthData = NULL;
  3186. BOOLEAN CrossRealm;
  3187. PKERB_TICKET_CACHE_ENTRY ExistingTgt = NULL;
  3188. HANDLE ClientToken = NULL;
  3189. PKERB_INTERNAL_NAME ServiceName = NULL;
  3190. UNICODE_STRING ServiceRealm = NULL_UNICODE_STRING;
  3191. PKERB_KDC_REPLY KdcReply = NULL;
  3192. PKERB_ENCRYPTED_KDC_REPLY KdcReplyBody = NULL;
  3193. BOOLEAN TicketCacheLocked = FALSE;
  3194. PKERB_TICKET_CACHE_ENTRY NewTicket = NULL;
  3195. ULONG CacheFlags = 0;
  3196. BOOLEAN UseSuppliedCreds = FALSE;
  3197. //
  3198. // Capture the existing TGT
  3199. //
  3200. Status = LsaFunctions->ImpersonateClient();
  3201. if (!NT_SUCCESS(Status))
  3202. {
  3203. goto Cleanup;
  3204. }
  3205. Status = NtOpenThreadToken(
  3206. NtCurrentThread(),
  3207. TOKEN_QUERY,
  3208. TRUE, // open as self
  3209. &ClientToken
  3210. );
  3211. if (!NT_SUCCESS(Status))
  3212. {
  3213. goto Cleanup;
  3214. }
  3215. RevertToSelf();
  3216. //
  3217. // Capture the restrictions for this token
  3218. //
  3219. AuthData = (PKERB_AUTHORIZATION_DATA) MIDL_user_allocate(sizeof(KERB_AUTHORIZATION_DATA));
  3220. if (AuthData == NULL)
  3221. {
  3222. Status = STATUS_INSUFFICIENT_RESOURCES;
  3223. goto Cleanup;
  3224. }
  3225. Status = KerbCaptureTokenRestrictions(
  3226. ClientToken,
  3227. AuthData
  3228. );
  3229. if (!NT_SUCCESS(Status))
  3230. {
  3231. D_DebugLog((DEB_ERROR,"Failed to capture token restrictions: 0x%x\n",Status));
  3232. goto Cleanup;
  3233. }
  3234. KerbWriteLockLogonSessions(LogonSession);
  3235. Credential->AuthData = AuthData;
  3236. //
  3237. // Turn off tgt avail to force us to get a new tgt
  3238. //
  3239. Credential->CredentialFlags &= ~KERB_CRED_TGT_AVAIL;
  3240. AuthData = NULL;
  3241. KerbUnlockLogonSessions(LogonSession);
  3242. Cleanup:
  3243. if (AuthData != NULL)
  3244. {
  3245. if (AuthData->value.auth_data.value != NULL)
  3246. {
  3247. MIDL_user_free(AuthData->value.auth_data.value);
  3248. }
  3249. MIDL_user_free(AuthData);
  3250. }
  3251. if (ClientToken != NULL)
  3252. {
  3253. NtClose(ClientToken);
  3254. }
  3255. return(Status);
  3256. }
  3257. //+-------------------------------------------------------------------------
  3258. //
  3259. // Function: KerbBuildTokenRestrictionAuthData
  3260. //
  3261. // Synopsis:
  3262. //
  3263. // Effects:
  3264. //
  3265. // Arguments:
  3266. //
  3267. // Requires:
  3268. //
  3269. // Returns:
  3270. //
  3271. // Notes: Not called yet - used for restricted tickets
  3272. //
  3273. //
  3274. //--------------------------------------------------------------------------
  3275. NTSTATUS
  3276. KerbBuildEncryptedAuthData(
  3277. OUT PKERB_ENCRYPTED_DATA EncryptedAuthData,
  3278. IN PKERB_TICKET_CACHE_ENTRY Ticket,
  3279. IN PKERB_AUTHORIZATION_DATA PlainAuthData
  3280. )
  3281. {
  3282. KERBERR KerbErr;
  3283. NTSTATUS Status = STATUS_SUCCESS;
  3284. KERB_MESSAGE_BUFFER PackedAuthData = {0};
  3285. KerbErr = KerbPackData(
  3286. &PlainAuthData,
  3287. PKERB_AUTHORIZATION_DATA_LIST_PDU,
  3288. &PackedAuthData.BufferSize,
  3289. &PackedAuthData.Buffer
  3290. );
  3291. if (!KERB_SUCCESS(KerbErr))
  3292. {
  3293. Status = KerbMapKerbError(KerbErr);
  3294. goto Cleanup;
  3295. }
  3296. KerbReadLockTicketCache();
  3297. KerbErr = KerbAllocateEncryptionBufferWrapper(
  3298. Ticket->SessionKey.keytype,
  3299. PackedAuthData.BufferSize,
  3300. &EncryptedAuthData->cipher_text.length,
  3301. &EncryptedAuthData->cipher_text.value
  3302. );
  3303. if (KERB_SUCCESS(KerbErr))
  3304. {
  3305. KerbErr = KerbEncryptDataEx(
  3306. EncryptedAuthData,
  3307. PackedAuthData.BufferSize,
  3308. PackedAuthData.Buffer,
  3309. KERB_NO_KEY_VERSION,
  3310. KERB_TGS_REQ_SESSKEY_SALT, // was KERB_NON_KERB_SALT need to check for KERB_TGS_REQ_SUBKEY_SALT also
  3311. &Ticket->SessionKey
  3312. );
  3313. }
  3314. KerbUnlockTicketCache();
  3315. if (!KERB_SUCCESS(KerbErr))
  3316. {
  3317. Status = KerbMapKerbError(KerbErr);
  3318. goto Cleanup;
  3319. }
  3320. Cleanup:
  3321. if (PackedAuthData.Buffer != NULL)
  3322. {
  3323. MIDL_user_free(PackedAuthData.Buffer);
  3324. }
  3325. return(Status);
  3326. }
  3327. //+-------------------------------------------------------------------------
  3328. //
  3329. // Function: KerbGetRestrictedTgtForCredential
  3330. //
  3331. // Synopsis:
  3332. //
  3333. // Effects:
  3334. //
  3335. // Arguments:
  3336. //
  3337. // Requires:
  3338. //
  3339. // Returns:
  3340. //
  3341. // Notes:
  3342. //
  3343. //
  3344. //--------------------------------------------------------------------------
  3345. NTSTATUS
  3346. KerbGetRestrictedTgtForCredential(
  3347. IN PKERB_LOGON_SESSION LogonSession,
  3348. IN PKERB_CREDENTIAL Credential
  3349. )
  3350. {
  3351. NTSTATUS Status = STATUS_SUCCESS;
  3352. PKERB_AUTHORIZATION_DATA AuthData = NULL;
  3353. BOOLEAN CrossRealm;
  3354. PKERB_TICKET_CACHE_ENTRY ExistingTgt = NULL;
  3355. PKERB_INTERNAL_NAME ServiceName = NULL;
  3356. UNICODE_STRING ServiceRealm = NULL_UNICODE_STRING;
  3357. PKERB_KDC_REPLY KdcReply = NULL;
  3358. PKERB_ENCRYPTED_KDC_REPLY KdcReplyBody = NULL;
  3359. BOOLEAN TicketCacheLocked = FALSE;
  3360. PKERB_TICKET_CACHE_ENTRY NewTicket = NULL;
  3361. ULONG CacheFlags = 0, RetryFlags = 0;
  3362. BOOLEAN UseSuppliedCreds = FALSE;
  3363. //
  3364. // First get an old TGT
  3365. //
  3366. KerbReadLockLogonSessions(LogonSession);
  3367. if (Credential->SuppliedCredentials == NULL)
  3368. {
  3369. ULONG Flags;
  3370. //
  3371. // We don't have supplied creds, but we need them, so copy
  3372. // from the logon session.
  3373. //
  3374. Status = KerbCaptureSuppliedCreds(
  3375. LogonSession,
  3376. NULL, // no auth data
  3377. NULL, // no principal name
  3378. &Credential->SuppliedCredentials,
  3379. &Flags
  3380. );
  3381. if (!NT_SUCCESS(Status))
  3382. {
  3383. D_DebugLog((DEB_ERROR,"Failed to capture dummy supplied creds: 0x%x\n",Status));
  3384. KerbUnlockLogonSessions(LogonSession);
  3385. goto Cleanup;
  3386. }
  3387. AuthData = Credential->AuthData;
  3388. }
  3389. else
  3390. {
  3391. UseSuppliedCreds = FALSE;
  3392. }
  3393. DsysAssert(Credential->SuppliedCredentials != NULL);
  3394. Status = KerbGetTgtForService(
  3395. LogonSession,
  3396. (UseSuppliedCreds) ? Credential : NULL,
  3397. NULL,
  3398. NULL, // no SuppRealm
  3399. &Credential->SuppliedCredentials->DomainName,
  3400. &ExistingTgt,
  3401. &CrossRealm
  3402. );
  3403. KerbUnlockLogonSessions(LogonSession);
  3404. if (!NT_SUCCESS(Status))
  3405. {
  3406. goto Cleanup;
  3407. }
  3408. //
  3409. // Now get a new TGT with this ticket
  3410. //
  3411. //
  3412. // Copy the names out of the input structures so we can
  3413. // unlock the structures while going over the network.
  3414. //
  3415. DsysAssert( !TicketCacheLocked );
  3416. KerbReadLockTicketCache();
  3417. TicketCacheLocked = TRUE;
  3418. //
  3419. // If the renew time is not much bigger than the end time, don't bother
  3420. // renewing
  3421. //
  3422. Status = KerbDuplicateString(
  3423. &ServiceRealm,
  3424. &ExistingTgt->DomainName
  3425. );
  3426. if (!NT_SUCCESS(Status))
  3427. {
  3428. goto Cleanup;
  3429. }
  3430. Status = KerbDuplicateKdcName(
  3431. &ServiceName,
  3432. ExistingTgt->ServiceName
  3433. );
  3434. if (!NT_SUCCESS(Status))
  3435. {
  3436. goto Cleanup;
  3437. }
  3438. CacheFlags = ExistingTgt->CacheFlags;
  3439. DsysAssert( TicketCacheLocked );
  3440. KerbUnlockTicketCache();
  3441. TicketCacheLocked = FALSE;
  3442. Status = KerbGetTgsTicket(
  3443. &ServiceRealm,
  3444. ExistingTgt,
  3445. ServiceName,
  3446. FALSE,
  3447. 0, // no ticket optiosn
  3448. 0, // no encryption type
  3449. AuthData, // no authorization data
  3450. NULL, // no tgt reply
  3451. NULL,
  3452. NULL,
  3453. &KdcReply,
  3454. &KdcReplyBody,
  3455. &RetryFlags
  3456. );
  3457. if (!NT_SUCCESS(Status))
  3458. {
  3459. D_DebugLog((DEB_ERROR,"Failed to get restricted tgs ticket: 0x%x\n",Status));
  3460. goto Cleanup;
  3461. }
  3462. //
  3463. // Now we want to purge the existing ticket cache and add this ticket
  3464. //
  3465. KerbPurgeTicketCache(
  3466. &Credential->SuppliedCredentials->AuthenticationTicketCache
  3467. );
  3468. KerbPurgeTicketCache(
  3469. &Credential->SuppliedCredentials->ServerTicketCache
  3470. );
  3471. KerbReadLockLogonSessions(LogonSession);
  3472. Status = KerbCreateTicketCacheEntry(
  3473. KdcReply,
  3474. KdcReplyBody,
  3475. ServiceName,
  3476. &ServiceRealm,
  3477. CacheFlags,
  3478. &Credential->SuppliedCredentials->AuthenticationTicketCache,
  3479. NULL, // no credential key
  3480. &NewTicket
  3481. );
  3482. KerbUnlockLogonSessions(LogonSession);
  3483. Cleanup:
  3484. if (TicketCacheLocked)
  3485. {
  3486. KerbUnlockTicketCache();
  3487. }
  3488. if (ExistingTgt != NULL)
  3489. {
  3490. KerbDereferenceTicketCacheEntry(ExistingTgt);
  3491. }
  3492. if (NewTicket != NULL)
  3493. {
  3494. KerbDereferenceTicketCacheEntry(NewTicket);
  3495. }
  3496. KerbFreeTgsReply(KdcReply);
  3497. KerbFreeKdcReplyBody(KdcReplyBody);
  3498. KerbFreeKdcName(&ServiceName);
  3499. KerbFreeString(&ServiceRealm);
  3500. return(Status);
  3501. }
  3502. #endif
  3503. #endif // WIN32_CHICAGO