1 /*                      _             _
2 **  _ __ ___   ___   __| |    ___ ___| |  mod_ssl
3 ** | '_ ` _ \ / _ \ / _` |   / __/ __| |  Apache Interface to OpenSSL
4 ** | | | | | | (_) | (_| |   \__ \__ \ |  www.modssl.org
5 ** |_| |_| |_|\___/ \__,_|___|___/___/_|  ftp.modssl.org
6 **                      |_____|
7 **  ssl_util_ssl.c
8 **  Additional Utility Functions for OpenSSL
9 */
10 
11 /* ====================================================================
12  * Copyright (c) 1998-2003 Ralf S. Engelschall. All rights reserved.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  *
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  *
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following
23  *    disclaimer in the documentation and/or other materials
24  *    provided with the distribution.
25  *
26  * 3. All advertising materials mentioning features or use of this
27  *    software must display the following acknowledgment:
28  *    "This product includes software developed by
29  *     Ralf S. Engelschall <rse@engelschall.com> for use in the
30  *     mod_ssl project (http://www.modssl.org/)."
31  *
32  * 4. The names "mod_ssl" must not be used to endorse or promote
33  *    products derived from this software without prior written
34  *    permission. For written permission, please contact
35  *    rse@engelschall.com.
36  *
37  * 5. Products derived from this software may not be called "mod_ssl"
38  *    nor may "mod_ssl" appear in their names without prior
39  *    written permission of Ralf S. Engelschall.
40  *
41  * 6. Redistributions of any form whatsoever must retain the following
42  *    acknowledgment:
43  *    "This product includes software developed by
44  *     Ralf S. Engelschall <rse@engelschall.com> for use in the
45  *     mod_ssl project (http://www.modssl.org/)."
46  *
47  * THIS SOFTWARE IS PROVIDED BY RALF S. ENGELSCHALL ``AS IS'' AND ANY
48  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
50  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL RALF S. ENGELSCHALL OR
51  * HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
52  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
53  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
54  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
56  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
57  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
58  * OF THE POSSIBILITY OF SUCH DAMAGE.
59  * ====================================================================
60  */
61 
62 #include "mod_ssl.h"
63 
64 
65 /*  _________________________________________________________________
66 **
67 **  Additional High-Level Functions for OpenSSL
68 **  _________________________________________________________________
69 */
70 
SSL_get_app_data2_idx(void)71 int SSL_get_app_data2_idx(void)
72 {
73    static int app_data2_idx = -1;
74 
75    if (app_data2_idx < 0) {
76       app_data2_idx = SSL_get_ex_new_index(0,
77            "Second Application Data for SSL", NULL, NULL, NULL);
78       app_data2_idx = SSL_get_ex_new_index(0,
79            "Second Application Data for SSL", NULL, NULL, NULL);
80    }
81    return(app_data2_idx);
82 }
83 
SSL_get_app_data2(SSL * ssl)84 void *SSL_get_app_data2(SSL *ssl)
85 {
86     return (void *)SSL_get_ex_data(ssl, SSL_get_app_data2_idx());
87 }
88 
SSL_set_app_data2(SSL * ssl,void * arg)89 void SSL_set_app_data2(SSL *ssl, void *arg)
90 {
91     SSL_set_ex_data(ssl, SSL_get_app_data2_idx(), (char *)arg);
92     return;
93 }
94 
95 /*  _________________________________________________________________
96 **
97 **  High-Level Certificate / Private Key Loading
98 **  _________________________________________________________________
99 */
100 
SSL_read_X509(FILE * fp,X509 ** x509,int (* cb)())101 X509 *SSL_read_X509(FILE *fp, X509 **x509, int (*cb)())
102 {
103     X509 *rc;
104     BIO *bioS;
105     BIO *bioF;
106 
107     /* 1. try PEM (= DER+Base64+headers) */
108     rc = PEM_read_X509(fp, x509, cb, NULL);
109     if (rc == NULL) {
110         /* 2. try DER+Base64 */
111         fseek(fp, 0L, SEEK_SET);
112         if ((bioS = BIO_new(BIO_s_fd())) == NULL)
113             return NULL;
114         BIO_set_fd(bioS, fileno(fp), BIO_NOCLOSE);
115         if ((bioF = BIO_new(BIO_f_base64())) == NULL) {
116             BIO_free(bioS);
117             return NULL;
118         }
119         bioS = BIO_push(bioF, bioS);
120         rc = d2i_X509_bio(bioS, NULL);
121         BIO_free_all(bioS);
122         if (rc == NULL) {
123             /* 3. try plain DER */
124             fseek(fp, 0L, SEEK_SET);
125             if ((bioS = BIO_new(BIO_s_fd())) == NULL)
126                 return NULL;
127             BIO_set_fd(bioS, fileno(fp), BIO_NOCLOSE);
128             rc = d2i_X509_bio(bioS, NULL);
129             BIO_free(bioS);
130         }
131     }
132     if (rc != NULL && x509 != NULL) {
133         if (*x509 != NULL)
134             X509_free(*x509);
135         *x509 = rc;
136     }
137     return rc;
138 }
139 
SSL_read_PrivateKey(FILE * fp,EVP_PKEY ** key,int (* cb)())140 EVP_PKEY *SSL_read_PrivateKey(FILE *fp, EVP_PKEY **key, int (*cb)())
141 {
142     EVP_PKEY *rc;
143     BIO *bioS;
144     BIO *bioF;
145 
146     /* 1. try PEM (= DER+Base64+headers) */
147     rc = PEM_read_PrivateKey(fp, key, cb, NULL);
148     if (rc == NULL) {
149         /* 2. try DER+Base64 */
150         fseek(fp, 0L, SEEK_SET);
151         if ((bioS = BIO_new(BIO_s_fd())) == NULL)
152             return NULL;
153         BIO_set_fd(bioS, fileno(fp), BIO_NOCLOSE);
154         if ((bioF = BIO_new(BIO_f_base64())) == NULL) {
155             BIO_free(bioS);
156             return NULL;
157         }
158         bioS = BIO_push(bioF, bioS);
159         rc = d2i_PrivateKey_bio(bioS, NULL);
160         BIO_free_all(bioS);
161         if (rc == NULL) {
162             /* 3. try plain DER */
163             fseek(fp, 0L, SEEK_SET);
164             if ((bioS = BIO_new(BIO_s_fd())) == NULL)
165                 return NULL;
166             BIO_set_fd(bioS, fileno(fp), BIO_NOCLOSE);
167             rc = d2i_PrivateKey_bio(bioS, NULL);
168             BIO_free(bioS);
169         }
170     }
171     if (rc != NULL && key != NULL) {
172         if (*key != NULL)
173             EVP_PKEY_free(*key);
174         *key = rc;
175     }
176     return rc;
177 }
178 
179 /*  _________________________________________________________________
180 **
181 **  Smart shutdown
182 **  _________________________________________________________________
183 */
184 
SSL_smart_shutdown(SSL * ssl)185 int SSL_smart_shutdown(SSL *ssl)
186 {
187     int i;
188     int rc;
189 
190     /*
191      * Repeat the calls, because SSL_shutdown internally dispatches through a
192      * little state machine. Usually only one or two interation should be
193      * needed, so we restrict the total number of restrictions in order to
194      * avoid process hangs in case the client played bad with the socket
195      * connection and OpenSSL cannot recognize it.
196      */
197     rc = 0;
198     for (i = 0; i < 4 /* max 2x pending + 2x data = 4 */; i++) {
199         if ((rc = SSL_shutdown(ssl)))
200             break;
201     }
202     return rc;
203 }
204 
205 /*  _________________________________________________________________
206 **
207 **  Certificate Revocation List (CRL) Storage
208 **  _________________________________________________________________
209 */
210 
SSL_X509_STORE_create(char * cpFile,char * cpPath)211 X509_STORE *SSL_X509_STORE_create(char *cpFile, char *cpPath)
212 {
213     X509_STORE *pStore;
214     X509_LOOKUP *pLookup;
215 
216     if (cpFile == NULL && cpPath == NULL)
217         return NULL;
218     if ((pStore = X509_STORE_new()) == NULL)
219         return NULL;
220     if (cpFile != NULL) {
221         if ((pLookup = X509_STORE_add_lookup(pStore, X509_LOOKUP_file())) == NULL) {
222             X509_STORE_free(pStore);
223             return NULL;
224         }
225         X509_LOOKUP_load_file(pLookup, cpFile, X509_FILETYPE_PEM);
226     }
227     if (cpPath != NULL) {
228         if ((pLookup = X509_STORE_add_lookup(pStore, X509_LOOKUP_hash_dir())) == NULL) {
229             X509_STORE_free(pStore);
230             return NULL;
231         }
232         X509_LOOKUP_add_dir(pLookup, cpPath, X509_FILETYPE_PEM);
233     }
234     return pStore;
235 }
236 
SSL_X509_STORE_lookup(X509_STORE * pStore,int nType,X509_NAME * pName,X509_OBJECT * pObj)237 int SSL_X509_STORE_lookup(X509_STORE *pStore, int nType,
238                           X509_NAME *pName, X509_OBJECT *pObj)
239 {
240     X509_STORE_CTX pStoreCtx;
241     int rc;
242 
243     X509_STORE_CTX_init(&pStoreCtx, pStore, NULL, NULL);
244     rc = X509_STORE_get_by_subject(&pStoreCtx, nType, pName, pObj);
245     X509_STORE_CTX_cleanup(&pStoreCtx);
246     return rc;
247 }
248 
249 /*  _________________________________________________________________
250 **
251 **  Cipher Suite Spec String Creation
252 **  _________________________________________________________________
253 */
254 
SSL_make_ciphersuite(pool * p,SSL * ssl)255 char *SSL_make_ciphersuite(pool *p, SSL *ssl)
256 {
257     STACK_OF(SSL_CIPHER) *sk;
258     SSL_CIPHER *c;
259     int i;
260     int l;
261     char *cpCipherSuite;
262     char *cp;
263 
264     if (ssl == NULL)
265         return "";
266     if ((sk = SSL_get_ciphers(ssl)) == NULL)
267         return "";
268     l = 0;
269     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
270         c = sk_SSL_CIPHER_value(sk, i);
271         l += strlen(c->name)+2+1;
272     }
273     if (l == 0)
274         return "";
275     cpCipherSuite = (char *)ap_palloc(p, l+1);
276     cp = cpCipherSuite;
277     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
278         c = sk_SSL_CIPHER_value(sk, i);
279         l = strlen(c->name);
280         memcpy(cp, c->name, l);
281         cp += l;
282         *cp++ = '/';
283         *cp++ = (c->valid == 1 ? '1' : '0');
284         *cp++ = ':';
285     }
286     *(cp-1) = NUL;
287     return cpCipherSuite;
288 }
289 
290 /*  _________________________________________________________________
291 **
292 **  Certificate Checks
293 **  _________________________________________________________________
294 */
295 
296 /* check whether cert contains extended key usage with a SGC tag */
SSL_X509_isSGC(X509 * cert)297 BOOL SSL_X509_isSGC(X509 *cert)
298 {
299     X509_EXTENSION *ext;
300     int ext_nid;
301     STACK *sk;
302     BOOL is_sgc;
303     int idx;
304     int i;
305 
306     is_sgc = FALSE;
307     idx = X509_get_ext_by_NID(cert, NID_ext_key_usage, -1);
308     if (idx >= 0) {
309         ext = X509_get_ext(cert, idx);
310         if ((sk = (STACK *)X509V3_EXT_d2i(ext)) != NULL) {
311             for (i = 0; i < sk_num(sk); i++) {
312                 ext_nid = OBJ_obj2nid((ASN1_OBJECT *)sk_value(sk, i));
313                 if (ext_nid == NID_ms_sgc || ext_nid == NID_ns_sgc) {
314                     is_sgc = TRUE;
315                     break;
316                 }
317             }
318         }
319     }
320     return is_sgc;
321 }
322 
323 /* retrieve basic constraints ingredients */
SSL_X509_getBC(X509 * cert,int * ca,int * pathlen)324 BOOL SSL_X509_getBC(X509 *cert, int *ca, int *pathlen)
325 {
326     X509_EXTENSION *ext;
327     BASIC_CONSTRAINTS *bc;
328     int idx;
329     BIGNUM *bn = NULL;
330     char *cp;
331 
332     if ((idx = X509_get_ext_by_NID(cert, NID_basic_constraints, -1)) < 0)
333         return FALSE;
334     ext = X509_get_ext(cert, idx);
335     if (ext == NULL)
336         return FALSE;
337     if ((bc = (BASIC_CONSTRAINTS *)X509V3_EXT_d2i(ext)) == NULL)
338         return FALSE;
339     *ca = bc->ca;
340     *pathlen = -1 /* unlimited */;
341     if (bc->pathlen != NULL) {
342         if ((bn = ASN1_INTEGER_to_BN(bc->pathlen, NULL)) == NULL)
343             return FALSE;
344         if ((cp = BN_bn2dec(bn)) == NULL)
345             return FALSE;
346         *pathlen = atoi(cp);
347         OPENSSL_free(cp);
348         BN_free(bn);
349     }
350     BASIC_CONSTRAINTS_free(bc);
351     return TRUE;
352 }
353 
354 /* retrieve subject CommonName of certificate */
SSL_X509_getCN(pool * p,X509 * xs,char ** cppCN)355 BOOL SSL_X509_getCN(pool *p, X509 *xs, char **cppCN)
356 {
357     X509_NAME *xsn;
358     X509_NAME_ENTRY *xsne;
359     int i, nid;
360 
361     xsn = X509_get_subject_name(xs);
362     for (i = 0; i < sk_X509_NAME_ENTRY_num(xsn->entries); i++) {
363         xsne = sk_X509_NAME_ENTRY_value(xsn->entries, i);
364         nid = OBJ_obj2nid(xsne->object);
365         if (nid == NID_commonName) {
366             *cppCN = ap_palloc(p, xsne->value->length+1);
367             ap_cpystrn(*cppCN, (char *)xsne->value->data, xsne->value->length+1);
368             (*cppCN)[xsne->value->length] = NUL;
369             return TRUE;
370         }
371     }
372     return FALSE;
373 }
374 
375 /*  _________________________________________________________________
376 **
377 **  Low-Level CA Certificate Loading
378 **  _________________________________________________________________
379 */
380 
381 #ifdef SSL_EXPERIMENTAL_PROXY
382 
SSL_load_CrtAndKeyInfo_file(pool * p,STACK_OF (X509_INFO)* sk,char * filename)383 BOOL SSL_load_CrtAndKeyInfo_file(pool *p, STACK_OF(X509_INFO) *sk, char *filename)
384 {
385     BIO *in;
386 
387     if ((in = BIO_new(BIO_s_file())) == NULL)
388         return FALSE;
389     if (BIO_read_filename(in, filename) <= 0) {
390         BIO_free(in);
391         return FALSE;
392     }
393     ERR_clear_error();
394     PEM_X509_INFO_read_bio(in, sk, NULL, NULL);
395     BIO_free(in);
396     return TRUE;
397 }
398 
SSL_load_CrtAndKeyInfo_path(pool * p,STACK_OF (X509_INFO)* sk,char * pathname)399 BOOL SSL_load_CrtAndKeyInfo_path(pool *p, STACK_OF(X509_INFO) *sk, char *pathname)
400 {
401     struct stat st;
402     DIR *dir;
403     pool *sp;
404     struct dirent *nextent;
405     char *fullname;
406     BOOL ok;
407 
408     sp = ap_make_sub_pool(p);
409     if ((dir = ap_popendir(sp, pathname)) == NULL) {
410         ap_destroy_pool(sp);
411         return FALSE;
412     }
413     ok = FALSE;
414     while ((nextent = readdir(dir)) != NULL) {
415         fullname = ap_pstrcat(sp, pathname, "/", nextent->d_name, NULL);
416         if (stat(fullname, &st) != 0)
417             continue;
418         if (!S_ISREG(st.st_mode))
419             continue;
420         if (SSL_load_CrtAndKeyInfo_file(sp, sk, fullname))
421             ok = TRUE;
422     }
423     ap_pclosedir(p, dir);
424     ap_destroy_pool(sp);
425     return ok;
426 }
427 
428 #endif /* SSL_EXPERIMENTAL_PROXY */
429 
430 /*  _________________________________________________________________
431 **
432 **  Extra Server Certificate Chain Support
433 **  _________________________________________________________________
434 */
435 
436 /*
437  * Read a file that optionally contains the server certificate in PEM
438  * format, possibly followed by a sequence of CA certificates that
439  * should be sent to the peer in the SSL Certificate message.
440  */
SSL_CTX_use_certificate_chain(SSL_CTX * ctx,char * file,int skipfirst,int (* cb)())441 int SSL_CTX_use_certificate_chain(
442     SSL_CTX *ctx, char *file, int skipfirst, int (*cb)())
443 {
444     BIO *bio;
445     X509 *x509;
446     unsigned long err;
447     int n;
448 
449     if ((bio = BIO_new(BIO_s_file_internal())) == NULL)
450         return -1;
451     if (BIO_read_filename(bio, file) <= 0) {
452         BIO_free(bio);
453         return -1;
454     }
455     /* optionally skip a leading server certificate */
456     if (skipfirst) {
457         if ((x509 = PEM_read_bio_X509(bio, NULL, cb, NULL)) == NULL) {
458             BIO_free(bio);
459             return -1;
460         }
461         X509_free(x509);
462     }
463     /* free a perhaps already configured extra chain */
464     if (ctx->extra_certs != NULL) {
465         sk_X509_pop_free(ctx->extra_certs, X509_free);
466         ctx->extra_certs = NULL;
467     }
468     /* create new extra chain by loading the certs */
469     n = 0;
470     while ((x509 = PEM_read_bio_X509(bio, NULL, cb, NULL)) != NULL) {
471         if (!SSL_CTX_add_extra_chain_cert(ctx, x509)) {
472             X509_free(x509);
473             BIO_free(bio);
474             return -1;
475         }
476         n++;
477     }
478     /* Make sure that only the error is just an EOF */
479     if ((err = ERR_peek_error()) > 0) {
480         if (!(   ERR_GET_LIB(err) == ERR_LIB_PEM
481               && ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
482             BIO_free(bio);
483             return -1;
484         }
485         while (ERR_get_error() > 0) ;
486     }
487     BIO_free(bio);
488     return n;
489 }
490 
491 /*  _________________________________________________________________
492 **
493 **  Session Stuff
494 **  _________________________________________________________________
495 */
496 
SSL_SESSION_id2sz(unsigned char * id,int idlen)497 char *SSL_SESSION_id2sz(unsigned char *id, int idlen)
498 {
499     static char str[(SSL_MAX_SSL_SESSION_ID_LENGTH+1)*2];
500     char *cp;
501     int n;
502 
503     cp = str;
504     for (n = 0; n < idlen && n < SSL_MAX_SSL_SESSION_ID_LENGTH; n++) {
505         ap_snprintf(cp, sizeof(str)-(cp-str), "%02X", id[n]);
506         cp += strlen(cp);
507     }
508     *cp = NUL;
509     return str;
510 }
511 
512