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.

4780 lines
140 KiB

  1. //+---------------------------------------------------------------------------
  2. //
  3. // Microsoft Windows
  4. // Copyright (C) Microsoft Corporation, 1992 - 1996.
  5. //
  6. // File: security.cxx
  7. //
  8. // Contents:
  9. //
  10. // Classes:
  11. //
  12. // Functions: None.
  13. //
  14. // History: 15-May-96 MarkBl Created
  15. // 26-Feb-01 JBenton Prefix Bug 160502 - using uninit memory
  16. // 17-Apr-01 a-JyotiG Fixed Bug 367263 - Should not assign any privilege/right
  17. // to system account.
  18. //
  19. //----------------------------------------------------------------------------
  20. #include "..\pch\headers.hxx"
  21. #include <modes.h> // found in private\inc\crypto
  22. #include <ntsecapi.h>
  23. #include <ntdsapi.h> // DsCrackNames
  24. #include "resource.h"
  25. #include "globals.hxx" // BUGBUG 254102
  26. #include "sch_cls.hxx" // To implement AddAtJobWithHash
  27. #include "authzi.h" // for auditing
  28. #include <FolderSecurity.h>
  29. #include "svc_core.hxx"
  30. #include "security.hxx"
  31. #include "auditing.hxx"
  32. #include "misc.hxx"
  33. //
  34. // some prototypes for functions not in a header
  35. //
  36. BOOL IsThreadCallerAnAdmin(
  37. HANDLE hThreadToken);
  38. //
  39. // global stuff
  40. //
  41. WCHAR gwszComputerName[MAX_COMPUTERNAME_LENGTH + 2] = L""; // this buffer must remain this size or it will break old credentials
  42. LPWSTR gpwszComputerName = NULL;
  43. DWORD gdwKeyElement = 0;
  44. DWORD gccComputerName = MAX_COMPUTERNAME_LENGTH + 2;
  45. POLICY_ACCOUNT_DOMAIN_INFO* gpDomainInfo = NULL;
  46. DWORD gcbMachineSid = 0;
  47. PSID gpMachineSid = NULL;
  48. extern CStaticCritSec gcsSSCritSection;
  49. //+---------------------------------------------------------------------------
  50. //
  51. // Helper function: ValidateRunAs
  52. //
  53. // Synopsis: Verify that password entered for Run As account is correct
  54. // by actually trying to log on using the credentials
  55. //
  56. // *** Verification of NULL passwords is handled elsewhere ***
  57. //
  58. // Returns: bool
  59. //
  60. //----------------------------------------------------------------------------
  61. bool ValidateRunAs(
  62. LPCWSTR pwszAccount,
  63. LPCWSTR pwszDomain,
  64. LPCWSTR pwszPassword)
  65. {
  66. // NOTE - don't zero out the password anywhere in here -- we still need it!
  67. //
  68. // copy to buffers we can manipulate
  69. //
  70. WCHAR wszDomain [MAX_DOMAINNAME + 1];
  71. WCHAR wszAccount [MAX_USERNAME + 1];
  72. //
  73. // if the domain is present in the account name (SAM names), skip over it
  74. //
  75. WCHAR* pSlash = (WCHAR *) wcschr(pwszAccount, L'\\');
  76. if (pSlash)
  77. StringCchCopy(wszAccount, MAX_USERNAME + 1, pSlash + 1);
  78. else
  79. StringCchCopy(wszAccount, MAX_USERNAME + 1, pwszAccount);
  80. StringCchCopy(wszDomain, MAX_DOMAINNAME + 1, pwszDomain);
  81. //
  82. // If the name was passed in as a UPN, convert it to a SAM name first.
  83. // Treat the account name as a UPN if it lacks a \ and has an @.
  84. // Otherwise, treat it as a SAM name.
  85. //
  86. if (wcschr(pwszAccount, L'\\') == NULL && wcschr(pwszAccount, L'@') != NULL)
  87. {
  88. LPWSTR pwszSamName;
  89. DWORD dwErr = SchedUPNToAccountName(pwszAccount, &pwszSamName);
  90. if (dwErr != NO_ERROR)
  91. {
  92. return false;
  93. }
  94. else
  95. {
  96. pSlash = wcschr(pwszSamName, L'\\');
  97. schAssert(pSlash);
  98. *pSlash = L'\0';
  99. StringCchCopy(wszDomain, MAX_DOMAINNAME + 1, pwszSamName);
  100. StringCchCopy(wszAccount, MAX_USERNAME + 1, pSlash + 1);
  101. delete pwszSamName;
  102. }
  103. }
  104. HANDLE hToken = NULL;
  105. if (LogonUser(wszAccount,
  106. wszDomain,
  107. pwszPassword,
  108. LOGON32_LOGON_NETWORK,
  109. LOGON32_PROVIDER_DEFAULT,
  110. &hToken))
  111. {
  112. CloseHandle(hToken);
  113. return true;
  114. }
  115. else
  116. {
  117. return false;
  118. }
  119. }
  120. //+---------------------------------------------------------------------------
  121. //
  122. // Helper function: NotifyLsaOfPasswordChange
  123. //
  124. // Synopsis: Notify LSA if the password has been changed for an account so
  125. // that it can determine if any user sessions need to be refreshed.
  126. //
  127. // This code was stolen and modified from base\cluster\service\nm\setpass.c.
  128. //
  129. // Returns: ERROR_SUCCESS if successful, Win32 error code otherwise.
  130. //
  131. //----------------------------------------------------------------------------
  132. DWORD NotifyLsaOfPasswordChange(
  133. LPCWSTR pwszAccount,
  134. LPCWSTR pwszDomain,
  135. LPCWSTR pwszPassword)
  136. {
  137. DWORD ReturnStatus;
  138. NTSTATUS Status;
  139. NTSTATUS SubStatus;
  140. LSA_STRING LsaStringBuf;
  141. char* AuthPackage = MSV1_0_PACKAGE_NAME;
  142. HANDLE LsaHandle = NULL;
  143. ULONG PackageId;
  144. PMSV1_0_CHANGEPASSWORD_REQUEST Request = NULL;
  145. ULONG RequestSize;
  146. PBYTE Where;
  147. PVOID Response = NULL;
  148. ULONG ResponseSize;
  149. //
  150. // Change password in LSA cache
  151. //
  152. Status = LsaConnectUntrusted(&LsaHandle);
  153. if (Status != STATUS_SUCCESS)
  154. {
  155. ReturnStatus = LsaNtStatusToWinError(Status);
  156. goto ErrorExit;
  157. }
  158. RtlInitString(&LsaStringBuf, AuthPackage);
  159. Status = LsaLookupAuthenticationPackage(
  160. LsaHandle, // Handle
  161. &LsaStringBuf, // MSV1_0 authentication package
  162. &PackageId // output: authentication package identifier
  163. );
  164. if (Status != STATUS_SUCCESS)
  165. {
  166. ReturnStatus = LsaNtStatusToWinError(Status);
  167. goto ErrorExit;
  168. }
  169. //
  170. // Prepare to call LsaCallAuthenticationPackage()
  171. //
  172. RequestSize = sizeof(MSV1_0_CHANGEPASSWORD_REQUEST) +
  173. ( ( wcslen(pwszAccount) +
  174. wcslen(pwszDomain) +
  175. wcslen(pwszPassword) + 3
  176. ) * sizeof(WCHAR)
  177. );
  178. Request = (PMSV1_0_CHANGEPASSWORD_REQUEST)
  179. HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, RequestSize);
  180. if (Request == NULL)
  181. {
  182. ReturnStatus = ERROR_NOT_ENOUGH_MEMORY;
  183. goto ErrorExit;
  184. }
  185. ULONG BuffSize = RequestSize;
  186. Where = (PBYTE) (Request + 1);
  187. BuffSize--;
  188. Request->MessageType = MsV1_0ChangeCachedPassword;
  189. StringCbCopy((LPWSTR) Where, BuffSize, pwszDomain );
  190. RtlInitUnicodeString( &Request->DomainName, (wchar_t *) Where );
  191. Where += Request->DomainName.MaximumLength;
  192. BuffSize -= Request->DomainName.MaximumLength;
  193. StringCbCopy((LPWSTR) Where, BuffSize , pwszAccount );
  194. RtlInitUnicodeString( &Request->AccountName, (wchar_t *) Where );
  195. Where += Request->AccountName.MaximumLength;
  196. BuffSize -= Request->AccountName.MaximumLength;
  197. StringCbCopy((LPWSTR) Where, BuffSize , pwszPassword );
  198. RtlInitUnicodeString( &Request->NewPassword, (wchar_t *) Where );
  199. Where += Request->NewPassword.MaximumLength;
  200. Status = LsaCallAuthenticationPackage(
  201. LsaHandle,
  202. PackageId,
  203. Request, // MSV1_0_CHANGEPASSWORD_REQUEST
  204. RequestSize,
  205. &Response,
  206. &ResponseSize,
  207. &SubStatus // Receives NSTATUS code indicating the
  208. // completion status of the authentication
  209. // package if ERROR_SUCCESS is returned.
  210. );
  211. if (Status != STATUS_SUCCESS)
  212. {
  213. ReturnStatus = LsaNtStatusToWinError(Status);
  214. goto ErrorExit;
  215. }
  216. else if (LsaNtStatusToWinError(SubStatus) != ERROR_SUCCESS)
  217. {
  218. ReturnStatus = LsaNtStatusToWinError(SubStatus);
  219. goto ErrorExit;
  220. }
  221. ReturnStatus = ERROR_SUCCESS;
  222. ErrorExit:
  223. if (LsaHandle != NULL)
  224. {
  225. Status = LsaDeregisterLogonProcess(LsaHandle);
  226. if (Status != STATUS_SUCCESS)
  227. {
  228. // ignore; could possibly log this
  229. }
  230. }
  231. if (Request != NULL)
  232. {
  233. if (!HeapFree(GetProcessHeap(), 0, Request))
  234. {
  235. // ignore; could possibly log this
  236. }
  237. }
  238. if (Response != NULL)
  239. {
  240. Status = LsaFreeReturnBuffer(Response);
  241. if (Status != STATUS_SUCCESS)
  242. {
  243. // ignore; could possibly log this
  244. }
  245. }
  246. return ReturnStatus;
  247. }
  248. //+---------------------------------------------------------------------------
  249. //
  250. // RPC: SASetAccountInformation
  251. //
  252. // Synopsis:
  253. //
  254. // Arguments: [Handle] --
  255. // [pwszJobName] -- Relative job name. eg: MyJob.job.
  256. // [pwszAccount] --
  257. // [pwszPassword] --
  258. //
  259. // Returns: HRESULT
  260. //
  261. // Notes: None.
  262. //
  263. //----------------------------------------------------------------------------
  264. HRESULT
  265. SASetAccountInformation(
  266. SASEC_HANDLE Handle,
  267. LPCWSTR pwszJobName,
  268. LPCWSTR pwszAccount,
  269. LPCWSTR pwszPassword,
  270. DWORD dwJobFlags)
  271. {
  272. HRESULT hr = S_OK;
  273. // we're going to do the access check in two stages,
  274. // first make sure that the principal is allowed to
  275. // do any scheduling whatsoever - later on, we'll
  276. // check permissions on the specific file in question
  277. if (FAILED(hr = RPCFolderAccessCheck(g_TasksFolderInfo.ptszPath, FILE_WRITE_DATA, HandleImpersonation)))
  278. {
  279. CHECK_HRESULT(hr);
  280. return hr;
  281. }
  282. //
  283. // Check for invalid params (note that pwszPassword is allowed to be NULL)
  284. //
  285. if (pwszJobName == NULL || pwszAccount == NULL)
  286. {
  287. CHECK_HRESULT(E_INVALIDARG);
  288. return(E_INVALIDARG);
  289. }
  290. //
  291. // Disallow files outside the tasks folder
  292. //
  293. if (wcschr(pwszJobName, L'\\') || wcschr(pwszJobName, L'/'))
  294. {
  295. CHECK_HRESULT(E_INVALIDARG);
  296. return(E_INVALIDARG);
  297. }
  298. //
  299. // Append the job name to the local Task's folder path.
  300. //
  301. schAssert(g_TasksFolderInfo.ptszPath != NULL);
  302. WCHAR wszJobPath[MAX_PATH + 1];
  303. if ((wcslen(g_TasksFolderInfo.ptszPath) + 1 + wcslen(pwszJobName) + 1) > (MAX_PATH + 1))
  304. {
  305. CHECK_HRESULT(SCHED_E_CANNOT_OPEN_TASK);
  306. return(SCHED_E_CANNOT_OPEN_TASK);
  307. }
  308. StringCchCopy(wszJobPath, MAX_PATH + 1, g_TasksFolderInfo.ptszPath);
  309. StringCchCat(wszJobPath, MAX_PATH + 1, L"\\");
  310. StringCchCat(wszJobPath, MAX_PATH + 1, pwszJobName);
  311. //
  312. // Get the account's SID and domain
  313. //
  314. PSID pAccountSid = NULL;
  315. DWORD cbAccountSid = MAX_SID_SIZE;
  316. DWORD ccDomain = MAX_DOMAINNAME + 1;
  317. BYTE pbAccountSid[MAX_SID_SIZE];
  318. WCHAR wszDomain[MAX_DOMAINNAME + 1] = L"";
  319. HRESULT hrGetAccountSidAndDomain = GetAccountSidAndDomain(pwszAccount, pbAccountSid, cbAccountSid, wszDomain, ccDomain);
  320. if (FAILED(hrGetAccountSidAndDomain))
  321. {
  322. // continue on -- we don't want to return yet on failure, because we don't want to reveal that
  323. // the "run as" account is invalid if the caller shouldn't even be allowed to make this call;
  324. }
  325. else
  326. {
  327. pAccountSid = pbAccountSid;
  328. }
  329. //
  330. // Impersonate the caller, open his token, then end impersonation so we aren't impersonated during Auditing
  331. //
  332. DWORD RpcStatus = RpcImpersonateClient(NULL);
  333. if (RpcStatus != RPC_S_OK)
  334. {
  335. hr = _HRESULT_FROM_WIN32(RpcStatus);
  336. CHECK_HRESULT(hr);
  337. return hr;
  338. }
  339. HANDLE hToken;
  340. if (!OpenThreadToken(GetCurrentThread(),
  341. TOKEN_QUERY, // Desired access.
  342. TRUE, // Open as self.
  343. &hToken))
  344. {
  345. hr = _HRESULT_FROM_WIN32(GetLastError());
  346. CHECK_HRESULT(hr);
  347. goto Clean0;
  348. }
  349. if ((RpcStatus = RpcRevertToSelf()) != RPC_S_OK)
  350. {
  351. hr = _HRESULT_FROM_WIN32(RpcStatus);
  352. CHECK_HRESULT(hr);
  353. goto Clean1;
  354. }
  355. //
  356. // Now that we have the thread token, audit the job creation.
  357. // We do this here regardless of whether the user gets access denied down below.
  358. // However, we can only do this if we succeeded in looking up the "run as" account,
  359. // as that information is needed for the audit logging.
  360. //
  361. if (SUCCEEDED(hrGetAccountSidAndDomain))
  362. {
  363. hr = AuditJob(hToken, pAccountSid, wszJobPath);
  364. if (FAILED(hr))
  365. {
  366. ERR_OUT("SASetAccountInformation: AuditJob", hr);
  367. // let's just forget this happened, OK?
  368. hr = S_OK;
  369. }
  370. }
  371. //
  372. // Reimpersonate client
  373. //
  374. RpcStatus = RpcImpersonateClient(NULL);
  375. if (RpcStatus != RPC_S_OK)
  376. {
  377. hr = _HRESULT_FROM_WIN32(RpcStatus);
  378. CHECK_HRESULT(hr);
  379. goto Clean1;
  380. }
  381. //
  382. // Check whether caller should even be allowed to make this call
  383. //
  384. if (FAILED(hr = FolderAccessCheck(wszJobPath, hToken, FILE_WRITE_DATA)))
  385. {
  386. CHECK_HRESULT(hr);
  387. goto Clean1;
  388. }
  389. if (FAILED(hrGetAccountSidAndDomain))
  390. {
  391. //
  392. // OK, caller passed the above access check, so reveal that the "run as" account is bad
  393. //
  394. hr = hrGetAccountSidAndDomain;
  395. CHECK_HRESULT(hr);
  396. goto Clean1;
  397. }
  398. //
  399. // If the password is NULL, this task is meant to be run
  400. // without prompting the user for credentials
  401. //
  402. if (pwszPassword == NULL)
  403. {
  404. DWORD dwError = NO_ERROR;
  405. do // Not a loop. Error break out.
  406. {
  407. //
  408. // If the caller has a restricted token (e.g., an ActiveX
  409. // control), it's not allowed to use a NULL password.
  410. //
  411. if (IsTokenRestricted(hToken))
  412. {
  413. dwError = ERROR_ACCESS_DENIED;
  414. schDebugOut((DEB_ERROR, "Restricted token tried to set NULL "
  415. "password for %ws. Denying access.\n", pwszJobName));
  416. break;
  417. }
  418. //
  419. // To set credentials for the job, the caller must have write
  420. // access to the job file.
  421. //
  422. HANDLE hFile;
  423. hr = OpenFileWithRetry(wszJobPath, GENERIC_WRITE, FILE_SHARE_WRITE, &hFile);
  424. if (FAILED(hr))
  425. {
  426. ERR_OUT("SASetAccountInformation: caller's open of task file", hr);
  427. break;
  428. }
  429. CloseHandle(hFile);
  430. //
  431. // Unless the task is being set to run as LocalSystem, a NULL
  432. // password means that the task must be scheduled to run only
  433. // if the user is logged on, so make sure that flag is set in
  434. // that case
  435. //
  436. // An account name of "" signifies the local system account.
  437. //
  438. BOOL fIsAccountLocalSystem = (pwszAccount[0] == L'\0');
  439. if (!fIsAccountLocalSystem
  440. &&
  441. !(dwJobFlags & TASK_FLAG_RUN_ONLY_IF_LOGGED_ON))
  442. {
  443. schDebugOut((DEB_ERROR, "SetAccountInformation with NULL "
  444. "password is only supported for LocalSystem "
  445. "account or for job with "
  446. "TASK_FLAG_RUN_ONLY_IF_LOGGED_ON\n",
  447. pwszJobName));
  448. hr = SCHED_E_UNSUPPORTED_ACCOUNT_OPTION;
  449. break;
  450. }
  451. //
  452. // The caller must be either LocalSystem, an administrator or
  453. // the user named in pwszAccount (the latter being the most
  454. // common case. CODEWORK - rearrange to optimize for that case?)
  455. //
  456. BOOL fIsCallerLocalSystem;
  457. SID LocalSystemSid = {SID_REVISION,
  458. 1,
  459. SECURITY_NT_AUTHORITY,
  460. SECURITY_LOCAL_SYSTEM_RID };
  461. if (!CheckTokenMembership(hToken,
  462. &LocalSystemSid,
  463. &fIsCallerLocalSystem))
  464. {
  465. dwError = GetLastError();
  466. ERR_OUT("CheckTokenMembership", dwError);
  467. // translate this to E_UNEXPECTED?
  468. break;
  469. }
  470. if (fIsCallerLocalSystem || IsThreadCallerAnAdmin(hToken))
  471. {
  472. //
  473. // (success)
  474. //
  475. break;
  476. }
  477. if (fIsAccountLocalSystem)
  478. {
  479. hr = HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED);
  480. schDebugOut((DEB_ERROR, "Non-system, non-admin tried "
  481. "to schedule task as LocalSystem\n"));
  482. break;
  483. }
  484. //
  485. // Compare the caller's token with the account's SID
  486. //
  487. BOOL fIsCallerAccount;
  488. if (!CheckTokenMembership(hToken,
  489. pAccountSid,
  490. &fIsCallerAccount))
  491. {
  492. dwError = GetLastError();
  493. ERR_OUT("CheckTokenMembership", dwError);
  494. // translate this to E_UNEXPECTED?
  495. break;
  496. }
  497. if (! fIsCallerAccount)
  498. {
  499. schDebugOut((DEB_ERROR, "Caller is neither LocalSystem "
  500. "nor admin nor the named account\n"));
  501. hr = HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED);
  502. }
  503. //
  504. // else success -- the caller is the named account
  505. //
  506. } while (0);
  507. if (dwError != NO_ERROR)
  508. {
  509. hr = _HRESULT_FROM_WIN32(dwError);
  510. }
  511. if (FAILED(hr))
  512. {
  513. CHECK_HRESULT(hr);
  514. }
  515. else
  516. {
  517. schDebugOut((DEB_TRACE, "Saving NULL password for %ws\n", pwszJobName));
  518. }
  519. // end of NULL password stuff
  520. }
  521. else
  522. {
  523. //
  524. // Verify that the credentials entered actually work.
  525. // This prevents someone from scheduling jobs for a valid account with an invalid password
  526. // and causing the credential database to be updated with the bad password.
  527. // It also prevents someone from creating lots of bogus jobs.
  528. //
  529. if (!ValidateRunAs(pwszAccount, wszDomain, pwszPassword))
  530. {
  531. hr = E_ACCESSDENIED;
  532. CHECK_HRESULT(hr);
  533. }
  534. }
  535. Clean1:
  536. //
  537. // Close the handle to the thread token
  538. //
  539. CloseHandle(hToken);
  540. Clean0:
  541. //
  542. // End impersonation.
  543. //
  544. if ((RpcStatus = RpcRevertToSelf()) != RPC_S_OK)
  545. {
  546. ERR_OUT("RpcRevertToSelf", RpcStatus);
  547. schAssert(!"RpcRevertToSelf failed");
  548. }
  549. if (SUCCEEDED(hr))
  550. {
  551. //
  552. // Write the credentials to the database
  553. // If given a UPN, save "" for the domain and the entire UPN for the user.
  554. // Treat the account name as a UPN if it lacks a \ and has an @.
  555. // Otherwise, treat it as a SAM name.
  556. //
  557. BOOL fUpn = (wcschr(pwszAccount, L'\\') == NULL && wcschr(pwszAccount, L'@') != NULL);
  558. //
  559. // Retrieve the original creds and compare with the ones we're about to save
  560. // in order to determine if just the password is being updated. If so, notify LSA.
  561. // There's no need to do any of this for local system, and we also shouldn't do this
  562. // if the job is flagged to run only if logged on, as the NULL password supplied in
  563. // this case is not really the user's password. We can exclude both cases by testing
  564. // for a non-NULL password as there is no other situation where a NULL password will
  565. // be allowed. Blank passwords are legit, but they are non-NULL and therefore OK.
  566. //
  567. if (pwszPassword)
  568. {
  569. JOB_CREDENTIALS jc;
  570. hr = GetAccountInformation(wszJobPath, &jc);
  571. if (SUCCEEDED(hr))
  572. {
  573. if ((lstrcmpiW(jc.wszAccount, fUpn ? pwszAccount : SkipDomainName(pwszAccount)) == 0) &&
  574. (lstrcmpiW(jc.wszPassword, pwszPassword) != 0))
  575. {
  576. NotifyLsaOfPasswordChange(fUpn ? pwszAccount : SkipDomainName(pwszAccount),
  577. fUpn ? L"" : wszDomain,
  578. pwszPassword);
  579. }
  580. ZERO_PASSWORD(jc.wszPassword);
  581. }
  582. }
  583. hr = SaveJobCredentials(
  584. wszJobPath,
  585. fUpn ? pwszAccount : SkipDomainName(pwszAccount),
  586. fUpn ? L"" : wszDomain,
  587. pwszPassword,
  588. pAccountSid
  589. );
  590. }
  591. return hr;
  592. }
  593. //+---------------------------------------------------------------------------
  594. //
  595. // Function: GetAccountSidAndDomain
  596. //
  597. // Synopsis: Gets the SID and Domain of an account.
  598. // This was factored out of SASetAccountInformation() above, because this is a
  599. // task that now needs to be performed in more than one place, and I did not
  600. // wish to duplicate code.
  601. //
  602. // Arguments:
  603. // IN LPCWSTR pwszAccount -- account to look up
  604. // IN OUT PSID pAccountSid -- pointer to buffer to receive SID
  605. // IN DWORD cbAccountSid -- size of buffer
  606. // IN OUT LPWSTR pwszDomain -- pointer to buffer to receive domain
  607. // IN DWORD ccDomain -- size of buffer
  608. //
  609. // Returns: HRESULT
  610. //
  611. //----------------------------------------------------------------------------
  612. HRESULT
  613. GetAccountSidAndDomain(
  614. LPCWSTR pwszAccount,
  615. PSID pAccountSid,
  616. DWORD cbAccountSid,
  617. LPWSTR pwszDomain,
  618. DWORD ccDomain)
  619. {
  620. HRESULT hr = S_OK;
  621. if (pwszAccount == NULL || pAccountSid == NULL || pwszDomain == NULL)
  622. {
  623. CHECK_HRESULT(E_INVALIDARG);
  624. return(E_INVALIDARG);
  625. }
  626. //
  627. // An account name of "" signifies the local system account.
  628. //
  629. BOOL fIsAccountLocalSystem = (pwszAccount[0] == L'\0');
  630. //
  631. // Get the account's SID
  632. //
  633. if (fIsAccountLocalSystem)
  634. {
  635. SID LocalSystemSid = {SID_REVISION,
  636. 1,
  637. SECURITY_NT_AUTHORITY,
  638. SECURITY_LOCAL_SYSTEM_RID };
  639. if (!CopySid(cbAccountSid, pAccountSid, &LocalSystemSid))
  640. {
  641. hr = HRESULT_FROM_WIN32(GetLastError());
  642. CHECK_HRESULT(hr);
  643. return hr;
  644. }
  645. }
  646. else
  647. {
  648. //
  649. // Treat the account name as a UPN if it lacks a \ and has an @.
  650. // Otherwise, treat it as a SAM name.
  651. //
  652. BOOL fUpn = (wcschr(pwszAccount, L'\\') == NULL && wcschr(pwszAccount, L'@') != NULL);
  653. schDebugOut((DEB_TRACE, "Name '%S' is a %s name\n", pwszAccount, fUpn ? "UPN" : "SAM"));
  654. LPWSTR pwszSamName;
  655. if (fUpn)
  656. {
  657. //
  658. // Get the SAM name, so we can call LookupAccountName
  659. //
  660. DWORD dwErr = SchedUPNToAccountName(pwszAccount, &pwszSamName);
  661. if (dwErr != NO_ERROR)
  662. {
  663. hr = HRESULT_FROM_WIN32(dwErr);
  664. CHECK_HRESULT(hr);
  665. return hr;
  666. }
  667. }
  668. else
  669. {
  670. pwszSamName = (LPWSTR) pwszAccount;
  671. }
  672. DWORD ccDomain = MAX_DOMAINNAME + 1;
  673. WCHAR wszDomain[MAX_DOMAINNAME + 1] = L"";
  674. SID_NAME_USE snu;
  675. if (!LookupAccountNameWrap(NULL,
  676. pwszSamName,
  677. pAccountSid,
  678. &cbAccountSid,
  679. pwszDomain,
  680. &ccDomain,
  681. &snu))
  682. {
  683. CHECK_HRESULT(_HRESULT_FROM_WIN32(GetLastError()));
  684. hr = SCHED_E_ACCOUNT_NAME_NOT_FOUND;
  685. }
  686. if (fUpn)
  687. {
  688. delete pwszSamName;
  689. }
  690. if (FAILED(hr))
  691. {
  692. return hr;
  693. }
  694. schAssert(IsValidSid(pAccountSid));
  695. }
  696. return hr;
  697. }
  698. //+---------------------------------------------------------------------------
  699. //
  700. // Function: GetNSAccountSid
  701. //
  702. // Synopsis: Gets the SID of the account set to be used with the Net Schedule API (AT command).
  703. //
  704. // Arguments:
  705. // IN OUT PSID pAccountSid -- pointer to buffer to receive SID
  706. // IN DWORD cbAccountSid -- size of buffer
  707. //
  708. // Returns: HRESULT
  709. //
  710. //----------------------------------------------------------------------------
  711. HRESULT
  712. GetNSAccountSid(
  713. PSID pAccountSid,
  714. DWORD cbAccountSid)
  715. {
  716. HRESULT hr = S_OK;
  717. if (pAccountSid == NULL)
  718. {
  719. CHECK_HRESULT(E_INVALIDARG);
  720. return(E_INVALIDARG);
  721. }
  722. //
  723. // get the name of the AT service account
  724. //
  725. DWORD cchAccount = MAX_USERNAME + 1;
  726. WCHAR wszAccount[MAX_USERNAME + 1];
  727. hr = SAGetNSAccountInformation(NULL, cchAccount, wszAccount);
  728. if (FAILED(hr))
  729. return hr;
  730. //
  731. // Get the account's SID
  732. //
  733. DWORD ccDomain = MAX_DOMAINNAME + 1;
  734. WCHAR wszDomain[MAX_DOMAINNAME + 1] = L"";
  735. hr = GetAccountSidAndDomain(wszAccount, pAccountSid, cbAccountSid, wszDomain, ccDomain);
  736. return hr;
  737. }
  738. //+---------------------------------------------------------------------------
  739. //
  740. // Function: SaveJobCredentials
  741. //
  742. // Synopsis: Writes the job credentials to the credential database
  743. //
  744. // Arguments:
  745. //
  746. // Returns: HRESULT
  747. //
  748. //----------------------------------------------------------------------------
  749. HRESULT
  750. SaveJobCredentials(
  751. LPCWSTR pwszJobPath,
  752. LPCWSTR pwszAccount,
  753. LPCWSTR pwszDomain,
  754. LPCWSTR pwszPassword,
  755. PSID pAccountSid
  756. )
  757. {
  758. BYTE rgbIdentity[HASH_DATA_SIZE];
  759. BYTE rgbHashedAccountSid[HASH_DATA_SIZE] = { 0 };
  760. RC2_KEY_INFO RC2KeyInfo;
  761. HRESULT hr;
  762. DWORD cbSAI;
  763. DWORD cbSAC;
  764. DWORD cbCredentialNew;
  765. DWORD cbEncryptedData;
  766. DWORD CredentialIndexNew, CredentialIndexPrev;
  767. BYTE * pbEncryptedData;
  768. BYTE * pbFoundIdentity;
  769. BYTE * pbIdentitySet;
  770. BYTE * pbCredentialNew = NULL;
  771. BYTE * pbSAI = NULL;
  772. BYTE * pbSAC = NULL;
  773. HCRYPTPROV hCSP = NULL;
  774. //
  775. // Obtain a provider handle to the CSP (for use with Crypto API).
  776. //
  777. hr = GetCSPHandle(&hCSP);
  778. if (FAILED(hr))
  779. {
  780. return(hr);
  781. }
  782. //
  783. // Hash the job into a unique identity.
  784. //
  785. hr = HashJobIdentity(hCSP, pwszJobPath, rgbIdentity);
  786. if (FAILED(hr))
  787. {
  788. CloseCSPHandle(hCSP);
  789. return(hr);
  790. }
  791. //
  792. // Store a NULL password by flipping the last bit of the hash data.
  793. //
  794. if (pwszPassword == NULL)
  795. {
  796. LAST_HASH_BYTE(rgbIdentity) ^= 1;
  797. }
  798. //
  799. // Guard SA security database access.
  800. //
  801. EnterCriticalSection(&gcsSSCritSection);
  802. //
  803. // Generate the encryption key & encrypt the account information passed.
  804. //
  805. hr = ComputeCredentialKey(hCSP, &RC2KeyInfo);
  806. if (FAILED(hr))
  807. {
  808. CHECK_HRESULT(hr);
  809. goto ErrorExit;
  810. }
  811. hr = EncryptCredentials(RC2KeyInfo,
  812. pwszAccount,
  813. pwszDomain,
  814. pwszPassword,
  815. pAccountSid,
  816. &cbEncryptedData,
  817. &pbEncryptedData);
  818. if (FAILED(hr))
  819. {
  820. CHECK_HRESULT(hr);
  821. goto ErrorExit;
  822. }
  823. //
  824. // Read SAI & SAC databases.
  825. //
  826. hr = ReadSecurityDBase(&cbSAI, &pbSAI, &cbSAC, &pbSAC);
  827. if (FAILED(hr))
  828. {
  829. CHECK_HRESULT(hr);
  830. goto ErrorExit;
  831. }
  832. //
  833. // Check whether we will be in danger of exceeding the max secret size.
  834. // We don't know at this time whether we'll be increasing the size of the
  835. // secret as the data may already be present, but if it does need to be added,
  836. // the calculation below will show if the size will be over the limit. If so,
  837. // do a scavenge operation first as a precaution to remove all unused data,
  838. // then reread the db.
  839. //
  840. if ((cbSAI + sizeof(DWORD) + HASH_DATA_SIZE) > MAX_SECRET_SIZE ||
  841. (cbSAC + sizeof(DWORD) + HASH_DATA_SIZE + cbEncryptedData) > MAX_SECRET_SIZE)
  842. {
  843. if (pbSAI != NULL) LocalFree(pbSAI);
  844. if (pbSAC != NULL) LocalFree(pbSAC);
  845. pbSAI = pbSAC = NULL;
  846. ScavengeSASecurityDBase();
  847. hr = ReadSecurityDBase(&cbSAI, &pbSAI, &cbSAC, &pbSAC);
  848. if (FAILED(hr))
  849. {
  850. CHECK_HRESULT(hr);
  851. goto ErrorExit;
  852. }
  853. }
  854. //
  855. // Check if the identity exists in the SAI.
  856. // (Note, SAIFindIdentity ignores the last bit of the hash data
  857. // when searching for a match.)
  858. //
  859. hr = SAIFindIdentity(rgbIdentity,
  860. cbSAI,
  861. pbSAI,
  862. &CredentialIndexPrev,
  863. NULL,
  864. &pbFoundIdentity,
  865. NULL,
  866. &pbIdentitySet);
  867. if (FAILED(hr))
  868. {
  869. CHECK_HRESULT(hr);
  870. goto ErrorExit;
  871. }
  872. //
  873. // Check if the caller-specified credentials already exist in the SAC.
  874. // Ensure also, if the credentials exist, that the caller has access.
  875. //
  876. hr = CredentialLookupAndAccessCheck(hCSP,
  877. pAccountSid,
  878. cbSAC,
  879. pbSAC,
  880. &CredentialIndexNew,
  881. rgbHashedAccountSid,
  882. &cbCredentialNew,
  883. &pbCredentialNew);
  884. if (FAILED(hr) && hr != SCHED_E_ACCOUNT_INFORMATION_NOT_SET)
  885. {
  886. goto ErrorExit;
  887. }
  888. if (pbFoundIdentity == NULL)
  889. {
  890. //
  891. // This job is new to the SAI. That is, there are no credentials
  892. // associated with this job yet.
  893. //
  894. if (pbCredentialNew != NULL)
  895. {
  896. //
  897. // If the credentials the caller specified already exist in the
  898. // SAC, use them. Note, we've already established the caller
  899. // has permission to use them.
  900. //
  901. // Insert the job identity into the SAI identity set associated
  902. // with this credential.
  903. //
  904. hr = SAIIndexIdentity(cbSAI,
  905. pbSAI,
  906. CredentialIndexNew,
  907. 0,
  908. NULL,
  909. NULL,
  910. &pbIdentitySet);
  911. if (hr == S_FALSE)
  912. {
  913. //
  914. // The SAC & SAI databases are out of sync.
  915. // Should *never* occur. Logic on exit handles this.
  916. //
  917. ASSERT_SECURITY_DBASE_CORRUPT();
  918. hr = SCHED_E_ACCOUNT_DBASE_CORRUPT;
  919. goto ErrorExit;
  920. }
  921. else if (SUCCEEDED(hr))
  922. {
  923. hr = SAIInsertIdentity(rgbIdentity,
  924. pbIdentitySet,
  925. &cbSAI,
  926. &pbSAI);
  927. CHECK_HRESULT(hr);
  928. if (SUCCEEDED(hr) && pwszPassword != NULL)
  929. {
  930. //
  931. // Simply change of existing credentials (password change).
  932. // If we're setting a NULL password, we're setting it for
  933. // this job alone, and we don't need to touch the SAC.
  934. // If we're setting a non-NULL password, we're setting it
  935. // for all jobs in this account, and we need to update the
  936. // SAC credential in-place.
  937. //
  938. hr = SACUpdateCredential(cbEncryptedData,
  939. pbEncryptedData,
  940. cbCredentialNew,
  941. pbCredentialNew,
  942. &cbSAC,
  943. &pbSAC);
  944. CHECK_HRESULT(hr);
  945. }
  946. }
  947. else
  948. {
  949. CHECK_HRESULT(hr);
  950. goto ErrorExit;
  951. }
  952. }
  953. else
  954. {
  955. //
  956. // The credentials didn't exist in the SAC.
  957. //
  958. // Append new credentials to the SAC & append the new job
  959. // identity to the SAI. As a result, the identity will be
  960. // associated with the new credentials.
  961. //
  962. hr = SACAddCredential(rgbHashedAccountSid,
  963. cbEncryptedData,
  964. pbEncryptedData,
  965. &cbSAC,
  966. &pbSAC);
  967. if (FAILED(hr))
  968. {
  969. CHECK_HRESULT(hr);
  970. goto ErrorExit;
  971. }
  972. hr = SAIAddIdentity(rgbIdentity, &cbSAI, &pbSAI);
  973. CHECK_HRESULT(hr);
  974. }
  975. }
  976. else
  977. {
  978. //
  979. // Account change for an existing job's credentials.
  980. //
  981. // Ensure the caller has permission to change account information.
  982. // Do so by verifying caller access to the existing credentials.
  983. //
  984. DWORD cbCredentialPrev;
  985. BYTE * pbCredentialPrev;
  986. hr = SACIndexCredential(CredentialIndexPrev,
  987. cbSAC,
  988. pbSAC,
  989. &cbCredentialPrev,
  990. &pbCredentialPrev);
  991. if (hr == S_FALSE)
  992. {
  993. //
  994. // Credential not found? The SAC & SAI databases are out of sync.
  995. // This should *never* occur. Logic on exit handles this.
  996. //
  997. ASSERT_SECURITY_DBASE_CORRUPT();
  998. hr = SCHED_E_ACCOUNT_DBASE_CORRUPT;
  999. goto ErrorExit;
  1000. }
  1001. else if (FAILED(hr))
  1002. {
  1003. CHECK_HRESULT(hr);
  1004. goto ErrorExit;
  1005. }
  1006. //
  1007. // Only check the credentials if we're dealing with a non-NULL password
  1008. //
  1009. if (pwszPassword != NULL)
  1010. {
  1011. //
  1012. // pbCredentialPrev points to the start of the credential identity.
  1013. //
  1014. if (!CredentialAccessCheck(hCSP,
  1015. pbCredentialPrev))
  1016. {
  1017. hr = HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED);
  1018. CHECK_HRESULT(hr);
  1019. goto ErrorExit;
  1020. }
  1021. }
  1022. if ((pbCredentialNew != NULL) &&
  1023. (CredentialIndexPrev != CredentialIndexNew))
  1024. {
  1025. //
  1026. // The credentials the caller wishes to use already exist in the
  1027. // SAC, yet it differs from the previous.
  1028. //
  1029. // Remove the job identity from its existing SAI position
  1030. // (associated with the previous credentials) and relocate
  1031. // to be associated with the new credentials.
  1032. //
  1033. // SAIRemoveIdentity could result in removal of the associated
  1034. // credential, if this was the last identity associated with it.
  1035. // Save away the original SAC size to see if we must fix up the
  1036. // new credential index on remove.
  1037. //
  1038. DWORD cbSACOrg = cbSAC;
  1039. hr = SAIRemoveIdentity(pbFoundIdentity,
  1040. pbIdentitySet,
  1041. &cbSAI,
  1042. &pbSAI,
  1043. CredentialIndexPrev,
  1044. &cbSAC,
  1045. &pbSAC);
  1046. if (FAILED(hr))
  1047. {
  1048. CHECK_HRESULT(hr);
  1049. goto ErrorExit;
  1050. }
  1051. if (cbSACOrg != cbSAC)
  1052. {
  1053. //
  1054. // The new credential index must be adjusted.
  1055. //
  1056. if (CredentialIndexNew > CredentialIndexPrev)
  1057. {
  1058. CredentialIndexNew--;
  1059. }
  1060. }
  1061. hr = SAIIndexIdentity(cbSAI,
  1062. pbSAI,
  1063. CredentialIndexNew,
  1064. 0,
  1065. NULL,
  1066. NULL,
  1067. &pbIdentitySet); // [out] ptr.
  1068. if (hr == S_FALSE)
  1069. {
  1070. //
  1071. // The SAC & SAI databases are out of sync. This should
  1072. // *never* occur. Logic on exit handles this.
  1073. //
  1074. ASSERT_SECURITY_DBASE_CORRUPT();
  1075. hr = SCHED_E_ACCOUNT_DBASE_CORRUPT;
  1076. goto ErrorExit;
  1077. }
  1078. else if (SUCCEEDED(hr))
  1079. {
  1080. hr = SAIInsertIdentity(rgbIdentity,
  1081. pbIdentitySet,
  1082. &cbSAI,
  1083. &pbSAI);
  1084. CHECK_HRESULT(hr);
  1085. if (SUCCEEDED(hr) && pwszPassword != NULL)
  1086. {
  1087. //
  1088. // Update the existing credentials if the user has
  1089. // specified a non-NULL password.
  1090. //
  1091. // First, re-index the credential since the remove
  1092. // above may have altered SAC content.
  1093. //
  1094. hr = SACIndexCredential(CredentialIndexNew,
  1095. cbSAC,
  1096. pbSAC,
  1097. &cbCredentialNew,
  1098. &pbCredentialNew);
  1099. if (hr == S_FALSE)
  1100. {
  1101. //
  1102. // Something is terribly wrong. This should *never*
  1103. // occur. Logic on exit handles this.
  1104. //
  1105. ASSERT_SECURITY_DBASE_CORRUPT();
  1106. hr = SCHED_E_ACCOUNT_DBASE_CORRUPT;
  1107. goto ErrorExit;
  1108. }
  1109. else if (FAILED(hr))
  1110. {
  1111. CHECK_HRESULT(hr);
  1112. goto ErrorExit;
  1113. }
  1114. hr = SACUpdateCredential(cbEncryptedData,
  1115. pbEncryptedData,
  1116. cbCredentialNew,
  1117. pbCredentialNew,
  1118. &cbSAC,
  1119. &pbSAC);
  1120. CHECK_HRESULT(hr);
  1121. }
  1122. }
  1123. else
  1124. {
  1125. CHECK_HRESULT(hr);
  1126. goto ErrorExit;
  1127. }
  1128. }
  1129. else if (pbCredentialNew == NULL)
  1130. {
  1131. //
  1132. // The credentials the caller wishes to use do not exist in the
  1133. // SAC.
  1134. //
  1135. // Remove the job identity from its existing SAI position
  1136. // (associated with the previous credentials), then add both
  1137. // the new credentials and the identity to the SAC & SAI
  1138. // respectively. As a result, the identity will be associated
  1139. // with the new credentials.
  1140. //
  1141. //
  1142. // NB : This routine also removes the associated credential from
  1143. // the SAC if this was the last identity associated with it.
  1144. // Also, do not reference pbFoundIdentity & pbIdentitySet
  1145. // after this call, as they will be invalid.
  1146. //
  1147. hr = SAIRemoveIdentity(pbFoundIdentity,
  1148. pbIdentitySet,
  1149. &cbSAI,
  1150. &pbSAI,
  1151. CredentialIndexPrev,
  1152. &cbSAC,
  1153. &pbSAC);
  1154. if (FAILED(hr))
  1155. {
  1156. CHECK_HRESULT(hr);
  1157. goto ErrorExit;
  1158. }
  1159. //
  1160. // Append the identity and the new credentials to the SAI and
  1161. // SAC respectively.
  1162. //
  1163. hr = SACAddCredential(rgbHashedAccountSid,
  1164. cbEncryptedData,
  1165. pbEncryptedData,
  1166. &cbSAC,
  1167. &pbSAC);
  1168. if (FAILED(hr))
  1169. {
  1170. CHECK_HRESULT(hr);
  1171. goto ErrorExit;
  1172. }
  1173. hr = SAIAddIdentity(rgbIdentity, &cbSAI, &pbSAI);
  1174. if (FAILED(hr))
  1175. {
  1176. CHECK_HRESULT(hr);
  1177. goto ErrorExit;
  1178. }
  1179. }
  1180. else
  1181. {
  1182. //
  1183. // Simply change of existing credentials (password change).
  1184. // If we're setting a NULL password, we're setting it for this job
  1185. // alone, and we don't need to touch the SAC. If we're setting a
  1186. // non-NULL password, we're setting it for all jobs in this
  1187. // account, and we need to update the SAC credential in-place.
  1188. //
  1189. if (pwszPassword != NULL)
  1190. {
  1191. hr = SACUpdateCredential(cbEncryptedData,
  1192. pbEncryptedData,
  1193. cbCredentialPrev,
  1194. pbCredentialPrev,
  1195. &cbSAC,
  1196. &pbSAC);
  1197. if (FAILED(hr))
  1198. {
  1199. CHECK_HRESULT(hr);
  1200. goto ErrorExit;
  1201. }
  1202. }
  1203. //
  1204. // We also need to rewrite the SAI data, because if the password
  1205. // changed from NULL to non-NULL or vice versa, the last bit of
  1206. // the SAI data will have changed.
  1207. //
  1208. hr = SAIUpdateIdentity(rgbIdentity,
  1209. pbFoundIdentity,
  1210. cbSAI,
  1211. pbSAI);
  1212. CHECK_HRESULT(hr);
  1213. }
  1214. }
  1215. if (SUCCEEDED(hr))
  1216. {
  1217. hr = WriteSecurityDBase(cbSAI, pbSAI, cbSAC, pbSAC);
  1218. CHECK_HRESULT(hr);
  1219. if (SUCCEEDED(hr))
  1220. {
  1221. //
  1222. // Grant the account batch privilege.
  1223. // We could choose to ignore the return code here, since the
  1224. // privilege can still be granted later; but if we ignored it,
  1225. // a caller might never know that the call failed until it was
  1226. // time to run the job, which is not good behavior. (See
  1227. // bug 366582)
  1228. //
  1229. //Also we should not assign any privilege/right to system account. Refer to bug 367263
  1230. SID LocalSystemSid = { SID_REVISION,
  1231. 1,
  1232. SECURITY_NT_AUTHORITY,
  1233. SECURITY_LOCAL_SYSTEM_RID };
  1234. if(!EqualSid(&LocalSystemSid,pAccountSid)) {
  1235. hr = GrantAccountBatchPrivilege(pAccountSid);
  1236. }
  1237. }
  1238. }
  1239. ErrorExit:
  1240. if (pbSAI != NULL) LocalFree(pbSAI);
  1241. if (pbSAC != NULL) LocalFree(pbSAC);
  1242. if (hCSP != NULL) CloseCSPHandle(hCSP);
  1243. //
  1244. // Log an error & rest the SA security dbases SAI & SAC if corruption
  1245. // is detected.
  1246. //
  1247. if (hr == SCHED_E_ACCOUNT_DBASE_CORRUPT)
  1248. {
  1249. //
  1250. // Log an error.
  1251. //
  1252. LogServiceError(IERR_SECURITY_DBASE_CORRUPTION, 0,
  1253. IDS_HELP_HINT_DBASE_CORRUPT);
  1254. //
  1255. // Reset SAI & SAC by writing four bytes of zeros into each.
  1256. // Ignore the return code. No recourse if this fails.
  1257. //
  1258. DWORD dwZero = 0;
  1259. WriteSecurityDBase(sizeof(dwZero), (BYTE *)&dwZero, sizeof(dwZero),
  1260. (BYTE *)&dwZero);
  1261. }
  1262. LeaveCriticalSection(&gcsSSCritSection);
  1263. return(hr);
  1264. }
  1265. //+---------------------------------------------------------------------------
  1266. //
  1267. // RPC: SASetNSAccountInformation
  1268. //
  1269. // Synopsis: Configure the NetSchedule account.
  1270. //
  1271. // Arguments: [Handle] -- Unused.
  1272. // [pwszAccount] -- Account name. If NULL, reset the credential
  1273. // information to zero.
  1274. // [pwszPassword] -- Account password.
  1275. //
  1276. // Returns: S_OK -- Operation successful.
  1277. // HRESULT -- Error.
  1278. //
  1279. // Notes: None.
  1280. //
  1281. //----------------------------------------------------------------------------
  1282. HRESULT
  1283. SASetNSAccountInformation(
  1284. SASEC_HANDLE Handle,
  1285. LPCWSTR pwszAccount,
  1286. LPCWSTR pwszPassword)
  1287. {
  1288. HRESULT hr = S_OK;
  1289. RPC_STATUS RpcStatus;
  1290. //
  1291. // If not done so already, initialize the DWORD global data element to be
  1292. // used in generation of the encryption key. It's possible this hasn't
  1293. // been performed yet.
  1294. //
  1295. if (!gdwKeyElement)
  1296. {
  1297. //
  1298. // NB : This routine enters (and leaves) the gcsSSCritSection
  1299. // critical section.
  1300. //
  1301. SetMysteryDWORDValue();
  1302. }
  1303. //
  1304. // The RPC caller must be an administrator to perform this function.
  1305. //
  1306. // Impersonate the caller.
  1307. //
  1308. if ((RpcStatus = RpcImpersonateClient(NULL)) != RPC_S_OK)
  1309. {
  1310. hr = _HRESULT_FROM_WIN32(RpcStatus);
  1311. CHECK_HRESULT(hr);
  1312. return(hr);
  1313. }
  1314. if (! IsThreadCallerAnAdmin(NULL))
  1315. {
  1316. hr = HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED);
  1317. }
  1318. //
  1319. // End impersonation.
  1320. //
  1321. if ((RpcStatus = RpcRevertToSelf()) != RPC_S_OK)
  1322. {
  1323. //
  1324. // BUGBUG : What to do if the impersonation revert fails?
  1325. //
  1326. hr = _HRESULT_FROM_WIN32(RpcStatus);
  1327. CHECK_HRESULT(hr);
  1328. schAssert(!"Couldn't revert to self");
  1329. }
  1330. if (FAILED(hr))
  1331. {
  1332. return(hr);
  1333. }
  1334. if (pwszPassword && wcslen(pwszPassword) > REAL_PWLEN)
  1335. return _HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
  1336. //
  1337. // Privilege level check above succeeded if we've gotten to this point.
  1338. //
  1339. // Retrieve the SID of the account name specified.
  1340. //
  1341. RC2_KEY_INFO RC2KeyInfo;
  1342. BYTE pbAccountSid[MAX_SID_SIZE];
  1343. PSID pAccountSid = NULL;
  1344. WCHAR wszDomain[MAX_DOMAINNAME + 1] = L"";
  1345. DWORD cbAccountSid = MAX_SID_SIZE;
  1346. DWORD ccDomain = MAX_DOMAINNAME + 1;
  1347. DWORD dwZero = 0;
  1348. DWORD cbEncryptedData = 0;
  1349. BYTE * pbEncryptedData = NULL;
  1350. SID_NAME_USE snu;
  1351. HCRYPTPROV hCSP = NULL;
  1352. if (pwszAccount != NULL)
  1353. {
  1354. if (!LookupAccountName(NULL,
  1355. pwszAccount,
  1356. pbAccountSid,
  1357. &cbAccountSid,
  1358. wszDomain,
  1359. &ccDomain,
  1360. &snu))
  1361. {
  1362. hr = _HRESULT_FROM_WIN32(GetLastError());
  1363. CHECK_HRESULT(hr);
  1364. return(SCHED_E_ACCOUNT_NAME_NOT_FOUND);
  1365. }
  1366. pAccountSid = pbAccountSid;
  1367. pwszAccount = SkipDomainName(pwszAccount);
  1368. //
  1369. // Verify that the credentials entered actually work.
  1370. // Also note that for NetSchedule jobs, there is no TASK_FLAG_RUN_ONLY_IF_LOGGED_ON,
  1371. // so if a NULL password is entered that mean the password really is supposed to be NULL.
  1372. //
  1373. if (!ValidateRunAs(pwszAccount, wszDomain, pwszPassword))
  1374. {
  1375. hr = E_ACCESSDENIED;
  1376. CHECK_HRESULT(hr);
  1377. return hr;
  1378. }
  1379. //
  1380. // Retrieve the original creds and compare with the ones we're about to save
  1381. // in order to determine if just the password is being updated. If so, notify LSA.
  1382. //
  1383. JOB_CREDENTIALS jc;
  1384. hr = GetNSAccountInformation(&jc);
  1385. if (SUCCEEDED(hr))
  1386. {
  1387. if ((lstrcmpiW(jc.wszAccount, pwszAccount) == 0) &&
  1388. (lstrcmpiW(jc.wszPassword, pwszPassword) != 0))
  1389. {
  1390. NotifyLsaOfPasswordChange(pwszAccount, wszDomain, pwszPassword);
  1391. }
  1392. ZERO_PASSWORD(jc.wszPassword);
  1393. }
  1394. }
  1395. //
  1396. // Guard SA security database access.
  1397. //
  1398. EnterCriticalSection(&gcsSSCritSection);
  1399. if (pwszAccount == NULL)
  1400. {
  1401. //
  1402. // zero the cred info out to indicate LocalSystem
  1403. //
  1404. hr = WriteLsaData(sizeof(WSZ_SANSC), WSZ_SANSC, sizeof(dwZero),
  1405. (BYTE *)&dwZero);
  1406. if (FAILED(hr))
  1407. {
  1408. CHECK_HRESULT(hr);
  1409. goto ErrorExit;
  1410. }
  1411. }
  1412. else
  1413. {
  1414. //
  1415. // Obtain a provider handle to the CSP (for use with Crypto API).
  1416. //
  1417. hr = GetCSPHandle(&hCSP);
  1418. if (FAILED(hr))
  1419. {
  1420. goto ErrorExit;
  1421. }
  1422. //
  1423. // Generate the encryption key & encrypt the account information
  1424. // passed.
  1425. //
  1426. hr = ComputeCredentialKey(hCSP, &RC2KeyInfo);
  1427. if (FAILED(hr))
  1428. {
  1429. goto ErrorExit;
  1430. }
  1431. hr = EncryptCredentials(RC2KeyInfo,
  1432. pwszAccount,
  1433. wszDomain,
  1434. pwszPassword,
  1435. pAccountSid,
  1436. &cbEncryptedData,
  1437. &pbEncryptedData);
  1438. // Clear key content.
  1439. //
  1440. SecureZeroMemory(&RC2KeyInfo, sizeof(RC2KeyInfo));
  1441. if (FAILED(hr))
  1442. {
  1443. goto ErrorExit;
  1444. }
  1445. hr = WriteLsaData(sizeof(WSZ_SANSC), WSZ_SANSC, cbEncryptedData,
  1446. pbEncryptedData);
  1447. delete [] pbEncryptedData;
  1448. if (FAILED(hr))
  1449. {
  1450. CHECK_HRESULT(hr);
  1451. goto ErrorExit;
  1452. }
  1453. }
  1454. //
  1455. // Grant the account batch privilege.
  1456. // We could choose to ignore the return code here, since the
  1457. // privilege can still be granted later; but if we ignored it,
  1458. // a caller might never know that the call failed until it was
  1459. // time to run the job, which is not good behavior. (See
  1460. // bug 366582)
  1461. //
  1462. if (pAccountSid != NULL)
  1463. {
  1464. hr = GrantAccountBatchPrivilege(pAccountSid);
  1465. }
  1466. ErrorExit:
  1467. LeaveCriticalSection(&gcsSSCritSection);
  1468. if (hCSP != NULL) CloseCSPHandle(hCSP);
  1469. return(hr);
  1470. }
  1471. //+---------------------------------------------------------------------------
  1472. //
  1473. // RPC: SAGetNSAccountInformation
  1474. //
  1475. // Synopsis: Retrieve the NetSchedule account name.
  1476. //
  1477. // Arguments: [Handle] --
  1478. // [ccBufferSize] --
  1479. // [wszBuffer] --
  1480. //
  1481. // Returns: S_OK -- Operation successful.
  1482. // S_FALSE -- No account specified.
  1483. // HRESULT -- Error.
  1484. //
  1485. // Notes: None.
  1486. //
  1487. //----------------------------------------------------------------------------
  1488. HRESULT
  1489. SAGetNSAccountInformation(
  1490. SASEC_HANDLE Handle,
  1491. DWORD ccBufferSize,
  1492. WCHAR wszBuffer[])
  1493. {
  1494. HRESULT hr = S_OK;
  1495. //
  1496. // Verify that caller has permission before proceeding any further
  1497. //
  1498. schAssert(g_TasksFolderInfo.ptszPath != NULL);
  1499. if (FAILED(hr = RPCFolderAccessCheck(g_TasksFolderInfo.ptszPath, FILE_READ_DATA, HandleImpersonation)))
  1500. return hr;
  1501. //
  1502. // Check for invalid params
  1503. //
  1504. if (!wszBuffer)
  1505. {
  1506. CHECK_HRESULT(E_INVALIDARG);
  1507. return(E_INVALIDARG);
  1508. }
  1509. //
  1510. // Retrieve the NetSchedule credentials, but return only the account name.
  1511. //
  1512. JOB_CREDENTIALS jc;
  1513. hr = GetNSAccountInformation(&jc);
  1514. if (SUCCEEDED(hr) && hr != S_FALSE)
  1515. {
  1516. ZERO_PASSWORD(jc.wszPassword); // Not needed; NULL handled.
  1517. if (ccBufferSize > (jc.ccAccount + 1 + jc.ccDomain))
  1518. {
  1519. StringCchCopy(wszBuffer, ccBufferSize, jc.wszDomain);
  1520. StringCchCat(wszBuffer, ccBufferSize, L"\\");
  1521. StringCchCat(wszBuffer, ccBufferSize, jc.wszAccount);
  1522. }
  1523. else
  1524. {
  1525. //
  1526. // Should *never* occur.
  1527. //
  1528. hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
  1529. CHECK_HRESULT(hr);
  1530. }
  1531. }
  1532. else
  1533. {
  1534. //
  1535. // Note that LocalSystem accounts will be returned under the S_FALSE condition;
  1536. // set the buffer to the empty string to reflect this
  1537. //
  1538. if (S_FALSE == hr)
  1539. {
  1540. StringCchCopy(wszBuffer, ccBufferSize, L"");
  1541. }
  1542. }
  1543. return(hr);
  1544. }
  1545. //+---------------------------------------------------------------------------
  1546. //
  1547. // Function: GetNSAccountInformation
  1548. //
  1549. // Synopsis: Retrieve the NetSchedule account credentials.
  1550. //
  1551. // Arguments: [pjc] -- Returned credentials.
  1552. //
  1553. // Returns: S_OK -- Operation successful.
  1554. // S_FALSE -- No account specified.
  1555. // HRESULT -- Error.
  1556. //
  1557. // Notes: None.
  1558. //
  1559. //----------------------------------------------------------------------------
  1560. HRESULT
  1561. GetNSAccountInformation(
  1562. PJOB_CREDENTIALS pjc)
  1563. {
  1564. RC2_KEY_INFO RC2KeyInfo;
  1565. DWORD cbEncryptedData = 0;
  1566. BYTE * pbEncryptedData = NULL;
  1567. HCRYPTPROV hCSP = NULL;
  1568. HRESULT hr;
  1569. //
  1570. // If not done so already, initialize the DWORD global data element to be
  1571. // used in generation of the encryption key. It's possible this hasn't
  1572. // been performed yet.
  1573. //
  1574. if (!gdwKeyElement)
  1575. {
  1576. //
  1577. // NB : This routine enters (and leaves) the gcsSSCritSection
  1578. // critical section.
  1579. //
  1580. SetMysteryDWORDValue();
  1581. }
  1582. //
  1583. // Guard SA security database access.
  1584. //
  1585. EnterCriticalSection(&gcsSSCritSection);
  1586. //
  1587. // Read SAI & SAC databases.
  1588. //
  1589. hr = ReadLsaData(sizeof(WSZ_SANSC), WSZ_SANSC, &cbEncryptedData,
  1590. &pbEncryptedData);
  1591. if (FAILED(hr) || hr == S_FALSE)
  1592. {
  1593. CHECK_HRESULT(hr);
  1594. goto ErrorExit;
  1595. }
  1596. else if (cbEncryptedData <= sizeof(DWORD))
  1597. {
  1598. //
  1599. // The information was specified previously but has been reset since.
  1600. //
  1601. // NOTE: This will be the case if the value has been reset back to LocalSystem,
  1602. // as it merely stores a dword = 0x00000000 in that case
  1603. //
  1604. hr = S_FALSE;
  1605. goto ErrorExit;
  1606. }
  1607. //
  1608. // Obtain a provider handle to the CSP (for use with Crypto API).
  1609. //
  1610. hr = GetCSPHandle(&hCSP);
  1611. if (FAILED(hr))
  1612. {
  1613. goto ErrorExit;
  1614. }
  1615. //
  1616. // Generate key & decrypt the credentials.
  1617. //
  1618. hr = ComputeCredentialKey(hCSP, &RC2KeyInfo);
  1619. if (SUCCEEDED(hr))
  1620. {
  1621. // *** Important ***
  1622. //
  1623. // The encrypted credentials passed are decrypted *in-place*.
  1624. // The decrypted data must be zeroed immediately following decryption
  1625. // (even in a failure case).
  1626. //
  1627. hr = DecryptCredentials(RC2KeyInfo,
  1628. cbEncryptedData,
  1629. pbEncryptedData,
  1630. pjc);
  1631. // Don't leave the plain-text password on the heap.
  1632. //
  1633. SecureZeroMemory(pbEncryptedData, cbEncryptedData);
  1634. // Clear key content.
  1635. //
  1636. SecureZeroMemory(&RC2KeyInfo, sizeof(RC2KeyInfo));
  1637. }
  1638. ErrorExit:
  1639. LeaveCriticalSection(&gcsSSCritSection);
  1640. if (pbEncryptedData != NULL) LocalFree(pbEncryptedData);
  1641. if (hCSP != NULL) CloseCSPHandle(hCSP);
  1642. return(hr);
  1643. }
  1644. //+---------------------------------------------------------------------------
  1645. //
  1646. // RPC: SAGetAccountInformation
  1647. //
  1648. // Synopsis:
  1649. //
  1650. // Arguments: [pwszJobName] -- Relative job name. eg: MyJob.job.
  1651. // [ccBufferSize] --
  1652. // [wszBuffer] --
  1653. //
  1654. // Returns: HRESULT
  1655. //
  1656. // Notes: None.
  1657. //
  1658. //----------------------------------------------------------------------------
  1659. HRESULT
  1660. SAGetAccountInformation(
  1661. SASEC_HANDLE Handle,
  1662. LPCWSTR pwszJobName,
  1663. DWORD ccBufferSize,
  1664. WCHAR wszBuffer[])
  1665. {
  1666. HRESULT hr = S_OK;
  1667. // we're going to do the access check in two stages,
  1668. // first make sure that the principal is allowed to
  1669. // do any scheduling whatsoever - later on, we'll
  1670. // check permissions on the specific file in question
  1671. if (FAILED(hr = RPCFolderAccessCheck(g_TasksFolderInfo.ptszPath, FILE_READ_DATA, HandleImpersonation)))
  1672. {
  1673. CHECK_HRESULT(hr);
  1674. return hr;
  1675. }
  1676. //
  1677. // Check for invalid params
  1678. //
  1679. if (pwszJobName == NULL || wszBuffer == NULL)
  1680. {
  1681. CHECK_HRESULT(E_INVALIDARG);
  1682. return(E_INVALIDARG);
  1683. }
  1684. //
  1685. // Disallow files outside the tasks folder
  1686. //
  1687. if (wcschr(pwszJobName, L'\\') || wcschr(pwszJobName, L'/'))
  1688. {
  1689. CHECK_HRESULT(E_INVALIDARG);
  1690. return(E_INVALIDARG);
  1691. }
  1692. //
  1693. // Append the job name to the local Task's folder path.
  1694. //
  1695. WCHAR wszJobPath[MAX_PATH + 1];
  1696. schAssert(g_TasksFolderInfo.ptszPath != NULL);
  1697. if ((wcslen(g_TasksFolderInfo.ptszPath) + 1 + wcslen(pwszJobName) + 1) > (MAX_PATH + 1))
  1698. {
  1699. CHECK_HRESULT(SCHED_E_CANNOT_OPEN_TASK);
  1700. return(SCHED_E_CANNOT_OPEN_TASK);
  1701. }
  1702. StringCchCopy(wszJobPath, MAX_PATH + 1, g_TasksFolderInfo.ptszPath);
  1703. StringCchCat(wszJobPath, MAX_PATH + 1, L"\\");
  1704. StringCchCat(wszJobPath, MAX_PATH + 1, pwszJobName);
  1705. //
  1706. // Verify that caller has permission before proceeding any further
  1707. //
  1708. if (FAILED(hr = RPCFolderAccessCheck(wszJobPath, FILE_READ_DATA, HandleImpersonation)))
  1709. return hr;
  1710. //
  1711. // Retrieve the job's credentials, but return only the account name.
  1712. //
  1713. JOB_CREDENTIALS jc;
  1714. hr = GetAccountInformation(wszJobPath, &jc);
  1715. if (SUCCEEDED(hr))
  1716. {
  1717. ZERO_PASSWORD(jc.wszPassword); // Not needed; NULL handled.
  1718. if (ccBufferSize > (jc.ccAccount + 1 + jc.ccDomain))
  1719. {
  1720. //
  1721. // If the job was scheduled to run in the LocalSystem account,
  1722. // Accountname is the empty string
  1723. //
  1724. if (jc.wszAccount[0] == L'\0')
  1725. {
  1726. wszBuffer[0] = L'\0';
  1727. }
  1728. else
  1729. {
  1730. //
  1731. // If the account was supplied as a UPN, DomainName is
  1732. // the empty string
  1733. //
  1734. StringCchCopy(wszBuffer, ccBufferSize, jc.wszDomain);
  1735. if (wszBuffer[0] != L'\0')
  1736. {
  1737. StringCchCat(wszBuffer, ccBufferSize, L"\\");
  1738. }
  1739. StringCchCat(wszBuffer, ccBufferSize, jc.wszAccount);
  1740. }
  1741. }
  1742. else
  1743. {
  1744. //
  1745. // Should *never* occur.
  1746. //
  1747. hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
  1748. CHECK_HRESULT(hr);
  1749. }
  1750. }
  1751. return(hr);
  1752. }
  1753. //+---------------------------------------------------------------------------
  1754. //
  1755. // Function: GetAccountInformation
  1756. //
  1757. // Synopsis:
  1758. //
  1759. // Arguments: [pwszJobPath] -- Fully qualified job path.
  1760. // eg: D:\NT\Tasks\MyJob.job.
  1761. // [pjc] --
  1762. //
  1763. // Returns: HRESULT
  1764. //
  1765. // Notes: None.
  1766. //
  1767. //----------------------------------------------------------------------------
  1768. HRESULT
  1769. GetAccountInformation(
  1770. LPCWSTR pwszJobPath,
  1771. PJOB_CREDENTIALS pjc)
  1772. {
  1773. BYTE rgbIdentity[HASH_DATA_SIZE];
  1774. HCRYPTPROV hCSP = NULL;
  1775. DWORD CredentialIndex;
  1776. DWORD cbSAI;
  1777. DWORD cbSAC;
  1778. DWORD cbCredential;
  1779. BYTE * pbCredential;
  1780. BYTE * pbSAI = NULL;
  1781. BYTE * pbSAC = NULL;
  1782. BOOL fIsPasswordNull = FALSE;
  1783. HRESULT hr;
  1784. //
  1785. // Obtain a provider handle to the CSP (for use with Crypto API).
  1786. //
  1787. hr = GetCSPHandle(&hCSP);
  1788. if (FAILED(hr))
  1789. {
  1790. return(hr);
  1791. }
  1792. //
  1793. // Hash the job into a unique identity.
  1794. // It will be used for credential lookup.
  1795. //
  1796. hr = HashJobIdentity(hCSP, pwszJobPath, rgbIdentity);
  1797. if (FAILED(hr))
  1798. {
  1799. CloseCSPHandle(hCSP);
  1800. return(hr);
  1801. }
  1802. //
  1803. // Guard SA security database access.
  1804. //
  1805. EnterCriticalSection(&gcsSSCritSection);
  1806. //
  1807. // Read SAI & SAC databases.
  1808. //
  1809. hr = ReadSecurityDBase(&cbSAI, &pbSAI, &cbSAC, &pbSAC);
  1810. if (FAILED(hr))
  1811. {
  1812. CHECK_HRESULT(hr);
  1813. goto ErrorExit;
  1814. }
  1815. //
  1816. // Does this identity exist in the LSA?
  1817. //
  1818. hr = SAIFindIdentity(rgbIdentity,
  1819. cbSAI,
  1820. pbSAI,
  1821. &CredentialIndex,
  1822. &fIsPasswordNull);
  1823. if (FAILED(hr))
  1824. {
  1825. CHECK_HRESULT(hr);
  1826. goto ErrorExit;
  1827. }
  1828. else if (hr == S_OK) // Found it.
  1829. {
  1830. //
  1831. // Index the credential associated with the identity.
  1832. //
  1833. hr = SACIndexCredential(CredentialIndex,
  1834. cbSAC,
  1835. pbSAC,
  1836. &cbCredential,
  1837. &pbCredential);
  1838. if (FAILED(hr))
  1839. {
  1840. CHECK_HRESULT(hr);
  1841. goto ErrorExit;
  1842. }
  1843. else if (hr == S_FALSE)
  1844. {
  1845. //
  1846. // Credential not found? The SAC & SAI databases are out of sync.
  1847. // This should *never* occur.
  1848. //
  1849. ASSERT_SECURITY_DBASE_CORRUPT();
  1850. hr = SCHED_E_ACCOUNT_DBASE_CORRUPT;
  1851. goto ErrorExit;
  1852. }
  1853. //
  1854. // Generate key & decrypt the credentials.
  1855. //
  1856. RC2_KEY_INFO RC2KeyInfo;
  1857. hr = ComputeCredentialKey(hCSP, &RC2KeyInfo);
  1858. if (SUCCEEDED(hr))
  1859. {
  1860. // *** Important ***
  1861. //
  1862. // The encrypted credentials passed are decrypted
  1863. // *in-place*. Therefore, SAC buffer content has been
  1864. // compromised; plus, the decrypted data must be zeroed
  1865. // immediately following decryption (even in a failure
  1866. // case).
  1867. //
  1868. // NB : The start of the credential refers to the
  1869. // credential identity. Skip over this to refer
  1870. // to the encrypted bits.
  1871. //
  1872. DWORD cbEncryptedData = cbCredential - HASH_DATA_SIZE;
  1873. BYTE * pbEncryptedData = pbCredential + HASH_DATA_SIZE;
  1874. hr = DecryptCredentials(RC2KeyInfo,
  1875. cbEncryptedData,
  1876. pbEncryptedData,
  1877. pjc);
  1878. CHECK_HRESULT(hr);
  1879. if (SUCCEEDED(hr))
  1880. {
  1881. // Don't leave the plain-text password on the heap.
  1882. //
  1883. SecureZeroMemory(pbEncryptedData, cbEncryptedData);
  1884. //
  1885. // If the SAI said this job has a null password, that
  1886. // overrides the password read from the SAC.
  1887. //
  1888. if (fIsPasswordNull)
  1889. {
  1890. pjc->fIsPasswordNull = TRUE;
  1891. SecureZeroMemory(pjc->wszPassword, sizeof pjc->wszPassword);
  1892. pjc->ccPassword = 0;
  1893. }
  1894. }
  1895. // Clear key content.
  1896. //
  1897. SecureZeroMemory(&RC2KeyInfo, sizeof(RC2KeyInfo));
  1898. }
  1899. }
  1900. else
  1901. {
  1902. hr = SCHED_E_ACCOUNT_INFORMATION_NOT_SET;
  1903. }
  1904. ErrorExit:
  1905. if (pbSAI != NULL) LocalFree(pbSAI);
  1906. if (pbSAC != NULL) LocalFree(pbSAC);
  1907. if (hCSP != NULL) CloseCSPHandle(hCSP);
  1908. //
  1909. // Log an error & rest the SA security dbases SAI & SAC
  1910. // if corruption is detected.
  1911. //
  1912. if (hr == SCHED_E_ACCOUNT_DBASE_CORRUPT)
  1913. {
  1914. //
  1915. // Log an error.
  1916. //
  1917. LogServiceError(IERR_SECURITY_DBASE_CORRUPTION, 0,
  1918. IDS_HELP_HINT_DBASE_CORRUPT);
  1919. //
  1920. // Reset SAI & SAC by writing four bytes of zeros into each.
  1921. // Ignore the return code. No recourse if this fails.
  1922. //
  1923. DWORD dwZero = 0;
  1924. WriteSecurityDBase(sizeof(dwZero), (BYTE *)&dwZero, sizeof(dwZero),
  1925. (BYTE *)&dwZero);
  1926. }
  1927. LeaveCriticalSection(&gcsSSCritSection);
  1928. return(hr);
  1929. }
  1930. //+---------------------------------------------------------------------------
  1931. //
  1932. // Function: HashJobIdentity
  1933. //
  1934. // Synopsis: calculate a hash from several pieces of data specific to the job file
  1935. // that can help to uniquely identify the job and detect tampering
  1936. //
  1937. // Arguments: [hCSP] -- handle to cryptographic service provider
  1938. // [pwszFileName] -- job file name
  1939. // [rgbHash] -- hashed identity
  1940. // [dwHashMethod -- dword value indicating which hash method to use;
  1941. // Default if not specified is the latest method.
  1942. //
  1943. // Returns: HRESULT
  1944. //
  1945. // Notes: 11/09/2002 - it was discovered that the value retrieved for domain name
  1946. // (and possibly account name) may not always be the same case, thus causing
  1947. // different hashes to be produced even though the domain had not changed,
  1948. // and the file had not been touched. Always forcing the names to upper case
  1949. // prior to calculating the hash prevents such a change from affecting the
  1950. // hash. Removing the values from the hash calculation altogether also
  1951. // avoids the problem and prevents localization from having negative affects
  1952. // as well. A new parameter, dwHashMethod, has been introduced to allow different
  1953. // hashing methods to be employed to facilitate conversion of existing data.
  1954. //
  1955. //----------------------------------------------------------------------------
  1956. HRESULT
  1957. HashJobIdentity(
  1958. HCRYPTPROV hCSP,
  1959. LPCWSTR pwszFileName,
  1960. BYTE rgbHash[],
  1961. DWORD dwHashMethod /* = 1 */)
  1962. {
  1963. WCHAR wszApplication[MAX_PATH + 1] = L"";
  1964. WCHAR wszOwnerName[MAX_USERNAME + 1] = L"";
  1965. WCHAR wszOwnerDomain[MAX_DOMAINNAME + 1] = L"";
  1966. UUID JobID;
  1967. FILETIME ftCreationTime;
  1968. PSECURITY_DESCRIPTOR pOwnerSecDescr = NULL;
  1969. DWORD cbOwnerSid;
  1970. PSID pOwnerSid;
  1971. DWORD dwVolumeSerialNo;
  1972. HRESULT hr;
  1973. hr = GetFileInformation(pwszFileName,
  1974. &cbOwnerSid,
  1975. &pOwnerSid,
  1976. &pOwnerSecDescr,
  1977. &JobID,
  1978. MAX_USERNAME + 1,
  1979. MAX_DOMAINNAME + 1,
  1980. MAX_PATH + 1,
  1981. wszOwnerName,
  1982. wszOwnerDomain,
  1983. wszApplication,
  1984. &ftCreationTime,
  1985. &dwVolumeSerialNo);
  1986. if (SUCCEEDED(hr))
  1987. {
  1988. DWORD cbHash = HASH_DATA_SIZE;
  1989. BYTE * pbHash = rgbHash;
  1990. if (dwHashMethod == 0)
  1991. {
  1992. hr = MarshalData(hCSP,
  1993. NULL,
  1994. HashAndSign,
  1995. &cbHash,
  1996. &pbHash,
  1997. 7,
  1998. cbOwnerSid,
  1999. pOwnerSid,
  2000. sizeof(JobID),
  2001. &JobID,
  2002. (wcslen(wszOwnerName) + 1) * sizeof(WCHAR),
  2003. wszOwnerName,
  2004. (wcslen(wszOwnerDomain) + 1) * sizeof(WCHAR),
  2005. wszOwnerDomain,
  2006. (wcslen(wszApplication) + 1) * sizeof(WCHAR),
  2007. wszApplication,
  2008. sizeof(ftCreationTime),
  2009. &ftCreationTime,
  2010. sizeof(dwVolumeSerialNo),
  2011. &dwVolumeSerialNo);
  2012. }
  2013. else /* if (dwHashMethod == 1) */
  2014. {
  2015. hr = MarshalData(hCSP,
  2016. NULL,
  2017. HashAndSign,
  2018. &cbHash,
  2019. &pbHash,
  2020. 5,
  2021. cbOwnerSid,
  2022. pOwnerSid,
  2023. sizeof(JobID),
  2024. &JobID,
  2025. (wcslen(wszApplication) + 1) * sizeof(WCHAR),
  2026. wszApplication,
  2027. sizeof(ftCreationTime),
  2028. &ftCreationTime,
  2029. sizeof(dwVolumeSerialNo),
  2030. &dwVolumeSerialNo);
  2031. }
  2032. schAssert(pbHash == rgbHash);
  2033. }
  2034. // BUGBUG Is pOwnerSid leaked???
  2035. delete pOwnerSecDescr;
  2036. return(hr);
  2037. }
  2038. //+---------------------------------------------------------------------------
  2039. //
  2040. // Function: GrantAccountBatchPrivilege
  2041. //
  2042. // Synopsis: Grant the account batch privilege.
  2043. //
  2044. // Arguments: [pAccountSid] -- Account set.
  2045. //
  2046. // Arguments: None.
  2047. //
  2048. // Returns: HRESULTs
  2049. //
  2050. // Notes: None.
  2051. //
  2052. //----------------------------------------------------------------------------
  2053. HRESULT
  2054. GrantAccountBatchPrivilege(PSID pAccountSid)
  2055. {
  2056. HRESULT hr = S_OK;
  2057. LSA_OBJECT_ATTRIBUTES ObjectAttributes = {
  2058. sizeof(LSA_OBJECT_ATTRIBUTES),
  2059. NULL,
  2060. NULL,
  2061. 0L,
  2062. NULL,
  2063. NULL
  2064. };
  2065. LSA_HANDLE hPolicy;
  2066. NTSTATUS Status = LsaOpenPolicy(NULL,
  2067. &ObjectAttributes,
  2068. POLICY_CREATE_ACCOUNT,
  2069. &hPolicy);
  2070. if (Status >= 0)
  2071. {
  2072. LSA_UNICODE_STRING PrivilegeString = {
  2073. sizeof(SE_BATCH_LOGON_NAME) - 2,
  2074. sizeof(SE_BATCH_LOGON_NAME),
  2075. SE_BATCH_LOGON_NAME,
  2076. };
  2077. Status = LsaAddAccountRights(hPolicy, pAccountSid, &PrivilegeString, 1);
  2078. if (Status < 0)
  2079. {
  2080. ERR_OUT("LsaAddAccountRights", Status);
  2081. }
  2082. LsaClose(hPolicy);
  2083. }
  2084. else
  2085. {
  2086. ERR_OUT("LsaOpenPolicy", Status);
  2087. }
  2088. if (Status < 0)
  2089. {
  2090. schAssert(!"Grant Batch Privilege failed, shouldn't have");
  2091. DWORD err = RtlNtStatusToDosError(Status);
  2092. hr = HRESULT_FROM_WIN32(err);
  2093. }
  2094. return hr;
  2095. }
  2096. //+---------------------------------------------------------------------------
  2097. //
  2098. // Function: MarshalData
  2099. //
  2100. // Synopsis: [hCSP] --
  2101. // [phHash] --
  2102. // [MarshalFunction] --
  2103. // [pcbSignature] --
  2104. // [ppbSignature] --
  2105. // [cArgs] --
  2106. // [...] --
  2107. //
  2108. // Arguments: None.
  2109. //
  2110. // Returns: HRESULT
  2111. //
  2112. // Notes: None.
  2113. //
  2114. //----------------------------------------------------------------------------
  2115. HRESULT
  2116. MarshalData(
  2117. HCRYPTPROV hCSP,
  2118. HCRYPTHASH * phHash,
  2119. MARSHAL_FUNCTION MarshalFunction,
  2120. DWORD * pcbSignature,
  2121. BYTE ** ppbSignature,
  2122. DWORD cArgs,
  2123. ...)
  2124. {
  2125. #define COPYMEMORY(dest, src, size) { \
  2126. CopyMemory(*dest, src, size); \
  2127. *(BYTE **)dest += size; \
  2128. }
  2129. HCRYPTHASH hHash = NULL;
  2130. DWORD cbSignature = 0;
  2131. BYTE * pbSignature = NULL;
  2132. HRESULT hr = S_OK;
  2133. va_list pvarg;
  2134. va_start(pvarg, cArgs);
  2135. DWORD i, cbSize, cbData = 0;
  2136. for (i = cArgs; i--; )
  2137. {
  2138. cbData += va_arg(pvarg, DWORD);
  2139. va_arg(pvarg, BYTE *);
  2140. }
  2141. BYTE * pbData, * pb;
  2142. pbData = pb = new BYTE[cbData];
  2143. if (pbData == NULL)
  2144. {
  2145. hr = E_OUTOFMEMORY;
  2146. CHECK_HRESULT(hr);
  2147. goto ErrorExit;
  2148. }
  2149. va_start(pvarg, cArgs);
  2150. for (i = cArgs; i--; )
  2151. {
  2152. cbSize = va_arg(pvarg, DWORD);
  2153. COPYMEMORY(&pb, va_arg(pvarg, BYTE *), cbSize);
  2154. }
  2155. if (MarshalFunction == Marshal)
  2156. {
  2157. //
  2158. // Done. Return marshal data in the signature return args.
  2159. //
  2160. *pcbSignature = cbData;
  2161. *ppbSignature = pbData;
  2162. va_end(pvarg);
  2163. return(S_OK);
  2164. }
  2165. //
  2166. // Acquire a handle to an MD5 hashing object. MD5 is the most secure
  2167. // hashing algorithm.
  2168. //
  2169. schAssert(hCSP != NULL);
  2170. #if DBG
  2171. //
  2172. // We must not be impersonating while calling the Crypto APIs.
  2173. // If we are, the key data will go in the wrong hives.
  2174. //
  2175. HANDLE hToken;
  2176. schAssert(!OpenThreadToken(GetCurrentThread(),
  2177. TOKEN_QUERY, // Desired access.
  2178. TRUE, // Open as self.
  2179. &hToken));
  2180. #endif
  2181. if (!CryptCreateHash(hCSP,
  2182. CALG_MD5, // Use MD5 hashing.
  2183. 0, // MD5 is non-keyed.
  2184. 0, // New key container.
  2185. &hHash)) // Returned handle.
  2186. {
  2187. hr = _HRESULT_FROM_WIN32(GetLastError());
  2188. CHECK_HRESULT(hr);
  2189. goto ErrorExit;
  2190. }
  2191. //
  2192. // Hash and optionally sign the data. The hash is cached w/in the hash
  2193. // object and returned upon signing.
  2194. //
  2195. if (!CryptHashData(hHash,
  2196. pbData, // Hash data.
  2197. cbData, // Hash data size.
  2198. 0)) // No special flags.
  2199. {
  2200. hr = _HRESULT_FROM_WIN32(GetLastError());
  2201. CHECK_HRESULT(hr);
  2202. goto ErrorExit;
  2203. }
  2204. if (MarshalFunction == HashAndSign)
  2205. {
  2206. //
  2207. // First, determine necessary signature buffer size & allocate it.
  2208. //
  2209. if (!CryptSignHash(hHash,
  2210. AT_SIGNATURE, // Signature private key.
  2211. NULL, // No signature.
  2212. 0, // Reserved.
  2213. NULL, // NULL return buffer.
  2214. &cbSignature)) // Returned size.
  2215. {
  2216. hr = _HRESULT_FROM_WIN32(GetLastError());
  2217. CHECK_HRESULT(hr);
  2218. goto ErrorExit;
  2219. }
  2220. //
  2221. // Caller can supply a buffer to return the signed data only with
  2222. // the HashAndSign option. This is an optimization to reduce the
  2223. // number of memory allocations with known data sizes such as
  2224. // hashed data.
  2225. //
  2226. if (*pcbSignature)
  2227. {
  2228. if (*pcbSignature >= cbSignature)
  2229. {
  2230. //
  2231. // Caller supplied a buffer & the signed data will fit in it.
  2232. //
  2233. pbSignature = *ppbSignature;
  2234. }
  2235. else
  2236. {
  2237. //
  2238. // Caller supplied buffer insufficient size.
  2239. // This is a developer error only.
  2240. //
  2241. hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
  2242. schAssert(0 && "MarshalData insufficient buffer!");
  2243. goto ErrorExit;
  2244. }
  2245. }
  2246. else
  2247. {
  2248. pbSignature = new BYTE[cbSignature];
  2249. if (pbSignature == NULL)
  2250. {
  2251. hr = E_OUTOFMEMORY;
  2252. CHECK_HRESULT(hr);
  2253. goto ErrorExit;
  2254. }
  2255. }
  2256. //
  2257. // Perform the actual signing.
  2258. //
  2259. if (!CryptSignHash(hHash,
  2260. AT_SIGNATURE, // Signature private key.
  2261. NULL, // No signature.
  2262. 0, // Reserved.
  2263. pbSignature, // Signature buffer.
  2264. &cbSignature)) // Buffer size.
  2265. {
  2266. hr = _HRESULT_FROM_WIN32(GetLastError());
  2267. CHECK_HRESULT(hr);
  2268. goto ErrorExit;
  2269. }
  2270. *pcbSignature = cbSignature;
  2271. *ppbSignature = pbSignature;
  2272. }
  2273. if (phHash != NULL)
  2274. {
  2275. *phHash = hHash;
  2276. hHash = NULL;
  2277. }
  2278. ErrorExit:
  2279. delete pbData;
  2280. if (FAILED(hr))
  2281. {
  2282. //
  2283. // Caller may have supplied the signature data buffer in the
  2284. // HashAndSign option. If so, don't delete it.
  2285. //
  2286. if (pbSignature != *ppbSignature)
  2287. {
  2288. delete pbSignature;
  2289. }
  2290. }
  2291. if (hHash != NULL) CryptDestroyHash(hHash);
  2292. va_end(pvarg);
  2293. return(hr);
  2294. }
  2295. //+---------------------------------------------------------------------------
  2296. //
  2297. // Function: HashSid
  2298. //
  2299. // Synopsis: [hCSP] --
  2300. // [pSid] --
  2301. // [rgbHash] --
  2302. //
  2303. // Arguments: None.
  2304. //
  2305. // Returns: HRESULT
  2306. //
  2307. // Notes: None.
  2308. //
  2309. //----------------------------------------------------------------------------
  2310. STATIC HRESULT
  2311. HashSid(
  2312. HCRYPTPROV hCSP,
  2313. PSID pSid,
  2314. BYTE rgbHash[])
  2315. {
  2316. DWORD rgdwSubAuthorities[SID_MAX_SUB_AUTHORITIES];
  2317. SID_IDENTIFIER_AUTHORITY * pAuthority;
  2318. //
  2319. // Validate the sid passed. This is important since the win32
  2320. // documentation for the sid-related api states the returns are
  2321. // undefined if the functions fail.
  2322. //
  2323. if (!IsValidSid(pSid))
  2324. {
  2325. CHECK_HRESULT(_HRESULT_FROM_WIN32(GetLastError()));
  2326. return(E_UNEXPECTED);
  2327. }
  2328. //
  2329. // Fetch the sid identifier authority.
  2330. // BUGBUG : I hate this. The doc states if these functions fail, the
  2331. // return value is undefined. How to determine failure?
  2332. //
  2333. pAuthority = GetSidIdentifierAuthority(pSid);
  2334. //
  2335. // Fetch all sid subauthorities. Copy them to a temporary buffer in
  2336. // preparation for hashing.
  2337. //
  2338. PUCHAR pcSubAuthorities = GetSidSubAuthorityCount(pSid);
  2339. UCHAR cSubAuthoritiesCopied = min(*pcSubAuthorities,
  2340. SID_MAX_SUB_AUTHORITIES);
  2341. for (UCHAR i = 0; i < cSubAuthoritiesCopied; i++)
  2342. {
  2343. rgdwSubAuthorities[i] = *GetSidSubAuthority(pSid, i);
  2344. }
  2345. DWORD cbHash = HASH_DATA_SIZE;
  2346. BYTE * pbHash = rgbHash;
  2347. HRESULT hr = MarshalData(hCSP,
  2348. NULL,
  2349. HashAndSign,
  2350. &cbHash,
  2351. &pbHash,
  2352. 2,
  2353. sizeof(SID_IDENTIFIER_AUTHORITY),
  2354. pAuthority,
  2355. cSubAuthoritiesCopied * sizeof(DWORD),
  2356. rgdwSubAuthorities);
  2357. schAssert(pbHash == rgbHash);
  2358. return(hr);
  2359. }
  2360. //+---------------------------------------------------------------------------
  2361. //
  2362. // Function: InitSS
  2363. //
  2364. // Synopsis:
  2365. //
  2366. // Arguments: None.
  2367. //
  2368. // Returns: HRESULT
  2369. //
  2370. // Notes: None.
  2371. //
  2372. //----------------------------------------------------------------------------
  2373. HRESULT
  2374. InitSS(void)
  2375. {
  2376. LSA_OBJECT_ATTRIBUTES ObjectAttributes = {
  2377. sizeof(LSA_OBJECT_ATTRIBUTES),
  2378. NULL,
  2379. NULL,
  2380. 0L,
  2381. NULL,
  2382. NULL
  2383. };
  2384. NTSTATUS Status;
  2385. HRESULT hr;
  2386. gccComputerName = sizeof(gwszComputerName) / sizeof(TCHAR);
  2387. if (!GetComputerName(gwszComputerName, &gccComputerName))
  2388. {
  2389. hr = _HRESULT_FROM_WIN32(GetLastError());
  2390. CHECK_HRESULT(hr);
  2391. goto ErrorExit;
  2392. }
  2393. //
  2394. // gwszComputerName will be munged. Save an unmunged copy in
  2395. // gpwszComputerName.
  2396. //
  2397. gpwszComputerName = new WCHAR[gccComputerName + 1];
  2398. if (gpwszComputerName == NULL)
  2399. {
  2400. hr = E_OUTOFMEMORY;
  2401. CHECK_HRESULT(hr);
  2402. goto ErrorExit;
  2403. }
  2404. StringCchCopy(gpwszComputerName, gccComputerName + 1, gwszComputerName);
  2405. //
  2406. // gwszComputerName is used only for credential encryption. The
  2407. // computer might have been renamed since the credential database was
  2408. // created, so the credential database might have been encrypted using
  2409. // a different computer name than the present one. If a computer name
  2410. // is stored in the registry, use that one rather than the present name.
  2411. // If no name is stored in the registry, store the present one.
  2412. //
  2413. {
  2414. //
  2415. // Open the schedule agent key
  2416. //
  2417. HKEY hSchedKey;
  2418. long lErr = RegOpenKeyEx(HKEY_LOCAL_MACHINE, SCH_AGENT_KEY, 0,
  2419. KEY_QUERY_VALUE | KEY_SET_VALUE, &hSchedKey);
  2420. if (lErr != ERROR_SUCCESS)
  2421. {
  2422. hr = HRESULT_FROM_WIN32(lErr);
  2423. CHECK_HRESULT(hr);
  2424. goto ErrorExit;
  2425. }
  2426. //
  2427. // Get the saved computer name
  2428. //
  2429. WCHAR wszOldName[MAX_COMPUTERNAME_LENGTH + 2];
  2430. DWORD dwType;
  2431. DWORD cb = sizeof(wszOldName);
  2432. lErr = RegQueryValueEx(hSchedKey, SCH_OLDNAME_VALUE, NULL, &dwType,
  2433. (LPBYTE)wszOldName, &cb);
  2434. if (lErr != ERROR_SUCCESS || dwType != REG_SZ)
  2435. {
  2436. schDebugOut((DEB_ERROR, "InitSS: Couldn't read OldName: err %u, "
  2437. "type %u. Writing '%ws'\n",
  2438. lErr, dwType, gwszComputerName));
  2439. //
  2440. // Write the present computer name
  2441. //
  2442. lErr = RegSetValueEx(hSchedKey, SCH_OLDNAME_VALUE, NULL, REG_SZ,
  2443. (LPBYTE) gwszComputerName,
  2444. (gccComputerName + 1) * sizeof(WCHAR));
  2445. if (lErr != ERROR_SUCCESS)
  2446. {
  2447. schDebugOut((DEB_ERROR, "InitSS: Couldn't write OldName: err %u\n",
  2448. lErr));
  2449. }
  2450. }
  2451. else if (lstrcmpi(gwszComputerName, wszOldName) != 0)
  2452. {
  2453. //
  2454. // Use the stored name instead of the present name
  2455. //
  2456. schDebugOut((DEB_ERROR, "InitSS: Using OldName '%ws'\n", wszOldName));
  2457. StringCchCopy(gwszComputerName, MAX_COMPUTERNAME_LENGTH + 2, wszOldName);
  2458. gccComputerName = (cb / sizeof(WCHAR)) - 1;
  2459. }
  2460. //
  2461. // Close the key
  2462. //
  2463. RegCloseKey(hSchedKey);
  2464. }
  2465. LSA_HANDLE hPolicy;
  2466. if (!(LsaOpenPolicy(NULL,
  2467. &ObjectAttributes,
  2468. POLICY_VIEW_LOCAL_INFORMATION,
  2469. &hPolicy) >= 0))
  2470. {
  2471. hr = E_UNEXPECTED;
  2472. CHECK_HRESULT(hr);
  2473. goto ErrorExit;
  2474. }
  2475. Status = LsaQueryInformationPolicy(hPolicy,
  2476. PolicyAccountDomainInformation,
  2477. (void **)&gpDomainInfo);
  2478. LsaClose(hPolicy);
  2479. if (!(Status >= 0))
  2480. {
  2481. hr = E_UNEXPECTED;
  2482. CHECK_HRESULT(hr);
  2483. goto ErrorExit;
  2484. }
  2485. MungeComputerName(gccComputerName);
  2486. gpMachineSid = gpDomainInfo->DomainSid;
  2487. gcbMachineSid = GetLengthSid(gpDomainInfo->DomainSid);
  2488. DWORD dwRet = StartupAuditing();
  2489. return _HRESULT_FROM_WIN32(dwRet);
  2490. ErrorExit:
  2491. return(hr);
  2492. }
  2493. //+---------------------------------------------------------------------------
  2494. //
  2495. // Function: UninitSS
  2496. //
  2497. // Synopsis:
  2498. //
  2499. // Arguments: None.
  2500. //
  2501. // Returns: None.
  2502. //
  2503. // Notes: None.
  2504. //
  2505. //----------------------------------------------------------------------------
  2506. void
  2507. UninitSS(void)
  2508. {
  2509. ShutdownAuditing();
  2510. if (gpDomainInfo != NULL)
  2511. {
  2512. LsaFreeMemory(gpDomainInfo);
  2513. gpDomainInfo = NULL;
  2514. }
  2515. if (gpwszComputerName != NULL)
  2516. {
  2517. delete gpwszComputerName;
  2518. gpwszComputerName = NULL;
  2519. }
  2520. }
  2521. //+---------------------------------------------------------------------------
  2522. //
  2523. // Function: MungeComputerName
  2524. //
  2525. // Synopsis:
  2526. //
  2527. // Arguments: [psidUser] --
  2528. // [ccAccountName] --
  2529. // [wszAccountName] --
  2530. // [wszAccountNameSize] --
  2531. //
  2532. // Returns: None.
  2533. //
  2534. // Notes: None.
  2535. //
  2536. //----------------------------------------------------------------------------
  2537. STATIC void
  2538. MungeComputerName(DWORD ccComputerName)
  2539. {
  2540. WCHAR * pwszStart = gwszComputerName;
  2541. while (*pwszStart) pwszStart++;
  2542. gwszComputerName[MAX_COMPUTERNAME_LENGTH + 1] = L'\0';
  2543. //
  2544. // Set the character following the computername to a '+' or '-' depending
  2545. // on the value of ccAccountName (if the 2nd bit is set).
  2546. //
  2547. if ((ccComputerName - 1) & 0x00000001)
  2548. {
  2549. gwszComputerName[MAX_COMPUTERNAME_LENGTH] = L'+';
  2550. }
  2551. else
  2552. {
  2553. gwszComputerName[MAX_COMPUTERNAME_LENGTH] = L'-';
  2554. }
  2555. //
  2556. // Fill any intermediary buffer space with space characters. Note, no
  2557. // portion of the computername is overwritten.
  2558. //
  2559. // NB : The astute reader will notice the subtle difference in behavior
  2560. // if the computername should be of maximum length. In this case,
  2561. // the '+' or '-' character written above will be overwritten with
  2562. // a space.
  2563. //
  2564. WCHAR * pwszEnd = &gwszComputerName[MAX_COMPUTERNAME_LENGTH - 1];
  2565. if (pwszEnd > pwszStart)
  2566. {
  2567. while (pwszEnd != pwszStart)
  2568. {
  2569. *pwszEnd-- = L' ';
  2570. }
  2571. }
  2572. *pwszStart = L' ';
  2573. }
  2574. //+---------------------------------------------------------------------------
  2575. //
  2576. // Function: GetCSPHandle
  2577. //
  2578. // Synopsis:
  2579. //
  2580. // Arguments: None.
  2581. //
  2582. // Returns: HRESULT
  2583. //
  2584. // Notes: None.
  2585. //
  2586. //----------------------------------------------------------------------------
  2587. HRESULT
  2588. GetCSPHandle(HCRYPTPROV * phCSP)
  2589. {
  2590. #if DBG
  2591. //
  2592. // We must not be impersonating while calling the Crypto APIs.
  2593. // If we are, the key data will go in the wrong hives.
  2594. //
  2595. HANDLE hToken;
  2596. schAssert(!OpenThreadToken(GetCurrentThread(),
  2597. TOKEN_QUERY, // Desired access.
  2598. TRUE, // Open as self.
  2599. &hToken));
  2600. #endif
  2601. HRESULT hr;
  2602. if (!CryptAcquireContext(phCSP, // Returned CSP handle.
  2603. g_tszSrvcName, // Default Key container.
  2604. // MSFT RSA Base Provider.
  2605. NULL, // Default user provider.
  2606. PROV_RSA_FULL, // Default provider type.
  2607. 0)) // No special flags.
  2608. {
  2609. DWORD Status = GetLastError();
  2610. if (Status == NTE_KEYSET_ENTRY_BAD || Status == NTE_BAD_KEYSET)
  2611. {
  2612. //
  2613. // Delete the keyset and try again.
  2614. // Ignore this return code.
  2615. //
  2616. if (!CryptAcquireContext(phCSP,
  2617. g_tszSrvcName,
  2618. NULL,
  2619. PROV_RSA_FULL,
  2620. CRYPT_DELETEKEYSET))
  2621. {
  2622. ERR_OUT("CryptAcquireContext(delete)", GetLastError());
  2623. }
  2624. else
  2625. {
  2626. LogServiceError(IERR_SECURITY_KEYSET_CORRUPT, 0, IDS_HELP_HINT_DBASE_CORRUPT);
  2627. }
  2628. }
  2629. else
  2630. {
  2631. //
  2632. // Print the error in debug builds, but otherwise ignore it.
  2633. //
  2634. ERR_OUT("CryptAcquireContext(open)", Status);
  2635. }
  2636. //
  2637. // Assume this is the first time this code has been run on this
  2638. // particular machine. Must create a new keyset & key.
  2639. //
  2640. if (!CryptAcquireContext(phCSP,
  2641. g_tszSrvcName,
  2642. NULL,
  2643. PROV_RSA_FULL,
  2644. CRYPT_NEWKEYSET)) // New keyset.
  2645. {
  2646. Status = GetLastError();
  2647. if (Status == NTE_EXISTS)
  2648. {
  2649. //
  2650. // Our assumption was wrong!
  2651. // Delete the keyset and try again.
  2652. // Ignore this return code.
  2653. //
  2654. if (!CryptAcquireContext(phCSP,
  2655. g_tszSrvcName,
  2656. NULL,
  2657. PROV_RSA_FULL,
  2658. CRYPT_DELETEKEYSET))
  2659. {
  2660. hr = _HRESULT_FROM_WIN32(GetLastError());
  2661. CHECK_HRESULT(hr);
  2662. return(hr);
  2663. }
  2664. else
  2665. {
  2666. LogServiceError(IERR_SECURITY_KEYSET_CORRUPT, 0, IDS_HELP_HINT_DBASE_CORRUPT);
  2667. }
  2668. //
  2669. // Must now create a new keyset & key.
  2670. //
  2671. if (!CryptAcquireContext(phCSP,
  2672. g_tszSrvcName,
  2673. NULL,
  2674. PROV_RSA_FULL,
  2675. CRYPT_NEWKEYSET)) // New keyset.
  2676. {
  2677. hr = _HRESULT_FROM_WIN32(GetLastError());
  2678. CHECK_HRESULT(hr);
  2679. return(hr);
  2680. }
  2681. }
  2682. else
  2683. {
  2684. hr = _HRESULT_FROM_WIN32(Status);
  2685. CHECK_HRESULT(hr);
  2686. return(hr);
  2687. }
  2688. }
  2689. HCRYPTKEY hKey;
  2690. //
  2691. // The upper 16 bits of the 3rd parm to CryptGenKey specify the key
  2692. // size in bits. The size of the signature from CryptSignHash will
  2693. // be equal to the size of this key. Since we rely on the signature
  2694. // being a specific size, we must explicitly specify the key size.
  2695. //
  2696. if (!CryptGenKey(*phCSP,
  2697. AT_SIGNATURE, // Digital signature.
  2698. (HASH_DATA_SIZE * 8) << 16, // see above
  2699. &hKey ))
  2700. {
  2701. hr = _HRESULT_FROM_WIN32(GetLastError());
  2702. CHECK_HRESULT(hr);
  2703. return(hr);
  2704. }
  2705. CryptDestroyKey(hKey); // No further use for
  2706. // the key.
  2707. }
  2708. return(S_OK);
  2709. }
  2710. //+---------------------------------------------------------------------------
  2711. //
  2712. // Function: CloseCSPHandle
  2713. //
  2714. // Synopsis:
  2715. //
  2716. // Arguments: None.
  2717. //
  2718. // Returns: None.
  2719. //
  2720. // Notes: None.
  2721. //
  2722. //----------------------------------------------------------------------------
  2723. void
  2724. CloseCSPHandle(HCRYPTPROV hCSP)
  2725. {
  2726. CryptReleaseContext(hCSP, 0);
  2727. }
  2728. //+---------------------------------------------------------------------------
  2729. //
  2730. // Function: ComputeCredentialKey
  2731. //
  2732. // Synopsis:
  2733. //
  2734. // Arguments: [hCSP] --
  2735. // [pRC2KeyInfo] --
  2736. //
  2737. // Returns: HRESULT
  2738. //
  2739. // Notes: None.
  2740. //
  2741. //----------------------------------------------------------------------------
  2742. HRESULT
  2743. ComputeCredentialKey(HCRYPTPROV hCSP, RC2_KEY_INFO * pRC2KeyInfo)
  2744. {
  2745. BYTE rgbHash[HASH_DATA_SIZE];
  2746. HCRYPTHASH hHash = NULL;
  2747. DWORD cbHash = 0;
  2748. BYTE * pbHash = NULL;
  2749. HRESULT hr = S_OK;
  2750. DWORD i;
  2751. //
  2752. // Hash misc. global data.
  2753. //
  2754. // NB : MarshalData actually does nothing with the 3rd & 4th arguments
  2755. // with the Hash option.
  2756. //
  2757. hr = MarshalData(hCSP,
  2758. &hHash,
  2759. Hash,
  2760. &cbHash,
  2761. &pbHash,
  2762. 2,
  2763. (gccComputerName & 0x00000001 ?
  2764. (MAX_COMPUTERNAME_LENGTH + 2) * sizeof(WCHAR) :
  2765. sizeof(DWORD)),
  2766. (gccComputerName & 0x00000001 ?
  2767. (BYTE *)gwszComputerName : (BYTE *)&gdwKeyElement),
  2768. gcbMachineSid,
  2769. gpMachineSid);
  2770. //
  2771. // Generate the key.
  2772. //
  2773. // NB : In place of CryptDeriveKey, statically generate the key. This
  2774. // is done to work around Crypto restrictions in France.
  2775. //
  2776. // Old:
  2777. //
  2778. // CryptDeriveKey(ghCSP, CALG_RC2, hHash, 0, &hKey);
  2779. //
  2780. // New:
  2781. //
  2782. cbHash = sizeof(rgbHash);
  2783. if (!CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0))
  2784. {
  2785. hr = _HRESULT_FROM_WIN32(GetLastError());
  2786. CHECK_HRESULT(hr);
  2787. goto ErrorExit;
  2788. }
  2789. //
  2790. // Clear RC2KeyInfo content.
  2791. //
  2792. schAssert(pRC2KeyInfo != NULL);
  2793. SecureZeroMemory(pRC2KeyInfo, sizeof(*pRC2KeyInfo));
  2794. //
  2795. // Set the upper eleven bytes to 0x00 because Derive key by default
  2796. // uses 11 bytes of 0x00 salt
  2797. //
  2798. SecureZeroMemory(rgbHash + 5, 11);
  2799. //
  2800. // Use the 5 bytes (40 bits) of the hash as a key.
  2801. //
  2802. RC2KeyEx(pRC2KeyInfo->rgwKeyTable, rgbHash, 16, 40);
  2803. ErrorExit:
  2804. if (hHash != NULL) CryptDestroyHash(hHash);
  2805. return(hr);
  2806. }
  2807. //+---------------------------------------------------------------------------
  2808. //
  2809. // Function: EncryptCredentials
  2810. //
  2811. // Synopsis:
  2812. //
  2813. // Arguments: [RC2KeyInfo] --
  2814. // [pwszAccount] --
  2815. // [pwszDomain] --
  2816. // [pwszPassword] --
  2817. // [pSid] --
  2818. // [pcbEncryptedData] --
  2819. // [ppbEncryptedData] --
  2820. //
  2821. // Returns: HRESULT
  2822. //
  2823. // Notes: None.
  2824. //
  2825. //----------------------------------------------------------------------------
  2826. HRESULT
  2827. EncryptCredentials(
  2828. const RC2_KEY_INFO & RC2KeyInfo,
  2829. LPCWSTR pwszAccount,
  2830. LPCWSTR pwszDomain,
  2831. LPCWSTR pwszPassword,
  2832. PSID pSid,
  2833. DWORD * pcbEncryptedData,
  2834. BYTE ** ppbEncryptedData)
  2835. {
  2836. BYTE rgbBuf[RC2_BLOCKLEN];
  2837. WCHAR * pwszPasswordLocal;
  2838. DWORD cbAccount;
  2839. DWORD cbDomain;
  2840. DWORD cbPassword;
  2841. DWORD cbData = 0;
  2842. DWORD cbEncryptedData = 0;
  2843. DWORD cbPartial;
  2844. DWORD dwPadVal;
  2845. BYTE * pbData = NULL;
  2846. BYTE * pbEncryptedData = NULL;
  2847. HRESULT hr;
  2848. *pcbEncryptedData = 0;
  2849. *ppbEncryptedData = NULL;
  2850. if (pwszAccount == NULL || pwszDomain == NULL)
  2851. {
  2852. CHECK_HRESULT(E_INVALIDARG);
  2853. return(E_INVALIDARG);
  2854. }
  2855. if (pwszPassword == NULL)
  2856. {
  2857. //
  2858. // In the SAC, a NULL password is stored the same as a "" password.
  2859. // (The distinction is made per-job, in the SAI.)
  2860. //
  2861. pwszPasswordLocal = L"";
  2862. }
  2863. else
  2864. {
  2865. pwszPasswordLocal = (WCHAR *)pwszPassword;
  2866. }
  2867. cbAccount = wcslen(pwszAccount) * sizeof(WCHAR);
  2868. cbDomain = wcslen(pwszDomain) * sizeof(WCHAR);
  2869. cbPassword = wcslen(pwszPasswordLocal) * sizeof(WCHAR);
  2870. hr = MarshalData(NULL,
  2871. NULL,
  2872. Marshal,
  2873. &cbData,
  2874. &pbData,
  2875. 6,
  2876. sizeof(cbAccount),
  2877. &cbAccount,
  2878. cbAccount,
  2879. pwszAccount,
  2880. sizeof(cbDomain),
  2881. &cbDomain,
  2882. cbDomain,
  2883. pwszDomain,
  2884. sizeof(cbPassword),
  2885. &cbPassword,
  2886. cbPassword,
  2887. pwszPasswordLocal);
  2888. if (SUCCEEDED(hr))
  2889. {
  2890. //
  2891. // NB : This code exists in place of a call to CryptEncrypt to
  2892. // work around France's Crypto API restrictions. Since
  2893. // CryptEncrypt cannot be called directly, the code from
  2894. // the API to accomplish cypher block encryption is duplicated
  2895. // here.
  2896. //
  2897. //
  2898. // Calculate the number of pad bytes necessary (must be a multiple)
  2899. // of RC2_BLOCKLEN). If already a multiple of blocklen, do a full
  2900. // block of pad.
  2901. //
  2902. cbPartial = (cbData % RC2_BLOCKLEN);
  2903. dwPadVal = RC2_BLOCKLEN - cbPartial;
  2904. cbEncryptedData = cbData + dwPadVal;
  2905. //
  2906. // Allocate a buffer for the encrypted data.
  2907. //
  2908. pbEncryptedData = new BYTE[cbEncryptedData];
  2909. if (pbEncryptedData == NULL)
  2910. {
  2911. hr = E_OUTOFMEMORY;
  2912. CHECK_HRESULT(hr);
  2913. goto ErrorExit;
  2914. }
  2915. CopyMemory(pbEncryptedData, pbData, cbData);
  2916. if (dwPadVal)
  2917. {
  2918. //
  2919. // Fill the pad with a value equal to the length of the padding,
  2920. // so decrypt will know the length of the original data and as
  2921. // a simple integrity check.
  2922. //
  2923. memset(pbEncryptedData + cbData, (INT)dwPadVal, (size_t)dwPadVal);
  2924. }
  2925. //
  2926. // Perform the encryption - cypher block.
  2927. //
  2928. *pcbEncryptedData = cbEncryptedData;
  2929. *ppbEncryptedData = pbEncryptedData;
  2930. while (cbEncryptedData)
  2931. {
  2932. //
  2933. // Put the plaintext into a temporary buffer, then encrypt the
  2934. // data back into the allocated buffer.
  2935. //
  2936. CopyMemory(rgbBuf, pbEncryptedData, RC2_BLOCKLEN);
  2937. CBC(RC2,
  2938. RC2_BLOCKLEN,
  2939. pbEncryptedData,
  2940. rgbBuf,
  2941. (void *)RC2KeyInfo.rgwKeyTable,
  2942. ENCRYPT,
  2943. (BYTE *)RC2KeyInfo.rgbIV);
  2944. pbEncryptedData += RC2_BLOCKLEN;
  2945. cbEncryptedData -= RC2_BLOCKLEN;
  2946. }
  2947. }
  2948. pbEncryptedData = NULL; // For delete below.
  2949. ErrorExit:
  2950. delete pbData;
  2951. delete pbEncryptedData;
  2952. return(hr);
  2953. }
  2954. //+---------------------------------------------------------------------------
  2955. //
  2956. // Function: SkipDomainName
  2957. //
  2958. // Synopsis: Return the relative username if the username passed is in
  2959. // distinguished form. eg: return 'Joe' from 'DogFood\Joe'.
  2960. //
  2961. // Arguments: [pwszUserName] -- User name.
  2962. //
  2963. // Returns: Pointer index to/into pwszUserName.
  2964. //
  2965. // Notes: None.
  2966. //
  2967. //----------------------------------------------------------------------------
  2968. LPWSTR
  2969. SkipDomainName(LPCWSTR pwszUserName)
  2970. {
  2971. LPWSTR pwsz = (LPWSTR)pwszUserName;
  2972. while (*pwsz && *pwsz != '\\')
  2973. {
  2974. pwsz++;
  2975. }
  2976. if (*pwsz == L'\\')
  2977. {
  2978. return(++pwsz);
  2979. }
  2980. return((LPWSTR)pwszUserName);
  2981. }
  2982. //+---------------------------------------------------------------------------
  2983. //
  2984. // Function: DecryptCredentials
  2985. //
  2986. // Synopsis:
  2987. //
  2988. // Arguments: [RC2KeyInfo] --
  2989. // [cbEncryptedData] --
  2990. // [pbEncryptedData] --
  2991. // [pjc] --
  2992. // [fDecryptInPlace] --
  2993. //
  2994. // Returns: HRESULT
  2995. //
  2996. // Notes: None.
  2997. //
  2998. //----------------------------------------------------------------------------
  2999. HRESULT
  3000. DecryptCredentials(
  3001. const RC2_KEY_INFO & RC2KeyInfo,
  3002. DWORD cbEncryptedData,
  3003. BYTE * pbEncryptedData,
  3004. PJOB_CREDENTIALS pjc,
  3005. BOOL fDecryptInPlace)
  3006. {
  3007. BYTE rgbBuf[RC2_BLOCKLEN];
  3008. DWORD cbDecryptedData = cbEncryptedData;
  3009. BYTE * pbDecryptedData;
  3010. DWORD BytePos;
  3011. DWORD dwPadVal;
  3012. DWORD i;
  3013. DWORD cbAccount, cbDomain, cbPassword;
  3014. BYTE * pbAccount, * pbDomain, * pbPassword;
  3015. BOOL fIsPasswordNull = FALSE;
  3016. BYTE * pb;
  3017. HRESULT hr = S_OK;
  3018. //
  3019. // The encrypted data length *must* be a multiple of RC2_BLOCKLEN.
  3020. //
  3021. if (cbEncryptedData % RC2_BLOCKLEN)
  3022. {
  3023. CHECK_HRESULT(E_UNEXPECTED);
  3024. return(E_UNEXPECTED);
  3025. }
  3026. //
  3027. // Decrypt overwrites the encrypted data with the decrypted data.
  3028. // If fDecryptInPlace is FALSE, allocate an additional buffer for
  3029. // the decrypted bits, so the encrypted data buffer will not be
  3030. // overwritten.
  3031. //
  3032. if (!fDecryptInPlace)
  3033. {
  3034. pbDecryptedData = new BYTE[cbEncryptedData];
  3035. if (pbDecryptedData == NULL)
  3036. {
  3037. CHECK_HRESULT(E_OUTOFMEMORY);
  3038. return(E_OUTOFMEMORY);
  3039. }
  3040. CopyMemory(pbDecryptedData, pbEncryptedData, cbEncryptedData);
  3041. }
  3042. else
  3043. {
  3044. pbDecryptedData = pbEncryptedData;
  3045. }
  3046. //
  3047. // NB : This code exists in place of a call to CryptDencrypt to
  3048. // work around France's Crypto API restrictions. Since
  3049. // CryptDecrypt cannot be called directly, the code from
  3050. // the API to accomplish cypher block decryption is duplicated
  3051. // here.
  3052. //
  3053. for (BytePos = 0; (BytePos + RC2_BLOCKLEN) <= cbEncryptedData;
  3054. BytePos += RC2_BLOCKLEN)
  3055. {
  3056. //
  3057. // Use a temporary buffer to store the encrypted data.
  3058. //
  3059. CopyMemory(rgbBuf, pbDecryptedData + BytePos, RC2_BLOCKLEN);
  3060. CBC(RC2,
  3061. RC2_BLOCKLEN,
  3062. pbDecryptedData + BytePos,
  3063. rgbBuf,
  3064. (void *)RC2KeyInfo.rgwKeyTable,
  3065. DECRYPT,
  3066. (BYTE *)RC2KeyInfo.rgbIV);
  3067. }
  3068. //
  3069. // Verify the padding and remove the pad size from the data length.
  3070. // NOTE: The padding is filled with a value equal to the length
  3071. // of the padding and we are guaranteed >= 1 byte of pad.
  3072. //
  3073. // NB : If the pad is wrong, the user's buffer is hosed, because
  3074. // we've decrypted into the user's buffer -- can we re-encrypt it?
  3075. //
  3076. dwPadVal = (DWORD)*(pbDecryptedData + cbEncryptedData - 1);
  3077. if (dwPadVal == 0 || dwPadVal > (DWORD) RC2_BLOCKLEN)
  3078. {
  3079. hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
  3080. CHECK_HRESULT(hr);
  3081. goto ErrorExit;
  3082. }
  3083. //
  3084. // Make sure all the (rest of the) pad bytes are correct.
  3085. //
  3086. for (i = 1; i < dwPadVal; i++)
  3087. {
  3088. if (pbDecryptedData[cbEncryptedData - (i + 1)] != dwPadVal)
  3089. {
  3090. hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
  3091. CHECK_HRESULT(hr);
  3092. goto ErrorExit;
  3093. }
  3094. }
  3095. pb = pbDecryptedData;
  3096. //
  3097. // Have to do the following incantation since otherwise we'd likely
  3098. // fault on an unaligned fetch.
  3099. //
  3100. // Cache account name size & position.
  3101. //
  3102. CopyMemory(&cbAccount, pb, sizeof(cbAccount));
  3103. pbAccount = pb + sizeof(cbAccount);
  3104. pb = pbAccount + cbAccount;
  3105. if (((DWORD)(pb - pbDecryptedData) > cbDecryptedData) || // Check size.
  3106. (cbAccount > (MAX_USERNAME * sizeof(WCHAR))))
  3107. {
  3108. hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
  3109. CHECK_HRESULT(hr);
  3110. goto ErrorExit;
  3111. }
  3112. //
  3113. // Cache domain name size & position.
  3114. //
  3115. CopyMemory(&cbDomain, pb, sizeof(cbDomain));
  3116. pbDomain = pb + sizeof(cbDomain);
  3117. pb = pbDomain + cbDomain;
  3118. if (((DWORD)(pb - pbDecryptedData) > cbDecryptedData) || // Check size.
  3119. (cbDomain > (MAX_DOMAINNAME * sizeof(WCHAR))))
  3120. {
  3121. hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
  3122. CHECK_HRESULT(hr);
  3123. goto ErrorExit;
  3124. }
  3125. //
  3126. // Cache password size & position.
  3127. //
  3128. CopyMemory(&cbPassword, pb, sizeof(cbPassword));
  3129. pbPassword = pb + sizeof(cbPassword);
  3130. // In the IE 5 release of the Task Scheduler, a NULL password was denoted
  3131. // by a size of 0xFFFFFFFF in the SAC. The following check lets us read
  3132. // databases created by the IE 5 TS.
  3133. if (cbPassword == NULL_PASSWORD_SIZE)
  3134. {
  3135. fIsPasswordNull = TRUE;
  3136. cbPassword = 0;
  3137. }
  3138. pb = pbPassword + cbPassword;
  3139. if (((DWORD)(pb - pbDecryptedData) > cbDecryptedData) || // Check size.
  3140. (cbPassword > (MAX_PASSWORD * sizeof(WCHAR))))
  3141. {
  3142. hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
  3143. CHECK_HRESULT(hr);
  3144. goto ErrorExit;
  3145. }
  3146. //
  3147. // Finally, copy the return data.
  3148. //
  3149. CopyMemory(pjc->wszAccount, pbAccount, cbAccount);
  3150. *(WCHAR *)(((BYTE *)pjc->wszAccount) + cbAccount) = L'\0';
  3151. pjc->ccAccount = cbAccount / sizeof(WCHAR);
  3152. CopyMemory(pjc->wszDomain, pbDomain, cbDomain);
  3153. *(WCHAR *)(((BYTE *)pjc->wszDomain) + cbDomain) = L'\0';
  3154. pjc->ccDomain = cbDomain / sizeof(WCHAR);
  3155. CopyMemory(pjc->wszPassword, pbPassword, cbPassword);
  3156. *(WCHAR *)(((BYTE *)pjc->wszPassword) + cbPassword) = L'\0';
  3157. pjc->ccPassword = cbPassword / sizeof(WCHAR);
  3158. pjc->fIsPasswordNull = fIsPasswordNull;
  3159. ErrorExit:
  3160. if (!fDecryptInPlace) delete pbDecryptedData;
  3161. return(hr);
  3162. }
  3163. //+---------------------------------------------------------------------------
  3164. //
  3165. // Function: CredentialLookupAndAccessCheck
  3166. //
  3167. // Synopsis:
  3168. //
  3169. // Arguments: [hCSP] --
  3170. // [pSid] --
  3171. // [cbSAC] --
  3172. // [pbSAC] --
  3173. // [pCredentialIndex] --
  3174. // [rgbHashedSid] --
  3175. // [pcbCredential] --
  3176. // [ppbCredential] --
  3177. //
  3178. // Returns: HRESULT
  3179. //
  3180. // Notes: None.
  3181. //
  3182. //----------------------------------------------------------------------------
  3183. STATIC HRESULT
  3184. CredentialLookupAndAccessCheck(
  3185. HCRYPTPROV hCSP,
  3186. PSID pSid,
  3187. DWORD cbSAC,
  3188. BYTE * pbSAC,
  3189. DWORD * pCredentialIndex,
  3190. BYTE rgbHashedSid[],
  3191. DWORD * pcbCredential,
  3192. BYTE ** ppbCredential)
  3193. {
  3194. HRESULT hr;
  3195. // Either pSid or rgbHashedSid must be specified.
  3196. //
  3197. schAssert(rgbHashedSid != NULL && (pSid != NULL || *rgbHashedSid));
  3198. if (pSid != NULL)
  3199. {
  3200. if (!IsValidSid(pSid))
  3201. {
  3202. CHECK_HRESULT(E_UNEXPECTED);
  3203. return(E_UNEXPECTED);
  3204. }
  3205. hr = HashSid(hCSP, pSid, rgbHashedSid);
  3206. if (FAILED(hr))
  3207. {
  3208. return(hr);
  3209. }
  3210. }
  3211. //
  3212. // Find the credential in the SAC associated with the account sid. The
  3213. // hashed account sid is utilized as a SAC database key.
  3214. //
  3215. DWORD cbEncryptedData;
  3216. BYTE * pbEncryptedData;
  3217. hr = SACFindCredential(rgbHashedSid,
  3218. cbSAC,
  3219. pbSAC,
  3220. pCredentialIndex,
  3221. &cbEncryptedData,
  3222. &pbEncryptedData);
  3223. if (hr == S_OK)
  3224. {
  3225. //
  3226. // Found it. Does the caller have access to this credential?
  3227. //
  3228. BYTE * pbCredential = pbEncryptedData - HASH_DATA_SIZE;
  3229. if (CredentialAccessCheck(hCSP, pbCredential))
  3230. {
  3231. // Update out ptrs.
  3232. //
  3233. *ppbCredential = pbCredential;
  3234. CopyMemory(pcbCredential,
  3235. *ppbCredential - sizeof(*pcbCredential),
  3236. sizeof(*pcbCredential));
  3237. }
  3238. else
  3239. {
  3240. hr = HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED);
  3241. }
  3242. }
  3243. else if (hr == S_FALSE)
  3244. {
  3245. //
  3246. // Didn't find the credential.
  3247. //
  3248. hr = SCHED_E_ACCOUNT_INFORMATION_NOT_SET;
  3249. }
  3250. return(hr);
  3251. }
  3252. //+---------------------------------------------------------------------------
  3253. //
  3254. // Function: CredentialAccessCheck
  3255. //
  3256. // Synopsis: Determine if the RPC client has access to the credential
  3257. // indicated.
  3258. //
  3259. // Arguments: [hCSP] -- CSP provider handle (for use with
  3260. // Crypto API).
  3261. // [pbCredentialIdentity] -- Credential identity.
  3262. //
  3263. // Returns: TRUE -- RPC client has permission to access this credential.
  3264. // FALSE -- RPC client doesn't have credential access or an
  3265. // unexpected error occurred.
  3266. //
  3267. // Notes: ** Important **
  3268. //
  3269. // Thread impersonation is performed in this routine via
  3270. // RpcImpersonateClient; therefore, it is assumed only RPC
  3271. // threads enter it.
  3272. //
  3273. //----------------------------------------------------------------------------
  3274. STATIC BOOL
  3275. CredentialAccessCheck(
  3276. HCRYPTPROV hCSP,
  3277. BYTE * pbCredentialIdentity)
  3278. {
  3279. RPC_STATUS RpcStatus;
  3280. //
  3281. // Impersonate the caller.
  3282. //
  3283. if ((RpcStatus = RpcImpersonateClient(NULL)) != RPC_S_OK)
  3284. {
  3285. CHECK_HRESULT(RpcStatus);
  3286. return(FALSE);
  3287. }
  3288. HANDLE hToken;
  3289. BOOL bRet;
  3290. if (!OpenThreadToken(GetCurrentThread(),
  3291. TOKEN_QUERY, // Desired access.
  3292. TRUE, // Open as self.
  3293. &hToken))
  3294. {
  3295. CHECK_HRESULT(_HRESULT_FROM_WIN32(GetLastError()));
  3296. return FALSE;
  3297. }
  3298. //
  3299. // End impersonation, but don't close the token yet.
  3300. // (We must not be impersonating when we call HashSid, which is
  3301. // called by MatchThreadCallerAgainstCredential.)
  3302. //
  3303. if ((RpcStatus = RpcRevertToSelf()) != RPC_S_OK)
  3304. {
  3305. ERR_OUT("RpcRevertToSelf", RpcStatus);
  3306. schAssert(!"RpcRevertToSelf failed");
  3307. }
  3308. //
  3309. // Does the thread caller's hashed SID match the credential identity.
  3310. // If so, the caller's account is the same as that specified in the
  3311. // credentials.
  3312. //
  3313. if (!(bRet = MatchThreadCallerAgainstCredential(hCSP,
  3314. hToken,
  3315. pbCredentialIdentity)))
  3316. {
  3317. //
  3318. // Nope. Thread caller account/credential account mismatch.
  3319. // Is the caller an administrator?
  3320. //
  3321. bRet = IsThreadCallerAnAdmin(hToken);
  3322. }
  3323. CloseHandle(hToken);
  3324. return(bRet);
  3325. }
  3326. //+---------------------------------------------------------------------------
  3327. //
  3328. // Function: MatchThreadCallerAgainstCredential
  3329. //
  3330. // Synopsis: Hash the user SID of the thread indicated and compare it
  3331. // against the credential identity passed. A credential identity
  3332. // is the hashed SID of the associated account.
  3333. //
  3334. // Arguments: [hCSP] -- CSP provider handle (for use with
  3335. // Cryto API).
  3336. // [hThreadToken] -- Obtain the user SID from this
  3337. // thread.
  3338. // [pbCredentialIdentity] -- Matched credential identity.
  3339. //
  3340. // Returns: TRUE -- Match
  3341. // FALSE -- No match or an error occurred.
  3342. //
  3343. // Notes: None.
  3344. //
  3345. //----------------------------------------------------------------------------
  3346. STATIC BOOL
  3347. MatchThreadCallerAgainstCredential(
  3348. HCRYPTPROV hCSP,
  3349. HANDLE hThreadToken,
  3350. BYTE * pbCredentialIdentity)
  3351. {
  3352. BYTE rgbTokenInformation[USER_TOKEN_STACK_BUFFER_SIZE];
  3353. TOKEN_USER * pTokenUser = (TOKEN_USER *)rgbTokenInformation;
  3354. DWORD cbReturnLength;
  3355. DWORD Status = ERROR_SUCCESS;
  3356. if (!GetTokenInformation(hThreadToken,
  3357. TokenUser,
  3358. pTokenUser,
  3359. USER_TOKEN_STACK_BUFFER_SIZE,
  3360. &cbReturnLength))
  3361. {
  3362. //
  3363. // Buffer space should have been sufficient. Check if we goofed.
  3364. //
  3365. schAssert(GetLastError() != ERROR_INSUFFICIENT_BUFFER);
  3366. CHECK_HRESULT(_HRESULT_FROM_WIN32(GetLastError()));
  3367. return(FALSE);
  3368. }
  3369. //
  3370. // Hash the user's SID.
  3371. //
  3372. BYTE rgbHashedSid[HASH_DATA_SIZE] = { 0 };
  3373. if (SUCCEEDED(HashSid(hCSP, pTokenUser->User.Sid, rgbHashedSid)))
  3374. {
  3375. if (memcmp(pbCredentialIdentity, rgbHashedSid, HASH_DATA_SIZE) == 0)
  3376. {
  3377. return(TRUE);
  3378. }
  3379. else
  3380. {
  3381. CHECK_HRESULT(HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED));
  3382. }
  3383. }
  3384. return(FALSE);
  3385. }
  3386. //+---------------------------------------------------------------------------
  3387. //
  3388. // Function: ScavengeSASecurityDBase
  3389. //
  3390. // Synopsis: Enumerate the jobs folder and remove identities in the SAI
  3391. // for which no current jobs hash to. Note, SAC credentials
  3392. // are also removed if the removed identity was the last to be
  3393. // associated with it.
  3394. //
  3395. // Arguments: None.
  3396. //
  3397. // Returns: None.
  3398. //
  3399. // Notes: Should read of any job fail, for any reason, the scavenge
  3400. // task is abandoned. Reason is, if the removal process was
  3401. // to continue anyway, credentials might be removed for existent
  3402. // jobs.
  3403. //
  3404. // The service state is checked periodically as this could
  3405. // potentially be a lengthy routine time-wise. Bail as soon
  3406. // as service stop or service stop pending is detected.
  3407. //
  3408. //----------------------------------------------------------------------------
  3409. void
  3410. ScavengeSASecurityDBase(void)
  3411. {
  3412. TCHAR tszSearchPath[MAX_PATH + 1];
  3413. BYTE rgbIdentity[HASH_DATA_SIZE];
  3414. WIN32_FIND_DATA fd;
  3415. JOB_IDENTITY_SET * rgIdentitySet = NULL;
  3416. HRESULT hr = S_OK;
  3417. HANDLE hFileEnum;
  3418. DWORD dwZero = 0;
  3419. DWORD i, j;
  3420. DWORD iConcatenation;
  3421. DWORD dwRet;
  3422. DWORD dwSetCount = 0;
  3423. DWORD dwSetSubCount;
  3424. DWORD cbIdentitySetArraySize;
  3425. BYTE * pbSet;
  3426. BOOL fDirty = FALSE;
  3427. //
  3428. // Build the enumeration search path.
  3429. //
  3430. StringCchCopy(tszSearchPath, MAX_PATH + 1, g_TasksFolderInfo.ptszPath);
  3431. StringCchCat(tszSearchPath, MAX_PATH + 1, EXTENSION_WILDCARD TSZ_JOB);
  3432. //
  3433. // Initialize the enumeration.
  3434. //
  3435. if ((hFileEnum = FindFirstFile(tszSearchPath,
  3436. &fd)) == INVALID_HANDLE_VALUE)
  3437. {
  3438. //
  3439. // Either no jobs, or an error occurred.
  3440. //
  3441. dwRet = GetLastError();
  3442. if (dwRet == ERROR_FILE_NOT_FOUND)
  3443. {
  3444. EnterCriticalSection(&gcsSSCritSection);
  3445. //
  3446. // No files found. Reset SAI & SAC by writing four bytes of
  3447. // zeros into each.
  3448. //
  3449. hr = WriteSecurityDBase(sizeof(dwZero), (BYTE *)&dwZero,
  3450. sizeof(dwZero), (BYTE *)&dwZero);
  3451. CHECK_HRESULT(hr);
  3452. LeaveCriticalSection(&gcsSSCritSection);
  3453. }
  3454. else
  3455. {
  3456. CHECK_HRESULT(_HRESULT_FROM_WIN32(dwRet));
  3457. }
  3458. return;
  3459. }
  3460. DWORD cbSAI;
  3461. DWORD cbSAC;
  3462. BYTE * pbSAI = NULL;
  3463. BYTE * pbSAC = NULL;
  3464. BYTE * pbSAIEnd;
  3465. BYTE * pb;
  3466. HCRYPTPROV hCSP = NULL;
  3467. //
  3468. // Check if the service is stopping.
  3469. //
  3470. if (IsServiceStopping())
  3471. {
  3472. return;
  3473. }
  3474. EnterCriticalSection(&gcsSSCritSection);
  3475. hr = ReadSecurityDBase(&cbSAI, &pbSAI, &cbSAC, &pbSAC);
  3476. if (FAILED(hr))
  3477. {
  3478. CHECK_HRESULT(hr);
  3479. goto ErrorExit;
  3480. }
  3481. if (cbSAI <= SAI_HEADER_SIZE)
  3482. {
  3483. //
  3484. // Database empty.
  3485. //
  3486. hr = S_OK;
  3487. goto ErrorExit;
  3488. }
  3489. //
  3490. // Some background first. The SAI consists of an array of arrays. The
  3491. // first dimension represents the set of job identities per credential
  3492. // in the SAC. SAI/SAC indices are associative in this case. The set of
  3493. // job identities at SAI row[n] correspond to the credential at SAC
  3494. // row[n].
  3495. //
  3496. // We need to construct an SAI pending deletion data structure. It will
  3497. // consist of an array of JOB_IDENTITY_SET structures, in which each
  3498. // structure refers to an array of pointers to job identities in the
  3499. // SAI (literally indexing the SAI).
  3500. //
  3501. // Once the data structure is built and initialized, we'll enumerate the
  3502. // jobs in the local tasks folder. For each job found, the corresponding
  3503. // job identity pointer in the job identity set array will be set to NULL.
  3504. // Upon completion of the enumeration, the non-NULL job identity ptr
  3505. // entries within the job identity set array refer to non-existent jobs.
  3506. // The job identitites these entries refer to are removed from the SAI,
  3507. // and the associated credential in the SAC, if there are no longer
  3508. // entries in the SAI associated with it.
  3509. //
  3510. // First, allocate the array.
  3511. //
  3512. pb = pbSAI + USN_SIZE;
  3513. CopyMemory(&dwSetCount, pb, sizeof(dwSetCount));
  3514. pb += sizeof(dwSetCount);
  3515. cbIdentitySetArraySize = dwSetCount * sizeof(JOB_IDENTITY_SET);
  3516. rgIdentitySet = (JOB_IDENTITY_SET *)LocalAlloc(LMEM_FIXED,
  3517. cbIdentitySetArraySize);
  3518. if (rgIdentitySet == NULL)
  3519. {
  3520. hr = E_OUTOFMEMORY;
  3521. CHECK_HRESULT(hr);
  3522. goto ErrorExit;
  3523. }
  3524. SecureZeroMemory(rgIdentitySet, cbIdentitySetArraySize);
  3525. pb = pbSAI + SAI_HEADER_SIZE;
  3526. pbSAIEnd = pbSAI + cbSAI;
  3527. //
  3528. // Check if the service is stopping.
  3529. //
  3530. if (IsServiceStopping())
  3531. {
  3532. hr = S_OK;
  3533. goto ErrorExit;
  3534. }
  3535. //
  3536. // Now allocate, intialize individual identity sets.
  3537. //
  3538. for (i = 0; i < dwSetCount; i++)
  3539. {
  3540. //
  3541. // Check boundary.
  3542. //
  3543. if ((pb + sizeof(dwSetSubCount)) > pbSAIEnd)
  3544. {
  3545. ASSERT_SECURITY_DBASE_CORRUPT();
  3546. hr = SCHED_E_ACCOUNT_DBASE_CORRUPT;
  3547. goto ErrorExit;
  3548. }
  3549. CopyMemory(&dwSetSubCount, pb, sizeof(dwSetSubCount));
  3550. pb += sizeof(dwSetSubCount);
  3551. BYTE ** rgpbIdentity = (BYTE **)LocalAlloc(
  3552. LMEM_FIXED,
  3553. sizeof(BYTE *) * dwSetSubCount);
  3554. if (rgpbIdentity == NULL)
  3555. {
  3556. hr = E_OUTOFMEMORY;
  3557. CHECK_HRESULT(hr);
  3558. goto ErrorExit;
  3559. }
  3560. rgIdentitySet[i].pbSetStart = pb;
  3561. rgIdentitySet[i].dwSetSubCount = dwSetSubCount;
  3562. rgIdentitySet[i].rgpbIdentity = rgpbIdentity;
  3563. for (j = 0; j < dwSetSubCount; j++)
  3564. {
  3565. rgpbIdentity[j] = pb;
  3566. pb += HASH_DATA_SIZE;
  3567. if (pb > pbSAIEnd)
  3568. {
  3569. ASSERT_SECURITY_DBASE_CORRUPT();
  3570. hr = SCHED_E_ACCOUNT_DBASE_CORRUPT;
  3571. goto ErrorExit;
  3572. }
  3573. }
  3574. }
  3575. //
  3576. // Check if the service is stopping.
  3577. //
  3578. if (IsServiceStopping())
  3579. {
  3580. hr = S_OK;
  3581. goto ErrorExit;
  3582. }
  3583. //
  3584. // Enumerate job objects in the task's folder directory. Set
  3585. // corresponding job identity ptrs in the job identity set array to
  3586. // NULL for existent jobs.
  3587. //
  3588. //
  3589. // First, obtain a provider handle to the CSP (for use with Crypto API).
  3590. //
  3591. hr = GetCSPHandle(&hCSP);
  3592. if (FAILED(hr))
  3593. {
  3594. goto ErrorExit;
  3595. }
  3596. //
  3597. // Must concatenate the filename returned from the enumeration onto
  3598. // the folder path.
  3599. //
  3600. StringCchCopy(tszSearchPath, MAX_PATH + 1, g_TasksFolderInfo.ptszPath);
  3601. iConcatenation = lstrlenW(g_TasksFolderInfo.ptszPath);
  3602. tszSearchPath[iConcatenation++] = L'\\';
  3603. for (;;)
  3604. {
  3605. //
  3606. // Append the filename to the folder path.
  3607. //
  3608. tszSearchPath[iConcatenation] = L'\0';
  3609. StringCchCat(tszSearchPath, MAX_PATH + 1, fd.cFileName);
  3610. //
  3611. // Hash the job into a unique identity.
  3612. //
  3613. hr = HashJobIdentity(hCSP, tszSearchPath, rgbIdentity);
  3614. if (FAILED(hr))
  3615. {
  3616. //
  3617. // Must bail if the hash fails. If this is ignored, one, or more,
  3618. // identities may be removed for existent jobs - not good.
  3619. //
  3620. // TBD : Log error.
  3621. //
  3622. goto ErrorExit;
  3623. }
  3624. //
  3625. // Does an identity exist in the SAI for this job? If so, NULL out
  3626. // the corresponding entry in the job identity set array.
  3627. //
  3628. DWORD CredentialIndex;
  3629. BYTE * pbIdentity;
  3630. hr = SAIFindIdentity(rgbIdentity,
  3631. cbSAI,
  3632. pbSAI,
  3633. &CredentialIndex,
  3634. NULL,
  3635. &pbIdentity,
  3636. NULL,
  3637. &pbSet);
  3638. if (FAILED(hr))
  3639. {
  3640. CHECK_HRESULT(hr);
  3641. goto ErrorExit;
  3642. }
  3643. if (pbIdentity != NULL)
  3644. {
  3645. for (i = 0; i < dwSetCount; i++)
  3646. {
  3647. for (j = 0; j < rgIdentitySet[i].dwSetSubCount; j++)
  3648. {
  3649. if (pbIdentity == rgIdentitySet[i].rgpbIdentity[j])
  3650. {
  3651. rgIdentitySet[i].rgpbIdentity[j] = NULL;
  3652. break;
  3653. }
  3654. }
  3655. }
  3656. }
  3657. if (!FindNextFile(hFileEnum, &fd))
  3658. {
  3659. dwRet = GetLastError();
  3660. if (dwRet == ERROR_NO_MORE_FILES)
  3661. {
  3662. break;
  3663. }
  3664. else
  3665. {
  3666. hr = _HRESULT_FROM_WIN32(GetLastError());
  3667. CHECK_HRESULT(hr);
  3668. goto ErrorExit;
  3669. }
  3670. }
  3671. }
  3672. //
  3673. // Check if the service is stopping.
  3674. //
  3675. if (IsServiceStopping())
  3676. {
  3677. hr = S_OK;
  3678. goto ErrorExit;
  3679. }
  3680. //
  3681. // Non-NULL entries in the identity set array refer to job identities in
  3682. // the SAI to be removed. Mark them for removal.
  3683. //
  3684. for (i = 0; i < dwSetCount; i++)
  3685. {
  3686. if (rgIdentitySet[i].rgpbIdentity != NULL)
  3687. {
  3688. dwSetSubCount = rgIdentitySet[i].dwSetSubCount;
  3689. for (j = 0; j < dwSetSubCount; j++)
  3690. {
  3691. if (rgIdentitySet[i].rgpbIdentity[j] != NULL)
  3692. {
  3693. MARK_DELETED_ENTRY(rgIdentitySet[i].rgpbIdentity[j]);
  3694. rgIdentitySet[i].dwSetSubCount--;
  3695. fDirty = TRUE;
  3696. if (rgIdentitySet[i].dwSetSubCount == 0)
  3697. {
  3698. //
  3699. // Last identity in set. Mark associated SAC
  3700. // credential for removal also.
  3701. //
  3702. DWORD cbCredential;
  3703. BYTE * pbCredential;
  3704. hr = SACIndexCredential(i,
  3705. cbSAC,
  3706. pbSAC,
  3707. &cbCredential,
  3708. &pbCredential);
  3709. if (hr == S_FALSE)
  3710. {
  3711. //
  3712. // This should *never* happen. Consider the
  3713. // database corrupt if so.
  3714. //
  3715. ASSERT_SECURITY_DBASE_CORRUPT();
  3716. hr = SCHED_E_ACCOUNT_DBASE_CORRUPT;
  3717. goto ErrorExit;
  3718. }
  3719. else if (FAILED(hr))
  3720. {
  3721. CHECK_HRESULT(hr);
  3722. goto ErrorExit;
  3723. }
  3724. else
  3725. {
  3726. MARK_DELETED_ENTRY(pbCredential);
  3727. }
  3728. }
  3729. }
  3730. }
  3731. }
  3732. }
  3733. //
  3734. // Check if the service is stopping.
  3735. //
  3736. if (IsServiceStopping())
  3737. {
  3738. hr = S_OK;
  3739. goto ErrorExit;
  3740. }
  3741. //
  3742. // Removed entries marked for deletion.
  3743. //
  3744. if (fDirty)
  3745. {
  3746. hr = SAICoalesceDeletedEntries(&cbSAI, &pbSAI);
  3747. CHECK_HRESULT(hr);
  3748. if (SUCCEEDED(hr))
  3749. {
  3750. hr = SACCoalesceDeletedEntries(&cbSAC, &pbSAC);
  3751. CHECK_HRESULT(hr);
  3752. }
  3753. if (FAILED(hr))
  3754. {
  3755. goto ErrorExit;
  3756. }
  3757. //
  3758. // Finally, persist the changes made to the SAI & SAC.
  3759. //
  3760. hr = WriteSecurityDBase(cbSAI, pbSAI, cbSAC, pbSAC);
  3761. CHECK_HRESULT(hr);
  3762. }
  3763. ErrorExit:
  3764. //
  3765. // Deallocate data structures allocated above.
  3766. //
  3767. for (i = 0; i < dwSetCount; i++)
  3768. {
  3769. if (rgIdentitySet[i].rgpbIdentity != NULL)
  3770. {
  3771. LocalFree(rgIdentitySet[i].rgpbIdentity);
  3772. }
  3773. }
  3774. if (rgIdentitySet != NULL) LocalFree(rgIdentitySet);
  3775. if (pbSAI != NULL) LocalFree(pbSAI);
  3776. if (pbSAC != NULL) LocalFree(pbSAC);
  3777. if (hFileEnum != INVALID_HANDLE_VALUE) FindClose(hFileEnum);
  3778. if (hCSP != NULL) CloseCSPHandle(hCSP);
  3779. //
  3780. // Log an error & rest the SA security dbases SAI & SAC if corruption
  3781. // is detected.
  3782. //
  3783. if (hr == SCHED_E_ACCOUNT_DBASE_CORRUPT)
  3784. {
  3785. //
  3786. // Log an error.
  3787. //
  3788. LogServiceError(IERR_SECURITY_DBASE_CORRUPTION, 0,
  3789. IDS_HELP_HINT_DBASE_CORRUPT);
  3790. //
  3791. // Reset SAI & SAC by writing four bytes of zeros into each.
  3792. // Ignore the return code. No recourse if this fails.
  3793. //
  3794. DWORD dwZero = 0;
  3795. WriteSecurityDBase(sizeof(dwZero), (BYTE *)&dwZero, sizeof(dwZero),
  3796. (BYTE *)&dwZero);
  3797. }
  3798. LeaveCriticalSection(&gcsSSCritSection);
  3799. }
  3800. //+---------------------------------------------------------------------------
  3801. //
  3802. // Function: SchedUPNToAccountName
  3803. //
  3804. // Synopsis: Converts a UPN to an Account Name
  3805. //
  3806. // Arguments: lpUPN - The UPN
  3807. // ppAccountName - Pointer to the location to create/copy the account name
  3808. //
  3809. // Returns: NO_ERROR - Success (ppAccountName contains the converted UPN)
  3810. // Any other Win32 error - error at some stage of conversion
  3811. //
  3812. //----------------------------------------------------------------------------
  3813. DWORD
  3814. SchedUPNToAccountName(
  3815. IN LPCWSTR lpUPN,
  3816. OUT LPWSTR *ppAccountName
  3817. )
  3818. {
  3819. DWORD dwError;
  3820. HANDLE hDS;
  3821. PDS_NAME_RESULT pdsResult;
  3822. schAssert(ppAccountName != NULL);
  3823. schDebugOut((DEB_TRACE, "SchedUPNToAccountName: Converting \"%ws\"\n", lpUPN));
  3824. //
  3825. // Get a binding handle to the DS
  3826. //
  3827. dwError = DsBind(NULL, NULL, &hDS);
  3828. if (dwError != NO_ERROR)
  3829. {
  3830. schDebugOut((DEB_ERROR, "SchedUPNToAccountName: DsBind failed %d\n", dwError));
  3831. return dwError;
  3832. }
  3833. dwError = DsCrackNames(hDS, // Handle to the DS
  3834. DS_NAME_NO_FLAGS, // No parsing flags
  3835. DS_USER_PRINCIPAL_NAME, // We have a UPN
  3836. DS_NT4_ACCOUNT_NAME, // We want Domain\User
  3837. 1, // Number of names to crack
  3838. &lpUPN, // Array of name(s)
  3839. &pdsResult); // Filled in by API
  3840. if (dwError != NO_ERROR)
  3841. {
  3842. schDebugOut((DEB_ERROR, "SchedUPNToAccountName: DsCrackNames failed %d\n", dwError));
  3843. DsUnBind(&hDS);
  3844. return dwError;
  3845. }
  3846. schAssert(pdsResult->cItems == 1);
  3847. schAssert(pdsResult->rItems != NULL);
  3848. if (pdsResult->rItems[0].status == DS_NAME_ERROR_DOMAIN_ONLY)
  3849. {
  3850. //
  3851. // Couldn't crack the name but we got the name of
  3852. // the domain where it is -- let's try it
  3853. //
  3854. DsUnBind(&hDS);
  3855. schAssert(pdsResult->rItems[0].pDomain != NULL);
  3856. schDebugOut((DEB_TRACE, "Retrying DsBind on domain %ws\n", pdsResult->rItems[0].pDomain));
  3857. dwError = DsBind(NULL, pdsResult->rItems[0].pDomain, &hDS);
  3858. //
  3859. // Free up the structure holding the old info
  3860. //
  3861. DsFreeNameResult(pdsResult);
  3862. if (dwError != NO_ERROR)
  3863. {
  3864. schDebugOut((DEB_ERROR, "SchedUPNToAccountName: DsBind #2 failed %d\n", dwError));
  3865. return dwError;
  3866. }
  3867. dwError = DsCrackNames(hDS, // Handle to the DS
  3868. DS_NAME_NO_FLAGS, // No parsing flags
  3869. DS_USER_PRINCIPAL_NAME, // We have a UPN
  3870. DS_NT4_ACCOUNT_NAME, // We want Domain\User
  3871. 1, // Number of names to crack
  3872. &lpUPN, // Array of name(s)
  3873. &pdsResult); // Filled in by API
  3874. if (dwError != NO_ERROR)
  3875. {
  3876. schDebugOut((DEB_ERROR, "SchedUPNToAccountName: DsCrackNames #2 failed %d\n", dwError));
  3877. DsUnBind(&hDS);
  3878. return dwError;
  3879. }
  3880. schAssert(pdsResult->cItems == 1);
  3881. schAssert(pdsResult->rItems != NULL);
  3882. }
  3883. if (pdsResult->rItems[0].status != DS_NAME_NO_ERROR)
  3884. {
  3885. schDebugOut((DEB_ERROR, "SchedUPNToAccountName: DsCrackNames failure (status %#x)\n", pdsResult->rItems[0].status));
  3886. //
  3887. // DS errors don't map to Win32 errors -- this is the best we can do
  3888. //
  3889. dwError = SCHED_E_ACCOUNT_NAME_NOT_FOUND;
  3890. }
  3891. else
  3892. {
  3893. schDebugOut((DEB_TRACE, "SchedUPNToAccountName: Got \"%ws\"\n",
  3894. pdsResult->rItems[0].pName));
  3895. size_t cchBuff = wcslen(pdsResult->rItems[0].pName) + 1;
  3896. *ppAccountName = new WCHAR[cchBuff];
  3897. if (*ppAccountName != NULL)
  3898. {
  3899. StringCchCopy(*ppAccountName, cchBuff, pdsResult->rItems[0].pName);
  3900. }
  3901. else
  3902. {
  3903. dwError = GetLastError();
  3904. schDebugOut((DEB_ERROR, "SchedUPNToAccountName: LocalAlloc failed %d\n", dwError));
  3905. }
  3906. }
  3907. DsUnBind(&hDS);
  3908. DsFreeNameResult(pdsResult);
  3909. return dwError;
  3910. }
  3911. //+---------------------------------------------------------------------------
  3912. //
  3913. // Function: LookupAccountNameWrap
  3914. //
  3915. // Synopsis: BUGBUG This is a workaround for bug 254102 - LookupAccountName
  3916. // doesn't work when the DC can't be reached, even for the
  3917. // currently logged-on user, and even though LookupAccountSid
  3918. // does work. Remove this function when that bug is fixed.
  3919. //
  3920. // Arguments: Same as LookupAccountName - but cbSid and cbReferencedDomainName
  3921. // are assumed to be large enough, and peUse is ignored.
  3922. //
  3923. // Returns: Same as LookupAccountName.
  3924. //
  3925. //----------------------------------------------------------------------------
  3926. BOOL
  3927. LookupAccountNameWrap(
  3928. LPCTSTR lpSystemName, // address of string for system name
  3929. LPCTSTR lpAccountName, // address of string for account name
  3930. PSID Sid, // address of security identifier
  3931. LPDWORD cbSid, // address of size of security identifier
  3932. LPTSTR ReferencedDomainName,
  3933. // address of string for referenced domain
  3934. LPDWORD cbReferencedDomainName,
  3935. // address of size of domain string
  3936. PSID_NAME_USE peUse // address of SID-type indicator
  3937. )
  3938. {
  3939. //
  3940. // See if the account name matches the account name we cached
  3941. //
  3942. EnterCriticalSection(gUserLogonInfo.CritSection);
  3943. if (gUserLogonInfo.DomainUserName != NULL &&
  3944. lstrcmpi(gUserLogonInfo.DomainUserName, lpAccountName) == 0)
  3945. {
  3946. //
  3947. // The names match. Return the cached SID.
  3948. //
  3949. schDebugOut((DEB_TRACE, "Using cached SID for user \"%ws\"\n", lpAccountName));
  3950. if (CopySid(*cbSid, Sid, gUserLogonInfo.Sid))
  3951. {
  3952. LeaveCriticalSection(gUserLogonInfo.CritSection);
  3953. //
  3954. // Copy the ReferencedDomainName from the account name
  3955. //
  3956. PCWCH pchSlash = wcschr(lpAccountName, L'\\');
  3957. schAssert(pchSlash != NULL);
  3958. DWORD DomainLen = (DWORD)(pchSlash - lpAccountName);
  3959. schAssert(DomainLen+1 <= *cbReferencedDomainName);
  3960. wcsncpy(ReferencedDomainName, lpAccountName, DomainLen);
  3961. ReferencedDomainName[DomainLen] = L'\0';
  3962. return TRUE;
  3963. }
  3964. else
  3965. {
  3966. schAssert(0);
  3967. CHECK_HRESULT(HRESULT_FROM_WIN32(GetLastError()));
  3968. }
  3969. }
  3970. LeaveCriticalSection(gUserLogonInfo.CritSection);
  3971. return LookupAccountName(
  3972. lpSystemName,
  3973. lpAccountName,
  3974. Sid,
  3975. cbSid,
  3976. ReferencedDomainName,
  3977. cbReferencedDomainName,
  3978. peUse
  3979. );
  3980. }
  3981. //+----------------------------------------------------------------------------
  3982. //
  3983. // Member: ComputeJobSignature
  3984. //
  3985. // Synopsis: Creates a signature for the job file
  3986. //
  3987. // Arguments: [pwszFileName] - name of job file
  3988. // [pSignature] - block in which to store the signature. Must
  3989. // be at least SIGNATURE_SIZE bytes long.
  3990. // [dwHashMethod - dword value indicating which hash method to use;
  3991. // Default if not specified is the latest method.
  3992. //
  3993. // Returns: HRESULT
  3994. //
  3995. // Notes: The job must have been saved to disk before calling this
  3996. // function.
  3997. //
  3998. //-----------------------------------------------------------------------------
  3999. HRESULT
  4000. ComputeJobSignature(
  4001. LPCWSTR pwszFileName,
  4002. LPBYTE pbSignature,
  4003. DWORD dwHashMethod /* = 1 */
  4004. )
  4005. {
  4006. HCRYPTPROV hCSP;
  4007. HRESULT hr = GetCSPHandle(&hCSP);
  4008. if (SUCCEEDED(hr))
  4009. {
  4010. hr = HashJobIdentity(hCSP, pwszFileName, pbSignature, dwHashMethod);
  4011. CloseCSPHandle(hCSP);
  4012. }
  4013. return hr;
  4014. }
  4015. //+----------------------------------------------------------------------------
  4016. //
  4017. // Member: CJob::Sign
  4018. //
  4019. // Synopsis: Computes and sets the job's signature
  4020. //
  4021. // Arguments: None
  4022. //
  4023. // Notes: The job must have been written to disk before calling this method
  4024. //
  4025. //-----------------------------------------------------------------------------
  4026. HRESULT
  4027. CJob::Sign(
  4028. VOID
  4029. )
  4030. {
  4031. BYTE rgbSignature[SIGNATURE_SIZE];
  4032. HRESULT hr = ComputeJobSignature(m_ptszFileName, rgbSignature);
  4033. if (FAILED(hr))
  4034. {
  4035. CHECK_HRESULT(hr);
  4036. return hr;
  4037. }
  4038. hr = _SetSignature(rgbSignature);
  4039. return hr;
  4040. }
  4041. //+----------------------------------------------------------------------------
  4042. //
  4043. // Member: CJob::VerifySignature
  4044. //
  4045. // Synopsis: Compares the job file's hash to the one stored in the file
  4046. //
  4047. // Arguments: None
  4048. //
  4049. // Notes: The job must have been written to disk before calling this method
  4050. //
  4051. //-----------------------------------------------------------------------------
  4052. BOOL
  4053. CJob::VerifySignature(
  4054. DWORD dwHashMethod /* = 1 */
  4055. ) const
  4056. {
  4057. if (m_pbSignature == NULL)
  4058. {
  4059. CHECK_HRESULT(SCHED_E_ACCOUNT_INFORMATION_NOT_SET);
  4060. return FALSE;
  4061. }
  4062. BYTE rgbSignature[SIGNATURE_SIZE];
  4063. HRESULT hr = ComputeJobSignature(m_ptszFileName, rgbSignature, dwHashMethod);
  4064. if (FAILED(hr))
  4065. {
  4066. CHECK_HRESULT(hr);
  4067. return FALSE;
  4068. }
  4069. if (memcmp(m_pbSignature, rgbSignature, SIGNATURE_SIZE) != 0)
  4070. {
  4071. CHECK_HRESULT(E_ACCESSDENIED);
  4072. return(FALSE);
  4073. }
  4074. return TRUE;
  4075. }
  4076. //+----------------------------------------------------------------------------
  4077. //
  4078. // Member: CSchedule::AddAtJobWithHash
  4079. //
  4080. // Synopsis: create a downlevel job
  4081. //
  4082. // Arguments: [At] - reference to an AT_INFO struct
  4083. // [pID] - returns the new ID (optional, can be NULL)
  4084. //
  4085. // Returns: HRESULTS
  4086. //
  4087. // Notes: This method is not exposed to external clients, thus it is not
  4088. // part of a public interface.
  4089. //-----------------------------------------------------------------------------
  4090. STDMETHODIMP
  4091. CSchedule::AddAtJobWithHash(const AT_INFO &At, DWORD * pID)
  4092. {
  4093. TRACE(CSchedule, AddAtJob);
  4094. HRESULT hr = S_OK;
  4095. CJob *pJob;
  4096. WCHAR wszName[MAX_PATH + 1];
  4097. WCHAR wszID[SCH_SMBUF_LEN];
  4098. hr = AddAtJobCommon(At, pID, &pJob, wszName, MAX_PATH + 1, wszID);
  4099. if (FAILED(hr))
  4100. {
  4101. ERR_OUT("AddAtJobWithHash: AddAtJobCommon", hr);
  4102. return hr;
  4103. }
  4104. hr = AuditATJob(At, wszName);
  4105. if (FAILED(hr))
  4106. {
  4107. ERR_OUT("AddAtJobWithHash: AuditATJob", hr);
  4108. }
  4109. //
  4110. // Now get a signature for the job file and add it to the job object
  4111. //
  4112. hr = pJob->Sign();
  4113. if (FAILED(hr))
  4114. {
  4115. ERR_OUT("AddAtJobWithHash: Sign", hr);
  4116. pJob->Release();
  4117. return hr;
  4118. }
  4119. hr = pJob->SaveWithRetry(pJob->GetFileName(),
  4120. FALSE,
  4121. SAVEP_VARIABLE_LENGTH_DATA |
  4122. SAVEP_PRESERVE_NET_SCHEDULE);
  4123. //
  4124. // Free the job object.
  4125. //
  4126. pJob->Release();
  4127. //
  4128. // Return the new job's ID and increment the ID counter
  4129. //
  4130. if (pID != NULL)
  4131. {
  4132. *pID = m_dwNextID;
  4133. }
  4134. hr = IncrementAndSaveID();
  4135. return hr;
  4136. }