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