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