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