]> git.sur5r.net Git - openldap/blob - libraries/libldap/tls.c
We'll need queue macros in -llber...
[openldap] / libraries / libldap / tls.c
1 /* $OpenLDAP$ */
2 /*
3  * Copyright 1998-2000 The OpenLDAP Foundation, All Rights Reserved.
4  * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
5  *
6  * tls.c - Handle tls/ssl using SSLeay or OpenSSL.
7  */
8
9 #include "portable.h"
10
11 #include <stdio.h>
12
13 #include <ac/stdlib.h>
14 #include <ac/errno.h>
15 #include <ac/socket.h>
16 #include <ac/string.h>
17 #include <ac/time.h>
18 #include <ac/unistd.h>
19 #include <ac/param.h>
20
21 #include "ldap-int.h"
22
23 #ifdef HAVE_TLS
24
25 #ifdef LDAP_R_COMPILE
26 #include <ldap_pvt_thread.h>
27 #endif
28
29 #ifdef HAVE_OPENSSL_SSL_H
30 #include <openssl/ssl.h>
31 #include <openssl/x509v3.h>
32 #include <openssl/err.h>
33 #include <openssl/rand.h>
34 #include <openssl/safestack.h>
35 #elif defined( HAVE_SSL_H )
36 #include <ssl.h>
37 #endif
38
39 static int  tls_opt_trace = 1;
40 static char *tls_opt_certfile = NULL;
41 static char *tls_opt_keyfile = NULL;
42 static char *tls_opt_cacertfile = NULL;
43 static char *tls_opt_cacertdir = NULL;
44 static int  tls_opt_require_cert = 0;
45 static char *tls_opt_ciphersuite = NULL;
46 static char *tls_opt_randfile = NULL;
47
48 #define HAS_TLS( sb )   ber_sockbuf_ctrl( sb, LBER_SB_OPT_HAS_IO, \
49                                 (void *)&sb_tls_sbio )
50
51 static void tls_report_error( void );
52
53 static void tls_info_cb( SSL *ssl, int where, int ret );
54 static int tls_verify_cb( int ok, X509_STORE_CTX *ctx );
55 static RSA * tls_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
56 static STACK_OF(X509_NAME) * get_ca_list( char * bundle, char * dir );
57
58 #if 0   /* Currently this is not used by anyone */
59 static DH * tls_tmp_dh_cb( SSL *ssl, int is_export, int key_length );
60 #endif
61
62 static SSL_CTX *tls_def_ctx = NULL;
63
64 static int tls_seed_PRNG( const char *randfile );
65
66 #ifdef LDAP_R_COMPILE
67 /*
68  * provide mutexes for the SSLeay library.
69  */
70 static ldap_pvt_thread_mutex_t  tls_mutexes[CRYPTO_NUM_LOCKS];
71
72 static void tls_locking_cb( int mode, int type, const char *file, int line )
73 {
74         if ( mode & CRYPTO_LOCK ) {
75                 ldap_pvt_thread_mutex_lock( &tls_mutexes[type] );
76         } else {
77                 ldap_pvt_thread_mutex_unlock( &tls_mutexes[type] );
78         }
79 }
80
81 /*
82  * an extra mutex for the default ctx.
83  */
84
85 static ldap_pvt_thread_mutex_t tls_def_ctx_mutex;
86
87 static void tls_init_threads( void )
88 {
89         int i;
90
91         for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
92                 ldap_pvt_thread_mutex_init( &tls_mutexes[i] );
93         }
94         CRYPTO_set_locking_callback( tls_locking_cb );
95         /* FIXME: the thread id should be added somehow... */
96
97         ldap_pvt_thread_mutex_init( &tls_def_ctx_mutex );
98 }
99 #endif /* LDAP_R_COMPILE */
100
101 /*
102  * Tear down the TLS subsystem. Should only be called once.
103  */
104 void
105 ldap_pvt_tls_destroy( void )
106 {
107         SSL_CTX_free(tls_def_ctx);
108         EVP_cleanup();
109         ERR_free_strings();
110 }
111
112 /*
113  * Initialize TLS subsystem. Should be called only once.
114  */
115 int
116 ldap_pvt_tls_init( void )
117 {
118         static int tls_initialized = 0;
119
120         if ( tls_initialized ) return 0;
121         tls_initialized = 1;
122
123         (void) tls_seed_PRNG( tls_opt_randfile );
124
125 #ifdef LDAP_R_COMPILE
126         tls_init_threads();
127 #endif
128
129         SSL_load_error_strings();
130         SSLeay_add_ssl_algorithms();
131
132         /* FIXME: mod_ssl does this */
133         X509V3_add_standard_extensions();
134         return 0;
135 }
136
137 /*
138  * initialize the default context
139  */
140 int
141 ldap_pvt_tls_init_def_ctx( void )
142 {
143         STACK_OF(X509_NAME) *calist;
144
145 #ifdef LDAP_R_COMPILE
146         ldap_pvt_thread_mutex_lock( &tls_def_ctx_mutex );
147 #endif
148         if ( tls_def_ctx == NULL ) {
149                 tls_def_ctx = SSL_CTX_new( SSLv23_method() );
150                 if ( tls_def_ctx == NULL ) {
151                         Debug( LDAP_DEBUG_ANY,
152                        "TLS: could not allocate default ctx (%d).\n",
153                                 ERR_peek_error(),0,0);
154                         goto error_exit;
155                 }
156                 if ( tls_opt_ciphersuite &&
157                      !SSL_CTX_set_cipher_list( tls_def_ctx,
158                         tls_opt_ciphersuite ) )
159                 {
160                         Debug( LDAP_DEBUG_ANY,
161                                "TLS: could not set cipher list %s.\n",
162                                tls_opt_ciphersuite, 0, 0 );
163                         tls_report_error();
164                         goto error_exit;
165                 }
166                 if (tls_opt_cacertfile != NULL || tls_opt_cacertdir != NULL) {
167                         if ( !SSL_CTX_load_verify_locations( tls_def_ctx,
168                                                              tls_opt_cacertfile,
169                                                              tls_opt_cacertdir )
170                              || !SSL_CTX_set_default_verify_paths( tls_def_ctx ) )
171                         {
172                                 Debug( LDAP_DEBUG_ANY, "TLS: "
173                                         "could not load verify locations (file:`%s',dir:`%s').\n",
174                                         tls_opt_cacertfile ? tls_opt_cacertfile : "",
175                                         tls_opt_cacertdir ? tls_opt_cacertdir : "",
176                                         0 );
177                                 tls_report_error();
178                                 goto error_exit;
179                         }
180                         calist = get_ca_list( tls_opt_cacertfile, tls_opt_cacertdir );
181                         if ( !calist ) {
182                                 Debug( LDAP_DEBUG_ANY, "TLS: "
183                                         "could not load client CA list (file:`%s',dir:`%s').\n",
184                                         tls_opt_cacertfile ? tls_opt_cacertfile : "",
185                                         tls_opt_cacertdir ? tls_opt_cacertdir : "",
186                                         0 );
187                                 tls_report_error();
188                                 goto error_exit;
189                         }
190                         SSL_CTX_set_client_CA_list( tls_def_ctx, calist );
191                 }
192                 if ( tls_opt_keyfile &&
193                      !SSL_CTX_use_PrivateKey_file( tls_def_ctx,
194                                                    tls_opt_keyfile,
195                                                    SSL_FILETYPE_PEM ) )
196                 {
197                         Debug( LDAP_DEBUG_ANY,
198                                "TLS: could not use key file `%s'.\n",
199                                tls_opt_keyfile,0,0);
200                         tls_report_error();
201                         goto error_exit;
202                 }
203                 if ( tls_opt_certfile &&
204                      !SSL_CTX_use_certificate_file( tls_def_ctx,
205                                                     tls_opt_certfile,
206                                                     SSL_FILETYPE_PEM ) )
207                 {
208                         Debug( LDAP_DEBUG_ANY,
209                                "TLS: could not use certificate `%s'.\n",
210                                tls_opt_certfile,0,0);
211                         tls_report_error();
212                         goto error_exit;
213                 }
214                 if ( ( tls_opt_certfile || tls_opt_keyfile ) &&
215                      !SSL_CTX_check_private_key( tls_def_ctx ) )
216                 {
217                         Debug( LDAP_DEBUG_ANY,
218                                "TLS: private key mismatch.\n",
219                                0,0,0);
220                         tls_report_error();
221                         goto error_exit;
222                 }
223                 if ( tls_opt_trace ) {
224                         SSL_CTX_set_info_callback( tls_def_ctx, tls_info_cb );
225                 }
226                 SSL_CTX_set_verify( tls_def_ctx,
227                         tls_opt_require_cert ?
228                         (SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT) :
229                         SSL_VERIFY_NONE,
230                         tls_verify_cb );
231                 SSL_CTX_set_tmp_rsa_callback( tls_def_ctx, tls_tmp_rsa_cb );
232                 /* SSL_CTX_set_tmp_dh_callback( tls_def_ctx, tls_tmp_dh_cb ); */
233         }
234 #ifdef LDAP_R_COMPILE
235         ldap_pvt_thread_mutex_unlock( &tls_def_ctx_mutex );
236 #endif
237         return 0;
238 error_exit:
239         if ( tls_def_ctx != NULL ) {
240                 SSL_CTX_free( tls_def_ctx );
241                 tls_def_ctx = NULL;
242         }
243 #ifdef LDAP_R_COMPILE
244         ldap_pvt_thread_mutex_unlock( &tls_def_ctx_mutex );
245 #endif
246         return -1;
247 }
248
249 static STACK_OF(X509_NAME) *
250 get_ca_list( char * bundle, char * dir )
251 {
252         STACK_OF(X509_NAME) *ca_list = NULL;
253
254         if ( bundle ) {
255                 ca_list = SSL_load_client_CA_file( bundle );
256         }
257         /*
258          * FIXME: We have now to go over all files in dir, load them
259          * and add every certificate there to ca_list.
260          */
261         return ca_list;
262 }
263
264 static SSL *
265 alloc_handle( void *ctx_arg )
266 {
267         SSL_CTX *ctx;
268         SSL     *ssl;
269
270         if ( ctx_arg ) {
271                 ctx = (SSL_CTX *) ctx_arg;
272         } else {
273                 if ( ldap_pvt_tls_init_def_ctx() < 0 ) return NULL;
274                 ctx = tls_def_ctx;
275         }
276
277         ssl = SSL_new( ctx );
278         if ( ssl == NULL ) {
279                 Debug( LDAP_DEBUG_ANY,"TLS: can't create ssl handle.\n",0,0,0);
280                 return NULL;
281         }
282         return ssl;
283 }
284
285 static int
286 update_flags( Sockbuf *sb, SSL * ssl, int rc )
287 {
288         int err = SSL_get_error(ssl, rc);
289
290         sb->sb_trans_needs_read  = 0;
291         sb->sb_trans_needs_write = 0;
292         if (err == SSL_ERROR_WANT_READ)
293         {
294             sb->sb_trans_needs_read  = 1;
295             return 1;
296         } else if (err == SSL_ERROR_WANT_WRITE)
297         {
298             sb->sb_trans_needs_write = 1;
299             return 1;
300         } else if (err == SSL_ERROR_WANT_CONNECT)
301         {
302             return 1;
303         }
304         return 0;
305 }
306
307 /*
308  * TLS support for LBER Sockbufs
309  */
310
311 struct tls_data {
312         SSL                     *ssl;
313         Sockbuf_IO_Desc         *sbiod;
314 };
315
316 static BIO_METHOD sb_tls_bio_method;
317
318 static int
319 sb_tls_setup( Sockbuf_IO_Desc *sbiod, void *arg )
320 {
321         struct tls_data         *p;
322         BIO                     *bio;
323
324         assert( sbiod != NULL );
325
326         p = LBER_MALLOC( sizeof( *p ) );
327         if ( p == NULL )
328                 return -1;
329         
330         p->ssl = (SSL *)arg;
331         p->sbiod = sbiod;
332         bio = BIO_new( &sb_tls_bio_method );
333         bio->ptr = (void *)p;
334         SSL_set_bio( p->ssl, bio, bio );
335         sbiod->sbiod_pvt = p;
336         return 0;
337 }
338
339 static int
340 sb_tls_remove( Sockbuf_IO_Desc *sbiod )
341 {
342         struct tls_data         *p;
343         
344         assert( sbiod != NULL );
345         assert( sbiod->sbiod_pvt != NULL );
346
347         p = (struct tls_data *)sbiod->sbiod_pvt;
348         SSL_free( p->ssl );
349         LBER_FREE( sbiod->sbiod_pvt );
350         sbiod->sbiod_pvt = NULL;
351         return 0;
352 }
353
354 static int
355 sb_tls_close( Sockbuf_IO_Desc *sbiod )
356 {
357         struct tls_data         *p;
358         
359         assert( sbiod != NULL );
360         assert( sbiod->sbiod_pvt != NULL );
361
362         p = (struct tls_data *)sbiod->sbiod_pvt;
363         SSL_shutdown( p->ssl );
364         return 0;
365 }
366
367 static int
368 sb_tls_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
369 {
370         struct tls_data         *p;
371         
372         assert( sbiod != NULL );
373         assert( sbiod->sbiod_pvt != NULL );
374
375         p = (struct tls_data *)sbiod->sbiod_pvt;
376         
377         if ( opt == LBER_SB_OPT_GET_SSL ) {
378                 *((SSL **)arg) = p->ssl;
379                 return 1;
380
381         } else if ( opt == LBER_SB_OPT_DATA_READY ) {
382                 if( SSL_pending( p->ssl ) > 0 ) {
383                         return 1;
384                 }
385         }
386         
387         return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
388 }
389
390 static ber_slen_t
391 sb_tls_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
392 {
393         struct tls_data         *p;
394         ber_slen_t              ret;
395         int                     err;
396
397         assert( sbiod != NULL );
398         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
399
400         p = (struct tls_data *)sbiod->sbiod_pvt;
401
402         ret = SSL_read( p->ssl, (char *)buf, len );
403 #ifdef HAVE_WINSOCK
404         errno = WSAGetLastError();
405 #endif
406         err = SSL_get_error( p->ssl, ret );
407         if (err == SSL_ERROR_WANT_READ ) {
408                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
409 #ifdef WIN32
410                 errno = EWOULDBLOCK;
411 #endif
412         }
413         else
414                 sbiod->sbiod_sb->sb_trans_needs_read = 0;
415         return ret;
416 }
417
418 static ber_slen_t
419 sb_tls_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
420 {
421         struct tls_data         *p;
422         ber_slen_t              ret;
423         int                     err;
424
425         assert( sbiod != NULL );
426         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
427
428         p = (struct tls_data *)sbiod->sbiod_pvt;
429
430         ret = SSL_write( p->ssl, (char *)buf, len );
431 #ifdef HAVE_WINSOCK
432         errno = WSAGetLastError();
433 #endif
434         err = SSL_get_error( p->ssl, ret );
435         if (err == SSL_ERROR_WANT_WRITE ) {
436                 sbiod->sbiod_sb->sb_trans_needs_write = 1;
437 #ifdef WIN32
438                 errno = EWOULDBLOCK;
439 #endif
440         }
441         else
442                 sbiod->sbiod_sb->sb_trans_needs_write = 0;
443         return ret;
444 }
445
446 static Sockbuf_IO sb_tls_sbio =
447 {
448         sb_tls_setup,           /* sbi_setup */
449         sb_tls_remove,          /* sbi_remove */
450         sb_tls_ctrl,            /* sbi_ctrl */
451         sb_tls_read,            /* sbi_read */
452         sb_tls_write,           /* sbi_write */
453         sb_tls_close            /* sbi_close */
454 };
455
456 static int
457 sb_tls_bio_create( BIO *b ) {
458         b->init = 1;
459         b->num = 0;
460         b->ptr = NULL;
461         b->flags = 0;
462         return 1;
463 }
464
465 static int
466 sb_tls_bio_destroy( BIO *b )
467 {
468         if ( b == NULL )
469                 return 0;
470
471         b->ptr = NULL;          /* sb_tls_remove() will free it */
472         b->init = 0;
473         b->flags = 0;
474         return 1;
475 }
476
477 static int
478 sb_tls_bio_read( BIO *b, char *buf, int len )
479 {
480         struct tls_data         *p;
481         int                     ret;
482                 
483         if ( buf == NULL || len <= 0 )
484                 return 0;
485
486         p = (struct tls_data *)b->ptr;
487
488         if ( p == NULL || p->sbiod == NULL )
489                 return 0;
490
491         ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
492
493         BIO_clear_retry_flags( b );
494         if ( ret < 0 && errno == EWOULDBLOCK )
495                 BIO_set_retry_read( b );
496
497         return ret;
498 }
499
500 static int
501 sb_tls_bio_write( BIO *b, const char *buf, int len )
502 {
503         struct tls_data         *p;
504         int                     ret;
505         
506         if ( buf == NULL || len <= 0 )
507                 return 0;
508         
509         p = (struct tls_data *)b->ptr;
510
511         if ( p == NULL || p->sbiod == NULL )
512                 return 0;
513
514         ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
515
516         BIO_clear_retry_flags( b );
517         if ( ret < 0 && errno == EWOULDBLOCK )
518                 BIO_set_retry_write( b );
519
520         return ret;
521 }
522
523 static long
524 sb_tls_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
525 {
526         if ( cmd == BIO_CTRL_FLUSH ) {
527                 /* The OpenSSL library needs this */
528                 return 1;
529         }
530         return 0;
531 }
532
533 static int
534 sb_tls_bio_gets( BIO *b, char *buf, int len )
535 {
536         return -1;
537 }
538
539 static int
540 sb_tls_bio_puts( BIO *b, const char *str )
541 {
542         return sb_tls_bio_write( b, str, strlen( str ) );
543 }
544         
545 static BIO_METHOD sb_tls_bio_method =
546 {
547         ( 100 | 0x400 ),                /* it's a source/sink BIO */
548         "sockbuf glue",
549         sb_tls_bio_write,
550         sb_tls_bio_read,
551         sb_tls_bio_puts,
552         sb_tls_bio_gets,
553         sb_tls_bio_ctrl,
554         sb_tls_bio_create,
555         sb_tls_bio_destroy
556 };
557
558 /*
559  * Call this to do a TLS connect on a sockbuf. ctx_arg can be
560  * a SSL_CTX * or NULL, in which case the default ctx is used.
561  *
562  * Return value:
563  *
564  *  0 - Success. Connection is ready for communication.
565  * <0 - Error. Can't create a TLS stream.
566  * >0 - Partial success.
567  *        Do a select (using information from lber_pvt_sb_needs_{read,write}
568  *              and call again.
569  */
570
571 static int
572 ldap_int_tls_connect( LDAP *ld, LDAPConn *conn )
573 {
574         Sockbuf *sb = conn->lconn_sb;
575         int     err;
576         SSL     *ssl;
577
578         if ( HAS_TLS( sb ) ) {
579                 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&ssl );
580
581         } else {
582                 void *ctx = ld->ld_defconn
583                         ? ld->ld_defconn->lconn_tls_ctx : NULL;
584
585                 ssl = alloc_handle( ctx );
586
587                 if ( ssl == NULL ) return -1;
588
589 #ifdef LDAP_DEBUG
590                 ber_sockbuf_add_io( sb, &ber_sockbuf_io_debug,
591                         LBER_SBIOD_LEVEL_TRANSPORT, (void *)"tls_" );
592 #endif
593                 ber_sockbuf_add_io( sb, &sb_tls_sbio,
594                         LBER_SBIOD_LEVEL_TRANSPORT, (void *)ssl );
595
596                 if( ctx == NULL ) {
597                         conn->lconn_tls_ctx = tls_def_ctx;
598                 }
599         }
600
601         err = SSL_connect( ssl );
602
603 #ifdef HAVE_WINSOCK
604         errno = WSAGetLastError();
605 #endif
606         if ( err <= 0 ) {
607                 if ( update_flags( sb, ssl, err )) {
608                         return 1;
609                 }
610                 if ((err = ERR_peek_error())) {
611                         char buf[256];
612                         ld->ld_error = LDAP_STRDUP(ERR_error_string(err, buf));
613                 }
614                 Debug( LDAP_DEBUG_ANY,"TLS: can't connect.\n",0,0,0);
615                 ber_sockbuf_remove_io( sb, &sb_tls_sbio,
616                         LBER_SBIOD_LEVEL_TRANSPORT );
617 #ifdef LDAP_DEBUG
618                 ber_sockbuf_remove_io( sb, &ber_sockbuf_io_debug,
619                         LBER_SBIOD_LEVEL_TRANSPORT );
620 #endif
621                 return -1;
622         }
623
624         return 0;
625 }
626
627 /*
628  * Call this to do a TLS accept on a sockbuf.
629  * Everything else is the same as with tls_connect.
630  */
631 int
632 ldap_pvt_tls_accept( Sockbuf *sb, void *ctx_arg )
633 {
634         int     err;
635         SSL     *ssl;
636
637         if ( HAS_TLS( sb ) ) {
638                 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&ssl );
639         } else {
640                 ssl = alloc_handle( ctx_arg );
641                 if ( ssl == NULL )
642                         return -1;
643 #ifdef LDAP_DEBUG
644                 ber_sockbuf_add_io( sb, &ber_sockbuf_io_debug,
645                         LBER_SBIOD_LEVEL_TRANSPORT, (void *)"tls_" );
646 #endif
647                 ber_sockbuf_add_io( sb, &sb_tls_sbio,
648                         LBER_SBIOD_LEVEL_TRANSPORT, (void *)ssl );
649         }
650
651         err = SSL_accept( ssl );
652
653 #ifdef HAVE_WINSOCK
654         errno = WSAGetLastError();
655 #endif
656         if ( err <= 0 ) {
657                 if ( update_flags( sb, ssl, err ))
658                         return 1;
659                 Debug( LDAP_DEBUG_ANY,"TLS: can't accept.\n",0,0,0 );
660                 tls_report_error();
661                 ber_sockbuf_remove_io( sb, &sb_tls_sbio,
662                         LBER_SBIOD_LEVEL_TRANSPORT );
663 #ifdef LDAP_DEBUG
664                 ber_sockbuf_remove_io( sb, &ber_sockbuf_io_debug,
665                         LBER_SBIOD_LEVEL_TRANSPORT );
666 #endif
667                 return -1;
668         }
669
670         return 0;
671 }
672
673 int
674 ldap_pvt_tls_inplace ( Sockbuf *sb )
675 {
676         if ( HAS_TLS( sb ) )
677                 return(1);
678         return(0);
679 }
680
681 void *
682 ldap_pvt_tls_sb_ctx( Sockbuf *sb )
683 {
684         void                    *p;
685         
686         if (HAS_TLS( sb )) {
687                 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&p );
688                 return p;
689         }
690
691         return NULL;
692 }
693
694 int
695 ldap_pvt_tls_get_strength( void *s )
696 {
697     SSL_CIPHER *c;
698
699     c = SSL_get_current_cipher((SSL *)s);
700     return SSL_CIPHER_get_bits(c, NULL);
701 }
702
703
704 char *
705 ldap_pvt_tls_get_peer( void *s )
706 {
707     X509 *x;
708     X509_NAME *xn;
709     char buf[2048], *p;
710
711     x = SSL_get_peer_certificate((SSL *)s);
712
713     if (!x)
714         return NULL;
715     
716     xn = X509_get_subject_name(x);
717     p = LDAP_STRDUP(X509_NAME_oneline(xn, buf, sizeof(buf)));
718     X509_free(x);
719     return p;
720 }
721
722 char *
723 ldap_pvt_tls_get_peer_dn( void *s )
724 {
725         X509 *x;
726         X509_NAME *xn;
727         char buf[2048], *p, *dn;
728
729         x = SSL_get_peer_certificate((SSL *)s);
730
731         if (!x) return NULL;
732     
733         xn = X509_get_subject_name(x);
734         p = X509_NAME_oneline(xn, buf, sizeof(buf));
735
736         dn = ldap_dcedn2dn( p );
737
738         X509_free(x);
739         return dn;
740 }
741
742 char *
743 ldap_pvt_tls_get_peer_hostname( void *s )
744 {
745         X509 *x;
746         X509_NAME *xn;
747         char buf[2048], *p;
748         int ret;
749
750         x = SSL_get_peer_certificate((SSL *)s);
751
752         if (!x)
753                 return NULL;
754         
755         xn = X509_get_subject_name(x);
756
757         ret = X509_NAME_get_text_by_NID(xn, NID_commonName, buf, sizeof(buf));
758         if( ret == -1 ) {
759                 X509_free(x);
760                 return NULL;
761         }
762
763         p = LDAP_STRDUP(buf);
764         X509_free(x);
765         return p;
766 }
767
768 int
769 ldap_pvt_tls_check_hostname( void *s, const char *name_in )
770 {
771     int i, ret = LDAP_LOCAL_ERROR;
772     X509 *x;
773         const char *name;
774
775         if( ldap_int_hostname &&
776                 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
777         {
778                 name = ldap_int_hostname;
779         } else {
780                 name = name_in;
781         }
782
783     x = SSL_get_peer_certificate((SSL *)s);
784     if (!x)
785     {
786         Debug( LDAP_DEBUG_ANY,
787                 "TLS: unable to get peer certificate.\n",
788                 0, 0, 0 );
789         return ret;
790     }
791
792     i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
793     if (i >= 0)
794     {
795         X509_EXTENSION *ex;
796         STACK_OF(GENERAL_NAME) *alt;
797
798         ex = X509_get_ext(x, i);
799         alt = X509V3_EXT_d2i(ex);
800         if (alt)
801         {
802             int n, len1, len2;
803             char *domain;
804             GENERAL_NAME *gn;
805             X509V3_EXT_METHOD *method;
806
807             len1 = strlen(name);
808             n = sk_GENERAL_NAME_num(alt);
809             domain = strchr(name, '.');
810             if (domain)
811                 len2 = len1 - (domain-name);
812             for (i=0; i<n; i++)
813             {
814                 gn = sk_GENERAL_NAME_value(alt, i);
815                 if (gn->type == GEN_DNS)
816                 {
817                     char *sn = ASN1_STRING_data(gn->d.ia5);
818                     int sl = ASN1_STRING_length(gn->d.ia5);
819
820                     /* Is this an exact match? */
821                     if ((len1 == sl) && !strncasecmp(name, sn, len1))
822                         break;
823
824                     /* Is this a wildcard match? */
825                     if ((*sn == '*') && domain && (len2 == sl-1) &&
826                         !strncasecmp(domain, sn+1, len2))
827                         break;
828                 }
829             }
830             method = X509V3_EXT_get(ex);
831             method->ext_free(alt);
832             if (i < n)  /* Found a match */
833                 ret = LDAP_SUCCESS;
834         }
835     }
836
837     if (ret != LDAP_SUCCESS)
838     {
839         X509_NAME *xn;
840         char buf[2048];
841
842         xn = X509_get_subject_name(x);
843
844         if (X509_NAME_get_text_by_NID(xn, NID_commonName, buf, sizeof(buf))
845             == -1)
846         {
847             Debug( LDAP_DEBUG_ANY,
848                     "TLS: unable to get common name from peer certificate.\n",
849                     0, 0, 0 );
850         } else if (strcasecmp(name, buf))
851         {
852             Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
853                     "common name in certificate (%s).\n", 
854                     name, buf, 0 );
855             ret =  LDAP_CONNECT_ERROR;
856         } else
857         {
858             ret = LDAP_SUCCESS;
859         }
860     }
861     X509_free(x);
862     return ret;
863 }
864
865 const char *
866 ldap_pvt_tls_get_peer_issuer( void *s )
867 {
868 #if 0   /* currently unused; see ldap_pvt_tls_get_peer() if needed */
869     X509 *x;
870     X509_NAME *xn;
871     char buf[2048], *p;
872
873     x = SSL_get_peer_certificate((SSL *)s);
874
875     if (!x)
876         return NULL;
877     
878     xn = X509_get_issuer_name(x);
879     p = LDAP_STRDUP(X509_NAME_oneline(xn, buf, sizeof(buf)));
880     X509_free(x);
881     return p;
882 #else
883     return NULL;
884 #endif
885 }
886
887 int
888 ldap_int_tls_config( LDAP *ld, int option, const char *arg )
889 {
890         int i;
891
892         switch( option ) {
893         case LDAP_OPT_X_TLS_CACERTFILE:
894         case LDAP_OPT_X_TLS_CACERTDIR:
895         case LDAP_OPT_X_TLS_CERTFILE:
896         case LDAP_OPT_X_TLS_KEYFILE:
897         case LDAP_OPT_X_TLS_RANDOM_FILE:
898                 return ldap_pvt_tls_set_option( ld, option, (void *) arg );
899
900         case LDAP_OPT_X_TLS_REQUIRE_CERT:
901                 i = ( ( strcasecmp( arg, "on" ) == 0 ) ||
902                       ( strcasecmp( arg, "yes" ) == 0) ||
903                       ( strcasecmp( arg, "true" ) == 0 ) );
904                 return ldap_pvt_tls_set_option( ld, option, (void *) &i );
905
906         case LDAP_OPT_X_TLS:
907                 i = -1;
908                 if ( strcasecmp( arg, "never" ) == 0 )
909                         i = LDAP_OPT_X_TLS_NEVER ;
910                 if ( strcasecmp( arg, "demand" ) == 0 )
911                         i = LDAP_OPT_X_TLS_DEMAND ;
912                 if ( strcasecmp( arg, "allow" ) == 0 )
913                         i = LDAP_OPT_X_TLS_ALLOW ;
914                 if ( strcasecmp( arg, "try" ) == 0 )
915                         i = LDAP_OPT_X_TLS_TRY ;
916                 if ( strcasecmp( arg, "hard" ) == 0 )
917                         i = LDAP_OPT_X_TLS_HARD ;
918
919                 if (i >= 0) {
920                         return ldap_pvt_tls_set_option( ld, option, &i );
921                 }
922                 return -1;
923         }
924
925         return -1;
926 }
927
928 int
929 ldap_pvt_tls_get_option( LDAP *ld, int option, void *arg )
930 {
931         struct ldapoptions *lo;
932
933         if( ld != NULL ) {
934                 assert( LDAP_VALID( ld ) );
935
936                 if( !LDAP_VALID( ld ) ) {
937                         return LDAP_OPT_ERROR;
938                 }
939
940                 lo = &ld->ld_options;
941
942         } else {
943                 /* Get pointer to global option structure */
944                 lo = LDAP_INT_GLOBAL_OPT();   
945                 if ( lo == NULL ) {
946                         return LDAP_NO_MEMORY;
947                 }
948         }
949
950         switch( option ) {
951         case LDAP_OPT_X_TLS:
952                 *(int *)arg = lo->ldo_tls_mode;
953                 break;
954         case LDAP_OPT_X_TLS_CTX:
955                 if ( ld == NULL )
956                         *(void **)arg = (void *) tls_def_ctx;
957                 else
958                         *(void **)arg = ld->ld_defconn->lconn_tls_ctx;
959                 break;
960         case LDAP_OPT_X_TLS_CACERTFILE:
961                 *(char **)arg = tls_opt_cacertfile ?
962                         LDAP_STRDUP( tls_opt_cacertfile ) : NULL;
963                 break;
964         case LDAP_OPT_X_TLS_CACERTDIR:
965                 *(char **)arg = tls_opt_cacertdir ?
966                         LDAP_STRDUP( tls_opt_cacertdir ) : NULL;
967                 break;
968         case LDAP_OPT_X_TLS_CERTFILE:
969                 *(char **)arg = tls_opt_certfile ?
970                         LDAP_STRDUP( tls_opt_certfile ) : NULL;
971                 break;
972         case LDAP_OPT_X_TLS_KEYFILE:
973                 *(char **)arg = tls_opt_keyfile ?
974                         LDAP_STRDUP( tls_opt_keyfile ) : NULL;
975                 break;
976         case LDAP_OPT_X_TLS_REQUIRE_CERT:
977                 *(int *)arg = tls_opt_require_cert;
978                 break;
979         case LDAP_OPT_X_TLS_RANDOM_FILE:
980                 *(char **)arg = tls_opt_randfile;
981                 break;
982         default:
983                 return -1;
984         }
985         return 0;
986 }
987
988 int
989 ldap_pvt_tls_set_option( LDAP *ld, int option, void *arg )
990 {
991         struct ldapoptions *lo;
992
993         if( ld != NULL ) {
994                 assert( LDAP_VALID( ld ) );
995
996                 if( !LDAP_VALID( ld ) ) {
997                         return LDAP_OPT_ERROR;
998                 }
999
1000                 lo = &ld->ld_options;
1001
1002         } else {
1003                 /* Get pointer to global option structure */
1004                 lo = LDAP_INT_GLOBAL_OPT();   
1005                 if ( lo == NULL ) {
1006                         return LDAP_NO_MEMORY;
1007                 }
1008         }
1009
1010         switch( option ) {
1011         case LDAP_OPT_X_TLS:
1012                 switch( *(int *) arg ) {
1013                 case LDAP_OPT_X_TLS_NEVER:
1014                 case LDAP_OPT_X_TLS_DEMAND:
1015                 case LDAP_OPT_X_TLS_ALLOW:
1016                 case LDAP_OPT_X_TLS_TRY:
1017                 case LDAP_OPT_X_TLS_HARD:
1018                         if (lo != NULL) {
1019                                 lo->ldo_tls_mode = *(int *)arg;
1020                         }
1021
1022                         return 0;
1023                 }
1024                 return -1;
1025
1026         case LDAP_OPT_X_TLS_CTX:
1027                 if ( ld == NULL ) {
1028                         tls_def_ctx = (SSL_CTX *) arg;
1029
1030                 } else {
1031                         ld->ld_defconn->lconn_tls_ctx = arg;
1032                 }
1033                 return 0;
1034         }
1035
1036         if ( ld != NULL ) {
1037                 return -1;
1038         }
1039
1040         switch( option ) {
1041         case LDAP_OPT_X_TLS_CACERTFILE:
1042                 if ( tls_opt_cacertfile ) LDAP_FREE( tls_opt_cacertfile );
1043                 tls_opt_cacertfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1044                 break;
1045         case LDAP_OPT_X_TLS_CACERTDIR:
1046                 if ( tls_opt_cacertdir ) LDAP_FREE( tls_opt_cacertdir );
1047                 tls_opt_cacertdir = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1048                 break;
1049         case LDAP_OPT_X_TLS_CERTFILE:
1050                 if ( tls_opt_certfile ) LDAP_FREE( tls_opt_certfile );
1051                 tls_opt_certfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1052                 break;
1053         case LDAP_OPT_X_TLS_KEYFILE:
1054                 if ( tls_opt_keyfile ) LDAP_FREE( tls_opt_keyfile );
1055                 tls_opt_keyfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1056                 break;
1057         case LDAP_OPT_X_TLS_REQUIRE_CERT:
1058                 tls_opt_require_cert = * (int *) arg;
1059                 break;
1060         case LDAP_OPT_X_TLS_CIPHER_SUITE:
1061                 if ( tls_opt_ciphersuite ) LDAP_FREE( tls_opt_ciphersuite );
1062                 tls_opt_ciphersuite = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1063                 break;
1064         case LDAP_OPT_X_TLS_RANDOM_FILE:
1065                 if (tls_opt_randfile ) LDAP_FREE (tls_opt_randfile );
1066                 tls_opt_randfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1067                 break;
1068         default:
1069                 return -1;
1070         }
1071         return 0;
1072 }
1073
1074 int
1075 ldap_int_tls_start ( LDAP *ld, LDAPConn *conn, LDAPURLDesc *srv )
1076 {
1077         Sockbuf *sb = conn->lconn_sb;
1078         char *host;
1079         void *ssl;
1080
1081         if( srv ) {
1082                 host = srv->lud_host;
1083         } else {
1084                 host = conn->lconn_server->lud_host;
1085         }
1086
1087         /* avoid NULL host */
1088         if( host == NULL ) {
1089                 host = "localhost";
1090         }
1091
1092         (void) ldap_pvt_tls_init();
1093
1094         /*
1095          * Fortunately, the lib uses blocking io...
1096          */
1097         if ( ldap_int_tls_connect( ld, conn ) < 0 ) {
1098                 ld->ld_errno = LDAP_CONNECT_ERROR;
1099                 return (ld->ld_errno);
1100         }
1101
1102         ssl = (void *) ldap_pvt_tls_sb_ctx( sb );
1103         assert( ssl != NULL );
1104
1105         /* 
1106          * compare host with name(s) in certificate
1107          */
1108         ld->ld_errno = ldap_pvt_tls_check_hostname( ssl, host );
1109         if (ld->ld_errno != LDAP_SUCCESS) {
1110                 return ld->ld_errno;
1111         }
1112
1113         /*
1114          * set SASL properties to TLS ssf and authid
1115          */
1116         {
1117                 const char *authid;
1118                 ber_len_t ssf;
1119
1120                 /* we need to let SASL know */
1121                 ssf = ldap_pvt_tls_get_strength( ssl );
1122                 authid = ldap_pvt_tls_get_peer( ssl );
1123
1124                 (void) ldap_int_sasl_external( ld, conn, authid, ssf );
1125         }
1126
1127         return LDAP_SUCCESS;
1128 }
1129
1130 /* Derived from openssl/apps/s_cb.c */
1131 static void
1132 tls_info_cb( SSL *ssl, int where, int ret )
1133 {
1134         int w;
1135         char *op;
1136
1137         w = where & ~SSL_ST_MASK;
1138         if ( w & SSL_ST_CONNECT ) {
1139                 op = "SSL_connect";
1140         } else if ( w & SSL_ST_ACCEPT ) {
1141                 op = "SSL_accept";
1142         } else {
1143                 op = "undefined";
1144         }
1145
1146         if ( where & SSL_CB_LOOP ) {
1147                 Debug( LDAP_DEBUG_TRACE,
1148                        "TLS trace: %s:%s\n",
1149                        op, SSL_state_string_long( ssl ), 0 );
1150         } else if ( where & SSL_CB_ALERT ) {
1151                 op = ( where & SSL_CB_READ ) ? "read" : "write";
1152                 Debug( LDAP_DEBUG_TRACE,
1153                        "TLS trace: SSL3 alert %s:%s:%s\n",
1154                        op,
1155                        SSL_alert_type_string_long( ret ),
1156                        SSL_alert_desc_string_long( ret) );
1157         } else if ( where & SSL_CB_EXIT ) {
1158                 if ( ret == 0 ) {
1159                         Debug( LDAP_DEBUG_TRACE,
1160                                "TLS trace: %s:failed in %s\n",
1161                                op, SSL_state_string_long( ssl ), 0 );
1162                 } else if ( ret < 0 ) {
1163                         Debug( LDAP_DEBUG_TRACE,
1164                                "TLS trace: %s:error in %s\n",
1165                                op, SSL_state_string_long( ssl ), 0 );
1166                 }
1167         }
1168 }
1169
1170 static int
1171 tls_verify_cb( int ok, X509_STORE_CTX *ctx )
1172 {
1173         X509 *cert;
1174         int errnum;
1175         int errdepth;
1176         X509_NAME *subject;
1177         X509_NAME *issuer;
1178         char *sname;
1179         char *iname;
1180
1181         cert = X509_STORE_CTX_get_current_cert( ctx );
1182         errnum = X509_STORE_CTX_get_error( ctx );
1183         errdepth = X509_STORE_CTX_get_error_depth( ctx );
1184
1185         /*
1186          * X509_get_*_name return pointers to the internal copies of
1187          * those things requested.  So do not free them.
1188          */
1189         subject = X509_get_subject_name( cert );
1190         issuer = X509_get_issuer_name( cert );
1191         /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1192         sname = X509_NAME_oneline( subject, NULL, 0 );
1193         iname = X509_NAME_oneline( issuer, NULL, 0 );
1194         Debug( LDAP_DEBUG_TRACE,
1195                "TLS certificate verification: depth: %d, subject: %s, issuer: %s\n",
1196                errdepth,
1197                sname ? sname : "-unknown-",
1198                iname ? iname : "-unknown-" );
1199         if ( sname )
1200                 CRYPTO_free ( sname );
1201         if ( iname )
1202                 CRYPTO_free ( iname );
1203
1204         return ok;
1205 }
1206
1207 /* Inspired by ERR_print_errors in OpenSSL */
1208 static void
1209 tls_report_error( void )
1210 {
1211         unsigned long l;
1212         char buf[200];
1213         const char *file;
1214         int line;
1215
1216         while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1217                         Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1218                                ERR_error_string( l, buf ), file, line );
1219         }
1220 }
1221
1222 static RSA *
1223 tls_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1224 {
1225         RSA *tmp_rsa;
1226
1227         /* FIXME:  Pregenerate the key on startup */
1228         /* FIXME:  Who frees the key? */
1229         tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1230
1231         if ( !tmp_rsa ) {
1232                 Debug( LDAP_DEBUG_ANY,
1233                         "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1234                         key_length, is_export ? "export" : "domestic", 0 );
1235                 return NULL;
1236         }
1237         return tmp_rsa;
1238 }
1239
1240 static int
1241 tls_seed_PRNG( const char *randfile )
1242 {
1243 #ifndef URANDOM_DEVICE
1244         /* no /dev/urandom (or equiv) */
1245         long total=0;
1246         char buffer[MAXPATHLEN];
1247
1248         if (randfile == NULL) {
1249                 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1250                  * If $HOME is not set or buffer too small to hold the pathname,
1251                  * an error occurs.    - From RAND_file_name() man page.
1252                  * The fact is that when $HOME is NULL, .rnd is used.
1253                  */
1254                 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1255
1256         } else if (RAND_egd(randfile) > 0) {
1257                 /* EGD socket */
1258                 return 0;
1259         }
1260
1261         if (randfile == NULL) {
1262                 Debug( LDAP_DEBUG_ANY,
1263                         "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1264                         0, 0, 0);
1265                 return -1;
1266         }
1267
1268         total = RAND_load_file(randfile, -1);
1269
1270         if (RAND_status() == 0) {
1271                 Debug( LDAP_DEBUG_ANY,
1272                         "TLS: PRNG not been seeded with enough data\n",
1273                         0, 0, 0);
1274                 return -1;
1275         }
1276
1277         /* assume if there was enough bits to seed that it's okay
1278          * to write derived bits to the file
1279          */
1280         RAND_write_file(randfile);
1281
1282 #endif
1283
1284         return 0;
1285 }
1286
1287 #if 0
1288 static DH *
1289 tls_tmp_dh_cb( SSL *ssl, int is_export, int key_length )
1290 {
1291         return NULL;
1292 }
1293 #endif
1294 #endif
1295
1296 int
1297 ldap_start_tls_s ( LDAP *ld,
1298         LDAPControl **serverctrls,
1299         LDAPControl **clientctrls )
1300 {
1301         int rc;
1302
1303 #ifdef HAVE_TLS
1304         char *rspoid = NULL;
1305         struct berval *rspdata = NULL;
1306
1307         /* XXYYZ: this initiates operation only on default connection! */
1308
1309         if ( ldap_pvt_tls_inplace( ld->ld_sb ) != 0 ) {
1310                 return LDAP_LOCAL_ERROR;
1311         }
1312
1313         rc = ldap_extended_operation_s( ld, LDAP_EXOP_START_TLS,
1314                 NULL, serverctrls, clientctrls, &rspoid, &rspdata );
1315         if ( rc != LDAP_SUCCESS ) {
1316                 return rc;
1317         }
1318
1319         if ( rspoid != NULL ) {
1320                 LDAP_FREE(rspoid);
1321         }
1322
1323         if ( rspdata != NULL ) {
1324                 ber_bvfree( rspdata );
1325         }
1326
1327         rc = ldap_int_tls_start( ld, ld->ld_defconn, NULL );
1328 #else
1329         rc = LDAP_NOT_SUPPORTED;
1330 #endif
1331         return rc;
1332 }
1333