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