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