]> granicus.if.org Git - apache/blob - modules/ssl/ssl_util_ssl.c
XML updates.
[apache] / modules / ssl / ssl_util_ssl.c
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  */
41 static int app_data2_idx = -1;
42
43 void modssl_init_app_data2_idx(void)
44 {
45     int i;
46
47     if (app_data2_idx > -1) {
48         return;
49     }
50
51     /* we _do_ need to call this twice */
52     for (i = 0; i <= 1; i++) {
53         app_data2_idx =
54             SSL_get_ex_new_index(0,
55                                  "Second Application Data for SSL",
56                                  NULL, NULL, NULL);
57     }
58 }
59
60 void *modssl_get_app_data2(SSL *ssl)
61 {
62     return (void *)SSL_get_ex_data(ssl, app_data2_idx);
63 }
64
65 void modssl_set_app_data2(SSL *ssl, void *arg)
66 {
67     SSL_set_ex_data(ssl, app_data2_idx, (char *)arg);
68     return;
69 }
70
71 /*  _________________________________________________________________
72 **
73 **  High-Level Private Key Loading
74 **  _________________________________________________________________
75 */
76
77 EVP_PKEY *modssl_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 typedef struct {
119     const char *pass;
120     int pass_len;
121 } pass_ctx;
122
123 static int provide_pass(char *buf, int size, int rwflag, void *baton)
124 {
125     pass_ctx *ctx = baton;
126     if (ctx->pass_len > 0) {
127         if (ctx->pass_len < size) {
128             size = (int)ctx->pass_len;
129         }
130         memcpy(buf, ctx->pass, size);
131     }
132     return ctx->pass_len;
133 }
134
135 EVP_PKEY   *modssl_read_encrypted_pkey(const char *filename, EVP_PKEY **key, 
136                                        const char *pass, apr_size_t pass_len)
137 {
138     pass_ctx ctx;
139     
140     ctx.pass = pass;
141     ctx.pass_len = pass_len;
142     return modssl_read_privatekey(filename, key, provide_pass, &ctx);
143 }
144
145 /*  _________________________________________________________________
146 **
147 **  Smart shutdown
148 **  _________________________________________________________________
149 */
150
151 int modssl_smart_shutdown(SSL *ssl)
152 {
153     int i;
154     int rc;
155     int flush;
156
157     /*
158      * Repeat the calls, because SSL_shutdown internally dispatches through a
159      * little state machine. Usually only one or two interation should be
160      * needed, so we restrict the total number of restrictions in order to
161      * avoid process hangs in case the client played bad with the socket
162      * connection and OpenSSL cannot recognize it.
163      */
164     rc = 0;
165     flush = !(SSL_get_shutdown(ssl) & SSL_SENT_SHUTDOWN);
166     for (i = 0; i < 4 /* max 2x pending + 2x data = 4 */; i++) {
167         rc = SSL_shutdown(ssl);
168         if (rc >= 0 && flush && (SSL_get_shutdown(ssl) & SSL_SENT_SHUTDOWN)) {
169             /* Once the close notity is sent through the output filters,
170              * ensure it is flushed through the socket.
171              */
172             if (BIO_flush(SSL_get_wbio(ssl)) <= 0) {
173                 rc = -1;
174                 break;
175             }
176             flush = 0;
177         }
178         if (rc != 0)
179             break;
180     }
181     return rc;
182 }
183
184 /*  _________________________________________________________________
185 **
186 **  Certificate Checks
187 **  _________________________________________________________________
188 */
189
190 /* retrieve basic constraints ingredients */
191 BOOL modssl_X509_getBC(X509 *cert, int *ca, int *pathlen)
192 {
193     BASIC_CONSTRAINTS *bc;
194     BIGNUM *bn = NULL;
195     char *cp;
196
197     bc = X509_get_ext_d2i(cert, NID_basic_constraints, NULL, NULL);
198     if (bc == NULL)
199         return FALSE;
200     *ca = bc->ca;
201     *pathlen = -1 /* unlimited */;
202     if (bc->pathlen != NULL) {
203         if ((bn = ASN1_INTEGER_to_BN(bc->pathlen, NULL)) == NULL) {
204             BASIC_CONSTRAINTS_free(bc);
205             return FALSE;
206         }
207         if ((cp = BN_bn2dec(bn)) == NULL) {
208             BN_free(bn);
209             BASIC_CONSTRAINTS_free(bc);
210             return FALSE;
211         }
212         *pathlen = atoi(cp);
213         OPENSSL_free(cp);
214         BN_free(bn);
215     }
216     BASIC_CONSTRAINTS_free(bc);
217     return TRUE;
218 }
219
220 /* Convert ASN.1 string to a pool-allocated char * string, escaping
221  * control characters.  If raw is zero, convert to UTF-8, otherwise
222  * unchanged from the character set. */
223 static char *asn1_string_convert(apr_pool_t *p, ASN1_STRING *asn1str, int raw)
224 {
225     char *result = NULL;
226     BIO *bio;
227     int len, flags = ASN1_STRFLGS_ESC_CTRL;
228
229     if ((bio = BIO_new(BIO_s_mem())) == NULL)
230         return NULL;
231
232     if (!raw) flags |= ASN1_STRFLGS_UTF8_CONVERT;
233     
234     ASN1_STRING_print_ex(bio, asn1str, flags);
235     len = BIO_pending(bio);
236     if (len > 0) {
237         result = apr_palloc(p, len+1);
238         len = BIO_read(bio, result, len);
239         result[len] = NUL;
240     }
241     BIO_free(bio);
242     return result;
243 }
244
245 #define asn1_string_to_utf8(p, a) asn1_string_convert(p, a, 0)
246
247 /* convert a NAME_ENTRY to UTF8 string */
248 char *modssl_X509_NAME_ENTRY_to_string(apr_pool_t *p, X509_NAME_ENTRY *xsne,
249                                        int raw)
250 {
251     char *result = asn1_string_convert(p, X509_NAME_ENTRY_get_data(xsne), raw);
252     ap_xlate_proto_from_ascii(result, len);
253     return result;
254 }
255
256 /*
257  * convert an X509_NAME to an RFC 2253 formatted string, optionally truncated
258  * to maxlen characters (specify a maxlen of 0 for no length limit)
259  */
260 char *modssl_X509_NAME_to_string(apr_pool_t *p, X509_NAME *dn, int maxlen)
261 {
262     char *result = NULL;
263     BIO *bio;
264     int len;
265
266     if ((bio = BIO_new(BIO_s_mem())) == NULL)
267         return NULL;
268     X509_NAME_print_ex(bio, dn, 0, XN_FLAG_RFC2253);
269     len = BIO_pending(bio);
270     if (len > 0) {
271         result = apr_palloc(p, (maxlen > 0) ? maxlen+1 : len+1);
272         if (maxlen > 0 && maxlen < len) {
273             len = BIO_read(bio, result, maxlen);
274             if (maxlen > 2) {
275                 /* insert trailing ellipsis if there's enough space */
276                 apr_snprintf(result + maxlen - 3, 4, "...");
277             }
278         } else {
279             len = BIO_read(bio, result, len);
280         }
281         result[len] = NUL;
282     }
283     BIO_free(bio);
284
285     return result;
286 }
287
288 static void parse_otherName_value(apr_pool_t *p, ASN1_TYPE *value,
289                                   const char *onf, apr_array_header_t **entries)
290 {
291     const char *str;
292     int nid = onf ? OBJ_txt2nid(onf) : NID_undef;
293
294     if (!value || (nid == NID_undef) || !*entries)
295        return;
296
297     /* 
298      * Currently supported otherName forms (values for "onf"):
299      * "msUPN" (1.3.6.1.4.1.311.20.2.3): Microsoft User Principal Name
300      * "id-on-dnsSRV" (1.3.6.1.5.5.7.8.7): SRVName, as specified in RFC 4985
301      */
302     if ((nid == NID_ms_upn) && (value->type == V_ASN1_UTF8STRING) &&
303         (str = asn1_string_to_utf8(p, value->value.utf8string))) {
304         APR_ARRAY_PUSH(*entries, const char *) = str;
305     } else if (strEQ(onf, "id-on-dnsSRV") &&
306                (value->type == V_ASN1_IA5STRING) &&
307                (str = asn1_string_to_utf8(p, value->value.ia5string))) {
308         APR_ARRAY_PUSH(*entries, const char *) = str;
309     }
310 }
311
312 /* 
313  * Return an array of subjectAltName entries of type "type". If idx is -1,
314  * return all entries of the given type, otherwise return an array consisting
315  * of the n-th occurrence of that type only. Currently supported types:
316  * GEN_EMAIL (rfc822Name)
317  * GEN_DNS (dNSName)
318  * GEN_OTHERNAME (requires the otherName form ["onf"] argument to be supplied,
319  *                see parse_otherName_value for the currently supported forms)
320  */
321 BOOL modssl_X509_getSAN(apr_pool_t *p, X509 *x509, int type, const char *onf,
322                         int idx, apr_array_header_t **entries)
323 {
324     STACK_OF(GENERAL_NAME) *names;
325     int nid = onf ? OBJ_txt2nid(onf) : NID_undef;
326
327     if (!x509 || (type < GEN_OTHERNAME) ||
328         ((type == GEN_OTHERNAME) && (nid == NID_undef)) ||
329         (type > GEN_RID) || (idx < -1) ||
330         !(*entries = apr_array_make(p, 0, sizeof(char *)))) {
331         *entries = NULL;
332         return FALSE;
333     }
334
335     if ((names = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL))) {
336         int i, n = 0;
337         GENERAL_NAME *name;
338         const char *utf8str;
339
340         for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
341             name = sk_GENERAL_NAME_value(names, i);
342
343             if (name->type != type)
344                 continue;
345
346             switch (type) {
347             case GEN_EMAIL:
348             case GEN_DNS:
349                 if (((idx == -1) || (n == idx)) &&
350                     (utf8str = asn1_string_to_utf8(p, name->d.ia5))) {
351                     APR_ARRAY_PUSH(*entries, const char *) = utf8str;
352                 }
353                 n++;
354                 break;
355             case GEN_OTHERNAME:
356                 if (OBJ_obj2nid(name->d.otherName->type_id) == nid) {
357                     if (((idx == -1) || (n == idx))) {
358                         parse_otherName_value(p, name->d.otherName->value,
359                                               onf, entries);
360                     }
361                     n++;
362                 }
363                 break;
364             default:
365                 /*
366                  * Not implemented right now:
367                  * GEN_X400 (x400Address)
368                  * GEN_DIRNAME (directoryName)
369                  * GEN_EDIPARTY (ediPartyName)
370                  * GEN_URI (uniformResourceIdentifier)
371                  * GEN_IPADD (iPAddress)
372                  * GEN_RID (registeredID)
373                  */
374                 break;
375             }
376
377             if ((idx != -1) && (n > idx))
378                break;
379         }
380
381         sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
382     }
383
384     return apr_is_empty_array(*entries) ? FALSE : TRUE;
385 }
386
387 /* return an array of (RFC 6125 coined) DNS-IDs and CN-IDs in a certificate */
388 static BOOL getIDs(apr_pool_t *p, X509 *x509, apr_array_header_t **ids)
389 {
390     X509_NAME *subj;
391     int i = -1;
392
393     /* First, the DNS-IDs (dNSName entries in the subjectAltName extension) */
394     if (!x509 ||
395         (modssl_X509_getSAN(p, x509, GEN_DNS, NULL, -1, ids) == FALSE && !*ids)) {
396         *ids = NULL;
397         return FALSE;
398     }
399
400     /* Second, the CN-IDs (commonName attributes in the subject DN) */
401     subj = X509_get_subject_name(x509);
402     while ((i = X509_NAME_get_index_by_NID(subj, NID_commonName, i)) != -1) {
403         APR_ARRAY_PUSH(*ids, const char *) = 
404             modssl_X509_NAME_ENTRY_to_string(p, X509_NAME_get_entry(subj, i), 0);
405     }
406
407     return apr_is_empty_array(*ids) ? FALSE : TRUE;
408 }
409
410 /* 
411  * Check if a certificate matches for a particular name, by iterating over its
412  * DNS-IDs and CN-IDs (RFC 6125), optionally with basic wildcard matching.
413  * If server_rec is non-NULL, some (debug/trace) logging is enabled.
414  */
415 BOOL modssl_X509_match_name(apr_pool_t *p, X509 *x509, const char *name,
416                             BOOL allow_wildcard, server_rec *s)
417 {
418     BOOL matched = FALSE;
419     apr_array_header_t *ids;
420
421     /*
422      * At some day in the future, this might be replaced with X509_check_host()
423      * (available in OpenSSL 1.0.2 and later), but two points should be noted:
424      * 1) wildcard matching in X509_check_host() might yield different
425      *    results (by default, it supports a broader set of patterns, e.g.
426      *    wildcards in non-initial positions);
427      * 2) we lose the option of logging each DNS- and CN-ID (until a match
428      *    is found).
429      */
430
431     if (getIDs(p, x509, &ids)) {
432         const char *cp;
433         int i;
434         char **id = (char **)ids->elts;
435         BOOL is_wildcard;
436
437         for (i = 0; i < ids->nelts; i++) {
438             if (!id[i])
439                 continue;
440
441             /*
442              * Determine if it is a wildcard ID - we're restrictive
443              * in the sense that we require the wildcard character to be
444              * THE left-most label (i.e., the ID must start with "*.")
445              */
446             is_wildcard = (*id[i] == '*' && *(id[i]+1) == '.') ? TRUE : FALSE;
447
448             /*
449              * If the ID includes a wildcard character (and the caller is
450              * allowing wildcards), check if it matches for the left-most
451              * DNS label - i.e., the wildcard character is not allowed
452              * to match a dot. Otherwise, try a simple string compare.
453              */
454             if ((allow_wildcard == TRUE && is_wildcard == TRUE &&
455                  (cp = ap_strchr_c(name, '.')) && !strcasecmp(id[i]+1, cp)) ||
456                 !strcasecmp(id[i], name)) {
457                 matched = TRUE;
458             }
459
460             if (s) {
461                 ap_log_error(APLOG_MARK, APLOG_TRACE3, 0, s,
462                              "[%s] modssl_X509_match_name: expecting name '%s', "
463                              "%smatched by ID '%s'",
464                              (mySrvConfig(s))->vhost_id, name,
465                              matched == TRUE ? "" : "NOT ", id[i]);
466             }
467
468             if (matched == TRUE) {
469                 break;
470             }
471         }
472
473     }
474
475     if (s) {
476         ssl_log_xerror(SSLLOG_MARK, APLOG_DEBUG, 0, p, s, x509,
477                        APLOGNO(02412) "[%s] Cert %s for name '%s'",
478                        (mySrvConfig(s))->vhost_id,
479                        matched == TRUE ? "matches" : "does not match",
480                        name);
481     }
482
483     return matched;
484 }
485
486 /*  _________________________________________________________________
487 **
488 **  Custom (EC)DH parameter support
489 **  _________________________________________________________________
490 */
491
492 DH *ssl_dh_GetParamFromFile(const char *file)
493 {
494     DH *dh = NULL;
495     BIO *bio;
496
497     if ((bio = BIO_new_file(file, "r")) == NULL)
498         return NULL;
499     dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
500     BIO_free(bio);
501     return (dh);
502 }
503
504 #ifdef HAVE_ECC
505 EC_GROUP *ssl_ec_GetParamFromFile(const char *file)
506 {
507     EC_GROUP *group = NULL;
508     BIO *bio;
509
510     if ((bio = BIO_new_file(file, "r")) == NULL)
511         return NULL;
512     group = PEM_read_bio_ECPKParameters(bio, NULL, NULL, NULL);
513     BIO_free(bio);
514     return (group);
515 }
516 #endif
517
518 /*  _________________________________________________________________
519 **
520 **  Session Stuff
521 **  _________________________________________________________________
522 */
523
524 char *modssl_SSL_SESSION_id2sz(IDCONST unsigned char *id, int idlen,
525                                char *str, int strsize)
526 {
527     if (idlen > SSL_MAX_SSL_SESSION_ID_LENGTH)
528         idlen = SSL_MAX_SSL_SESSION_ID_LENGTH;
529         
530     /* We must ensure not to process more than what would fit in the
531      * destination buffer, including terminating NULL */
532     if (idlen > (strsize-1) / 2)
533         idlen = (strsize-1) / 2;
534
535     ap_bin2hex(id, idlen, str);
536
537     return str;
538 }