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