]> git.sur5r.net Git - openldap/blob - libraries/libldap/tls_o.c
ITS#8753 Public key pinning support in libldap
[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                 mdctx = EVP_MD_CTX_new();
871                 if ( !mdctx ) {
872                         rc = -1;
873                         goto done;
874                 }
875
876                 EVP_DigestInit_ex( mdctx, md, NULL );
877                 EVP_DigestUpdate( mdctx, key.bv_val, key.bv_len );
878                 EVP_DigestFinal_ex( mdctx, (unsigned char *)keyhash.bv_val, &len );
879                 keyhash.bv_len = len;
880                 EVP_MD_CTX_free( mdctx );
881         } else {
882                 keyhash = key;
883         }
884
885         if ( ber_bvcmp( hash, &keyhash ) ) {
886                 rc = LDAP_CONNECT_ERROR;
887                 Debug( LDAP_DEBUG_ANY, "tlso_session_pinning: "
888                                 "public key hash does not match provided pin.\n", 0, 0, 0 );
889                 if ( ld->ld_error ) {
890                         LDAP_FREE( ld->ld_error );
891                 }
892                 ld->ld_error = LDAP_STRDUP(
893                         _("TLS: public key hash does not match provided pin"));
894         }
895
896 done:
897         LDAP_FREE( key.bv_val );
898         return rc;
899 }
900
901 /*
902  * TLS support for LBER Sockbufs
903  */
904
905 struct tls_data {
906         tlso_session            *session;
907         Sockbuf_IO_Desc         *sbiod;
908 };
909
910 #if OPENSSL_VERSION_NUMBER < 0x10100000
911 #define BIO_set_init(b, x)      b->init = x
912 #define BIO_set_data(b, x)      b->ptr = x
913 #define BIO_clear_flags(b, x)   b->flags &= ~(x)
914 #define BIO_get_data(b) b->ptr
915 #endif
916 static int
917 tlso_bio_create( BIO *b ) {
918         BIO_set_init( b, 1 );
919         BIO_set_data( b, NULL );
920         BIO_clear_flags( b, ~0 );
921         return 1;
922 }
923
924 static int
925 tlso_bio_destroy( BIO *b )
926 {
927         if ( b == NULL ) return 0;
928
929         BIO_set_data( b, NULL );                /* sb_tls_remove() will free it */
930         BIO_set_init( b, 0 );
931         BIO_clear_flags( b, ~0 );
932         return 1;
933 }
934
935 static int
936 tlso_bio_read( BIO *b, char *buf, int len )
937 {
938         struct tls_data         *p;
939         int                     ret;
940                 
941         if ( buf == NULL || len <= 0 ) return 0;
942
943         p = (struct tls_data *)BIO_get_data(b);
944
945         if ( p == NULL || p->sbiod == NULL ) {
946                 return 0;
947         }
948
949         ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
950
951         BIO_clear_retry_flags( b );
952         if ( ret < 0 ) {
953                 int err = sock_errno();
954                 if ( err == EAGAIN || err == EWOULDBLOCK ) {
955                         BIO_set_retry_read( b );
956                 }
957         }
958
959         return ret;
960 }
961
962 static int
963 tlso_bio_write( BIO *b, const char *buf, int len )
964 {
965         struct tls_data         *p;
966         int                     ret;
967         
968         if ( buf == NULL || len <= 0 ) return 0;
969         
970         p = (struct tls_data *)BIO_get_data(b);
971
972         if ( p == NULL || p->sbiod == NULL ) {
973                 return 0;
974         }
975
976         ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
977
978         BIO_clear_retry_flags( b );
979         if ( ret < 0 ) {
980                 int err = sock_errno();
981                 if ( err == EAGAIN || err == EWOULDBLOCK ) {
982                         BIO_set_retry_write( b );
983                 }
984         }
985
986         return ret;
987 }
988
989 static long
990 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
991 {
992         if ( cmd == BIO_CTRL_FLUSH ) {
993                 /* The OpenSSL library needs this */
994                 return 1;
995         }
996         return 0;
997 }
998
999 static int
1000 tlso_bio_gets( BIO *b, char *buf, int len )
1001 {
1002         return -1;
1003 }
1004
1005 static int
1006 tlso_bio_puts( BIO *b, const char *str )
1007 {
1008         return tlso_bio_write( b, str, strlen( str ) );
1009 }
1010
1011 #if OPENSSL_VERSION_NUMBER >= 0x10100000
1012 struct bio_method_st {
1013     int type;
1014     const char *name;
1015     int (*bwrite) (BIO *, const char *, int);
1016     int (*bread) (BIO *, char *, int);
1017     int (*bputs) (BIO *, const char *);
1018     int (*bgets) (BIO *, char *, int);
1019     long (*ctrl) (BIO *, int, long, void *);
1020     int (*create) (BIO *);
1021     int (*destroy) (BIO *);
1022     long (*callback_ctrl) (BIO *, int, bio_info_cb *);
1023 };
1024 #endif
1025
1026 static BIO_METHOD tlso_bio_method =
1027 {
1028         ( 100 | 0x400 ),                /* it's a source/sink BIO */
1029         "sockbuf glue",
1030         tlso_bio_write,
1031         tlso_bio_read,
1032         tlso_bio_puts,
1033         tlso_bio_gets,
1034         tlso_bio_ctrl,
1035         tlso_bio_create,
1036         tlso_bio_destroy
1037 };
1038
1039 static int
1040 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
1041 {
1042         struct tls_data         *p;
1043         BIO                     *bio;
1044
1045         assert( sbiod != NULL );
1046
1047         p = LBER_MALLOC( sizeof( *p ) );
1048         if ( p == NULL ) {
1049                 return -1;
1050         }
1051         
1052         p->session = arg;
1053         p->sbiod = sbiod;
1054         bio = BIO_new( &tlso_bio_method );
1055         BIO_set_data( bio, p );
1056         SSL_set_bio( p->session, bio, bio );
1057         sbiod->sbiod_pvt = p;
1058         return 0;
1059 }
1060
1061 static int
1062 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
1063 {
1064         struct tls_data         *p;
1065         
1066         assert( sbiod != NULL );
1067         assert( sbiod->sbiod_pvt != NULL );
1068
1069         p = (struct tls_data *)sbiod->sbiod_pvt;
1070         SSL_free( p->session );
1071         LBER_FREE( sbiod->sbiod_pvt );
1072         sbiod->sbiod_pvt = NULL;
1073         return 0;
1074 }
1075
1076 static int
1077 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
1078 {
1079         struct tls_data         *p;
1080         
1081         assert( sbiod != NULL );
1082         assert( sbiod->sbiod_pvt != NULL );
1083
1084         p = (struct tls_data *)sbiod->sbiod_pvt;
1085         SSL_shutdown( p->session );
1086         return 0;
1087 }
1088
1089 static int
1090 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
1091 {
1092         struct tls_data         *p;
1093         
1094         assert( sbiod != NULL );
1095         assert( sbiod->sbiod_pvt != NULL );
1096
1097         p = (struct tls_data *)sbiod->sbiod_pvt;
1098         
1099         if ( opt == LBER_SB_OPT_GET_SSL ) {
1100                 *((tlso_session **)arg) = p->session;
1101                 return 1;
1102
1103         } else if ( opt == LBER_SB_OPT_DATA_READY ) {
1104                 if( SSL_pending( p->session ) > 0 ) {
1105                         return 1;
1106                 }
1107         }
1108         
1109         return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
1110 }
1111
1112 static ber_slen_t
1113 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1114 {
1115         struct tls_data         *p;
1116         ber_slen_t              ret;
1117         int                     err;
1118
1119         assert( sbiod != NULL );
1120         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1121
1122         p = (struct tls_data *)sbiod->sbiod_pvt;
1123
1124         ret = SSL_read( p->session, (char *)buf, len );
1125 #ifdef HAVE_WINSOCK
1126         errno = WSAGetLastError();
1127 #endif
1128         err = SSL_get_error( p->session, ret );
1129         if (err == SSL_ERROR_WANT_READ ) {
1130                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1131                 sock_errset(EWOULDBLOCK);
1132         }
1133         else
1134                 sbiod->sbiod_sb->sb_trans_needs_read = 0;
1135         return ret;
1136 }
1137
1138 static ber_slen_t
1139 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1140 {
1141         struct tls_data         *p;
1142         ber_slen_t              ret;
1143         int                     err;
1144
1145         assert( sbiod != NULL );
1146         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1147
1148         p = (struct tls_data *)sbiod->sbiod_pvt;
1149
1150         ret = SSL_write( p->session, (char *)buf, len );
1151 #ifdef HAVE_WINSOCK
1152         errno = WSAGetLastError();
1153 #endif
1154         err = SSL_get_error( p->session, ret );
1155         if (err == SSL_ERROR_WANT_WRITE ) {
1156                 sbiod->sbiod_sb->sb_trans_needs_write = 1;
1157                 sock_errset(EWOULDBLOCK);
1158
1159         } else {
1160                 sbiod->sbiod_sb->sb_trans_needs_write = 0;
1161         }
1162         return ret;
1163 }
1164
1165 static Sockbuf_IO tlso_sbio =
1166 {
1167         tlso_sb_setup,          /* sbi_setup */
1168         tlso_sb_remove,         /* sbi_remove */
1169         tlso_sb_ctrl,           /* sbi_ctrl */
1170         tlso_sb_read,           /* sbi_read */
1171         tlso_sb_write,          /* sbi_write */
1172         tlso_sb_close           /* sbi_close */
1173 };
1174
1175 /* Derived from openssl/apps/s_cb.c */
1176 static void
1177 tlso_info_cb( const SSL *ssl, int where, int ret )
1178 {
1179         int w;
1180         char *op;
1181         char *state = (char *) SSL_state_string_long( (SSL *)ssl );
1182
1183         w = where & ~SSL_ST_MASK;
1184         if ( w & SSL_ST_CONNECT ) {
1185                 op = "SSL_connect";
1186         } else if ( w & SSL_ST_ACCEPT ) {
1187                 op = "SSL_accept";
1188         } else {
1189                 op = "undefined";
1190         }
1191
1192 #ifdef HAVE_EBCDIC
1193         if ( state ) {
1194                 state = LDAP_STRDUP( state );
1195                 __etoa( state );
1196         }
1197 #endif
1198         if ( where & SSL_CB_LOOP ) {
1199                 Debug( LDAP_DEBUG_TRACE,
1200                            "TLS trace: %s:%s\n",
1201                            op, state, 0 );
1202
1203         } else if ( where & SSL_CB_ALERT ) {
1204                 char *atype = (char *) SSL_alert_type_string_long( ret );
1205                 char *adesc = (char *) SSL_alert_desc_string_long( ret );
1206                 op = ( where & SSL_CB_READ ) ? "read" : "write";
1207 #ifdef HAVE_EBCDIC
1208                 if ( atype ) {
1209                         atype = LDAP_STRDUP( atype );
1210                         __etoa( atype );
1211                 }
1212                 if ( adesc ) {
1213                         adesc = LDAP_STRDUP( adesc );
1214                         __etoa( adesc );
1215                 }
1216 #endif
1217                 Debug( LDAP_DEBUG_TRACE,
1218                            "TLS trace: SSL3 alert %s:%s:%s\n",
1219                            op, atype, adesc );
1220 #ifdef HAVE_EBCDIC
1221                 if ( atype ) LDAP_FREE( atype );
1222                 if ( adesc ) LDAP_FREE( adesc );
1223 #endif
1224         } else if ( where & SSL_CB_EXIT ) {
1225                 if ( ret == 0 ) {
1226                         Debug( LDAP_DEBUG_TRACE,
1227                                    "TLS trace: %s:failed in %s\n",
1228                                    op, state, 0 );
1229                 } else if ( ret < 0 ) {
1230                         Debug( LDAP_DEBUG_TRACE,
1231                                    "TLS trace: %s:error in %s\n",
1232                                    op, state, 0 );
1233                 }
1234         }
1235 #ifdef HAVE_EBCDIC
1236         if ( state ) LDAP_FREE( state );
1237 #endif
1238 }
1239
1240 static int
1241 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
1242 {
1243         X509 *cert;
1244         int errnum;
1245         int errdepth;
1246         X509_NAME *subject;
1247         X509_NAME *issuer;
1248         char *sname;
1249         char *iname;
1250         char *certerr = NULL;
1251
1252         cert = X509_STORE_CTX_get_current_cert( ctx );
1253         errnum = X509_STORE_CTX_get_error( ctx );
1254         errdepth = X509_STORE_CTX_get_error_depth( ctx );
1255
1256         /*
1257          * X509_get_*_name return pointers to the internal copies of
1258          * those things requested.  So do not free them.
1259          */
1260         subject = X509_get_subject_name( cert );
1261         issuer = X509_get_issuer_name( cert );
1262         /* X509_NAME_oneline, if passed a NULL buf, allocate memory */
1263         sname = X509_NAME_oneline( subject, NULL, 0 );
1264         iname = X509_NAME_oneline( issuer, NULL, 0 );
1265         if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1266 #ifdef HAVE_EBCDIC
1267         if ( sname ) __etoa( sname );
1268         if ( iname ) __etoa( iname );
1269         if ( certerr ) {
1270                 certerr = LDAP_STRDUP( certerr );
1271                 __etoa( certerr );
1272         }
1273 #endif
1274         Debug( LDAP_DEBUG_TRACE,
1275                    "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1276                    errdepth, errnum,
1277                    sname ? sname : "-unknown-" );
1278         Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1279         if ( !ok ) {
1280                 Debug( LDAP_DEBUG_ANY,
1281                         "TLS certificate verification: Error, %s\n",
1282                         certerr, 0, 0 );
1283         }
1284         if ( sname )
1285                 OPENSSL_free ( sname );
1286         if ( iname )
1287                 OPENSSL_free ( iname );
1288 #ifdef HAVE_EBCDIC
1289         if ( certerr ) LDAP_FREE( certerr );
1290 #endif
1291         return ok;
1292 }
1293
1294 static int
1295 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1296 {
1297         (void) tlso_verify_cb( ok, ctx );
1298         return 1;
1299 }
1300
1301 /* Inspired by ERR_print_errors in OpenSSL */
1302 static void
1303 tlso_report_error( void )
1304 {
1305         unsigned long l;
1306         char buf[200];
1307         const char *file;
1308         int line;
1309
1310         while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1311                 ERR_error_string_n( l, buf, sizeof( buf ) );
1312 #ifdef HAVE_EBCDIC
1313                 if ( file ) {
1314                         file = LDAP_STRDUP( file );
1315                         __etoa( (char *)file );
1316                 }
1317                 __etoa( buf );
1318 #endif
1319                 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1320                         buf, file, line );
1321 #ifdef HAVE_EBCDIC
1322                 if ( file ) LDAP_FREE( (void *)file );
1323 #endif
1324         }
1325 }
1326
1327 #if OPENSSL_VERSION_NUMBER < 0x10100000
1328 static RSA *
1329 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1330 {
1331         RSA *tmp_rsa;
1332         /* FIXME:  Pregenerate the key on startup */
1333         /* FIXME:  Who frees the key? */
1334 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1335         BIGNUM *bn = BN_new();
1336         tmp_rsa = NULL;
1337         if ( bn ) {
1338                 if ( BN_set_word( bn, RSA_F4 )) {
1339                         tmp_rsa = RSA_new();
1340                         if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1341                                 RSA_free( tmp_rsa );
1342                                 tmp_rsa = NULL;
1343                         }
1344                 }
1345                 BN_free( bn );
1346         }
1347 #else
1348         tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1349 #endif
1350
1351         if ( !tmp_rsa ) {
1352                 Debug( LDAP_DEBUG_ANY,
1353                         "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1354                         key_length, is_export ? "export" : "domestic", 0 );
1355         }
1356         return tmp_rsa;
1357 }
1358 #endif /* OPENSSL_VERSION_NUMBER < 1.1 */
1359
1360 static int
1361 tlso_seed_PRNG( const char *randfile )
1362 {
1363 #ifndef URANDOM_DEVICE
1364         /* no /dev/urandom (or equiv) */
1365         long total=0;
1366         char buffer[MAXPATHLEN];
1367
1368         if (randfile == NULL) {
1369                 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1370                  * If $HOME is not set or buffer too small to hold the pathname,
1371                  * an error occurs.     - From RAND_file_name() man page.
1372                  * The fact is that when $HOME is NULL, .rnd is used.
1373                  */
1374                 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1375         }
1376 #ifndef OPENSSL_NO_EGD
1377         else if (RAND_egd(randfile) > 0) {
1378                 /* EGD socket */
1379                 return 0;
1380         }
1381 #endif
1382
1383         if (randfile == NULL) {
1384                 Debug( LDAP_DEBUG_ANY,
1385                         "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1386                         0, 0, 0);
1387                 return -1;
1388         }
1389
1390         total = RAND_load_file(randfile, -1);
1391
1392         if (RAND_status() == 0) {
1393                 Debug( LDAP_DEBUG_ANY,
1394                         "TLS: PRNG not been seeded with enough data\n",
1395                         0, 0, 0);
1396                 return -1;
1397         }
1398
1399         /* assume if there was enough bits to seed that it's okay
1400          * to write derived bits to the file
1401          */
1402         RAND_write_file(randfile);
1403
1404 #endif
1405
1406         return 0;
1407 }
1408
1409
1410 tls_impl ldap_int_tls_impl = {
1411         "OpenSSL",
1412
1413         tlso_init,
1414         tlso_destroy,
1415
1416         tlso_ctx_new,
1417         tlso_ctx_ref,
1418         tlso_ctx_free,
1419         tlso_ctx_init,
1420
1421         tlso_session_new,
1422         tlso_session_connect,
1423         tlso_session_accept,
1424         tlso_session_upflags,
1425         tlso_session_errmsg,
1426         tlso_session_my_dn,
1427         tlso_session_peer_dn,
1428         tlso_session_chkhost,
1429         tlso_session_strength,
1430         tlso_session_unique,
1431         tlso_session_version,
1432         tlso_session_cipher,
1433         tlso_session_peercert,
1434         tlso_session_pinning,
1435
1436         &tlso_sbio,
1437
1438 #ifdef LDAP_R_COMPILE
1439         tlso_thr_init,
1440 #else
1441         NULL,
1442 #endif
1443
1444         0
1445 };
1446
1447 #endif /* HAVE_OPENSSL */