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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * _ __ ___ ___ __| | ___ ___| | mod_ssl
19 * | '_ ` _ \ / _ \ / _` | / __/ __| | Apache Interface to OpenSSL
20 * | | | | | | (_) | (_| | \__ \__ \ |
21 * |_| |_| |_|\___/ \__,_|___|___/___/_|
24 * Additional Utility Functions for OpenSSL
27 #include "ssl_private.h"
29 /* _________________________________________________________________
31 ** Additional High-Level Functions for OpenSSL
32 ** _________________________________________________________________
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.
41 static int app_data2_idx = -1;
43 void modssl_init_app_data2_idx(void)
47 if (app_data2_idx > -1) {
51 /* we _do_ need to call this twice */
52 for (i = 0; i <= 1; i++) {
54 SSL_get_ex_new_index(0,
55 "Second Application Data for SSL",
60 void *modssl_get_app_data2(SSL *ssl)
62 return (void *)SSL_get_ex_data(ssl, app_data2_idx);
65 void modssl_set_app_data2(SSL *ssl, void *arg)
67 SSL_set_ex_data(ssl, app_data2_idx, (char *)arg);
71 /* _________________________________________________________________
73 ** High-Level Private Key Loading
74 ** _________________________________________________________________
77 EVP_PKEY *modssl_read_privatekey(const char* filename, EVP_PKEY **key, pem_password_cb *cb, void *s)
83 /* 1. try PEM (= DER+Base64+headers) */
84 if ((bioS=BIO_new_file(filename, "r")) == NULL)
86 rc = PEM_read_bio_PrivateKey(bioS, key, cb, s);
90 /* 2. try DER+Base64 */
91 if ((bioS = BIO_new_file(filename, "r")) == NULL)
94 if ((bioF = BIO_new(BIO_f_base64())) == NULL) {
98 bioS = BIO_push(bioF, bioS);
99 rc = d2i_PrivateKey_bio(bioS, NULL);
103 /* 3. try plain DER */
104 if ((bioS = BIO_new_file(filename, "r")) == NULL)
106 rc = d2i_PrivateKey_bio(bioS, NULL);
110 if (rc != NULL && key != NULL) {
123 static int provide_pass(char *buf, int size, int rwflag, void *baton)
125 pass_ctx *ctx = baton;
126 if (ctx->pass_len > 0) {
127 if (ctx->pass_len < size) {
128 size = (int)ctx->pass_len;
130 memcpy(buf, ctx->pass, size);
132 return ctx->pass_len;
135 EVP_PKEY *modssl_read_encrypted_pkey(const char *filename, EVP_PKEY **key,
136 const char *pass, apr_size_t pass_len)
141 ctx.pass_len = pass_len;
142 return modssl_read_privatekey(filename, key, provide_pass, &ctx);
145 /* _________________________________________________________________
148 ** _________________________________________________________________
151 int modssl_smart_shutdown(SSL *ssl)
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.
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.
172 if (BIO_flush(SSL_get_wbio(ssl)) <= 0) {
184 /* _________________________________________________________________
186 ** Certificate Checks
187 ** _________________________________________________________________
190 /* retrieve basic constraints ingredients */
191 BOOL modssl_X509_getBC(X509 *cert, int *ca, int *pathlen)
193 BASIC_CONSTRAINTS *bc;
197 bc = X509_get_ext_d2i(cert, NID_basic_constraints, NULL, NULL);
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);
207 if ((cp = BN_bn2dec(bn)) == NULL) {
209 BASIC_CONSTRAINTS_free(bc);
216 BASIC_CONSTRAINTS_free(bc);
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)
227 int len, flags = ASN1_STRFLGS_ESC_CTRL;
229 if ((bio = BIO_new(BIO_s_mem())) == NULL)
232 if (!raw) flags |= ASN1_STRFLGS_UTF8_CONVERT;
234 ASN1_STRING_print_ex(bio, asn1str, flags);
235 len = BIO_pending(bio);
237 result = apr_palloc(p, len+1);
238 len = BIO_read(bio, result, len);
245 #define asn1_string_to_utf8(p, a) asn1_string_convert(p, a, 0)
247 /* convert a NAME_ENTRY to UTF8 string */
248 char *modssl_X509_NAME_ENTRY_to_string(apr_pool_t *p, X509_NAME_ENTRY *xsne,
251 char *result = asn1_string_convert(p, X509_NAME_ENTRY_get_data(xsne), raw);
252 ap_xlate_proto_from_ascii(result, len);
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)
260 char *modssl_X509_NAME_to_string(apr_pool_t *p, X509_NAME *dn, int maxlen)
266 if ((bio = BIO_new(BIO_s_mem())) == NULL)
268 X509_NAME_print_ex(bio, dn, 0, XN_FLAG_RFC2253);
269 len = BIO_pending(bio);
271 result = apr_palloc(p, (maxlen > 0) ? maxlen+1 : len+1);
272 if (maxlen > 0 && maxlen < len) {
273 len = BIO_read(bio, result, maxlen);
275 /* insert trailing ellipsis if there's enough space */
276 apr_snprintf(result + maxlen - 3, 4, "...");
279 len = BIO_read(bio, result, len);
288 static void parse_otherName_value(apr_pool_t *p, ASN1_TYPE *value,
289 const char *onf, apr_array_header_t **entries)
292 int nid = onf ? OBJ_txt2nid(onf) : NID_undef;
294 if (!value || (nid == NID_undef) || !*entries)
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
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;
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)
318 * GEN_OTHERNAME (requires the otherName form ["onf"] argument to be supplied,
319 * see parse_otherName_value for the currently supported forms)
321 BOOL modssl_X509_getSAN(apr_pool_t *p, X509 *x509, int type, const char *onf,
322 int idx, apr_array_header_t **entries)
324 STACK_OF(GENERAL_NAME) *names;
325 int nid = onf ? OBJ_txt2nid(onf) : NID_undef;
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 *)))) {
335 if ((names = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL))) {
340 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
341 name = sk_GENERAL_NAME_value(names, i);
343 if (name->type != type)
349 if (((idx == -1) || (n == idx)) &&
350 (utf8str = asn1_string_to_utf8(p, name->d.ia5))) {
351 APR_ARRAY_PUSH(*entries, const char *) = utf8str;
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,
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)
377 if ((idx != -1) && (n > idx))
381 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
384 return apr_is_empty_array(*entries) ? FALSE : TRUE;
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)
393 /* First, the DNS-IDs (dNSName entries in the subjectAltName extension) */
395 (modssl_X509_getSAN(p, x509, GEN_DNS, NULL, -1, ids) == FALSE && !*ids)) {
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);
407 return apr_is_empty_array(*ids) ? FALSE : TRUE;
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.
415 BOOL modssl_X509_match_name(apr_pool_t *p, X509 *x509, const char *name,
416 BOOL allow_wildcard, server_rec *s)
418 BOOL matched = FALSE;
419 apr_array_header_t *ids;
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
431 if (getIDs(p, x509, &ids)) {
434 char **id = (char **)ids->elts;
437 for (i = 0; i < ids->nelts; i++) {
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 "*.")
446 is_wildcard = (*id[i] == '*' && *(id[i]+1) == '.') ? TRUE : FALSE;
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.
454 if ((allow_wildcard == TRUE && is_wildcard == TRUE &&
455 (cp = ap_strchr_c(name, '.')) && !strcasecmp(id[i]+1, cp)) ||
456 !strcasecmp(id[i], name)) {
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]);
468 if (matched == TRUE) {
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",
486 /* _________________________________________________________________
488 ** Custom (EC)DH parameter support
489 ** _________________________________________________________________
492 DH *ssl_dh_GetParamFromFile(const char *file)
497 if ((bio = BIO_new_file(file, "r")) == NULL)
499 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
505 EC_GROUP *ssl_ec_GetParamFromFile(const char *file)
507 EC_GROUP *group = NULL;
510 if ((bio = BIO_new_file(file, "r")) == NULL)
512 group = PEM_read_bio_ECPKParameters(bio, NULL, NULL, NULL);
518 /* _________________________________________________________________
521 ** _________________________________________________________________
524 char *modssl_SSL_SESSION_id2sz(IDCONST unsigned char *id, int idlen,
525 char *str, int strsize)
527 if (idlen > SSL_MAX_SSL_SESSION_ID_LENGTH)
528 idlen = SSL_MAX_SSL_SESSION_ID_LENGTH;
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;
535 ap_bin2hex(id, idlen, str);