]> granicus.if.org Git - apache/blob - modules/ssl/ssl_engine_kernel.c
4ca5931923076c48d5b24dc58f49dd84464cdb32
[apache] / modules / ssl / ssl_engine_kernel.c
1 /* Copyright 2001-2005 The Apache Software Foundation or its licensors, as
2  * applicable.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * 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_engine_kernel.c
24  *  The SSL engine kernel
25  */
26                              /* ``It took me fifteen years to discover
27                                   I had no talent for programming, but
28                                   I couldn't give it up because by that
29                                   time I was too famous.''
30                                             -- Unknown                */
31 #include "ssl_private.h"
32
33 static void ssl_configure_env(request_rec *r, SSLConnRec *sslconn);
34
35 /*
36  *  Post Read Request Handler
37  */
38 int ssl_hook_ReadReq(request_rec *r)
39 {
40     SSLConnRec *sslconn = myConnConfig(r->connection);
41     SSL *ssl;
42
43     if (!sslconn) {
44         return DECLINED;
45     }
46
47     if (sslconn->non_ssl_request) {
48         const char *errmsg;
49         char *thisurl;
50         char *thisport = "";
51         int port = ap_get_server_port(r);
52
53         if (!ap_is_default_port(port, r)) {
54             thisport = apr_psprintf(r->pool, ":%u", port);
55         }
56
57         thisurl = ap_escape_html(r->pool,
58                                  apr_psprintf(r->pool, "https://%s%s/",
59                                               ap_get_server_name(r),
60                                               thisport));
61
62         errmsg = apr_psprintf(r->pool,
63                               "Reason: You're speaking plain HTTP "
64                               "to an SSL-enabled server port.<br />\n"
65                               "Instead use the HTTPS scheme to access "
66                               "this URL, please.<br />\n"
67                               "<blockquote>Hint: "
68                               "<a href=\"%s\"><b>%s</b></a></blockquote>",
69                               thisurl, thisurl);
70
71         apr_table_setn(r->notes, "error-notes", errmsg);
72
73         /* Now that we have caught this error, forget it. we are done
74          * with using SSL on this request.
75          */
76         sslconn->non_ssl_request = 0;
77
78
79         return HTTP_BAD_REQUEST;
80     }
81
82     /*
83      * Get the SSL connection structure and perform the
84      * delayed interlinking from SSL back to request_rec
85      */
86     ssl = sslconn->ssl;
87     if (!ssl) {
88         return DECLINED;
89     }
90     SSL_set_app_data2(ssl, r);
91
92     /*
93      * Log information about incoming HTTPS requests
94      */
95     if (r->server->loglevel >= APLOG_INFO && ap_is_initial_req(r)) {
96         ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
97                      "%s HTTPS request received for child %ld (server %s)",
98                      (r->connection->keepalives <= 0 ?
99                      "Initial (No.1)" :
100                      apr_psprintf(r->pool, "Subsequent (No.%d)",
101                                   r->connection->keepalives+1)),
102                      r->connection->id,
103                      ssl_util_vhostid(r->pool, r->server));
104     }
105
106     /* SetEnvIf ssl-*-shutdown flags can only be per-server,
107      * so they won't change across keepalive requests
108      */
109     if (sslconn->shutdown_type == SSL_SHUTDOWN_TYPE_UNSET) {
110         ssl_configure_env(r, sslconn);
111     }
112
113     return DECLINED;
114 }
115
116 /*
117  * Move SetEnvIf information from request_rec to conn_rec/BUFF
118  * to allow the close connection handler to use them.
119  */
120
121 static void ssl_configure_env(request_rec *r, SSLConnRec *sslconn)
122 {
123     int i;
124     const apr_array_header_t *arr = apr_table_elts(r->subprocess_env);
125     const apr_table_entry_t *elts = (const apr_table_entry_t *)arr->elts;
126
127     sslconn->shutdown_type = SSL_SHUTDOWN_TYPE_STANDARD;
128
129     for (i = 0; i < arr->nelts; i++) {
130         const char *key = elts[i].key;
131
132         switch (*key) {
133           case 's':
134             /* being case-sensitive here.
135              * and not checking for the -shutdown since these are the only
136              * SetEnvIf "flags" we support
137              */
138             if (!strncmp(key+1, "sl-", 3)) {
139                 key += 4;
140                 if (!strncmp(key, "unclean", 7)) {
141                     sslconn->shutdown_type = SSL_SHUTDOWN_TYPE_UNCLEAN;
142                 }
143                 else if (!strncmp(key, "accurate", 8)) {
144                     sslconn->shutdown_type = SSL_SHUTDOWN_TYPE_ACCURATE;
145                 }
146                 return; /* should only ever be one ssl-*-shutdown */
147             }
148             break;
149         }
150     }
151 }
152
153 /*
154  *  Access Handler
155  */
156 int ssl_hook_Access(request_rec *r)
157 {
158     SSLDirConfigRec *dc = myDirConfig(r);
159     SSLSrvConfigRec *sc = mySrvConfig(r->server);
160     SSLConnRec *sslconn = myConnConfig(r->connection);
161     SSL *ssl            = sslconn ? sslconn->ssl : NULL;
162     SSL_CTX *ctx = NULL;
163     apr_array_header_t *requires;
164     ssl_require_t *ssl_requires;
165     char *cp;
166     int ok, i;
167     BOOL renegotiate = FALSE, renegotiate_quick = FALSE;
168     X509 *cert;
169     X509 *peercert;
170     X509_STORE *cert_store = NULL;
171     X509_STORE_CTX cert_store_ctx;
172     STACK_OF(SSL_CIPHER) *cipher_list_old = NULL, *cipher_list = NULL;
173     SSL_CIPHER *cipher = NULL;
174     int depth, verify_old, verify, n;
175
176     if (ssl) {
177         ctx = SSL_get_SSL_CTX(ssl);
178     }
179
180     /*
181      * Support for SSLRequireSSL directive
182      */
183     if (dc->bSSLRequired && !ssl) {
184         if (sc->enabled == SSL_ENABLED_OPTIONAL) {
185             /* This vhost was configured for optional SSL, just tell the
186              * client that we need to upgrade.
187              */
188             apr_table_setn(r->err_headers_out, "Upgrade", "TLS/1.0, HTTP/1.1");
189             apr_table_setn(r->err_headers_out, "Connection", "Upgrade");
190
191             return HTTP_UPGRADE_REQUIRED;
192         }
193
194         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
195                       "access to %s failed, reason: %s",
196                       r->filename, "SSL connection required");
197
198         /* remember forbidden access for strict require option */
199         apr_table_setn(r->notes, "ssl-access-forbidden", "1");
200
201         return HTTP_FORBIDDEN;
202     }
203
204     /*
205      * Check to see whether SSL is in use; if it's not, then no
206      * further access control checks are relevant.  (the test for
207      * sc->enabled is probably strictly unnecessary)
208      */
209     if (sc->enabled == SSL_ENABLED_FALSE || !ssl) {
210         return DECLINED;
211     }
212
213     /*
214      * Support for per-directory reconfigured SSL connection parameters.
215      *
216      * This is implemented by forcing an SSL renegotiation with the
217      * reconfigured parameter suite. But Apache's internal API processing
218      * makes our life very hard here, because when internal sub-requests occur
219      * we nevertheless should avoid multiple unnecessary SSL handshakes (they
220      * require extra network I/O and especially time to perform).
221      *
222      * But the optimization for filtering out the unnecessary handshakes isn't
223      * obvious and trivial.  Especially because while Apache is in its
224      * sub-request processing the client could force additional handshakes,
225      * too. And these take place perhaps without our notice. So the only
226      * possibility is to explicitly _ask_ OpenSSL whether the renegotiation
227      * has to be performed or not. It has to performed when some parameters
228      * which were previously known (by us) are not those we've now
229      * reconfigured (as known by OpenSSL) or (in optimized way) at least when
230      * the reconfigured parameter suite is stronger (more restrictions) than
231      * the currently active one.
232      */
233
234     /*
235      * Override of SSLCipherSuite
236      *
237      * We provide two options here:
238      *
239      * o The paranoid and default approach where we force a renegotiation when
240      *   the cipher suite changed in _any_ way (which is straight-forward but
241      *   often forces renegotiations too often and is perhaps not what the
242      *   user actually wanted).
243      *
244      * o The optimized and still secure way where we force a renegotiation
245      *   only if the currently active cipher is no longer contained in the
246      *   reconfigured/new cipher suite. Any other changes are not important
247      *   because it's the servers choice to select a cipher from the ones the
248      *   client supports. So as long as the current cipher is still in the new
249      *   cipher suite we're happy. Because we can assume we would have
250      *   selected it again even when other (better) ciphers exists now in the
251      *   new cipher suite. This approach is fine because the user explicitly
252      *   has to enable this via ``SSLOptions +OptRenegotiate''. So we do no
253      *   implicit optimizations.
254      */
255     if (dc->szCipherSuite) {
256         /* remember old state */
257
258         if (dc->nOptions & SSL_OPT_OPTRENEGOTIATE) {
259             cipher = SSL_get_current_cipher(ssl);
260         }
261         else {
262             cipher_list_old = (STACK_OF(SSL_CIPHER) *)SSL_get_ciphers(ssl);
263
264             if (cipher_list_old) {
265                 cipher_list_old = sk_SSL_CIPHER_dup(cipher_list_old);
266             }
267         }
268
269         /* configure new state */
270         if (!modssl_set_cipher_list(ssl, dc->szCipherSuite)) {
271             ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
272                          r->server,
273                          "Unable to reconfigure (per-directory) "
274                          "permitted SSL ciphers");
275             ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, r->server);
276
277             if (cipher_list_old) {
278                 sk_SSL_CIPHER_free(cipher_list_old);
279             }
280
281             return HTTP_FORBIDDEN;
282         }
283
284         /* determine whether a renegotiation has to be forced */
285         cipher_list = (STACK_OF(SSL_CIPHER) *)SSL_get_ciphers(ssl);
286
287         if (dc->nOptions & SSL_OPT_OPTRENEGOTIATE) {
288             /* optimized way */
289             if ((!cipher && cipher_list) ||
290                 (cipher && !cipher_list))
291             {
292                 renegotiate = TRUE;
293             }
294             else if (cipher && cipher_list &&
295                      (sk_SSL_CIPHER_find(cipher_list, cipher) < 0))
296             {
297                 renegotiate = TRUE;
298             }
299         }
300         else {
301             /* paranoid way */
302             if ((!cipher_list_old && cipher_list) ||
303                 (cipher_list_old && !cipher_list))
304             {
305                 renegotiate = TRUE;
306             }
307             else if (cipher_list_old && cipher_list) {
308                 for (n = 0;
309                      !renegotiate && (n < sk_SSL_CIPHER_num(cipher_list));
310                      n++)
311                 {
312                     SSL_CIPHER *value = sk_SSL_CIPHER_value(cipher_list, n);
313
314                     if (sk_SSL_CIPHER_find(cipher_list_old, value) < 0) {
315                         renegotiate = TRUE;
316                     }
317                 }
318
319                 for (n = 0;
320                      !renegotiate && (n < sk_SSL_CIPHER_num(cipher_list_old));
321                      n++)
322                 {
323                     SSL_CIPHER *value = sk_SSL_CIPHER_value(cipher_list_old, n);
324
325                     if (sk_SSL_CIPHER_find(cipher_list, value) < 0) {
326                         renegotiate = TRUE;
327                     }
328                 }
329             }
330         }
331
332         /* cleanup */
333         if (cipher_list_old) {
334             sk_SSL_CIPHER_free(cipher_list_old);
335         }
336
337         /* tracing */
338         if (renegotiate) {
339             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
340                          "Reconfigured cipher suite will force renegotiation");
341         }
342     }
343
344     /*
345      * override of SSLVerifyDepth
346      *
347      * The depth checks are handled by us manually inside the verify callback
348      * function and not by OpenSSL internally (and our function is aware of
349      * both the per-server and per-directory contexts). So we cannot ask
350      * OpenSSL about the currently verify depth. Instead we remember it in our
351      * ap_ctx attached to the SSL* of OpenSSL.  We've to force the
352      * renegotiation if the reconfigured/new verify depth is less than the
353      * currently active/remembered verify depth (because this means more
354      * restriction on the certificate chain).
355      */
356     if (dc->nVerifyDepth != UNSET) {
357         /* XXX: doesnt look like sslconn->verify_depth is actually used */
358         if (!(n = sslconn->verify_depth)) {
359             sslconn->verify_depth = n = sc->server->auth.verify_depth;
360         }
361
362         /* determine whether a renegotiation has to be forced */
363         if (dc->nVerifyDepth < n) {
364             renegotiate = TRUE;
365             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
366                          "Reduced client verification depth will force "
367                          "renegotiation");
368         }
369     }
370
371     /*
372      * override of SSLVerifyClient
373      *
374      * We force a renegotiation if the reconfigured/new verify type is
375      * stronger than the currently active verify type.
376      *
377      * The order is: none << optional_no_ca << optional << require
378      *
379      * Additionally the following optimization is possible here: When the
380      * currently active verify type is "none" but a client certificate is
381      * already known/present, it's enough to manually force a client
382      * verification but at least skip the I/O-intensive renegotation
383      * handshake.
384      */
385     if (dc->nVerifyClient != SSL_CVERIFY_UNSET) {
386         /* remember old state */
387         verify_old = SSL_get_verify_mode(ssl);
388         /* configure new state */
389         verify = SSL_VERIFY_NONE;
390
391         if (dc->nVerifyClient == SSL_CVERIFY_REQUIRE) {
392             verify |= SSL_VERIFY_PEER_STRICT;
393         }
394
395         if ((dc->nVerifyClient == SSL_CVERIFY_OPTIONAL) ||
396             (dc->nVerifyClient == SSL_CVERIFY_OPTIONAL_NO_CA))
397         {
398             verify |= SSL_VERIFY_PEER;
399         }
400
401         modssl_set_verify(ssl, verify, ssl_callback_SSLVerify);
402         SSL_set_verify_result(ssl, X509_V_OK);
403
404         /* determine whether we've to force a renegotiation */
405         if (!renegotiate && verify != verify_old) {
406             if (((verify_old == SSL_VERIFY_NONE) &&
407                  (verify     != SSL_VERIFY_NONE)) ||
408
409                 (!(verify_old & SSL_VERIFY_PEER) &&
410                   (verify     & SSL_VERIFY_PEER)) ||
411
412                 (!(verify_old & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) &&
413                   (verify     & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)))
414             {
415                 renegotiate = TRUE;
416                 /* optimization */
417
418                 if ((dc->nOptions & SSL_OPT_OPTRENEGOTIATE) &&
419                     (verify_old == SSL_VERIFY_NONE) &&
420                     ((peercert = SSL_get_peer_certificate(ssl)) != NULL))
421                 {
422                     renegotiate_quick = TRUE;
423                     X509_free(peercert);
424                 }
425
426                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
427                              r->server,
428                              "Changed client verification type will force "
429                              "%srenegotiation",
430                              renegotiate_quick ? "quick " : "");
431              }
432         }
433     }
434
435     /*
436      * override SSLCACertificateFile & SSLCACertificatePath
437      * This is only enabled if the SSL_set_cert_store() function
438      * is available in the ssl library.  the 1.x based mod_ssl
439      * used SSL_CTX_set_cert_store which is not thread safe.
440      */
441
442 #ifdef HAVE_SSL_SET_CERT_STORE
443     /*
444      * check if per-dir and per-server config field are not the same.
445      * if f is defined in per-dir and not defined in per-server
446      * or f is defined in both but not the equal ...
447      */
448 #define MODSSL_CFG_NE(f) \
449      (dc->f && (!sc->f || (sc->f && strNE(dc->f, sc->f))))
450
451 #define MODSSL_CFG_CA(f) \
452      (dc->f ? dc->f : sc->f)
453
454     if (MODSSL_CFG_NE(szCACertificateFile) ||
455         MODSSL_CFG_NE(szCACertificatePath))
456     {
457         STACK_OF(X509_NAME) *ca_list;
458         const char *ca_file = MODSSL_CFG_CA(szCACertificateFile);
459         const char *ca_path = MODSSL_CFG_CA(szCACertificatePath);
460
461         cert_store = X509_STORE_new();
462
463         if (!X509_STORE_load_locations(cert_store, ca_file, ca_path)) {
464             ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
465                          "Unable to reconfigure verify locations "
466                          "for client authentication");
467             ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, r->server);
468
469             X509_STORE_free(cert_store);
470
471             return HTTP_FORBIDDEN;
472         }
473
474         /* SSL_free will free cert_store */
475         SSL_set_cert_store(ssl, cert_store);
476
477         if (!(ca_list = ssl_init_FindCAList(r->server, r->pool,
478                                             ca_file, ca_path)))
479         {
480             ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
481                          "Unable to determine list of available "
482                          "CA certificates for client authentication");
483
484             return HTTP_FORBIDDEN;
485         }
486
487         SSL_set_client_CA_list(ssl, ca_list);
488         renegotiate = TRUE;
489
490         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
491                      "Changed client verification locations will force "
492                      "renegotiation");
493     }
494 #endif /* HAVE_SSL_SET_CERT_STORE */
495
496     /* If a renegotiation is now required for this location, and the
497      * request includes a message body (and the client has not
498      * requested a "100 Continue" response), then the client will be
499      * streaming the request body over the wire already.  In that
500      * case, it is not possible to stop and perform a new SSL
501      * handshake immediately; once the SSL library moves to the
502      * "accept" state, it will reject the SSL packets which the client
503      * is sending for the request body.
504      *
505      * To allow authentication to complete in this auth hook, the
506      * solution used here is to fill a (bounded) buffer with the
507      * request body, and then to reinject that request body later.
508      */
509     if (renegotiate && !renegotiate_quick
510         && (apr_table_get(r->headers_in, "transfer-encoding")
511             || (apr_table_get(r->headers_in, "content-length")
512                 && strcmp(apr_table_get(r->headers_in, "content-length"), "0")))
513         && !r->expecting_100) {
514         int rv;
515
516         /* Fill the I/O buffer with the request body if possible. */
517         rv = ssl_io_buffer_fill(r);
518
519         if (rv) {
520             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
521                           "could not buffer message body to allow "
522                           "SSL renegotiation to proceed");
523             return rv;
524         }
525     }
526
527     /*
528      * now do the renegotiation if anything was actually reconfigured
529      */
530     if (renegotiate) {
531         /*
532          * Now we force the SSL renegotation by sending the Hello Request
533          * message to the client. Here we have to do a workaround: Actually
534          * OpenSSL returns immediately after sending the Hello Request (the
535          * intent AFAIK is because the SSL/TLS protocol says it's not a must
536          * that the client replies to a Hello Request). But because we insist
537          * on a reply (anything else is an error for us) we have to go to the
538          * ACCEPT state manually. Using SSL_set_accept_state() doesn't work
539          * here because it resets too much of the connection.  So we set the
540          * state explicitly and continue the handshake manually.
541          */
542         ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
543                      "Requesting connection re-negotiation");
544
545         if (renegotiate_quick) {
546             STACK_OF(X509) *cert_stack;
547
548             /* perform just a manual re-verification of the peer */
549             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
550                          "Performing quick renegotiation: "
551                          "just re-verifying the peer");
552
553             cert_stack = (STACK_OF(X509) *)SSL_get_peer_cert_chain(ssl);
554
555             cert = SSL_get_peer_certificate(ssl);
556
557             if (!cert_stack && cert) {
558                 /* client cert is in the session cache, but there is
559                  * no chain, since ssl3_get_client_certificate()
560                  * sk_X509_shift-ed the peer cert out of the chain.
561                  * we put it back here for the purpose of quick_renegotiation.
562                  */
563                 cert_stack = sk_new_null();
564                 sk_X509_push(cert_stack, MODSSL_PCHAR_CAST cert);
565             }
566
567             if (!cert_stack || (sk_X509_num(cert_stack) == 0)) {
568                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
569                              "Cannot find peer certificate chain");
570
571                 return HTTP_FORBIDDEN;
572             }
573
574             if (!(cert_store ||
575                   (cert_store = SSL_CTX_get_cert_store(ctx))))
576             {
577                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
578                              "Cannot find certificate storage");
579
580                 return HTTP_FORBIDDEN;
581             }
582
583             if (!cert) {
584                 cert = sk_X509_value(cert_stack, 0);
585             }
586
587             X509_STORE_CTX_init(&cert_store_ctx, cert_store, cert, cert_stack);
588             depth = SSL_get_verify_depth(ssl);
589
590             if (depth >= 0) {
591                 X509_STORE_CTX_set_depth(&cert_store_ctx, depth);
592             }
593
594             X509_STORE_CTX_set_ex_data(&cert_store_ctx,
595                                        SSL_get_ex_data_X509_STORE_CTX_idx(),
596                                        (char *)ssl);
597
598             if (!modssl_X509_verify_cert(&cert_store_ctx)) {
599                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
600                              "Re-negotiation verification step failed");
601                 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, r->server);
602             }
603
604             SSL_set_verify_result(ssl, cert_store_ctx.error);
605             X509_STORE_CTX_cleanup(&cert_store_ctx);
606
607             if (cert_stack != SSL_get_peer_cert_chain(ssl)) {
608                 /* we created this ourselves, so free it */
609                 sk_X509_pop_free(cert_stack, X509_free);
610             }
611         }
612         else {
613             request_rec *id = r->main ? r->main : r;
614
615             /* do a full renegotiation */
616             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
617                          "Performing full renegotiation: "
618                          "complete handshake protocol");
619
620             SSL_set_session_id_context(ssl,
621                                        (unsigned char *)&id,
622                                        sizeof(id));
623
624             SSL_renegotiate(ssl);
625             SSL_do_handshake(ssl);
626
627             if (SSL_get_state(ssl) != SSL_ST_OK) {
628                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
629                              "Re-negotiation request failed");
630
631                 r->connection->aborted = 1;
632                 return HTTP_FORBIDDEN;
633             }
634
635             ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
636                          "Awaiting re-negotiation handshake");
637
638             /* XXX: Should replace SSL_set_state with SSL_renegotiate(ssl);
639              * However, this causes failures in perl-framework currently,
640              * perhaps pre-test if we have already negotiated?
641              */
642             SSL_set_state(ssl, SSL_ST_ACCEPT);
643             SSL_do_handshake(ssl);
644
645             if (SSL_get_state(ssl) != SSL_ST_OK) {
646                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
647                              "Re-negotiation handshake failed: "
648                         "Not accepted by client!?");
649
650                 r->connection->aborted = 1;
651                 return HTTP_FORBIDDEN;
652             }
653         }
654
655         /*
656          * Remember the peer certificate's DN
657          */
658         if ((cert = SSL_get_peer_certificate(ssl))) {
659             if (sslconn->client_cert) {
660                 X509_free(sslconn->client_cert);
661             }
662             sslconn->client_cert = cert;
663             sslconn->client_dn = NULL;
664         }
665
666         /*
667          * Finally check for acceptable renegotiation results
668          */
669         if (dc->nVerifyClient != SSL_CVERIFY_NONE) {
670             BOOL do_verify = (dc->nVerifyClient == SSL_CVERIFY_REQUIRE);
671
672             if (do_verify && (SSL_get_verify_result(ssl) != X509_V_OK)) {
673                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
674                              "Re-negotiation handshake failed: "
675                              "Client verification failed");
676
677                 return HTTP_FORBIDDEN;
678             }
679
680             if (do_verify) {
681                 if ((peercert = SSL_get_peer_certificate(ssl)) == NULL) {
682                     ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
683                                  "Re-negotiation handshake failed: "
684                                  "Client certificate missing");
685
686                     return HTTP_FORBIDDEN;
687                 }
688
689                 X509_free(peercert);
690             }
691         }
692
693         /*
694          * Also check that SSLCipherSuite has been enforced as expected.
695          */
696         if (cipher_list) {
697             cipher = SSL_get_current_cipher(ssl);
698             if (sk_SSL_CIPHER_find(cipher_list, cipher) < 0) {
699                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
700                              "SSL cipher suite not renegotiated: "
701                              "access to %s denied using cipher %s",
702                               r->filename,
703                               SSL_CIPHER_get_name(cipher));
704                 return HTTP_FORBIDDEN;
705             }
706         }
707     }
708
709     /* If we're trying to have the user name set from a client
710      * certificate then we need to set it here. This should be safe as
711      * the user name probably isn't important from an auth checking point
712      * of view as the certificate supplied acts in that capacity.
713      * However, if FakeAuth is being used then this isn't the case so
714      * we need to postpone setting the username until later.
715      */
716     if ((dc->nOptions & SSL_OPT_FAKEBASICAUTH) == 0 && dc->szUserName) {
717         char *val = ssl_var_lookup(r->pool, r->server, r->connection,
718                                    r, (char *)dc->szUserName);
719         if (val && val[0])
720             r->user = val;
721         else
722             ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
723                           "Failed to set r->user to '%s'", dc->szUserName);
724     }
725
726     /*
727      * Check SSLRequire boolean expressions
728      */
729     requires = dc->aRequirement;
730     ssl_requires = (ssl_require_t *)requires->elts;
731
732     for (i = 0; i < requires->nelts; i++) {
733         ssl_require_t *req = &ssl_requires[i];
734         ok = ssl_expr_exec(r, req->mpExpr);
735
736         if (ok < 0) {
737             cp = apr_psprintf(r->pool,
738                               "Failed to execute "
739                               "SSL requirement expression: %s",
740                               ssl_expr_get_error());
741
742             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
743                           "access to %s failed, reason: %s",
744                           r->filename, cp);
745
746             /* remember forbidden access for strict require option */
747             apr_table_setn(r->notes, "ssl-access-forbidden", "1");
748
749             return HTTP_FORBIDDEN;
750         }
751
752         if (ok != 1) {
753             ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
754                          "Access to %s denied for %s "
755                          "(requirement expression not fulfilled)",
756                          r->filename, r->connection->remote_ip);
757
758             ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
759                          "Failed expression: %s", req->cpExpr);
760
761             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
762                           "access to %s failed, reason: %s",
763                           r->filename,
764                           "SSL requirement expression not fulfilled "
765                           "(see SSL logfile for more details)");
766
767             /* remember forbidden access for strict require option */
768             apr_table_setn(r->notes, "ssl-access-forbidden", "1");
769
770             return HTTP_FORBIDDEN;
771         }
772     }
773
774     /*
775      * Else access is granted from our point of view (except vendor
776      * handlers override). But we have to return DECLINED here instead
777      * of OK, because mod_auth and other modules still might want to
778      * deny access.
779      */
780
781     return DECLINED;
782 }
783
784 /*
785  *  Authentication Handler:
786  *  Fake a Basic authentication from the X509 client certificate.
787  *
788  *  This must be run fairly early on to prevent a real authentication from
789  *  occuring, in particular it must be run before anything else that
790  *  authenticates a user.  This means that the Module statement for this
791  *  module should be LAST in the Configuration file.
792  */
793 int ssl_hook_UserCheck(request_rec *r)
794 {
795     SSLConnRec *sslconn = myConnConfig(r->connection);
796     SSLSrvConfigRec *sc = mySrvConfig(r->server);
797     SSLDirConfigRec *dc = myDirConfig(r);
798     char *clientdn;
799     const char *auth_line, *username, *password;
800
801     /*
802      * Additionally forbid access (again)
803      * when strict require option is used.
804      */
805     if ((dc->nOptions & SSL_OPT_STRICTREQUIRE) &&
806         (apr_table_get(r->notes, "ssl-access-forbidden")))
807     {
808         return HTTP_FORBIDDEN;
809     }
810
811     /*
812      * We decline when we are in a subrequest.  The Authorization header
813      * would already be present if it was added in the main request.
814      */
815     if (!ap_is_initial_req(r)) {
816         return DECLINED;
817     }
818
819     /*
820      * Make sure the user is not able to fake the client certificate
821      * based authentication by just entering an X.509 Subject DN
822      * ("/XX=YYY/XX=YYY/..") as the username and "password" as the
823      * password.
824      */
825     if ((auth_line = apr_table_get(r->headers_in, "Authorization"))) {
826         if (strcEQ(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
827             while ((*auth_line == ' ') || (*auth_line == '\t')) {
828                 auth_line++;
829             }
830
831             auth_line = ap_pbase64decode(r->pool, auth_line);
832             username = ap_getword_nulls(r->pool, &auth_line, ':');
833             password = auth_line;
834
835             if ((username[0] == '/') && strEQ(password, "password")) {
836                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
837                     "Encountered FakeBasicAuth spoof: %s", username);
838                 return HTTP_FORBIDDEN;
839             }
840         }
841     }
842
843     /*
844      * We decline operation in various situations...
845      * - SSLOptions +FakeBasicAuth not configured
846      * - r->user already authenticated
847      * - ssl not enabled
848      * - client did not present a certificate
849      */
850     if (!((sc->enabled == SSL_ENABLED_TRUE || sc->enabled == SSL_ENABLED_OPTIONAL)
851           && sslconn && sslconn->ssl && sslconn->client_cert) ||
852         !(dc->nOptions & SSL_OPT_FAKEBASICAUTH) || r->user)
853     {
854         return DECLINED;
855     }
856
857     if (!sslconn->client_dn) {
858         X509_NAME *name = X509_get_subject_name(sslconn->client_cert);
859         char *cp = X509_NAME_oneline(name, NULL, 0);
860         sslconn->client_dn = apr_pstrdup(r->connection->pool, cp);
861         modssl_free(cp);
862     }
863
864     clientdn = (char *)sslconn->client_dn;
865
866     /*
867      * Fake a password - which one would be immaterial, as, it seems, an empty
868      * password in the users file would match ALL incoming passwords, if only
869      * we were using the standard crypt library routine. Unfortunately, OpenSSL
870      * "fixes" a "bug" in crypt and thus prevents blank passwords from
871      * working.  (IMHO what they really fix is a bug in the users of the code
872      * - failing to program correctly for shadow passwords).  We need,
873      * therefore, to provide a password. This password can be matched by
874      * adding the string "xxj31ZMTZzkVA" as the password in the user file.
875      * This is just the crypted variant of the word "password" ;-)
876      */
877     auth_line = apr_pstrcat(r->pool, "Basic ",
878                             ap_pbase64encode(r->pool,
879                                              apr_pstrcat(r->pool, clientdn,
880                                                          ":password", NULL)),
881                             NULL);
882     apr_table_set(r->headers_in, "Authorization", auth_line);
883
884     ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
885                  "Faking HTTP Basic Auth header: \"Authorization: %s\"",
886                  auth_line);
887
888     return DECLINED;
889 }
890
891 /* authorization phase */
892 int ssl_hook_Auth(request_rec *r)
893 {
894     SSLDirConfigRec *dc = myDirConfig(r);
895
896     /*
897      * Additionally forbid access (again)
898      * when strict require option is used.
899      */
900     if ((dc->nOptions & SSL_OPT_STRICTREQUIRE) &&
901         (apr_table_get(r->notes, "ssl-access-forbidden")))
902     {
903         return HTTP_FORBIDDEN;
904     }
905
906     return DECLINED;
907 }
908
909 /*
910  *   Fixup Handler
911  */
912
913 static const char *ssl_hook_Fixup_vars[] = {
914     "SSL_VERSION_INTERFACE",
915     "SSL_VERSION_LIBRARY",
916     "SSL_PROTOCOL",
917     "SSL_COMPRESS_METHOD",
918     "SSL_CIPHER",
919     "SSL_CIPHER_EXPORT",
920     "SSL_CIPHER_USEKEYSIZE",
921     "SSL_CIPHER_ALGKEYSIZE",
922     "SSL_CLIENT_VERIFY",
923     "SSL_CLIENT_M_VERSION",
924     "SSL_CLIENT_M_SERIAL",
925     "SSL_CLIENT_V_START",
926     "SSL_CLIENT_V_END",
927     "SSL_CLIENT_V_REMAIN",
928     "SSL_CLIENT_S_DN",
929     "SSL_CLIENT_S_DN_C",
930     "SSL_CLIENT_S_DN_ST",
931     "SSL_CLIENT_S_DN_L",
932     "SSL_CLIENT_S_DN_O",
933     "SSL_CLIENT_S_DN_OU",
934     "SSL_CLIENT_S_DN_CN",
935     "SSL_CLIENT_S_DN_T",
936     "SSL_CLIENT_S_DN_I",
937     "SSL_CLIENT_S_DN_G",
938     "SSL_CLIENT_S_DN_S",
939     "SSL_CLIENT_S_DN_D",
940     "SSL_CLIENT_S_DN_UID",
941     "SSL_CLIENT_S_DN_Email",
942     "SSL_CLIENT_I_DN",
943     "SSL_CLIENT_I_DN_C",
944     "SSL_CLIENT_I_DN_ST",
945     "SSL_CLIENT_I_DN_L",
946     "SSL_CLIENT_I_DN_O",
947     "SSL_CLIENT_I_DN_OU",
948     "SSL_CLIENT_I_DN_CN",
949     "SSL_CLIENT_I_DN_T",
950     "SSL_CLIENT_I_DN_I",
951     "SSL_CLIENT_I_DN_G",
952     "SSL_CLIENT_I_DN_S",
953     "SSL_CLIENT_I_DN_D",
954     "SSL_CLIENT_I_DN_UID",
955     "SSL_CLIENT_I_DN_Email",
956     "SSL_CLIENT_A_KEY",
957     "SSL_CLIENT_A_SIG",
958     "SSL_SERVER_M_VERSION",
959     "SSL_SERVER_M_SERIAL",
960     "SSL_SERVER_V_START",
961     "SSL_SERVER_V_END",
962     "SSL_SERVER_S_DN",
963     "SSL_SERVER_S_DN_C",
964     "SSL_SERVER_S_DN_ST",
965     "SSL_SERVER_S_DN_L",
966     "SSL_SERVER_S_DN_O",
967     "SSL_SERVER_S_DN_OU",
968     "SSL_SERVER_S_DN_CN",
969     "SSL_SERVER_S_DN_T",
970     "SSL_SERVER_S_DN_I",
971     "SSL_SERVER_S_DN_G",
972     "SSL_SERVER_S_DN_S",
973     "SSL_SERVER_S_DN_D",
974     "SSL_SERVER_S_DN_UID",
975     "SSL_SERVER_S_DN_Email",
976     "SSL_SERVER_I_DN",
977     "SSL_SERVER_I_DN_C",
978     "SSL_SERVER_I_DN_ST",
979     "SSL_SERVER_I_DN_L",
980     "SSL_SERVER_I_DN_O",
981     "SSL_SERVER_I_DN_OU",
982     "SSL_SERVER_I_DN_CN",
983     "SSL_SERVER_I_DN_T",
984     "SSL_SERVER_I_DN_I",
985     "SSL_SERVER_I_DN_G",
986     "SSL_SERVER_I_DN_S",
987     "SSL_SERVER_I_DN_D",
988     "SSL_SERVER_I_DN_UID",
989     "SSL_SERVER_I_DN_Email",
990     "SSL_SERVER_A_KEY",
991     "SSL_SERVER_A_SIG",
992     "SSL_SESSION_ID",
993     NULL
994 };
995
996 int ssl_hook_Fixup(request_rec *r)
997 {
998     SSLConnRec *sslconn = myConnConfig(r->connection);
999     SSLSrvConfigRec *sc = mySrvConfig(r->server);
1000     SSLDirConfigRec *dc = myDirConfig(r);
1001     apr_table_t *env = r->subprocess_env;
1002     char *var, *val = "";
1003     STACK_OF(X509) *peer_certs;
1004     SSL *ssl;
1005     int i;
1006
1007     if (sc->enabled == SSL_ENABLED_OPTIONAL && !(sslconn && sslconn->ssl)) {
1008         apr_table_setn(r->headers_out, "Upgrade", "TLS/1.0, HTTP/1.1");
1009     }
1010
1011     /*
1012      * Check to see if SSL is on
1013      */
1014     if (!(((sc->enabled == SSL_ENABLED_TRUE) || (sc->enabled == SSL_ENABLED_OPTIONAL)) && sslconn && (ssl = sslconn->ssl))) {
1015         return DECLINED;
1016     }
1017
1018     /*
1019      * Annotate the SSI/CGI environment with standard SSL information
1020      */
1021     /* the always present HTTPS (=HTTP over SSL) flag! */
1022     apr_table_setn(env, "HTTPS", "on");
1023
1024     /* standard SSL environment variables */
1025     if (dc->nOptions & SSL_OPT_STDENVVARS) {
1026         for (i = 0; ssl_hook_Fixup_vars[i]; i++) {
1027             var = (char *)ssl_hook_Fixup_vars[i];
1028             val = ssl_var_lookup(r->pool, r->server, r->connection, r, var);
1029             if (!strIsEmpty(val)) {
1030                 apr_table_setn(env, var, val);
1031             }
1032         }
1033     }
1034
1035     /*
1036      * On-demand bloat up the SSI/CGI environment with certificate data
1037      */
1038     if (dc->nOptions & SSL_OPT_EXPORTCERTDATA) {
1039         val = ssl_var_lookup(r->pool, r->server, r->connection,
1040                              r, "SSL_SERVER_CERT");
1041
1042         apr_table_setn(env, "SSL_SERVER_CERT", val);
1043
1044         val = ssl_var_lookup(r->pool, r->server, r->connection,
1045                              r, "SSL_CLIENT_CERT");
1046
1047         apr_table_setn(env, "SSL_CLIENT_CERT", val);
1048
1049         if ((peer_certs = (STACK_OF(X509) *)SSL_get_peer_cert_chain(ssl))) {
1050             for (i = 0; i < sk_X509_num(peer_certs); i++) {
1051                 var = apr_psprintf(r->pool, "SSL_CLIENT_CERT_CHAIN_%d", i);
1052                 val = ssl_var_lookup(r->pool, r->server, r->connection,
1053                                      r, var);
1054                 if (val) {
1055                     apr_table_setn(env, var, val);
1056                 }
1057             }
1058         }
1059     }
1060
1061     return DECLINED;
1062 }
1063
1064 /*  _________________________________________________________________
1065 **
1066 **  OpenSSL Callback Functions
1067 **  _________________________________________________________________
1068 */
1069
1070 /*
1071  * Handle out temporary RSA private keys on demand
1072  *
1073  * The background of this as the TLSv1 standard explains it:
1074  *
1075  * | D.1. Temporary RSA keys
1076  * |
1077  * |    US Export restrictions limit RSA keys used for encryption to 512
1078  * |    bits, but do not place any limit on lengths of RSA keys used for
1079  * |    signing operations. Certificates often need to be larger than 512
1080  * |    bits, since 512-bit RSA keys are not secure enough for high-value
1081  * |    transactions or for applications requiring long-term security. Some
1082  * |    certificates are also designated signing-only, in which case they
1083  * |    cannot be used for key exchange.
1084  * |
1085  * |    When the public key in the certificate cannot be used for encryption,
1086  * |    the server signs a temporary RSA key, which is then exchanged. In
1087  * |    exportable applications, the temporary RSA key should be the maximum
1088  * |    allowable length (i.e., 512 bits). Because 512-bit RSA keys are
1089  * |    relatively insecure, they should be changed often. For typical
1090  * |    electronic commerce applications, it is suggested that keys be
1091  * |    changed daily or every 500 transactions, and more often if possible.
1092  * |    Note that while it is acceptable to use the same temporary key for
1093  * |    multiple transactions, it must be signed each time it is used.
1094  * |
1095  * |    RSA key generation is a time-consuming process. In many cases, a
1096  * |    low-priority process can be assigned the task of key generation.
1097  * |    Whenever a new key is completed, the existing temporary key can be
1098  * |    replaced with the new one.
1099  *
1100  * XXX: base on comment above, if thread support is enabled,
1101  * we should spawn a low-priority thread to generate new keys
1102  * on the fly.
1103  *
1104  * So we generated 512 and 1024 bit temporary keys on startup
1105  * which we now just hand out on demand....
1106  */
1107
1108 RSA *ssl_callback_TmpRSA(SSL *ssl, int export, int keylen)
1109 {
1110     conn_rec *c = (conn_rec *)SSL_get_app_data(ssl);
1111     SSLModConfigRec *mc = myModConfig(c->base_server);
1112     int idx;
1113
1114     ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c,
1115                   "handing out temporary %d bit RSA key", keylen);
1116
1117     /* doesn't matter if export flag is on,
1118      * we won't be asked for keylen > 512 in that case.
1119      * if we are asked for a keylen > 1024, it is too expensive
1120      * to generate on the fly.
1121      * XXX: any reason not to generate 2048 bit keys at startup?
1122      */
1123
1124     switch (keylen) {
1125       case 512:
1126         idx = SSL_TMP_KEY_RSA_512;
1127         break;
1128
1129       case 1024:
1130       default:
1131         idx = SSL_TMP_KEY_RSA_1024;
1132     }
1133
1134     return (RSA *)mc->pTmpKeys[idx];
1135 }
1136
1137 /*
1138  * Hand out the already generated DH parameters...
1139  */
1140 DH *ssl_callback_TmpDH(SSL *ssl, int export, int keylen)
1141 {
1142     conn_rec *c = (conn_rec *)SSL_get_app_data(ssl);
1143     SSLModConfigRec *mc = myModConfig(c->base_server);
1144     int idx;
1145
1146     ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c,
1147                   "handing out temporary %d bit DH key", keylen);
1148
1149     switch (keylen) {
1150       case 512:
1151         idx = SSL_TMP_KEY_DH_512;
1152         break;
1153
1154       case 1024:
1155       default:
1156         idx = SSL_TMP_KEY_DH_1024;
1157     }
1158
1159     return (DH *)mc->pTmpKeys[idx];
1160 }
1161
1162 /*
1163  * This OpenSSL callback function is called when OpenSSL
1164  * does client authentication and verifies the certificate chain.
1165  */
1166 int ssl_callback_SSLVerify(int ok, X509_STORE_CTX *ctx)
1167 {
1168     /* Get Apache context back through OpenSSL context */
1169     SSL *ssl = X509_STORE_CTX_get_ex_data(ctx,
1170                                           SSL_get_ex_data_X509_STORE_CTX_idx());
1171     conn_rec *conn      = (conn_rec *)SSL_get_app_data(ssl);
1172     server_rec *s       = conn->base_server;
1173     request_rec *r      = (request_rec *)SSL_get_app_data2(ssl);
1174
1175     SSLSrvConfigRec *sc = mySrvConfig(s);
1176     SSLDirConfigRec *dc = r ? myDirConfig(r) : NULL;
1177     SSLConnRec *sslconn = myConnConfig(conn);
1178     modssl_ctx_t *mctx  = myCtxConfig(sslconn, sc);
1179
1180     /* Get verify ingredients */
1181     int errnum   = X509_STORE_CTX_get_error(ctx);
1182     int errdepth = X509_STORE_CTX_get_error_depth(ctx);
1183     int depth, verify;
1184
1185     /*
1186      * Log verification information
1187      */
1188     if (s->loglevel >= APLOG_DEBUG) {
1189         X509 *cert  = X509_STORE_CTX_get_current_cert(ctx);
1190         char *sname = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
1191         char *iname = X509_NAME_oneline(X509_get_issuer_name(cert),  NULL, 0);
1192
1193         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1194                      "Certificate Verification: "
1195                      "depth: %d, subject: %s, issuer: %s",
1196                      errdepth,
1197                      sname ? sname : "-unknown-",
1198                      iname ? iname : "-unknown-");
1199
1200         if (sname) {
1201             modssl_free(sname);
1202         }
1203
1204         if (iname) {
1205             modssl_free(iname);
1206         }
1207     }
1208
1209     /*
1210      * Check for optionally acceptable non-verifiable issuer situation
1211      */
1212     if (dc && (dc->nVerifyClient != SSL_CVERIFY_UNSET)) {
1213         verify = dc->nVerifyClient;
1214     }
1215     else {
1216         verify = mctx->auth.verify_mode;
1217     }
1218
1219     if (verify == SSL_CVERIFY_NONE) {
1220         /*
1221          * SSLProxyVerify is either not configured or set to "none".
1222          * (this callback doesn't happen in the server context if SSLVerify
1223          *  is not configured or set to "none")
1224          */
1225         return TRUE;
1226     }
1227
1228     if (ssl_verify_error_is_optional(errnum) &&
1229         (verify == SSL_CVERIFY_OPTIONAL_NO_CA))
1230     {
1231         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1232                      "Certificate Verification: Verifiable Issuer is "
1233                      "configured as optional, therefore we're accepting "
1234                      "the certificate");
1235
1236         sslconn->verify_info = "GENEROUS";
1237         ok = TRUE;
1238     }
1239
1240     /*
1241      * Additionally perform CRL-based revocation checks
1242      */
1243     if (ok) {
1244         if (!(ok = ssl_callback_SSLVerify_CRL(ok, ctx, conn))) {
1245             errnum = X509_STORE_CTX_get_error(ctx);
1246         }
1247     }
1248
1249     /*
1250      * If we already know it's not ok, log the real reason
1251      */
1252     if (!ok) {
1253         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1254                      "Certificate Verification: Error (%d): %s",
1255                      errnum, X509_verify_cert_error_string(errnum));
1256
1257         if (sslconn->client_cert) {
1258             X509_free(sslconn->client_cert);
1259             sslconn->client_cert = NULL;
1260         }
1261         sslconn->client_dn = NULL;
1262         sslconn->verify_error = X509_verify_cert_error_string(errnum);
1263     }
1264
1265     /*
1266      * Finally check the depth of the certificate verification
1267      */
1268     if (dc && (dc->nVerifyDepth != UNSET)) {
1269         depth = dc->nVerifyDepth;
1270     }
1271     else {
1272         depth = mctx->auth.verify_depth;
1273     }
1274
1275     if (errdepth > depth) {
1276         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1277                      "Certificate Verification: Certificate Chain too long "
1278                      "(chain has %d certificates, but maximum allowed are "
1279                      "only %d)",
1280                      errdepth, depth);
1281
1282         errnum = X509_V_ERR_CERT_CHAIN_TOO_LONG;
1283         sslconn->verify_error = X509_verify_cert_error_string(errnum);
1284
1285         ok = FALSE;
1286     }
1287
1288     /*
1289      * And finally signal OpenSSL the (perhaps changed) state
1290      */
1291     return ok;
1292 }
1293
1294 int ssl_callback_SSLVerify_CRL(int ok, X509_STORE_CTX *ctx, conn_rec *c)
1295 {
1296     server_rec *s       = c->base_server;
1297     SSLSrvConfigRec *sc = mySrvConfig(s);
1298     SSLConnRec *sslconn = myConnConfig(c);
1299     modssl_ctx_t *mctx  = myCtxConfig(sslconn, sc);
1300     X509_OBJECT obj;
1301     X509_NAME *subject, *issuer;
1302     X509 *cert;
1303     X509_CRL *crl;
1304     EVP_PKEY *pubkey;
1305     int i, n, rc;
1306
1307     /*
1308      * Unless a revocation store for CRLs was created we
1309      * cannot do any CRL-based verification, of course.
1310      */
1311     if (!mctx->crl) {
1312         return ok;
1313     }
1314
1315     /*
1316      * Determine certificate ingredients in advance
1317      */
1318     cert    = X509_STORE_CTX_get_current_cert(ctx);
1319     subject = X509_get_subject_name(cert);
1320     issuer  = X509_get_issuer_name(cert);
1321
1322     /*
1323      * OpenSSL provides the general mechanism to deal with CRLs but does not
1324      * use them automatically when verifying certificates, so we do it
1325      * explicitly here. We will check the CRL for the currently checked
1326      * certificate, if there is such a CRL in the store.
1327      *
1328      * We come through this procedure for each certificate in the certificate
1329      * chain, starting with the root-CA's certificate. At each step we've to
1330      * both verify the signature on the CRL (to make sure it's a valid CRL)
1331      * and it's revocation list (to make sure the current certificate isn't
1332      * revoked).  But because to check the signature on the CRL we need the
1333      * public key of the issuing CA certificate (which was already processed
1334      * one round before), we've a little problem. But we can both solve it and
1335      * at the same time optimize the processing by using the following
1336      * verification scheme (idea and code snippets borrowed from the GLOBUS
1337      * project):
1338      *
1339      * 1. We'll check the signature of a CRL in each step when we find a CRL
1340      *    through the _subject_ name of the current certificate. This CRL
1341      *    itself will be needed the first time in the next round, of course.
1342      *    But we do the signature processing one round before this where the
1343      *    public key of the CA is available.
1344      *
1345      * 2. We'll check the revocation list of a CRL in each step when
1346      *    we find a CRL through the _issuer_ name of the current certificate.
1347      *    This CRLs signature was then already verified one round before.
1348      *
1349      * This verification scheme allows a CA to revoke its own certificate as
1350      * well, of course.
1351      */
1352
1353     /*
1354      * Try to retrieve a CRL corresponding to the _subject_ of
1355      * the current certificate in order to verify it's integrity.
1356      */
1357     memset((char *)&obj, 0, sizeof(obj));
1358     rc = SSL_X509_STORE_lookup(mctx->crl,
1359                                X509_LU_CRL, subject, &obj);
1360     crl = obj.data.crl;
1361
1362     if ((rc > 0) && crl) {
1363         /*
1364          * Log information about CRL
1365          * (A little bit complicated because of ASN.1 and BIOs...)
1366          */
1367         if (s->loglevel >= APLOG_DEBUG) {
1368             char buff[512]; /* should be plenty */
1369             BIO *bio = BIO_new(BIO_s_mem());
1370
1371             BIO_printf(bio, "CA CRL: Issuer: ");
1372             X509_NAME_print(bio, issuer, 0);
1373
1374             BIO_printf(bio, ", lastUpdate: ");
1375             ASN1_UTCTIME_print(bio, X509_CRL_get_lastUpdate(crl));
1376
1377             BIO_printf(bio, ", nextUpdate: ");
1378             ASN1_UTCTIME_print(bio, X509_CRL_get_nextUpdate(crl));
1379
1380             n = BIO_read(bio, buff, sizeof(buff) - 1);
1381             buff[n] = '\0';
1382
1383             BIO_free(bio);
1384
1385             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, "%s", buff);
1386         }
1387
1388         /*
1389          * Verify the signature on this CRL
1390          */
1391         pubkey = X509_get_pubkey(cert);
1392         rc = X509_CRL_verify(crl, pubkey);
1393 #ifdef OPENSSL_VERSION_NUMBER
1394         /* Only refcounted in OpenSSL */
1395         if (pubkey)
1396             EVP_PKEY_free(pubkey);
1397 #endif
1398         if (rc <= 0) {
1399             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1400                          "Invalid signature on CRL");
1401
1402             X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE);
1403             X509_OBJECT_free_contents(&obj);
1404             return FALSE;
1405         }
1406
1407         /*
1408          * Check date of CRL to make sure it's not expired
1409          */
1410         i = X509_cmp_current_time(X509_CRL_get_nextUpdate(crl));
1411
1412         if (i == 0) {
1413             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1414                          "Found CRL has invalid nextUpdate field");
1415
1416             X509_STORE_CTX_set_error(ctx,
1417                                      X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD);
1418             X509_OBJECT_free_contents(&obj);
1419
1420             return FALSE;
1421         }
1422
1423         if (i < 0) {
1424             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1425                          "Found CRL is expired - "
1426                          "revoking all certificates until you get updated CRL");
1427
1428             X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_HAS_EXPIRED);
1429             X509_OBJECT_free_contents(&obj);
1430
1431             return FALSE;
1432         }
1433
1434         X509_OBJECT_free_contents(&obj);
1435     }
1436
1437     /*
1438      * Try to retrieve a CRL corresponding to the _issuer_ of
1439      * the current certificate in order to check for revocation.
1440      */
1441     memset((char *)&obj, 0, sizeof(obj));
1442     rc = SSL_X509_STORE_lookup(mctx->crl,
1443                                X509_LU_CRL, issuer, &obj);
1444
1445     crl = obj.data.crl;
1446     if ((rc > 0) && crl) {
1447         /*
1448          * Check if the current certificate is revoked by this CRL
1449          */
1450         n = sk_X509_REVOKED_num(X509_CRL_get_REVOKED(crl));
1451
1452         for (i = 0; i < n; i++) {
1453             X509_REVOKED *revoked =
1454                 sk_X509_REVOKED_value(X509_CRL_get_REVOKED(crl), i);
1455
1456             ASN1_INTEGER *sn = X509_REVOKED_get_serialNumber(revoked);
1457
1458             if (!ASN1_INTEGER_cmp(sn, X509_get_serialNumber(cert))) {
1459                 if (s->loglevel >= APLOG_DEBUG) {
1460                     char *cp = X509_NAME_oneline(issuer, NULL, 0);
1461                     long serial = ASN1_INTEGER_get(sn);
1462
1463                     ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
1464                                  "Certificate with serial %ld (0x%lX) "
1465                                  "revoked per CRL from issuer %s",
1466                                  serial, serial, cp);
1467                     modssl_free(cp);
1468                 }
1469
1470                 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
1471                 X509_OBJECT_free_contents(&obj);
1472
1473                 return FALSE;
1474             }
1475         }
1476
1477         X509_OBJECT_free_contents(&obj);
1478     }
1479
1480     return ok;
1481 }
1482
1483 #define SSLPROXY_CERT_CB_LOG_FMT \
1484    "Proxy client certificate callback: (%s) "
1485
1486 static void modssl_proxy_info_log(server_rec *s,
1487                                   X509_INFO *info,
1488                                   const char *msg)
1489 {
1490     SSLSrvConfigRec *sc = mySrvConfig(s);
1491     char name_buf[256];
1492     X509_NAME *name;
1493     char *dn;
1494
1495     if (s->loglevel < APLOG_DEBUG) {
1496         return;
1497     }
1498
1499     name = X509_get_subject_name(info->x509);
1500     dn = X509_NAME_oneline(name, name_buf, sizeof(name_buf));
1501
1502     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1503                  SSLPROXY_CERT_CB_LOG_FMT "%s, sending %s",
1504                  sc->vhost_id, msg, dn ? dn : "-uknown-");
1505 }
1506
1507 /*
1508  * caller will decrement the cert and key reference
1509  * so we need to increment here to prevent them from
1510  * being freed.
1511  */
1512 #define modssl_set_cert_info(info, cert, pkey) \
1513     *cert = info->x509; \
1514     X509_reference_inc(*cert); \
1515     *pkey = info->x_pkey->dec_pkey; \
1516     EVP_PKEY_reference_inc(*pkey)
1517
1518 int ssl_callback_proxy_cert(SSL *ssl, MODSSL_CLIENT_CERT_CB_ARG_TYPE **x509, EVP_PKEY **pkey)
1519 {
1520     conn_rec *c = (conn_rec *)SSL_get_app_data(ssl);
1521     server_rec *s = c->base_server;
1522     SSLSrvConfigRec *sc = mySrvConfig(s);
1523     X509_NAME *ca_name, *issuer;
1524     X509_INFO *info;
1525     STACK_OF(X509_NAME) *ca_list;
1526     STACK_OF(X509_INFO) *certs = sc->proxy->pkp->certs;
1527     int i, j;
1528
1529     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1530                  SSLPROXY_CERT_CB_LOG_FMT "entered",
1531                  sc->vhost_id);
1532
1533     if (!certs || (sk_X509_INFO_num(certs) <= 0)) {
1534         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1535                      SSLPROXY_CERT_CB_LOG_FMT
1536                      "downstream server wanted client certificate "
1537                      "but none are configured", sc->vhost_id);
1538         return FALSE;
1539     }
1540
1541     ca_list = SSL_get_client_CA_list(ssl);
1542
1543     if (!ca_list || (sk_X509_NAME_num(ca_list) <= 0)) {
1544         /*
1545          * downstream server didn't send us a list of acceptable CA certs,
1546          * so we send the first client cert in the list.
1547          */
1548         info = sk_X509_INFO_value(certs, 0);
1549
1550         modssl_proxy_info_log(s, info, "no acceptable CA list");
1551
1552         modssl_set_cert_info(info, x509, pkey);
1553
1554         return TRUE;
1555     }
1556
1557     for (i = 0; i < sk_X509_NAME_num(ca_list); i++) {
1558         ca_name = sk_X509_NAME_value(ca_list, i);
1559
1560         for (j = 0; j < sk_X509_INFO_num(certs); j++) {
1561             info = sk_X509_INFO_value(certs, j);
1562             issuer = X509_get_issuer_name(info->x509);
1563
1564             if (X509_NAME_cmp(issuer, ca_name) == 0) {
1565                 modssl_proxy_info_log(s, info, "found acceptable cert");
1566
1567                 modssl_set_cert_info(info, x509, pkey);
1568
1569                 return TRUE;
1570             }
1571         }
1572     }
1573
1574     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1575                  SSLPROXY_CERT_CB_LOG_FMT
1576                  "no client certificate found!?", sc->vhost_id);
1577
1578     return FALSE;
1579 }
1580
1581 static void ssl_session_log(server_rec *s,
1582                             const char *request,
1583                             unsigned char *id,
1584                             unsigned int idlen,
1585                             const char *status,
1586                             const char *result,
1587                             long timeout)
1588 {
1589     char buf[SSL_SESSION_ID_STRING_LEN];
1590     char timeout_str[56] = {'\0'};
1591
1592     if (s->loglevel < APLOG_DEBUG) {
1593         return;
1594     }
1595
1596     if (timeout) {
1597         apr_snprintf(timeout_str, sizeof(timeout_str),
1598                      "timeout=%lds ", (timeout - time(NULL)));
1599     }
1600
1601     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1602                  "Inter-Process Session Cache: "
1603                  "request=%s status=%s id=%s %s(session %s)",
1604                  request, status,
1605                  SSL_SESSION_id2sz(id, idlen, buf, sizeof(buf)),
1606                  timeout_str, result);
1607 }
1608
1609 /*
1610  *  This callback function is executed by OpenSSL whenever a new SSL_SESSION is
1611  *  added to the internal OpenSSL session cache. We use this hook to spread the
1612  *  SSL_SESSION also to the inter-process disk-cache to make share it with our
1613  *  other Apache pre-forked server processes.
1614  */
1615 int ssl_callback_NewSessionCacheEntry(SSL *ssl, SSL_SESSION *session)
1616 {
1617     /* Get Apache context back through OpenSSL context */
1618     conn_rec *conn      = (conn_rec *)SSL_get_app_data(ssl);
1619     server_rec *s       = conn->base_server;
1620     SSLSrvConfigRec *sc = mySrvConfig(s);
1621     long timeout        = sc->session_cache_timeout;
1622     BOOL rc;
1623     unsigned char *id;
1624     unsigned int idlen;
1625
1626     /*
1627      * Set the timeout also for the internal OpenSSL cache, because this way
1628      * our inter-process cache is consulted only when it's really necessary.
1629      */
1630     SSL_set_timeout(session, timeout);
1631
1632     /*
1633      * Store the SSL_SESSION in the inter-process cache with the
1634      * same expire time, so it expires automatically there, too.
1635      */
1636     id = SSL_SESSION_get_session_id(session);
1637     idlen = SSL_SESSION_get_session_id_length(session);
1638
1639     timeout += modssl_session_get_time(session);
1640
1641     rc = ssl_scache_store(s, id, idlen, timeout, session);
1642
1643     ssl_session_log(s, "SET", id, idlen,
1644                     rc == TRUE ? "OK" : "BAD",
1645                     "caching", timeout);
1646
1647     /*
1648      * return 0 which means to OpenSSL that the session is still
1649      * valid and was not freed by us with SSL_SESSION_free().
1650      */
1651     return 0;
1652 }
1653
1654 /*
1655  *  This callback function is executed by OpenSSL whenever a
1656  *  SSL_SESSION is looked up in the internal OpenSSL cache and it
1657  *  was not found. We use this to lookup the SSL_SESSION in the
1658  *  inter-process disk-cache where it was perhaps stored by one
1659  *  of our other Apache pre-forked server processes.
1660  */
1661 SSL_SESSION *ssl_callback_GetSessionCacheEntry(SSL *ssl,
1662                                                unsigned char *id,
1663                                                int idlen, int *do_copy)
1664 {
1665     /* Get Apache context back through OpenSSL context */
1666     conn_rec *conn = (conn_rec *)SSL_get_app_data(ssl);
1667     server_rec *s  = conn->base_server;
1668     SSL_SESSION *session;
1669
1670     /*
1671      * Try to retrieve the SSL_SESSION from the inter-process cache
1672      */
1673     session = ssl_scache_retrieve(s, id, idlen);
1674
1675     ssl_session_log(s, "GET", id, idlen,
1676                     session ? "FOUND" : "MISSED",
1677                     session ? "reuse" : "renewal", 0);
1678
1679     /*
1680      * Return NULL or the retrieved SSL_SESSION. But indicate (by
1681      * setting do_copy to 0) that the reference count on the
1682      * SSL_SESSION should not be incremented by the SSL library,
1683      * because we will no longer hold a reference to it ourself.
1684      */
1685     *do_copy = 0;
1686
1687     return session;
1688 }
1689
1690 /*
1691  *  This callback function is executed by OpenSSL whenever a
1692  *  SSL_SESSION is removed from the the internal OpenSSL cache.
1693  *  We use this to remove the SSL_SESSION in the inter-process
1694  *  disk-cache, too.
1695  */
1696 void ssl_callback_DelSessionCacheEntry(SSL_CTX *ctx,
1697                                        SSL_SESSION *session)
1698 {
1699     server_rec *s;
1700     SSLSrvConfigRec *sc;
1701     unsigned char *id;
1702     unsigned int idlen;
1703
1704     /*
1705      * Get Apache context back through OpenSSL context
1706      */
1707     if (!(s = (server_rec *)SSL_CTX_get_app_data(ctx))) {
1708         return; /* on server shutdown Apache is already gone */
1709     }
1710
1711     sc = mySrvConfig(s);
1712
1713     /*
1714      * Remove the SSL_SESSION from the inter-process cache
1715      */
1716     id = SSL_SESSION_get_session_id(session);
1717     idlen = SSL_SESSION_get_session_id_length(session);
1718
1719     ssl_scache_remove(s, id, idlen);
1720
1721     ssl_session_log(s, "REM", id, idlen,
1722                     "OK", "dead", 0);
1723
1724     return;
1725 }
1726
1727 /*
1728  * This callback function is executed while OpenSSL processes the
1729  * SSL handshake and does SSL record layer stuff. We use it to
1730  * trace OpenSSL's processing in out SSL logfile.
1731  */
1732 void ssl_callback_LogTracingState(MODSSL_INFO_CB_ARG_TYPE ssl, int where, int rc)
1733 {
1734     conn_rec *c;
1735     server_rec *s;
1736     SSLSrvConfigRec *sc;
1737
1738     /*
1739      * find corresponding server
1740      */
1741     if (!(c = (conn_rec *)SSL_get_app_data((SSL *)ssl))) {
1742         return;
1743     }
1744
1745     s = c->base_server;
1746     if (!(sc = mySrvConfig(s))) {
1747         return;
1748     }
1749
1750     /*
1751      * create the various trace messages
1752      */
1753     if (s->loglevel >= APLOG_DEBUG) {
1754         if (where & SSL_CB_HANDSHAKE_START) {
1755             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1756                          "%s: Handshake: start", SSL_LIBRARY_NAME);
1757         }
1758         else if (where & SSL_CB_HANDSHAKE_DONE) {
1759             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1760                          "%s: Handshake: done", SSL_LIBRARY_NAME);
1761         }
1762         else if (where & SSL_CB_LOOP) {
1763             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1764                          "%s: Loop: %s",
1765                          SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1766         }
1767         else if (where & SSL_CB_READ) {
1768             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1769                          "%s: Read: %s",
1770                          SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1771         }
1772         else if (where & SSL_CB_WRITE) {
1773             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1774                          "%s: Write: %s",
1775                          SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1776         }
1777         else if (where & SSL_CB_ALERT) {
1778             char *str = (where & SSL_CB_READ) ? "read" : "write";
1779             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1780                          "%s: Alert: %s:%s:%s",
1781                          SSL_LIBRARY_NAME, str,
1782                          SSL_alert_type_string_long(rc),
1783                          SSL_alert_desc_string_long(rc));
1784         }
1785         else if (where & SSL_CB_EXIT) {
1786             if (rc == 0) {
1787                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1788                              "%s: Exit: failed in %s",
1789                              SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1790             }
1791             else if (rc < 0) {
1792                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1793                              "%s: Exit: error in %s",
1794                              SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1795             }
1796         }
1797     }
1798
1799     /*
1800      * Because SSL renegotations can happen at any time (not only after
1801      * SSL_accept()), the best way to log the current connection details is
1802      * right after a finished handshake.
1803      */
1804     if (where & SSL_CB_HANDSHAKE_DONE) {
1805         ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
1806                      "Connection: Client IP: %s, Protocol: %s, "
1807                      "Cipher: %s (%s/%s bits)",
1808                      ssl_var_lookup(NULL, s, c, NULL, "REMOTE_ADDR"),
1809                      ssl_var_lookup(NULL, s, c, NULL, "SSL_PROTOCOL"),
1810                      ssl_var_lookup(NULL, s, c, NULL, "SSL_CIPHER"),
1811                      ssl_var_lookup(NULL, s, c, NULL, "SSL_CIPHER_USEKEYSIZE"),
1812                      ssl_var_lookup(NULL, s, c, NULL, "SSL_CIPHER_ALGKEYSIZE"));
1813     }
1814 }
1815