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