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