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