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