]> granicus.if.org Git - apache/blob - modules/ssl/ssl_util_ssl.c
finished that boring job:
[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-2003 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 = modssl_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
135         if (rc == NULL) {
136             /* 3. try plain DER */
137             if ((bioS=BIO_new_file(filename, "r")) == NULL)
138                 return NULL;
139             rc = d2i_X509_bio(bioS, NULL);
140             BIO_free(bioS);
141         }
142     }
143     if (rc != NULL && x509 != NULL) {
144         if (*x509 != NULL)
145             X509_free(*x509);
146         *x509 = rc;
147     }
148     return rc;
149 }
150
151 #if SSL_LIBRARY_VERSION <= 0x00904100
152 static EVP_PKEY *d2i_PrivateKey_bio(BIO *bio, EVP_PKEY **key)
153 {
154      return ((EVP_PKEY *)ASN1_d2i_bio(
155              (char *(*)())EVP_PKEY_new, 
156              (char *(*)())d2i_PrivateKey, 
157              (bio), (unsigned char **)(key)));
158 }
159 #endif
160
161 EVP_PKEY *SSL_read_PrivateKey(char* filename, EVP_PKEY **key, int (*cb)(char*,int,int,void*), void *s)
162 {
163     EVP_PKEY *rc;
164     BIO *bioS;
165     BIO *bioF;
166
167     /* 1. try PEM (= DER+Base64+headers) */
168     if ((bioS=BIO_new_file(filename, "r")) == NULL)
169         return NULL;
170     rc = modssl_PEM_read_bio_PrivateKey(bioS, key, cb, s);
171     BIO_free(bioS);
172
173     if (rc == NULL) {
174         /* 2. try DER+Base64 */
175         if ((bioS = BIO_new_file(filename, "r")) == NULL)
176             return NULL;
177
178         if ((bioF = BIO_new(BIO_f_base64())) == NULL) {
179             BIO_free(bioS);
180             return NULL;
181         }
182         bioS = BIO_push(bioF, bioS);
183         rc = d2i_PrivateKey_bio(bioS, NULL);
184         BIO_free_all(bioS);
185
186         if (rc == NULL) {
187             /* 3. try plain DER */
188             if ((bioS = BIO_new_file(filename, "r")) == NULL)
189                 return NULL;
190             rc = d2i_PrivateKey_bio(bioS, NULL);
191             BIO_free(bioS);
192         }
193     }
194     if (rc != NULL && key != NULL) {
195         if (*key != NULL)
196             EVP_PKEY_free(*key);
197         *key = rc;
198     }
199     return rc;
200 }
201
202 /*  _________________________________________________________________
203 **
204 **  Smart shutdown
205 **  _________________________________________________________________
206 */
207
208 int SSL_smart_shutdown(SSL *ssl)
209 {
210     int i;
211     int rc;
212
213     /*
214      * Repeat the calls, because SSL_shutdown internally dispatches through a
215      * little state machine. Usually only one or two interation should be
216      * needed, so we restrict the total number of restrictions in order to
217      * avoid process hangs in case the client played bad with the socket
218      * connection and OpenSSL cannot recognize it.
219      */
220     rc = 0;
221     for (i = 0; i < 4 /* max 2x pending + 2x data = 4 */; i++) {
222         if ((rc = SSL_shutdown(ssl)))
223             break;
224     }
225     return rc;
226 }
227
228 /*  _________________________________________________________________
229 **
230 **  Certificate Revocation List (CRL) Storage
231 **  _________________________________________________________________
232 */
233
234 X509_STORE *SSL_X509_STORE_create(char *cpFile, char *cpPath)
235 {
236     X509_STORE *pStore;
237     X509_LOOKUP *pLookup;
238
239     if (cpFile == NULL && cpPath == NULL)
240         return NULL;
241     if ((pStore = X509_STORE_new()) == NULL)
242         return NULL;
243     if (cpFile != NULL) {
244         pLookup = X509_STORE_add_lookup(pStore, X509_LOOKUP_file());
245         if (pLookup == NULL) {
246             X509_STORE_free(pStore);
247             return NULL;
248         }
249         X509_LOOKUP_load_file(pLookup, cpFile, X509_FILETYPE_PEM);
250     }
251     if (cpPath != NULL) {
252         pLookup = X509_STORE_add_lookup(pStore, X509_LOOKUP_hash_dir());
253         if (pLookup == NULL) {
254             X509_STORE_free(pStore);
255             return NULL;
256         }
257         X509_LOOKUP_add_dir(pLookup, cpPath, X509_FILETYPE_PEM);
258     }
259     return pStore;
260 }
261
262 int SSL_X509_STORE_lookup(X509_STORE *pStore, int nType,
263                           X509_NAME *pName, X509_OBJECT *pObj)
264 {
265     X509_STORE_CTX pStoreCtx;
266     int rc;
267
268     X509_STORE_CTX_init(&pStoreCtx, pStore, NULL, NULL);
269     rc = X509_STORE_get_by_subject(&pStoreCtx, nType, pName, pObj);
270     X509_STORE_CTX_cleanup(&pStoreCtx);
271     return rc;
272 }
273
274 /*  _________________________________________________________________
275 **
276 **  Cipher Suite Spec String Creation
277 **  _________________________________________________________________
278 */
279
280 char *SSL_make_ciphersuite(apr_pool_t *p, SSL *ssl)
281 {
282     STACK_OF(SSL_CIPHER) *sk;
283     SSL_CIPHER *c;
284     int i;
285     int l;
286     char *cpCipherSuite;
287     char *cp;
288
289     if (ssl == NULL) 
290         return "";
291     if ((sk = (STACK_OF(SSL_CIPHER) *)SSL_get_ciphers(ssl)) == NULL)
292         return "";
293     l = 0;
294     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
295         c = sk_SSL_CIPHER_value(sk, i);
296         l += strlen(SSL_CIPHER_get_name(c))+2+1;
297     }
298     if (l == 0)
299         return "";
300     cpCipherSuite = (char *)apr_palloc(p, l+1);
301     cp = cpCipherSuite;
302     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
303         c = sk_SSL_CIPHER_value(sk, i);
304         l = strlen(SSL_CIPHER_get_name(c));
305         memcpy(cp, SSL_CIPHER_get_name(c), l);
306         cp += l;
307         *cp++ = '/';
308         *cp++ = (SSL_CIPHER_get_valid(c) == 1 ? '1' : '0');
309         *cp++ = ':';
310     }
311     *(cp-1) = NUL;
312     return cpCipherSuite;
313 }
314
315 /*  _________________________________________________________________
316 **
317 **  Certificate Checks
318 **  _________________________________________________________________
319 */
320
321 /* check whether cert contains extended key usage with a SGC tag */
322 BOOL SSL_X509_isSGC(X509 *cert)
323 {
324 #ifdef HAVE_SSL_X509V3_EXT_d2i
325     X509_EXTENSION *ext;
326     int ext_nid;
327     STACK *sk;
328     BOOL is_sgc;
329     int idx;
330     int i;
331     
332     is_sgc = FALSE;
333     idx = X509_get_ext_by_NID(cert, NID_ext_key_usage, -1);
334     if (idx >= 0) {
335         ext = X509_get_ext(cert, idx);
336         if ((sk = (STACK *)X509V3_EXT_d2i(ext)) != NULL) {
337             for (i = 0; i < sk_num(sk); i++) {
338                 ext_nid = OBJ_obj2nid((ASN1_OBJECT *)sk_value(sk, i));
339                 if (ext_nid == NID_ms_sgc || ext_nid == NID_ns_sgc) {
340                     is_sgc = TRUE;
341                     break;
342                 }
343             }
344         }
345     }
346     return is_sgc;
347 #else
348     return FALSE;
349 #endif
350 }
351
352 /* retrieve basic constraints ingredients */
353 BOOL SSL_X509_getBC(X509 *cert, int *ca, int *pathlen)
354 {
355 #ifdef HAVE_SSL_X509V3_EXT_d2i
356     X509_EXTENSION *ext;
357     BASIC_CONSTRAINTS *bc;
358     int idx;
359     BIGNUM *bn = NULL;
360     char *cp;
361     
362     if ((idx = X509_get_ext_by_NID(cert, NID_basic_constraints, -1)) < 0)
363         return FALSE;
364     ext = X509_get_ext(cert, idx);
365     if (ext == NULL)
366         return FALSE;
367     if ((bc = (BASIC_CONSTRAINTS *)X509V3_EXT_d2i(ext)) == NULL)
368         return FALSE;
369     *ca = bc->ca;
370     *pathlen = -1 /* unlimited */;
371     if (bc->pathlen != NULL) {
372         if ((bn = ASN1_INTEGER_to_BN(bc->pathlen, NULL)) == NULL)
373             return FALSE;
374         if ((cp = BN_bn2dec(bn)) == NULL)
375             return FALSE;
376         *pathlen = atoi(cp);
377         free(cp);
378         BN_free(bn);
379     }
380     BASIC_CONSTRAINTS_free(bc);
381     return TRUE;
382 #else
383     return FALSE;
384 #endif
385 }
386
387 /* retrieve subject CommonName of certificate */
388 BOOL SSL_X509_getCN(apr_pool_t *p, X509 *xs, char **cppCN)
389 {
390     X509_NAME *xsn;
391     X509_NAME_ENTRY *xsne;
392     int i, nid;
393     unsigned char *data_ptr;
394     int data_len;
395
396     xsn = X509_get_subject_name(xs);
397     for (i = 0; i < sk_X509_NAME_ENTRY_num((STACK_OF(X509_NAME_ENTRY) *)
398                                            X509_NAME_get_entries(xsn)); i++) {
399         xsne = sk_X509_NAME_ENTRY_value((STACK_OF(X509_NAME_ENTRY) *)
400                                          X509_NAME_get_entries(xsn), i);
401         nid = OBJ_obj2nid((ASN1_OBJECT *)X509_NAME_ENTRY_get_object(xsne));
402         if (nid == NID_commonName) {
403             data_ptr = X509_NAME_ENTRY_get_data_ptr(xsne);
404             data_len = X509_NAME_ENTRY_get_data_len(xsne);
405             *cppCN = apr_palloc(p, data_len+1);
406             apr_cpystrn(*cppCN, (char *)data_ptr, data_len+1);
407             (*cppCN)[data_len] = NUL;
408 #ifdef CHARSET_EBCDIC
409             ascii2ebcdic(*cppCN, *cppCN, strlen(*cppCN));
410 #endif
411             return TRUE;
412         }
413     }
414     return FALSE;
415 }
416
417 /*  _________________________________________________________________
418 **
419 **  Low-Level CA Certificate Loading
420 **  _________________________________________________________________
421 */
422
423 BOOL SSL_X509_INFO_load_file(apr_pool_t *ptemp,
424                              STACK_OF(X509_INFO) *sk,
425                              const char *filename)
426 {
427     BIO *in;
428
429     if (!(in = BIO_new(BIO_s_file()))) {
430         return FALSE;
431     }
432
433     if (BIO_read_filename(in, filename) <= 0) {
434         BIO_free(in);
435         return FALSE;
436     }
437
438     ERR_clear_error();
439
440     modssl_PEM_X509_INFO_read_bio(in, sk, NULL, NULL);
441
442     BIO_free(in);
443
444     return TRUE;
445 }
446
447 BOOL SSL_X509_INFO_load_path(apr_pool_t *ptemp,
448                              STACK_OF(X509_INFO) *sk,
449                              const char *pathname)
450 {
451     /* XXX: this dir read code is exactly the same as that in
452      * ssl_engine_init.c, only the call to handle the fullname is different,
453      * should fold the duplication.
454      */
455     apr_dir_t *dir;
456     apr_finfo_t dirent;
457     apr_int32_t finfo_flags = APR_FINFO_TYPE|APR_FINFO_NAME;
458     const char *fullname;
459     BOOL ok = FALSE;
460
461     if (apr_dir_open(&dir, pathname, ptemp) != APR_SUCCESS) {
462         return FALSE;
463     }
464
465     while ((apr_dir_read(&dirent, finfo_flags, dir)) == APR_SUCCESS) {
466         if (dirent.filetype == APR_DIR) {
467             continue; /* don't try to load directories */
468         }
469
470         fullname = apr_pstrcat(ptemp,
471                                pathname, "/", dirent.name,
472                                NULL);
473
474         if (SSL_X509_INFO_load_file(ptemp, sk, fullname)) {
475             ok = TRUE;
476         }
477     }
478
479     apr_dir_close(dir);
480
481     return ok;
482 }              
483
484 /*  _________________________________________________________________
485 **
486 **  Extra Server Certificate Chain Support
487 **  _________________________________________________________________
488 */
489
490 /* 
491  * Read a file that optionally contains the server certificate in PEM
492  * format, possibly followed by a sequence of CA certificates that
493  * should be sent to the peer in the SSL Certificate message.
494  */
495 int SSL_CTX_use_certificate_chain(
496     SSL_CTX *ctx, char *file, int skipfirst, int (*cb)(char*,int,int,void*))
497 {
498     BIO *bio;
499     X509 *x509;
500     unsigned long err;
501     int n;
502     STACK *extra_certs;
503
504     if ((bio = BIO_new(BIO_s_file_internal())) == NULL)
505         return -1;
506     if (BIO_read_filename(bio, file) <= 0) {
507         BIO_free(bio);
508         return -1;
509     }
510     /* optionally skip a leading server certificate */
511     if (skipfirst) {
512         if ((x509 = modssl_PEM_read_bio_X509(bio, NULL, cb, NULL)) == NULL) {
513             BIO_free(bio);
514             return -1;
515         }
516         X509_free(x509);
517     }
518     /* free a perhaps already configured extra chain */
519     extra_certs=SSL_CTX_get_extra_certs(ctx);
520     if (extra_certs != NULL) {
521         sk_X509_pop_free((STACK_OF(X509) *)extra_certs, X509_free);
522         SSL_CTX_set_extra_certs(ctx,NULL);
523     }
524     /* create new extra chain by loading the certs */
525     n = 0;
526     while ((x509 = modssl_PEM_read_bio_X509(bio, NULL, cb, NULL)) != NULL) {
527         if (!SSL_CTX_add_extra_chain_cert(ctx, x509)) { 
528             X509_free(x509);
529             BIO_free(bio);
530             return -1;
531         }
532         n++;
533     }
534     /* Make sure that only the error is just an EOF */
535     if ((err = ERR_peek_error()) > 0) {
536         if (!(   ERR_GET_LIB(err) == ERR_LIB_PEM 
537               && ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
538             BIO_free(bio);
539             return -1;
540         }
541         while (ERR_get_error() > 0) ;
542     }
543     BIO_free(bio);
544     return n;
545 }
546
547 /*  _________________________________________________________________
548 **
549 **  Session Stuff
550 **  _________________________________________________________________
551 */
552
553 char *SSL_SESSION_id2sz(unsigned char *id, int idlen,
554                         char *str, int strsize)
555 {
556     char *cp;
557     int n;
558
559     cp = str;
560     for (n = 0; n < idlen && n < SSL_MAX_SSL_SESSION_ID_LENGTH; n++) {
561         apr_snprintf(cp, strsize - (cp-str), "%02X", id[n]);
562         cp += 2;
563     }
564     *cp = NUL;
565     return str;
566 }
567
568 /* sslc+OpenSSL compat */
569
570 int modssl_session_get_time(SSL_SESSION *session)
571 {
572 #ifdef OPENSSL_VERSION_NUMBER
573     return SSL_SESSION_get_time(session);
574 #else /* assume sslc */
575     CRYPTO_TIME_T ct;
576     SSL_SESSION_get_time(session, &ct);
577     return CRYPTO_time_to_int(&ct);
578 #endif
579 }
580
581 #ifndef SSLC_VERSION_NUMBER
582 #define SSLC_VERSION_NUMBER 0x0000
583 #endif
584
585 DH *modssl_dh_configure(unsigned char *p, int plen,
586                         unsigned char *g, int glen)
587 {
588     DH *dh;
589
590     if (!(dh = DH_new())) {
591         return NULL;
592     }
593
594 #if defined(OPENSSL_VERSION_NUMBER) || (SSLC_VERSION_NUMBER < 0x2000)
595     dh->p = BN_bin2bn(p, plen, NULL);
596     dh->g = BN_bin2bn(g, glen, NULL);
597     if (!(dh->p && dh->g)) {
598         DH_free(dh);
599         return NULL;
600     }
601 #else
602     R_EITEMS_add(dh->data, PK_TYPE_DH, PK_DH_P, 0, p, plen, R_EITEMS_PF_COPY);
603     R_EITEMS_add(dh->data, PK_TYPE_DH, PK_DH_G, 0, g, glen, R_EITEMS_PF_COPY);
604 #endif
605
606     return dh;
607 }