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