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