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 SSL_app_data2_idx = -1;
43 void SSL_init_app_data2_idx(void)
47 if (SSL_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 *SSL_get_app_data2(SSL *ssl)
62 return (void *)SSL_get_ex_data(ssl, SSL_app_data2_idx);
65 void SSL_set_app_data2(SSL *ssl, void *arg)
67 SSL_set_ex_data(ssl, SSL_app_data2_idx, (char *)arg);
71 /* _________________________________________________________________
73 ** High-Level Certificate / Private Key Loading
74 ** _________________________________________________________________
77 X509 *SSL_read_X509(char* filename, X509 **x509, pem_password_cb *cb)
83 /* 1. try PEM (= DER+Base64+headers) */
84 if ((bioS=BIO_new_file(filename, "r")) == NULL)
86 rc = PEM_read_bio_X509 (bioS, x509, cb, NULL);
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_X509_bio(bioS, NULL);
103 /* 3. try plain DER */
104 if ((bioS=BIO_new_file(filename, "r")) == NULL)
106 rc = d2i_X509_bio(bioS, NULL);
110 if (rc != NULL && x509 != NULL) {
118 EVP_PKEY *SSL_read_PrivateKey(char* filename, EVP_PKEY **key, pem_password_cb *cb, void *s)
124 /* 1. try PEM (= DER+Base64+headers) */
125 if ((bioS=BIO_new_file(filename, "r")) == NULL)
127 rc = PEM_read_bio_PrivateKey(bioS, key, cb, s);
131 /* 2. try DER+Base64 */
132 if ((bioS = BIO_new_file(filename, "r")) == NULL)
135 if ((bioF = BIO_new(BIO_f_base64())) == NULL) {
139 bioS = BIO_push(bioF, bioS);
140 rc = d2i_PrivateKey_bio(bioS, NULL);
144 /* 3. try plain DER */
145 if ((bioS = BIO_new_file(filename, "r")) == NULL)
147 rc = d2i_PrivateKey_bio(bioS, NULL);
151 if (rc != NULL && key != NULL) {
159 /* _________________________________________________________________
162 ** _________________________________________________________________
165 int SSL_smart_shutdown(SSL *ssl)
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.
178 for (i = 0; i < 4 /* max 2x pending + 2x data = 4 */; i++) {
179 if ((rc = SSL_shutdown(ssl)))
185 /* _________________________________________________________________
187 ** Cipher Suite Spec String Creation
188 ** _________________________________________________________________
191 char *SSL_make_ciphersuite(apr_pool_t *p, SSL *ssl)
193 STACK_OF(SSL_CIPHER) *sk;
202 if ((sk = (STACK_OF(SSL_CIPHER) *)SSL_get_ciphers(ssl)) == NULL)
205 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
206 c = sk_SSL_CIPHER_value(sk, i);
207 l += strlen(SSL_CIPHER_get_name(c))+2+1;
211 cpCipherSuite = (char *)apr_palloc(p, l+1);
213 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
214 c = sk_SSL_CIPHER_value(sk, i);
215 l = strlen(SSL_CIPHER_get_name(c));
216 memcpy(cp, SSL_CIPHER_get_name(c), l);
219 *cp++ = (c->valid == 1 ? '1' : '0');
223 return cpCipherSuite;
226 /* _________________________________________________________________
228 ** Certificate Checks
229 ** _________________________________________________________________
232 /* check whether cert contains extended key usage with a SGC tag */
233 BOOL SSL_X509_isSGC(X509 *cert)
236 EXTENDED_KEY_USAGE *sk;
241 sk = X509_get_ext_d2i(cert, NID_ext_key_usage, NULL, NULL);
243 for (i = 0; i < sk_ASN1_OBJECT_num(sk); i++) {
244 ext_nid = OBJ_obj2nid(sk_ASN1_OBJECT_value(sk, i));
245 if (ext_nid == NID_ms_sgc || ext_nid == NID_ns_sgc) {
250 EXTENDED_KEY_USAGE_free(sk);
255 /* retrieve basic constraints ingredients */
256 BOOL SSL_X509_getBC(X509 *cert, int *ca, int *pathlen)
258 BASIC_CONSTRAINTS *bc;
262 bc = X509_get_ext_d2i(cert, NID_basic_constraints, NULL, NULL);
266 *pathlen = -1 /* unlimited */;
267 if (bc->pathlen != NULL) {
268 if ((bn = ASN1_INTEGER_to_BN(bc->pathlen, NULL)) == NULL)
270 if ((cp = BN_bn2dec(bn)) == NULL)
276 BASIC_CONSTRAINTS_free(bc);
280 /* convert a NAME_ENTRY to UTF8 string */
281 char *SSL_X509_NAME_ENTRY_to_string(apr_pool_t *p, X509_NAME_ENTRY *xsne)
287 if ((bio = BIO_new(BIO_s_mem())) == NULL)
289 ASN1_STRING_print_ex(bio, X509_NAME_ENTRY_get_data(xsne),
290 ASN1_STRFLGS_ESC_CTRL|ASN1_STRFLGS_UTF8_CONVERT);
291 len = BIO_pending(bio);
292 result = apr_palloc(p, len+1);
293 len = BIO_read(bio, result, len);
296 ap_xlate_proto_from_ascii(result, len);
301 * convert an X509_NAME to an RFC 2253 formatted string, optionally truncated
302 * to maxlen characters (specify a maxlen of 0 for no length limit)
304 char *SSL_X509_NAME_to_string(apr_pool_t *p, X509_NAME *dn, unsigned int maxlen)
310 if ((bio = BIO_new(BIO_s_mem())) == NULL)
312 X509_NAME_print_ex(bio, dn, 0, XN_FLAG_RFC2253);
313 len = BIO_pending(bio);
315 result = apr_palloc(p, maxlen ? maxlen+1 : len+1);
316 if (maxlen && maxlen < len) {
317 len = BIO_read(bio, result, maxlen);
319 /* insert trailing ellipsis if there's enough space */
320 apr_snprintf(result + maxlen - 3, 4, "...");
323 len = BIO_read(bio, result, len);
332 /* return an array of (RFC 6125 coined) DNS-IDs and CN-IDs in a certificate */
333 BOOL SSL_X509_getIDs(apr_pool_t *p, X509 *x509, apr_array_header_t **ids)
335 STACK_OF(GENERAL_NAME) *names;
341 if (!x509 || !(*ids = apr_array_make(p, 0, sizeof(char *)))) {
346 /* First, the DNS-IDs (dNSName entries in the subjectAltName extension) */
347 if ((names = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL)) &&
348 (bio = BIO_new(BIO_s_mem()))) {
351 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
352 name = sk_GENERAL_NAME_value(names, i);
353 if (name->type == GEN_DNS) {
354 ASN1_STRING_print_ex(bio, name->d.ia5, ASN1_STRFLGS_ESC_CTRL|
355 ASN1_STRFLGS_UTF8_CONVERT);
356 n = BIO_pending(bio);
358 cpp = (char **)apr_array_push(*ids);
359 *cpp = apr_palloc(p, n+1);
360 n = BIO_read(bio, *cpp, n);
369 sk_GENERAL_NAME_free(names);
371 /* Second, the CN-IDs (commonName attributes in the subject DN) */
372 subj = X509_get_subject_name(x509);
374 while ((i = X509_NAME_get_index_by_NID(subj, NID_commonName, i)) != -1) {
375 cpp = (char **)apr_array_push(*ids);
376 *cpp = SSL_X509_NAME_ENTRY_to_string(p, X509_NAME_get_entry(subj, i));
379 return apr_is_empty_array(*ids) ? FALSE : TRUE;
382 /* _________________________________________________________________
384 ** Low-Level CA Certificate Loading
385 ** _________________________________________________________________
388 BOOL SSL_X509_INFO_load_file(apr_pool_t *ptemp,
389 STACK_OF(X509_INFO) *sk,
390 const char *filename)
394 if (!(in = BIO_new(BIO_s_file()))) {
398 if (BIO_read_filename(in, filename) <= 0) {
405 PEM_X509_INFO_read_bio(in, sk, NULL, NULL);
412 BOOL SSL_X509_INFO_load_path(apr_pool_t *ptemp,
413 STACK_OF(X509_INFO) *sk,
414 const char *pathname)
416 /* XXX: this dir read code is exactly the same as that in
417 * ssl_engine_init.c, only the call to handle the fullname is different,
418 * should fold the duplication.
422 apr_int32_t finfo_flags = APR_FINFO_TYPE|APR_FINFO_NAME;
423 const char *fullname;
426 if (apr_dir_open(&dir, pathname, ptemp) != APR_SUCCESS) {
430 while ((apr_dir_read(&dirent, finfo_flags, dir)) == APR_SUCCESS) {
431 if (dirent.filetype == APR_DIR) {
432 continue; /* don't try to load directories */
435 fullname = apr_pstrcat(ptemp,
436 pathname, "/", dirent.name,
439 if (SSL_X509_INFO_load_file(ptemp, sk, fullname)) {
449 /* _________________________________________________________________
451 ** Extra Server Certificate Chain Support
452 ** _________________________________________________________________
456 * Read a file that optionally contains the server certificate in PEM
457 * format, possibly followed by a sequence of CA certificates that
458 * should be sent to the peer in the SSL Certificate message.
460 int SSL_CTX_use_certificate_chain(
461 SSL_CTX *ctx, char *file, int skipfirst, pem_password_cb *cb)
467 STACK_OF(X509) *extra_certs;
469 if ((bio = BIO_new(BIO_s_file_internal())) == NULL)
471 if (BIO_read_filename(bio, file) <= 0) {
475 /* optionally skip a leading server certificate */
477 if ((x509 = PEM_read_bio_X509(bio, NULL, cb, NULL)) == NULL) {
483 /* free a perhaps already configured extra chain */
484 extra_certs = ctx->extra_certs;
485 if (extra_certs != NULL) {
486 sk_X509_pop_free((STACK_OF(X509) *)extra_certs, X509_free);
487 ctx->extra_certs = NULL;
489 /* create new extra chain by loading the certs */
491 while ((x509 = PEM_read_bio_X509(bio, NULL, cb, NULL)) != NULL) {
492 if (!SSL_CTX_add_extra_chain_cert(ctx, x509)) {
499 /* Make sure that only the error is just an EOF */
500 if ((err = ERR_peek_error()) > 0) {
501 if (!( ERR_GET_LIB(err) == ERR_LIB_PEM
502 && ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
506 while (ERR_get_error() > 0) ;
512 /* _________________________________________________________________
515 ** _________________________________________________________________
518 char *SSL_SESSION_id2sz(unsigned char *id, int idlen,
519 char *str, int strsize)
525 for (n = 0; n < idlen && n < SSL_MAX_SSL_SESSION_ID_LENGTH; n++) {
526 apr_snprintf(cp, strsize - (cp-str), "%02X", id[n]);