2 ** _ __ ___ ___ __| | ___ ___| | mod_ssl
3 ** | '_ ` _ \ / _ \ / _` | / __/ __| | Apache Interface to OpenSSL
4 ** | | | | | | (_) | (_| | \__ \__ \ | www.modssl.org
5 ** |_| |_| |_|\___/ \__,_|___|___/___/_| ftp.modssl.org
8 ** The SSL engine kernel
11 /* ====================================================================
12 * The Apache Software License, Version 1.1
14 * Copyright (c) 2000-2001 The Apache Software Foundation. All rights
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
21 * 1. Redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in
26 * the documentation and/or other materials provided with the
29 * 3. The end-user documentation included with the redistribution,
30 * if any, must include the following acknowledgment:
31 * "This product includes software developed by the
32 * Apache Software Foundation (http://www.apache.org/)."
33 * Alternately, this acknowledgment may appear in the software itself,
34 * if and wherever such third-party acknowledgments normally appear.
36 * 4. The names "Apache" and "Apache Software Foundation" must
37 * not be used to endorse or promote products derived from this
38 * software without prior written permission. For written
39 * permission, please contact apache@apache.org.
41 * 5. Products derived from this software may not be called "Apache",
42 * nor may "Apache" appear in their name, without prior written
43 * permission of the Apache Software Foundation.
45 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
46 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
47 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
48 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
49 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
50 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
51 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
52 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
53 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
54 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
55 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
57 * ====================================================================
59 /* ``It took me fifteen years to discover
60 I had no talent for programming, but
61 I couldn't give it up because by that
62 time I was too famous.''
67 * Close the SSL part of the socket connection
68 * (called immediately _before_ the socket is closed)
70 /* XXX: perhaps ssl_abort() should call us or vice-versa
71 * lot of the same happening in both places
73 apr_status_t ssl_hook_CloseConnection(SSLFilterRec *filter)
80 conn = (conn_rec *)SSL_get_app_data(ssl);
86 * Now close the SSL layer of the connection. We've to take
87 * the TLSv1 standard into account here:
89 * | 7.2.1. Closure alerts
91 * | The client and the server must share knowledge that the connection is
92 * | ending in order to avoid a truncation attack. Either party may
93 * | initiate the exchange of closing messages.
96 * | This message notifies the recipient that the sender will not send
97 * | any more messages on this connection. The session becomes
98 * | unresumable if any connection is terminated without proper
99 * | close_notify messages with level equal to warning.
101 * | Either party may initiate a close by sending a close_notify alert.
102 * | Any data received after a closure alert is ignored.
104 * | Each party is required to send a close_notify alert before closing
105 * | the write side of the connection. It is required that the other party
106 * | respond with a close_notify alert of its own and close down the
107 * | connection immediately, discarding any pending writes. It is not
108 * | required for the initiator of the close to wait for the responding
109 * | close_notify alert before closing the read side of the connection.
111 * This means we've to send a close notify message, but haven't to wait
112 * for the close notify of the client. Actually we cannot wait for the
113 * close notify of the client because some clients (including Netscape
114 * 4.x) don't send one, so we would hang.
118 * exchange close notify messages, but allow the user
119 * to force the type of handshake via SetEnvIf directive
121 if (apr_table_get(conn->notes, "ssl::flag::unclean-shutdown") == PTRUE) {
122 /* perform no close notify handshake at all
123 (violates the SSL/TLS standard!) */
124 SSL_set_shutdown(ssl, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
127 else if (apr_table_get(conn->notes, "ssl::flag::accurate-shutdown") == PTRUE) {
128 /* send close notify and wait for clients close notify
129 (standard compliant, but usually causes connection hangs) */
130 SSL_set_shutdown(ssl, 0);
134 /* send close notify, but don't wait for clients close notify
135 (standard compliant and safe, so it's the DEFAULT!) */
136 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
139 SSL_smart_shutdown(ssl);
141 /* and finally log the fact that we've closed the connection */
142 ssl_log(conn->base_server, SSL_LOG_INFO,
143 "Connection to child %d closed with %s shutdown (server %s, client %s)",
144 conn->id, cpType, ssl_util_vhostid(conn->pool, conn->base_server),
145 conn->remote_ip != NULL ? conn->remote_ip : "unknown");
147 /* deallocate the SSL connection */
149 apr_table_setn(conn->notes, "ssl", NULL);
150 filter->pssl = NULL; /* so filters know we've been shutdown */
156 * Post Read Request Handler
158 int ssl_hook_ReadReq(request_rec *r)
164 * Get the SSL connection structure and perform the
165 * delayed interlinking from SSL back to request_rec
167 ssl = (SSL *)apr_table_get(r->connection->notes, "ssl");
169 apctx = (apr_table_t *)SSL_get_app_data2(ssl);
170 apr_table_setn(apctx, "ssl::request_rec", (const char *)r);
174 * Force the mod_ssl content handler when URL indicates this
176 if (strEQn(r->uri, "/mod_ssl:", 9))
177 r->handler = "mod_ssl:content-handler";
179 apr_table_setn(r->notes, "ap::http::method", "https");
180 apr_table_setn(r->notes, "ap::default::port", "443");
183 apr_table_setn(r->notes, "ap::http::method", NULL);
184 apr_table_setn(r->notes, "ap::default::port", NULL);
190 * URL Translation Handler
192 int ssl_hook_Translate(request_rec *r)
194 if (apr_table_get(r->connection->notes, "ssl") == NULL)
198 * Log information about incoming HTTPS requests
200 if (ap_is_initial_req(r))
201 ssl_log(r->server, SSL_LOG_INFO,
202 "%s HTTPS request received for child %d (server %s)",
203 r->connection->keepalives <= 0 ?
205 apr_psprintf(r->pool, "Subsequent (No.%d)",
206 r->connection->keepalives+1),
208 ssl_util_vhostid(r->pool, r->server));
211 * Move SetEnvIf information from request_rec to conn_rec/BUFF
212 * to allow the close connection handler to use them.
214 if (apr_table_get(r->subprocess_env, "ssl-unclean-shutdown") != NULL)
215 apr_table_setn(r->connection->notes, "ssl::flag::unclean-shutdown", PTRUE);
217 apr_table_setn(r->connection->notes, "ssl::flag::unclean-shutdown", PFALSE);
218 if (apr_table_get(r->subprocess_env, "ssl-accurate-shutdown") != NULL)
219 apr_table_setn(r->connection->notes, "ssl::flag::accurate-shutdown", PTRUE);
221 apr_table_setn(r->connection->notes, "ssl::flag::accurate-shutdown", PFALSE);
229 int ssl_hook_Handler(request_rec *r)
235 if (strNE(r->handler, "mod_ssl:content-handler"))
237 if (strNEn(r->uri, "/mod_ssl:", 9))
240 if (strEQ(r->uri, "/mod_ssl:error:HTTP-request")) {
242 port = ap_get_server_port(r);
243 if (!ap_is_default_port(port, r))
244 thisport = apr_psprintf(r->pool, ":%u", port);
245 thisurl = ap_escape_html(r->pool, apr_psprintf(r->pool, "https://%s%s/",
246 ap_get_server_name(r), thisport));
248 apr_table_setn(r->notes, "error-notes", apr_psprintf(r->pool,
249 "Reason: You're speaking plain HTTP to an SSL-enabled server port.<br />\n"
250 "Instead use the HTTPS scheme to access this URL, please.<br />\n"
251 "<blockquote>Hint: <a href=\"%s\"><b>%s</b></a></blockquote>",
255 return HTTP_BAD_REQUEST;
258 typedef long bio_hook_t (BIO *, int, const char *, int, long, long);
260 static void bio_hook_set(BIO *b, bio_hook_t *hook, void *data)
263 BIO_set_callback(b, hook);
264 BIO_set_callback_arg(b, data);
269 /* XXX: save/restore current callbacks if any? */
270 #define ssl_bio_hooks_set(ssl, hook, data) \
271 bio_hook_set(SSL_get_wbio(ssl), hook, data); \
272 bio_hook_set(SSL_get_rbio(ssl), hook, data)
274 #define ssl_bio_renegotiate_hook_set(ssl, data) \
275 ssl_bio_hooks_set(ssl, ssl_renegotiate_hook, data)
277 #define ssl_bio_hooks_unset(ssl) \
278 ssl_bio_hooks_set(ssl, NULL, NULL)
280 #define bio_mem_length(b) ((BUF_MEM *)b->ptr)->length
282 /* if we need to renegotiate in the access phase
283 * data needs to be pushed to / pulled from the filter chain
284 * otherwise, a BIO_write just sits in memory and theres nothing
288 static long ssl_renegotiate_hook(BIO *bio, int cmd, const char *argp,
289 int argi, long argl, long rc)
291 request_rec *r = (request_rec *)BIO_get_callback_arg(bio);
294 int is_failed_read = (cmd == (BIO_CB_READ|BIO_CB_RETURN) && (rc == -1));
295 int is_flush = ((cmd == BIO_CB_CTRL) && (argi == BIO_CTRL_FLUSH));
297 if (is_flush || is_failed_read) {
298 ssl = (SSL *)apr_table_get(r->connection->notes, "ssl");
299 /* disable this callback to prevent recursion
300 * and leave a "note" so the input filter leaves the rbio
303 ssl_bio_hooks_set(ssl, NULL, (void*)SSL_ST_RENEGOTIATE);
310 /* flush what was written into wbio to the client */
311 ssl_log(r->server, SSL_LOG_DEBUG,
312 "flushing %d bytes to the client",
313 bio_mem_length(bio));
317 /* force read from the client socket */
318 apr_bucket_brigade *bb = apr_brigade_create(r->connection->pool);
319 apr_off_t bytes = argi;
320 ap_get_brigade(r->input_filters, bb,
321 AP_MODE_BLOCKING, &bytes);
323 rc = BIO_read(bio, (void *)argp, argi);
325 ssl_log(r->server, SSL_LOG_DEBUG,
326 "retry read: wanted %d, got %d, %d remain\n",
327 argi, rc, bio_mem_length(bio));
330 /* reset this bio hook for further read/writes */
331 ssl_bio_renegotiate_hook_set(ssl, r);
339 int ssl_hook_Access(request_rec *r)
345 apr_array_header_t *apRequirement;
346 ssl_require_t *pRequirements;
347 ssl_require_t *pRequirement;
352 BOOL renegotiate_quick;
353 #ifdef SSL_EXPERIMENTAL_PERDIRCA
354 BOOL reconfigured_locations;
355 STACK_OF(X509_NAME) *skCAList;
360 STACK_OF(X509) *certstack;
361 X509_STORE *certstore;
362 X509_STORE_CTX certstorectx;
364 STACK_OF(SSL_CIPHER) *skCipherOld;
365 STACK_OF(SSL_CIPHER) *skCipher;
375 sc = mySrvConfig(r->server);
376 ssl = (SSL *)apr_table_get(r->connection->notes, "ssl");
378 ctx = SSL_get_SSL_CTX(ssl);
381 * Support for SSLRequireSSL directive
383 if (dc->bSSLRequired && ssl == NULL) {
384 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
385 "access to %s failed for %s, reason: %s", r->filename,
386 ap_get_remote_host(r->connection, r->per_dir_config, REMOTE_NAME, NULL),
387 "SSL connection required");
388 /* remember forbidden access for strict require option */
389 apr_table_setn(r->notes, "ssl-access-forbidden", (void *)1);
390 return HTTP_FORBIDDEN;
394 * Check to see if SSL protocol is on
402 * Support for per-directory reconfigured SSL connection parameters.
404 * This is implemented by forcing an SSL renegotiation with the
405 * reconfigured parameter suite. But Apache's internal API processing
406 * makes our life very hard here, because when internal sub-requests occur
407 * we nevertheless should avoid multiple unnecessary SSL handshakes (they
408 * require extra network I/O and especially time to perform).
410 * But the optimization for filtering out the unnecessary handshakes isn't
411 * obvious and trivial. Especially because while Apache is in its
412 * sub-request processing the client could force additional handshakes,
413 * too. And these take place perhaps without our notice. So the only
414 * possibility is to explicitly _ask_ OpenSSL whether the renegotiation
415 * has to be performed or not. It has to performed when some parameters
416 * which were previously known (by us) are not those we've now
417 * reconfigured (as known by OpenSSL) or (in optimized way) at least when
418 * the reconfigured parameter suite is stronger (more restrictions) than
419 * the currently active one.
422 renegotiate_quick = FALSE;
423 #ifdef SSL_EXPERIMENTAL_PERDIRCA
424 reconfigured_locations = FALSE;
428 * Override of SSLCipherSuite
430 * We provide two options here:
432 * o The paranoid and default approach where we force a renegotiation when
433 * the cipher suite changed in _any_ way (which is straight-forward but
434 * often forces renegotiations too often and is perhaps not what the
435 * user actually wanted).
437 * o The optimized and still secure way where we force a renegotiation
438 * only if the currently active cipher is no longer contained in the
439 * reconfigured/new cipher suite. Any other changes are not important
440 * because it's the servers choice to select a cipher from the ones the
441 * client supports. So as long as the current cipher is still in the new
442 * cipher suite we're happy. Because we can assume we would have
443 * selected it again even when other (better) ciphers exists now in the
444 * new cipher suite. This approach is fine because the user explicitly
445 * has to enable this via ``SSLOptions +OptRenegotiate''. So we do no
446 * implicit optimizations.
448 if (dc->szCipherSuite != NULL) {
449 /* remember old state */
452 if (dc->nOptions & SSL_OPT_OPTRENEGOTIATE)
453 pCipher = SSL_get_current_cipher(ssl);
455 skCipherOld = SSL_get_ciphers(ssl);
456 if (skCipherOld != NULL)
457 skCipherOld = sk_SSL_CIPHER_dup(skCipherOld);
459 /* configure new state */
460 if (!SSL_set_cipher_list(ssl, dc->szCipherSuite)) {
461 ssl_log(r->server, SSL_LOG_WARN|SSL_ADD_SSLERR,
462 "Unable to reconfigure (per-directory) permitted SSL ciphers");
463 if (skCipherOld != NULL)
464 sk_SSL_CIPHER_free(skCipherOld);
465 return HTTP_FORBIDDEN;
467 /* determine whether a renegotiation has to be forced */
468 skCipher = SSL_get_ciphers(ssl);
469 if (dc->nOptions & SSL_OPT_OPTRENEGOTIATE) {
471 if ((pCipher == NULL && skCipher != NULL) ||
472 (pCipher != NULL && skCipher == NULL) )
474 else if (pCipher != NULL && skCipher != NULL
475 && sk_SSL_CIPHER_find(skCipher, pCipher) < 0) {
481 if ((skCipherOld == NULL && skCipher != NULL) ||
482 (skCipherOld != NULL && skCipher == NULL) )
484 else if (skCipherOld != NULL && skCipher != NULL) {
485 for (n = 0; !renegotiate && n < sk_SSL_CIPHER_num(skCipher); n++) {
486 if (sk_SSL_CIPHER_find(skCipherOld, sk_SSL_CIPHER_value(skCipher, n)) < 0)
489 for (n = 0; !renegotiate && n < sk_SSL_CIPHER_num(skCipherOld); n++) {
490 if (sk_SSL_CIPHER_find(skCipher, sk_SSL_CIPHER_value(skCipherOld, n)) < 0)
496 if (skCipherOld != NULL)
497 sk_SSL_CIPHER_free(skCipherOld);
500 ssl_log(r->server, SSL_LOG_TRACE,
501 "Reconfigured cipher suite will force renegotiation");
505 * override of SSLVerifyDepth
507 * The depth checks are handled by us manually inside the verify callback
508 * function and not by OpenSSL internally (and our function is aware of
509 * both the per-server and per-directory contexts). So we cannot ask
510 * OpenSSL about the currently verify depth. Instead we remember it in our
511 * ap_ctx attached to the SSL* of OpenSSL. We've to force the
512 * renegotiation if the reconfigured/new verify depth is less than the
513 * currently active/remembered verify depth (because this means more
514 * restriction on the certificate chain).
516 if (dc->nVerifyDepth != UNSET) {
517 apctx = (apr_table_t *)SSL_get_app_data2(ssl);
518 if ((vp = (void *)apr_table_get(apctx, "ssl::verify::depth")) != NULL)
519 n = (int)AP_CTX_PTR2NUM(vp);
521 n = sc->nVerifyDepth;
522 apr_table_setn(apctx, "ssl::verify::depth",
523 (const char *)AP_CTX_NUM2PTR(dc->nVerifyDepth));
524 /* determine whether a renegotiation has to be forced */
525 if (dc->nVerifyDepth < n) {
527 ssl_log(r->server, SSL_LOG_TRACE,
528 "Reduced client verification depth will force renegotiation");
533 * override of SSLVerifyClient
535 * We force a renegotiation if the reconfigured/new verify type is
536 * stronger than the currently active verify type.
538 * The order is: none << optional_no_ca << optional << require
540 * Additionally the following optimization is possible here: When the
541 * currently active verify type is "none" but a client certificate is
542 * already known/present, it's enough to manually force a client
543 * verification but at least skip the I/O-intensive renegotation
546 if (dc->nVerifyClient != SSL_CVERIFY_UNSET) {
547 /* remember old state */
548 nVerifyOld = SSL_get_verify_mode(ssl);
549 /* configure new state */
550 nVerify = SSL_VERIFY_NONE;
551 if (dc->nVerifyClient == SSL_CVERIFY_REQUIRE)
552 nVerify |= SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
553 if ( (dc->nVerifyClient == SSL_CVERIFY_OPTIONAL)
554 || (dc->nVerifyClient == SSL_CVERIFY_OPTIONAL_NO_CA) )
555 nVerify |= SSL_VERIFY_PEER;
556 SSL_set_verify(ssl, nVerify, ssl_callback_SSLVerify);
557 SSL_set_verify_result(ssl, X509_V_OK);
558 /* determine whether we've to force a renegotiation */
559 if (nVerify != nVerifyOld) {
560 if ( ( (nVerifyOld == SSL_VERIFY_NONE)
561 && (nVerify != SSL_VERIFY_NONE))
562 || ( !(nVerifyOld & SSL_VERIFY_PEER)
563 && (nVerify & SSL_VERIFY_PEER))
564 || ( !(nVerifyOld & (SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
565 && (nVerify & (SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT)))) {
568 if ( dc->nOptions & SSL_OPT_OPTRENEGOTIATE
569 && nVerifyOld == SSL_VERIFY_NONE
570 && SSL_get_peer_certificate(ssl) != NULL)
571 renegotiate_quick = TRUE;
572 ssl_log(r->server, SSL_LOG_TRACE,
573 "Changed client verification type will force %srenegotiation",
574 renegotiate_quick ? "quick " : "");
580 * override SSLCACertificateFile & SSLCACertificatePath
581 * This is tagged experimental because it has to use an ugly kludge: We
582 * have to change the locations inside the SSL_CTX* (per-server global)
583 * instead inside SSL* (per-connection local) and reconfigure it to the
584 * old values later. That's problematic at least for the threaded process
585 * model of Apache under Win32 or when an error occurs. But unless
586 * OpenSSL provides a SSL_load_verify_locations() function we've no other
587 * chance to provide this functionality...
589 #ifdef SSL_EXPERIMENTAL_PERDIRCA
590 if ( ( dc->szCACertificateFile != NULL
591 && ( sc->szCACertificateFile == NULL
592 || ( sc->szCACertificateFile != NULL
593 && strNE(dc->szCACertificateFile, sc->szCACertificateFile))))
594 || ( dc->szCACertificatePath != NULL
595 && ( sc->szCACertificatePath == NULL
596 || ( sc->szCACertificatePath != NULL
597 && strNE(dc->szCACertificatePath, sc->szCACertificatePath)))) ) {
598 cpCAFile = dc->szCACertificateFile != NULL ?
599 dc->szCACertificateFile : sc->szCACertificateFile;
600 cpCAPath = dc->szCACertificatePath != NULL ?
601 dc->szCACertificatePath : sc->szCACertificatePath;
603 FIXME: This should be...
604 if (!SSL_load_verify_locations(ssl, cpCAFile, cpCAPath)) {
605 ...but OpenSSL still doesn't provide this!
607 if (!SSL_CTX_load_verify_locations(ctx, cpCAFile, cpCAPath)) {
608 ssl_log(r->server, SSL_LOG_ERROR|SSL_ADD_SSLERR,
609 "Unable to reconfigure verify locations "
610 "for client authentication");
611 return HTTP_FORBIDDEN;
613 if ((skCAList = ssl_init_FindCAList(r->server, r->pool,
614 cpCAFile, cpCAPath)) == NULL) {
615 ssl_log(r->server, SSL_LOG_ERROR,
616 "Unable to determine list of available "
617 "CA certificates for client authentication");
618 return HTTP_FORBIDDEN;
620 SSL_set_client_CA_list(ssl, skCAList);
622 reconfigured_locations = TRUE;
623 ssl_log(r->server, SSL_LOG_TRACE,
624 "Changed client verification locations will force renegotiation");
626 #endif /* SSL_EXPERIMENTAL_PERDIRCA */
629 * SSL renegotiations in conjunction with HTTP
630 * requests using the POST method are not supported.
634 * 1. When the client sends a HTTP/HTTPS request, Apache's core code
635 * reads only the request line ("METHOD /path HTTP/x.y") and the
636 * attached MIME headers ("Foo: bar") up to the terminating line ("CR
637 * LF"). An attached request body (for instance the data of a POST
638 * method) is _NOT_ read. Instead it is read by mod_cgi's content
639 * handler and directly passed to the CGI script.
641 * 2. mod_ssl supports per-directory re-configuration of SSL parameters.
642 * This is implemented by performing an SSL renegotiation of the
643 * re-configured parameters after the request is read, but before the
644 * response is sent. In more detail: the renegotiation happens after the
645 * request line and MIME headers were read, but _before_ the attached
646 * request body is read. The reason simply is that in the HTTP protocol
647 * usually there is no acknowledgment step between the headers and the
648 * body (there is the 100-continue feature and the chunking facility
649 * only), so Apache has no API hook for this step.
651 * 3. the problem now occurs when the client sends a POST request for
652 * URL /foo via HTTPS the server and the server has SSL parameters
653 * re-configured on a per-URL basis for /foo. Then mod_ssl has to
654 * perform an SSL renegotiation after the request was read and before
655 * the response is sent. But the problem is the pending POST body data
656 * in the receive buffer of SSL (which Apache still has not read - it's
657 * pending until mod_cgi sucks it in). When mod_ssl now tries to perform
658 * the renegotiation the pending data leads to an I/O error.
662 * There are only two solutions: Either to simply state that POST
663 * requests to URLs with SSL re-configurations are not allowed, or to
664 * renegotiate really after the _complete_ request (i.e. including
665 * the POST body) was read. Obviously the latter would be preferred,
666 * but it cannot be done easily inside Apache, because as already
667 * mentioned, there is no API step between the body reading and the body
668 * processing. And even when we mod_ssl would hook directly into the
669 * loop of mod_cgi, we wouldn't solve the problem for other handlers, of
670 * course. So the only general solution is to suck in the pending data
671 * of the request body from the OpenSSL BIO into the Apache BUFF. Then
672 * the renegotiation can be done and after this step Apache can proceed
673 * processing the request as before.
675 * Solution Implementation:
677 * We cannot simply suck in the data via an SSL_read-based loop because of
678 * HTTP chunking. Instead we _have_ to use the Apache API for this step which
679 * is aware of HTTP chunking. So the trick is to suck in the pending request
680 * data via the Apache API (which uses Apache's BUFF code and in the
681 * background mod_ssl's I/O glue code) and re-inject it later into the Apache
682 * BUFF code again. This way the data flows twice through the Apache BUFF, of
683 * course. But this way the solution doesn't depend on any Apache specifics
684 * and is fully transparent to Apache modules.
686 * !! BUT ALL THIS IS STILL NOT RE-IMPLEMENTED FOR APACHE 2.0 !!
688 if (renegotiate && r->method_number == M_POST) {
689 ssl_log(r->server, SSL_LOG_ERROR,
690 "SSL Re-negotiation in conjunction with POST method not supported!");
691 return HTTP_METHOD_NOT_ALLOWED;
695 * now do the renegotiation if anything was actually reconfigured
699 * Now we force the SSL renegotation by sending the Hello Request
700 * message to the client. Here we have to do a workaround: Actually
701 * OpenSSL returns immediately after sending the Hello Request (the
702 * intent AFAIK is because the SSL/TLS protocol says it's not a must
703 * that the client replies to a Hello Request). But because we insist
704 * on a reply (anything else is an error for us) we have to go to the
705 * ACCEPT state manually. Using SSL_set_accept_state() doesn't work
706 * here because it resets too much of the connection. So we set the
707 * state explicitly and continue the handshake manually.
709 ssl_log(r->server, SSL_LOG_INFO, "Requesting connection re-negotiation");
710 if (renegotiate_quick) {
711 /* perform just a manual re-verification of the peer */
712 ssl_log(r->server, SSL_LOG_TRACE,
713 "Performing quick renegotiation: just re-verifying the peer");
714 certstore = SSL_CTX_get_cert_store(ctx);
715 if (certstore == NULL) {
716 ssl_log(r->server, SSL_LOG_ERROR, "Cannot find certificate storage");
717 return HTTP_FORBIDDEN;
719 certstack = SSL_get_peer_cert_chain(ssl);
720 if (certstack == NULL || sk_X509_num(certstack) == 0) {
721 ssl_log(r->server, SSL_LOG_ERROR, "Cannot find peer certificate chain");
722 return HTTP_FORBIDDEN;
724 cert = sk_X509_value(certstack, 0);
725 X509_STORE_CTX_init(&certstorectx, certstore, cert, certstack);
726 depth = SSL_get_verify_depth(ssl);
728 X509_STORE_CTX_set_depth(&certstorectx, depth);
729 X509_STORE_CTX_set_ex_data(&certstorectx,
730 SSL_get_ex_data_X509_STORE_CTX_idx(), (char *)ssl);
731 if (!X509_verify_cert(&certstorectx))
732 ssl_log(r->server, SSL_LOG_ERROR|SSL_ADD_SSLERR,
733 "Re-negotiation verification step failed");
734 SSL_set_verify_result(ssl, certstorectx.error);
735 X509_STORE_CTX_cleanup(&certstorectx);
738 /* do a full renegotiation */
739 ssl_log(r->server, SSL_LOG_TRACE,
740 "Performing full renegotiation: complete handshake protocol");
742 SSL_set_session_id_context(ssl, (unsigned char *)&(r->main), sizeof(r->main));
744 SSL_set_session_id_context(ssl, (unsigned char *)&r, sizeof(r));
745 /* will need to push to / pull from filters to renegotiate */
746 ssl_bio_renegotiate_hook_set(ssl, r);
747 SSL_renegotiate(ssl);
748 SSL_do_handshake(ssl);
750 if (SSL_get_state(ssl) != SSL_ST_OK) {
751 ssl_log(r->server, SSL_LOG_ERROR, "Re-negotiation request failed");
752 ssl_bio_hooks_unset(ssl);
753 return HTTP_FORBIDDEN;
755 ssl_log(r->server, SSL_LOG_INFO, "Awaiting re-negotiation handshake");
756 SSL_set_state(ssl, SSL_ST_ACCEPT);
757 SSL_do_handshake(ssl);
759 ssl_bio_hooks_unset(ssl);
761 if (SSL_get_state(ssl) != SSL_ST_OK) {
762 ssl_log(r->server, SSL_LOG_ERROR,
763 "Re-negotiation handshake failed: Not accepted by client!?");
764 return HTTP_FORBIDDEN;
769 * Remember the peer certificate's DN
771 if ((cert = SSL_get_peer_certificate(ssl)) != NULL) {
772 cp = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
773 apr_table_setn(r->connection->notes, "ssl::client::dn",
774 apr_pstrdup(r->connection->pool, cp));
779 * Finally check for acceptable renegotiation results
781 if (dc->nVerifyClient != SSL_CVERIFY_NONE) {
782 if ( dc->nVerifyClient == SSL_CVERIFY_REQUIRE
783 && SSL_get_verify_result(ssl) != X509_V_OK ) {
784 ssl_log(r->server, SSL_LOG_ERROR,
785 "Re-negotiation handshake failed: Client verification failed");
786 return HTTP_FORBIDDEN;
788 if ( dc->nVerifyClient == SSL_CVERIFY_REQUIRE
789 && SSL_get_peer_certificate(ssl) == NULL ) {
790 ssl_log(r->server, SSL_LOG_ERROR,
791 "Re-negotiation handshake failed: Client certificate missing");
792 return HTTP_FORBIDDEN;
798 * Under old OpenSSL we had to change the X509_STORE inside the
799 * SSL_CTX instead inside the SSL structure, so we have to reconfigure it
800 * to the old values. This should be changed with forthcoming OpenSSL
801 * versions when better functionality is avaiable.
803 #ifdef SSL_EXPERIMENTAL_PERDIRCA
804 if (renegotiate && reconfigured_locations) {
805 if (!SSL_CTX_load_verify_locations(ctx,
806 sc->szCACertificateFile, sc->szCACertificatePath)) {
807 ssl_log(r->server, SSL_LOG_ERROR|SSL_ADD_SSLERR,
808 "Unable to reconfigure verify locations "
809 "to per-server configuration parameters");
810 return HTTP_FORBIDDEN;
813 #endif /* SSL_EXPERIMENTAL_PERDIRCA */
816 * Check SSLRequire boolean expressions
818 apRequirement = dc->aRequirement;
819 pRequirements = (ssl_require_t *)apRequirement->elts;
820 for (i = 0; i < apRequirement->nelts; i++) {
821 pRequirement = &pRequirements[i];
822 ok = ssl_expr_exec(r, pRequirement->mpExpr);
824 cp = apr_psprintf(r->pool, "Failed to execute SSL requirement expression: %s",
825 ssl_expr_get_error());
826 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
827 "access to %s failed for %s, reason: %s", r->filename,
828 ap_get_remote_host(r->connection, r->per_dir_config, 1, NULL), cp);
829 /* remember forbidden access for strict require option */
830 apr_table_setn(r->notes, "ssl-access-forbidden", (void *)1);
831 return HTTP_FORBIDDEN;
834 ssl_log(r->server, SSL_LOG_INFO,
835 "Access to %s denied for %s (requirement expression not fulfilled)",
836 r->filename, r->connection->remote_ip);
837 ssl_log(r->server, SSL_LOG_INFO,
838 "Failed expression: %s", pRequirement->cpExpr);
839 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
840 "access to %s failed for %s, reason: %s", r->filename,
841 ap_get_remote_host(r->connection, r->per_dir_config, 1, NULL),
842 "SSL requirement expression not fulfilled "
843 "(see SSL logfile for more details)");
844 /* remember forbidden access for strict require option */
845 apr_table_setn(r->notes, "ssl-access-forbidden", (void *)1);
846 return HTTP_FORBIDDEN;
851 * Else access is granted from our point of view (except vendor
852 * handlers override). But we have to return DECLINED here instead
853 * of OK, because mod_auth and other modules still might want to
861 * Authentication Handler:
862 * Fake a Basic authentication from the X509 client certificate.
864 * This must be run fairly early on to prevent a real authentication from
865 * occuring, in particular it must be run before anything else that
866 * authenticates a user. This means that the Module statement for this
867 * module should be LAST in the Configuration file.
869 int ssl_hook_UserCheck(request_rec *r)
871 SSLSrvConfigRec *sc = mySrvConfig(r->server);
872 SSLDirConfigRec *dc = myDirConfig(r);
873 char b1[MAX_STRING_LEN], b2[MAX_STRING_LEN];
880 * Additionally forbid access (again)
881 * when strict require option is used.
883 if ( (dc->nOptions & SSL_OPT_STRICTREQUIRE)
884 && (apr_table_get(r->notes, "ssl-access-forbidden") != NULL))
885 return HTTP_FORBIDDEN;
888 * Make sure the user is not able to fake the client certificate
889 * based authentication by just entering an X.509 Subject DN
890 * ("/XX=YYY/XX=YYY/..") as the username and "password" as the
893 if ((cpAL = apr_table_get(r->headers_in, "Authorization")) != NULL) {
894 if (strcEQ(ap_getword(r->pool, &cpAL, ' '), "Basic")) {
895 while (*cpAL == ' ' || *cpAL == '\t')
897 cpAL = ap_pbase64decode(r->pool, cpAL);
898 cpUN = ap_getword_nulls(r->pool, &cpAL, ':');
900 if (cpUN[0] == '/' && strEQ(cpPW, "password"))
901 return HTTP_FORBIDDEN;
906 * We decline operation in various situations...
910 if (apr_table_get(r->connection->notes, "ssl") == NULL)
912 if (!(dc->nOptions & SSL_OPT_FAKEBASICAUTH))
916 if ((clientdn = (char *)apr_table_get(r->connection->notes, "ssl::client::dn")) == NULL)
920 * Fake a password - which one would be immaterial, as, it seems, an empty
921 * password in the users file would match ALL incoming passwords, if only
922 * we were using the standard crypt library routine. Unfortunately, OpenSSL
923 * "fixes" a "bug" in crypt and thus prevents blank passwords from
924 * working. (IMHO what they really fix is a bug in the users of the code
925 * - failing to program correctly for shadow passwords). We need,
926 * therefore, to provide a password. This password can be matched by
927 * adding the string "xxj31ZMTZzkVA" as the password in the user file.
928 * This is just the crypted variant of the word "password" ;-)
930 apr_snprintf(b1, sizeof(b1), "%s:password", clientdn);
931 ssl_util_uuencode(b2, b1, FALSE);
932 apr_snprintf(b1, sizeof(b1), "Basic %s", b2);
933 apr_table_set(r->headers_in, "Authorization", b1);
934 ssl_log(r->server, SSL_LOG_INFO,
935 "Faking HTTP Basic Auth header: \"Authorization: %s\"", b1);
940 /* authorization phase */
941 int ssl_hook_Auth(request_rec *r)
943 SSLDirConfigRec *dc = myDirConfig(r);
946 * Additionally forbid access (again)
947 * when strict require option is used.
949 if ( (dc->nOptions & SSL_OPT_STRICTREQUIRE)
950 && (apr_table_get(r->notes, "ssl-access-forbidden") != NULL))
951 return HTTP_FORBIDDEN;
960 static const char *ssl_hook_Fixup_vars[] = {
961 "SSL_VERSION_INTERFACE",
962 "SSL_VERSION_LIBRARY",
966 "SSL_CIPHER_USEKEYSIZE",
967 "SSL_CIPHER_ALGKEYSIZE",
969 "SSL_CLIENT_M_VERSION",
970 "SSL_CLIENT_M_SERIAL",
971 "SSL_CLIENT_V_START",
975 "SSL_CLIENT_S_DN_ST",
978 "SSL_CLIENT_S_DN_OU",
979 "SSL_CLIENT_S_DN_CN",
985 "SSL_CLIENT_S_DN_UID",
986 "SSL_CLIENT_S_DN_Email",
989 "SSL_CLIENT_I_DN_ST",
992 "SSL_CLIENT_I_DN_OU",
993 "SSL_CLIENT_I_DN_CN",
999 "SSL_CLIENT_I_DN_UID",
1000 "SSL_CLIENT_I_DN_Email",
1003 "SSL_SERVER_M_VERSION",
1004 "SSL_SERVER_M_SERIAL",
1005 "SSL_SERVER_V_START",
1008 "SSL_SERVER_S_DN_C",
1009 "SSL_SERVER_S_DN_ST",
1010 "SSL_SERVER_S_DN_L",
1011 "SSL_SERVER_S_DN_O",
1012 "SSL_SERVER_S_DN_OU",
1013 "SSL_SERVER_S_DN_CN",
1014 "SSL_SERVER_S_DN_T",
1015 "SSL_SERVER_S_DN_I",
1016 "SSL_SERVER_S_DN_G",
1017 "SSL_SERVER_S_DN_S",
1018 "SSL_SERVER_S_DN_D",
1019 "SSL_SERVER_S_DN_UID",
1020 "SSL_SERVER_S_DN_Email",
1022 "SSL_SERVER_I_DN_C",
1023 "SSL_SERVER_I_DN_ST",
1024 "SSL_SERVER_I_DN_L",
1025 "SSL_SERVER_I_DN_O",
1026 "SSL_SERVER_I_DN_OU",
1027 "SSL_SERVER_I_DN_CN",
1028 "SSL_SERVER_I_DN_T",
1029 "SSL_SERVER_I_DN_I",
1030 "SSL_SERVER_I_DN_G",
1031 "SSL_SERVER_I_DN_S",
1032 "SSL_SERVER_I_DN_D",
1033 "SSL_SERVER_I_DN_UID",
1034 "SSL_SERVER_I_DN_Email",
1041 int ssl_hook_Fixup(request_rec *r)
1043 SSLSrvConfigRec *sc = mySrvConfig(r->server);
1044 SSLDirConfigRec *dc = myDirConfig(r);
1045 apr_table_t *e = r->subprocess_env;
1053 * Check to see if SSL is on
1057 if ((ssl = (SSL *)apr_table_get(r->connection->notes, "ssl")) == NULL)
1061 * Annotate the SSI/CGI environment with standard SSL information
1063 /* the always present HTTPS (=HTTP over SSL) flag! */
1064 apr_table_set(e, "HTTPS", "on");
1065 /* standard SSL environment variables */
1066 if (dc->nOptions & SSL_OPT_STDENVVARS) {
1067 for (i = 0; ssl_hook_Fixup_vars[i] != NULL; i++) {
1068 var = (char *)ssl_hook_Fixup_vars[i];
1069 val = ssl_var_lookup(r->pool, r->server, r->connection, r, var);
1070 if (!strIsEmpty(val))
1071 apr_table_set(e, var, val);
1076 * On-demand bloat up the SSI/CGI environment with certificate data
1078 if (dc->nOptions & SSL_OPT_EXPORTCERTDATA) {
1079 val = ssl_var_lookup(r->pool, r->server, r->connection, r, "SSL_SERVER_CERT");
1080 apr_table_set(e, "SSL_SERVER_CERT", val);
1081 val = ssl_var_lookup(r->pool, r->server, r->connection, r, "SSL_CLIENT_CERT");
1082 apr_table_set(e, "SSL_CLIENT_CERT", val);
1083 if ((sk = SSL_get_peer_cert_chain(ssl)) != NULL) {
1084 for (i = 0; i < sk_X509_num(sk); i++) {
1085 var = apr_psprintf(r->pool, "SSL_CLIENT_CERT_CHAIN_%d", i);
1086 val = ssl_var_lookup(r->pool, r->server, r->connection, r, var);
1088 apr_table_setn(e, var, val);
1096 /* _________________________________________________________________
1098 ** OpenSSL Callback Functions
1099 ** _________________________________________________________________
1103 * Handle out temporary RSA private keys on demand
1105 * The background of this as the TLSv1 standard explains it:
1107 * | D.1. Temporary RSA keys
1109 * | US Export restrictions limit RSA keys used for encryption to 512
1110 * | bits, but do not place any limit on lengths of RSA keys used for
1111 * | signing operations. Certificates often need to be larger than 512
1112 * | bits, since 512-bit RSA keys are not secure enough for high-value
1113 * | transactions or for applications requiring long-term security. Some
1114 * | certificates are also designated signing-only, in which case they
1115 * | cannot be used for key exchange.
1117 * | When the public key in the certificate cannot be used for encryption,
1118 * | the server signs a temporary RSA key, which is then exchanged. In
1119 * | exportable applications, the temporary RSA key should be the maximum
1120 * | allowable length (i.e., 512 bits). Because 512-bit RSA keys are
1121 * | relatively insecure, they should be changed often. For typical
1122 * | electronic commerce applications, it is suggested that keys be
1123 * | changed daily or every 500 transactions, and more often if possible.
1124 * | Note that while it is acceptable to use the same temporary key for
1125 * | multiple transactions, it must be signed each time it is used.
1127 * | RSA key generation is a time-consuming process. In many cases, a
1128 * | low-priority process can be assigned the task of key generation.
1129 * | Whenever a new key is completed, the existing temporary key can be
1130 * | replaced with the new one.
1132 * So we generated 512 and 1024 bit temporary keys on startup
1133 * which we now just handle out on demand....
1135 RSA *ssl_callback_TmpRSA(SSL *pSSL, int nExport, int nKeyLen)
1137 SSLModConfigRec *mc = ssl_util_getmodconfig_ssl(pSSL, "ssl_module");
1142 /* It's because an export cipher is used */
1144 rsa = (RSA *)mc->pTmpKeys[SSL_TKPIDX_RSA512];
1145 else if (nKeyLen == 1024)
1146 rsa = (RSA *)mc->pTmpKeys[SSL_TKPIDX_RSA1024];
1148 /* it's too expensive to generate on-the-fly, so keep 1024bit */
1149 rsa = (RSA *)mc->pTmpKeys[SSL_TKPIDX_RSA1024];
1152 /* It's because a sign-only certificate situation exists */
1153 rsa = (RSA *)mc->pTmpKeys[SSL_TKPIDX_RSA1024];
1159 * Handle out the already generated DH parameters...
1161 DH *ssl_callback_TmpDH(SSL *pSSL, int nExport, int nKeyLen)
1163 SSLModConfigRec *mc = ssl_util_getmodconfig_ssl(pSSL, "ssl_module");
1168 /* It's because an export cipher is used */
1170 dh = (DH *)mc->pTmpKeys[SSL_TKPIDX_DH512];
1171 else if (nKeyLen == 1024)
1172 dh = (DH *)mc->pTmpKeys[SSL_TKPIDX_DH1024];
1174 /* it's too expensive to generate on-the-fly, so keep 1024bit */
1175 dh = (DH *)mc->pTmpKeys[SSL_TKPIDX_DH1024];
1178 /* It's because a sign-only certificate situation exists */
1179 dh = (DH *)mc->pTmpKeys[SSL_TKPIDX_DH1024];
1185 * This OpenSSL callback function is called when OpenSSL
1186 * does client authentication and verifies the certificate chain.
1188 int ssl_callback_SSLVerify(int ok, X509_STORE_CTX *ctx)
1194 SSLSrvConfigRec *sc;
1195 SSLDirConfigRec *dc;
1206 * Get Apache context back through OpenSSL context
1208 ssl = (SSL *)X509_STORE_CTX_get_app_data(ctx);
1209 conn = (conn_rec *)SSL_get_app_data(ssl);
1210 actx = (apr_table_t *)SSL_get_app_data2(ssl);
1211 r = (request_rec *)apr_table_get(actx, "ssl::request_rec");
1212 s = conn->base_server;
1213 sc = mySrvConfig(s);
1214 dc = (r != NULL ? myDirConfig(r) : NULL);
1217 * Get verify ingredients
1219 xs = X509_STORE_CTX_get_current_cert(ctx);
1220 errnum = X509_STORE_CTX_get_error(ctx);
1221 errdepth = X509_STORE_CTX_get_error_depth(ctx);
1224 * Log verification information
1226 cp = X509_NAME_oneline(X509_get_subject_name(xs), NULL, 0);
1227 cp2 = X509_NAME_oneline(X509_get_issuer_name(xs), NULL, 0);
1228 ssl_log(s, SSL_LOG_TRACE,
1229 "Certificate Verification: depth: %d, subject: %s, issuer: %s",
1230 errdepth, cp != NULL ? cp : "-unknown-",
1231 cp2 != NULL ? cp2 : "-unknown");
1238 * Check for optionally acceptable non-verifiable issuer situation
1240 if (dc != NULL && dc->nVerifyClient != SSL_CVERIFY_UNSET)
1241 verify = dc->nVerifyClient;
1243 verify = sc->nVerifyClient;
1244 if (ssl_verify_error_is_optional(errnum) &&
1245 verify == SSL_CVERIFY_OPTIONAL_NO_CA)
1247 ssl_log(s, SSL_LOG_TRACE,
1248 "Certificate Verification: Verifiable Issuer is configured as "
1249 "optional, therefore we're accepting the certificate");
1250 apr_table_setn(conn->notes, "ssl::verify::info", "GENEROUS");
1255 * Additionally perform CRL-based revocation checks
1258 ok = ssl_callback_SSLVerify_CRL(ok, ctx, s);
1260 errnum = X509_STORE_CTX_get_error(ctx);
1264 * If we already know it's not ok, log the real reason
1267 ssl_log(s, SSL_LOG_ERROR, "Certificate Verification: Error (%d): %s",
1268 errnum, X509_verify_cert_error_string(errnum));
1269 apr_table_setn(conn->notes, "ssl::client::dn", NULL);
1270 apr_table_setn(conn->notes, "ssl::verify::error",
1271 (void *)X509_verify_cert_error_string(errnum));
1275 * Finally check the depth of the certificate verification
1277 if (dc != NULL && dc->nVerifyDepth != UNSET)
1278 depth = dc->nVerifyDepth;
1280 depth = sc->nVerifyDepth;
1281 if (errdepth > depth) {
1282 ssl_log(s, SSL_LOG_ERROR,
1283 "Certificate Verification: Certificate Chain too long "
1284 "(chain has %d certificates, but maximum allowed are only %d)",
1286 apr_table_setn(conn->notes, "ssl::verify::error",
1287 (void *)X509_verify_cert_error_string(X509_V_ERR_CERT_CHAIN_TOO_LONG));
1292 * And finally signal OpenSSL the (perhaps changed) state
1297 int ssl_callback_SSLVerify_CRL(
1298 int ok, X509_STORE_CTX *ctx, server_rec *s)
1300 SSLSrvConfigRec *sc;
1306 X509_REVOKED *revoked;
1314 * Unless a revocation store for CRLs was created we
1315 * cannot do any CRL-based verification, of course.
1317 sc = mySrvConfig(s);
1318 if (sc->pRevocationStore == NULL)
1322 * Determine certificate ingredients in advance
1324 xs = X509_STORE_CTX_get_current_cert(ctx);
1325 subject = X509_get_subject_name(xs);
1326 issuer = X509_get_issuer_name(xs);
1329 * OpenSSL provides the general mechanism to deal with CRLs but does not
1330 * use them automatically when verifying certificates, so we do it
1331 * explicitly here. We will check the CRL for the currently checked
1332 * certificate, if there is such a CRL in the store.
1334 * We come through this procedure for each certificate in the certificate
1335 * chain, starting with the root-CA's certificate. At each step we've to
1336 * both verify the signature on the CRL (to make sure it's a valid CRL)
1337 * and it's revocation list (to make sure the current certificate isn't
1338 * revoked). But because to check the signature on the CRL we need the
1339 * public key of the issuing CA certificate (which was already processed
1340 * one round before), we've a little problem. But we can both solve it and
1341 * at the same time optimize the processing by using the following
1342 * verification scheme (idea and code snippets borrowed from the GLOBUS
1345 * 1. We'll check the signature of a CRL in each step when we find a CRL
1346 * through the _subject_ name of the current certificate. This CRL
1347 * itself will be needed the first time in the next round, of course.
1348 * But we do the signature processing one round before this where the
1349 * public key of the CA is available.
1351 * 2. We'll check the revocation list of a CRL in each step when
1352 * we find a CRL through the _issuer_ name of the current certificate.
1353 * This CRLs signature was then already verified one round before.
1355 * This verification scheme allows a CA to revoke its own certificate as
1360 * Try to retrieve a CRL corresponding to the _subject_ of
1361 * the current certificate in order to verify it's integrity.
1363 memset((char *)&obj, 0, sizeof(obj));
1364 rc = SSL_X509_STORE_lookup(sc->pRevocationStore, X509_LU_CRL, subject, &obj);
1366 if (rc > 0 && crl != NULL) {
1368 * Log information about CRL
1369 * (A little bit complicated because of ASN.1 and BIOs...)
1371 if (ssl_log_applies(s, SSL_LOG_TRACE)) {
1372 bio = BIO_new(BIO_s_mem());
1373 BIO_printf(bio, "lastUpdate: ");
1374 ASN1_UTCTIME_print(bio, X509_CRL_get_lastUpdate(crl));
1375 BIO_printf(bio, ", nextUpdate: ");
1376 ASN1_UTCTIME_print(bio, X509_CRL_get_nextUpdate(crl));
1377 n = BIO_pending(bio);
1379 n = BIO_read(bio, cp, n);
1382 cp2 = X509_NAME_oneline(subject, NULL, 0);
1383 ssl_log(s, SSL_LOG_TRACE, "CA CRL: Issuer: %s, %s", cp2, cp);
1389 * Verify the signature on this CRL
1391 if (X509_CRL_verify(crl, X509_get_pubkey(xs)) <= 0) {
1392 ssl_log(s, SSL_LOG_WARN, "Invalid signature on CRL");
1393 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE);
1394 X509_OBJECT_free_contents(&obj);
1399 * Check date of CRL to make sure it's not expired
1401 i = X509_cmp_current_time(X509_CRL_get_nextUpdate(crl));
1403 ssl_log(s, SSL_LOG_WARN, "Found CRL has invalid nextUpdate field");
1404 X509_STORE_CTX_set_error(ctx, X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD);
1405 X509_OBJECT_free_contents(&obj);
1409 ssl_log(s, SSL_LOG_WARN,
1410 "Found CRL is expired - "
1411 "revoking all certificates until you get updated CRL");
1412 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_HAS_EXPIRED);
1413 X509_OBJECT_free_contents(&obj);
1416 X509_OBJECT_free_contents(&obj);
1420 * Try to retrieve a CRL corresponding to the _issuer_ of
1421 * the current certificate in order to check for revocation.
1423 memset((char *)&obj, 0, sizeof(obj));
1424 rc = SSL_X509_STORE_lookup(sc->pRevocationStore, X509_LU_CRL, issuer, &obj);
1426 if (rc > 0 && crl != NULL) {
1428 * Check if the current certificate is revoked by this CRL
1430 #if SSL_LIBRARY_VERSION < 0x00904000
1431 n = sk_num(X509_CRL_get_REVOKED(crl));
1433 n = sk_X509_REVOKED_num(X509_CRL_get_REVOKED(crl));
1435 for (i = 0; i < n; i++) {
1436 #if SSL_LIBRARY_VERSION < 0x00904000
1437 revoked = (X509_REVOKED *)sk_value(X509_CRL_get_REVOKED(crl), i);
1439 revoked = sk_X509_REVOKED_value(X509_CRL_get_REVOKED(crl), i);
1441 if (ASN1_INTEGER_cmp(revoked->serialNumber, X509_get_serialNumber(xs)) == 0) {
1443 serial = ASN1_INTEGER_get(revoked->serialNumber);
1444 cp = X509_NAME_oneline(issuer, NULL, 0);
1445 ssl_log(s, SSL_LOG_INFO,
1446 "Certificate with serial %ld (0x%lX) "
1447 "revoked per CRL from issuer %s",
1448 serial, serial, cp);
1451 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
1452 X509_OBJECT_free_contents(&obj);
1456 X509_OBJECT_free_contents(&obj);
1462 * This callback function is executed by OpenSSL whenever a new SSL_SESSION is
1463 * added to the internal OpenSSL session cache. We use this hook to spread the
1464 * SSL_SESSION also to the inter-process disk-cache to make share it with our
1465 * other Apache pre-forked server processes.
1467 int ssl_callback_NewSessionCacheEntry(SSL *ssl, SSL_SESSION *pNew)
1471 SSLSrvConfigRec *sc;
1476 * Get Apache context back through OpenSSL context
1478 conn = (conn_rec *)SSL_get_app_data(ssl);
1479 s = conn->base_server;
1480 sc = mySrvConfig(s);
1483 * Set the timeout also for the internal OpenSSL cache, because this way
1484 * our inter-process cache is consulted only when it's really necessary.
1486 t = sc->nSessionCacheTimeout;
1487 SSL_set_timeout(pNew, t);
1490 * Store the SSL_SESSION in the inter-process cache with the
1491 * same expire time, so it expires automatically there, too.
1493 t = (SSL_get_time(pNew) + sc->nSessionCacheTimeout);
1494 rc = ssl_scache_store(s, pNew->session_id, pNew->session_id_length, t, pNew);
1497 * Log this cache operation
1499 ssl_log(s, SSL_LOG_TRACE, "Inter-Process Session Cache: "
1500 "request=SET status=%s id=%s timeout=%ds (session caching)",
1501 rc == TRUE ? "OK" : "BAD",
1502 SSL_SESSION_id2sz(pNew->session_id, pNew->session_id_length),
1506 * return 0 which means to OpenSSL that the pNew is still
1507 * valid and was not freed by us with SSL_SESSION_free().
1513 * This callback function is executed by OpenSSL whenever a
1514 * SSL_SESSION is looked up in the internal OpenSSL cache and it
1515 * was not found. We use this to lookup the SSL_SESSION in the
1516 * inter-process disk-cache where it was perhaps stored by one
1517 * of our other Apache pre-forked server processes.
1519 SSL_SESSION *ssl_callback_GetSessionCacheEntry(
1520 SSL *ssl, unsigned char *id, int idlen, int *pCopy)
1524 SSL_SESSION *pSession;
1527 * Get Apache context back through OpenSSL context
1529 conn = (conn_rec *)SSL_get_app_data(ssl);
1530 s = conn->base_server;
1533 * Try to retrieve the SSL_SESSION from the inter-process cache
1535 pSession = ssl_scache_retrieve(s, id, idlen);
1538 * Log this cache operation
1540 if (pSession != NULL)
1541 ssl_log(s, SSL_LOG_TRACE, "Inter-Process Session Cache: "
1542 "request=GET status=FOUND id=%s (session reuse)",
1543 SSL_SESSION_id2sz(id, idlen));
1545 ssl_log(s, SSL_LOG_TRACE, "Inter-Process Session Cache: "
1546 "request=GET status=MISSED id=%s (session renewal)",
1547 SSL_SESSION_id2sz(id, idlen));
1550 * Return NULL or the retrieved SSL_SESSION. But indicate (by
1551 * setting pCopy to 0) that the reference count on the
1552 * SSL_SESSION should not be incremented by the SSL library,
1553 * because we will no longer hold a reference to it ourself.
1560 * This callback function is executed by OpenSSL whenever a
1561 * SSL_SESSION is removed from the the internal OpenSSL cache.
1562 * We use this to remove the SSL_SESSION in the inter-process
1565 void ssl_callback_DelSessionCacheEntry(
1566 SSL_CTX *ctx, SSL_SESSION *pSession)
1571 * Get Apache context back through OpenSSL context
1573 s = (server_rec *)SSL_CTX_get_app_data(ctx);
1574 if (s == NULL) /* on server shutdown Apache is already gone */
1578 * Remove the SSL_SESSION from the inter-process cache
1580 ssl_scache_remove(s, pSession->session_id, pSession->session_id_length);
1583 * Log this cache operation
1585 ssl_log(s, SSL_LOG_TRACE, "Inter-Process Session Cache: "
1586 "request=REM status=OK id=%s (session dead)",
1587 SSL_SESSION_id2sz(pSession->session_id,
1588 pSession->session_id_length));
1594 * This callback function is executed while OpenSSL processes the
1595 * SSL handshake and does SSL record layer stuff. We use it to
1596 * trace OpenSSL's processing in out SSL logfile.
1598 void ssl_callback_LogTracingState(SSL *ssl, int where, int rc)
1602 SSLSrvConfigRec *sc;
1606 * find corresponding server
1608 if ((c = (conn_rec *)SSL_get_app_data(ssl)) == NULL)
1611 if ((sc = mySrvConfig(s)) == NULL)
1615 * create the various trace messages
1617 if (sc->nLogLevel >= SSL_LOG_TRACE) {
1618 if (where & SSL_CB_HANDSHAKE_START)
1619 ssl_log(s, SSL_LOG_TRACE, "%s: Handshake: start", SSL_LIBRARY_NAME);
1620 else if (where & SSL_CB_HANDSHAKE_DONE)
1621 ssl_log(s, SSL_LOG_TRACE, "%s: Handshake: done", SSL_LIBRARY_NAME);
1622 else if (where & SSL_CB_LOOP)
1623 ssl_log(s, SSL_LOG_TRACE, "%s: Loop: %s",
1624 SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1625 else if (where & SSL_CB_READ)
1626 ssl_log(s, SSL_LOG_TRACE, "%s: Read: %s",
1627 SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1628 else if (where & SSL_CB_WRITE)
1629 ssl_log(s, SSL_LOG_TRACE, "%s: Write: %s",
1630 SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1631 else if (where & SSL_CB_ALERT) {
1632 str = (where & SSL_CB_READ) ? "read" : "write";
1633 ssl_log(s, SSL_LOG_TRACE, "%s: Alert: %s:%s:%s\n",
1634 SSL_LIBRARY_NAME, str,
1635 SSL_alert_type_string_long(rc),
1636 SSL_alert_desc_string_long(rc));
1638 else if (where & SSL_CB_EXIT) {
1640 ssl_log(s, SSL_LOG_TRACE, "%s: Exit: failed in %s",
1641 SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1643 ssl_log(s, SSL_LOG_TRACE, "%s: Exit: error in %s",
1644 SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1649 * Because SSL renegotations can happen at any time (not only after
1650 * SSL_accept()), the best way to log the current connection details is
1651 * right after a finished handshake.
1653 if (where & SSL_CB_HANDSHAKE_DONE) {
1654 ssl_log(s, SSL_LOG_INFO,
1655 "Connection: Client IP: %s, Protocol: %s, Cipher: %s (%s/%s bits)",
1656 ssl_var_lookup(NULL, s, c, NULL, "REMOTE_ADDR"),
1657 ssl_var_lookup(NULL, s, c, NULL, "SSL_PROTOCOL"),
1658 ssl_var_lookup(NULL, s, c, NULL, "SSL_CIPHER"),
1659 ssl_var_lookup(NULL, s, c, NULL, "SSL_CIPHER_USEKEYSIZE"),
1660 ssl_var_lookup(NULL, s, c, NULL, "SSL_CIPHER_ALGKEYSIZE"));