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