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