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