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