andre@0: /* This Source Code Form is subject to the terms of the Mozilla Public andre@0: * License, v. 2.0. If a copy of the MPL was not distributed with this andre@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ andre@0: andre@0: /* andre@0: * Implementation of OCSP services, for both client and server. andre@0: * (XXX, really, mostly just for client right now, but intended to do both.) andre@0: */ andre@0: andre@0: #include "prerror.h" andre@0: #include "prprf.h" andre@0: #include "plarena.h" andre@0: #include "prnetdb.h" andre@0: andre@0: #include "seccomon.h" andre@0: #include "secitem.h" andre@0: #include "secoidt.h" andre@0: #include "secasn1.h" andre@0: #include "secder.h" andre@0: #include "cert.h" andre@0: #include "certi.h" andre@0: #include "xconst.h" andre@0: #include "secerr.h" andre@0: #include "secoid.h" andre@0: #include "hasht.h" andre@0: #include "sechash.h" andre@0: #include "secasn1.h" andre@0: #include "plbase64.h" andre@0: #include "keyhi.h" andre@0: #include "cryptohi.h" andre@0: #include "ocsp.h" andre@0: #include "ocspti.h" andre@0: #include "ocspi.h" andre@0: #include "genname.h" andre@0: #include "certxutl.h" andre@0: #include "pk11func.h" /* for PK11_HashBuf */ andre@0: #include andre@0: #include andre@0: andre@0: #define DEFAULT_OCSP_CACHE_SIZE 1000 andre@0: #define DEFAULT_MINIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT 1*60*60L andre@0: #define DEFAULT_MAXIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT 24*60*60L andre@0: #define DEFAULT_OSCP_TIMEOUT_SECONDS 60 andre@0: #define MICROSECONDS_PER_SECOND 1000000L andre@0: andre@0: typedef struct OCSPCacheItemStr OCSPCacheItem; andre@0: typedef struct OCSPCacheDataStr OCSPCacheData; andre@0: andre@0: struct OCSPCacheItemStr { andre@0: /* LRU linking */ andre@0: OCSPCacheItem *moreRecent; andre@0: OCSPCacheItem *lessRecent; andre@0: andre@0: /* key */ andre@0: CERTOCSPCertID *certID; andre@0: /* CertID's arena also used to allocate "this" cache item */ andre@0: andre@0: /* cache control information */ andre@0: PRTime nextFetchAttemptTime; andre@0: andre@0: /* Cached contents. Use a separate arena, because lifetime is different */ andre@0: PLArenaPool *certStatusArena; /* NULL means: no cert status cached */ andre@0: ocspCertStatus certStatus; andre@0: andre@0: /* This may contain an error code when no OCSP response is available. */ andre@0: SECErrorCodes missingResponseError; andre@0: andre@0: PRPackedBool haveThisUpdate; andre@0: PRPackedBool haveNextUpdate; andre@0: PRTime thisUpdate; andre@0: PRTime nextUpdate; andre@0: }; andre@0: andre@0: struct OCSPCacheDataStr { andre@0: PLHashTable *entries; andre@0: PRUint32 numberOfEntries; andre@0: OCSPCacheItem *MRUitem; /* most recently used cache item */ andre@0: OCSPCacheItem *LRUitem; /* least recently used cache item */ andre@0: }; andre@0: andre@0: static struct OCSPGlobalStruct { andre@0: PRMonitor *monitor; andre@0: const SEC_HttpClientFcn *defaultHttpClientFcn; andre@0: PRInt32 maxCacheEntries; andre@0: PRUint32 minimumSecondsToNextFetchAttempt; andre@0: PRUint32 maximumSecondsToNextFetchAttempt; andre@0: PRUint32 timeoutSeconds; andre@0: OCSPCacheData cache; andre@0: SEC_OcspFailureMode ocspFailureMode; andre@0: CERT_StringFromCertFcn alternateOCSPAIAFcn; andre@0: PRBool forcePost; andre@0: } OCSP_Global = { NULL, andre@0: NULL, andre@0: DEFAULT_OCSP_CACHE_SIZE, andre@0: DEFAULT_MINIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT, andre@0: DEFAULT_MAXIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT, andre@0: DEFAULT_OSCP_TIMEOUT_SECONDS, andre@0: {NULL, 0, NULL, NULL}, andre@0: ocspMode_FailureIsVerificationFailure, andre@0: NULL, andre@0: PR_FALSE andre@0: }; andre@0: andre@0: andre@0: andre@0: /* Forward declarations */ andre@0: static SECItem * andre@0: ocsp_GetEncodedOCSPResponseFromRequest(PLArenaPool *arena, andre@0: CERTOCSPRequest *request, andre@0: const char *location, andre@0: const char *method, andre@0: PRTime time, andre@0: PRBool addServiceLocator, andre@0: void *pwArg, andre@0: CERTOCSPRequest **pRequest); andre@0: static SECStatus andre@0: ocsp_GetOCSPStatusFromNetwork(CERTCertDBHandle *handle, andre@0: CERTOCSPCertID *certID, andre@0: CERTCertificate *cert, andre@0: PRTime time, andre@0: void *pwArg, andre@0: PRBool *certIDWasConsumed, andre@0: SECStatus *rv_ocsp); andre@0: andre@0: static SECStatus andre@0: ocsp_GetDecodedVerifiedSingleResponseForID(CERTCertDBHandle *handle, andre@0: CERTOCSPCertID *certID, andre@0: CERTCertificate *cert, andre@0: PRTime time, andre@0: void *pwArg, andre@0: const SECItem *encodedResponse, andre@0: CERTOCSPResponse **pDecodedResponse, andre@0: CERTOCSPSingleResponse **pSingle); andre@0: andre@0: static SECStatus andre@0: ocsp_CertRevokedAfter(ocspRevokedInfo *revokedInfo, PRTime time); andre@0: andre@0: static CERTOCSPCertID * andre@0: cert_DupOCSPCertID(const CERTOCSPCertID *src); andre@0: andre@0: #ifndef DEBUG andre@0: #define OCSP_TRACE(msg) andre@0: #define OCSP_TRACE_TIME(msg, time) andre@0: #define OCSP_TRACE_CERT(cert) andre@0: #define OCSP_TRACE_CERTID(certid) andre@0: #else andre@0: #define OCSP_TRACE(msg) ocsp_Trace msg andre@0: #define OCSP_TRACE_TIME(msg, time) ocsp_dumpStringWithTime(msg, time) andre@0: #define OCSP_TRACE_CERT(cert) dumpCertificate(cert) andre@0: #define OCSP_TRACE_CERTID(certid) dumpCertID(certid) andre@0: andre@0: #if defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_BEOS) \ andre@0: || defined(XP_MACOSX) andre@0: #define NSS_HAVE_GETENV 1 andre@0: #endif andre@0: andre@0: static PRBool wantOcspTrace(void) andre@0: { andre@0: static PRBool firstTime = PR_TRUE; andre@0: static PRBool wantTrace = PR_FALSE; andre@0: andre@0: #ifdef NSS_HAVE_GETENV andre@0: if (firstTime) { andre@0: char *ev = getenv("NSS_TRACE_OCSP"); andre@0: if (ev && ev[0]) { andre@0: wantTrace = PR_TRUE; andre@0: } andre@0: firstTime = PR_FALSE; andre@0: } andre@0: #endif andre@0: return wantTrace; andre@0: } andre@0: andre@0: static void andre@0: ocsp_Trace(const char *format, ...) andre@0: { andre@0: char buf[2000]; andre@0: va_list args; andre@0: andre@0: if (!wantOcspTrace()) andre@0: return; andre@0: va_start(args, format); andre@0: PR_vsnprintf(buf, sizeof(buf), format, args); andre@0: va_end(args); andre@0: PR_LogPrint("%s", buf); andre@0: } andre@0: andre@0: static void andre@0: ocsp_dumpStringWithTime(const char *str, PRTime time) andre@0: { andre@0: PRExplodedTime timePrintable; andre@0: char timestr[256]; andre@0: andre@0: if (!wantOcspTrace()) andre@0: return; andre@0: PR_ExplodeTime(time, PR_GMTParameters, &timePrintable); andre@0: if (PR_FormatTime(timestr, 256, "%a %b %d %H:%M:%S %Y", &timePrintable)) { andre@0: ocsp_Trace("OCSP %s %s\n", str, timestr); andre@0: } andre@0: } andre@0: andre@0: static void andre@0: printHexString(const char *prefix, SECItem *hexval) andre@0: { andre@0: unsigned int i; andre@0: char *hexbuf = NULL; andre@0: andre@0: for (i = 0; i < hexval->len; i++) { andre@0: if (i != hexval->len - 1) { andre@0: hexbuf = PR_sprintf_append(hexbuf, "%02x:", hexval->data[i]); andre@0: } else { andre@0: hexbuf = PR_sprintf_append(hexbuf, "%02x", hexval->data[i]); andre@0: } andre@0: } andre@0: if (hexbuf) { andre@0: ocsp_Trace("%s %s\n", prefix, hexbuf); andre@0: PR_smprintf_free(hexbuf); andre@0: } andre@0: } andre@0: andre@0: static void andre@0: dumpCertificate(CERTCertificate *cert) andre@0: { andre@0: if (!wantOcspTrace()) andre@0: return; andre@0: andre@0: ocsp_Trace("OCSP ----------------\n"); andre@0: ocsp_Trace("OCSP ## SUBJECT: %s\n", cert->subjectName); andre@0: { andre@0: PRTime timeBefore, timeAfter; andre@0: PRExplodedTime beforePrintable, afterPrintable; andre@0: char beforestr[256], afterstr[256]; andre@0: PRStatus rv1, rv2; andre@0: DER_DecodeTimeChoice(&timeBefore, &cert->validity.notBefore); andre@0: DER_DecodeTimeChoice(&timeAfter, &cert->validity.notAfter); andre@0: PR_ExplodeTime(timeBefore, PR_GMTParameters, &beforePrintable); andre@0: PR_ExplodeTime(timeAfter, PR_GMTParameters, &afterPrintable); andre@0: rv1 = PR_FormatTime(beforestr, 256, "%a %b %d %H:%M:%S %Y", andre@0: &beforePrintable); andre@0: rv2 = PR_FormatTime(afterstr, 256, "%a %b %d %H:%M:%S %Y", andre@0: &afterPrintable); andre@0: ocsp_Trace("OCSP ## VALIDITY: %s to %s\n", rv1 ? beforestr : "", andre@0: rv2 ? afterstr : ""); andre@0: } andre@0: ocsp_Trace("OCSP ## ISSUER: %s\n", cert->issuerName); andre@0: printHexString("OCSP ## SERIAL NUMBER:", &cert->serialNumber); andre@0: } andre@0: andre@0: static void andre@0: dumpCertID(CERTOCSPCertID *certID) andre@0: { andre@0: if (!wantOcspTrace()) andre@0: return; andre@0: andre@0: printHexString("OCSP certID issuer", &certID->issuerNameHash); andre@0: printHexString("OCSP certID serial", &certID->serialNumber); andre@0: } andre@0: #endif andre@0: andre@0: SECStatus andre@0: SEC_RegisterDefaultHttpClient(const SEC_HttpClientFcn *fcnTable) andre@0: { andre@0: if (!OCSP_Global.monitor) { andre@0: PORT_SetError(SEC_ERROR_NOT_INITIALIZED); andre@0: return SECFailure; andre@0: } andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: OCSP_Global.defaultHttpClientFcn = fcnTable; andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: andre@0: return SECSuccess; andre@0: } andre@0: andre@0: SECStatus andre@0: CERT_RegisterAlternateOCSPAIAInfoCallBack( andre@0: CERT_StringFromCertFcn newCallback, andre@0: CERT_StringFromCertFcn * oldCallback) andre@0: { andre@0: CERT_StringFromCertFcn old; andre@0: andre@0: if (!OCSP_Global.monitor) { andre@0: PORT_SetError(SEC_ERROR_NOT_INITIALIZED); andre@0: return SECFailure; andre@0: } andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: old = OCSP_Global.alternateOCSPAIAFcn; andre@0: OCSP_Global.alternateOCSPAIAFcn = newCallback; andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: if (oldCallback) andre@0: *oldCallback = old; andre@0: return SECSuccess; andre@0: } andre@0: andre@0: static PLHashNumber PR_CALLBACK andre@0: ocsp_CacheKeyHashFunction(const void *key) andre@0: { andre@0: CERTOCSPCertID *cid = (CERTOCSPCertID *)key; andre@0: PLHashNumber hash = 0; andre@0: unsigned int i; andre@0: unsigned char *walk; andre@0: andre@0: /* a very simple hash calculation for the initial coding phase */ andre@0: walk = (unsigned char*)cid->issuerNameHash.data; andre@0: for (i=0; i < cid->issuerNameHash.len; ++i, ++walk) { andre@0: hash += *walk; andre@0: } andre@0: walk = (unsigned char*)cid->issuerKeyHash.data; andre@0: for (i=0; i < cid->issuerKeyHash.len; ++i, ++walk) { andre@0: hash += *walk; andre@0: } andre@0: walk = (unsigned char*)cid->serialNumber.data; andre@0: for (i=0; i < cid->serialNumber.len; ++i, ++walk) { andre@0: hash += *walk; andre@0: } andre@0: return hash; andre@0: } andre@0: andre@0: static PRIntn PR_CALLBACK andre@0: ocsp_CacheKeyCompareFunction(const void *v1, const void *v2) andre@0: { andre@0: CERTOCSPCertID *cid1 = (CERTOCSPCertID *)v1; andre@0: CERTOCSPCertID *cid2 = (CERTOCSPCertID *)v2; andre@0: andre@0: return (SECEqual == SECITEM_CompareItem(&cid1->issuerNameHash, andre@0: &cid2->issuerNameHash) andre@0: && SECEqual == SECITEM_CompareItem(&cid1->issuerKeyHash, andre@0: &cid2->issuerKeyHash) andre@0: && SECEqual == SECITEM_CompareItem(&cid1->serialNumber, andre@0: &cid2->serialNumber)); andre@0: } andre@0: andre@0: static SECStatus andre@0: ocsp_CopyRevokedInfo(PLArenaPool *arena, ocspCertStatus *dest, andre@0: ocspRevokedInfo *src) andre@0: { andre@0: SECStatus rv = SECFailure; andre@0: void *mark; andre@0: andre@0: mark = PORT_ArenaMark(arena); andre@0: andre@0: dest->certStatusInfo.revokedInfo = andre@0: (ocspRevokedInfo *) PORT_ArenaZAlloc(arena, sizeof(ocspRevokedInfo)); andre@0: if (!dest->certStatusInfo.revokedInfo) { andre@0: goto loser; andre@0: } andre@0: andre@0: rv = SECITEM_CopyItem(arena, andre@0: &dest->certStatusInfo.revokedInfo->revocationTime, andre@0: &src->revocationTime); andre@0: if (rv != SECSuccess) { andre@0: goto loser; andre@0: } andre@0: andre@0: if (src->revocationReason) { andre@0: dest->certStatusInfo.revokedInfo->revocationReason = andre@0: SECITEM_ArenaDupItem(arena, src->revocationReason); andre@0: if (!dest->certStatusInfo.revokedInfo->revocationReason) { andre@0: goto loser; andre@0: } andre@0: } else { andre@0: dest->certStatusInfo.revokedInfo->revocationReason = NULL; andre@0: } andre@0: andre@0: PORT_ArenaUnmark(arena, mark); andre@0: return SECSuccess; andre@0: andre@0: loser: andre@0: PORT_ArenaRelease(arena, mark); andre@0: return SECFailure; andre@0: } andre@0: andre@0: static SECStatus andre@0: ocsp_CopyCertStatus(PLArenaPool *arena, ocspCertStatus *dest, andre@0: ocspCertStatus*src) andre@0: { andre@0: SECStatus rv = SECFailure; andre@0: dest->certStatusType = src->certStatusType; andre@0: andre@0: switch (src->certStatusType) { andre@0: case ocspCertStatus_good: andre@0: dest->certStatusInfo.goodInfo = andre@0: SECITEM_ArenaDupItem(arena, src->certStatusInfo.goodInfo); andre@0: if (dest->certStatusInfo.goodInfo != NULL) { andre@0: rv = SECSuccess; andre@0: } andre@0: break; andre@0: case ocspCertStatus_revoked: andre@0: rv = ocsp_CopyRevokedInfo(arena, dest, andre@0: src->certStatusInfo.revokedInfo); andre@0: break; andre@0: case ocspCertStatus_unknown: andre@0: dest->certStatusInfo.unknownInfo = andre@0: SECITEM_ArenaDupItem(arena, src->certStatusInfo.unknownInfo); andre@0: if (dest->certStatusInfo.unknownInfo != NULL) { andre@0: rv = SECSuccess; andre@0: } andre@0: break; andre@0: case ocspCertStatus_other: andre@0: default: andre@0: PORT_Assert(src->certStatusType == ocspCertStatus_other); andre@0: dest->certStatusInfo.otherInfo = andre@0: SECITEM_ArenaDupItem(arena, src->certStatusInfo.otherInfo); andre@0: if (dest->certStatusInfo.otherInfo != NULL) { andre@0: rv = SECSuccess; andre@0: } andre@0: break; andre@0: } andre@0: return rv; andre@0: } andre@0: andre@0: static void andre@0: ocsp_AddCacheItemToLinkedList(OCSPCacheData *cache, OCSPCacheItem *new_most_recent) andre@0: { andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: andre@0: if (!cache->LRUitem) { andre@0: cache->LRUitem = new_most_recent; andre@0: } andre@0: new_most_recent->lessRecent = cache->MRUitem; andre@0: new_most_recent->moreRecent = NULL; andre@0: andre@0: if (cache->MRUitem) { andre@0: cache->MRUitem->moreRecent = new_most_recent; andre@0: } andre@0: cache->MRUitem = new_most_recent; andre@0: andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: } andre@0: andre@0: static void andre@0: ocsp_RemoveCacheItemFromLinkedList(OCSPCacheData *cache, OCSPCacheItem *item) andre@0: { andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: andre@0: if (!item->lessRecent && !item->moreRecent) { andre@0: /* andre@0: * Fail gracefully on attempts to remove an item from the list, andre@0: * which is currently not part of the list. andre@0: * But check for the edge case it is the single entry in the list. andre@0: */ andre@0: if (item == cache->LRUitem && andre@0: item == cache->MRUitem) { andre@0: /* remove the single entry */ andre@0: PORT_Assert(cache->numberOfEntries == 1); andre@0: PORT_Assert(item->moreRecent == NULL); andre@0: cache->MRUitem = NULL; andre@0: cache->LRUitem = NULL; andre@0: } andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return; andre@0: } andre@0: andre@0: PORT_Assert(cache->numberOfEntries > 1); andre@0: andre@0: if (item == cache->LRUitem) { andre@0: PORT_Assert(item != cache->MRUitem); andre@0: PORT_Assert(item->lessRecent == NULL); andre@0: PORT_Assert(item->moreRecent != NULL); andre@0: PORT_Assert(item->moreRecent->lessRecent == item); andre@0: cache->LRUitem = item->moreRecent; andre@0: cache->LRUitem->lessRecent = NULL; andre@0: } andre@0: else if (item == cache->MRUitem) { andre@0: PORT_Assert(item->moreRecent == NULL); andre@0: PORT_Assert(item->lessRecent != NULL); andre@0: PORT_Assert(item->lessRecent->moreRecent == item); andre@0: cache->MRUitem = item->lessRecent; andre@0: cache->MRUitem->moreRecent = NULL; andre@0: } else { andre@0: /* remove an entry in the middle of the list */ andre@0: PORT_Assert(item->moreRecent != NULL); andre@0: PORT_Assert(item->lessRecent != NULL); andre@0: PORT_Assert(item->lessRecent->moreRecent == item); andre@0: PORT_Assert(item->moreRecent->lessRecent == item); andre@0: item->moreRecent->lessRecent = item->lessRecent; andre@0: item->lessRecent->moreRecent = item->moreRecent; andre@0: } andre@0: andre@0: item->lessRecent = NULL; andre@0: item->moreRecent = NULL; andre@0: andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: } andre@0: andre@0: static void andre@0: ocsp_MakeCacheEntryMostRecent(OCSPCacheData *cache, OCSPCacheItem *new_most_recent) andre@0: { andre@0: OCSP_TRACE(("OCSP ocsp_MakeCacheEntryMostRecent THREADID %p\n", andre@0: PR_GetCurrentThread())); andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: if (cache->MRUitem == new_most_recent) { andre@0: OCSP_TRACE(("OCSP ocsp_MakeCacheEntryMostRecent ALREADY MOST\n")); andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return; andre@0: } andre@0: OCSP_TRACE(("OCSP ocsp_MakeCacheEntryMostRecent NEW entry\n")); andre@0: ocsp_RemoveCacheItemFromLinkedList(cache, new_most_recent); andre@0: ocsp_AddCacheItemToLinkedList(cache, new_most_recent); andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: } andre@0: andre@0: static PRBool andre@0: ocsp_IsCacheDisabled(void) andre@0: { andre@0: /* andre@0: * maxCacheEntries == 0 means unlimited cache entries andre@0: * maxCacheEntries < 0 means cache is disabled andre@0: */ andre@0: PRBool retval; andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: retval = (OCSP_Global.maxCacheEntries < 0); andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return retval; andre@0: } andre@0: andre@0: static OCSPCacheItem * andre@0: ocsp_FindCacheEntry(OCSPCacheData *cache, CERTOCSPCertID *certID) andre@0: { andre@0: OCSPCacheItem *found_ocsp_item = NULL; andre@0: OCSP_TRACE(("OCSP ocsp_FindCacheEntry\n")); andre@0: OCSP_TRACE_CERTID(certID); andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: if (ocsp_IsCacheDisabled()) andre@0: goto loser; andre@0: andre@0: found_ocsp_item = (OCSPCacheItem *)PL_HashTableLookup( andre@0: cache->entries, certID); andre@0: if (!found_ocsp_item) andre@0: goto loser; andre@0: andre@0: OCSP_TRACE(("OCSP ocsp_FindCacheEntry FOUND!\n")); andre@0: ocsp_MakeCacheEntryMostRecent(cache, found_ocsp_item); andre@0: andre@0: loser: andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return found_ocsp_item; andre@0: } andre@0: andre@0: static void andre@0: ocsp_FreeCacheItem(OCSPCacheItem *item) andre@0: { andre@0: OCSP_TRACE(("OCSP ocsp_FreeCacheItem\n")); andre@0: if (item->certStatusArena) { andre@0: PORT_FreeArena(item->certStatusArena, PR_FALSE); andre@0: } andre@0: if (item->certID->poolp) { andre@0: /* freeing this poolp arena will also free item */ andre@0: PORT_FreeArena(item->certID->poolp, PR_FALSE); andre@0: } andre@0: } andre@0: andre@0: static void andre@0: ocsp_RemoveCacheItem(OCSPCacheData *cache, OCSPCacheItem *item) andre@0: { andre@0: /* The item we're removing could be either the least recently used item, andre@0: * or it could be an item that couldn't get updated with newer status info andre@0: * because of an allocation failure, or it could get removed because we're andre@0: * cleaning up. andre@0: */ andre@0: PRBool couldRemoveFromHashTable; andre@0: OCSP_TRACE(("OCSP ocsp_RemoveCacheItem, THREADID %p\n", PR_GetCurrentThread())); andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: andre@0: ocsp_RemoveCacheItemFromLinkedList(cache, item); andre@0: couldRemoveFromHashTable = PL_HashTableRemove(cache->entries, andre@0: item->certID); andre@0: PORT_Assert(couldRemoveFromHashTable); andre@0: --cache->numberOfEntries; andre@0: ocsp_FreeCacheItem(item); andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: } andre@0: andre@0: static void andre@0: ocsp_CheckCacheSize(OCSPCacheData *cache) andre@0: { andre@0: OCSP_TRACE(("OCSP ocsp_CheckCacheSize\n")); andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: if (OCSP_Global.maxCacheEntries > 0) { andre@0: /* Cache is not disabled. Number of cache entries is limited. andre@0: * The monitor ensures that maxCacheEntries remains positive. andre@0: */ andre@0: while (cache->numberOfEntries > andre@0: (PRUint32)OCSP_Global.maxCacheEntries) { andre@0: ocsp_RemoveCacheItem(cache, cache->LRUitem); andre@0: } andre@0: } andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: } andre@0: andre@0: SECStatus andre@0: CERT_ClearOCSPCache(void) andre@0: { andre@0: OCSP_TRACE(("OCSP CERT_ClearOCSPCache\n")); andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: while (OCSP_Global.cache.numberOfEntries > 0) { andre@0: ocsp_RemoveCacheItem(&OCSP_Global.cache, andre@0: OCSP_Global.cache.LRUitem); andre@0: } andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return SECSuccess; andre@0: } andre@0: andre@0: static SECStatus andre@0: ocsp_CreateCacheItemAndConsumeCertID(OCSPCacheData *cache, andre@0: CERTOCSPCertID *certID, andre@0: OCSPCacheItem **pCacheItem) andre@0: { andre@0: PLArenaPool *arena; andre@0: void *mark; andre@0: PLHashEntry *new_hash_entry; andre@0: OCSPCacheItem *item; andre@0: andre@0: PORT_Assert(pCacheItem != NULL); andre@0: *pCacheItem = NULL; andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: arena = certID->poolp; andre@0: mark = PORT_ArenaMark(arena); andre@0: andre@0: /* ZAlloc will init all Bools to False and all Pointers to NULL andre@0: and all error codes to zero/good. */ andre@0: item = (OCSPCacheItem *)PORT_ArenaZAlloc(certID->poolp, andre@0: sizeof(OCSPCacheItem)); andre@0: if (!item) { andre@0: goto loser; andre@0: } andre@0: item->certID = certID; andre@0: new_hash_entry = PL_HashTableAdd(cache->entries, item->certID, andre@0: item); andre@0: if (!new_hash_entry) { andre@0: goto loser; andre@0: } andre@0: ++cache->numberOfEntries; andre@0: PORT_ArenaUnmark(arena, mark); andre@0: ocsp_AddCacheItemToLinkedList(cache, item); andre@0: *pCacheItem = item; andre@0: andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return SECSuccess; andre@0: andre@0: loser: andre@0: PORT_ArenaRelease(arena, mark); andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return SECFailure; andre@0: } andre@0: andre@0: static SECStatus andre@0: ocsp_SetCacheItemResponse(OCSPCacheItem *item, andre@0: const CERTOCSPSingleResponse *response) andre@0: { andre@0: if (item->certStatusArena) { andre@0: PORT_FreeArena(item->certStatusArena, PR_FALSE); andre@0: item->certStatusArena = NULL; andre@0: } andre@0: item->haveThisUpdate = item->haveNextUpdate = PR_FALSE; andre@0: if (response) { andre@0: SECStatus rv; andre@0: item->certStatusArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); andre@0: if (item->certStatusArena == NULL) { andre@0: return SECFailure; andre@0: } andre@0: rv = ocsp_CopyCertStatus(item->certStatusArena, &item->certStatus, andre@0: response->certStatus); andre@0: if (rv != SECSuccess) { andre@0: PORT_FreeArena(item->certStatusArena, PR_FALSE); andre@0: item->certStatusArena = NULL; andre@0: return rv; andre@0: } andre@0: item->missingResponseError = 0; andre@0: rv = DER_GeneralizedTimeToTime(&item->thisUpdate, andre@0: &response->thisUpdate); andre@0: item->haveThisUpdate = (rv == SECSuccess); andre@0: if (response->nextUpdate) { andre@0: rv = DER_GeneralizedTimeToTime(&item->nextUpdate, andre@0: response->nextUpdate); andre@0: item->haveNextUpdate = (rv == SECSuccess); andre@0: } else { andre@0: item->haveNextUpdate = PR_FALSE; andre@0: } andre@0: } andre@0: return SECSuccess; andre@0: } andre@0: andre@0: static void andre@0: ocsp_FreshenCacheItemNextFetchAttemptTime(OCSPCacheItem *cacheItem) andre@0: { andre@0: PRTime now; andre@0: PRTime earliestAllowedNextFetchAttemptTime; andre@0: PRTime latestTimeWhenResponseIsConsideredFresh; andre@0: andre@0: OCSP_TRACE(("OCSP ocsp_FreshenCacheItemNextFetchAttemptTime\n")); andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: andre@0: now = PR_Now(); andre@0: OCSP_TRACE_TIME("now:", now); andre@0: andre@0: if (cacheItem->haveThisUpdate) { andre@0: OCSP_TRACE_TIME("thisUpdate:", cacheItem->thisUpdate); andre@0: latestTimeWhenResponseIsConsideredFresh = cacheItem->thisUpdate + andre@0: OCSP_Global.maximumSecondsToNextFetchAttempt * andre@0: MICROSECONDS_PER_SECOND; andre@0: OCSP_TRACE_TIME("latestTimeWhenResponseIsConsideredFresh:", andre@0: latestTimeWhenResponseIsConsideredFresh); andre@0: } else { andre@0: latestTimeWhenResponseIsConsideredFresh = now + andre@0: OCSP_Global.minimumSecondsToNextFetchAttempt * andre@0: MICROSECONDS_PER_SECOND; andre@0: OCSP_TRACE_TIME("no thisUpdate, " andre@0: "latestTimeWhenResponseIsConsideredFresh:", andre@0: latestTimeWhenResponseIsConsideredFresh); andre@0: } andre@0: andre@0: if (cacheItem->haveNextUpdate) { andre@0: OCSP_TRACE_TIME("have nextUpdate:", cacheItem->nextUpdate); andre@0: } andre@0: andre@0: if (cacheItem->haveNextUpdate && andre@0: cacheItem->nextUpdate < latestTimeWhenResponseIsConsideredFresh) { andre@0: latestTimeWhenResponseIsConsideredFresh = cacheItem->nextUpdate; andre@0: OCSP_TRACE_TIME("nextUpdate is smaller than latestFresh, setting " andre@0: "latestTimeWhenResponseIsConsideredFresh:", andre@0: latestTimeWhenResponseIsConsideredFresh); andre@0: } andre@0: andre@0: earliestAllowedNextFetchAttemptTime = now + andre@0: OCSP_Global.minimumSecondsToNextFetchAttempt * andre@0: MICROSECONDS_PER_SECOND; andre@0: OCSP_TRACE_TIME("earliestAllowedNextFetchAttemptTime:", andre@0: earliestAllowedNextFetchAttemptTime); andre@0: andre@0: if (latestTimeWhenResponseIsConsideredFresh < andre@0: earliestAllowedNextFetchAttemptTime) { andre@0: latestTimeWhenResponseIsConsideredFresh = andre@0: earliestAllowedNextFetchAttemptTime; andre@0: OCSP_TRACE_TIME("latest < earliest, setting latest to:", andre@0: latestTimeWhenResponseIsConsideredFresh); andre@0: } andre@0: andre@0: cacheItem->nextFetchAttemptTime = andre@0: latestTimeWhenResponseIsConsideredFresh; andre@0: OCSP_TRACE_TIME("nextFetchAttemptTime", andre@0: latestTimeWhenResponseIsConsideredFresh); andre@0: andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: } andre@0: andre@0: static PRBool andre@0: ocsp_IsCacheItemFresh(OCSPCacheItem *cacheItem) andre@0: { andre@0: PRTime now; andre@0: PRBool fresh; andre@0: andre@0: now = PR_Now(); andre@0: andre@0: fresh = cacheItem->nextFetchAttemptTime > now; andre@0: andre@0: /* Work around broken OCSP responders that return unknown responses for andre@0: * certificates, especially certificates that were just recently issued. andre@0: */ andre@0: if (fresh && cacheItem->certStatusArena && andre@0: cacheItem->certStatus.certStatusType == ocspCertStatus_unknown) { andre@0: fresh = PR_FALSE; andre@0: } andre@0: andre@0: OCSP_TRACE(("OCSP ocsp_IsCacheItemFresh: %d\n", fresh)); andre@0: andre@0: return fresh; andre@0: } andre@0: andre@0: /* andre@0: * Status in *certIDWasConsumed will always be correct, regardless of andre@0: * return value. andre@0: * If the caller is unable to transfer ownership of certID, andre@0: * then the caller must set certIDWasConsumed to NULL, andre@0: * and this function will potentially duplicate the certID object. andre@0: */ andre@0: static SECStatus andre@0: ocsp_CreateOrUpdateCacheEntry(OCSPCacheData *cache, andre@0: CERTOCSPCertID *certID, andre@0: CERTOCSPSingleResponse *single, andre@0: PRBool *certIDWasConsumed) andre@0: { andre@0: SECStatus rv; andre@0: OCSPCacheItem *cacheItem; andre@0: OCSP_TRACE(("OCSP ocsp_CreateOrUpdateCacheEntry\n")); andre@0: andre@0: if (certIDWasConsumed) andre@0: *certIDWasConsumed = PR_FALSE; andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: PORT_Assert(OCSP_Global.maxCacheEntries >= 0); andre@0: andre@0: cacheItem = ocsp_FindCacheEntry(cache, certID); andre@0: andre@0: /* Don't replace an unknown or revoked entry with an error entry, even if andre@0: * the existing entry is expired. Instead, we'll continue to use the andre@0: * existing (possibly expired) cache entry until we receive a valid signed andre@0: * response to replace it. andre@0: */ andre@0: if (!single && cacheItem && cacheItem->certStatusArena && andre@0: (cacheItem->certStatus.certStatusType == ocspCertStatus_revoked || andre@0: cacheItem->certStatus.certStatusType == ocspCertStatus_unknown)) { andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return SECSuccess; andre@0: } andre@0: andre@0: if (!cacheItem) { andre@0: CERTOCSPCertID *myCertID; andre@0: if (certIDWasConsumed) { andre@0: myCertID = certID; andre@0: *certIDWasConsumed = PR_TRUE; andre@0: } else { andre@0: myCertID = cert_DupOCSPCertID(certID); andre@0: if (!myCertID) { andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: PORT_SetError(PR_OUT_OF_MEMORY_ERROR); andre@0: return SECFailure; andre@0: } andre@0: } andre@0: andre@0: rv = ocsp_CreateCacheItemAndConsumeCertID(cache, myCertID, andre@0: &cacheItem); andre@0: if (rv != SECSuccess) { andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return rv; andre@0: } andre@0: } andre@0: if (single) { andre@0: PRTime thisUpdate; andre@0: rv = DER_GeneralizedTimeToTime(&thisUpdate, &single->thisUpdate); andre@0: andre@0: if (!cacheItem->haveThisUpdate || andre@0: (rv == SECSuccess && cacheItem->thisUpdate < thisUpdate)) { andre@0: rv = ocsp_SetCacheItemResponse(cacheItem, single); andre@0: if (rv != SECSuccess) { andre@0: ocsp_RemoveCacheItem(cache, cacheItem); andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return rv; andre@0: } andre@0: } else { andre@0: OCSP_TRACE(("Not caching response because the response is not " andre@0: "newer than the cache")); andre@0: } andre@0: } else { andre@0: cacheItem->missingResponseError = PORT_GetError(); andre@0: if (cacheItem->certStatusArena) { andre@0: PORT_FreeArena(cacheItem->certStatusArena, PR_FALSE); andre@0: cacheItem->certStatusArena = NULL; andre@0: } andre@0: } andre@0: ocsp_FreshenCacheItemNextFetchAttemptTime(cacheItem); andre@0: ocsp_CheckCacheSize(cache); andre@0: andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return SECSuccess; andre@0: } andre@0: andre@0: extern SECStatus andre@0: CERT_SetOCSPFailureMode(SEC_OcspFailureMode ocspFailureMode) andre@0: { andre@0: switch (ocspFailureMode) { andre@0: case ocspMode_FailureIsVerificationFailure: andre@0: case ocspMode_FailureIsNotAVerificationFailure: andre@0: break; andre@0: default: andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: return SECFailure; andre@0: } andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: OCSP_Global.ocspFailureMode = ocspFailureMode; andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return SECSuccess; andre@0: } andre@0: andre@0: SECStatus andre@0: CERT_OCSPCacheSettings(PRInt32 maxCacheEntries, andre@0: PRUint32 minimumSecondsToNextFetchAttempt, andre@0: PRUint32 maximumSecondsToNextFetchAttempt) andre@0: { andre@0: if (minimumSecondsToNextFetchAttempt > maximumSecondsToNextFetchAttempt andre@0: || maxCacheEntries < -1) { andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: return SECFailure; andre@0: } andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: andre@0: if (maxCacheEntries < 0) { andre@0: OCSP_Global.maxCacheEntries = -1; /* disable cache */ andre@0: } else if (maxCacheEntries == 0) { andre@0: OCSP_Global.maxCacheEntries = 0; /* unlimited cache entries */ andre@0: } else { andre@0: OCSP_Global.maxCacheEntries = maxCacheEntries; andre@0: } andre@0: andre@0: if (minimumSecondsToNextFetchAttempt < andre@0: OCSP_Global.minimumSecondsToNextFetchAttempt andre@0: || maximumSecondsToNextFetchAttempt < andre@0: OCSP_Global.maximumSecondsToNextFetchAttempt) { andre@0: /* andre@0: * Ensure our existing cache entries are not used longer than the andre@0: * new settings allow, we're lazy and just clear the cache andre@0: */ andre@0: CERT_ClearOCSPCache(); andre@0: } andre@0: andre@0: OCSP_Global.minimumSecondsToNextFetchAttempt = andre@0: minimumSecondsToNextFetchAttempt; andre@0: OCSP_Global.maximumSecondsToNextFetchAttempt = andre@0: maximumSecondsToNextFetchAttempt; andre@0: ocsp_CheckCacheSize(&OCSP_Global.cache); andre@0: andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return SECSuccess; andre@0: } andre@0: andre@0: SECStatus andre@0: CERT_SetOCSPTimeout(PRUint32 seconds) andre@0: { andre@0: /* no locking, see bug 406120 */ andre@0: OCSP_Global.timeoutSeconds = seconds; andre@0: return SECSuccess; andre@0: } andre@0: andre@0: /* this function is called at NSS initialization time */ andre@0: SECStatus OCSP_InitGlobal(void) andre@0: { andre@0: SECStatus rv = SECFailure; andre@0: andre@0: if (OCSP_Global.monitor == NULL) { andre@0: OCSP_Global.monitor = PR_NewMonitor(); andre@0: } andre@0: if (!OCSP_Global.monitor) andre@0: return SECFailure; andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: if (!OCSP_Global.cache.entries) { andre@0: OCSP_Global.cache.entries = andre@0: PL_NewHashTable(0, andre@0: ocsp_CacheKeyHashFunction, andre@0: ocsp_CacheKeyCompareFunction, andre@0: PL_CompareValues, andre@0: NULL, andre@0: NULL); andre@0: OCSP_Global.ocspFailureMode = ocspMode_FailureIsVerificationFailure; andre@0: OCSP_Global.cache.numberOfEntries = 0; andre@0: OCSP_Global.cache.MRUitem = NULL; andre@0: OCSP_Global.cache.LRUitem = NULL; andre@0: } else { andre@0: /* andre@0: * NSS might call this function twice while attempting to init. andre@0: * But it's not allowed to call this again after any activity. andre@0: */ andre@0: PORT_Assert(OCSP_Global.cache.numberOfEntries == 0); andre@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); andre@0: } andre@0: if (OCSP_Global.cache.entries) andre@0: rv = SECSuccess; andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return rv; andre@0: } andre@0: andre@0: SECStatus OCSP_ShutdownGlobal(void) andre@0: { andre@0: if (!OCSP_Global.monitor) andre@0: return SECSuccess; andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: if (OCSP_Global.cache.entries) { andre@0: CERT_ClearOCSPCache(); andre@0: PL_HashTableDestroy(OCSP_Global.cache.entries); andre@0: OCSP_Global.cache.entries = NULL; andre@0: } andre@0: PORT_Assert(OCSP_Global.cache.numberOfEntries == 0); andre@0: OCSP_Global.cache.MRUitem = NULL; andre@0: OCSP_Global.cache.LRUitem = NULL; andre@0: andre@0: OCSP_Global.defaultHttpClientFcn = NULL; andre@0: OCSP_Global.maxCacheEntries = DEFAULT_OCSP_CACHE_SIZE; andre@0: OCSP_Global.minimumSecondsToNextFetchAttempt = andre@0: DEFAULT_MINIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT; andre@0: OCSP_Global.maximumSecondsToNextFetchAttempt = andre@0: DEFAULT_MAXIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT; andre@0: OCSP_Global.ocspFailureMode = andre@0: ocspMode_FailureIsVerificationFailure; andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: andre@0: PR_DestroyMonitor(OCSP_Global.monitor); andre@0: OCSP_Global.monitor = NULL; andre@0: return SECSuccess; andre@0: } andre@0: andre@0: /* andre@0: * A return value of NULL means: andre@0: * The application did not register it's own HTTP client. andre@0: */ andre@0: const SEC_HttpClientFcn *SEC_GetRegisteredHttpClient(void) andre@0: { andre@0: const SEC_HttpClientFcn *retval; andre@0: andre@0: if (!OCSP_Global.monitor) { andre@0: PORT_SetError(SEC_ERROR_NOT_INITIALIZED); andre@0: return NULL; andre@0: } andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: retval = OCSP_Global.defaultHttpClientFcn; andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: andre@0: return retval; andre@0: } andre@0: andre@0: /* andre@0: * The following structure is only used internally. It is allocated when andre@0: * someone turns on OCSP checking, and hangs off of the status-configuration andre@0: * structure in the certdb structure. We use it to keep configuration andre@0: * information specific to OCSP checking. andre@0: */ andre@0: typedef struct ocspCheckingContextStr { andre@0: PRBool useDefaultResponder; andre@0: char *defaultResponderURI; andre@0: char *defaultResponderNickname; andre@0: CERTCertificate *defaultResponderCert; andre@0: } ocspCheckingContext; andre@0: andre@0: SEC_ASN1_MKSUB(SEC_AnyTemplate) andre@0: SEC_ASN1_MKSUB(SEC_IntegerTemplate) andre@0: SEC_ASN1_MKSUB(SEC_NullTemplate) andre@0: SEC_ASN1_MKSUB(SEC_OctetStringTemplate) andre@0: SEC_ASN1_MKSUB(SEC_PointerToAnyTemplate) andre@0: SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate) andre@0: SEC_ASN1_MKSUB(SEC_SequenceOfAnyTemplate) andre@0: SEC_ASN1_MKSUB(SEC_PointerToGeneralizedTimeTemplate) andre@0: SEC_ASN1_MKSUB(SEC_PointerToEnumeratedTemplate) andre@0: andre@0: /* andre@0: * Forward declarations of sub-types, so I can lay out the types in the andre@0: * same order as the ASN.1 is laid out in the OCSP spec itself. andre@0: * andre@0: * These are in alphabetical order (case-insensitive); please keep it that way! andre@0: */ andre@0: extern const SEC_ASN1Template ocsp_CertIDTemplate[]; andre@0: extern const SEC_ASN1Template ocsp_PointerToSignatureTemplate[]; andre@0: extern const SEC_ASN1Template ocsp_PointerToResponseBytesTemplate[]; andre@0: extern const SEC_ASN1Template ocsp_ResponseDataTemplate[]; andre@0: extern const SEC_ASN1Template ocsp_RevokedInfoTemplate[]; andre@0: extern const SEC_ASN1Template ocsp_SingleRequestTemplate[]; andre@0: extern const SEC_ASN1Template ocsp_SingleResponseTemplate[]; andre@0: extern const SEC_ASN1Template ocsp_TBSRequestTemplate[]; andre@0: andre@0: andre@0: /* andre@0: * Request-related templates... andre@0: */ andre@0: andre@0: /* andre@0: * OCSPRequest ::= SEQUENCE { andre@0: * tbsRequest TBSRequest, andre@0: * optionalSignature [0] EXPLICIT Signature OPTIONAL } andre@0: */ andre@0: static const SEC_ASN1Template ocsp_OCSPRequestTemplate[] = { andre@0: { SEC_ASN1_SEQUENCE, andre@0: 0, NULL, sizeof(CERTOCSPRequest) }, andre@0: { SEC_ASN1_POINTER, andre@0: offsetof(CERTOCSPRequest, tbsRequest), andre@0: ocsp_TBSRequestTemplate }, andre@0: { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | andre@0: SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, andre@0: offsetof(CERTOCSPRequest, optionalSignature), andre@0: ocsp_PointerToSignatureTemplate }, andre@0: { 0 } andre@0: }; andre@0: andre@0: /* andre@0: * TBSRequest ::= SEQUENCE { andre@0: * version [0] EXPLICIT Version DEFAULT v1, andre@0: * requestorName [1] EXPLICIT GeneralName OPTIONAL, andre@0: * requestList SEQUENCE OF Request, andre@0: * requestExtensions [2] EXPLICIT Extensions OPTIONAL } andre@0: * andre@0: * Version ::= INTEGER { v1(0) } andre@0: * andre@0: * Note: this should be static but the AIX compiler doesn't like it (because it andre@0: * was forward-declared above); it is not meant to be exported, but this andre@0: * is the only way it will compile. andre@0: */ andre@0: const SEC_ASN1Template ocsp_TBSRequestTemplate[] = { andre@0: { SEC_ASN1_SEQUENCE, andre@0: 0, NULL, sizeof(ocspTBSRequest) }, andre@0: { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | /* XXX DER_DEFAULT */ andre@0: SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, andre@0: offsetof(ocspTBSRequest, version), andre@0: SEC_ASN1_SUB(SEC_IntegerTemplate) }, andre@0: { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | andre@0: SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1, andre@0: offsetof(ocspTBSRequest, derRequestorName), andre@0: SEC_ASN1_SUB(SEC_PointerToAnyTemplate) }, andre@0: { SEC_ASN1_SEQUENCE_OF, andre@0: offsetof(ocspTBSRequest, requestList), andre@0: ocsp_SingleRequestTemplate }, andre@0: { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | andre@0: SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 2, andre@0: offsetof(ocspTBSRequest, requestExtensions), andre@0: CERT_SequenceOfCertExtensionTemplate }, andre@0: { 0 } andre@0: }; andre@0: andre@0: /* andre@0: * Signature ::= SEQUENCE { andre@0: * signatureAlgorithm AlgorithmIdentifier, andre@0: * signature BIT STRING, andre@0: * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } andre@0: */ andre@0: static const SEC_ASN1Template ocsp_SignatureTemplate[] = { andre@0: { SEC_ASN1_SEQUENCE, andre@0: 0, NULL, sizeof(ocspSignature) }, andre@0: { SEC_ASN1_INLINE | SEC_ASN1_XTRN, andre@0: offsetof(ocspSignature, signatureAlgorithm), andre@0: SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, andre@0: { SEC_ASN1_BIT_STRING, andre@0: offsetof(ocspSignature, signature) }, andre@0: { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | andre@0: SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, andre@0: offsetof(ocspSignature, derCerts), andre@0: SEC_ASN1_SUB(SEC_SequenceOfAnyTemplate) }, andre@0: { 0 } andre@0: }; andre@0: andre@0: /* andre@0: * This template is just an extra level to use in an explicitly-tagged andre@0: * reference to a Signature. andre@0: * andre@0: * Note: this should be static but the AIX compiler doesn't like it (because it andre@0: * was forward-declared above); it is not meant to be exported, but this andre@0: * is the only way it will compile. andre@0: */ andre@0: const SEC_ASN1Template ocsp_PointerToSignatureTemplate[] = { andre@0: { SEC_ASN1_POINTER, 0, ocsp_SignatureTemplate } andre@0: }; andre@0: andre@0: /* andre@0: * Request ::= SEQUENCE { andre@0: * reqCert CertID, andre@0: * singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL } andre@0: * andre@0: * Note: this should be static but the AIX compiler doesn't like it (because it andre@0: * was forward-declared above); it is not meant to be exported, but this andre@0: * is the only way it will compile. andre@0: */ andre@0: const SEC_ASN1Template ocsp_SingleRequestTemplate[] = { andre@0: { SEC_ASN1_SEQUENCE, andre@0: 0, NULL, sizeof(ocspSingleRequest) }, andre@0: { SEC_ASN1_POINTER, andre@0: offsetof(ocspSingleRequest, reqCert), andre@0: ocsp_CertIDTemplate }, andre@0: { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | andre@0: SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, andre@0: offsetof(ocspSingleRequest, singleRequestExtensions), andre@0: CERT_SequenceOfCertExtensionTemplate }, andre@0: { 0 } andre@0: }; andre@0: andre@0: andre@0: /* andre@0: * This data structure and template (CertID) is used by both OCSP andre@0: * requests and responses. It is the only one that is shared. andre@0: * andre@0: * CertID ::= SEQUENCE { andre@0: * hashAlgorithm AlgorithmIdentifier, andre@0: * issuerNameHash OCTET STRING, -- Hash of Issuer DN andre@0: * issuerKeyHash OCTET STRING, -- Hash of Issuer public key andre@0: * serialNumber CertificateSerialNumber } andre@0: * andre@0: * CertificateSerialNumber ::= INTEGER andre@0: * andre@0: * Note: this should be static but the AIX compiler doesn't like it (because it andre@0: * was forward-declared above); it is not meant to be exported, but this andre@0: * is the only way it will compile. andre@0: */ andre@0: const SEC_ASN1Template ocsp_CertIDTemplate[] = { andre@0: { SEC_ASN1_SEQUENCE, andre@0: 0, NULL, sizeof(CERTOCSPCertID) }, andre@0: { SEC_ASN1_INLINE | SEC_ASN1_XTRN, andre@0: offsetof(CERTOCSPCertID, hashAlgorithm), andre@0: SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, andre@0: { SEC_ASN1_OCTET_STRING, andre@0: offsetof(CERTOCSPCertID, issuerNameHash) }, andre@0: { SEC_ASN1_OCTET_STRING, andre@0: offsetof(CERTOCSPCertID, issuerKeyHash) }, andre@0: { SEC_ASN1_INTEGER, andre@0: offsetof(CERTOCSPCertID, serialNumber) }, andre@0: { 0 } andre@0: }; andre@0: andre@0: andre@0: /* andre@0: * Response-related templates... andre@0: */ andre@0: andre@0: /* andre@0: * OCSPResponse ::= SEQUENCE { andre@0: * responseStatus OCSPResponseStatus, andre@0: * responseBytes [0] EXPLICIT ResponseBytes OPTIONAL } andre@0: */ andre@0: const SEC_ASN1Template ocsp_OCSPResponseTemplate[] = { andre@0: { SEC_ASN1_SEQUENCE, andre@0: 0, NULL, sizeof(CERTOCSPResponse) }, andre@0: { SEC_ASN1_ENUMERATED, andre@0: offsetof(CERTOCSPResponse, responseStatus) }, andre@0: { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | andre@0: SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, andre@0: offsetof(CERTOCSPResponse, responseBytes), andre@0: ocsp_PointerToResponseBytesTemplate }, andre@0: { 0 } andre@0: }; andre@0: andre@0: /* andre@0: * ResponseBytes ::= SEQUENCE { andre@0: * responseType OBJECT IDENTIFIER, andre@0: * response OCTET STRING } andre@0: */ andre@0: const SEC_ASN1Template ocsp_ResponseBytesTemplate[] = { andre@0: { SEC_ASN1_SEQUENCE, andre@0: 0, NULL, sizeof(ocspResponseBytes) }, andre@0: { SEC_ASN1_OBJECT_ID, andre@0: offsetof(ocspResponseBytes, responseType) }, andre@0: { SEC_ASN1_OCTET_STRING, andre@0: offsetof(ocspResponseBytes, response) }, andre@0: { 0 } andre@0: }; andre@0: andre@0: /* andre@0: * This template is just an extra level to use in an explicitly-tagged andre@0: * reference to a ResponseBytes. andre@0: * andre@0: * Note: this should be static but the AIX compiler doesn't like it (because it andre@0: * was forward-declared above); it is not meant to be exported, but this andre@0: * is the only way it will compile. andre@0: */ andre@0: const SEC_ASN1Template ocsp_PointerToResponseBytesTemplate[] = { andre@0: { SEC_ASN1_POINTER, 0, ocsp_ResponseBytesTemplate } andre@0: }; andre@0: andre@0: /* andre@0: * BasicOCSPResponse ::= SEQUENCE { andre@0: * tbsResponseData ResponseData, andre@0: * signatureAlgorithm AlgorithmIdentifier, andre@0: * signature BIT STRING, andre@0: * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } andre@0: */ andre@0: static const SEC_ASN1Template ocsp_BasicOCSPResponseTemplate[] = { andre@0: { SEC_ASN1_SEQUENCE, andre@0: 0, NULL, sizeof(ocspBasicOCSPResponse) }, andre@0: { SEC_ASN1_ANY | SEC_ASN1_SAVE, andre@0: offsetof(ocspBasicOCSPResponse, tbsResponseDataDER) }, andre@0: { SEC_ASN1_POINTER, andre@0: offsetof(ocspBasicOCSPResponse, tbsResponseData), andre@0: ocsp_ResponseDataTemplate }, andre@0: { SEC_ASN1_INLINE | SEC_ASN1_XTRN, andre@0: offsetof(ocspBasicOCSPResponse, responseSignature.signatureAlgorithm), andre@0: SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, andre@0: { SEC_ASN1_BIT_STRING, andre@0: offsetof(ocspBasicOCSPResponse, responseSignature.signature) }, andre@0: { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | andre@0: SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, andre@0: offsetof(ocspBasicOCSPResponse, responseSignature.derCerts), andre@0: SEC_ASN1_SUB(SEC_SequenceOfAnyTemplate) }, andre@0: { 0 } andre@0: }; andre@0: andre@0: /* andre@0: * ResponseData ::= SEQUENCE { andre@0: * version [0] EXPLICIT Version DEFAULT v1, andre@0: * responderID ResponderID, andre@0: * producedAt GeneralizedTime, andre@0: * responses SEQUENCE OF SingleResponse, andre@0: * responseExtensions [1] EXPLICIT Extensions OPTIONAL } andre@0: * andre@0: * Note: this should be static but the AIX compiler doesn't like it (because it andre@0: * was forward-declared above); it is not meant to be exported, but this andre@0: * is the only way it will compile. andre@0: */ andre@0: const SEC_ASN1Template ocsp_ResponseDataTemplate[] = { andre@0: { SEC_ASN1_SEQUENCE, andre@0: 0, NULL, sizeof(ocspResponseData) }, andre@0: { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | /* XXX DER_DEFAULT */ andre@0: SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, andre@0: offsetof(ocspResponseData, version), andre@0: SEC_ASN1_SUB(SEC_IntegerTemplate) }, andre@0: { SEC_ASN1_ANY, andre@0: offsetof(ocspResponseData, derResponderID) }, andre@0: { SEC_ASN1_GENERALIZED_TIME, andre@0: offsetof(ocspResponseData, producedAt) }, andre@0: { SEC_ASN1_SEQUENCE_OF, andre@0: offsetof(ocspResponseData, responses), andre@0: ocsp_SingleResponseTemplate }, andre@0: { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | andre@0: SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, andre@0: offsetof(ocspResponseData, responseExtensions), andre@0: CERT_SequenceOfCertExtensionTemplate }, andre@0: { 0 } andre@0: }; andre@0: andre@0: /* andre@0: * ResponderID ::= CHOICE { andre@0: * byName [1] EXPLICIT Name, andre@0: * byKey [2] EXPLICIT KeyHash } andre@0: * andre@0: * KeyHash ::= OCTET STRING -- SHA-1 hash of responder's public key andre@0: * (excluding the tag and length fields) andre@0: * andre@0: * XXX Because the ASN.1 encoder and decoder currently do not provide andre@0: * a way to automatically handle a CHOICE, we need to do it in two andre@0: * steps, looking at the type tag and feeding the exact choice back andre@0: * to the ASN.1 code. Hopefully that will change someday and this andre@0: * can all be simplified down into a single template. Anyway, for andre@0: * now we list each choice as its own template: andre@0: */ andre@0: const SEC_ASN1Template ocsp_ResponderIDByNameTemplate[] = { andre@0: { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, andre@0: offsetof(ocspResponderID, responderIDValue.name), andre@0: CERT_NameTemplate } andre@0: }; andre@0: const SEC_ASN1Template ocsp_ResponderIDByKeyTemplate[] = { andre@0: { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | andre@0: SEC_ASN1_XTRN | 2, andre@0: offsetof(ocspResponderID, responderIDValue.keyHash), andre@0: SEC_ASN1_SUB(SEC_OctetStringTemplate) } andre@0: }; andre@0: static const SEC_ASN1Template ocsp_ResponderIDOtherTemplate[] = { andre@0: { SEC_ASN1_ANY, andre@0: offsetof(ocspResponderID, responderIDValue.other) } andre@0: }; andre@0: andre@0: /* Decode choice container, but leave x509 name object encoded */ andre@0: static const SEC_ASN1Template ocsp_ResponderIDDerNameTemplate[] = { andre@0: { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | andre@0: SEC_ASN1_XTRN | 1, 0, SEC_ASN1_SUB(SEC_AnyTemplate) } andre@0: }; andre@0: andre@0: /* andre@0: * SingleResponse ::= SEQUENCE { andre@0: * certID CertID, andre@0: * certStatus CertStatus, andre@0: * thisUpdate GeneralizedTime, andre@0: * nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL, andre@0: * singleExtensions [1] EXPLICIT Extensions OPTIONAL } andre@0: * andre@0: * Note: this should be static but the AIX compiler doesn't like it (because it andre@0: * was forward-declared above); it is not meant to be exported, but this andre@0: * is the only way it will compile. andre@0: */ andre@0: const SEC_ASN1Template ocsp_SingleResponseTemplate[] = { andre@0: { SEC_ASN1_SEQUENCE, andre@0: 0, NULL, sizeof(CERTOCSPSingleResponse) }, andre@0: { SEC_ASN1_POINTER, andre@0: offsetof(CERTOCSPSingleResponse, certID), andre@0: ocsp_CertIDTemplate }, andre@0: { SEC_ASN1_ANY, andre@0: offsetof(CERTOCSPSingleResponse, derCertStatus) }, andre@0: { SEC_ASN1_GENERALIZED_TIME, andre@0: offsetof(CERTOCSPSingleResponse, thisUpdate) }, andre@0: { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | andre@0: SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, andre@0: offsetof(CERTOCSPSingleResponse, nextUpdate), andre@0: SEC_ASN1_SUB(SEC_PointerToGeneralizedTimeTemplate) }, andre@0: { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | andre@0: SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, andre@0: offsetof(CERTOCSPSingleResponse, singleExtensions), andre@0: CERT_SequenceOfCertExtensionTemplate }, andre@0: { 0 } andre@0: }; andre@0: andre@0: /* andre@0: * CertStatus ::= CHOICE { andre@0: * good [0] IMPLICIT NULL, andre@0: * revoked [1] IMPLICIT RevokedInfo, andre@0: * unknown [2] IMPLICIT UnknownInfo } andre@0: * andre@0: * Because the ASN.1 encoder and decoder currently do not provide andre@0: * a way to automatically handle a CHOICE, we need to do it in two andre@0: * steps, looking at the type tag and feeding the exact choice back andre@0: * to the ASN.1 code. Hopefully that will change someday and this andre@0: * can all be simplified down into a single template. Anyway, for andre@0: * now we list each choice as its own template: andre@0: */ andre@0: static const SEC_ASN1Template ocsp_CertStatusGoodTemplate[] = { andre@0: { SEC_ASN1_POINTER | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, andre@0: offsetof(ocspCertStatus, certStatusInfo.goodInfo), andre@0: SEC_ASN1_SUB(SEC_NullTemplate) } andre@0: }; andre@0: static const SEC_ASN1Template ocsp_CertStatusRevokedTemplate[] = { andre@0: { SEC_ASN1_POINTER | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, andre@0: offsetof(ocspCertStatus, certStatusInfo.revokedInfo), andre@0: ocsp_RevokedInfoTemplate } andre@0: }; andre@0: static const SEC_ASN1Template ocsp_CertStatusUnknownTemplate[] = { andre@0: { SEC_ASN1_POINTER | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 2, andre@0: offsetof(ocspCertStatus, certStatusInfo.unknownInfo), andre@0: SEC_ASN1_SUB(SEC_NullTemplate) } andre@0: }; andre@0: static const SEC_ASN1Template ocsp_CertStatusOtherTemplate[] = { andre@0: { SEC_ASN1_POINTER | SEC_ASN1_XTRN, andre@0: offsetof(ocspCertStatus, certStatusInfo.otherInfo), andre@0: SEC_ASN1_SUB(SEC_AnyTemplate) } andre@0: }; andre@0: andre@0: /* andre@0: * RevokedInfo ::= SEQUENCE { andre@0: * revocationTime GeneralizedTime, andre@0: * revocationReason [0] EXPLICIT CRLReason OPTIONAL } andre@0: * andre@0: * Note: this should be static but the AIX compiler doesn't like it (because it andre@0: * was forward-declared above); it is not meant to be exported, but this andre@0: * is the only way it will compile. andre@0: */ andre@0: const SEC_ASN1Template ocsp_RevokedInfoTemplate[] = { andre@0: { SEC_ASN1_SEQUENCE, andre@0: 0, NULL, sizeof(ocspRevokedInfo) }, andre@0: { SEC_ASN1_GENERALIZED_TIME, andre@0: offsetof(ocspRevokedInfo, revocationTime) }, andre@0: { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | andre@0: SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | andre@0: SEC_ASN1_XTRN | 0, andre@0: offsetof(ocspRevokedInfo, revocationReason), andre@0: SEC_ASN1_SUB(SEC_PointerToEnumeratedTemplate) }, andre@0: { 0 } andre@0: }; andre@0: andre@0: andre@0: /* andre@0: * OCSP-specific extension templates: andre@0: */ andre@0: andre@0: /* andre@0: * ServiceLocator ::= SEQUENCE { andre@0: * issuer Name, andre@0: * locator AuthorityInfoAccessSyntax OPTIONAL } andre@0: */ andre@0: static const SEC_ASN1Template ocsp_ServiceLocatorTemplate[] = { andre@0: { SEC_ASN1_SEQUENCE, andre@0: 0, NULL, sizeof(ocspServiceLocator) }, andre@0: { SEC_ASN1_POINTER, andre@0: offsetof(ocspServiceLocator, issuer), andre@0: CERT_NameTemplate }, andre@0: { SEC_ASN1_OPTIONAL | SEC_ASN1_ANY, andre@0: offsetof(ocspServiceLocator, locator) }, andre@0: { 0 } andre@0: }; andre@0: andre@0: andre@0: /* andre@0: * REQUEST SUPPORT FUNCTIONS (encode/create/decode/destroy): andre@0: */ andre@0: andre@0: /* andre@0: * FUNCTION: CERT_EncodeOCSPRequest andre@0: * DER encodes an OCSP Request, possibly adding a signature as well. andre@0: * XXX Signing is not yet supported, however; see comments in code. andre@0: * INPUTS: andre@0: * PLArenaPool *arena andre@0: * The return value is allocated from here. andre@0: * If a NULL is passed in, allocation is done from the heap instead. andre@0: * CERTOCSPRequest *request andre@0: * The request to be encoded. andre@0: * void *pwArg andre@0: * Pointer to argument for password prompting, if needed. (Definitely andre@0: * not needed if not signing.) andre@0: * RETURN: andre@0: * Returns a NULL on error and a pointer to the SECItem with the andre@0: * encoded value otherwise. Any error is likely to be low-level andre@0: * (e.g. no memory). andre@0: */ andre@0: SECItem * andre@0: CERT_EncodeOCSPRequest(PLArenaPool *arena, CERTOCSPRequest *request, andre@0: void *pwArg) andre@0: { andre@0: SECStatus rv; andre@0: andre@0: /* XXX All of these should generate errors if they fail. */ andre@0: PORT_Assert(request); andre@0: PORT_Assert(request->tbsRequest); andre@0: andre@0: if (request->tbsRequest->extensionHandle != NULL) { andre@0: rv = CERT_FinishExtensions(request->tbsRequest->extensionHandle); andre@0: request->tbsRequest->extensionHandle = NULL; andre@0: if (rv != SECSuccess) andre@0: return NULL; andre@0: } andre@0: andre@0: /* andre@0: * XXX When signed requests are supported and request->optionalSignature andre@0: * is not NULL: andre@0: * - need to encode tbsRequest->requestorName andre@0: * - need to encode tbsRequest andre@0: * - need to sign that encoded result (using cert in sig), filling in the andre@0: * request->optionalSignature structure with the result, the signing andre@0: * algorithm and (perhaps?) the cert (and its chain?) in derCerts andre@0: */ andre@0: andre@0: return SEC_ASN1EncodeItem(arena, NULL, request, ocsp_OCSPRequestTemplate); andre@0: } andre@0: andre@0: andre@0: /* andre@0: * FUNCTION: CERT_DecodeOCSPRequest andre@0: * Decode a DER encoded OCSP Request. andre@0: * INPUTS: andre@0: * SECItem *src andre@0: * Pointer to a SECItem holding DER encoded OCSP Request. andre@0: * RETURN: andre@0: * Returns a pointer to a CERTOCSPRequest containing the decoded request. andre@0: * On error, returns NULL. Most likely error is trouble decoding andre@0: * (SEC_ERROR_OCSP_MALFORMED_REQUEST), or low-level problem (no memory). andre@0: */ andre@0: CERTOCSPRequest * andre@0: CERT_DecodeOCSPRequest(const SECItem *src) andre@0: { andre@0: PLArenaPool *arena = NULL; andre@0: SECStatus rv = SECFailure; andre@0: CERTOCSPRequest *dest = NULL; andre@0: int i; andre@0: SECItem newSrc; andre@0: andre@0: arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); andre@0: if (arena == NULL) { andre@0: goto loser; andre@0: } andre@0: dest = (CERTOCSPRequest *) PORT_ArenaZAlloc(arena, andre@0: sizeof(CERTOCSPRequest)); andre@0: if (dest == NULL) { andre@0: goto loser; andre@0: } andre@0: dest->arena = arena; andre@0: andre@0: /* copy the DER into the arena, since Quick DER returns data that points andre@0: into the DER input, which may get freed by the caller */ andre@0: rv = SECITEM_CopyItem(arena, &newSrc, src); andre@0: if ( rv != SECSuccess ) { andre@0: goto loser; andre@0: } andre@0: andre@0: rv = SEC_QuickDERDecodeItem(arena, dest, ocsp_OCSPRequestTemplate, &newSrc); andre@0: if (rv != SECSuccess) { andre@0: if (PORT_GetError() == SEC_ERROR_BAD_DER) andre@0: PORT_SetError(SEC_ERROR_OCSP_MALFORMED_REQUEST); andre@0: goto loser; andre@0: } andre@0: andre@0: /* andre@0: * XXX I would like to find a way to get rid of the necessity andre@0: * of doing this copying of the arena pointer. andre@0: */ andre@0: for (i = 0; dest->tbsRequest->requestList[i] != NULL; i++) { andre@0: dest->tbsRequest->requestList[i]->arena = arena; andre@0: } andre@0: andre@0: return dest; andre@0: andre@0: loser: andre@0: if (arena != NULL) { andre@0: PORT_FreeArena(arena, PR_FALSE); andre@0: } andre@0: return NULL; andre@0: } andre@0: andre@0: SECStatus andre@0: CERT_DestroyOCSPCertID(CERTOCSPCertID* certID) andre@0: { andre@0: if (certID && certID->poolp) { andre@0: PORT_FreeArena(certID->poolp, PR_FALSE); andre@0: return SECSuccess; andre@0: } andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: return SECFailure; andre@0: } andre@0: andre@0: /* andre@0: * Digest data using the specified algorithm. andre@0: * The necessary storage for the digest data is allocated. If "fill" is andre@0: * non-null, the data is put there, otherwise a SECItem is allocated. andre@0: * Allocation from "arena" if it is non-null, heap otherwise. Any problem andre@0: * results in a NULL being returned (and an appropriate error set). andre@0: */ andre@0: andre@0: SECItem * andre@0: ocsp_DigestValue(PLArenaPool *arena, SECOidTag digestAlg, andre@0: SECItem *fill, const SECItem *src) andre@0: { andre@0: const SECHashObject *digestObject; andre@0: SECItem *result = NULL; andre@0: void *mark = NULL; andre@0: void *digestBuff = NULL; andre@0: andre@0: if ( arena != NULL ) { andre@0: mark = PORT_ArenaMark(arena); andre@0: } andre@0: andre@0: digestObject = HASH_GetHashObjectByOidTag(digestAlg); andre@0: if ( digestObject == NULL ) { andre@0: goto loser; andre@0: } andre@0: andre@0: if (fill == NULL || fill->data == NULL) { andre@0: result = SECITEM_AllocItem(arena, fill, digestObject->length); andre@0: if ( result == NULL ) { andre@0: goto loser; andre@0: } andre@0: digestBuff = result->data; andre@0: } else { andre@0: if (fill->len < digestObject->length) { andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: goto loser; andre@0: } andre@0: digestBuff = fill->data; andre@0: } andre@0: andre@0: if (PK11_HashBuf(digestAlg, digestBuff, andre@0: src->data, src->len) != SECSuccess) { andre@0: goto loser; andre@0: } andre@0: andre@0: if ( arena != NULL ) { andre@0: PORT_ArenaUnmark(arena, mark); andre@0: } andre@0: andre@0: if (result == NULL) { andre@0: result = fill; andre@0: } andre@0: return result; andre@0: andre@0: loser: andre@0: if (arena != NULL) { andre@0: PORT_ArenaRelease(arena, mark); andre@0: } else { andre@0: if (result != NULL) { andre@0: SECITEM_FreeItem(result, (fill == NULL) ? PR_TRUE : PR_FALSE); andre@0: } andre@0: } andre@0: return(NULL); andre@0: } andre@0: andre@0: /* andre@0: * Digest the cert's subject public key using the specified algorithm. andre@0: * The necessary storage for the digest data is allocated. If "fill" is andre@0: * non-null, the data is put there, otherwise a SECItem is allocated. andre@0: * Allocation from "arena" if it is non-null, heap otherwise. Any problem andre@0: * results in a NULL being returned (and an appropriate error set). andre@0: */ andre@0: SECItem * andre@0: CERT_GetSubjectPublicKeyDigest(PLArenaPool *arena, const CERTCertificate *cert, andre@0: SECOidTag digestAlg, SECItem *fill) andre@0: { andre@0: SECItem spk; andre@0: andre@0: /* andre@0: * Copy just the length and data pointer (nothing needs to be freed) andre@0: * of the subject public key so we can convert the length from bits andre@0: * to bytes, which is what the digest function expects. andre@0: */ andre@0: spk = cert->subjectPublicKeyInfo.subjectPublicKey; andre@0: DER_ConvertBitString(&spk); andre@0: andre@0: return ocsp_DigestValue(arena, digestAlg, fill, &spk); andre@0: } andre@0: andre@0: /* andre@0: * Digest the cert's subject name using the specified algorithm. andre@0: */ andre@0: SECItem * andre@0: CERT_GetSubjectNameDigest(PLArenaPool *arena, const CERTCertificate *cert, andre@0: SECOidTag digestAlg, SECItem *fill) andre@0: { andre@0: SECItem name; andre@0: andre@0: /* andre@0: * Copy just the length and data pointer (nothing needs to be freed) andre@0: * of the subject name andre@0: */ andre@0: name = cert->derSubject; andre@0: andre@0: return ocsp_DigestValue(arena, digestAlg, fill, &name); andre@0: } andre@0: andre@0: /* andre@0: * Create and fill-in a CertID. This function fills in the hash values andre@0: * (issuerNameHash and issuerKeyHash), and is hardwired to use SHA1. andre@0: * Someday it might need to be more flexible about hash algorithm, but andre@0: * for now we have no intention/need to create anything else. andre@0: * andre@0: * Error causes a null to be returned; most likely cause is trouble andre@0: * finding the certificate issuer (SEC_ERROR_UNKNOWN_ISSUER). andre@0: * Other errors are low-level problems (no memory, bad database, etc.). andre@0: */ andre@0: static CERTOCSPCertID * andre@0: ocsp_CreateCertID(PLArenaPool *arena, CERTCertificate *cert, PRTime time) andre@0: { andre@0: CERTOCSPCertID *certID; andre@0: CERTCertificate *issuerCert = NULL; andre@0: void *mark = PORT_ArenaMark(arena); andre@0: SECStatus rv; andre@0: andre@0: PORT_Assert(arena != NULL); andre@0: andre@0: certID = PORT_ArenaZNew(arena, CERTOCSPCertID); andre@0: if (certID == NULL) { andre@0: goto loser; andre@0: } andre@0: andre@0: rv = SECOID_SetAlgorithmID(arena, &certID->hashAlgorithm, SEC_OID_SHA1, andre@0: NULL); andre@0: if (rv != SECSuccess) { andre@0: goto loser; andre@0: } andre@0: andre@0: issuerCert = CERT_FindCertIssuer(cert, time, certUsageAnyCA); andre@0: if (issuerCert == NULL) { andre@0: goto loser; andre@0: } andre@0: andre@0: if (CERT_GetSubjectNameDigest(arena, issuerCert, SEC_OID_SHA1, andre@0: &(certID->issuerNameHash)) == NULL) { andre@0: goto loser; andre@0: } andre@0: certID->issuerSHA1NameHash.data = certID->issuerNameHash.data; andre@0: certID->issuerSHA1NameHash.len = certID->issuerNameHash.len; andre@0: andre@0: if (CERT_GetSubjectNameDigest(arena, issuerCert, SEC_OID_MD5, andre@0: &(certID->issuerMD5NameHash)) == NULL) { andre@0: goto loser; andre@0: } andre@0: andre@0: if (CERT_GetSubjectNameDigest(arena, issuerCert, SEC_OID_MD2, andre@0: &(certID->issuerMD2NameHash)) == NULL) { andre@0: goto loser; andre@0: } andre@0: andre@0: if (CERT_GetSubjectPublicKeyDigest(arena, issuerCert, SEC_OID_SHA1, andre@0: &certID->issuerKeyHash) == NULL) { andre@0: goto loser; andre@0: } andre@0: certID->issuerSHA1KeyHash.data = certID->issuerKeyHash.data; andre@0: certID->issuerSHA1KeyHash.len = certID->issuerKeyHash.len; andre@0: /* cache the other two hash algorithms as well */ andre@0: if (CERT_GetSubjectPublicKeyDigest(arena, issuerCert, SEC_OID_MD5, andre@0: &certID->issuerMD5KeyHash) == NULL) { andre@0: goto loser; andre@0: } andre@0: if (CERT_GetSubjectPublicKeyDigest(arena, issuerCert, SEC_OID_MD2, andre@0: &certID->issuerMD2KeyHash) == NULL) { andre@0: goto loser; andre@0: } andre@0: andre@0: andre@0: /* now we are done with issuerCert */ andre@0: CERT_DestroyCertificate(issuerCert); andre@0: issuerCert = NULL; andre@0: andre@0: rv = SECITEM_CopyItem(arena, &certID->serialNumber, &cert->serialNumber); andre@0: if (rv != SECSuccess) { andre@0: goto loser; andre@0: } andre@0: andre@0: PORT_ArenaUnmark(arena, mark); andre@0: return certID; andre@0: andre@0: loser: andre@0: if (issuerCert != NULL) { andre@0: CERT_DestroyCertificate(issuerCert); andre@0: } andre@0: PORT_ArenaRelease(arena, mark); andre@0: return NULL; andre@0: } andre@0: andre@0: CERTOCSPCertID* andre@0: CERT_CreateOCSPCertID(CERTCertificate *cert, PRTime time) andre@0: { andre@0: PLArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); andre@0: CERTOCSPCertID *certID; andre@0: PORT_Assert(arena != NULL); andre@0: if (!arena) andre@0: return NULL; andre@0: andre@0: certID = ocsp_CreateCertID(arena, cert, time); andre@0: if (!certID) { andre@0: PORT_FreeArena(arena, PR_FALSE); andre@0: return NULL; andre@0: } andre@0: certID->poolp = arena; andre@0: return certID; andre@0: } andre@0: andre@0: static CERTOCSPCertID * andre@0: cert_DupOCSPCertID(const CERTOCSPCertID *src) andre@0: { andre@0: CERTOCSPCertID *dest; andre@0: PLArenaPool *arena = NULL; andre@0: andre@0: if (!src) { andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: return NULL; andre@0: } andre@0: andre@0: arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); andre@0: if (!arena) andre@0: goto loser; andre@0: andre@0: dest = PORT_ArenaZNew(arena, CERTOCSPCertID); andre@0: if (!dest) andre@0: goto loser; andre@0: andre@0: #define DUPHELP(element) \ andre@0: if (src->element.data && \ andre@0: SECITEM_CopyItem(arena, &dest->element, &src->element) \ andre@0: != SECSuccess) { \ andre@0: goto loser; \ andre@0: } andre@0: andre@0: DUPHELP(hashAlgorithm.algorithm) andre@0: DUPHELP(hashAlgorithm.parameters) andre@0: DUPHELP(issuerNameHash) andre@0: DUPHELP(issuerKeyHash) andre@0: DUPHELP(serialNumber) andre@0: DUPHELP(issuerSHA1NameHash) andre@0: DUPHELP(issuerMD5NameHash) andre@0: DUPHELP(issuerMD2NameHash) andre@0: DUPHELP(issuerSHA1KeyHash) andre@0: DUPHELP(issuerMD5KeyHash) andre@0: DUPHELP(issuerMD2KeyHash) andre@0: andre@0: dest->poolp = arena; andre@0: return dest; andre@0: andre@0: loser: andre@0: if (arena) andre@0: PORT_FreeArena(arena, PR_FALSE); andre@0: PORT_SetError(PR_OUT_OF_MEMORY_ERROR); andre@0: return NULL; andre@0: } andre@0: andre@0: /* andre@0: * Callback to set Extensions in request object andre@0: */ andre@0: void SetSingleReqExts(void *object, CERTCertExtension **exts) andre@0: { andre@0: ocspSingleRequest *singleRequest = andre@0: (ocspSingleRequest *)object; andre@0: andre@0: singleRequest->singleRequestExtensions = exts; andre@0: } andre@0: andre@0: /* andre@0: * Add the Service Locator extension to the singleRequestExtensions andre@0: * for the given singleRequest. andre@0: * andre@0: * All errors are internal or low-level problems (e.g. no memory). andre@0: */ andre@0: static SECStatus andre@0: ocsp_AddServiceLocatorExtension(ocspSingleRequest *singleRequest, andre@0: CERTCertificate *cert) andre@0: { andre@0: ocspServiceLocator *serviceLocator = NULL; andre@0: void *extensionHandle = NULL; andre@0: SECStatus rv = SECFailure; andre@0: andre@0: serviceLocator = PORT_ZNew(ocspServiceLocator); andre@0: if (serviceLocator == NULL) andre@0: goto loser; andre@0: andre@0: /* andre@0: * Normally it would be a bad idea to do a direct reference like andre@0: * this rather than allocate and copy the name *or* at least dup andre@0: * a reference of the cert. But all we need is to be able to read andre@0: * the issuer name during the encoding we are about to do, so a andre@0: * copy is just a waste of time. andre@0: */ andre@0: serviceLocator->issuer = &cert->issuer; andre@0: andre@0: rv = CERT_FindCertExtension(cert, SEC_OID_X509_AUTH_INFO_ACCESS, andre@0: &serviceLocator->locator); andre@0: if (rv != SECSuccess) { andre@0: if (PORT_GetError() != SEC_ERROR_EXTENSION_NOT_FOUND) andre@0: goto loser; andre@0: } andre@0: andre@0: /* prepare for following loser gotos */ andre@0: rv = SECFailure; andre@0: PORT_SetError(0); andre@0: andre@0: extensionHandle = cert_StartExtensions(singleRequest, andre@0: singleRequest->arena, SetSingleReqExts); andre@0: if (extensionHandle == NULL) andre@0: goto loser; andre@0: andre@0: rv = CERT_EncodeAndAddExtension(extensionHandle, andre@0: SEC_OID_PKIX_OCSP_SERVICE_LOCATOR, andre@0: serviceLocator, PR_FALSE, andre@0: ocsp_ServiceLocatorTemplate); andre@0: andre@0: loser: andre@0: if (extensionHandle != NULL) { andre@0: /* andre@0: * Either way we have to finish out the extension context (so it gets andre@0: * freed). But careful not to override any already-set bad status. andre@0: */ andre@0: SECStatus tmprv = CERT_FinishExtensions(extensionHandle); andre@0: if (rv == SECSuccess) andre@0: rv = tmprv; andre@0: } andre@0: andre@0: /* andre@0: * Finally, free the serviceLocator structure itself and we are done. andre@0: */ andre@0: if (serviceLocator != NULL) { andre@0: if (serviceLocator->locator.data != NULL) andre@0: SECITEM_FreeItem(&serviceLocator->locator, PR_FALSE); andre@0: PORT_Free(serviceLocator); andre@0: } andre@0: andre@0: return rv; andre@0: } andre@0: andre@0: /* andre@0: * Creates an array of ocspSingleRequest based on a list of certs. andre@0: * Note that the code which later compares the request list with the andre@0: * response expects this array to be in the exact same order as the andre@0: * certs are found in the list. It would be harder to change that andre@0: * order than preserve it, but since the requirement is not obvious, andre@0: * it deserves to be mentioned. andre@0: * andre@0: * Any problem causes a null return and error set: andre@0: * SEC_ERROR_UNKNOWN_ISSUER andre@0: * Other errors are low-level problems (no memory, bad database, etc.). andre@0: */ andre@0: static ocspSingleRequest ** andre@0: ocsp_CreateSingleRequestList(PLArenaPool *arena, CERTCertList *certList, andre@0: PRTime time, PRBool includeLocator) andre@0: { andre@0: ocspSingleRequest **requestList = NULL; andre@0: CERTCertListNode *node = NULL; andre@0: int i, count; andre@0: void *mark = PORT_ArenaMark(arena); andre@0: andre@0: node = CERT_LIST_HEAD(certList); andre@0: for (count = 0; !CERT_LIST_END(node, certList); count++) { andre@0: node = CERT_LIST_NEXT(node); andre@0: } andre@0: andre@0: if (count == 0) andre@0: goto loser; andre@0: andre@0: requestList = PORT_ArenaNewArray(arena, ocspSingleRequest *, count + 1); andre@0: if (requestList == NULL) andre@0: goto loser; andre@0: andre@0: node = CERT_LIST_HEAD(certList); andre@0: for (i = 0; !CERT_LIST_END(node, certList); i++) { andre@0: requestList[i] = PORT_ArenaZNew(arena, ocspSingleRequest); andre@0: if (requestList[i] == NULL) andre@0: goto loser; andre@0: andre@0: OCSP_TRACE(("OCSP CERT_CreateOCSPRequest %s\n", node->cert->subjectName)); andre@0: requestList[i]->arena = arena; andre@0: requestList[i]->reqCert = ocsp_CreateCertID(arena, node->cert, time); andre@0: if (requestList[i]->reqCert == NULL) andre@0: goto loser; andre@0: andre@0: if (includeLocator == PR_TRUE) { andre@0: SECStatus rv; andre@0: andre@0: rv = ocsp_AddServiceLocatorExtension(requestList[i], node->cert); andre@0: if (rv != SECSuccess) andre@0: goto loser; andre@0: } andre@0: andre@0: node = CERT_LIST_NEXT(node); andre@0: } andre@0: andre@0: PORT_Assert(i == count); andre@0: andre@0: PORT_ArenaUnmark(arena, mark); andre@0: requestList[i] = NULL; andre@0: return requestList; andre@0: andre@0: loser: andre@0: PORT_ArenaRelease(arena, mark); andre@0: return NULL; andre@0: } andre@0: andre@0: static ocspSingleRequest ** andre@0: ocsp_CreateRequestFromCert(PLArenaPool *arena, andre@0: CERTOCSPCertID *certID, andre@0: CERTCertificate *singleCert, andre@0: PRTime time, andre@0: PRBool includeLocator) andre@0: { andre@0: ocspSingleRequest **requestList = NULL; andre@0: void *mark = PORT_ArenaMark(arena); andre@0: PORT_Assert(certID != NULL && singleCert != NULL); andre@0: andre@0: /* meaning of value 2: one entry + one end marker */ andre@0: requestList = PORT_ArenaNewArray(arena, ocspSingleRequest *, 2); andre@0: if (requestList == NULL) andre@0: goto loser; andre@0: requestList[0] = PORT_ArenaZNew(arena, ocspSingleRequest); andre@0: if (requestList[0] == NULL) andre@0: goto loser; andre@0: requestList[0]->arena = arena; andre@0: /* certID will live longer than the request */ andre@0: requestList[0]->reqCert = certID; andre@0: andre@0: if (includeLocator == PR_TRUE) { andre@0: SECStatus rv; andre@0: rv = ocsp_AddServiceLocatorExtension(requestList[0], singleCert); andre@0: if (rv != SECSuccess) andre@0: goto loser; andre@0: } andre@0: andre@0: PORT_ArenaUnmark(arena, mark); andre@0: requestList[1] = NULL; andre@0: return requestList; andre@0: andre@0: loser: andre@0: PORT_ArenaRelease(arena, mark); andre@0: return NULL; andre@0: } andre@0: andre@0: static CERTOCSPRequest * andre@0: ocsp_prepareEmptyOCSPRequest(void) andre@0: { andre@0: PLArenaPool *arena = NULL; andre@0: CERTOCSPRequest *request = NULL; andre@0: ocspTBSRequest *tbsRequest = NULL; andre@0: andre@0: arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); andre@0: if (arena == NULL) { andre@0: goto loser; andre@0: } andre@0: request = PORT_ArenaZNew(arena, CERTOCSPRequest); andre@0: if (request == NULL) { andre@0: goto loser; andre@0: } andre@0: request->arena = arena; andre@0: andre@0: tbsRequest = PORT_ArenaZNew(arena, ocspTBSRequest); andre@0: if (tbsRequest == NULL) { andre@0: goto loser; andre@0: } andre@0: request->tbsRequest = tbsRequest; andre@0: /* version 1 is the default, so we need not fill in a version number */ andre@0: return request; andre@0: andre@0: loser: andre@0: if (arena != NULL) { andre@0: PORT_FreeArena(arena, PR_FALSE); andre@0: } andre@0: return NULL; andre@0: } andre@0: andre@0: CERTOCSPRequest * andre@0: cert_CreateSingleCertOCSPRequest(CERTOCSPCertID *certID, andre@0: CERTCertificate *singleCert, andre@0: PRTime time, andre@0: PRBool addServiceLocator, andre@0: CERTCertificate *signerCert) andre@0: { andre@0: CERTOCSPRequest *request; andre@0: OCSP_TRACE(("OCSP cert_CreateSingleCertOCSPRequest %s\n", singleCert->subjectName)); andre@0: andre@0: /* XXX Support for signerCert may be implemented later, andre@0: * see also the comment in CERT_CreateOCSPRequest. andre@0: */ andre@0: if (signerCert != NULL) { andre@0: PORT_SetError(PR_NOT_IMPLEMENTED_ERROR); andre@0: return NULL; andre@0: } andre@0: andre@0: request = ocsp_prepareEmptyOCSPRequest(); andre@0: if (!request) andre@0: return NULL; andre@0: /* andre@0: * Version 1 is the default, so we need not fill in a version number. andre@0: * Now create the list of single requests, one for each cert. andre@0: */ andre@0: request->tbsRequest->requestList = andre@0: ocsp_CreateRequestFromCert(request->arena, andre@0: certID, andre@0: singleCert, andre@0: time, andre@0: addServiceLocator); andre@0: if (request->tbsRequest->requestList == NULL) { andre@0: PORT_FreeArena(request->arena, PR_FALSE); andre@0: return NULL; andre@0: } andre@0: return request; andre@0: } andre@0: andre@0: /* andre@0: * FUNCTION: CERT_CreateOCSPRequest andre@0: * Creates a CERTOCSPRequest, requesting the status of the certs in andre@0: * the given list. andre@0: * INPUTS: andre@0: * CERTCertList *certList andre@0: * A list of certs for which status will be requested. andre@0: * Note that all of these certificates should have the same issuer, andre@0: * or it's expected the response will be signed by a trusted responder. andre@0: * If the certs need to be broken up into multiple requests, that andre@0: * must be handled by the caller (and thus by having multiple calls andre@0: * to this routine), who knows about where the request(s) are being andre@0: * sent and whether there are any trusted responders in place. andre@0: * PRTime time andre@0: * Indicates the time for which the certificate status is to be andre@0: * determined -- this may be used in the search for the cert's issuer andre@0: * but has no effect on the request itself. andre@0: * PRBool addServiceLocator andre@0: * If true, the Service Locator extension should be added to the andre@0: * single request(s) for each cert. andre@0: * CERTCertificate *signerCert andre@0: * If non-NULL, means sign the request using this cert. Otherwise, andre@0: * do not sign. andre@0: * XXX note that request signing is not yet supported; see comment in code andre@0: * RETURN: andre@0: * A pointer to a CERTOCSPRequest structure containing an OCSP request andre@0: * for the cert list. On error, null is returned, with an error set andre@0: * indicating the reason. This is likely SEC_ERROR_UNKNOWN_ISSUER. andre@0: * (The issuer is needed to create a request for the certificate.) andre@0: * Other errors are low-level problems (no memory, bad database, etc.). andre@0: */ andre@0: CERTOCSPRequest * andre@0: CERT_CreateOCSPRequest(CERTCertList *certList, PRTime time, andre@0: PRBool addServiceLocator, andre@0: CERTCertificate *signerCert) andre@0: { andre@0: CERTOCSPRequest *request = NULL; andre@0: andre@0: if (!certList) { andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: return NULL; andre@0: } andre@0: /* andre@0: * XXX When we are prepared to put signing of requests back in, andre@0: * we will need to allocate a signature andre@0: * structure for the request, fill in the "derCerts" field in it, andre@0: * save the signerCert there, as well as fill in the "requestorName" andre@0: * field of the tbsRequest. andre@0: */ andre@0: if (signerCert != NULL) { andre@0: PORT_SetError(PR_NOT_IMPLEMENTED_ERROR); andre@0: return NULL; andre@0: } andre@0: request = ocsp_prepareEmptyOCSPRequest(); andre@0: if (!request) andre@0: return NULL; andre@0: /* andre@0: * Now create the list of single requests, one for each cert. andre@0: */ andre@0: request->tbsRequest->requestList = andre@0: ocsp_CreateSingleRequestList(request->arena, andre@0: certList, andre@0: time, andre@0: addServiceLocator); andre@0: if (request->tbsRequest->requestList == NULL) { andre@0: PORT_FreeArena(request->arena, PR_FALSE); andre@0: return NULL; andre@0: } andre@0: return request; andre@0: } andre@0: andre@0: /* andre@0: * FUNCTION: CERT_AddOCSPAcceptableResponses andre@0: * Add the AcceptableResponses extension to an OCSP Request. andre@0: * INPUTS: andre@0: * CERTOCSPRequest *request andre@0: * The request to which the extension should be added. andre@0: * ... andre@0: * A list (of one or more) of SECOidTag -- each of the response types andre@0: * to be added. The last OID *must* be SEC_OID_PKIX_OCSP_BASIC_RESPONSE. andre@0: * (This marks the end of the list, and it must be specified because a andre@0: * client conforming to the OCSP standard is required to handle the basic andre@0: * response type.) The OIDs are not checked in any way. andre@0: * RETURN: andre@0: * SECSuccess if the extension is added; SECFailure if anything goes wrong. andre@0: * All errors are internal or low-level problems (e.g. no memory). andre@0: */ andre@0: andre@0: void SetRequestExts(void *object, CERTCertExtension **exts) andre@0: { andre@0: CERTOCSPRequest *request = (CERTOCSPRequest *)object; andre@0: andre@0: request->tbsRequest->requestExtensions = exts; andre@0: } andre@0: andre@0: SECStatus andre@0: CERT_AddOCSPAcceptableResponses(CERTOCSPRequest *request, andre@0: SECOidTag responseType0, ...) andre@0: { andre@0: void *extHandle; andre@0: va_list ap; andre@0: int i, count; andre@0: SECOidTag responseType; andre@0: SECOidData *responseOid; andre@0: SECItem **acceptableResponses = NULL; andre@0: SECStatus rv = SECFailure; andre@0: andre@0: extHandle = request->tbsRequest->extensionHandle; andre@0: if (extHandle == NULL) { andre@0: extHandle = cert_StartExtensions(request, request->arena, SetRequestExts); andre@0: if (extHandle == NULL) andre@0: goto loser; andre@0: } andre@0: andre@0: /* Count number of OIDS going into the extension value. */ andre@0: count = 1; andre@0: if (responseType0 != SEC_OID_PKIX_OCSP_BASIC_RESPONSE) { andre@0: va_start(ap, responseType0); andre@0: do { andre@0: count++; andre@0: responseType = va_arg(ap, SECOidTag); andre@0: } while (responseType != SEC_OID_PKIX_OCSP_BASIC_RESPONSE); andre@0: va_end(ap); andre@0: } andre@0: andre@0: acceptableResponses = PORT_NewArray(SECItem *, count + 1); andre@0: if (acceptableResponses == NULL) andre@0: goto loser; andre@0: andre@0: i = 0; andre@0: responseOid = SECOID_FindOIDByTag(responseType0); andre@0: acceptableResponses[i++] = &(responseOid->oid); andre@0: if (count > 1) { andre@0: va_start(ap, responseType0); andre@0: for ( ; i < count; i++) { andre@0: responseType = va_arg(ap, SECOidTag); andre@0: responseOid = SECOID_FindOIDByTag(responseType); andre@0: acceptableResponses[i] = &(responseOid->oid); andre@0: } andre@0: va_end(ap); andre@0: } andre@0: acceptableResponses[i] = NULL; andre@0: andre@0: rv = CERT_EncodeAndAddExtension(extHandle, SEC_OID_PKIX_OCSP_RESPONSE, andre@0: &acceptableResponses, PR_FALSE, andre@0: SEC_ASN1_GET(SEC_SequenceOfObjectIDTemplate)); andre@0: if (rv != SECSuccess) andre@0: goto loser; andre@0: andre@0: PORT_Free(acceptableResponses); andre@0: if (request->tbsRequest->extensionHandle == NULL) andre@0: request->tbsRequest->extensionHandle = extHandle; andre@0: return SECSuccess; andre@0: andre@0: loser: andre@0: if (acceptableResponses != NULL) andre@0: PORT_Free(acceptableResponses); andre@0: if (extHandle != NULL) andre@0: (void) CERT_FinishExtensions(extHandle); andre@0: return rv; andre@0: } andre@0: andre@0: andre@0: /* andre@0: * FUNCTION: CERT_DestroyOCSPRequest andre@0: * Frees an OCSP Request structure. andre@0: * INPUTS: andre@0: * CERTOCSPRequest *request andre@0: * Pointer to CERTOCSPRequest to be freed. andre@0: * RETURN: andre@0: * No return value; no errors. andre@0: */ andre@0: void andre@0: CERT_DestroyOCSPRequest(CERTOCSPRequest *request) andre@0: { andre@0: if (request == NULL) andre@0: return; andre@0: andre@0: if (request->tbsRequest != NULL) { andre@0: if (request->tbsRequest->requestorName != NULL) andre@0: CERT_DestroyGeneralNameList(request->tbsRequest->requestorName); andre@0: if (request->tbsRequest->extensionHandle != NULL) andre@0: (void) CERT_FinishExtensions(request->tbsRequest->extensionHandle); andre@0: } andre@0: andre@0: if (request->optionalSignature != NULL) { andre@0: if (request->optionalSignature->cert != NULL) andre@0: CERT_DestroyCertificate(request->optionalSignature->cert); andre@0: andre@0: /* andre@0: * XXX Need to free derCerts? Or do they come out of arena? andre@0: * (Currently we never fill in derCerts, which is why the andre@0: * answer is not obvious. Once we do, add any necessary code andre@0: * here and remove this comment.) andre@0: */ andre@0: } andre@0: andre@0: /* andre@0: * We should actually never have a request without an arena, andre@0: * but check just in case. (If there isn't one, there is not andre@0: * much we can do about it...) andre@0: */ andre@0: PORT_Assert(request->arena != NULL); andre@0: if (request->arena != NULL) andre@0: PORT_FreeArena(request->arena, PR_FALSE); andre@0: } andre@0: andre@0: andre@0: /* andre@0: * RESPONSE SUPPORT FUNCTIONS (encode/create/decode/destroy): andre@0: */ andre@0: andre@0: /* andre@0: * Helper function for encoding or decoding a ResponderID -- based on the andre@0: * given type, return the associated template for that choice. andre@0: */ andre@0: static const SEC_ASN1Template * andre@0: ocsp_ResponderIDTemplateByType(CERTOCSPResponderIDType responderIDType) andre@0: { andre@0: const SEC_ASN1Template *responderIDTemplate; andre@0: andre@0: switch (responderIDType) { andre@0: case ocspResponderID_byName: andre@0: responderIDTemplate = ocsp_ResponderIDByNameTemplate; andre@0: break; andre@0: case ocspResponderID_byKey: andre@0: responderIDTemplate = ocsp_ResponderIDByKeyTemplate; andre@0: break; andre@0: case ocspResponderID_other: andre@0: default: andre@0: PORT_Assert(responderIDType == ocspResponderID_other); andre@0: responderIDTemplate = ocsp_ResponderIDOtherTemplate; andre@0: break; andre@0: } andre@0: andre@0: return responderIDTemplate; andre@0: } andre@0: andre@0: /* andre@0: * Helper function for encoding or decoding a CertStatus -- based on the andre@0: * given type, return the associated template for that choice. andre@0: */ andre@0: static const SEC_ASN1Template * andre@0: ocsp_CertStatusTemplateByType(ocspCertStatusType certStatusType) andre@0: { andre@0: const SEC_ASN1Template *certStatusTemplate; andre@0: andre@0: switch (certStatusType) { andre@0: case ocspCertStatus_good: andre@0: certStatusTemplate = ocsp_CertStatusGoodTemplate; andre@0: break; andre@0: case ocspCertStatus_revoked: andre@0: certStatusTemplate = ocsp_CertStatusRevokedTemplate; andre@0: break; andre@0: case ocspCertStatus_unknown: andre@0: certStatusTemplate = ocsp_CertStatusUnknownTemplate; andre@0: break; andre@0: case ocspCertStatus_other: andre@0: default: andre@0: PORT_Assert(certStatusType == ocspCertStatus_other); andre@0: certStatusTemplate = ocsp_CertStatusOtherTemplate; andre@0: break; andre@0: } andre@0: andre@0: return certStatusTemplate; andre@0: } andre@0: andre@0: /* andre@0: * Helper function for decoding a certStatus -- turn the actual DER tag andre@0: * into our local translation. andre@0: */ andre@0: static ocspCertStatusType andre@0: ocsp_CertStatusTypeByTag(int derTag) andre@0: { andre@0: ocspCertStatusType certStatusType; andre@0: andre@0: switch (derTag) { andre@0: case 0: andre@0: certStatusType = ocspCertStatus_good; andre@0: break; andre@0: case 1: andre@0: certStatusType = ocspCertStatus_revoked; andre@0: break; andre@0: case 2: andre@0: certStatusType = ocspCertStatus_unknown; andre@0: break; andre@0: default: andre@0: certStatusType = ocspCertStatus_other; andre@0: break; andre@0: } andre@0: andre@0: return certStatusType; andre@0: } andre@0: andre@0: /* andre@0: * Helper function for decoding SingleResponses -- they each contain andre@0: * a status which is encoded as CHOICE, which needs to be decoded "by hand". andre@0: * andre@0: * Note -- on error, this routine does not release the memory it may andre@0: * have allocated; it expects its caller to do that. andre@0: */ andre@0: static SECStatus andre@0: ocsp_FinishDecodingSingleResponses(PLArenaPool *reqArena, andre@0: CERTOCSPSingleResponse **responses) andre@0: { andre@0: ocspCertStatus *certStatus; andre@0: ocspCertStatusType certStatusType; andre@0: const SEC_ASN1Template *certStatusTemplate; andre@0: int derTag; andre@0: int i; andre@0: SECStatus rv = SECFailure; andre@0: andre@0: if (!reqArena) { andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: return SECFailure; andre@0: } andre@0: andre@0: if (responses == NULL) /* nothing to do */ andre@0: return SECSuccess; andre@0: andre@0: for (i = 0; responses[i] != NULL; i++) { andre@0: SECItem* newStatus; andre@0: /* andre@0: * The following assert points out internal errors (problems in andre@0: * the template definitions or in the ASN.1 decoder itself, etc.). andre@0: */ andre@0: PORT_Assert(responses[i]->derCertStatus.data != NULL); andre@0: andre@0: derTag = responses[i]->derCertStatus.data[0] & SEC_ASN1_TAGNUM_MASK; andre@0: certStatusType = ocsp_CertStatusTypeByTag(derTag); andre@0: certStatusTemplate = ocsp_CertStatusTemplateByType(certStatusType); andre@0: andre@0: certStatus = PORT_ArenaZAlloc(reqArena, sizeof(ocspCertStatus)); andre@0: if (certStatus == NULL) { andre@0: goto loser; andre@0: } andre@0: newStatus = SECITEM_ArenaDupItem(reqArena, &responses[i]->derCertStatus); andre@0: if (!newStatus) { andre@0: goto loser; andre@0: } andre@0: rv = SEC_QuickDERDecodeItem(reqArena, certStatus, certStatusTemplate, andre@0: newStatus); andre@0: if (rv != SECSuccess) { andre@0: if (PORT_GetError() == SEC_ERROR_BAD_DER) andre@0: PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); andre@0: goto loser; andre@0: } andre@0: andre@0: certStatus->certStatusType = certStatusType; andre@0: responses[i]->certStatus = certStatus; andre@0: } andre@0: andre@0: return SECSuccess; andre@0: andre@0: loser: andre@0: return rv; andre@0: } andre@0: andre@0: /* andre@0: * Helper function for decoding a responderID -- turn the actual DER tag andre@0: * into our local translation. andre@0: */ andre@0: static CERTOCSPResponderIDType andre@0: ocsp_ResponderIDTypeByTag(int derTag) andre@0: { andre@0: CERTOCSPResponderIDType responderIDType; andre@0: andre@0: switch (derTag) { andre@0: case 1: andre@0: responderIDType = ocspResponderID_byName; andre@0: break; andre@0: case 2: andre@0: responderIDType = ocspResponderID_byKey; andre@0: break; andre@0: default: andre@0: responderIDType = ocspResponderID_other; andre@0: break; andre@0: } andre@0: andre@0: return responderIDType; andre@0: } andre@0: andre@0: /* andre@0: * Decode "src" as a BasicOCSPResponse, returning the result. andre@0: */ andre@0: static ocspBasicOCSPResponse * andre@0: ocsp_DecodeBasicOCSPResponse(PLArenaPool *arena, SECItem *src) andre@0: { andre@0: void *mark; andre@0: ocspBasicOCSPResponse *basicResponse; andre@0: ocspResponseData *responseData; andre@0: ocspResponderID *responderID; andre@0: CERTOCSPResponderIDType responderIDType; andre@0: const SEC_ASN1Template *responderIDTemplate; andre@0: int derTag; andre@0: SECStatus rv; andre@0: SECItem newsrc; andre@0: andre@0: mark = PORT_ArenaMark(arena); andre@0: andre@0: basicResponse = PORT_ArenaZAlloc(arena, sizeof(ocspBasicOCSPResponse)); andre@0: if (basicResponse == NULL) { andre@0: goto loser; andre@0: } andre@0: andre@0: /* copy the DER into the arena, since Quick DER returns data that points andre@0: into the DER input, which may get freed by the caller */ andre@0: rv = SECITEM_CopyItem(arena, &newsrc, src); andre@0: if ( rv != SECSuccess ) { andre@0: goto loser; andre@0: } andre@0: andre@0: rv = SEC_QuickDERDecodeItem(arena, basicResponse, andre@0: ocsp_BasicOCSPResponseTemplate, &newsrc); andre@0: if (rv != SECSuccess) { andre@0: if (PORT_GetError() == SEC_ERROR_BAD_DER) andre@0: PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); andre@0: goto loser; andre@0: } andre@0: andre@0: responseData = basicResponse->tbsResponseData; andre@0: andre@0: /* andre@0: * The following asserts point out internal errors (problems in andre@0: * the template definitions or in the ASN.1 decoder itself, etc.). andre@0: */ andre@0: PORT_Assert(responseData != NULL); andre@0: PORT_Assert(responseData->derResponderID.data != NULL); andre@0: andre@0: /* andre@0: * XXX Because responderID is a CHOICE, which is not currently handled andre@0: * by our ASN.1 decoder, we have to decode it "by hand". andre@0: */ andre@0: derTag = responseData->derResponderID.data[0] & SEC_ASN1_TAGNUM_MASK; andre@0: responderIDType = ocsp_ResponderIDTypeByTag(derTag); andre@0: responderIDTemplate = ocsp_ResponderIDTemplateByType(responderIDType); andre@0: andre@0: responderID = PORT_ArenaZAlloc(arena, sizeof(ocspResponderID)); andre@0: if (responderID == NULL) { andre@0: goto loser; andre@0: } andre@0: andre@0: rv = SEC_QuickDERDecodeItem(arena, responderID, responderIDTemplate, andre@0: &responseData->derResponderID); andre@0: if (rv != SECSuccess) { andre@0: if (PORT_GetError() == SEC_ERROR_BAD_DER) andre@0: PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); andre@0: goto loser; andre@0: } andre@0: andre@0: responderID->responderIDType = responderIDType; andre@0: responseData->responderID = responderID; andre@0: andre@0: /* andre@0: * XXX Each SingleResponse also contains a CHOICE, which has to be andre@0: * fixed up by hand. andre@0: */ andre@0: rv = ocsp_FinishDecodingSingleResponses(arena, responseData->responses); andre@0: if (rv != SECSuccess) { andre@0: goto loser; andre@0: } andre@0: andre@0: PORT_ArenaUnmark(arena, mark); andre@0: return basicResponse; andre@0: andre@0: loser: andre@0: PORT_ArenaRelease(arena, mark); andre@0: return NULL; andre@0: } andre@0: andre@0: andre@0: /* andre@0: * Decode the responseBytes based on the responseType found in "rbytes", andre@0: * leaving the resulting translated/decoded information in there as well. andre@0: */ andre@0: static SECStatus andre@0: ocsp_DecodeResponseBytes(PLArenaPool *arena, ocspResponseBytes *rbytes) andre@0: { andre@0: if (rbytes == NULL) { andre@0: PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE); andre@0: return SECFailure; andre@0: } andre@0: andre@0: rbytes->responseTypeTag = SECOID_FindOIDTag(&rbytes->responseType); andre@0: switch (rbytes->responseTypeTag) { andre@0: case SEC_OID_PKIX_OCSP_BASIC_RESPONSE: andre@0: { andre@0: ocspBasicOCSPResponse *basicResponse; andre@0: andre@0: basicResponse = ocsp_DecodeBasicOCSPResponse(arena, andre@0: &rbytes->response); andre@0: if (basicResponse == NULL) andre@0: return SECFailure; andre@0: andre@0: rbytes->decodedResponse.basic = basicResponse; andre@0: } andre@0: break; andre@0: andre@0: /* andre@0: * Add new/future response types here. andre@0: */ andre@0: andre@0: default: andre@0: PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE); andre@0: return SECFailure; andre@0: } andre@0: andre@0: return SECSuccess; andre@0: } andre@0: andre@0: andre@0: /* andre@0: * FUNCTION: CERT_DecodeOCSPResponse andre@0: * Decode a DER encoded OCSP Response. andre@0: * INPUTS: andre@0: * SECItem *src andre@0: * Pointer to a SECItem holding DER encoded OCSP Response. andre@0: * RETURN: andre@0: * Returns a pointer to a CERTOCSPResponse (the decoded OCSP Response); andre@0: * the caller is responsible for destroying it. Or NULL if error (either andre@0: * response could not be decoded (SEC_ERROR_OCSP_MALFORMED_RESPONSE), andre@0: * it was of an unexpected type (SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE), andre@0: * or a low-level or internal error occurred). andre@0: */ andre@0: CERTOCSPResponse * andre@0: CERT_DecodeOCSPResponse(const SECItem *src) andre@0: { andre@0: PLArenaPool *arena = NULL; andre@0: CERTOCSPResponse *response = NULL; andre@0: SECStatus rv = SECFailure; andre@0: ocspResponseStatus sv; andre@0: SECItem newSrc; andre@0: andre@0: arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); andre@0: if (arena == NULL) { andre@0: goto loser; andre@0: } andre@0: response = (CERTOCSPResponse *) PORT_ArenaZAlloc(arena, andre@0: sizeof(CERTOCSPResponse)); andre@0: if (response == NULL) { andre@0: goto loser; andre@0: } andre@0: response->arena = arena; andre@0: andre@0: /* copy the DER into the arena, since Quick DER returns data that points andre@0: into the DER input, which may get freed by the caller */ andre@0: rv = SECITEM_CopyItem(arena, &newSrc, src); andre@0: if ( rv != SECSuccess ) { andre@0: goto loser; andre@0: } andre@0: andre@0: rv = SEC_QuickDERDecodeItem(arena, response, ocsp_OCSPResponseTemplate, &newSrc); andre@0: if (rv != SECSuccess) { andre@0: if (PORT_GetError() == SEC_ERROR_BAD_DER) andre@0: PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); andre@0: goto loser; andre@0: } andre@0: andre@0: sv = (ocspResponseStatus) DER_GetInteger(&response->responseStatus); andre@0: response->statusValue = sv; andre@0: if (sv != ocspResponse_successful) { andre@0: /* andre@0: * If the response status is anything but successful, then we andre@0: * are all done with decoding; the status is all there is. andre@0: */ andre@0: return response; andre@0: } andre@0: andre@0: /* andre@0: * A successful response contains much more information, still encoded. andre@0: * Now we need to decode that. andre@0: */ andre@0: rv = ocsp_DecodeResponseBytes(arena, response->responseBytes); andre@0: if (rv != SECSuccess) { andre@0: goto loser; andre@0: } andre@0: andre@0: return response; andre@0: andre@0: loser: andre@0: if (arena != NULL) { andre@0: PORT_FreeArena(arena, PR_FALSE); andre@0: } andre@0: return NULL; andre@0: } andre@0: andre@0: /* andre@0: * The way an OCSPResponse is defined, there are many levels to descend andre@0: * before getting to the actual response information. And along the way andre@0: * we need to check that the response *type* is recognizable, which for andre@0: * now means that it is a BasicOCSPResponse, because that is the only andre@0: * type currently defined. Rather than force all routines to perform andre@0: * a bunch of sanity checking every time they want to work on a response, andre@0: * this function isolates that and gives back the interesting part. andre@0: * Note that no copying is done, this just returns a pointer into the andre@0: * substructure of the response which is passed in. andre@0: * andre@0: * XXX This routine only works when a valid response structure is passed andre@0: * into it; this is checked with many assertions. Assuming the response andre@0: * was creating by decoding, it wouldn't make it this far without being andre@0: * okay. That is a sufficient assumption since the entire OCSP interface andre@0: * is only used internally. When this interface is officially exported, andre@0: * each assertion below will need to be followed-up with setting an error andre@0: * and returning (null). andre@0: * andre@0: * FUNCTION: ocsp_GetResponseData andre@0: * Returns ocspResponseData structure and a pointer to tbs response andre@0: * data DER from a valid ocsp response. andre@0: * INPUTS: andre@0: * CERTOCSPResponse *response andre@0: * structure of a valid ocsp response andre@0: * RETURN: andre@0: * Returns a pointer to ocspResponseData structure: decoded OCSP response andre@0: * data, and a pointer(tbsResponseDataDER) to its undecoded data DER. andre@0: */ andre@0: ocspResponseData * andre@0: ocsp_GetResponseData(CERTOCSPResponse *response, SECItem **tbsResponseDataDER) andre@0: { andre@0: ocspBasicOCSPResponse *basic; andre@0: ocspResponseData *responseData; andre@0: andre@0: PORT_Assert(response != NULL); andre@0: andre@0: PORT_Assert(response->responseBytes != NULL); andre@0: andre@0: PORT_Assert(response->responseBytes->responseTypeTag andre@0: == SEC_OID_PKIX_OCSP_BASIC_RESPONSE); andre@0: andre@0: basic = response->responseBytes->decodedResponse.basic; andre@0: PORT_Assert(basic != NULL); andre@0: andre@0: responseData = basic->tbsResponseData; andre@0: PORT_Assert(responseData != NULL); andre@0: andre@0: if (tbsResponseDataDER) { andre@0: *tbsResponseDataDER = &basic->tbsResponseDataDER; andre@0: andre@0: PORT_Assert((*tbsResponseDataDER)->data != NULL); andre@0: PORT_Assert((*tbsResponseDataDER)->len != 0); andre@0: } andre@0: andre@0: return responseData; andre@0: } andre@0: andre@0: /* andre@0: * Much like the routine above, except it returns the response signature. andre@0: * Again, no copy is done. andre@0: */ andre@0: ocspSignature * andre@0: ocsp_GetResponseSignature(CERTOCSPResponse *response) andre@0: { andre@0: ocspBasicOCSPResponse *basic; andre@0: andre@0: PORT_Assert(response != NULL); andre@0: if (NULL == response->responseBytes) { andre@0: return NULL; andre@0: } andre@0: if (response->responseBytes->responseTypeTag andre@0: != SEC_OID_PKIX_OCSP_BASIC_RESPONSE) { andre@0: return NULL; andre@0: } andre@0: basic = response->responseBytes->decodedResponse.basic; andre@0: PORT_Assert(basic != NULL); andre@0: andre@0: return &(basic->responseSignature); andre@0: } andre@0: andre@0: andre@0: /* andre@0: * FUNCTION: CERT_DestroyOCSPResponse andre@0: * Frees an OCSP Response structure. andre@0: * INPUTS: andre@0: * CERTOCSPResponse *request andre@0: * Pointer to CERTOCSPResponse to be freed. andre@0: * RETURN: andre@0: * No return value; no errors. andre@0: */ andre@0: void andre@0: CERT_DestroyOCSPResponse(CERTOCSPResponse *response) andre@0: { andre@0: if (response != NULL) { andre@0: ocspSignature *signature = ocsp_GetResponseSignature(response); andre@0: if (signature && signature->cert != NULL) andre@0: CERT_DestroyCertificate(signature->cert); andre@0: andre@0: /* andre@0: * We should actually never have a response without an arena, andre@0: * but check just in case. (If there isn't one, there is not andre@0: * much we can do about it...) andre@0: */ andre@0: PORT_Assert(response->arena != NULL); andre@0: if (response->arena != NULL) { andre@0: PORT_FreeArena(response->arena, PR_FALSE); andre@0: } andre@0: } andre@0: } andre@0: andre@0: andre@0: /* andre@0: * OVERALL OCSP CLIENT SUPPORT (make and send a request, verify a response): andre@0: */ andre@0: andre@0: andre@0: /* andre@0: * Pick apart a URL, saving the important things in the passed-in pointers. andre@0: * andre@0: * We expect to find "http://[:]/[path]", though we will andre@0: * tolerate that final slash character missing, as well as beginning and andre@0: * trailing whitespace, and any-case-characters for "http". All of that andre@0: * tolerance is what complicates this routine. What we want is just to andre@0: * pick out the hostname, the port, and the path. andre@0: * andre@0: * On a successful return, the caller will need to free the output pieces andre@0: * of hostname and path, which are copies of the values found in the url. andre@0: */ andre@0: static SECStatus andre@0: ocsp_ParseURL(const char *url, char **pHostname, PRUint16 *pPort, char **pPath) andre@0: { andre@0: unsigned short port = 80; /* default, in case not in url */ andre@0: char *hostname = NULL; andre@0: char *path = NULL; andre@0: const char *save; andre@0: char c; andre@0: int len; andre@0: andre@0: if (url == NULL) andre@0: goto loser; andre@0: andre@0: /* andre@0: * Skip beginning whitespace. andre@0: */ andre@0: c = *url; andre@0: while ((c == ' ' || c == '\t') && c != '\0') { andre@0: url++; andre@0: c = *url; andre@0: } andre@0: if (c == '\0') andre@0: goto loser; andre@0: andre@0: /* andre@0: * Confirm, then skip, protocol. (Since we only know how to do http, andre@0: * that is all we will accept). andre@0: */ andre@0: if (PORT_Strncasecmp(url, "http://", 7) != 0) andre@0: goto loser; andre@0: url += 7; andre@0: andre@0: /* andre@0: * Whatever comes next is the hostname (or host IP address). We just andre@0: * save it aside and then search for its end so we can determine its andre@0: * length and copy it. andre@0: * andre@0: * XXX Note that because we treat a ':' as a terminator character andre@0: * (and below, we expect that to mean there is a port specification andre@0: * immediately following), we will not handle IPv6 addresses. That is andre@0: * apparently an acceptable limitation, for the time being. Some day, andre@0: * when there is a clear way to specify a URL with an IPv6 address that andre@0: * can be parsed unambiguously, this code should be made to do that. andre@0: */ andre@0: save = url; andre@0: c = *url; andre@0: while (c != '/' && c != ':' && c != '\0' && c != ' ' && c != '\t') { andre@0: url++; andre@0: c = *url; andre@0: } andre@0: len = url - save; andre@0: hostname = PORT_Alloc(len + 1); andre@0: if (hostname == NULL) andre@0: goto loser; andre@0: PORT_Memcpy(hostname, save, len); andre@0: hostname[len] = '\0'; andre@0: andre@0: /* andre@0: * Now we figure out if there was a port specified or not. andre@0: * If so, we need to parse it (as a number) and skip it. andre@0: */ andre@0: if (c == ':') { andre@0: url++; andre@0: port = (unsigned short) PORT_Atoi(url); andre@0: c = *url; andre@0: while (c != '/' && c != '\0' && c != ' ' && c != '\t') { andre@0: if (c < '0' || c > '9') andre@0: goto loser; andre@0: url++; andre@0: c = *url; andre@0: } andre@0: } andre@0: andre@0: /* andre@0: * Last thing to find is a path. There *should* be a slash, andre@0: * if nothing else -- but if there is not we provide one. andre@0: */ andre@0: if (c == '/') { andre@0: save = url; andre@0: while (c != '\0' && c != ' ' && c != '\t') { andre@0: url++; andre@0: c = *url; andre@0: } andre@0: len = url - save; andre@0: path = PORT_Alloc(len + 1); andre@0: if (path == NULL) andre@0: goto loser; andre@0: PORT_Memcpy(path, save, len); andre@0: path[len] = '\0'; andre@0: } else { andre@0: path = PORT_Strdup("/"); andre@0: if (path == NULL) andre@0: goto loser; andre@0: } andre@0: andre@0: *pHostname = hostname; andre@0: *pPort = port; andre@0: *pPath = path; andre@0: return SECSuccess; andre@0: andre@0: loser: andre@0: if (hostname != NULL) andre@0: PORT_Free(hostname); andre@0: PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION); andre@0: return SECFailure; andre@0: } andre@0: andre@0: /* andre@0: * Open a socket to the specified host on the specified port, and return it. andre@0: * The host is either a hostname or an IP address. andre@0: */ andre@0: static PRFileDesc * andre@0: ocsp_ConnectToHost(const char *host, PRUint16 port) andre@0: { andre@0: PRFileDesc *sock = NULL; andre@0: PRIntervalTime timeout; andre@0: PRNetAddr addr; andre@0: char *netdbbuf = NULL; andre@0: andre@0: sock = PR_NewTCPSocket(); andre@0: if (sock == NULL) andre@0: goto loser; andre@0: andre@0: /* XXX Some day need a way to set (and get?) the following value */ andre@0: timeout = PR_SecondsToInterval(30); andre@0: andre@0: /* andre@0: * If the following converts an IP address string in "dot notation" andre@0: * into a PRNetAddr. If it fails, we assume that is because we do not andre@0: * have such an address, but instead a host *name*. In that case we andre@0: * then lookup the host by name. Using the NSPR function this way andre@0: * means we do not have to have our own logic for distinguishing a andre@0: * valid numerical IP address from a hostname. andre@0: */ andre@0: if (PR_StringToNetAddr(host, &addr) != PR_SUCCESS) { andre@0: PRIntn hostIndex; andre@0: PRHostEnt hostEntry; andre@0: andre@0: netdbbuf = PORT_Alloc(PR_NETDB_BUF_SIZE); andre@0: if (netdbbuf == NULL) andre@0: goto loser; andre@0: andre@0: if (PR_GetHostByName(host, netdbbuf, PR_NETDB_BUF_SIZE, andre@0: &hostEntry) != PR_SUCCESS) andre@0: goto loser; andre@0: andre@0: hostIndex = 0; andre@0: do { andre@0: hostIndex = PR_EnumerateHostEnt(hostIndex, &hostEntry, port, &addr); andre@0: if (hostIndex <= 0) andre@0: goto loser; andre@0: } while (PR_Connect(sock, &addr, timeout) != PR_SUCCESS); andre@0: andre@0: PORT_Free(netdbbuf); andre@0: } else { andre@0: /* andre@0: * First put the port into the address, then connect. andre@0: */ andre@0: if (PR_InitializeNetAddr(PR_IpAddrNull, port, &addr) != PR_SUCCESS) andre@0: goto loser; andre@0: if (PR_Connect(sock, &addr, timeout) != PR_SUCCESS) andre@0: goto loser; andre@0: } andre@0: andre@0: return sock; andre@0: andre@0: loser: andre@0: if (sock != NULL) andre@0: PR_Close(sock); andre@0: if (netdbbuf != NULL) andre@0: PORT_Free(netdbbuf); andre@0: return NULL; andre@0: } andre@0: andre@0: /* andre@0: * Sends an encoded OCSP request to the server identified by "location", andre@0: * and returns the socket on which it was sent (so can listen for the reply). andre@0: * "location" is expected to be a valid URL -- an error parsing it produces andre@0: * SEC_ERROR_CERT_BAD_ACCESS_LOCATION. Other errors are likely problems andre@0: * connecting to it, or writing to it, or allocating memory, and the low-level andre@0: * errors appropriate to the problem will be set. andre@0: * if (encodedRequest == NULL) andre@0: * then location MUST already include the full request, andre@0: * including base64 and urlencode, andre@0: * and the request will be sent with GET andre@0: * if (encodedRequest != NULL) andre@0: * then the request will be sent with POST andre@0: */ andre@0: static PRFileDesc * andre@0: ocsp_SendEncodedRequest(const char *location, const SECItem *encodedRequest) andre@0: { andre@0: char *hostname = NULL; andre@0: char *path = NULL; andre@0: PRUint16 port; andre@0: SECStatus rv; andre@0: PRFileDesc *sock = NULL; andre@0: PRFileDesc *returnSock = NULL; andre@0: char *header = NULL; andre@0: char portstr[16]; andre@0: andre@0: /* andre@0: * Take apart the location, getting the hostname, port, and path. andre@0: */ andre@0: rv = ocsp_ParseURL(location, &hostname, &port, &path); andre@0: if (rv != SECSuccess) andre@0: goto loser; andre@0: andre@0: PORT_Assert(hostname != NULL); andre@0: PORT_Assert(path != NULL); andre@0: andre@0: sock = ocsp_ConnectToHost(hostname, port); andre@0: if (sock == NULL) andre@0: goto loser; andre@0: andre@0: portstr[0] = '\0'; andre@0: if (port != 80) { andre@0: PR_snprintf(portstr, sizeof(portstr), ":%d", port); andre@0: } andre@0: andre@0: if (!encodedRequest) { andre@0: header = PR_smprintf("GET %s HTTP/1.0\r\n" andre@0: "Host: %s%s\r\n\r\n", andre@0: path, hostname, portstr); andre@0: if (header == NULL) andre@0: goto loser; andre@0: andre@0: /* andre@0: * The NSPR documentation promises that if it can, it will write the full andre@0: * amount; this will not return a partial value expecting us to loop. andre@0: */ andre@0: if (PR_Write(sock, header, (PRInt32) PORT_Strlen(header)) < 0) andre@0: goto loser; andre@0: } andre@0: else { andre@0: header = PR_smprintf("POST %s HTTP/1.0\r\n" andre@0: "Host: %s%s\r\n" andre@0: "Content-Type: application/ocsp-request\r\n" andre@0: "Content-Length: %u\r\n\r\n", andre@0: path, hostname, portstr, encodedRequest->len); andre@0: if (header == NULL) andre@0: goto loser; andre@0: andre@0: /* andre@0: * The NSPR documentation promises that if it can, it will write the full andre@0: * amount; this will not return a partial value expecting us to loop. andre@0: */ andre@0: if (PR_Write(sock, header, (PRInt32) PORT_Strlen(header)) < 0) andre@0: goto loser; andre@0: andre@0: if (PR_Write(sock, encodedRequest->data, andre@0: (PRInt32) encodedRequest->len) < 0) andre@0: goto loser; andre@0: } andre@0: andre@0: returnSock = sock; andre@0: sock = NULL; andre@0: andre@0: loser: andre@0: if (header != NULL) andre@0: PORT_Free(header); andre@0: if (sock != NULL) andre@0: PR_Close(sock); andre@0: if (path != NULL) andre@0: PORT_Free(path); andre@0: if (hostname != NULL) andre@0: PORT_Free(hostname); andre@0: andre@0: return returnSock; andre@0: } andre@0: andre@0: /* andre@0: * Read from "fd" into "buf" -- expect/attempt to read a given number of bytes andre@0: * Obviously, stop if hit end-of-stream. Timeout is passed in. andre@0: */ andre@0: andre@0: static int andre@0: ocsp_read(PRFileDesc *fd, char *buf, int toread, PRIntervalTime timeout) andre@0: { andre@0: int total = 0; andre@0: andre@0: while (total < toread) andre@0: { andre@0: PRInt32 got; andre@0: andre@0: got = PR_Recv(fd, buf + total, (PRInt32) (toread - total), 0, timeout); andre@0: if (got < 0) andre@0: { andre@0: if (0 == total) andre@0: { andre@0: total = -1; /* report the error if we didn't read anything yet */ andre@0: } andre@0: break; andre@0: } andre@0: else andre@0: if (got == 0) andre@0: { /* EOS */ andre@0: break; andre@0: } andre@0: andre@0: total += got; andre@0: } andre@0: andre@0: return total; andre@0: } andre@0: andre@0: #define OCSP_BUFSIZE 1024 andre@0: andre@0: #define AbortHttpDecode(error) \ andre@0: { \ andre@0: if (inBuffer) \ andre@0: PORT_Free(inBuffer); \ andre@0: PORT_SetError(error); \ andre@0: return NULL; \ andre@0: } andre@0: andre@0: andre@0: /* andre@0: * Reads on the given socket and returns an encoded response when received. andre@0: * Properly formatted HTTP/1.0 response headers are expected to be read andre@0: * from the socket, preceding a binary-encoded OCSP response. Problems andre@0: * with parsing cause the error SEC_ERROR_OCSP_BAD_HTTP_RESPONSE to be andre@0: * set; any other problems are likely low-level i/o or memory allocation andre@0: * errors. andre@0: */ andre@0: static SECItem * andre@0: ocsp_GetEncodedResponse(PLArenaPool *arena, PRFileDesc *sock) andre@0: { andre@0: /* first read HTTP status line and headers */ andre@0: andre@0: char* inBuffer = NULL; andre@0: PRInt32 offset = 0; andre@0: PRInt32 inBufsize = 0; andre@0: const PRInt32 bufSizeIncrement = OCSP_BUFSIZE; /* 1 KB at a time */ andre@0: const PRInt32 maxBufSize = 8 * bufSizeIncrement ; /* 8 KB max */ andre@0: const char* CRLF = "\r\n"; andre@0: const PRInt32 CRLFlen = strlen(CRLF); andre@0: const char* headerEndMark = "\r\n\r\n"; andre@0: const PRInt32 markLen = strlen(headerEndMark); andre@0: const PRIntervalTime ocsptimeout = andre@0: PR_SecondsToInterval(30); /* hardcoded to 30s for now */ andre@0: char* headerEnd = NULL; andre@0: PRBool EOS = PR_FALSE; andre@0: const char* httpprotocol = "HTTP/"; andre@0: const PRInt32 httplen = strlen(httpprotocol); andre@0: const char* httpcode = NULL; andre@0: const char* contenttype = NULL; andre@0: PRInt32 contentlength = 0; andre@0: PRInt32 bytesRead = 0; andre@0: char* statusLineEnd = NULL; andre@0: char* space = NULL; andre@0: char* nextHeader = NULL; andre@0: SECItem* result = NULL; andre@0: andre@0: /* read up to at least the end of the HTTP headers */ andre@0: do andre@0: { andre@0: inBufsize += bufSizeIncrement; andre@0: inBuffer = PORT_Realloc(inBuffer, inBufsize+1); andre@0: if (NULL == inBuffer) andre@0: { andre@0: AbortHttpDecode(SEC_ERROR_NO_MEMORY); andre@0: } andre@0: bytesRead = ocsp_read(sock, inBuffer + offset, bufSizeIncrement, andre@0: ocsptimeout); andre@0: if (bytesRead > 0) andre@0: { andre@0: PRInt32 searchOffset = (offset - markLen) >0 ? offset-markLen : 0; andre@0: offset += bytesRead; andre@0: *(inBuffer + offset) = '\0'; /* NULL termination */ andre@0: headerEnd = strstr((const char*)inBuffer + searchOffset, headerEndMark); andre@0: if (bytesRead < bufSizeIncrement) andre@0: { andre@0: /* we read less data than requested, therefore we are at andre@0: EOS or there was a read error */ andre@0: EOS = PR_TRUE; andre@0: } andre@0: } andre@0: else andre@0: { andre@0: /* recv error or EOS */ andre@0: EOS = PR_TRUE; andre@0: } andre@0: } while ( (!headerEnd) && (PR_FALSE == EOS) && andre@0: (inBufsize < maxBufSize) ); andre@0: andre@0: if (!headerEnd) andre@0: { andre@0: AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); andre@0: } andre@0: andre@0: /* parse the HTTP status line */ andre@0: statusLineEnd = strstr((const char*)inBuffer, CRLF); andre@0: if (!statusLineEnd) andre@0: { andre@0: AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); andre@0: } andre@0: *statusLineEnd = '\0'; andre@0: andre@0: /* check for HTTP/ response */ andre@0: space = strchr((const char*)inBuffer, ' '); andre@0: if (!space || PORT_Strncasecmp((const char*)inBuffer, httpprotocol, httplen) != 0 ) andre@0: { andre@0: AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); andre@0: } andre@0: andre@0: /* check the HTTP status code of 200 */ andre@0: httpcode = space +1; andre@0: space = strchr(httpcode, ' '); andre@0: if (!space) andre@0: { andre@0: AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); andre@0: } andre@0: *space = 0; andre@0: if (0 != strcmp(httpcode, "200")) andre@0: { andre@0: AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); andre@0: } andre@0: andre@0: /* parse the HTTP headers in the buffer . We only care about andre@0: content-type and content-length andre@0: */ andre@0: andre@0: nextHeader = statusLineEnd + CRLFlen; andre@0: *headerEnd = '\0'; /* terminate */ andre@0: do andre@0: { andre@0: char* thisHeaderEnd = NULL; andre@0: char* value = NULL; andre@0: char* colon = strchr(nextHeader, ':'); andre@0: andre@0: if (!colon) andre@0: { andre@0: AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); andre@0: } andre@0: andre@0: *colon = '\0'; andre@0: value = colon + 1; andre@0: andre@0: /* jpierre - note : the following code will only handle the basic form andre@0: of HTTP/1.0 response headers, of the form "name: value" . Headers andre@0: split among multiple lines are not supported. This is not common andre@0: and should not be an issue, but it could become one in the andre@0: future */ andre@0: andre@0: if (*value != ' ') andre@0: { andre@0: AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); andre@0: } andre@0: andre@0: value++; andre@0: thisHeaderEnd = strstr(value, CRLF); andre@0: if (thisHeaderEnd ) andre@0: { andre@0: *thisHeaderEnd = '\0'; andre@0: } andre@0: andre@0: if (0 == PORT_Strcasecmp(nextHeader, "content-type")) andre@0: { andre@0: contenttype = value; andre@0: } andre@0: else andre@0: if (0 == PORT_Strcasecmp(nextHeader, "content-length")) andre@0: { andre@0: contentlength = atoi(value); andre@0: } andre@0: andre@0: if (thisHeaderEnd ) andre@0: { andre@0: nextHeader = thisHeaderEnd + CRLFlen; andre@0: } andre@0: else andre@0: { andre@0: nextHeader = NULL; andre@0: } andre@0: andre@0: } while (nextHeader && (nextHeader < (headerEnd + CRLFlen) ) ); andre@0: andre@0: /* check content-type */ andre@0: if (!contenttype || andre@0: (0 != PORT_Strcasecmp(contenttype, "application/ocsp-response")) ) andre@0: { andre@0: AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); andre@0: } andre@0: andre@0: /* read the body of the OCSP response */ andre@0: offset = offset - (PRInt32) (headerEnd - (const char*)inBuffer) - markLen; andre@0: if (offset) andre@0: { andre@0: /* move all data to the beginning of the buffer */ andre@0: PORT_Memmove(inBuffer, headerEnd + markLen, offset); andre@0: } andre@0: andre@0: /* resize buffer to only what's needed to hold the current response */ andre@0: inBufsize = (1 + (offset-1) / bufSizeIncrement ) * bufSizeIncrement ; andre@0: andre@0: while ( (PR_FALSE == EOS) && andre@0: ( (contentlength == 0) || (offset < contentlength) ) && andre@0: (inBufsize < maxBufSize) andre@0: ) andre@0: { andre@0: /* we still need to receive more body data */ andre@0: inBufsize += bufSizeIncrement; andre@0: inBuffer = PORT_Realloc(inBuffer, inBufsize+1); andre@0: if (NULL == inBuffer) andre@0: { andre@0: AbortHttpDecode(SEC_ERROR_NO_MEMORY); andre@0: } andre@0: bytesRead = ocsp_read(sock, inBuffer + offset, bufSizeIncrement, andre@0: ocsptimeout); andre@0: if (bytesRead > 0) andre@0: { andre@0: offset += bytesRead; andre@0: if (bytesRead < bufSizeIncrement) andre@0: { andre@0: /* we read less data than requested, therefore we are at andre@0: EOS or there was a read error */ andre@0: EOS = PR_TRUE; andre@0: } andre@0: } andre@0: else andre@0: { andre@0: /* recv error or EOS */ andre@0: EOS = PR_TRUE; andre@0: } andre@0: } andre@0: andre@0: if (0 == offset) andre@0: { andre@0: AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); andre@0: } andre@0: andre@0: /* andre@0: * Now allocate the item to hold the data. andre@0: */ andre@0: result = SECITEM_AllocItem(arena, NULL, offset); andre@0: if (NULL == result) andre@0: { andre@0: AbortHttpDecode(SEC_ERROR_NO_MEMORY); andre@0: } andre@0: andre@0: /* andre@0: * And copy the data left in the buffer. andre@0: */ andre@0: PORT_Memcpy(result->data, inBuffer, offset); andre@0: andre@0: /* and free the temporary buffer */ andre@0: PORT_Free(inBuffer); andre@0: return result; andre@0: } andre@0: andre@0: SECStatus andre@0: CERT_ParseURL(const char *url, char **pHostname, PRUint16 *pPort, char **pPath) andre@0: { andre@0: return ocsp_ParseURL(url, pHostname, pPort, pPath); andre@0: } andre@0: andre@0: /* andre@0: * Limit the size of http responses we are willing to accept. andre@0: */ andre@0: #define MAX_WANTED_OCSP_RESPONSE_LEN 64*1024 andre@0: andre@0: /* if (encodedRequest == NULL) andre@0: * then location MUST already include the full request, andre@0: * including base64 and urlencode, andre@0: * and the request will be sent with GET andre@0: * if (encodedRequest != NULL) andre@0: * then the request will be sent with POST andre@0: */ andre@0: static SECItem * andre@0: fetchOcspHttpClientV1(PLArenaPool *arena, andre@0: const SEC_HttpClientFcnV1 *hcv1, andre@0: const char *location, andre@0: const SECItem *encodedRequest) andre@0: { andre@0: char *hostname = NULL; andre@0: char *path = NULL; andre@0: PRUint16 port; andre@0: SECItem *encodedResponse = NULL; andre@0: SEC_HTTP_SERVER_SESSION pServerSession = NULL; andre@0: SEC_HTTP_REQUEST_SESSION pRequestSession = NULL; andre@0: PRUint16 myHttpResponseCode; andre@0: const char *myHttpResponseData; andre@0: PRUint32 myHttpResponseDataLen; andre@0: andre@0: if (ocsp_ParseURL(location, &hostname, &port, &path) == SECFailure) { andre@0: PORT_SetError(SEC_ERROR_OCSP_MALFORMED_REQUEST); andre@0: goto loser; andre@0: } andre@0: andre@0: PORT_Assert(hostname != NULL); andre@0: PORT_Assert(path != NULL); andre@0: andre@0: if ((*hcv1->createSessionFcn)( andre@0: hostname, andre@0: port, andre@0: &pServerSession) != SECSuccess) { andre@0: PORT_SetError(SEC_ERROR_OCSP_SERVER_ERROR); andre@0: goto loser; andre@0: } andre@0: andre@0: /* We use a non-zero timeout, which means: andre@0: - the client will use blocking I/O andre@0: - TryFcn will not return WOULD_BLOCK nor a poll descriptor andre@0: - it's sufficient to call TryFcn once andre@0: No lock for accessing OCSP_Global.timeoutSeconds, bug 406120 andre@0: */ andre@0: andre@0: if ((*hcv1->createFcn)( andre@0: pServerSession, andre@0: "http", andre@0: path, andre@0: encodedRequest ? "POST" : "GET", andre@0: PR_TicksPerSecond() * OCSP_Global.timeoutSeconds, andre@0: &pRequestSession) != SECSuccess) { andre@0: PORT_SetError(SEC_ERROR_OCSP_SERVER_ERROR); andre@0: goto loser; andre@0: } andre@0: andre@0: if (encodedRequest && andre@0: (*hcv1->setPostDataFcn)( andre@0: pRequestSession, andre@0: (char*)encodedRequest->data, andre@0: encodedRequest->len, andre@0: "application/ocsp-request") != SECSuccess) { andre@0: PORT_SetError(SEC_ERROR_OCSP_SERVER_ERROR); andre@0: goto loser; andre@0: } andre@0: andre@0: /* we don't want result objects larger than this: */ andre@0: myHttpResponseDataLen = MAX_WANTED_OCSP_RESPONSE_LEN; andre@0: andre@0: OCSP_TRACE(("OCSP trySendAndReceive %s\n", location)); andre@0: andre@0: if ((*hcv1->trySendAndReceiveFcn)( andre@0: pRequestSession, andre@0: NULL, andre@0: &myHttpResponseCode, andre@0: NULL, andre@0: NULL, andre@0: &myHttpResponseData, andre@0: &myHttpResponseDataLen) != SECSuccess) { andre@0: PORT_SetError(SEC_ERROR_OCSP_SERVER_ERROR); andre@0: goto loser; andre@0: } andre@0: andre@0: OCSP_TRACE(("OCSP trySendAndReceive result http %d\n", myHttpResponseCode)); andre@0: andre@0: if (myHttpResponseCode != 200) { andre@0: PORT_SetError(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); andre@0: goto loser; andre@0: } andre@0: andre@0: encodedResponse = SECITEM_AllocItem(arena, NULL, myHttpResponseDataLen); andre@0: andre@0: if (!encodedResponse) { andre@0: PORT_SetError(SEC_ERROR_NO_MEMORY); andre@0: goto loser; andre@0: } andre@0: andre@0: PORT_Memcpy(encodedResponse->data, myHttpResponseData, myHttpResponseDataLen); andre@0: andre@0: loser: andre@0: if (pRequestSession != NULL) andre@0: (*hcv1->freeFcn)(pRequestSession); andre@0: if (pServerSession != NULL) andre@0: (*hcv1->freeSessionFcn)(pServerSession); andre@0: if (path != NULL) andre@0: PORT_Free(path); andre@0: if (hostname != NULL) andre@0: PORT_Free(hostname); andre@0: andre@0: return encodedResponse; andre@0: } andre@0: andre@0: /* andre@0: * FUNCTION: CERT_GetEncodedOCSPResponseByMethod andre@0: * Creates and sends a request to an OCSP responder, then reads and andre@0: * returns the (encoded) response. andre@0: * INPUTS: andre@0: * PLArenaPool *arena andre@0: * Pointer to arena from which return value will be allocated. andre@0: * If NULL, result will be allocated from the heap (and thus should andre@0: * be freed via SECITEM_FreeItem). andre@0: * CERTCertList *certList andre@0: * A list of certs for which status will be requested. andre@0: * Note that all of these certificates should have the same issuer, andre@0: * or it's expected the response will be signed by a trusted responder. andre@0: * If the certs need to be broken up into multiple requests, that andre@0: * must be handled by the caller (and thus by having multiple calls andre@0: * to this routine), who knows about where the request(s) are being andre@0: * sent and whether there are any trusted responders in place. andre@0: * const char *location andre@0: * The location of the OCSP responder (a URL). andre@0: * const char *method andre@0: * The protocol method used when retrieving the OCSP response. andre@0: * Currently support: "GET" (http GET) and "POST" (http POST). andre@0: * Additionals methods for http or other protocols might be added andre@0: * in the future. andre@0: * PRTime time andre@0: * Indicates the time for which the certificate status is to be andre@0: * determined -- this may be used in the search for the cert's issuer andre@0: * but has no other bearing on the operation. andre@0: * PRBool addServiceLocator andre@0: * If true, the Service Locator extension should be added to the andre@0: * single request(s) for each cert. andre@0: * CERTCertificate *signerCert andre@0: * If non-NULL, means sign the request using this cert. Otherwise, andre@0: * do not sign. andre@0: * void *pwArg andre@0: * Pointer to argument for password prompting, if needed. (Definitely andre@0: * not needed if not signing.) andre@0: * OUTPUTS: andre@0: * CERTOCSPRequest **pRequest andre@0: * Pointer in which to store the OCSP request created for the given andre@0: * list of certificates. It is only filled in if the entire operation andre@0: * is successful and the pointer is not null -- and in that case the andre@0: * caller is then reponsible for destroying it. andre@0: * RETURN: andre@0: * Returns a pointer to the SECItem holding the response. andre@0: * On error, returns null with error set describing the reason: andre@0: * SEC_ERROR_UNKNOWN_ISSUER andre@0: * SEC_ERROR_CERT_BAD_ACCESS_LOCATION andre@0: * SEC_ERROR_OCSP_BAD_HTTP_RESPONSE andre@0: * Other errors are low-level problems (no memory, bad database, etc.). andre@0: */ andre@0: SECItem * andre@0: CERT_GetEncodedOCSPResponseByMethod(PLArenaPool *arena, CERTCertList *certList, andre@0: const char *location, const char *method, andre@0: PRTime time, PRBool addServiceLocator, andre@0: CERTCertificate *signerCert, void *pwArg, andre@0: CERTOCSPRequest **pRequest) andre@0: { andre@0: CERTOCSPRequest *request; andre@0: request = CERT_CreateOCSPRequest(certList, time, addServiceLocator, andre@0: signerCert); andre@0: if (!request) andre@0: return NULL; andre@0: return ocsp_GetEncodedOCSPResponseFromRequest(arena, request, location, andre@0: method, time, addServiceLocator, andre@0: pwArg, pRequest); andre@0: } andre@0: andre@0: /* andre@0: * FUNCTION: CERT_GetEncodedOCSPResponse andre@0: * Creates and sends a request to an OCSP responder, then reads and andre@0: * returns the (encoded) response. andre@0: * andre@0: * This is a legacy API that behaves identically to andre@0: * CERT_GetEncodedOCSPResponseByMethod using the "POST" method. andre@0: */ andre@0: SECItem * andre@0: CERT_GetEncodedOCSPResponse(PLArenaPool *arena, CERTCertList *certList, andre@0: const char *location, PRTime time, andre@0: PRBool addServiceLocator, andre@0: CERTCertificate *signerCert, void *pwArg, andre@0: CERTOCSPRequest **pRequest) andre@0: { andre@0: return CERT_GetEncodedOCSPResponseByMethod(arena, certList, location, andre@0: "POST", time, addServiceLocator, andre@0: signerCert, pwArg, pRequest); andre@0: } andre@0: andre@0: /* URL encode a buffer that consists of base64-characters, only, andre@0: * which means we can use a simple encoding logic. andre@0: * andre@0: * No output buffer size checking is performed. andre@0: * You should call the function twice, to calculate the required buffer size. andre@0: * andre@0: * If the outpufBuf parameter is NULL, the function will calculate the andre@0: * required size, including the trailing zero termination char. andre@0: * andre@0: * The function returns the number of bytes calculated or produced. andre@0: */ andre@0: size_t andre@0: ocsp_UrlEncodeBase64Buf(const char *base64Buf, char *outputBuf) andre@0: { andre@0: const char *walkInput = NULL; andre@0: char *walkOutput = outputBuf; andre@0: size_t count = 0; andre@0: andre@0: for (walkInput=base64Buf; *walkInput; ++walkInput) { andre@0: char c = *walkInput; andre@0: if (isspace(c)) andre@0: continue; andre@0: switch (c) { andre@0: case '+': andre@0: if (outputBuf) { andre@0: strcpy(walkOutput, "%2B"); andre@0: walkOutput += 3; andre@0: } andre@0: count += 3; andre@0: break; andre@0: case '/': andre@0: if (outputBuf) { andre@0: strcpy(walkOutput, "%2F"); andre@0: walkOutput += 3; andre@0: } andre@0: count += 3; andre@0: break; andre@0: case '=': andre@0: if (outputBuf) { andre@0: strcpy(walkOutput, "%3D"); andre@0: walkOutput += 3; andre@0: } andre@0: count += 3; andre@0: break; andre@0: default: andre@0: if (outputBuf) { andre@0: *walkOutput = *walkInput; andre@0: ++walkOutput; andre@0: } andre@0: ++count; andre@0: break; andre@0: } andre@0: } andre@0: if (outputBuf) { andre@0: *walkOutput = 0; andre@0: } andre@0: ++count; andre@0: return count; andre@0: } andre@0: andre@0: enum { max_get_request_size = 255 }; /* defined by RFC2560 */ andre@0: andre@0: static SECItem * andre@0: cert_GetOCSPResponse(PLArenaPool *arena, const char *location, andre@0: const SECItem *encodedRequest); andre@0: andre@0: static SECItem * andre@0: ocsp_GetEncodedOCSPResponseFromRequest(PLArenaPool *arena, andre@0: CERTOCSPRequest *request, andre@0: const char *location, andre@0: const char *method, andre@0: PRTime time, andre@0: PRBool addServiceLocator, andre@0: void *pwArg, andre@0: CERTOCSPRequest **pRequest) andre@0: { andre@0: SECItem *encodedRequest = NULL; andre@0: SECItem *encodedResponse = NULL; andre@0: SECStatus rv; andre@0: andre@0: if (!location || !*location) /* location should be at least one byte */ andre@0: goto loser; andre@0: andre@0: rv = CERT_AddOCSPAcceptableResponses(request, andre@0: SEC_OID_PKIX_OCSP_BASIC_RESPONSE); andre@0: if (rv != SECSuccess) andre@0: goto loser; andre@0: andre@0: encodedRequest = CERT_EncodeOCSPRequest(NULL, request, pwArg); andre@0: if (encodedRequest == NULL) andre@0: goto loser; andre@0: andre@0: if (!strcmp(method, "GET")) { andre@0: encodedResponse = cert_GetOCSPResponse(arena, location, encodedRequest); andre@0: } andre@0: else if (!strcmp(method, "POST")) { andre@0: encodedResponse = CERT_PostOCSPRequest(arena, location, encodedRequest); andre@0: } andre@0: else { andre@0: goto loser; andre@0: } andre@0: andre@0: if (encodedResponse != NULL && pRequest != NULL) { andre@0: *pRequest = request; andre@0: request = NULL; /* avoid destroying below */ andre@0: } andre@0: andre@0: loser: andre@0: if (request != NULL) andre@0: CERT_DestroyOCSPRequest(request); andre@0: if (encodedRequest != NULL) andre@0: SECITEM_FreeItem(encodedRequest, PR_TRUE); andre@0: return encodedResponse; andre@0: } andre@0: andre@0: static SECItem * andre@0: cert_FetchOCSPResponse(PLArenaPool *arena, const char *location, andre@0: const SECItem *encodedRequest); andre@0: andre@0: /* using HTTP GET method */ andre@0: static SECItem * andre@0: cert_GetOCSPResponse(PLArenaPool *arena, const char *location, andre@0: const SECItem *encodedRequest) andre@0: { andre@0: char *walkOutput = NULL; andre@0: char *fullGetPath = NULL; andre@0: size_t pathLength; andre@0: PRInt32 urlEncodedBufLength; andre@0: size_t base64size; andre@0: char b64ReqBuf[max_get_request_size+1]; andre@0: size_t slashLengthIfNeeded = 0; andre@0: size_t getURLLength; andre@0: SECItem *item; andre@0: andre@0: if (!location || !*location) { andre@0: return NULL; andre@0: } andre@0: andre@0: pathLength = strlen(location); andre@0: if (location[pathLength-1] != '/') { andre@0: slashLengthIfNeeded = 1; andre@0: } andre@0: andre@0: /* Calculation as documented by PL_Base64Encode function. andre@0: * Use integer conversion to avoid having to use function ceil(). andre@0: */ andre@0: base64size = (((encodedRequest->len +2)/3) * 4); andre@0: if (base64size > max_get_request_size) { andre@0: return NULL; andre@0: } andre@0: memset(b64ReqBuf, 0, sizeof(b64ReqBuf)); andre@0: PL_Base64Encode((const char*)encodedRequest->data, encodedRequest->len, andre@0: b64ReqBuf); andre@0: andre@0: urlEncodedBufLength = ocsp_UrlEncodeBase64Buf(b64ReqBuf, NULL); andre@0: getURLLength = pathLength + urlEncodedBufLength + slashLengthIfNeeded; andre@0: andre@0: /* urlEncodedBufLength already contains room for the zero terminator. andre@0: * Add another if we must add the '/' char. andre@0: */ andre@0: if (arena) { andre@0: fullGetPath = (char*)PORT_ArenaAlloc(arena, getURLLength); andre@0: } else { andre@0: fullGetPath = (char*)PORT_Alloc(getURLLength); andre@0: } andre@0: if (!fullGetPath) { andre@0: return NULL; andre@0: } andre@0: andre@0: strcpy(fullGetPath, location); andre@0: walkOutput = fullGetPath + pathLength; andre@0: andre@0: if (walkOutput > fullGetPath && slashLengthIfNeeded) { andre@0: strcpy(walkOutput, "/"); andre@0: ++walkOutput; andre@0: } andre@0: ocsp_UrlEncodeBase64Buf(b64ReqBuf, walkOutput); andre@0: andre@0: item = cert_FetchOCSPResponse(arena, fullGetPath, NULL); andre@0: if (!arena) { andre@0: PORT_Free(fullGetPath); andre@0: } andre@0: return item; andre@0: } andre@0: andre@0: SECItem * andre@0: CERT_PostOCSPRequest(PLArenaPool *arena, const char *location, andre@0: const SECItem *encodedRequest) andre@0: { andre@0: return cert_FetchOCSPResponse(arena, location, encodedRequest); andre@0: } andre@0: andre@0: SECItem * andre@0: cert_FetchOCSPResponse(PLArenaPool *arena, const char *location, andre@0: const SECItem *encodedRequest) andre@0: { andre@0: const SEC_HttpClientFcn *registeredHttpClient; andre@0: SECItem *encodedResponse = NULL; andre@0: andre@0: registeredHttpClient = SEC_GetRegisteredHttpClient(); andre@0: andre@0: if (registeredHttpClient && registeredHttpClient->version == 1) { andre@0: encodedResponse = fetchOcspHttpClientV1( andre@0: arena, andre@0: ®isteredHttpClient->fcnTable.ftable1, andre@0: location, andre@0: encodedRequest); andre@0: } else { andre@0: /* use internal http client */ andre@0: PRFileDesc *sock = ocsp_SendEncodedRequest(location, encodedRequest); andre@0: if (sock) { andre@0: encodedResponse = ocsp_GetEncodedResponse(arena, sock); andre@0: PR_Close(sock); andre@0: } andre@0: } andre@0: andre@0: return encodedResponse; andre@0: } andre@0: andre@0: static SECItem * andre@0: ocsp_GetEncodedOCSPResponseForSingleCert(PLArenaPool *arena, andre@0: CERTOCSPCertID *certID, andre@0: CERTCertificate *singleCert, andre@0: const char *location, andre@0: const char *method, andre@0: PRTime time, andre@0: PRBool addServiceLocator, andre@0: void *pwArg, andre@0: CERTOCSPRequest **pRequest) andre@0: { andre@0: CERTOCSPRequest *request; andre@0: request = cert_CreateSingleCertOCSPRequest(certID, singleCert, time, andre@0: addServiceLocator, NULL); andre@0: if (!request) andre@0: return NULL; andre@0: return ocsp_GetEncodedOCSPResponseFromRequest(arena, request, location, andre@0: method, time, addServiceLocator, andre@0: pwArg, pRequest); andre@0: } andre@0: andre@0: /* Checks a certificate for the key usage extension of OCSP signer. */ andre@0: static PRBool andre@0: ocsp_CertIsOCSPDesignatedResponder(CERTCertificate *cert) andre@0: { andre@0: SECStatus rv; andre@0: SECItem extItem; andre@0: SECItem **oids; andre@0: SECItem *oid; andre@0: SECOidTag oidTag; andre@0: PRBool retval; andre@0: CERTOidSequence *oidSeq = NULL; andre@0: andre@0: andre@0: extItem.data = NULL; andre@0: rv = CERT_FindCertExtension(cert, SEC_OID_X509_EXT_KEY_USAGE, &extItem); andre@0: if ( rv != SECSuccess ) { andre@0: goto loser; andre@0: } andre@0: andre@0: oidSeq = CERT_DecodeOidSequence(&extItem); andre@0: if ( oidSeq == NULL ) { andre@0: goto loser; andre@0: } andre@0: andre@0: oids = oidSeq->oids; andre@0: while ( *oids != NULL ) { andre@0: oid = *oids; andre@0: andre@0: oidTag = SECOID_FindOIDTag(oid); andre@0: andre@0: if ( oidTag == SEC_OID_OCSP_RESPONDER ) { andre@0: goto success; andre@0: } andre@0: andre@0: oids++; andre@0: } andre@0: andre@0: loser: andre@0: retval = PR_FALSE; andre@0: PORT_SetError(SEC_ERROR_OCSP_INVALID_SIGNING_CERT); andre@0: goto done; andre@0: success: andre@0: retval = PR_TRUE; andre@0: done: andre@0: if ( extItem.data != NULL ) { andre@0: PORT_Free(extItem.data); andre@0: } andre@0: if ( oidSeq != NULL ) { andre@0: CERT_DestroyOidSequence(oidSeq); andre@0: } andre@0: andre@0: return(retval); andre@0: } andre@0: andre@0: andre@0: #ifdef LATER /* andre@0: * XXX This function is not currently used, but will andre@0: * be needed later when we do revocation checking of andre@0: * the responder certificate. Of course, it may need andre@0: * revising then, if the cert extension interface has andre@0: * changed. (Hopefully it will!) andre@0: */ andre@0: andre@0: /* Checks a certificate to see if it has the OCSP no check extension. */ andre@0: static PRBool andre@0: ocsp_CertHasNoCheckExtension(CERTCertificate *cert) andre@0: { andre@0: SECStatus rv; andre@0: andre@0: rv = CERT_FindCertExtension(cert, SEC_OID_PKIX_OCSP_NO_CHECK, andre@0: NULL); andre@0: if (rv == SECSuccess) { andre@0: return PR_TRUE; andre@0: } andre@0: return PR_FALSE; andre@0: } andre@0: #endif /* LATER */ andre@0: andre@0: static PRBool andre@0: ocsp_matchcert(SECItem *certIndex,CERTCertificate *testCert) andre@0: { andre@0: SECItem item; andre@0: unsigned char buf[HASH_LENGTH_MAX]; andre@0: andre@0: item.data = buf; andre@0: item.len = SHA1_LENGTH; andre@0: andre@0: if (CERT_GetSubjectPublicKeyDigest(NULL,testCert,SEC_OID_SHA1, andre@0: &item) == NULL) { andre@0: return PR_FALSE; andre@0: } andre@0: if (SECITEM_ItemsAreEqual(certIndex,&item)) { andre@0: return PR_TRUE; andre@0: } andre@0: if (CERT_GetSubjectPublicKeyDigest(NULL,testCert,SEC_OID_MD5, andre@0: &item) == NULL) { andre@0: return PR_FALSE; andre@0: } andre@0: if (SECITEM_ItemsAreEqual(certIndex,&item)) { andre@0: return PR_TRUE; andre@0: } andre@0: if (CERT_GetSubjectPublicKeyDigest(NULL,testCert,SEC_OID_MD2, andre@0: &item) == NULL) { andre@0: return PR_FALSE; andre@0: } andre@0: if (SECITEM_ItemsAreEqual(certIndex,&item)) { andre@0: return PR_TRUE; andre@0: } andre@0: andre@0: return PR_FALSE; andre@0: } andre@0: andre@0: static CERTCertificate * andre@0: ocsp_CertGetDefaultResponder(CERTCertDBHandle *handle,CERTOCSPCertID *certID); andre@0: andre@0: CERTCertificate * andre@0: ocsp_GetSignerCertificate(CERTCertDBHandle *handle, ocspResponseData *tbsData, andre@0: ocspSignature *signature, CERTCertificate *issuer) andre@0: { andre@0: CERTCertificate **certs = NULL; andre@0: CERTCertificate *signerCert = NULL; andre@0: SECStatus rv = SECFailure; andre@0: PRBool lookupByName = PR_TRUE; andre@0: void *certIndex = NULL; andre@0: int certCount = 0; andre@0: andre@0: PORT_Assert(tbsData->responderID != NULL); andre@0: switch (tbsData->responderID->responderIDType) { andre@0: case ocspResponderID_byName: andre@0: lookupByName = PR_TRUE; andre@0: certIndex = &tbsData->derResponderID; andre@0: break; andre@0: case ocspResponderID_byKey: andre@0: lookupByName = PR_FALSE; andre@0: certIndex = &tbsData->responderID->responderIDValue.keyHash; andre@0: break; andre@0: case ocspResponderID_other: andre@0: default: andre@0: PORT_Assert(0); andre@0: PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); andre@0: return NULL; andre@0: } andre@0: andre@0: /* andre@0: * If the signature contains some certificates as well, temporarily andre@0: * import them in case they are needed for verification. andre@0: * andre@0: * Note that the result of this is that each cert in "certs" needs andre@0: * to be destroyed. andre@0: */ andre@0: if (signature->derCerts != NULL) { andre@0: for (; signature->derCerts[certCount] != NULL; certCount++) { andre@0: /* just counting */ andre@0: } andre@0: rv = CERT_ImportCerts(handle, certUsageStatusResponder, certCount, andre@0: signature->derCerts, &certs, andre@0: PR_FALSE, PR_FALSE, NULL); andre@0: if (rv != SECSuccess) andre@0: goto finish; andre@0: } andre@0: andre@0: /* andre@0: * Now look up the certificate that did the signing. andre@0: * The signer can be specified either by name or by key hash. andre@0: */ andre@0: if (lookupByName) { andre@0: SECItem *crIndex = (SECItem*)certIndex; andre@0: SECItem encodedName; andre@0: PLArenaPool *arena; andre@0: andre@0: arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); andre@0: if (arena != NULL) { andre@0: andre@0: rv = SEC_QuickDERDecodeItem(arena, &encodedName, andre@0: ocsp_ResponderIDDerNameTemplate, andre@0: crIndex); andre@0: if (rv != SECSuccess) { andre@0: if (PORT_GetError() == SEC_ERROR_BAD_DER) andre@0: PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); andre@0: } else { andre@0: signerCert = CERT_FindCertByName(handle, &encodedName); andre@0: } andre@0: PORT_FreeArena(arena, PR_FALSE); andre@0: } andre@0: } else { andre@0: /* andre@0: * The signer is either 1) a known issuer CA we passed in, andre@0: * 2) the default OCSP responder, or 3) an intermediate CA andre@0: * passed in the cert list to use. Figure out which it is. andre@0: */ andre@0: int i; andre@0: CERTCertificate *responder = andre@0: ocsp_CertGetDefaultResponder(handle, NULL); andre@0: if (responder && ocsp_matchcert(certIndex,responder)) { andre@0: signerCert = CERT_DupCertificate(responder); andre@0: } else if (issuer && ocsp_matchcert(certIndex,issuer)) { andre@0: signerCert = CERT_DupCertificate(issuer); andre@0: } andre@0: for (i=0; (signerCert == NULL) && (i < certCount); i++) { andre@0: if (ocsp_matchcert(certIndex,certs[i])) { andre@0: signerCert = CERT_DupCertificate(certs[i]); andre@0: } andre@0: } andre@0: if (signerCert == NULL) { andre@0: PORT_SetError(SEC_ERROR_UNKNOWN_CERT); andre@0: } andre@0: } andre@0: andre@0: finish: andre@0: if (certs != NULL) { andre@0: CERT_DestroyCertArray(certs, certCount); andre@0: } andre@0: andre@0: return signerCert; andre@0: } andre@0: andre@0: SECStatus andre@0: ocsp_VerifyResponseSignature(CERTCertificate *signerCert, andre@0: ocspSignature *signature, andre@0: SECItem *tbsResponseDataDER, andre@0: void *pwArg) andre@0: { andre@0: SECKEYPublicKey *signerKey = NULL; andre@0: SECStatus rv = SECFailure; andre@0: CERTSignedData signedData; andre@0: andre@0: /* andre@0: * Now get the public key from the signer's certificate; we need andre@0: * it to perform the verification. andre@0: */ andre@0: signerKey = CERT_ExtractPublicKey(signerCert); andre@0: if (signerKey == NULL) { andre@0: return SECFailure; andre@0: } andre@0: andre@0: /* andre@0: * We copy the signature data *pointer* and length, so that we can andre@0: * modify the length without damaging the original copy. This is a andre@0: * simple copy, not a dup, so no destroy/free is necessary. andre@0: */ andre@0: signedData.signature = signature->signature; andre@0: signedData.signatureAlgorithm = signature->signatureAlgorithm; andre@0: signedData.data = *tbsResponseDataDER; andre@0: andre@0: rv = CERT_VerifySignedDataWithPublicKey(&signedData, signerKey, pwArg); andre@0: if (rv != SECSuccess && andre@0: (PORT_GetError() == SEC_ERROR_BAD_SIGNATURE || andre@0: PORT_GetError() == SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED)) { andre@0: PORT_SetError(SEC_ERROR_OCSP_BAD_SIGNATURE); andre@0: } andre@0: andre@0: if (signerKey != NULL) { andre@0: SECKEY_DestroyPublicKey(signerKey); andre@0: } andre@0: andre@0: return rv; andre@0: } andre@0: andre@0: andre@0: /* andre@0: * FUNCTION: CERT_VerifyOCSPResponseSignature andre@0: * Check the signature on an OCSP Response. Will also perform a andre@0: * verification of the signer's certificate. Note, however, that a andre@0: * successful verification does not make any statement about the andre@0: * signer's *authority* to provide status for the certificate(s), andre@0: * that must be checked individually for each certificate. andre@0: * INPUTS: andre@0: * CERTOCSPResponse *response andre@0: * Pointer to response structure with signature to be checked. andre@0: * CERTCertDBHandle *handle andre@0: * Pointer to CERTCertDBHandle for certificate DB to use for verification. andre@0: * void *pwArg andre@0: * Pointer to argument for password prompting, if needed. andre@0: * OUTPUTS: andre@0: * CERTCertificate **pSignerCert andre@0: * Pointer in which to store signer's certificate; only filled-in if andre@0: * non-null. andre@0: * RETURN: andre@0: * Returns SECSuccess when signature is valid, anything else means invalid. andre@0: * Possible errors set: andre@0: * SEC_ERROR_OCSP_MALFORMED_RESPONSE - unknown type of ResponderID andre@0: * SEC_ERROR_INVALID_TIME - bad format of "ProducedAt" time andre@0: * SEC_ERROR_UNKNOWN_SIGNER - signer's cert could not be found andre@0: * SEC_ERROR_BAD_SIGNATURE - the signature did not verify andre@0: * Other errors are any of the many possible failures in cert verification andre@0: * (e.g. SEC_ERROR_REVOKED_CERTIFICATE, SEC_ERROR_UNTRUSTED_ISSUER) when andre@0: * verifying the signer's cert, or low-level problems (no memory, etc.) andre@0: */ andre@0: SECStatus andre@0: CERT_VerifyOCSPResponseSignature(CERTOCSPResponse *response, andre@0: CERTCertDBHandle *handle, void *pwArg, andre@0: CERTCertificate **pSignerCert, andre@0: CERTCertificate *issuer) andre@0: { andre@0: SECItem *tbsResponseDataDER; andre@0: CERTCertificate *signerCert = NULL; andre@0: SECStatus rv = SECFailure; andre@0: PRTime producedAt; andre@0: andre@0: /* ocsp_DecodeBasicOCSPResponse will fail if asn1 decoder is unable andre@0: * to properly decode tbsData (see the function and andre@0: * ocsp_BasicOCSPResponseTemplate). Thus, tbsData can not be andre@0: * equal to null */ andre@0: ocspResponseData *tbsData = ocsp_GetResponseData(response, andre@0: &tbsResponseDataDER); andre@0: ocspSignature *signature = ocsp_GetResponseSignature(response); andre@0: andre@0: if (!signature) { andre@0: PORT_SetError(SEC_ERROR_OCSP_BAD_SIGNATURE); andre@0: return SECFailure; andre@0: } andre@0: andre@0: /* andre@0: * If this signature has already gone through verification, just andre@0: * return the cached result. andre@0: */ andre@0: if (signature->wasChecked) { andre@0: if (signature->status == SECSuccess) { andre@0: if (pSignerCert != NULL) andre@0: *pSignerCert = CERT_DupCertificate(signature->cert); andre@0: } else { andre@0: PORT_SetError(signature->failureReason); andre@0: } andre@0: return signature->status; andre@0: } andre@0: andre@0: signerCert = ocsp_GetSignerCertificate(handle, tbsData, andre@0: signature, issuer); andre@0: if (signerCert == NULL) { andre@0: rv = SECFailure; andre@0: if (PORT_GetError() == SEC_ERROR_UNKNOWN_CERT) { andre@0: /* Make the error a little more specific. */ andre@0: PORT_SetError(SEC_ERROR_OCSP_INVALID_SIGNING_CERT); andre@0: } andre@0: goto finish; andre@0: } andre@0: andre@0: /* andre@0: * We could mark this true at the top of this function, or always andre@0: * below at "finish", but if the problem was just that we could not andre@0: * find the signer's cert, leave that as if the signature hasn't andre@0: * been checked in case a subsequent call might have better luck. andre@0: */ andre@0: signature->wasChecked = PR_TRUE; andre@0: andre@0: /* andre@0: * The function will also verify the signer certificate; we andre@0: * need to tell it *when* that certificate must be valid -- for our andre@0: * purposes we expect it to be valid when the response was signed. andre@0: * The value of "producedAt" is the signing time. andre@0: */ andre@0: rv = DER_GeneralizedTimeToTime(&producedAt, &tbsData->producedAt); andre@0: if (rv != SECSuccess) andre@0: goto finish; andre@0: andre@0: /* andre@0: * Just because we have a cert does not mean it is any good; check andre@0: * it for validity, trust and usage. andre@0: */ andre@0: if (ocsp_CertIsOCSPDefaultResponder(handle, signerCert)) { andre@0: rv = SECSuccess; andre@0: } else { andre@0: SECCertUsage certUsage; andre@0: if (CERT_IsCACert(signerCert, NULL)) { andre@0: certUsage = certUsageAnyCA; andre@0: } else { andre@0: certUsage = certUsageStatusResponder; andre@0: } andre@0: rv = cert_VerifyCertWithFlags(handle, signerCert, PR_TRUE, certUsage, andre@0: producedAt, CERT_VERIFYCERT_SKIP_OCSP, andre@0: pwArg, NULL); andre@0: if (rv != SECSuccess) { andre@0: PORT_SetError(SEC_ERROR_OCSP_INVALID_SIGNING_CERT); andre@0: goto finish; andre@0: } andre@0: } andre@0: andre@0: rv = ocsp_VerifyResponseSignature(signerCert, signature, andre@0: tbsResponseDataDER, andre@0: pwArg); andre@0: andre@0: finish: andre@0: if (signature->wasChecked) andre@0: signature->status = rv; andre@0: andre@0: if (rv != SECSuccess) { andre@0: signature->failureReason = PORT_GetError(); andre@0: if (signerCert != NULL) andre@0: CERT_DestroyCertificate(signerCert); andre@0: } else { andre@0: /* andre@0: * Save signer's certificate in signature. andre@0: */ andre@0: signature->cert = signerCert; andre@0: if (pSignerCert != NULL) { andre@0: /* andre@0: * Pass pointer to signer's certificate back to our caller, andre@0: * who is also now responsible for destroying it. andre@0: */ andre@0: *pSignerCert = CERT_DupCertificate(signerCert); andre@0: } andre@0: } andre@0: andre@0: return rv; andre@0: } andre@0: andre@0: /* andre@0: * See if the request's certID and the single response's certID match. andre@0: * This can be easy or difficult, depending on whether the same hash andre@0: * algorithm was used. andre@0: */ andre@0: static PRBool andre@0: ocsp_CertIDsMatch(CERTOCSPCertID *requestCertID, andre@0: CERTOCSPCertID *responseCertID) andre@0: { andre@0: PRBool match = PR_FALSE; andre@0: SECOidTag hashAlg; andre@0: SECItem *keyHash = NULL; andre@0: SECItem *nameHash = NULL; andre@0: andre@0: /* andre@0: * In order to match, they must have the same issuer and the same andre@0: * serial number. andre@0: * andre@0: * We just compare the easier things first. andre@0: */ andre@0: if (SECITEM_CompareItem(&requestCertID->serialNumber, andre@0: &responseCertID->serialNumber) != SECEqual) { andre@0: goto done; andre@0: } andre@0: andre@0: /* andre@0: * Make sure the "parameters" are not too bogus. Since we encoded andre@0: * requestCertID->hashAlgorithm, we don't need to check it. andre@0: */ andre@0: if (responseCertID->hashAlgorithm.parameters.len > 2) { andre@0: goto done; andre@0: } andre@0: if (SECITEM_CompareItem(&requestCertID->hashAlgorithm.algorithm, andre@0: &responseCertID->hashAlgorithm.algorithm) == SECEqual) { andre@0: /* andre@0: * If the hash algorithms match then we can do a simple compare andre@0: * of the hash values themselves. andre@0: */ andre@0: if ((SECITEM_CompareItem(&requestCertID->issuerNameHash, andre@0: &responseCertID->issuerNameHash) == SECEqual) andre@0: && (SECITEM_CompareItem(&requestCertID->issuerKeyHash, andre@0: &responseCertID->issuerKeyHash) == SECEqual)) { andre@0: match = PR_TRUE; andre@0: } andre@0: goto done; andre@0: } andre@0: andre@0: hashAlg = SECOID_FindOIDTag(&responseCertID->hashAlgorithm.algorithm); andre@0: switch (hashAlg) { andre@0: case SEC_OID_SHA1: andre@0: keyHash = &requestCertID->issuerSHA1KeyHash; andre@0: nameHash = &requestCertID->issuerSHA1NameHash; andre@0: break; andre@0: case SEC_OID_MD5: andre@0: keyHash = &requestCertID->issuerMD5KeyHash; andre@0: nameHash = &requestCertID->issuerMD5NameHash; andre@0: break; andre@0: case SEC_OID_MD2: andre@0: keyHash = &requestCertID->issuerMD2KeyHash; andre@0: nameHash = &requestCertID->issuerMD2NameHash; andre@0: break; andre@0: default: andre@0: PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); andre@0: return PR_FALSE; andre@0: } andre@0: andre@0: if ((keyHash != NULL) andre@0: && (SECITEM_CompareItem(nameHash, andre@0: &responseCertID->issuerNameHash) == SECEqual) andre@0: && (SECITEM_CompareItem(keyHash, andre@0: &responseCertID->issuerKeyHash) == SECEqual)) { andre@0: match = PR_TRUE; andre@0: } andre@0: andre@0: done: andre@0: return match; andre@0: } andre@0: andre@0: /* andre@0: * Find the single response for the cert specified by certID. andre@0: * No copying is done; this just returns a pointer to the appropriate andre@0: * response within responses, if it is found (and null otherwise). andre@0: * This is fine, of course, since this function is internal-use only. andre@0: */ andre@0: static CERTOCSPSingleResponse * andre@0: ocsp_GetSingleResponseForCertID(CERTOCSPSingleResponse **responses, andre@0: CERTCertDBHandle *handle, andre@0: CERTOCSPCertID *certID) andre@0: { andre@0: CERTOCSPSingleResponse *single; andre@0: int i; andre@0: andre@0: if (responses == NULL) andre@0: return NULL; andre@0: andre@0: for (i = 0; responses[i] != NULL; i++) { andre@0: single = responses[i]; andre@0: if (ocsp_CertIDsMatch(certID, single->certID)) { andre@0: return single; andre@0: } andre@0: } andre@0: andre@0: /* andre@0: * The OCSP server should have included a response even if it knew andre@0: * nothing about the certificate in question. Since it did not, andre@0: * this will make it look as if it had. andre@0: * andre@0: * XXX Should we make this a separate error to notice the server's andre@0: * bad behavior? andre@0: */ andre@0: PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_CERT); andre@0: return NULL; andre@0: } andre@0: andre@0: static ocspCheckingContext * andre@0: ocsp_GetCheckingContext(CERTCertDBHandle *handle) andre@0: { andre@0: CERTStatusConfig *statusConfig; andre@0: ocspCheckingContext *ocspcx = NULL; andre@0: andre@0: statusConfig = CERT_GetStatusConfig(handle); andre@0: if (statusConfig != NULL) { andre@0: ocspcx = statusConfig->statusContext; andre@0: andre@0: /* andre@0: * This is actually an internal error, because we should never andre@0: * have a good statusConfig without a good statusContext, too. andre@0: * For lack of anything better, though, we just assert and use andre@0: * the same error as if there were no statusConfig (set below). andre@0: */ andre@0: PORT_Assert(ocspcx != NULL); andre@0: } andre@0: andre@0: if (ocspcx == NULL) andre@0: PORT_SetError(SEC_ERROR_OCSP_NOT_ENABLED); andre@0: andre@0: return ocspcx; andre@0: } andre@0: andre@0: /* andre@0: * Return cert reference if the given signerCert is the default responder for andre@0: * the given certID. If not, or if any error, return NULL. andre@0: */ andre@0: static CERTCertificate * andre@0: ocsp_CertGetDefaultResponder(CERTCertDBHandle *handle, CERTOCSPCertID *certID) andre@0: { andre@0: ocspCheckingContext *ocspcx; andre@0: andre@0: ocspcx = ocsp_GetCheckingContext(handle); andre@0: if (ocspcx == NULL) andre@0: goto loser; andre@0: andre@0: /* andre@0: * Right now we have only one default responder. It applies to andre@0: * all certs when it is used, so the check is simple and certID andre@0: * has no bearing on the answer. Someday in the future we may andre@0: * allow configuration of different responders for different andre@0: * issuers, and then we would have to use the issuer specified andre@0: * in certID to determine if signerCert is the right one. andre@0: */ andre@0: if (ocspcx->useDefaultResponder) { andre@0: PORT_Assert(ocspcx->defaultResponderCert != NULL); andre@0: return ocspcx->defaultResponderCert; andre@0: } andre@0: andre@0: loser: andre@0: return NULL; andre@0: } andre@0: andre@0: /* andre@0: * Return true if the cert is one of the default responders configured for andre@0: * ocsp context. If not, or if any error, return false. andre@0: */ andre@0: PRBool andre@0: ocsp_CertIsOCSPDefaultResponder(CERTCertDBHandle *handle, CERTCertificate *cert) andre@0: { andre@0: ocspCheckingContext *ocspcx; andre@0: andre@0: ocspcx = ocsp_GetCheckingContext(handle); andre@0: if (ocspcx == NULL) andre@0: return PR_FALSE; andre@0: andre@0: /* andre@0: * Right now we have only one default responder. It applies to andre@0: * all certs when it is used, so the check is simple and certID andre@0: * has no bearing on the answer. Someday in the future we may andre@0: * allow configuration of different responders for different andre@0: * issuers, and then we would have to use the issuer specified andre@0: * in certID to determine if signerCert is the right one. andre@0: */ andre@0: if (ocspcx->useDefaultResponder && andre@0: CERT_CompareCerts(ocspcx->defaultResponderCert, cert)) { andre@0: return PR_TRUE; andre@0: } andre@0: andre@0: return PR_FALSE; andre@0: } andre@0: andre@0: /* andre@0: * Check that the given signer certificate is authorized to sign status andre@0: * information for the given certID. Return true if it is, false if not andre@0: * (or if there is any error along the way). If false is returned because andre@0: * the signer is not authorized, the following error will be set: andre@0: * SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE andre@0: * Other errors are low-level problems (no memory, bad database, etc.). andre@0: * andre@0: * There are three ways to be authorized. In the order in which we check, andre@0: * using the terms used in the OCSP spec, the signer must be one of: andre@0: * 1. A "trusted responder" -- it matches a local configuration andre@0: * of OCSP signing authority for the certificate in question. andre@0: * 2. The CA who issued the certificate in question. andre@0: * 3. A "CA designated responder", aka an "authorized responder" -- it andre@0: * must be represented by a special cert issued by the CA who issued andre@0: * the certificate in question. andre@0: */ andre@0: static PRBool andre@0: ocsp_AuthorizedResponderForCertID(CERTCertDBHandle *handle, andre@0: CERTCertificate *signerCert, andre@0: CERTOCSPCertID *certID, andre@0: PRTime thisUpdate) andre@0: { andre@0: CERTCertificate *issuerCert = NULL, *defRespCert; andre@0: SECItem *keyHash = NULL; andre@0: SECItem *nameHash = NULL; andre@0: SECOidTag hashAlg; andre@0: PRBool keyHashEQ = PR_FALSE, nameHashEQ = PR_FALSE; andre@0: andre@0: /* andre@0: * Check first for a trusted responder, which overrides everything else. andre@0: */ andre@0: if ((defRespCert = ocsp_CertGetDefaultResponder(handle, certID)) && andre@0: CERT_CompareCerts(defRespCert, signerCert)) { andre@0: return PR_TRUE; andre@0: } andre@0: andre@0: /* andre@0: * In the other two cases, we need to do an issuer comparison. andre@0: * How we do it depends on whether the signer certificate has the andre@0: * special extension (for a designated responder) or not. andre@0: * andre@0: * First, lets check if signer of the response is the actual issuer andre@0: * of the cert. For that we will use signer cert key hash and cert subj andre@0: * name hash and will compare them with already calculated issuer key andre@0: * hash and issuer name hash. The hash algorithm is picked from response andre@0: * certID hash to avoid second hash calculation. andre@0: */ andre@0: andre@0: hashAlg = SECOID_FindOIDTag(&certID->hashAlgorithm.algorithm); andre@0: andre@0: keyHash = CERT_GetSubjectPublicKeyDigest(NULL, signerCert, hashAlg, NULL); andre@0: if (keyHash != NULL) { andre@0: andre@0: keyHashEQ = andre@0: (SECITEM_CompareItem(keyHash, andre@0: &certID->issuerKeyHash) == SECEqual); andre@0: SECITEM_FreeItem(keyHash, PR_TRUE); andre@0: } andre@0: if (keyHashEQ && andre@0: (nameHash = CERT_GetSubjectNameDigest(NULL, signerCert, andre@0: hashAlg, NULL))) { andre@0: nameHashEQ = andre@0: (SECITEM_CompareItem(nameHash, andre@0: &certID->issuerNameHash) == SECEqual); andre@0: andre@0: SECITEM_FreeItem(nameHash, PR_TRUE); andre@0: if (nameHashEQ) { andre@0: /* The issuer of the cert is the the signer of the response */ andre@0: return PR_TRUE; andre@0: } andre@0: } andre@0: andre@0: andre@0: keyHashEQ = PR_FALSE; andre@0: nameHashEQ = PR_FALSE; andre@0: andre@0: if (!ocsp_CertIsOCSPDesignatedResponder(signerCert)) { andre@0: PORT_SetError(SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE); andre@0: return PR_FALSE; andre@0: } andre@0: andre@0: /* andre@0: * The signer is a designated responder. Its issuer must match andre@0: * the issuer of the cert being checked. andre@0: */ andre@0: issuerCert = CERT_FindCertIssuer(signerCert, thisUpdate, andre@0: certUsageAnyCA); andre@0: if (issuerCert == NULL) { andre@0: /* andre@0: * We could leave the SEC_ERROR_UNKNOWN_ISSUER error alone, andre@0: * but the following will give slightly more information. andre@0: * Once we have an error stack, things will be much better. andre@0: */ andre@0: PORT_SetError(SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE); andre@0: return PR_FALSE; andre@0: } andre@0: andre@0: keyHash = CERT_GetSubjectPublicKeyDigest(NULL, issuerCert, hashAlg, NULL); andre@0: nameHash = CERT_GetSubjectNameDigest(NULL, issuerCert, hashAlg, NULL); andre@0: andre@0: CERT_DestroyCertificate(issuerCert); andre@0: andre@0: if (keyHash != NULL && nameHash != NULL) { andre@0: keyHashEQ = andre@0: (SECITEM_CompareItem(keyHash, andre@0: &certID->issuerKeyHash) == SECEqual); andre@0: andre@0: nameHashEQ = andre@0: (SECITEM_CompareItem(nameHash, andre@0: &certID->issuerNameHash) == SECEqual); andre@0: } andre@0: andre@0: if (keyHash) { andre@0: SECITEM_FreeItem(keyHash, PR_TRUE); andre@0: } andre@0: if (nameHash) { andre@0: SECITEM_FreeItem(nameHash, PR_TRUE); andre@0: } andre@0: andre@0: if (keyHashEQ && nameHashEQ) { andre@0: return PR_TRUE; andre@0: } andre@0: andre@0: PORT_SetError(SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE); andre@0: return PR_FALSE; andre@0: } andre@0: andre@0: /* andre@0: * We need to check that a responder gives us "recent" information. andre@0: * Since a responder can pre-package responses, we need to pick an amount andre@0: * of time that is acceptable to us, and reject any response that is andre@0: * older than that. andre@0: * andre@0: * XXX This *should* be based on some configuration parameter, so that andre@0: * different usages could specify exactly what constitutes "sufficiently andre@0: * recent". But that is not going to happen right away. For now, we andre@0: * want something from within the last 24 hours. This macro defines that andre@0: * number in seconds. andre@0: */ andre@0: #define OCSP_ALLOWABLE_LAPSE_SECONDS (24L * 60L * 60L) andre@0: andre@0: static PRBool andre@0: ocsp_TimeIsRecent(PRTime checkTime) andre@0: { andre@0: PRTime now = PR_Now(); andre@0: PRTime lapse, tmp; andre@0: andre@0: LL_I2L(lapse, OCSP_ALLOWABLE_LAPSE_SECONDS); andre@0: LL_I2L(tmp, PR_USEC_PER_SEC); andre@0: LL_MUL(lapse, lapse, tmp); /* allowable lapse in microseconds */ andre@0: andre@0: LL_ADD(checkTime, checkTime, lapse); andre@0: if (LL_CMP(now, >, checkTime)) andre@0: return PR_FALSE; andre@0: andre@0: return PR_TRUE; andre@0: } andre@0: andre@0: #define OCSP_SLOP (5L*60L) /* OCSP responses are allowed to be 5 minutes andre@0: in the future by default */ andre@0: andre@0: static PRUint32 ocspsloptime = OCSP_SLOP; /* seconds */ andre@0: andre@0: /* andre@0: * If an old response contains the revoked certificate status, we want andre@0: * to return SECSuccess so the response will be used. andre@0: */ andre@0: static SECStatus andre@0: ocsp_HandleOldSingleResponse(CERTOCSPSingleResponse *single, PRTime time) andre@0: { andre@0: SECStatus rv; andre@0: ocspCertStatus *status = single->certStatus; andre@0: if (status->certStatusType == ocspCertStatus_revoked) { andre@0: rv = ocsp_CertRevokedAfter(status->certStatusInfo.revokedInfo, time); andre@0: if (rv != SECSuccess && andre@0: PORT_GetError() == SEC_ERROR_REVOKED_CERTIFICATE) { andre@0: /* andre@0: * Return SECSuccess now. The subsequent ocsp_CertRevokedAfter andre@0: * call in ocsp_CertHasGoodStatus will cause andre@0: * ocsp_CertHasGoodStatus to fail with andre@0: * SEC_ERROR_REVOKED_CERTIFICATE. andre@0: */ andre@0: return SECSuccess; andre@0: } andre@0: andre@0: } andre@0: PORT_SetError(SEC_ERROR_OCSP_OLD_RESPONSE); andre@0: return SECFailure; andre@0: } andre@0: andre@0: /* andre@0: * Check that this single response is okay. A return of SECSuccess means: andre@0: * 1. The signer (represented by "signerCert") is authorized to give status andre@0: * for the cert represented by the individual response in "single". andre@0: * 2. The value of thisUpdate is earlier than now. andre@0: * 3. The value of producedAt is later than or the same as thisUpdate. andre@0: * 4. If nextUpdate is given: andre@0: * - The value of nextUpdate is later than now. andre@0: * - The value of producedAt is earlier than nextUpdate. andre@0: * Else if no nextUpdate: andre@0: * - The value of thisUpdate is fairly recent. andre@0: * - The value of producedAt is fairly recent. andre@0: * However we do not need to perform an explicit check for this last andre@0: * constraint because it is already guaranteed by checking that andre@0: * producedAt is later than thisUpdate and thisUpdate is recent. andre@0: * Oh, and any responder is "authorized" to say that a cert is unknown to it. andre@0: * andre@0: * If any of those checks fail, SECFailure is returned and an error is set: andre@0: * SEC_ERROR_OCSP_FUTURE_RESPONSE andre@0: * SEC_ERROR_OCSP_OLD_RESPONSE andre@0: * SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE andre@0: * Other errors are low-level problems (no memory, bad database, etc.). andre@0: */ andre@0: static SECStatus andre@0: ocsp_VerifySingleResponse(CERTOCSPSingleResponse *single, andre@0: CERTCertDBHandle *handle, andre@0: CERTCertificate *signerCert, andre@0: PRTime producedAt) andre@0: { andre@0: CERTOCSPCertID *certID = single->certID; andre@0: PRTime now, thisUpdate, nextUpdate, tmstamp, tmp; andre@0: SECStatus rv; andre@0: andre@0: OCSP_TRACE(("OCSP ocsp_VerifySingleResponse, nextUpdate: %d\n", andre@0: ((single->nextUpdate) != 0))); andre@0: /* andre@0: * If all the responder said was that the given cert was unknown to it, andre@0: * that is a valid response. Not very interesting to us, of course, andre@0: * but all this function is concerned with is validity of the response, andre@0: * not the status of the cert. andre@0: */ andre@0: PORT_Assert(single->certStatus != NULL); andre@0: if (single->certStatus->certStatusType == ocspCertStatus_unknown) andre@0: return SECSuccess; andre@0: andre@0: /* andre@0: * We need to extract "thisUpdate" for use below and to pass along andre@0: * to AuthorizedResponderForCertID in case it needs it for doing an andre@0: * issuer look-up. andre@0: */ andre@0: rv = DER_GeneralizedTimeToTime(&thisUpdate, &single->thisUpdate); andre@0: if (rv != SECSuccess) andre@0: return rv; andre@0: andre@0: /* andre@0: * First confirm that signerCert is authorized to give this status. andre@0: */ andre@0: if (ocsp_AuthorizedResponderForCertID(handle, signerCert, certID, andre@0: thisUpdate) != PR_TRUE) andre@0: return SECFailure; andre@0: andre@0: /* andre@0: * Now check the time stuff, as described above. andre@0: */ andre@0: now = PR_Now(); andre@0: /* allow slop time for future response */ andre@0: LL_UI2L(tmstamp, ocspsloptime); /* get slop time in seconds */ andre@0: LL_UI2L(tmp, PR_USEC_PER_SEC); andre@0: LL_MUL(tmp, tmstamp, tmp); /* convert the slop time to PRTime */ andre@0: LL_ADD(tmstamp, tmp, now); /* add current time to it */ andre@0: andre@0: if (LL_CMP(thisUpdate, >, tmstamp) || LL_CMP(producedAt, <, thisUpdate)) { andre@0: PORT_SetError(SEC_ERROR_OCSP_FUTURE_RESPONSE); andre@0: return SECFailure; andre@0: } andre@0: if (single->nextUpdate != NULL) { andre@0: rv = DER_GeneralizedTimeToTime(&nextUpdate, single->nextUpdate); andre@0: if (rv != SECSuccess) andre@0: return rv; andre@0: andre@0: LL_ADD(tmp, tmp, nextUpdate); andre@0: if (LL_CMP(tmp, <, now) || LL_CMP(producedAt, >, nextUpdate)) andre@0: return ocsp_HandleOldSingleResponse(single, now); andre@0: } else if (ocsp_TimeIsRecent(thisUpdate) != PR_TRUE) { andre@0: return ocsp_HandleOldSingleResponse(single, now); andre@0: } andre@0: andre@0: return SECSuccess; andre@0: } andre@0: andre@0: andre@0: /* andre@0: * FUNCTION: CERT_GetOCSPAuthorityInfoAccessLocation andre@0: * Get the value of the URI of the OCSP responder for the given cert. andre@0: * This is found in the (optional) Authority Information Access extension andre@0: * in the cert. andre@0: * INPUTS: andre@0: * CERTCertificate *cert andre@0: * The certificate being examined. andre@0: * RETURN: andre@0: * char * andre@0: * A copy of the URI for the OCSP method, if found. If either the andre@0: * extension is not present or it does not contain an entry for OCSP, andre@0: * SEC_ERROR_CERT_BAD_ACCESS_LOCATION will be set and a NULL returned. andre@0: * Any other error will also result in a NULL being returned. andre@0: * andre@0: * This result should be freed (via PORT_Free) when no longer in use. andre@0: */ andre@0: char * andre@0: CERT_GetOCSPAuthorityInfoAccessLocation(const CERTCertificate *cert) andre@0: { andre@0: CERTGeneralName *locname = NULL; andre@0: SECItem *location = NULL; andre@0: SECItem *encodedAuthInfoAccess = NULL; andre@0: CERTAuthInfoAccess **authInfoAccess = NULL; andre@0: char *locURI = NULL; andre@0: PLArenaPool *arena = NULL; andre@0: SECStatus rv; andre@0: int i; andre@0: andre@0: /* andre@0: * Allocate this one from the heap because it will get filled in andre@0: * by CERT_FindCertExtension which will also allocate from the heap, andre@0: * and we can free the entire thing on our way out. andre@0: */ andre@0: encodedAuthInfoAccess = SECITEM_AllocItem(NULL, NULL, 0); andre@0: if (encodedAuthInfoAccess == NULL) andre@0: goto loser; andre@0: andre@0: rv = CERT_FindCertExtension(cert, SEC_OID_X509_AUTH_INFO_ACCESS, andre@0: encodedAuthInfoAccess); andre@0: if (rv == SECFailure) { andre@0: PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION); andre@0: goto loser; andre@0: } andre@0: andre@0: /* andre@0: * The rest of the things allocated in the routine will come out of andre@0: * this arena, which is temporary just for us to decode and get at the andre@0: * AIA extension. The whole thing will be destroyed on our way out, andre@0: * after we have copied the location string (url) itself (if found). andre@0: */ andre@0: arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); andre@0: if (arena == NULL) andre@0: goto loser; andre@0: andre@0: authInfoAccess = CERT_DecodeAuthInfoAccessExtension(arena, andre@0: encodedAuthInfoAccess); andre@0: if (authInfoAccess == NULL) andre@0: goto loser; andre@0: andre@0: for (i = 0; authInfoAccess[i] != NULL; i++) { andre@0: if (SECOID_FindOIDTag(&authInfoAccess[i]->method) == SEC_OID_PKIX_OCSP) andre@0: locname = authInfoAccess[i]->location; andre@0: } andre@0: andre@0: /* andre@0: * If we found an AIA extension, but it did not include an OCSP method, andre@0: * that should look to our caller as if we did not find the extension andre@0: * at all, because it is only an OCSP method that we care about. andre@0: * So set the same error that would be set if the AIA extension was andre@0: * not there at all. andre@0: */ andre@0: if (locname == NULL) { andre@0: PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION); andre@0: goto loser; andre@0: } andre@0: andre@0: /* andre@0: * The following is just a pointer back into locname (i.e. not a copy); andre@0: * thus it should not be freed. andre@0: */ andre@0: location = CERT_GetGeneralNameByType(locname, certURI, PR_FALSE); andre@0: if (location == NULL) { andre@0: /* andre@0: * XXX Appears that CERT_GetGeneralNameByType does not set an andre@0: * error if there is no name by that type. For lack of anything andre@0: * better, act as if the extension was not found. In the future andre@0: * this should probably be something more like the extension was andre@0: * badly formed. andre@0: */ andre@0: PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION); andre@0: goto loser; andre@0: } andre@0: andre@0: /* andre@0: * That location is really a string, but it has a specified length andre@0: * without a null-terminator. We need a real string that does have andre@0: * a null-terminator, and we need a copy of it anyway to return to andre@0: * our caller -- so allocate and copy. andre@0: */ andre@0: locURI = PORT_Alloc(location->len + 1); andre@0: if (locURI == NULL) { andre@0: goto loser; andre@0: } andre@0: PORT_Memcpy(locURI, location->data, location->len); andre@0: locURI[location->len] = '\0'; andre@0: andre@0: loser: andre@0: if (arena != NULL) andre@0: PORT_FreeArena(arena, PR_FALSE); andre@0: andre@0: if (encodedAuthInfoAccess != NULL) andre@0: SECITEM_FreeItem(encodedAuthInfoAccess, PR_TRUE); andre@0: andre@0: return locURI; andre@0: } andre@0: andre@0: andre@0: /* andre@0: * Figure out where we should go to find out the status of the given cert andre@0: * via OCSP. If allowed to use a default responder uri and a default andre@0: * responder is set up, then that is our answer. andre@0: * If not, see if the certificate has an Authority Information Access (AIA) andre@0: * extension for OCSP, and return the value of that. Otherwise return NULL. andre@0: * We also let our caller know whether or not the responder chosen was andre@0: * a default responder or not through the output variable isDefault; andre@0: * its value has no meaning unless a good (non-null) value is returned andre@0: * for the location. andre@0: * andre@0: * The result needs to be freed (PORT_Free) when no longer in use. andre@0: */ andre@0: char * andre@0: ocsp_GetResponderLocation(CERTCertDBHandle *handle, CERTCertificate *cert, andre@0: PRBool canUseDefault, PRBool *isDefault) andre@0: { andre@0: ocspCheckingContext *ocspcx = NULL; andre@0: char *ocspUrl = NULL; andre@0: andre@0: if (canUseDefault) { andre@0: ocspcx = ocsp_GetCheckingContext(handle); andre@0: } andre@0: if (ocspcx != NULL && ocspcx->useDefaultResponder) { andre@0: /* andre@0: * A default responder wins out, if specified. andre@0: * XXX Someday this may be a more complicated determination based andre@0: * on the cert's issuer. (That is, we could have different default andre@0: * responders configured for different issuers.) andre@0: */ andre@0: PORT_Assert(ocspcx->defaultResponderURI != NULL); andre@0: *isDefault = PR_TRUE; andre@0: return (PORT_Strdup(ocspcx->defaultResponderURI)); andre@0: } andre@0: andre@0: /* andre@0: * No default responder set up, so go see if we can find an AIA andre@0: * extension that has a value for OCSP, and get the url from that. andre@0: */ andre@0: *isDefault = PR_FALSE; andre@0: ocspUrl = CERT_GetOCSPAuthorityInfoAccessLocation(cert); andre@0: if (!ocspUrl) { andre@0: CERT_StringFromCertFcn altFcn; andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: altFcn = OCSP_Global.alternateOCSPAIAFcn; andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: if (altFcn) { andre@0: ocspUrl = (*altFcn)(cert); andre@0: if (ocspUrl) andre@0: *isDefault = PR_TRUE; andre@0: } andre@0: } andre@0: return ocspUrl; andre@0: } andre@0: andre@0: /* andre@0: * Return SECSuccess if the cert was revoked *after* "time", andre@0: * SECFailure otherwise. andre@0: */ andre@0: static SECStatus andre@0: ocsp_CertRevokedAfter(ocspRevokedInfo *revokedInfo, PRTime time) andre@0: { andre@0: PRTime revokedTime; andre@0: SECStatus rv; andre@0: andre@0: rv = DER_GeneralizedTimeToTime(&revokedTime, &revokedInfo->revocationTime); andre@0: if (rv != SECSuccess) andre@0: return rv; andre@0: andre@0: /* andre@0: * Set the error even if we will return success; someone might care. andre@0: */ andre@0: PORT_SetError(SEC_ERROR_REVOKED_CERTIFICATE); andre@0: andre@0: if (LL_CMP(revokedTime, >, time)) andre@0: return SECSuccess; andre@0: andre@0: return SECFailure; andre@0: } andre@0: andre@0: /* andre@0: * See if the cert represented in the single response had a good status andre@0: * at the specified time. andre@0: */ andre@0: SECStatus andre@0: ocsp_CertHasGoodStatus(ocspCertStatus *status, PRTime time) andre@0: { andre@0: SECStatus rv; andre@0: switch (status->certStatusType) { andre@0: case ocspCertStatus_good: andre@0: rv = SECSuccess; andre@0: break; andre@0: case ocspCertStatus_revoked: andre@0: rv = ocsp_CertRevokedAfter(status->certStatusInfo.revokedInfo, time); andre@0: break; andre@0: case ocspCertStatus_unknown: andre@0: PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_CERT); andre@0: rv = SECFailure; andre@0: break; andre@0: case ocspCertStatus_other: andre@0: default: andre@0: PORT_Assert(0); andre@0: PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); andre@0: rv = SECFailure; andre@0: break; andre@0: } andre@0: return rv; andre@0: } andre@0: andre@0: static SECStatus andre@0: ocsp_SingleResponseCertHasGoodStatus(CERTOCSPSingleResponse *single, andre@0: PRTime time) andre@0: { andre@0: return ocsp_CertHasGoodStatus(single->certStatus, time); andre@0: } andre@0: andre@0: /* SECFailure means the arguments were invalid. andre@0: * On SECSuccess, the out parameters contain the OCSP status. andre@0: * rvOcsp contains the overall result of the OCSP operation. andre@0: * Depending on input parameter ignoreGlobalOcspFailureSetting, andre@0: * a soft failure might be converted into *rvOcsp=SECSuccess. andre@0: * If the cached attempt to obtain OCSP information had resulted andre@0: * in a failure, missingResponseError shows the error code of andre@0: * that failure. andre@0: * cacheFreshness is ocspMissing if no entry was found, andre@0: * ocspFresh if a fresh entry was found, or andre@0: * ocspStale if a stale entry was found. andre@0: */ andre@0: SECStatus andre@0: ocsp_GetCachedOCSPResponseStatus(CERTOCSPCertID *certID, andre@0: PRTime time, andre@0: PRBool ignoreGlobalOcspFailureSetting, andre@0: SECStatus *rvOcsp, andre@0: SECErrorCodes *missingResponseError, andre@0: OCSPFreshness *cacheFreshness) andre@0: { andre@0: OCSPCacheItem *cacheItem = NULL; andre@0: andre@0: if (!certID || !missingResponseError || !rvOcsp || !cacheFreshness) { andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: return SECFailure; andre@0: } andre@0: *rvOcsp = SECFailure; andre@0: *missingResponseError = 0; andre@0: *cacheFreshness = ocspMissing; andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: cacheItem = ocsp_FindCacheEntry(&OCSP_Global.cache, certID); andre@0: if (cacheItem) { andre@0: *cacheFreshness = ocsp_IsCacheItemFresh(cacheItem) ? ocspFresh andre@0: : ocspStale; andre@0: /* having an arena means, we have a cached certStatus */ andre@0: if (cacheItem->certStatusArena) { andre@0: *rvOcsp = ocsp_CertHasGoodStatus(&cacheItem->certStatus, time); andre@0: if (*rvOcsp != SECSuccess) { andre@0: *missingResponseError = PORT_GetError(); andre@0: } andre@0: } else { andre@0: /* andre@0: * No status cached, the previous attempt failed. andre@0: * If OCSP is required, we never decide based on a failed attempt andre@0: * However, if OCSP is optional, a recent OCSP failure is andre@0: * an allowed good state. andre@0: */ andre@0: if (*cacheFreshness == ocspFresh && andre@0: !ignoreGlobalOcspFailureSetting && andre@0: OCSP_Global.ocspFailureMode == andre@0: ocspMode_FailureIsNotAVerificationFailure) { andre@0: *rvOcsp = SECSuccess; andre@0: } andre@0: *missingResponseError = cacheItem->missingResponseError; andre@0: } andre@0: } andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return SECSuccess; andre@0: } andre@0: andre@0: PRBool andre@0: ocsp_FetchingFailureIsVerificationFailure(void) andre@0: { andre@0: PRBool isFailure; andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: isFailure = andre@0: OCSP_Global.ocspFailureMode == ocspMode_FailureIsVerificationFailure; andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return isFailure; andre@0: } andre@0: andre@0: /* andre@0: * FUNCTION: CERT_CheckOCSPStatus andre@0: * Checks the status of a certificate via OCSP. Will only check status for andre@0: * a certificate that has an AIA (Authority Information Access) extension andre@0: * for OCSP *or* when a "default responder" is specified and enabled. andre@0: * (If no AIA extension for OCSP and no default responder in place, the andre@0: * cert is considered to have a good status and SECSuccess is returned.) andre@0: * INPUTS: andre@0: * CERTCertDBHandle *handle andre@0: * certificate DB of the cert that is being checked andre@0: * CERTCertificate *cert andre@0: * the certificate being checked andre@0: * XXX in the long term also need a boolean parameter that specifies andre@0: * whether to check the cert chain, as well; for now we check only andre@0: * the leaf (the specified certificate) andre@0: * PRTime time andre@0: * time for which status is to be determined andre@0: * void *pwArg andre@0: * argument for password prompting, if needed andre@0: * RETURN: andre@0: * Returns SECSuccess if an approved OCSP responder "knows" the cert andre@0: * *and* returns a non-revoked status for it; SECFailure otherwise, andre@0: * with an error set describing the reason: andre@0: * andre@0: * SEC_ERROR_OCSP_BAD_HTTP_RESPONSE andre@0: * SEC_ERROR_OCSP_FUTURE_RESPONSE andre@0: * SEC_ERROR_OCSP_MALFORMED_REQUEST andre@0: * SEC_ERROR_OCSP_MALFORMED_RESPONSE andre@0: * SEC_ERROR_OCSP_OLD_RESPONSE andre@0: * SEC_ERROR_OCSP_REQUEST_NEEDS_SIG andre@0: * SEC_ERROR_OCSP_SERVER_ERROR andre@0: * SEC_ERROR_OCSP_TRY_SERVER_LATER andre@0: * SEC_ERROR_OCSP_UNAUTHORIZED_REQUEST andre@0: * SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE andre@0: * SEC_ERROR_OCSP_UNKNOWN_CERT andre@0: * SEC_ERROR_OCSP_UNKNOWN_RESPONSE_STATUS andre@0: * SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE andre@0: * andre@0: * SEC_ERROR_BAD_SIGNATURE andre@0: * SEC_ERROR_CERT_BAD_ACCESS_LOCATION andre@0: * SEC_ERROR_INVALID_TIME andre@0: * SEC_ERROR_REVOKED_CERTIFICATE andre@0: * SEC_ERROR_UNKNOWN_ISSUER andre@0: * SEC_ERROR_UNKNOWN_SIGNER andre@0: * andre@0: * Other errors are any of the many possible failures in cert verification andre@0: * (e.g. SEC_ERROR_REVOKED_CERTIFICATE, SEC_ERROR_UNTRUSTED_ISSUER) when andre@0: * verifying the signer's cert, or low-level problems (error allocating andre@0: * memory, error performing ASN.1 decoding, etc.). andre@0: */ andre@0: SECStatus andre@0: CERT_CheckOCSPStatus(CERTCertDBHandle *handle, CERTCertificate *cert, andre@0: PRTime time, void *pwArg) andre@0: { andre@0: CERTOCSPCertID *certID; andre@0: PRBool certIDWasConsumed = PR_FALSE; andre@0: SECStatus rv; andre@0: SECStatus rvOcsp; andre@0: SECErrorCodes cachedErrorCode; andre@0: OCSPFreshness cachedResponseFreshness; andre@0: andre@0: OCSP_TRACE_CERT(cert); andre@0: OCSP_TRACE_TIME("## requested validity time:", time); andre@0: andre@0: certID = CERT_CreateOCSPCertID(cert, time); andre@0: if (!certID) andre@0: return SECFailure; andre@0: rv = ocsp_GetCachedOCSPResponseStatus( andre@0: certID, time, PR_FALSE, /* ignoreGlobalOcspFailureSetting */ andre@0: &rvOcsp, &cachedErrorCode, &cachedResponseFreshness); andre@0: if (rv != SECSuccess) { andre@0: CERT_DestroyOCSPCertID(certID); andre@0: return SECFailure; andre@0: } andre@0: if (cachedResponseFreshness == ocspFresh) { andre@0: CERT_DestroyOCSPCertID(certID); andre@0: if (rvOcsp != SECSuccess) { andre@0: PORT_SetError(cachedErrorCode); andre@0: } andre@0: return rvOcsp; andre@0: } andre@0: andre@0: rv = ocsp_GetOCSPStatusFromNetwork(handle, certID, cert, time, pwArg, andre@0: &certIDWasConsumed, andre@0: &rvOcsp); andre@0: if (rv != SECSuccess) { andre@0: PRErrorCode err = PORT_GetError(); andre@0: if (ocsp_FetchingFailureIsVerificationFailure()) { andre@0: PORT_SetError(err); andre@0: rvOcsp = SECFailure; andre@0: } else if (cachedResponseFreshness == ocspStale && andre@0: (cachedErrorCode == SEC_ERROR_OCSP_UNKNOWN_CERT || andre@0: cachedErrorCode == SEC_ERROR_REVOKED_CERTIFICATE)) { andre@0: /* If we couldn't get a response for a certificate that the OCSP andre@0: * responder previously told us was bad, then assume it is still andre@0: * bad until we hear otherwise, as it is very unlikely that the andre@0: * certificate status has changed from "revoked" to "good" and it andre@0: * is also unlikely that the certificate status has changed from andre@0: * "unknown" to "good", except for some buggy OCSP responders. andre@0: */ andre@0: PORT_SetError(cachedErrorCode); andre@0: rvOcsp = SECFailure; andre@0: } else { andre@0: rvOcsp = SECSuccess; andre@0: } andre@0: } andre@0: if (!certIDWasConsumed) { andre@0: CERT_DestroyOCSPCertID(certID); andre@0: } andre@0: return rvOcsp; andre@0: } andre@0: andre@0: /* andre@0: * FUNCTION: CERT_CacheOCSPResponseFromSideChannel andre@0: * First, this function checks the OCSP cache to see if a good response andre@0: * for the given certificate already exists. If it does, then the function andre@0: * returns successfully. andre@0: * andre@0: * If not, then it validates that the given OCSP response is a valid, andre@0: * good response for the given certificate and inserts it into the andre@0: * cache. andre@0: * andre@0: * This function is intended for use when OCSP responses are provided via a andre@0: * side-channel, i.e. TLS OCSP stapling (a.k.a. the status_request extension). andre@0: * andre@0: * INPUTS: andre@0: * CERTCertDBHandle *handle andre@0: * certificate DB of the cert that is being checked andre@0: * CERTCertificate *cert andre@0: * the certificate being checked andre@0: * PRTime time andre@0: * time for which status is to be determined andre@0: * SECItem *encodedResponse andre@0: * the DER encoded bytes of the OCSP response andre@0: * void *pwArg andre@0: * argument for password prompting, if needed andre@0: * RETURN: andre@0: * SECSuccess if the cert was found in the cache, or if the OCSP response was andre@0: * found to be valid and inserted into the cache. SECFailure otherwise. andre@0: */ andre@0: SECStatus andre@0: CERT_CacheOCSPResponseFromSideChannel(CERTCertDBHandle *handle, andre@0: CERTCertificate *cert, andre@0: PRTime time, andre@0: const SECItem *encodedResponse, andre@0: void *pwArg) andre@0: { andre@0: CERTOCSPCertID *certID = NULL; andre@0: PRBool certIDWasConsumed = PR_FALSE; andre@0: SECStatus rv = SECFailure; andre@0: SECStatus rvOcsp = SECFailure; andre@0: SECErrorCodes dummy_error_code; /* we ignore this */ andre@0: CERTOCSPResponse *decodedResponse = NULL; andre@0: CERTOCSPSingleResponse *singleResponse = NULL; andre@0: OCSPFreshness freshness; andre@0: andre@0: /* The OCSP cache can be in three states regarding this certificate: andre@0: * + Good (cached, timely, 'good' response, or revoked in the future) andre@0: * + Revoked (cached, timely, but doesn't fit in the last category) andre@0: * + Miss (no knowledge) andre@0: * andre@0: * Likewise, the side-channel information can be andre@0: * + Good (timely, 'good' response, or revoked in the future) andre@0: * + Revoked (timely, but doesn't fit in the last category) andre@0: * + Invalid (bad syntax, bad signature, not timely etc) andre@0: * andre@0: * The common case is that the cache result is Good and so is the andre@0: * side-channel information. We want to save processing time in this case andre@0: * so we say that any time we see a Good result from the cache we return andre@0: * early. andre@0: * andre@0: * Cache result andre@0: * | Good Revoked Miss andre@0: * ---+-------------------------------------------- andre@0: * G | noop Cache more Cache it andre@0: * S | recent result andre@0: * i | andre@0: * d | andre@0: * e | andre@0: * R | noop Cache more Cache it andre@0: * C | recent result andre@0: * h | andre@0: * a | andre@0: * n | andre@0: * n I | noop Noop Noop andre@0: * e | andre@0: * l | andre@0: * andre@0: * When we fetch from the network we might choose to cache a negative andre@0: * result when the response is invalid. This saves us hammering, uselessly, andre@0: * at a broken responder. However, side channels are commonly attacker andre@0: * controlled and so we must not cache a negative result for an Invalid andre@0: * side channel. andre@0: */ andre@0: andre@0: if (!cert || !encodedResponse) { andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: return SECFailure; andre@0: } andre@0: certID = CERT_CreateOCSPCertID(cert, time); andre@0: if (!certID) andre@0: return SECFailure; andre@0: andre@0: /* We pass PR_TRUE for ignoreGlobalOcspFailureSetting so that a cached andre@0: * error entry is not interpreted as being a 'Good' entry here. andre@0: */ andre@0: rv = ocsp_GetCachedOCSPResponseStatus( andre@0: certID, time, PR_TRUE, /* ignoreGlobalOcspFailureSetting */ andre@0: &rvOcsp, &dummy_error_code, &freshness); andre@0: if (rv == SECSuccess && rvOcsp == SECSuccess && freshness == ocspFresh) { andre@0: /* The cached value is good. We don't want to waste time validating andre@0: * this OCSP response. This is the first column in the table above. */ andre@0: CERT_DestroyOCSPCertID(certID); andre@0: return rv; andre@0: } andre@0: andre@0: /* The logic for caching the more recent response is handled in andre@0: * ocsp_CacheSingleResponse. */ andre@0: andre@0: rv = ocsp_GetDecodedVerifiedSingleResponseForID(handle, certID, cert, andre@0: time, pwArg, andre@0: encodedResponse, andre@0: &decodedResponse, andre@0: &singleResponse); andre@0: if (rv == SECSuccess) { andre@0: rvOcsp = ocsp_SingleResponseCertHasGoodStatus(singleResponse, time); andre@0: /* Cache any valid singleResponse, regardless of status. */ andre@0: ocsp_CacheSingleResponse(certID, singleResponse, &certIDWasConsumed); andre@0: } andre@0: if (decodedResponse) { andre@0: CERT_DestroyOCSPResponse(decodedResponse); andre@0: } andre@0: if (!certIDWasConsumed) { andre@0: CERT_DestroyOCSPCertID(certID); andre@0: } andre@0: return rv == SECSuccess ? rvOcsp : rv; andre@0: } andre@0: andre@0: /* andre@0: * Status in *certIDWasConsumed will always be correct, regardless of andre@0: * return value. andre@0: */ andre@0: static SECStatus andre@0: ocsp_GetOCSPStatusFromNetwork(CERTCertDBHandle *handle, andre@0: CERTOCSPCertID *certID, andre@0: CERTCertificate *cert, andre@0: PRTime time, andre@0: void *pwArg, andre@0: PRBool *certIDWasConsumed, andre@0: SECStatus *rv_ocsp) andre@0: { andre@0: char *location = NULL; andre@0: PRBool locationIsDefault; andre@0: SECItem *encodedResponse = NULL; andre@0: CERTOCSPRequest *request = NULL; andre@0: SECStatus rv = SECFailure; andre@0: andre@0: CERTOCSPResponse *decodedResponse = NULL; andre@0: CERTOCSPSingleResponse *singleResponse = NULL; andre@0: enum { stageGET, stagePOST } currentStage; andre@0: PRBool retry = PR_FALSE; andre@0: andre@0: if (!certIDWasConsumed || !rv_ocsp) { andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: return SECFailure; andre@0: } andre@0: *certIDWasConsumed = PR_FALSE; andre@0: *rv_ocsp = SECFailure; andre@0: andre@0: if (!OCSP_Global.monitor) { andre@0: PORT_SetError(SEC_ERROR_NOT_INITIALIZED); andre@0: return SECFailure; andre@0: } andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: if (OCSP_Global.forcePost) { andre@0: currentStage = stagePOST; andre@0: } else { andre@0: currentStage = stageGET; andre@0: } andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: andre@0: /* andre@0: * The first thing we need to do is find the location of the responder. andre@0: * This will be the value of the default responder (if enabled), else andre@0: * it will come out of the AIA extension in the cert (if present). andre@0: * If we have no such location, then this cert does not "deserve" to andre@0: * be checked -- that is, we consider it a success and just return. andre@0: * The way we tell that is by looking at the error number to see if andre@0: * the problem was no AIA extension was found; any other error was andre@0: * a true failure that we unfortunately have to treat as an overall andre@0: * failure here. andre@0: */ andre@0: location = ocsp_GetResponderLocation(handle, cert, PR_TRUE, andre@0: &locationIsDefault); andre@0: if (location == NULL) { andre@0: int err = PORT_GetError(); andre@0: if (err == SEC_ERROR_EXTENSION_NOT_FOUND || andre@0: err == SEC_ERROR_CERT_BAD_ACCESS_LOCATION) { andre@0: PORT_SetError(0); andre@0: *rv_ocsp = SECSuccess; andre@0: return SECSuccess; andre@0: } andre@0: return SECFailure; andre@0: } andre@0: andre@0: /* andre@0: * XXX In the fullness of time, we will want/need to handle a andre@0: * certificate chain. This will be done either when a new parameter andre@0: * tells us to, or some configuration variable tells us to. In any andre@0: * case, handling it is complicated because we may need to send as andre@0: * many requests (and receive as many responses) as we have certs andre@0: * in the chain. If we are going to talk to a default responder, andre@0: * and we only support one default responder, we can put all of the andre@0: * certs together into one request. Otherwise, we must break them up andre@0: * into multiple requests. (Even if all of the requests will go to andre@0: * the same location, the signature on each response will be different, andre@0: * because each issuer is different. Carefully read the OCSP spec andre@0: * if you do not understand this.) andre@0: */ andre@0: andre@0: /* andre@0: * XXX If/when signing of requests is supported, that second NULL andre@0: * should be changed to be the signer certificate. Not sure if that andre@0: * should be passed into this function or retrieved via some operation andre@0: * on the handle/context. andre@0: */ andre@0: andre@0: do { andre@0: const char *method; andre@0: PRBool validResponseWithAccurateInfo = PR_FALSE; andre@0: retry = PR_FALSE; andre@0: *rv_ocsp = SECFailure; andre@0: andre@0: if (currentStage == stageGET) { andre@0: method = "GET"; andre@0: } else { andre@0: PORT_Assert(currentStage == stagePOST); andre@0: method = "POST"; andre@0: } andre@0: andre@0: encodedResponse = andre@0: ocsp_GetEncodedOCSPResponseForSingleCert(NULL, certID, cert, andre@0: location, method, andre@0: time, locationIsDefault, andre@0: pwArg, &request); andre@0: andre@0: if (encodedResponse) { andre@0: rv = ocsp_GetDecodedVerifiedSingleResponseForID(handle, certID, cert, andre@0: time, pwArg, andre@0: encodedResponse, andre@0: &decodedResponse, andre@0: &singleResponse); andre@0: if (rv == SECSuccess) { andre@0: switch (singleResponse->certStatus->certStatusType) { andre@0: case ocspCertStatus_good: andre@0: case ocspCertStatus_revoked: andre@0: validResponseWithAccurateInfo = PR_TRUE; andre@0: break; andre@0: default: andre@0: break; andre@0: } andre@0: *rv_ocsp = ocsp_SingleResponseCertHasGoodStatus(singleResponse, time); andre@0: } andre@0: } andre@0: andre@0: if (currentStage == stageGET) { andre@0: /* only accept GET response if good or revoked */ andre@0: if (validResponseWithAccurateInfo) { andre@0: ocsp_CacheSingleResponse(certID, singleResponse, andre@0: certIDWasConsumed); andre@0: } else { andre@0: retry = PR_TRUE; andre@0: currentStage = stagePOST; andre@0: } andre@0: } else { andre@0: /* cache the POST respone, regardless of status */ andre@0: if (!singleResponse) { andre@0: cert_RememberOCSPProcessingFailure(certID, certIDWasConsumed); andre@0: } else { andre@0: ocsp_CacheSingleResponse(certID, singleResponse, andre@0: certIDWasConsumed); andre@0: } andre@0: } andre@0: andre@0: if (encodedResponse) { andre@0: SECITEM_FreeItem(encodedResponse, PR_TRUE); andre@0: encodedResponse = NULL; andre@0: } andre@0: if (request) { andre@0: CERT_DestroyOCSPRequest(request); andre@0: request = NULL; andre@0: } andre@0: if (decodedResponse) { andre@0: CERT_DestroyOCSPResponse(decodedResponse); andre@0: decodedResponse = NULL; andre@0: } andre@0: singleResponse = NULL; andre@0: andre@0: } while (retry); andre@0: andre@0: PORT_Free(location); andre@0: return rv; andre@0: } andre@0: andre@0: /* andre@0: * FUNCTION: ocsp_GetDecodedVerifiedSingleResponseForID andre@0: * This function decodes an OCSP response and checks for a valid response andre@0: * concerning the given certificate. andre@0: * andre@0: * Note: a 'valid' response is one that parses successfully, is not an OCSP andre@0: * exception (see RFC 2560 Section 2.3), is correctly signed and is current. andre@0: * A 'good' response is a valid response that attests that the certificate andre@0: * is not currently revoked (see RFC 2560 Section 2.2). andre@0: * andre@0: * INPUTS: andre@0: * CERTCertDBHandle *handle andre@0: * certificate DB of the cert that is being checked andre@0: * CERTOCSPCertID *certID andre@0: * the cert ID corresponding to |cert| andre@0: * CERTCertificate *cert andre@0: * the certificate being checked andre@0: * PRTime time andre@0: * time for which status is to be determined andre@0: * void *pwArg andre@0: * the opaque argument to the password prompting function. andre@0: * SECItem *encodedResponse andre@0: * the DER encoded bytes of the OCSP response andre@0: * CERTOCSPResponse **pDecodedResponse andre@0: * (output) The caller must ALWAYS check for this output parameter, andre@0: * and if it's non-null, must destroy it using CERT_DestroyOCSPResponse. andre@0: * CERTOCSPSingleResponse **pSingle andre@0: * (output) on success, this points to the single response that corresponds andre@0: * to the certID parameter. Points to the inside of pDecodedResponse. andre@0: * It isn't a copy, don't free it. andre@0: * RETURN: andre@0: * SECSuccess iff the response is valid. andre@0: */ andre@0: static SECStatus andre@0: ocsp_GetDecodedVerifiedSingleResponseForID(CERTCertDBHandle *handle, andre@0: CERTOCSPCertID *certID, andre@0: CERTCertificate *cert, andre@0: PRTime time, andre@0: void *pwArg, andre@0: const SECItem *encodedResponse, andre@0: CERTOCSPResponse **pDecodedResponse, andre@0: CERTOCSPSingleResponse **pSingle) andre@0: { andre@0: CERTCertificate *signerCert = NULL; andre@0: CERTCertificate *issuerCert = NULL; andre@0: SECStatus rv = SECFailure; andre@0: andre@0: if (!pSingle || !pDecodedResponse) { andre@0: return SECFailure; andre@0: } andre@0: *pSingle = NULL; andre@0: *pDecodedResponse = CERT_DecodeOCSPResponse(encodedResponse); andre@0: if (!*pDecodedResponse) { andre@0: return SECFailure; andre@0: } andre@0: andre@0: /* andre@0: * Okay, we at least have a response that *looks* like a response! andre@0: * Now see if the overall response status value is good or not. andre@0: * If not, we set an error and give up. (It means that either the andre@0: * server had a problem, or it didn't like something about our andre@0: * request. Either way there is nothing to do but give up.) andre@0: * Otherwise, we continue to find the actual per-cert status andre@0: * in the response. andre@0: */ andre@0: if (CERT_GetOCSPResponseStatus(*pDecodedResponse) != SECSuccess) { andre@0: goto loser; andre@0: } andre@0: andre@0: /* andre@0: * If we've made it this far, we expect a response with a good signature. andre@0: * So, check for that. andre@0: */ andre@0: issuerCert = CERT_FindCertIssuer(cert, time, certUsageAnyCA); andre@0: rv = CERT_VerifyOCSPResponseSignature(*pDecodedResponse, handle, pwArg, andre@0: &signerCert, issuerCert); andre@0: if (rv != SECSuccess) { andre@0: goto loser; andre@0: } andre@0: andre@0: PORT_Assert(signerCert != NULL); /* internal consistency check */ andre@0: /* XXX probably should set error, return failure if signerCert is null */ andre@0: andre@0: /* andre@0: * Again, we are only doing one request for one cert. andre@0: * XXX When we handle cert chains, the following code will obviously andre@0: * have to be modified, in coordation with the code above that will andre@0: * have to determine how to make multiple requests, etc. andre@0: */ andre@0: rv = ocsp_GetVerifiedSingleResponseForCertID(handle, *pDecodedResponse, certID, andre@0: signerCert, time, pSingle); andre@0: loser: andre@0: if (issuerCert != NULL) andre@0: CERT_DestroyCertificate(issuerCert); andre@0: if (signerCert != NULL) andre@0: CERT_DestroyCertificate(signerCert); andre@0: return rv; andre@0: } andre@0: andre@0: /* andre@0: * FUNCTION: ocsp_CacheSingleResponse andre@0: * This function requires that the caller has checked that the response andre@0: * is valid and verified. andre@0: * The (positive or negative) valid response will be used to update the cache. andre@0: * INPUTS: andre@0: * CERTOCSPCertID *certID andre@0: * the cert ID corresponding to |cert| andre@0: * PRBool *certIDWasConsumed andre@0: * (output) on return, this is true iff |certID| was consumed by this andre@0: * function. andre@0: */ andre@0: void andre@0: ocsp_CacheSingleResponse(CERTOCSPCertID *certID, andre@0: CERTOCSPSingleResponse *single, andre@0: PRBool *certIDWasConsumed) andre@0: { andre@0: if (single != NULL) { andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: if (OCSP_Global.maxCacheEntries >= 0) { andre@0: ocsp_CreateOrUpdateCacheEntry(&OCSP_Global.cache, certID, single, andre@0: certIDWasConsumed); andre@0: /* ignore cache update failures */ andre@0: } andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: } andre@0: } andre@0: andre@0: SECStatus andre@0: ocsp_GetVerifiedSingleResponseForCertID(CERTCertDBHandle *handle, andre@0: CERTOCSPResponse *response, andre@0: CERTOCSPCertID *certID, andre@0: CERTCertificate *signerCert, andre@0: PRTime time, andre@0: CERTOCSPSingleResponse andre@0: **pSingleResponse) andre@0: { andre@0: SECStatus rv; andre@0: ocspResponseData *responseData; andre@0: PRTime producedAt; andre@0: CERTOCSPSingleResponse *single; andre@0: andre@0: /* andre@0: * The ResponseData part is the real guts of the response. andre@0: */ andre@0: responseData = ocsp_GetResponseData(response, NULL); andre@0: if (responseData == NULL) { andre@0: rv = SECFailure; andre@0: goto loser; andre@0: } andre@0: andre@0: /* andre@0: * There is one producedAt time for the entire response (and a separate andre@0: * thisUpdate time for each individual single response). We need to andre@0: * compare them, so get the overall time to pass into the check of each andre@0: * single response. andre@0: */ andre@0: rv = DER_GeneralizedTimeToTime(&producedAt, &responseData->producedAt); andre@0: if (rv != SECSuccess) andre@0: goto loser; andre@0: andre@0: single = ocsp_GetSingleResponseForCertID(responseData->responses, andre@0: handle, certID); andre@0: if (single == NULL) { andre@0: rv = SECFailure; andre@0: goto loser; andre@0: } andre@0: andre@0: rv = ocsp_VerifySingleResponse(single, handle, signerCert, producedAt); andre@0: if (rv != SECSuccess) andre@0: goto loser; andre@0: *pSingleResponse = single; andre@0: andre@0: loser: andre@0: return rv; andre@0: } andre@0: andre@0: SECStatus andre@0: CERT_GetOCSPStatusForCertID(CERTCertDBHandle *handle, andre@0: CERTOCSPResponse *response, andre@0: CERTOCSPCertID *certID, andre@0: CERTCertificate *signerCert, andre@0: PRTime time) andre@0: { andre@0: /* andre@0: * We do not update the cache, because: andre@0: * andre@0: * CERT_GetOCSPStatusForCertID is an old exported API that was introduced andre@0: * before the OCSP cache got implemented. andre@0: * andre@0: * The implementation of helper function cert_ProcessOCSPResponse andre@0: * requires the ability to transfer ownership of the the given certID to andre@0: * the cache. The external API doesn't allow us to prevent the caller from andre@0: * destroying the certID. We don't have the original certificate available, andre@0: * therefore we are unable to produce another certID object (that could andre@0: * be stored in the cache). andre@0: * andre@0: * Should we ever implement code to produce a deep copy of certID, andre@0: * then this could be changed to allow updating the cache. andre@0: * The duplication would have to be done in andre@0: * cert_ProcessOCSPResponse, if the out parameter to indicate andre@0: * a transfer of ownership is NULL. andre@0: */ andre@0: return cert_ProcessOCSPResponse(handle, response, certID, andre@0: signerCert, time, andre@0: NULL, NULL); andre@0: } andre@0: andre@0: /* andre@0: * The first 5 parameters match the definition of CERT_GetOCSPStatusForCertID. andre@0: */ andre@0: SECStatus andre@0: cert_ProcessOCSPResponse(CERTCertDBHandle *handle, andre@0: CERTOCSPResponse *response, andre@0: CERTOCSPCertID *certID, andre@0: CERTCertificate *signerCert, andre@0: PRTime time, andre@0: PRBool *certIDWasConsumed, andre@0: SECStatus *cacheUpdateStatus) andre@0: { andre@0: SECStatus rv; andre@0: SECStatus rv_cache = SECSuccess; andre@0: CERTOCSPSingleResponse *single = NULL; andre@0: andre@0: rv = ocsp_GetVerifiedSingleResponseForCertID(handle, response, certID, andre@0: signerCert, time, &single); andre@0: if (rv == SECSuccess) { andre@0: /* andre@0: * Check whether the status says revoked, and if so andre@0: * how that compares to the time value passed into this routine. andre@0: */ andre@0: rv = ocsp_SingleResponseCertHasGoodStatus(single, time); andre@0: } andre@0: andre@0: if (certIDWasConsumed) { andre@0: /* andre@0: * We don't have copy-of-certid implemented. In order to update andre@0: * the cache, the caller must supply an out variable andre@0: * certIDWasConsumed, allowing us to return ownership status. andre@0: */ andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: if (OCSP_Global.maxCacheEntries >= 0) { andre@0: /* single == NULL means: remember response failure */ andre@0: rv_cache = andre@0: ocsp_CreateOrUpdateCacheEntry(&OCSP_Global.cache, certID, andre@0: single, certIDWasConsumed); andre@0: } andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: if (cacheUpdateStatus) { andre@0: *cacheUpdateStatus = rv_cache; andre@0: } andre@0: } andre@0: andre@0: return rv; andre@0: } andre@0: andre@0: SECStatus andre@0: cert_RememberOCSPProcessingFailure(CERTOCSPCertID *certID, andre@0: PRBool *certIDWasConsumed) andre@0: { andre@0: SECStatus rv = SECSuccess; andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: if (OCSP_Global.maxCacheEntries >= 0) { andre@0: rv = ocsp_CreateOrUpdateCacheEntry(&OCSP_Global.cache, certID, NULL, andre@0: certIDWasConsumed); andre@0: } andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: return rv; andre@0: } andre@0: andre@0: /* andre@0: * Disable status checking and destroy related structures/data. andre@0: */ andre@0: static SECStatus andre@0: ocsp_DestroyStatusChecking(CERTStatusConfig *statusConfig) andre@0: { andre@0: ocspCheckingContext *statusContext; andre@0: andre@0: /* andre@0: * Disable OCSP checking andre@0: */ andre@0: statusConfig->statusChecker = NULL; andre@0: andre@0: statusContext = statusConfig->statusContext; andre@0: PORT_Assert(statusContext != NULL); andre@0: if (statusContext == NULL) andre@0: return SECFailure; andre@0: andre@0: if (statusContext->defaultResponderURI != NULL) andre@0: PORT_Free(statusContext->defaultResponderURI); andre@0: if (statusContext->defaultResponderNickname != NULL) andre@0: PORT_Free(statusContext->defaultResponderNickname); andre@0: andre@0: PORT_Free(statusContext); andre@0: statusConfig->statusContext = NULL; andre@0: andre@0: PORT_Free(statusConfig); andre@0: andre@0: return SECSuccess; andre@0: } andre@0: andre@0: andre@0: /* andre@0: * FUNCTION: CERT_DisableOCSPChecking andre@0: * Turns off OCSP checking for the given certificate database. andre@0: * This routine disables OCSP checking. Though it will return andre@0: * SECFailure if OCSP checking is not enabled, it is "safe" to andre@0: * call it that way and just ignore the return value, if it is andre@0: * easier to just call it than to "remember" whether it is enabled. andre@0: * INPUTS: andre@0: * CERTCertDBHandle *handle andre@0: * Certificate database for which OCSP checking will be disabled. andre@0: * RETURN: andre@0: * Returns SECFailure if an error occurred (usually means that OCSP andre@0: * checking was not enabled or status contexts were not initialized -- andre@0: * error set will be SEC_ERROR_OCSP_NOT_ENABLED); SECSuccess otherwise. andre@0: */ andre@0: SECStatus andre@0: CERT_DisableOCSPChecking(CERTCertDBHandle *handle) andre@0: { andre@0: CERTStatusConfig *statusConfig; andre@0: ocspCheckingContext *statusContext; andre@0: andre@0: if (handle == NULL) { andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: return SECFailure; andre@0: } andre@0: andre@0: statusConfig = CERT_GetStatusConfig(handle); andre@0: statusContext = ocsp_GetCheckingContext(handle); andre@0: if (statusContext == NULL) andre@0: return SECFailure; andre@0: andre@0: if (statusConfig->statusChecker != CERT_CheckOCSPStatus) { andre@0: /* andre@0: * Status configuration is present, but either not currently andre@0: * enabled or not for OCSP. andre@0: */ andre@0: PORT_SetError(SEC_ERROR_OCSP_NOT_ENABLED); andre@0: return SECFailure; andre@0: } andre@0: andre@0: /* cache no longer necessary */ andre@0: CERT_ClearOCSPCache(); andre@0: andre@0: /* andre@0: * This is how we disable status checking. Everything else remains andre@0: * in place in case we are enabled again. andre@0: */ andre@0: statusConfig->statusChecker = NULL; andre@0: andre@0: return SECSuccess; andre@0: } andre@0: andre@0: /* andre@0: * Allocate and initialize the informational structures for status checking. andre@0: * This is done when some configuration of OCSP is being done or when OCSP andre@0: * checking is being turned on, whichever comes first. andre@0: */ andre@0: static SECStatus andre@0: ocsp_InitStatusChecking(CERTCertDBHandle *handle) andre@0: { andre@0: CERTStatusConfig *statusConfig = NULL; andre@0: ocspCheckingContext *statusContext = NULL; andre@0: andre@0: PORT_Assert(CERT_GetStatusConfig(handle) == NULL); andre@0: if (CERT_GetStatusConfig(handle) != NULL) { andre@0: /* XXX or call statusConfig->statusDestroy and continue? */ andre@0: return SECFailure; andre@0: } andre@0: andre@0: statusConfig = PORT_ZNew(CERTStatusConfig); andre@0: if (statusConfig == NULL) andre@0: goto loser; andre@0: andre@0: statusContext = PORT_ZNew(ocspCheckingContext); andre@0: if (statusContext == NULL) andre@0: goto loser; andre@0: andre@0: statusConfig->statusDestroy = ocsp_DestroyStatusChecking; andre@0: statusConfig->statusContext = statusContext; andre@0: andre@0: CERT_SetStatusConfig(handle, statusConfig); andre@0: andre@0: return SECSuccess; andre@0: andre@0: loser: andre@0: if (statusConfig != NULL) andre@0: PORT_Free(statusConfig); andre@0: return SECFailure; andre@0: } andre@0: andre@0: andre@0: /* andre@0: * FUNCTION: CERT_EnableOCSPChecking andre@0: * Turns on OCSP checking for the given certificate database. andre@0: * INPUTS: andre@0: * CERTCertDBHandle *handle andre@0: * Certificate database for which OCSP checking will be enabled. andre@0: * RETURN: andre@0: * Returns SECFailure if an error occurred (likely only problem andre@0: * allocating memory); SECSuccess otherwise. andre@0: */ andre@0: SECStatus andre@0: CERT_EnableOCSPChecking(CERTCertDBHandle *handle) andre@0: { andre@0: CERTStatusConfig *statusConfig; andre@0: andre@0: SECStatus rv; andre@0: andre@0: if (handle == NULL) { andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: return SECFailure; andre@0: } andre@0: andre@0: statusConfig = CERT_GetStatusConfig(handle); andre@0: if (statusConfig == NULL) { andre@0: rv = ocsp_InitStatusChecking(handle); andre@0: if (rv != SECSuccess) andre@0: return rv; andre@0: andre@0: /* Get newly established value */ andre@0: statusConfig = CERT_GetStatusConfig(handle); andre@0: PORT_Assert(statusConfig != NULL); andre@0: } andre@0: andre@0: /* andre@0: * Setting the checker function is what really enables the checking andre@0: * when each cert verification is done. andre@0: */ andre@0: statusConfig->statusChecker = CERT_CheckOCSPStatus; andre@0: andre@0: return SECSuccess; andre@0: } andre@0: andre@0: andre@0: /* andre@0: * FUNCTION: CERT_SetOCSPDefaultResponder andre@0: * Specify the location and cert of the default responder. andre@0: * If OCSP checking is already enabled *and* use of a default responder andre@0: * is also already enabled, all OCSP checking from now on will go directly andre@0: * to the specified responder. If OCSP checking is not enabled, or if andre@0: * it is but use of a default responder is not enabled, the information andre@0: * will be recorded and take effect whenever both are enabled. andre@0: * INPUTS: andre@0: * CERTCertDBHandle *handle andre@0: * Cert database on which OCSP checking should use the default responder. andre@0: * char *url andre@0: * The location of the default responder (e.g. "http://foo.com:80/ocsp") andre@0: * Note that the location will not be tested until the first attempt andre@0: * to send a request there. andre@0: * char *name andre@0: * The nickname of the cert to trust (expected) to sign the OCSP responses. andre@0: * If the corresponding cert cannot be found, SECFailure is returned. andre@0: * RETURN: andre@0: * Returns SECFailure if an error occurred; SECSuccess otherwise. andre@0: * The most likely error is that the cert for "name" could not be found andre@0: * (probably SEC_ERROR_UNKNOWN_CERT). Other errors are low-level (no memory, andre@0: * bad database, etc.). andre@0: */ andre@0: SECStatus andre@0: CERT_SetOCSPDefaultResponder(CERTCertDBHandle *handle, andre@0: const char *url, const char *name) andre@0: { andre@0: CERTCertificate *cert; andre@0: ocspCheckingContext *statusContext; andre@0: char *url_copy = NULL; andre@0: char *name_copy = NULL; andre@0: SECStatus rv; andre@0: andre@0: if (handle == NULL || url == NULL || name == NULL) { andre@0: /* andre@0: * XXX When interface is exported, probably want better errors; andre@0: * perhaps different one for each parameter. andre@0: */ andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: return SECFailure; andre@0: } andre@0: andre@0: /* andre@0: * Find the certificate for the specified nickname. Do this first andre@0: * because it seems the most likely to fail. andre@0: * andre@0: * XXX Shouldn't need that cast if the FindCertByNickname interface andre@0: * used const to convey that it does not modify the name. Maybe someday. andre@0: */ andre@0: cert = CERT_FindCertByNickname(handle, (char *) name); andre@0: if (cert == NULL) { andre@0: /* andre@0: * look for the cert on an external token. andre@0: */ andre@0: cert = PK11_FindCertFromNickname((char *)name, NULL); andre@0: } andre@0: if (cert == NULL) andre@0: return SECFailure; andre@0: andre@0: /* andre@0: * Make a copy of the url and nickname. andre@0: */ andre@0: url_copy = PORT_Strdup(url); andre@0: name_copy = PORT_Strdup(name); andre@0: if (url_copy == NULL || name_copy == NULL) { andre@0: rv = SECFailure; andre@0: goto loser; andre@0: } andre@0: andre@0: statusContext = ocsp_GetCheckingContext(handle); andre@0: andre@0: /* andre@0: * Allocate and init the context if it doesn't already exist. andre@0: */ andre@0: if (statusContext == NULL) { andre@0: rv = ocsp_InitStatusChecking(handle); andre@0: if (rv != SECSuccess) andre@0: goto loser; andre@0: andre@0: statusContext = ocsp_GetCheckingContext(handle); andre@0: PORT_Assert(statusContext != NULL); /* extreme paranoia */ andre@0: } andre@0: andre@0: /* andre@0: * Note -- we do not touch the status context until after all of andre@0: * the steps which could cause errors. If something goes wrong, andre@0: * we want to leave things as they were. andre@0: */ andre@0: andre@0: /* andre@0: * Get rid of old url and name if there. andre@0: */ andre@0: if (statusContext->defaultResponderNickname != NULL) andre@0: PORT_Free(statusContext->defaultResponderNickname); andre@0: if (statusContext->defaultResponderURI != NULL) andre@0: PORT_Free(statusContext->defaultResponderURI); andre@0: andre@0: /* andre@0: * And replace them with the new ones. andre@0: */ andre@0: statusContext->defaultResponderURI = url_copy; andre@0: statusContext->defaultResponderNickname = name_copy; andre@0: andre@0: /* andre@0: * If there was already a cert in place, get rid of it and replace it. andre@0: * Otherwise, we are not currently enabled, so we don't want to save it; andre@0: * it will get re-found and set whenever use of a default responder is andre@0: * enabled. andre@0: */ andre@0: if (statusContext->defaultResponderCert != NULL) { andre@0: CERT_DestroyCertificate(statusContext->defaultResponderCert); andre@0: statusContext->defaultResponderCert = cert; andre@0: /*OCSP enabled, switching responder: clear cache*/ andre@0: CERT_ClearOCSPCache(); andre@0: } else { andre@0: PORT_Assert(statusContext->useDefaultResponder == PR_FALSE); andre@0: CERT_DestroyCertificate(cert); andre@0: /*OCSP currently not enabled, no need to clear cache*/ andre@0: } andre@0: andre@0: return SECSuccess; andre@0: andre@0: loser: andre@0: CERT_DestroyCertificate(cert); andre@0: if (url_copy != NULL) andre@0: PORT_Free(url_copy); andre@0: if (name_copy != NULL) andre@0: PORT_Free(name_copy); andre@0: return rv; andre@0: } andre@0: andre@0: andre@0: /* andre@0: * FUNCTION: CERT_EnableOCSPDefaultResponder andre@0: * Turns on use of a default responder when OCSP checking. andre@0: * If OCSP checking is already enabled, this will make subsequent checks andre@0: * go directly to the default responder. (The location of the responder andre@0: * and the nickname of the responder cert must already be specified.) andre@0: * If OCSP checking is not enabled, this will be recorded and take effect andre@0: * whenever it is enabled. andre@0: * INPUTS: andre@0: * CERTCertDBHandle *handle andre@0: * Cert database on which OCSP checking should use the default responder. andre@0: * RETURN: andre@0: * Returns SECFailure if an error occurred; SECSuccess otherwise. andre@0: * No errors are especially likely unless the caller did not previously andre@0: * perform a successful call to SetOCSPDefaultResponder (in which case andre@0: * the error set will be SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER). andre@0: */ andre@0: SECStatus andre@0: CERT_EnableOCSPDefaultResponder(CERTCertDBHandle *handle) andre@0: { andre@0: ocspCheckingContext *statusContext; andre@0: CERTCertificate *cert; andre@0: SECStatus rv; andre@0: SECCertificateUsage usage; andre@0: andre@0: if (handle == NULL) { andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: return SECFailure; andre@0: } andre@0: andre@0: statusContext = ocsp_GetCheckingContext(handle); andre@0: andre@0: if (statusContext == NULL) { andre@0: /* andre@0: * Strictly speaking, the error already set is "correct", andre@0: * but cover over it with one more helpful in this context. andre@0: */ andre@0: PORT_SetError(SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER); andre@0: return SECFailure; andre@0: } andre@0: andre@0: if (statusContext->defaultResponderURI == NULL) { andre@0: PORT_SetError(SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER); andre@0: return SECFailure; andre@0: } andre@0: andre@0: if (statusContext->defaultResponderNickname == NULL) { andre@0: PORT_SetError(SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER); andre@0: return SECFailure; andre@0: } andre@0: andre@0: /* andre@0: * Find the cert for the nickname. andre@0: */ andre@0: cert = CERT_FindCertByNickname(handle, andre@0: statusContext->defaultResponderNickname); andre@0: if (cert == NULL) { andre@0: cert = PK11_FindCertFromNickname(statusContext->defaultResponderNickname, andre@0: NULL); andre@0: } andre@0: /* andre@0: * We should never have trouble finding the cert, because its andre@0: * existence should have been proven by SetOCSPDefaultResponder. andre@0: */ andre@0: PORT_Assert(cert != NULL); andre@0: if (cert == NULL) andre@0: return SECFailure; andre@0: andre@0: /* andre@0: * Supplied cert should at least have a signing capability in order for us andre@0: * to use it as a trusted responder cert. Ability to sign is guaranteed if andre@0: * cert is validated to have any set of the usages below. andre@0: */ andre@0: rv = CERT_VerifyCertificateNow(handle, cert, PR_TRUE, andre@0: certificateUsageCheckAllUsages, andre@0: NULL, &usage); andre@0: if (rv != SECSuccess || (usage & (certificateUsageSSLClient | andre@0: certificateUsageSSLServer | andre@0: certificateUsageSSLServerWithStepUp | andre@0: certificateUsageEmailSigner | andre@0: certificateUsageObjectSigner | andre@0: certificateUsageStatusResponder | andre@0: certificateUsageSSLCA)) == 0) { andre@0: PORT_SetError(SEC_ERROR_OCSP_RESPONDER_CERT_INVALID); andre@0: return SECFailure; andre@0: } andre@0: andre@0: /* andre@0: * And hang onto it. andre@0: */ andre@0: statusContext->defaultResponderCert = cert; andre@0: andre@0: /* we don't allow a mix of cache entries from different responders */ andre@0: CERT_ClearOCSPCache(); andre@0: andre@0: /* andre@0: * Finally, record the fact that we now have a default responder enabled. andre@0: */ andre@0: statusContext->useDefaultResponder = PR_TRUE; andre@0: return SECSuccess; andre@0: } andre@0: andre@0: andre@0: /* andre@0: * FUNCTION: CERT_DisableOCSPDefaultResponder andre@0: * Turns off use of a default responder when OCSP checking. andre@0: * (Does nothing if use of a default responder is not enabled.) andre@0: * INPUTS: andre@0: * CERTCertDBHandle *handle andre@0: * Cert database on which OCSP checking should stop using a default andre@0: * responder. andre@0: * RETURN: andre@0: * Returns SECFailure if an error occurred; SECSuccess otherwise. andre@0: * Errors very unlikely (like random memory corruption...). andre@0: */ andre@0: SECStatus andre@0: CERT_DisableOCSPDefaultResponder(CERTCertDBHandle *handle) andre@0: { andre@0: CERTStatusConfig *statusConfig; andre@0: ocspCheckingContext *statusContext; andre@0: CERTCertificate *tmpCert; andre@0: andre@0: if (handle == NULL) { andre@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); andre@0: return SECFailure; andre@0: } andre@0: andre@0: statusConfig = CERT_GetStatusConfig(handle); andre@0: if (statusConfig == NULL) andre@0: return SECSuccess; andre@0: andre@0: statusContext = ocsp_GetCheckingContext(handle); andre@0: PORT_Assert(statusContext != NULL); andre@0: if (statusContext == NULL) andre@0: return SECFailure; andre@0: andre@0: tmpCert = statusContext->defaultResponderCert; andre@0: if (tmpCert) { andre@0: statusContext->defaultResponderCert = NULL; andre@0: CERT_DestroyCertificate(tmpCert); andre@0: /* we don't allow a mix of cache entries from different responders */ andre@0: CERT_ClearOCSPCache(); andre@0: } andre@0: andre@0: /* andre@0: * Finally, record the fact. andre@0: */ andre@0: statusContext->useDefaultResponder = PR_FALSE; andre@0: return SECSuccess; andre@0: } andre@0: andre@0: SECStatus andre@0: CERT_ForcePostMethodForOCSP(PRBool forcePost) andre@0: { andre@0: if (!OCSP_Global.monitor) { andre@0: PORT_SetError(SEC_ERROR_NOT_INITIALIZED); andre@0: return SECFailure; andre@0: } andre@0: andre@0: PR_EnterMonitor(OCSP_Global.monitor); andre@0: OCSP_Global.forcePost = forcePost; andre@0: PR_ExitMonitor(OCSP_Global.monitor); andre@0: andre@0: return SECSuccess; andre@0: } andre@0: andre@0: SECStatus andre@0: CERT_GetOCSPResponseStatus(CERTOCSPResponse *response) andre@0: { andre@0: PORT_Assert(response); andre@0: if (response->statusValue == ocspResponse_successful) andre@0: return SECSuccess; andre@0: andre@0: switch (response->statusValue) { andre@0: case ocspResponse_malformedRequest: andre@0: PORT_SetError(SEC_ERROR_OCSP_MALFORMED_REQUEST); andre@0: break; andre@0: case ocspResponse_internalError: andre@0: PORT_SetError(SEC_ERROR_OCSP_SERVER_ERROR); andre@0: break; andre@0: case ocspResponse_tryLater: andre@0: PORT_SetError(SEC_ERROR_OCSP_TRY_SERVER_LATER); andre@0: break; andre@0: case ocspResponse_sigRequired: andre@0: /* XXX We *should* retry with a signature, if possible. */ andre@0: PORT_SetError(SEC_ERROR_OCSP_REQUEST_NEEDS_SIG); andre@0: break; andre@0: case ocspResponse_unauthorized: andre@0: PORT_SetError(SEC_ERROR_OCSP_UNAUTHORIZED_REQUEST); andre@0: break; andre@0: case ocspResponse_unused: andre@0: default: andre@0: PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_RESPONSE_STATUS); andre@0: break; andre@0: } andre@0: return SECFailure; andre@0: }