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