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