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_util_ssl.c
24 *  Additional Utility Functions for OpenSSL
25 */
26
27#include "ssl_private.h"
28
29/*  _________________________________________________________________
30**
31**  Additional High-Level Functions for OpenSSL
32**  _________________________________________________________________
33*/
34
35/* we initialize this index at startup time
36 * and never write to it at request time,
37 * so this static is thread safe.
38 * also note that OpenSSL increments at static variable when
39 * SSL_get_ex_new_index() is called, so we _must_ do this at startup.
40 */
41static int SSL_app_data2_idx = -1;
42
43void SSL_init_app_data2_idx(void)
44{
45    int i;
46
47    if (SSL_app_data2_idx > -1) {
48        return;
49    }
50
51    /* we _do_ need to call this twice */
52    for (i=0; i<=1; i++) {
53        SSL_app_data2_idx =
54            SSL_get_ex_new_index(0,
55                                 "Second Application Data for SSL",
56                                 NULL, NULL, NULL);
57    }
58}
59
60void *SSL_get_app_data2(SSL *ssl)
61{
62    return (void *)SSL_get_ex_data(ssl, SSL_app_data2_idx);
63}
64
65void SSL_set_app_data2(SSL *ssl, void *arg)
66{
67    SSL_set_ex_data(ssl, SSL_app_data2_idx, (char *)arg);
68    return;
69}
70
71/*  _________________________________________________________________
72**
73**  High-Level Private Key Loading
74**  _________________________________________________________________
75*/
76
77EVP_PKEY *SSL_read_PrivateKey(const char* filename, EVP_PKEY **key, pem_password_cb *cb, void *s)
78{
79    EVP_PKEY *rc;
80    BIO *bioS;
81    BIO *bioF;
82
83    /* 1. try PEM (= DER+Base64+headers) */
84    if ((bioS=BIO_new_file(filename, "r")) == NULL)
85        return NULL;
86    rc = PEM_read_bio_PrivateKey(bioS, key, cb, s);
87    BIO_free(bioS);
88
89    if (rc == NULL) {
90        /* 2. try DER+Base64 */
91        if ((bioS = BIO_new_file(filename, "r")) == NULL)
92            return NULL;
93
94        if ((bioF = BIO_new(BIO_f_base64())) == NULL) {
95            BIO_free(bioS);
96            return NULL;
97        }
98        bioS = BIO_push(bioF, bioS);
99        rc = d2i_PrivateKey_bio(bioS, NULL);
100        BIO_free_all(bioS);
101
102        if (rc == NULL) {
103            /* 3. try plain DER */
104            if ((bioS = BIO_new_file(filename, "r")) == NULL)
105                return NULL;
106            rc = d2i_PrivateKey_bio(bioS, NULL);
107            BIO_free(bioS);
108        }
109    }
110    if (rc != NULL && key != NULL) {
111        if (*key != NULL)
112            EVP_PKEY_free(*key);
113        *key = rc;
114    }
115    return rc;
116}
117
118/*  _________________________________________________________________
119**
120**  Smart shutdown
121**  _________________________________________________________________
122*/
123
124int SSL_smart_shutdown(SSL *ssl)
125{
126    int i;
127    int rc;
128
129    /*
130     * Repeat the calls, because SSL_shutdown internally dispatches through a
131     * little state machine. Usually only one or two interation should be
132     * needed, so we restrict the total number of restrictions in order to
133     * avoid process hangs in case the client played bad with the socket
134     * connection and OpenSSL cannot recognize it.
135     */
136    rc = 0;
137    for (i = 0; i < 4 /* max 2x pending + 2x data = 4 */; i++) {
138        if ((rc = SSL_shutdown(ssl)))
139            break;
140    }
141    return rc;
142}
143
144/*  _________________________________________________________________
145**
146**  Certificate Checks
147**  _________________________________________________________________
148*/
149
150/* retrieve basic constraints ingredients */
151BOOL SSL_X509_getBC(X509 *cert, int *ca, int *pathlen)
152{
153    BASIC_CONSTRAINTS *bc;
154    BIGNUM *bn = NULL;
155    char *cp;
156
157    bc = X509_get_ext_d2i(cert, NID_basic_constraints, NULL, NULL);
158    if (bc == NULL)
159        return FALSE;
160    *ca = bc->ca;
161    *pathlen = -1 /* unlimited */;
162    if (bc->pathlen != NULL) {
163        if ((bn = ASN1_INTEGER_to_BN(bc->pathlen, NULL)) == NULL)
164            return FALSE;
165        if ((cp = BN_bn2dec(bn)) == NULL)
166            return FALSE;
167        *pathlen = atoi(cp);
168        free(cp);
169        BN_free(bn);
170    }
171    BASIC_CONSTRAINTS_free(bc);
172    return TRUE;
173}
174
175/* convert a NAME_ENTRY to UTF8 string */
176char *SSL_X509_NAME_ENTRY_to_string(apr_pool_t *p, X509_NAME_ENTRY *xsne)
177{
178    char *result = NULL;
179    BIO* bio;
180    int len;
181
182    if ((bio = BIO_new(BIO_s_mem())) == NULL)
183        return NULL;
184    ASN1_STRING_print_ex(bio, X509_NAME_ENTRY_get_data(xsne),
185                         ASN1_STRFLGS_ESC_CTRL|ASN1_STRFLGS_UTF8_CONVERT);
186    len = BIO_pending(bio);
187    result = apr_palloc(p, len+1);
188    len = BIO_read(bio, result, len);
189    result[len] = NUL;
190    BIO_free(bio);
191    ap_xlate_proto_from_ascii(result, len);
192    return result;
193}
194
195/*
196 * convert an X509_NAME to an RFC 2253 formatted string, optionally truncated
197 * to maxlen characters (specify a maxlen of 0 for no length limit)
198 */
199char *SSL_X509_NAME_to_string(apr_pool_t *p, X509_NAME *dn, int maxlen)
200{
201    char *result = NULL;
202    BIO *bio;
203    int len;
204
205    if ((bio = BIO_new(BIO_s_mem())) == NULL)
206        return NULL;
207    X509_NAME_print_ex(bio, dn, 0, XN_FLAG_RFC2253);
208    len = BIO_pending(bio);
209    if (len > 0) {
210        result = apr_palloc(p, (maxlen > 0) ? maxlen+1 : len+1);
211        if (maxlen > 0 && maxlen < len) {
212            len = BIO_read(bio, result, maxlen);
213            if (maxlen > 2) {
214                /* insert trailing ellipsis if there's enough space */
215                apr_snprintf(result + maxlen - 3, 4, "...");
216            }
217        } else {
218            len = BIO_read(bio, result, len);
219        }
220        result[len] = NUL;
221    }
222    BIO_free(bio);
223
224    return result;
225}
226
227/* return an array of (RFC 6125 coined) DNS-IDs and CN-IDs in a certificate */
228BOOL SSL_X509_getIDs(apr_pool_t *p, X509 *x509, apr_array_header_t **ids)
229{
230    STACK_OF(GENERAL_NAME) *names;
231    BIO *bio;
232    X509_NAME *subj;
233    char **cpp;
234    int i, n;
235
236    if (!x509 || !(*ids = apr_array_make(p, 0, sizeof(char *)))) {
237        *ids = NULL;
238        return FALSE;
239    }
240
241    /* First, the DNS-IDs (dNSName entries in the subjectAltName extension) */
242    if ((names = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL)) &&
243        (bio = BIO_new(BIO_s_mem()))) {
244        GENERAL_NAME *name;
245
246        for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
247            name = sk_GENERAL_NAME_value(names, i);
248            if (name->type == GEN_DNS) {
249                ASN1_STRING_print_ex(bio, name->d.ia5, ASN1_STRFLGS_ESC_CTRL|
250                                     ASN1_STRFLGS_UTF8_CONVERT);
251                n = BIO_pending(bio);
252                if (n > 0) {
253                    cpp = (char **)apr_array_push(*ids);
254                    *cpp = apr_palloc(p, n+1);
255                    n = BIO_read(bio, *cpp, n);
256                    (*cpp)[n] = NUL;
257                }
258            }
259        }
260        BIO_free(bio);
261    }
262
263    if (names)
264        sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
265
266    /* Second, the CN-IDs (commonName attributes in the subject DN) */
267    subj = X509_get_subject_name(x509);
268    i = -1;
269    while ((i = X509_NAME_get_index_by_NID(subj, NID_commonName, i)) != -1) {
270        cpp = (char **)apr_array_push(*ids);
271        *cpp = SSL_X509_NAME_ENTRY_to_string(p, X509_NAME_get_entry(subj, i));
272    }
273
274    return apr_is_empty_array(*ids) ? FALSE : TRUE;
275}
276
277/*
278 * Check if a certificate matches for a particular name, by iterating over its
279 * DNS-IDs and CN-IDs (RFC 6125), optionally with basic wildcard matching.
280 * If server_rec is non-NULL, some (debug/trace) logging is enabled.
281 */
282BOOL SSL_X509_match_name(apr_pool_t *p, X509 *x509, const char *name,
283                         BOOL allow_wildcard, server_rec *s)
284{
285    BOOL matched = FALSE;
286    apr_array_header_t *ids;
287
288    /*
289     * At some day in the future, this might be replaced with X509_check_host()
290     * (available in OpenSSL 1.0.2 and later), but two points should be noted:
291     * 1) wildcard matching in X509_check_host() might yield different
292     *    results (by default, it supports a broader set of patterns, e.g.
293     *    wildcards in non-initial positions);
294     * 2) we lose the option of logging each DNS- and CN-ID (until a match
295     *    is found).
296     */
297
298    if (SSL_X509_getIDs(p, x509, &ids)) {
299        const char *cp;
300        int i;
301        char **id = (char **)ids->elts;
302        BOOL is_wildcard;
303
304        for (i = 0; i < ids->nelts; i++) {
305            if (!id[i])
306                continue;
307
308            /*
309             * Determine if it is a wildcard ID - we're restrictive
310             * in the sense that we require the wildcard character to be
311             * THE left-most label (i.e., the ID must start with "*.")
312             */
313            is_wildcard = (*id[i] == '*' && *(id[i]+1) == '.') ? TRUE : FALSE;
314
315            /*
316             * If the ID includes a wildcard character (and the caller is
317             * allowing wildcards), check if it matches for the left-most
318             * DNS label - i.e., the wildcard character is not allowed
319             * to match a dot. Otherwise, try a simple string compare.
320             */
321            if ((allow_wildcard == TRUE && is_wildcard == TRUE &&
322                 (cp = ap_strchr_c(name, '.')) && !strcasecmp(id[i]+1, cp)) ||
323                !strcasecmp(id[i], name)) {
324                matched = TRUE;
325            }
326
327            if (s) {
328                ap_log_error(APLOG_MARK, APLOG_TRACE3, 0, s,
329                             "[%s] SSL_X509_match_name: expecting name '%s', "
330                             "%smatched by ID '%s'",
331                             (mySrvConfig(s))->vhost_id, name,
332                             matched == TRUE ? "" : "NOT ", id[i]);
333            }
334
335            if (matched == TRUE) {
336                break;
337            }
338        }
339
340    }
341
342    if (s) {
343        ssl_log_xerror(SSLLOG_MARK, APLOG_DEBUG, 0, p, s, x509,
344                       APLOGNO(02412) "[%s] Cert %s for name '%s'",
345                       (mySrvConfig(s))->vhost_id,
346                       matched == TRUE ? "matches" : "does not match",
347                       name);
348    }
349
350    return matched;
351}
352
353/*  _________________________________________________________________
354**
355**  Low-Level CA Certificate Loading
356**  _________________________________________________________________
357*/
358
359BOOL SSL_X509_INFO_load_file(apr_pool_t *ptemp,
360                             STACK_OF(X509_INFO) *sk,
361                             const char *filename)
362{
363    BIO *in;
364
365    if (!(in = BIO_new(BIO_s_file()))) {
366        return FALSE;
367    }
368
369    if (BIO_read_filename(in, filename) <= 0) {
370        BIO_free(in);
371        return FALSE;
372    }
373
374    ERR_clear_error();
375
376    PEM_X509_INFO_read_bio(in, sk, NULL, NULL);
377
378    BIO_free(in);
379
380    return TRUE;
381}
382
383BOOL SSL_X509_INFO_load_path(apr_pool_t *ptemp,
384                             STACK_OF(X509_INFO) *sk,
385                             const char *pathname)
386{
387    /* XXX: this dir read code is exactly the same as that in
388     * ssl_engine_init.c, only the call to handle the fullname is different,
389     * should fold the duplication.
390     */
391    apr_dir_t *dir;
392    apr_finfo_t dirent;
393    apr_int32_t finfo_flags = APR_FINFO_TYPE|APR_FINFO_NAME;
394    const char *fullname;
395    BOOL ok = FALSE;
396
397    if (apr_dir_open(&dir, pathname, ptemp) != APR_SUCCESS) {
398        return FALSE;
399    }
400
401    while ((apr_dir_read(&dirent, finfo_flags, dir)) == APR_SUCCESS) {
402        if (dirent.filetype == APR_DIR) {
403            continue; /* don't try to load directories */
404        }
405
406        fullname = apr_pstrcat(ptemp,
407                               pathname, "/", dirent.name,
408                               NULL);
409
410        if (SSL_X509_INFO_load_file(ptemp, sk, fullname)) {
411            ok = TRUE;
412        }
413    }
414
415    apr_dir_close(dir);
416
417    return ok;
418}
419
420/*  _________________________________________________________________
421**
422**  Custom (EC)DH parameter support
423**  _________________________________________________________________
424*/
425
426DH *ssl_dh_GetParamFromFile(const char *file)
427{
428    DH *dh = NULL;
429    BIO *bio;
430
431    if ((bio = BIO_new_file(file, "r")) == NULL)
432        return NULL;
433    dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
434    BIO_free(bio);
435    return (dh);
436}
437
438#ifdef HAVE_ECC
439EC_GROUP *ssl_ec_GetParamFromFile(const char *file)
440{
441    EC_GROUP *group = NULL;
442    BIO *bio;
443
444    if ((bio = BIO_new_file(file, "r")) == NULL)
445        return NULL;
446    group = PEM_read_bio_ECPKParameters(bio, NULL, NULL, NULL);
447    BIO_free(bio);
448    return (group);
449}
450#endif
451
452/*  _________________________________________________________________
453**
454**  Extra Server Certificate Chain Support
455**  _________________________________________________________________
456*/
457
458/*
459 * Read a file that optionally contains the server certificate in PEM
460 * format, possibly followed by a sequence of CA certificates that
461 * should be sent to the peer in the SSL Certificate message.
462 */
463int SSL_CTX_use_certificate_chain(
464    SSL_CTX *ctx, char *file, int skipfirst, pem_password_cb *cb)
465{
466    BIO *bio;
467    X509 *x509;
468    unsigned long err;
469    int n;
470
471    if ((bio = BIO_new(BIO_s_file_internal())) == NULL)
472        return -1;
473    if (BIO_read_filename(bio, file) <= 0) {
474        BIO_free(bio);
475        return -1;
476    }
477    /* optionally skip a leading server certificate */
478    if (skipfirst) {
479        if ((x509 = PEM_read_bio_X509(bio, NULL, cb, NULL)) == NULL) {
480            BIO_free(bio);
481            return -1;
482        }
483        X509_free(x509);
484    }
485    /* free a perhaps already configured extra chain */
486#ifdef OPENSSL_NO_SSL_INTERN
487    SSL_CTX_clear_extra_chain_certs(ctx);
488#else
489    if (ctx->extra_certs != NULL) {
490        sk_X509_pop_free((STACK_OF(X509) *)ctx->extra_certs, X509_free);
491        ctx->extra_certs = NULL;
492    }
493#endif
494    /* create new extra chain by loading the certs */
495    n = 0;
496    while ((x509 = PEM_read_bio_X509(bio, NULL, cb, NULL)) != NULL) {
497        if (!SSL_CTX_add_extra_chain_cert(ctx, x509)) {
498            X509_free(x509);
499            BIO_free(bio);
500            return -1;
501        }
502        n++;
503    }
504    /* Make sure that only the error is just an EOF */
505    if ((err = ERR_peek_error()) > 0) {
506        if (!(   ERR_GET_LIB(err) == ERR_LIB_PEM
507              && ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
508            BIO_free(bio);
509            return -1;
510        }
511        while (ERR_get_error() > 0) ;
512    }
513    BIO_free(bio);
514    return n;
515}
516
517/*  _________________________________________________________________
518**
519**  Session Stuff
520**  _________________________________________________________________
521*/
522
523char *SSL_SESSION_id2sz(unsigned char *id, int idlen,
524                        char *str, int strsize)
525{
526    if (idlen > SSL_MAX_SSL_SESSION_ID_LENGTH)
527        idlen = SSL_MAX_SSL_SESSION_ID_LENGTH;
528
529    /* We must ensure not to process more than what would fit in the
530     * destination buffer, including terminating NULL */
531    if (idlen > (strsize-1) / 2)
532        idlen = (strsize-1) / 2;
533
534    ap_bin2hex(id, idlen, str);
535
536    return str;
537}
538