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