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