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