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