Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4693 lines
112 KiB

  1. //+-------------------------------------------------------------------------n-
  2. //
  3. // Microsoft Windows
  4. // Copyright (C) Microsoft Corporation, 1996 - 1999
  5. //
  6. // File: crl.cpp
  7. //
  8. // Contents: Cert Server CRL processing
  9. //
  10. //---------------------------------------------------------------------------
  11. #include <pch.cpp>
  12. #pragma hdrstop
  13. #include <stdio.h>
  14. #include <esent.h>
  15. #include "cscom.h"
  16. #include "csprop.h"
  17. #include "dbtable.h"
  18. #include "resource.h"
  19. #include "elog.h"
  20. #include "certlog.h"
  21. #include <winldap.h>
  22. #include "csldap.h"
  23. #include "cainfop.h"
  24. #define __dwFILE__ __dwFILE_CERTSRV_CRL_CPP__
  25. HANDLE g_hCRLManualPublishEvent = NULL;
  26. FILETIME g_ftCRLNextPublish;
  27. FILETIME g_ftDeltaCRLNextPublish;
  28. BOOL g_fCRLPublishDisabled = FALSE; // manual publishing always allowed
  29. BOOL g_fDeltaCRLPublishDisabled = FALSE; // controls manual publishing, too
  30. DWORD g_dwCRLFlags = CRLF_DELETE_EXPIRED_CRLS;
  31. LDAP *g_pld = NULL;
  32. typedef struct _CSMEMBLOCK
  33. {
  34. struct _CSMEMBLOCK *pNext;
  35. BYTE *pbFree;
  36. DWORD cbFree;
  37. } CSMEMBLOCK;
  38. #define CBMEMBLOCK 4096
  39. typedef struct _CSCRLELEMENT
  40. {
  41. USHORT usRevocationReason;
  42. USHORT uscbSerialNumber;
  43. BYTE *pbSerialNumber;
  44. FILETIME ftRevocationDate;
  45. } CSCRLELEMENT;
  46. // size the structure just under CBMEMBLOCK to keep it from being just over
  47. // a page size.
  48. #define CCRLELEMENT ((CBMEMBLOCK - 2 * sizeof(DWORD)) / sizeof(CSCRLELEMENT))
  49. typedef struct _CSCRLBLOCK
  50. {
  51. struct _CSCRLBLOCK *pNext;
  52. DWORD cCRLElement;
  53. CSCRLELEMENT aCRLElement[CCRLELEMENT];
  54. } CSCRLBLOCK;
  55. typedef struct _CSCRLREASON
  56. {
  57. struct _CSCRLREASON *pNext;
  58. DWORD RevocationReason;
  59. CERT_EXTENSION ExtReason;
  60. } CSCRLREASON;
  61. typedef struct _CSCRLPERIOD
  62. {
  63. LONG lCRLPeriodCount;
  64. ENUM_PERIOD enumCRLPeriod;
  65. DWORD dwCRLOverlapMinutes;
  66. } CSCRLPERIOD;
  67. #ifdef DBG_CERTSRV_DEBUG_PRINT
  68. # define DPT_DATE 1
  69. # define DPT_DELTA 2
  70. # define DPT_DELTASEC 3
  71. # define DPT_DELTAMS 4
  72. # define DBGPRINTTIME(pfDelta, pszName, Type, ft) \
  73. DbgPrintTime((pfDelta), (pszName), __LINE__, (Type), (ft))
  74. VOID
  75. DbgPrintTime(
  76. OPTIONAL IN BOOL const *pfDelta,
  77. IN char const *pszName,
  78. IN DWORD Line,
  79. IN DWORD Type,
  80. IN FILETIME ft)
  81. {
  82. HRESULT hr;
  83. WCHAR *pwszTime = NULL;
  84. WCHAR awc[1];
  85. LLFILETIME llft;
  86. llft.ft = ft;
  87. if (Type == DPT_DATE)
  88. {
  89. if (0 != llft.ll)
  90. {
  91. hr = myGMTFileTimeToWszLocalTime(&ft, TRUE, &pwszTime);
  92. _PrintIfError(hr, "myGMTFileTimeToWszLocalTime");
  93. }
  94. }
  95. else
  96. {
  97. if (DPT_DELTAMS == Type)
  98. {
  99. llft.ll /= 1000; // milliseconds to seconds
  100. Type = DPT_DELTASEC;
  101. }
  102. if (DPT_DELTASEC == Type)
  103. {
  104. llft.ll *= CVT_BASE; // seconds to FILETIME period
  105. }
  106. llft.ll = -llft.ll; // FILETIME Period must be negative
  107. if (0 != llft.ll)
  108. {
  109. hr = myFileTimePeriodToWszTimePeriod(
  110. &llft.ft,
  111. TRUE, // fExact
  112. &pwszTime);
  113. _PrintIfError(hr, "myFileTimePeriodToWszTimePeriod");
  114. }
  115. }
  116. if (NULL == pwszTime)
  117. {
  118. awc[0] = L'\0';
  119. pwszTime = awc;
  120. }
  121. DBGPRINT((
  122. DBG_SS_CERTSRVI,
  123. "%hs(%d):%hs time(%hs): %lx:%08lx %ws\n",
  124. "crl.cpp",
  125. Line,
  126. NULL == pfDelta? "" : (*pfDelta? " Delta CRL" : " Base CRL"),
  127. pszName,
  128. ft.dwHighDateTime,
  129. ft.dwLowDateTime,
  130. pwszTime));
  131. //error:
  132. if (NULL != pwszTime && awc != pwszTime)
  133. {
  134. LocalFree(pwszTime);
  135. }
  136. }
  137. VOID
  138. CertSrvDbgPrintTime(
  139. IN char const *pszDesc,
  140. IN FILETIME const *pftGMT)
  141. {
  142. HRESULT hr;
  143. WCHAR *pwszTime = NULL;
  144. WCHAR awc[1];
  145. hr = myGMTFileTimeToWszLocalTime(pftGMT, TRUE, &pwszTime);
  146. _PrintIfError(hr, "myGMTFileTimeToWszLocalTime");
  147. if (S_OK != hr)
  148. {
  149. awc[0] = L'\0';
  150. pwszTime = awc;
  151. }
  152. DBGPRINT((DBG_SS_CERTSRV, "%hs: %ws\n", pszDesc, pwszTime));
  153. //error:
  154. if (NULL != pwszTime && awc != pwszTime)
  155. {
  156. LocalFree(pwszTime);
  157. }
  158. }
  159. #else // DBG_CERTSRV_DEBUG_PRINT
  160. # define DBGPRINTTIME(pfDelta, pszName, Type, ft)
  161. #endif // DBG_CERTSRV_DEBUG_PRINT
  162. HRESULT
  163. crlMemBlockAlloc(
  164. IN OUT CSMEMBLOCK **ppBlock,
  165. IN DWORD cb,
  166. OUT BYTE **ppb)
  167. {
  168. HRESULT hr;
  169. CSMEMBLOCK *pBlock = *ppBlock;
  170. *ppb = NULL;
  171. cb = POINTERROUND(cb);
  172. if (NULL == pBlock || cb > pBlock->cbFree)
  173. {
  174. pBlock = (CSMEMBLOCK *) LocalAlloc(LMEM_FIXED, CBMEMBLOCK);
  175. if (NULL == pBlock)
  176. {
  177. hr = E_OUTOFMEMORY;
  178. _JumpError(hr, error, "LocalAlloc");
  179. }
  180. pBlock->pNext = *ppBlock;
  181. pBlock->pbFree = (BYTE *) Add2Ptr(pBlock, sizeof(CSMEMBLOCK));
  182. pBlock->cbFree = CBMEMBLOCK - sizeof(CSMEMBLOCK);
  183. *ppBlock = pBlock;
  184. }
  185. CSASSERT(cb <= pBlock->cbFree);
  186. *ppb = pBlock->pbFree;
  187. pBlock->pbFree += cb;
  188. pBlock->cbFree -= cb;
  189. hr = S_OK;
  190. error:
  191. return(hr);
  192. }
  193. VOID
  194. crlBlockListFree(
  195. IN OUT CSMEMBLOCK *pBlock)
  196. {
  197. CSMEMBLOCK *pBlockNext;
  198. while (NULL != pBlock)
  199. {
  200. pBlockNext = pBlock->pNext;
  201. LocalFree(pBlock);
  202. pBlock = pBlockNext;
  203. }
  204. }
  205. HRESULT
  206. crlElementAlloc(
  207. IN OUT CSCRLBLOCK **ppBlock,
  208. OUT CSCRLELEMENT **ppCRLElement)
  209. {
  210. HRESULT hr;
  211. CSCRLBLOCK *pBlock = *ppBlock;
  212. *ppCRLElement = NULL;
  213. if (NULL == pBlock ||
  214. ARRAYSIZE(pBlock->aCRLElement) <= pBlock->cCRLElement)
  215. {
  216. pBlock = (CSCRLBLOCK *) LocalAlloc(LMEM_FIXED, sizeof(*pBlock));
  217. if (NULL == pBlock)
  218. {
  219. hr = E_OUTOFMEMORY;
  220. _JumpError(hr, error, "LocalAlloc");
  221. }
  222. pBlock->pNext = *ppBlock;
  223. pBlock->cCRLElement = 0;
  224. *ppBlock = pBlock;
  225. }
  226. CSASSERT(ARRAYSIZE(pBlock->aCRLElement) > pBlock->cCRLElement);
  227. *ppCRLElement = &pBlock->aCRLElement[pBlock->cCRLElement++];
  228. hr = S_OK;
  229. error:
  230. return(hr);
  231. }
  232. VOID
  233. crlFreeCRLArray(
  234. IN OUT VOID *pvBlockSerial,
  235. IN OUT CRL_ENTRY *paCRL)
  236. {
  237. crlBlockListFree((CSMEMBLOCK *) pvBlockSerial);
  238. if (NULL != paCRL)
  239. {
  240. LocalFree(paCRL);
  241. }
  242. }
  243. HRESULT
  244. crlCreateCRLReason(
  245. IN OUT CSMEMBLOCK **ppBlock,
  246. IN OUT CSCRLREASON **ppReason,
  247. IN DWORD RevocationReason,
  248. OUT DWORD *pcExtension,
  249. OUT CERT_EXTENSION **ppExtension)
  250. {
  251. HRESULT hr;
  252. CSCRLREASON *pReason = *ppReason;
  253. BYTE *pbEncoded = NULL;
  254. DWORD cbEncoded;
  255. for (pReason = *ppReason; NULL != pReason; pReason = pReason->pNext)
  256. {
  257. if (RevocationReason == pReason->RevocationReason)
  258. {
  259. break;
  260. }
  261. }
  262. if (NULL == pReason)
  263. {
  264. if (!myEncodeObject(
  265. X509_ASN_ENCODING,
  266. X509_ENUMERATED,
  267. (const void *) &RevocationReason,
  268. 0,
  269. CERTLIB_USE_LOCALALLOC,
  270. &pbEncoded,
  271. &cbEncoded))
  272. {
  273. hr = myHLastError();
  274. _JumpError(hr, error, "myEncodeObject");
  275. }
  276. hr = crlMemBlockAlloc(
  277. ppBlock,
  278. sizeof(CSCRLREASON) + cbEncoded,
  279. (BYTE **) &pReason);
  280. _JumpIfError(hr, error, "crlMemBlockAlloc");
  281. pReason->pNext = *ppReason;
  282. pReason->RevocationReason = RevocationReason;
  283. pReason->ExtReason.pszObjId = szOID_CRL_REASON_CODE;
  284. pReason->ExtReason.fCritical = FALSE;
  285. pReason->ExtReason.Value.pbData =
  286. (BYTE *) Add2Ptr(pReason, sizeof(*pReason));
  287. pReason->ExtReason.Value.cbData = cbEncoded;
  288. CopyMemory(pReason->ExtReason.Value.pbData, pbEncoded, cbEncoded);
  289. *ppReason = pReason;
  290. //printf("crlCreateCRLReason: new %x cb %x\n", RevocationReason, cbEncoded);
  291. }
  292. //printf("crlCreateCRLReason: %x\n", RevocationReason);
  293. CSASSERT(NULL != pReason && RevocationReason == pReason->RevocationReason);
  294. *pcExtension = 1;
  295. *ppExtension = &pReason->ExtReason;
  296. hr = S_OK;
  297. error:
  298. if (NULL != pbEncoded)
  299. {
  300. LocalFree(pbEncoded);
  301. }
  302. return(hr);
  303. }
  304. // Convert linked list of CRL blocks to an array.
  305. // If the output array pointer is NULL, just free the list.
  306. HRESULT
  307. ConvertOrFreeCRLList(
  308. IN OUT CSCRLBLOCK **ppBlockCRL, // Freed
  309. IN OUT CSMEMBLOCK **ppBlockReason, // Used to allocate reason extensions
  310. IN DWORD cCRL,
  311. OPTIONAL OUT CRL_ENTRY **paCRL)
  312. {
  313. HRESULT hr;
  314. CSCRLREASON *pReasonList = NULL; // linked list of reason extensions
  315. CSCRLBLOCK *pBlockCRL = *ppBlockCRL;
  316. CRL_ENTRY *aCRL = NULL;
  317. CRL_ENTRY *pCRL;
  318. DWORD i;
  319. if (NULL != paCRL)
  320. {
  321. aCRL = (CRL_ENTRY *) LocalAlloc(LMEM_FIXED, sizeof(aCRL[0]) * cCRL);
  322. if (NULL == aCRL)
  323. {
  324. hr = E_OUTOFMEMORY;
  325. _JumpError(hr, error, "LocalAlloc");
  326. }
  327. }
  328. pCRL = aCRL;
  329. while (NULL != pBlockCRL)
  330. {
  331. CSCRLBLOCK *pBlockCRLNext;
  332. if (NULL != pCRL)
  333. {
  334. for (i = 0; i < pBlockCRL->cCRLElement; i++)
  335. {
  336. CSCRLELEMENT *pCRLElement = &pBlockCRL->aCRLElement[i];
  337. pCRL->SerialNumber.pbData = pCRLElement->pbSerialNumber;
  338. pCRL->SerialNumber.cbData = pCRLElement->uscbSerialNumber;
  339. pCRL->RevocationDate = pCRLElement->ftRevocationDate;
  340. pCRL->cExtension = 0;
  341. pCRL->rgExtension = NULL;
  342. if (CRL_REASON_UNSPECIFIED != pCRLElement->usRevocationReason)
  343. {
  344. hr = crlCreateCRLReason(
  345. ppBlockReason,
  346. &pReasonList,
  347. pCRLElement->usRevocationReason,
  348. &pCRL->cExtension,
  349. &pCRL->rgExtension);
  350. _JumpIfError(hr, error, "crlCreateCRLReason");
  351. }
  352. pCRL++;
  353. }
  354. }
  355. pBlockCRLNext = pBlockCRL->pNext;
  356. LocalFree(pBlockCRL);
  357. pBlockCRL = pBlockCRLNext;
  358. }
  359. if (NULL != paCRL)
  360. {
  361. CSASSERT(pCRL == &aCRL[cCRL]);
  362. *paCRL = aCRL;
  363. aCRL = NULL;
  364. }
  365. CSASSERT(NULL == pBlockCRL);
  366. hr = S_OK;
  367. error:
  368. *ppBlockCRL = pBlockCRL;
  369. if (NULL != aCRL)
  370. {
  371. LocalFree(aCRL);
  372. }
  373. return(hr);
  374. }
  375. HRESULT
  376. AddCRLElement(
  377. IN OUT CSMEMBLOCK **ppBlockSerial,
  378. IN OUT CSCRLBLOCK **ppBlockCRL,
  379. IN WCHAR const *pwszSerialNumber,
  380. IN FILETIME const *pftRevokedEffectiveWhen,
  381. IN DWORD RevocationReason)
  382. {
  383. HRESULT hr;
  384. CSCRLELEMENT *pCRLElement;
  385. DWORD cbSerial;
  386. BYTE *pbSerial = NULL;
  387. hr = crlElementAlloc(ppBlockCRL, &pCRLElement);
  388. _JumpIfError(hr, error, "crlElementAlloc");
  389. hr = WszToMultiByteInteger(
  390. FALSE,
  391. pwszSerialNumber,
  392. &cbSerial,
  393. &pbSerial);
  394. _JumpIfError(hr, error, "WszToMultiByteInteger");
  395. hr = crlMemBlockAlloc(ppBlockSerial, cbSerial, &pCRLElement->pbSerialNumber);
  396. _JumpIfError(hr, error, "crlMemBlockAlloc");
  397. CopyMemory(pCRLElement->pbSerialNumber, pbSerial, cbSerial);
  398. pCRLElement->ftRevocationDate = *pftRevokedEffectiveWhen;
  399. pCRLElement->usRevocationReason = (USHORT) RevocationReason;
  400. pCRLElement->uscbSerialNumber = (USHORT) cbSerial;
  401. CSASSERT(pCRLElement->usRevocationReason == RevocationReason);
  402. CSASSERT(pCRLElement->uscbSerialNumber == cbSerial);
  403. error:
  404. if (NULL != pbSerial)
  405. {
  406. LocalFree(pbSerial);
  407. }
  408. return(hr);
  409. }
  410. DWORD g_aColCRL[] = {
  411. #define ICOL_DISPOSITION 0
  412. DTI_REQUESTTABLE | DTR_REQUESTDISPOSITION,
  413. #define ICOL_SERIAL 1
  414. DTI_CERTIFICATETABLE | DTC_CERTIFICATESERIALNUMBER,
  415. #define ICOL_EFFECTIVEWHEN 2
  416. DTI_REQUESTTABLE | DTR_REQUESTREVOKEDEFFECTIVEWHEN,
  417. #define ICOL_REASON 3
  418. DTI_REQUESTTABLE | DTR_REQUESTREVOKEDREASON,
  419. };
  420. HRESULT
  421. BuildCRLList(
  422. IN BOOL fDelta,
  423. IN DWORD iKey,
  424. OPTIONAL IN FILETIME const *pftQueryMinimum,
  425. IN FILETIME const *pftThisPublish,
  426. IN FILETIME const *pftLastPublishBase,
  427. IN OUT DWORD *pcCRL,
  428. IN OUT CSCRLBLOCK **ppBlockCRL,
  429. IN OUT CSMEMBLOCK **ppBlockSerial)
  430. {
  431. HRESULT hr;
  432. CERTVIEWRESTRICTION acvr[5];
  433. CERTVIEWRESTRICTION *pcvr;
  434. IEnumCERTDBRESULTROW *pView = NULL;
  435. DWORD celtFetched;
  436. DWORD NameIdMin;
  437. DWORD NameIdMax;
  438. DWORD i;
  439. BOOL fEnd;
  440. CERTDBRESULTROW aResult[10];
  441. BOOL fResultActive = FALSE;
  442. DWORD cCRL = *pcCRL;
  443. CSCRLBLOCK *pBlockCRL = *ppBlockCRL;
  444. CSMEMBLOCK *pBlockSerial = *ppBlockSerial;
  445. DBGPRINTTIME(NULL, "*pftThisPublish", DPT_DATE, *pftThisPublish);
  446. // Set up restrictions as follows:
  447. pcvr = acvr;
  448. // Request.RevokedEffectiveWhen <= *pftThisPublish (indexed column)
  449. pcvr->ColumnIndex = DTI_REQUESTTABLE | DTR_REQUESTREVOKEDEFFECTIVEWHEN;
  450. pcvr->SeekOperator = CVR_SEEK_LE;
  451. pcvr->SortOrder = CVR_SORT_DESCEND;
  452. pcvr->pbValue = (BYTE *) pftThisPublish;
  453. pcvr->cbValue = sizeof(*pftThisPublish);
  454. pcvr++;
  455. // Cert.NotAfter >= *pftLastPublishBase
  456. if (0 == (CRLF_PUBLISH_EXPIRED_CERT_CRLS & g_dwCRLFlags))
  457. {
  458. pcvr->ColumnIndex = DTI_CERTIFICATETABLE | DTC_CERTIFICATENOTAFTERDATE;
  459. pcvr->SeekOperator = CVR_SEEK_GE;
  460. pcvr->SortOrder = CVR_SORT_NONE;
  461. pcvr->pbValue = (BYTE *) pftLastPublishBase;
  462. pcvr->cbValue = sizeof(*pftLastPublishBase);
  463. pcvr++;
  464. }
  465. // NameId >= MAKECANAMEID(iCert == 0, iKey)
  466. NameIdMin = MAKECANAMEID(0, iKey);
  467. pcvr->ColumnIndex = DTI_CERTIFICATETABLE | DTC_CERTIFICATEISSUERNAMEID;
  468. pcvr->SeekOperator = CVR_SEEK_GE;
  469. pcvr->SortOrder = CVR_SORT_NONE;
  470. pcvr->pbValue = (BYTE *) &NameIdMin;
  471. pcvr->cbValue = sizeof(NameIdMin);
  472. pcvr++;
  473. // NameId <= MAKECANAMEID(iCert == _16BITMASK, iKey)
  474. NameIdMax = MAKECANAMEID(_16BITMASK, iKey);
  475. pcvr->ColumnIndex = DTI_CERTIFICATETABLE | DTC_CERTIFICATEISSUERNAMEID;
  476. pcvr->SeekOperator = CVR_SEEK_LE;
  477. pcvr->SortOrder = CVR_SORT_NONE;
  478. pcvr->pbValue = (BYTE *) &NameIdMax;
  479. pcvr->cbValue = sizeof(NameIdMax);
  480. pcvr++;
  481. CSASSERT(ARRAYSIZE(acvr) > SAFE_SUBTRACT_POINTERS(pcvr, acvr));
  482. if (NULL != pftQueryMinimum)
  483. {
  484. // Request.RevokedWhen >= *pftQueryMinimum
  485. pcvr->ColumnIndex = DTI_REQUESTTABLE | DTR_REQUESTREVOKEDWHEN;
  486. pcvr->SeekOperator = CVR_SEEK_GE;
  487. pcvr->SortOrder = CVR_SORT_NONE;
  488. pcvr->pbValue = (BYTE *) pftQueryMinimum;
  489. pcvr->cbValue = sizeof(*pftQueryMinimum);
  490. pcvr++;
  491. CSASSERT(ARRAYSIZE(acvr) >= SAFE_SUBTRACT_POINTERS(pcvr, acvr));
  492. }
  493. hr = g_pCertDB->OpenView(
  494. SAFE_SUBTRACT_POINTERS(pcvr, acvr),
  495. acvr,
  496. ARRAYSIZE(g_aColCRL),
  497. g_aColCRL,
  498. 0, // no worker thread
  499. &pView);
  500. _JumpIfError(hr, error, "OpenView");
  501. fEnd = FALSE;
  502. while (!fEnd)
  503. {
  504. hr = pView->Next(ARRAYSIZE(aResult), aResult, &celtFetched);
  505. if (S_FALSE == hr)
  506. {
  507. fEnd = TRUE;
  508. if (0 == celtFetched)
  509. {
  510. break;
  511. }
  512. hr = S_OK;
  513. }
  514. _JumpIfError(hr, error, "Next");
  515. fResultActive = TRUE;
  516. CSASSERT(ARRAYSIZE(aResult) >= celtFetched);
  517. for (i = 0; i < celtFetched; i++)
  518. {
  519. DWORD Disposition;
  520. DWORD Reason;
  521. CERTDBRESULTROW *pResult = &aResult[i];
  522. CSASSERT(ARRAYSIZE(g_aColCRL) == pResult->ccol);
  523. CSASSERT(NULL != pResult->acol[ICOL_DISPOSITION].pbValue);
  524. CSASSERT(PROPTYPE_LONG == (PROPTYPE_MASK & pResult->acol[ICOL_DISPOSITION].Type));
  525. CSASSERT(sizeof(Disposition) == pResult->acol[ICOL_DISPOSITION].cbValue);
  526. Disposition = *(DWORD *) pResult->acol[ICOL_DISPOSITION].pbValue;
  527. CSASSERT(NULL != pResult->acol[ICOL_SERIAL].pbValue);
  528. CSASSERT(PROPTYPE_STRING == (PROPTYPE_MASK & pResult->acol[ICOL_SERIAL].Type));
  529. CSASSERT(0 < pResult->acol[ICOL_SERIAL].cbValue);
  530. if (NULL == pResult->acol[ICOL_EFFECTIVEWHEN].pbValue)
  531. {
  532. continue;
  533. }
  534. CSASSERT(sizeof(FILETIME) == pResult->acol[ICOL_EFFECTIVEWHEN].cbValue);
  535. CSASSERT(PROPTYPE_DATE == (PROPTYPE_MASK & pResult->acol[ICOL_EFFECTIVEWHEN].Type));
  536. CSASSERT(PROPTYPE_LONG == (PROPTYPE_MASK & pResult->acol[ICOL_REASON].Type));
  537. Reason = CRL_REASON_UNSPECIFIED;
  538. if (NULL != pResult->acol[ICOL_REASON].pbValue)
  539. {
  540. CSASSERT(sizeof(Reason) == pResult->acol[ICOL_REASON].cbValue);
  541. Reason = *(DWORD *) pResult->acol[ICOL_REASON].pbValue;
  542. }
  543. if (NULL == pResult->acol[ICOL_SERIAL].pbValue ||
  544. CRL_REASON_REMOVE_FROM_CRL == Reason)
  545. {
  546. continue;
  547. }
  548. // Add to CRL unless it's:
  549. // not a revoked issued cert &&
  550. // not a root CA cert &&
  551. // not an unrevoked issued cert
  552. if (DB_DISP_REVOKED != Disposition &&
  553. !(DB_DISP_CA_CERT == Disposition && IsRootCA(g_CAType)) &&
  554. !(DB_DISP_ISSUED == Disposition && MAXDWORD == Reason))
  555. {
  556. continue;
  557. }
  558. if (MAXDWORD == Reason)
  559. {
  560. if (!fDelta)
  561. {
  562. continue;
  563. }
  564. Reason = CRL_REASON_REMOVE_FROM_CRL;
  565. }
  566. hr = AddCRLElement(
  567. &pBlockSerial,
  568. &pBlockCRL,
  569. (WCHAR const *) pResult->acol[ICOL_SERIAL].pbValue,
  570. (FILETIME const *) pResult->acol[ICOL_EFFECTIVEWHEN].pbValue,
  571. Reason);
  572. _JumpIfError(hr, error, "AddCRLElement");
  573. CONSOLEPRINT3((
  574. DBG_SS_CERTSRV,
  575. "Cert is %ws: %ws: %d\n",
  576. CRL_REASON_REMOVE_FROM_CRL == Reason?
  577. L"UNREVOKED" : L"Revoked",
  578. pResult->acol[ICOL_SERIAL].pbValue,
  579. Reason));
  580. cCRL++;
  581. }
  582. pView->ReleaseResultRow(celtFetched, aResult);
  583. fResultActive = FALSE;
  584. }
  585. *pcCRL = cCRL;
  586. hr = S_OK;
  587. error:
  588. *ppBlockSerial = pBlockSerial;
  589. *ppBlockCRL = pBlockCRL;
  590. if (NULL != pView)
  591. {
  592. if (fResultActive)
  593. {
  594. pView->ReleaseResultRow(celtFetched, aResult);
  595. }
  596. pView->Release();
  597. }
  598. return(hr);
  599. }
  600. #undef ICOL_DISPOSITION
  601. #undef ICOL_SERIAL
  602. #undef ICOL_EFFECTIVEWHEN
  603. #undef ICOL_REASON
  604. HRESULT
  605. crlBuildCRLArray(
  606. IN BOOL fDelta,
  607. OPTIONAL IN FILETIME const *pftQueryMinimum,
  608. IN FILETIME const *pftThisPublish,
  609. IN FILETIME const *pftLastPublishBase,
  610. IN DWORD iKey,
  611. OUT DWORD *pcCRL,
  612. OUT CRL_ENTRY **paCRL,
  613. OUT VOID **ppvBlock)
  614. {
  615. HRESULT hr;
  616. BOOL fCoInitialized = FALSE;
  617. CSCRLBLOCK *pBlockCRL = NULL;
  618. CSMEMBLOCK *pBlockSerial = NULL;
  619. *pcCRL = 0;
  620. *paCRL = NULL;
  621. *ppvBlock = NULL;
  622. hr = CoInitializeEx(NULL, GetCertsrvComThreadingModel());
  623. if (S_OK != hr && S_FALSE != hr)
  624. {
  625. _JumpError(hr, error, "CoInitializeEx");
  626. }
  627. fCoInitialized = TRUE;
  628. hr = BuildCRLList(
  629. fDelta,
  630. iKey,
  631. pftQueryMinimum,
  632. pftThisPublish,
  633. pftLastPublishBase,
  634. pcCRL,
  635. &pBlockCRL,
  636. &pBlockSerial);
  637. _JumpIfError(hr, error, "BuildCRLList");
  638. hr = ConvertOrFreeCRLList(&pBlockCRL, &pBlockSerial, *pcCRL, paCRL);
  639. _JumpIfError(hr, error, "ConvertOrFreeCRLList");
  640. *ppvBlock = pBlockSerial;
  641. pBlockSerial = NULL;
  642. error:
  643. if (NULL != pBlockCRL)
  644. {
  645. ConvertOrFreeCRLList(&pBlockCRL, NULL, 0, NULL);
  646. }
  647. if (NULL != pBlockSerial)
  648. {
  649. crlBlockListFree(pBlockSerial);
  650. }
  651. if (fCoInitialized)
  652. {
  653. CoUninitialize();
  654. }
  655. return(hr);
  656. }
  657. HRESULT
  658. crlGetRegCRLNextPublish(
  659. IN BOOL fDelta,
  660. IN WCHAR const *pwszSanitizedName,
  661. IN WCHAR const *pwszRegName,
  662. OUT FILETIME *pftNextPublish)
  663. {
  664. HRESULT hr;
  665. BYTE *pbData = NULL;
  666. DWORD cbData;
  667. DWORD dwType;
  668. hr = myGetCertRegValue(
  669. NULL,
  670. pwszSanitizedName,
  671. NULL,
  672. NULL,
  673. pwszRegName,
  674. &pbData, // free using LocalFree
  675. &cbData,
  676. &dwType);
  677. if (HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr)
  678. {
  679. hr = S_OK;
  680. goto error;
  681. }
  682. _JumpIfErrorStr(hr, error, "myGetCertRegValue", pwszRegName);
  683. if (REG_BINARY != dwType || sizeof(*pftNextPublish) != cbData)
  684. {
  685. hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
  686. goto error;
  687. }
  688. *pftNextPublish = *(FILETIME *) pbData;
  689. DBGPRINTTIME(&fDelta, "*pftNextPublish", DPT_DATE, *pftNextPublish);
  690. error:
  691. if (NULL != pbData)
  692. {
  693. LocalFree(pbData);
  694. }
  695. return(hr);
  696. }
  697. HRESULT
  698. crlSetRegCRLNextPublish(
  699. IN BOOL fDelta,
  700. IN WCHAR const *pwszSanitizedName,
  701. IN WCHAR const *pwszRegName,
  702. IN FILETIME const *pftNextPublish)
  703. {
  704. HRESULT hr;
  705. hr = mySetCertRegValue(
  706. NULL,
  707. pwszSanitizedName,
  708. NULL,
  709. NULL,
  710. pwszRegName,
  711. REG_BINARY,
  712. (BYTE const *) pftNextPublish,
  713. sizeof(*pftNextPublish),
  714. FALSE);
  715. _JumpIfErrorStr(hr, error, "mySetCertRegValue", pwszRegName);
  716. DBGPRINTTIME(&fDelta, "*pftNextPublish", DPT_DATE, *pftNextPublish);
  717. error:
  718. return(hr);
  719. }
  720. // called from CoreInit
  721. // inits process-static data: g_ftCRLNextPublish, etc.
  722. HRESULT
  723. CRLInit(
  724. IN WCHAR const *pwszSanitizedName)
  725. {
  726. HRESULT hr;
  727. DWORD dw;
  728. ZeroMemory(&g_ftCRLNextPublish, sizeof(g_ftCRLNextPublish));
  729. ZeroMemory(&g_ftDeltaCRLNextPublish, sizeof(g_ftDeltaCRLNextPublish));
  730. hr = crlGetRegCRLNextPublish(
  731. FALSE,
  732. pwszSanitizedName,
  733. wszREGCRLNEXTPUBLISH,
  734. &g_ftCRLNextPublish);
  735. _JumpIfError(hr, error, "crlGetRegCRLNextPublish");
  736. hr = crlGetRegCRLNextPublish(
  737. TRUE,
  738. pwszSanitizedName,
  739. wszREGCRLDELTANEXTPUBLISH,
  740. &g_ftDeltaCRLNextPublish);
  741. _JumpIfError(hr, error, "crlGetRegCRLNextPublish");
  742. hr = myGetCertRegDWValue(
  743. pwszSanitizedName,
  744. NULL,
  745. NULL,
  746. wszREGCRLFLAGS,
  747. (DWORD *) &dw);
  748. _PrintIfErrorStr(hr, "myGetCertRegDWValue", wszREGCRLFLAGS);
  749. if (S_OK == hr)
  750. {
  751. g_dwCRLFlags = dw;
  752. }
  753. hr = S_OK;
  754. error:
  755. return(hr);
  756. }
  757. VOID
  758. CRLTerminate()
  759. {
  760. if (NULL != g_pld)
  761. {
  762. ldap_unbind(g_pld);
  763. g_pld = NULL;
  764. }
  765. }
  766. HRESULT
  767. crlGetRegPublishParams(
  768. IN BOOL fDelta,
  769. IN WCHAR const *pwszSanitizedName,
  770. IN WCHAR const *pwszRegCRLPeriodCount,
  771. IN WCHAR const *pwszRegCRLPeriodString,
  772. IN WCHAR const *pwszRegCRLOverlapPeriodCount,
  773. IN WCHAR const *pwszRegCRLOverlapPeriodString,
  774. IN LONG lPeriodCountDefault,
  775. IN WCHAR const *pwszPeriodStringDefault,
  776. OPTIONAL OUT CSCRLPERIOD *pccp,
  777. OUT BOOL *pfCRLPublishDisabled)
  778. {
  779. HRESULT hr;
  780. WCHAR *pwszCRLPeriodString = NULL;
  781. WCHAR *pwszCRLOverlapPeriodString = NULL;
  782. DWORD cbData;
  783. DWORD dwPeriod;
  784. DWORD dwType;
  785. CSCRLPERIOD ccp;
  786. if (NULL == pccp)
  787. {
  788. pccp = &ccp;
  789. }
  790. ZeroMemory(pccp, sizeof(*pccp));
  791. CSASSERT(NULL != pfCRLPublishDisabled);
  792. // get if need lCRLPeriodCount OR enumCRLPeriod
  793. // if any of these fail, skip to error handling below
  794. hr = myGetCertRegDWValue(
  795. pwszSanitizedName,
  796. NULL,
  797. NULL,
  798. pwszRegCRLPeriodCount,
  799. (DWORD *) &pccp->lCRLPeriodCount);
  800. _PrintIfErrorStr(hr, "myGetCertRegDWValue", pwszRegCRLPeriodCount);
  801. if (hr == S_OK)
  802. {
  803. hr = myGetCertRegStrValue(
  804. pwszSanitizedName,
  805. NULL,
  806. NULL,
  807. pwszRegCRLPeriodString,
  808. &pwszCRLPeriodString);
  809. _PrintIfErrorStr(hr, "myGetCertRegDWValue", pwszRegCRLPeriodString);
  810. if (hr == S_OK)
  811. {
  812. hr = myTranslatePeriodUnits(
  813. pwszCRLPeriodString,
  814. pccp->lCRLPeriodCount,
  815. &pccp->enumCRLPeriod,
  816. &pccp->lCRLPeriodCount);
  817. _PrintIfError(hr, "myTranslatePeriodUnits");
  818. }
  819. // don't allow base to be disabled anymore: force defaults to be loaded
  820. if (!fDelta &&
  821. (0 == pccp->lCRLPeriodCount || -1 == pccp->lCRLPeriodCount))
  822. {
  823. hr = E_INVALIDARG;
  824. }
  825. }
  826. if (hr != S_OK)
  827. {
  828. _PrintError(hr, "Error reading CRLPub params. Overwriting with defaults.");
  829. if (CERTLOG_WARNING <= g_dwLogLevel)
  830. {
  831. hr = LogEvent(
  832. EVENTLOG_WARNING_TYPE,
  833. MSG_INVALID_CRL_SETTINGS,
  834. 0,
  835. NULL);
  836. _PrintIfError(hr, "LogEvent");
  837. }
  838. // slam default publishing to whatever the caller said
  839. hr = myTranslatePeriodUnits(
  840. pwszPeriodStringDefault,
  841. lPeriodCountDefault,
  842. &pccp->enumCRLPeriod,
  843. &pccp->lCRLPeriodCount);
  844. _JumpIfError(hr, error, "myTranslatePeriodUnits");
  845. // blindly reset defaults
  846. mySetCertRegDWValue(
  847. pwszSanitizedName,
  848. NULL,
  849. NULL,
  850. pwszRegCRLPeriodCount,
  851. pccp->lCRLPeriodCount);
  852. mySetCertRegStrValue(
  853. pwszSanitizedName,
  854. NULL,
  855. NULL,
  856. pwszRegCRLPeriodString,
  857. pwszPeriodStringDefault);
  858. }
  859. *pfCRLPublishDisabled = 0 == pccp->lCRLPeriodCount;
  860. if (&ccp != pccp) // If caller wants the data
  861. {
  862. BOOL fRegistryOverlap = FALSE;
  863. DWORD dwCRLOverlapCount;
  864. ENUM_PERIOD enumCRLOverlap;
  865. LLFILETIME llftDeltaPeriod;
  866. // try and gather overlap values from registry - bail on any failure
  867. hr = myGetCertRegDWValue(
  868. pwszSanitizedName,
  869. NULL,
  870. NULL,
  871. pwszRegCRLOverlapPeriodCount,
  872. &dwCRLOverlapCount);
  873. if (hr == S_OK && 0 != dwCRLOverlapCount) // if not disabled
  874. {
  875. hr = myGetCertRegStrValue(
  876. pwszSanitizedName,
  877. NULL,
  878. NULL,
  879. pwszRegCRLOverlapPeriodString,
  880. &pwszCRLOverlapPeriodString);// free w/ LocalFree
  881. if (hr == S_OK)
  882. {
  883. hr = myTranslatePeriodUnits(
  884. pwszCRLOverlapPeriodString,
  885. dwCRLOverlapCount,
  886. &enumCRLOverlap,
  887. (LONG *) &dwCRLOverlapCount);
  888. // we have enough info to override overlap calculation
  889. if (hr == S_OK)
  890. {
  891. fRegistryOverlap = TRUE;
  892. DBGPRINT((
  893. DBG_SS_CERTSRVI,
  894. "Loaded CRL Overlap values. Overriding overlap calculation with specified values.\n"));
  895. }
  896. }
  897. }
  898. // always possible to revert to calculated value
  899. if (fRegistryOverlap)
  900. {
  901. LLFILETIME llftOverlap;
  902. // convert registry-specified CRL overlap to FILETIME
  903. llftOverlap.ll = 0;
  904. myMakeExprDateTime(
  905. &llftOverlap.ft,
  906. dwCRLOverlapCount,
  907. enumCRLOverlap);
  908. DBGPRINTTIME(&fDelta, "ftdelta1", DPT_DELTA, llftOverlap.ft);
  909. llftOverlap.ll /= CVT_BASE; // now in seconds
  910. // (DELTA sec / 60 secpermin)
  911. pccp->dwCRLOverlapMinutes = (DWORD) (llftOverlap.ll / CVT_MINUTES);
  912. }
  913. // convert CRL period to FILETIME
  914. llftDeltaPeriod.ll = 0;
  915. myMakeExprDateTime(
  916. &llftDeltaPeriod.ft,
  917. pccp->lCRLPeriodCount,
  918. pccp->enumCRLPeriod);
  919. DBGPRINTTIME(&fDelta, "ftdelta2", DPT_DELTA, llftDeltaPeriod.ft);
  920. llftDeltaPeriod.ll /= CVT_BASE; // now in seconds
  921. llftDeltaPeriod.ll /= CVT_MINUTES; // now in minutes
  922. if (!fRegistryOverlap)
  923. {
  924. if (fDelta)
  925. {
  926. // default CRLOverlap for delta CRLs: same as period
  927. pccp->dwCRLOverlapMinutes = llftDeltaPeriod.ft.dwLowDateTime;
  928. }
  929. else
  930. {
  931. // default CRLOverlap for base CRLs: 10% of period
  932. pccp->dwCRLOverlapMinutes = (DWORD) (llftDeltaPeriod.ll / 10);
  933. }
  934. // Clamp computed overlap to less than 12 hours
  935. if (pccp->dwCRLOverlapMinutes > 12 * 60)
  936. {
  937. pccp->dwCRLOverlapMinutes = 12 * 60;
  938. }
  939. }
  940. // Always clamp lower bound: (1.5 * skew) < g_dwCRLOverlapMinutes
  941. // must be at least 1.5x skew
  942. dwCRLOverlapCount = (3 * g_dwClockSkewMinutes) >> 1;
  943. if (pccp->dwCRLOverlapMinutes < dwCRLOverlapCount)
  944. {
  945. pccp->dwCRLOverlapMinutes = dwCRLOverlapCount;
  946. }
  947. // Always clamp upper bound: must be no more than CRL period
  948. if (pccp->dwCRLOverlapMinutes > llftDeltaPeriod.ft.dwLowDateTime)
  949. {
  950. pccp->dwCRLOverlapMinutes = llftDeltaPeriod.ft.dwLowDateTime;
  951. }
  952. }
  953. hr = S_OK;
  954. error:
  955. if (NULL != pwszCRLPeriodString)
  956. {
  957. LocalFree(pwszCRLPeriodString);
  958. }
  959. if (NULL != pwszCRLOverlapPeriodString)
  960. {
  961. LocalFree(pwszCRLOverlapPeriodString);
  962. }
  963. return(hr);
  964. }
  965. // Reload publication params during each CRL publication
  966. HRESULT
  967. crlGetRegCRLPublishParams(
  968. IN WCHAR const *pwszSanitizedName,
  969. OPTIONAL OUT CSCRLPERIOD *pccpBase,
  970. OPTIONAL OUT CSCRLPERIOD *pccpDelta)
  971. {
  972. HRESULT hr;
  973. hr = crlGetRegPublishParams(
  974. FALSE,
  975. pwszSanitizedName,
  976. wszREGCRLPERIODCOUNT,
  977. wszREGCRLPERIODSTRING,
  978. wszREGCRLOVERLAPPERIODCOUNT,
  979. wszREGCRLOVERLAPPERIODSTRING,
  980. dwCRLPERIODCOUNTDEFAULT, // default period
  981. wszCRLPERIODSTRINGDEFAULT, // default period
  982. pccpBase,
  983. &g_fCRLPublishDisabled);
  984. _JumpIfError(hr, error, "crlGetRegPublishParams");
  985. hr = crlGetRegPublishParams(
  986. TRUE,
  987. pwszSanitizedName,
  988. wszREGCRLDELTAPERIODCOUNT,
  989. wszREGCRLDELTAPERIODSTRING,
  990. wszREGCRLDELTAOVERLAPPERIODCOUNT,
  991. wszREGCRLDELTAOVERLAPPERIODSTRING,
  992. dwCRLDELTAPERIODCOUNTDEFAULT, // default period
  993. wszCRLDELTAPERIODSTRINGDEFAULT, // default period
  994. pccpDelta,
  995. &g_fDeltaCRLPublishDisabled);
  996. _JumpIfError(hr, error, "crlGetRegPublishParams");
  997. error:
  998. return(hr);
  999. }
  1000. #define CERTSRV_CRLPUB_RETRY_COUNT_DEFAULT 10
  1001. #define CERTSRV_CRLPUB_RETRY_SECONDS (10 * CVT_MINUTES)
  1002. VOID
  1003. crlComputeTimeOutSub(
  1004. OPTIONAL IN BOOL *pfDelta,
  1005. IN FILETIME const *pftFirst,
  1006. IN FILETIME const *pftLast,
  1007. OUT DWORD *pdwMSTimeOut)
  1008. {
  1009. LLFILETIME llft;
  1010. // llft.ll = *pftLast - *pftFirst;
  1011. llft.ll = mySubtractFileTimes(pftLast, pftFirst);
  1012. DBGPRINTTIME(pfDelta, "*pftFirst", DPT_DATE, *pftFirst);
  1013. DBGPRINTTIME(pfDelta, "*pftLast", DPT_DATE, *pftLast);
  1014. llft.ll /= (CVT_BASE / 1000); // convert 100ns to msecs
  1015. DBGPRINTTIME(pfDelta, "llft", DPT_DELTAMS, llft.ft);
  1016. if (0 > llft.ll || MAXLONG < llft.ll)
  1017. {
  1018. // wait as long as we can without going infinite
  1019. llft.ll = MAXLONG;
  1020. }
  1021. *pdwMSTimeOut = llft.ft.dwLowDateTime;
  1022. }
  1023. VOID
  1024. crlComputeTimeOutEx(
  1025. IN BOOL fDelta,
  1026. IN FILETIME const *pftFirst,
  1027. IN FILETIME const *pftLast,
  1028. OUT DWORD *pdwMSTimeOut)
  1029. {
  1030. crlComputeTimeOutSub(&fDelta, pftFirst, pftLast, pdwMSTimeOut);
  1031. }
  1032. VOID
  1033. CRLComputeTimeOut(
  1034. IN FILETIME const *pftFirst,
  1035. IN FILETIME const *pftLast,
  1036. OUT DWORD *pdwMSTimeOut)
  1037. {
  1038. crlComputeTimeOutSub(NULL, pftFirst, pftLast, pdwMSTimeOut);
  1039. }
  1040. #ifdef DBG_CERTSRV_DEBUG_PRINT
  1041. VOID
  1042. DbgPrintRemainTime(
  1043. IN BOOL fDelta,
  1044. IN FILETIME const *pftCurrent,
  1045. IN FILETIME const *pftCRLNextPublish)
  1046. {
  1047. HRESULT hr;
  1048. LLFILETIME llftDelta;
  1049. WCHAR *pwszTime = NULL;
  1050. WCHAR awc[1];
  1051. llftDelta.ll = mySubtractFileTimes(pftCRLNextPublish, pftCurrent);
  1052. DBGPRINTTIME(&fDelta, "delta", DPT_DELTA, llftDelta.ft);
  1053. llftDelta.ll = -llftDelta.ll;
  1054. hr = myFileTimePeriodToWszTimePeriod(
  1055. &llftDelta.ft,
  1056. TRUE, // fExact
  1057. &pwszTime);
  1058. _PrintIfError(hr, "myFileTimePeriodToWszTimePeriod");
  1059. if (S_OK != hr)
  1060. {
  1061. awc[0] = L'\0';
  1062. pwszTime = awc;
  1063. }
  1064. DBGPRINT((
  1065. DBG_SS_CERTSRV,
  1066. "CRLPubWakeupEvent(tid=%d): Next %hs CRL: %ws\n",
  1067. GetCurrentThreadId(),
  1068. fDelta? "Delta" : "Base",
  1069. pwszTime));
  1070. if (NULL != pwszTime && awc != pwszTime)
  1071. {
  1072. LocalFree(pwszTime);
  1073. }
  1074. }
  1075. #endif // DBG_CERTSRV_DEBUG_PRINT
  1076. DWORD g_aColExpiredCRL[] = {
  1077. #define ICOLEXP_ROWID 0
  1078. DTI_CRLTABLE | DTL_ROWID,
  1079. #define ICOLEXP_MINBASE 1
  1080. DTI_CRLTABLE | DTL_MINBASE,
  1081. #define ICOLEXP_CRLNEXTUPDATE 2
  1082. DTI_CRLTABLE | DTL_NEXTUPDATEDATE,
  1083. };
  1084. HRESULT
  1085. crlDeleteExpiredCRLs(
  1086. IN FILETIME const *pftCurrent,
  1087. IN FILETIME const *pftQueryDeltaDelete,
  1088. IN DWORD RowIdBase)
  1089. {
  1090. HRESULT hr;
  1091. CERTVIEWRESTRICTION acvr[1];
  1092. CERTVIEWRESTRICTION *pcvr;
  1093. IEnumCERTDBRESULTROW *pView = NULL;
  1094. BOOL fResultActive = FALSE;
  1095. CERTDBRESULTROW aResult[1];
  1096. CERTDBRESULTROW *pResult;
  1097. DWORD celtFetched;
  1098. if (CRLF_DELETE_EXPIRED_CRLS & g_dwCRLFlags)
  1099. {
  1100. DBGPRINTTIME(NULL, "DeleteCRL:*pftCurrent", DPT_DATE, *pftCurrent);
  1101. DBGPRINTTIME(NULL, "DeleteCRL:*pftQueryDeltaDelete", DPT_DATE, *pftQueryDeltaDelete);
  1102. // Set up restrictions as follows:
  1103. pcvr = acvr;
  1104. // CRL Expiration < ftCurrent (indexed column)
  1105. pcvr->ColumnIndex = DTI_CRLTABLE | DTL_NEXTPUBLISHDATE;
  1106. pcvr->SeekOperator = CVR_SEEK_LT;
  1107. pcvr->SortOrder = CVR_SORT_ASCEND; // Oldest propagated CRL first
  1108. pcvr->pbValue = (BYTE *) pftCurrent;
  1109. pcvr->cbValue = sizeof(*pftCurrent);
  1110. pcvr++;
  1111. CSASSERT(ARRAYSIZE(acvr) == SAFE_SUBTRACT_POINTERS(pcvr, acvr));
  1112. hr = g_pCertDB->OpenView(
  1113. ARRAYSIZE(acvr),
  1114. acvr,
  1115. ARRAYSIZE(g_aColExpiredCRL),
  1116. g_aColExpiredCRL,
  1117. 0, // no worker thread
  1118. &pView);
  1119. _JumpIfError(hr, error, "OpenView");
  1120. while (TRUE)
  1121. {
  1122. DWORD RowId;
  1123. DWORD MinBase;
  1124. FILETIME ftNextUpdate;
  1125. BOOL fDelete;
  1126. hr = pView->Next(ARRAYSIZE(aResult), aResult, &celtFetched);
  1127. if (S_FALSE == hr)
  1128. {
  1129. if (0 == celtFetched)
  1130. {
  1131. break;
  1132. }
  1133. }
  1134. _JumpIfError(hr, error, "Next");
  1135. fResultActive = TRUE;
  1136. CSASSERT(ARRAYSIZE(aResult) == celtFetched);
  1137. pResult = &aResult[0];
  1138. CSASSERT(ARRAYSIZE(g_aColExpiredCRL) == pResult->ccol);
  1139. CSASSERT(NULL != pResult->acol[ICOLEXP_ROWID].pbValue);
  1140. CSASSERT(PROPTYPE_LONG == (PROPTYPE_MASK & pResult->acol[ICOLEXP_ROWID].Type));
  1141. CSASSERT(sizeof(RowId) == pResult->acol[ICOLEXP_ROWID].cbValue);
  1142. RowId = *(DWORD *) pResult->acol[ICOLEXP_ROWID].pbValue;
  1143. CSASSERT(NULL != pResult->acol[ICOLEXP_MINBASE].pbValue);
  1144. CSASSERT(PROPTYPE_LONG == (PROPTYPE_MASK & pResult->acol[ICOLEXP_MINBASE].Type));
  1145. CSASSERT(sizeof(MinBase) == pResult->acol[ICOLEXP_MINBASE].cbValue);
  1146. MinBase = *(DWORD *) pResult->acol[ICOLEXP_MINBASE].pbValue;
  1147. CSASSERT(NULL != pResult->acol[ICOLEXP_CRLNEXTUPDATE].pbValue);
  1148. CSASSERT(PROPTYPE_DATE == (PROPTYPE_MASK & pResult->acol[ICOLEXP_CRLNEXTUPDATE].Type));
  1149. CSASSERT(sizeof(FILETIME) == pResult->acol[ICOLEXP_CRLNEXTUPDATE].cbValue);
  1150. ftNextUpdate = *(FILETIME *) pResult->acol[ICOLEXP_CRLNEXTUPDATE].pbValue;
  1151. pView->ReleaseResultRow(celtFetched, aResult);
  1152. fResultActive = FALSE;
  1153. CSASSERT(0 != RowId);
  1154. // Delete the CRL row if it is not the current Base CRL and the
  1155. // row represents a CRL that expired prior to the current Base CRL.
  1156. fDelete = FALSE;
  1157. if (RowIdBase != RowId &&
  1158. 0 < CompareFileTime(pftQueryDeltaDelete, &ftNextUpdate))
  1159. {
  1160. fDelete = TRUE;
  1161. }
  1162. DBGPRINTTIME(NULL, "DeleteCRL:ftNextUpdate", DPT_DATE, ftNextUpdate);
  1163. DBGPRINT((
  1164. DBG_SS_CERTSRVI,
  1165. "crlDeleteExpiredCRLs(RowId=%x) %ws\n",
  1166. RowId,
  1167. fDelete? L"DELETE" : L"SKIP"));
  1168. if (fDelete)
  1169. {
  1170. ICertDBRow *prow;
  1171. hr = g_pCertDB->OpenRow(
  1172. PROPOPEN_DELETE | PROPTABLE_CRL,
  1173. RowId,
  1174. NULL,
  1175. &prow);
  1176. _JumpIfError(hr, error, "OpenRow");
  1177. hr = prow->Delete();
  1178. _PrintIfError(hr, "Delete");
  1179. if (S_OK == hr)
  1180. {
  1181. hr = prow->CommitTransaction(TRUE);
  1182. _PrintIfError(hr, "CommitTransaction");
  1183. }
  1184. if (S_OK != hr)
  1185. {
  1186. HRESULT hr2 = prow->CommitTransaction(FALSE);
  1187. _PrintIfError(hr2, "CommitTransaction");
  1188. }
  1189. prow->Release();
  1190. }
  1191. }
  1192. }
  1193. hr = S_OK;
  1194. error:
  1195. if (NULL != pView)
  1196. {
  1197. if (fResultActive)
  1198. {
  1199. pView->ReleaseResultRow(celtFetched, aResult);
  1200. }
  1201. pView->Release();
  1202. }
  1203. return(hr);
  1204. }
  1205. #undef ICOLEXP_ROWID
  1206. #undef ICOLEXP_MINBASE
  1207. #undef ICOLEXP_CRLNEXTUPDATE
  1208. ///////////////////////////////////////////////////
  1209. // CRLPubWakeupEvent is the handler for wakeup notifications.
  1210. //
  1211. // This function is called at miscellaneous times and
  1212. // determines whether or not it is time to rebuild the
  1213. // CRL to be published.
  1214. //
  1215. // It then calls CRLPublishCRLs and advises it as to whether to
  1216. // rebuild or not.
  1217. //
  1218. // Its final task is to recalculate the next wakeup time, which
  1219. // depends on current time, if the exit module needs to be retried,
  1220. // or whether CRL publishing is disabled.
  1221. HRESULT
  1222. CRLPubWakeupEvent(
  1223. OUT DWORD *pdwMSTimeOut)
  1224. {
  1225. HRESULT hr;
  1226. HRESULT hrPublish;
  1227. FILETIME ftZero;
  1228. FILETIME ftCurrent;
  1229. BOOL fBaseTrigger = TRUE;
  1230. BOOL fRebuildCRL = FALSE;
  1231. BOOL fForceRepublish = FALSE;
  1232. BOOL fShadowDelta = FALSE;
  1233. BOOL fSetRetryTimer = FALSE;
  1234. DWORD dwMSTimeOut = CERTSRV_CRLPUB_RETRY_SECONDS * 1000;
  1235. DWORD State = 0;
  1236. static BOOL s_fFirstWakeup = TRUE;
  1237. CSASSERT(NULL != pdwMSTimeOut);
  1238. // if anything goes wrong, call us again after a pause
  1239. hr = CertSrvEnterServer(&State);
  1240. _JumpIfError(hr, error, "CertSrvEnterServer");
  1241. __try
  1242. {
  1243. BOOL fCRLPublishDisabledOld = g_fCRLPublishDisabled;
  1244. BOOL fDeltaCRLPublishDisabledOld = g_fDeltaCRLPublishDisabled;
  1245. // Recalc Timeout
  1246. GetSystemTimeAsFileTime(&ftCurrent);
  1247. #ifdef DBG_CERTSRV_DEBUG_PRINT
  1248. {
  1249. WCHAR *pwszNow = NULL;
  1250. myGMTFileTimeToWszLocalTime(&ftCurrent, TRUE, &pwszNow);
  1251. DBGPRINT((DBG_SS_CERTSRV, "CRLPubWakeupEvent(%ws)\n", pwszNow));
  1252. if (NULL != pwszNow)
  1253. {
  1254. LocalFree(pwszNow);
  1255. }
  1256. }
  1257. #endif // DBG_CERTSRV_DEBUG_PRINT
  1258. // get current publish params
  1259. hr = crlGetRegCRLPublishParams(g_wszSanitizedName, NULL, NULL);
  1260. _LeaveIfError(hr, "crlGetRegCRLPublishParams");
  1261. if (s_fFirstWakeup)
  1262. {
  1263. s_fFirstWakeup = FALSE;
  1264. if (g_fDBRecovered)
  1265. {
  1266. fForceRepublish = TRUE;
  1267. }
  1268. }
  1269. else
  1270. {
  1271. if (!g_fCRLPublishDisabled &&
  1272. (fCRLPublishDisabledOld ||
  1273. g_fDeltaCRLPublishDisabled != fDeltaCRLPublishDisabledOld))
  1274. {
  1275. fRebuildCRL = TRUE; // state change: force new CRLs
  1276. // If delta CRLs were just now disabled, make one attempt to
  1277. // publish shadow deltas; force clients to fetch a new base CRL.
  1278. if (!fDeltaCRLPublishDisabledOld && g_fDeltaCRLPublishDisabled)
  1279. {
  1280. fShadowDelta = TRUE; // force shadow delta
  1281. }
  1282. }
  1283. }
  1284. // if "not yet ready"
  1285. if (0 < CompareFileTime(&g_ftCRLNextPublish, &ftCurrent))
  1286. {
  1287. fBaseTrigger = FALSE;
  1288. #ifdef DBG_CERTSRV_DEBUG_PRINT
  1289. // give next pub status
  1290. DbgPrintRemainTime(FALSE, &ftCurrent, &g_ftCRLNextPublish);
  1291. #endif // DBG_CERTSRV_DEBUG_PRINT
  1292. }
  1293. // if "not yet ready"
  1294. if (!fBaseTrigger &&
  1295. (g_fDeltaCRLPublishDisabled ||
  1296. 0 < CompareFileTime(&g_ftDeltaCRLNextPublish, &ftCurrent)))
  1297. {
  1298. #ifdef DBG_CERTSRV_DEBUG_PRINT
  1299. // give next pub status
  1300. if (!g_fDeltaCRLPublishDisabled)
  1301. {
  1302. DbgPrintRemainTime(TRUE, &ftCurrent, &g_ftDeltaCRLNextPublish);
  1303. }
  1304. #endif // DBG_CERTSRV_DEBUG_PRINT
  1305. }
  1306. else // "ready to publish" trigger
  1307. {
  1308. if (!g_fCRLPublishDisabled) // is publishing enabled?
  1309. {
  1310. fRebuildCRL = TRUE; // ENABLED, ready to go!
  1311. }
  1312. else
  1313. {
  1314. DBGPRINT((
  1315. DBG_SS_CERTSRV,
  1316. "CRLPubWakeupEvent(tid=%d): Publishing disabled\n",
  1317. GetCurrentThreadId() ));
  1318. }
  1319. }
  1320. ftZero.dwLowDateTime = 0;
  1321. ftZero.dwHighDateTime = 0;
  1322. while (TRUE)
  1323. {
  1324. hr = CRLPublishCRLs(
  1325. fRebuildCRL,
  1326. fForceRepublish,
  1327. NULL, // pwszUserName
  1328. !fForceRepublish && // fDeltaOnly
  1329. !fBaseTrigger &&
  1330. !g_fDeltaCRLPublishDisabled &&
  1331. !fDeltaCRLPublishDisabledOld,
  1332. fShadowDelta,
  1333. ftZero,
  1334. &fSetRetryTimer,
  1335. &hrPublish);
  1336. if (S_OK == hr)
  1337. {
  1338. break;
  1339. }
  1340. _PrintError(hr, "CRLPublishCRLs");
  1341. if (!fForceRepublish || fRebuildCRL)
  1342. {
  1343. _leave; // give up
  1344. }
  1345. // We failed to republish existing CRLs after a database restore
  1346. // and recovery; generate new base and delta CRLs and publish them.
  1347. fRebuildCRL = TRUE;
  1348. }
  1349. _PrintIfError(hrPublish, "CRLPublishCRLs(hrPublish)");
  1350. // if we called CRLPublishCRLs, clear the manual event it'll trigger
  1351. ResetEvent(g_hCRLManualPublishEvent);
  1352. // how many ms until next publish? set dwMSTimeOut
  1353. if (g_fCRLPublishDisabled)
  1354. {
  1355. // if disabled, don't set timeout
  1356. dwMSTimeOut = INFINITE;
  1357. CONSOLEPRINT1((
  1358. DBG_SS_CERTSRV,
  1359. "CRL Publishing Disabled, TimeOut=INFINITE (%d ms)\n",
  1360. dwMSTimeOut));
  1361. }
  1362. else
  1363. {
  1364. DWORD dwMSTimeOutDelta;
  1365. WCHAR *pwszCRLType = NULL;
  1366. crlComputeTimeOutEx(
  1367. FALSE,
  1368. &ftCurrent,
  1369. &g_ftCRLNextPublish,
  1370. &dwMSTimeOut);
  1371. if (g_fDeltaCRLPublishDisabled)
  1372. {
  1373. pwszCRLType = L"Base";
  1374. }
  1375. else
  1376. {
  1377. crlComputeTimeOutEx(
  1378. TRUE,
  1379. &ftCurrent,
  1380. &g_ftDeltaCRLNextPublish,
  1381. &dwMSTimeOutDelta);
  1382. if (dwMSTimeOut > dwMSTimeOutDelta)
  1383. {
  1384. dwMSTimeOut = dwMSTimeOutDelta;
  1385. }
  1386. pwszCRLType = L"Base + Delta";
  1387. }
  1388. if (NULL != pwszCRLType)
  1389. {
  1390. LONGLONG ll;
  1391. WCHAR *pwszTimePeriod = NULL;
  1392. WCHAR awc[1];
  1393. ll = dwMSTimeOut;
  1394. ll *= CVT_BASE / 1000; // milliseconds to FILETIME Period
  1395. ll = -ll; // FILETIME Period must be negative
  1396. hr = myFileTimePeriodToWszTimePeriod(
  1397. (FILETIME const *) &ll,
  1398. TRUE, // fExact
  1399. &pwszTimePeriod);
  1400. _PrintIfError(hr, "myFileTimePeriodToWszTimePeriod");
  1401. if (S_OK != hr)
  1402. {
  1403. awc[0] = L'\0';
  1404. pwszTimePeriod = awc;
  1405. }
  1406. CONSOLEPRINT3((
  1407. DBG_SS_CERTSRV,
  1408. "%ws CRL Publishing Enabled, TimeOut=%ds, %ws\n",
  1409. pwszCRLType,
  1410. dwMSTimeOut/1000,
  1411. pwszTimePeriod));
  1412. if (NULL != pwszTimePeriod && awc != pwszTimePeriod)
  1413. {
  1414. LocalFree(pwszTimePeriod);
  1415. }
  1416. }
  1417. }
  1418. // if we need to retry, wait no longer than the retry period
  1419. if (fSetRetryTimer)
  1420. {
  1421. if (dwMSTimeOut > CERTSRV_CRLPUB_RETRY_SECONDS * 1000)
  1422. {
  1423. dwMSTimeOut = CERTSRV_CRLPUB_RETRY_SECONDS * 1000;
  1424. CONSOLEPRINT1((
  1425. DBG_SS_CERTSRV,
  1426. "CRL Publishing periodic retry, TimeOut=%ds\n",
  1427. dwMSTimeOut/1000));
  1428. }
  1429. }
  1430. hr = S_OK;
  1431. }
  1432. __except(hr = myHEXCEPTIONCODE(), EXCEPTION_EXECUTE_HANDLER)
  1433. {
  1434. _PrintError(hr, "Exception");
  1435. }
  1436. error:
  1437. *pdwMSTimeOut = dwMSTimeOut;
  1438. CertSrvExitServer(State);
  1439. return(hr);
  1440. }
  1441. HRESULT
  1442. WriteToLockedFile(
  1443. IN BYTE const *pbEncoded,
  1444. IN DWORD cbEncoded,
  1445. IN LPCWSTR szFileDir,
  1446. IN LPCWSTR szFile)
  1447. {
  1448. HRESULT hr;
  1449. WCHAR wszTmpPrepFile[MAX_PATH];
  1450. WCHAR wszTmpInUseFile[MAX_PATH];
  1451. BYTE *pbData = NULL;
  1452. DWORD cbData;
  1453. // According to JohnL, the best way to do this is to gen a temp
  1454. // file name, rename the existing file to that, then delete it.
  1455. //
  1456. // Logic:
  1457. // create unique preparation filename
  1458. // write new data to prep file
  1459. // create unique destination filename for old file (possibly locked)
  1460. // move old file to destination filename
  1461. // move prep file to (vacated) file name
  1462. // delete old file from destination filename
  1463. hr = DecodeFileW(szFile, &pbData, &cbData, CRYPT_STRING_BINARY);
  1464. if (S_OK == hr &&
  1465. cbEncoded == cbData &&
  1466. 0 == memcmp(pbData, pbEncoded, cbData))
  1467. {
  1468. CSASSERT(S_OK == hr);
  1469. goto error; // already written, do nothing
  1470. }
  1471. // create a prep file
  1472. if (0 == GetTempFileName(szFileDir, L"pre", 0, wszTmpPrepFile))
  1473. {
  1474. hr = myHLastError();
  1475. _JumpError(hr, error, "GetTempFileName");
  1476. }
  1477. // write file to prep area
  1478. hr = EncodeToFileW(
  1479. wszTmpPrepFile,
  1480. pbEncoded,
  1481. cbEncoded,
  1482. DECF_FORCEOVERWRITE | CRYPT_STRING_BINARY);
  1483. _JumpIfError(hr, error, "EncodeToFileW");
  1484. if (0 == GetTempFileName(szFileDir, L"crl", 0, wszTmpInUseFile))
  1485. {
  1486. hr = myHLastError();
  1487. _JumpError(hr, error, "GetTempFileName");
  1488. }
  1489. // move old to "in use" file (empty file already exists from
  1490. // GetTempFileName call) may not exist, so don't bother checking status
  1491. MoveFileEx(
  1492. szFile,
  1493. wszTmpInUseFile,
  1494. MOVEFILE_WRITE_THROUGH | MOVEFILE_REPLACE_EXISTING);
  1495. // move prepared file to current file
  1496. if (!MoveFileEx(wszTmpPrepFile, szFile, MOVEFILE_WRITE_THROUGH))
  1497. {
  1498. hr = myHLastError();
  1499. _JumpError(hr, error, "MoveFileEx");
  1500. }
  1501. // The "in use" file may not exist, so don't bother checking status.
  1502. DeleteFile(wszTmpInUseFile);
  1503. hr = S_OK;
  1504. error:
  1505. if (NULL != pbData)
  1506. {
  1507. LocalFree(pbData);
  1508. }
  1509. return(hr);
  1510. }
  1511. WCHAR const g_wszPropCRLNumber[] = wszPROPCRLNUMBER;
  1512. WCHAR const g_wszPropCRLMinBase[] = wszPROPCRLMINBASE;
  1513. WCHAR const g_wszPropCRLNameId[] = wszPROPCRLNAMEID;
  1514. WCHAR const g_wszPropCRLCount[] = wszPROPCRLCOUNT;
  1515. WCHAR const g_wszPropCRLThisUpdateDate[] = wszPROPCRLTHISUPDATE;
  1516. WCHAR const g_wszPropCRLNextUpdateDate[] = wszPROPCRLNEXTUPDATE;
  1517. WCHAR const g_wszPropCRLThisPublishDate[] = wszPROPCRLTHISPUBLISH;
  1518. WCHAR const g_wszPropCRLNextPublishDate[] = wszPROPCRLNEXTPUBLISH;
  1519. WCHAR const g_wszPropCRLEffectiveDate[] = wszPROPCRLEFFECTIVE;
  1520. WCHAR const g_wszPropCRLPropagationCompleteDate[] = wszPROPCRLPROPAGATIONCOMPLETE;
  1521. WCHAR const g_wszPropCRLLastPublished[] = wszPROPCRLLASTPUBLISHED;
  1522. WCHAR const g_wszPropCRLPublishAttempts[] = wszPROPCRLPUBLISHATTEMPTS;
  1523. WCHAR const g_wszPropCRLPublishFlags[] = wszPROPCRLPUBLISHFLAGS;
  1524. WCHAR const g_wszPropCRLPublishStatusCode[] = wszPROPCRLPUBLISHSTATUSCODE;
  1525. WCHAR const g_wszPropCRLPublishError[] = wszPROPCRLPUBLISHERROR;
  1526. WCHAR const g_wszPropCRLRawCRL[] = wszPROPCRLRAWCRL;
  1527. HRESULT
  1528. crlWriteCRLToDB(
  1529. IN DWORD CRLNumber,
  1530. IN DWORD CRLMinBase, // 0 implies base CRL
  1531. OPTIONAL IN WCHAR const *pwszUserName, // else timer thread
  1532. IN BOOL fShadowDelta, // empty delta CRL with new MinBaseCRL
  1533. IN DWORD CRLNameId,
  1534. IN DWORD CRLCount,
  1535. IN FILETIME const *pftThisUpdate,
  1536. IN FILETIME const *pftNextUpdate,
  1537. IN FILETIME const *pftThisPublish,
  1538. IN FILETIME const *pftNextPublish,
  1539. OPTIONAL IN FILETIME const *pftQuery,
  1540. IN FILETIME const *pftPropagationComplete,
  1541. OPTIONAL IN BYTE const *pbCRL,
  1542. IN DWORD cbCRL,
  1543. OUT DWORD *pdwRowId)
  1544. {
  1545. HRESULT hr;
  1546. ICertDBRow *prow = NULL;
  1547. DWORD CRLPublishFlags;
  1548. BOOL fCommitted = FALSE;
  1549. *pdwRowId = 0;
  1550. // Create a new CRL table entry
  1551. hr = g_pCertDB->OpenRow(
  1552. PROPTABLE_CRL,
  1553. 0,
  1554. NULL,
  1555. &prow);
  1556. _JumpIfError(hr, error, "OpenRow");
  1557. prow->GetRowId(pdwRowId);
  1558. hr = prow->SetProperty(
  1559. g_wszPropCRLNumber,
  1560. PROPTYPE_LONG | PROPCALLER_SERVER | PROPTABLE_CRL,
  1561. sizeof(CRLNumber),
  1562. (BYTE const *) &CRLNumber);
  1563. _JumpIfError(hr, error, "SetProperty");
  1564. hr = prow->SetProperty(
  1565. g_wszPropCRLMinBase,
  1566. PROPTYPE_LONG | PROPCALLER_SERVER | PROPTABLE_CRL,
  1567. sizeof(CRLMinBase),
  1568. (BYTE const *) &CRLMinBase);
  1569. _JumpIfError(hr, error, "SetProperty");
  1570. hr = prow->SetProperty(
  1571. g_wszPropCRLNameId,
  1572. PROPTYPE_LONG | PROPCALLER_SERVER | PROPTABLE_CRL,
  1573. sizeof(CRLNameId),
  1574. (BYTE const *) &CRLNameId);
  1575. _JumpIfError(hr, error, "SetProperty");
  1576. hr = prow->SetProperty(
  1577. g_wszPropCRLCount,
  1578. PROPTYPE_LONG | PROPCALLER_SERVER | PROPTABLE_CRL,
  1579. sizeof(CRLCount),
  1580. (BYTE const *) &CRLCount);
  1581. _JumpIfError(hr, error, "SetProperty");
  1582. hr = prow->SetProperty(
  1583. g_wszPropCRLThisUpdateDate,
  1584. PROPTYPE_DATE | PROPCALLER_SERVER | PROPTABLE_CRL,
  1585. sizeof(*pftThisUpdate),
  1586. (BYTE const *) pftThisUpdate);
  1587. _JumpIfError(hr, error, "SetProperty");
  1588. hr = prow->SetProperty(
  1589. g_wszPropCRLNextUpdateDate,
  1590. PROPTYPE_DATE | PROPCALLER_SERVER | PROPTABLE_CRL,
  1591. sizeof(*pftNextUpdate),
  1592. (BYTE const *) pftNextUpdate);
  1593. _JumpIfError(hr, error, "SetProperty");
  1594. hr = prow->SetProperty(
  1595. g_wszPropCRLThisPublishDate,
  1596. PROPTYPE_DATE | PROPCALLER_SERVER | PROPTABLE_CRL,
  1597. sizeof(*pftThisPublish),
  1598. (BYTE const *) pftThisPublish);
  1599. _JumpIfError(hr, error, "SetProperty");
  1600. hr = prow->SetProperty(
  1601. g_wszPropCRLNextPublishDate,
  1602. PROPTYPE_DATE | PROPCALLER_SERVER | PROPTABLE_CRL,
  1603. sizeof(*pftNextPublish),
  1604. (BYTE const *) pftNextPublish);
  1605. _JumpIfError(hr, error, "SetProperty");
  1606. if (NULL != pftQuery)
  1607. {
  1608. hr = prow->SetProperty(
  1609. g_wszPropCRLEffectiveDate,
  1610. PROPTYPE_DATE | PROPCALLER_SERVER | PROPTABLE_CRL,
  1611. sizeof(*pftQuery),
  1612. (BYTE const *) pftQuery);
  1613. _JumpIfError(hr, error, "SetProperty");
  1614. }
  1615. hr = prow->SetProperty(
  1616. g_wszPropCRLPropagationCompleteDate,
  1617. PROPTYPE_DATE | PROPCALLER_SERVER | PROPTABLE_CRL,
  1618. sizeof(*pftPropagationComplete),
  1619. (BYTE const *) pftPropagationComplete);
  1620. _JumpIfError(hr, error, "SetProperty");
  1621. CRLPublishFlags = 0 == CRLMinBase? CPF_BASE : CPF_DELTA;
  1622. if (fShadowDelta)
  1623. {
  1624. CRLPublishFlags |= CPF_SHADOW;
  1625. }
  1626. if (NULL != pwszUserName)
  1627. {
  1628. CRLPublishFlags |= CPF_MANUAL;
  1629. }
  1630. hr = prow->SetProperty(
  1631. g_wszPropCRLPublishFlags,
  1632. PROPTYPE_LONG | PROPCALLER_SERVER | PROPTABLE_CRL,
  1633. sizeof(CRLPublishFlags),
  1634. (BYTE const *) &CRLPublishFlags);
  1635. _JumpIfError(hr, error, "SetProperty");
  1636. hr = prow->SetProperty(
  1637. g_wszPropCRLRawCRL,
  1638. PROPTYPE_BINARY | PROPCALLER_SERVER | PROPTABLE_CRL,
  1639. cbCRL,
  1640. pbCRL);
  1641. _JumpIfError(hr, error, "SetProperty");
  1642. hr = prow->CommitTransaction(TRUE);
  1643. _JumpIfError(hr, error, "CommitTransaction");
  1644. fCommitted = TRUE;
  1645. error:
  1646. if (NULL != prow)
  1647. {
  1648. if (S_OK != hr && !fCommitted)
  1649. {
  1650. HRESULT hr2 = prow->CommitTransaction(FALSE);
  1651. _PrintIfError(hr2, "CommitTransaction");
  1652. }
  1653. prow->Release();
  1654. }
  1655. return(hr);
  1656. }
  1657. HRESULT
  1658. crlCombineCRLError(
  1659. IN ICertDBRow *prow,
  1660. OPTIONAL IN WCHAR const *pwszUserName, // else timer thread
  1661. OPTIONAL IN WCHAR const *pwszCRLError,
  1662. OUT WCHAR **ppwszCRLErrorNew)
  1663. {
  1664. HRESULT hr;
  1665. WCHAR *pwszCRLErrorOld = NULL;
  1666. WCHAR *pwszCRLErrorNew = NULL;
  1667. WCHAR *pwsz;
  1668. DWORD cwc;
  1669. DWORD cwc2;
  1670. *ppwszCRLErrorNew = NULL;
  1671. hr = PKCSGetProperty(
  1672. prow,
  1673. g_wszPropCRLPublishError,
  1674. PROPTYPE_STRING | PROPCALLER_SERVER | PROPTABLE_CRL,
  1675. NULL,
  1676. (BYTE **) &pwszCRLErrorOld);
  1677. _PrintIfError2(hr, "PKCSGetProperty", CERTSRV_E_PROPERTY_EMPTY);
  1678. cwc = 0;
  1679. if (NULL != pwszCRLErrorOld)
  1680. {
  1681. pwsz = wcsstr(pwszCRLErrorOld, L"\n\n");
  1682. if (NULL == pwsz)
  1683. {
  1684. pwsz = pwszCRLErrorOld;
  1685. }
  1686. *pwsz = L'\0';
  1687. cwc = wcslen(pwszCRLErrorOld);
  1688. if (0 != cwc)
  1689. {
  1690. cwc++; // newline separator
  1691. }
  1692. }
  1693. if (NULL != pwszUserName)
  1694. {
  1695. cwc2 = wcslen(g_pwszPublishedBy) + wcslen(pwszUserName);
  1696. cwc += cwc2;
  1697. }
  1698. else
  1699. {
  1700. cwc++;
  1701. }
  1702. cwc += 2; // double newline separator
  1703. if (NULL != pwszCRLError)
  1704. {
  1705. cwc += wcslen(pwszCRLError);
  1706. }
  1707. pwszCRLErrorNew = (WCHAR *) LocalAlloc(
  1708. LMEM_FIXED,
  1709. (cwc + 1) * sizeof(WCHAR));
  1710. if (NULL == pwszCRLErrorNew)
  1711. {
  1712. hr = E_OUTOFMEMORY;
  1713. _JumpError(hr, error, "LocalAlloc");
  1714. }
  1715. *pwszCRLErrorNew = L'\0';
  1716. if (NULL != pwszCRLErrorOld && L'\0' != *pwszCRLErrorOld)
  1717. {
  1718. wcscpy(pwszCRLErrorNew, pwszCRLErrorOld);
  1719. wcscat(pwszCRLErrorNew, L"\n");
  1720. }
  1721. if (NULL != pwszUserName)
  1722. {
  1723. pwsz = &pwszCRLErrorNew[wcslen(pwszCRLErrorNew)];
  1724. _snwprintf(pwsz, cwc2, g_pwszPublishedBy, pwszUserName);
  1725. }
  1726. else
  1727. {
  1728. wcscat(pwszCRLErrorNew, L"-");
  1729. }
  1730. wcscat(pwszCRLErrorNew, L"\n\n"); // double newline separator
  1731. if (NULL != pwszCRLError)
  1732. {
  1733. wcscat(pwszCRLErrorNew, pwszCRLError);
  1734. }
  1735. CSASSERT(wcslen(pwszCRLErrorNew) <= cwc);
  1736. CSASSERT(
  1737. wcslen(pwszCRLErrorNew) +
  1738. (NULL != pwszUserName? wcslen(L"%ws") : 0) == cwc);
  1739. *ppwszCRLErrorNew = pwszCRLErrorNew;
  1740. pwszCRLErrorNew = NULL;
  1741. hr = S_OK;
  1742. error:
  1743. if (NULL != pwszCRLErrorOld)
  1744. {
  1745. LocalFree(pwszCRLErrorOld);
  1746. }
  1747. if (NULL != pwszCRLErrorNew)
  1748. {
  1749. LocalFree(pwszCRLErrorNew);
  1750. }
  1751. return(hr);
  1752. }
  1753. HRESULT
  1754. crlUpdateCRLPublishStateInDB(
  1755. IN DWORD RowId,
  1756. IN FILETIME const *pftCurrent,
  1757. IN HRESULT hrCRLPublish,
  1758. IN DWORD CRLPublishFlags,
  1759. OPTIONAL IN WCHAR const *pwszUserName, // else timer thread
  1760. OPTIONAL IN WCHAR const *pwszCRLError)
  1761. {
  1762. HRESULT hr;
  1763. ICertDBRow *prow = NULL;
  1764. WCHAR *pwszCRLErrorNew = NULL;
  1765. DWORD cb;
  1766. DWORD dw;
  1767. BOOL fCommitted = FALSE;
  1768. hr = g_pCertDB->OpenRow(
  1769. PROPTABLE_CRL,
  1770. RowId,
  1771. NULL,
  1772. &prow);
  1773. _JumpIfError(hr, error, "OpenRow");
  1774. hr = prow->SetProperty(
  1775. g_wszPropCRLLastPublished,
  1776. PROPTYPE_DATE | PROPCALLER_SERVER | PROPTABLE_CRL,
  1777. sizeof(*pftCurrent),
  1778. (BYTE const *) pftCurrent);
  1779. _JumpIfError(hr, error, "SetProperty");
  1780. cb = sizeof(dw);
  1781. hr = prow->GetProperty(
  1782. g_wszPropCRLPublishAttempts,
  1783. PROPTYPE_LONG | PROPCALLER_SERVER | PROPTABLE_CRL,
  1784. &cb,
  1785. (BYTE *) &dw);
  1786. if (S_OK != hr)
  1787. {
  1788. dw = 0;
  1789. }
  1790. dw++;
  1791. hr = prow->SetProperty(
  1792. g_wszPropCRLPublishAttempts,
  1793. PROPTYPE_LONG | PROPCALLER_SERVER | PROPTABLE_CRL,
  1794. sizeof(dw),
  1795. (BYTE const *) &dw);
  1796. _JumpIfError(hr, error, "SetProperty");
  1797. cb = sizeof(dw);
  1798. hr = prow->GetProperty(
  1799. g_wszPropCRLPublishFlags,
  1800. PROPTYPE_LONG | PROPCALLER_SERVER | PROPTABLE_CRL,
  1801. &cb,
  1802. (BYTE *) &dw);
  1803. if (S_OK != hr)
  1804. {
  1805. dw = 0;
  1806. }
  1807. CRLPublishFlags |= (CPF_BASE | CPF_DELTA | CPF_SHADOW | CPF_MANUAL) & dw;
  1808. if (S_OK == hrCRLPublish)
  1809. {
  1810. CRLPublishFlags |= CPF_COMPLETE;
  1811. }
  1812. hr = prow->SetProperty(
  1813. g_wszPropCRLPublishFlags,
  1814. PROPTYPE_LONG | PROPCALLER_SERVER | PROPTABLE_CRL,
  1815. sizeof(CRLPublishFlags),
  1816. (BYTE const *) &CRLPublishFlags);
  1817. _JumpIfError(hr, error, "SetProperty");
  1818. // Always set error string property to clear out previous errors.
  1819. hr = prow->SetProperty(
  1820. g_wszPropCRLPublishStatusCode,
  1821. PROPTYPE_LONG | PROPCALLER_SERVER | PROPTABLE_CRL,
  1822. sizeof(hrCRLPublish),
  1823. (BYTE const *) &hrCRLPublish);
  1824. _JumpIfError(hr, error, "SetProperty");
  1825. hr = crlCombineCRLError(prow, pwszUserName, pwszCRLError, &pwszCRLErrorNew);
  1826. _JumpIfError(hr, error, "crlCombineCRLError");
  1827. hr = prow->SetProperty(
  1828. g_wszPropCRLPublishError,
  1829. PROPTYPE_STRING | PROPCALLER_SERVER | PROPTABLE_CRL,
  1830. NULL == pwszCRLErrorNew? 0 : MAXDWORD,
  1831. (BYTE const *) pwszCRLErrorNew);
  1832. _JumpIfError(hr, error, "SetProperty");
  1833. hr = prow->CommitTransaction(TRUE);
  1834. _JumpIfError(hr, error, "CommitTransaction");
  1835. fCommitted = TRUE;
  1836. error:
  1837. if (NULL != prow)
  1838. {
  1839. if (S_OK != hr && !fCommitted)
  1840. {
  1841. HRESULT hr2 = prow->CommitTransaction(FALSE);
  1842. _PrintIfError(hr2, "CommitTransaction");
  1843. }
  1844. prow->Release();
  1845. }
  1846. if (NULL != pwszCRLErrorNew)
  1847. {
  1848. LocalFree(pwszCRLErrorNew);
  1849. }
  1850. return(hr);
  1851. }
  1852. HRESULT
  1853. WriteCRLToDSAttribute(
  1854. IN WCHAR const *pwszCRLDN,
  1855. IN BOOL fDelta,
  1856. IN BYTE const *pbCRL,
  1857. IN DWORD cbCRL,
  1858. OUT WCHAR **ppwszError)
  1859. {
  1860. HRESULT hr;
  1861. DWORD ldaperr;
  1862. BOOL fRebind = FALSE;
  1863. LDAPMod crlmod;
  1864. struct berval crlberval;
  1865. struct berval *crlVals[2];
  1866. LDAPMod *mods[2];
  1867. while (TRUE)
  1868. {
  1869. if (NULL == g_pld)
  1870. {
  1871. hr = myRobustLdapBind(&g_pld, FALSE);
  1872. _JumpIfError(hr, error, "myRobustLdapBind");
  1873. }
  1874. mods[0] = &crlmod;
  1875. mods[1] = NULL;
  1876. crlmod.mod_op = LDAP_MOD_BVALUES | LDAP_MOD_REPLACE;
  1877. crlmod.mod_type = fDelta? wszDSDELTACRLATTRIBUTE : wszDSBASECRLATTRIBUTE;
  1878. crlmod.mod_bvalues = crlVals;
  1879. crlVals[0] = &crlberval;
  1880. crlVals[1] = NULL;
  1881. crlberval.bv_len = cbCRL;
  1882. crlberval.bv_val = (char *) pbCRL;
  1883. ldaperr = ldap_modify_ext_s(
  1884. g_pld,
  1885. const_cast<WCHAR *>(pwszCRLDN),
  1886. mods,
  1887. NULL,
  1888. NULL);
  1889. hr = myHLdapError(g_pld, ldaperr, ppwszError);
  1890. _PrintIfErrorStr(hr, "ldap_modify_ext_s", pwszCRLDN);
  1891. if (fRebind || S_OK == hr)
  1892. {
  1893. break;
  1894. }
  1895. if (!myLdapRebindRequired(ldaperr, g_pld))
  1896. {
  1897. _JumpErrorStr(hr, error, "ldap_modify_ext_s", pwszCRLDN);
  1898. }
  1899. fRebind = TRUE;
  1900. if (NULL != g_pld)
  1901. {
  1902. ldap_unbind(g_pld);
  1903. g_pld = NULL;
  1904. }
  1905. }
  1906. error:
  1907. return(hr);
  1908. }
  1909. HRESULT
  1910. crlParseURLPrefix(
  1911. IN WCHAR const *pwszIn,
  1912. IN DWORD cwcPrefix,
  1913. OUT WCHAR *pwcPrefix,
  1914. OUT WCHAR const **ppwszOut)
  1915. {
  1916. HRESULT hr;
  1917. WCHAR const *pwsz;
  1918. CSASSERT(6 <= cwcPrefix);
  1919. wcscpy(pwcPrefix, L"file:");
  1920. *ppwszOut = pwszIn;
  1921. if (L'\\' != pwszIn[0] || L'\\' != pwszIn[1])
  1922. {
  1923. pwsz = wcschr(pwszIn, L':');
  1924. if (NULL != pwsz)
  1925. {
  1926. DWORD cwc;
  1927. pwsz++;
  1928. cwc = SAFE_SUBTRACT_POINTERS(pwsz, pwszIn);
  1929. if (2 < cwc && cwc < cwcPrefix)
  1930. {
  1931. CopyMemory(pwcPrefix, pwszIn, cwc * sizeof(WCHAR));
  1932. pwcPrefix[cwc] = L'\0';
  1933. if (0 == lstrcmpi(pwcPrefix, L"file:") &&
  1934. L'/' == pwsz[0] &&
  1935. L'/' == pwsz[1])
  1936. {
  1937. pwsz += 2;
  1938. }
  1939. *ppwszOut = pwsz;
  1940. }
  1941. }
  1942. }
  1943. hr = S_OK;
  1944. //error:
  1945. return(hr);
  1946. }
  1947. VOID
  1948. crlLogError(
  1949. IN BOOL fDelta,
  1950. IN BOOL fLdapURL,
  1951. IN DWORD iKey,
  1952. IN WCHAR const *pwszURL,
  1953. IN WCHAR const *pwszError,
  1954. IN HRESULT hrPublish)
  1955. {
  1956. HRESULT hr;
  1957. WCHAR const *apwsz[6];
  1958. WORD cpwsz;
  1959. WCHAR wszKey[11 + 1];
  1960. WCHAR awchr[cwcHRESULTSTRING];
  1961. WCHAR const *pwszMessageText = NULL;
  1962. WCHAR *pwszHostName = NULL;
  1963. DWORD LogMsg;
  1964. if (fLdapURL && NULL != g_pld)
  1965. {
  1966. myLdapGetDSHostName(g_pld, &pwszHostName);
  1967. }
  1968. wsprintf(wszKey, L"%u", iKey);
  1969. pwszMessageText = myGetErrorMessageText(hrPublish, TRUE);
  1970. if (NULL == pwszMessageText)
  1971. {
  1972. pwszMessageText = myHResultToStringRaw(awchr, hrPublish);
  1973. }
  1974. cpwsz = 0;
  1975. apwsz[cpwsz++] = wszKey;
  1976. apwsz[cpwsz++] = pwszURL;
  1977. apwsz[cpwsz++] = pwszMessageText;
  1978. LogMsg = fDelta?
  1979. MSG_E_DELTA_CRL_PUBLICATION : MSG_E_BASE_CRL_PUBLICATION;
  1980. if (NULL != pwszHostName)
  1981. {
  1982. LogMsg = fDelta?
  1983. MSG_E_DELTA_CRL_PUBLICATION_HOST_NAME :
  1984. MSG_E_BASE_CRL_PUBLICATION_HOST_NAME;
  1985. }
  1986. else
  1987. {
  1988. pwszHostName = L"";
  1989. }
  1990. apwsz[cpwsz++] = pwszHostName;
  1991. apwsz[cpwsz++] = NULL != pwszError? L"\n" : L"";
  1992. apwsz[cpwsz++] = NULL != pwszError? pwszError : L"";
  1993. CSASSERT(ARRAYSIZE(apwsz) >= cpwsz);
  1994. if (CERTLOG_ERROR <= g_dwLogLevel)
  1995. {
  1996. hr = LogEvent(EVENTLOG_ERROR_TYPE, LogMsg, cpwsz, apwsz);
  1997. _PrintIfError(hr, "LogEvent");
  1998. }
  1999. //error:
  2000. if (NULL != pwszMessageText && awchr != pwszMessageText)
  2001. {
  2002. LocalFree(const_cast<WCHAR *>(pwszMessageText));
  2003. }
  2004. }
  2005. HRESULT
  2006. crlWriteCRLToURL(
  2007. IN BOOL fDelta,
  2008. IN BOOL iKey,
  2009. IN WCHAR const *pwszURL,
  2010. IN BYTE const *pbCRL,
  2011. IN DWORD cbCRL,
  2012. OUT DWORD *pPublishFlags)
  2013. {
  2014. HRESULT hr;
  2015. WCHAR *pwszDup = NULL;
  2016. WCHAR const *pwsz2;
  2017. WCHAR *pwszT;
  2018. WCHAR awcPrefix[6]; // file:/ftp:/http:/ldap: and trailing '\0'
  2019. DWORD ErrorFlags;
  2020. WCHAR *pwszError = NULL;
  2021. *pPublishFlags = 0;
  2022. ErrorFlags = CPF_BADURL_ERROR;
  2023. hr = crlParseURLPrefix(
  2024. pwszURL,
  2025. ARRAYSIZE(awcPrefix),
  2026. awcPrefix,
  2027. &pwsz2);
  2028. _JumpIfError(hr, error, "crlParseURLPrefix");
  2029. DBGPRINT((
  2030. DBG_SS_CERTSRV,
  2031. "crlWriteCRLToURL: \"%ws\" %ws\n",
  2032. awcPrefix,
  2033. pwsz2));
  2034. if (0 == lstrcmpi(awcPrefix, L"file:"))
  2035. {
  2036. ErrorFlags = CPF_FILE_ERROR;
  2037. hr = myDupString(pwsz2, &pwszDup);
  2038. _JumpIfError(hr, error, "myDupString");
  2039. pwszT = wcsrchr(pwszDup, L'\\');
  2040. if (NULL != pwszT)
  2041. {
  2042. *pwszT = L'\0'; // for dir path, remove "\filename.crl"
  2043. }
  2044. // tricky
  2045. hr = WriteToLockedFile(pbCRL, cbCRL, pwszDup, pwsz2);
  2046. _JumpIfError(hr, error, "WriteToLockedFile");
  2047. }
  2048. else if (0 == lstrcmpi(awcPrefix, L"ftp:"))
  2049. {
  2050. ErrorFlags = CPF_FTP_ERROR;
  2051. hr = HRESULT_FROM_WIN32(ERROR_BAD_PATHNAME);
  2052. _JumpError(hr, error, "Publish to ftp:");
  2053. }
  2054. else if (0 == lstrcmpi(awcPrefix, L"http:"))
  2055. {
  2056. ErrorFlags = CPF_HTTP_ERROR;
  2057. hr = HRESULT_FROM_WIN32(ERROR_BAD_PATHNAME);
  2058. _JumpError(hr, error, "Publish to http:");
  2059. }
  2060. else if (0 == lstrcmpi(awcPrefix, L"ldap:"))
  2061. {
  2062. ErrorFlags = CPF_LDAP_ERROR;
  2063. while (L'/' == *pwsz2)
  2064. {
  2065. pwsz2++;
  2066. }
  2067. hr = myDupString(pwsz2, &pwszDup);
  2068. _JumpIfError(hr, error, "myDupString");
  2069. pwszT = wcschr(pwszDup, L'?');
  2070. if (NULL != pwszT)
  2071. {
  2072. *pwszT = L'\0';
  2073. }
  2074. hr = WriteCRLToDSAttribute(pwszDup, fDelta, pbCRL, cbCRL, &pwszError);
  2075. _JumpIfError(hr, error, "WriteCRLToDSAttribute");
  2076. }
  2077. else
  2078. {
  2079. ErrorFlags = CPF_BADURL_ERROR;
  2080. hr = HRESULT_FROM_WIN32(ERROR_BAD_PATHNAME);
  2081. _JumpError(hr, error, "Publish to unknown URL type");
  2082. }
  2083. CSASSERT(S_OK == hr);
  2084. error:
  2085. if (S_OK != hr)
  2086. {
  2087. *pPublishFlags = ErrorFlags;
  2088. crlLogError(
  2089. fDelta,
  2090. CPF_LDAP_ERROR == ErrorFlags,
  2091. iKey,
  2092. pwszURL,
  2093. pwszError,
  2094. hr);
  2095. }
  2096. if (NULL != pwszError)
  2097. {
  2098. LocalFree(pwszError);
  2099. }
  2100. if (NULL != pwszDup)
  2101. {
  2102. LocalFree(pwszDup);
  2103. }
  2104. return(hr);
  2105. }
  2106. HRESULT
  2107. crlWriteCRLToURLList(
  2108. IN BOOL fDelta,
  2109. IN DWORD iKey,
  2110. IN WCHAR const * const *papwszURLs,
  2111. IN BYTE const *pbCRL,
  2112. IN DWORD cbCRL,
  2113. IN OUT DWORD *pCRLPublishFlags,
  2114. OUT WCHAR **ppwszCRLError)
  2115. {
  2116. HRESULT hr = S_OK;
  2117. HRESULT hr2;
  2118. WCHAR *pwszCRLError = NULL;
  2119. DWORD PublishFlags;
  2120. *ppwszCRLError = NULL;
  2121. // publish this CRL in multiple places
  2122. if (NULL != papwszURLs)
  2123. {
  2124. WCHAR const * const *ppwsz;
  2125. for (ppwsz = papwszURLs; NULL != *ppwsz; ppwsz++)
  2126. {
  2127. PublishFlags = 0;
  2128. hr2 = crlWriteCRLToURL(
  2129. fDelta,
  2130. iKey,
  2131. *ppwsz,
  2132. pbCRL,
  2133. cbCRL,
  2134. &PublishFlags);
  2135. *pCRLPublishFlags |= PublishFlags;
  2136. if (S_OK != hr2)
  2137. {
  2138. DWORD cwc;
  2139. WCHAR *pwsz;
  2140. if (S_OK == hr)
  2141. {
  2142. hr = hr2; // Save first error
  2143. }
  2144. _PrintError(hr2, "crlWriteCRLToURL");
  2145. cwc = wcslen(*ppwsz) + 1;
  2146. if (NULL != pwszCRLError)
  2147. {
  2148. cwc += wcslen(pwszCRLError) + 1;
  2149. }
  2150. pwsz = (WCHAR *) LocalAlloc(LMEM_FIXED, cwc * sizeof(WCHAR));
  2151. if (NULL == pwsz)
  2152. {
  2153. hr2 = E_OUTOFMEMORY;
  2154. _PrintError(hr2, "LocalAlloc");
  2155. if (S_OK == hr)
  2156. {
  2157. hr = hr2; // Save first error
  2158. }
  2159. }
  2160. else
  2161. {
  2162. pwsz[0] = L'\0';
  2163. if (NULL != pwszCRLError)
  2164. {
  2165. wcscpy(pwsz, pwszCRLError);
  2166. wcscat(pwsz, L"\n");
  2167. LocalFree(pwszCRLError);
  2168. }
  2169. wcscat(pwsz, *ppwsz);
  2170. pwszCRLError = pwsz;
  2171. }
  2172. }
  2173. }
  2174. }
  2175. *ppwszCRLError = pwszCRLError;
  2176. pwszCRLError = NULL;
  2177. //error:
  2178. if (NULL != pwszCRLError)
  2179. {
  2180. LocalFree(pwszCRLError);
  2181. }
  2182. return(hr);
  2183. }
  2184. HRESULT
  2185. crlIsDeltaCRL(
  2186. IN CRL_CONTEXT const *pCRL,
  2187. OUT BOOL *pfIsDeltaCRL)
  2188. {
  2189. HRESULT hr;
  2190. CERT_EXTENSION *pExt;
  2191. *pfIsDeltaCRL = FALSE;
  2192. pExt = CertFindExtension(
  2193. szOID_DELTA_CRL_INDICATOR,
  2194. pCRL->pCrlInfo->cExtension,
  2195. pCRL->pCrlInfo->rgExtension);
  2196. if (NULL != pExt)
  2197. {
  2198. *pfIsDeltaCRL = TRUE;
  2199. }
  2200. hr = S_OK;
  2201. //error:
  2202. return(hr);
  2203. }
  2204. HRESULT
  2205. crlWriteCRLToCAStore(
  2206. IN BOOL fDelta,
  2207. IN DWORD iKey,
  2208. IN BYTE const *pbCRL,
  2209. IN DWORD cbCRL,
  2210. IN CERT_CONTEXT const *pccCA)
  2211. {
  2212. HRESULT hr;
  2213. HCERTSTORE hStore = NULL;
  2214. CRL_CONTEXT const *pCRLStore = NULL;
  2215. CRL_CONTEXT const *pCRLNew = NULL;
  2216. BOOL fFound = FALSE;
  2217. hStore = CertOpenStore(
  2218. CERT_STORE_PROV_SYSTEM_W,
  2219. X509_ASN_ENCODING,
  2220. NULL, // hProv
  2221. CERT_SYSTEM_STORE_LOCAL_MACHINE,
  2222. wszCA_CERTSTORE);
  2223. if (NULL == hStore)
  2224. {
  2225. hr = myHLastError();
  2226. _JumpError(hr, error, "CertOpenStore");
  2227. }
  2228. while (TRUE)
  2229. {
  2230. DWORD dwCryptFlags;
  2231. BOOL fIsDeltaCRL;
  2232. CRL_CONTEXT const *pCRL;
  2233. dwCryptFlags = CERT_STORE_SIGNATURE_FLAG;
  2234. pCRLStore = CertGetCRLFromStore(
  2235. hStore,
  2236. pccCA,
  2237. pCRLStore,
  2238. &dwCryptFlags);
  2239. if (NULL == pCRLStore)
  2240. {
  2241. break;
  2242. }
  2243. // delete this CRL from the store ONLY if the CRL signature matches
  2244. // this CA context's public key
  2245. if (0 != dwCryptFlags)
  2246. {
  2247. continue; // no match -- skip
  2248. }
  2249. hr = crlIsDeltaCRL(pCRLStore, &fIsDeltaCRL);
  2250. _JumpIfError(hr, error, "crlIsDeltaCRL");
  2251. if (fIsDeltaCRL)
  2252. {
  2253. if (!fDelta)
  2254. {
  2255. continue; // no match -- skip Delta CRLs
  2256. }
  2257. }
  2258. else
  2259. {
  2260. if (fDelta)
  2261. {
  2262. continue; // no match -- skip Base CRLs
  2263. }
  2264. }
  2265. // See if it has already been published
  2266. if (cbCRL == pCRLStore->cbCrlEncoded &&
  2267. 0 == memcmp(pbCRL, pCRLStore->pbCrlEncoded, cbCRL))
  2268. {
  2269. fFound = TRUE;
  2270. continue; // exact match -- already published
  2271. }
  2272. pCRL = CertDuplicateCRLContext(pCRLStore);
  2273. if (!CertDeleteCRLFromStore(pCRL))
  2274. {
  2275. hr = myHLastError();
  2276. _JumpError(hr, error, "CertDeleteCRLFromStore");
  2277. }
  2278. }
  2279. if (!fFound)
  2280. {
  2281. pCRLNew = CertCreateCRLContext(X509_ASN_ENCODING, pbCRL, cbCRL);
  2282. if (NULL == pCRLNew)
  2283. {
  2284. hr = myHLastError();
  2285. _JumpError(hr, error, "CertCreateCRLContext");
  2286. }
  2287. if (!CertAddCRLContextToStore(
  2288. hStore,
  2289. pCRLNew,
  2290. CERT_STORE_ADD_ALWAYS,
  2291. NULL))
  2292. {
  2293. hr = myHLastError();
  2294. _JumpError(hr, error, "CertAddCRLContextToStore");
  2295. }
  2296. }
  2297. hr = S_OK;
  2298. error:
  2299. if (S_OK != hr)
  2300. {
  2301. crlLogError(fDelta, FALSE, iKey, g_pwszIntermediateCAStore, NULL, hr);
  2302. }
  2303. if (NULL != pCRLNew)
  2304. {
  2305. CertFreeCRLContext(pCRLNew);
  2306. }
  2307. if (NULL != pCRLStore)
  2308. {
  2309. CertFreeCRLContext(pCRLStore);
  2310. }
  2311. if (NULL != hStore)
  2312. {
  2313. CertCloseStore(hStore, CERT_CLOSE_STORE_CHECK_FLAG);
  2314. }
  2315. return(hr);
  2316. }
  2317. HRESULT
  2318. crlPublishGeneratedCRL(
  2319. IN DWORD RowId,
  2320. IN FILETIME const *pftCurrent,
  2321. OPTIONAL IN WCHAR const *pwszUserName, // else timer thread
  2322. IN BOOL fDelta,
  2323. IN DWORD iKey,
  2324. IN BYTE const *pbCRL,
  2325. IN DWORD cbCRL,
  2326. IN CACTX const *pCAContext,
  2327. OUT BOOL *pfRetryNeeded,
  2328. OUT HRESULT *phrCRLPublish)
  2329. {
  2330. HRESULT hr;
  2331. HRESULT hrCRLPublish;
  2332. DWORD CRLPublishFlags;
  2333. WCHAR *pwszCRLError = NULL;
  2334. *pfRetryNeeded = FALSE;
  2335. hrCRLPublish = S_OK;
  2336. CRLPublishFlags = 0;
  2337. hr = crlWriteCRLToCAStore(fDelta, iKey, pbCRL, cbCRL, pCAContext->pccCA);
  2338. if (S_OK != hr)
  2339. {
  2340. _PrintError(hr, "crlWriteCRLToCAStore");
  2341. hrCRLPublish = hr;
  2342. CRLPublishFlags |= CPF_CASTORE_ERROR;
  2343. }
  2344. hr = crlWriteCRLToURLList(
  2345. fDelta,
  2346. iKey,
  2347. fDelta?
  2348. pCAContext->papwszDeltaCRLFiles :
  2349. pCAContext->papwszCRLFiles,
  2350. pbCRL,
  2351. cbCRL,
  2352. &CRLPublishFlags,
  2353. &pwszCRLError);
  2354. if (S_OK != hr)
  2355. {
  2356. _PrintError(hr, "crlWriteCRLToURLList");
  2357. if (S_OK == hrCRLPublish)
  2358. {
  2359. hrCRLPublish = hr; // save first error
  2360. }
  2361. }
  2362. if (S_OK != hrCRLPublish)
  2363. {
  2364. *pfRetryNeeded = TRUE;
  2365. }
  2366. hr = crlUpdateCRLPublishStateInDB(
  2367. RowId,
  2368. pftCurrent,
  2369. hrCRLPublish,
  2370. CRLPublishFlags,
  2371. pwszUserName,
  2372. pwszCRLError);
  2373. _JumpIfError(hr, error, "crlUpdateCRLPublishStateInDB");
  2374. error:
  2375. *phrCRLPublish = hrCRLPublish;
  2376. if (NULL != pwszCRLError)
  2377. {
  2378. LocalFree(pwszCRLError);
  2379. }
  2380. return(hr);
  2381. }
  2382. HRESULT
  2383. crlSignAndSaveCRL(
  2384. IN DWORD CRLNumber,
  2385. IN DWORD CRLNumberBaseMin, // 0 implies Base CRL; else Delta CRL
  2386. OPTIONAL IN WCHAR const *pwszUserName, // else timer thread
  2387. IN BOOL fShadowDelta, // empty delta CRL with new MinBaseCRL
  2388. IN CACTX const *pCAContext,
  2389. IN DWORD cCRL,
  2390. IN CRL_ENTRY *aCRL,
  2391. IN FILETIME const *pftCurrent,
  2392. IN FILETIME const *pftThisUpdate, // includes skew
  2393. IN FILETIME const *pftNextUpdate, // includes skew & overlap
  2394. IN FILETIME const *pftThisPublish,
  2395. IN FILETIME const *pftNextPublish,
  2396. OPTIONAL IN FILETIME const *pftQuery,
  2397. IN FILETIME const *pftPropagationComplete,
  2398. OUT BOOL *pfRetryNeeded,
  2399. OUT HRESULT *phrCRLPublish)
  2400. {
  2401. HRESULT hr;
  2402. CRL_INFO CRLInfo;
  2403. DWORD i;
  2404. DWORD cb;
  2405. DWORD cbCRL;
  2406. BYTE *pbCrlEncoded = NULL;
  2407. BYTE *pbCRL = NULL;
  2408. #define CCRLEXT 6
  2409. CERT_EXTENSION aext[CCRLEXT];
  2410. BYTE *apbFree[CCRLEXT];
  2411. DWORD cpbFree = 0;
  2412. DWORD RowId;
  2413. *pfRetryNeeded = FALSE;
  2414. *phrCRLPublish = S_OK;
  2415. ZeroMemory(&CRLInfo, sizeof(CRLInfo));
  2416. CRLInfo.dwVersion = CRL_V2;
  2417. CRLInfo.SignatureAlgorithm.pszObjId = pCAContext->pszObjIdSignatureAlgorithm;
  2418. CRLInfo.Issuer.pbData = pCAContext->pccCA->pCertInfo->Subject.pbData;
  2419. CRLInfo.Issuer.cbData = pCAContext->pccCA->pCertInfo->Subject.cbData;
  2420. CRLInfo.ThisUpdate = *pftThisUpdate;
  2421. CRLInfo.NextUpdate = *pftNextUpdate;
  2422. CRLInfo.cCRLEntry = cCRL;
  2423. CRLInfo.rgCRLEntry = aCRL;
  2424. CRLInfo.cExtension = 0;
  2425. CRLInfo.rgExtension = aext;
  2426. ZeroMemory(aext, sizeof(aext));
  2427. if (NULL != pCAContext->KeyAuthority2CRL.pbData)
  2428. {
  2429. aext[CRLInfo.cExtension].pszObjId = szOID_AUTHORITY_KEY_IDENTIFIER2;
  2430. if (EDITF_ENABLEAKICRITICAL & g_CRLEditFlags)
  2431. {
  2432. aext[CRLInfo.cExtension].fCritical = TRUE;
  2433. }
  2434. aext[CRLInfo.cExtension].Value = pCAContext->KeyAuthority2CRL;
  2435. CRLInfo.cExtension++;
  2436. }
  2437. if (!myEncodeObject(
  2438. X509_ASN_ENCODING,
  2439. X509_INTEGER,
  2440. &pCAContext->NameId,
  2441. 0,
  2442. CERTLIB_USE_LOCALALLOC,
  2443. &aext[CRLInfo.cExtension].Value.pbData,
  2444. &aext[CRLInfo.cExtension].Value.cbData))
  2445. {
  2446. hr = myHLastError();
  2447. _JumpError(hr, error, "myEncodeObject");
  2448. }
  2449. aext[CRLInfo.cExtension].pszObjId = szOID_CERTSRV_CA_VERSION;
  2450. apbFree[cpbFree++] = aext[CRLInfo.cExtension].Value.pbData,
  2451. CRLInfo.cExtension++;
  2452. if (!myEncodeObject(
  2453. X509_ASN_ENCODING,
  2454. X509_INTEGER,
  2455. &CRLNumber,
  2456. 0,
  2457. CERTLIB_USE_LOCALALLOC,
  2458. &aext[CRLInfo.cExtension].Value.pbData,
  2459. &aext[CRLInfo.cExtension].Value.cbData))
  2460. {
  2461. hr = myHLastError();
  2462. _JumpError(hr, error, "myEncodeObject");
  2463. }
  2464. aext[CRLInfo.cExtension].pszObjId = szOID_CRL_NUMBER;
  2465. apbFree[cpbFree++] = aext[CRLInfo.cExtension].Value.pbData;
  2466. if ((CRLF_CRLNUMBER_CRITICAL & g_dwCRLFlags) && 0 == CRLNumberBaseMin)
  2467. {
  2468. aext[CRLInfo.cExtension].fCritical = TRUE;
  2469. }
  2470. CRLInfo.cExtension++;
  2471. // NextPublish is the earliest the client should look for a newer CRL.
  2472. if (!myEncodeObject(
  2473. X509_ASN_ENCODING,
  2474. X509_CHOICE_OF_TIME,
  2475. pftNextPublish,
  2476. 0,
  2477. CERTLIB_USE_LOCALALLOC,
  2478. &aext[CRLInfo.cExtension].Value.pbData,
  2479. &aext[CRLInfo.cExtension].Value.cbData))
  2480. {
  2481. hr = myHLastError();
  2482. _JumpError(hr, error, "myEncodeObject");
  2483. }
  2484. aext[CRLInfo.cExtension].pszObjId = szOID_CRL_NEXT_PUBLISH;
  2485. apbFree[cpbFree++] = aext[CRLInfo.cExtension].Value.pbData,
  2486. CRLInfo.cExtension++;
  2487. if (0 != CRLNumberBaseMin) // if Delta CRL
  2488. {
  2489. if (!myEncodeObject(
  2490. X509_ASN_ENCODING,
  2491. X509_INTEGER,
  2492. &CRLNumberBaseMin,
  2493. 0,
  2494. CERTLIB_USE_LOCALALLOC,
  2495. &aext[CRLInfo.cExtension].Value.pbData,
  2496. &aext[CRLInfo.cExtension].Value.cbData))
  2497. {
  2498. hr = myHLastError();
  2499. _JumpError(hr, error, "myEncodeObject");
  2500. }
  2501. aext[CRLInfo.cExtension].pszObjId = szOID_DELTA_CRL_INDICATOR;
  2502. aext[CRLInfo.cExtension].fCritical = TRUE;
  2503. apbFree[cpbFree++] = aext[CRLInfo.cExtension].Value.pbData,
  2504. CRLInfo.cExtension++;
  2505. // Add a CDP to base and delta CRLs to make it easier to manually
  2506. // publish an off-line CA's CRLs to the correct DS location.
  2507. if (NULL != pCAContext->CDPCRLDelta.pbData)
  2508. {
  2509. aext[CRLInfo.cExtension].pszObjId = szOID_CRL_SELF_CDP;
  2510. aext[CRLInfo.cExtension].Value = pCAContext->CDPCRLDelta;
  2511. CRLInfo.cExtension++;
  2512. }
  2513. }
  2514. else
  2515. {
  2516. // else if Base CRL (and if delta CRLs are enabled)
  2517. if (!g_fDeltaCRLPublishDisabled &&
  2518. NULL != pCAContext->CDPCRLFreshest.pbData)
  2519. {
  2520. aext[CRLInfo.cExtension].pszObjId = szOID_FRESHEST_CRL;
  2521. aext[CRLInfo.cExtension].Value = pCAContext->CDPCRLFreshest;
  2522. CRLInfo.cExtension++;
  2523. }
  2524. // Add a CDP to base and delta CRLs to make it easier to manually
  2525. // publish an off-line CA's CRLs to the correct DS location.
  2526. if (NULL != pCAContext->CDPCRLBase.pbData)
  2527. {
  2528. aext[CRLInfo.cExtension].pszObjId = szOID_CRL_SELF_CDP;
  2529. aext[CRLInfo.cExtension].Value = pCAContext->CDPCRLBase;
  2530. CRLInfo.cExtension++;
  2531. }
  2532. }
  2533. CSASSERT(ARRAYSIZE(aext) >= CRLInfo.cExtension);
  2534. if (!myEncodeObject(
  2535. X509_ASN_ENCODING,
  2536. X509_CERT_CRL_TO_BE_SIGNED,
  2537. &CRLInfo,
  2538. 0,
  2539. CERTLIB_USE_LOCALALLOC,
  2540. &pbCrlEncoded, // pbEncoded
  2541. &cb))
  2542. {
  2543. hr = myHLastError();
  2544. _JumpError(hr, error, "myEncodeObject");
  2545. }
  2546. hr = myEncodeSignedContent(
  2547. pCAContext->hProvCA,
  2548. X509_ASN_ENCODING,
  2549. pCAContext->pszObjIdSignatureAlgorithm,
  2550. pbCrlEncoded,
  2551. cb,
  2552. CERTLIB_USE_LOCALALLOC,
  2553. &pbCRL,
  2554. &cbCRL); // use LocalAlloc*
  2555. _JumpIfError(hr, error, "myEncodeSignedContent");
  2556. hr = crlWriteCRLToDB(
  2557. CRLNumber, // CRLNumber
  2558. CRLNumberBaseMin, // CRLMinBase: 0 implies Base CRL
  2559. pwszUserName,
  2560. fShadowDelta,
  2561. pCAContext->NameId, // CRLNameId
  2562. cCRL, // CRLCount
  2563. &CRLInfo.ThisUpdate, // pftThisUpdate
  2564. &CRLInfo.NextUpdate, // pftNextUpdate
  2565. pftThisPublish, // pftThisPublish
  2566. pftNextPublish, // pftNextPublish
  2567. pftQuery,
  2568. pftPropagationComplete,
  2569. pbCRL, // pbCRL
  2570. cbCRL, // cbCRL
  2571. &RowId);
  2572. _JumpIfError(hr, error, "crlWriteCRLToDB");
  2573. hr = crlPublishGeneratedCRL(
  2574. RowId,
  2575. pftCurrent,
  2576. pwszUserName,
  2577. 0 != CRLNumberBaseMin, // fDelta
  2578. pCAContext->iKey,
  2579. pbCRL, // pbCRL
  2580. cbCRL, // cbCRL
  2581. pCAContext,
  2582. pfRetryNeeded,
  2583. phrCRLPublish);
  2584. _JumpIfError(hr, error, "crlPublishGeneratedCRL");
  2585. error:
  2586. CSASSERT(ARRAYSIZE(aext) >= CRLInfo.cExtension);
  2587. CSASSERT(ARRAYSIZE(apbFree) >= cpbFree);
  2588. for (i = 0; i < cpbFree; i++)
  2589. {
  2590. CSASSERT(NULL != apbFree[i]);
  2591. LocalFree(apbFree[i]);
  2592. }
  2593. if (NULL != pbCrlEncoded)
  2594. {
  2595. LocalFree(pbCrlEncoded);
  2596. }
  2597. if (NULL != pbCRL)
  2598. {
  2599. LocalFree(pbCRL);
  2600. }
  2601. return(myHError(hr));
  2602. }
  2603. ///////////////////////////////////////////////////
  2604. // crlPublishCRLFromCAContext is called to build and save one CRL.
  2605. //
  2606. HRESULT
  2607. crlPublishCRLFromCAContext(
  2608. IN DWORD CRLNumber,
  2609. IN DWORD CRLNumberBaseMin, // 0 implies Base CRL; else Delta CRL
  2610. OPTIONAL IN WCHAR const *pwszUserName, // else timer thread
  2611. IN BOOL fShadowDelta, // empty delta CRL with new MinBaseCRL
  2612. IN CACTX const *pCAContext,
  2613. IN FILETIME const *pftCurrent,
  2614. IN FILETIME ftThisUpdate, // clamped by CA cert
  2615. IN OUT FILETIME *pftNextUpdate, // clamped by CA cert
  2616. OPTIONAL OUT BOOL *pfClamped,
  2617. OPTIONAL IN FILETIME const *pftQuery,
  2618. IN FILETIME const *pftThisPublish,
  2619. IN FILETIME const *pftNextPublish,
  2620. IN FILETIME const *pftLastPublishBase,
  2621. IN FILETIME const *pftPropagationComplete,
  2622. OUT BOOL *pfRetryNeeded,
  2623. OUT HRESULT *phrPublish)
  2624. {
  2625. HRESULT hr;
  2626. DWORD cCRL = 0;
  2627. CRL_ENTRY *aCRL = NULL;
  2628. VOID *pvBlockSerial = NULL;
  2629. CERT_INFO const *pCertInfo = pCAContext->pccCA->pCertInfo;
  2630. *pfRetryNeeded = FALSE;
  2631. *phrPublish = S_OK;
  2632. __try
  2633. {
  2634. if (!fShadowDelta)
  2635. {
  2636. hr = crlBuildCRLArray(
  2637. 0 != CRLNumberBaseMin, // fDelta
  2638. pftQuery,
  2639. pftThisPublish,
  2640. pftLastPublishBase,
  2641. pCAContext->iKey,
  2642. &cCRL,
  2643. &aCRL,
  2644. &pvBlockSerial);
  2645. _JumpIfError(hr, error, "crlBuildCRLArray");
  2646. }
  2647. // Ensure it is not before the CA certificate's start date.
  2648. if (0 > CompareFileTime(&ftThisUpdate, &pCertInfo->NotBefore))
  2649. {
  2650. // clamp
  2651. ftThisUpdate = pCertInfo->NotBefore;
  2652. }
  2653. // Ensure it is not after the CA certificate's end date.
  2654. if (NULL != pfClamped)
  2655. {
  2656. //init to FALSE
  2657. *pfClamped = FALSE;
  2658. }
  2659. if (0 == (CRLF_PUBLISH_EXPIRED_CERT_CRLS & g_dwCRLFlags) &&
  2660. 0 < CompareFileTime(pftNextUpdate, &pCertInfo->NotAfter))
  2661. {
  2662. // clamp
  2663. *pftNextUpdate = pCertInfo->NotAfter;
  2664. if (NULL != pfClamped)
  2665. {
  2666. *pfClamped = TRUE;
  2667. }
  2668. }
  2669. #ifdef DBG_CERTSRV_DEBUG_PRINT
  2670. {
  2671. WCHAR *pwszNow = NULL;
  2672. WCHAR *pwszQuery = NULL;
  2673. WCHAR *pwszThisUpdate = NULL;
  2674. WCHAR *pwszNextUpdate = NULL;
  2675. WCHAR const *pwszCRLType = 0 == CRLNumberBaseMin? L"Base" : L"Delta";
  2676. myGMTFileTimeToWszLocalTime(pftThisPublish, TRUE, &pwszNow);
  2677. if (NULL != pftQuery)
  2678. {
  2679. myGMTFileTimeToWszLocalTime(pftQuery, TRUE, &pwszQuery);
  2680. }
  2681. myGMTFileTimeToWszLocalTime(&ftThisUpdate, TRUE, &pwszThisUpdate);
  2682. myGMTFileTimeToWszLocalTime(pftNextUpdate, TRUE, &pwszNextUpdate);
  2683. DBGPRINT((
  2684. DBG_SS_ERROR | DBG_SS_CERTSRV,
  2685. "crlPublishCRLFromCAContext(tid=%d, CA Version=%u.%u): %ws CRL %u,%hs %u\n"
  2686. " %ws CRL Publishing now(%ws)\n"
  2687. " %ws CRL Query(%ws)\n"
  2688. " %ws CRL ThisUpdate(%ws)\n"
  2689. " %ws CRL NextUpdate(%ws)\n",
  2690. GetCurrentThreadId(),
  2691. pCAContext->iCert,
  2692. pCAContext->iKey,
  2693. pwszCRLType,
  2694. CRLNumber,
  2695. 0 == CRLNumberBaseMin? "" : " Min Base",
  2696. CRLNumberBaseMin,
  2697. pwszCRLType,
  2698. pwszNow,
  2699. pwszCRLType,
  2700. NULL != pftQuery? pwszQuery : L"None",
  2701. pwszCRLType,
  2702. pwszThisUpdate,
  2703. pwszCRLType,
  2704. pwszNextUpdate));
  2705. if (NULL != pwszNow)
  2706. {
  2707. LocalFree(pwszNow);
  2708. }
  2709. if (NULL != pwszQuery)
  2710. {
  2711. LocalFree(pwszQuery);
  2712. }
  2713. if (NULL != pwszThisUpdate)
  2714. {
  2715. LocalFree(pwszThisUpdate);
  2716. }
  2717. if (NULL != pwszNextUpdate)
  2718. {
  2719. LocalFree(pwszNextUpdate);
  2720. }
  2721. }
  2722. #endif //DBG_CERTSRV_DEBUG_PRINT
  2723. hr = CertSrvTestServerState();
  2724. _JumpIfError(hr, error, "CertSrvTestServerState");
  2725. hr = crlSignAndSaveCRL(
  2726. CRLNumber,
  2727. CRLNumberBaseMin,
  2728. pwszUserName,
  2729. fShadowDelta,
  2730. pCAContext,
  2731. cCRL,
  2732. aCRL,
  2733. pftCurrent,
  2734. &ftThisUpdate,
  2735. pftNextUpdate,
  2736. pftThisPublish, // - no skew or overlap
  2737. pftNextPublish, // no skew
  2738. pftQuery,
  2739. pftPropagationComplete,
  2740. pfRetryNeeded,
  2741. phrPublish);
  2742. _JumpIfError(hr, error, "crlSignAndSaveCRL");
  2743. CONSOLEPRINT4((
  2744. DBG_SS_CERTSRV,
  2745. "Published %hs CRL #%u for key %u.%u\n",
  2746. 0 == CRLNumberBaseMin? "Base" : "Delta",
  2747. CRLNumber,
  2748. pCAContext->iCert,
  2749. pCAContext->iKey));
  2750. CSASSERT(S_OK == hr);
  2751. }
  2752. __except(hr = myHEXCEPTIONCODE(), EXCEPTION_EXECUTE_HANDLER)
  2753. {
  2754. }
  2755. error:
  2756. crlFreeCRLArray(pvBlockSerial, aCRL);
  2757. CSASSERT(S_OK == hr || FAILED(hr));
  2758. return(hr);
  2759. }
  2760. DWORD g_aColCRLNumber[] = {
  2761. #define ICOL_CRLNUMBER 0
  2762. DTI_CRLTABLE | DTL_NUMBER,
  2763. };
  2764. HRESULT
  2765. crlGetNextCRLNumber(
  2766. OUT DWORD *pdwCRLNumber)
  2767. {
  2768. HRESULT hr;
  2769. CERTVIEWRESTRICTION acvr[1];
  2770. CERTVIEWRESTRICTION *pcvr;
  2771. IEnumCERTDBRESULTROW *pView = NULL;
  2772. DWORD Zero = 0;
  2773. CERTDBRESULTROW aResult[1];
  2774. CERTDBRESULTROW *pResult;
  2775. DWORD celtFetched;
  2776. BOOL fResultActive = FALSE;
  2777. *pdwCRLNumber = 1;
  2778. // Set up restrictions as follows:
  2779. pcvr = acvr;
  2780. // CRLNumber > 0 (indexed column)
  2781. pcvr->ColumnIndex = DTI_CRLTABLE | DTL_NUMBER;
  2782. pcvr->SeekOperator = CVR_SEEK_GT;
  2783. pcvr->SortOrder = CVR_SORT_DESCEND; // highest CRL Number first
  2784. pcvr->pbValue = (BYTE *) &Zero;
  2785. pcvr->cbValue = sizeof(Zero);
  2786. pcvr++;
  2787. CSASSERT(ARRAYSIZE(acvr) == SAFE_SUBTRACT_POINTERS(pcvr, acvr));
  2788. hr = g_pCertDB->OpenView(
  2789. ARRAYSIZE(acvr),
  2790. acvr,
  2791. ARRAYSIZE(g_aColCRLNumber),
  2792. g_aColCRLNumber,
  2793. 0, // no worker thread
  2794. &pView);
  2795. _JumpIfError(hr, error, "OpenView");
  2796. hr = pView->Next(ARRAYSIZE(aResult), aResult, &celtFetched);
  2797. if (S_FALSE == hr)
  2798. {
  2799. if (0 == celtFetched)
  2800. {
  2801. hr = S_OK;
  2802. goto error;
  2803. }
  2804. }
  2805. _JumpIfError(hr, error, "Next");
  2806. fResultActive = TRUE;
  2807. CSASSERT(ARRAYSIZE(aResult) == celtFetched);
  2808. pResult = &aResult[0];
  2809. CSASSERT(ARRAYSIZE(g_aColCRLNumber) == pResult->ccol);
  2810. CSASSERT(NULL != pResult->acol[ICOL_CRLNUMBER].pbValue);
  2811. CSASSERT(PROPTYPE_LONG == (PROPTYPE_MASK & pResult->acol[ICOL_CRLNUMBER].Type));
  2812. CSASSERT(sizeof(*pdwCRLNumber) == pResult->acol[ICOL_CRLNUMBER].cbValue);
  2813. *pdwCRLNumber = 1 + *(DWORD *) pResult->acol[ICOL_CRLNUMBER].pbValue;
  2814. hr = S_OK;
  2815. error:
  2816. if (NULL != pView)
  2817. {
  2818. if (fResultActive)
  2819. {
  2820. pView->ReleaseResultRow(celtFetched, aResult);
  2821. }
  2822. pView->Release();
  2823. }
  2824. DBGPRINT((
  2825. DBG_SS_CERTSRVI,
  2826. "crlGetNextCRLNumber -> %u\n",
  2827. *pdwCRLNumber));
  2828. return(hr);
  2829. }
  2830. #undef ICOL_CRLNUMBER
  2831. //+--------------------------------------------------------------------------
  2832. // crlGetBaseCRLInfo -- get database column data for the most recent Base CRL
  2833. //
  2834. //---------------------------------------------------------------------------
  2835. DWORD g_aColBaseCRLInfo[] = {
  2836. #define ICOLBI_CRLNUMBER 0
  2837. DTI_CRLTABLE | DTL_NUMBER,
  2838. #define ICOLBI_CRLTHISUPDATE 1
  2839. DTI_CRLTABLE | DTL_THISUPDATEDATE,
  2840. #define ICOLBI_CRLNEXTUPDATE 2
  2841. DTI_CRLTABLE | DTL_NEXTUPDATEDATE,
  2842. #define ICOLBI_CRLNAMEID 3
  2843. DTI_CRLTABLE | DTL_NAMEID,
  2844. };
  2845. HRESULT
  2846. crlGetBaseCRLInfo(
  2847. IN FILETIME const *pftCurrent,
  2848. IN BOOL fOldestUnexpiredBase, // else newest propagated CRL
  2849. OUT DWORD *pdwRowId,
  2850. OUT DWORD *pdwCRLNumber,
  2851. OUT FILETIME *pftThisUpdate)
  2852. {
  2853. HRESULT hr;
  2854. CERTVIEWRESTRICTION acvr[2];
  2855. CERTVIEWRESTRICTION *pcvr;
  2856. IEnumCERTDBRESULTROW *pView = NULL;
  2857. DWORD Zero = 0;
  2858. CERTDBRESULTROW aResult[1];
  2859. CERTDBRESULTROW *pResult;
  2860. DWORD celtFetched;
  2861. BOOL fResultActive = FALSE;
  2862. BOOL fSaveCRLInfo;
  2863. DWORD RowId = 0;
  2864. DWORD CRLNumber;
  2865. FILETIME ftThisUpdate;
  2866. FILETIME ftNextUpdate;
  2867. *pdwRowId = 0;
  2868. *pdwCRLNumber = 0;
  2869. pftThisUpdate->dwHighDateTime = 0;
  2870. pftThisUpdate->dwLowDateTime = 0;
  2871. if (CRLF_DELTA_USE_OLDEST_UNEXPIRED_BASE & g_dwCRLFlags)
  2872. {
  2873. fOldestUnexpiredBase = TRUE;
  2874. }
  2875. // Set up restrictions as follows:
  2876. pcvr = acvr;
  2877. if (fOldestUnexpiredBase)
  2878. {
  2879. // NextUpdate >= now
  2880. pcvr->ColumnIndex = DTI_CRLTABLE | DTL_NEXTUPDATEDATE;
  2881. pcvr->SeekOperator = CVR_SEEK_GE;
  2882. }
  2883. else // else newest propagated CRL
  2884. {
  2885. // PropagationComplete < now
  2886. pcvr->ColumnIndex = DTI_CRLTABLE | DTL_PROPAGATIONCOMPLETEDATE;
  2887. pcvr->SeekOperator = CVR_SEEK_LT;
  2888. }
  2889. pcvr->SortOrder = CVR_SORT_DESCEND; // Newest CRL first
  2890. pcvr->pbValue = (BYTE *) pftCurrent;
  2891. pcvr->cbValue = sizeof(*pftCurrent);
  2892. pcvr++;
  2893. // CRL Minimum Base == 0 (to eliminate delta CRLs)
  2894. pcvr->ColumnIndex = DTI_CRLTABLE | DTL_MINBASE;
  2895. pcvr->SeekOperator = CVR_SEEK_EQ;
  2896. pcvr->SortOrder = CVR_SORT_NONE;
  2897. pcvr->pbValue = (BYTE *) &Zero;
  2898. pcvr->cbValue = sizeof(Zero);
  2899. pcvr++;
  2900. CSASSERT(ARRAYSIZE(acvr) == SAFE_SUBTRACT_POINTERS(pcvr, acvr));
  2901. hr = g_pCertDB->OpenView(
  2902. ARRAYSIZE(acvr),
  2903. acvr,
  2904. ARRAYSIZE(g_aColBaseCRLInfo),
  2905. g_aColBaseCRLInfo,
  2906. 0, // no worker thread
  2907. &pView);
  2908. _JumpIfError(hr, error, "OpenView");
  2909. while (0 == RowId || fOldestUnexpiredBase)
  2910. {
  2911. hr = pView->Next(ARRAYSIZE(aResult), aResult, &celtFetched);
  2912. if (S_FALSE == hr)
  2913. {
  2914. CSASSERT(0 == celtFetched);
  2915. if (0 != RowId)
  2916. {
  2917. break;
  2918. }
  2919. hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
  2920. }
  2921. _JumpIfError(hr, error, "Next: no matching base CRL");
  2922. fResultActive = TRUE;
  2923. CSASSERT(ARRAYSIZE(aResult) == celtFetched);
  2924. pResult = &aResult[0];
  2925. CSASSERT(ARRAYSIZE(g_aColBaseCRLInfo) == pResult->ccol);
  2926. CSASSERT(NULL != pResult->acol[ICOLBI_CRLNUMBER].pbValue);
  2927. CSASSERT(PROPTYPE_LONG == (PROPTYPE_MASK & pResult->acol[ICOLBI_CRLNUMBER].Type));
  2928. CSASSERT(sizeof(DWORD) == pResult->acol[ICOLBI_CRLNUMBER].cbValue);
  2929. CSASSERT(NULL != pResult->acol[ICOLBI_CRLTHISUPDATE].pbValue);
  2930. CSASSERT(PROPTYPE_DATE == (PROPTYPE_MASK & pResult->acol[ICOLBI_CRLTHISUPDATE].Type));
  2931. CSASSERT(sizeof(FILETIME) == pResult->acol[ICOLBI_CRLTHISUPDATE].cbValue);
  2932. CSASSERT(NULL != pResult->acol[ICOLBI_CRLNEXTUPDATE].pbValue);
  2933. CSASSERT(PROPTYPE_DATE == (PROPTYPE_MASK & pResult->acol[ICOLBI_CRLNEXTUPDATE].Type));
  2934. CSASSERT(sizeof(FILETIME) == pResult->acol[ICOLBI_CRLNEXTUPDATE].cbValue);
  2935. DBGPRINT((DBG_SS_CERTSRVI, "Query:RowId: %u\n", pResult->rowid));
  2936. DBGPRINT((DBG_SS_CERTSRVI, "Query:CRLNumber: %u\n", *(DWORD *) pResult->acol[ICOLBI_CRLNUMBER].pbValue));
  2937. DBGPRINT((DBG_SS_CERTSRVI, "Query:NameId: 0x%x\n", *(DWORD *) pResult->acol[ICOLBI_CRLNAMEID].pbValue));
  2938. DBGPRINTTIME(NULL, "Query:ThisUpdate", DPT_DATE, *(FILETIME *) pResult->acol[ICOLBI_CRLNEXTUPDATE].pbValue);
  2939. DBGPRINTTIME(NULL, "Query:NextUpdate", DPT_DATE, *(FILETIME *) pResult->acol[ICOLBI_CRLTHISUPDATE].pbValue);
  2940. if (0 == RowId)
  2941. {
  2942. // save first matching row info
  2943. fSaveCRLInfo = TRUE;
  2944. }
  2945. else
  2946. {
  2947. // save row info, if looking for
  2948. // oldest unexpired base & this CRL expires before the saved CRL
  2949. // +1 if first > second -- saved > this
  2950. CSASSERT(fOldestUnexpiredBase);
  2951. fSaveCRLInfo = 0 < CompareFileTime(
  2952. &ftNextUpdate,
  2953. (FILETIME *) pResult->acol[ICOLBI_CRLNEXTUPDATE].pbValue);
  2954. }
  2955. if (fSaveCRLInfo)
  2956. {
  2957. CRLNumber = *(DWORD *) pResult->acol[ICOLBI_CRLNUMBER].pbValue;
  2958. ftThisUpdate = *(FILETIME *) pResult->acol[ICOLBI_CRLTHISUPDATE].pbValue;
  2959. ftNextUpdate = *(FILETIME *) pResult->acol[ICOLBI_CRLNEXTUPDATE].pbValue;
  2960. RowId = pResult->rowid;
  2961. DBGPRINT((
  2962. DBG_SS_CERTSRVI,
  2963. "Query: SAVED RowId=%u CRLNumber=%u\n",
  2964. pResult->rowid,
  2965. CRLNumber));
  2966. DBGPRINTTIME(NULL, "ftThisUpdate", DPT_DATE, ftThisUpdate);
  2967. }
  2968. pView->ReleaseResultRow(celtFetched, aResult);
  2969. fResultActive = FALSE;
  2970. }
  2971. *pdwRowId = RowId;
  2972. *pdwCRLNumber = CRLNumber;
  2973. *pftThisUpdate = ftThisUpdate;
  2974. DBGPRINTTIME(NULL, "*pftThisUpdate", DPT_DATE, *pftThisUpdate);
  2975. DBGPRINTTIME(NULL, "ftNextUpdate", DPT_DATE, ftNextUpdate);
  2976. hr = S_OK;
  2977. error:
  2978. if (NULL != pView)
  2979. {
  2980. if (fResultActive)
  2981. {
  2982. pView->ReleaseResultRow(celtFetched, aResult);
  2983. }
  2984. pView->Release();
  2985. }
  2986. DBGPRINT((
  2987. DBG_SS_CERTSRV,
  2988. "crlGetBaseCRLInfo -> RowId=%u, CRL=%u\n",
  2989. *pdwRowId,
  2990. *pdwCRLNumber));
  2991. return(hr);
  2992. }
  2993. #undef ICOLBI_CRLNUMBER
  2994. #undef ICOLBI_CRLTHISUPDATE
  2995. #undef ICOLBI_CRLNEXTUPDATE
  2996. #undef ICOLBI_CRLNAMEID
  2997. DWORD g_aColRepublishCRLInfo[] = {
  2998. #define ICOLRI_CRLNUMBER 0
  2999. DTI_CRLTABLE | DTL_NUMBER,
  3000. #define ICOLRI_CRLNAMEID 1
  3001. DTI_CRLTABLE | DTL_NAMEID,
  3002. #define ICOLRI_CRLPUBLISHFLAGS 2
  3003. DTI_CRLTABLE | DTL_PUBLISHFLAGS,
  3004. #define ICOLRI_CRLTHISUPDATE 3
  3005. DTI_CRLTABLE | DTL_THISUPDATEDATE,
  3006. #define ICOLRI_CRLNEXTUPDATE 4
  3007. DTI_CRLTABLE | DTL_NEXTUPDATEDATE,
  3008. #define ICOLRI_CRLRAWCRL 5
  3009. DTI_CRLTABLE | DTL_RAWCRL,
  3010. };
  3011. HRESULT
  3012. crlGetRowIdAndCRL(
  3013. IN BOOL fDelta,
  3014. IN CACTX *pCAContext,
  3015. OUT DWORD *pdwRowId,
  3016. OUT DWORD *pcbCRL,
  3017. OPTIONAL OUT BYTE **ppbCRL,
  3018. OPTIONAL OUT DWORD *pdwCRLPublishFlags)
  3019. {
  3020. HRESULT hr;
  3021. CERTVIEWRESTRICTION acvr[4];
  3022. CERTVIEWRESTRICTION *pcvr;
  3023. IEnumCERTDBRESULTROW *pView = NULL;
  3024. DWORD Zero = 0;
  3025. DWORD NameIdMin;
  3026. DWORD NameIdMax;
  3027. CERTDBRESULTROW aResult[1];
  3028. CERTDBRESULTROW *pResult;
  3029. DWORD celtFetched;
  3030. BOOL fResultActive = FALSE;
  3031. FILETIME ftCurrent;
  3032. DWORD RowId = 0;
  3033. BYTE *pbCRL = NULL;
  3034. DWORD cbCRL;
  3035. *pdwRowId = 0;
  3036. *pcbCRL = 0;
  3037. if (NULL != ppbCRL)
  3038. {
  3039. *ppbCRL = NULL;
  3040. }
  3041. if (NULL != pdwCRLPublishFlags)
  3042. {
  3043. *pdwCRLPublishFlags = 0;
  3044. }
  3045. GetSystemTimeAsFileTime(&ftCurrent);
  3046. DBGPRINT((
  3047. DBG_SS_CERTSRVI,
  3048. "crlGetRowIdAndCRL(%ws, NameId=%x)\n",
  3049. fDelta? L"Delta" : L"Base",
  3050. pCAContext->NameId));
  3051. // Set up restrictions as follows:
  3052. pcvr = acvr;
  3053. // RowId > 0
  3054. pcvr->ColumnIndex = DTI_CRLTABLE | DTL_ROWID;
  3055. pcvr->SeekOperator = CVR_SEEK_GE;
  3056. pcvr->SortOrder = CVR_SORT_DESCEND; // Newest CRL first
  3057. pcvr->pbValue = (BYTE *) &Zero;
  3058. pcvr->cbValue = sizeof(Zero);
  3059. pcvr++;
  3060. if (fDelta)
  3061. {
  3062. // CRL Minimum Base > 0 (to eliminate base CRLs)
  3063. pcvr->SeekOperator = CVR_SEEK_GT;
  3064. }
  3065. else
  3066. {
  3067. // CRL Minimum Base == 0 (to eliminate delta CRLs)
  3068. pcvr->SeekOperator = CVR_SEEK_EQ;
  3069. }
  3070. pcvr->ColumnIndex = DTI_CRLTABLE | DTL_MINBASE;
  3071. pcvr->SortOrder = CVR_SORT_NONE;
  3072. pcvr->pbValue = (BYTE *) &Zero;
  3073. pcvr->cbValue = sizeof(Zero);
  3074. pcvr++;
  3075. // NameId >= MAKECANAMEID(iCert == 0, pCAContext->iKey)
  3076. NameIdMin = MAKECANAMEID(0, pCAContext->iKey);
  3077. pcvr->ColumnIndex = DTI_CRLTABLE | DTL_NAMEID;
  3078. pcvr->SeekOperator = CVR_SEEK_GE;
  3079. pcvr->SortOrder = CVR_SORT_NONE;
  3080. pcvr->pbValue = (BYTE *) &NameIdMin;
  3081. pcvr->cbValue = sizeof(NameIdMin);
  3082. pcvr++;
  3083. // NameId <= MAKECANAMEID(iCert == _16BITMASK, pCAContext->iKey)
  3084. NameIdMax = MAKECANAMEID(_16BITMASK, pCAContext->iKey);
  3085. pcvr->ColumnIndex = DTI_CRLTABLE | DTL_NAMEID;
  3086. pcvr->SeekOperator = CVR_SEEK_LE;
  3087. pcvr->SortOrder = CVR_SORT_NONE;
  3088. pcvr->pbValue = (BYTE *) &NameIdMax;
  3089. pcvr->cbValue = sizeof(NameIdMax);
  3090. pcvr++;
  3091. CSASSERT(ARRAYSIZE(acvr) == SAFE_SUBTRACT_POINTERS(pcvr, acvr));
  3092. hr = g_pCertDB->OpenView(
  3093. ARRAYSIZE(acvr),
  3094. acvr,
  3095. ((NULL != ppbCRL) ?
  3096. (DWORD) ARRAYSIZE(g_aColRepublishCRLInfo) :
  3097. (DWORD) ARRAYSIZE(g_aColRepublishCRLInfo) - 1 ), // explicitly describe expected return value
  3098. g_aColRepublishCRLInfo,
  3099. 0, // no worker thread
  3100. &pView);
  3101. _JumpIfError(hr, error, "OpenView");
  3102. while (0 == RowId)
  3103. {
  3104. hr = pView->Next(ARRAYSIZE(aResult), aResult, &celtFetched);
  3105. if (S_FALSE == hr)
  3106. {
  3107. CSASSERT(0 == celtFetched);
  3108. hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
  3109. }
  3110. _JumpIfErrorStr(
  3111. hr,
  3112. error,
  3113. "Next: no matching CRL",
  3114. fDelta? L"delta" : L"base");
  3115. fResultActive = TRUE;
  3116. CSASSERT(ARRAYSIZE(aResult) == celtFetched);
  3117. pResult = &aResult[0];
  3118. CSASSERT(ARRAYSIZE(g_aColRepublishCRLInfo) == pResult->ccol);
  3119. // verify CRLNumber data & schema
  3120. CSASSERT(NULL != pResult->acol[ICOLRI_CRLNUMBER].pbValue);
  3121. CSASSERT(PROPTYPE_LONG == (PROPTYPE_MASK & pResult->acol[ICOLRI_CRLNUMBER].Type));
  3122. CSASSERT(sizeof(DWORD) == pResult->acol[ICOLRI_CRLNUMBER].cbValue);
  3123. // verify ThisUpdate data & schema
  3124. CSASSERT(NULL != pResult->acol[ICOLRI_CRLTHISUPDATE].pbValue);
  3125. CSASSERT(PROPTYPE_DATE == (PROPTYPE_MASK & pResult->acol[ICOLRI_CRLTHISUPDATE].Type));
  3126. CSASSERT(sizeof(FILETIME) == pResult->acol[ICOLRI_CRLTHISUPDATE].cbValue);
  3127. // verify NextUpdate data & schema
  3128. CSASSERT(NULL != pResult->acol[ICOLRI_CRLNEXTUPDATE].pbValue);
  3129. CSASSERT(PROPTYPE_DATE == (PROPTYPE_MASK & pResult->acol[ICOLRI_CRLNEXTUPDATE].Type));
  3130. CSASSERT(sizeof(FILETIME) == pResult->acol[ICOLRI_CRLNEXTUPDATE].cbValue);
  3131. // verify RawCRL data & schema
  3132. if (NULL != ppbCRL)
  3133. {
  3134. CSASSERT(NULL != pResult->acol[ICOLRI_CRLRAWCRL].pbValue);
  3135. CSASSERT(PROPTYPE_BINARY == (PROPTYPE_MASK & pResult->acol[ICOLRI_CRLRAWCRL].Type));
  3136. }
  3137. // DBGPRINT query results
  3138. DBGPRINT((DBG_SS_CERTSRVI, "Query:RowId: %u\n", pResult->rowid));
  3139. DBGPRINT((DBG_SS_CERTSRVI, "Query:CRLNumber: %u\n", *(DWORD *) pResult->acol[ICOLRI_CRLNUMBER].pbValue));
  3140. DBGPRINT((DBG_SS_CERTSRVI, "Query:NameId: 0x%x\n", *(DWORD *) pResult->acol[ICOLRI_CRLNAMEID].pbValue));
  3141. DBGPRINTTIME(NULL, "Query:ThisUpdate", DPT_DATE, *(FILETIME *) pResult->acol[ICOLRI_CRLNEXTUPDATE].pbValue);
  3142. DBGPRINTTIME(NULL, "Query:NextUpdate", DPT_DATE, *(FILETIME *) pResult->acol[ICOLRI_CRLTHISUPDATE].pbValue);
  3143. if (NULL != ppbCRL)
  3144. {
  3145. DBGPRINT((DBG_SS_CERTSRVI, "Query:RawCRL: cb=%x\n", pResult->acol[ICOLRI_CRLRAWCRL].cbValue));
  3146. }
  3147. if (NULL != pResult->acol[ICOLRI_CRLPUBLISHFLAGS].pbValue)
  3148. {
  3149. DBGPRINT((
  3150. DBG_SS_CERTSRVI,
  3151. "Query:PublishFlags: f=%x\n",
  3152. *(DWORD *) pResult->acol[ICOLRI_CRLPUBLISHFLAGS].pbValue));
  3153. }
  3154. if (0 < CompareFileTime(
  3155. (FILETIME *) pResult->acol[ICOLRI_CRLTHISUPDATE].pbValue,
  3156. &ftCurrent))
  3157. {
  3158. _PrintError(E_INVALIDARG, "ThisUpdate in future");
  3159. }
  3160. if (0 > CompareFileTime(
  3161. (FILETIME *) pResult->acol[ICOLRI_CRLNEXTUPDATE].pbValue,
  3162. &ftCurrent))
  3163. {
  3164. hr = E_INVALIDARG;
  3165. _JumpError(hr, error, "NextUpdate in past");
  3166. }
  3167. CSASSERT(0 != pResult->rowid);
  3168. CSASSERT(NULL == pbCRL);
  3169. RowId = pResult->rowid;
  3170. if (NULL != ppbCRL)
  3171. {
  3172. cbCRL = pResult->acol[ICOLRI_CRLRAWCRL].cbValue;
  3173. pbCRL = (BYTE *) LocalAlloc(LMEM_FIXED, cbCRL);
  3174. if (NULL == pbCRL)
  3175. {
  3176. hr = E_OUTOFMEMORY;
  3177. _JumpError(hr, error, "LocalAlloc");
  3178. }
  3179. CopyMemory(
  3180. pbCRL,
  3181. pResult->acol[ICOLRI_CRLRAWCRL].pbValue,
  3182. cbCRL);
  3183. }
  3184. if (NULL != pdwCRLPublishFlags &&
  3185. NULL != pResult->acol[ICOLRI_CRLPUBLISHFLAGS].pbValue)
  3186. {
  3187. *pdwCRLPublishFlags = *(DWORD *) pResult->acol[ICOLRI_CRLPUBLISHFLAGS].pbValue;
  3188. }
  3189. DBGPRINT((DBG_SS_CERTSRVI, "Query:RowId: SAVED %u\n", pResult->rowid));
  3190. pView->ReleaseResultRow(celtFetched, aResult);
  3191. fResultActive = FALSE;
  3192. }
  3193. *pdwRowId = RowId;
  3194. if (NULL != ppbCRL)
  3195. {
  3196. *pcbCRL = cbCRL;
  3197. *ppbCRL = pbCRL;
  3198. pbCRL = NULL;
  3199. }
  3200. hr = S_OK;
  3201. error:
  3202. if (NULL != pbCRL)
  3203. {
  3204. LocalFree(pbCRL);
  3205. }
  3206. if (NULL != pView)
  3207. {
  3208. if (fResultActive)
  3209. {
  3210. pView->ReleaseResultRow(celtFetched, aResult);
  3211. }
  3212. pView->Release();
  3213. }
  3214. DBGPRINT((
  3215. DBG_SS_CERTSRVI,
  3216. "crlGetRowIdAndCRL(%ws) -> RowId=%u, cbCRL=%x, hr=%x\n",
  3217. fDelta? L"Delta" : L"Base",
  3218. *pdwRowId,
  3219. *pcbCRL,
  3220. hr));
  3221. return(hr);
  3222. }
  3223. #undef ICOLRI_CRLNUMBER
  3224. #undef ICOLRI_CRLNAMEID
  3225. #undef ICOLRI_CRLRAWCRL
  3226. #undef ICOLRI_CRLPUBLISHFLAGS
  3227. #undef ICOLRI_CRLTHISUPDATEDATE
  3228. #undef ICOLRI_CRLNEXTUPDATEDATE
  3229. HRESULT
  3230. crlRepublishCRLFromCAContext(
  3231. IN FILETIME const *pftCurrent,
  3232. OPTIONAL IN WCHAR const *pwszUserName, // else timer thread
  3233. IN BOOL fDelta,
  3234. IN CACTX *pCAContext,
  3235. OUT BOOL *pfRetryNeeded,
  3236. OUT HRESULT *phrPublish)
  3237. {
  3238. HRESULT hr;
  3239. DWORD cbCRL;
  3240. BYTE *pbCRL = NULL;
  3241. DWORD RowId;
  3242. *pfRetryNeeded = FALSE;
  3243. *phrPublish = S_OK;
  3244. hr = crlGetRowIdAndCRL(fDelta, pCAContext, &RowId, &cbCRL, &pbCRL, NULL);
  3245. _JumpIfError(hr, error, "crlGetRowIdAndCRL");
  3246. hr = crlPublishGeneratedCRL(
  3247. RowId,
  3248. pftCurrent,
  3249. pwszUserName,
  3250. fDelta,
  3251. pCAContext->iKey,
  3252. pbCRL,
  3253. cbCRL,
  3254. pCAContext,
  3255. pfRetryNeeded,
  3256. phrPublish);
  3257. _JumpIfError(hr, error, "crlPublishGeneratedCRL");
  3258. error:
  3259. if (NULL != pbCRL)
  3260. {
  3261. LocalFree(pbCRL);
  3262. }
  3263. return(hr);
  3264. }
  3265. HRESULT
  3266. crlRepublishExistingCRLs(
  3267. OPTIONAL IN WCHAR const *pwszUserName, // else timer thread
  3268. IN BOOL fDeltaOnly,
  3269. IN BOOL fShadowDelta,
  3270. IN FILETIME const *pftCurrent,
  3271. OUT BOOL *pfRetryNeeded,
  3272. OUT HRESULT *phrPublish)
  3273. {
  3274. HRESULT hr;
  3275. HRESULT hrPublish;
  3276. BOOL fRetryNeeded;
  3277. DWORD i;
  3278. *pfRetryNeeded = FALSE;
  3279. *phrPublish = S_OK;
  3280. // Walk global CA Context array from the back, and republish CRLs for
  3281. // each unique CA key. This causes the most current CRL to be published
  3282. // first, and the most current CA Cert context to be used to publish a CRL
  3283. // that covers multiple CA Certs due to key reuse.
  3284. for (i = g_cCACerts; i > 0; i--)
  3285. {
  3286. CACTX *pCAContext = &g_aCAContext[i - 1];
  3287. PKCSVerifyCAState(pCAContext);
  3288. if (CTXF_SKIPCRL & pCAContext->Flags)
  3289. {
  3290. continue;
  3291. }
  3292. if (!fDeltaOnly)
  3293. {
  3294. // Publish the most recent existing Base CRL
  3295. hr = CertSrvTestServerState();
  3296. _JumpIfError(hr, error, "CertSrvTestServerState");
  3297. hr = crlRepublishCRLFromCAContext(
  3298. pftCurrent,
  3299. pwszUserName,
  3300. FALSE, // fDelta
  3301. pCAContext,
  3302. &fRetryNeeded,
  3303. &hrPublish);
  3304. _JumpIfError(hr, error, "crlRepublishCRLFromCAContext");
  3305. if (fRetryNeeded)
  3306. {
  3307. *pfRetryNeeded = TRUE;
  3308. }
  3309. if (S_OK == *phrPublish)
  3310. {
  3311. *phrPublish = hrPublish;
  3312. }
  3313. }
  3314. if (!g_fDeltaCRLPublishDisabled || fShadowDelta)
  3315. {
  3316. // Publish the most recent existing Delta CRL
  3317. hr = CertSrvTestServerState();
  3318. _JumpIfError(hr, error, "CertSrvTestServerState");
  3319. hr = crlRepublishCRLFromCAContext(
  3320. pftCurrent,
  3321. pwszUserName,
  3322. TRUE, // fDelta
  3323. pCAContext,
  3324. &fRetryNeeded,
  3325. &hrPublish);
  3326. _JumpIfError(hr, error, "crlRepublishCRLFromCAContext");
  3327. if (fRetryNeeded)
  3328. {
  3329. *pfRetryNeeded = TRUE;
  3330. }
  3331. if (S_OK == *phrPublish)
  3332. {
  3333. *phrPublish = hrPublish;
  3334. }
  3335. }
  3336. }
  3337. hr = S_OK;
  3338. error:
  3339. return(hr);
  3340. }
  3341. HRESULT
  3342. crlComputeCRLTimes(
  3343. IN BOOL fDelta,
  3344. IN CSCRLPERIOD const *pccp,
  3345. IN FILETIME const *pftCurrent,
  3346. OUT FILETIME *pftThisUpdate, // ftCurrent - clock skew
  3347. IN OUT FILETIME *pftNextUpdate, // ftCurrent + period + overlap + skew
  3348. OUT FILETIME *pftNextPublish, // ftCurrent + CRL period
  3349. OUT FILETIME *pftPropagationComplete) // ftCurrent + overlap
  3350. {
  3351. HRESULT hr;
  3352. LONGLONG lldelta;
  3353. if (0 == pftNextUpdate->dwHighDateTime &&
  3354. 0 == pftNextUpdate->dwLowDateTime)
  3355. {
  3356. // Calculate expiration date for this CRL:
  3357. // ftCurrent + CRL period
  3358. DBGPRINTTIME(&fDelta, "*pftCurrent", DPT_DATE, *pftCurrent);
  3359. *pftNextUpdate = *pftCurrent;
  3360. DBGPRINT((
  3361. DBG_SS_CERTSRVI,
  3362. "+ count=%d, enum=%d\n",
  3363. pccp->lCRLPeriodCount,
  3364. pccp->enumCRLPeriod));
  3365. myMakeExprDateTime(
  3366. pftNextUpdate,
  3367. pccp->lCRLPeriodCount,
  3368. pccp->enumCRLPeriod);
  3369. DBGPRINTTIME(&fDelta, "*pftNextUpdate", DPT_DATE, *pftNextUpdate);
  3370. }
  3371. if (0 > CompareFileTime(pftNextUpdate, pftCurrent))
  3372. {
  3373. hr = E_INVALIDARG;
  3374. _JumpError(hr, error, "*pftNextUpdate in past");
  3375. }
  3376. *pftThisUpdate = *pftCurrent;
  3377. *pftNextPublish = *pftNextUpdate; // unmodified expiration time
  3378. // Subtract clock skew from the current time for ftThisUpdate time.
  3379. lldelta = g_dwClockSkewMinutes * CVT_MINUTES;
  3380. myAddToFileTime(pftThisUpdate, -lldelta * CVT_BASE);
  3381. // Add clock skew to ftNextUpdate,
  3382. // Add propogation overlap to ftNextUpdate.
  3383. lldelta += pccp->dwCRLOverlapMinutes * CVT_MINUTES;
  3384. myAddToFileTime(pftNextUpdate, lldelta * CVT_BASE);
  3385. *pftPropagationComplete = *pftCurrent;
  3386. lldelta = pccp->dwCRLOverlapMinutes * CVT_MINUTES;
  3387. myAddToFileTime(pftPropagationComplete, lldelta * CVT_BASE);
  3388. DBGPRINTTIME(&fDelta, "*pftCurrent", DPT_DATE, *pftCurrent);
  3389. DBGPRINTTIME(&fDelta, "*pftThisUpdate", DPT_DATE, *pftThisUpdate);
  3390. DBGPRINTTIME(&fDelta, "*pftNextUpdate", DPT_DATE, *pftNextUpdate);
  3391. DBGPRINTTIME(&fDelta, "*pftNextPublish", DPT_DATE, *pftNextPublish);
  3392. DBGPRINTTIME(&fDelta, "*pftPropagationComplete", DPT_DATE, *pftPropagationComplete);
  3393. hr = S_OK;
  3394. error:
  3395. return(hr);
  3396. }
  3397. HRESULT
  3398. crlGenerateAndPublishCRLs(
  3399. OPTIONAL IN WCHAR const *pwszUserName, // else timer thread
  3400. IN BOOL fDeltaOnly, // else base (and delta, if enabled)
  3401. IN BOOL fShadowDelta, // empty delta CRL with new MinBaseCRL
  3402. IN FILETIME const *pftCurrent,
  3403. IN FILETIME ftNextUpdateBase,
  3404. OUT DWORD *pdwRowIdBase,
  3405. OUT FILETIME *pftQueryDeltaDelete,
  3406. OUT BOOL *pfRetryNeeded,
  3407. OUT HRESULT *phrPublish)
  3408. {
  3409. HRESULT hr;
  3410. HRESULT hrPublish;
  3411. HKEY hkeyBase = NULL;
  3412. HKEY hkeyCA = NULL;
  3413. BOOL fClamped = FALSE;
  3414. DWORD CRLNumber;
  3415. DWORD CRLNumberBaseMin = 0;
  3416. DWORD i;
  3417. BOOL fRetryNeeded;
  3418. FILETIME ftNextUpdateDelta;
  3419. FILETIME ftThisUpdate;
  3420. FILETIME ftQueryDelta;
  3421. FILETIME *pftQueryDelta = &ftQueryDelta;
  3422. FILETIME ftLastPublishBase;
  3423. FILETIME ftNextPublishBase;
  3424. FILETIME ftNextUpdateBaseClamped = ftNextUpdateBase; // if clamped
  3425. FILETIME ftNextPublishDelta;
  3426. FILETIME ftPropagationCompleteBase;
  3427. FILETIME ftPropagationCompleteDelta;
  3428. CSCRLPERIOD ccpBase;
  3429. CSCRLPERIOD ccpDelta;
  3430. *pfRetryNeeded = FALSE;
  3431. pftQueryDeltaDelete->dwHighDateTime = 0;
  3432. pftQueryDeltaDelete->dwLowDateTime = 0;
  3433. *phrPublish = S_OK;
  3434. hr = crlGetNextCRLNumber(&CRLNumber);
  3435. _JumpIfError(hr, error, "crlGetNextCRLNumber");
  3436. hr = crlGetRegCRLPublishParams(
  3437. g_wszSanitizedName,
  3438. &ccpBase,
  3439. &ccpDelta);
  3440. _JumpIfError(hr, error, "crlGetRegCRLPublishParams");
  3441. // in manual publish case, 0 implies use default publish period
  3442. if (fDeltaOnly)
  3443. {
  3444. ftNextUpdateDelta = ftNextUpdateBase;
  3445. ZeroMemory(&ftNextUpdateBase, sizeof(ftNextUpdateBase));
  3446. }
  3447. else
  3448. {
  3449. ZeroMemory(&ftNextUpdateDelta, sizeof(ftNextUpdateDelta));
  3450. }
  3451. hr = crlComputeCRLTimes(
  3452. FALSE, // fDelta
  3453. &ccpBase, // IN
  3454. pftCurrent, // IN
  3455. &ftThisUpdate, // OUT includes skew
  3456. &ftNextUpdateBase, // INOUT includes overlap, skew
  3457. &ftNextPublishBase, // OUT unmodified expire time
  3458. &ftPropagationCompleteBase); // OUT includes overlap
  3459. _JumpIfError(hr, error, "crlComputeCRLTimes");
  3460. hr = crlComputeCRLTimes(
  3461. TRUE, // fDelta
  3462. fShadowDelta? &ccpBase : &ccpDelta, // IN
  3463. pftCurrent, // IN
  3464. &ftThisUpdate, // OUT includes skew
  3465. &ftNextUpdateDelta, // INOUT includes overlap, skew
  3466. &ftNextPublishDelta, // OUT unmodified expire time
  3467. &ftPropagationCompleteDelta); // OUT includes overlap
  3468. _JumpIfError(hr, error, "crlComputeCRLTimes");
  3469. // Set ftLastPublishBase to *pftCurrent minus lifetime of this base CRL,
  3470. // which is an educated guess for the ftThisPublish value for the last
  3471. // CRL issued.
  3472. ftLastPublishBase = *pftCurrent;
  3473. myAddToFileTime(
  3474. &ftLastPublishBase,
  3475. -mySubtractFileTimes(&ftNextPublishBase, pftCurrent));
  3476. // Clamp delta CRL to not end after base CRL.
  3477. if (0 < CompareFileTime(&ftNextPublishDelta, &ftNextPublishBase))
  3478. {
  3479. ftNextPublishDelta = ftNextPublishBase;
  3480. DBGPRINTTIME(NULL, "ftNextPublishDelta", DPT_DATE, ftNextPublishDelta);
  3481. }
  3482. if (0 < CompareFileTime(&ftNextUpdateDelta, &ftNextUpdateBase))
  3483. {
  3484. ftNextUpdateDelta = ftNextUpdateBase;
  3485. DBGPRINTTIME(NULL, "ftNextUpdateDelta", DPT_DATE, ftNextUpdateDelta);
  3486. }
  3487. if (0 < CompareFileTime(&ftPropagationCompleteDelta, &ftPropagationCompleteBase))
  3488. {
  3489. ftPropagationCompleteDelta = ftPropagationCompleteBase;
  3490. DBGPRINTTIME(NULL, "ftPropagationCompleteDelta", DPT_DATE, ftPropagationCompleteDelta);
  3491. }
  3492. if (!g_fDeltaCRLPublishDisabled || fShadowDelta)
  3493. {
  3494. hr = crlGetBaseCRLInfo(
  3495. pftCurrent,
  3496. FALSE, // try newest propagated CRL
  3497. pdwRowIdBase,
  3498. &CRLNumberBaseMin,
  3499. &ftQueryDelta);
  3500. _PrintIfError(hr, "crlGetBaseCRLInfo");
  3501. if (S_OK != hr)
  3502. {
  3503. hr = crlGetBaseCRLInfo(
  3504. pftCurrent,
  3505. TRUE, // try oldest unexpired CRL
  3506. pdwRowIdBase,
  3507. &CRLNumberBaseMin,
  3508. &ftQueryDelta);
  3509. _PrintIfError(hr, "crlGetBaseCRLInfo");
  3510. if (S_OK != hr)
  3511. {
  3512. CRLNumberBaseMin = 1;
  3513. if (!fDeltaOnly && 1 == CRLNumber)
  3514. {
  3515. ftQueryDelta = *pftCurrent; // empty CRL
  3516. }
  3517. else
  3518. {
  3519. pftQueryDelta = NULL; // full CRL
  3520. }
  3521. }
  3522. }
  3523. if (S_OK == hr)
  3524. {
  3525. // Delete old CRLs that expired at least one base CRL period prior
  3526. // to the "minimum" base crl ThisUpdate date found in the database.
  3527. *pftQueryDeltaDelete = ftQueryDelta;
  3528. myAddToFileTime(
  3529. pftQueryDeltaDelete,
  3530. -mySubtractFileTimes(&ftNextUpdateBase, &ftThisUpdate));
  3531. }
  3532. if (fShadowDelta)
  3533. {
  3534. CRLNumberBaseMin = CRLNumber;
  3535. }
  3536. CSASSERT(0 != CRLNumberBaseMin);
  3537. }
  3538. // Walk global CA Context array from the back, and generate a CRL for
  3539. // each unique CA key. This causes the most current CRL to be built
  3540. // first, and the most current CA Cert to be used to build a CRL that
  3541. // covers multiple CA Certs due to key reuse.
  3542. for (i = g_cCACerts; i > 0; i--)
  3543. {
  3544. CACTX *pCAContext = &g_aCAContext[i - 1];
  3545. PKCSVerifyCAState(pCAContext);
  3546. if (CTXF_SKIPCRL & pCAContext->Flags)
  3547. {
  3548. continue;
  3549. }
  3550. if (!fDeltaOnly)
  3551. {
  3552. // Publish a new Base CRL
  3553. // make a local copy in case clamped
  3554. FILETIME ftNextUpdateBaseTemp = ftNextUpdateBase;
  3555. fClamped = FALSE;
  3556. hr = CertSrvTestServerState();
  3557. _JumpIfError(hr, error, "CertSrvTestServerState");
  3558. hr = crlPublishCRLFromCAContext(
  3559. CRLNumber,
  3560. 0, // CRLNumberBaseMin
  3561. pwszUserName,
  3562. FALSE, // fShadowDelta
  3563. pCAContext,
  3564. pftCurrent,
  3565. ftThisUpdate,
  3566. &ftNextUpdateBaseTemp,
  3567. &fClamped,
  3568. NULL,
  3569. pftCurrent,
  3570. &ftNextPublishBase,
  3571. &ftLastPublishBase,
  3572. &ftPropagationCompleteBase,
  3573. &fRetryNeeded,
  3574. &hrPublish);
  3575. _JumpIfError(hr, error, "crlPublishCRLFromCAContext");
  3576. if (fRetryNeeded)
  3577. {
  3578. *pfRetryNeeded = TRUE;
  3579. }
  3580. if (S_OK == *phrPublish)
  3581. {
  3582. *phrPublish = hrPublish;
  3583. }
  3584. {
  3585. CertSrv::CAuditEvent event(SE_AUDITID_CERTSRV_AUTOPUBLISHCRL, g_dwAuditFilter);
  3586. hr = event.AddData(true); // %1 base crl?
  3587. _JumpIfError(hr, error, "CAuditEvent::AddData");
  3588. hr = event.AddData(CRLNumber); // %2 CRL#
  3589. _JumpIfError(hr, error, "CAuditEvent::AddData");
  3590. hr = event.AddData(pCAContext->pwszKeyContainerName); // %3 key container
  3591. _JumpIfError(hr, error, "CAuditEvent::AddData");
  3592. hr = event.AddData(ftNextPublishBase); // %4 next publish
  3593. _JumpIfError(hr, error, "CAuditEvent::AddData");
  3594. hr = event.AddData((LPCWSTR*)pCAContext->papwszCRLFiles); //%5 URLs
  3595. _JumpIfError(hr, error, "CAuditEvent::AddData");
  3596. hr = event.Report();
  3597. _JumpIfError(hr, error, "CAuditEvent::Report");
  3598. }
  3599. if (i == g_cCACerts && fClamped)
  3600. {
  3601. // new next publish clamps with CA expiration, only update
  3602. // the current crl with new one for later reg save
  3603. ftNextUpdateBaseClamped = ftNextUpdateBaseTemp;
  3604. }
  3605. }
  3606. if (!g_fDeltaCRLPublishDisabled || fShadowDelta)
  3607. {
  3608. // Publish a new Delta CRL
  3609. FILETIME ftNextUpdateDeltaTemp = ftNextUpdateDelta;
  3610. hr = CertSrvTestServerState();
  3611. _JumpIfError(hr, error, "CertSrvTestServerState");
  3612. hr = crlPublishCRLFromCAContext(
  3613. CRLNumber,
  3614. CRLNumberBaseMin,
  3615. pwszUserName,
  3616. fShadowDelta,
  3617. pCAContext,
  3618. pftCurrent,
  3619. ftThisUpdate,
  3620. &ftNextUpdateDeltaTemp,
  3621. NULL,
  3622. pftQueryDelta,
  3623. pftCurrent,
  3624. &ftNextPublishDelta,
  3625. &ftLastPublishBase, // Base!
  3626. &ftPropagationCompleteDelta,
  3627. &fRetryNeeded,
  3628. &hrPublish);
  3629. _JumpIfError(hr, error, "crlPublishCRLFromCAContext");
  3630. if (fRetryNeeded)
  3631. {
  3632. *pfRetryNeeded = TRUE;
  3633. }
  3634. if (S_OK == *phrPublish)
  3635. {
  3636. *phrPublish = hrPublish;
  3637. }
  3638. {
  3639. CertSrv::CAuditEvent event(SE_AUDITID_CERTSRV_AUTOPUBLISHCRL, g_dwAuditFilter);
  3640. hr = event.AddData(false); // %1 base crl?
  3641. _JumpIfError(hr, error, "CAuditEvent::AddData");
  3642. hr = event.AddData(CRLNumber); // %2 CRL#
  3643. _JumpIfError(hr, error, "CAuditEvent::AddData");
  3644. hr = event.AddData(pCAContext->pwszKeyContainerName); // %3 key container
  3645. _JumpIfError(hr, error, "CAuditEvent::AddData");
  3646. hr = event.AddData(ftNextPublishDelta); // %4 next publish
  3647. _JumpIfError(hr, error, "CAuditEvent::AddData");
  3648. hr = event.AddData((LPCWSTR*)pCAContext->papwszDeltaCRLFiles); // %5 URLs
  3649. _JumpIfError(hr, error, "CAuditEvent::AddData");
  3650. hr = event.Report();
  3651. _JumpIfError(hr, error, "CAuditEvent::Report");
  3652. }
  3653. }
  3654. }
  3655. // update the registry and global variables
  3656. if (!fDeltaOnly)
  3657. {
  3658. if (!fClamped)
  3659. {
  3660. g_ftCRLNextPublish = ftNextPublishBase;
  3661. }
  3662. else
  3663. {
  3664. g_ftCRLNextPublish = ftNextUpdateBaseClamped;
  3665. }
  3666. hr = crlSetRegCRLNextPublish(
  3667. FALSE,
  3668. g_wszSanitizedName,
  3669. wszREGCRLNEXTPUBLISH,
  3670. &g_ftCRLNextPublish);
  3671. _JumpIfError(hr, error, "crlSetRegCRLNextPublish");
  3672. }
  3673. g_ftDeltaCRLNextPublish = ftNextPublishDelta;
  3674. if (!g_fDeltaCRLPublishDisabled)
  3675. {
  3676. hr = crlSetRegCRLNextPublish(
  3677. TRUE,
  3678. g_wszSanitizedName,
  3679. wszREGCRLDELTANEXTPUBLISH,
  3680. &g_ftDeltaCRLNextPublish);
  3681. _JumpIfError(hr, error, "crlSetRegCRLNextPublish");
  3682. }
  3683. hr = S_OK;
  3684. error:
  3685. if (NULL != hkeyCA)
  3686. {
  3687. RegCloseKey(hkeyCA);
  3688. }
  3689. if (NULL != hkeyBase)
  3690. {
  3691. RegCloseKey(hkeyBase);
  3692. }
  3693. return(hr);
  3694. }
  3695. ///////////////////////////////////////////////////
  3696. // CRLPublishCRLs is called to publish a set of CRLs.
  3697. //
  3698. // if fRebuildCRL is TRUE, the CRLs are rebuilt from the database.
  3699. // otherwise, the exit module is re-notified of the CRLs.
  3700. // For consistency, if the exit module returns ERROR_RETRY, this
  3701. // function will write the retry bit into the registry which will
  3702. // trigger the Wakeup function, which then recalculates when the
  3703. // next publish should happen.
  3704. //
  3705. // pfRetryNeeded is an OUT param that notifies the autopublish routine if
  3706. // a retry is immediately necessary following a rebuilt CRL. In this
  3707. // case the registry would not be changed and the registry trigger
  3708. // would not fire.
  3709. //
  3710. // (Current_time - skew) is used as ThisUpdate
  3711. // (ftNextUpdate+skew+Overlap) is used as NextUpdate
  3712. // (ftNextUpdate) is next wakeup/publish time
  3713. //
  3714. // There are registry values to specify the overlap.
  3715. // HLKLM\SYSTEM\CurrentControlSet\Services\CertSvc\Configuration\<CA Name>:
  3716. // CRLOverlapPeriod REG_SZ = Hours (or Minutes)
  3717. // CRLOverlapUnits REG_DWORD = 0 (0) -- DISABLED
  3718. //
  3719. // If the above registry values are set and valid, the registry overlap period
  3720. // is calculated as:
  3721. // max(Registry CRL Overlap Period, 1.5 * Registry clock skew minutes)
  3722. //
  3723. // If they are not present or invalid, the overlap period is calculated as:
  3724. // max(
  3725. // min(Registry CRL Period / 10, 12 hours),
  3726. // 1.5 * Registry clock skew minutes) +
  3727. // Registry clock skew minutes
  3728. //
  3729. // ThisUpdate is calculated as:
  3730. // max(Current Time - Registry clock skew minutes, CA cert NotBefore date)
  3731. //
  3732. // NextUpdate is calculated as:
  3733. // min(
  3734. // Current Time +
  3735. // Registry CRL period +
  3736. // calculated overlap period +
  3737. // Registry clock skew minutes,
  3738. // CA cert NotAfter date)
  3739. //
  3740. // The Next CRL publication time is calculated as:
  3741. // Current Time + Registry CRL period
  3742. //
  3743. // This function sets g_hCRLManualPublishEvent. Automatic publishing
  3744. // is personally responsible for clearing this event if it calls us.
  3745. HRESULT
  3746. CRLPublishCRLs(
  3747. IN BOOL fRebuildCRL, // else republish only
  3748. IN BOOL fForceRepublish, // else check registry retry count
  3749. OPTIONAL IN WCHAR const *pwszUserName, // else timer thread
  3750. IN BOOL fDeltaOnly, // else base (and delta, if enabled)
  3751. IN BOOL fShadowDelta, // empty delta CRL with new MinBaseCRL
  3752. IN FILETIME ftNextUpdateBase,
  3753. OUT BOOL *pfRetryNeeded,
  3754. OUT HRESULT *phrPublish)
  3755. {
  3756. HRESULT hr;
  3757. BOOL fRetryNeeded = FALSE;
  3758. BOOL fExitNotify = FALSE;
  3759. BOOL fCoInitialized = FALSE;
  3760. DWORD RowIdBase = 0;
  3761. FILETIME ftQueryDeltaDelete = { 0, 0 };
  3762. DWORD dwPreviousAttempts;
  3763. DWORD dwCurrentAttempts;
  3764. static BOOL s_fSkipRetry = FALSE;
  3765. *pfRetryNeeded = FALSE;
  3766. *phrPublish = S_OK;
  3767. if (fDeltaOnly && g_fDeltaCRLPublishDisabled && !fShadowDelta)
  3768. {
  3769. hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DISABLED);
  3770. _JumpError(hr, error, "g_fDeltaCRLPublishDisabled");
  3771. }
  3772. // retrieve initial retry value (optional registry value)
  3773. hr = myGetCertRegDWValue(
  3774. g_wszSanitizedName,
  3775. NULL,
  3776. NULL,
  3777. wszREGCRLATTEMPTREPUBLISH,
  3778. &dwPreviousAttempts);
  3779. if (HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr)
  3780. {
  3781. dwPreviousAttempts = 0; // assume no previous failed publish attempts
  3782. hr = S_OK;
  3783. }
  3784. _JumpIfErrorStr(
  3785. hr,
  3786. error,
  3787. "myGetCertRegDWValue",
  3788. wszREGCRLATTEMPTREPUBLISH);
  3789. dwCurrentAttempts = dwPreviousAttempts;
  3790. DBGPRINT((
  3791. DBG_SS_CERTSRV,
  3792. "CRLPublishCRLs(fRebuildCRL=%u, fForceRepublish=%u, User=%ws)\n",
  3793. fRebuildCRL,
  3794. fForceRepublish,
  3795. pwszUserName));
  3796. DBGPRINT((
  3797. DBG_SS_CERTSRV,
  3798. "CRLPublishCRLs(fDeltaOnly=%u, fShadowDelta=%u, dwPreviousAttempts=%u)\n",
  3799. fDeltaOnly,
  3800. fShadowDelta,
  3801. dwPreviousAttempts));
  3802. if (0 != dwPreviousAttempts && NULL == pwszUserName && s_fSkipRetry)
  3803. {
  3804. fRetryNeeded = TRUE;
  3805. }
  3806. else
  3807. {
  3808. FILETIME ftCurrent;
  3809. GetSystemTimeAsFileTime(&ftCurrent);
  3810. // generate CRLs if necessary
  3811. if (fRebuildCRL)
  3812. {
  3813. hr = crlGenerateAndPublishCRLs(
  3814. pwszUserName,
  3815. fDeltaOnly,
  3816. fShadowDelta,
  3817. &ftCurrent,
  3818. ftNextUpdateBase,
  3819. &RowIdBase,
  3820. &ftQueryDeltaDelete,
  3821. &fRetryNeeded,
  3822. phrPublish);
  3823. _JumpIfError(hr, error, "crlGenerateAndPublishCRLs");
  3824. fExitNotify = TRUE;
  3825. dwCurrentAttempts = 1;
  3826. }
  3827. else
  3828. if (fForceRepublish ||
  3829. (0 < dwPreviousAttempts &&
  3830. CERTSRV_CRLPUB_RETRY_COUNT_DEFAULT > dwPreviousAttempts))
  3831. {
  3832. // If the timer thread is auto-republishing due to previously
  3833. // failed publish attempts, retry base CRLs, too, because we
  3834. // can't tell if the retry is due to a base or delta CRL error.
  3835. if (NULL == pwszUserName)
  3836. {
  3837. fDeltaOnly = FALSE;
  3838. }
  3839. hr = crlRepublishExistingCRLs(
  3840. pwszUserName,
  3841. fDeltaOnly,
  3842. fShadowDelta,
  3843. &ftCurrent,
  3844. &fRetryNeeded,
  3845. phrPublish);
  3846. _JumpIfError(hr, error, "crlRepublishCRLs");
  3847. fExitNotify = TRUE;
  3848. dwCurrentAttempts++;
  3849. }
  3850. if (fExitNotify && g_fEnableExit)
  3851. {
  3852. hr = CoInitializeEx(NULL, GetCertsrvComThreadingModel());
  3853. if (S_OK != hr && S_FALSE != hr)
  3854. {
  3855. _JumpError(hr, error, "CoInitializeEx");
  3856. }
  3857. fCoInitialized = TRUE;
  3858. // make sure exit module(s) get notified for publish and republish
  3859. // in case of earlier exit module publish failure.
  3860. hr = ExitNotify(EXITEVENT_CRLISSUED, 0, MAXDWORD);
  3861. _PrintIfError(hr, "ExitNotify");
  3862. if ((HRESULT) ERROR_RETRY == hr ||
  3863. HRESULT_FROM_WIN32(ERROR_RETRY) == hr)
  3864. {
  3865. fRetryNeeded = TRUE;
  3866. if (S_OK == *phrPublish)
  3867. {
  3868. *phrPublish = HRESULT_FROM_WIN32(ERROR_RETRY);
  3869. }
  3870. }
  3871. CONSOLEPRINT0((DBG_SS_CERTSRV, "Issued CRL Exit Event\n"));
  3872. }
  3873. // If new or existing CRLs successfully published, reset count to 0
  3874. if (fExitNotify && !fRetryNeeded)
  3875. {
  3876. dwCurrentAttempts = 0;
  3877. if (CERTLOG_VERBOSE <= g_dwLogLevel)
  3878. {
  3879. WCHAR *pwszHostName = NULL;
  3880. DWORD LogMsg;
  3881. WORD cpwsz = 0;
  3882. if (NULL != g_pld)
  3883. {
  3884. myLdapGetDSHostName(g_pld, &pwszHostName);
  3885. }
  3886. LogMsg = fDeltaOnly?
  3887. MSG_DELTA_CRLS_PUBLISHED :
  3888. (g_fDeltaCRLPublishDisabled?
  3889. MSG_BASE_CRLS_PUBLISHED :
  3890. MSG_BASE_AND_DELTA_CRLS_PUBLISHED);
  3891. if (NULL != pwszHostName)
  3892. {
  3893. LogMsg = fDeltaOnly?
  3894. MSG_DELTA_CRLS_PUBLISHED_HOST_NAME :
  3895. (g_fDeltaCRLPublishDisabled?
  3896. MSG_BASE_CRLS_PUBLISHED_HOST_NAME :
  3897. MSG_BASE_AND_DELTA_CRLS_PUBLISHED_HOST_NAME);
  3898. }
  3899. hr = LogEvent(
  3900. EVENTLOG_INFORMATION_TYPE,
  3901. LogMsg,
  3902. NULL == pwszHostName? 0 : 1, // cStrings
  3903. (WCHAR const **) &pwszHostName); // apwszStrings
  3904. _PrintIfError(hr, "LogEvent");
  3905. }
  3906. }
  3907. // If the retry count has changed, update the registry.
  3908. if (dwCurrentAttempts != dwPreviousAttempts)
  3909. {
  3910. DBGPRINT((
  3911. DBG_SS_CERTSRV,
  3912. "CRLPublishCRLs(Attempts: %u --> %u)\n",
  3913. dwPreviousAttempts,
  3914. dwCurrentAttempts));
  3915. hr = mySetCertRegDWValue(
  3916. g_wszSanitizedName,
  3917. NULL,
  3918. NULL,
  3919. wszREGCRLATTEMPTREPUBLISH,
  3920. dwCurrentAttempts);
  3921. _JumpIfErrorStr(
  3922. hr,
  3923. error,
  3924. "mySetCertRegDWValue",
  3925. wszREGCRLATTEMPTREPUBLISH);
  3926. // If we tried unsuccessfully too many times to publish these CRLs,
  3927. // and we're about to give up until a new set is generated, log an
  3928. // event saying so.
  3929. if (fExitNotify &&
  3930. CERTSRV_CRLPUB_RETRY_COUNT_DEFAULT == dwCurrentAttempts &&
  3931. CERTLOG_ERROR <= g_dwLogLevel)
  3932. {
  3933. WCHAR wszAttempts[11 + 1];
  3934. WCHAR const *pwsz = wszAttempts;
  3935. wsprintf(wszAttempts, L"%u", dwCurrentAttempts);
  3936. hr = LogEvent(
  3937. EVENTLOG_ERROR_TYPE,
  3938. MSG_E_CRL_PUBLICATION_TOO_MANY_RETRIES,
  3939. 1, // cStrings
  3940. &pwsz); // apwszStrings
  3941. _PrintIfError(hr, "LogEvent");
  3942. }
  3943. }
  3944. if (fRebuildCRL)
  3945. {
  3946. // Delete old CRLs only if new CRLs built & published successfully.
  3947. if (!fRetryNeeded)
  3948. {
  3949. hr = CertSrvTestServerState();
  3950. _JumpIfError(hr, error, "CertSrvTestServerState");
  3951. hr = crlDeleteExpiredCRLs(
  3952. &ftCurrent,
  3953. &ftQueryDeltaDelete,
  3954. RowIdBase);
  3955. _PrintIfError(hr, "crlDeleteExpiredCRLs");
  3956. }
  3957. // Clear force CRL flag only when we build new CRLs.
  3958. hr = SetSetupStatus(g_wszSanitizedName, SETUP_FORCECRL_FLAG, FALSE);
  3959. _PrintIfError(hr, "SetSetupStatus");
  3960. }
  3961. }
  3962. s_fSkipRetry = NULL != pwszUserName;
  3963. if (fRebuildCRL || fRetryNeeded)
  3964. {
  3965. // If we are doing ANYTHING that will affect automatic wakeup, trigger
  3966. // our publish event.
  3967. // NOTE: do this last or else state might not be updated
  3968. SetEvent(g_hCRLManualPublishEvent);
  3969. }
  3970. hr = S_OK;
  3971. error:
  3972. *pfRetryNeeded = fRetryNeeded;
  3973. if (fCoInitialized)
  3974. {
  3975. CoUninitialize();
  3976. }
  3977. return(hr);
  3978. }
  3979. HRESULT
  3980. CRLGetCRL(
  3981. IN DWORD iCertArg,
  3982. IN BOOL fDelta,
  3983. OPTIONAL OUT CRL_CONTEXT const **ppCRL,
  3984. OPTIONAL OUT DWORD *pdwCRLPublishFlags)
  3985. {
  3986. HRESULT hr;
  3987. DWORD State;
  3988. DWORD iCert;
  3989. DWORD iCRL;
  3990. CACTX *pCAContext;
  3991. DWORD dwRowId;
  3992. BYTE *pbCRL = NULL;
  3993. DWORD cbCRL;
  3994. if (NULL != ppCRL)
  3995. {
  3996. *ppCRL = NULL;
  3997. }
  3998. hr = PKCSMapCRLIndex(iCertArg, &iCert, &iCRL, &State);
  3999. _JumpIfError(hr, error, "PKCSMapCRLIndex");
  4000. if (MAXDWORD != iCertArg && CA_DISP_VALID != State)
  4001. {
  4002. hr = E_INVALIDARG;
  4003. _JumpError(hr, error, "No CRL for this Cert");
  4004. }
  4005. // Now we know iCert is a valid Cert Index:
  4006. hr = crlGetRowIdAndCRL(
  4007. fDelta,
  4008. &g_aCAContext[iCert],
  4009. &dwRowId,
  4010. &cbCRL,
  4011. &pbCRL,
  4012. pdwCRLPublishFlags);
  4013. _JumpIfError(hr, error, "crlGetRowIdAndCRL");
  4014. if (NULL != ppCRL)
  4015. {
  4016. *ppCRL = CertCreateCRLContext(X509_ASN_ENCODING, pbCRL, cbCRL);
  4017. if (NULL == *ppCRL)
  4018. {
  4019. hr = myHLastError();
  4020. _JumpError(hr, error, "CertCreateCRLContext");
  4021. }
  4022. }
  4023. hr = S_OK;
  4024. error:
  4025. if (NULL != pbCRL)
  4026. {
  4027. LocalFree(pbCRL);
  4028. }
  4029. return(hr);
  4030. }