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