2 ** _ __ ___ ___ __| | ___ ___| | mod_ssl
3 ** | '_ ` _ \ / _ \ / _` | / __/ __| | Apache Interface to OpenSSL
4 ** | | | | | | (_) | (_| | \__ \__ \ | www.modssl.org
5 ** |_| |_| |_|\___/ \__,_|___|___/___/_| ftp.modssl.org
8 ** The SSL engine kernel
11 /* ====================================================================
12 * The Apache Software License, Version 1.1
14 * Copyright (c) 2000-2002 The Apache Software Foundation. All rights
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
21 * 1. Redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer.
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
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.
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.
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.
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
57 * ====================================================================
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.''
67 * Close the SSL part of the socket connection
68 * (called immediately _before_ the socket is closed)
70 /* XXX: perhaps ssl_abort() should call us or vice-versa
71 * lot of the same happening in both places
73 apr_status_t ssl_hook_CloseConnection(SSLFilterRec *filter)
75 SSL *ssl = filter->pssl;
76 const char *type = "";
84 conn = (conn_rec *)SSL_get_app_data(ssl);
85 sslconn = myConnConfig(conn);
88 * Now close the SSL layer of the connection. We've to take
89 * the TLSv1 standard into account here:
91 * | 7.2.1. Closure alerts
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.
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.
103 * | Either party may initiate a close by sending a close_notify alert.
104 * | Any data received after a closure alert is ignored.
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.
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.
120 * exchange close notify messages, but allow the user
121 * to force the type of handshake via SetEnvIf directive
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);
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);
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);
145 SSL_smart_shutdown(ssl);
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)",
153 ssl_util_vhostid(conn->pool, conn->base_server),
154 conn->remote_ip ? conn->remote_ip : "unknown");
157 /* deallocate the SSL connection */
160 filter->pssl = NULL; /* so filters know we've been shutdown */
166 * Post Read Request Handler
168 int ssl_hook_ReadReq(request_rec *r)
170 SSLConnRec *sslconn = myConnConfig(r->connection);
178 * Get the SSL connection structure and perform the
179 * delayed interlinking from SSL back to request_rec
181 if ((ssl = sslconn->ssl)) {
182 SSL_set_app_data2(ssl, r);
186 * Force the mod_ssl content handler when URL indicates this
188 if (strEQn(r->uri, "/mod_ssl:", 9)) {
189 r->handler = "mod_ssl:content-handler";
196 * Move SetEnvIf information from request_rec to conn_rec/BUFF
197 * to allow the close connection handler to use them.
200 static void ssl_configure_env(request_rec *r, SSLConnRec *sslconn)
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;
206 sslconn->shutdown_type = SSL_SHUTDOWN_TYPE_STANDARD;
208 for (i = 0; i < arr->nelts; i++) {
209 const char *key = elts[i].key;
213 /* being case-sensitive here.
214 * and not checking for the -shutdown since these are the only
215 * SetEnvIf "flags" we support
217 if (!strncmp(key+1, "sl-", 3)) {
219 if (!strncmp(key, "unclean", 7)) {
220 sslconn->shutdown_type = SSL_SHUTDOWN_TYPE_UNCLEAN;
222 else if (!strncmp(key, "accurate", 8)) {
223 sslconn->shutdown_type = SSL_SHUTDOWN_TYPE_ACCURATE;
225 return; /* should only ever be one ssl-*-shutdown */
233 * URL Translation Handler
235 int ssl_hook_Translate(request_rec *r)
237 SSLConnRec *sslconn = myConnConfig(r->connection);
239 if (!(sslconn && sslconn->ssl)) {
244 * Log information about incoming HTTPS requests
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 ?
251 apr_psprintf(r->pool, "Subsequent (No.%d)",
252 r->connection->keepalives+1)),
254 ssl_util_vhostid(r->pool, r->server));
257 /* SetEnvIf ssl-*-shutdown flags can only be per-server,
258 * so they won't change across keepalive requests
260 if (sslconn->shutdown_type == SSL_SHUTDOWN_TYPE_UNSET) {
261 ssl_configure_env(r, sslconn);
270 int ssl_hook_Handler(request_rec *r)
272 if (strNE(r->handler, "mod_ssl:content-handler")) {
276 if (strNEn(r->uri, "/mod_ssl:", 9)) {
280 if (strEQ(r->uri, "/mod_ssl:error:HTTP-request")) {
284 int port = ap_get_server_port(r);
286 if (!ap_is_default_port(port, r)) {
287 thisport = apr_psprintf(r->pool, ":%u", port);
290 thisurl = ap_escape_html(r->pool,
291 apr_psprintf(r->pool, "https://%s%s/",
292 ap_get_server_name(r),
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"
301 "<a href=\"%s\"><b>%s</b></a></blockquote>",
304 apr_table_setn(r->notes, "error-notes", errmsg);
307 return HTTP_BAD_REQUEST;
313 int ssl_hook_Access(request_rec *r)
315 SSLDirConfigRec *dc = myDirConfig(r);
316 SSLSrvConfigRec *sc = mySrvConfig(r->server);
317 SSLConnRec *sslconn = myConnConfig(r->connection);
318 SSL *ssl = sslconn ? sslconn->ssl : NULL;
320 apr_array_header_t *requires;
321 ssl_require_t *ssl_requires;
324 BOOL renegotiate = FALSE, renegotiate_quick = FALSE;
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;
333 ctx = SSL_get_SSL_CTX(ssl);
337 * Support for SSLRequireSSL directive
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");
344 /* remember forbidden access for strict require option */
345 apr_table_setn(r->notes, "ssl-access-forbidden", "1");
347 return HTTP_FORBIDDEN;
351 * Check to see if SSL protocol is on
353 if (!(sc->bEnabled || ssl)) {
357 * Support for per-directory reconfigured SSL connection parameters.
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).
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.
378 * Override of SSLCipherSuite
380 * We provide two options here:
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).
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.
398 if (dc->szCipherSuite) {
399 /* remember old state */
401 if (dc->nOptions & SSL_OPT_OPTRENEGOTIATE) {
402 cipher = SSL_get_current_cipher(ssl);
405 cipher_list_old = (STACK_OF(SSL_CIPHER) *)SSL_get_ciphers(ssl);
407 if (cipher_list_old) {
408 cipher_list_old = sk_SSL_CIPHER_dup(cipher_list_old);
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");
418 if (cipher_list_old) {
419 sk_SSL_CIPHER_free(cipher_list_old);
422 return HTTP_FORBIDDEN;
425 /* determine whether a renegotiation has to be forced */
426 cipher_list = (STACK_OF(SSL_CIPHER) *)SSL_get_ciphers(ssl);
428 if (dc->nOptions & SSL_OPT_OPTRENEGOTIATE) {
430 if ((!cipher && cipher_list) ||
431 (cipher && !cipher_list))
435 else if (cipher && cipher_list &&
436 (sk_SSL_CIPHER_find(cipher_list, cipher) < 0))
443 if ((!cipher_list_old && cipher_list) ||
444 (cipher_list_old && !cipher_list))
448 else if (cipher_list_old && cipher_list) {
450 !renegotiate && (n < sk_SSL_CIPHER_num(cipher_list));
453 SSL_CIPHER *value = sk_SSL_CIPHER_value(cipher_list, n);
455 if (sk_SSL_CIPHER_find(cipher_list_old, value) < 0) {
461 !renegotiate && (n < sk_SSL_CIPHER_num(cipher_list_old));
464 SSL_CIPHER *value = sk_SSL_CIPHER_value(cipher_list_old, n);
466 if (sk_SSL_CIPHER_find(cipher_list, value) < 0) {
474 if (cipher_list_old) {
475 sk_SSL_CIPHER_free(cipher_list_old);
480 ssl_log(r->server, SSL_LOG_TRACE,
481 "Reconfigured cipher suite will force renegotiation");
486 * override of SSLVerifyDepth
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).
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;
503 /* determine whether a renegotiation has to be forced */
504 if (dc->nVerifyDepth < n) {
506 ssl_log(r->server, SSL_LOG_TRACE,
507 "Reduced client verification depth "
508 "will force renegotiation");
513 * override of SSLVerifyClient
515 * We force a renegotiation if the reconfigured/new verify type is
516 * stronger than the currently active verify type.
518 * The order is: none << optional_no_ca << optional << require
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
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;
532 if (dc->nVerifyClient == SSL_CVERIFY_REQUIRE) {
533 verify |= SSL_VERIFY_PEER_STRICT;
536 if ((dc->nVerifyClient == SSL_CVERIFY_OPTIONAL) ||
537 (dc->nVerifyClient == SSL_CVERIFY_OPTIONAL_NO_CA))
539 verify |= SSL_VERIFY_PEER;
542 modssl_set_verify(ssl, verify, ssl_callback_SSLVerify);
543 SSL_set_verify_result(ssl, X509_V_OK);
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)) ||
550 (!(verify_old & SSL_VERIFY_PEER) &&
551 (verify & SSL_VERIFY_PEER)) ||
553 (!(verify_old & SSL_VERIFY_PEER_STRICT) &&
554 (verify & SSL_VERIFY_PEER_STRICT)))
559 if ((dc->nOptions & SSL_OPT_OPTRENEGOTIATE) &&
560 (verify_old == SSL_VERIFY_NONE) &&
561 SSL_get_peer_certificate(ssl))
563 renegotiate_quick = TRUE;
566 ssl_log(r->server, SSL_LOG_TRACE,
567 "Changed client verification type "
568 "will force %srenegotiation",
569 renegotiate_quick ? "quick " : "");
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.
581 #if MODSSL_HAVE_SSL_SET_CERT_STORE
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 ...
587 #define MODSSL_CFG_NE(f) \
588 (dc->f && (!sc->f || (sc->f && strNE(dc->f, sc->f))))
590 #define MODSSL_CFG_CA(f) \
591 (dc->f ? dc->f : sc->f)
593 if (MODSSL_CFG_NE(szCACertificateFile) ||
594 MODSSL_CFG_NE(szCACertificatePath))
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);
600 cert_store = X509_STORE_new();
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");
607 X509_STORE_free(cert_store);
609 return HTTP_FORBIDDEN;
612 /* SSL_free will free cert_store */
613 SSL_set_cert_store(ssl, cert_store);
615 if (!(ca_list = ssl_init_FindCAList(r->server, r->pool,
618 ssl_log(r->server, SSL_LOG_ERROR,
619 "Unable to determine list of available "
620 "CA certificates for client authentication");
622 return HTTP_FORBIDDEN;
625 SSL_set_client_CA_list(ssl, ca_list);
628 ssl_log(r->server, SSL_LOG_TRACE,
629 "Changed client verification locations "
630 "will force renegotiation");
632 #endif /* MODSSL_HAVE_SSL_SET_CERT_STORE */
635 * SSL renegotiations in conjunction with HTTP
636 * requests using the POST method are not supported.
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.
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.
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.
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.
681 * Solution Implementation:
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.
692 * !! BUT ALL THIS IS STILL NOT RE-IMPLEMENTED FOR APACHE 2.0 !!
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!");
699 return HTTP_METHOD_NOT_ALLOWED;
703 * now do the renegotiation if anything was actually reconfigured
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.
717 ssl_log(r->server, SSL_LOG_INFO,
718 "Requesting connection re-negotiation");
720 if (renegotiate_quick) {
721 STACK_OF(X509) *cert_stack;
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");
728 cert_stack = (STACK_OF(X509) *)SSL_get_peer_cert_chain(ssl);
730 if (!cert_stack || (sk_X509_num(cert_stack) == 0)) {
731 ssl_log(r->server, SSL_LOG_ERROR,
732 "Cannot find peer certificate chain");
734 return HTTP_FORBIDDEN;
738 (cert_store = SSL_CTX_get_cert_store(ctx))))
740 ssl_log(r->server, SSL_LOG_ERROR,
741 "Cannot find certificate storage");
743 return HTTP_FORBIDDEN;
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);
751 X509_STORE_CTX_set_depth(&cert_store_ctx, depth);
754 X509_STORE_CTX_set_ex_data(&cert_store_ctx,
755 SSL_get_ex_data_X509_STORE_CTX_idx(),
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");
763 SSL_set_verify_result(ssl, cert_store_ctx.error);
764 X509_STORE_CTX_cleanup(&cert_store_ctx);
767 request_rec *id = r->main ? r->main : r;
769 /* do a full renegotiation */
770 ssl_log(r->server, SSL_LOG_TRACE,
771 "Performing full renegotiation: "
772 "complete handshake protocol");
774 SSL_set_session_id_context(ssl,
775 (unsigned char *)&id,
778 SSL_renegotiate(ssl);
779 SSL_do_handshake(ssl);
781 if (SSL_get_state(ssl) != SSL_ST_OK) {
782 ssl_log(r->server, SSL_LOG_ERROR,
783 "Re-negotiation request failed");
785 return HTTP_FORBIDDEN;
788 ssl_log(r->server, SSL_LOG_INFO,
789 "Awaiting re-negotiation handshake");
791 SSL_set_state(ssl, SSL_ST_ACCEPT);
792 SSL_do_handshake(ssl);
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!?");
799 return HTTP_FORBIDDEN;
804 * Remember the peer certificate's DN
806 if ((cert = SSL_get_peer_certificate(ssl))) {
807 sslconn->client_cert = cert;
808 sslconn->client_dn = NULL;
812 * Finally check for acceptable renegotiation results
814 if (dc->nVerifyClient != SSL_CVERIFY_NONE) {
815 BOOL do_verify = (dc->nVerifyClient == SSL_CVERIFY_REQUIRE);
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");
822 return HTTP_FORBIDDEN;
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");
830 return HTTP_FORBIDDEN;
836 * Check SSLRequire boolean expressions
838 requires = dc->aRequirement;
839 ssl_requires = (ssl_require_t *)requires->elts;
841 for (i = 0; i < requires->nelts; i++) {
842 ssl_require_t *req = &ssl_requires[i];
843 ok = ssl_expr_exec(r, req->mpExpr);
846 cp = apr_psprintf(r->pool,
848 "SSL requirement expression: %s",
849 ssl_expr_get_error());
851 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
852 "access to %s failed, reason: %s",
855 /* remember forbidden access for strict require option */
856 apr_table_setn(r->notes, "ssl-access-forbidden", "1");
858 return HTTP_FORBIDDEN;
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);
867 ssl_log(r->server, SSL_LOG_INFO,
868 "Failed expression: %s", req->cpExpr);
870 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
871 "access to %s failed, reason: %s",
873 "SSL requirement expression not fulfilled "
874 "(see SSL logfile for more details)");
876 /* remember forbidden access for strict require option */
877 apr_table_setn(r->notes, "ssl-access-forbidden", "1");
879 return HTTP_FORBIDDEN;
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
894 * Authentication Handler:
895 * Fake a Basic authentication from the X509 client certificate.
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.
902 int ssl_hook_UserCheck(request_rec *r)
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];
909 const char *auth_line, *username, *password;
912 * Additionally forbid access (again)
913 * when strict require option is used.
915 if ((dc->nOptions & SSL_OPT_STRICTREQUIRE) &&
916 (apr_table_get(r->notes, "ssl-access-forbidden")))
918 return HTTP_FORBIDDEN;
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
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')) {
933 auth_line = ap_pbase64decode(r->pool, auth_line);
934 username = ap_getword_nulls(r->pool, &auth_line, ':');
935 password = auth_line;
937 if ((username[0] == '/') && strEQ(password, "password")) {
938 return HTTP_FORBIDDEN;
944 * We decline operation in various situations...
945 * - SSLOptions +FakeBasicAuth not configured
946 * - r->user already authenticated
948 * - client did not present a certificate
950 if (!(sc->bEnabled && sslconn->ssl && sslconn->client_cert) ||
951 !(dc->nOptions & SSL_OPT_FAKEBASICAUTH) || r->user)
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);
963 clientdn = (char *)sslconn->client_dn;
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" ;-)
976 apr_snprintf(buf1, sizeof(buf1), "%s:password", clientdn);
977 ssl_util_uuencode(buf2, buf1, FALSE);
979 apr_snprintf(buf1, sizeof(buf1), "Basic %s", buf2);
980 apr_table_set(r->headers_in, "Authorization", buf1);
982 ssl_log(r->server, SSL_LOG_INFO,
983 "Faking HTTP Basic Auth header: \"Authorization: %s\"", buf1);
988 /* authorization phase */
989 int ssl_hook_Auth(request_rec *r)
991 SSLDirConfigRec *dc = myDirConfig(r);
994 * Additionally forbid access (again)
995 * when strict require option is used.
997 if ((dc->nOptions & SSL_OPT_STRICTREQUIRE) &&
998 (apr_table_get(r->notes, "ssl-access-forbidden")))
1000 return HTTP_FORBIDDEN;
1010 static const char *ssl_hook_Fixup_vars[] = {
1011 "SSL_VERSION_INTERFACE",
1012 "SSL_VERSION_LIBRARY",
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",
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",
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",
1053 "SSL_SERVER_M_VERSION",
1054 "SSL_SERVER_M_SERIAL",
1055 "SSL_SERVER_V_START",
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",
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",
1091 int ssl_hook_Fixup(request_rec *r)
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;
1103 * Check to see if SSL is on
1105 if (!(sc->bEnabled && sslconn && (ssl = sslconn->ssl))) {
1110 * Annotate the SSI/CGI environment with standard SSL information
1112 /* the always present HTTPS (=HTTP over SSL) flag! */
1113 apr_table_setn(env, "HTTPS", "on");
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);
1127 * On-demand bloat up the SSI/CGI environment with certificate data
1129 if (dc->nOptions & SSL_OPT_EXPORTCERTDATA) {
1130 val = ssl_var_lookup(r->pool, r->server, r->connection,
1131 r, "SSL_SERVER_CERT");
1133 apr_table_setn(env, "SSL_SERVER_CERT", val);
1135 val = ssl_var_lookup(r->pool, r->server, r->connection,
1136 r, "SSL_CLIENT_CERT");
1138 apr_table_setn(env, "SSL_CLIENT_CERT", val);
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,
1146 apr_table_setn(env, var, val);
1155 /* _________________________________________________________________
1157 ** OpenSSL Callback Functions
1158 ** _________________________________________________________________
1162 * Handle out temporary RSA private keys on demand
1164 * The background of this as the TLSv1 standard explains it:
1166 * | D.1. Temporary RSA keys
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.
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.
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.
1191 * XXX: base on comment above, if thread support is enabled,
1192 * we should spawn a low-priority thread to generate new keys
1195 * So we generated 512 and 1024 bit temporary keys on startup
1196 * which we now just hand out on demand....
1199 RSA *ssl_callback_TmpRSA(SSL *ssl, int export, int keylen)
1201 conn_rec *c = (conn_rec *)SSL_get_app_data(ssl);
1202 SSLModConfigRec *mc = myModConfig(c->base_server);
1205 ssl_log(c->base_server, SSL_LOG_TRACE,
1206 "handing out temporary %d bit RSA key", keylen);
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?
1217 idx = SSL_TMP_KEY_RSA_512;
1222 idx = SSL_TMP_KEY_RSA_1024;
1225 return (RSA *)mc->pTmpKeys[idx];
1229 * Hand out the already generated DH parameters...
1231 DH *ssl_callback_TmpDH(SSL *ssl, int export, int keylen)
1233 conn_rec *c = (conn_rec *)SSL_get_app_data(ssl);
1234 SSLModConfigRec *mc = myModConfig(c->base_server);
1237 ssl_log(c->base_server, SSL_LOG_TRACE,
1238 "handing out temporary %d bit DH key", keylen);
1242 idx = SSL_TMP_KEY_DH_512;
1247 idx = SSL_TMP_KEY_DH_1024;
1250 return (DH *)mc->pTmpKeys[idx];
1254 * This OpenSSL callback function is called when OpenSSL
1255 * does client authentication and verifies the certificate chain.
1257 int ssl_callback_SSLVerify(int ok, X509_STORE_CTX *ctx)
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);
1265 SSLSrvConfigRec *sc = mySrvConfig(s);
1266 SSLDirConfigRec *dc = r ? myDirConfig(r) : NULL;
1267 SSLConnRec *sslconn = myConnConfig(conn);
1269 /* Get verify ingredients */
1270 int errnum = X509_STORE_CTX_get_error(ctx);
1271 int errdepth = X509_STORE_CTX_get_error_depth(ctx);
1275 * Log verification information
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);
1282 ssl_log(s, SSL_LOG_TRACE,
1283 "Certificate Verification: depth: %d, subject: %s, issuer: %s",
1285 sname ? sname : "-unknown-",
1286 iname ? iname : "-unknown-");
1298 * Check for optionally acceptable non-verifiable issuer situation
1300 if (dc && (dc->nVerifyClient != SSL_CVERIFY_UNSET)) {
1301 verify = dc->nVerifyClient;
1304 verify = sc->nVerifyClient;
1307 if (ssl_verify_error_is_optional(errnum) &&
1308 (verify == SSL_CVERIFY_OPTIONAL_NO_CA))
1310 ssl_log(s, SSL_LOG_TRACE,
1311 "Certificate Verification: Verifiable Issuer is configured as "
1312 "optional, therefore we're accepting the certificate");
1314 sslconn->verify_info = "GENEROUS";
1319 * Additionally perform CRL-based revocation checks
1322 if (!(ok = ssl_callback_SSLVerify_CRL(ok, ctx, s))) {
1323 errnum = X509_STORE_CTX_get_error(ctx);
1328 * If we already know it's not ok, log the real reason
1331 ssl_log(s, SSL_LOG_ERROR,
1332 "Certificate Verification: Error (%d): %s",
1333 errnum, X509_verify_cert_error_string(errnum));
1335 sslconn->client_dn = NULL;
1336 sslconn->client_cert = NULL;
1337 sslconn->verify_error = X509_verify_cert_error_string(errnum);
1341 * Finally check the depth of the certificate verification
1343 if (dc && (dc->nVerifyDepth != UNSET)) {
1344 depth = dc->nVerifyDepth;
1347 depth = sc->nVerifyDepth;
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)",
1356 errnum = X509_V_ERR_CERT_CHAIN_TOO_LONG;
1357 sslconn->verify_error = X509_verify_cert_error_string(errnum);
1363 * And finally signal OpenSSL the (perhaps changed) state
1368 int ssl_callback_SSLVerify_CRL(int ok, X509_STORE_CTX *ctx, server_rec *s)
1370 SSLSrvConfigRec *sc = mySrvConfig(s);
1372 X509_NAME *subject, *issuer;
1378 * Unless a revocation store for CRLs was created we
1379 * cannot do any CRL-based verification, of course.
1381 if (!sc->pRevocationStore) {
1386 * Determine certificate ingredients in advance
1388 cert = X509_STORE_CTX_get_current_cert(ctx);
1389 subject = X509_get_subject_name(cert);
1390 issuer = X509_get_issuer_name(cert);
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.
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
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.
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.
1419 * This verification scheme allows a CA to revoke its own certificate as
1424 * Try to retrieve a CRL corresponding to the _subject_ of
1425 * the current certificate in order to verify it's integrity.
1427 memset((char *)&obj, 0, sizeof(obj));
1428 rc = SSL_X509_STORE_lookup(sc->pRevocationStore,
1429 X509_LU_CRL, subject, &obj);
1432 if ((rc > 0) && crl) {
1434 * Log information about CRL
1435 * (A little bit complicated because of ASN.1 and BIOs...)
1437 if (sc->nLogLevel >= SSL_LOG_TRACE) {
1438 char buff[512]; /* should be plenty */
1439 BIO *bio = BIO_new(BIO_s_mem());
1441 BIO_printf(bio, "CA CRL: Issuer: ");
1442 X509_NAME_print(bio, issuer, 0);
1444 BIO_printf(bio, ", lastUpdate: ");
1445 ASN1_UTCTIME_print(bio, X509_CRL_get_lastUpdate(crl));
1447 BIO_printf(bio, ", nextUpdate: ");
1448 ASN1_UTCTIME_print(bio, X509_CRL_get_nextUpdate(crl));
1450 n = BIO_read(bio, buff, sizeof(buff));
1455 ssl_log(s, SSL_LOG_TRACE, buff);
1459 * Verify the signature on this CRL
1461 if (X509_CRL_verify(crl, X509_get_pubkey(cert)) <= 0) {
1462 ssl_log(s, SSL_LOG_WARN, "Invalid signature on CRL");
1464 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE);
1465 X509_OBJECT_free_contents(&obj);
1471 * Check date of CRL to make sure it's not expired
1473 i = X509_cmp_current_time(X509_CRL_get_nextUpdate(crl));
1476 ssl_log(s, SSL_LOG_WARN,
1477 "Found CRL has invalid nextUpdate field");
1479 X509_STORE_CTX_set_error(ctx,
1480 X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD);
1481 X509_OBJECT_free_contents(&obj);
1487 ssl_log(s, SSL_LOG_WARN,
1488 "Found CRL is expired - "
1489 "revoking all certificates until you get updated CRL");
1491 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_HAS_EXPIRED);
1492 X509_OBJECT_free_contents(&obj);
1497 X509_OBJECT_free_contents(&obj);
1501 * Try to retrieve a CRL corresponding to the _issuer_ of
1502 * the current certificate in order to check for revocation.
1504 memset((char *)&obj, 0, sizeof(obj));
1505 rc = SSL_X509_STORE_lookup(sc->pRevocationStore,
1506 X509_LU_CRL, issuer, &obj);
1509 if ((rc > 0) && crl) {
1511 * Check if the current certificate is revoked by this CRL
1513 n = sk_X509_REVOKED_num(X509_CRL_get_REVOKED(crl));
1515 for (i = 0; i < n; i++) {
1516 X509_REVOKED *revoked =
1517 sk_X509_REVOKED_value(X509_CRL_get_REVOKED(crl), i);
1519 ASN1_INTEGER *sn = X509_REVOKED_get_serialNumber(revoked);
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);
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);
1533 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
1534 X509_OBJECT_free_contents(&obj);
1540 X509_OBJECT_free_contents(&obj);
1546 static void ssl_session_log(server_rec *s,
1547 const char *request,
1554 SSLSrvConfigRec *sc = mySrvConfig(s);
1555 char buf[SSL_SESSION_ID_STRING_LEN];
1556 char timeout_str[56] = {'\0'};
1558 if (sc->nLogLevel < SSL_LOG_TRACE) {
1563 apr_snprintf(timeout_str, sizeof(timeout_str),
1564 "timeout=%lds ", (timeout - time(NULL)));
1567 ssl_log(s, SSL_LOG_TRACE, "Inter-Process Session Cache: "
1568 "request=%s status=%s id=%s %s(session %s)",
1570 SSL_SESSION_id2sz(id, idlen, buf, sizeof(buf)),
1571 timeout_str, result);
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.
1580 int ssl_callback_NewSessionCacheEntry(SSL *ssl, SSL_SESSION *session)
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;
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.
1595 SSL_set_timeout(session, timeout);
1598 * Store the SSL_SESSION in the inter-process cache with the
1599 * same expire time, so it expires automatically there, too.
1601 id = SSL_SESSION_get_session_id(session);
1602 idlen = SSL_SESSION_get_session_id_length(session);
1604 timeout += modssl_session_get_time(session);
1606 rc = ssl_scache_store(s, id, idlen, timeout, session);
1608 ssl_session_log(s, "SET", id, idlen,
1609 rc == TRUE ? "OK" : "BAD",
1610 "caching", timeout);
1613 * return 0 which means to OpenSSL that the session is still
1614 * valid and was not freed by us with SSL_SESSION_free().
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.
1626 SSL_SESSION *ssl_callback_GetSessionCacheEntry(SSL *ssl,
1628 int idlen, int *do_copy)
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;
1636 * Try to retrieve the SSL_SESSION from the inter-process cache
1638 session = ssl_scache_retrieve(s, id, idlen);
1640 ssl_session_log(s, "GET", id, idlen,
1641 session ? "FOUND" : "MISSED",
1642 session ? "reuse" : "renewal", 0);
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.
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
1661 void ssl_callback_DelSessionCacheEntry(SSL_CTX *ctx,
1662 SSL_SESSION *session)
1665 SSLSrvConfigRec *sc;
1670 * Get Apache context back through OpenSSL context
1672 if (!(s = (server_rec *)SSL_CTX_get_app_data(ctx))) {
1673 return; /* on server shutdown Apache is already gone */
1676 sc = mySrvConfig(s);
1679 * Remove the SSL_SESSION from the inter-process cache
1681 id = SSL_SESSION_get_session_id(session);
1682 idlen = SSL_SESSION_get_session_id_length(session);
1684 ssl_scache_remove(s, id, idlen);
1686 ssl_session_log(s, "REM", id, idlen,
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.
1697 void ssl_callback_LogTracingState(SSL *ssl, int where, int rc)
1701 SSLSrvConfigRec *sc;
1704 * find corresponding server
1706 if (!(c = (conn_rec *)SSL_get_app_data((SSL *)ssl))) {
1711 if (!(sc = mySrvConfig(s))) {
1716 * create the various trace messages
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);
1723 else if (where & SSL_CB_HANDSHAKE_DONE) {
1724 ssl_log(s, SSL_LOG_TRACE,
1725 "%s: Handshake: done", SSL_LIBRARY_NAME);
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));
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));
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));
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));
1746 else if (where & SSL_CB_EXIT) {
1748 ssl_log(s, SSL_LOG_TRACE, "%s: Exit: failed in %s",
1749 SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1752 ssl_log(s, SSL_LOG_TRACE, "%s: Exit: error in %s",
1753 SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
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.
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"));