]> granicus.if.org Git - apache/blob - modules/ssl/ssl_util_ssl.c
Port ssl_util_ssl.[ch] stuff to APR.
[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-2001 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 int SSL_get_app_data2_idx(void)
69 {
70    static int app_data2_idx = -1;
71
72    if (app_data2_idx < 0) {
73       app_data2_idx = SSL_get_ex_new_index(0,
74            "Second Application Data for SSL", NULL, NULL, NULL);
75       app_data2_idx = SSL_get_ex_new_index(0,
76            "Second Application Data for SSL", NULL, NULL, NULL);
77    }
78    return(app_data2_idx);
79 }
80
81 void *SSL_get_app_data2(SSL *ssl)
82 {
83     return (void *)SSL_get_ex_data(ssl, SSL_get_app_data2_idx());
84 }
85
86 void SSL_set_app_data2(SSL *ssl, void *arg)
87 {
88     SSL_set_ex_data(ssl, SSL_get_app_data2_idx(), (char *)arg);
89     return;
90 }
91
92 /*  _________________________________________________________________
93 **
94 **  High-Level Certificate / Private Key Loading
95 **  _________________________________________________________________
96 */
97
98 X509 *SSL_read_X509(FILE *fp, X509 **x509, int (*cb)())
99 {
100     X509 *rc;
101     BIO *bioS;
102     BIO *bioF;
103
104     /* 1. try PEM (= DER+Base64+headers) */
105 #if SSL_LIBRARY_VERSION < 0x00904000
106     rc = PEM_read_X509(fp, x509, cb);
107 #else
108     rc = PEM_read_X509(fp, x509, cb, NULL);
109 #endif
110     if (rc == NULL) {
111         /* 2. try DER+Base64 */
112         fseek(fp, 0L, SEEK_SET);
113         if ((bioS = BIO_new(BIO_s_fd())) == NULL)
114             return NULL;
115         BIO_set_fd(bioS, fileno(fp), BIO_NOCLOSE);
116         if ((bioF = BIO_new(BIO_f_base64())) == NULL) {
117             BIO_free(bioS);
118             return NULL;
119         }
120         bioS = BIO_push(bioF, bioS);
121         rc = d2i_X509_bio(bioS, NULL);
122         BIO_free_all(bioS);
123         if (rc == NULL) {
124             /* 3. try plain DER */
125             fseek(fp, 0L, SEEK_SET);
126             if ((bioS = BIO_new(BIO_s_fd())) == NULL)
127                 return NULL;
128             BIO_set_fd(bioS, fileno(fp), BIO_NOCLOSE);
129             rc = d2i_X509_bio(bioS, NULL);
130             BIO_free(bioS);
131         }
132     }
133     if (rc != NULL && x509 != NULL) {
134         if (*x509 != NULL)
135             X509_free(*x509);
136         *x509 = rc;
137     }
138     return rc;
139 }
140
141 #if SSL_LIBRARY_VERSION <= 0x00904100
142 static EVP_PKEY *d2i_PrivateKey_bio(BIO *bio, EVP_PKEY **key)
143 {
144      return ((EVP_PKEY *)ASN1_d2i_bio(
145              (char *(*)())EVP_PKEY_new, 
146              (char *(*)())d2i_PrivateKey, 
147              (bio), (unsigned char **)(key)));
148 }
149 #endif
150
151 EVP_PKEY *SSL_read_PrivateKey(FILE *fp, EVP_PKEY **key, int (*cb)())
152 {
153     EVP_PKEY *rc;
154     BIO *bioS;
155     BIO *bioF;
156
157     /* 1. try PEM (= DER+Base64+headers) */
158 #if SSL_LIBRARY_VERSION < 0x00904000
159     rc = PEM_read_PrivateKey(fp, key, cb);
160 #else
161     rc = PEM_read_PrivateKey(fp, key, cb, NULL);
162 #endif
163     if (rc == NULL) {
164         /* 2. try DER+Base64 */
165         fseek(fp, 0L, SEEK_SET);
166         if ((bioS = BIO_new(BIO_s_fd())) == NULL)
167             return NULL;
168         BIO_set_fd(bioS, fileno(fp), BIO_NOCLOSE);
169         if ((bioF = BIO_new(BIO_f_base64())) == NULL) {
170             BIO_free(bioS);
171             return NULL;
172         }
173         bioS = BIO_push(bioF, bioS);
174         rc = d2i_PrivateKey_bio(bioS, NULL);
175         BIO_free_all(bioS);
176         if (rc == NULL) {
177             /* 3. try plain DER */
178             fseek(fp, 0L, SEEK_SET);
179             if ((bioS = BIO_new(BIO_s_fd())) == NULL)
180                 return NULL;
181             BIO_set_fd(bioS, fileno(fp), BIO_NOCLOSE);
182             rc = d2i_PrivateKey_bio(bioS, NULL);
183             BIO_free(bioS);
184         }
185     }
186     if (rc != NULL && key != NULL) {
187         if (*key != NULL)
188             EVP_PKEY_free(*key);
189         *key = rc;
190     }
191     return rc;
192 }
193
194 /*  _________________________________________________________________
195 **
196 **  Smart shutdown
197 **  _________________________________________________________________
198 */
199
200 int SSL_smart_shutdown(SSL *ssl)
201 {
202     int i;
203     int rc;
204
205     /*
206      * Repeat the calls, because SSL_shutdown internally dispatches through a
207      * little state machine. Usually only one or two interation should be
208      * needed, so we restrict the total number of restrictions in order to
209      * avoid process hangs in case the client played bad with the socket
210      * connection and OpenSSL cannot recognize it.
211      */
212     rc = 0;
213     for (i = 0; i < 4 /* max 2x pending + 2x data = 4 */; i++) {
214         if ((rc = SSL_shutdown(ssl)))
215             break;
216     }
217     return rc;
218 }
219
220 /*  _________________________________________________________________
221 **
222 **  Certificate Revocation List (CRL) Storage
223 **  _________________________________________________________________
224 */
225
226 X509_STORE *SSL_X509_STORE_create(char *cpFile, char *cpPath)
227 {
228     X509_STORE *pStore;
229     X509_LOOKUP *pLookup;
230
231     if (cpFile == NULL && cpPath == NULL)
232         return NULL;
233     if ((pStore = X509_STORE_new()) == NULL)
234         return NULL;
235     if (cpFile != NULL) {
236         if ((pLookup = X509_STORE_add_lookup(pStore, X509_LOOKUP_file())) == NULL) {
237             X509_STORE_free(pStore);
238             return NULL;
239         }
240         X509_LOOKUP_load_file(pLookup, cpFile, X509_FILETYPE_PEM);
241     }
242     if (cpPath != NULL) {
243         if ((pLookup = X509_STORE_add_lookup(pStore, X509_LOOKUP_hash_dir())) == NULL) {
244             X509_STORE_free(pStore);
245             return NULL;
246         }
247         X509_LOOKUP_add_dir(pLookup, cpPath, X509_FILETYPE_PEM);
248     }
249     return pStore;
250 }
251
252 int SSL_X509_STORE_lookup(X509_STORE *pStore, int nType,
253                           X509_NAME *pName, X509_OBJECT *pObj)
254 {
255     X509_STORE_CTX pStoreCtx;
256     int rc;
257
258     X509_STORE_CTX_init(&pStoreCtx, pStore, NULL, NULL);
259     rc = X509_STORE_get_by_subject(&pStoreCtx, nType, pName, pObj);
260     X509_STORE_CTX_cleanup(&pStoreCtx);
261     return rc;
262 }
263
264 /*  _________________________________________________________________
265 **
266 **  Cipher Suite Spec String Creation
267 **  _________________________________________________________________
268 */
269
270 char *SSL_make_ciphersuite(apr_pool_t *p, SSL *ssl)
271 {
272     STACK_OF(SSL_CIPHER) *sk;
273     SSL_CIPHER *c;
274     int i;
275     int l;
276     char *cpCipherSuite;
277     char *cp;
278
279     if (ssl == NULL) 
280         return "";
281     if ((sk = SSL_get_ciphers(ssl)) == NULL)
282         return "";
283     l = 0;
284     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
285         c = sk_SSL_CIPHER_value(sk, i);
286         l += strlen(c->name)+2+1;
287     }
288     if (l == 0)
289         return "";
290     cpCipherSuite = (char *)apr_palloc(p, l+1);
291     cp = cpCipherSuite;
292     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
293         c = sk_SSL_CIPHER_value(sk, i);
294         l = strlen(c->name);
295         memcpy(cp, c->name, l);
296         cp += l;
297         *cp++ = '/';
298         *cp++ = (c->valid == 1 ? '1' : '0');
299         *cp++ = ':';
300     }
301     *(cp-1) = NUL;
302     return cpCipherSuite;
303 }
304
305 /*  _________________________________________________________________
306 **
307 **  Certificate Checks
308 **  _________________________________________________________________
309 */
310
311 /* check whether cert contains extended key usage with a SGC tag */
312 BOOL SSL_X509_isSGC(X509 *cert)
313 {
314     X509_EXTENSION *ext;
315     int ext_nid;
316     STACK *sk;
317     BOOL is_sgc;
318     int idx;
319     int i;
320     
321     is_sgc = FALSE;
322     idx = X509_get_ext_by_NID(cert, NID_ext_key_usage, -1);
323     if (idx >= 0) {
324         ext = X509_get_ext(cert, idx);
325         if ((sk = (STACK *)X509V3_EXT_d2i(ext)) != NULL) {
326             for (i = 0; i < sk_num(sk); i++) {
327                 ext_nid = OBJ_obj2nid((ASN1_OBJECT *)sk_value(sk, i));
328                 if (ext_nid == NID_ms_sgc || ext_nid == NID_ns_sgc) {
329                     is_sgc = TRUE;
330                     break;
331                 }
332             }
333         }
334     }
335     return is_sgc;
336 }
337
338 /* retrieve basic constraints ingredients */
339 BOOL SSL_X509_getBC(X509 *cert, int *ca, int *pathlen)
340 {
341     X509_EXTENSION *ext;
342     BASIC_CONSTRAINTS *bc;
343     int idx;
344     BIGNUM *bn = NULL;
345     char *cp;
346     
347     if ((idx = X509_get_ext_by_NID(cert, NID_basic_constraints, -1)) < 0)
348         return FALSE;
349     ext = X509_get_ext(cert, idx);
350     if (ext == NULL)
351         return FALSE;
352     if ((bc = (BASIC_CONSTRAINTS *)X509V3_EXT_d2i(ext)) == NULL)
353         return FALSE;
354     *ca = bc->ca;
355     *pathlen = -1 /* unlimited */;
356     if (bc->pathlen != NULL) {
357         if ((bn = ASN1_INTEGER_to_BN(bc->pathlen, NULL)) == NULL)
358             return FALSE;
359         if ((cp = BN_bn2dec(bn)) == NULL)
360             return FALSE;
361         *pathlen = atoi(cp);
362         free(cp);
363         BN_free(bn);
364     }
365     BASIC_CONSTRAINTS_free(bc);
366     return TRUE;
367 }
368
369 /* retrieve subject CommonName of certificate */
370 BOOL SSL_X509_getCN(apr_pool_t *p, X509 *xs, char **cppCN)
371 {
372     X509_NAME *xsn;
373     X509_NAME_ENTRY *xsne;
374     int i, nid;
375
376     xsn = X509_get_subject_name(xs);
377     for (i = 0; i < sk_X509_NAME_ENTRY_num(xsn->entries); i++) {
378         xsne = sk_X509_NAME_ENTRY_value(xsn->entries, i);
379         nid = OBJ_obj2nid(xsne->object);
380         if (nid == NID_commonName) {
381             *cppCN = apr_palloc(p, xsne->value->length+1);
382             apr_cpystrn(*cppCN, (char *)xsne->value->data, xsne->value->length+1);
383             (*cppCN)[xsne->value->length] = NUL;
384 #ifdef CHARSET_EBCDIC
385             ascii2ebcdic(*cppCN, *cppCN, strlen(*cppCN));
386 #endif
387             return TRUE;
388         }
389     }
390     return FALSE;
391 }
392
393 /*  _________________________________________________________________
394 **
395 **  Low-Level CA Certificate Loading
396 **  _________________________________________________________________
397 */
398
399 #ifdef SSL_EXPERIMENTAL_PROXY
400
401 BOOL SSL_load_CrtAndKeyInfo_file(apr_pool_t *p, STACK_OF(X509_INFO) *sk, char *filename)
402 {
403     BIO *in;
404
405     if ((in = BIO_new(BIO_s_file())) == NULL)
406         return FALSE;
407     if (BIO_read_filename(in, filename) <= 0) {
408         BIO_free(in);
409         return FALSE;
410     }
411     ERR_clear_error();
412 #if SSL_LIBRARY_VERSION < 0x00904000
413     PEM_X509_INFO_read_bio(in, sk, NULL);
414 #else
415     PEM_X509_INFO_read_bio(in, sk, NULL, NULL);
416 #endif
417     BIO_free(in);
418     return TRUE;
419 }
420
421 BOOL SSL_load_CrtAndKeyInfo_path(apr_pool_t *p, STACK_OF(X509_INFO) *sk, char *pathname)
422 {
423     apr_pool_t *sp;
424     apr_dir_t *dir;
425     apr_finfo_t dirent;
426     char *fullname;
427     BOOL ok;
428
429     sp = apr_pool_sub_make(p, NULL);
430     if (apr_dir_open(&dir, pathname, sp)) != APR_SUCCESS) {
431         apr_pool_destroy(sp);
432         return FALSE;
433     }
434     ok = FALSE;
435     while ((apr_dir_read(&dirent, APR_FINFO_DIRENT, dir)) == APR_SUCCESS) {
436         fullname = apr_pstrcat(sp, pathname, "/", dirent.name, NULL);
437         if (dirent.filetype != APR_REG)
438             continue;
439         if (SSL_load_CrtAndKeyInfo_file(sp, sk, fullname))
440             ok = TRUE;
441     }
442     apr_dir_close(dir);
443     apr_pool_destroy(sp);
444     return ok;
445 }              
446
447 #endif /* SSL_EXPERIMENTAL_PROXY */
448
449 /*  _________________________________________________________________
450 **
451 **  Extra Server Certificate Chain Support
452 **  _________________________________________________________________
453 */
454
455 /* 
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.
459  */
460 int SSL_CTX_use_certificate_chain(
461     SSL_CTX *ctx, char *file, int skipfirst, int (*cb)())
462 {
463     BIO *bio;
464     X509 *x509;
465     unsigned long err;
466     int n;
467
468     if ((bio = BIO_new(BIO_s_file_internal())) == NULL)
469         return -1;
470     if (BIO_read_filename(bio, file) <= 0) {
471         BIO_free(bio);
472         return -1;
473     }
474     /* optionally skip a leading server certificate */
475     if (skipfirst) {
476 #if SSL_LIBRARY_VERSION < 0x00904000
477         if ((x509 = PEM_read_bio_X509(bio, NULL, cb)) == NULL) {
478 #else
479         if ((x509 = PEM_read_bio_X509(bio, NULL, cb, NULL)) == NULL) {
480 #endif
481             BIO_free(bio);
482             return -1;
483         }
484         X509_free(x509);
485     }
486     /* free a perhaps already configured extra chain */
487     if (ctx->extra_certs != NULL) {
488         sk_X509_pop_free(ctx->extra_certs, X509_free);
489         ctx->extra_certs = NULL;
490     }
491     /* create new extra chain by loading the certs */
492     n = 0;
493 #if SSL_LIBRARY_VERSION < 0x00904000
494     while ((x509 = PEM_read_bio_X509(bio, NULL, cb)) != NULL) {
495 #else
496     while ((x509 = PEM_read_bio_X509(bio, NULL, cb, NULL)) != NULL) {
497 #endif
498         if (!SSL_CTX_add_extra_chain_cert(ctx, x509)) { 
499             X509_free(x509);
500             BIO_free(bio);
501             return -1;
502         }
503         n++;
504     }
505     /* Make sure that only the error is just an EOF */
506     if ((err = ERR_peek_error()) > 0) {
507         if (!(   ERR_GET_LIB(err) == ERR_LIB_PEM 
508               && ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
509             BIO_free(bio);
510             return -1;
511         }
512         while (ERR_get_error() > 0) ;
513     }
514     BIO_free(bio);
515     return n;
516 }
517
518 /*  _________________________________________________________________
519 **
520 **  Session Stuff
521 **  _________________________________________________________________
522 */
523
524 char *SSL_SESSION_id2sz(unsigned char *id, int idlen)
525 {
526     static char str[(SSL_MAX_SSL_SESSION_ID_LENGTH+1)*2];
527     char *cp;
528     int n;
529
530     cp = str;
531     for (n = 0; n < idlen && n < SSL_MAX_SSL_SESSION_ID_LENGTH; n++) {
532         apr_snprintf(cp, sizeof(str)-(cp-str), "%02X", id[n]);
533         cp += 2;
534     }
535     *cp = NUL;
536     return str;
537 }
538