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