Apache HTTPD
ssl_util_ssl.c
Go to the documentation of this file.
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 app_data2_idx = -1;
42
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++) {
55 "Second Application Data for SSL",
56 NULL, NULL, NULL);
57 }
58}
59
61{
62 return (void *)SSL_get_ex_data(ssl, app_data2_idx);
63}
64
65void 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
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;
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) {
96 return NULL;
97 }
101
102 if (rc == NULL) {
103 /* 3. try plain DER */
104 if ((bioS = BIO_new_file(filename, "r")) == NULL)
105 return NULL;
107 BIO_free(bioS);
108 }
109 }
110 return rc;
111}
112
113/* _________________________________________________________________
114**
115** Smart shutdown
116** _________________________________________________________________
117*/
118
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;
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 */
159BOOL modssl_X509_getBC(X509 *cert, int *ca, int *pathlen)
160{
162 BIGNUM *bn = NULL;
163 char *cp;
164
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) {
173 return FALSE;
174 }
175 if ((cp = BN_bn2dec(bn)) == NULL) {
176 BN_free(bn);
178 return FALSE;
179 }
180 *pathlen = atoi(cp);
181 OPENSSL_free(cp);
182 BN_free(bn);
183 }
185 return TRUE;
186}
187
189{
190 int len = BIO_pending(bio);
191 char *result = NULL;
192
193 if (len > 0) {
194 result = apr_palloc(p, len+1);
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. */
206{
207 BIO *bio;
209
210 if ((bio = BIO_new(BIO_s_mem())) == NULL)
211 return NULL;
212
214
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 */
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 */
236{
237 char *result = NULL;
238 BIO *bio;
239 int len;
240
241 if ((bio = BIO_new(BIO_s_mem())) == NULL)
242 return NULL;
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 {
255 }
256 result[len] = NUL;
257 }
258 BIO_free(bio);
259
260 return result;
261}
262
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 */
296BOOL modssl_X509_getSAN(apr_pool_t *p, X509 *x509, int type, const char *onf,
297 int idx, apr_array_header_t **entries)
298{
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
311 int i, n = 0;
313 const char *utf8str;
314
315 for (i = 0; i < sk_GENERAL_NAME_num(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
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 */
364{
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) */
377 while ((i = X509_NAME_get_index_by_NID(subj, NID_commonName, i)) != -1) {
378 APR_ARRAY_PUSH(*ids, const char *) =
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 */
392{
393 BOOL matched = FALSE;
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;
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) {
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) {
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
467#if OPENSSL_VERSION_NUMBER < 0x30000000L
469{
470 DH *dh;
471 BIO *bio;
472
473 if ((bio = BIO_new_file(file, "r")) == NULL)
474 return NULL;
476 BIO_free(bio);
477
478 return dh;
479}
480#else
482{
483 EVP_PKEY *pkey;
484 BIO *bio;
485
486 if ((bio = BIO_new_file(file, "r")) == NULL)
487 return NULL;
489 BIO_free(bio);
490
491 return pkey;
492}
493#endif
494
495#ifdef HAVE_ECC
497{
498 EC_GROUP *group;
499 BIO *bio;
500
501 if ((bio = BIO_new_file(file, "r")) == NULL)
502 return NULL;
503#if OPENSSL_VERSION_NUMBER < 0x30000000L
505#else
508 NULL, NULL, NULL);
509#endif
510 BIO_free(bio);
511
512 return group;
513}
514#endif
515
516/* _________________________________________________________________
517**
518** Session Stuff
519** _________________________________________________________________
520*/
521
522char *modssl_SSL_SESSION_id2sz(IDCONST unsigned char *id, int idlen,
523 char *str, int strsize)
524{
527
528 /* We must ensure not to process more than what would fit in the
529 * destination buffer, including terminating NULL */
530 if (idlen > (strsize-1) / 2)
531 idlen = (strsize-1) / 2;
532
533 ap_bin2hex(id, idlen, str);
534
535 return str;
536}
537
538/* _________________________________________________________________
539**
540** Certificate/Key Stuff
541** _________________________________________________________________
542*/
543
545 const char *cert_pem, const char *key_pem,
546 pem_password_cb *cb, void *ud,
547 X509 **pcert, EVP_PKEY **pkey)
548{
549 BIO *in;
550 X509 *x = NULL;
551 EVP_PKEY *key = NULL;
553
554 in = BIO_new_mem_buf(cert_pem, -1);
555 if (in == NULL) {
556 rv = APR_ENOMEM;
557 goto cleanup;
558 }
559
560 x = PEM_read_bio_X509(in, NULL, cb, ud);
561 if (x == NULL) {
562 rv = APR_ENOENT;
563 goto cleanup;
564 }
565
566 BIO_free(in);
567 in = BIO_new_mem_buf(key_pem? key_pem : cert_pem, -1);
568 if (in == NULL) {
569 rv = APR_ENOMEM;
570 goto cleanup;
571 }
573 if (key == NULL) {
574 rv = APR_ENOENT;
575 goto cleanup;
576 }
577
578cleanup:
579 if (rv == APR_SUCCESS) {
580 *pcert = x;
581 *pkey = key;
582 }
583 else {
584 *pcert = NULL;
585 *pkey = NULL;
586 if (x) X509_free(x);
587 if (key) EVP_PKEY_free(key);
588 }
589 if (in != NULL) BIO_free(in);
590 return rv;
591}
592
594 X509 *cert1, X509 *cert2,
595 const char **ppem)
596{
598 BIO *bio;
599
600 if ((bio = BIO_new(BIO_s_mem())) == NULL) goto cleanup;
601 if (PEM_write_bio_X509(bio, cert1) != 1) goto cleanup;
602 if (cert2 && PEM_write_bio_X509(bio, cert2) != 1) goto cleanup;
603 rv = APR_SUCCESS;
604
605cleanup:
606 if (rv != APR_SUCCESS) {
607 *ppem = NULL;
608 if (bio) BIO_free(bio);
609 }
610 else {
612 }
613 return rv;
614}
615
617{
618#ifdef SSL_OP_NO_RENEGOTIATION
619 switch (state) {
620 case RENEG_ALLOW:
622 break;
623 default:
625 break;
626 }
627#else
628 sslconn->reneg_state = state;
629#endif
630}
int n
Definition ap_regex.h:278
const char apr_size_t len
Definition ap_regex.h:187
#define TRUE
Definition abts.h:38
#define FALSE
Definition abts.h:35
int flush
#define ap_xlate_proto_from_ascii(x, y)
Definition util_ebcdic.h:81
#define APLOGNO(n)
Definition http_log.h:117
#define APLOG_TRACE3
Definition http_log.h:74
#define ap_log_error
Definition http_log.h:370
#define APLOG_MARK
Definition http_log.h:283
#define APLOG_DEBUG
Definition http_log.h:71
void const char * arg
Definition http_vhost.h:63
#define APR_ENOMEM
Definition apr_errno.h:683
#define APR_ENOENT
Definition apr_errno.h:662
apr_datum_t * pkey
Definition apr_dbm.h:158
const char apr_ssize_t int flags
Definition apr_encode.h:168
apr_redis_t * rc
Definition apr_redis.h:173
modssl_reneg_state
#define SSLLOG_MARK
#define mySrvConfig(srv)
DH * modssl_dh_from_file(const char *file)
void modssl_set_reneg_state(SSLConnRec *sslconn, modssl_reneg_state state)
#define IDCONST
#define BOOL
Definition ssl_private.h:81
#define NUL
@ RENEG_ALLOW
apr_status_t 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)
void modssl_init_app_data2_idx(void)
unsigned int modssl_X509_getBC(X509 *cert, int *ca, int *pathlen)
void modssl_set_app_data2(SSL *ssl, void *arg)
apr_status_t modssl_cert_get_pem(apr_pool_t *p, X509 *cert1, X509 *cert2, const char **ppem)
char * modssl_X509_NAME_to_string(apr_pool_t *p, X509_NAME *dn, int maxlen)
int modssl_smart_shutdown(SSL *ssl)
EVP_PKEY * modssl_read_privatekey(const char *filename, pem_password_cb *cb, void *s)
char * modssl_bio_free_read(apr_pool_t *p, BIO *bio)
unsigned int modssl_X509_getSAN(apr_pool_t *p, X509 *x509, int type, const char *onf, int idx, apr_array_header_t **entries)
char * modssl_X509_NAME_ENTRY_to_string(apr_pool_t *p, X509_NAME_ENTRY *xsne, int raw)
void * modssl_get_app_data2(SSL *ssl)
void ap_bin2hex(const void *src, apr_size_t srclen, char *dest)
Definition util.c:2314
#define ap_strchr_c(s, c)
Definition httpd.h:2353
apr_size_t size
const char * value
Definition apr_env.h:51
#define APR_SUCCESS
Definition apr_errno.h:225
int apr_status_t
Definition apr_errno.h:44
const char * key
const char apr_file_t * file
void const char apr_status_t(* cleanup)(void *))
int type
apr_array_header_t ** result
int strcasecmp(const char *a, const char *b)
apr_size_t const char * filename
Definition apr_shm.h:72
const char * s
Definition apr_strings.h:95
#define APR_ARRAY_PUSH(ary, type)
Definition apr_tables.h:150
apr_int32_t in
apr_pool_t * p
Definition md_event.c:32
#define strEQ(s1, s2)
Definition mod_nw_ssl.c:88
return NULL
Definition mod_so.c:359
int i
Definition mod_so.c:347
STACK_OF(X509_NAME)
void ssl_log_xerror(const char *file, int line, int level, apr_status_t rv, apr_pool_t *ptemp, server_rec *s, X509 *cert, const char *fmt,...)
char * name
int nid
Internal interfaces private to mod_ssl.
static int app_data2_idx
static char * asn1_string_convert(apr_pool_t *p, ASN1_STRING *asn1str, int raw)
#define asn1_string_to_utf8(p, a)
unsigned int modssl_X509_match_name(apr_pool_t *p, X509 *x509, const char *name, unsigned int allow_wildcard, server_rec *s)
static unsigned int getIDs(apr_pool_t *p, X509 *x509, apr_array_header_t **ids)
char * modssl_SSL_SESSION_id2sz(unsigned char *id, int idlen, char *str, int strsize)
static void parse_otherName_value(apr_pool_t *p, ASN1_TYPE *value, const char *onf, apr_array_header_t **entries)
A structure to store information for each virtual server.
Definition httpd.h:1322
#define str