1/* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements.  See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License.  You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*                      _             _
18 *  _ __ ___   ___   __| |    ___ ___| |  mod_ssl
19 * | '_ ` _ \ / _ \ / _` |   / __/ __| |  Apache Interface to OpenSSL
20 * | | | | | | (_) | (_| |   \__ \__ \ |
21 * |_| |_| |_|\___/ \__,_|___|___/___/_|
22 *                      |_____|
23 *  ssl_engine_kernel.c
24 *  The SSL engine kernel
25 */
26                             /* ``It took me fifteen years to discover
27                                  I had no talent for programming, but
28                                  I couldn't give it up because by that
29                                  time I was too famous.''
30                                            -- Unknown                */
31#include "ssl_private.h"
32#include "util_md5.h"
33
34static void ssl_configure_env(request_rec *r, SSLConnRec *sslconn);
35#ifdef HAVE_TLSEXT
36static int ssl_find_vhost(void *servername, conn_rec *c, server_rec *s);
37#endif
38
39#define SWITCH_STATUS_LINE "HTTP/1.1 101 Switching Protocols"
40#define UPGRADE_HEADER "Upgrade: TLS/1.0, HTTP/1.1"
41#define CONNECTION_HEADER "Connection: Upgrade"
42
43/* Perform an upgrade-to-TLS for the given request, per RFC 2817. */
44static apr_status_t upgrade_connection(request_rec *r)
45{
46    struct conn_rec *conn = r->connection;
47    apr_bucket_brigade *bb;
48    SSLConnRec *sslconn;
49    apr_status_t rv;
50    SSL *ssl;
51
52    ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02028)
53                  "upgrading connection to TLS");
54
55    bb = apr_brigade_create(r->pool, conn->bucket_alloc);
56
57    rv = ap_fputstrs(conn->output_filters, bb, SWITCH_STATUS_LINE, CRLF,
58                     UPGRADE_HEADER, CRLF, CONNECTION_HEADER, CRLF, CRLF, NULL);
59    if (rv == APR_SUCCESS) {
60        APR_BRIGADE_INSERT_TAIL(bb,
61                                apr_bucket_flush_create(conn->bucket_alloc));
62        rv = ap_pass_brigade(conn->output_filters, bb);
63    }
64
65    if (rv) {
66        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02029)
67                      "failed to send 101 interim response for connection "
68                      "upgrade");
69        return rv;
70    }
71
72    ssl_init_ssl_connection(conn, r);
73
74    sslconn = myConnConfig(conn);
75    ssl = sslconn->ssl;
76
77    /* Perform initial SSL handshake. */
78    SSL_set_accept_state(ssl);
79    SSL_do_handshake(ssl);
80
81    if (SSL_get_state(ssl) != SSL_ST_OK) {
82        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02030)
83                      "TLS upgrade handshake failed: not accepted by client!?");
84
85        return APR_ECONNABORTED;
86    }
87
88    return APR_SUCCESS;
89}
90
91/* Perform a speculative (and non-blocking) read from the connection
92 * filters for the given request, to determine whether there is any
93 * pending data to read.  Return non-zero if there is, else zero. */
94static int has_buffered_data(request_rec *r)
95{
96    apr_bucket_brigade *bb;
97    apr_off_t len;
98    apr_status_t rv;
99    int result;
100
101    bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
102
103    rv = ap_get_brigade(r->connection->input_filters, bb, AP_MODE_SPECULATIVE,
104                        APR_NONBLOCK_READ, 1);
105    result = rv == APR_SUCCESS
106        && apr_brigade_length(bb, 1, &len) == APR_SUCCESS
107        && len > 0;
108
109    apr_brigade_destroy(bb);
110
111    return result;
112}
113
114/*
115 *  Post Read Request Handler
116 */
117int ssl_hook_ReadReq(request_rec *r)
118{
119    SSLSrvConfigRec *sc = mySrvConfig(r->server);
120    SSLConnRec *sslconn;
121    const char *upgrade;
122#ifdef HAVE_TLSEXT
123    const char *servername;
124#endif
125    SSL *ssl;
126
127    /* Perform TLS upgrade here if "SSLEngine optional" is configured,
128     * SSL is not already set up for this connection, and the client
129     * has sent a suitable Upgrade header. */
130    if (sc->enabled == SSL_ENABLED_OPTIONAL && !myConnConfig(r->connection)
131        && (upgrade = apr_table_get(r->headers_in, "Upgrade")) != NULL
132        && ap_find_token(r->pool, upgrade, "TLS/1.0")) {
133        if (upgrade_connection(r)) {
134            return HTTP_INTERNAL_SERVER_ERROR;
135        }
136    }
137
138    sslconn = myConnConfig(r->connection);
139    if (!sslconn) {
140        return DECLINED;
141    }
142
143    if (sslconn->non_ssl_request == NON_SSL_SET_ERROR_MSG) {
144        apr_table_setn(r->notes, "error-notes",
145                       "Reason: You're speaking plain HTTP to an SSL-enabled "
146                       "server port.<br />\n Instead use the HTTPS scheme to "
147                       "access this URL, please.<br />\n");
148
149        /* Now that we have caught this error, forget it. we are done
150         * with using SSL on this request.
151         */
152        sslconn->non_ssl_request = NON_SSL_OK;
153
154        return HTTP_BAD_REQUEST;
155    }
156
157    /*
158     * Get the SSL connection structure and perform the
159     * delayed interlinking from SSL back to request_rec
160     */
161    ssl = sslconn->ssl;
162    if (!ssl) {
163        return DECLINED;
164    }
165#ifdef HAVE_TLSEXT
166    if (r->proxyreq != PROXYREQ_PROXY) {
167        if ((servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name))) {
168            char *host, *scope_id;
169            apr_port_t port;
170            apr_status_t rv;
171
172            /*
173             * The SNI extension supplied a hostname. So don't accept requests
174             * with either no hostname or a different hostname as this could
175             * cause us to end up in a different virtual host as the one that
176             * was used for the handshake causing different SSL parameters to
177             * be applied as SSLProtocol, SSLCACertificateFile/Path and
178             * SSLCADNRequestFile/Path cannot be renegotioated (SSLCA* due
179             * to current limitiations in Openssl, see
180             * http://mail-archives.apache.org/mod_mbox/httpd-dev/200806.mbox/%3C48592955.2090303@velox.ch%3E
181             * and
182             * http://mail-archives.apache.org/mod_mbox/httpd-dev/201312.mbox/%3CCAKQ1sVNpOrdiBm-UPw1hEdSN7YQXRRjeaT-MCWbW_7mN%3DuFiOw%40mail.gmail.com%3E
183             * )
184             */
185            if (!r->hostname) {
186                ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server, APLOGNO(02031)
187                            "Hostname %s provided via SNI, but no hostname"
188                            " provided in HTTP request", servername);
189                return HTTP_BAD_REQUEST;
190            }
191            rv = apr_parse_addr_port(&host, &scope_id, &port, r->hostname, r->pool);
192            if (rv != APR_SUCCESS || scope_id) {
193                return HTTP_BAD_REQUEST;
194            }
195            if (strcasecmp(host, servername)) {
196                ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server, APLOGNO(02032)
197                            "Hostname %s provided via SNI and hostname %s provided"
198                            " via HTTP are different", servername, host);
199                return HTTP_BAD_REQUEST;
200            }
201        }
202        else if (((sc->strict_sni_vhost_check == SSL_ENABLED_TRUE)
203                 || (mySrvConfig(sslconn->server))->strict_sni_vhost_check
204                    == SSL_ENABLED_TRUE)
205                 && r->connection->vhost_lookup_data) {
206            /*
207             * We are using a name based configuration here, but no hostname was
208             * provided via SNI. Don't allow that if are requested to do strict
209             * checking. Check wether this strict checking was setup either in the
210             * server config we used for handshaking or in our current server.
211             * This should avoid insecure configuration by accident.
212             */
213            ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server, APLOGNO(02033)
214                         "No hostname was provided via SNI for a name based"
215                         " virtual host");
216            return HTTP_FORBIDDEN;
217        }
218    }
219#endif
220    SSL_set_app_data2(ssl, r);
221
222    /*
223     * Log information about incoming HTTPS requests
224     */
225    if (APLOGrinfo(r) && ap_is_initial_req(r)) {
226        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02034)
227                     "%s HTTPS request received for child %ld (server %s)",
228                     (r->connection->keepalives <= 0 ?
229                     "Initial (No.1)" :
230                     apr_psprintf(r->pool, "Subsequent (No.%d)",
231                                  r->connection->keepalives+1)),
232                     r->connection->id,
233                     ssl_util_vhostid(r->pool, r->server));
234    }
235
236    /* SetEnvIf ssl-*-shutdown flags can only be per-server,
237     * so they won't change across keepalive requests
238     */
239    if (sslconn->shutdown_type == SSL_SHUTDOWN_TYPE_UNSET) {
240        ssl_configure_env(r, sslconn);
241    }
242
243    return DECLINED;
244}
245
246/*
247 * Move SetEnvIf information from request_rec to conn_rec/BUFF
248 * to allow the close connection handler to use them.
249 */
250
251static void ssl_configure_env(request_rec *r, SSLConnRec *sslconn)
252{
253    int i;
254    const apr_array_header_t *arr = apr_table_elts(r->subprocess_env);
255    const apr_table_entry_t *elts = (const apr_table_entry_t *)arr->elts;
256
257    sslconn->shutdown_type = SSL_SHUTDOWN_TYPE_STANDARD;
258
259    for (i = 0; i < arr->nelts; i++) {
260        const char *key = elts[i].key;
261
262        switch (*key) {
263          case 's':
264            /* being case-sensitive here.
265             * and not checking for the -shutdown since these are the only
266             * SetEnvIf "flags" we support
267             */
268            if (!strncmp(key+1, "sl-", 3)) {
269                key += 4;
270                if (!strncmp(key, "unclean", 7)) {
271                    sslconn->shutdown_type = SSL_SHUTDOWN_TYPE_UNCLEAN;
272                }
273                else if (!strncmp(key, "accurate", 8)) {
274                    sslconn->shutdown_type = SSL_SHUTDOWN_TYPE_ACCURATE;
275                }
276                return; /* should only ever be one ssl-*-shutdown */
277            }
278            break;
279        }
280    }
281}
282
283/*
284 *  Access Handler
285 */
286int ssl_hook_Access(request_rec *r)
287{
288    SSLDirConfigRec *dc         = myDirConfig(r);
289    SSLSrvConfigRec *sc         = mySrvConfig(r->server);
290    SSLConnRec *sslconn         = myConnConfig(r->connection);
291    SSL *ssl                    = sslconn ? sslconn->ssl : NULL;
292    server_rec *handshakeserver = sslconn ? sslconn->server : NULL;
293    SSL_CTX *ctx = NULL;
294    apr_array_header_t *requires;
295    ssl_require_t *ssl_requires;
296    int ok, i;
297    BOOL renegotiate = FALSE, renegotiate_quick = FALSE;
298    X509 *cert;
299    X509 *peercert;
300    X509_STORE *cert_store = NULL;
301    X509_STORE_CTX cert_store_ctx;
302    STACK_OF(SSL_CIPHER) *cipher_list_old = NULL, *cipher_list = NULL;
303    const SSL_CIPHER *cipher = NULL;
304    int depth, verify_old, verify, n;
305
306    if (ssl) {
307        ctx = SSL_get_SSL_CTX(ssl);
308    }
309
310    /*
311     * Support for SSLRequireSSL directive
312     */
313    if (dc->bSSLRequired && !ssl) {
314        if (sc->enabled == SSL_ENABLED_OPTIONAL) {
315            /* This vhost was configured for optional SSL, just tell the
316             * client that we need to upgrade.
317             */
318            apr_table_setn(r->err_headers_out, "Upgrade", "TLS/1.0, HTTP/1.1");
319            apr_table_setn(r->err_headers_out, "Connection", "Upgrade");
320
321            return HTTP_UPGRADE_REQUIRED;
322        }
323
324        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02219)
325                      "access to %s failed, reason: %s",
326                      r->filename, "SSL connection required");
327
328        /* remember forbidden access for strict require option */
329        apr_table_setn(r->notes, "ssl-access-forbidden", "1");
330
331        return HTTP_FORBIDDEN;
332    }
333
334    /*
335     * Check to see whether SSL is in use; if it's not, then no
336     * further access control checks are relevant.  (the test for
337     * sc->enabled is probably strictly unnecessary)
338     */
339    if (sc->enabled == SSL_ENABLED_FALSE || !ssl) {
340        return DECLINED;
341    }
342
343#ifdef HAVE_SRP
344    /*
345     * Support for per-directory reconfigured SSL connection parameters
346     *
347     * We do not force any renegotiation if the user is already authenticated
348     * via SRP.
349     *
350     */
351    if (SSL_get_srp_username(ssl)) {
352        return DECLINED;
353    }
354#endif
355
356    /*
357     * Support for per-directory reconfigured SSL connection parameters.
358     *
359     * This is implemented by forcing an SSL renegotiation with the
360     * reconfigured parameter suite. But Apache's internal API processing
361     * makes our life very hard here, because when internal sub-requests occur
362     * we nevertheless should avoid multiple unnecessary SSL handshakes (they
363     * require extra network I/O and especially time to perform).
364     *
365     * But the optimization for filtering out the unnecessary handshakes isn't
366     * obvious and trivial.  Especially because while Apache is in its
367     * sub-request processing the client could force additional handshakes,
368     * too. And these take place perhaps without our notice. So the only
369     * possibility is to explicitly _ask_ OpenSSL whether the renegotiation
370     * has to be performed or not. It has to performed when some parameters
371     * which were previously known (by us) are not those we've now
372     * reconfigured (as known by OpenSSL) or (in optimized way) at least when
373     * the reconfigured parameter suite is stronger (more restrictions) than
374     * the currently active one.
375     */
376
377    /*
378     * Override of SSLCipherSuite
379     *
380     * We provide two options here:
381     *
382     * o The paranoid and default approach where we force a renegotiation when
383     *   the cipher suite changed in _any_ way (which is straight-forward but
384     *   often forces renegotiations too often and is perhaps not what the
385     *   user actually wanted).
386     *
387     * o The optimized and still secure way where we force a renegotiation
388     *   only if the currently active cipher is no longer contained in the
389     *   reconfigured/new cipher suite. Any other changes are not important
390     *   because it's the servers choice to select a cipher from the ones the
391     *   client supports. So as long as the current cipher is still in the new
392     *   cipher suite we're happy. Because we can assume we would have
393     *   selected it again even when other (better) ciphers exists now in the
394     *   new cipher suite. This approach is fine because the user explicitly
395     *   has to enable this via ``SSLOptions +OptRenegotiate''. So we do no
396     *   implicit optimizations.
397     */
398    if (dc->szCipherSuite || (r->server != handshakeserver)) {
399        /* remember old state */
400
401        if (dc->nOptions & SSL_OPT_OPTRENEGOTIATE) {
402            cipher = SSL_get_current_cipher(ssl);
403        }
404        else {
405            cipher_list_old = (STACK_OF(SSL_CIPHER) *)SSL_get_ciphers(ssl);
406
407            if (cipher_list_old) {
408                cipher_list_old = sk_SSL_CIPHER_dup(cipher_list_old);
409            }
410        }
411
412        /* configure new state */
413        if ((dc->szCipherSuite || sc->server->auth.cipher_suite) &&
414            !SSL_set_cipher_list(ssl, dc->szCipherSuite ?
415                                      dc->szCipherSuite :
416                                      sc->server->auth.cipher_suite)) {
417            ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(02253)
418                          "Unable to reconfigure (per-directory) "
419                          "permitted SSL ciphers");
420            ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, r->server);
421
422            if (cipher_list_old) {
423                sk_SSL_CIPHER_free(cipher_list_old);
424            }
425
426            return HTTP_FORBIDDEN;
427        }
428
429        /* determine whether a renegotiation has to be forced */
430        cipher_list = (STACK_OF(SSL_CIPHER) *)SSL_get_ciphers(ssl);
431
432        if (dc->nOptions & SSL_OPT_OPTRENEGOTIATE) {
433            /* optimized way */
434            if ((!cipher && cipher_list) ||
435                (cipher && !cipher_list))
436            {
437                renegotiate = TRUE;
438            }
439            else if (cipher && cipher_list &&
440                     (sk_SSL_CIPHER_find(cipher_list, cipher) < 0))
441            {
442                renegotiate = TRUE;
443            }
444        }
445        else {
446            /* paranoid way */
447            if ((!cipher_list_old && cipher_list) ||
448                (cipher_list_old && !cipher_list))
449            {
450                renegotiate = TRUE;
451            }
452            else if (cipher_list_old && cipher_list) {
453                for (n = 0;
454                     !renegotiate && (n < sk_SSL_CIPHER_num(cipher_list));
455                     n++)
456                {
457                    SSL_CIPHER *value = sk_SSL_CIPHER_value(cipher_list, n);
458
459                    if (sk_SSL_CIPHER_find(cipher_list_old, value) < 0) {
460                        renegotiate = TRUE;
461                    }
462                }
463
464                for (n = 0;
465                     !renegotiate && (n < sk_SSL_CIPHER_num(cipher_list_old));
466                     n++)
467                {
468                    SSL_CIPHER *value = sk_SSL_CIPHER_value(cipher_list_old, n);
469
470                    if (sk_SSL_CIPHER_find(cipher_list, value) < 0) {
471                        renegotiate = TRUE;
472                    }
473                }
474            }
475        }
476
477        /* cleanup */
478        if (cipher_list_old) {
479            sk_SSL_CIPHER_free(cipher_list_old);
480        }
481
482        if (renegotiate) {
483#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
484            if (sc->cipher_server_pref == TRUE) {
485                SSL_set_options(ssl, SSL_OP_CIPHER_SERVER_PREFERENCE);
486            }
487#endif
488            /* tracing */
489            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02220)
490                         "Reconfigured cipher suite will force renegotiation");
491        }
492    }
493
494    /*
495     * override of SSLVerifyDepth
496     *
497     * The depth checks are handled by us manually inside the verify callback
498     * function and not by OpenSSL internally (and our function is aware of
499     * both the per-server and per-directory contexts). So we cannot ask
500     * OpenSSL about the currently verify depth. Instead we remember it in our
501     * SSLConnRec attached to the SSL* of OpenSSL.  We've to force the
502     * renegotiation if the reconfigured/new verify depth is less than the
503     * currently active/remembered verify depth (because this means more
504     * restriction on the certificate chain).
505     */
506    n = (sslconn->verify_depth != UNSET) ?
507        sslconn->verify_depth :
508        (mySrvConfig(handshakeserver))->server->auth.verify_depth;
509    /* determine the new depth */
510    sslconn->verify_depth = (dc->nVerifyDepth != UNSET) ?
511                            dc->nVerifyDepth : sc->server->auth.verify_depth;
512    if (sslconn->verify_depth < n) {
513        renegotiate = TRUE;
514        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02254)
515                     "Reduced client verification depth will force "
516                     "renegotiation");
517    }
518
519    /*
520     * override of SSLVerifyClient
521     *
522     * We force a renegotiation if the reconfigured/new verify type is
523     * stronger than the currently active verify type.
524     *
525     * The order is: none << optional_no_ca << optional << require
526     *
527     * Additionally the following optimization is possible here: When the
528     * currently active verify type is "none" but a client certificate is
529     * already known/present, it's enough to manually force a client
530     * verification but at least skip the I/O-intensive renegotiation
531     * handshake.
532     */
533    if ((dc->nVerifyClient != SSL_CVERIFY_UNSET) ||
534        (sc->server->auth.verify_mode != SSL_CVERIFY_UNSET)) {
535        /* remember old state */
536        verify_old = SSL_get_verify_mode(ssl);
537        /* configure new state */
538        verify = SSL_VERIFY_NONE;
539
540        if ((dc->nVerifyClient == SSL_CVERIFY_REQUIRE) ||
541            (sc->server->auth.verify_mode == SSL_CVERIFY_REQUIRE)) {
542            verify |= SSL_VERIFY_PEER_STRICT;
543        }
544
545        if ((dc->nVerifyClient == SSL_CVERIFY_OPTIONAL) ||
546            (dc->nVerifyClient == SSL_CVERIFY_OPTIONAL_NO_CA) ||
547            (sc->server->auth.verify_mode == SSL_CVERIFY_OPTIONAL) ||
548            (sc->server->auth.verify_mode == SSL_CVERIFY_OPTIONAL_NO_CA))
549        {
550            verify |= SSL_VERIFY_PEER;
551        }
552
553        SSL_set_verify(ssl, verify, ssl_callback_SSLVerify);
554        SSL_set_verify_result(ssl, X509_V_OK);
555
556        /* determine whether we've to force a renegotiation */
557        if (!renegotiate && verify != verify_old) {
558            if (((verify_old == SSL_VERIFY_NONE) &&
559                 (verify     != SSL_VERIFY_NONE)) ||
560
561                (!(verify_old & SSL_VERIFY_PEER) &&
562                  (verify     & SSL_VERIFY_PEER)) ||
563
564                (!(verify_old & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) &&
565                  (verify     & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)))
566            {
567                renegotiate = TRUE;
568                /* optimization */
569
570                if ((dc->nOptions & SSL_OPT_OPTRENEGOTIATE) &&
571                    (verify_old == SSL_VERIFY_NONE) &&
572                    ((peercert = SSL_get_peer_certificate(ssl)) != NULL))
573                {
574                    renegotiate_quick = TRUE;
575                    X509_free(peercert);
576                }
577
578                ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02255)
579                              "Changed client verification type will force "
580                              "%srenegotiation",
581                              renegotiate_quick ? "quick " : "");
582             }
583        }
584        /* If we're handling a request for a vhost other than the default one,
585         * then we need to make sure that client authentication is properly
586         * enforced. For clients supplying an SNI extension, the peer
587         * certificate verification has happened in the handshake already
588         * (and r->server == handshakeserver). For non-SNI requests,
589         * an additional check is needed here. If client authentication
590         * is configured as mandatory, then we can only proceed if the
591         * CA list doesn't have to be changed (OpenSSL doesn't provide
592         * an option to change the list for an existing session).
593         */
594        if ((r->server != handshakeserver)
595            && renegotiate
596            && ((verify & SSL_VERIFY_PEER) ||
597                (verify & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))) {
598            SSLSrvConfigRec *hssc = mySrvConfig(handshakeserver);
599
600#define MODSSL_CFG_CA_NE(f, sc1, sc2) \
601            (sc1->server->auth.f && \
602             (!sc2->server->auth.f || \
603              strNE(sc1->server->auth.f, sc2->server->auth.f)))
604
605            if (MODSSL_CFG_CA_NE(ca_cert_file, sc, hssc) ||
606                MODSSL_CFG_CA_NE(ca_cert_path, sc, hssc)) {
607                if (verify & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
608                    ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02256)
609                         "Non-default virtual host with SSLVerify set to "
610                         "'require' and VirtualHost-specific CA certificate "
611                         "list is only available to clients with TLS server "
612                         "name indication (SNI) support");
613                    SSL_set_verify(ssl, verify_old, NULL);
614                    return HTTP_FORBIDDEN;
615                } else
616                    /* let it pass, possibly with an "incorrect" peer cert,
617                     * so make sure the SSL_CLIENT_VERIFY environment variable
618                     * will indicate partial success only, later on.
619                     */
620                    sslconn->verify_info = "GENEROUS";
621            }
622        }
623    }
624
625    /* If a renegotiation is now required for this location, and the
626     * request includes a message body (and the client has not
627     * requested a "100 Continue" response), then the client will be
628     * streaming the request body over the wire already.  In that
629     * case, it is not possible to stop and perform a new SSL
630     * handshake immediately; once the SSL library moves to the
631     * "accept" state, it will reject the SSL packets which the client
632     * is sending for the request body.
633     *
634     * To allow authentication to complete in this auth hook, the
635     * solution used here is to fill a (bounded) buffer with the
636     * request body, and then to reinject that request body later.
637     */
638    if (renegotiate && !renegotiate_quick
639        && (apr_table_get(r->headers_in, "transfer-encoding")
640            || (apr_table_get(r->headers_in, "content-length")
641                && strcmp(apr_table_get(r->headers_in, "content-length"), "0")))
642        && !r->expecting_100) {
643        int rv;
644        apr_size_t rsize;
645
646        rsize = dc->nRenegBufferSize == UNSET ? DEFAULT_RENEG_BUFFER_SIZE :
647                                                dc->nRenegBufferSize;
648        if (rsize > 0) {
649            /* Fill the I/O buffer with the request body if possible. */
650            rv = ssl_io_buffer_fill(r, rsize);
651        }
652        else {
653            /* If the reneg buffer size is set to zero, just fail. */
654            rv = HTTP_REQUEST_ENTITY_TOO_LARGE;
655        }
656
657        if (rv) {
658            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02257)
659                          "could not buffer message body to allow "
660                          "SSL renegotiation to proceed");
661            return rv;
662        }
663    }
664
665    /*
666     * now do the renegotiation if anything was actually reconfigured
667     */
668    if (renegotiate) {
669        /*
670         * Now we force the SSL renegotiation by sending the Hello Request
671         * message to the client. Here we have to do a workaround: Actually
672         * OpenSSL returns immediately after sending the Hello Request (the
673         * intent AFAIK is because the SSL/TLS protocol says it's not a must
674         * that the client replies to a Hello Request). But because we insist
675         * on a reply (anything else is an error for us) we have to go to the
676         * ACCEPT state manually. Using SSL_set_accept_state() doesn't work
677         * here because it resets too much of the connection.  So we set the
678         * state explicitly and continue the handshake manually.
679         */
680        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02221)
681                      "Requesting connection re-negotiation");
682
683        if (renegotiate_quick) {
684            STACK_OF(X509) *cert_stack;
685
686            /* perform just a manual re-verification of the peer */
687            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02258)
688                         "Performing quick renegotiation: "
689                         "just re-verifying the peer");
690
691            cert_stack = (STACK_OF(X509) *)SSL_get_peer_cert_chain(ssl);
692
693            cert = SSL_get_peer_certificate(ssl);
694
695            if (!cert_stack && cert) {
696                /* client cert is in the session cache, but there is
697                 * no chain, since ssl3_get_client_certificate()
698                 * sk_X509_shift-ed the peer cert out of the chain.
699                 * we put it back here for the purpose of quick_renegotiation.
700                 */
701                cert_stack = sk_X509_new_null();
702                sk_X509_push(cert_stack, cert);
703            }
704
705            if (!cert_stack || (sk_X509_num(cert_stack) == 0)) {
706                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02222)
707                              "Cannot find peer certificate chain");
708
709                return HTTP_FORBIDDEN;
710            }
711
712            if (!(cert_store ||
713                  (cert_store = SSL_CTX_get_cert_store(ctx))))
714            {
715                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02223)
716                              "Cannot find certificate storage");
717
718                return HTTP_FORBIDDEN;
719            }
720
721            if (!cert) {
722                cert = sk_X509_value(cert_stack, 0);
723            }
724
725            X509_STORE_CTX_init(&cert_store_ctx, cert_store, cert, cert_stack);
726            depth = SSL_get_verify_depth(ssl);
727
728            if (depth >= 0) {
729                X509_STORE_CTX_set_depth(&cert_store_ctx, depth);
730            }
731
732            X509_STORE_CTX_set_ex_data(&cert_store_ctx,
733                                       SSL_get_ex_data_X509_STORE_CTX_idx(),
734                                       (char *)ssl);
735
736            if (!X509_verify_cert(&cert_store_ctx)) {
737                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02224)
738                              "Re-negotiation verification step failed");
739                ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, r->server);
740            }
741
742            SSL_set_verify_result(ssl, cert_store_ctx.error);
743            X509_STORE_CTX_cleanup(&cert_store_ctx);
744
745            if (cert_stack != SSL_get_peer_cert_chain(ssl)) {
746                /* we created this ourselves, so free it */
747                sk_X509_pop_free(cert_stack, X509_free);
748            }
749        }
750        else {
751            const char *reneg_support;
752            request_rec *id = r->main ? r->main : r;
753
754            /* Additional mitigation for CVE-2009-3555: At this point,
755             * before renegotiating, an (entire) request has been read
756             * from the connection.  An attacker may have sent further
757             * data to "prefix" any subsequent request by the victim's
758             * client after the renegotiation; this data may already
759             * have been read and buffered.  Forcing a connection
760             * closure after the response ensures such data will be
761             * discarded.  Legimately pipelined HTTP requests will be
762             * retried anyway with this approach. */
763            if (has_buffered_data(r)) {
764                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02259)
765                              "insecure SSL re-negotiation required, but "
766                              "a pipelined request is present; keepalive "
767                              "disabled");
768                r->connection->keepalive = AP_CONN_CLOSE;
769            }
770
771#if defined(SSL_get_secure_renegotiation_support)
772            reneg_support = SSL_get_secure_renegotiation_support(ssl) ?
773                            "client does" : "client does not";
774#else
775            reneg_support = "server does not";
776#endif
777            /* Perform a full renegotiation. */
778            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02260)
779                          "Performing full renegotiation: complete handshake "
780                          "protocol (%s support secure renegotiation)",
781                          reneg_support);
782
783            SSL_set_session_id_context(ssl,
784                                       (unsigned char *)&id,
785                                       sizeof(id));
786
787            /* Toggle the renegotiation state to allow the new
788             * handshake to proceed. */
789            sslconn->reneg_state = RENEG_ALLOW;
790
791            SSL_renegotiate(ssl);
792            SSL_do_handshake(ssl);
793
794            if (SSL_get_state(ssl) != SSL_ST_OK) {
795                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02225)
796                              "Re-negotiation request failed");
797                ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, r->server);
798
799                r->connection->keepalive = AP_CONN_CLOSE;
800                return HTTP_FORBIDDEN;
801            }
802
803            ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02226)
804                          "Awaiting re-negotiation handshake");
805
806            /* XXX: Should replace setting state with SSL_renegotiate(ssl);
807             * However, this causes failures in perl-framework currently,
808             * perhaps pre-test if we have already negotiated?
809             */
810#ifdef OPENSSL_NO_SSL_INTERN
811            SSL_set_state(ssl, SSL_ST_ACCEPT);
812#else
813            ssl->state = SSL_ST_ACCEPT;
814#endif
815            SSL_do_handshake(ssl);
816
817            sslconn->reneg_state = RENEG_REJECT;
818
819            if (SSL_get_state(ssl) != SSL_ST_OK) {
820                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02261)
821                              "Re-negotiation handshake failed: "
822                              "Not accepted by client!?");
823
824                r->connection->keepalive = AP_CONN_CLOSE;
825                return HTTP_FORBIDDEN;
826            }
827        }
828
829        /*
830         * Remember the peer certificate's DN
831         */
832        if ((cert = SSL_get_peer_certificate(ssl))) {
833            if (sslconn->client_cert) {
834                X509_free(sslconn->client_cert);
835            }
836            sslconn->client_cert = cert;
837            sslconn->client_dn = NULL;
838        }
839
840        /*
841         * Finally check for acceptable renegotiation results
842         */
843        if ((dc->nVerifyClient != SSL_CVERIFY_NONE) ||
844            (sc->server->auth.verify_mode != SSL_CVERIFY_NONE)) {
845            BOOL do_verify = ((dc->nVerifyClient == SSL_CVERIFY_REQUIRE) ||
846                              (sc->server->auth.verify_mode == SSL_CVERIFY_REQUIRE));
847
848            if (do_verify && (SSL_get_verify_result(ssl) != X509_V_OK)) {
849                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02262)
850                              "Re-negotiation handshake failed: "
851                              "Client verification failed");
852
853                return HTTP_FORBIDDEN;
854            }
855
856            if (do_verify) {
857                if ((peercert = SSL_get_peer_certificate(ssl)) == NULL) {
858                    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02263)
859                                  "Re-negotiation handshake failed: "
860                                  "Client certificate missing");
861
862                    return HTTP_FORBIDDEN;
863                }
864
865                X509_free(peercert);
866            }
867        }
868
869        /*
870         * Also check that SSLCipherSuite has been enforced as expected.
871         */
872        if (cipher_list) {
873            cipher = SSL_get_current_cipher(ssl);
874            if (sk_SSL_CIPHER_find(cipher_list, cipher) < 0) {
875                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02264)
876                             "SSL cipher suite not renegotiated: "
877                             "access to %s denied using cipher %s",
878                              r->filename,
879                              SSL_CIPHER_get_name(cipher));
880                return HTTP_FORBIDDEN;
881            }
882        }
883    }
884
885    /* If we're trying to have the user name set from a client
886     * certificate then we need to set it here. This should be safe as
887     * the user name probably isn't important from an auth checking point
888     * of view as the certificate supplied acts in that capacity.
889     * However, if FakeAuth is being used then this isn't the case so
890     * we need to postpone setting the username until later.
891     */
892    if ((dc->nOptions & SSL_OPT_FAKEBASICAUTH) == 0 && dc->szUserName) {
893        char *val = ssl_var_lookup(r->pool, r->server, r->connection,
894                                   r, (char *)dc->szUserName);
895        if (val && val[0])
896            r->user = val;
897        else
898            ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(02227)
899                          "Failed to set r->user to '%s'", dc->szUserName);
900    }
901
902    /*
903     * Check SSLRequire boolean expressions
904     */
905    requires = dc->aRequirement;
906    ssl_requires = (ssl_require_t *)requires->elts;
907
908    for (i = 0; i < requires->nelts; i++) {
909        ssl_require_t *req = &ssl_requires[i];
910        const char *errstring;
911        ok = ap_expr_exec(r, req->mpExpr, &errstring);
912
913        if (ok < 0) {
914            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02265)
915                          "access to %s failed, reason: Failed to execute "
916                          "SSL requirement expression: %s",
917                          r->filename, errstring);
918
919            /* remember forbidden access for strict require option */
920            apr_table_setn(r->notes, "ssl-access-forbidden", "1");
921
922            return HTTP_FORBIDDEN;
923        }
924
925        if (ok != 1) {
926            ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02266)
927                          "Access to %s denied for %s "
928                          "(requirement expression not fulfilled)",
929                          r->filename, r->useragent_ip);
930
931            ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02228)
932                          "Failed expression: %s", req->cpExpr);
933
934            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02229)
935                          "access to %s failed, reason: %s",
936                          r->filename,
937                          "SSL requirement expression not fulfilled");
938
939            /* remember forbidden access for strict require option */
940            apr_table_setn(r->notes, "ssl-access-forbidden", "1");
941
942            return HTTP_FORBIDDEN;
943        }
944    }
945
946    /*
947     * Else access is granted from our point of view (except vendor
948     * handlers override). But we have to return DECLINED here instead
949     * of OK, because mod_auth and other modules still might want to
950     * deny access.
951     */
952
953    return DECLINED;
954}
955
956/*
957 *  Authentication Handler:
958 *  Fake a Basic authentication from the X509 client certificate.
959 *
960 *  This must be run fairly early on to prevent a real authentication from
961 *  occuring, in particular it must be run before anything else that
962 *  authenticates a user.  This means that the Module statement for this
963 *  module should be LAST in the Configuration file.
964 */
965int ssl_hook_UserCheck(request_rec *r)
966{
967    SSLConnRec *sslconn = myConnConfig(r->connection);
968    SSLSrvConfigRec *sc = mySrvConfig(r->server);
969    SSLDirConfigRec *dc = myDirConfig(r);
970    char *clientdn;
971    const char *auth_line, *username, *password;
972
973    /*
974     * Additionally forbid access (again)
975     * when strict require option is used.
976     */
977    if ((dc->nOptions & SSL_OPT_STRICTREQUIRE) &&
978        (apr_table_get(r->notes, "ssl-access-forbidden")))
979    {
980        return HTTP_FORBIDDEN;
981    }
982
983    /*
984     * We decline when we are in a subrequest.  The Authorization header
985     * would already be present if it was added in the main request.
986     */
987    if (!ap_is_initial_req(r)) {
988        return DECLINED;
989    }
990
991    /*
992     * Make sure the user is not able to fake the client certificate
993     * based authentication by just entering an X.509 Subject DN
994     * ("/XX=YYY/XX=YYY/..") as the username and "password" as the
995     * password.
996     */
997    if ((auth_line = apr_table_get(r->headers_in, "Authorization"))) {
998        if (strcEQ(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
999            while ((*auth_line == ' ') || (*auth_line == '\t')) {
1000                auth_line++;
1001            }
1002
1003            auth_line = ap_pbase64decode(r->pool, auth_line);
1004            username = ap_getword_nulls(r->pool, &auth_line, ':');
1005            password = auth_line;
1006
1007            if ((username[0] == '/') && strEQ(password, "password")) {
1008                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02035)
1009                    "Encountered FakeBasicAuth spoof: %s", username);
1010                return HTTP_FORBIDDEN;
1011            }
1012        }
1013    }
1014
1015    /*
1016     * We decline operation in various situations...
1017     * - SSLOptions +FakeBasicAuth not configured
1018     * - r->user already authenticated
1019     * - ssl not enabled
1020     * - client did not present a certificate
1021     */
1022    if (!((sc->enabled == SSL_ENABLED_TRUE || sc->enabled == SSL_ENABLED_OPTIONAL)
1023          && sslconn && sslconn->ssl && sslconn->client_cert) ||
1024        !(dc->nOptions & SSL_OPT_FAKEBASICAUTH) || r->user)
1025    {
1026        return DECLINED;
1027    }
1028
1029    if (!sslconn->client_dn) {
1030        X509_NAME *name = X509_get_subject_name(sslconn->client_cert);
1031        char *cp = X509_NAME_oneline(name, NULL, 0);
1032        sslconn->client_dn = apr_pstrdup(r->connection->pool, cp);
1033        OPENSSL_free(cp);
1034    }
1035
1036    clientdn = (char *)sslconn->client_dn;
1037
1038    /*
1039     * Fake a password - which one would be immaterial, as, it seems, an empty
1040     * password in the users file would match ALL incoming passwords, if only
1041     * we were using the standard crypt library routine. Unfortunately, OpenSSL
1042     * "fixes" a "bug" in crypt and thus prevents blank passwords from
1043     * working.  (IMHO what they really fix is a bug in the users of the code
1044     * - failing to program correctly for shadow passwords).  We need,
1045     * therefore, to provide a password. This password can be matched by
1046     * adding the string "xxj31ZMTZzkVA" as the password in the user file.
1047     * This is just the crypted variant of the word "password" ;-)
1048     */
1049    auth_line = apr_pstrcat(r->pool, "Basic ",
1050                            ap_pbase64encode(r->pool,
1051                                             apr_pstrcat(r->pool, clientdn,
1052                                                         ":password", NULL)),
1053                            NULL);
1054    apr_table_setn(r->headers_in, "Authorization", auth_line);
1055
1056    ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02036)
1057                  "Faking HTTP Basic Auth header: \"Authorization: %s\"",
1058                  auth_line);
1059
1060    return DECLINED;
1061}
1062
1063/* authorization phase */
1064int ssl_hook_Auth(request_rec *r)
1065{
1066    SSLDirConfigRec *dc = myDirConfig(r);
1067
1068    /*
1069     * Additionally forbid access (again)
1070     * when strict require option is used.
1071     */
1072    if ((dc->nOptions & SSL_OPT_STRICTREQUIRE) &&
1073        (apr_table_get(r->notes, "ssl-access-forbidden")))
1074    {
1075        return HTTP_FORBIDDEN;
1076    }
1077
1078    return DECLINED;
1079}
1080
1081/*
1082 *   Fixup Handler
1083 */
1084
1085static const char *ssl_hook_Fixup_vars[] = {
1086    "SSL_VERSION_INTERFACE",
1087    "SSL_VERSION_LIBRARY",
1088    "SSL_PROTOCOL",
1089    "SSL_SECURE_RENEG",
1090    "SSL_COMPRESS_METHOD",
1091    "SSL_CIPHER",
1092    "SSL_CIPHER_EXPORT",
1093    "SSL_CIPHER_USEKEYSIZE",
1094    "SSL_CIPHER_ALGKEYSIZE",
1095    "SSL_CLIENT_VERIFY",
1096    "SSL_CLIENT_M_VERSION",
1097    "SSL_CLIENT_M_SERIAL",
1098    "SSL_CLIENT_V_START",
1099    "SSL_CLIENT_V_END",
1100    "SSL_CLIENT_V_REMAIN",
1101    "SSL_CLIENT_S_DN",
1102    "SSL_CLIENT_I_DN",
1103    "SSL_CLIENT_A_KEY",
1104    "SSL_CLIENT_A_SIG",
1105    "SSL_SERVER_M_VERSION",
1106    "SSL_SERVER_M_SERIAL",
1107    "SSL_SERVER_V_START",
1108    "SSL_SERVER_V_END",
1109    "SSL_SERVER_S_DN",
1110    "SSL_SERVER_I_DN",
1111    "SSL_SERVER_A_KEY",
1112    "SSL_SERVER_A_SIG",
1113    "SSL_SESSION_ID",
1114    "SSL_SESSION_RESUMED",
1115#ifdef HAVE_SRP
1116    "SSL_SRP_USER",
1117    "SSL_SRP_USERINFO",
1118#endif
1119    NULL
1120};
1121
1122int ssl_hook_Fixup(request_rec *r)
1123{
1124    SSLConnRec *sslconn = myConnConfig(r->connection);
1125    SSLSrvConfigRec *sc = mySrvConfig(r->server);
1126    SSLDirConfigRec *dc = myDirConfig(r);
1127    apr_table_t *env = r->subprocess_env;
1128    char *var, *val = "";
1129#ifdef HAVE_TLSEXT
1130    const char *servername;
1131#endif
1132    STACK_OF(X509) *peer_certs;
1133    SSL *ssl;
1134    int i;
1135
1136    /* If "SSLEngine optional" is configured, this is not an SSL
1137     * connection, and this isn't a subrequest, send an Upgrade
1138     * response header. */
1139    if (sc->enabled == SSL_ENABLED_OPTIONAL && !(sslconn && sslconn->ssl)
1140        && !r->main) {
1141        apr_table_setn(r->headers_out, "Upgrade", "TLS/1.0, HTTP/1.1");
1142        apr_table_mergen(r->headers_out, "Connection", "upgrade");
1143    }
1144
1145    /*
1146     * Check to see if SSL is on
1147     */
1148    if (!(((sc->enabled == SSL_ENABLED_TRUE) || (sc->enabled == SSL_ENABLED_OPTIONAL)) && sslconn && (ssl = sslconn->ssl))) {
1149        return DECLINED;
1150    }
1151
1152    /*
1153     * Annotate the SSI/CGI environment with standard SSL information
1154     */
1155    /* the always present HTTPS (=HTTP over SSL) flag! */
1156    apr_table_setn(env, "HTTPS", "on");
1157
1158#ifdef HAVE_TLSEXT
1159    /* add content of SNI TLS extension (if supplied with ClientHello) */
1160    if ((servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name))) {
1161        apr_table_set(env, "SSL_TLS_SNI", servername);
1162    }
1163#endif
1164
1165    /* standard SSL environment variables */
1166    if (dc->nOptions & SSL_OPT_STDENVVARS) {
1167        modssl_var_extract_dns(env, sslconn->ssl, r->pool);
1168
1169        for (i = 0; ssl_hook_Fixup_vars[i]; i++) {
1170            var = (char *)ssl_hook_Fixup_vars[i];
1171            val = ssl_var_lookup(r->pool, r->server, r->connection, r, var);
1172            if (!strIsEmpty(val)) {
1173                apr_table_setn(env, var, val);
1174            }
1175        }
1176    }
1177
1178    /*
1179     * On-demand bloat up the SSI/CGI environment with certificate data
1180     */
1181    if (dc->nOptions & SSL_OPT_EXPORTCERTDATA) {
1182        val = ssl_var_lookup(r->pool, r->server, r->connection,
1183                             r, "SSL_SERVER_CERT");
1184
1185        apr_table_setn(env, "SSL_SERVER_CERT", val);
1186
1187        val = ssl_var_lookup(r->pool, r->server, r->connection,
1188                             r, "SSL_CLIENT_CERT");
1189
1190        apr_table_setn(env, "SSL_CLIENT_CERT", val);
1191
1192        if ((peer_certs = (STACK_OF(X509) *)SSL_get_peer_cert_chain(ssl))) {
1193            for (i = 0; i < sk_X509_num(peer_certs); i++) {
1194                var = apr_psprintf(r->pool, "SSL_CLIENT_CERT_CHAIN_%d", i);
1195                val = ssl_var_lookup(r->pool, r->server, r->connection,
1196                                     r, var);
1197                if (val) {
1198                    apr_table_setn(env, var, val);
1199                }
1200            }
1201        }
1202    }
1203
1204
1205#ifdef SSL_get_secure_renegotiation_support
1206    apr_table_setn(r->notes, "ssl-secure-reneg",
1207                   SSL_get_secure_renegotiation_support(ssl) ? "1" : "0");
1208#endif
1209
1210    return DECLINED;
1211}
1212
1213/*  _________________________________________________________________
1214**
1215**  Authz providers for use with mod_authz_core
1216**  _________________________________________________________________
1217*/
1218
1219static authz_status ssl_authz_require_ssl_check(request_rec *r,
1220                                                const char *require_line,
1221                                                const void *parsed)
1222{
1223    SSLConnRec *sslconn = myConnConfig(r->connection);
1224    SSL *ssl = sslconn ? sslconn->ssl : NULL;
1225
1226    if (ssl)
1227        return AUTHZ_GRANTED;
1228    else
1229        return AUTHZ_DENIED;
1230}
1231
1232static const char *ssl_authz_require_ssl_parse(cmd_parms *cmd,
1233                                               const char *require_line,
1234                                               const void **parsed)
1235{
1236    if (require_line && require_line[0])
1237        return "'Require ssl' does not take arguments";
1238
1239    return NULL;
1240}
1241
1242const authz_provider ssl_authz_provider_require_ssl =
1243{
1244    &ssl_authz_require_ssl_check,
1245    &ssl_authz_require_ssl_parse,
1246};
1247
1248static authz_status ssl_authz_verify_client_check(request_rec *r,
1249                                                  const char *require_line,
1250                                                  const void *parsed)
1251{
1252    SSLConnRec *sslconn = myConnConfig(r->connection);
1253    SSL *ssl = sslconn ? sslconn->ssl : NULL;
1254
1255    if (!ssl)
1256        return AUTHZ_DENIED;
1257
1258    if (sslconn->verify_error == NULL &&
1259        sslconn->verify_info == NULL &&
1260        SSL_get_verify_result(ssl) == X509_V_OK)
1261    {
1262        X509 *xs = SSL_get_peer_certificate(ssl);
1263
1264        if (xs) {
1265            X509_free(xs);
1266            return AUTHZ_GRANTED;
1267        }
1268        else {
1269            X509_free(xs);
1270        }
1271    }
1272
1273    return AUTHZ_DENIED;
1274}
1275
1276static const char *ssl_authz_verify_client_parse(cmd_parms *cmd,
1277                                                 const char *require_line,
1278                                                 const void **parsed)
1279{
1280    if (require_line && require_line[0])
1281        return "'Require ssl-verify-client' does not take arguments";
1282
1283    return NULL;
1284}
1285
1286const authz_provider ssl_authz_provider_verify_client =
1287{
1288    &ssl_authz_verify_client_check,
1289    &ssl_authz_verify_client_parse,
1290};
1291
1292
1293
1294/*  _________________________________________________________________
1295**
1296**  OpenSSL Callback Functions
1297**  _________________________________________________________________
1298*/
1299
1300/*
1301 * Grab well-defined DH parameters from OpenSSL, see <openssl/bn.h>
1302 * (get_rfc*) for all available primes.
1303 */
1304#define make_get_dh(rfc,size,gen) \
1305static DH *get_dh##size(void) \
1306{ \
1307    DH *dh; \
1308    if (!(dh = DH_new())) { \
1309        return NULL; \
1310    } \
1311    dh->p = get_##rfc##_prime_##size(NULL); \
1312    BN_dec2bn(&dh->g, #gen); \
1313    if (!dh->p || !dh->g) { \
1314        DH_free(dh); \
1315        return NULL; \
1316    } \
1317    return dh; \
1318}
1319
1320/*
1321 * Prepare DH parameters from 1024 to 4096 bits, in 1024-bit increments
1322 */
1323make_get_dh(rfc2409, 1024, 2)
1324make_get_dh(rfc3526, 2048, 2)
1325make_get_dh(rfc3526, 3072, 2)
1326make_get_dh(rfc3526, 4096, 2)
1327
1328/*
1329 * Hand out standard DH parameters, based on the authentication strength
1330 */
1331DH *ssl_callback_TmpDH(SSL *ssl, int export, int keylen)
1332{
1333    conn_rec *c = (conn_rec *)SSL_get_app_data(ssl);
1334    EVP_PKEY *pkey = SSL_get_privatekey(ssl);
1335    int type = pkey ? EVP_PKEY_type(pkey->type) : EVP_PKEY_NONE;
1336
1337    /*
1338     * OpenSSL will call us with either keylen == 512 or keylen == 1024
1339     * (see the definition of SSL_EXPORT_PKEYLENGTH in ssl_locl.h).
1340     * Adjust the DH parameter length according to the size of the
1341     * RSA/DSA private key used for the current connection, and always
1342     * use at least 1024-bit parameters.
1343     * Note: This may cause interoperability issues with implementations
1344     * which limit their DH support to 1024 bit - e.g. Java 7 and earlier.
1345     * In this case, SSLCertificateFile can be used to specify fixed
1346     * 1024-bit DH parameters (with the effect that OpenSSL skips this
1347     * callback).
1348     */
1349    if ((type == EVP_PKEY_RSA) || (type == EVP_PKEY_DSA)) {
1350        keylen = EVP_PKEY_bits(pkey);
1351    }
1352
1353    ap_log_cerror(APLOG_MARK, APLOG_TRACE2, 0, c,
1354                  "handing out built-in DH parameters for %d-bit authenticated connection", keylen);
1355
1356    if (keylen >= 4096)
1357        return get_dh4096();
1358    else if (keylen >= 3072)
1359        return get_dh3072();
1360    else if (keylen >= 2048)
1361        return get_dh2048();
1362    else
1363        return get_dh1024();
1364}
1365
1366/*
1367 * This OpenSSL callback function is called when OpenSSL
1368 * does client authentication and verifies the certificate chain.
1369 */
1370int ssl_callback_SSLVerify(int ok, X509_STORE_CTX *ctx)
1371{
1372    /* Get Apache context back through OpenSSL context */
1373    SSL *ssl = X509_STORE_CTX_get_ex_data(ctx,
1374                                          SSL_get_ex_data_X509_STORE_CTX_idx());
1375    conn_rec *conn      = (conn_rec *)SSL_get_app_data(ssl);
1376    request_rec *r      = (request_rec *)SSL_get_app_data2(ssl);
1377    server_rec *s       = r ? r->server : mySrvFromConn(conn);
1378
1379    SSLSrvConfigRec *sc = mySrvConfig(s);
1380    SSLDirConfigRec *dc = r ? myDirConfig(r) : NULL;
1381    SSLConnRec *sslconn = myConnConfig(conn);
1382    modssl_ctx_t *mctx  = myCtxConfig(sslconn, sc);
1383
1384    /* Get verify ingredients */
1385    int errnum   = X509_STORE_CTX_get_error(ctx);
1386    int errdepth = X509_STORE_CTX_get_error_depth(ctx);
1387    int depth, verify;
1388
1389    /*
1390     * Log verification information
1391     */
1392    ssl_log_cxerror(SSLLOG_MARK, APLOG_DEBUG, 0, conn,
1393                    X509_STORE_CTX_get_current_cert(ctx), APLOGNO(02275)
1394                    "Certificate Verification, depth %d, "
1395                    "CRL checking mode: %s", errdepth,
1396                    mctx->crl_check_mode == SSL_CRLCHECK_CHAIN ?
1397                    "chain" : (mctx->crl_check_mode == SSL_CRLCHECK_LEAF ?
1398                               "leaf" : "none"));
1399
1400    /*
1401     * Check for optionally acceptable non-verifiable issuer situation
1402     */
1403    if (dc && (dc->nVerifyClient != SSL_CVERIFY_UNSET)) {
1404        verify = dc->nVerifyClient;
1405    }
1406    else {
1407        verify = mctx->auth.verify_mode;
1408    }
1409
1410    if (verify == SSL_CVERIFY_NONE) {
1411        /*
1412         * SSLProxyVerify is either not configured or set to "none".
1413         * (this callback doesn't happen in the server context if SSLVerify
1414         *  is not configured or set to "none")
1415         */
1416        return TRUE;
1417    }
1418
1419    if (ssl_verify_error_is_optional(errnum) &&
1420        (verify == SSL_CVERIFY_OPTIONAL_NO_CA))
1421    {
1422        ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, conn, APLOGNO(02037)
1423                      "Certificate Verification: Verifiable Issuer is "
1424                      "configured as optional, therefore we're accepting "
1425                      "the certificate");
1426
1427        sslconn->verify_info = "GENEROUS";
1428        ok = TRUE;
1429    }
1430
1431    /*
1432     * Expired certificates vs. "expired" CRLs: by default, OpenSSL
1433     * turns X509_V_ERR_CRL_HAS_EXPIRED into a "certificate_expired(45)"
1434     * SSL alert, but that's not really the message we should convey to the
1435     * peer (at the very least, it's confusing, and in many cases, it's also
1436     * inaccurate, as the certificate itself may very well not have expired
1437     * yet). We set the X509_STORE_CTX error to something which OpenSSL's
1438     * s3_both.c:ssl_verify_alarm_type() maps to SSL_AD_CERTIFICATE_UNKNOWN,
1439     * i.e. the peer will receive a "certificate_unknown(46)" alert.
1440     * We do not touch errnum, though, so that later on we will still log
1441     * the "real" error, as returned by OpenSSL.
1442     */
1443    if (!ok && errnum == X509_V_ERR_CRL_HAS_EXPIRED) {
1444        X509_STORE_CTX_set_error(ctx, -1);
1445    }
1446
1447#ifndef OPENSSL_NO_OCSP
1448    /*
1449     * Perform OCSP-based revocation checks
1450     */
1451    if (ok && sc->server->ocsp_enabled) {
1452        /* If there was an optional verification error, it's not
1453         * possible to perform OCSP validation since the issuer may be
1454         * missing/untrusted.  Fail in that case. */
1455        if (ssl_verify_error_is_optional(errnum)) {
1456            X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION);
1457            errnum = X509_V_ERR_APPLICATION_VERIFICATION;
1458            ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, conn, APLOGNO(02038)
1459                          "cannot perform OCSP validation for cert "
1460                          "if issuer has not been verified "
1461                          "(optional_no_ca configured)");
1462            ok = FALSE;
1463        } else {
1464            ok = modssl_verify_ocsp(ctx, sc, s, conn, conn->pool);
1465            if (!ok) {
1466                errnum = X509_STORE_CTX_get_error(ctx);
1467            }
1468        }
1469    }
1470#endif
1471
1472    /*
1473     * If we already know it's not ok, log the real reason
1474     */
1475    if (!ok) {
1476        if (APLOGcinfo(conn)) {
1477            ssl_log_cxerror(SSLLOG_MARK, APLOG_INFO, 0, conn,
1478                            X509_STORE_CTX_get_current_cert(ctx), APLOGNO(02276)
1479                            "Certificate Verification: Error (%d): %s",
1480                            errnum, X509_verify_cert_error_string(errnum));
1481        } else {
1482            ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, conn, APLOGNO(02039)
1483                          "Certificate Verification: Error (%d): %s",
1484                          errnum, X509_verify_cert_error_string(errnum));
1485        }
1486
1487        if (sslconn->client_cert) {
1488            X509_free(sslconn->client_cert);
1489            sslconn->client_cert = NULL;
1490        }
1491        sslconn->client_dn = NULL;
1492        sslconn->verify_error = X509_verify_cert_error_string(errnum);
1493    }
1494
1495    /*
1496     * Finally check the depth of the certificate verification
1497     */
1498    if (dc && (dc->nVerifyDepth != UNSET)) {
1499        depth = dc->nVerifyDepth;
1500    }
1501    else {
1502        depth = mctx->auth.verify_depth;
1503    }
1504
1505    if (errdepth > depth) {
1506        ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, conn, APLOGNO(02040)
1507                      "Certificate Verification: Certificate Chain too long "
1508                      "(chain has %d certificates, but maximum allowed are "
1509                      "only %d)",
1510                      errdepth, depth);
1511
1512        errnum = X509_V_ERR_CERT_CHAIN_TOO_LONG;
1513        sslconn->verify_error = X509_verify_cert_error_string(errnum);
1514
1515        ok = FALSE;
1516    }
1517
1518    /*
1519     * And finally signal OpenSSL the (perhaps changed) state
1520     */
1521    return ok;
1522}
1523
1524#define SSLPROXY_CERT_CB_LOG_FMT \
1525   "Proxy client certificate callback: (%s) "
1526
1527static void modssl_proxy_info_log(conn_rec *c,
1528                                  X509_INFO *info,
1529                                  const char *msg)
1530{
1531    ssl_log_cxerror(SSLLOG_MARK, APLOG_DEBUG, 0, c, info->x509, APLOGNO(02277)
1532                    SSLPROXY_CERT_CB_LOG_FMT "%s, sending",
1533                    (mySrvConfigFromConn(c))->vhost_id, msg);
1534}
1535
1536/*
1537 * caller will decrement the cert and key reference
1538 * so we need to increment here to prevent them from
1539 * being freed.
1540 */
1541#define modssl_set_cert_info(info, cert, pkey) \
1542    *cert = info->x509; \
1543    CRYPTO_add(&(*cert)->references, +1, CRYPTO_LOCK_X509); \
1544    *pkey = info->x_pkey->dec_pkey; \
1545    CRYPTO_add(&(*pkey)->references, +1, CRYPTO_LOCK_X509_PKEY)
1546
1547int ssl_callback_proxy_cert(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
1548{
1549    conn_rec *c = (conn_rec *)SSL_get_app_data(ssl);
1550    server_rec *s = mySrvFromConn(c);
1551    SSLSrvConfigRec *sc = mySrvConfig(s);
1552    X509_NAME *ca_name, *issuer, *ca_issuer;
1553    X509_INFO *info;
1554    X509 *ca_cert;
1555    STACK_OF(X509_NAME) *ca_list;
1556    STACK_OF(X509_INFO) *certs = sc->proxy->pkp->certs;
1557    STACK_OF(X509) *ca_certs;
1558    STACK_OF(X509) **ca_cert_chains;
1559    int i, j, k;
1560
1561    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02267)
1562                 SSLPROXY_CERT_CB_LOG_FMT "entered",
1563                 sc->vhost_id);
1564
1565    if (!certs || (sk_X509_INFO_num(certs) <= 0)) {
1566        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(02268)
1567                     SSLPROXY_CERT_CB_LOG_FMT
1568                     "downstream server wanted client certificate "
1569                     "but none are configured", sc->vhost_id);
1570        return FALSE;
1571    }
1572
1573    ca_list = SSL_get_client_CA_list(ssl);
1574
1575    if (!ca_list || (sk_X509_NAME_num(ca_list) <= 0)) {
1576        /*
1577         * downstream server didn't send us a list of acceptable CA certs,
1578         * so we send the first client cert in the list.
1579         */
1580        info = sk_X509_INFO_value(certs, 0);
1581
1582        modssl_proxy_info_log(c, info, APLOGNO(02278) "no acceptable CA list");
1583
1584        modssl_set_cert_info(info, x509, pkey);
1585
1586        return TRUE;
1587    }
1588
1589    ca_cert_chains = sc->proxy->pkp->ca_certs;
1590    for (i = 0; i < sk_X509_NAME_num(ca_list); i++) {
1591        ca_name = sk_X509_NAME_value(ca_list, i);
1592
1593        for (j = 0; j < sk_X509_INFO_num(certs); j++) {
1594            info = sk_X509_INFO_value(certs, j);
1595            issuer = X509_get_issuer_name(info->x509);
1596
1597            /* Search certs (by issuer name) one by one*/
1598            if (X509_NAME_cmp(issuer, ca_name) == 0) {
1599                modssl_proxy_info_log(c, info, APLOGNO(02279)
1600                                      "found acceptable cert");
1601
1602                modssl_set_cert_info(info, x509, pkey);
1603
1604                return TRUE;
1605            }
1606
1607            if (ca_cert_chains) {
1608                /*
1609                 * Failed to find direct issuer - search intermediates
1610                 * (by issuer name), if provided.
1611                 */
1612                ca_certs = ca_cert_chains[j];
1613                for (k = 0; k < sk_X509_num(ca_certs); k++) {
1614                    ca_cert = sk_X509_value(ca_certs, k);
1615                    ca_issuer = X509_get_issuer_name(ca_cert);
1616
1617                    if(X509_NAME_cmp(ca_issuer, ca_name) == 0 ) {
1618                        modssl_proxy_info_log(c, info, APLOGNO(02280)
1619                                              "found acceptable cert by intermediate CA");
1620
1621                        modssl_set_cert_info(info, x509, pkey);
1622
1623                        return TRUE;
1624                    }
1625                } /* end loop through chained certs */
1626            }
1627        } /* end loop through available certs */
1628    }
1629
1630    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02269)
1631                 SSLPROXY_CERT_CB_LOG_FMT
1632                 "no client certificate found!?", sc->vhost_id);
1633
1634    return FALSE;
1635}
1636
1637static void ssl_session_log(server_rec *s,
1638                            const char *request,
1639                            unsigned char *id,
1640                            unsigned int idlen,
1641                            const char *status,
1642                            const char *result,
1643                            long timeout)
1644{
1645    char buf[SSL_SESSION_ID_STRING_LEN];
1646    char timeout_str[56] = {'\0'};
1647
1648    if (!APLOGdebug(s)) {
1649        return;
1650    }
1651
1652    if (timeout) {
1653        apr_snprintf(timeout_str, sizeof(timeout_str),
1654                     "timeout=%lds ", timeout);
1655    }
1656
1657    ap_log_error(APLOG_MARK, APLOG_TRACE2, 0, s,
1658                 "Inter-Process Session Cache: "
1659                 "request=%s status=%s id=%s %s(session %s)",
1660                 request, status,
1661                 SSL_SESSION_id2sz(id, idlen, buf, sizeof(buf)),
1662                 timeout_str, result);
1663}
1664
1665/*
1666 *  This callback function is executed by OpenSSL whenever a new SSL_SESSION is
1667 *  added to the internal OpenSSL session cache. We use this hook to spread the
1668 *  SSL_SESSION also to the inter-process disk-cache to make share it with our
1669 *  other Apache pre-forked server processes.
1670 */
1671int ssl_callback_NewSessionCacheEntry(SSL *ssl, SSL_SESSION *session)
1672{
1673    /* Get Apache context back through OpenSSL context */
1674    conn_rec *conn      = (conn_rec *)SSL_get_app_data(ssl);
1675    server_rec *s       = mySrvFromConn(conn);
1676    SSLSrvConfigRec *sc = mySrvConfig(s);
1677    long timeout        = sc->session_cache_timeout;
1678    BOOL rc;
1679    unsigned char *id;
1680    unsigned int idlen;
1681
1682    /*
1683     * Set the timeout also for the internal OpenSSL cache, because this way
1684     * our inter-process cache is consulted only when it's really necessary.
1685     */
1686    SSL_set_timeout(session, timeout);
1687
1688    /*
1689     * Store the SSL_SESSION in the inter-process cache with the
1690     * same expire time, so it expires automatically there, too.
1691     */
1692#ifdef OPENSSL_NO_SSL_INTERN
1693    id = (unsigned char *)SSL_SESSION_get_id(session, &idlen);
1694#else
1695    id = session->session_id;
1696    idlen = session->session_id_length;
1697#endif
1698
1699    rc = ssl_scache_store(s, id, idlen,
1700                          apr_time_from_sec(SSL_SESSION_get_time(session)
1701                                          + timeout),
1702                          session, conn->pool);
1703
1704    ssl_session_log(s, "SET", id, idlen,
1705                    rc == TRUE ? "OK" : "BAD",
1706                    "caching", timeout);
1707
1708    /*
1709     * return 0 which means to OpenSSL that the session is still
1710     * valid and was not freed by us with SSL_SESSION_free().
1711     */
1712    return 0;
1713}
1714
1715/*
1716 *  This callback function is executed by OpenSSL whenever a
1717 *  SSL_SESSION is looked up in the internal OpenSSL cache and it
1718 *  was not found. We use this to lookup the SSL_SESSION in the
1719 *  inter-process disk-cache where it was perhaps stored by one
1720 *  of our other Apache pre-forked server processes.
1721 */
1722SSL_SESSION *ssl_callback_GetSessionCacheEntry(SSL *ssl,
1723                                               unsigned char *id,
1724                                               int idlen, int *do_copy)
1725{
1726    /* Get Apache context back through OpenSSL context */
1727    conn_rec *conn = (conn_rec *)SSL_get_app_data(ssl);
1728    server_rec *s  = mySrvFromConn(conn);
1729    SSL_SESSION *session;
1730
1731    /*
1732     * Try to retrieve the SSL_SESSION from the inter-process cache
1733     */
1734    session = ssl_scache_retrieve(s, id, idlen, conn->pool);
1735
1736    ssl_session_log(s, "GET", id, idlen,
1737                    session ? "FOUND" : "MISSED",
1738                    session ? "reuse" : "renewal", 0);
1739
1740    /*
1741     * Return NULL or the retrieved SSL_SESSION. But indicate (by
1742     * setting do_copy to 0) that the reference count on the
1743     * SSL_SESSION should not be incremented by the SSL library,
1744     * because we will no longer hold a reference to it ourself.
1745     */
1746    *do_copy = 0;
1747
1748    return session;
1749}
1750
1751/*
1752 *  This callback function is executed by OpenSSL whenever a
1753 *  SSL_SESSION is removed from the the internal OpenSSL cache.
1754 *  We use this to remove the SSL_SESSION in the inter-process
1755 *  disk-cache, too.
1756 */
1757void ssl_callback_DelSessionCacheEntry(SSL_CTX *ctx,
1758                                       SSL_SESSION *session)
1759{
1760    server_rec *s;
1761    SSLSrvConfigRec *sc;
1762    unsigned char *id;
1763    unsigned int idlen;
1764
1765    /*
1766     * Get Apache context back through OpenSSL context
1767     */
1768    if (!(s = (server_rec *)SSL_CTX_get_app_data(ctx))) {
1769        return; /* on server shutdown Apache is already gone */
1770    }
1771
1772    sc = mySrvConfig(s);
1773
1774    /*
1775     * Remove the SSL_SESSION from the inter-process cache
1776     */
1777#ifdef OPENSSL_NO_SSL_INTERN
1778    id = (unsigned char *)SSL_SESSION_get_id(session, &idlen);
1779#else
1780    id = session->session_id;
1781    idlen = session->session_id_length;
1782#endif
1783
1784    /* TODO: Do we need a temp pool here, or are we always shutting down? */
1785    ssl_scache_remove(s, id, idlen, sc->mc->pPool);
1786
1787    ssl_session_log(s, "REM", id, idlen,
1788                    "OK", "dead", 0);
1789
1790    return;
1791}
1792
1793/* Dump debugginfo trace to the log file. */
1794static void log_tracing_state(const SSL *ssl, conn_rec *c,
1795                              server_rec *s, int where, int rc)
1796{
1797    /*
1798     * create the various trace messages
1799     */
1800    if (where & SSL_CB_HANDSHAKE_START) {
1801        ap_log_cerror(APLOG_MARK, APLOG_TRACE3, 0, c,
1802                      "%s: Handshake: start", SSL_LIBRARY_NAME);
1803    }
1804    else if (where & SSL_CB_HANDSHAKE_DONE) {
1805        ap_log_cerror(APLOG_MARK, APLOG_TRACE3, 0, c,
1806                      "%s: Handshake: done", SSL_LIBRARY_NAME);
1807    }
1808    else if (where & SSL_CB_LOOP) {
1809        ap_log_cerror(APLOG_MARK, APLOG_TRACE3, 0, c,
1810                      "%s: Loop: %s",
1811                      SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1812    }
1813    else if (where & SSL_CB_READ) {
1814        ap_log_cerror(APLOG_MARK, APLOG_TRACE3, 0, c,
1815                      "%s: Read: %s",
1816                      SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1817    }
1818    else if (where & SSL_CB_WRITE) {
1819        ap_log_cerror(APLOG_MARK, APLOG_TRACE3, 0, c,
1820                      "%s: Write: %s",
1821                      SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1822    }
1823    else if (where & SSL_CB_ALERT) {
1824        char *str = (where & SSL_CB_READ) ? "read" : "write";
1825        ap_log_cerror(APLOG_MARK, APLOG_TRACE3, 0, c,
1826                      "%s: Alert: %s:%s:%s",
1827                      SSL_LIBRARY_NAME, str,
1828                      SSL_alert_type_string_long(rc),
1829                      SSL_alert_desc_string_long(rc));
1830    }
1831    else if (where & SSL_CB_EXIT) {
1832        if (rc == 0) {
1833            ap_log_cerror(APLOG_MARK, APLOG_TRACE3, 0, c,
1834                          "%s: Exit: failed in %s",
1835                          SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1836        }
1837        else if (rc < 0) {
1838            ap_log_cerror(APLOG_MARK, APLOG_TRACE3, 0, c,
1839                          "%s: Exit: error in %s",
1840                          SSL_LIBRARY_NAME, SSL_state_string_long(ssl));
1841        }
1842    }
1843
1844    /*
1845     * Because SSL renegotiations can happen at any time (not only after
1846     * SSL_accept()), the best way to log the current connection details is
1847     * right after a finished handshake.
1848     */
1849    if (where & SSL_CB_HANDSHAKE_DONE) {
1850        ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(02041)
1851                      "Protocol: %s, Cipher: %s (%s/%s bits)",
1852                      ssl_var_lookup(NULL, s, c, NULL, "SSL_PROTOCOL"),
1853                      ssl_var_lookup(NULL, s, c, NULL, "SSL_CIPHER"),
1854                      ssl_var_lookup(NULL, s, c, NULL, "SSL_CIPHER_USEKEYSIZE"),
1855                      ssl_var_lookup(NULL, s, c, NULL, "SSL_CIPHER_ALGKEYSIZE"));
1856    }
1857}
1858
1859/*
1860 * This callback function is executed while OpenSSL processes the SSL
1861 * handshake and does SSL record layer stuff.  It's used to trap
1862 * client-initiated renegotiations, and for dumping everything to the
1863 * log.
1864 */
1865void ssl_callback_Info(const SSL *ssl, int where, int rc)
1866{
1867    conn_rec *c;
1868    server_rec *s;
1869    SSLConnRec *scr;
1870
1871    /* Retrieve the conn_rec and the associated SSLConnRec. */
1872    if ((c = (conn_rec *)SSL_get_app_data((SSL *)ssl)) == NULL) {
1873        return;
1874    }
1875
1876    if ((scr = myConnConfig(c)) == NULL) {
1877        return;
1878    }
1879
1880    /* If the reneg state is to reject renegotiations, check the SSL
1881     * state machine and move to ABORT if a Client Hello is being
1882     * read. */
1883    if ((where & SSL_CB_ACCEPT_LOOP) && scr->reneg_state == RENEG_REJECT) {
1884        int state = SSL_get_state((SSL *)ssl);
1885
1886        if (state == SSL3_ST_SR_CLNT_HELLO_A
1887            || state == SSL23_ST_SR_CLNT_HELLO_A) {
1888            scr->reneg_state = RENEG_ABORT;
1889            ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c, APLOGNO(02042)
1890                          "rejecting client initiated renegotiation");
1891        }
1892    }
1893    /* If the first handshake is complete, change state to reject any
1894     * subsequent client-initated renegotiation. */
1895    else if ((where & SSL_CB_HANDSHAKE_DONE) && scr->reneg_state == RENEG_INIT) {
1896        scr->reneg_state = RENEG_REJECT;
1897    }
1898
1899    s = mySrvFromConn(c);
1900    if (s && APLOGdebug(s)) {
1901        log_tracing_state(ssl, c, s, where, rc);
1902    }
1903}
1904
1905#ifdef HAVE_TLSEXT
1906/*
1907 * This callback function is executed when OpenSSL encounters an extended
1908 * client hello with a server name indication extension ("SNI", cf. RFC 4366).
1909 */
1910int ssl_callback_ServerNameIndication(SSL *ssl, int *al, modssl_ctx_t *mctx)
1911{
1912    const char *servername =
1913                SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1914
1915    if (servername) {
1916        conn_rec *c = (conn_rec *)SSL_get_app_data(ssl);
1917        if (c) {
1918            if (ap_vhost_iterate_given_conn(c, ssl_find_vhost,
1919                                            (void *)servername)) {
1920                ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(02043)
1921                              "SSL virtual host for servername %s found",
1922                              servername);
1923                return SSL_TLSEXT_ERR_OK;
1924            }
1925            else {
1926                ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(02044)
1927                              "No matching SSL virtual host for servername "
1928                              "%s found (using default/first virtual host)",
1929                              servername);
1930                return SSL_TLSEXT_ERR_ALERT_WARNING;
1931            }
1932        }
1933    }
1934
1935    return SSL_TLSEXT_ERR_NOACK;
1936}
1937
1938/*
1939 * Find a (name-based) SSL virtual host where either the ServerName
1940 * or one of the ServerAliases matches the supplied name (to be used
1941 * with ap_vhost_iterate_given_conn())
1942 */
1943static int ssl_find_vhost(void *servername, conn_rec *c, server_rec *s)
1944{
1945    SSLSrvConfigRec *sc;
1946    SSL *ssl;
1947    BOOL found = FALSE;
1948    apr_array_header_t *names;
1949    int i;
1950    SSLConnRec *sslcon;
1951
1952    /* check ServerName */
1953    if (!strcasecmp(servername, s->server_hostname)) {
1954        found = TRUE;
1955    }
1956
1957    /*
1958     * if not matched yet, check ServerAlias entries
1959     * (adapted from vhost.c:matches_aliases())
1960     */
1961    if (!found) {
1962        names = s->names;
1963        if (names) {
1964            char **name = (char **)names->elts;
1965            for (i = 0; i < names->nelts; ++i) {
1966                if (!name[i])
1967                    continue;
1968                if (!strcasecmp(servername, name[i])) {
1969                    found = TRUE;
1970                    break;
1971                }
1972            }
1973        }
1974    }
1975
1976    /* if still no match, check ServerAlias entries with wildcards */
1977    if (!found) {
1978        names = s->wild_names;
1979        if (names) {
1980            char **name = (char **)names->elts;
1981            for (i = 0; i < names->nelts; ++i) {
1982                if (!name[i])
1983                    continue;
1984                if (!ap_strcasecmp_match(servername, name[i])) {
1985                    found = TRUE;
1986                    break;
1987                }
1988            }
1989        }
1990    }
1991
1992    /* set SSL_CTX (if matched) */
1993    sslcon = myConnConfig(c);
1994    if (found && (ssl = sslcon->ssl) &&
1995        (sc = mySrvConfig(s))) {
1996        SSL_CTX *ctx = SSL_set_SSL_CTX(ssl, sc->server->ssl_ctx);
1997        /*
1998         * SSL_set_SSL_CTX() only deals with the server cert,
1999         * so we need to duplicate a few additional settings
2000         * from the ctx by hand
2001         */
2002        SSL_set_options(ssl, SSL_CTX_get_options(ctx));
2003        if ((SSL_get_verify_mode(ssl) == SSL_VERIFY_NONE) ||
2004            (SSL_num_renegotiations(ssl) == 0)) {
2005           /*
2006            * Only initialize the verification settings from the ctx
2007            * if they are not yet set, or if we're called when a new
2008            * SSL connection is set up (num_renegotiations == 0).
2009            * Otherwise, we would possibly reset a per-directory
2010            * configuration which was put into effect by ssl_hook_Access.
2011            */
2012            SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx),
2013                           SSL_CTX_get_verify_callback(ctx));
2014        }
2015
2016        /*
2017         * Adjust the session id context. ssl_init_ssl_connection()
2018         * always picks the configuration of the first vhost when
2019         * calling SSL_new(), but we want to tie the session to the
2020         * vhost we have just switched to. Again, we have to make sure
2021         * that we're not overwriting a session id context which was
2022         * possibly set in ssl_hook_Access(), before triggering
2023         * a renegotation.
2024         */
2025        if (SSL_num_renegotiations(ssl) == 0) {
2026            unsigned char *sid_ctx =
2027                (unsigned char *)ap_md5_binary(c->pool,
2028                                               (unsigned char *)sc->vhost_id,
2029                                               sc->vhost_id_len);
2030            SSL_set_session_id_context(ssl, sid_ctx, APR_MD5_DIGESTSIZE*2);
2031        }
2032
2033        /*
2034         * Save the found server into our SSLConnRec for later
2035         * retrieval
2036         */
2037        sslcon->server = s;
2038
2039        /*
2040         * There is one special filter callback, which is set
2041         * very early depending on the base_server's log level.
2042         * If this is not the first vhost we're now selecting
2043         * (and the first vhost doesn't use APLOG_TRACE4), then
2044         * we need to set that callback here.
2045         */
2046        if (APLOGtrace4(s)) {
2047            BIO_set_callback(SSL_get_rbio(ssl), ssl_io_data_cb);
2048            BIO_set_callback_arg(SSL_get_rbio(ssl), (void *)ssl);
2049        }
2050
2051        return 1;
2052    }
2053
2054    return 0;
2055}
2056#endif /* HAVE_TLSEXT */
2057
2058#ifdef HAVE_TLS_SESSION_TICKETS
2059/*
2060 * This callback function is executed when OpenSSL needs a key for encrypting/
2061 * decrypting a TLS session ticket (RFC 5077) and a ticket key file has been
2062 * configured through SSLSessionTicketKeyFile.
2063 */
2064int ssl_callback_SessionTicket(SSL *ssl,
2065                               unsigned char *keyname,
2066                               unsigned char *iv,
2067                               EVP_CIPHER_CTX *cipher_ctx,
2068                               HMAC_CTX *hctx,
2069                               int mode)
2070{
2071    conn_rec *c = (conn_rec *)SSL_get_app_data(ssl);
2072    server_rec *s = mySrvFromConn(c);
2073    SSLSrvConfigRec *sc = mySrvConfig(s);
2074    SSLConnRec *sslconn = myConnConfig(c);
2075    modssl_ctx_t *mctx = myCtxConfig(sslconn, sc);
2076    modssl_ticket_key_t *ticket_key = mctx->ticket_key;
2077
2078    if (mode == 1) {
2079        /*
2080         * OpenSSL is asking for a key for encrypting a ticket,
2081         * see s3_srvr.c:ssl3_send_newsession_ticket()
2082         */
2083
2084        if (ticket_key == NULL) {
2085            /* should never happen, but better safe than sorry */
2086            return -1;
2087        }
2088
2089        memcpy(keyname, ticket_key->key_name, 16);
2090        RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH);
2091        EVP_EncryptInit_ex(cipher_ctx, EVP_aes_128_cbc(), NULL,
2092                           ticket_key->aes_key, iv);
2093        HMAC_Init_ex(hctx, ticket_key->hmac_secret, 16, tlsext_tick_md(), NULL);
2094
2095        ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(02289)
2096                      "TLS session ticket key for %s successfully set, "
2097                      "creating new session ticket", sc->vhost_id);
2098
2099        return 0;
2100    }
2101    else if (mode == 0) {
2102        /*
2103         * OpenSSL is asking for the decryption key,
2104         * see t1_lib.c:tls_decrypt_ticket()
2105         */
2106
2107        /* check key name */
2108        if (ticket_key == NULL || memcmp(keyname, ticket_key->key_name, 16)) {
2109            return 0;
2110        }
2111
2112        EVP_DecryptInit_ex(cipher_ctx, EVP_aes_128_cbc(), NULL,
2113                           ticket_key->aes_key, iv);
2114        HMAC_Init_ex(hctx, ticket_key->hmac_secret, 16, tlsext_tick_md(), NULL);
2115
2116        ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(02290)
2117                      "TLS session ticket key for %s successfully set, "
2118                      "decrypting existing session ticket", sc->vhost_id);
2119
2120        return 1;
2121    }
2122
2123    /* OpenSSL is not expected to call us with modes other than 1 or 0 */
2124    return -1;
2125}
2126#endif /* HAVE_TLS_SESSION_TICKETS */
2127
2128#ifdef HAVE_SRP
2129
2130int ssl_callback_SRPServerParams(SSL *ssl, int *ad, void *arg)
2131{
2132    modssl_ctx_t *mctx = (modssl_ctx_t *)arg;
2133    char *username = SSL_get_srp_username(ssl);
2134    SRP_user_pwd *u;
2135
2136    if (username == NULL
2137        || (u = SRP_VBASE_get_by_user(mctx->srp_vbase, username)) == NULL) {
2138        *ad = SSL_AD_UNKNOWN_PSK_IDENTITY;
2139        return SSL3_AL_FATAL;
2140    }
2141
2142    if (SSL_set_srp_server_param(ssl, u->N, u->g, u->s, u->v, u->info) < 0) {
2143        *ad = SSL_AD_INTERNAL_ERROR;
2144        return SSL3_AL_FATAL;
2145    }
2146
2147    /* reset all other options */
2148    SSL_set_verify(ssl, SSL_VERIFY_NONE,  ssl_callback_SSLVerify);
2149    return SSL_ERROR_NONE;
2150}
2151
2152#endif /* HAVE_SRP */
2153