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.''
33 static void ssl_configure_env(request_rec *r, SSLConnRec *sslconn);
35 /* Perform a speculative (and non-blocking) read from the connection
36 * filters for the given request, to determine whether there is any
37 * pending data to read. Return non-zero if there is, else zero. */
38 static int has_buffered_data(request_rec *r)
40 apr_bucket_brigade *bb;
45 bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
47 rv = ap_get_brigade(r->connection->input_filters, bb, AP_MODE_SPECULATIVE,
48 APR_NONBLOCK_READ, 1);
49 result = rv == APR_SUCCESS
50 && apr_brigade_length(bb, 1, &len) == APR_SUCCESS
53 apr_brigade_destroy(bb);
59 * Post Read Request Handler
61 int ssl_hook_ReadReq(request_rec *r)
63 SSLConnRec *sslconn = myConnConfig(r->connection);
70 if (sslconn->non_ssl_request) {
74 int port = ap_get_server_port(r);
76 if (!ap_is_default_port(port, r)) {
77 thisport = apr_psprintf(r->pool, ":%u", port);
80 thisurl = ap_escape_html(r->pool,
81 apr_psprintf(r->pool, "https://%s%s/",
82 ap_get_server_name(r),
85 errmsg = apr_psprintf(r->pool,
86 "Reason: You're speaking plain HTTP "
87 "to an SSL-enabled server port.<br />\n"
88 "Instead use the HTTPS scheme to access "
89 "this URL, please.<br />\n"
91 "<a href=\"%s\"><b>%s</b></a></blockquote>",
94 apr_table_setn(r->notes, "error-notes", errmsg);
96 /* Now that we have caught this error, forget it. we are done
97 * with using SSL on this request.
99 sslconn->non_ssl_request = 0;
102 return HTTP_BAD_REQUEST;
106 * Get the SSL connection structure and perform the
107 * delayed interlinking from SSL back to request_rec
113 SSL_set_app_data2(ssl, r);
116 * Log information about incoming HTTPS requests
118 if (r->server->loglevel >= APLOG_INFO && ap_is_initial_req(r)) {
119 ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
120 "%s HTTPS request received for child %ld (server %s)",
121 (r->connection->keepalives <= 0 ?
123 apr_psprintf(r->pool, "Subsequent (No.%d)",
124 r->connection->keepalives+1)),
126 ssl_util_vhostid(r->pool, r->server));
129 /* SetEnvIf ssl-*-shutdown flags can only be per-server,
130 * so they won't change across keepalive requests
132 if (sslconn->shutdown_type == SSL_SHUTDOWN_TYPE_UNSET) {
133 ssl_configure_env(r, sslconn);
140 * Move SetEnvIf information from request_rec to conn_rec/BUFF
141 * to allow the close connection handler to use them.
144 static void ssl_configure_env(request_rec *r, SSLConnRec *sslconn)
147 const apr_array_header_t *arr = apr_table_elts(r->subprocess_env);
148 const apr_table_entry_t *elts = (const apr_table_entry_t *)arr->elts;
150 sslconn->shutdown_type = SSL_SHUTDOWN_TYPE_STANDARD;
152 for (i = 0; i < arr->nelts; i++) {
153 const char *key = elts[i].key;
157 /* being case-sensitive here.
158 * and not checking for the -shutdown since these are the only
159 * SetEnvIf "flags" we support
161 if (!strncmp(key+1, "sl-", 3)) {
163 if (!strncmp(key, "unclean", 7)) {
164 sslconn->shutdown_type = SSL_SHUTDOWN_TYPE_UNCLEAN;
166 else if (!strncmp(key, "accurate", 8)) {
167 sslconn->shutdown_type = SSL_SHUTDOWN_TYPE_ACCURATE;
169 return; /* should only ever be one ssl-*-shutdown */
179 int ssl_hook_Access(request_rec *r)
181 SSLDirConfigRec *dc = myDirConfig(r);
182 SSLSrvConfigRec *sc = mySrvConfig(r->server);
183 SSLConnRec *sslconn = myConnConfig(r->connection);
184 SSL *ssl = sslconn ? sslconn->ssl : NULL;
186 apr_array_header_t *requires;
187 ssl_require_t *ssl_requires;
190 BOOL renegotiate = FALSE, renegotiate_quick = FALSE;
193 X509_STORE *cert_store = NULL;
194 X509_STORE_CTX cert_store_ctx;
195 STACK_OF(SSL_CIPHER) *cipher_list_old = NULL, *cipher_list = NULL;
196 SSL_CIPHER *cipher = NULL;
197 int depth, verify_old, verify, n;
200 ctx = SSL_get_SSL_CTX(ssl);
204 * Support for SSLRequireSSL directive
206 if (dc->bSSLRequired && !ssl) {
207 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
208 "access to %s failed, reason: %s",
209 r->filename, "SSL connection required");
211 /* remember forbidden access for strict require option */
212 apr_table_setn(r->notes, "ssl-access-forbidden", "1");
214 return HTTP_FORBIDDEN;
218 * Check to see whether SSL is in use; if it's not, then no
219 * further access control checks are relevant. (the test for
220 * sc->enabled is probably strictly unnecessary)
222 if (!sc->enabled || !ssl) {
227 * Support for per-directory reconfigured SSL connection parameters.
229 * This is implemented by forcing an SSL renegotiation with the
230 * reconfigured parameter suite. But Apache's internal API processing
231 * makes our life very hard here, because when internal sub-requests occur
232 * we nevertheless should avoid multiple unnecessary SSL handshakes (they
233 * require extra network I/O and especially time to perform).
235 * But the optimization for filtering out the unnecessary handshakes isn't
236 * obvious and trivial. Especially because while Apache is in its
237 * sub-request processing the client could force additional handshakes,
238 * too. And these take place perhaps without our notice. So the only
239 * possibility is to explicitly _ask_ OpenSSL whether the renegotiation
240 * has to be performed or not. It has to performed when some parameters
241 * which were previously known (by us) are not those we've now
242 * reconfigured (as known by OpenSSL) or (in optimized way) at least when
243 * the reconfigured parameter suite is stronger (more restrictions) than
244 * the currently active one.
248 * Override of SSLCipherSuite
250 * We provide two options here:
252 * o The paranoid and default approach where we force a renegotiation when
253 * the cipher suite changed in _any_ way (which is straight-forward but
254 * often forces renegotiations too often and is perhaps not what the
255 * user actually wanted).
257 * o The optimized and still secure way where we force a renegotiation
258 * only if the currently active cipher is no longer contained in the
259 * reconfigured/new cipher suite. Any other changes are not important
260 * because it's the servers choice to select a cipher from the ones the
261 * client supports. So as long as the current cipher is still in the new
262 * cipher suite we're happy. Because we can assume we would have
263 * selected it again even when other (better) ciphers exists now in the
264 * new cipher suite. This approach is fine because the user explicitly
265 * has to enable this via ``SSLOptions +OptRenegotiate''. So we do no
266 * implicit optimizations.
268 if (dc->szCipherSuite) {
269 /* remember old state */
271 if (dc->nOptions & SSL_OPT_OPTRENEGOTIATE) {
272 cipher = SSL_get_current_cipher(ssl);
275 cipher_list_old = (STACK_OF(SSL_CIPHER) *)SSL_get_ciphers(ssl);
277 if (cipher_list_old) {
278 cipher_list_old = sk_SSL_CIPHER_dup(cipher_list_old);
282 /* configure new state */
283 if (!modssl_set_cipher_list(ssl, dc->szCipherSuite)) {
284 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
286 "Unable to reconfigure (per-directory) "
287 "permitted SSL ciphers");
288 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, r->server);
290 if (cipher_list_old) {
291 sk_SSL_CIPHER_free(cipher_list_old);
294 return HTTP_FORBIDDEN;
297 /* determine whether a renegotiation has to be forced */
298 cipher_list = (STACK_OF(SSL_CIPHER) *)SSL_get_ciphers(ssl);
300 if (dc->nOptions & SSL_OPT_OPTRENEGOTIATE) {
302 if ((!cipher && cipher_list) ||
303 (cipher && !cipher_list))
307 else if (cipher && cipher_list &&
308 (sk_SSL_CIPHER_find(cipher_list, cipher) < 0))
315 if ((!cipher_list_old && cipher_list) ||
316 (cipher_list_old && !cipher_list))
320 else if (cipher_list_old && cipher_list) {
322 !renegotiate && (n < sk_SSL_CIPHER_num(cipher_list));
325 SSL_CIPHER *value = sk_SSL_CIPHER_value(cipher_list, n);
327 if (sk_SSL_CIPHER_find(cipher_list_old, value) < 0) {
333 !renegotiate && (n < sk_SSL_CIPHER_num(cipher_list_old));
336 SSL_CIPHER *value = sk_SSL_CIPHER_value(cipher_list_old, n);
338 if (sk_SSL_CIPHER_find(cipher_list, value) < 0) {
346 if (cipher_list_old) {
347 sk_SSL_CIPHER_free(cipher_list_old);
352 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
353 "Reconfigured cipher suite will force renegotiation");
358 * override of SSLVerifyDepth
360 * The depth checks are handled by us manually inside the verify callback
361 * function and not by OpenSSL internally (and our function is aware of
362 * both the per-server and per-directory contexts). So we cannot ask
363 * OpenSSL about the currently verify depth. Instead we remember it in our
364 * ap_ctx attached to the SSL* of OpenSSL. We've to force the
365 * renegotiation if the reconfigured/new verify depth is less than the
366 * currently active/remembered verify depth (because this means more
367 * restriction on the certificate chain).
369 if (dc->nVerifyDepth != UNSET) {
370 /* XXX: doesnt look like sslconn->verify_depth is actually used */
371 if (!(n = sslconn->verify_depth)) {
372 sslconn->verify_depth = n = sc->server->auth.verify_depth;
375 /* determine whether a renegotiation has to be forced */
376 if (dc->nVerifyDepth < n) {
378 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
379 "Reduced client verification depth will force "
385 * override of SSLVerifyClient
387 * We force a renegotiation if the reconfigured/new verify type is
388 * stronger than the currently active verify type.
390 * The order is: none << optional_no_ca << optional << require
392 * Additionally the following optimization is possible here: When the
393 * currently active verify type is "none" but a client certificate is
394 * already known/present, it's enough to manually force a client
395 * verification but at least skip the I/O-intensive renegotation
398 if (dc->nVerifyClient != SSL_CVERIFY_UNSET) {
399 /* remember old state */
400 verify_old = SSL_get_verify_mode(ssl);
401 /* configure new state */
402 verify = SSL_VERIFY_NONE;
404 if (dc->nVerifyClient == SSL_CVERIFY_REQUIRE) {
405 verify |= SSL_VERIFY_PEER_STRICT;
408 if ((dc->nVerifyClient == SSL_CVERIFY_OPTIONAL) ||
409 (dc->nVerifyClient == SSL_CVERIFY_OPTIONAL_NO_CA))
411 verify |= SSL_VERIFY_PEER;
414 modssl_set_verify(ssl, verify, ssl_callback_SSLVerify);
415 SSL_set_verify_result(ssl, X509_V_OK);
417 /* determine whether we've to force a renegotiation */
418 if (!renegotiate && verify != verify_old) {
419 if (((verify_old == SSL_VERIFY_NONE) &&
420 (verify != SSL_VERIFY_NONE)) ||
422 (!(verify_old & SSL_VERIFY_PEER) &&
423 (verify & SSL_VERIFY_PEER)) ||
425 (!(verify_old & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) &&
426 (verify & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)))
431 if ((dc->nOptions & SSL_OPT_OPTRENEGOTIATE) &&
432 (verify_old == SSL_VERIFY_NONE) &&
433 ((peercert = SSL_get_peer_certificate(ssl)) != NULL))
435 renegotiate_quick = TRUE;
439 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
441 "Changed client verification type will force "
443 renegotiate_quick ? "quick " : "");
449 * override SSLCACertificateFile & SSLCACertificatePath
450 * This is only enabled if the SSL_set_cert_store() function
451 * is available in the ssl library. the 1.x based mod_ssl
452 * used SSL_CTX_set_cert_store which is not thread safe.
455 #ifdef HAVE_SSL_SET_CERT_STORE
457 * check if per-dir and per-server config field are not the same.
458 * if f is defined in per-dir and not defined in per-server
459 * or f is defined in both but not the equal ...
461 #define MODSSL_CFG_NE(f) \
462 (dc->f && (!sc->f || (sc->f && strNE(dc->f, sc->f))))
464 #define MODSSL_CFG_CA(f) \
465 (dc->f ? dc->f : sc->f)
467 if (MODSSL_CFG_NE(szCACertificateFile) ||
468 MODSSL_CFG_NE(szCACertificatePath))
470 STACK_OF(X509_NAME) *ca_list;
471 const char *ca_file = MODSSL_CFG_CA(szCACertificateFile);
472 const char *ca_path = MODSSL_CFG_CA(szCACertificatePath);
474 cert_store = X509_STORE_new();
476 if (!X509_STORE_load_locations(cert_store, ca_file, ca_path)) {
477 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
478 "Unable to reconfigure verify locations "
479 "for client authentication");
480 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, r->server);
482 X509_STORE_free(cert_store);
484 return HTTP_FORBIDDEN;
487 /* SSL_free will free cert_store */
488 SSL_set_cert_store(ssl, cert_store);
490 if (!(ca_list = ssl_init_FindCAList(r->server, r->pool,
493 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
494 "Unable to determine list of available "
495 "CA certificates for client authentication");
497 return HTTP_FORBIDDEN;
500 SSL_set_client_CA_list(ssl, ca_list);
503 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
504 "Changed client verification locations will force "
507 #endif /* HAVE_SSL_SET_CERT_STORE */
509 /* If a renegotiation is now required for this location, and the
510 * request includes a message body (and the client has not
511 * requested a "100 Continue" response), then the client will be
512 * streaming the request body over the wire already. In that
513 * case, it is not possible to stop and perform a new SSL
514 * handshake immediately; once the SSL library moves to the
515 * "accept" state, it will reject the SSL packets which the client
516 * is sending for the request body.
518 * To allow authentication to complete in this auth hook, the
519 * solution used here is to fill a (bounded) buffer with the
520 * request body, and then to reinject that request body later.
522 if (renegotiate && !renegotiate_quick
523 && (apr_table_get(r->headers_in, "transfer-encoding")
524 || (apr_table_get(r->headers_in, "content-length")
525 && strcmp(apr_table_get(r->headers_in, "content-length"), "0")))
526 && !r->expecting_100) {
529 /* Fill the I/O buffer with the request body if possible. */
530 rv = ssl_io_buffer_fill(r);
533 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
534 "could not buffer message body to allow "
535 "SSL renegotiation to proceed");
541 * now do the renegotiation if anything was actually reconfigured
545 * Now we force the SSL renegotation by sending the Hello Request
546 * message to the client. Here we have to do a workaround: Actually
547 * OpenSSL returns immediately after sending the Hello Request (the
548 * intent AFAIK is because the SSL/TLS protocol says it's not a must
549 * that the client replies to a Hello Request). But because we insist
550 * on a reply (anything else is an error for us) we have to go to the
551 * ACCEPT state manually. Using SSL_set_accept_state() doesn't work
552 * here because it resets too much of the connection. So we set the
553 * state explicitly and continue the handshake manually.
555 ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
556 "Requesting connection re-negotiation");
558 if (renegotiate_quick) {
559 STACK_OF(X509) *cert_stack;
561 /* perform just a manual re-verification of the peer */
562 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
563 "Performing quick renegotiation: "
564 "just re-verifying the peer");
566 cert_stack = (STACK_OF(X509) *)SSL_get_peer_cert_chain(ssl);
568 cert = SSL_get_peer_certificate(ssl);
570 if (!cert_stack && cert) {
571 /* client cert is in the session cache, but there is
572 * no chain, since ssl3_get_client_certificate()
573 * sk_X509_shift-ed the peer cert out of the chain.
574 * we put it back here for the purpose of quick_renegotiation.
576 cert_stack = sk_new_null();
577 sk_X509_push(cert_stack, MODSSL_PCHAR_CAST cert);
580 if (!cert_stack || (sk_X509_num(cert_stack) == 0)) {
581 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
582 "Cannot find peer certificate chain");
584 return HTTP_FORBIDDEN;
588 (cert_store = SSL_CTX_get_cert_store(ctx))))
590 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
591 "Cannot find certificate storage");
593 return HTTP_FORBIDDEN;
597 cert = sk_X509_value(cert_stack, 0);
600 X509_STORE_CTX_init(&cert_store_ctx, cert_store, cert, cert_stack);
601 depth = SSL_get_verify_depth(ssl);
604 X509_STORE_CTX_set_depth(&cert_store_ctx, depth);
607 X509_STORE_CTX_set_ex_data(&cert_store_ctx,
608 SSL_get_ex_data_X509_STORE_CTX_idx(),
611 if (!modssl_X509_verify_cert(&cert_store_ctx)) {
612 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
613 "Re-negotiation verification step failed");
614 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, r->server);
617 SSL_set_verify_result(ssl, cert_store_ctx.error);
618 X509_STORE_CTX_cleanup(&cert_store_ctx);
620 if (cert_stack != SSL_get_peer_cert_chain(ssl)) {
621 /* we created this ourselves, so free it */
622 sk_X509_pop_free(cert_stack, X509_free);
626 request_rec *id = r->main ? r->main : r;
628 /* Additional mitigation for CVE-2009-3555: At this point,
629 * before renegotiating, an (entire) request has been read
630 * from the connection. An attacker may have sent further
631 * data to "prefix" any subsequent request by the victim's
632 * client after the renegotiation; this data may already
633 * have been read and buffered. Forcing a connection
634 * closure after the response ensures such data will be
635 * discarded. Legimately pipelined HTTP requests will be
636 * retried anyway with this approach. */
637 if (has_buffered_data(r)) {
638 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
639 "insecure SSL re-negotiation required, but "
640 "a pipelined request is present; keepalive "
642 r->connection->keepalive = AP_CONN_CLOSE;
645 /* Perform a full renegotiation. */
646 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
647 "Performing full renegotiation: complete handshake "
648 "protocol (%s support secure renegotiation)",
649 #if defined(SSL_get_secure_renegotiation_support)
650 SSL_get_secure_renegotiation_support(ssl) ?
651 "client does" : "client does not"
657 SSL_set_session_id_context(ssl,
658 (unsigned char *)&id,
661 /* Toggle the renegotiation state to allow the new
662 * handshake to proceed. */
663 sslconn->reneg_state = RENEG_ALLOW;
665 SSL_renegotiate(ssl);
666 SSL_do_handshake(ssl);
668 if (SSL_get_state(ssl) != SSL_ST_OK) {
669 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
670 "Re-negotiation request failed");
671 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, r->server);
673 r->connection->aborted = 1;
674 return HTTP_FORBIDDEN;
677 ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
678 "Awaiting re-negotiation handshake");
680 SSL_set_state(ssl, SSL_ST_ACCEPT);
681 SSL_do_handshake(ssl);
683 sslconn->reneg_state = RENEG_REJECT;
685 if (SSL_get_state(ssl) != SSL_ST_OK) {
686 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
687 "Re-negotiation handshake failed: "
688 "Not accepted by client!?");
690 r->connection->aborted = 1;
691 return HTTP_FORBIDDEN;
696 * Remember the peer certificate's DN
698 if ((cert = SSL_get_peer_certificate(ssl))) {
699 if (sslconn->client_cert) {
700 X509_free(sslconn->client_cert);
702 sslconn->client_cert = cert;
703 sslconn->client_dn = NULL;
707 * Finally check for acceptable renegotiation results
709 if (dc->nVerifyClient != SSL_CVERIFY_NONE) {
710 BOOL do_verify = (dc->nVerifyClient == SSL_CVERIFY_REQUIRE);
712 if (do_verify && (SSL_get_verify_result(ssl) != X509_V_OK)) {
713 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
714 "Re-negotiation handshake failed: "
715 "Client verification failed");
717 return HTTP_FORBIDDEN;
721 if ((peercert = SSL_get_peer_certificate(ssl)) == NULL) {
722 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
723 "Re-negotiation handshake failed: "
724 "Client certificate missing");
726 return HTTP_FORBIDDEN;
734 * Also check that SSLCipherSuite has been enforced as expected.
737 cipher = SSL_get_current_cipher(ssl);
738 if (sk_SSL_CIPHER_find(cipher_list, cipher) < 0) {
739 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
740 "SSL cipher suite not renegotiated: "
741 "access to %s denied using cipher %s",
743 SSL_CIPHER_get_name(cipher));
744 return HTTP_FORBIDDEN;
749 /* If we're trying to have the user name set from a client
750 * certificate then we need to set it here. This should be safe as
751 * the user name probably isn't important from an auth checking point
752 * of view as the certificate supplied acts in that capacity.
753 * However, if FakeAuth is being used then this isn't the case so
754 * we need to postpone setting the username until later.
756 if ((dc->nOptions & SSL_OPT_FAKEBASICAUTH) == 0 && dc->szUserName) {
757 char *val = ssl_var_lookup(r->pool, r->server, r->connection,
758 r, (char *)dc->szUserName);
764 * Check SSLRequire boolean expressions
766 requires = dc->aRequirement;
767 ssl_requires = (ssl_require_t *)requires->elts;
769 for (i = 0; i < requires->nelts; i++) {
770 ssl_require_t *req = &ssl_requires[i];
771 ok = ssl_expr_exec(r, req->mpExpr);
774 cp = apr_psprintf(r->pool,
776 "SSL requirement expression: %s",
777 ssl_expr_get_error());
779 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
780 "access to %s failed, reason: %s",
783 /* remember forbidden access for strict require option */
784 apr_table_setn(r->notes, "ssl-access-forbidden", "1");
786 return HTTP_FORBIDDEN;
790 ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
791 "Access to %s denied for %s "
792 "(requirement expression not fulfilled)",
793 r->filename, r->connection->remote_ip);
795 ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
796 "Failed expression: %s", req->cpExpr);
798 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
799 "access to %s failed, reason: %s",
801 "SSL requirement expression not fulfilled "
802 "(see SSL logfile for more details)");
804 /* remember forbidden access for strict require option */
805 apr_table_setn(r->notes, "ssl-access-forbidden", "1");
807 return HTTP_FORBIDDEN;
812 * Else access is granted from our point of view (except vendor
813 * handlers override). But we have to return DECLINED here instead
814 * of OK, because mod_auth and other modules still might want to
822 * Authentication Handler:
823 * Fake a Basic authentication from the X509 client certificate.
825 * This must be run fairly early on to prevent a real authentication from
826 * occuring, in particular it must be run before anything else that
827 * authenticates a user. This means that the Module statement for this
828 * module should be LAST in the Configuration file.
830 int ssl_hook_UserCheck(request_rec *r)
832 SSLConnRec *sslconn = myConnConfig(r->connection);
833 SSLSrvConfigRec *sc = mySrvConfig(r->server);
834 SSLDirConfigRec *dc = myDirConfig(r);
836 const char *auth_line, *username, *password;
839 * Additionally forbid access (again)
840 * when strict require option is used.
842 if ((dc->nOptions & SSL_OPT_STRICTREQUIRE) &&
843 (apr_table_get(r->notes, "ssl-access-forbidden")))
845 return HTTP_FORBIDDEN;
849 * We decline when we are in a subrequest. The Authorization header
850 * would already be present if it was added in the main request.
852 if (!ap_is_initial_req(r)) {
857 * Make sure the user is not able to fake the client certificate
858 * based authentication by just entering an X.509 Subject DN
859 * ("/XX=YYY/XX=YYY/..") as the username and "password" as the
862 if ((auth_line = apr_table_get(r->headers_in, "Authorization"))) {
863 if (strcEQ(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
864 while ((*auth_line == ' ') || (*auth_line == '\t')) {
868 auth_line = ap_pbase64decode(r->pool, auth_line);
869 username = ap_getword_nulls(r->pool, &auth_line, ':');
870 password = auth_line;
872 if ((username[0] == '/') && strEQ(password, "password")) {
873 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
874 "Encountered FakeBasicAuth spoof: %s", username);
875 return HTTP_FORBIDDEN;
881 * We decline operation in various situations...
882 * - SSLOptions +FakeBasicAuth not configured
883 * - r->user already authenticated
885 * - client did not present a certificate
887 if (!(sc->enabled && sslconn && sslconn->ssl && sslconn->client_cert) ||
888 !(dc->nOptions & SSL_OPT_FAKEBASICAUTH) || r->user)
893 if (!sslconn->client_dn) {
894 X509_NAME *name = X509_get_subject_name(sslconn->client_cert);
895 char *cp = X509_NAME_oneline(name, NULL, 0);
896 sslconn->client_dn = apr_pstrdup(r->connection->pool, cp);
900 clientdn = (char *)sslconn->client_dn;
903 * Fake a password - which one would be immaterial, as, it seems, an empty
904 * password in the users file would match ALL incoming passwords, if only
905 * we were using the standard crypt library routine. Unfortunately, OpenSSL
906 * "fixes" a "bug" in crypt and thus prevents blank passwords from
907 * working. (IMHO what they really fix is a bug in the users of the code
908 * - failing to program correctly for shadow passwords). We need,
909 * therefore, to provide a password. This password can be matched by
910 * adding the string "xxj31ZMTZzkVA" as the password in the user file.
911 * This is just the crypted variant of the word "password" ;-)
913 auth_line = apr_pstrcat(r->pool, "Basic ",
914 ap_pbase64encode(r->pool,
915 apr_pstrcat(r->pool, clientdn,
918 apr_table_set(r->headers_in, "Authorization", auth_line);
920 ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
921 "Faking HTTP Basic Auth header: \"Authorization: %s\"",
927 /* authorization phase */
928 int ssl_hook_Auth(request_rec *r)
930 SSLDirConfigRec *dc = myDirConfig(r);
933 * Additionally forbid access (again)
934 * when strict require option is used.
936 if ((dc->nOptions & SSL_OPT_STRICTREQUIRE) &&
937 (apr_table_get(r->notes, "ssl-access-forbidden")))
939 return HTTP_FORBIDDEN;
949 static const char *ssl_hook_Fixup_vars[] = {
950 "SSL_VERSION_INTERFACE",
951 "SSL_VERSION_LIBRARY",
956 "SSL_CIPHER_USEKEYSIZE",
957 "SSL_CIPHER_ALGKEYSIZE",
959 "SSL_CLIENT_M_VERSION",
960 "SSL_CLIENT_M_SERIAL",
961 "SSL_CLIENT_V_START",
965 "SSL_CLIENT_S_DN_ST",
968 "SSL_CLIENT_S_DN_OU",
969 "SSL_CLIENT_S_DN_CN",
975 "SSL_CLIENT_S_DN_UID",
976 "SSL_CLIENT_S_DN_Email",
979 "SSL_CLIENT_I_DN_ST",
982 "SSL_CLIENT_I_DN_OU",
983 "SSL_CLIENT_I_DN_CN",
989 "SSL_CLIENT_I_DN_UID",
990 "SSL_CLIENT_I_DN_Email",
993 "SSL_SERVER_M_VERSION",
994 "SSL_SERVER_M_SERIAL",
995 "SSL_SERVER_V_START",
999 "SSL_SERVER_S_DN_ST",
1000 "SSL_SERVER_S_DN_L",
1001 "SSL_SERVER_S_DN_O",
1002 "SSL_SERVER_S_DN_OU",
1003 "SSL_SERVER_S_DN_CN",
1004 "SSL_SERVER_S_DN_T",
1005 "SSL_SERVER_S_DN_I",
1006 "SSL_SERVER_S_DN_G",
1007 "SSL_SERVER_S_DN_S",
1008 "SSL_SERVER_S_DN_D",
1009 "SSL_SERVER_S_DN_UID",
1010 "SSL_SERVER_S_DN_Email",
1012 "SSL_SERVER_I_DN_C",
1013 "SSL_SERVER_I_DN_ST",
1014 "SSL_SERVER_I_DN_L",
1015 "SSL_SERVER_I_DN_O",
1016 "SSL_SERVER_I_DN_OU",
1017 "SSL_SERVER_I_DN_CN",
1018 "SSL_SERVER_I_DN_T",
1019 "SSL_SERVER_I_DN_I",
1020 "SSL_SERVER_I_DN_G",
1021 "SSL_SERVER_I_DN_S",
1022 "SSL_SERVER_I_DN_D",
1023 "SSL_SERVER_I_DN_UID",
1024 "SSL_SERVER_I_DN_Email",
1031 int ssl_hook_Fixup(request_rec *r)
1033 SSLConnRec *sslconn = myConnConfig(r->connection);
1034 SSLSrvConfigRec *sc = mySrvConfig(r->server);
1035 SSLDirConfigRec *dc = myDirConfig(r);
1036 apr_table_t *env = r->subprocess_env;
1037 char *var, *val = "";
1038 STACK_OF(X509) *peer_certs;
1043 * Check to see if SSL is on
1045 if (!(sc->enabled && sslconn && (ssl = sslconn->ssl))) {
1050 * Annotate the SSI/CGI environment with standard SSL information
1052 /* the always present HTTPS (=HTTP over SSL) flag! */
1053 apr_table_setn(env, "HTTPS", "on");
1055 /* standard SSL environment variables */
1056 if (dc->nOptions & SSL_OPT_STDENVVARS) {
1057 for (i = 0; ssl_hook_Fixup_vars[i]; i++) {
1058 var = (char *)ssl_hook_Fixup_vars[i];
1059 val = ssl_var_lookup(r->pool, r->server, r->connection, r, var);
1060 if (!strIsEmpty(val)) {
1061 apr_table_setn(env, var, val);
1067 * On-demand bloat up the SSI/CGI environment with certificate data
1069 if (dc->nOptions & SSL_OPT_EXPORTCERTDATA) {
1070 val = ssl_var_lookup(r->pool, r->server, r->connection,
1071 r, "SSL_SERVER_CERT");
1073 apr_table_setn(env, "SSL_SERVER_CERT", val);
1075 val = ssl_var_lookup(r->pool, r->server, r->connection,
1076 r, "SSL_CLIENT_CERT");
1078 apr_table_setn(env, "SSL_CLIENT_CERT", val);
1080 if ((peer_certs = (STACK_OF(X509) *)SSL_get_peer_cert_chain(ssl))) {
1081 for (i = 0; i < sk_X509_num(peer_certs); i++) {
1082 var = apr_psprintf(r->pool, "SSL_CLIENT_CERT_CHAIN_%d", i);
1083 val = ssl_var_lookup(r->pool, r->server, r->connection,
1086 apr_table_setn(env, var, val);
1093 #ifdef SSL_get_secure_renegotiation_support
1094 apr_table_setn(r->notes, "ssl-secure-reneg",
1095 SSL_get_secure_renegotiation_support(ssl) ? "1" : "0");
1101 /* _________________________________________________________________
1103 ** OpenSSL Callback Functions
1104 ** _________________________________________________________________
1108 * Handle out temporary RSA private keys on demand
1110 * The background of this as the TLSv1 standard explains it:
1112 * | D.1. Temporary RSA keys
1114 * | US Export restrictions limit RSA keys used for encryption to 512
1115 * | bits, but do not place any limit on lengths of RSA keys used for
1116 * | signing operations. Certificates often need to be larger than 512
1117 * | bits, since 512-bit RSA keys are not secure enough for high-value
1118 * | transactions or for applications requiring long-term security. Some
1119 * | certificates are also designated signing-only, in which case they
1120 * | cannot be used for key exchange.
1122 * | When the public key in the certificate cannot be used for encryption,
1123 * | the server signs a temporary RSA key, which is then exchanged. In
1124 * | exportable applications, the temporary RSA key should be the maximum
1125 * | allowable length (i.e., 512 bits). Because 512-bit RSA keys are
1126 * | relatively insecure, they should be changed often. For typical
1127 * | electronic commerce applications, it is suggested that keys be
1128 * | changed daily or every 500 transactions, and more often if possible.
1129 * | Note that while it is acceptable to use the same temporary key for
1130 * | multiple transactions, it must be signed each time it is used.
1132 * | RSA key generation is a time-consuming process. In many cases, a
1133 * | low-priority process can be assigned the task of key generation.
1134 * | Whenever a new key is completed, the existing temporary key can be
1135 * | replaced with the new one.
1137 * XXX: base on comment above, if thread support is enabled,
1138 * we should spawn a low-priority thread to generate new keys
1141 * So we generated 512 and 1024 bit temporary keys on startup
1142 * which we now just hand out on demand....
1145 RSA *ssl_callback_TmpRSA(SSL *ssl, int export, int keylen)
1147 conn_rec *c = (conn_rec *)SSL_get_app_data(ssl);
1148 SSLModConfigRec *mc = myModConfig(c->base_server);
1151 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, c->base_server,
1152 "handing out temporary %d bit RSA key", keylen);
1154 /* doesn't matter if export flag is on,
1155 * we won't be asked for keylen > 512 in that case.
1156 * if we are asked for a keylen > 1024, it is too expensive
1157 * to generate on the fly.
1158 * XXX: any reason not to generate 2048 bit keys at startup?
1163 idx = SSL_TMP_KEY_RSA_512;
1168 idx = SSL_TMP_KEY_RSA_1024;
1171 return (RSA *)mc->pTmpKeys[idx];
1175 * Hand out the already generated DH parameters...
1177 DH *ssl_callback_TmpDH(SSL *ssl, int export, int keylen)
1179 conn_rec *c = (conn_rec *)SSL_get_app_data(ssl);
1180 SSLModConfigRec *mc = myModConfig(c->base_server);
1183 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, c->base_server,
1184 "handing out temporary %d bit DH key", keylen);
1188 idx = SSL_TMP_KEY_DH_512;
1193 idx = SSL_TMP_KEY_DH_1024;
1196 return (DH *)mc->pTmpKeys[idx];
1200 * This OpenSSL callback function is called when OpenSSL
1201 * does client authentication and verifies the certificate chain.
1203 int ssl_callback_SSLVerify(int ok, X509_STORE_CTX *ctx)
1205 /* Get Apache context back through OpenSSL context */
1206 SSL *ssl = X509_STORE_CTX_get_ex_data(ctx,
1207 SSL_get_ex_data_X509_STORE_CTX_idx());
1208 conn_rec *conn = (conn_rec *)SSL_get_app_data(ssl);
1209 server_rec *s = conn->base_server;
1210 request_rec *r = (request_rec *)SSL_get_app_data2(ssl);
1212 SSLSrvConfigRec *sc = mySrvConfig(s);
1213 SSLDirConfigRec *dc = r ? myDirConfig(r) : NULL;
1214 SSLConnRec *sslconn = myConnConfig(conn);
1215 modssl_ctx_t *mctx = myCtxConfig(sslconn, sc);
1217 /* Get verify ingredients */
1218 int errnum = X509_STORE_CTX_get_error(ctx);
1219 int errdepth = X509_STORE_CTX_get_error_depth(ctx);
1223 * Log verification information
1225 if (s->loglevel >= APLOG_DEBUG) {
1226 X509 *cert = X509_STORE_CTX_get_current_cert(ctx);
1227 char *sname = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
1228 char *iname = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
1230 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1231 "Certificate Verification: "
1232 "depth: %d, subject: %s, issuer: %s",
1234 sname ? sname : "-unknown-",
1235 iname ? iname : "-unknown-");
1247 * Check for optionally acceptable non-verifiable issuer situation
1249 if (dc && (dc->nVerifyClient != SSL_CVERIFY_UNSET)) {
1250 verify = dc->nVerifyClient;
1253 verify = mctx->auth.verify_mode;
1256 if (verify == SSL_CVERIFY_NONE) {
1258 * SSLProxyVerify is either not configured or set to "none".
1259 * (this callback doesn't happen in the server context if SSLVerify
1260 * is not configured or set to "none")
1265 if (ssl_verify_error_is_optional(errnum) &&
1266 (verify == SSL_CVERIFY_OPTIONAL_NO_CA))
1268 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1269 "Certificate Verification: Verifiable Issuer is "
1270 "configured as optional, therefore we're accepting "
1273 sslconn->verify_info = "GENEROUS";
1278 * Additionally perform CRL-based revocation checks
1281 if (!(ok = ssl_callback_SSLVerify_CRL(ok, ctx, conn))) {
1282 errnum = X509_STORE_CTX_get_error(ctx);
1287 * If we already know it's not ok, log the real reason
1290 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1291 "Certificate Verification: Error (%d): %s",
1292 errnum, X509_verify_cert_error_string(errnum));
1294 if (sslconn->client_cert) {
1295 X509_free(sslconn->client_cert);
1296 sslconn->client_cert = NULL;
1298 sslconn->client_dn = NULL;
1299 sslconn->verify_error = X509_verify_cert_error_string(errnum);
1303 * Finally check the depth of the certificate verification
1305 if (dc && (dc->nVerifyDepth != UNSET)) {
1306 depth = dc->nVerifyDepth;
1309 depth = mctx->auth.verify_depth;
1312 if (errdepth > depth) {
1313 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1314 "Certificate Verification: Certificate Chain too long "
1315 "(chain has %d certificates, but maximum allowed are "
1319 errnum = X509_V_ERR_CERT_CHAIN_TOO_LONG;
1320 sslconn->verify_error = X509_verify_cert_error_string(errnum);
1326 * And finally signal OpenSSL the (perhaps changed) state
1331 int ssl_callback_SSLVerify_CRL(int ok, X509_STORE_CTX *ctx, conn_rec *c)
1333 server_rec *s = c->base_server;
1334 SSLSrvConfigRec *sc = mySrvConfig(s);
1335 SSLConnRec *sslconn = myConnConfig(c);
1336 modssl_ctx_t *mctx = myCtxConfig(sslconn, sc);
1338 X509_NAME *subject, *issuer;
1345 * Unless a revocation store for CRLs was created we
1346 * cannot do any CRL-based verification, of course.
1353 * Determine certificate ingredients in advance
1355 cert = X509_STORE_CTX_get_current_cert(ctx);
1356 subject = X509_get_subject_name(cert);
1357 issuer = X509_get_issuer_name(cert);
1360 * OpenSSL provides the general mechanism to deal with CRLs but does not
1361 * use them automatically when verifying certificates, so we do it
1362 * explicitly here. We will check the CRL for the currently checked
1363 * certificate, if there is such a CRL in the store.
1365 * We come through this procedure for each certificate in the certificate
1366 * chain, starting with the root-CA's certificate. At each step we've to
1367 * both verify the signature on the CRL (to make sure it's a valid CRL)
1368 * and it's revocation list (to make sure the current certificate isn't
1369 * revoked). But because to check the signature on the CRL we need the
1370 * public key of the issuing CA certificate (which was already processed
1371 * one round before), we've a little problem. But we can both solve it and
1372 * at the same time optimize the processing by using the following
1373 * verification scheme (idea and code snippets borrowed from the GLOBUS
1376 * 1. We'll check the signature of a CRL in each step when we find a CRL
1377 * through the _subject_ name of the current certificate. This CRL
1378 * itself will be needed the first time in the next round, of course.
1379 * But we do the signature processing one round before this where the
1380 * public key of the CA is available.
1382 * 2. We'll check the revocation list of a CRL in each step when
1383 * we find a CRL through the _issuer_ name of the current certificate.
1384 * This CRLs signature was then already verified one round before.
1386 * This verification scheme allows a CA to revoke its own certificate as
1391 * Try to retrieve a CRL corresponding to the _subject_ of
1392 * the current certificate in order to verify it's integrity.
1394 memset((char *)&obj, 0, sizeof(obj));
1395 rc = SSL_X509_STORE_lookup(mctx->crl,
1396 X509_LU_CRL, subject, &obj);
1399 if ((rc > 0) && crl) {
1401 * Log information about CRL
1402 * (A little bit complicated because of ASN.1 and BIOs...)
1404 if (s->loglevel >= APLOG_DEBUG) {
1405 char buff[512]; /* should be plenty */
1406 BIO *bio = BIO_new(BIO_s_mem());
1408 BIO_printf(bio, "CA CRL: Issuer: ");
1409 X509_NAME_print(bio, issuer, 0);
1411 BIO_printf(bio, ", lastUpdate: ");
1412 ASN1_UTCTIME_print(bio, X509_CRL_get_lastUpdate(crl));
1414 BIO_printf(bio, ", nextUpdate: ");
1415 ASN1_UTCTIME_print(bio, X509_CRL_get_nextUpdate(crl));
1417 n = BIO_read(bio, buff, sizeof(buff) - 1);
1422 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, buff);
1426 * Verify the signature on this CRL
1428 pubkey = X509_get_pubkey(cert);
1429 rc = X509_CRL_verify(crl, pubkey);
1430 #ifdef OPENSSL_VERSION_NUMBER
1431 /* Only refcounted in OpenSSL */
1433 EVP_PKEY_free(pubkey);
1436 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1437 "Invalid signature on CRL");
1439 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE);
1440 X509_OBJECT_free_contents(&obj);
1445 * Check date of CRL to make sure it's not expired
1447 i = X509_cmp_current_time(X509_CRL_get_nextUpdate(crl));
1450 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1451 "Found CRL has invalid nextUpdate field");
1453 X509_STORE_CTX_set_error(ctx,
1454 X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD);
1455 X509_OBJECT_free_contents(&obj);
1461 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1462 "Found CRL is expired - "
1463 "revoking all certificates until you get updated CRL");
1465 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_HAS_EXPIRED);
1466 X509_OBJECT_free_contents(&obj);
1471 X509_OBJECT_free_contents(&obj);
1475 * Try to retrieve a CRL corresponding to the _issuer_ of
1476 * the current certificate in order to check for revocation.
1478 memset((char *)&obj, 0, sizeof(obj));
1479 rc = SSL_X509_STORE_lookup(mctx->crl,
1480 X509_LU_CRL, issuer, &obj);
1483 if ((rc > 0) && crl) {
1485 * Check if the current certificate is revoked by this CRL
1487 n = sk_X509_REVOKED_num(X509_CRL_get_REVOKED(crl));
1489 for (i = 0; i < n; i++) {
1490 X509_REVOKED *revoked =
1491 sk_X509_REVOKED_value(X509_CRL_get_REVOKED(crl), i);
1493 ASN1_INTEGER *sn = X509_REVOKED_get_serialNumber(revoked);
1495 if (!ASN1_INTEGER_cmp(sn, X509_get_serialNumber(cert))) {
1496 if (s->loglevel >= APLOG_DEBUG) {
1497 char *cp = X509_NAME_oneline(issuer, NULL, 0);
1498 long serial = ASN1_INTEGER_get(sn);
1500 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
1501 "Certificate with serial %ld (0x%lX) "
1502 "revoked per CRL from issuer %s",
1503 serial, serial, cp);
1507 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
1508 X509_OBJECT_free_contents(&obj);
1514 X509_OBJECT_free_contents(&obj);
1520 #define SSLPROXY_CERT_CB_LOG_FMT \
1521 "Proxy client certificate callback: (%s) "
1523 static void modssl_proxy_info_log(server_rec *s,
1527 SSLSrvConfigRec *sc = mySrvConfig(s);
1532 if (s->loglevel < APLOG_DEBUG) {
1536 name = X509_get_subject_name(info->x509);
1537 dn = X509_NAME_oneline(name, name_buf, sizeof(name_buf));
1539 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1540 SSLPROXY_CERT_CB_LOG_FMT "%s, sending %s",
1541 sc->vhost_id, msg, dn ? dn : "-uknown-");
1545 * caller will decrement the cert and key reference
1546 * so we need to increment here to prevent them from
1549 #define modssl_set_cert_info(info, cert, pkey) \
1550 *cert = info->x509; \
1551 X509_reference_inc(*cert); \
1552 *pkey = info->x_pkey->dec_pkey; \
1553 EVP_PKEY_reference_inc(*pkey)
1555 int ssl_callback_proxy_cert(SSL *ssl, MODSSL_CLIENT_CERT_CB_ARG_TYPE **x509, EVP_PKEY **pkey)
1557 conn_rec *c = (conn_rec *)SSL_get_app_data(ssl);
1558 server_rec *s = c->base_server;
1559 SSLSrvConfigRec *sc = mySrvConfig(s);
1560 X509_NAME *ca_name, *issuer;
1562 STACK_OF(X509_NAME) *ca_list;
1563 STACK_OF(X509_INFO) *certs = sc->proxy->pkp->certs;
1566 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1567 SSLPROXY_CERT_CB_LOG_FMT "entered",
1570 if (!certs || (sk_X509_INFO_num(certs) <= 0)) {
1571 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1572 SSLPROXY_CERT_CB_LOG_FMT
1573 "downstream server wanted client certificate "
1574 "but none are configured", sc->vhost_id);
1578 ca_list = SSL_get_client_CA_list(ssl);
1580 if (!ca_list || (sk_X509_NAME_num(ca_list) <= 0)) {
1582 * downstream server didn't send us a list of acceptable CA certs,
1583 * so we send the first client cert in the list.
1585 info = sk_X509_INFO_value(certs, 0);
1587 modssl_proxy_info_log(s, info, "no acceptable CA list");
1589 modssl_set_cert_info(info, x509, pkey);
1594 for (i = 0; i < sk_X509_NAME_num(ca_list); i++) {
1595 ca_name = sk_X509_NAME_value(ca_list, i);
1597 for (j = 0; j < sk_X509_INFO_num(certs); j++) {
1598 info = sk_X509_INFO_value(certs, j);
1599 issuer = X509_get_issuer_name(info->x509);
1601 if (X509_NAME_cmp(issuer, ca_name) == 0) {
1602 modssl_proxy_info_log(s, info, "found acceptable cert");
1604 modssl_set_cert_info(info, x509, pkey);
1611 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1612 SSLPROXY_CERT_CB_LOG_FMT
1613 "no client certificate found!?", sc->vhost_id);
1618 static void ssl_session_log(server_rec *s,
1619 const char *request,
1626 char buf[SSL_SESSION_ID_STRING_LEN];
1627 char timeout_str[56] = {'\0'};
1629 if (s->loglevel < APLOG_DEBUG) {
1634 apr_snprintf(timeout_str, sizeof(timeout_str),
1635 "timeout=%lds ", (timeout - time(NULL)));
1638 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1639 "Inter-Process Session Cache: "
1640 "request=%s status=%s id=%s %s(session %s)",
1642 SSL_SESSION_id2sz(id, idlen, buf, sizeof(buf)),
1643 timeout_str, result);
1647 * This callback function is executed by OpenSSL whenever a new SSL_SESSION is
1648 * added to the internal OpenSSL session cache. We use this hook to spread the
1649 * SSL_SESSION also to the inter-process disk-cache to make share it with our
1650 * other Apache pre-forked server processes.
1652 int ssl_callback_NewSessionCacheEntry(SSL *ssl, SSL_SESSION *session)
1654 /* Get Apache context back through OpenSSL context */
1655 conn_rec *conn = (conn_rec *)SSL_get_app_data(ssl);
1656 server_rec *s = conn->base_server;
1657 SSLSrvConfigRec *sc = mySrvConfig(s);
1658 long timeout = sc->session_cache_timeout;
1664 * Set the timeout also for the internal OpenSSL cache, because this way
1665 * our inter-process cache is consulted only when it's really necessary.
1667 SSL_set_timeout(session, timeout);
1670 * Store the SSL_SESSION in the inter-process cache with the
1671 * same expire time, so it expires automatically there, too.
1673 id = SSL_SESSION_get_session_id(session);
1674 idlen = SSL_SESSION_get_session_id_length(session);
1676 timeout += modssl_session_get_time(session);
1678 rc = ssl_scache_store(s, id, idlen, timeout, session);
1680 ssl_session_log(s, "SET", id, idlen,
1681 rc == TRUE ? "OK" : "BAD",
1682 "caching", timeout);
1685 * return 0 which means to OpenSSL that the session is still
1686 * valid and was not freed by us with SSL_SESSION_free().
1692 * This callback function is executed by OpenSSL whenever a
1693 * SSL_SESSION is looked up in the internal OpenSSL cache and it
1694 * was not found. We use this to lookup the SSL_SESSION in the
1695 * inter-process disk-cache where it was perhaps stored by one
1696 * of our other Apache pre-forked server processes.
1698 SSL_SESSION *ssl_callback_GetSessionCacheEntry(SSL *ssl,
1700 int idlen, int *do_copy)
1702 /* Get Apache context back through OpenSSL context */
1703 conn_rec *conn = (conn_rec *)SSL_get_app_data(ssl);
1704 server_rec *s = conn->base_server;
1705 SSL_SESSION *session;
1708 * Try to retrieve the SSL_SESSION from the inter-process cache
1710 session = ssl_scache_retrieve(s, id, idlen);
1712 ssl_session_log(s, "GET", id, idlen,
1713 session ? "FOUND" : "MISSED",
1714 session ? "reuse" : "renewal", 0);
1717 * Return NULL or the retrieved SSL_SESSION. But indicate (by
1718 * setting do_copy to 0) that the reference count on the
1719 * SSL_SESSION should not be incremented by the SSL library,
1720 * because we will no longer hold a reference to it ourself.
1728 * This callback function is executed by OpenSSL whenever a
1729 * SSL_SESSION is removed from the the internal OpenSSL cache.
1730 * We use this to remove the SSL_SESSION in the inter-process
1733 void ssl_callback_DelSessionCacheEntry(SSL_CTX *ctx,
1734 SSL_SESSION *session)
1737 SSLSrvConfigRec *sc;
1742 * Get Apache context back through OpenSSL context
1744 if (!(s = (server_rec *)SSL_CTX_get_app_data(ctx))) {
1745 return; /* on server shutdown Apache is already gone */
1748 sc = mySrvConfig(s);
1751 * Remove the SSL_SESSION from the inter-process cache
1753 id = SSL_SESSION_get_session_id(session);
1754 idlen = SSL_SESSION_get_session_id_length(session);
1756 ssl_scache_remove(s, id, idlen);
1758 ssl_session_log(s, "REM", id, idlen,
1764 /* Dump debugginfo trace to the log file. */
1765 static void log_tracing_state(MODSSL_INFO_CB_ARG_TYPE ssl, conn_rec *c,
1766 server_rec *s, int where, int rc)
1769 * create the various trace messages
1771 if (where & SSL_CB_HANDSHAKE_START) {
1772 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1773 "%s: Handshake: start", SSL_LIBRARY_NAME);
1775 else if (where & SSL_CB_HANDSHAKE_DONE) {
1776 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1777 "%s: Handshake: done", SSL_LIBRARY_NAME);
1779 else if (where & SSL_CB_LOOP) {
1780 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1782 SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1784 else if (where & SSL_CB_READ) {
1785 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1787 SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1789 else if (where & SSL_CB_WRITE) {
1790 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1792 SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1794 else if (where & SSL_CB_ALERT) {
1795 char *str = (where & SSL_CB_READ) ? "read" : "write";
1796 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1797 "%s: Alert: %s:%s:%s",
1798 SSL_LIBRARY_NAME, str,
1799 SSL_alert_type_string_long(rc),
1800 SSL_alert_desc_string_long(rc));
1802 else if (where & SSL_CB_EXIT) {
1804 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1805 "%s: Exit: failed in %s",
1806 SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1809 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1810 "%s: Exit: error in %s",
1811 SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1816 * Because SSL renegotations can happen at any time (not only after
1817 * SSL_accept()), the best way to log the current connection details is
1818 * right after a finished handshake.
1820 if (where & SSL_CB_HANDSHAKE_DONE) {
1821 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
1822 "Connection: Client IP: %s, Protocol: %s, "
1823 "Cipher: %s (%s/%s bits)",
1824 ssl_var_lookup(NULL, s, c, NULL, "REMOTE_ADDR"),
1825 ssl_var_lookup(NULL, s, c, NULL, "SSL_PROTOCOL"),
1826 ssl_var_lookup(NULL, s, c, NULL, "SSL_CIPHER"),
1827 ssl_var_lookup(NULL, s, c, NULL, "SSL_CIPHER_USEKEYSIZE"),
1828 ssl_var_lookup(NULL, s, c, NULL, "SSL_CIPHER_ALGKEYSIZE"));
1833 * This callback function is executed while OpenSSL processes the SSL
1834 * handshake and does SSL record layer stuff. It's used to trap
1835 * client-initiated renegotiations, and for dumping everything to the
1838 void ssl_callback_Info(MODSSL_INFO_CB_ARG_TYPE ssl, int where, int rc)
1844 /* Retrieve the conn_rec and the associated SSLConnRec. */
1845 if ((c = (conn_rec *)SSL_get_app_data((SSL *)ssl)) == NULL) {
1849 if ((scr = myConnConfig(c)) == NULL) {
1853 /* If the reneg state is to reject renegotiations, check the SSL
1854 * state machine and move to ABORT if a Client Hello is being
1856 if ((where & SSL_CB_ACCEPT_LOOP) && scr->reneg_state == RENEG_REJECT) {
1857 int state = SSL_get_state((SSL *)ssl);
1859 if (state == SSL3_ST_SR_CLNT_HELLO_A
1860 || state == SSL23_ST_SR_CLNT_HELLO_A) {
1861 scr->reneg_state = RENEG_ABORT;
1862 ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c,
1863 "rejecting client initiated renegotiation");
1866 /* If the first handshake is complete, change state to reject any
1867 * subsequent client-initated renegotiation. */
1868 else if ((where & SSL_CB_HANDSHAKE_DONE) && scr->reneg_state == RENEG_INIT) {
1869 scr->reneg_state = RENEG_REJECT;
1873 if (s && s->loglevel >= APLOG_DEBUG) {
1874 log_tracing_state(ssl, c, s, where, rc);