]> git.sur5r.net Git - openldap/blob - libraries/libldap/tls_o.c
ITS#8353 partial fixes
[openldap] / libraries / libldap / tls_o.c
1 /* tls_o.c - Handle tls/ssl using OpenSSL */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2008-2016 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 /* ACKNOWLEDGEMENTS: Rewritten by Howard Chu
17  */
18
19 #include "portable.h"
20
21 #ifdef HAVE_OPENSSL
22
23 #include "ldap_config.h"
24
25 #include <stdio.h>
26
27 #include <ac/stdlib.h>
28 #include <ac/errno.h>
29 #include <ac/socket.h>
30 #include <ac/string.h>
31 #include <ac/ctype.h>
32 #include <ac/time.h>
33 #include <ac/unistd.h>
34 #include <ac/param.h>
35 #include <ac/dirent.h>
36
37 #include "ldap-int.h"
38 #include "ldap-tls.h"
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 typedef SSL_CTX tlso_ctx;
51 typedef SSL tlso_session;
52
53 static int  tlso_opt_trace = 1;
54
55 static void tlso_report_error( void );
56
57 static void tlso_info_cb( const SSL *ssl, int where, int ret );
58 static int tlso_verify_cb( int ok, X509_STORE_CTX *ctx );
59 static int tlso_verify_ok( int ok, X509_STORE_CTX *ctx );
60 static RSA * tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
61
62 static int tlso_seed_PRNG( const char *randfile );
63
64 #ifdef LDAP_R_COMPILE
65 /*
66  * provide mutexes for the OpenSSL library.
67  */
68 static ldap_pvt_thread_mutex_t  tlso_mutexes[CRYPTO_NUM_LOCKS];
69
70 static void tlso_locking_cb( int mode, int type, const char *file, int line )
71 {
72         if ( mode & CRYPTO_LOCK ) {
73                 ldap_pvt_thread_mutex_lock( &tlso_mutexes[type] );
74         } else {
75                 ldap_pvt_thread_mutex_unlock( &tlso_mutexes[type] );
76         }
77 }
78
79 static unsigned long tlso_thread_self( void )
80 {
81         /* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
82          * is an integral type that fits in an unsigned long
83          */
84
85         /* force an error if the ldap_pvt_thread_t type is too large */
86         enum { ok = sizeof( ldap_pvt_thread_t ) <= sizeof( unsigned long ) };
87         typedef struct { int dummy: ok ? 1 : -1; } Check[ok ? 1 : -1];
88
89         return (unsigned long) ldap_pvt_thread_self();
90 }
91
92 static void tlso_thr_init( void )
93 {
94         int i;
95
96         for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
97                 ldap_pvt_thread_mutex_init( &tlso_mutexes[i] );
98         }
99         CRYPTO_set_locking_callback( tlso_locking_cb );
100         CRYPTO_set_id_callback( tlso_thread_self );
101 }
102 #endif /* LDAP_R_COMPILE */
103
104 static STACK_OF(X509_NAME) *
105 tlso_ca_list( char * bundle, char * dir )
106 {
107         STACK_OF(X509_NAME) *ca_list = NULL;
108
109         if ( bundle ) {
110                 ca_list = SSL_load_client_CA_file( bundle );
111         }
112 #if defined(HAVE_DIRENT_H) || defined(dirent)
113         if ( dir ) {
114                 int freeit = 0;
115
116                 if ( !ca_list ) {
117                         ca_list = sk_X509_NAME_new_null();
118                         freeit = 1;
119                 }
120                 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
121                         freeit ) {
122                         sk_X509_NAME_free( ca_list );
123                         ca_list = NULL;
124                 }
125         }
126 #endif
127         return ca_list;
128 }
129
130 /*
131  * Initialize TLS subsystem. Should be called only once.
132  */
133 static int
134 tlso_init( void )
135 {
136         struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();   
137 #ifdef HAVE_EBCDIC
138         {
139                 char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
140                 if ( file ) __atoe( file );
141                 (void) tlso_seed_PRNG( file );
142                 LDAP_FREE( file );
143         }
144 #else
145         (void) tlso_seed_PRNG( lo->ldo_tls_randfile );
146 #endif
147
148         SSL_load_error_strings();
149         SSL_library_init();
150         OpenSSL_add_all_digests();
151
152         /* FIXME: mod_ssl does this */
153         X509V3_add_standard_extensions();
154
155         return 0;
156 }
157
158 /*
159  * Tear down the TLS subsystem. Should only be called once.
160  */
161 static void
162 tlso_destroy( void )
163 {
164         struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();   
165
166         EVP_cleanup();
167 #if OPENSSL_VERSION_NUMBER < 0x10000000
168         ERR_remove_state(0);
169 #else
170         ERR_remove_thread_state(NULL);
171 #endif
172         ERR_free_strings();
173
174         if ( lo->ldo_tls_randfile ) {
175                 LDAP_FREE( lo->ldo_tls_randfile );
176                 lo->ldo_tls_randfile = NULL;
177         }
178 }
179
180 static tls_ctx *
181 tlso_ctx_new( struct ldapoptions *lo )
182 {
183         return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
184 }
185
186 static void
187 tlso_ctx_ref( tls_ctx *ctx )
188 {
189         tlso_ctx *c = (tlso_ctx *)ctx;
190         CRYPTO_add( &c->references, 1, CRYPTO_LOCK_SSL_CTX );
191 }
192
193 static void
194 tlso_ctx_free ( tls_ctx *ctx )
195 {
196         tlso_ctx *c = (tlso_ctx *)ctx;
197         SSL_CTX_free( c );
198 }
199
200 /*
201  * initialize a new TLS context
202  */
203 static int
204 tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
205 {
206         tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
207         int i;
208
209         if ( is_server ) {
210                 SSL_CTX_set_session_id_context( ctx,
211                         (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
212         }
213
214 #ifdef SSL_OP_NO_TLSv1
215 #ifdef SSL_OP_NO_TLSv1_1
216 #ifdef SSL_OP_NO_TLSv1_2
217         if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_2)
218                 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
219                         SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 |
220                         SSL_OP_NO_TLSv1_2 );
221         else
222 #endif
223         if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_1)
224                 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
225                         SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 );
226         else
227 #endif
228         if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_0)
229                 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
230                         SSL_OP_NO_TLSv1);
231         else
232 #endif
233         if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
234                 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 );
235         else if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 )
236                 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 );
237
238         if ( lo->ldo_tls_ciphersuite &&
239                 !SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
240         {
241                 Debug( LDAP_DEBUG_ANY,
242                            "TLS: could not set cipher list %s.\n",
243                            lo->ldo_tls_ciphersuite, 0, 0 );
244                 tlso_report_error();
245                 return -1;
246         }
247
248         if (lo->ldo_tls_cacertfile != NULL || lo->ldo_tls_cacertdir != NULL) {
249                 if ( !SSL_CTX_load_verify_locations( ctx,
250                                 lt->lt_cacertfile, lt->lt_cacertdir ) ||
251                         !SSL_CTX_set_default_verify_paths( ctx ) )
252                 {
253                         Debug( LDAP_DEBUG_ANY, "TLS: "
254                                 "could not load verify locations (file:`%s',dir:`%s').\n",
255                                 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
256                                 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
257                                 0 );
258                         tlso_report_error();
259                         return -1;
260                 }
261
262                 if ( is_server ) {
263                         STACK_OF(X509_NAME) *calist;
264                         /* List of CA names to send to a client */
265                         calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir );
266                         if ( !calist ) {
267                                 Debug( LDAP_DEBUG_ANY, "TLS: "
268                                         "could not load client CA list (file:`%s',dir:`%s').\n",
269                                         lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
270                                         lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
271                                         0 );
272                                 tlso_report_error();
273                                 return -1;
274                         }
275
276                         SSL_CTX_set_client_CA_list( ctx, calist );
277                 }
278         }
279
280         if ( lo->ldo_tls_certfile &&
281                 !SSL_CTX_use_certificate_file( ctx,
282                         lt->lt_certfile, SSL_FILETYPE_PEM ) )
283         {
284                 Debug( LDAP_DEBUG_ANY,
285                         "TLS: could not use certificate `%s'.\n",
286                         lo->ldo_tls_certfile,0,0);
287                 tlso_report_error();
288                 return -1;
289         }
290
291         /* Key validity is checked automatically if cert has already been set */
292         if ( lo->ldo_tls_keyfile &&
293                 !SSL_CTX_use_PrivateKey_file( ctx,
294                         lt->lt_keyfile, SSL_FILETYPE_PEM ) )
295         {
296                 Debug( LDAP_DEBUG_ANY,
297                         "TLS: could not use key file `%s'.\n",
298                         lo->ldo_tls_keyfile,0,0);
299                 tlso_report_error();
300                 return -1;
301         }
302
303         if ( lo->ldo_tls_dhfile ) {
304                 DH *dh = NULL;
305                 BIO *bio;
306                 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_DH_USE );
307
308                 if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
309                         Debug( LDAP_DEBUG_ANY,
310                                 "TLS: could not use DH parameters file `%s'.\n",
311                                 lo->ldo_tls_dhfile,0,0);
312                         tlso_report_error();
313                         return -1;
314                 }
315                 if (!( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
316                         Debug( LDAP_DEBUG_ANY,
317                                 "TLS: could not read DH parameters file `%s'.\n",
318                                 lo->ldo_tls_dhfile,0,0);
319                         tlso_report_error();
320                         BIO_free( bio );
321                         return -1;
322                 }
323                 BIO_free( bio );
324                 SSL_CTX_set_tmp_dh( ctx, dh );
325         }
326
327         if ( tlso_opt_trace ) {
328                 SSL_CTX_set_info_callback( ctx, tlso_info_cb );
329         }
330
331         i = SSL_VERIFY_NONE;
332         if ( lo->ldo_tls_require_cert ) {
333                 i = SSL_VERIFY_PEER;
334                 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
335                          lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
336                         i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
337                 }
338         }
339
340         SSL_CTX_set_verify( ctx, i,
341                 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
342                 tlso_verify_ok : tlso_verify_cb );
343         SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
344 #ifdef HAVE_OPENSSL_CRL
345         if ( lo->ldo_tls_crlcheck ) {
346                 X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
347                 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
348                         X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
349                 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
350                         X509_STORE_set_flags( x509_s, 
351                                         X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL  );
352                 }
353         }
354 #endif
355         return 0;
356 }
357
358 static tls_session *
359 tlso_session_new( tls_ctx *ctx, int is_server )
360 {
361         tlso_ctx *c = (tlso_ctx *)ctx;
362         return (tls_session *)SSL_new( c );
363 }
364
365 static int
366 tlso_session_connect( LDAP *ld, tls_session *sess )
367 {
368         tlso_session *s = (tlso_session *)sess;
369
370         /* Caller expects 0 = success, OpenSSL returns 1 = success */
371         return SSL_connect( s ) - 1;
372 }
373
374 static int
375 tlso_session_accept( tls_session *sess )
376 {
377         tlso_session *s = (tlso_session *)sess;
378
379         /* Caller expects 0 = success, OpenSSL returns 1 = success */
380         return SSL_accept( s ) - 1;
381 }
382
383 static int
384 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
385 {
386         tlso_session *s = (tlso_session *)sess;
387
388         /* 1 was subtracted above, offset it back now */
389         rc = SSL_get_error(s, rc+1);
390         if (rc == SSL_ERROR_WANT_READ) {
391                 sb->sb_trans_needs_read  = 1;
392                 return 1;
393
394         } else if (rc == SSL_ERROR_WANT_WRITE) {
395                 sb->sb_trans_needs_write = 1;
396                 return 1;
397
398         } else if (rc == SSL_ERROR_WANT_CONNECT) {
399                 return 1;
400         }
401         return 0;
402 }
403
404 static char *
405 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
406 {
407         char err[256] = "";
408         const char *certerr=NULL;
409         tlso_session *s = (tlso_session *)sess;
410
411         rc = ERR_peek_error();
412         if ( rc ) {
413                 ERR_error_string_n( rc, err, sizeof(err) );
414                 if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) && 
415                                 ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
416                         int certrc = SSL_get_verify_result(s);
417                         certerr = (char *)X509_verify_cert_error_string(certrc);
418                 }
419                 snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"", 
420                                 certerr ? certerr : "", certerr ?  ")" : "" );
421                 return buf;
422         }
423         return NULL;
424 }
425
426 static int
427 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
428 {
429         tlso_session *s = (tlso_session *)sess;
430         X509 *x;
431         X509_NAME *xn;
432
433         x = SSL_get_certificate( s );
434
435         if (!x) return LDAP_INVALID_CREDENTIALS;
436         
437         xn = X509_get_subject_name(x);
438         der_dn->bv_len = i2d_X509_NAME( xn, NULL );
439         der_dn->bv_val = xn->bytes->data;
440         /* Don't X509_free, the session is still using it */
441         return 0;
442 }
443
444 static X509 *
445 tlso_get_cert( SSL *s )
446 {
447         /* If peer cert was bad, treat as if no cert was given */
448         if (SSL_get_verify_result(s)) {
449                 return NULL;
450         }
451         return SSL_get_peer_certificate(s);
452 }
453
454 static int
455 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
456 {
457         tlso_session *s = (tlso_session *)sess;
458         X509 *x = tlso_get_cert( s );
459         X509_NAME *xn;
460
461         if ( !x )
462                 return LDAP_INVALID_CREDENTIALS;
463
464         xn = X509_get_subject_name(x);
465         der_dn->bv_len = i2d_X509_NAME( xn, NULL );
466         der_dn->bv_val = xn->bytes->data;
467         X509_free(x);
468         return 0;
469 }
470
471 /* what kind of hostname were we given? */
472 #define IS_DNS  0
473 #define IS_IP4  1
474 #define IS_IP6  2
475
476 static int
477 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
478 {
479         tlso_session *s = (tlso_session *)sess;
480         int i, ret = LDAP_LOCAL_ERROR;
481         X509 *x;
482         const char *name;
483         char *ptr;
484         int ntype = IS_DNS, nlen;
485 #ifdef LDAP_PF_INET6
486         struct in6_addr addr;
487 #else
488         struct in_addr addr;
489 #endif
490
491         if( ldap_int_hostname &&
492                 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
493         {
494                 name = ldap_int_hostname;
495         } else {
496                 name = name_in;
497         }
498         nlen = strlen(name);
499
500         x = tlso_get_cert(s);
501         if (!x) {
502                 Debug( LDAP_DEBUG_ANY,
503                         "TLS: unable to get peer certificate.\n",
504                         0, 0, 0 );
505                 /* If this was a fatal condition, things would have
506                  * aborted long before now.
507                  */
508                 return LDAP_SUCCESS;
509         }
510
511 #ifdef LDAP_PF_INET6
512         if (inet_pton(AF_INET6, name, &addr)) {
513                 ntype = IS_IP6;
514         } else 
515 #endif
516         if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
517                 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
518         }
519         
520         i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
521         if (i >= 0) {
522                 X509_EXTENSION *ex;
523                 STACK_OF(GENERAL_NAME) *alt;
524
525                 ex = X509_get_ext(x, i);
526                 alt = X509V3_EXT_d2i(ex);
527                 if (alt) {
528                         int n, len2 = 0;
529                         char *domain = NULL;
530                         GENERAL_NAME *gn;
531
532                         if (ntype == IS_DNS) {
533                                 domain = strchr(name, '.');
534                                 if (domain) {
535                                         len2 = nlen - (domain-name);
536                                 }
537                         }
538                         n = sk_GENERAL_NAME_num(alt);
539                         for (i=0; i<n; i++) {
540                                 char *sn;
541                                 int sl;
542                                 gn = sk_GENERAL_NAME_value(alt, i);
543                                 if (gn->type == GEN_DNS) {
544                                         if (ntype != IS_DNS) continue;
545
546                                         sn = (char *) ASN1_STRING_data(gn->d.ia5);
547                                         sl = ASN1_STRING_length(gn->d.ia5);
548
549                                         /* ignore empty */
550                                         if (sl == 0) continue;
551
552                                         /* Is this an exact match? */
553                                         if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
554                                                 break;
555                                         }
556
557                                         /* Is this a wildcard match? */
558                                         if (domain && (sn[0] == '*') && (sn[1] == '.') &&
559                                                 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
560                                         {
561                                                 break;
562                                         }
563
564                                 } else if (gn->type == GEN_IPADD) {
565                                         if (ntype == IS_DNS) continue;
566
567                                         sn = (char *) ASN1_STRING_data(gn->d.ia5);
568                                         sl = ASN1_STRING_length(gn->d.ia5);
569
570 #ifdef LDAP_PF_INET6
571                                         if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
572                                                 continue;
573                                         } else
574 #endif
575                                         if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
576                                                 continue;
577                                         }
578                                         if (!memcmp(sn, &addr, sl)) {
579                                                 break;
580                                         }
581                                 }
582                         }
583
584                         GENERAL_NAMES_free(alt);
585                         if (i < n) {    /* Found a match */
586                                 ret = LDAP_SUCCESS;
587                         }
588                 }
589         }
590
591         if (ret != LDAP_SUCCESS) {
592                 X509_NAME *xn;
593                 X509_NAME_ENTRY *ne;
594                 ASN1_OBJECT *obj;
595                 ASN1_STRING *cn = NULL;
596                 int navas;
597
598                 /* find the last CN */
599                 obj = OBJ_nid2obj( NID_commonName );
600                 if ( !obj ) goto no_cn; /* should never happen */
601
602                 xn = X509_get_subject_name(x);
603                 navas = X509_NAME_entry_count( xn );
604                 for ( i=navas-1; i>=0; i-- ) {
605                         ne = X509_NAME_get_entry( xn, i );
606                         if ( !OBJ_cmp( X509_NAME_ENTRY_get_object(ne), obj )) {
607                                 cn = X509_NAME_ENTRY_get_data( ne );
608                                 break;
609                         }
610                 }
611
612                 if( !cn )
613                 {
614 no_cn:
615                         Debug( LDAP_DEBUG_ANY,
616                                 "TLS: unable to get common name from peer certificate.\n",
617                                 0, 0, 0 );
618                         ret = LDAP_CONNECT_ERROR;
619                         if ( ld->ld_error ) {
620                                 LDAP_FREE( ld->ld_error );
621                         }
622                         ld->ld_error = LDAP_STRDUP(
623                                 _("TLS: unable to get CN from peer certificate"));
624
625                 } else if ( cn->length == nlen &&
626                         strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
627                         ret = LDAP_SUCCESS;
628
629                 } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
630                         char *domain = strchr(name, '.');
631                         if( domain ) {
632                                 int dlen;
633
634                                 dlen = nlen - (domain-name);
635
636                                 /* Is this a wildcard match? */
637                                 if ((dlen == cn->length-1) &&
638                                         !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
639                                         ret = LDAP_SUCCESS;
640                                 }
641                         }
642                 }
643
644                 if( ret == LDAP_LOCAL_ERROR ) {
645                         Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
646                                 "common name in certificate (%.*s).\n", 
647                                 name, cn->length, cn->data );
648                         ret = LDAP_CONNECT_ERROR;
649                         if ( ld->ld_error ) {
650                                 LDAP_FREE( ld->ld_error );
651                         }
652                         ld->ld_error = LDAP_STRDUP(
653                                 _("TLS: hostname does not match CN in peer certificate"));
654                 }
655         }
656         X509_free(x);
657         return ret;
658 }
659
660 static int
661 tlso_session_strength( tls_session *sess )
662 {
663         tlso_session *s = (tlso_session *)sess;
664
665         return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
666 }
667
668 /*
669  * TLS support for LBER Sockbufs
670  */
671
672 struct tls_data {
673         tlso_session            *session;
674         Sockbuf_IO_Desc         *sbiod;
675 };
676
677 static int
678 tlso_bio_create( BIO *b ) {
679         b->init = 1;
680         b->num = 0;
681         b->ptr = NULL;
682         b->flags = 0;
683         return 1;
684 }
685
686 static int
687 tlso_bio_destroy( BIO *b )
688 {
689         if ( b == NULL ) return 0;
690
691         b->ptr = NULL;          /* sb_tls_remove() will free it */
692         b->init = 0;
693         b->flags = 0;
694         return 1;
695 }
696
697 static int
698 tlso_bio_read( BIO *b, char *buf, int len )
699 {
700         struct tls_data         *p;
701         int                     ret;
702                 
703         if ( buf == NULL || len <= 0 ) return 0;
704
705         p = (struct tls_data *)b->ptr;
706
707         if ( p == NULL || p->sbiod == NULL ) {
708                 return 0;
709         }
710
711         ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
712
713         BIO_clear_retry_flags( b );
714         if ( ret < 0 ) {
715                 int err = sock_errno();
716                 if ( err == EAGAIN || err == EWOULDBLOCK ) {
717                         BIO_set_retry_read( b );
718                 }
719         }
720
721         return ret;
722 }
723
724 static int
725 tlso_bio_write( BIO *b, const char *buf, int len )
726 {
727         struct tls_data         *p;
728         int                     ret;
729         
730         if ( buf == NULL || len <= 0 ) return 0;
731         
732         p = (struct tls_data *)b->ptr;
733
734         if ( p == NULL || p->sbiod == NULL ) {
735                 return 0;
736         }
737
738         ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
739
740         BIO_clear_retry_flags( b );
741         if ( ret < 0 ) {
742                 int err = sock_errno();
743                 if ( err == EAGAIN || err == EWOULDBLOCK ) {
744                         BIO_set_retry_write( b );
745                 }
746         }
747
748         return ret;
749 }
750
751 static long
752 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
753 {
754         if ( cmd == BIO_CTRL_FLUSH ) {
755                 /* The OpenSSL library needs this */
756                 return 1;
757         }
758         return 0;
759 }
760
761 static int
762 tlso_bio_gets( BIO *b, char *buf, int len )
763 {
764         return -1;
765 }
766
767 static int
768 tlso_bio_puts( BIO *b, const char *str )
769 {
770         return tlso_bio_write( b, str, strlen( str ) );
771 }
772         
773 static BIO_METHOD tlso_bio_method =
774 {
775         ( 100 | 0x400 ),                /* it's a source/sink BIO */
776         "sockbuf glue",
777         tlso_bio_write,
778         tlso_bio_read,
779         tlso_bio_puts,
780         tlso_bio_gets,
781         tlso_bio_ctrl,
782         tlso_bio_create,
783         tlso_bio_destroy
784 };
785
786 static int
787 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
788 {
789         struct tls_data         *p;
790         BIO                     *bio;
791
792         assert( sbiod != NULL );
793
794         p = LBER_MALLOC( sizeof( *p ) );
795         if ( p == NULL ) {
796                 return -1;
797         }
798         
799         p->session = arg;
800         p->sbiod = sbiod;
801         bio = BIO_new( &tlso_bio_method );
802         bio->ptr = (void *)p;
803         SSL_set_bio( p->session, bio, bio );
804         sbiod->sbiod_pvt = p;
805         return 0;
806 }
807
808 static int
809 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
810 {
811         struct tls_data         *p;
812         
813         assert( sbiod != NULL );
814         assert( sbiod->sbiod_pvt != NULL );
815
816         p = (struct tls_data *)sbiod->sbiod_pvt;
817         SSL_free( p->session );
818         LBER_FREE( sbiod->sbiod_pvt );
819         sbiod->sbiod_pvt = NULL;
820         return 0;
821 }
822
823 static int
824 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
825 {
826         struct tls_data         *p;
827         
828         assert( sbiod != NULL );
829         assert( sbiod->sbiod_pvt != NULL );
830
831         p = (struct tls_data *)sbiod->sbiod_pvt;
832         SSL_shutdown( p->session );
833         return 0;
834 }
835
836 static int
837 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
838 {
839         struct tls_data         *p;
840         
841         assert( sbiod != NULL );
842         assert( sbiod->sbiod_pvt != NULL );
843
844         p = (struct tls_data *)sbiod->sbiod_pvt;
845         
846         if ( opt == LBER_SB_OPT_GET_SSL ) {
847                 *((tlso_session **)arg) = p->session;
848                 return 1;
849
850         } else if ( opt == LBER_SB_OPT_DATA_READY ) {
851                 if( SSL_pending( p->session ) > 0 ) {
852                         return 1;
853                 }
854         }
855         
856         return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
857 }
858
859 static ber_slen_t
860 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
861 {
862         struct tls_data         *p;
863         ber_slen_t              ret;
864         int                     err;
865
866         assert( sbiod != NULL );
867         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
868
869         p = (struct tls_data *)sbiod->sbiod_pvt;
870
871         ret = SSL_read( p->session, (char *)buf, len );
872 #ifdef HAVE_WINSOCK
873         errno = WSAGetLastError();
874 #endif
875         err = SSL_get_error( p->session, ret );
876         if (err == SSL_ERROR_WANT_READ ) {
877                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
878                 sock_errset(EWOULDBLOCK);
879         }
880         else
881                 sbiod->sbiod_sb->sb_trans_needs_read = 0;
882         return ret;
883 }
884
885 static ber_slen_t
886 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
887 {
888         struct tls_data         *p;
889         ber_slen_t              ret;
890         int                     err;
891
892         assert( sbiod != NULL );
893         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
894
895         p = (struct tls_data *)sbiod->sbiod_pvt;
896
897         ret = SSL_write( p->session, (char *)buf, len );
898 #ifdef HAVE_WINSOCK
899         errno = WSAGetLastError();
900 #endif
901         err = SSL_get_error( p->session, ret );
902         if (err == SSL_ERROR_WANT_WRITE ) {
903                 sbiod->sbiod_sb->sb_trans_needs_write = 1;
904                 sock_errset(EWOULDBLOCK);
905
906         } else {
907                 sbiod->sbiod_sb->sb_trans_needs_write = 0;
908         }
909         return ret;
910 }
911
912 static Sockbuf_IO tlso_sbio =
913 {
914         tlso_sb_setup,          /* sbi_setup */
915         tlso_sb_remove,         /* sbi_remove */
916         tlso_sb_ctrl,           /* sbi_ctrl */
917         tlso_sb_read,           /* sbi_read */
918         tlso_sb_write,          /* sbi_write */
919         tlso_sb_close           /* sbi_close */
920 };
921
922 /* Derived from openssl/apps/s_cb.c */
923 static void
924 tlso_info_cb( const SSL *ssl, int where, int ret )
925 {
926         int w;
927         char *op;
928         char *state = (char *) SSL_state_string_long( (SSL *)ssl );
929
930         w = where & ~SSL_ST_MASK;
931         if ( w & SSL_ST_CONNECT ) {
932                 op = "SSL_connect";
933         } else if ( w & SSL_ST_ACCEPT ) {
934                 op = "SSL_accept";
935         } else {
936                 op = "undefined";
937         }
938
939 #ifdef HAVE_EBCDIC
940         if ( state ) {
941                 state = LDAP_STRDUP( state );
942                 __etoa( state );
943         }
944 #endif
945         if ( where & SSL_CB_LOOP ) {
946                 Debug( LDAP_DEBUG_TRACE,
947                            "TLS trace: %s:%s\n",
948                            op, state, 0 );
949
950         } else if ( where & SSL_CB_ALERT ) {
951                 char *atype = (char *) SSL_alert_type_string_long( ret );
952                 char *adesc = (char *) SSL_alert_desc_string_long( ret );
953                 op = ( where & SSL_CB_READ ) ? "read" : "write";
954 #ifdef HAVE_EBCDIC
955                 if ( atype ) {
956                         atype = LDAP_STRDUP( atype );
957                         __etoa( atype );
958                 }
959                 if ( adesc ) {
960                         adesc = LDAP_STRDUP( adesc );
961                         __etoa( adesc );
962                 }
963 #endif
964                 Debug( LDAP_DEBUG_TRACE,
965                            "TLS trace: SSL3 alert %s:%s:%s\n",
966                            op, atype, adesc );
967 #ifdef HAVE_EBCDIC
968                 if ( atype ) LDAP_FREE( atype );
969                 if ( adesc ) LDAP_FREE( adesc );
970 #endif
971         } else if ( where & SSL_CB_EXIT ) {
972                 if ( ret == 0 ) {
973                         Debug( LDAP_DEBUG_TRACE,
974                                    "TLS trace: %s:failed in %s\n",
975                                    op, state, 0 );
976                 } else if ( ret < 0 ) {
977                         Debug( LDAP_DEBUG_TRACE,
978                                    "TLS trace: %s:error in %s\n",
979                                    op, state, 0 );
980                 }
981         }
982 #ifdef HAVE_EBCDIC
983         if ( state ) LDAP_FREE( state );
984 #endif
985 }
986
987 static int
988 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
989 {
990         X509 *cert;
991         int errnum;
992         int errdepth;
993         X509_NAME *subject;
994         X509_NAME *issuer;
995         char *sname;
996         char *iname;
997         char *certerr = NULL;
998
999         cert = X509_STORE_CTX_get_current_cert( ctx );
1000         errnum = X509_STORE_CTX_get_error( ctx );
1001         errdepth = X509_STORE_CTX_get_error_depth( ctx );
1002
1003         /*
1004          * X509_get_*_name return pointers to the internal copies of
1005          * those things requested.  So do not free them.
1006          */
1007         subject = X509_get_subject_name( cert );
1008         issuer = X509_get_issuer_name( cert );
1009         /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1010         sname = X509_NAME_oneline( subject, NULL, 0 );
1011         iname = X509_NAME_oneline( issuer, NULL, 0 );
1012         if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1013 #ifdef HAVE_EBCDIC
1014         if ( sname ) __etoa( sname );
1015         if ( iname ) __etoa( iname );
1016         if ( certerr ) {
1017                 certerr = LDAP_STRDUP( certerr );
1018                 __etoa( certerr );
1019         }
1020 #endif
1021         Debug( LDAP_DEBUG_TRACE,
1022                    "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1023                    errdepth, errnum,
1024                    sname ? sname : "-unknown-" );
1025         Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1026         if ( !ok ) {
1027                 Debug( LDAP_DEBUG_ANY,
1028                         "TLS certificate verification: Error, %s\n",
1029                         certerr, 0, 0 );
1030         }
1031         if ( sname )
1032                 CRYPTO_free ( sname );
1033         if ( iname )
1034                 CRYPTO_free ( iname );
1035 #ifdef HAVE_EBCDIC
1036         if ( certerr ) LDAP_FREE( certerr );
1037 #endif
1038         return ok;
1039 }
1040
1041 static int
1042 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1043 {
1044         (void) tlso_verify_cb( ok, ctx );
1045         return 1;
1046 }
1047
1048 /* Inspired by ERR_print_errors in OpenSSL */
1049 static void
1050 tlso_report_error( void )
1051 {
1052         unsigned long l;
1053         char buf[200];
1054         const char *file;
1055         int line;
1056
1057         while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1058                 ERR_error_string_n( l, buf, sizeof( buf ) );
1059 #ifdef HAVE_EBCDIC
1060                 if ( file ) {
1061                         file = LDAP_STRDUP( file );
1062                         __etoa( (char *)file );
1063                 }
1064                 __etoa( buf );
1065 #endif
1066                 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1067                         buf, file, line );
1068 #ifdef HAVE_EBCDIC
1069                 if ( file ) LDAP_FREE( (void *)file );
1070 #endif
1071         }
1072 }
1073
1074 static RSA *
1075 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1076 {
1077         RSA *tmp_rsa;
1078         /* FIXME:  Pregenerate the key on startup */
1079         /* FIXME:  Who frees the key? */
1080 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1081         BIGNUM *bn = BN_new();
1082         tmp_rsa = NULL;
1083         if ( bn ) {
1084                 if ( BN_set_word( bn, RSA_F4 )) {
1085                         tmp_rsa = RSA_new();
1086                         if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1087                                 RSA_free( tmp_rsa );
1088                                 tmp_rsa = NULL;
1089                         }
1090                 }
1091                 BN_free( bn );
1092         }
1093 #else
1094         tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1095 #endif
1096
1097         if ( !tmp_rsa ) {
1098                 Debug( LDAP_DEBUG_ANY,
1099                         "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1100                         key_length, is_export ? "export" : "domestic", 0 );
1101         }
1102         return tmp_rsa;
1103 }
1104
1105 static int
1106 tlso_seed_PRNG( const char *randfile )
1107 {
1108 #ifndef URANDOM_DEVICE
1109         /* no /dev/urandom (or equiv) */
1110         long total=0;
1111         char buffer[MAXPATHLEN];
1112
1113         if (randfile == NULL) {
1114                 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1115                  * If $HOME is not set or buffer too small to hold the pathname,
1116                  * an error occurs.     - From RAND_file_name() man page.
1117                  * The fact is that when $HOME is NULL, .rnd is used.
1118                  */
1119                 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1120
1121         } else if (RAND_egd(randfile) > 0) {
1122                 /* EGD socket */
1123                 return 0;
1124         }
1125
1126         if (randfile == NULL) {
1127                 Debug( LDAP_DEBUG_ANY,
1128                         "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1129                         0, 0, 0);
1130                 return -1;
1131         }
1132
1133         total = RAND_load_file(randfile, -1);
1134
1135         if (RAND_status() == 0) {
1136                 Debug( LDAP_DEBUG_ANY,
1137                         "TLS: PRNG not been seeded with enough data\n",
1138                         0, 0, 0);
1139                 return -1;
1140         }
1141
1142         /* assume if there was enough bits to seed that it's okay
1143          * to write derived bits to the file
1144          */
1145         RAND_write_file(randfile);
1146
1147 #endif
1148
1149         return 0;
1150 }
1151
1152
1153 tls_impl ldap_int_tls_impl = {
1154         "OpenSSL",
1155
1156         tlso_init,
1157         tlso_destroy,
1158
1159         tlso_ctx_new,
1160         tlso_ctx_ref,
1161         tlso_ctx_free,
1162         tlso_ctx_init,
1163
1164         tlso_session_new,
1165         tlso_session_connect,
1166         tlso_session_accept,
1167         tlso_session_upflags,
1168         tlso_session_errmsg,
1169         tlso_session_my_dn,
1170         tlso_session_peer_dn,
1171         tlso_session_chkhost,
1172         tlso_session_strength,
1173
1174         &tlso_sbio,
1175
1176 #ifdef LDAP_R_COMPILE
1177         tlso_thr_init,
1178 #else
1179         NULL,
1180 #endif
1181
1182         0
1183 };
1184
1185 #endif /* HAVE_OPENSSL */