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