]> git.saurik.com Git - apple/security.git/blob - Security/libsecurity_apple_x509_tp/lib/tpOcspVerify.cpp
Security-57031.20.26.tar.gz
[apple/security.git] / Security / libsecurity_apple_x509_tp / lib / tpOcspVerify.cpp
1 /*
2 * Copyright (c) 2004,2011-2012,2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 /*
25 * tpOcspVerify.cpp - top-level OCSP verification
26 */
27
28 #include "tpOcspVerify.h"
29 #include "tpdebugging.h"
30 #include "ocspRequest.h"
31 #include "tpOcspCache.h"
32 #include "tpOcspCertVfy.h"
33 #include <security_ocspd/ocspResponse.h>
34 #include "certGroupUtils.h"
35 #include <Security/certextensions.h>
36 #include <Security/oidsattr.h>
37 #include <Security/oidscert.h>
38 #include <security_asn1/SecNssCoder.h>
39 #include <security_ocspd/ocspdClient.h>
40 #include <security_ocspd/ocspdUtils.h>
41 #include "tpTime.h"
42
43 #pragma mark ---- private routines ----
44
45 /*
46 * Get a smart CertID for specified cert and issuer
47 */
48 static CSSM_RETURN tpOcspGetCertId(
49 TPCertInfo &subject,
50 TPCertInfo &issuer,
51 OCSPClientCertID *&certID) /* mallocd by coder and RETURNED */
52 {
53 CSSM_RETURN crtn;
54 CSSM_DATA_PTR issuerSubject = NULL;
55 CSSM_DATA_PTR issuerPubKeyData = NULL;
56 CSSM_KEY_PTR issuerPubKey;
57 CSSM_DATA issuerPubKeyBytes;
58 CSSM_DATA_PTR subjectSerial = NULL;
59
60 crtn = subject.fetchField(&CSSMOID_X509V1SerialNumber, &subjectSerial);
61 if(crtn) {
62 return crtn;
63 }
64 crtn = subject.fetchField(&CSSMOID_X509V1IssuerNameStd, &issuerSubject);
65 if(crtn) {
66 return crtn;
67 }
68 crtn = issuer.fetchField(&CSSMOID_CSSMKeyStruct, &issuerPubKeyData);
69 if(crtn) {
70 return crtn;
71 }
72 assert(issuerPubKeyData->Length == sizeof(CSSM_KEY));
73 issuerPubKey = (CSSM_KEY_PTR)issuerPubKeyData->Data;
74 ocspdGetPublicKeyBytes(NULL, issuerPubKey, issuerPubKeyBytes);
75 certID = new OCSPClientCertID(*issuerSubject, issuerPubKeyBytes, *subjectSerial);
76
77 subject.freeField(&CSSMOID_X509V1SerialNumber, subjectSerial);
78 issuer.freeField(&CSSMOID_X509V1IssuerNameStd, issuerSubject);
79 issuer.freeField(&CSSMOID_CSSMKeyStruct, issuerPubKeyData);
80 return CSSM_OK;
81 }
82
83 /*
84 * Examine cert, looking for AuthorityInfoAccess, with id-ad-ocsp URIs. Create
85 * an NULL_terminated array of CSSM_DATAs containing the URIs if found.
86 */
87 static CSSM_DATA **tpOcspUrlsFromCert(
88 TPCertInfo &subject,
89 SecNssCoder &coder)
90 {
91 CSSM_DATA_PTR extField = NULL;
92 CSSM_RETURN crtn;
93
94 crtn = subject.fetchField(&CSSMOID_AuthorityInfoAccess, &extField);
95 if(crtn) {
96 tpOcspDebug("tpOcspUrlsFromCert: no AIA extension");
97 return NULL;
98 }
99 if(extField->Length != sizeof(CSSM_X509_EXTENSION)) {
100 tpErrorLog("tpOcspUrlsFromCert: malformed CSSM_FIELD");
101 return NULL;
102 }
103 CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)extField->Data;
104 if(cssmExt->format != CSSM_X509_DATAFORMAT_PARSED) {
105 tpErrorLog("tpOcspUrlsFromCert: malformed CSSM_X509_EXTENSION");
106 return NULL;
107 }
108
109 CE_AuthorityInfoAccess *aia =
110 (CE_AuthorityInfoAccess *)cssmExt->value.parsedValue;
111 CSSM_DATA **urls = NULL;
112 unsigned numUrls = 0;
113 for(unsigned dex=0; dex<aia->numAccessDescriptions; dex++) {
114 CE_AccessDescription *ad = &aia->accessDescriptions[dex];
115 if(!tpCompareCssmData(&ad->accessMethod, &CSSMOID_AD_OCSP)) {
116 continue;
117 }
118 CE_GeneralName *genName = &ad->accessLocation;
119 if(genName->nameType != GNT_URI) {
120 tpErrorLog("tpOcspUrlsFromCert: CSSMOID_AD_OCSP, but not type URI");
121 continue;
122 }
123
124 /* got one */
125 if(urls == NULL) {
126 urls = coder.mallocn<CSSM_DATA_PTR>(2);
127 }
128 else {
129 /* realloc */
130 CSSM_DATA **oldUrls = urls;
131 urls = coder.mallocn<CSSM_DATA_PTR>(numUrls + 2);
132 for(unsigned i=0; i<numUrls; i++) {
133 urls[i] = oldUrls[i];
134 }
135 }
136 urls[numUrls] = coder.mallocn<CSSM_DATA>();
137 coder.allocCopyItem(genName->name, *urls[numUrls++]);
138 urls[numUrls] = NULL;
139 #ifndef NDEBUG
140 {
141 CSSM_DATA urlStr;
142 coder.allocItem(urlStr, genName->name.Length + 1);
143 memmove(urlStr.Data, genName->name.Data, genName->name.Length);
144 urlStr.Data[urlStr.Length-1] = '\0';
145 tpOcspDebug("tpOcspUrlsFromCert: found URI %s", urlStr.Data);
146 }
147 #endif
148 }
149 subject.freeField(&CSSMOID_AuthorityInfoAccess, extField);
150 return urls;
151 }
152
153 /*
154 * Create an SecAsn1OCSPDRequest for one cert. This consists of:
155 *
156 * -- cooking up an OCSPRequest if net fetch is enabled or a local responder
157 * is configured;
158 * -- extracting URLs from subject cert if net fetch is enabled;
159 * -- creating an SecAsn1OCSPDRequest, mallocd in coder's space;
160 */
161 static SecAsn1OCSPDRequest *tpGenOcspdReq(
162 TPVerifyContext &vfyCtx,
163 SecNssCoder &coder,
164 TPCertInfo &subject,
165 TPCertInfo &issuer,
166 OCSPClientCertID &certId,
167 const CSSM_DATA **urls, // from subject's AuthorityInfoAccess
168 CSSM_DATA &nonce) // possibly mallocd in coder's space and RETURNED
169 {
170 OCSPRequest *ocspReq = NULL;
171 SecAsn1OCSPDRequest *ocspdReq = NULL; // to return
172 OCSPClientCertID *certID = NULL;
173 CSSM_RETURN crtn;
174 bool deleteCertID = false;
175
176 /* gather options or their defaults */
177 CSSM_APPLE_TP_OCSP_OPT_FLAGS optFlags = 0;
178 const CSSM_APPLE_TP_OCSP_OPTIONS *ocspOpts = vfyCtx.ocspOpts;
179 CSSM_DATA_PTR localResponder = NULL;
180 CSSM_DATA_PTR localResponderCert = NULL;
181 if(ocspOpts != NULL) {
182 optFlags = vfyCtx.ocspOpts->Flags;
183 localResponder = ocspOpts->LocalResponder;
184 localResponderCert = ocspOpts->LocalResponderCert;
185 }
186 bool genNonce = optFlags & CSSM_TP_OCSP_GEN_NONCE ? true : false;
187 bool requireRespNonce = optFlags & CSSM_TP_OCSP_REQUIRE_RESP_NONCE ? true : false;
188
189 /*
190 * One degenerate case in case we can't really do anything.
191 * If no URI and no local responder, only proceed if cache is not disabled
192 * and we're requiring full OCSP per cert.
193 */
194 if( ( (optFlags & CSSM_TP_ACTION_OCSP_CACHE_READ_DISABLE) ||
195 !(optFlags & CSSM_TP_ACTION_OCSP_REQUIRE_PER_CERT)
196 ) &&
197 (localResponder == NULL) &&
198 (urls == NULL)) {
199 tpOcspDebug("tpGenOcspdReq: no route to OCSP; NULL return");
200 return NULL;
201 }
202
203 /* do we need an OCSP request? */
204 if(!(optFlags & CSSM_TP_ACTION_OCSP_DISABLE_NET) || (localResponder != NULL)) {
205 try {
206 ocspReq = new OCSPRequest(subject, issuer, genNonce);
207 certID = ocspReq->certID();
208 }
209 catch(...) {
210 /* not sure how this could even happen but that was a fair amount of code */
211 tpErrorLog("tpGenOcspdReq: error cooking up OCSPRequest\n");
212 if(ocspReq != NULL) {
213 delete ocspReq;
214 return NULL;
215 }
216 }
217 }
218
219 /* certID needed one way or the other */
220 if(certID == NULL) {
221 crtn = tpOcspGetCertId(subject, issuer, certID);
222 if(crtn) {
223 goto errOut;
224 }
225 deleteCertID = true;
226 }
227
228 /*
229 * Create the SecAsn1OCSPDRequest. All fields optional.
230 */
231 ocspdReq = coder.mallocn<SecAsn1OCSPDRequest>();
232 memset(ocspdReq, 0, sizeof(*ocspdReq));
233 if(optFlags & CSSM_TP_ACTION_OCSP_CACHE_WRITE_DISABLE) {
234 ocspdReq->cacheWriteDisable = coder.mallocn<CSSM_DATA>();
235 ocspdReq->cacheWriteDisable->Data = coder.mallocn<uint8>();
236 ocspdReq->cacheWriteDisable->Data[0] = 0xff;
237 ocspdReq->cacheWriteDisable->Length = 1;
238 }
239 /*
240 * Note we're enforcing a not-so-obvious policy here: if nonce match is
241 * required, disk cache reads by ocspd are disabled. In-core cache is
242 * still enabled and hits in that cache do NOT require nonce matches.
243 */
244 if((optFlags & CSSM_TP_ACTION_OCSP_CACHE_READ_DISABLE) || requireRespNonce) {
245 ocspdReq->cacheReadDisable = coder.mallocn<CSSM_DATA>();
246 ocspdReq->cacheReadDisable->Data = coder.mallocn<uint8>();
247 ocspdReq->cacheReadDisable->Data[0] = 0xff;
248 ocspdReq->cacheReadDisable->Length = 1;
249 }
250 /* CertID, only required field */
251 coder.allocCopyItem(*certID->encode(), ocspdReq->certID);
252 if(ocspReq != NULL) {
253 ocspdReq->ocspReq = coder.mallocn<CSSM_DATA>();
254 coder.allocCopyItem(*ocspReq->encode(), *ocspdReq->ocspReq);
255 if(genNonce) {
256 /* nonce not available until encode() called */
257 coder.allocCopyItem(*ocspReq->nonce(), nonce);
258 }
259 }
260 if(localResponder != NULL) {
261 ocspdReq->localRespURI = localResponder;
262 }
263 if(!(optFlags & CSSM_TP_ACTION_OCSP_DISABLE_NET)) {
264 ocspdReq->urls = const_cast<CSSM_DATA **>(urls);
265 }
266
267 errOut:
268 delete ocspReq;
269 if(deleteCertID) {
270 delete certID;
271 }
272 return ocspdReq;
273 }
274
275 static bool revocationTimeAfterVerificationTime(CFAbsoluteTime revokedTime, CSSM_TIMESTRING verifyTimeStr)
276 {
277 // Return true if the revocation time is after the specified verification time (i.e. "good")
278 // If verifyTime not specified, use now for the verifyTime
279
280 CFAbsoluteTime verifyTime = 0;
281
282 if (verifyTimeStr)
283 {
284 CFDateRef cfVerifyTime = NULL; // made with CFDateCreate
285 int rtn = timeStringToCfDate((char *)verifyTimeStr, (unsigned)strlen(verifyTimeStr), &cfVerifyTime);
286 if (!rtn)
287 if (cfVerifyTime)
288 {
289 verifyTime = CFDateGetAbsoluteTime(cfVerifyTime);
290 CFRelease(cfVerifyTime);
291 }
292 }
293
294 if (verifyTime == 0)
295 verifyTime = CFAbsoluteTimeGetCurrent();
296
297 return verifyTime < revokedTime;
298 }
299
300 /*
301 * Apply a verified OCSPSingleResponse to a TPCertInfo.
302 */
303 static CSSM_RETURN tpApplySingleResp(
304 OCSPSingleResponse &singleResp,
305 TPCertInfo &cert,
306 unsigned dex, // for debug
307 CSSM_APPLE_TP_OCSP_OPT_FLAGS flags, // for OCSP_SUFFICIENT
308 CSSM_TIMESTRING verifyTime, // Check revocation at specific time
309 bool &processed) // set true iff CS_Good or CS_Revoked found
310 {
311 SecAsn1OCSPCertStatusTag certStatus = singleResp.certStatus();
312 CSSM_RETURN crtn = CSSM_OK;
313 if ((certStatus == CS_Revoked) &&
314 revocationTimeAfterVerificationTime(singleResp.revokedTime(), verifyTime))
315 {
316 tpOcspDebug("tpApplySingleResp: CS_Revoked for cert %u, but revoked after verification time", dex);
317 certStatus = CS_Good;
318 }
319
320 switch(certStatus) {
321 case CS_Good:
322 tpOcspDebug("tpApplySingleResp: CS_Good for cert %u", dex);
323 cert.revokeCheckGood(true);
324 if(flags & CSSM_TP_ACTION_OCSP_SUFFICIENT) {
325 /* no more revocation checking necessary for this cert */
326 cert.revokeCheckComplete(true);
327 }
328 processed = true;
329 break;
330 case CS_Revoked:
331 tpOcspDebug("tpApplySingleResp: CS_Revoked for cert %u", dex);
332 switch(singleResp.crlReason()) {
333 case CE_CR_CertificateHold:
334 crtn = CSSMERR_TP_CERT_SUSPENDED;
335 break;
336 default:
337 /* FIXME - may want more detailed CRLReason-specific errors */
338 crtn = CSSMERR_TP_CERT_REVOKED;
339 break;
340 }
341 if(!cert.addStatusCode(crtn)) {
342 crtn = CSSM_OK;
343 }
344 processed = true;
345 break;
346 case CS_Unknown:
347 /* not an error, no per-cert status, nothing here */
348 tpOcspDebug("tpApplySingleResp: CS_Unknown for cert %u", dex);
349 break;
350 default:
351 tpOcspDebug("tpApplySingleResp: BAD certStatus (%d) for cert %u",
352 (int)certStatus, dex);
353 if(cert.addStatusCode(CSSMERR_APPLETP_OCSP_STATUS_UNRECOGNIZED)) {
354 crtn = CSSMERR_APPLETP_OCSP_STATUS_UNRECOGNIZED;
355 }
356 break;
357 }
358 return crtn;
359 }
360
361 /*
362 * An exceptional case: synchronously flush the OCSPD cache and send a new
363 * resquest for just this one cert.
364 */
365 static OCSPResponse *tpOcspFlushAndReFetch(
366 TPVerifyContext &vfyCtx,
367 SecNssCoder &coder,
368 TPCertInfo &subject,
369 TPCertInfo &issuer,
370 OCSPClientCertID &certID)
371 {
372 const CSSM_DATA *derCertID = certID.encode();
373 CSSM_RETURN crtn;
374
375 crtn = ocspdCacheFlush(*derCertID);
376 if(crtn) {
377 #ifndef NDEBUG
378 cssmPerror("ocspdCacheFlush", crtn);
379 #endif
380 return NULL;
381 }
382
383 /* Cook up an OCSPDRequests, one request, just for this */
384 /* send it to ocsdp */
385 /* munge reply into an OCSPRsponse and return it */
386 tpOcspDebug("pOcspFlushAndReFetch: Code on demand");
387 return NULL;
388 }
389
390 class PendingRequest
391 {
392 public:
393 PendingRequest(
394 TPCertInfo &subject,
395 TPCertInfo &issuer,
396 OCSPClientCertID &cid,
397 CSSM_DATA **u,
398 unsigned dex);
399 ~PendingRequest() {}
400
401 TPCertInfo &subject;
402 TPCertInfo &issuer;
403 OCSPClientCertID &certID; // owned by caller
404 CSSM_DATA **urls; // owner-managed array of URLs obtained from subject's
405 // AuthorityInfoAccess.id-ad-ocsp.
406 CSSM_DATA nonce; // owner-managed copy of this requests' nonce, if it
407 // has one
408 unsigned dex; // in inputCerts, for debug
409 bool processed;
410 };
411
412 PendingRequest::PendingRequest(
413 TPCertInfo &subj,
414 TPCertInfo &iss,
415 OCSPClientCertID &cid,
416 CSSM_DATA **u,
417 unsigned dx)
418 : subject(subj), issuer(iss), certID(cid),
419 urls(u), dex(dx), processed(false)
420 {
421 nonce.Data = NULL;
422 nonce.Length = 0;
423 }
424
425 #pragma mark ---- public API ----
426
427 CSSM_RETURN tpVerifyCertGroupWithOCSP(
428 TPVerifyContext &vfyCtx,
429 TPCertGroup &certGroup) // to be verified
430 {
431 assert(vfyCtx.clHand != 0);
432 assert(vfyCtx.policy == kRevokeOcsp);
433
434 CSSM_RETURN ourRtn = CSSM_OK;
435 OcspRespStatus respStat;
436 SecNssCoder coder;
437 CSSM_RETURN crtn;
438 SecAsn1OCSPDRequests ocspdReqs;
439 SecAsn1OCSPReplies ocspdReplies;
440 unsigned numRequests = 0; // in ocspdReqs
441 CSSM_DATA derOcspdRequests = {0, NULL};
442 CSSM_DATA derOcspdReplies = {0, NULL};
443 uint8 version = OCSPD_REQUEST_VERS;
444 unsigned numReplies;
445 unsigned numCerts = certGroup.numCerts();
446 if(numCerts <= 1) {
447 /* Can't verify without an issuer; we're done */
448 return CSSM_OK;
449 }
450 numCerts--;
451
452 /* gather options or their defaults */
453 CSSM_APPLE_TP_OCSP_OPT_FLAGS optFlags = 0;
454 const CSSM_APPLE_TP_OCSP_OPTIONS *ocspOpts = vfyCtx.ocspOpts;
455 CSSM_DATA_PTR localResponder = NULL;
456 CSSM_DATA_PTR localResponderCert = NULL;
457 bool cacheReadDisable = false;
458 bool cacheWriteDisable = false;
459 bool genNonce = false; // in outgoing request
460 bool requireRespNonce = false; // in incoming response
461 PRErrorCode prtn;
462
463 if(ocspOpts != NULL) {
464 optFlags = vfyCtx.ocspOpts->Flags;
465 localResponder = ocspOpts->LocalResponder;
466 localResponderCert = ocspOpts->LocalResponderCert;
467 }
468 if(optFlags & CSSM_TP_ACTION_OCSP_CACHE_READ_DISABLE) {
469 cacheReadDisable = true;
470 }
471 if(optFlags & CSSM_TP_ACTION_OCSP_CACHE_WRITE_DISABLE) {
472 cacheWriteDisable = true;
473 }
474 if(optFlags & CSSM_TP_OCSP_GEN_NONCE) {
475 genNonce = true;
476 }
477 if(optFlags & CSSM_TP_OCSP_REQUIRE_RESP_NONCE) {
478 requireRespNonce = true;
479 }
480 if(requireRespNonce & !genNonce) {
481 /* no can do */
482 tpErrorLog("tpVerifyCertGroupWithOCSP: requireRespNonce, !genNonce\n");
483 return CSSMERR_TP_INVALID_REQUEST_INPUTS;
484 }
485
486 tpOcspDebug("tpVerifyCertGroupWithOCSP numCerts %u optFlags 0x%lx",
487 numCerts, (unsigned long)optFlags);
488
489 /*
490 * create list of pendingRequests parallel to certGroup
491 */
492 PendingRequest **pending = coder.mallocn<PendingRequest *>(numCerts);
493 memset(pending, 0, (numCerts * sizeof(PendingRequest *)));
494
495 for(unsigned dex=0; dex<numCerts; dex++) {
496 OCSPClientCertID *certID = NULL;
497 TPCertInfo *subject = certGroup.certAtIndex(dex);
498
499 if(subject->trustSettingsFound()) {
500 /* functionally equivalent to root - we're done */
501 tpOcspDebug("...tpVerifyCertGroupWithOCSP: terminate per user trust at %u",
502 (unsigned)dex);
503 goto postOcspd;
504 }
505 TPCertInfo *issuer = certGroup.certAtIndex(dex + 1);
506 crtn = tpOcspGetCertId(*subject, *issuer, certID);
507 if(crtn) {
508 tpErrorLog("tpVerifyCertGroupWithOCSP: error extracting cert fields; "
509 "aborting\n");
510 goto errOut;
511 }
512
513 /*
514 * We use the URLs in the subject cert's AuthorityInfoAccess extension
515 * for two things - mainly to get the URL(s) for actual OCSP transactions,
516 * but also for CSSM_TP_ACTION_OCSP_REQUIRE_IF_RESP_PRESENT processing.
517 * So, we do the per-cert processing to get them right now even if we
518 * wind up using a local responder or getting verification from cache.
519 */
520 CSSM_DATA **urls = tpOcspUrlsFromCert(*subject, coder);
521 pending[dex] = new PendingRequest(*subject, *issuer, *certID, urls, dex);
522 }
523 /* subsequent errors to errOut: */
524
525 /*
526 * Create empty SecAsn1OCSPDRequests big enough for all certs
527 */
528 ocspdReqs.requests = coder.mallocn<SecAsn1OCSPDRequest *>(numCerts + 1);
529 memset(ocspdReqs.requests, 0, (numCerts + 1) * sizeof(SecAsn1OCSPDRequest *));
530 ocspdReqs.version.Data = &version;
531 ocspdReqs.version.Length = 1;
532
533 /*
534 * For each cert, either obtain a cached OCSPResponse, or create
535 * a request to get one.
536 *
537 * NOTE: in-core cache reads (via tpOcspCacheLookup() do NOT involve a
538 * nonce check, no matter what the app says. If nonce checking is required by the
539 * app, responses don't get added to cache if the nonce doesn't match, but once
540 * a response is validated and added to cache it's fair game for that task.
541 */
542 for(unsigned dex=0; dex<numCerts; dex++) {
543 PendingRequest *pendReq = pending[dex];
544 OCSPSingleResponse *singleResp = NULL;
545 if(!cacheReadDisable) {
546 singleResp = tpOcspCacheLookup(pendReq->certID, localResponder);
547 }
548 if(singleResp) {
549 tpOcspDebug("...tpVerifyCertGroupWithOCSP: localCache hit (1) dex %u",
550 (unsigned)dex);
551 crtn = tpApplySingleResp(*singleResp, pendReq->subject, dex, optFlags,
552 vfyCtx.verifyTime, pendReq->processed);
553 delete singleResp;
554 if(pendReq->processed) {
555 /* definitely done with this cert one way or the other */
556 if(crtn && (ourRtn == CSSM_OK)) {
557 /* real cert error: first error encountered; we'll keep going */
558 ourRtn = crtn;
559 }
560 continue;
561 }
562 if(crtn) {
563 /*
564 * This indicates a bad cached response. Well that's kinda weird, let's
565 * just flush this out and try a normal transaction.
566 */
567 tpOcspCacheFlush(pendReq->certID);
568 }
569 }
570
571 /*
572 * Prepare a request for ocspd
573 */
574 SecAsn1OCSPDRequest *ocspdReq = tpGenOcspdReq(vfyCtx, coder,
575 pendReq->subject, pendReq->issuer, pendReq->certID,
576 const_cast<const CSSM_DATA **>(pendReq->urls),
577 pendReq->nonce);
578 if(ocspdReq == NULL) {
579 /* tpGenOcspdReq determined there was no route to OCSP responder */
580 tpOcspDebug("tpVerifyCertGroupWithOCSP: no OCSP possible for cert %u", dex);
581 continue;
582 }
583 ocspdReqs.requests[numRequests++] = ocspdReq;
584 }
585 if(numRequests == 0) {
586 /* no candidates for OCSP: almost done */
587 goto postOcspd;
588 }
589
590 /* ship requests off to ocspd, get ocspReplies back */
591 if(coder.encodeItem(&ocspdReqs, kSecAsn1OCSPDRequestsTemplate, derOcspdRequests)) {
592 tpErrorLog("tpVerifyCertGroupWithOCSP: error encoding ocspdReqs\n");
593 ourRtn = CSSMERR_TP_INTERNAL_ERROR;
594 goto errOut;
595 }
596 crtn = ocspdFetch(vfyCtx.alloc, derOcspdRequests, derOcspdReplies);
597 if(crtn) {
598 tpErrorLog("tpVerifyCertGroupWithOCSP: error during ocspd RPC\n");
599 #ifndef NDEBUG
600 cssmPerror("ocspdFetch", crtn);
601 #endif
602 /* But this is not necessarily fatal...update per-cert status and check
603 * caller requirements below */
604 goto postOcspd;
605 }
606 memset(&ocspdReplies, 0, sizeof(ocspdReplies));
607 prtn = coder.decodeItem(derOcspdReplies, kSecAsn1OCSPDRepliesTemplate,
608 &ocspdReplies);
609 /* we're done with this, mallocd in ocspdFetch() */
610 vfyCtx.alloc.free(derOcspdReplies.Data);
611 if(prtn) {
612 /*
613 * This can happen when an OCSP server provides bad data...we cannot
614 * determine which cert is associated with this bad response;
615 * just flag it with the first one and proceed to the loop that
616 * handles CSSM_TP_ACTION_OCSP_REQUIRE_PER_CERT.
617 */
618 tpErrorLog("tpVerifyCertGroupWithOCSP: error decoding ocspd reply\n");
619 pending[0]->subject.addStatusCode(CSSMERR_APPLETP_OCSP_BAD_RESPONSE);
620 goto postOcspd;
621 }
622 if((ocspdReplies.version.Length != 1) ||
623 (ocspdReplies.version.Data[0] != OCSPD_REPLY_VERS)) {
624 tpErrorLog("tpVerifyCertGroupWithOCSP: ocspd reply version mismatch\n");
625 if(ourRtn == CSSM_OK) {
626 ourRtn = CSSMERR_TP_INTERNAL_ERROR; // maybe something better?
627 }
628 goto errOut;
629 }
630
631 /* process each reply */
632 numReplies = ocspdArraySize((const void **)ocspdReplies.replies);
633 for(unsigned dex=0; dex<numReplies; dex++) {
634 SecAsn1OCSPDReply *reply = ocspdReplies.replies[dex];
635
636 /* Cook up our version of an OCSPResponse from the encoded data */
637 OCSPResponse *ocspResp = NULL;
638 try {
639 ocspResp = new OCSPResponse(reply->ocspResp, TP_OCSP_CACHE_TTL);
640 }
641 catch(...) {
642 tpErrorLog("tpVerifyCertGroupWithOCSP: error decoding ocsp response\n");
643 /* what the heck, keep going */
644 continue;
645 }
646
647 /*
648 * Find matching subject cert if possible (it's technically optional for
649 * verification of the response in some cases, e.g., local responder).
650 */
651 PendingRequest *pendReq = NULL; // fully qualified
652 PendingRequest *reqWithIdMatch = NULL; // CertID match only, not nonce
653 for(unsigned pdex=0; pdex<numCerts; pdex++) {
654
655 /* first check ID match; that is required no matter what */
656 if((pending[pdex])->certID.compareToExist(reply->certID)) {
657 reqWithIdMatch = pending[pdex];
658 }
659 if(reqWithIdMatch == NULL) {
660 continue;
661 }
662 if(!genNonce) {
663 /* that's good enough */
664 pendReq = reqWithIdMatch;
665 tpOcspDebug("OCSP process reply: CertID match, no nonce");
666 break;
667 }
668 if(tpCompareCssmData(&reqWithIdMatch->nonce, ocspResp->nonce())) {
669 tpOcspDebug("OCSP process reply: nonce MATCH");
670 pendReq = reqWithIdMatch;
671 break;
672 }
673
674 /*
675 * In this case we keep going; if we never find a match, then we can
676 * use reqWithIdMatch if !requireRespNonce.
677 */
678 tpOcspDebug("OCSP process reply: certID match, nonce MISMATCH");
679 }
680 if(pendReq == NULL) {
681 if(requireRespNonce) {
682 tpOcspDebug("OCSP process reply: tossing out response due to "
683 "requireRespNonce");
684 delete ocspResp;
685 if(ourRtn == CSSM_OK) {
686 ourRtn = CSSMERR_APPLETP_OCSP_NONCE_MISMATCH;
687 }
688 continue;
689 }
690 if(reqWithIdMatch != NULL) {
691 /*
692 * Nonce mismatch but caller thinks that's OK. Log it and proceed.
693 */
694 assert(genNonce);
695 tpOcspDebug("OCSP process reply: using bad nonce due to !requireRespNonce");
696 pendReq = reqWithIdMatch;
697 pendReq->subject.addStatusCode(CSSMERR_APPLETP_OCSP_NONCE_MISMATCH);
698 }
699 }
700 TPCertInfo *issuer = NULL;
701 if(pendReq != NULL) {
702 issuer = &pendReq->issuer;
703 }
704
705 /* verify response and either throw out or add to local cache */
706 respStat = tpVerifyOcspResp(vfyCtx, coder, issuer, *ocspResp, crtn);
707 switch(respStat) {
708 case ORS_Good:
709 break;
710 case ORS_Unknown:
711 /* not an error but we can't use it */
712 if((crtn != CSSM_OK) && (pendReq != NULL)) {
713 /* pass this info back to caller here... */
714 pendReq->subject.addStatusCode(crtn);
715 }
716 delete ocspResp;
717 continue;
718 case ORS_Bad:
719 delete ocspResp;
720 /*
721 * An exceptional case: synchronously flush the OCSPD cache and send a
722 * new request for just this one cert.
723 * FIXME: does this really buy us anything? A DOS attacker who managed
724 * to get this bogus response into our cache is likely to be able
725 * to do it again and again.
726 */
727 tpOcspDebug("tpVerifyCertGroupWithOCSP: flush/refetch for cert %u", dex);
728 ocspResp = tpOcspFlushAndReFetch(vfyCtx, coder, pendReq->subject,
729 pendReq->issuer, pendReq->certID);
730 if(ocspResp == NULL) {
731 tpErrorLog("tpVerifyCertGroupWithOCSP: error on flush/refetch\n");
732 ourRtn = CSSMERR_APPLETP_OCSP_BAD_RESPONSE;
733 goto errOut;
734 }
735 respStat = tpVerifyOcspResp(vfyCtx, coder, issuer, *ocspResp, crtn);
736 if(respStat != ORS_Good) {
737 tpErrorLog("tpVerifyCertGroupWithOCSP: verify error after "
738 "flush/refetch\n");
739 if((crtn != CSSM_OK) && (pendReq != NULL)) {
740 /* pass this info back to caller here... */
741 if(pendReq->subject.addStatusCode(crtn)) {
742 ourRtn = CSSMERR_APPLETP_OCSP_BAD_RESPONSE;
743 }
744 }
745 else {
746 ourRtn = CSSMERR_APPLETP_OCSP_BAD_RESPONSE;
747 }
748 goto errOut;
749 }
750 /* Voila! Recovery. Proceed. */
751 tpOcspDebug("tpVerifyCertGroupWithOCSP: refetch for cert %u SUCCEEDED",
752 dex);
753 break;
754 } /* switch response status */
755
756 if(!cacheWriteDisable) {
757 tpOcspCacheAdd(reply->ocspResp, localResponder);
758 }
759
760 /* attempt to apply to pendReq */
761 if(pendReq != NULL) {
762 OCSPSingleResponse *singleResp =
763 ocspResp->singleResponseFor(pendReq->certID);
764 if(singleResp) {
765 crtn = tpApplySingleResp(*singleResp, pendReq->subject, pendReq->dex,
766 optFlags, vfyCtx.verifyTime, pendReq->processed);
767 if(crtn && (ourRtn == CSSM_OK)) {
768 ourRtn = crtn;
769 }
770 delete singleResp;
771 }
772 } /* a reply which matches a pending request */
773
774 /*
775 * Done with this - note local OCSP response cache doesn't store this
776 * object; it stores an encoded copy.
777 */
778 delete ocspResp;
779 } /* for each reply */
780
781 postOcspd:
782
783 /*
784 * Now process each cert which hasn't had an OCSP response applied to it.
785 * This can happen if we get back replies which are not strictly in 1-1 sync with
786 * our requests but which nevertheless contain valid info for more than one
787 * cert each.
788 */
789 for(unsigned dex=0; dex<numCerts; dex++) {
790 PendingRequest *pendReq = pending[dex];
791 if(pendReq == NULL) {
792 /* i.e. terminated due to user trust */
793 tpOcspDebug("...tpVerifyCertGroupWithOCSP: NULL pendReq dex %u",
794 (unsigned)dex);
795 break;
796 }
797 if(pendReq->processed) {
798 continue;
799 }
800 OCSPSingleResponse *singleResp = NULL;
801 /* Note this corner case will not work if cache is disabled. */
802 if(!cacheReadDisable) {
803 singleResp = tpOcspCacheLookup(pendReq->certID, localResponder);
804 }
805 if(singleResp) {
806 tpOcspDebug("...tpVerifyCertGroupWithOCSP: localCache (2) hit dex %u",
807 (unsigned)dex);
808 crtn = tpApplySingleResp(*singleResp, pendReq->subject, dex, optFlags,
809 vfyCtx.verifyTime, pendReq->processed);
810 if(crtn) {
811 if(ourRtn == CSSM_OK) {
812 ourRtn = crtn;
813 }
814 }
815 delete singleResp;
816 }
817 if(!pendReq->processed) {
818 /* Couldn't perform OCSP for this cert. */
819 tpOcspDebug("tpVerifyCertGroupWithOCSP: OCSP_UNAVAILABLE for cert %u", dex);
820 bool required = false;
821 CSSM_RETURN responseStatus = CSSM_OK;
822 if(pendReq->subject.numStatusCodes() > 0) {
823 /*
824 * Check whether we got a response for this cert, but it was rejected
825 * due to being improperly signed. That should result in an actual
826 * error, even under Best Attempt processing. (10743149)
827 */
828 if(pendReq->subject.hasStatusCode(CSSMERR_APPLETP_OCSP_BAD_RESPONSE)) {
829 // responseStatus = CSSMERR_APPLETP_OCSP_BAD_RESPONSE; <rdar://problem/10831157>
830 } else if(pendReq->subject.hasStatusCode(CSSMERR_APPLETP_OCSP_SIG_ERROR)) {
831 responseStatus = CSSMERR_APPLETP_OCSP_SIG_ERROR;
832 } else if(pendReq->subject.hasStatusCode(CSSMERR_APPLETP_OCSP_NO_SIGNER)) {
833 responseStatus = CSSMERR_APPLETP_OCSP_NO_SIGNER;
834 }
835 }
836 if(responseStatus == CSSM_OK) {
837 /* no response available (as opposed to getting an invalid response) */
838 pendReq->subject.addStatusCode(CSSMERR_APPLETP_OCSP_UNAVAILABLE);
839 }
840 if(optFlags & CSSM_TP_ACTION_OCSP_REQUIRE_PER_CERT) {
841 /* every cert needs OCSP */
842 tpOcspDebug("tpVerifyCertGroupWithOCSP: response required for all certs, missing for cert %u", dex);
843 required = true;
844 }
845 else if(optFlags & CSSM_TP_ACTION_OCSP_REQUIRE_IF_RESP_PRESENT) {
846 /* this cert needs OCSP if it had an AIA extension with an OCSP URI */
847 if(pendReq->urls) {
848 tpOcspDebug("tpVerifyCertGroupWithOCSP: OCSP URI present but no valid response for cert %u", dex);
849 required = true;
850 }
851 }
852 if( (required && pendReq->subject.isStatusFatal(CSSMERR_APPLETP_OCSP_UNAVAILABLE)) ||
853 (responseStatus != CSSM_OK && pendReq->subject.isStatusFatal(responseStatus)) ) {
854 /* fatal error, but we keep on processing */
855 if(ourRtn == CSSM_OK) {
856 ourRtn = (responseStatus != CSSM_OK) ? responseStatus : CSSMERR_APPLETP_OCSP_UNAVAILABLE;
857 }
858 }
859 }
860 }
861 errOut:
862 for(unsigned dex=0; dex<numCerts; dex++) {
863 PendingRequest *pendReq = pending[dex];
864 if(pendReq == NULL) {
865 /* i.e. terminated due to user trust */
866 break;
867 }
868 delete &pendReq->certID;
869 delete pendReq;
870 }
871 return ourRtn;
872 }