]> git.sur5r.net Git - openldap/blob - libraries/libldap/tls_o.c
Merge remote branch 'origin/mdb.master'
[openldap] / libraries / libldap / tls_o.c
1 /* tls_o.c - Handle tls/ssl using OpenSSL */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2008-2011 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16 /* ACKNOWLEDGEMENTS: Rewritten by Howard Chu
17  */
18
19 #include "portable.h"
20
21 #ifdef HAVE_OPENSSL
22
23 #include "ldap_config.h"
24
25 #include <stdio.h>
26
27 #include <ac/stdlib.h>
28 #include <ac/errno.h>
29 #include <ac/socket.h>
30 #include <ac/string.h>
31 #include <ac/ctype.h>
32 #include <ac/time.h>
33 #include <ac/unistd.h>
34 #include <ac/param.h>
35 #include <ac/dirent.h>
36
37 #include "ldap-int.h"
38 #include "ldap-tls.h"
39
40 #ifdef HAVE_OPENSSL_SSL_H
41 #include <openssl/ssl.h>
42 #include <openssl/x509v3.h>
43 #include <openssl/err.h>
44 #include <openssl/rand.h>
45 #include <openssl/safestack.h>
46 #elif defined( HAVE_SSL_H )
47 #include <ssl.h>
48 #endif
49
50 typedef SSL_CTX tlso_ctx;
51 typedef SSL tlso_session;
52
53 static int  tlso_opt_trace = 1;
54
55 static void tlso_report_error( void );
56
57 static void tlso_info_cb( const SSL *ssl, int where, int ret );
58 static int tlso_verify_cb( int ok, X509_STORE_CTX *ctx );
59 static int tlso_verify_ok( int ok, X509_STORE_CTX *ctx );
60 static RSA * tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
61
62 static DH * tlso_tmp_dh_cb( SSL *ssl, int is_export, int key_length );
63
64 typedef struct dhplist {
65         struct dhplist *next;
66         int keylength;
67         DH *param;
68 } dhplist;
69
70 static dhplist *tlso_dhparams;
71
72 static int tlso_seed_PRNG( const char *randfile );
73
74 #ifdef LDAP_R_COMPILE
75 /*
76  * provide mutexes for the OpenSSL library.
77  */
78 static ldap_pvt_thread_mutex_t  tlso_mutexes[CRYPTO_NUM_LOCKS];
79 static ldap_pvt_thread_mutex_t  tlso_dh_mutex;
80
81 static void tlso_locking_cb( int mode, int type, const char *file, int line )
82 {
83         if ( mode & CRYPTO_LOCK ) {
84                 ldap_pvt_thread_mutex_lock( &tlso_mutexes[type] );
85         } else {
86                 ldap_pvt_thread_mutex_unlock( &tlso_mutexes[type] );
87         }
88 }
89
90 static unsigned long tlso_thread_self( void )
91 {
92         /* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
93          * is an integral type that fits in an unsigned long
94          */
95
96         /* force an error if the ldap_pvt_thread_t type is too large */
97         enum { ok = sizeof( ldap_pvt_thread_t ) <= sizeof( unsigned long ) };
98         typedef struct { int dummy: ok ? 1 : -1; } Check[ok ? 1 : -1];
99
100         return (unsigned long) ldap_pvt_thread_self();
101 }
102
103 static void tlso_thr_init( void )
104 {
105         int i;
106
107         for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
108                 ldap_pvt_thread_mutex_init( &tlso_mutexes[i] );
109         }
110         ldap_pvt_thread_mutex_init( &tlso_dh_mutex );
111         CRYPTO_set_locking_callback( tlso_locking_cb );
112         CRYPTO_set_id_callback( tlso_thread_self );
113 }
114 #endif /* LDAP_R_COMPILE */
115
116 static STACK_OF(X509_NAME) *
117 tlso_ca_list( char * bundle, char * dir )
118 {
119         STACK_OF(X509_NAME) *ca_list = NULL;
120
121         if ( bundle ) {
122                 ca_list = SSL_load_client_CA_file( bundle );
123         }
124 #if defined(HAVE_DIRENT_H) || defined(dirent)
125         if ( dir ) {
126                 int freeit = 0;
127
128                 if ( !ca_list ) {
129                         ca_list = sk_X509_NAME_new_null();
130                         freeit = 1;
131                 }
132                 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
133                         freeit ) {
134                         sk_X509_NAME_free( ca_list );
135                         ca_list = NULL;
136                 }
137         }
138 #endif
139         return ca_list;
140 }
141
142 /*
143  * Initialize TLS subsystem. Should be called only once.
144  */
145 static int
146 tlso_init( void )
147 {
148         struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();   
149 #ifdef HAVE_EBCDIC
150         {
151                 char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
152                 if ( file ) __atoe( file );
153                 (void) tlso_seed_PRNG( file );
154                 LDAP_FREE( file );
155         }
156 #else
157         (void) tlso_seed_PRNG( lo->ldo_tls_randfile );
158 #endif
159
160         SSL_load_error_strings();
161         SSL_library_init();
162         OpenSSL_add_all_digests();
163
164         /* FIXME: mod_ssl does this */
165         X509V3_add_standard_extensions();
166
167         return 0;
168 }
169
170 /*
171  * Tear down the TLS subsystem. Should only be called once.
172  */
173 static void
174 tlso_destroy( void )
175 {
176         struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();   
177
178         EVP_cleanup();
179         ERR_remove_state(0);
180         ERR_free_strings();
181
182         if ( lo->ldo_tls_randfile ) {
183                 LDAP_FREE( lo->ldo_tls_randfile );
184                 lo->ldo_tls_randfile = NULL;
185         }
186 }
187
188 static tls_ctx *
189 tlso_ctx_new( struct ldapoptions *lo )
190 {
191         return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
192 }
193
194 static void
195 tlso_ctx_ref( tls_ctx *ctx )
196 {
197         tlso_ctx *c = (tlso_ctx *)ctx;
198         CRYPTO_add( &c->references, 1, CRYPTO_LOCK_SSL_CTX );
199 }
200
201 static void
202 tlso_ctx_free ( tls_ctx *ctx )
203 {
204         tlso_ctx *c = (tlso_ctx *)ctx;
205         SSL_CTX_free( c );
206 }
207
208 /*
209  * initialize a new TLS context
210  */
211 static int
212 tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
213 {
214         tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
215         int i;
216
217         if ( is_server ) {
218                 SSL_CTX_set_session_id_context( ctx,
219                         (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
220         }
221
222         if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
223                 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 );
224         else if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 )
225                 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 );
226
227         if ( lo->ldo_tls_ciphersuite &&
228                 !SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
229         {
230                 Debug( LDAP_DEBUG_ANY,
231                            "TLS: could not set cipher list %s.\n",
232                            lo->ldo_tls_ciphersuite, 0, 0 );
233                 tlso_report_error();
234                 return -1;
235         }
236
237         if (lo->ldo_tls_cacertfile != NULL || lo->ldo_tls_cacertdir != NULL) {
238                 if ( !SSL_CTX_load_verify_locations( ctx,
239                                 lt->lt_cacertfile, lt->lt_cacertdir ) ||
240                         !SSL_CTX_set_default_verify_paths( ctx ) )
241                 {
242                         Debug( LDAP_DEBUG_ANY, "TLS: "
243                                 "could not load verify locations (file:`%s',dir:`%s').\n",
244                                 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
245                                 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
246                                 0 );
247                         tlso_report_error();
248                         return -1;
249                 }
250
251                 if ( is_server ) {
252                         STACK_OF(X509_NAME) *calist;
253                         /* List of CA names to send to a client */
254                         calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir );
255                         if ( !calist ) {
256                                 Debug( LDAP_DEBUG_ANY, "TLS: "
257                                         "could not load client CA list (file:`%s',dir:`%s').\n",
258                                         lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
259                                         lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
260                                         0 );
261                                 tlso_report_error();
262                                 return -1;
263                         }
264
265                         SSL_CTX_set_client_CA_list( ctx, calist );
266                 }
267         }
268
269         if ( lo->ldo_tls_certfile &&
270                 !SSL_CTX_use_certificate_file( ctx,
271                         lt->lt_certfile, SSL_FILETYPE_PEM ) )
272         {
273                 Debug( LDAP_DEBUG_ANY,
274                         "TLS: could not use certificate `%s'.\n",
275                         lo->ldo_tls_certfile,0,0);
276                 tlso_report_error();
277                 return -1;
278         }
279
280         /* Key validity is checked automatically if cert has already been set */
281         if ( lo->ldo_tls_keyfile &&
282                 !SSL_CTX_use_PrivateKey_file( ctx,
283                         lt->lt_keyfile, SSL_FILETYPE_PEM ) )
284         {
285                 Debug( LDAP_DEBUG_ANY,
286                         "TLS: could not use key file `%s'.\n",
287                         lo->ldo_tls_keyfile,0,0);
288                 tlso_report_error();
289                 return -1;
290         }
291
292         if ( lo->ldo_tls_dhfile ) {
293                 DH *dh = NULL;
294                 BIO *bio;
295                 dhplist *p;
296
297                 if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
298                         Debug( LDAP_DEBUG_ANY,
299                                 "TLS: could not use DH parameters file `%s'.\n",
300                                 lo->ldo_tls_dhfile,0,0);
301                         tlso_report_error();
302                         return -1;
303                 }
304                 while (( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
305                         p = LDAP_MALLOC( sizeof(dhplist) );
306                         if ( p != NULL ) {
307                                 p->keylength = DH_size( dh ) * 8;
308                                 p->param = dh;
309                                 p->next = tlso_dhparams;
310                                 tlso_dhparams = p;
311                         }
312                 }
313                 BIO_free( bio );
314         }
315
316         if ( tlso_opt_trace ) {
317                 SSL_CTX_set_info_callback( ctx, tlso_info_cb );
318         }
319
320         i = SSL_VERIFY_NONE;
321         if ( lo->ldo_tls_require_cert ) {
322                 i = SSL_VERIFY_PEER;
323                 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
324                          lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
325                         i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
326                 }
327         }
328
329         SSL_CTX_set_verify( ctx, i,
330                 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
331                 tlso_verify_ok : tlso_verify_cb );
332         SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
333         if ( lo->ldo_tls_dhfile ) {
334                 SSL_CTX_set_tmp_dh_callback( ctx, tlso_tmp_dh_cb );
335         }
336 #ifdef HAVE_OPENSSL_CRL
337         if ( lo->ldo_tls_crlcheck ) {
338                 X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
339                 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
340                         X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
341                 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
342                         X509_STORE_set_flags( x509_s, 
343                                         X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL  );
344                 }
345         }
346 #endif
347         return 0;
348 }
349
350 static tls_session *
351 tlso_session_new( tls_ctx *ctx, int is_server )
352 {
353         tlso_ctx *c = (tlso_ctx *)ctx;
354         return (tls_session *)SSL_new( c );
355 }
356
357 static int
358 tlso_session_connect( LDAP *ld, tls_session *sess )
359 {
360         tlso_session *s = (tlso_session *)sess;
361
362         /* Caller expects 0 = success, OpenSSL returns 1 = success */
363         return SSL_connect( s ) - 1;
364 }
365
366 static int
367 tlso_session_accept( tls_session *sess )
368 {
369         tlso_session *s = (tlso_session *)sess;
370
371         /* Caller expects 0 = success, OpenSSL returns 1 = success */
372         return SSL_accept( s ) - 1;
373 }
374
375 static int
376 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
377 {
378         tlso_session *s = (tlso_session *)sess;
379
380         /* 1 was subtracted above, offset it back now */
381         rc = SSL_get_error(s, rc+1);
382         if (rc == SSL_ERROR_WANT_READ) {
383                 sb->sb_trans_needs_read  = 1;
384                 return 1;
385
386         } else if (rc == SSL_ERROR_WANT_WRITE) {
387                 sb->sb_trans_needs_write = 1;
388                 return 1;
389
390         } else if (rc == SSL_ERROR_WANT_CONNECT) {
391                 return 1;
392         }
393         return 0;
394 }
395
396 static char *
397 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
398 {
399         char err[256] = "";
400         const char *certerr=NULL;
401         tlso_session *s = (tlso_session *)sess;
402
403         rc = ERR_peek_error();
404         if ( rc ) {
405                 ERR_error_string_n( rc, err, sizeof(err) );
406                 if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) && 
407                                 ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
408                         int certrc = SSL_get_verify_result(s);
409                         certerr = (char *)X509_verify_cert_error_string(certrc);
410                 }
411                 snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"", 
412                                 certerr ? certerr : "", certerr ?  ")" : "" );
413                 return buf;
414         }
415         return NULL;
416 }
417
418 static int
419 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
420 {
421         tlso_session *s = (tlso_session *)sess;
422         X509 *x;
423         X509_NAME *xn;
424
425         x = SSL_get_certificate( s );
426
427         if (!x) return LDAP_INVALID_CREDENTIALS;
428         
429         xn = X509_get_subject_name(x);
430         der_dn->bv_len = i2d_X509_NAME( xn, NULL );
431         der_dn->bv_val = xn->bytes->data;
432         /* Don't X509_free, the session is still using it */
433         return 0;
434 }
435
436 static X509 *
437 tlso_get_cert( SSL *s )
438 {
439         /* If peer cert was bad, treat as if no cert was given */
440         if (SSL_get_verify_result(s)) {
441                 return NULL;
442         }
443         return SSL_get_peer_certificate(s);
444 }
445
446 static int
447 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
448 {
449         tlso_session *s = (tlso_session *)sess;
450         X509 *x = tlso_get_cert( s );
451         X509_NAME *xn;
452
453         if ( !x )
454                 return LDAP_INVALID_CREDENTIALS;
455
456         xn = X509_get_subject_name(x);
457         der_dn->bv_len = i2d_X509_NAME( xn, NULL );
458         der_dn->bv_val = xn->bytes->data;
459         X509_free(x);
460         return 0;
461 }
462
463 /* what kind of hostname were we given? */
464 #define IS_DNS  0
465 #define IS_IP4  1
466 #define IS_IP6  2
467
468 static int
469 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
470 {
471         tlso_session *s = (tlso_session *)sess;
472         int i, ret = LDAP_LOCAL_ERROR;
473         X509 *x;
474         const char *name;
475         char *ptr;
476         int ntype = IS_DNS, nlen;
477 #ifdef LDAP_PF_INET6
478         struct in6_addr addr;
479 #else
480         struct in_addr addr;
481 #endif
482
483         if( ldap_int_hostname &&
484                 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
485         {
486                 name = ldap_int_hostname;
487         } else {
488                 name = name_in;
489         }
490         nlen = strlen(name);
491
492         x = tlso_get_cert(s);
493         if (!x) {
494                 Debug( LDAP_DEBUG_ANY,
495                         "TLS: unable to get peer certificate.\n",
496                         0, 0, 0 );
497                 /* If this was a fatal condition, things would have
498                  * aborted long before now.
499                  */
500                 return LDAP_SUCCESS;
501         }
502
503 #ifdef LDAP_PF_INET6
504         if (name[0] == '[' && strchr(name, ']')) {
505                 char *n2 = ldap_strdup(name+1);
506                 *strchr(n2, ']') = 0;
507                 if (inet_pton(AF_INET6, n2, &addr))
508                         ntype = IS_IP6;
509                 LDAP_FREE(n2);
510         } else 
511 #endif
512         if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
513                 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
514         }
515         
516         i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
517         if (i >= 0) {
518                 X509_EXTENSION *ex;
519                 STACK_OF(GENERAL_NAME) *alt;
520
521                 ex = X509_get_ext(x, i);
522                 alt = X509V3_EXT_d2i(ex);
523                 if (alt) {
524                         int n, len2 = 0;
525                         char *domain = NULL;
526                         GENERAL_NAME *gn;
527
528                         if (ntype == IS_DNS) {
529                                 domain = strchr(name, '.');
530                                 if (domain) {
531                                         len2 = nlen - (domain-name);
532                                 }
533                         }
534                         n = sk_GENERAL_NAME_num(alt);
535                         for (i=0; i<n; i++) {
536                                 char *sn;
537                                 int sl;
538                                 gn = sk_GENERAL_NAME_value(alt, i);
539                                 if (gn->type == GEN_DNS) {
540                                         if (ntype != IS_DNS) continue;
541
542                                         sn = (char *) ASN1_STRING_data(gn->d.ia5);
543                                         sl = ASN1_STRING_length(gn->d.ia5);
544
545                                         /* ignore empty */
546                                         if (sl == 0) continue;
547
548                                         /* Is this an exact match? */
549                                         if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
550                                                 break;
551                                         }
552
553                                         /* Is this a wildcard match? */
554                                         if (domain && (sn[0] == '*') && (sn[1] == '.') &&
555                                                 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
556                                         {
557                                                 break;
558                                         }
559
560                                 } else if (gn->type == GEN_IPADD) {
561                                         if (ntype == IS_DNS) continue;
562
563                                         sn = (char *) ASN1_STRING_data(gn->d.ia5);
564                                         sl = ASN1_STRING_length(gn->d.ia5);
565
566 #ifdef LDAP_PF_INET6
567                                         if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
568                                                 continue;
569                                         } else
570 #endif
571                                         if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
572                                                 continue;
573                                         }
574                                         if (!memcmp(sn, &addr, sl)) {
575                                                 break;
576                                         }
577                                 }
578                         }
579
580                         GENERAL_NAMES_free(alt);
581                         if (i < n) {    /* Found a match */
582                                 ret = LDAP_SUCCESS;
583                         }
584                 }
585         }
586
587         if (ret != LDAP_SUCCESS) {
588                 X509_NAME *xn;
589                 X509_NAME_ENTRY *ne;
590                 ASN1_OBJECT *obj;
591                 ASN1_STRING *cn = NULL;
592                 int navas;
593
594                 /* find the last CN */
595                 obj = OBJ_nid2obj( NID_commonName );
596                 if ( !obj ) goto no_cn; /* should never happen */
597
598                 xn = X509_get_subject_name(x);
599                 navas = X509_NAME_entry_count( xn );
600                 for ( i=navas-1; i>=0; i-- ) {
601                         ne = X509_NAME_get_entry( xn, i );
602                         if ( !OBJ_cmp( ne->object, obj )) {
603                                 cn = X509_NAME_ENTRY_get_data( ne );
604                                 break;
605                         }
606                 }
607
608                 if( !cn )
609                 {
610 no_cn:
611                         Debug( LDAP_DEBUG_ANY,
612                                 "TLS: unable to get common name from peer certificate.\n",
613                                 0, 0, 0 );
614                         ret = LDAP_CONNECT_ERROR;
615                         if ( ld->ld_error ) {
616                                 LDAP_FREE( ld->ld_error );
617                         }
618                         ld->ld_error = LDAP_STRDUP(
619                                 _("TLS: unable to get CN from peer certificate"));
620
621                 } else if ( cn->length == nlen &&
622                         strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
623                         ret = LDAP_SUCCESS;
624
625                 } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
626                         char *domain = strchr(name, '.');
627                         if( domain ) {
628                                 int dlen;
629
630                                 dlen = nlen - (domain-name);
631
632                                 /* Is this a wildcard match? */
633                                 if ((dlen == cn->length-1) &&
634                                         !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
635                                         ret = LDAP_SUCCESS;
636                                 }
637                         }
638                 }
639
640                 if( ret == LDAP_LOCAL_ERROR ) {
641                         Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
642                                 "common name in certificate (%.*s).\n", 
643                                 name, cn->length, cn->data );
644                         ret = LDAP_CONNECT_ERROR;
645                         if ( ld->ld_error ) {
646                                 LDAP_FREE( ld->ld_error );
647                         }
648                         ld->ld_error = LDAP_STRDUP(
649                                 _("TLS: hostname does not match CN in peer certificate"));
650                 }
651         }
652         X509_free(x);
653         return ret;
654 }
655
656 static int
657 tlso_session_strength( tls_session *sess )
658 {
659         tlso_session *s = (tlso_session *)sess;
660         SSL_CIPHER *c;
661
662         c = SSL_get_current_cipher(s);
663         return SSL_CIPHER_get_bits(c, NULL);
664 }
665
666 /*
667  * TLS support for LBER Sockbufs
668  */
669
670 struct tls_data {
671         tlso_session            *session;
672         Sockbuf_IO_Desc         *sbiod;
673 };
674
675 static int
676 tlso_bio_create( BIO *b ) {
677         b->init = 1;
678         b->num = 0;
679         b->ptr = NULL;
680         b->flags = 0;
681         return 1;
682 }
683
684 static int
685 tlso_bio_destroy( BIO *b )
686 {
687         if ( b == NULL ) return 0;
688
689         b->ptr = NULL;          /* sb_tls_remove() will free it */
690         b->init = 0;
691         b->flags = 0;
692         return 1;
693 }
694
695 static int
696 tlso_bio_read( BIO *b, char *buf, int len )
697 {
698         struct tls_data         *p;
699         int                     ret;
700                 
701         if ( buf == NULL || len <= 0 ) return 0;
702
703         p = (struct tls_data *)b->ptr;
704
705         if ( p == NULL || p->sbiod == NULL ) {
706                 return 0;
707         }
708
709         ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
710
711         BIO_clear_retry_flags( b );
712         if ( ret < 0 ) {
713                 int err = sock_errno();
714                 if ( err == EAGAIN || err == EWOULDBLOCK ) {
715                         BIO_set_retry_read( b );
716                 }
717         }
718
719         return ret;
720 }
721
722 static int
723 tlso_bio_write( BIO *b, const char *buf, int len )
724 {
725         struct tls_data         *p;
726         int                     ret;
727         
728         if ( buf == NULL || len <= 0 ) return 0;
729         
730         p = (struct tls_data *)b->ptr;
731
732         if ( p == NULL || p->sbiod == NULL ) {
733                 return 0;
734         }
735
736         ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
737
738         BIO_clear_retry_flags( b );
739         if ( ret < 0 ) {
740                 int err = sock_errno();
741                 if ( err == EAGAIN || err == EWOULDBLOCK ) {
742                         BIO_set_retry_write( b );
743                 }
744         }
745
746         return ret;
747 }
748
749 static long
750 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
751 {
752         if ( cmd == BIO_CTRL_FLUSH ) {
753                 /* The OpenSSL library needs this */
754                 return 1;
755         }
756         return 0;
757 }
758
759 static int
760 tlso_bio_gets( BIO *b, char *buf, int len )
761 {
762         return -1;
763 }
764
765 static int
766 tlso_bio_puts( BIO *b, const char *str )
767 {
768         return tlso_bio_write( b, str, strlen( str ) );
769 }
770         
771 static BIO_METHOD tlso_bio_method =
772 {
773         ( 100 | 0x400 ),                /* it's a source/sink BIO */
774         "sockbuf glue",
775         tlso_bio_write,
776         tlso_bio_read,
777         tlso_bio_puts,
778         tlso_bio_gets,
779         tlso_bio_ctrl,
780         tlso_bio_create,
781         tlso_bio_destroy
782 };
783
784 static int
785 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
786 {
787         struct tls_data         *p;
788         BIO                     *bio;
789
790         assert( sbiod != NULL );
791
792         p = LBER_MALLOC( sizeof( *p ) );
793         if ( p == NULL ) {
794                 return -1;
795         }
796         
797         p->session = arg;
798         p->sbiod = sbiod;
799         bio = BIO_new( &tlso_bio_method );
800         bio->ptr = (void *)p;
801         SSL_set_bio( p->session, bio, bio );
802         sbiod->sbiod_pvt = p;
803         return 0;
804 }
805
806 static int
807 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
808 {
809         struct tls_data         *p;
810         
811         assert( sbiod != NULL );
812         assert( sbiod->sbiod_pvt != NULL );
813
814         p = (struct tls_data *)sbiod->sbiod_pvt;
815         SSL_free( p->session );
816         LBER_FREE( sbiod->sbiod_pvt );
817         sbiod->sbiod_pvt = NULL;
818         return 0;
819 }
820
821 static int
822 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
823 {
824         struct tls_data         *p;
825         
826         assert( sbiod != NULL );
827         assert( sbiod->sbiod_pvt != NULL );
828
829         p = (struct tls_data *)sbiod->sbiod_pvt;
830         SSL_shutdown( p->session );
831         return 0;
832 }
833
834 static int
835 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
836 {
837         struct tls_data         *p;
838         
839         assert( sbiod != NULL );
840         assert( sbiod->sbiod_pvt != NULL );
841
842         p = (struct tls_data *)sbiod->sbiod_pvt;
843         
844         if ( opt == LBER_SB_OPT_GET_SSL ) {
845                 *((tlso_session **)arg) = p->session;
846                 return 1;
847
848         } else if ( opt == LBER_SB_OPT_DATA_READY ) {
849                 if( SSL_pending( p->session ) > 0 ) {
850                         return 1;
851                 }
852         }
853         
854         return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
855 }
856
857 static ber_slen_t
858 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
859 {
860         struct tls_data         *p;
861         ber_slen_t              ret;
862         int                     err;
863
864         assert( sbiod != NULL );
865         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
866
867         p = (struct tls_data *)sbiod->sbiod_pvt;
868
869         ret = SSL_read( p->session, (char *)buf, len );
870 #ifdef HAVE_WINSOCK
871         errno = WSAGetLastError();
872 #endif
873         err = SSL_get_error( p->session, ret );
874         if (err == SSL_ERROR_WANT_READ ) {
875                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
876                 sock_errset(EWOULDBLOCK);
877         }
878         else
879                 sbiod->sbiod_sb->sb_trans_needs_read = 0;
880         return ret;
881 }
882
883 static ber_slen_t
884 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
885 {
886         struct tls_data         *p;
887         ber_slen_t              ret;
888         int                     err;
889
890         assert( sbiod != NULL );
891         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
892
893         p = (struct tls_data *)sbiod->sbiod_pvt;
894
895         ret = SSL_write( p->session, (char *)buf, len );
896 #ifdef HAVE_WINSOCK
897         errno = WSAGetLastError();
898 #endif
899         err = SSL_get_error( p->session, ret );
900         if (err == SSL_ERROR_WANT_WRITE ) {
901                 sbiod->sbiod_sb->sb_trans_needs_write = 1;
902                 sock_errset(EWOULDBLOCK);
903
904         } else {
905                 sbiod->sbiod_sb->sb_trans_needs_write = 0;
906         }
907         return ret;
908 }
909
910 static Sockbuf_IO tlso_sbio =
911 {
912         tlso_sb_setup,          /* sbi_setup */
913         tlso_sb_remove,         /* sbi_remove */
914         tlso_sb_ctrl,           /* sbi_ctrl */
915         tlso_sb_read,           /* sbi_read */
916         tlso_sb_write,          /* sbi_write */
917         tlso_sb_close           /* sbi_close */
918 };
919
920 /* Derived from openssl/apps/s_cb.c */
921 static void
922 tlso_info_cb( const SSL *ssl, int where, int ret )
923 {
924         int w;
925         char *op;
926         char *state = (char *) SSL_state_string_long( (SSL *)ssl );
927
928         w = where & ~SSL_ST_MASK;
929         if ( w & SSL_ST_CONNECT ) {
930                 op = "SSL_connect";
931         } else if ( w & SSL_ST_ACCEPT ) {
932                 op = "SSL_accept";
933         } else {
934                 op = "undefined";
935         }
936
937 #ifdef HAVE_EBCDIC
938         if ( state ) {
939                 state = LDAP_STRDUP( state );
940                 __etoa( state );
941         }
942 #endif
943         if ( where & SSL_CB_LOOP ) {
944                 Debug( LDAP_DEBUG_TRACE,
945                            "TLS trace: %s:%s\n",
946                            op, state, 0 );
947
948         } else if ( where & SSL_CB_ALERT ) {
949                 char *atype = (char *) SSL_alert_type_string_long( ret );
950                 char *adesc = (char *) SSL_alert_desc_string_long( ret );
951                 op = ( where & SSL_CB_READ ) ? "read" : "write";
952 #ifdef HAVE_EBCDIC
953                 if ( atype ) {
954                         atype = LDAP_STRDUP( atype );
955                         __etoa( atype );
956                 }
957                 if ( adesc ) {
958                         adesc = LDAP_STRDUP( adesc );
959                         __etoa( adesc );
960                 }
961 #endif
962                 Debug( LDAP_DEBUG_TRACE,
963                            "TLS trace: SSL3 alert %s:%s:%s\n",
964                            op, atype, adesc );
965 #ifdef HAVE_EBCDIC
966                 if ( atype ) LDAP_FREE( atype );
967                 if ( adesc ) LDAP_FREE( adesc );
968 #endif
969         } else if ( where & SSL_CB_EXIT ) {
970                 if ( ret == 0 ) {
971                         Debug( LDAP_DEBUG_TRACE,
972                                    "TLS trace: %s:failed in %s\n",
973                                    op, state, 0 );
974                 } else if ( ret < 0 ) {
975                         Debug( LDAP_DEBUG_TRACE,
976                                    "TLS trace: %s:error in %s\n",
977                                    op, state, 0 );
978                 }
979         }
980 #ifdef HAVE_EBCDIC
981         if ( state ) LDAP_FREE( state );
982 #endif
983 }
984
985 static int
986 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
987 {
988         X509 *cert;
989         int errnum;
990         int errdepth;
991         X509_NAME *subject;
992         X509_NAME *issuer;
993         char *sname;
994         char *iname;
995         char *certerr = NULL;
996
997         cert = X509_STORE_CTX_get_current_cert( ctx );
998         errnum = X509_STORE_CTX_get_error( ctx );
999         errdepth = X509_STORE_CTX_get_error_depth( ctx );
1000
1001         /*
1002          * X509_get_*_name return pointers to the internal copies of
1003          * those things requested.  So do not free them.
1004          */
1005         subject = X509_get_subject_name( cert );
1006         issuer = X509_get_issuer_name( cert );
1007         /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1008         sname = X509_NAME_oneline( subject, NULL, 0 );
1009         iname = X509_NAME_oneline( issuer, NULL, 0 );
1010         if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1011 #ifdef HAVE_EBCDIC
1012         if ( sname ) __etoa( sname );
1013         if ( iname ) __etoa( iname );
1014         if ( certerr ) {
1015                 certerr = LDAP_STRDUP( certerr );
1016                 __etoa( certerr );
1017         }
1018 #endif
1019         Debug( LDAP_DEBUG_TRACE,
1020                    "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1021                    errdepth, errnum,
1022                    sname ? sname : "-unknown-" );
1023         Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1024         if ( !ok ) {
1025                 Debug( LDAP_DEBUG_ANY,
1026                         "TLS certificate verification: Error, %s\n",
1027                         certerr, 0, 0 );
1028         }
1029         if ( sname )
1030                 CRYPTO_free ( sname );
1031         if ( iname )
1032                 CRYPTO_free ( iname );
1033 #ifdef HAVE_EBCDIC
1034         if ( certerr ) LDAP_FREE( certerr );
1035 #endif
1036         return ok;
1037 }
1038
1039 static int
1040 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1041 {
1042         (void) tlso_verify_cb( ok, ctx );
1043         return 1;
1044 }
1045
1046 /* Inspired by ERR_print_errors in OpenSSL */
1047 static void
1048 tlso_report_error( void )
1049 {
1050         unsigned long l;
1051         char buf[200];
1052         const char *file;
1053         int line;
1054
1055         while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1056                 ERR_error_string_n( l, buf, sizeof( buf ) );
1057 #ifdef HAVE_EBCDIC
1058                 if ( file ) {
1059                         file = LDAP_STRDUP( file );
1060                         __etoa( (char *)file );
1061                 }
1062                 __etoa( buf );
1063 #endif
1064                 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1065                         buf, file, line );
1066 #ifdef HAVE_EBCDIC
1067                 if ( file ) LDAP_FREE( (void *)file );
1068 #endif
1069         }
1070 }
1071
1072 static RSA *
1073 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1074 {
1075         RSA *tmp_rsa;
1076         /* FIXME:  Pregenerate the key on startup */
1077         /* FIXME:  Who frees the key? */
1078 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1079         BIGNUM *bn = BN_new();
1080         tmp_rsa = NULL;
1081         if ( bn ) {
1082                 if ( BN_set_word( bn, RSA_F4 )) {
1083                         tmp_rsa = RSA_new();
1084                         if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1085                                 RSA_free( tmp_rsa );
1086                                 tmp_rsa = NULL;
1087                         }
1088                 }
1089                 BN_free( bn );
1090         }
1091 #else
1092         tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1093 #endif
1094
1095         if ( !tmp_rsa ) {
1096                 Debug( LDAP_DEBUG_ANY,
1097                         "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1098                         key_length, is_export ? "export" : "domestic", 0 );
1099         }
1100         return tmp_rsa;
1101 }
1102
1103 static int
1104 tlso_seed_PRNG( const char *randfile )
1105 {
1106 #ifndef URANDOM_DEVICE
1107         /* no /dev/urandom (or equiv) */
1108         long total=0;
1109         char buffer[MAXPATHLEN];
1110
1111         if (randfile == NULL) {
1112                 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1113                  * If $HOME is not set or buffer too small to hold the pathname,
1114                  * an error occurs.     - From RAND_file_name() man page.
1115                  * The fact is that when $HOME is NULL, .rnd is used.
1116                  */
1117                 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1118
1119         } else if (RAND_egd(randfile) > 0) {
1120                 /* EGD socket */
1121                 return 0;
1122         }
1123
1124         if (randfile == NULL) {
1125                 Debug( LDAP_DEBUG_ANY,
1126                         "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1127                         0, 0, 0);
1128                 return -1;
1129         }
1130
1131         total = RAND_load_file(randfile, -1);
1132
1133         if (RAND_status() == 0) {
1134                 Debug( LDAP_DEBUG_ANY,
1135                         "TLS: PRNG not been seeded with enough data\n",
1136                         0, 0, 0);
1137                 return -1;
1138         }
1139
1140         /* assume if there was enough bits to seed that it's okay
1141          * to write derived bits to the file
1142          */
1143         RAND_write_file(randfile);
1144
1145 #endif
1146
1147         return 0;
1148 }
1149
1150 struct dhinfo {
1151         int keylength;
1152         const char *pem;
1153         size_t size;
1154 };
1155
1156
1157 /* From the OpenSSL 0.9.7 distro */
1158 static const char tlso_dhpem512[] =
1159 "-----BEGIN DH PARAMETERS-----\n\
1160 MEYCQQDaWDwW2YUiidDkr3VvTMqS3UvlM7gE+w/tlO+cikQD7VdGUNNpmdsp13Yn\n\
1161 a6LT1BLiGPTdHghM9tgAPnxHdOgzAgEC\n\
1162 -----END DH PARAMETERS-----\n";
1163
1164 static const char tlso_dhpem1024[] =
1165 "-----BEGIN DH PARAMETERS-----\n\
1166 MIGHAoGBAJf2QmHKtQXdKCjhPx1ottPb0PMTBH9A6FbaWMsTuKG/K3g6TG1Z1fkq\n\
1167 /Gz/PWk/eLI9TzFgqVAuPvr3q14a1aZeVUMTgo2oO5/y2UHe6VaJ+trqCTat3xlx\n\
1168 /mNbIK9HA2RgPC3gWfVLZQrY+gz3ASHHR5nXWHEyvpuZm7m3h+irAgEC\n\
1169 -----END DH PARAMETERS-----\n";
1170
1171 static const char tlso_dhpem2048[] =
1172 "-----BEGIN DH PARAMETERS-----\n\
1173 MIIBCAKCAQEA7ZKJNYJFVcs7+6J2WmkEYb8h86tT0s0h2v94GRFS8Q7B4lW9aG9o\n\
1174 AFO5Imov5Jo0H2XMWTKKvbHbSe3fpxJmw/0hBHAY8H/W91hRGXKCeyKpNBgdL8sh\n\
1175 z22SrkO2qCnHJ6PLAMXy5fsKpFmFor2tRfCzrfnggTXu2YOzzK7q62bmqVdmufEo\n\
1176 pT8igNcLpvZxk5uBDvhakObMym9mX3rAEBoe8PwttggMYiiw7NuJKO4MqD1llGkW\n\
1177 aVM8U2ATsCun1IKHrRxynkE1/MJ86VHeYYX8GZt2YA8z+GuzylIOKcMH6JAWzMwA\n\
1178 Gbatw6QwizOhr9iMjZ0B26TE3X8LvW84wwIBAg==\n\
1179 -----END DH PARAMETERS-----\n";
1180
1181 static const char tlso_dhpem4096[] =
1182 "-----BEGIN DH PARAMETERS-----\n\
1183 MIICCAKCAgEA/urRnb6vkPYc/KEGXWnbCIOaKitq7ySIq9dTH7s+Ri59zs77zty7\n\
1184 vfVlSe6VFTBWgYjD2XKUFmtqq6CqXMhVX5ElUDoYDpAyTH85xqNFLzFC7nKrff/H\n\
1185 TFKNttp22cZE9V0IPpzedPfnQkE7aUdmF9JnDyv21Z/818O93u1B4r0szdnmEvEF\n\
1186 bKuIxEHX+bp0ZR7RqE1AeifXGJX3d6tsd2PMAObxwwsv55RGkn50vHO4QxtTARr1\n\
1187 rRUV5j3B3oPMgC7Offxx+98Xn45B1/G0Prp11anDsR1PGwtaCYipqsvMwQUSJtyE\n\
1188 EOQWk+yFkeMe4vWv367eEi0Sd/wnC+TSXBE3pYvpYerJ8n1MceI5GQTdarJ77OW9\n\
1189 bGTHmxRsLSCM1jpLdPja5jjb4siAa6EHc4qN9c/iFKS3PQPJEnX7pXKBRs5f7AF3\n\
1190 W3RIGt+G9IVNZfXaS7Z/iCpgzgvKCs0VeqN38QsJGtC1aIkwOeyjPNy2G6jJ4yqH\n\
1191 ovXYt/0mc00vCWeSNS1wren0pR2EiLxX0ypjjgsU1mk/Z3b/+zVf7fZSIB+nDLjb\n\
1192 NPtUlJCVGnAeBK1J1nG3TQicqowOXoM6ISkdaXj5GPJdXHab2+S7cqhKGv5qC7rR\n\
1193 jT6sx7RUr0CNTxzLI7muV2/a4tGmj0PSdXQdsZ7tw7gbXlaWT1+MM2MCAQI=\n\
1194 -----END DH PARAMETERS-----\n";
1195
1196 static const struct dhinfo tlso_dhpem[] = {
1197         { 512, tlso_dhpem512, sizeof(tlso_dhpem512) },
1198         { 1024, tlso_dhpem1024, sizeof(tlso_dhpem1024) },
1199         { 2048, tlso_dhpem2048, sizeof(tlso_dhpem2048) },
1200         { 4096, tlso_dhpem4096, sizeof(tlso_dhpem4096) },
1201         { 0, NULL, 0 }
1202 };
1203
1204 static DH *
1205 tlso_tmp_dh_cb( SSL *ssl, int is_export, int key_length )
1206 {
1207         struct dhplist *p = NULL;
1208         BIO *b = NULL;
1209         DH *dh = NULL;
1210         int i;
1211
1212         /* Do we have params of this length already? */
1213         LDAP_MUTEX_LOCK( &tlso_dh_mutex );
1214         for ( p = tlso_dhparams; p; p=p->next ) {
1215                 if ( p->keylength == key_length ) {
1216                         LDAP_MUTEX_UNLOCK( &tlso_dh_mutex );
1217                         return p->param;
1218                 }
1219         }
1220
1221         /* No - check for hardcoded params */
1222
1223         for (i=0; tlso_dhpem[i].keylength; i++) {
1224                 if ( tlso_dhpem[i].keylength == key_length ) {
1225                         b = BIO_new_mem_buf( (char *)tlso_dhpem[i].pem, tlso_dhpem[i].size );
1226                         break;
1227                 }
1228         }
1229
1230         if ( b ) {
1231                 dh = PEM_read_bio_DHparams( b, NULL, NULL, NULL );
1232                 BIO_free( b );
1233         }
1234
1235         /* Generating on the fly is expensive/slow... */
1236         if ( !dh ) {
1237                 dh = DH_generate_parameters( key_length, DH_GENERATOR_2, NULL, NULL );
1238         }
1239         if ( dh ) {
1240                 p = LDAP_MALLOC( sizeof(struct dhplist) );
1241                 if ( p != NULL ) {
1242                         p->keylength = key_length;
1243                         p->param = dh;
1244                         p->next = tlso_dhparams;
1245                         tlso_dhparams = p;
1246                 }
1247         }
1248
1249         LDAP_MUTEX_UNLOCK( &tlso_dh_mutex );
1250         return dh;
1251 }
1252
1253 tls_impl ldap_int_tls_impl = {
1254         "OpenSSL",
1255
1256         tlso_init,
1257         tlso_destroy,
1258
1259         tlso_ctx_new,
1260         tlso_ctx_ref,
1261         tlso_ctx_free,
1262         tlso_ctx_init,
1263
1264         tlso_session_new,
1265         tlso_session_connect,
1266         tlso_session_accept,
1267         tlso_session_upflags,
1268         tlso_session_errmsg,
1269         tlso_session_my_dn,
1270         tlso_session_peer_dn,
1271         tlso_session_chkhost,
1272         tlso_session_strength,
1273
1274         &tlso_sbio,
1275
1276 #ifdef LDAP_R_COMPILE
1277         tlso_thr_init,
1278 #else
1279         NULL,
1280 #endif
1281
1282         0
1283 };
1284
1285 #endif /* HAVE_OPENSSL */