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