]> git.sur5r.net Git - openldap/blob - libraries/libldap/tls.c
53c4e3b0804090d6387be7feaa05873f3a9bc527
[openldap] / libraries / libldap / tls.c
1 /* $OpenLDAP$ */
2 /*
3  * Copyright 1998-1999 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 #ifdef HAVE_TLS
12
13 #include <stdio.h>
14
15 #include <ac/stdlib.h>
16 #include <ac/errno.h>
17 #include <ac/socket.h>
18 #include <ac/string.h>
19 #include <ac/time.h>
20 #include <ac/unistd.h>
21
22 #include "ldap-int.h"
23
24 #ifdef LDAP_R_COMPILE
25 #include <ldap_pvt_thread.h>
26 #endif
27
28 #ifdef HAVE_OPENSSL_SSL_H
29 #include <openssl/ssl.h>
30 #elif defined( HAVE_SSL_H )
31 #include <ssl.h>
32 #endif
33
34 static int  tls_opt_trace = 1;
35 static char *tls_opt_certfile = NULL;
36 static char *tls_opt_keyfile = NULL;
37 static char *tls_opt_cacertfile = NULL;
38 static char *tls_opt_cacertdir = NULL;
39 static int  tls_opt_require_cert = 0;
40 static char *tls_opt_ciphersuite = NULL;
41
42 #define HAS_TLS( sb ) ((sb)->sb_io==&tls_io)
43
44 static int tls_setup( Sockbuf *sb, void *arg );
45 static int tls_remove( Sockbuf *sb );
46 static ber_slen_t tls_read( Sockbuf *sb, void *buf, ber_len_t len );
47 static ber_slen_t tls_write( Sockbuf *sb, void *buf, ber_len_t len );
48 static int tls_close( Sockbuf *sb );
49 static int tls_report_error( void );
50
51 static Sockbuf_IO tls_io=
52 {
53    tls_setup,
54    tls_remove,
55    tls_read,
56    tls_write,
57    tls_close
58 };
59
60 static void tls_info_cb( SSL *ssl, int where, int ret );
61 static int tls_verify_cb( int ok, X509_STORE_CTX *ctx );
62 static RSA * tls_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
63 static DH * tls_tmp_dh_cb( SSL *ssl, int is_export, int key_length );
64 static STACK_OF(X509_NAME) * get_ca_list( char * bundle, char * dir );
65
66 static SSL_CTX *tls_def_ctx = NULL;
67
68 #ifdef LDAP_R_COMPILE
69 /*
70  * provide mutexes for the SSLeay library.
71  */
72 static ldap_pvt_thread_mutex_t  tls_mutexes[CRYPTO_NUM_LOCKS];
73
74 static void tls_locking_cb( int mode, int type, const char *file, int line )
75 {
76         if ( mode & CRYPTO_LOCK ) {
77                 ldap_pvt_thread_mutex_lock( tls_mutexes+type );
78         } else {
79                 ldap_pvt_thread_mutex_unlock( tls_mutexes+type );
80         }
81 }
82
83 /*
84  * an extra mutex for the default ctx.
85  */
86
87 static ldap_pvt_thread_mutex_t tls_def_ctx_mutex;
88
89 static void tls_init_threads( void )
90 {
91         int i;
92
93         for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
94                 ldap_pvt_thread_mutex_init( tls_mutexes+i );
95         }
96         CRYPTO_set_locking_callback( tls_locking_cb );
97         /* FIXME: the thread id should be added somehow... */
98
99         ldap_pvt_thread_mutex_init( &tls_def_ctx_mutex );
100 }
101 #endif /* LDAP_R_COMPILE */
102
103 /*
104  * Initialize tls system. Should be called only once.
105  */
106 int
107 ldap_pvt_tls_init( void )
108 {
109         static int tls_initialized = 0;
110
111         if ( tls_initialized )
112                 return -1;
113 #ifdef LDAP_R_COMPILE
114         tls_init_threads();
115 #endif
116         SSL_load_error_strings();
117         SSLeay_add_ssl_algorithms();
118         /* FIXME: mod_ssl does this */
119         X509V3_add_standard_extensions();
120         return 0;
121 }
122
123 /*
124  * initialize the default context
125  */
126 int
127 ldap_pvt_tls_init_def_ctx( void )
128 {
129         STACK_OF(X509_NAME) *calist;
130
131 #ifdef LDAP_R_COMPILE
132         ldap_pvt_thread_mutex_lock( &tls_def_ctx_mutex );
133 #endif
134         if ( tls_def_ctx == NULL ) {
135                 tls_def_ctx = SSL_CTX_new( SSLv23_method() );
136                 if ( tls_def_ctx == NULL ) {
137                         Debug( LDAP_DEBUG_ANY,
138                                "TLS: could not allocate default ctx.\n",0,0,0);
139                         goto error_exit;
140                 }
141                 if ( tls_opt_ciphersuite &&
142                      !SSL_CTX_set_cipher_list( tls_def_ctx,
143                         tls_opt_ciphersuite ) ) {
144                         Debug( LDAP_DEBUG_ANY,
145                                "TLS: could not set cipher list %s.\n",
146                                tls_opt_ciphersuite, 0, 0 );
147                         tls_report_error();
148                         goto error_exit;
149                 }
150                 if ( !SSL_CTX_load_verify_locations( tls_def_ctx,
151                                                      tls_opt_cacertfile,
152                                                      tls_opt_cacertdir ) ||
153                      !SSL_CTX_set_default_verify_paths( tls_def_ctx ) ) {
154                         Debug( LDAP_DEBUG_ANY,
155                 "TLS: could not load verify locations (file:`%s',dir:`%s').\n",
156                                tls_opt_cacertfile,tls_opt_cacertdir,0);
157                         tls_report_error();
158                         goto error_exit;
159                 }
160                 calist = get_ca_list( tls_opt_cacertfile, tls_opt_cacertdir );
161                 if ( !calist ) {
162                         Debug( LDAP_DEBUG_ANY,
163                 "TLS: could not load client CA list (file:`%s',dir:`%s').\n",
164                                tls_opt_cacertfile,tls_opt_cacertdir,0);
165                         tls_report_error();
166                         goto error_exit;
167                 }
168                 SSL_CTX_set_client_CA_list( tls_def_ctx, calist );
169                 if ( tls_opt_keyfile &&
170                      !SSL_CTX_use_PrivateKey_file( tls_def_ctx,
171                                                    tls_opt_keyfile,
172                                                    SSL_FILETYPE_PEM ) ) {
173                         Debug( LDAP_DEBUG_ANY,
174                                "TLS: could not use key file `%s'.\n",
175                                tls_opt_keyfile,0,0);
176                         tls_report_error();
177                         goto error_exit;
178                 }
179                 if ( tls_opt_certfile &&
180                      !SSL_CTX_use_certificate_file( tls_def_ctx,
181                                                     tls_opt_certfile,
182                                                     SSL_FILETYPE_PEM ) ) {
183                         Debug( LDAP_DEBUG_ANY,
184                                "TLS: could not use certificate `%s'.\n",
185                                tls_opt_certfile,0,0);
186                         tls_report_error();
187                         goto error_exit;
188                 }
189                 if ( ( tls_opt_certfile || tls_opt_keyfile ) &&
190                      !SSL_CTX_check_private_key( tls_def_ctx ) ) {
191                         Debug( LDAP_DEBUG_ANY,
192                                "TLS: private key mismatch.\n",
193                                0,0,0);
194                         tls_report_error();
195                         goto error_exit;
196                 }
197                 if ( tls_opt_trace ) {
198                         SSL_CTX_set_info_callback( tls_def_ctx, tls_info_cb );
199                 }
200                 SSL_CTX_set_verify( tls_def_ctx, (tls_opt_require_cert) ?
201                         (SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT) :
202                         SSL_VERIFY_PEER, tls_verify_cb );
203                 SSL_CTX_set_tmp_rsa_callback( tls_def_ctx, tls_tmp_rsa_cb );
204                 /* SSL_CTX_set_tmp_dh_callback( tls_def_ctx, tls_tmp_dh_cb ); */
205         }
206 #ifdef LDAP_R_COMPILE
207         ldap_pvt_thread_mutex_unlock( &tls_def_ctx_mutex );
208 #endif
209         return 0;
210 error_exit:
211 #ifdef LDAP_R_COMPILE
212         ldap_pvt_thread_mutex_unlock( &tls_def_ctx_mutex );
213 #endif
214         return -1;
215 }
216
217 static STACK_OF(X509_NAME) *
218 get_ca_list( char * bundle, char * dir )
219 {
220         STACK_OF(X509_NAME) *ca_list = NULL;
221
222         if ( bundle ) {
223                 ca_list = SSL_load_client_CA_file( bundle );
224         }
225         /*
226          * FIXME: We have now to go over all files in dir, load them
227          * and add every certificate there to ca_list.
228          */
229         return ca_list;
230 }
231
232 static SSL *
233 alloc_handle( Sockbuf *sb, void *ctx_arg )
234 {
235         int     err;
236         SSL_CTX *ctx;
237         SSL     *ssl;
238
239         if ( ctx_arg ) {
240                 ctx = (SSL_CTX *) ctx_arg;
241         } else {
242                 if ( ldap_pvt_tls_init_def_ctx() < 0 )
243                         return NULL;
244                 ctx = tls_def_ctx;
245         }
246
247         ssl = SSL_new( ctx );
248         if ( ssl == NULL ) {
249                 Debug( LDAP_DEBUG_ANY,"TLS: can't create ssl handle.\n",0,0,0);
250                 return NULL;
251         }
252
253         if ( tls_opt_trace ) {
254                 SSL_set_info_callback( ssl, tls_info_cb );
255         }
256         sb->sb_iodata = ssl;
257         SSL_set_fd( ssl, ber_pvt_sb_get_desc( sb ) );
258         return ssl;
259 }
260
261 static void
262 update_flags( Sockbuf *sb, SSL * ssl )
263 {
264         sb->sb_trans_needs_read  = SSL_want_read(ssl) ? 1 : 0;
265         sb->sb_trans_needs_write = SSL_want_write(ssl) ? 1 : 0;
266 }
267
268 /*
269  * Call this to do a TLS connect on a sockbuf. ctx_arg can be
270  * a SSL_CTX * or NULL, in which case the default ctx is used.
271  *
272  * Return value:
273  *
274  *  0 - Success. Connection is ready for communication.
275  * <0 - Error. Can't create a TLS stream.
276  * >0 - Partial success.
277  *        Do a select (using information from lber_pvt_sb_needs_{read,write}
278  *              and call again.
279  */
280
281 int
282 ldap_pvt_tls_connect( Sockbuf *sb, void *ctx_arg )
283 {
284         int     err;
285         SSL     *ssl;
286
287         if ( HAS_TLS( sb ) ) {
288                 ssl = (SSL *) sb->sb_iodata;
289         } else {
290                 ssl = alloc_handle( sb, ctx_arg );
291                 if ( ssl == NULL )
292                         return -1;
293                 ber_pvt_sb_clear_io( sb );
294                 ber_pvt_sb_set_io( sb, &tls_io, (void *)ssl );
295         }
296
297         err = SSL_connect( ssl );
298
299         if ( err <= 0 ) {
300                 if (
301 #ifdef EWOULDBLOCK
302                     (errno==EWOULDBLOCK) ||
303 #endif
304 #ifdef EAGAIN
305                     (errno==EAGAIN) ||
306 #endif
307                     (0)) {
308                         update_flags( sb, ssl );
309                         return 1;
310                 }
311                 Debug( LDAP_DEBUG_ANY,"TLS: can't connect.\n",0,0,0);
312                 ber_pvt_sb_clear_io( sb );
313                 ber_pvt_sb_set_io( sb, &ber_pvt_sb_io_tcp, NULL );
314                 return -1;
315         }
316         return 0;
317 }
318
319 /*
320  * Call this to do a TLS accept on a sockbuf.
321  * Everything else is the same as with tls_connect.
322  */
323 int
324 ldap_pvt_tls_accept( Sockbuf *sb, void *ctx_arg )
325 {
326         int     err;
327         SSL     *ssl;
328
329         if ( HAS_TLS( sb ) ) {
330                 ssl = (SSL *) sb->sb_iodata;
331         } else {
332                 ssl = alloc_handle( sb, ctx_arg );
333                 if ( ssl == NULL )
334                         return -1;
335                 ber_pvt_sb_clear_io( sb );
336                 ber_pvt_sb_set_io( sb, &tls_io, (void *)ssl );
337         }
338
339         err = SSL_accept( ssl );
340
341         if ( err <= 0 ) {
342                 if ( !SSL_want_nothing( ssl ) ) {
343                         update_flags( sb, ssl );
344                         return 1;
345                 }
346                 Debug( LDAP_DEBUG_ANY,"TLS: can't accept.\n",0,0,0 );
347                 tls_report_error();
348                 ber_pvt_sb_clear_io( sb );
349                 ber_pvt_sb_set_io( sb, &ber_pvt_sb_io_tcp, NULL );
350                 return -1;
351         }
352         return 0;
353 }
354
355 const char *
356 ldap_pvt_tls_get_peer( LDAP *ld )
357 {
358 }
359
360 const char *
361 ldap_pvt_tls_get_peer_issuer( LDAP *ld )
362 {
363 }
364
365 int
366 ldap_pvt_tls_config( struct ldapoptions *lo, int option, const char *arg )
367 {
368         int i;
369
370         switch( option ) {
371         case LDAP_OPT_X_TLS_CACERTFILE:
372         case LDAP_OPT_X_TLS_CACERTDIR:
373         case LDAP_OPT_X_TLS_CERTFILE:
374         case LDAP_OPT_X_TLS_KEYFILE:
375                 return ldap_pvt_tls_set_option( NULL, option, (void *) arg );
376         case LDAP_OPT_X_TLS_REQUIRE_CERT:
377                 i = ( ( strcasecmp( arg, "on" ) == 0 ) ||
378                       ( strcasecmp( arg, "yes" ) == 0) ||
379                       ( strcasecmp( arg, "true" ) == 0 ) );
380                 return ldap_pvt_tls_set_option( NULL, option, (void *) &i );
381         case LDAP_OPT_X_TLS:
382                 i = -1;
383                 if ( strcasecmp( arg, "never" ) == 0 )
384                         i = LDAP_OPT_X_TLS_NEVER ;
385                 if ( strcasecmp( arg, "demand" ) == 0 )
386                         i = LDAP_OPT_X_TLS_DEMAND ;
387                 if ( strcasecmp( arg, "allow" ) == 0 )
388                         i = LDAP_OPT_X_TLS_ALLOW ;
389                 if ( strcasecmp( arg, "try" ) == 0 )
390                         i = LDAP_OPT_X_TLS_TRY ;
391                 if ( strcasecmp( arg, "hard" ) == 0 )
392                         i = LDAP_OPT_X_TLS_HARD ;
393                 if (i >= 0)
394                         return ldap_pvt_tls_set_option( lo, option, &i );
395                 return -1;
396         default:
397                 return -1;
398         }
399 }
400
401 int
402 ldap_pvt_tls_get_option( struct ldapoptions *lo, int option, void *arg )
403 {
404         switch( option ) {
405         case LDAP_OPT_X_TLS:
406                 *(int *)arg = lo->ldo_tls_mode;
407                 break;
408         case LDAP_OPT_X_TLS_CERT:
409                 if ( lo == NULL )
410                         arg = (void *) tls_def_ctx;
411                 else
412                         arg = lo->ldo_tls_ctx;
413                 break;
414         case LDAP_OPT_X_TLS_CACERTFILE:
415                 *(char **)arg = tls_opt_cacertfile ?
416                         LDAP_STRDUP( tls_opt_cacertfile ) : NULL;
417                 break;
418         case LDAP_OPT_X_TLS_CACERTDIR:
419                 *(char **)arg = tls_opt_cacertdir ?
420                         LDAP_STRDUP( tls_opt_cacertdir ) : NULL;
421                 break;
422         case LDAP_OPT_X_TLS_CERTFILE:
423                 *(char **)arg = tls_opt_certfile ?
424                         LDAP_STRDUP( tls_opt_certfile ) : NULL;
425                 break;
426         case LDAP_OPT_X_TLS_KEYFILE:
427                 *(char **)arg = tls_opt_keyfile ?
428                         LDAP_STRDUP( tls_opt_keyfile ) : NULL;
429                 break;
430         case LDAP_OPT_X_TLS_REQUIRE_CERT:
431                 *(int *)arg = tls_opt_require_cert;
432                 break;
433         default:
434                 return -1;
435         }
436         return 0;
437 }
438
439 int
440 ldap_pvt_tls_set_option( struct ldapoptions *lo, int option, void *arg )
441 {
442         switch( option ) {
443         case LDAP_OPT_X_TLS:
444                 switch( *(int *) arg ) {
445                 case LDAP_OPT_X_TLS_NEVER:
446                 case LDAP_OPT_X_TLS_DEMAND:
447                 case LDAP_OPT_X_TLS_ALLOW:
448                 case LDAP_OPT_X_TLS_TRY:
449                 case LDAP_OPT_X_TLS_HARD:
450                         lo->ldo_tls_mode = *(int *)arg;
451                         break;
452                 default:
453                         return -1;
454                 }
455                 break;
456         case LDAP_OPT_X_TLS_CERT:
457                 if ( lo == NULL )
458                         tls_def_ctx = (SSL_CTX *) arg;
459                 else
460                         lo->ldo_tls_ctx = arg;
461                 break;
462         }
463         if ( lo != NULL )
464                 return -1;
465         switch( option ) {
466         case LDAP_OPT_X_TLS_CACERTFILE:
467                 if ( tls_opt_cacertfile ) free( tls_opt_cacertfile );
468                 tls_opt_cacertfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
469                 break;
470         case LDAP_OPT_X_TLS_CACERTDIR:
471                 if ( tls_opt_cacertdir ) free( tls_opt_cacertdir );
472                 tls_opt_cacertdir = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
473                 break;
474         case LDAP_OPT_X_TLS_CERTFILE:
475                 if ( tls_opt_certfile ) free( tls_opt_certfile );
476                 tls_opt_certfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
477                 break;
478         case LDAP_OPT_X_TLS_KEYFILE:
479                 if ( tls_opt_keyfile ) free( tls_opt_keyfile );
480                 tls_opt_keyfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
481                 break;
482         case LDAP_OPT_X_TLS_REQUIRE_CERT:
483                 tls_opt_require_cert = * (int *) arg;
484                 break;
485         case LDAP_OPT_X_TLS_CIPHER_SUITE:
486                 if ( tls_opt_ciphersuite ) free( tls_opt_ciphersuite );
487                 tls_opt_ciphersuite = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
488                 break;
489         default:
490                 return -1;
491         }
492         return 0;
493 }
494
495 static int
496 tls_setup( Sockbuf *sb, void *arg )
497 {
498         sb->sb_iodata = arg;
499         return 0;
500 }
501
502 static int
503 tls_remove( Sockbuf *sb )
504 {
505         SSL_free( (SSL *) sb->sb_iodata );
506         return 0;
507 }
508
509 static ber_slen_t
510 tls_write( Sockbuf *sb, void *buf, ber_len_t sz )
511 {
512         int ret = SSL_write( (SSL *)sb->sb_iodata, buf, sz );
513
514         update_flags(sb, (SSL *)sb->sb_iodata );
515         return ret;
516 }
517
518 static ber_slen_t
519 tls_read( Sockbuf *sb, void *buf, ber_len_t sz )
520 {
521         int ret = SSL_read( (SSL *)sb->sb_iodata, buf, sz );
522
523         update_flags(sb, (SSL *)sb->sb_iodata );
524         return ret;
525 }
526
527 static int
528 tls_close( Sockbuf *sb )
529 {
530         tcp_close( ber_pvt_sb_get_desc( sb ) );
531         return 0;
532 }
533
534 /* Derived from openssl/apps/s_cb.c */
535 static void
536 tls_info_cb( SSL *ssl, int where, int ret )
537 {
538         int w;
539         char *op;
540
541         w = where & ~SSL_ST_MASK;
542         if ( w & SSL_ST_CONNECT ) {
543                 op = "SSL_connect";
544         } else if ( w & SSL_ST_ACCEPT ) {
545                 op = "SSL_accept";
546         } else {
547                 op = "undefined";
548         }
549
550         if ( where & SSL_CB_LOOP ) {
551                 Debug( LDAP_DEBUG_TRACE,
552                        "TLS trace: %s:%s\n",
553                        op, SSL_state_string_long( ssl ), 0 );
554         } else if ( where & SSL_CB_ALERT ) {
555                 op = ( where & SSL_CB_READ ) ? "read" : "write";
556                 Debug( LDAP_DEBUG_TRACE,
557                        "TLS trace: SSL3 alert %s:%s:%s\n",
558                        op,
559                        SSL_alert_type_string_long( ret ),
560                        SSL_alert_desc_string_long( ret) );
561         } else if ( where & SSL_CB_EXIT ) {
562                 if ( ret == 0 ) {
563                         Debug( LDAP_DEBUG_TRACE,
564                                "TLS trace: %s:failed in %s\n",
565                                op, SSL_state_string_long( ssl ), 0 );
566                 } else if ( ret < 0 ) {
567                         Debug( LDAP_DEBUG_TRACE,
568                                "TLS trace: %s:error in %s\n",
569                                op, SSL_state_string_long( ssl ), 0 );
570                 }
571         }
572 }
573
574 static int
575 tls_verify_cb( int ok, X509_STORE_CTX *ctx )
576 {
577         X509 *cert;
578         int errnum;
579         int errdepth;
580         X509_NAME *subject;
581         X509_NAME *issuer;
582         char *sname;
583         char *iname;
584
585         cert = X509_STORE_CTX_get_current_cert( ctx );
586         errnum = X509_STORE_CTX_get_error( ctx );
587         errdepth = X509_STORE_CTX_get_error_depth( ctx );
588
589         /*
590          * X509_get_*_name return pointers to the internal copies of
591          * those things requested.  So do not free them.
592          */
593         subject = X509_get_subject_name( cert );
594         issuer = X509_get_issuer_name( cert );
595         /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
596         sname = X509_NAME_oneline( subject, NULL, 0 );
597         iname = X509_NAME_oneline( issuer, NULL, 0 );
598         Debug( LDAP_DEBUG_TRACE,
599                "TLS certificate verification: depth: %d, subject: %s, issuer: %s\n",
600                errdepth,
601                sname ? sname : "-unknown-",
602                iname ? iname : "-unknown-" );
603         if ( sname )
604                 free ( sname );
605         if ( iname )
606                 free ( iname );
607
608         return 1;
609 }
610
611 /* Inspired by ERR_print_errors in OpenSSL */
612 static int
613 tls_report_error( void )
614 {
615         unsigned long l;
616         char buf[200];
617         const char *file;
618         int line;
619
620         while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
621                         Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
622                                ERR_error_string( l, buf ), file, line );
623         }
624 }
625
626 static RSA *
627 tls_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
628 {
629         RSA *tmp_rsa;
630
631         /* FIXME:  Pregenerate the key on startup */
632         /* FIXME:  Who frees the key? */
633         tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
634
635         if ( !tmp_rsa ) {
636                 Debug( LDAP_DEBUG_ANY, "TLS: Failed to generate temporary %d-bit %s RSA key\n",
637                        key_length, is_export ? "export" : "domestic", 0 );
638                 return NULL;
639         }
640         return tmp_rsa;
641 }
642
643 static DH *
644 tls_tmp_dh_cb( SSL *ssl, int is_export, int key_length )
645 {
646         return NULL;
647 }
648
649 #else
650 static int dummy;
651 #endif