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