1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * _ __ ___ ___ __| | ___ ___| | mod_ssl
19 * | '_ ` _ \ / _ \ / _` | / __/ __| | Apache Interface to OpenSSL
20 * | | | | | | (_) | (_| | \__ \__ \ |
21 * |_| |_| |_|\___/ \__,_|___|___/___/_|
24 * The SSL engine kernel
26 /* ``It took me fifteen years to discover
27 I had no talent for programming, but
28 I couldn't give it up because by that
29 time I was too famous.''
31 #include "ssl_private.h"
33 static void ssl_configure_env(request_rec
*r
, SSLConnRec
*sslconn
);
34 #ifndef OPENSSL_NO_TLSEXT
35 static int ssl_find_vhost(void *servername
, conn_rec
*c
, server_rec
*s
);
38 #define SWITCH_STATUS_LINE "HTTP/1.1 101 Switching Protocols"
39 #define UPGRADE_HEADER "Upgrade: TLS/1.0, HTTP/1.1"
40 #define CONNECTION_HEADER "Connection: Upgrade"
42 /* Perform an upgrade-to-TLS for the given request, per RFC 2817. */
43 static apr_status_t
upgrade_connection(request_rec
*r
)
45 struct conn_rec
*conn
= r
->connection
;
46 apr_bucket_brigade
*bb
;
51 ap_log_rerror(APLOG_MARK
, APLOG_INFO
, 0, r
,
52 "upgrading connection to TLS");
54 bb
= apr_brigade_create(r
->pool
, conn
->bucket_alloc
);
56 rv
= ap_fputstrs(conn
->output_filters
, bb
, SWITCH_STATUS_LINE
, CRLF
,
57 UPGRADE_HEADER
, CRLF
, CONNECTION_HEADER
, CRLF
, CRLF
, NULL
);
58 if (rv
== APR_SUCCESS
) {
59 APR_BRIGADE_INSERT_TAIL(bb
,
60 apr_bucket_flush_create(conn
->bucket_alloc
));
61 rv
= ap_pass_brigade(conn
->output_filters
, bb
);
65 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
66 "failed to send 101 interim response for connection "
71 ssl_init_ssl_connection(conn
, r
);
73 sslconn
= myConnConfig(conn
);
76 /* Perform initial SSL handshake. */
77 SSL_set_accept_state(ssl
);
78 SSL_do_handshake(ssl
);
80 if (SSL_get_state(ssl
) != SSL_ST_OK
) {
81 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
82 "TLS upgrade handshake failed: not accepted by client!?");
84 return APR_ECONNABORTED
;
91 * Post Read Request Handler
93 int ssl_hook_ReadReq(request_rec
*r
)
95 SSLSrvConfigRec
*sc
= mySrvConfig(r
->server
);
98 #ifndef OPENSSL_NO_TLSEXT
99 const char *servername
;
103 /* Perform TLS upgrade here if "SSLEngine optional" is configured,
104 * SSL is not already set up for this connection, and the client
105 * has sent a suitable Upgrade header. */
106 if (sc
->enabled
== SSL_ENABLED_OPTIONAL
&& !myConnConfig(r
->connection
)
107 && (upgrade
= apr_table_get(r
->headers_in
, "Upgrade")) != NULL
108 && ap_find_token(r
->pool
, upgrade
, "TLS/1.0")) {
109 if (upgrade_connection(r
)) {
110 return HTTP_INTERNAL_SERVER_ERROR
;
114 sslconn
= myConnConfig(r
->connection
);
119 if (sslconn
->non_ssl_request
) {
123 int port
= ap_get_server_port(r
);
125 if (!ap_is_default_port(port
, r
)) {
126 thisport
= apr_psprintf(r
->pool
, ":%u", port
);
129 thisurl
= ap_escape_html(r
->pool
,
130 apr_psprintf(r
->pool
, "https://%s%s/",
131 ap_get_server_name(r
),
134 errmsg
= apr_psprintf(r
->pool
,
135 "Reason: You're speaking plain HTTP "
136 "to an SSL-enabled server port.<br />\n"
137 "Instead use the HTTPS scheme to access "
138 "this URL, please.<br />\n"
140 "<a href=\"%s\"><b>%s</b></a></blockquote>",
143 apr_table_setn(r
->notes
, "error-notes", errmsg
);
145 /* Now that we have caught this error, forget it. we are done
146 * with using SSL on this request.
148 sslconn
->non_ssl_request
= 0;
151 return HTTP_BAD_REQUEST
;
155 * Get the SSL connection structure and perform the
156 * delayed interlinking from SSL back to request_rec
162 #ifndef OPENSSL_NO_TLSEXT
164 (servername
= SSL_get_servername(ssl
, TLSEXT_NAMETYPE_host_name
))) {
165 /* Use the SNI extension as the hostname if no Host: header was sent */
166 r
->hostname
= apr_pstrdup(r
->pool
, servername
);
167 ap_update_vhost_from_headers(r
);
170 SSL_set_app_data2(ssl
, r
);
173 * Log information about incoming HTTPS requests
175 if (r
->server
->loglevel
>= APLOG_INFO
&& ap_is_initial_req(r
)) {
176 ap_log_error(APLOG_MARK
, APLOG_INFO
, 0, r
->server
,
177 "%s HTTPS request received for child %ld (server %s)",
178 (r
->connection
->keepalives
<= 0 ?
180 apr_psprintf(r
->pool
, "Subsequent (No.%d)",
181 r
->connection
->keepalives
+1)),
183 ssl_util_vhostid(r
->pool
, r
->server
));
186 /* SetEnvIf ssl-*-shutdown flags can only be per-server,
187 * so they won't change across keepalive requests
189 if (sslconn
->shutdown_type
== SSL_SHUTDOWN_TYPE_UNSET
) {
190 ssl_configure_env(r
, sslconn
);
197 * Move SetEnvIf information from request_rec to conn_rec/BUFF
198 * to allow the close connection handler to use them.
201 static void ssl_configure_env(request_rec
*r
, SSLConnRec
*sslconn
)
204 const apr_array_header_t
*arr
= apr_table_elts(r
->subprocess_env
);
205 const apr_table_entry_t
*elts
= (const apr_table_entry_t
*)arr
->elts
;
207 sslconn
->shutdown_type
= SSL_SHUTDOWN_TYPE_STANDARD
;
209 for (i
= 0; i
< arr
->nelts
; i
++) {
210 const char *key
= elts
[i
].key
;
214 /* being case-sensitive here.
215 * and not checking for the -shutdown since these are the only
216 * SetEnvIf "flags" we support
218 if (!strncmp(key
+1, "sl-", 3)) {
220 if (!strncmp(key
, "unclean", 7)) {
221 sslconn
->shutdown_type
= SSL_SHUTDOWN_TYPE_UNCLEAN
;
223 else if (!strncmp(key
, "accurate", 8)) {
224 sslconn
->shutdown_type
= SSL_SHUTDOWN_TYPE_ACCURATE
;
226 return; /* should only ever be one ssl-*-shutdown */
236 int ssl_hook_Access(request_rec
*r
)
238 SSLDirConfigRec
*dc
= myDirConfig(r
);
239 SSLSrvConfigRec
*sc
= mySrvConfig(r
->server
);
240 SSLConnRec
*sslconn
= myConnConfig(r
->connection
);
241 SSL
*ssl
= sslconn
? sslconn
->ssl
: NULL
;
243 apr_array_header_t
*requires
;
244 ssl_require_t
*ssl_requires
;
247 BOOL renegotiate
= FALSE
, renegotiate_quick
= FALSE
;
250 X509_STORE
*cert_store
= NULL
;
251 X509_STORE_CTX cert_store_ctx
;
252 STACK_OF(SSL_CIPHER
) *cipher_list_old
= NULL
, *cipher_list
= NULL
;
253 const SSL_CIPHER
*cipher
= NULL
;
254 int depth
, verify_old
, verify
, n
;
257 ctx
= SSL_get_SSL_CTX(ssl
);
261 * Support for SSLRequireSSL directive
263 if (dc
->bSSLRequired
&& !ssl
) {
264 if (sc
->enabled
== SSL_ENABLED_OPTIONAL
) {
265 /* This vhost was configured for optional SSL, just tell the
266 * client that we need to upgrade.
268 apr_table_setn(r
->err_headers_out
, "Upgrade", "TLS/1.0, HTTP/1.1");
269 apr_table_setn(r
->err_headers_out
, "Connection", "Upgrade");
271 return HTTP_UPGRADE_REQUIRED
;
274 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
275 "access to %s failed, reason: %s",
276 r
->filename
, "SSL connection required");
278 /* remember forbidden access for strict require option */
279 apr_table_setn(r
->notes
, "ssl-access-forbidden", "1");
281 return HTTP_FORBIDDEN
;
285 * Check to see whether SSL is in use; if it's not, then no
286 * further access control checks are relevant. (the test for
287 * sc->enabled is probably strictly unnecessary)
289 if (sc
->enabled
== SSL_ENABLED_FALSE
|| !ssl
) {
294 * Support for per-directory reconfigured SSL connection parameters.
296 * This is implemented by forcing an SSL renegotiation with the
297 * reconfigured parameter suite. But Apache's internal API processing
298 * makes our life very hard here, because when internal sub-requests occur
299 * we nevertheless should avoid multiple unnecessary SSL handshakes (they
300 * require extra network I/O and especially time to perform).
302 * But the optimization for filtering out the unnecessary handshakes isn't
303 * obvious and trivial. Especially because while Apache is in its
304 * sub-request processing the client could force additional handshakes,
305 * too. And these take place perhaps without our notice. So the only
306 * possibility is to explicitly _ask_ OpenSSL whether the renegotiation
307 * has to be performed or not. It has to performed when some parameters
308 * which were previously known (by us) are not those we've now
309 * reconfigured (as known by OpenSSL) or (in optimized way) at least when
310 * the reconfigured parameter suite is stronger (more restrictions) than
311 * the currently active one.
315 * Override of SSLCipherSuite
317 * We provide two options here:
319 * o The paranoid and default approach where we force a renegotiation when
320 * the cipher suite changed in _any_ way (which is straight-forward but
321 * often forces renegotiations too often and is perhaps not what the
322 * user actually wanted).
324 * o The optimized and still secure way where we force a renegotiation
325 * only if the currently active cipher is no longer contained in the
326 * reconfigured/new cipher suite. Any other changes are not important
327 * because it's the servers choice to select a cipher from the ones the
328 * client supports. So as long as the current cipher is still in the new
329 * cipher suite we're happy. Because we can assume we would have
330 * selected it again even when other (better) ciphers exists now in the
331 * new cipher suite. This approach is fine because the user explicitly
332 * has to enable this via ``SSLOptions +OptRenegotiate''. So we do no
333 * implicit optimizations.
335 if (dc
->szCipherSuite
) {
336 /* remember old state */
338 if (dc
->nOptions
& SSL_OPT_OPTRENEGOTIATE
) {
339 cipher
= SSL_get_current_cipher(ssl
);
342 cipher_list_old
= (STACK_OF(SSL_CIPHER
) *)SSL_get_ciphers(ssl
);
344 if (cipher_list_old
) {
345 cipher_list_old
= sk_SSL_CIPHER_dup(cipher_list_old
);
349 /* configure new state */
350 if (!modssl_set_cipher_list(ssl
, dc
->szCipherSuite
)) {
351 ap_log_rerror(APLOG_MARK
, APLOG_WARNING
, 0, r
,
352 "Unable to reconfigure (per-directory) "
353 "permitted SSL ciphers");
354 ssl_log_ssl_error(APLOG_MARK
, APLOG_ERR
, r
->server
);
356 if (cipher_list_old
) {
357 sk_SSL_CIPHER_free(cipher_list_old
);
360 return HTTP_FORBIDDEN
;
363 /* determine whether a renegotiation has to be forced */
364 cipher_list
= (STACK_OF(SSL_CIPHER
) *)SSL_get_ciphers(ssl
);
366 if (dc
->nOptions
& SSL_OPT_OPTRENEGOTIATE
) {
368 if ((!cipher
&& cipher_list
) ||
369 (cipher
&& !cipher_list
))
373 else if (cipher
&& cipher_list
&&
374 (sk_SSL_CIPHER_find(cipher_list
, cipher
) < 0))
381 if ((!cipher_list_old
&& cipher_list
) ||
382 (cipher_list_old
&& !cipher_list
))
386 else if (cipher_list_old
&& cipher_list
) {
388 !renegotiate
&& (n
< sk_SSL_CIPHER_num(cipher_list
));
391 SSL_CIPHER
*value
= sk_SSL_CIPHER_value(cipher_list
, n
);
393 if (sk_SSL_CIPHER_find(cipher_list_old
, value
) < 0) {
399 !renegotiate
&& (n
< sk_SSL_CIPHER_num(cipher_list_old
));
402 SSL_CIPHER
*value
= sk_SSL_CIPHER_value(cipher_list_old
, n
);
404 if (sk_SSL_CIPHER_find(cipher_list
, value
) < 0) {
412 if (cipher_list_old
) {
413 sk_SSL_CIPHER_free(cipher_list_old
);
418 ap_log_rerror(APLOG_MARK
, APLOG_DEBUG
, 0, r
,
419 "Reconfigured cipher suite will force renegotiation");
424 * override of SSLVerifyDepth
426 * The depth checks are handled by us manually inside the verify callback
427 * function and not by OpenSSL internally (and our function is aware of
428 * both the per-server and per-directory contexts). So we cannot ask
429 * OpenSSL about the currently verify depth. Instead we remember it in our
430 * ap_ctx attached to the SSL* of OpenSSL. We've to force the
431 * renegotiation if the reconfigured/new verify depth is less than the
432 * currently active/remembered verify depth (because this means more
433 * restriction on the certificate chain).
435 if ((sc
->server
->auth
.verify_depth
!= UNSET
) &&
436 (dc
->nVerifyDepth
== UNSET
)) {
437 /* apply per-vhost setting, if per-directory config is not set */
438 dc
->nVerifyDepth
= sc
->server
->auth
.verify_depth
;
440 if (dc
->nVerifyDepth
!= UNSET
) {
441 /* XXX: doesnt look like sslconn->verify_depth is actually used */
442 if (!(n
= sslconn
->verify_depth
)) {
443 sslconn
->verify_depth
= n
= sc
->server
->auth
.verify_depth
;
446 /* determine whether a renegotiation has to be forced */
447 if (dc
->nVerifyDepth
< n
) {
449 ap_log_rerror(APLOG_MARK
, APLOG_DEBUG
, 0, r
,
450 "Reduced client verification depth will force "
456 * override of SSLVerifyClient
458 * We force a renegotiation if the reconfigured/new verify type is
459 * stronger than the currently active verify type.
461 * The order is: none << optional_no_ca << optional << require
463 * Additionally the following optimization is possible here: When the
464 * currently active verify type is "none" but a client certificate is
465 * already known/present, it's enough to manually force a client
466 * verification but at least skip the I/O-intensive renegotation
469 if ((sc
->server
->auth
.verify_mode
!= SSL_CVERIFY_UNSET
) &&
470 (dc
->nVerifyClient
== SSL_CVERIFY_UNSET
)) {
471 /* apply per-vhost setting, if per-directory config is not set */
472 dc
->nVerifyClient
= sc
->server
->auth
.verify_mode
;
474 if (dc
->nVerifyClient
!= SSL_CVERIFY_UNSET
) {
475 /* remember old state */
476 verify_old
= SSL_get_verify_mode(ssl
);
477 /* configure new state */
478 verify
= SSL_VERIFY_NONE
;
480 if (dc
->nVerifyClient
== SSL_CVERIFY_REQUIRE
) {
481 verify
|= SSL_VERIFY_PEER_STRICT
;
484 if ((dc
->nVerifyClient
== SSL_CVERIFY_OPTIONAL
) ||
485 (dc
->nVerifyClient
== SSL_CVERIFY_OPTIONAL_NO_CA
))
487 verify
|= SSL_VERIFY_PEER
;
490 modssl_set_verify(ssl
, verify
, ssl_callback_SSLVerify
);
491 SSL_set_verify_result(ssl
, X509_V_OK
);
493 /* determine whether we've to force a renegotiation */
494 if (!renegotiate
&& verify
!= verify_old
) {
495 if (((verify_old
== SSL_VERIFY_NONE
) &&
496 (verify
!= SSL_VERIFY_NONE
)) ||
498 (!(verify_old
& SSL_VERIFY_PEER
) &&
499 (verify
& SSL_VERIFY_PEER
)) ||
501 (!(verify_old
& SSL_VERIFY_FAIL_IF_NO_PEER_CERT
) &&
502 (verify
& SSL_VERIFY_FAIL_IF_NO_PEER_CERT
)))
507 if ((dc
->nOptions
& SSL_OPT_OPTRENEGOTIATE
) &&
508 (verify_old
== SSL_VERIFY_NONE
) &&
509 ((peercert
= SSL_get_peer_certificate(ssl
)) != NULL
))
511 renegotiate_quick
= TRUE
;
515 ap_log_rerror(APLOG_MARK
, APLOG_DEBUG
, 0, r
,
516 "Changed client verification type will force "
518 renegotiate_quick
? "quick " : "");
524 * override SSLCACertificateFile & SSLCACertificatePath
525 * This is only enabled if the SSL_set_cert_store() function
526 * is available in the ssl library. the 1.x based mod_ssl
527 * used SSL_CTX_set_cert_store which is not thread safe.
530 #ifdef HAVE_SSL_SET_CERT_STORE
532 * check if per-dir and per-server config field are not the same.
533 * if f is defined in per-dir and not defined in per-server
534 * or f is defined in both but not the equal ...
536 #define MODSSL_CFG_NE(f) \
537 (dc->f && (!sc->f || (sc->f && strNE(dc->f, sc->f))))
539 #define MODSSL_CFG_CA(f) \
540 (dc->f ? dc->f : sc->f)
542 if (MODSSL_CFG_NE(szCACertificateFile
) ||
543 MODSSL_CFG_NE(szCACertificatePath
))
545 STACK_OF(X509_NAME
) *ca_list
;
546 const char *ca_file
= MODSSL_CFG_CA(szCACertificateFile
);
547 const char *ca_path
= MODSSL_CFG_CA(szCACertificatePath
);
549 cert_store
= X509_STORE_new();
551 if (!X509_STORE_load_locations(cert_store
, ca_file
, ca_path
)) {
552 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
553 "Unable to reconfigure verify locations "
554 "for client authentication");
555 ssl_log_ssl_error(APLOG_MARK
, APLOG_ERR
, r
->server
);
557 X509_STORE_free(cert_store
);
559 return HTTP_FORBIDDEN
;
562 /* SSL_free will free cert_store */
563 SSL_set_cert_store(ssl
, cert_store
);
565 if (!(ca_list
= ssl_init_FindCAList(r
->server
, r
->pool
,
568 ap_log_error(APLOG_MARK
, APLOG_ERR
, 0, r
->server
,
569 "Unable to determine list of available "
570 "CA certificates for client authentication");
572 return HTTP_FORBIDDEN
;
575 SSL_set_client_CA_list(ssl
, ca_list
);
578 ap_log_rerror(APLOG_MARK
, APLOG_DEBUG
, 0, r
,
579 "Changed client verification locations will force "
582 #endif /* HAVE_SSL_SET_CERT_STORE */
584 /* If a renegotiation is now required for this location, and the
585 * request includes a message body (and the client has not
586 * requested a "100 Continue" response), then the client will be
587 * streaming the request body over the wire already. In that
588 * case, it is not possible to stop and perform a new SSL
589 * handshake immediately; once the SSL library moves to the
590 * "accept" state, it will reject the SSL packets which the client
591 * is sending for the request body.
593 * To allow authentication to complete in this auth hook, the
594 * solution used here is to fill a (bounded) buffer with the
595 * request body, and then to reinject that request body later.
597 if (renegotiate
&& !renegotiate_quick
598 && (apr_table_get(r
->headers_in
, "transfer-encoding")
599 || (apr_table_get(r
->headers_in
, "content-length")
600 && strcmp(apr_table_get(r
->headers_in
, "content-length"), "0")))
601 && !r
->expecting_100
) {
605 rsize
= dc
->nRenegBufferSize
== UNSET
? DEFAULT_RENEG_BUFFER_SIZE
:
606 dc
->nRenegBufferSize
;
608 /* Fill the I/O buffer with the request body if possible. */
609 rv
= ssl_io_buffer_fill(r
, rsize
);
612 /* If the reneg buffer size is set to zero, just fail. */
613 rv
= HTTP_REQUEST_ENTITY_TOO_LARGE
;
617 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
618 "could not buffer message body to allow "
619 "SSL renegotiation to proceed");
625 * now do the renegotiation if anything was actually reconfigured
629 * Now we force the SSL renegotation by sending the Hello Request
630 * message to the client. Here we have to do a workaround: Actually
631 * OpenSSL returns immediately after sending the Hello Request (the
632 * intent AFAIK is because the SSL/TLS protocol says it's not a must
633 * that the client replies to a Hello Request). But because we insist
634 * on a reply (anything else is an error for us) we have to go to the
635 * ACCEPT state manually. Using SSL_set_accept_state() doesn't work
636 * here because it resets too much of the connection. So we set the
637 * state explicitly and continue the handshake manually.
639 ap_log_rerror(APLOG_MARK
, APLOG_INFO
, 0, r
,
640 "Requesting connection re-negotiation");
642 if (renegotiate_quick
) {
643 STACK_OF(X509
) *cert_stack
;
645 /* perform just a manual re-verification of the peer */
646 ap_log_rerror(APLOG_MARK
, APLOG_DEBUG
, 0, r
,
647 "Performing quick renegotiation: "
648 "just re-verifying the peer");
650 cert_stack
= (STACK_OF(X509
) *)SSL_get_peer_cert_chain(ssl
);
652 cert
= SSL_get_peer_certificate(ssl
);
654 if (!cert_stack
&& cert
) {
655 /* client cert is in the session cache, but there is
656 * no chain, since ssl3_get_client_certificate()
657 * sk_X509_shift-ed the peer cert out of the chain.
658 * we put it back here for the purpose of quick_renegotiation.
660 cert_stack
= sk_X509_new_null();
661 sk_X509_push(cert_stack
, MODSSL_PCHAR_CAST cert
);
664 if (!cert_stack
|| (sk_X509_num(cert_stack
) == 0)) {
665 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
666 "Cannot find peer certificate chain");
668 return HTTP_FORBIDDEN
;
672 (cert_store
= SSL_CTX_get_cert_store(ctx
))))
674 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
675 "Cannot find certificate storage");
677 return HTTP_FORBIDDEN
;
681 cert
= sk_X509_value(cert_stack
, 0);
684 X509_STORE_CTX_init(&cert_store_ctx
, cert_store
, cert
, cert_stack
);
685 depth
= SSL_get_verify_depth(ssl
);
688 X509_STORE_CTX_set_depth(&cert_store_ctx
, depth
);
691 X509_STORE_CTX_set_ex_data(&cert_store_ctx
,
692 SSL_get_ex_data_X509_STORE_CTX_idx(),
695 if (!modssl_X509_verify_cert(&cert_store_ctx
)) {
696 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
697 "Re-negotiation verification step failed");
698 ssl_log_ssl_error(APLOG_MARK
, APLOG_ERR
, r
->server
);
701 SSL_set_verify_result(ssl
, cert_store_ctx
.error
);
702 X509_STORE_CTX_cleanup(&cert_store_ctx
);
704 if (cert_stack
!= SSL_get_peer_cert_chain(ssl
)) {
705 /* we created this ourselves, so free it */
706 sk_X509_pop_free(cert_stack
, X509_free
);
710 request_rec
*id
= r
->main
? r
->main
: r
;
712 /* do a full renegotiation */
713 ap_log_rerror(APLOG_MARK
, APLOG_DEBUG
, 0, r
,
714 "Performing full renegotiation: "
715 "complete handshake protocol");
717 SSL_set_session_id_context(ssl
,
718 (unsigned char *)&id
,
721 SSL_renegotiate(ssl
);
722 SSL_do_handshake(ssl
);
724 if (SSL_get_state(ssl
) != SSL_ST_OK
) {
725 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
726 "Re-negotiation request failed");
728 r
->connection
->aborted
= 1;
729 return HTTP_FORBIDDEN
;
732 ap_log_rerror(APLOG_MARK
, APLOG_INFO
, 0, r
,
733 "Awaiting re-negotiation handshake");
735 /* XXX: Should replace SSL_set_state with SSL_renegotiate(ssl);
736 * However, this causes failures in perl-framework currently,
737 * perhaps pre-test if we have already negotiated?
739 SSL_set_state(ssl
, SSL_ST_ACCEPT
);
740 SSL_do_handshake(ssl
);
742 if (SSL_get_state(ssl
) != SSL_ST_OK
) {
743 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
744 "Re-negotiation handshake failed: "
745 "Not accepted by client!?");
747 r
->connection
->aborted
= 1;
748 return HTTP_FORBIDDEN
;
753 * Remember the peer certificate's DN
755 if ((cert
= SSL_get_peer_certificate(ssl
))) {
756 if (sslconn
->client_cert
) {
757 X509_free(sslconn
->client_cert
);
759 sslconn
->client_cert
= cert
;
760 sslconn
->client_dn
= NULL
;
764 * Finally check for acceptable renegotiation results
766 if (dc
->nVerifyClient
!= SSL_CVERIFY_NONE
) {
767 BOOL do_verify
= (dc
->nVerifyClient
== SSL_CVERIFY_REQUIRE
);
769 if (do_verify
&& (SSL_get_verify_result(ssl
) != X509_V_OK
)) {
770 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
771 "Re-negotiation handshake failed: "
772 "Client verification failed");
774 return HTTP_FORBIDDEN
;
778 if ((peercert
= SSL_get_peer_certificate(ssl
)) == NULL
) {
779 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
780 "Re-negotiation handshake failed: "
781 "Client certificate missing");
783 return HTTP_FORBIDDEN
;
791 * Also check that SSLCipherSuite has been enforced as expected.
794 cipher
= SSL_get_current_cipher(ssl
);
795 if (sk_SSL_CIPHER_find(cipher_list
, cipher
) < 0) {
796 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
797 "SSL cipher suite not renegotiated: "
798 "access to %s denied using cipher %s",
800 SSL_CIPHER_get_name(cipher
));
801 return HTTP_FORBIDDEN
;
806 /* If we're trying to have the user name set from a client
807 * certificate then we need to set it here. This should be safe as
808 * the user name probably isn't important from an auth checking point
809 * of view as the certificate supplied acts in that capacity.
810 * However, if FakeAuth is being used then this isn't the case so
811 * we need to postpone setting the username until later.
813 if ((dc
->nOptions
& SSL_OPT_FAKEBASICAUTH
) == 0 && dc
->szUserName
) {
814 char *val
= ssl_var_lookup(r
->pool
, r
->server
, r
->connection
,
815 r
, (char *)dc
->szUserName
);
819 ap_log_rerror(APLOG_MARK
, APLOG_WARNING
, 0, r
,
820 "Failed to set r->user to '%s'", dc
->szUserName
);
824 * Check SSLRequire boolean expressions
826 requires
= dc
->aRequirement
;
827 ssl_requires
= (ssl_require_t
*)requires
->elts
;
829 for (i
= 0; i
< requires
->nelts
; i
++) {
830 ssl_require_t
*req
= &ssl_requires
[i
];
831 ok
= ssl_expr_exec(r
, req
->mpExpr
);
834 cp
= apr_psprintf(r
->pool
,
836 "SSL requirement expression: %s",
837 ssl_expr_get_error());
839 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
840 "access to %s failed, reason: %s",
843 /* remember forbidden access for strict require option */
844 apr_table_setn(r
->notes
, "ssl-access-forbidden", "1");
846 return HTTP_FORBIDDEN
;
850 ap_log_rerror(APLOG_MARK
, APLOG_INFO
, 0, r
,
851 "Access to %s denied for %s "
852 "(requirement expression not fulfilled)",
853 r
->filename
, r
->connection
->remote_ip
);
855 ap_log_rerror(APLOG_MARK
, APLOG_INFO
, 0, r
,
856 "Failed expression: %s", req
->cpExpr
);
858 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
859 "access to %s failed, reason: %s",
861 "SSL requirement expression not fulfilled");
863 /* remember forbidden access for strict require option */
864 apr_table_setn(r
->notes
, "ssl-access-forbidden", "1");
866 return HTTP_FORBIDDEN
;
871 * Else access is granted from our point of view (except vendor
872 * handlers override). But we have to return DECLINED here instead
873 * of OK, because mod_auth and other modules still might want to
881 * Authentication Handler:
882 * Fake a Basic authentication from the X509 client certificate.
884 * This must be run fairly early on to prevent a real authentication from
885 * occuring, in particular it must be run before anything else that
886 * authenticates a user. This means that the Module statement for this
887 * module should be LAST in the Configuration file.
889 int ssl_hook_UserCheck(request_rec
*r
)
891 SSLConnRec
*sslconn
= myConnConfig(r
->connection
);
892 SSLSrvConfigRec
*sc
= mySrvConfig(r
->server
);
893 SSLDirConfigRec
*dc
= myDirConfig(r
);
895 const char *auth_line
, *username
, *password
;
898 * Additionally forbid access (again)
899 * when strict require option is used.
901 if ((dc
->nOptions
& SSL_OPT_STRICTREQUIRE
) &&
902 (apr_table_get(r
->notes
, "ssl-access-forbidden")))
904 return HTTP_FORBIDDEN
;
908 * We decline when we are in a subrequest. The Authorization header
909 * would already be present if it was added in the main request.
911 if (!ap_is_initial_req(r
)) {
916 * Make sure the user is not able to fake the client certificate
917 * based authentication by just entering an X.509 Subject DN
918 * ("/XX=YYY/XX=YYY/..") as the username and "password" as the
921 if ((auth_line
= apr_table_get(r
->headers_in
, "Authorization"))) {
922 if (strcEQ(ap_getword(r
->pool
, &auth_line
, ' '), "Basic")) {
923 while ((*auth_line
== ' ') || (*auth_line
== '\t')) {
927 auth_line
= ap_pbase64decode(r
->pool
, auth_line
);
928 username
= ap_getword_nulls(r
->pool
, &auth_line
, ':');
929 password
= auth_line
;
931 if ((username
[0] == '/') && strEQ(password
, "password")) {
932 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
933 "Encountered FakeBasicAuth spoof: %s", username
);
934 return HTTP_FORBIDDEN
;
940 * We decline operation in various situations...
941 * - SSLOptions +FakeBasicAuth not configured
942 * - r->user already authenticated
944 * - client did not present a certificate
946 if (!((sc
->enabled
== SSL_ENABLED_TRUE
|| sc
->enabled
== SSL_ENABLED_OPTIONAL
)
947 && sslconn
&& sslconn
->ssl
&& sslconn
->client_cert
) ||
948 !(dc
->nOptions
& SSL_OPT_FAKEBASICAUTH
) || r
->user
)
953 if (!sslconn
->client_dn
) {
954 X509_NAME
*name
= X509_get_subject_name(sslconn
->client_cert
);
955 char *cp
= X509_NAME_oneline(name
, NULL
, 0);
956 sslconn
->client_dn
= apr_pstrdup(r
->connection
->pool
, cp
);
960 clientdn
= (char *)sslconn
->client_dn
;
963 * Fake a password - which one would be immaterial, as, it seems, an empty
964 * password in the users file would match ALL incoming passwords, if only
965 * we were using the standard crypt library routine. Unfortunately, OpenSSL
966 * "fixes" a "bug" in crypt and thus prevents blank passwords from
967 * working. (IMHO what they really fix is a bug in the users of the code
968 * - failing to program correctly for shadow passwords). We need,
969 * therefore, to provide a password. This password can be matched by
970 * adding the string "xxj31ZMTZzkVA" as the password in the user file.
971 * This is just the crypted variant of the word "password" ;-)
973 auth_line
= apr_pstrcat(r
->pool
, "Basic ",
974 ap_pbase64encode(r
->pool
,
975 apr_pstrcat(r
->pool
, clientdn
,
978 apr_table_set(r
->headers_in
, "Authorization", auth_line
);
980 ap_log_rerror(APLOG_MARK
, APLOG_INFO
, 0, r
,
981 "Faking HTTP Basic Auth header: \"Authorization: %s\"",
987 /* authorization phase */
988 int ssl_hook_Auth(request_rec
*r
)
990 SSLDirConfigRec
*dc
= myDirConfig(r
);
993 * Additionally forbid access (again)
994 * when strict require option is used.
996 if ((dc
->nOptions
& SSL_OPT_STRICTREQUIRE
) &&
997 (apr_table_get(r
->notes
, "ssl-access-forbidden")))
999 return HTTP_FORBIDDEN
;
1009 static const char *ssl_hook_Fixup_vars
[] = {
1010 "SSL_VERSION_INTERFACE",
1011 "SSL_VERSION_LIBRARY",
1013 "SSL_COMPRESS_METHOD",
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",
1023 "SSL_CLIENT_V_REMAIN",
1026 "SSL_SERVER_M_VERSION",
1027 "SSL_SERVER_M_SERIAL",
1028 "SSL_SERVER_V_START",
1036 int ssl_hook_Fixup(request_rec
*r
)
1038 SSLConnRec
*sslconn
= myConnConfig(r
->connection
);
1039 SSLSrvConfigRec
*sc
= mySrvConfig(r
->server
);
1040 SSLDirConfigRec
*dc
= myDirConfig(r
);
1041 apr_table_t
*env
= r
->subprocess_env
;
1042 char *var
, *val
= "";
1043 #ifndef OPENSSL_NO_TLSEXT
1044 const char *servername
;
1046 STACK_OF(X509
) *peer_certs
;
1050 /* If "SSLEngine optional" is configured, this is not an SSL
1051 * connection, and this isn't a subrequest, send an Upgrade
1052 * response header. */
1053 if (sc
->enabled
== SSL_ENABLED_OPTIONAL
&& !(sslconn
&& sslconn
->ssl
)
1055 apr_table_setn(r
->headers_out
, "Upgrade", "TLS/1.0, HTTP/1.1");
1056 apr_table_mergen(r
->headers_out
, "Connection", "upgrade");
1060 * Check to see if SSL is on
1062 if (!(((sc
->enabled
== SSL_ENABLED_TRUE
) || (sc
->enabled
== SSL_ENABLED_OPTIONAL
)) && sslconn
&& (ssl
= sslconn
->ssl
))) {
1067 * Annotate the SSI/CGI environment with standard SSL information
1069 /* the always present HTTPS (=HTTP over SSL) flag! */
1070 apr_table_setn(env
, "HTTPS", "on");
1072 #ifndef OPENSSL_NO_TLSEXT
1073 /* add content of SNI TLS extension (if supplied with ClientHello) */
1074 if ((servername
= SSL_get_servername(ssl
, TLSEXT_NAMETYPE_host_name
))) {
1075 apr_table_set(env
, "SSL_TLS_SNI", servername
);
1079 /* standard SSL environment variables */
1080 if (dc
->nOptions
& SSL_OPT_STDENVVARS
) {
1081 modssl_var_extract_dns(env
, sslconn
->ssl
, r
->pool
);
1083 for (i
= 0; ssl_hook_Fixup_vars
[i
]; i
++) {
1084 var
= (char *)ssl_hook_Fixup_vars
[i
];
1085 val
= ssl_var_lookup(r
->pool
, r
->server
, r
->connection
, r
, var
);
1086 if (!strIsEmpty(val
)) {
1087 apr_table_setn(env
, var
, val
);
1093 * On-demand bloat up the SSI/CGI environment with certificate data
1095 if (dc
->nOptions
& SSL_OPT_EXPORTCERTDATA
) {
1096 val
= ssl_var_lookup(r
->pool
, r
->server
, r
->connection
,
1097 r
, "SSL_SERVER_CERT");
1099 apr_table_setn(env
, "SSL_SERVER_CERT", val
);
1101 val
= ssl_var_lookup(r
->pool
, r
->server
, r
->connection
,
1102 r
, "SSL_CLIENT_CERT");
1104 apr_table_setn(env
, "SSL_CLIENT_CERT", val
);
1106 if ((peer_certs
= (STACK_OF(X509
) *)SSL_get_peer_cert_chain(ssl
))) {
1107 for (i
= 0; i
< sk_X509_num(peer_certs
); i
++) {
1108 var
= apr_psprintf(r
->pool
, "SSL_CLIENT_CERT_CHAIN_%d", i
);
1109 val
= ssl_var_lookup(r
->pool
, r
->server
, r
->connection
,
1112 apr_table_setn(env
, var
, val
);
1121 /* _________________________________________________________________
1123 ** OpenSSL Callback Functions
1124 ** _________________________________________________________________
1128 * Handle out temporary RSA private keys on demand
1130 * The background of this as the TLSv1 standard explains it:
1132 * | D.1. Temporary RSA keys
1134 * | US Export restrictions limit RSA keys used for encryption to 512
1135 * | bits, but do not place any limit on lengths of RSA keys used for
1136 * | signing operations. Certificates often need to be larger than 512
1137 * | bits, since 512-bit RSA keys are not secure enough for high-value
1138 * | transactions or for applications requiring long-term security. Some
1139 * | certificates are also designated signing-only, in which case they
1140 * | cannot be used for key exchange.
1142 * | When the public key in the certificate cannot be used for encryption,
1143 * | the server signs a temporary RSA key, which is then exchanged. In
1144 * | exportable applications, the temporary RSA key should be the maximum
1145 * | allowable length (i.e., 512 bits). Because 512-bit RSA keys are
1146 * | relatively insecure, they should be changed often. For typical
1147 * | electronic commerce applications, it is suggested that keys be
1148 * | changed daily or every 500 transactions, and more often if possible.
1149 * | Note that while it is acceptable to use the same temporary key for
1150 * | multiple transactions, it must be signed each time it is used.
1152 * | RSA key generation is a time-consuming process. In many cases, a
1153 * | low-priority process can be assigned the task of key generation.
1154 * | Whenever a new key is completed, the existing temporary key can be
1155 * | replaced with the new one.
1157 * XXX: base on comment above, if thread support is enabled,
1158 * we should spawn a low-priority thread to generate new keys
1161 * So we generated 512 and 1024 bit temporary keys on startup
1162 * which we now just hand out on demand....
1165 RSA
*ssl_callback_TmpRSA(SSL
*ssl
, int export
, int keylen
)
1167 conn_rec
*c
= (conn_rec
*)SSL_get_app_data(ssl
);
1168 SSLModConfigRec
*mc
= myModConfig(c
->base_server
);
1171 ap_log_cerror(APLOG_MARK
, APLOG_DEBUG
, 0, c
,
1172 "handing out temporary %d bit RSA key", keylen
);
1174 /* doesn't matter if export flag is on,
1175 * we won't be asked for keylen > 512 in that case.
1176 * if we are asked for a keylen > 1024, it is too expensive
1177 * to generate on the fly.
1178 * XXX: any reason not to generate 2048 bit keys at startup?
1183 idx
= SSL_TMP_KEY_RSA_512
;
1188 idx
= SSL_TMP_KEY_RSA_1024
;
1191 return (RSA
*)mc
->pTmpKeys
[idx
];
1195 * Hand out the already generated DH parameters...
1197 DH
*ssl_callback_TmpDH(SSL
*ssl
, int export
, int keylen
)
1199 conn_rec
*c
= (conn_rec
*)SSL_get_app_data(ssl
);
1200 SSLModConfigRec
*mc
= myModConfig(c
->base_server
);
1203 ap_log_cerror(APLOG_MARK
, APLOG_DEBUG
, 0, c
,
1204 "handing out temporary %d bit DH key", keylen
);
1208 idx
= SSL_TMP_KEY_DH_512
;
1213 idx
= SSL_TMP_KEY_DH_1024
;
1216 return (DH
*)mc
->pTmpKeys
[idx
];
1220 * This OpenSSL callback function is called when OpenSSL
1221 * does client authentication and verifies the certificate chain.
1223 int ssl_callback_SSLVerify(int ok
, X509_STORE_CTX
*ctx
)
1225 /* Get Apache context back through OpenSSL context */
1226 SSL
*ssl
= X509_STORE_CTX_get_ex_data(ctx
,
1227 SSL_get_ex_data_X509_STORE_CTX_idx());
1228 conn_rec
*conn
= (conn_rec
*)SSL_get_app_data(ssl
);
1229 server_rec
*s
= conn
->base_server
;
1230 request_rec
*r
= (request_rec
*)SSL_get_app_data2(ssl
);
1232 SSLSrvConfigRec
*sc
= mySrvConfig(s
);
1233 SSLDirConfigRec
*dc
= r
? myDirConfig(r
) : NULL
;
1234 SSLConnRec
*sslconn
= myConnConfig(conn
);
1235 modssl_ctx_t
*mctx
= myCtxConfig(sslconn
, sc
);
1237 /* Get verify ingredients */
1238 int errnum
= X509_STORE_CTX_get_error(ctx
);
1239 int errdepth
= X509_STORE_CTX_get_error_depth(ctx
);
1243 * Log verification information
1245 ssl_log_cxerror(APLOG_MARK
, APLOG_DEBUG
, 0, conn
,
1246 X509_STORE_CTX_get_current_cert(ctx
),
1247 "Certificate Verification, depth %d",
1251 * Check for optionally acceptable non-verifiable issuer situation
1253 if (dc
&& (dc
->nVerifyClient
!= SSL_CVERIFY_UNSET
)) {
1254 verify
= dc
->nVerifyClient
;
1257 verify
= mctx
->auth
.verify_mode
;
1260 if (verify
== SSL_CVERIFY_NONE
) {
1262 * SSLProxyVerify is either not configured or set to "none".
1263 * (this callback doesn't happen in the server context if SSLVerify
1264 * is not configured or set to "none")
1269 if (ssl_verify_error_is_optional(errnum
) &&
1270 (verify
== SSL_CVERIFY_OPTIONAL_NO_CA
))
1272 ap_log_cerror(APLOG_MARK
, APLOG_DEBUG
, 0, conn
,
1273 "Certificate Verification: Verifiable Issuer is "
1274 "configured as optional, therefore we're accepting "
1277 sslconn
->verify_info
= "GENEROUS";
1282 * Perform OCSP/CRL-based revocation checks
1285 if (!(ok
= ssl_callback_SSLVerify_CRL(ok
, ctx
, conn
))) {
1286 errnum
= X509_STORE_CTX_get_error(ctx
);
1290 /* If there was an optional verification error, it's not
1291 * possible to perform OCSP validation since the issuer may be
1292 * missing/untrusted. Fail in that case. */
1293 if (ok
&& ssl_verify_error_is_optional(errnum
)
1294 && sc
->server
->ocsp_enabled
) {
1295 X509_STORE_CTX_set_error(ctx
, X509_V_ERR_APPLICATION_VERIFICATION
);
1296 errnum
= X509_V_ERR_APPLICATION_VERIFICATION
;
1297 ap_log_cerror(APLOG_MARK
, APLOG_ERR
, 0, conn
,
1298 "cannot perform OCSP validation for cert "
1299 "if issuer has not been verified "
1300 "(optional_no_ca configured)");
1304 if (ok
&& sc
->server
->ocsp_enabled
) {
1305 ok
= modssl_verify_ocsp(ctx
, sc
, s
, conn
, conn
->pool
);
1307 errnum
= X509_STORE_CTX_get_error(ctx
);
1314 * If we already know it's not ok, log the real reason
1317 ap_log_cerror(APLOG_MARK
, APLOG_ERR
, 0, conn
,
1318 "Certificate Verification: Error (%d): %s",
1319 errnum
, X509_verify_cert_error_string(errnum
));
1321 if (sslconn
->client_cert
) {
1322 X509_free(sslconn
->client_cert
);
1323 sslconn
->client_cert
= NULL
;
1325 sslconn
->client_dn
= NULL
;
1326 sslconn
->verify_error
= X509_verify_cert_error_string(errnum
);
1330 * Finally check the depth of the certificate verification
1332 if (dc
&& (dc
->nVerifyDepth
!= UNSET
)) {
1333 depth
= dc
->nVerifyDepth
;
1336 depth
= mctx
->auth
.verify_depth
;
1339 if (errdepth
> depth
) {
1340 ap_log_cerror(APLOG_MARK
, APLOG_ERR
, 0, conn
,
1341 "Certificate Verification: Certificate Chain too long "
1342 "(chain has %d certificates, but maximum allowed are "
1346 errnum
= X509_V_ERR_CERT_CHAIN_TOO_LONG
;
1347 sslconn
->verify_error
= X509_verify_cert_error_string(errnum
);
1353 * And finally signal OpenSSL the (perhaps changed) state
1358 int ssl_callback_SSLVerify_CRL(int ok
, X509_STORE_CTX
*ctx
, conn_rec
*c
)
1360 server_rec
*s
= c
->base_server
;
1361 SSLSrvConfigRec
*sc
= mySrvConfig(s
);
1362 SSLConnRec
*sslconn
= myConnConfig(c
);
1363 modssl_ctx_t
*mctx
= myCtxConfig(sslconn
, sc
);
1365 X509_NAME
*subject
, *issuer
;
1372 * Unless a revocation store for CRLs was created we
1373 * cannot do any CRL-based verification, of course.
1380 * Determine certificate ingredients in advance
1382 cert
= X509_STORE_CTX_get_current_cert(ctx
);
1383 subject
= X509_get_subject_name(cert
);
1384 issuer
= X509_get_issuer_name(cert
);
1387 * OpenSSL provides the general mechanism to deal with CRLs but does not
1388 * use them automatically when verifying certificates, so we do it
1389 * explicitly here. We will check the CRL for the currently checked
1390 * certificate, if there is such a CRL in the store.
1392 * We come through this procedure for each certificate in the certificate
1393 * chain, starting with the root-CA's certificate. At each step we've to
1394 * both verify the signature on the CRL (to make sure it's a valid CRL)
1395 * and it's revocation list (to make sure the current certificate isn't
1396 * revoked). But because to check the signature on the CRL we need the
1397 * public key of the issuing CA certificate (which was already processed
1398 * one round before), we've a little problem. But we can both solve it and
1399 * at the same time optimize the processing by using the following
1400 * verification scheme (idea and code snippets borrowed from the GLOBUS
1403 * 1. We'll check the signature of a CRL in each step when we find a CRL
1404 * through the _subject_ name of the current certificate. This CRL
1405 * itself will be needed the first time in the next round, of course.
1406 * But we do the signature processing one round before this where the
1407 * public key of the CA is available.
1409 * 2. We'll check the revocation list of a CRL in each step when
1410 * we find a CRL through the _issuer_ name of the current certificate.
1411 * This CRLs signature was then already verified one round before.
1413 * This verification scheme allows a CA to revoke its own certificate as
1418 * Try to retrieve a CRL corresponding to the _subject_ of
1419 * the current certificate in order to verify it's integrity.
1421 memset((char *)&obj
, 0, sizeof(obj
));
1422 rc
= SSL_X509_STORE_lookup(mctx
->crl
,
1423 X509_LU_CRL
, subject
, &obj
);
1426 if ((rc
> 0) && crl
) {
1428 * Log information about CRL
1429 * (A little bit complicated because of ASN.1 and BIOs...)
1431 if (s
->loglevel
>= APLOG_DEBUG
) {
1432 char buff
[512]; /* should be plenty */
1433 BIO
*bio
= BIO_new(BIO_s_mem());
1435 BIO_printf(bio
, "CA CRL: Issuer: ");
1436 X509_NAME_print(bio
, issuer
, 0);
1438 BIO_printf(bio
, ", lastUpdate: ");
1439 ASN1_UTCTIME_print(bio
, X509_CRL_get_lastUpdate(crl
));
1441 BIO_printf(bio
, ", nextUpdate: ");
1442 ASN1_UTCTIME_print(bio
, X509_CRL_get_nextUpdate(crl
));
1444 n
= BIO_read(bio
, buff
, sizeof(buff
) - 1);
1449 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, s
, "%s", buff
);
1453 * Verify the signature on this CRL
1455 pubkey
= X509_get_pubkey(cert
);
1456 rc
= X509_CRL_verify(crl
, pubkey
);
1457 #ifdef OPENSSL_VERSION_NUMBER
1458 /* Only refcounted in OpenSSL */
1460 EVP_PKEY_free(pubkey
);
1463 ap_log_error(APLOG_MARK
, APLOG_WARNING
, 0, s
,
1464 "Invalid signature on CRL");
1466 X509_STORE_CTX_set_error(ctx
, X509_V_ERR_CRL_SIGNATURE_FAILURE
);
1467 X509_OBJECT_free_contents(&obj
);
1472 * Check date of CRL to make sure it's not expired
1474 i
= X509_cmp_current_time(X509_CRL_get_nextUpdate(crl
));
1477 ap_log_error(APLOG_MARK
, APLOG_WARNING
, 0, s
,
1478 "Found CRL has invalid nextUpdate field");
1480 X509_STORE_CTX_set_error(ctx
,
1481 X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD
);
1482 X509_OBJECT_free_contents(&obj
);
1488 ap_log_error(APLOG_MARK
, APLOG_WARNING
, 0, s
,
1489 "Found CRL is expired - "
1490 "revoking all certificates until you get updated CRL");
1492 X509_STORE_CTX_set_error(ctx
, X509_V_ERR_CRL_HAS_EXPIRED
);
1493 X509_OBJECT_free_contents(&obj
);
1498 X509_OBJECT_free_contents(&obj
);
1502 * Try to retrieve a CRL corresponding to the _issuer_ of
1503 * the current certificate in order to check for revocation.
1505 memset((char *)&obj
, 0, sizeof(obj
));
1506 rc
= SSL_X509_STORE_lookup(mctx
->crl
,
1507 X509_LU_CRL
, issuer
, &obj
);
1510 if ((rc
> 0) && crl
) {
1512 * Check if the current certificate is revoked by this CRL
1514 n
= sk_X509_REVOKED_num(X509_CRL_get_REVOKED(crl
));
1516 for (i
= 0; i
< n
; i
++) {
1517 X509_REVOKED
*revoked
=
1518 sk_X509_REVOKED_value(X509_CRL_get_REVOKED(crl
), i
);
1520 ASN1_INTEGER
*sn
= X509_REVOKED_get_serialNumber(revoked
);
1522 if (!ASN1_INTEGER_cmp(sn
, X509_get_serialNumber(cert
))) {
1523 if (s
->loglevel
>= APLOG_DEBUG
) {
1524 char *cp
= X509_NAME_oneline(issuer
, NULL
, 0);
1525 long serial
= ASN1_INTEGER_get(sn
);
1527 ap_log_error(APLOG_MARK
, APLOG_INFO
, 0, s
,
1528 "Certificate with serial %ld (0x%lX) "
1529 "revoked per CRL from issuer %s",
1530 serial
, serial
, cp
);
1534 X509_STORE_CTX_set_error(ctx
, X509_V_ERR_CERT_REVOKED
);
1535 X509_OBJECT_free_contents(&obj
);
1541 X509_OBJECT_free_contents(&obj
);
1547 #define SSLPROXY_CERT_CB_LOG_FMT \
1548 "Proxy client certificate callback: (%s) "
1550 static void modssl_proxy_info_log(server_rec
*s
,
1554 SSLSrvConfigRec
*sc
= mySrvConfig(s
);
1559 if (s
->loglevel
< APLOG_DEBUG
) {
1563 name
= X509_get_subject_name(info
->x509
);
1564 dn
= X509_NAME_oneline(name
, name_buf
, sizeof(name_buf
));
1566 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, s
,
1567 SSLPROXY_CERT_CB_LOG_FMT
"%s, sending %s",
1568 sc
->vhost_id
, msg
, dn
? dn
: "-uknown-");
1572 * caller will decrement the cert and key reference
1573 * so we need to increment here to prevent them from
1576 #define modssl_set_cert_info(info, cert, pkey) \
1577 *cert = info->x509; \
1578 X509_reference_inc(*cert); \
1579 *pkey = info->x_pkey->dec_pkey; \
1580 EVP_PKEY_reference_inc(*pkey)
1582 int ssl_callback_proxy_cert(SSL
*ssl
, MODSSL_CLIENT_CERT_CB_ARG_TYPE
**x509
, EVP_PKEY
**pkey
)
1584 conn_rec
*c
= (conn_rec
*)SSL_get_app_data(ssl
);
1585 server_rec
*s
= c
->base_server
;
1586 SSLSrvConfigRec
*sc
= mySrvConfig(s
);
1587 X509_NAME
*ca_name
, *issuer
;
1589 STACK_OF(X509_NAME
) *ca_list
;
1590 STACK_OF(X509_INFO
) *certs
= sc
->proxy
->pkp
->certs
;
1593 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, s
,
1594 SSLPROXY_CERT_CB_LOG_FMT
"entered",
1597 if (!certs
|| (sk_X509_INFO_num(certs
) <= 0)) {
1598 ap_log_error(APLOG_MARK
, APLOG_WARNING
, 0, s
,
1599 SSLPROXY_CERT_CB_LOG_FMT
1600 "downstream server wanted client certificate "
1601 "but none are configured", sc
->vhost_id
);
1605 ca_list
= SSL_get_client_CA_list(ssl
);
1607 if (!ca_list
|| (sk_X509_NAME_num(ca_list
) <= 0)) {
1609 * downstream server didn't send us a list of acceptable CA certs,
1610 * so we send the first client cert in the list.
1612 info
= sk_X509_INFO_value(certs
, 0);
1614 modssl_proxy_info_log(s
, info
, "no acceptable CA list");
1616 modssl_set_cert_info(info
, x509
, pkey
);
1621 for (i
= 0; i
< sk_X509_NAME_num(ca_list
); i
++) {
1622 ca_name
= sk_X509_NAME_value(ca_list
, i
);
1624 for (j
= 0; j
< sk_X509_INFO_num(certs
); j
++) {
1625 info
= sk_X509_INFO_value(certs
, j
);
1626 issuer
= X509_get_issuer_name(info
->x509
);
1628 if (X509_NAME_cmp(issuer
, ca_name
) == 0) {
1629 modssl_proxy_info_log(s
, info
, "found acceptable cert");
1631 modssl_set_cert_info(info
, x509
, pkey
);
1638 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, s
,
1639 SSLPROXY_CERT_CB_LOG_FMT
1640 "no client certificate found!?", sc
->vhost_id
);
1645 static void ssl_session_log(server_rec
*s
,
1646 const char *request
,
1653 char buf
[SSL_SESSION_ID_STRING_LEN
];
1654 char timeout_str
[56] = {'\0'};
1656 if (s
->loglevel
< APLOG_DEBUG
) {
1661 apr_snprintf(timeout_str
, sizeof(timeout_str
),
1662 "timeout=%lds ", (timeout
- time(NULL
)));
1665 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, s
,
1666 "Inter-Process Session Cache: "
1667 "request=%s status=%s id=%s %s(session %s)",
1669 SSL_SESSION_id2sz(id
, idlen
, buf
, sizeof(buf
)),
1670 timeout_str
, result
);
1674 * This callback function is executed by OpenSSL whenever a new SSL_SESSION is
1675 * added to the internal OpenSSL session cache. We use this hook to spread the
1676 * SSL_SESSION also to the inter-process disk-cache to make share it with our
1677 * other Apache pre-forked server processes.
1679 int ssl_callback_NewSessionCacheEntry(SSL
*ssl
, SSL_SESSION
*session
)
1681 /* Get Apache context back through OpenSSL context */
1682 conn_rec
*conn
= (conn_rec
*)SSL_get_app_data(ssl
);
1683 server_rec
*s
= conn
->base_server
;
1684 SSLSrvConfigRec
*sc
= mySrvConfig(s
);
1685 long timeout
= sc
->session_cache_timeout
;
1691 * Set the timeout also for the internal OpenSSL cache, because this way
1692 * our inter-process cache is consulted only when it's really necessary.
1694 SSL_set_timeout(session
, timeout
);
1697 * Store the SSL_SESSION in the inter-process cache with the
1698 * same expire time, so it expires automatically there, too.
1700 id
= SSL_SESSION_get_session_id(session
);
1701 idlen
= SSL_SESSION_get_session_id_length(session
);
1703 timeout
+= modssl_session_get_time(session
);
1705 rc
= ssl_scache_store(s
, id
, idlen
, timeout
, session
, conn
->pool
);
1707 ssl_session_log(s
, "SET", id
, idlen
,
1708 rc
== TRUE
? "OK" : "BAD",
1709 "caching", timeout
);
1712 * return 0 which means to OpenSSL that the session is still
1713 * valid and was not freed by us with SSL_SESSION_free().
1719 * This callback function is executed by OpenSSL whenever a
1720 * SSL_SESSION is looked up in the internal OpenSSL cache and it
1721 * was not found. We use this to lookup the SSL_SESSION in the
1722 * inter-process disk-cache where it was perhaps stored by one
1723 * of our other Apache pre-forked server processes.
1725 SSL_SESSION
*ssl_callback_GetSessionCacheEntry(SSL
*ssl
,
1727 int idlen
, int *do_copy
)
1729 /* Get Apache context back through OpenSSL context */
1730 conn_rec
*conn
= (conn_rec
*)SSL_get_app_data(ssl
);
1731 server_rec
*s
= conn
->base_server
;
1732 SSL_SESSION
*session
;
1735 * Try to retrieve the SSL_SESSION from the inter-process cache
1737 session
= ssl_scache_retrieve(s
, id
, idlen
, conn
->pool
);
1739 ssl_session_log(s
, "GET", id
, idlen
,
1740 session
? "FOUND" : "MISSED",
1741 session
? "reuse" : "renewal", 0);
1744 * Return NULL or the retrieved SSL_SESSION. But indicate (by
1745 * setting do_copy to 0) that the reference count on the
1746 * SSL_SESSION should not be incremented by the SSL library,
1747 * because we will no longer hold a reference to it ourself.
1755 * This callback function is executed by OpenSSL whenever a
1756 * SSL_SESSION is removed from the the internal OpenSSL cache.
1757 * We use this to remove the SSL_SESSION in the inter-process
1760 void ssl_callback_DelSessionCacheEntry(SSL_CTX
*ctx
,
1761 SSL_SESSION
*session
)
1764 SSLSrvConfigRec
*sc
;
1769 * Get Apache context back through OpenSSL context
1771 if (!(s
= (server_rec
*)SSL_CTX_get_app_data(ctx
))) {
1772 return; /* on server shutdown Apache is already gone */
1775 sc
= mySrvConfig(s
);
1778 * Remove the SSL_SESSION from the inter-process cache
1780 id
= SSL_SESSION_get_session_id(session
);
1781 idlen
= SSL_SESSION_get_session_id_length(session
);
1783 /* TODO: Do we need a temp pool here, or are we always shutting down? */
1784 ssl_scache_remove(s
, id
, idlen
, sc
->mc
->pPool
);
1786 ssl_session_log(s
, "REM", id
, idlen
,
1793 * This callback function is executed while OpenSSL processes the
1794 * SSL handshake and does SSL record layer stuff. We use it to
1795 * trace OpenSSL's processing in out SSL logfile.
1797 void ssl_callback_LogTracingState(MODSSL_INFO_CB_ARG_TYPE ssl
, int where
, int rc
)
1801 SSLSrvConfigRec
*sc
;
1804 * find corresponding server
1806 if (!(c
= (conn_rec
*)SSL_get_app_data((SSL
*)ssl
))) {
1811 if (!(sc
= mySrvConfig(s
))) {
1816 * create the various trace messages
1818 if (s
->loglevel
>= APLOG_DEBUG
) {
1819 if (where
& SSL_CB_HANDSHAKE_START
) {
1820 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, s
,
1821 "%s: Handshake: start", SSL_LIBRARY_NAME
);
1823 else if (where
& SSL_CB_HANDSHAKE_DONE
) {
1824 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, s
,
1825 "%s: Handshake: done", SSL_LIBRARY_NAME
);
1827 else if (where
& SSL_CB_LOOP
) {
1828 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, s
,
1830 SSL_LIBRARY_NAME
, SSL_state_string_long(ssl
));
1832 else if (where
& SSL_CB_READ
) {
1833 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, s
,
1835 SSL_LIBRARY_NAME
, SSL_state_string_long(ssl
));
1837 else if (where
& SSL_CB_WRITE
) {
1838 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, s
,
1840 SSL_LIBRARY_NAME
, SSL_state_string_long(ssl
));
1842 else if (where
& SSL_CB_ALERT
) {
1843 char *str
= (where
& SSL_CB_READ
) ? "read" : "write";
1844 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, s
,
1845 "%s: Alert: %s:%s:%s",
1846 SSL_LIBRARY_NAME
, str
,
1847 SSL_alert_type_string_long(rc
),
1848 SSL_alert_desc_string_long(rc
));
1850 else if (where
& SSL_CB_EXIT
) {
1852 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, s
,
1853 "%s: Exit: failed in %s",
1854 SSL_LIBRARY_NAME
, SSL_state_string_long(ssl
));
1857 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, s
,
1858 "%s: Exit: error in %s",
1859 SSL_LIBRARY_NAME
, SSL_state_string_long(ssl
));
1865 * Because SSL renegotations can happen at any time (not only after
1866 * SSL_accept()), the best way to log the current connection details is
1867 * right after a finished handshake.
1869 if (where
& SSL_CB_HANDSHAKE_DONE
) {
1870 ap_log_error(APLOG_MARK
, APLOG_INFO
, 0, s
,
1871 "Connection: Client IP: %s, Protocol: %s, "
1872 "Cipher: %s (%s/%s bits)",
1873 ssl_var_lookup(NULL
, s
, c
, NULL
, "REMOTE_ADDR"),
1874 ssl_var_lookup(NULL
, s
, c
, NULL
, "SSL_PROTOCOL"),
1875 ssl_var_lookup(NULL
, s
, c
, NULL
, "SSL_CIPHER"),
1876 ssl_var_lookup(NULL
, s
, c
, NULL
, "SSL_CIPHER_USEKEYSIZE"),
1877 ssl_var_lookup(NULL
, s
, c
, NULL
, "SSL_CIPHER_ALGKEYSIZE"));
1881 #ifndef OPENSSL_NO_TLSEXT
1883 * This callback function is executed when OpenSSL encounters an extended
1884 * client hello with a server name indication extension ("SNI", cf. RFC 4366).
1886 int ssl_callback_ServerNameIndication(SSL
*ssl
, int *al
, modssl_ctx_t
*mctx
)
1888 const char *servername
=
1889 SSL_get_servername(ssl
, TLSEXT_NAMETYPE_host_name
);
1892 conn_rec
*c
= (conn_rec
*)SSL_get_app_data(ssl
);
1894 if (ap_vhost_iterate_given_conn(c
, ssl_find_vhost
,
1895 (void *)servername
)) {
1896 ap_log_cerror(APLOG_MARK
, APLOG_DEBUG
, 0, c
,
1897 "SSL virtual host for servername %s found",
1899 return SSL_TLSEXT_ERR_OK
;
1902 ap_log_cerror(APLOG_MARK
, APLOG_DEBUG
, 0, c
,
1903 "No matching SSL virtual host for servername "
1904 "%s found (using default/first virtual host)",
1906 return SSL_TLSEXT_ERR_ALERT_WARNING
;
1911 return SSL_TLSEXT_ERR_NOACK
;
1915 * Find a (name-based) SSL virtual host where either the ServerName
1916 * or one of the ServerAliases matches the supplied name (to be used
1917 * with ap_vhost_iterate_given_conn())
1919 static int ssl_find_vhost(void *servername
, conn_rec
*c
, server_rec
*s
)
1921 SSLSrvConfigRec
*sc
;
1924 apr_array_header_t
*names
;
1927 /* check ServerName */
1928 if (!strcasecmp(servername
, s
->server_hostname
)) {
1933 * if not matched yet, check ServerAlias entries
1934 * (adapted from vhost.c:matches_aliases())
1939 char **name
= (char **)names
->elts
;
1940 for (i
= 0; i
< names
->nelts
; ++i
) {
1943 if (!strcasecmp(servername
, name
[i
])) {
1951 /* if still no match, check ServerAlias entries with wildcards */
1953 names
= s
->wild_names
;
1955 char **name
= (char **)names
->elts
;
1956 for (i
= 0; i
< names
->nelts
; ++i
) {
1959 if (!ap_strcasecmp_match(servername
, name
[i
])) {
1967 /* set SSL_CTX (if matched) */
1968 if (found
&& (ssl
= ((SSLConnRec
*)myConnConfig(c
))->ssl
) &&
1969 (sc
= mySrvConfig(s
))) {
1970 SSL_set_SSL_CTX(ssl
, sc
->server
->ssl_ctx
);
1972 * SSL_set_SSL_CTX() only deals with the server cert,
1973 * so we need to duplicate a few additional settings
1974 * from the ctx by hand
1976 SSL_set_options(ssl
, SSL_CTX_get_options(ssl
->ctx
));
1977 if ((SSL_get_verify_mode(ssl
) == SSL_VERIFY_NONE
) ||
1978 (SSL_num_renegotiations(ssl
) == 0)) {
1980 * Only initialize the verification settings from the ctx
1981 * if they are not yet set, or if we're called when a new
1982 * SSL connection is set up (num_renegotiations == 0).
1983 * Otherwise, we would possibly reset a per-directory
1984 * configuration which was put into effect by ssl_hook_Access.
1986 SSL_set_verify(ssl
, SSL_CTX_get_verify_mode(ssl
->ctx
),
1987 SSL_CTX_get_verify_callback(ssl
->ctx
));
1991 * We also need to make sure that the correct mctx
1992 * (accessed through the c->base_server->module_config vector)
1993 * is assigned to the connection - the CRL callback e.g.
1994 * makes use of it for retrieving its store (mctx->crl).
1995 * Since logging in callbacks uses c->base_server in many
1996 * cases, it also ensures that these messages are routed
1997 * to the proper log.
2002 * There is one special filter callback, which is set
2003 * very early depending on the base_server's log level.
2004 * If this is not the first vhost we're now selecting
2005 * (and the first vhost doesn't use APLOG_DEBUG), then
2006 * we need to set that callback here.
2008 if (c
->base_server
->loglevel
>= APLOG_DEBUG
) {
2009 BIO_set_callback(SSL_get_rbio(ssl
), ssl_io_data_cb
);
2010 BIO_set_callback_arg(SSL_get_rbio(ssl
), (void *)ssl
);