]> granicus.if.org Git - apache/blob - modules/ssl/ssl_util_stapling.c
Support for OpenSSL 1.1.0:
[apache] / modules / ssl / ssl_util_stapling.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*                      _             _
18  *  _ __ ___   ___   __| |    ___ ___| |  mod_ssl
19  * | '_ ` _ \ / _ \ / _` |   / __/ __| |  Apache Interface to OpenSSL
20  * | | | | | | (_) | (_| |   \__ \__ \ |
21  * |_| |_| |_|\___/ \__,_|___|___/___/_|
22  *                      |_____|
23  *  ssl_stapling.c
24  *  OCSP Stapling Support
25  */
26                              /* ``Where's the spoons?
27                                   Where's the spoons?
28                                   Where's the bloody spoons?''
29                                             -- Alexei Sayle          */
30
31 #include "ssl_private.h"
32 #include "ap_mpm.h"
33 #include "apr_thread_mutex.h"
34
35 #ifdef HAVE_OCSP_STAPLING
36
37 static int stapling_cache_mutex_on(server_rec *s);
38 static int stapling_cache_mutex_off(server_rec *s);
39
40 /**
41  * Maxiumum OCSP stapling response size. This should be the response for a
42  * single certificate and will typically include the responder certificate chain
43  * so 10K should be more than enough.
44  *
45  */
46
47 #define MAX_STAPLING_DER 10240
48
49 /* Cached info stored in the global stapling_certinfo hash. */
50 typedef struct {
51     /* Index in session cache (SHA-1 digest of DER encoded certificate) */
52     UCHAR idx[SHA_DIGEST_LENGTH];
53     /* Certificate ID for OCSP request */
54     OCSP_CERTID *cid;
55     /* URI of the OCSP responder */
56     char *uri;
57 } certinfo;
58
59 static apr_status_t ssl_stapling_certid_free(void *data)
60 {
61     OCSP_CERTID *cid = data;
62
63     if (cid) {
64         OCSP_CERTID_free(cid);
65     }
66
67     return APR_SUCCESS;
68 }
69
70 static apr_hash_t *stapling_certinfo;
71
72 void ssl_stapling_certinfo_hash_init(apr_pool_t *p)
73 {
74     stapling_certinfo = apr_hash_make(p);
75 }
76
77 static X509 *stapling_get_issuer(modssl_ctx_t *mctx, X509 *x)
78 {
79     X509 *issuer = NULL;
80     int i;
81     X509_STORE *st = SSL_CTX_get_cert_store(mctx->ssl_ctx);
82     X509_STORE_CTX *inctx;
83     STACK_OF(X509) *extra_certs = NULL;
84
85 #ifdef OPENSSL_NO_SSL_INTERN
86     SSL_CTX_get_extra_chain_certs(mctx->ssl_ctx, &extra_certs);
87 #else
88     extra_certs = mctx->ssl_ctx->extra_certs;
89 #endif
90
91     for (i = 0; i < sk_X509_num(extra_certs); i++) {
92         issuer = sk_X509_value(extra_certs, i);
93         if (X509_check_issued(issuer, x) == X509_V_OK) {
94 #if OPENSSL_VERSION_NUMBER < 0x10100000L
95             CRYPTO_add(&issuer->references, 1, CRYPTO_LOCK_X509);
96 #else
97             X509_up_ref(issuer);
98 #endif
99             return issuer;
100         }
101     }
102
103     inctx = X509_STORE_CTX_new();
104     if (!X509_STORE_CTX_init(inctx, st, NULL, NULL))
105         return 0;
106     if (X509_STORE_CTX_get1_issuer(&issuer, inctx, x) <= 0)
107         issuer = NULL;
108     X509_STORE_CTX_cleanup(inctx);
109     X509_STORE_CTX_free(inctx);
110     return issuer;
111 }
112
113 int ssl_stapling_init_cert(server_rec *s, apr_pool_t *p, apr_pool_t *ptemp,
114                            modssl_ctx_t *mctx, X509 *x)
115 {
116     UCHAR idx[SHA_DIGEST_LENGTH];
117     certinfo *cinf = NULL;
118     X509 *issuer = NULL;
119     OCSP_CERTID *cid = NULL;
120     STACK_OF(OPENSSL_STRING) *aia = NULL;
121
122     if ((x == NULL) || (X509_digest(x, EVP_sha1(), idx, NULL) != 1))
123         return 0;
124
125     cinf = apr_hash_get(stapling_certinfo, idx, sizeof(idx));
126     if (cinf) {
127         /* 
128          * We already parsed the certificate, and no OCSP URI was found.
129          * The certificate might be used for multiple vhosts, though,
130          * so we check for a ForceURL for this vhost.
131          */
132         if (!cinf->uri && !mctx->stapling_force_url) {
133             ssl_log_xerror(SSLLOG_MARK, APLOG_ERR, 0, ptemp, s, x,
134                            APLOGNO(02814) "ssl_stapling_init_cert: no OCSP URI "
135                            "in certificate and no SSLStaplingForceURL "
136                            "configured for server %s", mctx->sc->vhost_id);
137             return 0;
138         }
139         return 1;
140     }
141
142     if (!(issuer = stapling_get_issuer(mctx, x))) {
143         ssl_log_xerror(SSLLOG_MARK, APLOG_ERR, 0, ptemp, s, x, APLOGNO(02217)
144                        "ssl_stapling_init_cert: can't retrieve issuer "
145                        "certificate!");
146         return 0;
147     }
148
149     cid = OCSP_cert_to_id(NULL, x, issuer);
150     X509_free(issuer);
151     if (!cid) {
152         ssl_log_xerror(SSLLOG_MARK, APLOG_ERR, 0, ptemp, s, x, APLOGNO(02815)
153                        "ssl_stapling_init_cert: can't create CertID "
154                        "for OCSP request");
155         return 0;
156     }
157
158     aia = X509_get1_ocsp(x);
159     if (!aia && !mctx->stapling_force_url) {
160         OCSP_CERTID_free(cid);
161         ssl_log_xerror(SSLLOG_MARK, APLOG_ERR, 0, ptemp, s, x,
162                        APLOGNO(02218) "ssl_stapling_init_cert: no OCSP URI "
163                        "in certificate and no SSLStaplingForceURL set");
164         return 0;
165     }
166
167     /* At this point, we have determined that there's something to store */
168     cinf = apr_pcalloc(p, sizeof(certinfo));
169     memcpy (cinf->idx, idx, sizeof(idx));
170     cinf->cid = cid;
171     /* make sure cid is also freed at pool cleanup */
172     apr_pool_cleanup_register(p, cid, ssl_stapling_certid_free,
173                               apr_pool_cleanup_null);
174     if (aia) {
175        /* allocate uri from the pconf pool */
176        cinf->uri = apr_pstrdup(p, sk_OPENSSL_STRING_value(aia, 0));
177        X509_email_free(aia);
178     }
179
180     ssl_log_xerror(SSLLOG_MARK, APLOG_TRACE1, 0, ptemp, s, x,
181                    "ssl_stapling_init_cert: storing certinfo for server %s",
182                    mctx->sc->vhost_id);
183
184     apr_hash_set(stapling_certinfo, cinf->idx, sizeof(cinf->idx), cinf);
185
186     return 1;
187 }
188
189 static certinfo *stapling_get_certinfo(server_rec *s, modssl_ctx_t *mctx,
190                                         SSL *ssl)
191 {
192     certinfo *cinf;
193     X509 *x;
194     UCHAR idx[SHA_DIGEST_LENGTH];
195     x = SSL_get_certificate(ssl);
196     if ((x == NULL) || (X509_digest(x, EVP_sha1(), idx, NULL) != 1))
197         return NULL;
198     cinf = apr_hash_get(stapling_certinfo, idx, sizeof(idx));
199     if (cinf && cinf->cid)
200         return cinf;
201     ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(01926)
202                  "stapling_get_certinfo: stapling not supported for certificate");
203     return NULL;
204 }
205
206 /*
207  * OCSP response caching code. The response is preceded by a flag value
208  * which indicates whether the response was invalid when it was stored.
209  * the purpose of this flag is to avoid repeated queries to a server
210  * which has given an invalid response while allowing a response which
211  * has subsequently become invalid to be retried immediately.
212  *
213  * The key for the cache is the hash of the certificate the response
214  * is for.
215  */
216 static BOOL stapling_cache_response(server_rec *s, modssl_ctx_t *mctx,
217                                     OCSP_RESPONSE *rsp, certinfo *cinf,
218                                     BOOL ok, apr_pool_t *pool)
219 {
220     SSLModConfigRec *mc = myModConfig(s);
221     unsigned char resp_der[MAX_STAPLING_DER]; /* includes one-byte flag + response */
222     unsigned char *p;
223     int resp_derlen, stored_len;
224     BOOL rv;
225     apr_time_t expiry;
226
227     resp_derlen = i2d_OCSP_RESPONSE(rsp, NULL);
228
229     if (resp_derlen <= 0) {
230         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01927)
231                      "OCSP stapling response encode error??");
232         return FALSE;
233     }
234
235     stored_len = resp_derlen + 1; /* response + ok flag */
236     if (stored_len > sizeof resp_der) {
237         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01928)
238                      "OCSP stapling response too big (%u bytes)", resp_derlen);
239         return FALSE;
240     }
241
242     p = resp_der;
243
244     /* TODO: potential optimization; _timeout members as apr_interval_time_t */
245     if (ok == TRUE) {
246         *p++ = 1;
247         expiry = apr_time_from_sec(mctx->stapling_cache_timeout);
248     }
249     else {
250         *p++ = 0;
251         expiry = apr_time_from_sec(mctx->stapling_errcache_timeout);
252     }
253
254     expiry += apr_time_now();
255
256     i2d_OCSP_RESPONSE(rsp, &p);
257
258     if (mc->stapling_cache->flags & AP_SOCACHE_FLAG_NOTMPSAFE)
259         stapling_cache_mutex_on(s);
260     rv = mc->stapling_cache->store(mc->stapling_cache_context, s,
261                                    cinf->idx, sizeof(cinf->idx),
262                                    expiry, resp_der, stored_len, pool);
263     if (mc->stapling_cache->flags & AP_SOCACHE_FLAG_NOTMPSAFE)
264         stapling_cache_mutex_off(s);
265     if (rv != APR_SUCCESS) {
266         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01929)
267                      "stapling_cache_response: OCSP response session store error!");
268         return FALSE;
269     }
270
271     return TRUE;
272 }
273
274 static void stapling_get_cached_response(server_rec *s, OCSP_RESPONSE **prsp,
275                                          BOOL *pok, certinfo *cinf,
276                                          apr_pool_t *pool)
277 {
278     SSLModConfigRec *mc = myModConfig(s);
279     apr_status_t rv;
280     OCSP_RESPONSE *rsp;
281     unsigned char resp_der[MAX_STAPLING_DER];
282     const unsigned char *p;
283     unsigned int resp_derlen = MAX_STAPLING_DER;
284
285     if (mc->stapling_cache->flags & AP_SOCACHE_FLAG_NOTMPSAFE)
286         stapling_cache_mutex_on(s);
287     rv = mc->stapling_cache->retrieve(mc->stapling_cache_context, s,
288                                       cinf->idx, sizeof(cinf->idx),
289                                       resp_der, &resp_derlen, pool);
290     if (mc->stapling_cache->flags & AP_SOCACHE_FLAG_NOTMPSAFE)
291         stapling_cache_mutex_off(s);
292     if (rv != APR_SUCCESS) {
293         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01930)
294                      "stapling_get_cached_response: cache miss");
295         return;
296     }
297     if (resp_derlen <= 1) {
298         /* should-not-occur; must have at least valid-when-stored flag +
299          * OCSPResponseStatus
300          */
301         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01931)
302                      "stapling_get_cached_response: response length invalid??");
303         return;
304     }
305     p = resp_der;
306     if (*p) /* valid when stored */
307         *pok = TRUE;
308     else
309         *pok = FALSE;
310     p++;
311     resp_derlen--;
312     rsp = d2i_OCSP_RESPONSE(NULL, &p, resp_derlen);
313     if (!rsp) {
314         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01932)
315                      "stapling_get_cached_response: response parse error??");
316         return;
317     }
318     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01933)
319                  "stapling_get_cached_response: cache hit");
320
321     *prsp = rsp;
322 }
323
324 static int stapling_set_response(SSL *ssl, OCSP_RESPONSE *rsp)
325 {
326     int rspderlen;
327     unsigned char *rspder = NULL;
328
329     rspderlen = i2d_OCSP_RESPONSE(rsp, &rspder);
330     if (rspderlen <= 0)
331         return 0;
332     SSL_set_tlsext_status_ocsp_resp(ssl, rspder, rspderlen);
333     return 1;
334 }
335
336 static int stapling_check_response(server_rec *s, modssl_ctx_t *mctx,
337                                    certinfo *cinf, OCSP_RESPONSE *rsp,
338                                    BOOL *pok)
339 {
340     int status = V_OCSP_CERTSTATUS_UNKNOWN;
341     int reason = OCSP_REVOKED_STATUS_NOSTATUS;
342     OCSP_BASICRESP *bs = NULL;
343     ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
344     int response_status = OCSP_response_status(rsp);
345     int rv = SSL_TLSEXT_ERR_OK;
346
347     if (pok)
348         *pok = FALSE;
349     /* Check to see if response is an error. If so we automatically accept
350      * it because it would have expired from the cache if it was time to
351      * retry.
352      */
353     if (response_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
354         if (mctx->stapling_return_errors)
355             return SSL_TLSEXT_ERR_OK;
356         else
357             return SSL_TLSEXT_ERR_NOACK;
358     }
359
360     bs = OCSP_response_get1_basic(rsp);
361     if (bs == NULL) {
362         /* If we can't parse response just pass it to client */
363         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01934)
364                      "stapling_check_response: Error Parsing Response!");
365         return SSL_TLSEXT_ERR_OK;
366     }
367
368     if (!OCSP_resp_find_status(bs, cinf->cid, &status, &reason, &rev,
369                                &thisupd, &nextupd)) {
370         /* If ID not present pass back to client (if configured so) */
371         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01935)
372                      "stapling_check_response: certificate ID not present in response!");
373         if (mctx->stapling_return_errors == FALSE)
374             rv = SSL_TLSEXT_ERR_NOACK;
375     }
376     else {
377         if (OCSP_check_validity(thisupd, nextupd,
378                                 mctx->stapling_resptime_skew,
379                                 mctx->stapling_resp_maxage)) {
380             if (pok)
381                 *pok = TRUE;
382         }
383         else {
384             /* If pok is not NULL response was direct from a responder and
385              * the times should be valide. If pok is NULL the response was
386              * retrieved from cache and it is expected to subsequently expire
387              */
388             if (pok) {
389                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01936)
390                              "stapling_check_response: response times invalid");
391             }
392             else {
393                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01937)
394                              "stapling_check_response: cached response expired");
395             }
396
397             rv = SSL_TLSEXT_ERR_NOACK;
398         }
399
400         if (status != V_OCSP_CERTSTATUS_GOOD) {
401             char snum[MAX_STRING_LEN] = { '\0' };
402             BIO *bio = BIO_new(BIO_s_mem());
403
404             if (bio) {
405                 int n;
406                 ASN1_INTEGER *pserial;
407                 OCSP_id_get0_info(NULL, NULL, NULL, &pserial, cinf->cid);
408                 if ((i2a_ASN1_INTEGER(bio, pserial) != -1) &&
409                     ((n = BIO_read(bio, snum, sizeof snum - 1)) > 0))
410                     snum[n] = '\0';
411                 BIO_free(bio);
412             }
413
414             ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(02969)
415                          "stapling_check_response: response has certificate "
416                          "status %s (reason: %s) for serial number %s",
417                          OCSP_cert_status_str(status),
418                          (reason != OCSP_REVOKED_STATUS_NOSTATUS) ?
419                          OCSP_crl_reason_str(reason) : "n/a",
420                          snum[0] ? snum : "[n/a]");
421
422             if (mctx->stapling_return_errors == FALSE) {
423                 if (pok)
424                     *pok = FALSE;
425                 rv = SSL_TLSEXT_ERR_NOACK;
426             }
427         }
428     }
429
430     OCSP_BASICRESP_free(bs);
431
432     return rv;
433 }
434
435 static BOOL stapling_renew_response(server_rec *s, modssl_ctx_t *mctx, SSL *ssl,
436                                     certinfo *cinf, OCSP_RESPONSE **prsp,
437                                     BOOL *pok, apr_pool_t *pool)
438 {
439     conn_rec *conn      = (conn_rec *)SSL_get_app_data(ssl);
440     apr_pool_t *vpool;
441     OCSP_REQUEST *req = NULL;
442     OCSP_CERTID *id = NULL;
443     STACK_OF(X509_EXTENSION) *exts;
444     int i;
445     BOOL rv = TRUE;
446     const char *ocspuri;
447     apr_uri_t uri;
448
449     *prsp = NULL;
450     /* Build up OCSP query from server certificate info */
451     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01938)
452                  "stapling_renew_response: querying responder");
453
454     req = OCSP_REQUEST_new();
455     if (!req)
456         goto err;
457     id = OCSP_CERTID_dup(cinf->cid);
458     if (!id)
459         goto err;
460     if (!OCSP_request_add0_id(req, id))
461         goto err;
462     id = NULL;
463     /* Add any extensions to the request */
464     SSL_get_tlsext_status_exts(ssl, &exts);
465     for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
466         X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
467         if (!OCSP_REQUEST_add_ext(req, ext, -1))
468             goto err;
469     }
470
471     if (mctx->stapling_force_url)
472         ocspuri = mctx->stapling_force_url;
473     else
474         ocspuri = cinf->uri;
475
476     if (!ocspuri) {
477         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(02621)
478                      "stapling_renew_response: no uri for responder");
479         rv = FALSE;
480         goto done;
481     }
482
483     /* Create a temporary pool to constrain memory use */
484     apr_pool_create(&vpool, conn->pool);
485
486     if (apr_uri_parse(vpool, ocspuri, &uri) != APR_SUCCESS) {
487         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01939)
488                      "stapling_renew_response: Error parsing uri %s",
489                       ocspuri);
490         rv = FALSE;
491         goto done;
492     }
493     else if (strcmp(uri.scheme, "http")) {
494         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01940)
495                      "stapling_renew_response: Unsupported uri %s", ocspuri);
496         rv = FALSE;
497         goto done;
498     }
499
500     if (!uri.port) {
501         uri.port = apr_uri_port_of_scheme(uri.scheme);
502     }
503
504     *prsp = modssl_dispatch_ocsp_request(&uri, mctx->stapling_responder_timeout,
505                                          req, conn, vpool);
506
507     apr_pool_destroy(vpool);
508
509     if (!*prsp) {
510         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01941)
511                      "stapling_renew_response: responder error");
512         if (mctx->stapling_fake_trylater) {
513             *prsp = OCSP_response_create(OCSP_RESPONSE_STATUS_TRYLATER, NULL);
514         }
515         else {
516             goto done;
517         }
518     }
519     else {
520         int response_status = OCSP_response_status(*prsp);
521
522         if (response_status == OCSP_RESPONSE_STATUS_SUCCESSFUL) {
523             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01942)
524                         "stapling_renew_response: query response received");
525             stapling_check_response(s, mctx, cinf, *prsp, pok);
526             if (*pok == FALSE) {
527                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01943)
528                              "stapling_renew_response: error in retrieved response!");
529             }
530         }
531         else {
532             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01944)
533                          "stapling_renew_response: responder error %s",
534                          OCSP_response_status_str(response_status));
535             *pok = FALSE;
536         }
537     }
538     if (stapling_cache_response(s, mctx, *prsp, cinf, *pok, pool) == FALSE) {
539         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01945)
540                      "stapling_renew_response: error caching response!");
541     }
542
543 done:
544     if (id)
545         OCSP_CERTID_free(id);
546     if (req)
547         OCSP_REQUEST_free(req);
548     return rv;
549 err:
550     rv = FALSE;
551     goto done;
552 }
553
554 /*
555  * SSL stapling mutex operations. Similar to SSL mutex except mutexes are
556  * mandatory if stapling is enabled.
557  */
558 static int ssl_stapling_mutex_init(server_rec *s, apr_pool_t *p)
559 {
560     SSLModConfigRec *mc = myModConfig(s);
561     SSLSrvConfigRec *sc = mySrvConfig(s);
562     apr_status_t rv;
563
564     /* already init or stapling not enabled? */
565     if (mc->stapling_refresh_mutex || sc->server->stapling_enabled != TRUE) {
566         return TRUE;
567     }
568
569     /* need a cache mutex? */
570     if (mc->stapling_cache->flags & AP_SOCACHE_FLAG_NOTMPSAFE) {
571         if ((rv = ap_global_mutex_create(&mc->stapling_cache_mutex, NULL,
572                                          SSL_STAPLING_CACHE_MUTEX_TYPE, NULL, s,
573                                          s->process->pool, 0)) != APR_SUCCESS) {
574             return FALSE;
575         }
576     }
577
578     /* always need stapling_refresh_mutex */
579     if ((rv = ap_global_mutex_create(&mc->stapling_refresh_mutex, NULL,
580                                      SSL_STAPLING_REFRESH_MUTEX_TYPE, NULL, s,
581                                      s->process->pool, 0)) != APR_SUCCESS) {
582         return FALSE;
583     }
584
585     return TRUE;
586 }
587
588 static int stapling_mutex_reinit_helper(server_rec *s, apr_pool_t *p, 
589                                         apr_global_mutex_t **mutex,
590                                         const char *type)
591 {
592     apr_status_t rv;
593     const char *lockfile;
594
595     lockfile = apr_global_mutex_lockfile(*mutex);
596     if ((rv = apr_global_mutex_child_init(mutex,
597                                           lockfile, p)) != APR_SUCCESS) {
598         if (lockfile) {
599             ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, APLOGNO(01946)
600                          "Cannot reinit %s mutex with file `%s'",
601                          type, lockfile);
602         }
603         else {
604             ap_log_error(APLOG_MARK, APLOG_WARNING, rv, s, APLOGNO(01947)
605                          "Cannot reinit %s mutex", type);
606         }
607         return FALSE;
608     }
609     return TRUE;
610 }
611
612 int ssl_stapling_mutex_reinit(server_rec *s, apr_pool_t *p)
613 {
614     SSLModConfigRec *mc = myModConfig(s);
615
616     if (mc->stapling_cache_mutex != NULL
617         && stapling_mutex_reinit_helper(s, p, &mc->stapling_cache_mutex,
618                                         SSL_STAPLING_CACHE_MUTEX_TYPE) == FALSE) {
619         return FALSE;
620     }
621
622     if (mc->stapling_refresh_mutex != NULL
623         && stapling_mutex_reinit_helper(s, p, &mc->stapling_refresh_mutex,
624                                         SSL_STAPLING_REFRESH_MUTEX_TYPE) == FALSE) {
625         return FALSE;
626     }
627
628     return TRUE;
629 }
630
631 static int stapling_mutex_on(server_rec *s, apr_global_mutex_t *mutex,
632                              const char *name)
633 {
634     apr_status_t rv;
635
636     if ((rv = apr_global_mutex_lock(mutex)) != APR_SUCCESS) {
637         ap_log_error(APLOG_MARK, APLOG_WARNING, rv, s, APLOGNO(01948)
638                      "Failed to acquire OCSP %s lock", name);
639         return FALSE;
640     }
641     return TRUE;
642 }
643
644 static int stapling_mutex_off(server_rec *s, apr_global_mutex_t *mutex,
645                               const char *name)
646 {
647     apr_status_t rv;
648
649     if ((rv = apr_global_mutex_unlock(mutex)) != APR_SUCCESS) {
650         ap_log_error(APLOG_MARK, APLOG_WARNING, rv, s, APLOGNO(01949)
651                      "Failed to release OCSP %s lock", name);
652         return FALSE;
653     }
654     return TRUE;
655 }
656
657 static int stapling_cache_mutex_on(server_rec *s)
658 {
659     SSLModConfigRec *mc = myModConfig(s);
660
661     return stapling_mutex_on(s, mc->stapling_cache_mutex,
662                              SSL_STAPLING_CACHE_MUTEX_TYPE);
663 }
664
665 static int stapling_cache_mutex_off(server_rec *s)
666 {
667     SSLModConfigRec *mc = myModConfig(s);
668
669     return stapling_mutex_off(s, mc->stapling_cache_mutex,
670                               SSL_STAPLING_CACHE_MUTEX_TYPE);
671 }
672
673 static int stapling_refresh_mutex_on(server_rec *s)
674 {
675     SSLModConfigRec *mc = myModConfig(s);
676
677     return stapling_mutex_on(s, mc->stapling_refresh_mutex,
678                              SSL_STAPLING_REFRESH_MUTEX_TYPE);
679 }
680
681 static int stapling_refresh_mutex_off(server_rec *s)
682 {
683     SSLModConfigRec *mc = myModConfig(s);
684
685     return stapling_mutex_off(s, mc->stapling_refresh_mutex,
686                               SSL_STAPLING_REFRESH_MUTEX_TYPE);
687 }
688
689 static int get_and_check_cached_response(server_rec *s, modssl_ctx_t *mctx,
690                                          OCSP_RESPONSE **rsp, BOOL *pok,
691                                          certinfo *cinf, apr_pool_t *p)
692 {
693     BOOL ok;
694     int rv;
695
696     AP_DEBUG_ASSERT(*rsp == NULL);
697
698     /* Check to see if we already have a response for this certificate */
699     stapling_get_cached_response(s, rsp, &ok, cinf, p);
700
701     if (*rsp) {
702         /* see if response is acceptable */
703         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01953)
704                      "stapling_cb: retrieved cached response");
705         rv = stapling_check_response(s, mctx, cinf, *rsp, NULL);
706         if (rv == SSL_TLSEXT_ERR_ALERT_FATAL) {
707             OCSP_RESPONSE_free(*rsp);
708             *rsp = NULL;
709             return SSL_TLSEXT_ERR_ALERT_FATAL;
710         }
711         else if (rv == SSL_TLSEXT_ERR_NOACK) {
712             /* Error in response. If this error was not present when it was
713              * stored (i.e. response no longer valid) then it can be
714              * renewed straight away.
715              *
716              * If the error *was* present at the time it was stored then we
717              * don't renew the response straight away; we just wait for the
718              * cached response to expire.
719              */
720             if (ok) {
721                 OCSP_RESPONSE_free(*rsp);
722                 *rsp = NULL;
723             }
724             else if (!mctx->stapling_return_errors) {
725                 OCSP_RESPONSE_free(*rsp);
726                 *rsp = NULL;
727                 *pok = FALSE;
728                 return SSL_TLSEXT_ERR_NOACK;
729             }
730         }
731     }
732     return 0;
733 }
734
735 /* Certificate Status callback. This is called when a client includes a
736  * certificate status request extension.
737  *
738  * Check for cached responses in session cache. If valid send back to
739  * client.  If absent or no longer valid, query responder and update
740  * cache.
741  */
742 static int stapling_cb(SSL *ssl, void *arg)
743 {
744     conn_rec *conn      = (conn_rec *)SSL_get_app_data(ssl);
745     server_rec *s       = mySrvFromConn(conn);
746     SSLSrvConfigRec *sc = mySrvConfig(s);
747     SSLConnRec *sslconn = myConnConfig(conn);
748     modssl_ctx_t *mctx  = myCtxConfig(sslconn, sc);
749     certinfo *cinf = NULL;
750     OCSP_RESPONSE *rsp = NULL;
751     int rv;
752     BOOL ok = TRUE;
753
754     if (sc->server->stapling_enabled != TRUE) {
755         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01950)
756                      "stapling_cb: OCSP Stapling disabled");
757         return SSL_TLSEXT_ERR_NOACK;
758     }
759
760     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01951)
761                  "stapling_cb: OCSP Stapling callback called");
762
763     cinf = stapling_get_certinfo(s, mctx, ssl);
764     if (cinf == NULL) {
765         return SSL_TLSEXT_ERR_NOACK;
766     }
767
768     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01952)
769                  "stapling_cb: retrieved cached certificate data");
770
771     rv = get_and_check_cached_response(s, mctx, &rsp, &ok, cinf, conn->pool);
772     if (rv != 0) {
773         return rv;
774     }
775
776     if (rsp == NULL) {
777         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01954)
778                      "stapling_cb: renewing cached response");
779         stapling_refresh_mutex_on(s);
780         /* Maybe another request refreshed the OCSP response while this
781          * thread waited for the mutex.  Check again.
782          */
783         rv = get_and_check_cached_response(s, mctx, &rsp, &ok, cinf,
784                                            conn->pool);
785         if (rv != 0) {
786             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(03236)
787                          "stapling_cb: error checking for cached response "
788                          "after obtaining refresh mutex");
789             stapling_refresh_mutex_off(s);
790             return rv;
791         }
792         else if (rsp) {
793             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(03237)
794                          "stapling_cb: don't need to refresh cached response "
795                          "after obtaining refresh mutex");
796             stapling_refresh_mutex_off(s);
797         }
798         else {
799             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(03238)
800                          "stapling_cb: still must refresh cached response "
801                          "after obtaining refresh mutex");
802             rv = stapling_renew_response(s, mctx, ssl, cinf, &rsp, &ok,
803                                          conn->pool);
804             stapling_refresh_mutex_off(s);
805
806             if (rv == TRUE) {
807                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(03040)
808                              "stapling_cb: success renewing response");
809             }
810             else {
811                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01955)
812                              "stapling_cb: fatal error renewing response");
813                 return SSL_TLSEXT_ERR_ALERT_FATAL;
814             }
815         }
816     }
817
818     if (rsp && ((ok == TRUE) || (mctx->stapling_return_errors == TRUE))) {
819         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01956)
820                      "stapling_cb: setting response");
821         if (!stapling_set_response(ssl, rsp))
822             return SSL_TLSEXT_ERR_ALERT_FATAL;
823         return SSL_TLSEXT_ERR_OK;
824     }
825     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01957)
826                  "stapling_cb: no suitable response available");
827
828     return SSL_TLSEXT_ERR_NOACK;
829
830 }
831
832 apr_status_t modssl_init_stapling(server_rec *s, apr_pool_t *p,
833                                   apr_pool_t *ptemp, modssl_ctx_t *mctx)
834 {
835     SSL_CTX *ctx = mctx->ssl_ctx;
836     SSLModConfigRec *mc = myModConfig(s);
837
838     if (mc->stapling_cache == NULL) {
839         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01958)
840                      "SSLStapling: no stapling cache available");
841         return ssl_die(s);
842     }
843     if (ssl_stapling_mutex_init(s, ptemp) == FALSE) {
844         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01959)
845                      "SSLStapling: cannot initialise stapling mutex");
846         return ssl_die(s);
847     }
848     /* Set some default values for parameters if they are not set */
849     if (mctx->stapling_resptime_skew == UNSET) {
850         mctx->stapling_resptime_skew = 60 * 5;
851     }
852     if (mctx->stapling_cache_timeout == UNSET) {
853         mctx->stapling_cache_timeout = 3600;
854     }
855     if (mctx->stapling_return_errors == UNSET) {
856         mctx->stapling_return_errors = TRUE;
857     }
858     if (mctx->stapling_fake_trylater == UNSET) {
859         mctx->stapling_fake_trylater = TRUE;
860     }
861     if (mctx->stapling_errcache_timeout == UNSET) {
862         mctx->stapling_errcache_timeout = 600;
863     }
864     if (mctx->stapling_responder_timeout == UNSET) {
865         mctx->stapling_responder_timeout = 10 * APR_USEC_PER_SEC;
866     }
867     SSL_CTX_set_tlsext_status_cb(ctx, stapling_cb);
868     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01960) "OCSP stapling initialized");
869
870     return APR_SUCCESS;
871 }
872
873 #endif