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