]> granicus.if.org Git - apache/blob - modules/ssl/ssl_engine_kernel.c
f255658710db6cc583c6152f1beb45905e957de6
[apache] / modules / ssl / ssl_engine_kernel.c
1 /*                      _             _
2 **  _ __ ___   ___   __| |    ___ ___| |  mod_ssl
3 ** | '_ ` _ \ / _ \ / _` |   / __/ __| |  Apache Interface to OpenSSL
4 ** | | | | | | (_) | (_| |   \__ \__ \ |  www.modssl.org
5 ** |_| |_| |_|\___/ \__,_|___|___/___/_|  ftp.modssl.org
6 **                      |_____|
7 **  ssl_engine_kernel.c
8 **  The SSL engine kernel
9 */
10
11 /* ====================================================================
12  * The Apache Software License, Version 1.1
13  *
14  * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
15  * reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  *
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  *
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
27  *    distribution.
28  *
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.
35  *
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.
40  *
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.
44  *
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
56  * SUCH DAMAGE.
57  * ====================================================================
58  */
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.''
63                                             -- Unknown                */
64 #include "mod_ssl.h"
65
66 /*
67  *  Close the SSL part of the socket connection
68  *  (called immediately _before_ the socket is closed)
69  */
70 /* XXX: perhaps ssl_abort() should call us or vice-versa
71  * lot of the same happening in both places
72  */
73 apr_status_t ssl_hook_CloseConnection(SSLFilterRec *filter)
74 {
75     SSL *ssl;
76     char *cpType;
77     conn_rec *conn;
78     
79     ssl  = filter->pssl;
80     conn = (conn_rec *)SSL_get_app_data(ssl);
81
82     if (ssl == NULL)
83         return APR_SUCCESS;
84
85     /*
86      * Now close the SSL layer of the connection. We've to take
87      * the TLSv1 standard into account here:
88      *
89      * | 7.2.1. Closure alerts
90      * |
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.
94      * |
95      * | close_notify
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.
100      * |
101      * | Either party may initiate a close by sending a close_notify alert.
102      * | Any data received after a closure alert is ignored.
103      * |
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.
110      *
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.
115      */
116
117     /*
118      * exchange close notify messages, but allow the user
119      * to force the type of handshake via SetEnvIf directive
120      */
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);
125         cpType = "unclean";
126     }
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);
131         cpType = "accurate";
132     }
133     else {
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);
137         cpType = "standard";
138     }
139     SSL_smart_shutdown(ssl);
140
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");
146
147     /* deallocate the SSL connection */
148     SSL_free(ssl);
149     apr_table_setn(conn->notes, "ssl", NULL);
150     filter->pssl = NULL; /* so filters know we've been shutdown */
151
152     return APR_SUCCESS;
153 }
154
155 /*
156  *  Post Read Request Handler
157  */
158 int ssl_hook_ReadReq(request_rec *r)
159 {
160     SSL *ssl;
161     apr_table_t *apctx;
162
163     /*
164      * Get the SSL connection structure and perform the
165      * delayed interlinking from SSL back to request_rec
166      */
167     ssl = (SSL *)apr_table_get(r->connection->notes, "ssl");
168     if (ssl != NULL) {
169         apctx = (apr_table_t *)SSL_get_app_data2(ssl);
170         apr_table_setn(apctx, "ssl::request_rec", (const char *)r);
171     }
172
173     /*
174      * Force the mod_ssl content handler when URL indicates this
175      */
176     if (strEQn(r->uri, "/mod_ssl:", 9))
177         r->handler = "mod_ssl:content-handler";
178     if (ssl != NULL) {
179         apr_table_setn(r->notes, "ap::http::method",  "https");
180         apr_table_setn(r->notes, "ap::default::port", "443");
181     }
182     else {
183         apr_table_setn(r->notes, "ap::http::method",  NULL);
184         apr_table_setn(r->notes, "ap::default::port", NULL);
185     }
186     return DECLINED;
187 }
188
189 /*
190  *  URL Translation Handler
191  */
192 int ssl_hook_Translate(request_rec *r)
193 {
194     if (apr_table_get(r->connection->notes, "ssl") == NULL)
195         return DECLINED;
196
197     /*
198      * Log information about incoming HTTPS requests
199      */
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 ?
204                     "Initial (No.1)" :
205                     apr_psprintf(r->pool, "Subsequent (No.%d)",
206                                  r->connection->keepalives+1),
207                 r->connection->id,
208                 ssl_util_vhostid(r->pool, r->server));
209
210     /*
211      * Move SetEnvIf information from request_rec to conn_rec/BUFF
212      * to allow the close connection handler to use them.
213      */
214     if (apr_table_get(r->subprocess_env, "ssl-unclean-shutdown") != NULL)
215         apr_table_setn(r->connection->notes, "ssl::flag::unclean-shutdown", PTRUE);
216     else
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);
220     else
221         apr_table_setn(r->connection->notes, "ssl::flag::accurate-shutdown", PFALSE);
222
223     return DECLINED;
224 }
225
226 /*
227  *  Content Handler
228  */
229 int ssl_hook_Handler(request_rec *r)
230 {
231     int port;
232     char *thisport;
233     char *thisurl;
234
235     if (strNE(r->handler, "mod_ssl:content-handler"))
236         return DECLINED;
237     if (strNEn(r->uri, "/mod_ssl:", 9))
238         return DECLINED;
239
240     if (strEQ(r->uri, "/mod_ssl:error:HTTP-request")) {
241         thisport = "";
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));
247
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>",
252                        thisurl, thisurl));
253     }
254
255     return HTTP_BAD_REQUEST;
256 }
257
258 typedef long bio_hook_t (BIO *, int, const char *, int, long, long);
259
260 static void bio_hook_set(BIO *b, bio_hook_t *hook, void *data)
261 {
262     while (b) {
263         BIO_set_callback(b, hook);
264         BIO_set_callback_arg(b, data);
265         b = BIO_next(b);
266     }
267 }
268
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)
273
274 #define ssl_bio_renegotiate_hook_set(ssl, data) \
275 ssl_bio_hooks_set(ssl, ssl_renegotiate_hook, data)
276
277 #define ssl_bio_hooks_unset(ssl) \
278 ssl_bio_hooks_set(ssl, NULL, NULL)
279
280 #define bio_mem_length(b) ((BUF_MEM *)b->ptr)->length
281
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
285  * to BIO_read
286  */
287
288 static long ssl_renegotiate_hook(BIO *bio, int cmd, const char *argp,
289                                  int argi, long argl, long rc)
290 {
291     request_rec *r = (request_rec *)BIO_get_callback_arg(bio);
292     SSL *ssl;
293
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));
296
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
301          * as-as
302          */
303         ssl_bio_hooks_set(ssl, NULL, (void*)SSL_ST_RENEGOTIATE);
304     }
305     else {
306         return rc;
307     }
308
309     if (is_flush) {
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));
314         ap_rflush(r);
315     }
316     else {
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);
322
323         rc = BIO_read(bio, (void *)argp, argi);
324
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));
328     }
329
330     /* reset this bio hook for further read/writes */
331     ssl_bio_renegotiate_hook_set(ssl, r);
332
333     return rc;
334 }
335
336 /*
337  *  Access Handler
338  */
339 int ssl_hook_Access(request_rec *r)
340 {
341     SSLDirConfigRec *dc;
342     SSLSrvConfigRec *sc;
343     SSL *ssl;
344     SSL_CTX *ctx = NULL;
345     apr_array_header_t *apRequirement;
346     ssl_require_t *pRequirements;
347     ssl_require_t *pRequirement;
348     char *cp;
349     int ok;
350     int i;
351     BOOL renegotiate;
352     BOOL renegotiate_quick;
353 #ifdef SSL_EXPERIMENTAL_PERDIRCA
354     BOOL reconfigured_locations;
355     STACK_OF(X509_NAME) *skCAList;
356     char *cpCAPath;
357     char *cpCAFile;
358 #endif
359     X509 *cert;
360     STACK_OF(X509) *certstack;
361     X509_STORE *certstore;
362     X509_STORE_CTX certstorectx;
363     int depth;
364     STACK_OF(SSL_CIPHER) *skCipherOld;
365     STACK_OF(SSL_CIPHER) *skCipher;
366     SSL_CIPHER *pCipher;
367     apr_table_t *apctx;
368     int nVerifyOld;
369     int nVerify;
370     int n;
371     void *vp;
372     int rc;
373
374     dc  = myDirConfig(r);
375     sc  = mySrvConfig(r->server);
376     ssl = (SSL *)apr_table_get(r->connection->notes, "ssl");
377     if (ssl != NULL)
378         ctx = SSL_get_SSL_CTX(ssl);
379
380     /*
381      * Support for SSLRequireSSL directive
382      */
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;
391     }
392
393     /*
394      * Check to see if SSL protocol is on
395      */
396     if (!sc->bEnabled)
397         return DECLINED;
398     if (ssl == NULL)
399         return DECLINED;
400
401     /*
402      * Support for per-directory reconfigured SSL connection parameters.
403      *
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). 
409      * 
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.
420      */
421     renegotiate            = FALSE;
422     renegotiate_quick      = FALSE;
423 #ifdef SSL_EXPERIMENTAL_PERDIRCA
424     reconfigured_locations = FALSE;
425 #endif
426
427     /*
428      * Override of SSLCipherSuite
429      *
430      * We provide two options here:
431      *
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).
436      *
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.
447      */
448     if (dc->szCipherSuite != NULL) {
449         /* remember old state */
450         pCipher = NULL;
451         skCipherOld = NULL;
452         if (dc->nOptions & SSL_OPT_OPTRENEGOTIATE)
453             pCipher = SSL_get_current_cipher(ssl);
454         else {
455             skCipherOld = SSL_get_ciphers(ssl);
456             if (skCipherOld != NULL)
457                 skCipherOld = sk_SSL_CIPHER_dup(skCipherOld);
458         }
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;
466         }
467         /* determine whether a renegotiation has to be forced */
468         skCipher = SSL_get_ciphers(ssl);
469         if (dc->nOptions & SSL_OPT_OPTRENEGOTIATE) {
470             /* optimized way */
471             if ((pCipher == NULL && skCipher != NULL) ||
472                 (pCipher != NULL && skCipher == NULL)   )
473                 renegotiate = TRUE;
474             else if (pCipher != NULL && skCipher != NULL
475                      && sk_SSL_CIPHER_find(skCipher, pCipher) < 0) {
476                 renegotiate = TRUE;
477             }
478         }
479         else {
480             /* paranoid way */
481             if ((skCipherOld == NULL && skCipher != NULL) ||
482                 (skCipherOld != NULL && skCipher == NULL)   )
483                 renegotiate = TRUE;
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)
487                         renegotiate = TRUE;
488                 }
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)
491                         renegotiate = TRUE;
492                 }
493             }
494         }
495         /* cleanup */
496         if (skCipherOld != NULL)
497             sk_SSL_CIPHER_free(skCipherOld);
498         /* tracing */
499         if (renegotiate)
500             ssl_log(r->server, SSL_LOG_TRACE,
501                     "Reconfigured cipher suite will force renegotiation");
502     }
503
504     /*
505      * override of SSLVerifyDepth
506      *
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).
515      */
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);
520         else
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) {
526             renegotiate = TRUE;
527             ssl_log(r->server, SSL_LOG_TRACE,
528                     "Reduced client verification depth will force renegotiation");
529         }
530     }
531
532     /*
533      * override of SSLVerifyClient
534      *
535      * We force a renegotiation if the reconfigured/new verify type is
536      * stronger than the currently active verify type. 
537      *
538      * The order is: none << optional_no_ca << optional << require
539      *
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
544      * handshake.
545      */
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)))) {
566                 renegotiate = TRUE;
567                 /* optimization */
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 " : "");
575              }
576         }
577     }
578
579     /*
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...
588      */
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;
602         /*
603            FIXME: This should be...
604            if (!SSL_load_verify_locations(ssl, cpCAFile, cpCAPath)) {
605            ...but OpenSSL still doesn't provide this!
606          */
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;
612         }
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;
619         }
620         SSL_set_client_CA_list(ssl, skCAList);
621         renegotiate = TRUE;
622         reconfigured_locations = TRUE;
623         ssl_log(r->server, SSL_LOG_TRACE,
624                 "Changed client verification locations will force renegotiation");
625     }
626 #endif /* SSL_EXPERIMENTAL_PERDIRCA */
627
628     /* 
629      * SSL renegotiations in conjunction with HTTP
630      * requests using the POST method are not supported.
631      *
632      * Background:
633      *
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.
640      *
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.
650      *
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.
659      *
660      * Solution Idea:
661      *
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.
674      *
675      * Solution Implementation:
676      *
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.
685      *
686      * !! BUT ALL THIS IS STILL NOT RE-IMPLEMENTED FOR APACHE 2.0 !!
687      */
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;
692     }
693
694     /*
695      * now do the renegotiation if anything was actually reconfigured
696      */
697     if (renegotiate) {
698         /*
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.
708          */
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;
718             }
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;
723             }
724             cert = sk_X509_value(certstack, 0);
725             X509_STORE_CTX_init(&certstorectx, certstore, cert, certstack);
726             depth = SSL_get_verify_depth(ssl);
727             if (depth >= 0)
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);
736         }
737         else {
738             /* do a full renegotiation */
739             ssl_log(r->server, SSL_LOG_TRACE,
740                     "Performing full renegotiation: complete handshake protocol");
741             if (r->main != NULL)
742                 SSL_set_session_id_context(ssl, (unsigned char *)&(r->main), sizeof(r->main));
743             else
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);
749
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;
754             }
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);
758
759             ssl_bio_hooks_unset(ssl);
760
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;
765             }
766         }
767
768         /*
769          * Remember the peer certificate's DN
770          */
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));
775             free(cp);
776         }
777
778         /*
779          * Finally check for acceptable renegotiation results
780          */
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;
787             }
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;
793             }
794         }
795     }
796
797     /*
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.
802      */
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;
811         }
812     }
813 #endif /* SSL_EXPERIMENTAL_PERDIRCA */
814
815     /*
816      * Check SSLRequire boolean expressions
817      */
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);
823         if (ok < 0) {
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;
832         }
833         if (ok != 1) {
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;
847         }
848     }
849
850     /*
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
854      * deny access.
855      */
856     rc = DECLINED;
857     return rc;
858 }
859
860 /*
861  *  Authentication Handler:
862  *  Fake a Basic authentication from the X509 client certificate.
863  *
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.
868  */
869 int ssl_hook_UserCheck(request_rec *r)
870 {
871     SSLSrvConfigRec *sc = mySrvConfig(r->server);
872     SSLDirConfigRec *dc = myDirConfig(r);
873     char b1[MAX_STRING_LEN], b2[MAX_STRING_LEN];
874     char *clientdn;
875     const char *cpAL;
876     const char *cpUN;
877     const char *cpPW;
878
879     /*
880      * Additionally forbid access (again)
881      * when strict require option is used.
882      */
883     if (   (dc->nOptions & SSL_OPT_STRICTREQUIRE)
884         && (apr_table_get(r->notes, "ssl-access-forbidden") != NULL))
885         return HTTP_FORBIDDEN;
886
887     /*
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
891      * password.
892      */
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')
896                 cpAL++;
897             cpAL = ap_pbase64decode(r->pool, cpAL);
898             cpUN = ap_getword_nulls(r->pool, &cpAL, ':');
899             cpPW = cpAL;
900             if (cpUN[0] == '/' && strEQ(cpPW, "password"))
901                 return HTTP_FORBIDDEN;
902         }
903     }
904
905     /*
906      * We decline operation in various situations...
907      */
908     if (!sc->bEnabled)
909         return DECLINED;
910     if (apr_table_get(r->connection->notes, "ssl") == NULL)
911         return DECLINED;
912     if (!(dc->nOptions & SSL_OPT_FAKEBASICAUTH))
913         return DECLINED;
914     if (r->user)
915         return DECLINED;
916     if ((clientdn = (char *)apr_table_get(r->connection->notes, "ssl::client::dn")) == NULL)
917         return DECLINED;
918
919     /*
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" ;-)
929      */
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);
936
937     return DECLINED;
938 }
939
940 /* authorization phase */
941 int ssl_hook_Auth(request_rec *r)
942 {
943     SSLDirConfigRec *dc = myDirConfig(r);
944
945     /*
946      * Additionally forbid access (again)
947      * when strict require option is used.
948      */
949     if (   (dc->nOptions & SSL_OPT_STRICTREQUIRE)
950         && (apr_table_get(r->notes, "ssl-access-forbidden") != NULL))
951         return HTTP_FORBIDDEN;
952
953     return DECLINED;
954 }
955
956 /*
957  *   Fixup Handler
958  */
959
960 static const char *ssl_hook_Fixup_vars[] = {
961     "SSL_VERSION_INTERFACE",
962     "SSL_VERSION_LIBRARY",
963     "SSL_PROTOCOL",
964     "SSL_CIPHER",
965     "SSL_CIPHER_EXPORT",
966     "SSL_CIPHER_USEKEYSIZE",
967     "SSL_CIPHER_ALGKEYSIZE",
968     "SSL_CLIENT_VERIFY",
969     "SSL_CLIENT_M_VERSION",
970     "SSL_CLIENT_M_SERIAL",
971     "SSL_CLIENT_V_START",
972     "SSL_CLIENT_V_END",
973     "SSL_CLIENT_S_DN",
974     "SSL_CLIENT_S_DN_C",
975     "SSL_CLIENT_S_DN_ST",
976     "SSL_CLIENT_S_DN_L",
977     "SSL_CLIENT_S_DN_O",
978     "SSL_CLIENT_S_DN_OU",
979     "SSL_CLIENT_S_DN_CN",
980     "SSL_CLIENT_S_DN_T",
981     "SSL_CLIENT_S_DN_I",
982     "SSL_CLIENT_S_DN_G",
983     "SSL_CLIENT_S_DN_S",
984     "SSL_CLIENT_S_DN_D",
985     "SSL_CLIENT_S_DN_UID",
986     "SSL_CLIENT_S_DN_Email",
987     "SSL_CLIENT_I_DN",
988     "SSL_CLIENT_I_DN_C",
989     "SSL_CLIENT_I_DN_ST",
990     "SSL_CLIENT_I_DN_L",
991     "SSL_CLIENT_I_DN_O",
992     "SSL_CLIENT_I_DN_OU",
993     "SSL_CLIENT_I_DN_CN",
994     "SSL_CLIENT_I_DN_T",
995     "SSL_CLIENT_I_DN_I",
996     "SSL_CLIENT_I_DN_G",
997     "SSL_CLIENT_I_DN_S",
998     "SSL_CLIENT_I_DN_D",
999     "SSL_CLIENT_I_DN_UID",
1000     "SSL_CLIENT_I_DN_Email",
1001     "SSL_CLIENT_A_KEY",
1002     "SSL_CLIENT_A_SIG",
1003     "SSL_SERVER_M_VERSION",
1004     "SSL_SERVER_M_SERIAL",
1005     "SSL_SERVER_V_START",
1006     "SSL_SERVER_V_END",
1007     "SSL_SERVER_S_DN",
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",
1021     "SSL_SERVER_I_DN",
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",
1035     "SSL_SERVER_A_KEY",
1036     "SSL_SERVER_A_SIG",
1037     "SSL_SESSION_ID",
1038     NULL
1039 };
1040
1041 int ssl_hook_Fixup(request_rec *r)
1042 {
1043     SSLSrvConfigRec *sc = mySrvConfig(r->server);
1044     SSLDirConfigRec *dc = myDirConfig(r);
1045     apr_table_t *e = r->subprocess_env;
1046     char *var;
1047     char *val = "";
1048     STACK_OF(X509) *sk;
1049     SSL *ssl;
1050     int i;
1051
1052     /*
1053      * Check to see if SSL is on
1054      */
1055     if (!sc->bEnabled)
1056         return DECLINED;
1057     if ((ssl = (SSL *)apr_table_get(r->connection->notes, "ssl")) == NULL)
1058         return DECLINED;
1059
1060     /*
1061      * Annotate the SSI/CGI environment with standard SSL information
1062      */
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);
1072         }
1073     }
1074
1075     /*
1076      * On-demand bloat up the SSI/CGI environment with certificate data
1077      */
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);
1087                 if (val != NULL)
1088                      apr_table_setn(e, var, val);
1089             }
1090         }
1091     }
1092
1093     return DECLINED;
1094 }
1095
1096 /*  _________________________________________________________________
1097 **
1098 **  OpenSSL Callback Functions
1099 **  _________________________________________________________________
1100 */
1101
1102 /*
1103  * Handle out temporary RSA private keys on demand
1104  *
1105  * The background of this as the TLSv1 standard explains it:
1106  *
1107  * | D.1. Temporary RSA keys
1108  * |
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.
1116  * |
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.
1126  * |
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.
1131  *
1132  * So we generated 512 and 1024 bit temporary keys on startup
1133  * which we now just handle out on demand....
1134  */
1135 RSA *ssl_callback_TmpRSA(SSL *pSSL, int nExport, int nKeyLen)
1136 {
1137     SSLModConfigRec *mc = ssl_util_getmodconfig_ssl(pSSL, "ssl_module");
1138     RSA *rsa;
1139
1140     rsa = NULL;
1141     if (nExport) {
1142         /* It's because an export cipher is used */
1143         if (nKeyLen == 512)
1144             rsa = (RSA *)mc->pTmpKeys[SSL_TKPIDX_RSA512];
1145         else if (nKeyLen == 1024)
1146             rsa = (RSA *)mc->pTmpKeys[SSL_TKPIDX_RSA1024];
1147         else
1148             /* it's too expensive to generate on-the-fly, so keep 1024bit */
1149             rsa = (RSA *)mc->pTmpKeys[SSL_TKPIDX_RSA1024];
1150     }
1151     else {
1152         /* It's because a sign-only certificate situation exists */
1153         rsa = (RSA *)mc->pTmpKeys[SSL_TKPIDX_RSA1024];
1154     }
1155     return rsa;
1156 }
1157
1158 /* 
1159  * Handle out the already generated DH parameters...
1160  */
1161 DH *ssl_callback_TmpDH(SSL *pSSL, int nExport, int nKeyLen)
1162 {
1163     SSLModConfigRec *mc = ssl_util_getmodconfig_ssl(pSSL, "ssl_module");
1164     DH *dh;
1165
1166     dh = NULL;
1167     if (nExport) {
1168         /* It's because an export cipher is used */
1169         if (nKeyLen == 512)
1170             dh = (DH *)mc->pTmpKeys[SSL_TKPIDX_DH512];
1171         else if (nKeyLen == 1024)
1172             dh = (DH *)mc->pTmpKeys[SSL_TKPIDX_DH1024];
1173         else
1174             /* it's too expensive to generate on-the-fly, so keep 1024bit */
1175             dh = (DH *)mc->pTmpKeys[SSL_TKPIDX_DH1024];
1176     }
1177     else {
1178         /* It's because a sign-only certificate situation exists */
1179         dh = (DH *)mc->pTmpKeys[SSL_TKPIDX_DH1024];
1180     }
1181     return dh;
1182 }
1183
1184 /*
1185  * This OpenSSL callback function is called when OpenSSL
1186  * does client authentication and verifies the certificate chain.
1187  */
1188 int ssl_callback_SSLVerify(int ok, X509_STORE_CTX *ctx)
1189 {
1190     SSL *ssl;
1191     conn_rec *conn;
1192     server_rec *s;
1193     request_rec *r;
1194     SSLSrvConfigRec *sc;
1195     SSLDirConfigRec *dc;
1196     apr_table_t *actx;
1197     X509 *xs;
1198     int errnum;
1199     int errdepth;
1200     char *cp;
1201     char *cp2;
1202     int depth;
1203     int verify;
1204
1205     /*
1206      * Get Apache context back through OpenSSL context
1207      */
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);
1215
1216     /*
1217      * Get verify ingredients
1218      */
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);
1222
1223     /*
1224      * Log verification information
1225      */
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");
1232     if (cp)
1233         free(cp);
1234     if (cp2)
1235         free(cp2);
1236
1237     /*
1238      * Check for optionally acceptable non-verifiable issuer situation
1239      */
1240     if (dc != NULL && dc->nVerifyClient != SSL_CVERIFY_UNSET)
1241         verify = dc->nVerifyClient;
1242     else
1243         verify = sc->nVerifyClient;
1244     if (ssl_verify_error_is_optional(errnum) &&
1245         verify == SSL_CVERIFY_OPTIONAL_NO_CA)
1246     {
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");
1251         ok = TRUE;
1252     }
1253
1254     /*
1255      * Additionally perform CRL-based revocation checks
1256      */
1257     if (ok) {
1258         ok = ssl_callback_SSLVerify_CRL(ok, ctx, s);
1259         if (!ok)
1260             errnum = X509_STORE_CTX_get_error(ctx);
1261     }
1262
1263     /*
1264      * If we already know it's not ok, log the real reason
1265      */
1266     if (!ok) {
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));
1272     }
1273
1274     /*
1275      * Finally check the depth of the certificate verification
1276      */
1277     if (dc != NULL && dc->nVerifyDepth != UNSET)
1278         depth = dc->nVerifyDepth;
1279     else
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)",
1285                 errdepth, depth);
1286         apr_table_setn(conn->notes, "ssl::verify::error",
1287                    (void *)X509_verify_cert_error_string(X509_V_ERR_CERT_CHAIN_TOO_LONG));
1288         ok = FALSE;
1289     }
1290
1291     /*
1292      * And finally signal OpenSSL the (perhaps changed) state
1293      */
1294     return (ok);
1295 }
1296
1297 int ssl_callback_SSLVerify_CRL(
1298     int ok, X509_STORE_CTX *ctx, server_rec *s)
1299 {
1300     SSLSrvConfigRec *sc;
1301     X509_OBJECT obj;
1302     X509_NAME *subject;
1303     X509_NAME *issuer;
1304     X509 *xs;
1305     X509_CRL *crl;
1306     X509_REVOKED *revoked;
1307     long serial;
1308     BIO *bio;
1309     int i, n, rc;
1310     char *cp;
1311     char *cp2;
1312
1313     /*
1314      * Unless a revocation store for CRLs was created we
1315      * cannot do any CRL-based verification, of course.
1316      */
1317     sc = mySrvConfig(s);
1318     if (sc->pRevocationStore == NULL)
1319         return ok;
1320
1321     /*
1322      * Determine certificate ingredients in advance
1323      */
1324     xs      = X509_STORE_CTX_get_current_cert(ctx);
1325     subject = X509_get_subject_name(xs);
1326     issuer  = X509_get_issuer_name(xs);
1327
1328     /*
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.
1333      *
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
1343      * project):
1344      *
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.
1350      *
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.
1354      *
1355      * This verification scheme allows a CA to revoke its own certificate as
1356      * well, of course.
1357      */
1358
1359     /*
1360      * Try to retrieve a CRL corresponding to the _subject_ of
1361      * the current certificate in order to verify it's integrity.
1362      */
1363     memset((char *)&obj, 0, sizeof(obj));
1364     rc = SSL_X509_STORE_lookup(sc->pRevocationStore, X509_LU_CRL, subject, &obj);
1365     crl = obj.data.crl;
1366     if (rc > 0 && crl != NULL) {
1367         /*
1368          * Log information about CRL
1369          * (A little bit complicated because of ASN.1 and BIOs...)
1370          */
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);
1378             cp = malloc(n+1);
1379             n = BIO_read(bio, cp, n);
1380             cp[n] = NUL;
1381             BIO_free(bio);
1382             cp2 = X509_NAME_oneline(subject, NULL, 0);
1383             ssl_log(s, SSL_LOG_TRACE, "CA CRL: Issuer: %s, %s", cp2, cp);
1384             free(cp2);
1385             free(cp);
1386         }
1387
1388         /*
1389          * Verify the signature on this CRL
1390          */
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);
1395             return FALSE;
1396         }
1397
1398         /*
1399          * Check date of CRL to make sure it's not expired
1400          */
1401         i = X509_cmp_current_time(X509_CRL_get_nextUpdate(crl));
1402         if (i == 0) {
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);
1406             return FALSE;
1407         }
1408         if (i < 0) {
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);
1414             return FALSE;
1415         }
1416         X509_OBJECT_free_contents(&obj);
1417     }
1418
1419     /*
1420      * Try to retrieve a CRL corresponding to the _issuer_ of
1421      * the current certificate in order to check for revocation.
1422      */
1423     memset((char *)&obj, 0, sizeof(obj));
1424     rc = SSL_X509_STORE_lookup(sc->pRevocationStore, X509_LU_CRL, issuer, &obj);
1425     crl = obj.data.crl;
1426     if (rc > 0 && crl != NULL) {
1427         /*
1428          * Check if the current certificate is revoked by this CRL
1429          */
1430 #if SSL_LIBRARY_VERSION < 0x00904000
1431         n = sk_num(X509_CRL_get_REVOKED(crl));
1432 #else
1433         n = sk_X509_REVOKED_num(X509_CRL_get_REVOKED(crl));
1434 #endif
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);
1438 #else
1439             revoked = sk_X509_REVOKED_value(X509_CRL_get_REVOKED(crl), i);
1440 #endif
1441             if (ASN1_INTEGER_cmp(revoked->serialNumber, X509_get_serialNumber(xs)) == 0) {
1442
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);
1449                 free(cp);
1450
1451                 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
1452                 X509_OBJECT_free_contents(&obj);
1453                 return FALSE;
1454             }
1455         }
1456         X509_OBJECT_free_contents(&obj);
1457     }
1458     return ok;
1459 }
1460
1461 /*
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.
1466  */
1467 int ssl_callback_NewSessionCacheEntry(SSL *ssl, SSL_SESSION *pNew)
1468 {
1469     conn_rec *conn;
1470     server_rec *s;
1471     SSLSrvConfigRec *sc;
1472     long t;
1473     BOOL rc;
1474
1475     /*
1476      * Get Apache context back through OpenSSL context
1477      */
1478     conn = (conn_rec *)SSL_get_app_data(ssl);
1479     s    = conn->base_server;
1480     sc   = mySrvConfig(s);
1481
1482     /*
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.
1485      */
1486     t = sc->nSessionCacheTimeout;
1487     SSL_set_timeout(pNew, t);
1488
1489     /*
1490      * Store the SSL_SESSION in the inter-process cache with the
1491      * same expire time, so it expires automatically there, too.
1492      */
1493     t = (SSL_get_time(pNew) + sc->nSessionCacheTimeout);
1494     rc = ssl_scache_store(s, pNew->session_id, pNew->session_id_length, t, pNew);
1495
1496     /*
1497      * Log this cache operation
1498      */
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),
1503             t-time(NULL));
1504
1505     /*
1506      * return 0 which means to OpenSSL that the pNew is still
1507      * valid and was not freed by us with SSL_SESSION_free().
1508      */
1509     return 0;
1510 }
1511
1512 /*
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.
1518  */
1519 SSL_SESSION *ssl_callback_GetSessionCacheEntry(
1520     SSL *ssl, unsigned char *id, int idlen, int *pCopy)
1521 {
1522     conn_rec *conn;
1523     server_rec *s;
1524     SSL_SESSION *pSession;
1525
1526     /*
1527      * Get Apache context back through OpenSSL context
1528      */
1529     conn = (conn_rec *)SSL_get_app_data(ssl);
1530     s    = conn->base_server;
1531
1532     /*
1533      * Try to retrieve the SSL_SESSION from the inter-process cache
1534      */
1535     pSession = ssl_scache_retrieve(s, id, idlen);
1536
1537     /*
1538      * Log this cache operation
1539      */
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));
1544     else
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));
1548
1549     /*
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.
1554      */
1555     *pCopy = 0;
1556     return pSession;
1557 }
1558
1559 /*
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
1563  *  disk-cache, too.
1564  */
1565 void ssl_callback_DelSessionCacheEntry(
1566     SSL_CTX *ctx, SSL_SESSION *pSession)
1567 {
1568     server_rec *s;
1569
1570     /*
1571      * Get Apache context back through OpenSSL context
1572      */
1573     s = (server_rec *)SSL_CTX_get_app_data(ctx);
1574     if (s == NULL) /* on server shutdown Apache is already gone */
1575         return;
1576
1577     /*
1578      * Remove the SSL_SESSION from the inter-process cache
1579      */
1580     ssl_scache_remove(s, pSession->session_id, pSession->session_id_length);
1581
1582     /*
1583      * Log this cache operation
1584      */
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));
1589
1590     return;
1591 }
1592
1593 /*
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.
1597  */
1598 void ssl_callback_LogTracingState(SSL *ssl, int where, int rc)
1599 {
1600     conn_rec *c;
1601     server_rec *s;
1602     SSLSrvConfigRec *sc;
1603     char *str;
1604
1605     /*
1606      * find corresponding server
1607      */
1608     if ((c = (conn_rec *)SSL_get_app_data(ssl)) == NULL)
1609         return;
1610     s = c->base_server;
1611     if ((sc = mySrvConfig(s)) == NULL)
1612         return;
1613
1614     /*
1615      * create the various trace messages
1616      */
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));
1637         }
1638         else if (where & SSL_CB_EXIT) {
1639             if (rc == 0)
1640                 ssl_log(s, SSL_LOG_TRACE, "%s: Exit: failed in %s",
1641                         SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1642             else if (rc < 0)
1643                 ssl_log(s, SSL_LOG_TRACE, "%s: Exit: error in %s",
1644                         SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1645         }
1646     }
1647
1648     /*
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.
1652      */
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"));
1661     }
1662
1663     return;
1664 }
1665