]> git.sur5r.net Git - openldap/blob - libraries/libldap/tls.c
expose ldap_tls_inplace()
[openldap] / libraries / libldap / tls.c
1 /* tls.c - Handle tls/ssl using SSLeay or OpenSSL. */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 1998-2005 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
17 #include "portable.h"
18 #include "ldap_config.h"
19
20 #include <stdio.h>
21
22 #include <ac/stdlib.h>
23 #include <ac/errno.h>
24 #include <ac/socket.h>
25 #include <ac/string.h>
26 #include <ac/ctype.h>
27 #include <ac/time.h>
28 #include <ac/unistd.h>
29 #include <ac/param.h>
30 #include <ac/dirent.h>
31
32 #include "ldap-int.h"
33
34 #ifdef HAVE_TLS
35
36 #ifdef LDAP_R_COMPILE
37 #include <ldap_pvt_thread.h>
38 #endif
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 static int  tls_opt_trace = 1;
51 static char *tls_opt_certfile = NULL;
52 static char *tls_opt_keyfile = NULL;
53 static char *tls_opt_cacertfile = NULL;
54 static char *tls_opt_cacertdir = NULL;
55 static int  tls_opt_require_cert = LDAP_OPT_X_TLS_DEMAND;
56 #ifdef HAVE_OPENSSL_CRL
57 static int  tls_opt_crlcheck = LDAP_OPT_X_TLS_CRL_NONE;
58 #endif
59 static char *tls_opt_ciphersuite = NULL;
60 static char *tls_opt_randfile = NULL;
61
62 #define HAS_TLS( sb )   ber_sockbuf_ctrl( sb, LBER_SB_OPT_HAS_IO, \
63                                 (void *)&sb_tls_sbio )
64
65 static void tls_report_error( void );
66
67 static void tls_info_cb( const SSL *ssl, int where, int ret );
68 static int tls_verify_cb( int ok, X509_STORE_CTX *ctx );
69 static int tls_verify_ok( int ok, X509_STORE_CTX *ctx );
70 static RSA * tls_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
71 static STACK_OF(X509_NAME) * get_ca_list( char * bundle, char * dir );
72
73 #if 0   /* Currently this is not used by anyone */
74 static DH * tls_tmp_dh_cb( SSL *ssl, int is_export, int key_length );
75 #endif
76
77 static SSL_CTX *tls_def_ctx = NULL;
78
79 static int tls_seed_PRNG( const char *randfile );
80
81 #ifdef LDAP_R_COMPILE
82 /*
83  * provide mutexes for the SSLeay library.
84  */
85 static ldap_pvt_thread_mutex_t  tls_mutexes[CRYPTO_NUM_LOCKS];
86
87 static void tls_locking_cb( int mode, int type, const char *file, int line )
88 {
89         if ( mode & CRYPTO_LOCK ) {
90                 ldap_pvt_thread_mutex_lock( &tls_mutexes[type] );
91         } else {
92                 ldap_pvt_thread_mutex_unlock( &tls_mutexes[type] );
93         }
94 }
95
96 /*
97  * an extra mutex for the default ctx.
98  */
99
100 static ldap_pvt_thread_mutex_t tls_def_ctx_mutex;
101
102 static void tls_init_threads( void )
103 {
104         int i;
105
106         for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
107                 ldap_pvt_thread_mutex_init( &tls_mutexes[i] );
108         }
109         CRYPTO_set_locking_callback( tls_locking_cb );
110         /* FIXME: the thread id should be added somehow... */
111
112         ldap_pvt_thread_mutex_init( &tls_def_ctx_mutex );
113 }
114 #endif /* LDAP_R_COMPILE */
115
116 /*
117  * Tear down the TLS subsystem. Should only be called once.
118  */
119 void
120 ldap_pvt_tls_destroy( void )
121 {
122         SSL_CTX_free(tls_def_ctx);
123         tls_def_ctx = NULL;
124
125         EVP_cleanup();
126         ERR_remove_state(0);
127         ERR_free_strings();
128
129         if ( tls_opt_certfile ) {
130                 LDAP_FREE( tls_opt_certfile );
131                 tls_opt_certfile = NULL;
132         }
133         if ( tls_opt_keyfile ) {
134                 LDAP_FREE( tls_opt_keyfile );
135                 tls_opt_keyfile = NULL;
136         }
137         if ( tls_opt_cacertfile ) {
138                 LDAP_FREE( tls_opt_cacertfile );
139                 tls_opt_cacertfile = NULL;
140         }
141         if ( tls_opt_cacertdir ) {
142                 LDAP_FREE( tls_opt_cacertdir );
143                 tls_opt_cacertdir = NULL;
144         }
145         if ( tls_opt_ciphersuite ) {
146                 LDAP_FREE( tls_opt_ciphersuite );
147                 tls_opt_ciphersuite = NULL;
148         }
149         if ( tls_opt_randfile ) {
150                 LDAP_FREE( tls_opt_randfile );
151                 tls_opt_randfile = NULL;
152         }
153 }
154
155 /*
156  * Initialize TLS subsystem. Should be called only once.
157  */
158 int
159 ldap_pvt_tls_init( void )
160 {
161         static int tls_initialized = 0;
162
163         if ( tls_initialized++ ) return 0;
164
165 #ifdef HAVE_EBCDIC
166         {
167                 char *file = LDAP_STRDUP( tls_opt_randfile );
168                 if ( file ) __atoe( file );
169                 (void) tls_seed_PRNG( file );
170                 LDAP_FREE( file );
171         }
172 #else
173         (void) tls_seed_PRNG( tls_opt_randfile );
174 #endif
175
176 #ifdef LDAP_R_COMPILE
177         tls_init_threads();
178 #endif
179
180         SSL_load_error_strings();
181         SSLeay_add_ssl_algorithms();
182
183         /* FIXME: mod_ssl does this */
184         X509V3_add_standard_extensions();
185         return 0;
186 }
187
188 /*
189  * initialize the default context
190  */
191 int
192 ldap_pvt_tls_init_def_ctx( void )
193 {
194         STACK_OF(X509_NAME) *calist;
195         int rc = 0;
196         char *ciphersuite = tls_opt_ciphersuite;
197         char *cacertfile = tls_opt_cacertfile;
198         char *cacertdir = tls_opt_cacertdir;
199         char *certfile = tls_opt_certfile;
200         char *keyfile = tls_opt_keyfile;
201
202 #ifdef HAVE_EBCDIC
203         /* This ASCII/EBCDIC handling is a real pain! */
204         if ( ciphersuite ) {
205                 ciphersuite = LDAP_STRDUP( ciphersuite );
206                 __atoe( ciphersuite );
207         }
208         if ( cacertfile ) {
209                 cacertfile = LDAP_STRDUP( cacertfile );
210                 __atoe( cacertfile );
211         }
212         if ( cacertdir ) {
213                 cacertdir = LDAP_STRDUP( cacertdir );
214                 __atoe( cacertdir );
215         }
216         if ( certfile ) {
217                 certfile = LDAP_STRDUP( certfile );
218                 __atoe( certfile );
219         }
220         if ( keyfile ) {
221                 keyfile = LDAP_STRDUP( keyfile );
222                 __atoe( keyfile );
223         }
224 #endif
225
226 #ifdef LDAP_R_COMPILE
227         ldap_pvt_thread_mutex_lock( &tls_def_ctx_mutex );
228 #endif
229         if ( tls_def_ctx == NULL ) {
230                 int i;
231                 tls_def_ctx = SSL_CTX_new( SSLv23_method() );
232                 if ( tls_def_ctx == NULL ) {
233                         Debug( LDAP_DEBUG_ANY,
234                            "TLS: could not allocate default ctx (%lu).\n",
235                                 ERR_peek_error(),0,0);
236                         rc = -1;
237                         goto error_exit;
238                 }
239
240                 SSL_CTX_set_session_id_context( tls_def_ctx,
241                         (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
242
243                 if ( tls_opt_ciphersuite &&
244                         !SSL_CTX_set_cipher_list( tls_def_ctx, ciphersuite ) )
245                 {
246                         Debug( LDAP_DEBUG_ANY,
247                                    "TLS: could not set cipher list %s.\n",
248                                    tls_opt_ciphersuite, 0, 0 );
249                         tls_report_error();
250                         rc = -1;
251                         goto error_exit;
252                 }
253
254                 if (tls_opt_cacertfile != NULL || tls_opt_cacertdir != NULL) {
255                         if ( !SSL_CTX_load_verify_locations( tls_def_ctx,
256                                         cacertfile, cacertdir ) ||
257                                 !SSL_CTX_set_default_verify_paths( tls_def_ctx ) )
258                         {
259                                 Debug( LDAP_DEBUG_ANY, "TLS: "
260                                         "could not load verify locations (file:`%s',dir:`%s').\n",
261                                         tls_opt_cacertfile ? tls_opt_cacertfile : "",
262                                         tls_opt_cacertdir ? tls_opt_cacertdir : "",
263                                         0 );
264                                 tls_report_error();
265                                 rc = -1;
266                                 goto error_exit;
267                         }
268
269                         calist = get_ca_list( cacertfile, cacertdir );
270                         if ( !calist ) {
271                                 Debug( LDAP_DEBUG_ANY, "TLS: "
272                                         "could not load client CA list (file:`%s',dir:`%s').\n",
273                                         tls_opt_cacertfile ? tls_opt_cacertfile : "",
274                                         tls_opt_cacertdir ? tls_opt_cacertdir : "",
275                                         0 );
276                                 tls_report_error();
277                                 rc = -1;
278                                 goto error_exit;
279                         }
280
281                         SSL_CTX_set_client_CA_list( tls_def_ctx, calist );
282                 }
283
284                 if ( tls_opt_keyfile &&
285                         !SSL_CTX_use_PrivateKey_file( tls_def_ctx,
286                                 keyfile, SSL_FILETYPE_PEM ) )
287                 {
288                         Debug( LDAP_DEBUG_ANY,
289                                 "TLS: could not use key file `%s'.\n",
290                                 tls_opt_keyfile,0,0);
291                         tls_report_error();
292                         rc = -1;
293                         goto error_exit;
294                 }
295
296                 if ( tls_opt_certfile &&
297                         !SSL_CTX_use_certificate_file( tls_def_ctx,
298                                 certfile, SSL_FILETYPE_PEM ) )
299                 {
300                         Debug( LDAP_DEBUG_ANY,
301                                 "TLS: could not use certificate `%s'.\n",
302                                 tls_opt_certfile,0,0);
303                         tls_report_error();
304                         rc = -1;
305                         goto error_exit;
306                 }
307
308                 if ( ( tls_opt_certfile || tls_opt_keyfile ) &&
309                         !SSL_CTX_check_private_key( tls_def_ctx ) )
310                 {
311                         Debug( LDAP_DEBUG_ANY,
312                                 "TLS: private key mismatch.\n",
313                                 0,0,0);
314                         tls_report_error();
315                         rc = -1;
316                         goto error_exit;
317                 }
318
319                 if ( tls_opt_trace ) {
320                         SSL_CTX_set_info_callback( tls_def_ctx, tls_info_cb );
321                 }
322
323                 i = SSL_VERIFY_NONE;
324                 if ( tls_opt_require_cert ) {
325                         i = SSL_VERIFY_PEER;
326                         if ( tls_opt_require_cert == LDAP_OPT_X_TLS_DEMAND ||
327                                  tls_opt_require_cert == LDAP_OPT_X_TLS_HARD ) {
328                                 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
329                         }
330                 }
331
332                 SSL_CTX_set_verify( tls_def_ctx, i,
333                         tls_opt_require_cert == LDAP_OPT_X_TLS_ALLOW ?
334                         tls_verify_ok : tls_verify_cb );
335                 SSL_CTX_set_tmp_rsa_callback( tls_def_ctx, tls_tmp_rsa_cb );
336                 /* SSL_CTX_set_tmp_dh_callback( tls_def_ctx, tls_tmp_dh_cb ); */
337 #ifdef HAVE_OPENSSL_CRL
338                 if ( tls_opt_crlcheck ) {
339                         X509_STORE *x509_s = SSL_CTX_get_cert_store( tls_def_ctx );
340                         if ( tls_opt_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
341                                 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
342                         } else if ( tls_opt_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
343                                 X509_STORE_set_flags( x509_s, 
344                                                 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL  );
345                         }
346                 }
347 #endif
348         }
349 error_exit:
350         if ( rc == -1 && tls_def_ctx != NULL ) {
351                 SSL_CTX_free( tls_def_ctx );
352                 tls_def_ctx = NULL;
353         }
354 #ifdef HAVE_EBCDIC
355         LDAP_FREE( ciphersuite );
356         LDAP_FREE( cacertfile );
357         LDAP_FREE( cacertdir );
358         LDAP_FREE( certfile );
359         LDAP_FREE( keyfile );
360 #endif
361 #ifdef LDAP_R_COMPILE
362         ldap_pvt_thread_mutex_unlock( &tls_def_ctx_mutex );
363 #endif
364         return rc;
365 }
366
367 static STACK_OF(X509_NAME) *
368 get_ca_list( char * bundle, char * dir )
369 {
370         STACK_OF(X509_NAME) *ca_list = NULL;
371
372         if ( bundle ) {
373                 ca_list = SSL_load_client_CA_file( bundle );
374         }
375 #if defined(HAVE_DIRENT_H) || defined(dirent)
376         if ( dir ) {
377                 int freeit = 0;
378
379                 if ( !ca_list ) {
380                         ca_list = sk_X509_NAME_new_null();
381                         freeit = 1;
382                 }
383                 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
384                         freeit ) {
385                         sk_X509_NAME_free( ca_list );
386                         ca_list = NULL;
387                 }
388         }
389 #endif
390         return ca_list;
391 }
392
393 static SSL *
394 alloc_handle( void *ctx_arg )
395 {
396         SSL_CTX *ctx;
397         SSL     *ssl;
398
399         if ( ctx_arg ) {
400                 ctx = (SSL_CTX *) ctx_arg;
401         } else {
402                 if ( ldap_pvt_tls_init_def_ctx() < 0 ) return NULL;
403                 ctx = tls_def_ctx;
404         }
405
406         ssl = SSL_new( ctx );
407         if ( ssl == NULL ) {
408                 Debug( LDAP_DEBUG_ANY,"TLS: can't create ssl handle.\n",0,0,0);
409                 return NULL;
410         }
411         return ssl;
412 }
413
414 static int
415 update_flags( Sockbuf *sb, SSL * ssl, int rc )
416 {
417         int err = SSL_get_error(ssl, rc);
418
419         sb->sb_trans_needs_read  = 0;
420         sb->sb_trans_needs_write = 0;
421
422         if (err == SSL_ERROR_WANT_READ) {
423                 sb->sb_trans_needs_read  = 1;
424                 return 1;
425
426         } else if (err == SSL_ERROR_WANT_WRITE) {
427                 sb->sb_trans_needs_write = 1;
428                 return 1;
429
430         } else if (err == SSL_ERROR_WANT_CONNECT) {
431                 return 1;
432         }
433         return 0;
434 }
435
436 /*
437  * TLS support for LBER Sockbufs
438  */
439
440 struct tls_data {
441         SSL                     *ssl;
442         Sockbuf_IO_Desc         *sbiod;
443 };
444
445 static BIO_METHOD sb_tls_bio_method;
446
447 static int
448 sb_tls_setup( Sockbuf_IO_Desc *sbiod, void *arg )
449 {
450         struct tls_data         *p;
451         BIO                     *bio;
452
453         assert( sbiod != NULL );
454
455         p = LBER_MALLOC( sizeof( *p ) );
456         if ( p == NULL ) {
457                 return -1;
458         }
459         
460         p->ssl = (SSL *)arg;
461         p->sbiod = sbiod;
462         bio = BIO_new( &sb_tls_bio_method );
463         bio->ptr = (void *)p;
464         SSL_set_bio( p->ssl, bio, bio );
465         sbiod->sbiod_pvt = p;
466         return 0;
467 }
468
469 static int
470 sb_tls_remove( Sockbuf_IO_Desc *sbiod )
471 {
472         struct tls_data         *p;
473         
474         assert( sbiod != NULL );
475         assert( sbiod->sbiod_pvt != NULL );
476
477         p = (struct tls_data *)sbiod->sbiod_pvt;
478         SSL_free( p->ssl );
479         LBER_FREE( sbiod->sbiod_pvt );
480         sbiod->sbiod_pvt = NULL;
481         return 0;
482 }
483
484 static int
485 sb_tls_close( Sockbuf_IO_Desc *sbiod )
486 {
487         struct tls_data         *p;
488         
489         assert( sbiod != NULL );
490         assert( sbiod->sbiod_pvt != NULL );
491
492         p = (struct tls_data *)sbiod->sbiod_pvt;
493         SSL_shutdown( p->ssl );
494         return 0;
495 }
496
497 static int
498 sb_tls_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
499 {
500         struct tls_data         *p;
501         
502         assert( sbiod != NULL );
503         assert( sbiod->sbiod_pvt != NULL );
504
505         p = (struct tls_data *)sbiod->sbiod_pvt;
506         
507         if ( opt == LBER_SB_OPT_GET_SSL ) {
508                 *((SSL **)arg) = p->ssl;
509                 return 1;
510
511         } else if ( opt == LBER_SB_OPT_DATA_READY ) {
512                 if( SSL_pending( p->ssl ) > 0 ) {
513                         return 1;
514                 }
515         }
516         
517         return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
518 }
519
520 static ber_slen_t
521 sb_tls_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
522 {
523         struct tls_data         *p;
524         ber_slen_t              ret;
525         int                     err;
526
527         assert( sbiod != NULL );
528         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
529
530         p = (struct tls_data *)sbiod->sbiod_pvt;
531
532         ret = SSL_read( p->ssl, (char *)buf, len );
533 #ifdef HAVE_WINSOCK
534         errno = WSAGetLastError();
535 #endif
536         err = SSL_get_error( p->ssl, ret );
537         if (err == SSL_ERROR_WANT_READ ) {
538                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
539                 errno = EWOULDBLOCK;
540         }
541         else
542                 sbiod->sbiod_sb->sb_trans_needs_read = 0;
543         return ret;
544 }
545
546 static ber_slen_t
547 sb_tls_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
548 {
549         struct tls_data         *p;
550         ber_slen_t              ret;
551         int                     err;
552
553         assert( sbiod != NULL );
554         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
555
556         p = (struct tls_data *)sbiod->sbiod_pvt;
557
558         ret = SSL_write( p->ssl, (char *)buf, len );
559 #ifdef HAVE_WINSOCK
560         errno = WSAGetLastError();
561 #endif
562         err = SSL_get_error( p->ssl, ret );
563         if (err == SSL_ERROR_WANT_WRITE ) {
564                 sbiod->sbiod_sb->sb_trans_needs_write = 1;
565                 errno = EWOULDBLOCK;
566
567         } else {
568                 sbiod->sbiod_sb->sb_trans_needs_write = 0;
569         }
570         return ret;
571 }
572
573 static Sockbuf_IO sb_tls_sbio =
574 {
575         sb_tls_setup,           /* sbi_setup */
576         sb_tls_remove,          /* sbi_remove */
577         sb_tls_ctrl,            /* sbi_ctrl */
578         sb_tls_read,            /* sbi_read */
579         sb_tls_write,           /* sbi_write */
580         sb_tls_close            /* sbi_close */
581 };
582
583 static int
584 sb_tls_bio_create( BIO *b ) {
585         b->init = 1;
586         b->num = 0;
587         b->ptr = NULL;
588         b->flags = 0;
589         return 1;
590 }
591
592 static int
593 sb_tls_bio_destroy( BIO *b )
594 {
595         if ( b == NULL ) return 0;
596
597         b->ptr = NULL;          /* sb_tls_remove() will free it */
598         b->init = 0;
599         b->flags = 0;
600         return 1;
601 }
602
603 static int
604 sb_tls_bio_read( BIO *b, char *buf, int len )
605 {
606         struct tls_data         *p;
607         int                     ret;
608                 
609         if ( buf == NULL || len <= 0 ) return 0;
610
611         p = (struct tls_data *)b->ptr;
612
613         if ( p == NULL || p->sbiod == NULL ) {
614                 return 0;
615         }
616
617         ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
618
619         BIO_clear_retry_flags( b );
620         if ( ret < 0 ) {
621                 int err = errno;
622                 if ( err == EAGAIN || err == EWOULDBLOCK ) {
623                         BIO_set_retry_read( b );
624                 }
625         }
626
627         return ret;
628 }
629
630 static int
631 sb_tls_bio_write( BIO *b, const char *buf, int len )
632 {
633         struct tls_data         *p;
634         int                     ret;
635         
636         if ( buf == NULL || len <= 0 ) return 0;
637         
638         p = (struct tls_data *)b->ptr;
639
640         if ( p == NULL || p->sbiod == NULL ) {
641                 return 0;
642         }
643
644         ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
645
646         BIO_clear_retry_flags( b );
647         if ( ret < 0 ) {
648                 int err = errno;
649                 if ( err == EAGAIN || err == EWOULDBLOCK ) {
650                         BIO_set_retry_write( b );
651                 }
652         }
653
654         return ret;
655 }
656
657 static long
658 sb_tls_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
659 {
660         if ( cmd == BIO_CTRL_FLUSH ) {
661                 /* The OpenSSL library needs this */
662                 return 1;
663         }
664         return 0;
665 }
666
667 static int
668 sb_tls_bio_gets( BIO *b, char *buf, int len )
669 {
670         return -1;
671 }
672
673 static int
674 sb_tls_bio_puts( BIO *b, const char *str )
675 {
676         return sb_tls_bio_write( b, str, strlen( str ) );
677 }
678         
679 static BIO_METHOD sb_tls_bio_method =
680 {
681         ( 100 | 0x400 ),                /* it's a source/sink BIO */
682         "sockbuf glue",
683         sb_tls_bio_write,
684         sb_tls_bio_read,
685         sb_tls_bio_puts,
686         sb_tls_bio_gets,
687         sb_tls_bio_ctrl,
688         sb_tls_bio_create,
689         sb_tls_bio_destroy
690 };
691
692 /*
693  * Call this to do a TLS connect on a sockbuf. ctx_arg can be
694  * a SSL_CTX * or NULL, in which case the default ctx is used.
695  *
696  * Return value:
697  *
698  *  0 - Success. Connection is ready for communication.
699  * <0 - Error. Can't create a TLS stream.
700  * >0 - Partial success.
701  *        Do a select (using information from lber_pvt_sb_needs_{read,write}
702  *              and call again.
703  */
704
705 static int
706 ldap_int_tls_connect( LDAP *ld, LDAPConn *conn )
707 {
708         Sockbuf *sb = conn->lconn_sb;
709         int     err;
710         SSL     *ssl;
711
712         if ( HAS_TLS( sb ) ) {
713                 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&ssl );
714
715         } else {
716                 struct ldapoptions *lo;
717                 void *ctx = ld->ld_defconn
718                         ? ld->ld_defconn->lconn_tls_ctx : NULL;
719
720                 ssl = alloc_handle( ctx );
721
722                 if ( ssl == NULL ) return -1;
723
724 #ifdef LDAP_DEBUG
725                 ber_sockbuf_add_io( sb, &ber_sockbuf_io_debug,
726                         LBER_SBIOD_LEVEL_TRANSPORT, (void *)"tls_" );
727 #endif
728                 ber_sockbuf_add_io( sb, &sb_tls_sbio,
729                         LBER_SBIOD_LEVEL_TRANSPORT, (void *)ssl );
730
731                 if( ctx == NULL ) {
732                         ctx = tls_def_ctx;
733                         conn->lconn_tls_ctx = tls_def_ctx;
734                 }
735                 lo = &ld->ld_options;
736                 if ( lo->ldo_tls_connect_cb )
737                         lo->ldo_tls_connect_cb( ld, ssl, ctx, lo->ldo_tls_connect_arg );
738                 lo = LDAP_INT_GLOBAL_OPT();   
739                 if ( lo && lo->ldo_tls_connect_cb )
740                         lo->ldo_tls_connect_cb( ld, ssl, ctx, lo->ldo_tls_connect_arg );
741         }
742
743         err = SSL_connect( ssl );
744
745 #ifdef HAVE_WINSOCK
746         errno = WSAGetLastError();
747 #endif
748
749         if ( err <= 0 ) {
750                 if ( update_flags( sb, ssl, err )) {
751                         return 1;
752                 }
753
754                 if ((err = ERR_peek_error())) {
755                         char buf[256];
756                         ld->ld_error = LDAP_STRDUP(ERR_error_string(err, buf));
757 #ifdef HAVE_EBCDIC
758                         if ( ld->ld_error ) __etoa(ld->ld_error);
759 #endif
760                 }
761
762                 Debug( LDAP_DEBUG_ANY,"TLS: can't connect.\n",0,0,0);
763
764                 ber_sockbuf_remove_io( sb, &sb_tls_sbio,
765                         LBER_SBIOD_LEVEL_TRANSPORT );
766 #ifdef LDAP_DEBUG
767                 ber_sockbuf_remove_io( sb, &ber_sockbuf_io_debug,
768                         LBER_SBIOD_LEVEL_TRANSPORT );
769 #endif
770                 return -1;
771         }
772
773         return 0;
774 }
775
776 /*
777  * Call this to do a TLS accept on a sockbuf.
778  * Everything else is the same as with tls_connect.
779  */
780 int
781 ldap_pvt_tls_accept( Sockbuf *sb, void *ctx_arg )
782 {
783         int     err;
784         SSL     *ssl;
785
786         if ( HAS_TLS( sb ) ) {
787                 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&ssl );
788
789         } else {
790                 ssl = alloc_handle( ctx_arg );
791                 if ( ssl == NULL ) return -1;
792
793 #ifdef LDAP_DEBUG
794                 ber_sockbuf_add_io( sb, &ber_sockbuf_io_debug,
795                         LBER_SBIOD_LEVEL_TRANSPORT, (void *)"tls_" );
796 #endif
797                 ber_sockbuf_add_io( sb, &sb_tls_sbio,
798                         LBER_SBIOD_LEVEL_TRANSPORT, (void *)ssl );
799         }
800
801         err = SSL_accept( ssl );
802
803 #ifdef HAVE_WINSOCK
804         errno = WSAGetLastError();
805 #endif
806         if ( err <= 0 ) {
807                 if ( update_flags( sb, ssl, err )) return 1;
808
809                 Debug( LDAP_DEBUG_ANY,"TLS: can't accept.\n",0,0,0 );
810
811                 tls_report_error();
812                 ber_sockbuf_remove_io( sb, &sb_tls_sbio,
813                         LBER_SBIOD_LEVEL_TRANSPORT );
814 #ifdef LDAP_DEBUG
815                 ber_sockbuf_remove_io( sb, &ber_sockbuf_io_debug,
816                         LBER_SBIOD_LEVEL_TRANSPORT );
817 #endif
818                 return -1;
819         }
820
821         return 0;
822 }
823
824 int
825 ldap_pvt_tls_inplace ( Sockbuf *sb )
826 {
827         return HAS_TLS( sb ) ? 1 : 0;
828 }
829
830 int
831 ldap_tls_inplace( LDAP *ld )
832 {
833         Sockbuf         *sb = NULL;
834         int             rc;
835
836         rc = ldap_get_option( ld, LDAP_OPT_SOCKBUF, (void *)&sb );
837         if ( rc != LDAP_SUCCESS || sb == NULL ) {
838                 return 0;
839         }
840
841         return ldap_pvt_tls_inplace( sb );
842 }
843
844 static X509 *
845 tls_get_cert( SSL *s )
846 {
847         /* If peer cert was bad, treat as if no cert was given */
848         if (SSL_get_verify_result(s)) {
849                 /* If we can send an alert, do so */
850                 if (SSL_version(s) != SSL2_VERSION) {
851                         ssl3_send_alert(s,SSL3_AL_WARNING,SSL3_AD_BAD_CERTIFICATE);
852                 }
853                 return NULL;
854         }
855         return SSL_get_peer_certificate(s);
856 }
857
858 int
859 ldap_pvt_tls_get_peer_dn( void *s, struct berval *dn,
860         LDAPDN_rewrite_dummy *func, unsigned flags )
861 {
862         X509 *x;
863         X509_NAME *xn;
864         int rc;
865
866         x = tls_get_cert((SSL *)s);
867
868         if (!x) return LDAP_INVALID_CREDENTIALS;
869         
870         xn = X509_get_subject_name(x);
871         rc = ldap_X509dn2bv(xn, dn, (LDAPDN_rewrite_func *)func, flags);
872         X509_free(x);
873         return rc;
874 }
875
876 char *
877 ldap_pvt_tls_get_peer_hostname( void *s )
878 {
879         X509 *x;
880         X509_NAME *xn;
881         char buf[2048], *p;
882         int ret;
883
884         x = tls_get_cert((SSL *)s);
885         if (!x) return NULL;
886         
887         xn = X509_get_subject_name(x);
888
889         ret = X509_NAME_get_text_by_NID(xn, NID_commonName, buf, sizeof(buf));
890         if( ret == -1 ) {
891                 X509_free(x);
892                 return NULL;
893         }
894
895         p = LDAP_STRDUP(buf);
896         X509_free(x);
897         return p;
898 }
899
900 /* what kind of hostname were we given? */
901 #define IS_DNS  0
902 #define IS_IP4  1
903 #define IS_IP6  2
904
905 int
906 ldap_pvt_tls_check_hostname( LDAP *ld, void *s, const char *name_in )
907 {
908         int i, ret = LDAP_LOCAL_ERROR;
909         X509 *x;
910         const char *name;
911         char *ptr;
912         int ntype = IS_DNS;
913 #ifdef LDAP_PF_INET6
914         struct in6_addr addr;
915 #else
916         struct in_addr addr;
917 #endif
918
919         if( ldap_int_hostname &&
920                 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
921         {
922                 name = ldap_int_hostname;
923         } else {
924                 name = name_in;
925         }
926
927         x = tls_get_cert((SSL *)s);
928         if (!x) {
929                 Debug( LDAP_DEBUG_ANY,
930                         "TLS: unable to get peer certificate.\n",
931                         0, 0, 0 );
932                 /* If this was a fatal condition, things would have
933                  * aborted long before now.
934                  */
935                 return LDAP_SUCCESS;
936         }
937
938 #ifdef LDAP_PF_INET6
939         if (name[0] == '[' && strchr(name, ']')) {
940                 char *n2 = ldap_strdup(name+1);
941                 *strchr(n2, ']') = 2;
942                 if (inet_pton(AF_INET6, n2, &addr))
943                         ntype = IS_IP6;
944                 LDAP_FREE(n2);
945         } else 
946 #endif
947         if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
948                 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
949         }
950         
951         i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
952         if (i >= 0) {
953                 X509_EXTENSION *ex;
954                 STACK_OF(GENERAL_NAME) *alt;
955
956                 ex = X509_get_ext(x, i);
957                 alt = X509V3_EXT_d2i(ex);
958                 if (alt) {
959                         int n, len1 = 0, len2 = 0;
960                         char *domain = NULL;
961                         GENERAL_NAME *gn;
962
963                         if (ntype == IS_DNS) {
964                                 len1 = strlen(name);
965                                 domain = strchr(name, '.');
966                                 if (domain) {
967                                         len2 = len1 - (domain-name);
968                                 }
969                         }
970                         n = sk_GENERAL_NAME_num(alt);
971                         for (i=0; i<n; i++) {
972                                 char *sn;
973                                 int sl;
974                                 gn = sk_GENERAL_NAME_value(alt, i);
975                                 if (gn->type == GEN_DNS) {
976                                         if (ntype != IS_DNS) continue;
977
978                                         sn = (char *) ASN1_STRING_data(gn->d.ia5);
979                                         sl = ASN1_STRING_length(gn->d.ia5);
980
981                                         /* ignore empty */
982                                         if (sl == 0) continue;
983
984                                         /* Is this an exact match? */
985                                         if ((len1 == sl) && !strncasecmp(name, sn, len1)) {
986                                                 break;
987                                         }
988
989                                         /* Is this a wildcard match? */
990                                         if (domain && (sn[0] == '*') && (sn[1] == '.') &&
991                                                 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
992                                         {
993                                                 break;
994                                         }
995
996                                 } else if (gn->type == GEN_IPADD) {
997                                         if (ntype == IS_DNS) continue;
998
999                                         sn = (char *) ASN1_STRING_data(gn->d.ia5);
1000                                         sl = ASN1_STRING_length(gn->d.ia5);
1001
1002 #ifdef LDAP_PF_INET6
1003                                         if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
1004                                                 continue;
1005                                         } else
1006 #endif
1007                                         if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
1008                                                 continue;
1009                                         }
1010                                         if (!memcmp(sn, &addr, sl)) {
1011                                                 break;
1012                                         }
1013                                 }
1014                         }
1015
1016                         GENERAL_NAMES_free(alt);
1017                         if (i < n) {    /* Found a match */
1018                                 ret = LDAP_SUCCESS;
1019                         }
1020                 }
1021         }
1022
1023         if (ret != LDAP_SUCCESS) {
1024                 X509_NAME *xn;
1025                 char buf[2048];
1026                 buf[0] = '\0';
1027
1028                 xn = X509_get_subject_name(x);
1029                 if( X509_NAME_get_text_by_NID( xn, NID_commonName,
1030                         buf, sizeof(buf)) == -1)
1031                 {
1032                         Debug( LDAP_DEBUG_ANY,
1033                                 "TLS: unable to get common name from peer certificate.\n",
1034                                 0, 0, 0 );
1035                 ret = LDAP_CONNECT_ERROR;
1036                         ld->ld_error = LDAP_STRDUP(
1037                                 _("TLS: unable to get CN from peer certificate"));
1038
1039                 } else if (strcasecmp(name, buf) == 0 ) {
1040                         ret = LDAP_SUCCESS;
1041
1042                 } else if (( buf[0] == '*' ) && ( buf[1] == '.' )) {
1043                         char *domain = strchr(name, '.');
1044                         if( domain ) {
1045                                 size_t dlen = 0;
1046                                 size_t sl;
1047
1048                                 sl = strlen(name);
1049                                 dlen = sl - (domain-name);
1050                                 sl = strlen(buf);
1051
1052                                 /* Is this a wildcard match? */
1053                                 if ((dlen == sl-1) && !strncasecmp(domain, &buf[1], dlen)) {
1054                                         ret = LDAP_SUCCESS;
1055                                 }
1056                         }
1057                 }
1058
1059                 if( ret == LDAP_LOCAL_ERROR ) {
1060                  Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
1061                          "common name in certificate (%s).\n", 
1062                          name, buf, 0 );
1063                  ret = LDAP_CONNECT_ERROR;
1064                  ld->ld_error = LDAP_STRDUP(
1065                          _("TLS: hostname does not match CN in peer certificate"));
1066                 }
1067         }
1068         X509_free(x);
1069         return ret;
1070 }
1071
1072 const char *
1073 ldap_pvt_tls_get_peer_issuer( void *s )
1074 {
1075 #if 0   /* currently unused; see ldap_pvt_tls_get_peer_dn() if needed */
1076         X509 *x;
1077         X509_NAME *xn;
1078         char buf[2048], *p;
1079
1080         x = SSL_get_peer_certificate((SSL *)s);
1081
1082         if (!x) return NULL;
1083         
1084         xn = X509_get_issuer_name(x);
1085         p = LDAP_STRDUP(X509_NAME_oneline(xn, buf, sizeof(buf)));
1086         X509_free(x);
1087         return p;
1088 #else
1089         return NULL;
1090 #endif
1091 }
1092
1093 int
1094 ldap_int_tls_config( LDAP *ld, int option, const char *arg )
1095 {
1096         int i;
1097
1098         switch( option ) {
1099         case LDAP_OPT_X_TLS_CACERTFILE:
1100         case LDAP_OPT_X_TLS_CACERTDIR:
1101         case LDAP_OPT_X_TLS_CERTFILE:
1102         case LDAP_OPT_X_TLS_KEYFILE:
1103         case LDAP_OPT_X_TLS_RANDOM_FILE:
1104         case LDAP_OPT_X_TLS_CIPHER_SUITE:
1105                 return ldap_pvt_tls_set_option( ld, option, (void *) arg );
1106
1107         case LDAP_OPT_X_TLS_REQUIRE_CERT:
1108         case LDAP_OPT_X_TLS:
1109                 i = -1;
1110                 if ( strcasecmp( arg, "never" ) == 0 ) {
1111                         i = LDAP_OPT_X_TLS_NEVER ;
1112
1113                 } else if ( strcasecmp( arg, "demand" ) == 0 ) {
1114                         i = LDAP_OPT_X_TLS_DEMAND ;
1115
1116                 } else if ( strcasecmp( arg, "allow" ) == 0 ) {
1117                         i = LDAP_OPT_X_TLS_ALLOW ;
1118
1119                 } else if ( strcasecmp( arg, "try" ) == 0 ) {
1120                         i = LDAP_OPT_X_TLS_TRY ;
1121
1122                 } else if ( ( strcasecmp( arg, "hard" ) == 0 ) ||
1123                         ( strcasecmp( arg, "on" ) == 0 ) ||
1124                         ( strcasecmp( arg, "yes" ) == 0) ||
1125                         ( strcasecmp( arg, "true" ) == 0 ) )
1126                 {
1127                         i = LDAP_OPT_X_TLS_HARD ;
1128                 }
1129
1130                 if (i >= 0) {
1131                         return ldap_pvt_tls_set_option( ld, option, &i );
1132                 }
1133                 return -1;
1134 #ifdef HAVE_OPENSSL_CRL
1135         case LDAP_OPT_X_TLS_CRLCHECK:
1136                 i = -1;
1137                 if ( strcasecmp( arg, "none" ) == 0 ) {
1138                         i = LDAP_OPT_X_TLS_CRL_NONE ;
1139                 } else if ( strcasecmp( arg, "peer" ) == 0 ) {
1140                         i = LDAP_OPT_X_TLS_CRL_PEER ;
1141                 } else if ( strcasecmp( arg, "all" ) == 0 ) {
1142                         i = LDAP_OPT_X_TLS_CRL_ALL ;
1143                 }
1144                 if (i >= 0) {
1145                         return ldap_pvt_tls_set_option( ld, option, &i );
1146                 }
1147                 return -1;
1148 #endif
1149         }
1150         return -1;
1151 }
1152
1153 int
1154 ldap_pvt_tls_get_option( LDAP *ld, int option, void *arg )
1155 {
1156         struct ldapoptions *lo;
1157
1158         if( ld != NULL ) {
1159                 assert( LDAP_VALID( ld ) );
1160
1161                 if( !LDAP_VALID( ld ) ) {
1162                         return LDAP_OPT_ERROR;
1163                 }
1164
1165                 lo = &ld->ld_options;
1166
1167         } else {
1168                 /* Get pointer to global option structure */
1169                 lo = LDAP_INT_GLOBAL_OPT();   
1170                 if ( lo == NULL ) {
1171                         return LDAP_NO_MEMORY;
1172                 }
1173         }
1174
1175         switch( option ) {
1176         case LDAP_OPT_X_TLS:
1177                 *(int *)arg = lo->ldo_tls_mode;
1178                 break;
1179         case LDAP_OPT_X_TLS_CTX:
1180                 if ( ld == NULL ) {
1181                         *(void **)arg = (void *) tls_def_ctx;
1182                 } else {
1183                         *(void **)arg = ld->ld_defconn->lconn_tls_ctx;
1184                 }
1185                 break;
1186         case LDAP_OPT_X_TLS_CACERTFILE:
1187                 *(char **)arg = tls_opt_cacertfile ?
1188                         LDAP_STRDUP( tls_opt_cacertfile ) : NULL;
1189                 break;
1190         case LDAP_OPT_X_TLS_CACERTDIR:
1191                 *(char **)arg = tls_opt_cacertdir ?
1192                         LDAP_STRDUP( tls_opt_cacertdir ) : NULL;
1193                 break;
1194         case LDAP_OPT_X_TLS_CERTFILE:
1195                 *(char **)arg = tls_opt_certfile ?
1196                         LDAP_STRDUP( tls_opt_certfile ) : NULL;
1197                 break;
1198         case LDAP_OPT_X_TLS_KEYFILE:
1199                 *(char **)arg = tls_opt_keyfile ?
1200                         LDAP_STRDUP( tls_opt_keyfile ) : NULL;
1201                 break;
1202         case LDAP_OPT_X_TLS_REQUIRE_CERT:
1203                 *(int *)arg = tls_opt_require_cert;
1204                 break;
1205 #ifdef HAVE_OPENSSL_CRL
1206         case LDAP_OPT_X_TLS_CRLCHECK:
1207                 *(int *)arg = tls_opt_crlcheck;
1208                 break;
1209 #endif
1210         case LDAP_OPT_X_TLS_RANDOM_FILE:
1211                 *(char **)arg = tls_opt_randfile ?
1212                         LDAP_STRDUP( tls_opt_randfile ) : NULL;
1213                 break;
1214         case LDAP_OPT_X_TLS_SSL_CTX: {
1215                 void *retval = 0;
1216                 if ( ld != NULL ) {
1217                         LDAPConn *conn = ld->ld_defconn;
1218                         if ( conn != NULL ) {
1219                                 Sockbuf *sb = conn->lconn_sb;
1220                                 retval = ldap_pvt_tls_sb_ctx( sb );
1221                         }
1222                 }
1223                 *(void **)arg = retval;
1224                 break;
1225         }
1226         case LDAP_OPT_X_TLS_CONNECT_CB:
1227                 *(LDAP_TLS_CONNECT_CB **)arg = lo->ldo_tls_connect_cb;
1228                 break;
1229         case LDAP_OPT_X_TLS_CONNECT_ARG:
1230                 *(void **)arg = lo->ldo_tls_connect_arg;
1231                 break;
1232         default:
1233                 return -1;
1234         }
1235         return 0;
1236 }
1237
1238 int
1239 ldap_pvt_tls_set_option( LDAP *ld, int option, void *arg )
1240 {
1241         struct ldapoptions *lo;
1242
1243         if( ld != NULL ) {
1244                 assert( LDAP_VALID( ld ) );
1245
1246                 if( !LDAP_VALID( ld ) ) {
1247                         return LDAP_OPT_ERROR;
1248                 }
1249
1250                 lo = &ld->ld_options;
1251
1252         } else {
1253                 /* Get pointer to global option structure */
1254                 lo = LDAP_INT_GLOBAL_OPT();   
1255                 if ( lo == NULL ) {
1256                         return LDAP_NO_MEMORY;
1257                 }
1258         }
1259
1260         switch( option ) {
1261         case LDAP_OPT_X_TLS:
1262                 switch( *(int *) arg ) {
1263                 case LDAP_OPT_X_TLS_NEVER:
1264                 case LDAP_OPT_X_TLS_DEMAND:
1265                 case LDAP_OPT_X_TLS_ALLOW:
1266                 case LDAP_OPT_X_TLS_TRY:
1267                 case LDAP_OPT_X_TLS_HARD:
1268                         if (lo != NULL) {
1269                                 lo->ldo_tls_mode = *(int *)arg;
1270                         }
1271
1272                         return 0;
1273                 }
1274                 return -1;
1275
1276         case LDAP_OPT_X_TLS_CTX:
1277                 if ( ld == NULL ) {
1278                         tls_def_ctx = (SSL_CTX *) arg;
1279
1280                 } else {
1281                         ld->ld_defconn->lconn_tls_ctx = arg;
1282                 }
1283                 return 0;
1284         case LDAP_OPT_X_TLS_CONNECT_CB:
1285                 lo->ldo_tls_connect_cb = (LDAP_TLS_CONNECT_CB *)arg;
1286                 return 0;
1287         case LDAP_OPT_X_TLS_CONNECT_ARG:
1288                 lo->ldo_tls_connect_arg = arg;
1289                 return 0;
1290         }
1291
1292         if ( ld != NULL ) {
1293                 return -1;
1294         }
1295
1296         switch( option ) {
1297         case LDAP_OPT_X_TLS_CACERTFILE:
1298                 if ( tls_opt_cacertfile ) LDAP_FREE( tls_opt_cacertfile );
1299                 tls_opt_cacertfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1300                 break;
1301         case LDAP_OPT_X_TLS_CACERTDIR:
1302                 if ( tls_opt_cacertdir ) LDAP_FREE( tls_opt_cacertdir );
1303                 tls_opt_cacertdir = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1304                 break;
1305         case LDAP_OPT_X_TLS_CERTFILE:
1306                 if ( tls_opt_certfile ) LDAP_FREE( tls_opt_certfile );
1307                 tls_opt_certfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1308                 break;
1309         case LDAP_OPT_X_TLS_KEYFILE:
1310                 if ( tls_opt_keyfile ) LDAP_FREE( tls_opt_keyfile );
1311                 tls_opt_keyfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1312                 break;
1313         case LDAP_OPT_X_TLS_REQUIRE_CERT:
1314                 switch( *(int *) arg ) {
1315                 case LDAP_OPT_X_TLS_NEVER:
1316                 case LDAP_OPT_X_TLS_DEMAND:
1317                 case LDAP_OPT_X_TLS_ALLOW:
1318                 case LDAP_OPT_X_TLS_TRY:
1319                 case LDAP_OPT_X_TLS_HARD:
1320                         tls_opt_require_cert = * (int *) arg;
1321                         return 0;
1322                 }
1323                 return -1;
1324 #ifdef HAVE_OPENSSL_CRL
1325         case LDAP_OPT_X_TLS_CRLCHECK:
1326                 switch( *(int *) arg ) {
1327                 case LDAP_OPT_X_TLS_CRL_NONE:
1328                 case LDAP_OPT_X_TLS_CRL_PEER:
1329                 case LDAP_OPT_X_TLS_CRL_ALL:
1330                         tls_opt_crlcheck = * (int *) arg;
1331                         return 0;
1332                 }
1333                 return -1;
1334 #endif
1335         case LDAP_OPT_X_TLS_CIPHER_SUITE:
1336                 if ( tls_opt_ciphersuite ) LDAP_FREE( tls_opt_ciphersuite );
1337                 tls_opt_ciphersuite = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1338                 break;
1339         case LDAP_OPT_X_TLS_RANDOM_FILE:
1340                 if (tls_opt_randfile ) LDAP_FREE (tls_opt_randfile );
1341                 tls_opt_randfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1342                 break;
1343         default:
1344                 return -1;
1345         }
1346         return 0;
1347 }
1348
1349 int
1350 ldap_int_tls_start ( LDAP *ld, LDAPConn *conn, LDAPURLDesc *srv )
1351 {
1352         Sockbuf *sb = conn->lconn_sb;
1353         char *host;
1354         void *ssl;
1355
1356         if( srv ) {
1357                 host = srv->lud_host;
1358         } else {
1359                 host = conn->lconn_server->lud_host;
1360         }
1361
1362         /* avoid NULL host */
1363         if( host == NULL ) {
1364                 host = "localhost";
1365         }
1366
1367         (void) ldap_pvt_tls_init();
1368
1369         /*
1370          * Fortunately, the lib uses blocking io...
1371          */
1372         if ( ldap_int_tls_connect( ld, conn ) < 0 ) {
1373                 ld->ld_errno = LDAP_CONNECT_ERROR;
1374                 return (ld->ld_errno);
1375         }
1376
1377         ssl = ldap_pvt_tls_sb_ctx( sb );
1378         assert( ssl != NULL );
1379
1380         /* 
1381          * compare host with name(s) in certificate
1382          */
1383         if (tls_opt_require_cert != LDAP_OPT_X_TLS_NEVER) {
1384                 ld->ld_errno = ldap_pvt_tls_check_hostname( ld, ssl, host );
1385                 if (ld->ld_errno != LDAP_SUCCESS) {
1386                         return ld->ld_errno;
1387                 }
1388         }
1389
1390         return LDAP_SUCCESS;
1391 }
1392
1393 /* Derived from openssl/apps/s_cb.c */
1394 static void
1395 tls_info_cb( const SSL *ssl, int where, int ret )
1396 {
1397         int w;
1398         char *op;
1399         char *state = (char *) SSL_state_string_long( (SSL *)ssl );
1400
1401         w = where & ~SSL_ST_MASK;
1402         if ( w & SSL_ST_CONNECT ) {
1403                 op = "SSL_connect";
1404         } else if ( w & SSL_ST_ACCEPT ) {
1405                 op = "SSL_accept";
1406         } else {
1407                 op = "undefined";
1408         }
1409
1410 #ifdef HAVE_EBCDIC
1411         if ( state ) {
1412                 state = LDAP_STRDUP( state );
1413                 __etoa( state );
1414         }
1415 #endif
1416         if ( where & SSL_CB_LOOP ) {
1417                 Debug( LDAP_DEBUG_TRACE,
1418                            "TLS trace: %s:%s\n",
1419                            op, state, 0 );
1420
1421         } else if ( where & SSL_CB_ALERT ) {
1422                 char *atype = (char *) SSL_alert_type_string_long( ret );
1423                 char *adesc = (char *) SSL_alert_desc_string_long( ret );
1424                 op = ( where & SSL_CB_READ ) ? "read" : "write";
1425 #ifdef HAVE_EBCDIC
1426                 if ( atype ) {
1427                         atype = LDAP_STRDUP( atype );
1428                         __etoa( atype );
1429                 }
1430                 if ( adesc ) {
1431                         adesc = LDAP_STRDUP( adesc );
1432                         __etoa( adesc );
1433                 }
1434 #endif
1435                 Debug( LDAP_DEBUG_TRACE,
1436                            "TLS trace: SSL3 alert %s:%s:%s\n",
1437                            op, atype, adesc );
1438 #ifdef HAVE_EBCDIC
1439                 if ( atype ) LDAP_FREE( atype );
1440                 if ( adesc ) LDAP_FREE( adesc );
1441 #endif
1442         } else if ( where & SSL_CB_EXIT ) {
1443                 if ( ret == 0 ) {
1444                         Debug( LDAP_DEBUG_TRACE,
1445                                    "TLS trace: %s:failed in %s\n",
1446                                    op, state, 0 );
1447                 } else if ( ret < 0 ) {
1448                         Debug( LDAP_DEBUG_TRACE,
1449                                    "TLS trace: %s:error in %s\n",
1450                                    op, state, 0 );
1451                 }
1452         }
1453 #ifdef HAVE_EBCDIC
1454         if ( state ) LDAP_FREE( state );
1455 #endif
1456 }
1457
1458 static int
1459 tls_verify_cb( int ok, X509_STORE_CTX *ctx )
1460 {
1461         X509 *cert;
1462         int errnum;
1463         int errdepth;
1464         X509_NAME *subject;
1465         X509_NAME *issuer;
1466         char *sname;
1467         char *iname;
1468         char *certerr = NULL;
1469
1470         cert = X509_STORE_CTX_get_current_cert( ctx );
1471         errnum = X509_STORE_CTX_get_error( ctx );
1472         errdepth = X509_STORE_CTX_get_error_depth( ctx );
1473
1474         /*
1475          * X509_get_*_name return pointers to the internal copies of
1476          * those things requested.  So do not free them.
1477          */
1478         subject = X509_get_subject_name( cert );
1479         issuer = X509_get_issuer_name( cert );
1480         /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1481         sname = X509_NAME_oneline( subject, NULL, 0 );
1482         iname = X509_NAME_oneline( issuer, NULL, 0 );
1483         if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1484 #ifdef HAVE_EBCDIC
1485         if ( sname ) __etoa( sname );
1486         if ( iname ) __etoa( iname );
1487         if ( certerr ) {
1488                 certerr = LDAP_STRDUP( certerr );
1489                 __etoa( certerr );
1490         }
1491 #endif
1492         Debug( LDAP_DEBUG_TRACE,
1493                    "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1494                    errdepth, errnum,
1495                    sname ? sname : "-unknown-" );
1496         Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1497         if ( !ok ) {
1498                 Debug( LDAP_DEBUG_ANY,
1499                         "TLS certificate verification: Error, %s\n",
1500                         certerr, 0, 0 );
1501         }
1502         if ( sname )
1503                 CRYPTO_free ( sname );
1504         if ( iname )
1505                 CRYPTO_free ( iname );
1506 #ifdef HAVE_EBCDIC
1507         if ( certerr ) LDAP_FREE( certerr );
1508 #endif
1509         return ok;
1510 }
1511
1512 static int
1513 tls_verify_ok( int ok, X509_STORE_CTX *ctx )
1514 {
1515         (void) tls_verify_cb( ok, ctx );
1516         return 1;
1517 }
1518
1519 /* Inspired by ERR_print_errors in OpenSSL */
1520 static void
1521 tls_report_error( void )
1522 {
1523         unsigned long l;
1524         char buf[200];
1525         const char *file;
1526         int line;
1527
1528         while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1529                 ERR_error_string_n( l, buf, sizeof( buf ) );
1530 #ifdef HAVE_EBCDIC
1531                 if ( file ) {
1532                         file = LDAP_STRDUP( file );
1533                         __etoa( (char *)file );
1534                 }
1535                 __etoa( buf );
1536 #endif
1537                 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1538                         buf, file, line );
1539 #ifdef HAVE_EBCDIC
1540                 if ( file ) LDAP_FREE( (void *)file );
1541 #endif
1542         }
1543 }
1544
1545 static RSA *
1546 tls_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1547 {
1548         RSA *tmp_rsa;
1549
1550         /* FIXME:  Pregenerate the key on startup */
1551         /* FIXME:  Who frees the key? */
1552         tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1553
1554         if ( !tmp_rsa ) {
1555                 Debug( LDAP_DEBUG_ANY,
1556                         "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1557                         key_length, is_export ? "export" : "domestic", 0 );
1558                 return NULL;
1559         }
1560         return tmp_rsa;
1561 }
1562
1563 static int
1564 tls_seed_PRNG( const char *randfile )
1565 {
1566 #ifndef URANDOM_DEVICE
1567         /* no /dev/urandom (or equiv) */
1568         long total=0;
1569         char buffer[MAXPATHLEN];
1570
1571         if (randfile == NULL) {
1572                 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1573                  * If $HOME is not set or buffer too small to hold the pathname,
1574                  * an error occurs.     - From RAND_file_name() man page.
1575                  * The fact is that when $HOME is NULL, .rnd is used.
1576                  */
1577                 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1578
1579         } else if (RAND_egd(randfile) > 0) {
1580                 /* EGD socket */
1581                 return 0;
1582         }
1583
1584         if (randfile == NULL) {
1585                 Debug( LDAP_DEBUG_ANY,
1586                         "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1587                         0, 0, 0);
1588                 return -1;
1589         }
1590
1591         total = RAND_load_file(randfile, -1);
1592
1593         if (RAND_status() == 0) {
1594                 Debug( LDAP_DEBUG_ANY,
1595                         "TLS: PRNG not been seeded with enough data\n",
1596                         0, 0, 0);
1597                 return -1;
1598         }
1599
1600         /* assume if there was enough bits to seed that it's okay
1601          * to write derived bits to the file
1602          */
1603         RAND_write_file(randfile);
1604
1605 #endif
1606
1607         return 0;
1608 }
1609
1610 #if 0
1611 static DH *
1612 tls_tmp_dh_cb( SSL *ssl, int is_export, int key_length )
1613 {
1614         return NULL;
1615 }
1616 #endif
1617 #endif
1618
1619 void *
1620 ldap_pvt_tls_sb_ctx( Sockbuf *sb )
1621 {
1622 #ifdef HAVE_TLS
1623         void                    *p;
1624         
1625         if (HAS_TLS( sb )) {
1626                 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&p );
1627                 return p;
1628         }
1629 #endif
1630
1631         return NULL;
1632 }
1633
1634 int
1635 ldap_pvt_tls_get_strength( void *s )
1636 {
1637 #ifdef HAVE_TLS
1638         SSL_CIPHER *c;
1639
1640         c = SSL_get_current_cipher((SSL *)s);
1641         return SSL_CIPHER_get_bits(c, NULL);
1642 #else
1643         return 0;
1644 #endif
1645 }
1646
1647
1648 int
1649 ldap_pvt_tls_get_my_dn( void *s, struct berval *dn, LDAPDN_rewrite_dummy *func, unsigned flags )
1650 {
1651 #ifdef HAVE_TLS
1652         X509 *x;
1653         X509_NAME *xn;
1654         int rc;
1655
1656         x = SSL_get_certificate((SSL *)s);
1657
1658         if (!x) return LDAP_INVALID_CREDENTIALS;
1659         
1660         xn = X509_get_subject_name(x);
1661         rc = ldap_X509dn2bv(xn, dn, (LDAPDN_rewrite_func *)func, flags );
1662         return rc;
1663 #else
1664         return LDAP_NOT_SUPPORTED;
1665 #endif
1666 }
1667
1668 int
1669 ldap_start_tls( LDAP *ld,
1670         LDAPControl **serverctrls,
1671         LDAPControl **clientctrls,
1672         int *msgidp )
1673 {
1674         return ldap_extended_operation( ld, LDAP_EXOP_START_TLS,
1675                 NULL, serverctrls, clientctrls, msgidp );
1676 }
1677
1678 int
1679 ldap_install_tls( LDAP *ld )
1680 {
1681 #ifndef HAVE_TLS
1682         return LDAP_NOT_SUPPORTED;
1683 #else
1684         if ( ld->ld_sb != NULL && ldap_pvt_tls_inplace( ld->ld_sb ) != 0 ) {
1685                 return LDAP_LOCAL_ERROR;
1686         }
1687
1688         return ldap_int_tls_start( ld, ld->ld_defconn, NULL );
1689 #endif
1690 }
1691
1692 int
1693 ldap_start_tls_s ( LDAP *ld,
1694         LDAPControl **serverctrls,
1695         LDAPControl **clientctrls )
1696 {
1697 #ifndef HAVE_TLS
1698         return LDAP_NOT_SUPPORTED;
1699 #else
1700         int rc;
1701         char *rspoid = NULL;
1702         struct berval *rspdata = NULL;
1703
1704         /* XXYYZ: this initiates operation only on default connection! */
1705
1706         if ( ld->ld_sb != NULL && ldap_pvt_tls_inplace( ld->ld_sb ) != 0 ) {
1707                 return LDAP_LOCAL_ERROR;
1708         }
1709
1710         rc = ldap_extended_operation_s( ld, LDAP_EXOP_START_TLS,
1711                 NULL, serverctrls, clientctrls, &rspoid, &rspdata );
1712
1713         if ( rspoid != NULL ) {
1714                 LDAP_FREE(rspoid);
1715         }
1716
1717         if ( rspdata != NULL ) {
1718                 ber_bvfree( rspdata );
1719         }
1720
1721         if ( rc == LDAP_SUCCESS ) {
1722                 rc = ldap_int_tls_start( ld, ld->ld_defconn, NULL );
1723         }
1724
1725         return rc;
1726 #endif
1727 }
1728