1 /* tls.c - Handle tls/ssl using SSLeay, OpenSSL or GNUTLS. */
2 /* $OpenLDAP: pkg/ldap/libraries/libldap/tls.c,v 1.133.2.11 2008/07/09 23:56:44 quanah Exp $ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2008 The OpenLDAP Foundation.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted only as authorized by the OpenLDAP
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>.
16 /* ACKNOWLEDGEMENTS: GNUTLS support written by Howard Chu and
17 * Matt Backes; sponsored by The Written Word (thewrittenword.com)
18 * and Stanford University (stanford.edu).
22 #include "ldap_config.h"
26 #include <ac/stdlib.h>
28 #include <ac/socket.h>
29 #include <ac/string.h>
32 #include <ac/unistd.h>
34 #include <ac/dirent.h>
41 #include <ldap_pvt_thread.h>
45 #include <gnutls/gnutls.h>
46 #include <gnutls/x509.h>
49 #define DH_BITS (1024)
52 #ifdef HAVE_OPENSSL_SSL_H
53 #include <openssl/ssl.h>
54 #include <openssl/x509v3.h>
55 #include <openssl/err.h>
56 #include <openssl/rand.h>
57 #include <openssl/safestack.h>
58 #elif defined( HAVE_SSL_H )
63 #define HAS_TLS( sb ) ber_sockbuf_ctrl( sb, LBER_SB_OPT_HAS_IO, \
64 (void *)&sb_tls_sbio )
68 /* RFC2459 minimum required set of supported attribute types
71 typedef struct oid_name
{
76 #define CN_OID oids[0].oid.bv_val
78 static oid_name oids
[] = {
79 { BER_BVC("2.5.4.3"), BER_BVC("cn") },
80 { BER_BVC("2.5.4.4"), BER_BVC("sn") },
81 { BER_BVC("2.5.4.6"), BER_BVC("c") },
82 { BER_BVC("2.5.4.7"), BER_BVC("l") },
83 { BER_BVC("2.5.4.8"), BER_BVC("st") },
84 { BER_BVC("2.5.4.10"), BER_BVC("o") },
85 { BER_BVC("2.5.4.11"), BER_BVC("ou") },
86 { BER_BVC("2.5.4.12"), BER_BVC("title") },
87 { BER_BVC("2.5.4.41"), BER_BVC("name") },
88 { BER_BVC("2.5.4.42"), BER_BVC("givenName") },
89 { BER_BVC("2.5.4.43"), BER_BVC("initials") },
90 { BER_BVC("2.5.4.44"), BER_BVC("generationQualifier") },
91 { BER_BVC("2.5.4.46"), BER_BVC("dnQualifier") },
92 { BER_BVC("1.2.840.113549.1.9.1"), BER_BVC("email") },
93 { BER_BVC("0.9.2342.19200300.100.1.25"), BER_BVC("dc") },
94 { BER_BVNULL
, BER_BVNULL
}
100 typedef struct tls_cipher_suite
{
102 gnutls_kx_algorithm_t kx
;
103 gnutls_cipher_algorithm_t cipher
;
104 gnutls_mac_algorithm_t mac
;
105 gnutls_protocol_t version
;
108 static tls_cipher_suite
*ciphers
;
109 static int n_ciphers
;
111 /* sorta replacing SSL_CTX */
112 typedef struct tls_ctx
{
113 struct ldapoptions
*lo
;
114 gnutls_certificate_credentials_t cred
;
115 gnutls_dh_params_t dh_params
;
116 unsigned long verify_depth
;
121 #ifdef LDAP_R_COMPILE
122 ldap_pvt_thread_mutex_t ref_mutex
;
126 /* sorta replacing SSL */
127 typedef struct tls_session
{
129 gnutls_session_t session
;
130 struct berval peer_der_dn
;
133 #ifdef LDAP_R_COMPILE
136 ldap_pvt_gcry_mutex_init( void **priv
)
139 ldap_pvt_thread_mutex_t
*lock
= LDAP_MALLOC( sizeof( ldap_pvt_thread_mutex_t
));
144 err
= ldap_pvt_thread_mutex_init( lock
);
153 ldap_pvt_gcry_mutex_destroy( void **lock
)
155 int err
= ldap_pvt_thread_mutex_destroy( *lock
);
160 ldap_pvt_gcry_mutex_lock( void **lock
)
162 return ldap_pvt_thread_mutex_lock( *lock
);
165 ldap_pvt_gcry_mutex_unlock( void **lock
)
167 return ldap_pvt_thread_mutex_unlock( *lock
);
170 static struct gcry_thread_cbs ldap_generic_thread_cbs
= {
171 GCRY_THREAD_OPTION_USER
,
173 ldap_pvt_gcry_mutex_init
,
174 ldap_pvt_gcry_mutex_destroy
,
175 ldap_pvt_gcry_mutex_lock
,
176 ldap_pvt_gcry_mutex_unlock
,
177 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
181 tls_init_threads( void )
183 gcry_control (GCRYCTL_SET_THREAD_CBS
, &ldap_generic_thread_cbs
);
185 #endif /* LDAP_R_COMPILE */
188 ldap_pvt_tls_ctx_free ( void *c
)
195 #ifdef LDAP_R_COMPILE
196 ldap_pvt_thread_mutex_lock( &ctx
->ref_mutex
);
198 refcount
= --ctx
->refcount
;
199 #ifdef LDAP_R_COMPILE
200 ldap_pvt_thread_mutex_unlock( &ctx
->ref_mutex
);
204 LDAP_FREE( ctx
->kx_list
);
205 gnutls_certificate_free_credentials( ctx
->cred
);
210 tls_ctx_new ( struct ldapoptions
*lo
)
214 ctx
= ber_memcalloc ( 1, sizeof (*ctx
) );
217 if ( gnutls_certificate_allocate_credentials( &ctx
->cred
)) {
222 #ifdef LDAP_R_COMPILE
223 ldap_pvt_thread_mutex_init( &ctx
->ref_mutex
);
230 tls_ctx_ref( tls_ctx
*ctx
)
232 #ifdef LDAP_R_COMPILE
233 ldap_pvt_thread_mutex_lock( &ctx
->ref_mutex
);
236 #ifdef LDAP_R_COMPILE
237 ldap_pvt_thread_mutex_unlock( &ctx
->ref_mutex
);
242 tls_session_new ( tls_ctx
* ctx
, int is_server
)
244 tls_session
*session
;
246 session
= ber_memcalloc ( 1, sizeof (*session
) );
251 gnutls_init( &session
->session
, is_server
? GNUTLS_SERVER
: GNUTLS_CLIENT
);
252 gnutls_set_default_priority( session
->session
);
253 if ( ctx
->kx_list
) {
254 gnutls_kx_set_priority( session
->session
, ctx
->kx_list
);
255 gnutls_cipher_set_priority( session
->session
, ctx
->cipher_list
);
256 gnutls_mac_set_priority( session
->session
, ctx
->mac_list
);
259 gnutls_credentials_set( session
->session
, GNUTLS_CRD_CERTIFICATE
, ctx
->cred
);
263 if ( ctx
->lo
->ldo_tls_require_cert
) {
264 flag
= GNUTLS_CERT_REQUEST
;
265 if ( ctx
->lo
->ldo_tls_require_cert
== LDAP_OPT_X_TLS_DEMAND
||
266 ctx
->lo
->ldo_tls_require_cert
== LDAP_OPT_X_TLS_HARD
)
267 flag
= GNUTLS_CERT_REQUIRE
;
268 gnutls_certificate_server_set_request( session
->session
, flag
);
275 tls_session_free ( tls_session
* session
)
277 ber_memfree ( session
);
280 #define tls_session_connect( ssl ) gnutls_handshake( ssl->session )
281 #define tls_session_accept( ssl ) gnutls_handshake( ssl->session )
283 /* suites is a string of colon-separated cipher suite names. */
285 tls_parse_ciphers( tls_ctx
*ctx
, char *suites
)
289 int *list
, nkx
= 0, ncipher
= 0, nmac
= 0;
290 int *kx
, *cipher
, *mac
;
295 end
= strchr(ptr
, ':');
300 for (i
=0; i
<n_ciphers
; i
++) {
301 if ( !strncasecmp( ciphers
[i
].name
, ptr
, len
)) {
306 if ( i
== n_ciphers
) {
307 /* unrecognized cipher suite */
313 /* Space for all 3 lists */
314 list
= LDAP_MALLOC( (num
+1) * sizeof(int) * 3 );
323 end
= strchr(ptr
, ':');
328 for (i
=0; i
<n_ciphers
; i
++) {
329 /* For each cipher suite, insert its algorithms into
330 * their respective priority lists. Make sure they
331 * only appear once in each list.
333 if ( !strncasecmp( ciphers
[i
].name
, ptr
, len
)) {
334 for (j
=0; j
<nkx
; j
++)
335 if ( kx
[j
] == ciphers
[i
].kx
)
338 kx
[nkx
++] = ciphers
[i
].kx
;
339 for (j
=0; j
<ncipher
; j
++)
340 if ( cipher
[j
] == ciphers
[i
].cipher
)
343 cipher
[ncipher
++] = ciphers
[i
].cipher
;
344 for (j
=0; j
<nmac
; j
++)
345 if ( mac
[j
] == ciphers
[i
].mac
)
348 mac
[nmac
++] = ciphers
[i
].mac
;
358 ctx
->cipher_list
= cipher
;
365 typedef SSL_CTX tls_ctx
;
366 typedef SSL tls_session
;
368 static int tls_opt_trace
= 1;
369 static char *tls_opt_randfile
= NULL
;
371 static void tls_report_error( void );
373 static void tls_info_cb( const SSL
*ssl
, int where
, int ret
);
374 static int tls_verify_cb( int ok
, X509_STORE_CTX
*ctx
);
375 static int tls_verify_ok( int ok
, X509_STORE_CTX
*ctx
);
376 static RSA
* tls_tmp_rsa_cb( SSL
*ssl
, int is_export
, int key_length
);
378 static DH
* tls_tmp_dh_cb( SSL
*ssl
, int is_export
, int key_length
);
380 typedef struct dhplist
{
381 struct dhplist
*next
;
386 static dhplist
*dhparams
;
388 static int tls_seed_PRNG( const char *randfile
);
390 #ifdef LDAP_R_COMPILE
392 * provide mutexes for the SSLeay library.
394 static ldap_pvt_thread_mutex_t tls_mutexes
[CRYPTO_NUM_LOCKS
];
396 static void tls_locking_cb( int mode
, int type
, const char *file
, int line
)
398 if ( mode
& CRYPTO_LOCK
) {
399 ldap_pvt_thread_mutex_lock( &tls_mutexes
[type
] );
401 ldap_pvt_thread_mutex_unlock( &tls_mutexes
[type
] );
405 static unsigned long tls_thread_self( void )
407 /* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
408 * is an integral type that fits in an unsigned long
411 /* force an error if the ldap_pvt_thread_t type is too large */
412 enum { ok
= sizeof( ldap_pvt_thread_t
) <= sizeof( unsigned long ) };
413 typedef struct { int dummy
: ok
? 1 : -1; } Check
[ok
? 1 : -1];
415 return (unsigned long) ldap_pvt_thread_self();
418 static void tls_init_threads( void )
422 for( i
=0; i
< CRYPTO_NUM_LOCKS
; i
++ ) {
423 ldap_pvt_thread_mutex_init( &tls_mutexes
[i
] );
425 CRYPTO_set_locking_callback( tls_locking_cb
);
426 CRYPTO_set_id_callback( tls_thread_self
);
428 #endif /* LDAP_R_COMPILE */
431 ldap_pvt_tls_ctx_free ( void *c
)
438 tls_ctx_new( struct ldapoptions
*lo
)
440 return SSL_CTX_new( SSLv23_method() );
444 tls_ctx_ref( void *c
)
447 CRYPTO_add( &ctx
->references
, 1, CRYPTO_LOCK_SSL_CTX
);
451 tls_session_new( tls_ctx
*ctx
, int is_server
)
453 return SSL_new( ctx
);
456 #define tls_session_connect( ssl ) SSL_connect( ssl )
457 #define tls_session_accept( ssl ) SSL_accept( ssl )
459 static STACK_OF(X509_NAME
) *
460 get_ca_list( char * bundle
, char * dir
)
462 STACK_OF(X509_NAME
) *ca_list
= NULL
;
465 ca_list
= SSL_load_client_CA_file( bundle
);
467 #if defined(HAVE_DIRENT_H) || defined(dirent)
472 ca_list
= sk_X509_NAME_new_null();
475 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list
, dir
) &&
477 sk_X509_NAME_free( ca_list
);
485 #endif /* HAVE_GNUTLS */
487 #ifdef LDAP_R_COMPILE
489 * an extra mutex for the default ctx.
491 static ldap_pvt_thread_mutex_t tls_def_ctx_mutex
;
495 ldap_int_tls_destroy( struct ldapoptions
*lo
)
497 if ( lo
->ldo_tls_ctx
) {
498 ldap_pvt_tls_ctx_free( lo
->ldo_tls_ctx
);
499 lo
->ldo_tls_ctx
= NULL
;
502 if ( lo
->ldo_tls_certfile
) {
503 LDAP_FREE( lo
->ldo_tls_certfile
);
504 lo
->ldo_tls_certfile
= NULL
;
506 if ( lo
->ldo_tls_keyfile
) {
507 LDAP_FREE( lo
->ldo_tls_keyfile
);
508 lo
->ldo_tls_keyfile
= NULL
;
510 if ( lo
->ldo_tls_dhfile
) {
511 LDAP_FREE( lo
->ldo_tls_dhfile
);
512 lo
->ldo_tls_dhfile
= NULL
;
514 if ( lo
->ldo_tls_cacertfile
) {
515 LDAP_FREE( lo
->ldo_tls_cacertfile
);
516 lo
->ldo_tls_cacertfile
= NULL
;
518 if ( lo
->ldo_tls_cacertdir
) {
519 LDAP_FREE( lo
->ldo_tls_cacertdir
);
520 lo
->ldo_tls_cacertdir
= NULL
;
522 if ( lo
->ldo_tls_ciphersuite
) {
523 LDAP_FREE( lo
->ldo_tls_ciphersuite
);
524 lo
->ldo_tls_ciphersuite
= NULL
;
527 if ( lo
->ldo_tls_crlfile
) {
528 LDAP_FREE( lo
->ldo_tls_crlfile
);
529 lo
->ldo_tls_crlfile
= NULL
;
535 * Tear down the TLS subsystem. Should only be called once.
538 ldap_pvt_tls_destroy( void )
540 struct ldapoptions
*lo
= LDAP_INT_GLOBAL_OPT();
542 ldap_int_tls_destroy( lo
);
545 LDAP_FREE( ciphers
);
548 gnutls_global_deinit();
554 if ( tls_opt_randfile
) {
555 LDAP_FREE( tls_opt_randfile
);
556 tls_opt_randfile
= NULL
;
562 * Initialize TLS subsystem. Should be called only once.
565 ldap_pvt_tls_init( void )
567 static int tls_initialized
= 0;
569 if ( tls_initialized
++ ) return 0;
571 #ifdef LDAP_R_COMPILE
573 ldap_pvt_thread_mutex_init( &tls_def_ctx_mutex
);
577 gnutls_global_init ();
579 /* GNUtls cipher suite handling: The library ought to parse suite
580 * names for us, but it doesn't. It will return a list of suite names
581 * that it supports, so we can do parsing ourselves. It ought to tell
582 * us how long the list is, but it doesn't do that either, so we just
583 * have to count it manually...
587 tls_cipher_suite
*ptr
, tmp
;
590 while ( gnutls_cipher_suite_info( i
, cs_id
, &tmp
.kx
, &tmp
.cipher
,
591 &tmp
.mac
, &tmp
.version
))
596 ciphers
= LDAP_MALLOC(n_ciphers
* sizeof(tls_cipher_suite
));
599 for ( i
=0; i
<n_ciphers
; i
++ ) {
600 ciphers
[i
].name
= gnutls_cipher_suite_info( i
, cs_id
,
601 &ciphers
[i
].kx
, &ciphers
[i
].cipher
, &ciphers
[i
].mac
,
602 &ciphers
[i
].version
);
606 #else /* !HAVE_GNUTLS */
610 char *file
= LDAP_STRDUP( tls_opt_randfile
);
611 if ( file
) __atoe( file
);
612 (void) tls_seed_PRNG( file
);
616 (void) tls_seed_PRNG( tls_opt_randfile
);
619 SSL_load_error_strings();
620 SSLeay_add_ssl_algorithms();
622 /* FIXME: mod_ssl does this */
623 X509V3_add_standard_extensions();
625 #endif /* HAVE_GNUTLS */
630 * initialize a new TLS context
633 ldap_int_tls_init_ctx( struct ldapoptions
*lo
, int is_server
)
636 char *ciphersuite
= lo
->ldo_tls_ciphersuite
;
637 char *cacertfile
= lo
->ldo_tls_cacertfile
;
638 char *cacertdir
= lo
->ldo_tls_cacertdir
;
639 char *certfile
= lo
->ldo_tls_certfile
;
640 char *keyfile
= lo
->ldo_tls_keyfile
;
642 char *crlfile
= lo
->ldo_tls_crlfile
;
644 char *dhfile
= lo
->ldo_tls_dhfile
;
647 if ( lo
->ldo_tls_ctx
)
652 if ( is_server
&& !certfile
&& !keyfile
&& !cacertfile
&& !cacertdir
) {
653 /* minimum configuration not provided */
654 return LDAP_NOT_SUPPORTED
;
658 /* This ASCII/EBCDIC handling is a real pain! */
660 ciphersuite
= LDAP_STRDUP( ciphersuite
);
661 __atoe( ciphersuite
);
664 cacertfile
= LDAP_STRDUP( cacertfile
);
665 __atoe( cacertfile
);
668 certfile
= LDAP_STRDUP( certfile
);
672 keyfile
= LDAP_STRDUP( keyfile
);
677 crlfile
= LDAP_STRDUP( crlfile
);
682 cacertdir
= LDAP_STRDUP( cacertdir
);
686 dhfile
= LDAP_STRDUP( dhfile
);
691 lo
->ldo_tls_ctx
= tls_ctx_new( lo
);
692 if ( lo
->ldo_tls_ctx
== NULL
) {
694 Debug( LDAP_DEBUG_ANY
,
695 "TLS: could not allocate default ctx.\n",
698 Debug( LDAP_DEBUG_ANY
,
699 "TLS: could not allocate default ctx (%lu).\n",
700 ERR_peek_error(),0,0);
707 if ( lo
->ldo_tls_ciphersuite
&&
708 tls_parse_ciphers( lo
->ldo_tls_ctx
,
710 Debug( LDAP_DEBUG_ANY
,
711 "TLS: could not set cipher list %s.\n",
712 lo
->ldo_tls_ciphersuite
, 0, 0 );
717 if (lo
->ldo_tls_cacertdir
!= NULL
) {
718 Debug( LDAP_DEBUG_ANY
,
719 "TLS: warning: cacertdir not implemented for gnutls\n",
723 if (lo
->ldo_tls_cacertfile
!= NULL
) {
724 rc
= gnutls_certificate_set_x509_trust_file(
725 ((tls_ctx
*) lo
->ldo_tls_ctx
)->cred
,
727 GNUTLS_X509_FMT_PEM
);
728 if ( rc
< 0 ) goto error_exit
;
731 if ( lo
->ldo_tls_certfile
&& lo
->ldo_tls_keyfile
) {
732 rc
= gnutls_certificate_set_x509_key_file(
733 ((tls_ctx
*) lo
->ldo_tls_ctx
)->cred
,
736 GNUTLS_X509_FMT_PEM
);
737 if ( rc
) goto error_exit
;
738 } else if ( lo
->ldo_tls_certfile
|| lo
->ldo_tls_keyfile
) {
739 Debug( LDAP_DEBUG_ANY
,
740 "TLS: only one of certfile and keyfile specified\n",
746 if ( lo
->ldo_tls_dhfile
) {
747 Debug( LDAP_DEBUG_ANY
,
748 "TLS: warning: ignoring dhfile\n",
752 if ( lo
->ldo_tls_crlfile
) {
753 rc
= gnutls_certificate_set_x509_crl_file(
754 ((tls_ctx
*) lo
->ldo_tls_ctx
)->cred
,
756 GNUTLS_X509_FMT_PEM
);
757 if ( rc
< 0 ) goto error_exit
;
761 gnutls_dh_params_init (&((tls_ctx
*)
762 lo
->ldo_tls_ctx
)->dh_params
);
763 gnutls_dh_params_generate2 (((tls_ctx
*)
764 lo
->ldo_tls_ctx
)->dh_params
,
768 #else /* !HAVE_GNUTLS */
771 SSL_CTX_set_session_id_context( lo
->ldo_tls_ctx
,
772 (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
775 if ( lo
->ldo_tls_ciphersuite
&&
776 !SSL_CTX_set_cipher_list( lo
->ldo_tls_ctx
, ciphersuite
) )
778 Debug( LDAP_DEBUG_ANY
,
779 "TLS: could not set cipher list %s.\n",
780 lo
->ldo_tls_ciphersuite
, 0, 0 );
786 if (lo
->ldo_tls_cacertfile
!= NULL
|| lo
->ldo_tls_cacertdir
!= NULL
) {
787 if ( !SSL_CTX_load_verify_locations( lo
->ldo_tls_ctx
,
788 cacertfile
, cacertdir
) ||
789 !SSL_CTX_set_default_verify_paths( lo
->ldo_tls_ctx
) )
791 Debug( LDAP_DEBUG_ANY
, "TLS: "
792 "could not load verify locations (file:`%s',dir:`%s').\n",
793 lo
->ldo_tls_cacertfile
? lo
->ldo_tls_cacertfile
: "",
794 lo
->ldo_tls_cacertdir
? lo
->ldo_tls_cacertdir
: "",
802 STACK_OF(X509_NAME
) *calist
;
803 /* List of CA names to send to a client */
804 calist
= get_ca_list( cacertfile
, cacertdir
);
806 Debug( LDAP_DEBUG_ANY
, "TLS: "
807 "could not load client CA list (file:`%s',dir:`%s').\n",
808 lo
->ldo_tls_cacertfile
? lo
->ldo_tls_cacertfile
: "",
809 lo
->ldo_tls_cacertdir
? lo
->ldo_tls_cacertdir
: "",
816 SSL_CTX_set_client_CA_list( lo
->ldo_tls_ctx
, calist
);
820 if ( lo
->ldo_tls_certfile
&&
821 !SSL_CTX_use_certificate_file( lo
->ldo_tls_ctx
,
822 certfile
, SSL_FILETYPE_PEM
) )
824 Debug( LDAP_DEBUG_ANY
,
825 "TLS: could not use certificate `%s'.\n",
826 lo
->ldo_tls_certfile
,0,0);
832 /* Key validity is checked automatically if cert has already been set */
833 if ( lo
->ldo_tls_keyfile
&&
834 !SSL_CTX_use_PrivateKey_file( lo
->ldo_tls_ctx
,
835 keyfile
, SSL_FILETYPE_PEM
) )
837 Debug( LDAP_DEBUG_ANY
,
838 "TLS: could not use key file `%s'.\n",
839 lo
->ldo_tls_keyfile
,0,0);
845 if ( lo
->ldo_tls_dhfile
) {
850 if (( bio
=BIO_new_file( dhfile
,"r" )) == NULL
) {
851 Debug( LDAP_DEBUG_ANY
,
852 "TLS: could not use DH parameters file `%s'.\n",
853 lo
->ldo_tls_dhfile
,0,0);
858 while (( dh
=PEM_read_bio_DHparams( bio
, NULL
, NULL
, NULL
))) {
859 p
= LDAP_MALLOC( sizeof(dhplist
) );
861 p
->keylength
= DH_size( dh
) * 8;
870 if ( tls_opt_trace
) {
871 SSL_CTX_set_info_callback( (SSL_CTX
*)lo
->ldo_tls_ctx
, tls_info_cb
);
875 if ( lo
->ldo_tls_require_cert
) {
877 if ( lo
->ldo_tls_require_cert
== LDAP_OPT_X_TLS_DEMAND
||
878 lo
->ldo_tls_require_cert
== LDAP_OPT_X_TLS_HARD
) {
879 i
|= SSL_VERIFY_FAIL_IF_NO_PEER_CERT
;
883 SSL_CTX_set_verify( lo
->ldo_tls_ctx
, i
,
884 lo
->ldo_tls_require_cert
== LDAP_OPT_X_TLS_ALLOW
?
885 tls_verify_ok
: tls_verify_cb
);
886 SSL_CTX_set_tmp_rsa_callback( lo
->ldo_tls_ctx
, tls_tmp_rsa_cb
);
887 if ( lo
->ldo_tls_dhfile
) {
888 SSL_CTX_set_tmp_dh_callback( lo
->ldo_tls_ctx
, tls_tmp_dh_cb
);
890 #ifdef HAVE_OPENSSL_CRL
891 if ( lo
->ldo_tls_crlcheck
) {
892 X509_STORE
*x509_s
= SSL_CTX_get_cert_store( lo
->ldo_tls_ctx
);
893 if ( lo
->ldo_tls_crlcheck
== LDAP_OPT_X_TLS_CRL_PEER
) {
894 X509_STORE_set_flags( x509_s
, X509_V_FLAG_CRL_CHECK
);
895 } else if ( lo
->ldo_tls_crlcheck
== LDAP_OPT_X_TLS_CRL_ALL
) {
896 X509_STORE_set_flags( x509_s
,
897 X509_V_FLAG_CRL_CHECK
| X509_V_FLAG_CRL_CHECK_ALL
);
902 #endif /* HAVE_GNUTLS */
905 if ( rc
== -1 && lo
->ldo_tls_ctx
!= NULL
) {
906 ldap_pvt_tls_ctx_free( lo
->ldo_tls_ctx
);
907 lo
->ldo_tls_ctx
= NULL
;
910 LDAP_FREE( ciphersuite
);
911 LDAP_FREE( cacertfile
);
912 LDAP_FREE( certfile
);
913 LDAP_FREE( keyfile
);
915 LDAP_FREE( crlfile
);
917 LDAP_FREE( cacertdir
);
925 * initialize the default context
928 ldap_pvt_tls_init_def_ctx( int is_server
)
930 struct ldapoptions
*lo
= LDAP_INT_GLOBAL_OPT();
932 #ifdef LDAP_R_COMPILE
933 ldap_pvt_thread_mutex_lock( &tls_def_ctx_mutex
);
935 rc
= ldap_int_tls_init_ctx( lo
, is_server
);
936 #ifdef LDAP_R_COMPILE
937 ldap_pvt_thread_mutex_unlock( &tls_def_ctx_mutex
);
943 alloc_handle( void *ctx_arg
, int is_server
)
951 struct ldapoptions
*lo
= LDAP_INT_GLOBAL_OPT();
952 if ( ldap_pvt_tls_init_def_ctx( is_server
) < 0 ) return NULL
;
953 ctx
= lo
->ldo_tls_ctx
;
956 ssl
= tls_session_new( ctx
, is_server
);
958 Debug( LDAP_DEBUG_ANY
,"TLS: can't create ssl handle.\n",0,0,0);
965 update_flags( Sockbuf
*sb
, tls_session
* ssl
, int rc
)
967 sb
->sb_trans_needs_read
= 0;
968 sb
->sb_trans_needs_write
= 0;
971 if ( rc
!= GNUTLS_E_INTERRUPTED
&& rc
!= GNUTLS_E_AGAIN
)
974 switch (gnutls_record_get_direction (ssl
->session
)) {
976 sb
->sb_trans_needs_read
= 1;
979 sb
->sb_trans_needs_write
= 1;
982 #else /* !HAVE_GNUTLS */
983 rc
= SSL_get_error(ssl
, rc
);
984 if (rc
== SSL_ERROR_WANT_READ
) {
985 sb
->sb_trans_needs_read
= 1;
988 } else if (rc
== SSL_ERROR_WANT_WRITE
) {
989 sb
->sb_trans_needs_write
= 1;
992 } else if (rc
== SSL_ERROR_WANT_CONNECT
) {
995 #endif /* HAVE_GNUTLS */
1000 * TLS support for LBER Sockbufs
1005 Sockbuf_IO_Desc
*sbiod
;
1011 sb_gtls_recv( gnutls_transport_ptr_t ptr
, void *buf
, size_t len
)
1015 if ( buf
== NULL
|| len
<= 0 ) return 0;
1017 p
= (struct tls_data
*)ptr
;
1019 if ( p
== NULL
|| p
->sbiod
== NULL
) {
1023 return LBER_SBIOD_READ_NEXT( p
->sbiod
, buf
, len
);
1027 sb_gtls_send( gnutls_transport_ptr_t ptr
, const void *buf
, size_t len
)
1031 if ( buf
== NULL
|| len
<= 0 ) return 0;
1033 p
= (struct tls_data
*)ptr
;
1035 if ( p
== NULL
|| p
->sbiod
== NULL
) {
1039 return LBER_SBIOD_WRITE_NEXT( p
->sbiod
, (char *)buf
, len
);
1043 sb_tls_setup( Sockbuf_IO_Desc
*sbiod
, void *arg
)
1046 tls_session
*session
= arg
;
1048 assert( sbiod
!= NULL
);
1050 p
= LBER_MALLOC( sizeof( *p
) );
1055 gnutls_transport_set_ptr( session
->session
, (gnutls_transport_ptr
)p
);
1056 gnutls_transport_set_pull_function( session
->session
, sb_gtls_recv
);
1057 gnutls_transport_set_push_function( session
->session
, sb_gtls_send
);
1060 sbiod
->sbiod_pvt
= p
;
1065 sb_tls_remove( Sockbuf_IO_Desc
*sbiod
)
1069 assert( sbiod
!= NULL
);
1070 assert( sbiod
->sbiod_pvt
!= NULL
);
1072 p
= (struct tls_data
*)sbiod
->sbiod_pvt
;
1073 gnutls_deinit ( p
->ssl
->session
);
1074 LBER_FREE( p
->ssl
);
1075 LBER_FREE( sbiod
->sbiod_pvt
);
1076 sbiod
->sbiod_pvt
= NULL
;
1081 sb_tls_close( Sockbuf_IO_Desc
*sbiod
)
1085 assert( sbiod
!= NULL
);
1086 assert( sbiod
->sbiod_pvt
!= NULL
);
1088 p
= (struct tls_data
*)sbiod
->sbiod_pvt
;
1089 gnutls_bye ( p
->ssl
->session
, GNUTLS_SHUT_RDWR
);
1094 sb_tls_ctrl( Sockbuf_IO_Desc
*sbiod
, int opt
, void *arg
)
1098 assert( sbiod
!= NULL
);
1099 assert( sbiod
->sbiod_pvt
!= NULL
);
1101 p
= (struct tls_data
*)sbiod
->sbiod_pvt
;
1103 if ( opt
== LBER_SB_OPT_GET_SSL
) {
1104 *((tls_session
**)arg
) = p
->ssl
;
1107 } else if ( opt
== LBER_SB_OPT_DATA_READY
) {
1108 if( gnutls_record_check_pending( p
->ssl
->session
) > 0 ) {
1113 return LBER_SBIOD_CTRL_NEXT( sbiod
, opt
, arg
);
1117 sb_tls_read( Sockbuf_IO_Desc
*sbiod
, void *buf
, ber_len_t len
)
1123 assert( sbiod
!= NULL
);
1124 assert( SOCKBUF_VALID( sbiod
->sbiod_sb
) );
1126 p
= (struct tls_data
*)sbiod
->sbiod_pvt
;
1128 ret
= gnutls_record_recv ( p
->ssl
->session
, buf
, len
);
1130 case GNUTLS_E_INTERRUPTED
:
1131 case GNUTLS_E_AGAIN
:
1132 sbiod
->sbiod_sb
->sb_trans_needs_read
= 1;
1133 sock_errset(EWOULDBLOCK
);
1136 case GNUTLS_E_REHANDSHAKE
:
1137 for ( ret
= gnutls_handshake ( p
->ssl
->session
);
1138 ret
== GNUTLS_E_INTERRUPTED
|| ret
== GNUTLS_E_AGAIN
;
1139 ret
= gnutls_handshake ( p
->ssl
->session
) );
1140 sbiod
->sbiod_sb
->sb_trans_needs_read
= 1;
1144 sbiod
->sbiod_sb
->sb_trans_needs_read
= 0;
1150 sb_tls_write( Sockbuf_IO_Desc
*sbiod
, void *buf
, ber_len_t len
)
1156 assert( sbiod
!= NULL
);
1157 assert( SOCKBUF_VALID( sbiod
->sbiod_sb
) );
1159 p
= (struct tls_data
*)sbiod
->sbiod_pvt
;
1161 ret
= gnutls_record_send ( p
->ssl
->session
, (char *)buf
, len
);
1163 if ( ret
== GNUTLS_E_INTERRUPTED
|| ret
== GNUTLS_E_AGAIN
) {
1164 sbiod
->sbiod_sb
->sb_trans_needs_write
= 1;
1165 sock_errset(EWOULDBLOCK
);
1168 sbiod
->sbiod_sb
->sb_trans_needs_write
= 0;
1173 #else /* !HAVE_GNUTLS */
1176 sb_tls_bio_create( BIO
*b
) {
1185 sb_tls_bio_destroy( BIO
*b
)
1187 if ( b
== NULL
) return 0;
1189 b
->ptr
= NULL
; /* sb_tls_remove() will free it */
1196 sb_tls_bio_read( BIO
*b
, char *buf
, int len
)
1201 if ( buf
== NULL
|| len
<= 0 ) return 0;
1203 p
= (struct tls_data
*)b
->ptr
;
1205 if ( p
== NULL
|| p
->sbiod
== NULL
) {
1209 ret
= LBER_SBIOD_READ_NEXT( p
->sbiod
, buf
, len
);
1211 BIO_clear_retry_flags( b
);
1213 int err
= sock_errno();
1214 if ( err
== EAGAIN
|| err
== EWOULDBLOCK
) {
1215 BIO_set_retry_read( b
);
1223 sb_tls_bio_write( BIO
*b
, const char *buf
, int len
)
1228 if ( buf
== NULL
|| len
<= 0 ) return 0;
1230 p
= (struct tls_data
*)b
->ptr
;
1232 if ( p
== NULL
|| p
->sbiod
== NULL
) {
1236 ret
= LBER_SBIOD_WRITE_NEXT( p
->sbiod
, (char *)buf
, len
);
1238 BIO_clear_retry_flags( b
);
1240 int err
= sock_errno();
1241 if ( err
== EAGAIN
|| err
== EWOULDBLOCK
) {
1242 BIO_set_retry_write( b
);
1250 sb_tls_bio_ctrl( BIO
*b
, int cmd
, long num
, void *ptr
)
1252 if ( cmd
== BIO_CTRL_FLUSH
) {
1253 /* The OpenSSL library needs this */
1260 sb_tls_bio_gets( BIO
*b
, char *buf
, int len
)
1266 sb_tls_bio_puts( BIO
*b
, const char *str
)
1268 return sb_tls_bio_write( b
, str
, strlen( str
) );
1271 static BIO_METHOD sb_tls_bio_method
=
1273 ( 100 | 0x400 ), /* it's a source/sink BIO */
1285 sb_tls_setup( Sockbuf_IO_Desc
*sbiod
, void *arg
)
1290 assert( sbiod
!= NULL
);
1292 p
= LBER_MALLOC( sizeof( *p
) );
1297 p
->ssl
= (SSL
*)arg
;
1299 bio
= BIO_new( &sb_tls_bio_method
);
1300 bio
->ptr
= (void *)p
;
1301 SSL_set_bio( p
->ssl
, bio
, bio
);
1302 sbiod
->sbiod_pvt
= p
;
1307 sb_tls_remove( Sockbuf_IO_Desc
*sbiod
)
1311 assert( sbiod
!= NULL
);
1312 assert( sbiod
->sbiod_pvt
!= NULL
);
1314 p
= (struct tls_data
*)sbiod
->sbiod_pvt
;
1316 LBER_FREE( sbiod
->sbiod_pvt
);
1317 sbiod
->sbiod_pvt
= NULL
;
1322 sb_tls_close( Sockbuf_IO_Desc
*sbiod
)
1326 assert( sbiod
!= NULL
);
1327 assert( sbiod
->sbiod_pvt
!= NULL
);
1329 p
= (struct tls_data
*)sbiod
->sbiod_pvt
;
1330 SSL_shutdown( p
->ssl
);
1335 sb_tls_ctrl( Sockbuf_IO_Desc
*sbiod
, int opt
, void *arg
)
1339 assert( sbiod
!= NULL
);
1340 assert( sbiod
->sbiod_pvt
!= NULL
);
1342 p
= (struct tls_data
*)sbiod
->sbiod_pvt
;
1344 if ( opt
== LBER_SB_OPT_GET_SSL
) {
1345 *((SSL
**)arg
) = p
->ssl
;
1348 } else if ( opt
== LBER_SB_OPT_DATA_READY
) {
1349 if( SSL_pending( p
->ssl
) > 0 ) {
1354 return LBER_SBIOD_CTRL_NEXT( sbiod
, opt
, arg
);
1358 sb_tls_read( Sockbuf_IO_Desc
*sbiod
, void *buf
, ber_len_t len
)
1364 assert( sbiod
!= NULL
);
1365 assert( SOCKBUF_VALID( sbiod
->sbiod_sb
) );
1367 p
= (struct tls_data
*)sbiod
->sbiod_pvt
;
1369 ret
= SSL_read( p
->ssl
, (char *)buf
, len
);
1371 errno
= WSAGetLastError();
1373 err
= SSL_get_error( p
->ssl
, ret
);
1374 if (err
== SSL_ERROR_WANT_READ
) {
1375 sbiod
->sbiod_sb
->sb_trans_needs_read
= 1;
1376 sock_errset(EWOULDBLOCK
);
1379 sbiod
->sbiod_sb
->sb_trans_needs_read
= 0;
1384 sb_tls_write( Sockbuf_IO_Desc
*sbiod
, void *buf
, ber_len_t len
)
1390 assert( sbiod
!= NULL
);
1391 assert( SOCKBUF_VALID( sbiod
->sbiod_sb
) );
1393 p
= (struct tls_data
*)sbiod
->sbiod_pvt
;
1395 ret
= SSL_write( p
->ssl
, (char *)buf
, len
);
1397 errno
= WSAGetLastError();
1399 err
= SSL_get_error( p
->ssl
, ret
);
1400 if (err
== SSL_ERROR_WANT_WRITE
) {
1401 sbiod
->sbiod_sb
->sb_trans_needs_write
= 1;
1402 sock_errset(EWOULDBLOCK
);
1405 sbiod
->sbiod_sb
->sb_trans_needs_write
= 0;
1412 static Sockbuf_IO sb_tls_sbio
=
1414 sb_tls_setup
, /* sbi_setup */
1415 sb_tls_remove
, /* sbi_remove */
1416 sb_tls_ctrl
, /* sbi_ctrl */
1417 sb_tls_read
, /* sbi_read */
1418 sb_tls_write
, /* sbi_write */
1419 sb_tls_close
/* sbi_close */
1423 /* Certs are not automatically varified during the handshake */
1425 tls_cert_verify( tls_session
*ssl
)
1427 unsigned int status
= 0;
1429 time_t now
= time(0);
1431 err
= gnutls_certificate_verify_peers2( ssl
->session
, &status
);
1433 Debug( LDAP_DEBUG_ANY
,"TLS: gnutls_certificate_verify_peers2 failed %d\n",
1438 Debug( LDAP_DEBUG_TRACE
,"TLS: peer cert untrusted or revoked (0x%x)\n",
1442 if ( gnutls_certificate_expiration_time_peers( ssl
->session
) < now
) {
1443 Debug( LDAP_DEBUG_ANY
, "TLS: peer certificate is expired\n",
1447 if ( gnutls_certificate_activation_time_peers( ssl
->session
) > now
) {
1448 Debug( LDAP_DEBUG_ANY
, "TLS: peer certificate not yet active\n",
1454 #endif /* HAVE_GNUTLS */
1457 * Call this to do a TLS connect on a sockbuf. ctx_arg can be
1458 * a SSL_CTX * or NULL, in which case the default ctx is used.
1462 * 0 - Success. Connection is ready for communication.
1463 * <0 - Error. Can't create a TLS stream.
1464 * >0 - Partial success.
1465 * Do a select (using information from lber_pvt_sb_needs_{read,write}
1470 ldap_int_tls_connect( LDAP
*ld
, LDAPConn
*conn
)
1472 Sockbuf
*sb
= conn
->lconn_sb
;
1476 if ( HAS_TLS( sb
) ) {
1477 ber_sockbuf_ctrl( sb
, LBER_SB_OPT_GET_SSL
, (void *)&ssl
);
1480 struct ldapoptions
*lo
;
1483 ctx
= ld
->ld_options
.ldo_tls_ctx
;
1485 ssl
= alloc_handle( ctx
, 0 );
1487 if ( ssl
== NULL
) return -1;
1490 ber_sockbuf_add_io( sb
, &ber_sockbuf_io_debug
,
1491 LBER_SBIOD_LEVEL_TRANSPORT
, (void *)"tls_" );
1493 ber_sockbuf_add_io( sb
, &sb_tls_sbio
,
1494 LBER_SBIOD_LEVEL_TRANSPORT
, (void *)ssl
);
1496 lo
= LDAP_INT_GLOBAL_OPT();
1498 ctx
= lo
->ldo_tls_ctx
;
1499 ld
->ld_options
.ldo_tls_ctx
= ctx
;
1502 if ( ld
->ld_options
.ldo_tls_connect_cb
)
1503 ld
->ld_options
.ldo_tls_connect_cb( ld
, ssl
, ctx
,
1504 ld
->ld_options
.ldo_tls_connect_arg
);
1505 if ( lo
&& lo
->ldo_tls_connect_cb
&& lo
->ldo_tls_connect_cb
!=
1506 ld
->ld_options
.ldo_tls_connect_cb
)
1507 lo
->ldo_tls_connect_cb( ld
, ssl
, ctx
, lo
->ldo_tls_connect_arg
);
1510 err
= tls_session_connect( ssl
);
1513 errno
= WSAGetLastError();
1522 if ( update_flags( sb
, ssl
, err
)) {
1527 if ((err
= ERR_peek_error()))
1530 if ( ld
->ld_error
) {
1531 LDAP_FREE( ld
->ld_error
);
1534 ld
->ld_error
= LDAP_STRDUP(gnutls_strerror( err
));
1538 ld
->ld_error
= LDAP_STRDUP(ERR_error_string(err
, buf
));
1542 if ( ld
->ld_error
) __etoa(ld
->ld_error
);
1546 Debug( LDAP_DEBUG_ANY
,"TLS: can't connect: %s.\n",
1547 ld
->ld_error
? ld
->ld_error
: "" ,0,0);
1549 ber_sockbuf_remove_io( sb
, &sb_tls_sbio
,
1550 LBER_SBIOD_LEVEL_TRANSPORT
);
1552 ber_sockbuf_remove_io( sb
, &ber_sockbuf_io_debug
,
1553 LBER_SBIOD_LEVEL_TRANSPORT
);
1559 if ( ld
->ld_options
.ldo_tls_require_cert
!= LDAP_OPT_X_TLS_NEVER
) {
1560 err
= tls_cert_verify( ssl
);
1561 if ( err
&& ld
->ld_options
.ldo_tls_require_cert
!= LDAP_OPT_X_TLS_ALLOW
)
1570 * Call this to do a TLS accept on a sockbuf.
1571 * Everything else is the same as with tls_connect.
1574 ldap_pvt_tls_accept( Sockbuf
*sb
, void *ctx_arg
)
1579 if ( HAS_TLS( sb
) ) {
1580 ber_sockbuf_ctrl( sb
, LBER_SB_OPT_GET_SSL
, (void *)&ssl
);
1583 ssl
= alloc_handle( ctx_arg
, 1 );
1584 if ( ssl
== NULL
) return -1;
1587 ber_sockbuf_add_io( sb
, &ber_sockbuf_io_debug
,
1588 LBER_SBIOD_LEVEL_TRANSPORT
, (void *)"tls_" );
1590 ber_sockbuf_add_io( sb
, &sb_tls_sbio
,
1591 LBER_SBIOD_LEVEL_TRANSPORT
, (void *)ssl
);
1594 err
= tls_session_accept( ssl
);
1597 errno
= WSAGetLastError();
1606 if ( update_flags( sb
, ssl
, err
)) return 1;
1609 Debug( LDAP_DEBUG_ANY
,"TLS: can't accept: %s.\n",
1610 gnutls_strerror( err
),0,0 );
1612 Debug( LDAP_DEBUG_ANY
,"TLS: can't accept.\n",0,0,0 );
1615 ber_sockbuf_remove_io( sb
, &sb_tls_sbio
,
1616 LBER_SBIOD_LEVEL_TRANSPORT
);
1618 ber_sockbuf_remove_io( sb
, &ber_sockbuf_io_debug
,
1619 LBER_SBIOD_LEVEL_TRANSPORT
);
1625 if ( ssl
->ctx
->lo
->ldo_tls_require_cert
!= LDAP_OPT_X_TLS_NEVER
) {
1626 err
= tls_cert_verify( ssl
);
1627 if ( err
&& ssl
->ctx
->lo
->ldo_tls_require_cert
!= LDAP_OPT_X_TLS_ALLOW
)
1635 ldap_pvt_tls_inplace ( Sockbuf
*sb
)
1637 return HAS_TLS( sb
) ? 1 : 0;
1641 ldap_tls_inplace( LDAP
*ld
)
1645 if ( ld
->ld_defconn
&& ld
->ld_defconn
->lconn_sb
) {
1646 sb
= ld
->ld_defconn
->lconn_sb
;
1648 } else if ( ld
->ld_sb
) {
1655 return ldap_pvt_tls_inplace( sb
);
1660 x509_cert_get_dn( struct berval
*cert
, struct berval
*dn
, int get_subject
)
1662 BerElementBuffer berbuf
;
1663 BerElement
*ber
= (BerElement
*)&berbuf
;
1668 ber_init2( ber
, cert
, LBER_USE_DER
);
1669 tag
= ber_skip_tag( ber
, &len
); /* Sequence */
1670 tag
= ber_skip_tag( ber
, &len
); /* Sequence */
1671 tag
= ber_skip_tag( ber
, &len
); /* Context + Constructed (version) */
1672 if ( tag
== 0xa0 ) /* Version is optional */
1673 tag
= ber_get_int( ber
, &i
); /* Int: Version */
1674 tag
= ber_get_int( ber
, &i
); /* Int: Serial */
1675 tag
= ber_skip_tag( ber
, &len
); /* Sequence: Signature */
1676 ber_skip_data( ber
, len
);
1677 if ( !get_subject
) {
1678 tag
= ber_peek_tag( ber
, &len
); /* Sequence: Issuer DN */
1680 tag
= ber_skip_tag( ber
, &len
);
1681 ber_skip_data( ber
, len
);
1682 tag
= ber_skip_tag( ber
, &len
); /* Sequence: Validity */
1683 ber_skip_data( ber
, len
);
1684 tag
= ber_peek_tag( ber
, &len
); /* Sequence: Subject DN */
1686 len
= ber_ptrlen( ber
);
1687 dn
->bv_val
= cert
->bv_val
+ len
;
1688 dn
->bv_len
= cert
->bv_len
- len
;
1692 tls_get_cert_dn( tls_session
*session
, struct berval
*dnbv
)
1694 if ( !session
->peer_der_dn
.bv_val
) {
1695 const gnutls_datum_t
*peer_cert_list
;
1699 peer_cert_list
= gnutls_certificate_get_peers( session
->session
,
1701 if ( !peer_cert_list
) return LDAP_INVALID_CREDENTIALS
;
1703 bv
.bv_len
= peer_cert_list
->size
;
1704 bv
.bv_val
= peer_cert_list
->data
;
1706 x509_cert_get_dn( &bv
, &session
->peer_der_dn
, 1 );
1707 *dnbv
= session
->peer_der_dn
;
1711 #else /* !HAVE_GNUTLS */
1713 tls_get_cert( SSL
*s
)
1715 /* If peer cert was bad, treat as if no cert was given */
1716 if (SSL_get_verify_result(s
)) {
1717 /* If we can send an alert, do so */
1718 if (SSL_version(s
) != SSL2_VERSION
) {
1719 ssl3_send_alert(s
,SSL3_AL_WARNING
,SSL3_AD_BAD_CERTIFICATE
);
1723 return SSL_get_peer_certificate(s
);
1727 tls_get_cert_dn( tls_session
*session
, struct berval
*dnbv
)
1730 X509
*x
= tls_get_cert( session
);
1733 return LDAP_INVALID_CREDENTIALS
;
1735 xn
= X509_get_subject_name(x
);
1736 dnbv
->bv_len
= i2d_X509_NAME( xn
, NULL
);
1737 dnbv
->bv_val
= xn
->bytes
->data
;
1740 #endif /* HAVE_GNUTLS */
1743 ldap_pvt_tls_get_peer_dn( void *s
, struct berval
*dn
,
1744 LDAPDN_rewrite_dummy
*func
, unsigned flags
)
1746 tls_session
*session
= s
;
1750 rc
= tls_get_cert_dn( session
, &bvdn
);
1751 if ( rc
) return rc
;
1753 rc
= ldap_X509dn2bv( &bvdn
, dn
,
1754 (LDAPDN_rewrite_func
*)func
, flags
);
1758 /* what kind of hostname were we given? */
1766 ldap_pvt_tls_check_hostname( LDAP
*ld
, void *s
, const char *name_in
)
1768 tls_session
*session
= s
;
1770 const gnutls_datum_t
*peer_cert_list
;
1773 char altname
[NI_MAXHOST
];
1776 gnutls_x509_crt_t cert
;
1780 char *domain
= NULL
;
1781 #ifdef LDAP_PF_INET6
1782 struct in6_addr addr
;
1784 struct in_addr addr
;
1786 int n
, len1
= 0, len2
= 0;
1788 time_t now
= time(0);
1790 if( ldap_int_hostname
&&
1791 ( !name_in
|| !strcasecmp( name_in
, "localhost" ) ) )
1793 name
= ldap_int_hostname
;
1798 peer_cert_list
= gnutls_certificate_get_peers( session
->session
,
1800 if ( !peer_cert_list
) {
1801 Debug( LDAP_DEBUG_ANY
,
1802 "TLS: unable to get peer certificate.\n",
1804 /* If this was a fatal condition, things would have
1805 * aborted long before now.
1807 return LDAP_SUCCESS
;
1809 ret
= gnutls_x509_crt_init( &cert
);
1811 return LDAP_LOCAL_ERROR
;
1812 ret
= gnutls_x509_crt_import( cert
, peer_cert_list
, GNUTLS_X509_FMT_DER
);
1814 gnutls_x509_crt_deinit( cert
);
1815 return LDAP_LOCAL_ERROR
;
1818 #ifdef LDAP_PF_INET6
1819 if (name
[0] == '[' && strchr(name
, ']')) {
1820 char *n2
= ldap_strdup(name
+1);
1821 *strchr(n2
, ']') = 2;
1822 if (inet_pton(AF_INET6
, n2
, &addr
))
1827 if ((ptr
= strrchr(name
, '.')) && isdigit((unsigned char)ptr
[1])) {
1828 if (inet_aton(name
, (struct in_addr
*)&addr
)) ntype
= IS_IP4
;
1831 if (ntype
== IS_DNS
) {
1832 len1
= strlen(name
);
1833 domain
= strchr(name
, '.');
1835 len2
= len1
- (domain
-name
);
1839 for ( i
=0, ret
=0; ret
>= 0; i
++ ) {
1840 altnamesize
= sizeof(altname
);
1841 ret
= gnutls_x509_crt_get_subject_alt_name( cert
, i
,
1842 altname
, &altnamesize
, NULL
);
1843 if ( ret
< 0 ) break;
1846 if ( altnamesize
== 0 ) continue;
1848 if ( ret
== GNUTLS_SAN_DNSNAME
) {
1849 if (ntype
!= IS_DNS
) continue;
1851 /* Is this an exact match? */
1852 if ((len1
== altnamesize
) && !strncasecmp(name
, altname
, len1
)) {
1856 /* Is this a wildcard match? */
1857 if (domain
&& (altname
[0] == '*') && (altname
[1] == '.') &&
1858 (len2
== altnamesize
-1) && !strncasecmp(domain
, &altname
[1], len2
))
1862 } else if ( ret
== GNUTLS_SAN_IPADDRESS
) {
1863 if (ntype
== IS_DNS
) continue;
1865 #ifdef LDAP_PF_INET6
1866 if (ntype
== IS_IP6
&& altnamesize
!= sizeof(struct in6_addr
)) {
1870 if (ntype
== IS_IP4
&& altnamesize
!= sizeof(struct in_addr
)) {
1873 if (!memcmp(altname
, &addr
, altnamesize
)) {
1881 altnamesize
= sizeof(altname
);
1882 ret
= gnutls_x509_crt_get_dn_by_oid( cert
, CN_OID
,
1883 0, 0, altname
, &altnamesize
);
1885 Debug( LDAP_DEBUG_ANY
,
1886 "TLS: unable to get common name from peer certificate.\n",
1888 ret
= LDAP_CONNECT_ERROR
;
1889 if ( ld
->ld_error
) {
1890 LDAP_FREE( ld
->ld_error
);
1892 ld
->ld_error
= LDAP_STRDUP(
1893 _("TLS: unable to get CN from peer certificate"));
1896 ret
= LDAP_LOCAL_ERROR
;
1897 if ( len1
== altnamesize
&& strncasecmp(name
, altname
, altnamesize
) == 0 ) {
1900 } else if (( altname
[0] == '*' ) && ( altname
[1] == '.' )) {
1901 /* Is this a wildcard match? */
1903 (len2
== altnamesize
-1) && !strncasecmp(domain
, &altname
[1], len2
)) {
1909 if( ret
== LDAP_LOCAL_ERROR
) {
1910 altname
[altnamesize
] = '\0';
1911 Debug( LDAP_DEBUG_ANY
, "TLS: hostname (%s) does not match "
1912 "common name in certificate (%s).\n",
1914 ret
= LDAP_CONNECT_ERROR
;
1915 if ( ld
->ld_error
) {
1916 LDAP_FREE( ld
->ld_error
);
1918 ld
->ld_error
= LDAP_STRDUP(
1919 _("TLS: hostname does not match CN in peer certificate"));
1922 gnutls_x509_crt_deinit( cert
);
1926 #else /* !HAVE_GNUTLS */
1929 ldap_pvt_tls_check_hostname( LDAP
*ld
, void *s
, const char *name_in
)
1931 int i
, ret
= LDAP_LOCAL_ERROR
;
1936 #ifdef LDAP_PF_INET6
1937 struct in6_addr addr
;
1939 struct in_addr addr
;
1942 if( ldap_int_hostname
&&
1943 ( !name_in
|| !strcasecmp( name_in
, "localhost" ) ) )
1945 name
= ldap_int_hostname
;
1950 x
= tls_get_cert((SSL
*)s
);
1952 Debug( LDAP_DEBUG_ANY
,
1953 "TLS: unable to get peer certificate.\n",
1955 /* If this was a fatal condition, things would have
1956 * aborted long before now.
1958 return LDAP_SUCCESS
;
1961 #ifdef LDAP_PF_INET6
1962 if (name
[0] == '[' && strchr(name
, ']')) {
1963 char *n2
= ldap_strdup(name
+1);
1964 *strchr(n2
, ']') = 2;
1965 if (inet_pton(AF_INET6
, n2
, &addr
))
1970 if ((ptr
= strrchr(name
, '.')) && isdigit((unsigned char)ptr
[1])) {
1971 if (inet_aton(name
, (struct in_addr
*)&addr
)) ntype
= IS_IP4
;
1974 i
= X509_get_ext_by_NID(x
, NID_subject_alt_name
, -1);
1977 STACK_OF(GENERAL_NAME
) *alt
;
1979 ex
= X509_get_ext(x
, i
);
1980 alt
= X509V3_EXT_d2i(ex
);
1982 int n
, len1
= 0, len2
= 0;
1983 char *domain
= NULL
;
1986 if (ntype
== IS_DNS
) {
1987 len1
= strlen(name
);
1988 domain
= strchr(name
, '.');
1990 len2
= len1
- (domain
-name
);
1993 n
= sk_GENERAL_NAME_num(alt
);
1994 for (i
=0; i
<n
; i
++) {
1997 gn
= sk_GENERAL_NAME_value(alt
, i
);
1998 if (gn
->type
== GEN_DNS
) {
1999 if (ntype
!= IS_DNS
) continue;
2001 sn
= (char *) ASN1_STRING_data(gn
->d
.ia5
);
2002 sl
= ASN1_STRING_length(gn
->d
.ia5
);
2005 if (sl
== 0) continue;
2007 /* Is this an exact match? */
2008 if ((len1
== sl
) && !strncasecmp(name
, sn
, len1
)) {
2012 /* Is this a wildcard match? */
2013 if (domain
&& (sn
[0] == '*') && (sn
[1] == '.') &&
2014 (len2
== sl
-1) && !strncasecmp(domain
, &sn
[1], len2
))
2019 } else if (gn
->type
== GEN_IPADD
) {
2020 if (ntype
== IS_DNS
) continue;
2022 sn
= (char *) ASN1_STRING_data(gn
->d
.ia5
);
2023 sl
= ASN1_STRING_length(gn
->d
.ia5
);
2025 #ifdef LDAP_PF_INET6
2026 if (ntype
== IS_IP6
&& sl
!= sizeof(struct in6_addr
)) {
2030 if (ntype
== IS_IP4
&& sl
!= sizeof(struct in_addr
)) {
2033 if (!memcmp(sn
, &addr
, sl
)) {
2039 GENERAL_NAMES_free(alt
);
2040 if (i
< n
) { /* Found a match */
2046 if (ret
!= LDAP_SUCCESS
) {
2051 xn
= X509_get_subject_name(x
);
2052 if( X509_NAME_get_text_by_NID( xn
, NID_commonName
,
2053 buf
, sizeof(buf
)) == -1)
2055 Debug( LDAP_DEBUG_ANY
,
2056 "TLS: unable to get common name from peer certificate.\n",
2058 ret
= LDAP_CONNECT_ERROR
;
2059 if ( ld
->ld_error
) {
2060 LDAP_FREE( ld
->ld_error
);
2062 ld
->ld_error
= LDAP_STRDUP(
2063 _("TLS: unable to get CN from peer certificate"));
2065 } else if (strcasecmp(name
, buf
) == 0 ) {
2068 } else if (( buf
[0] == '*' ) && ( buf
[1] == '.' )) {
2069 char *domain
= strchr(name
, '.');
2075 dlen
= sl
- (domain
-name
);
2078 /* Is this a wildcard match? */
2079 if ((dlen
== sl
-1) && !strncasecmp(domain
, &buf
[1], dlen
)) {
2085 if( ret
== LDAP_LOCAL_ERROR
) {
2086 Debug( LDAP_DEBUG_ANY
, "TLS: hostname (%s) does not match "
2087 "common name in certificate (%s).\n",
2089 ret
= LDAP_CONNECT_ERROR
;
2090 if ( ld
->ld_error
) {
2091 LDAP_FREE( ld
->ld_error
);
2093 ld
->ld_error
= LDAP_STRDUP(
2094 _("TLS: hostname does not match CN in peer certificate"));
2103 ldap_int_tls_config( LDAP
*ld
, int option
, const char *arg
)
2108 case LDAP_OPT_X_TLS_CACERTFILE
:
2109 case LDAP_OPT_X_TLS_CACERTDIR
:
2110 case LDAP_OPT_X_TLS_CERTFILE
:
2111 case LDAP_OPT_X_TLS_KEYFILE
:
2112 case LDAP_OPT_X_TLS_RANDOM_FILE
:
2113 case LDAP_OPT_X_TLS_CIPHER_SUITE
:
2114 case LDAP_OPT_X_TLS_DHFILE
:
2116 case LDAP_OPT_X_TLS_CRLFILE
:
2118 return ldap_pvt_tls_set_option( ld
, option
, (void *) arg
);
2120 case LDAP_OPT_X_TLS_REQUIRE_CERT
:
2121 case LDAP_OPT_X_TLS
:
2123 if ( strcasecmp( arg
, "never" ) == 0 ) {
2124 i
= LDAP_OPT_X_TLS_NEVER
;
2126 } else if ( strcasecmp( arg
, "demand" ) == 0 ) {
2127 i
= LDAP_OPT_X_TLS_DEMAND
;
2129 } else if ( strcasecmp( arg
, "allow" ) == 0 ) {
2130 i
= LDAP_OPT_X_TLS_ALLOW
;
2132 } else if ( strcasecmp( arg
, "try" ) == 0 ) {
2133 i
= LDAP_OPT_X_TLS_TRY
;
2135 } else if ( ( strcasecmp( arg
, "hard" ) == 0 ) ||
2136 ( strcasecmp( arg
, "on" ) == 0 ) ||
2137 ( strcasecmp( arg
, "yes" ) == 0) ||
2138 ( strcasecmp( arg
, "true" ) == 0 ) )
2140 i
= LDAP_OPT_X_TLS_HARD
;
2144 return ldap_pvt_tls_set_option( ld
, option
, &i
);
2147 #ifdef HAVE_OPENSSL_CRL
2148 case LDAP_OPT_X_TLS_CRLCHECK
:
2150 if ( strcasecmp( arg
, "none" ) == 0 ) {
2151 i
= LDAP_OPT_X_TLS_CRL_NONE
;
2152 } else if ( strcasecmp( arg
, "peer" ) == 0 ) {
2153 i
= LDAP_OPT_X_TLS_CRL_PEER
;
2154 } else if ( strcasecmp( arg
, "all" ) == 0 ) {
2155 i
= LDAP_OPT_X_TLS_CRL_ALL
;
2158 return ldap_pvt_tls_set_option( ld
, option
, &i
);
2167 ldap_pvt_tls_get_option( LDAP
*ld
, int option
, void *arg
)
2169 struct ldapoptions
*lo
;
2172 assert( LDAP_VALID( ld
) );
2174 if( !LDAP_VALID( ld
) ) {
2175 return LDAP_OPT_ERROR
;
2178 lo
= &ld
->ld_options
;
2181 /* Get pointer to global option structure */
2182 lo
= LDAP_INT_GLOBAL_OPT();
2184 return LDAP_NO_MEMORY
;
2189 case LDAP_OPT_X_TLS
:
2190 *(int *)arg
= lo
->ldo_tls_mode
;
2192 case LDAP_OPT_X_TLS_CTX
:
2193 *(void **)arg
= lo
->ldo_tls_ctx
;
2194 if ( lo
->ldo_tls_ctx
) {
2195 tls_ctx_ref( lo
->ldo_tls_ctx
);
2198 case LDAP_OPT_X_TLS_CACERTFILE
:
2199 *(char **)arg
= lo
->ldo_tls_cacertfile
?
2200 LDAP_STRDUP( lo
->ldo_tls_cacertfile
) : NULL
;
2202 case LDAP_OPT_X_TLS_CACERTDIR
:
2203 *(char **)arg
= lo
->ldo_tls_cacertdir
?
2204 LDAP_STRDUP( lo
->ldo_tls_cacertdir
) : NULL
;
2206 case LDAP_OPT_X_TLS_CERTFILE
:
2207 *(char **)arg
= lo
->ldo_tls_certfile
?
2208 LDAP_STRDUP( lo
->ldo_tls_certfile
) : NULL
;
2210 case LDAP_OPT_X_TLS_KEYFILE
:
2211 *(char **)arg
= lo
->ldo_tls_keyfile
?
2212 LDAP_STRDUP( lo
->ldo_tls_keyfile
) : NULL
;
2214 case LDAP_OPT_X_TLS_DHFILE
:
2215 *(char **)arg
= lo
->ldo_tls_dhfile
?
2216 LDAP_STRDUP( lo
->ldo_tls_dhfile
) : NULL
;
2219 case LDAP_OPT_X_TLS_CRLFILE
:
2220 *(char **)arg
= lo
->ldo_tls_crlfile
?
2221 LDAP_STRDUP( lo
->ldo_tls_crlfile
) : NULL
;
2224 case LDAP_OPT_X_TLS_REQUIRE_CERT
:
2225 *(int *)arg
= lo
->ldo_tls_require_cert
;
2227 #ifdef HAVE_OPENSSL_CRL
2228 case LDAP_OPT_X_TLS_CRLCHECK
:
2229 *(int *)arg
= lo
->ldo_tls_crlcheck
;
2232 case LDAP_OPT_X_TLS_CIPHER_SUITE
:
2233 *(char **)arg
= lo
->ldo_tls_ciphersuite
?
2234 LDAP_STRDUP( lo
->ldo_tls_ciphersuite
) : NULL
;
2236 case LDAP_OPT_X_TLS_RANDOM_FILE
:
2238 *(char **)arg
= tls_opt_randfile
?
2239 LDAP_STRDUP( tls_opt_randfile
) : NULL
;
2241 *(char **)arg
= NULL
;
2244 case LDAP_OPT_X_TLS_SSL_CTX
: {
2247 LDAPConn
*conn
= ld
->ld_defconn
;
2248 if ( conn
!= NULL
) {
2249 Sockbuf
*sb
= conn
->lconn_sb
;
2250 retval
= ldap_pvt_tls_sb_ctx( sb
);
2253 *(void **)arg
= retval
;
2256 case LDAP_OPT_X_TLS_CONNECT_CB
:
2257 *(LDAP_TLS_CONNECT_CB
**)arg
= lo
->ldo_tls_connect_cb
;
2259 case LDAP_OPT_X_TLS_CONNECT_ARG
:
2260 *(void **)arg
= lo
->ldo_tls_connect_arg
;
2269 ldap_pvt_tls_set_option( LDAP
*ld
, int option
, void *arg
)
2271 struct ldapoptions
*lo
;
2274 assert( LDAP_VALID( ld
) );
2276 if( !LDAP_VALID( ld
) ) {
2277 return LDAP_OPT_ERROR
;
2280 lo
= &ld
->ld_options
;
2283 /* Get pointer to global option structure */
2284 lo
= LDAP_INT_GLOBAL_OPT();
2286 return LDAP_NO_MEMORY
;
2291 case LDAP_OPT_X_TLS
:
2292 if ( !arg
) return -1;
2294 switch( *(int *) arg
) {
2295 case LDAP_OPT_X_TLS_NEVER
:
2296 case LDAP_OPT_X_TLS_DEMAND
:
2297 case LDAP_OPT_X_TLS_ALLOW
:
2298 case LDAP_OPT_X_TLS_TRY
:
2299 case LDAP_OPT_X_TLS_HARD
:
2301 lo
->ldo_tls_mode
= *(int *)arg
;
2308 case LDAP_OPT_X_TLS_CTX
:
2309 if ( lo
->ldo_tls_ctx
)
2310 ldap_pvt_tls_ctx_free( lo
->ldo_tls_ctx
);
2311 lo
->ldo_tls_ctx
= arg
;
2312 tls_ctx_ref( lo
->ldo_tls_ctx
);
2314 case LDAP_OPT_X_TLS_CONNECT_CB
:
2315 lo
->ldo_tls_connect_cb
= (LDAP_TLS_CONNECT_CB
*)arg
;
2317 case LDAP_OPT_X_TLS_CONNECT_ARG
:
2318 lo
->ldo_tls_connect_arg
= arg
;
2320 case LDAP_OPT_X_TLS_CACERTFILE
:
2321 if ( lo
->ldo_tls_cacertfile
) LDAP_FREE( lo
->ldo_tls_cacertfile
);
2322 lo
->ldo_tls_cacertfile
= arg
? LDAP_STRDUP( (char *) arg
) : NULL
;
2324 case LDAP_OPT_X_TLS_CACERTDIR
:
2325 if ( lo
->ldo_tls_cacertdir
) LDAP_FREE( lo
->ldo_tls_cacertdir
);
2326 lo
->ldo_tls_cacertdir
= arg
? LDAP_STRDUP( (char *) arg
) : NULL
;
2328 case LDAP_OPT_X_TLS_CERTFILE
:
2329 if ( lo
->ldo_tls_certfile
) LDAP_FREE( lo
->ldo_tls_certfile
);
2330 lo
->ldo_tls_certfile
= arg
? LDAP_STRDUP( (char *) arg
) : NULL
;
2332 case LDAP_OPT_X_TLS_KEYFILE
:
2333 if ( lo
->ldo_tls_keyfile
) LDAP_FREE( lo
->ldo_tls_keyfile
);
2334 lo
->ldo_tls_keyfile
= arg
? LDAP_STRDUP( (char *) arg
) : NULL
;
2336 case LDAP_OPT_X_TLS_DHFILE
:
2337 if ( lo
->ldo_tls_dhfile
) LDAP_FREE( lo
->ldo_tls_dhfile
);
2338 lo
->ldo_tls_dhfile
= arg
? LDAP_STRDUP( (char *) arg
) : NULL
;
2341 case LDAP_OPT_X_TLS_CRLFILE
:
2342 if ( lo
->ldo_tls_crlfile
) LDAP_FREE( lo
->ldo_tls_crlfile
);
2343 lo
->ldo_tls_crlfile
= arg
? LDAP_STRDUP( (char *) arg
) : NULL
;
2346 case LDAP_OPT_X_TLS_REQUIRE_CERT
:
2347 if ( !arg
) return -1;
2348 switch( *(int *) arg
) {
2349 case LDAP_OPT_X_TLS_NEVER
:
2350 case LDAP_OPT_X_TLS_DEMAND
:
2351 case LDAP_OPT_X_TLS_ALLOW
:
2352 case LDAP_OPT_X_TLS_TRY
:
2353 case LDAP_OPT_X_TLS_HARD
:
2354 lo
->ldo_tls_require_cert
= * (int *) arg
;
2358 #ifdef HAVE_OPENSSL_CRL
2359 case LDAP_OPT_X_TLS_CRLCHECK
:
2360 if ( !arg
) return -1;
2361 switch( *(int *) arg
) {
2362 case LDAP_OPT_X_TLS_CRL_NONE
:
2363 case LDAP_OPT_X_TLS_CRL_PEER
:
2364 case LDAP_OPT_X_TLS_CRL_ALL
:
2365 lo
->ldo_tls_crlcheck
= * (int *) arg
;
2370 case LDAP_OPT_X_TLS_CIPHER_SUITE
:
2371 if ( lo
->ldo_tls_ciphersuite
) LDAP_FREE( lo
->ldo_tls_ciphersuite
);
2372 lo
->ldo_tls_ciphersuite
= arg
? LDAP_STRDUP( (char *) arg
) : NULL
;
2375 case LDAP_OPT_X_TLS_RANDOM_FILE
:
2379 if (tls_opt_randfile
) LDAP_FREE (tls_opt_randfile
);
2380 tls_opt_randfile
= arg
? LDAP_STRDUP( (char *) arg
) : NULL
;
2384 case LDAP_OPT_X_TLS_NEWCTX
:
2385 if ( !arg
) return -1;
2386 if ( lo
->ldo_tls_ctx
)
2387 ldap_pvt_tls_ctx_free( lo
->ldo_tls_ctx
);
2388 lo
->ldo_tls_ctx
= NULL
;
2389 return ldap_int_tls_init_ctx( lo
, *(int *)arg
);
2397 ldap_int_tls_start ( LDAP
*ld
, LDAPConn
*conn
, LDAPURLDesc
*srv
)
2399 Sockbuf
*sb
= conn
->lconn_sb
;
2404 host
= srv
->lud_host
;
2406 host
= conn
->lconn_server
->lud_host
;
2409 /* avoid NULL host */
2410 if( host
== NULL
) {
2414 (void) ldap_pvt_tls_init();
2417 * Fortunately, the lib uses blocking io...
2419 if ( ldap_int_tls_connect( ld
, conn
) < 0 ) {
2420 ld
->ld_errno
= LDAP_CONNECT_ERROR
;
2421 return (ld
->ld_errno
);
2424 ssl
= ldap_pvt_tls_sb_ctx( sb
);
2425 assert( ssl
!= NULL
);
2428 * compare host with name(s) in certificate
2430 if (ld
->ld_options
.ldo_tls_require_cert
!= LDAP_OPT_X_TLS_NEVER
) {
2431 ld
->ld_errno
= ldap_pvt_tls_check_hostname( ld
, ssl
, host
);
2432 if (ld
->ld_errno
!= LDAP_SUCCESS
) {
2433 return ld
->ld_errno
;
2437 return LDAP_SUCCESS
;
2441 /* Derived from openssl/apps/s_cb.c */
2443 tls_info_cb( const SSL
*ssl
, int where
, int ret
)
2447 char *state
= (char *) SSL_state_string_long( (SSL
*)ssl
);
2449 w
= where
& ~SSL_ST_MASK
;
2450 if ( w
& SSL_ST_CONNECT
) {
2452 } else if ( w
& SSL_ST_ACCEPT
) {
2460 state
= LDAP_STRDUP( state
);
2464 if ( where
& SSL_CB_LOOP
) {
2465 Debug( LDAP_DEBUG_TRACE
,
2466 "TLS trace: %s:%s\n",
2469 } else if ( where
& SSL_CB_ALERT
) {
2470 char *atype
= (char *) SSL_alert_type_string_long( ret
);
2471 char *adesc
= (char *) SSL_alert_desc_string_long( ret
);
2472 op
= ( where
& SSL_CB_READ
) ? "read" : "write";
2475 atype
= LDAP_STRDUP( atype
);
2479 adesc
= LDAP_STRDUP( adesc
);
2483 Debug( LDAP_DEBUG_TRACE
,
2484 "TLS trace: SSL3 alert %s:%s:%s\n",
2487 if ( atype
) LDAP_FREE( atype
);
2488 if ( adesc
) LDAP_FREE( adesc
);
2490 } else if ( where
& SSL_CB_EXIT
) {
2492 Debug( LDAP_DEBUG_TRACE
,
2493 "TLS trace: %s:failed in %s\n",
2495 } else if ( ret
< 0 ) {
2496 Debug( LDAP_DEBUG_TRACE
,
2497 "TLS trace: %s:error in %s\n",
2502 if ( state
) LDAP_FREE( state
);
2507 tls_verify_cb( int ok
, X509_STORE_CTX
*ctx
)
2516 char *certerr
= NULL
;
2518 cert
= X509_STORE_CTX_get_current_cert( ctx
);
2519 errnum
= X509_STORE_CTX_get_error( ctx
);
2520 errdepth
= X509_STORE_CTX_get_error_depth( ctx
);
2523 * X509_get_*_name return pointers to the internal copies of
2524 * those things requested. So do not free them.
2526 subject
= X509_get_subject_name( cert
);
2527 issuer
= X509_get_issuer_name( cert
);
2528 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
2529 sname
= X509_NAME_oneline( subject
, NULL
, 0 );
2530 iname
= X509_NAME_oneline( issuer
, NULL
, 0 );
2531 if ( !ok
) certerr
= (char *)X509_verify_cert_error_string( errnum
);
2533 if ( sname
) __etoa( sname
);
2534 if ( iname
) __etoa( iname
);
2536 certerr
= LDAP_STRDUP( certerr
);
2540 Debug( LDAP_DEBUG_TRACE
,
2541 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
2543 sname
? sname
: "-unknown-" );
2544 Debug( LDAP_DEBUG_TRACE
, " issuer: %s\n", iname
? iname
: "-unknown-", 0, 0 );
2546 Debug( LDAP_DEBUG_ANY
,
2547 "TLS certificate verification: Error, %s\n",
2551 CRYPTO_free ( sname
);
2553 CRYPTO_free ( iname
);
2555 if ( certerr
) LDAP_FREE( certerr
);
2561 tls_verify_ok( int ok
, X509_STORE_CTX
*ctx
)
2563 (void) tls_verify_cb( ok
, ctx
);
2567 /* Inspired by ERR_print_errors in OpenSSL */
2569 tls_report_error( void )
2576 while ( ( l
= ERR_get_error_line( &file
, &line
) ) != 0 ) {
2577 ERR_error_string_n( l
, buf
, sizeof( buf
) );
2580 file
= LDAP_STRDUP( file
);
2581 __etoa( (char *)file
);
2585 Debug( LDAP_DEBUG_ANY
, "TLS: %s %s:%d\n",
2588 if ( file
) LDAP_FREE( (void *)file
);
2594 tls_tmp_rsa_cb( SSL
*ssl
, int is_export
, int key_length
)
2598 /* FIXME: Pregenerate the key on startup */
2599 /* FIXME: Who frees the key? */
2600 tmp_rsa
= RSA_generate_key( key_length
, RSA_F4
, NULL
, NULL
);
2603 Debug( LDAP_DEBUG_ANY
,
2604 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
2605 key_length
, is_export
? "export" : "domestic", 0 );
2612 tls_seed_PRNG( const char *randfile
)
2614 #ifndef URANDOM_DEVICE
2615 /* no /dev/urandom (or equiv) */
2617 char buffer
[MAXPATHLEN
];
2619 if (randfile
== NULL
) {
2620 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
2621 * If $HOME is not set or buffer too small to hold the pathname,
2622 * an error occurs. - From RAND_file_name() man page.
2623 * The fact is that when $HOME is NULL, .rnd is used.
2625 randfile
= RAND_file_name( buffer
, sizeof( buffer
) );
2627 } else if (RAND_egd(randfile
) > 0) {
2632 if (randfile
== NULL
) {
2633 Debug( LDAP_DEBUG_ANY
,
2634 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
2639 total
= RAND_load_file(randfile
, -1);
2641 if (RAND_status() == 0) {
2642 Debug( LDAP_DEBUG_ANY
,
2643 "TLS: PRNG not been seeded with enough data\n",
2648 /* assume if there was enough bits to seed that it's okay
2649 * to write derived bits to the file
2651 RAND_write_file(randfile
);
2665 /* From the OpenSSL 0.9.7 distro */
2666 static const char dhpem512
[] =
2667 "-----BEGIN DH PARAMETERS-----\n\
2668 MEYCQQDaWDwW2YUiidDkr3VvTMqS3UvlM7gE+w/tlO+cikQD7VdGUNNpmdsp13Yn\n\
2669 a6LT1BLiGPTdHghM9tgAPnxHdOgzAgEC\n\
2670 -----END DH PARAMETERS-----\n";
2672 static const char dhpem1024
[] =
2673 "-----BEGIN DH PARAMETERS-----\n\
2674 MIGHAoGBAJf2QmHKtQXdKCjhPx1ottPb0PMTBH9A6FbaWMsTuKG/K3g6TG1Z1fkq\n\
2675 /Gz/PWk/eLI9TzFgqVAuPvr3q14a1aZeVUMTgo2oO5/y2UHe6VaJ+trqCTat3xlx\n\
2676 /mNbIK9HA2RgPC3gWfVLZQrY+gz3ASHHR5nXWHEyvpuZm7m3h+irAgEC\n\
2677 -----END DH PARAMETERS-----\n";
2679 static const char dhpem2048
[] =
2680 "-----BEGIN DH PARAMETERS-----\n\
2681 MIIBCAKCAQEA7ZKJNYJFVcs7+6J2WmkEYb8h86tT0s0h2v94GRFS8Q7B4lW9aG9o\n\
2682 AFO5Imov5Jo0H2XMWTKKvbHbSe3fpxJmw/0hBHAY8H/W91hRGXKCeyKpNBgdL8sh\n\
2683 z22SrkO2qCnHJ6PLAMXy5fsKpFmFor2tRfCzrfnggTXu2YOzzK7q62bmqVdmufEo\n\
2684 pT8igNcLpvZxk5uBDvhakObMym9mX3rAEBoe8PwttggMYiiw7NuJKO4MqD1llGkW\n\
2685 aVM8U2ATsCun1IKHrRxynkE1/MJ86VHeYYX8GZt2YA8z+GuzylIOKcMH6JAWzMwA\n\
2686 Gbatw6QwizOhr9iMjZ0B26TE3X8LvW84wwIBAg==\n\
2687 -----END DH PARAMETERS-----\n";
2689 static const char dhpem4096
[] =
2690 "-----BEGIN DH PARAMETERS-----\n\
2691 MIICCAKCAgEA/urRnb6vkPYc/KEGXWnbCIOaKitq7ySIq9dTH7s+Ri59zs77zty7\n\
2692 vfVlSe6VFTBWgYjD2XKUFmtqq6CqXMhVX5ElUDoYDpAyTH85xqNFLzFC7nKrff/H\n\
2693 TFKNttp22cZE9V0IPpzedPfnQkE7aUdmF9JnDyv21Z/818O93u1B4r0szdnmEvEF\n\
2694 bKuIxEHX+bp0ZR7RqE1AeifXGJX3d6tsd2PMAObxwwsv55RGkn50vHO4QxtTARr1\n\
2695 rRUV5j3B3oPMgC7Offxx+98Xn45B1/G0Prp11anDsR1PGwtaCYipqsvMwQUSJtyE\n\
2696 EOQWk+yFkeMe4vWv367eEi0Sd/wnC+TSXBE3pYvpYerJ8n1MceI5GQTdarJ77OW9\n\
2697 bGTHmxRsLSCM1jpLdPja5jjb4siAa6EHc4qN9c/iFKS3PQPJEnX7pXKBRs5f7AF3\n\
2698 W3RIGt+G9IVNZfXaS7Z/iCpgzgvKCs0VeqN38QsJGtC1aIkwOeyjPNy2G6jJ4yqH\n\
2699 ovXYt/0mc00vCWeSNS1wren0pR2EiLxX0ypjjgsU1mk/Z3b/+zVf7fZSIB+nDLjb\n\
2700 NPtUlJCVGnAeBK1J1nG3TQicqowOXoM6ISkdaXj5GPJdXHab2+S7cqhKGv5qC7rR\n\
2701 jT6sx7RUr0CNTxzLI7muV2/a4tGmj0PSdXQdsZ7tw7gbXlaWT1+MM2MCAQI=\n\
2702 -----END DH PARAMETERS-----\n";
2704 static const struct dhinfo dhpem
[] = {
2705 { 512, dhpem512
, sizeof(dhpem512
) },
2706 { 1024, dhpem1024
, sizeof(dhpem1024
) },
2707 { 2048, dhpem2048
, sizeof(dhpem2048
) },
2708 { 4096, dhpem4096
, sizeof(dhpem4096
) },
2713 tls_tmp_dh_cb( SSL
*ssl
, int is_export
, int key_length
)
2715 struct dhplist
*p
= NULL
;
2720 /* Do we have params of this length already? */
2721 #ifdef LDAP_R_COMPILE
2722 ldap_pvt_thread_mutex_lock( &tls_def_ctx_mutex
);
2724 for ( p
= dhparams
; p
; p
=p
->next
) {
2725 if ( p
->keylength
== key_length
) {
2726 #ifdef LDAP_R_COMPILE
2727 ldap_pvt_thread_mutex_unlock( &tls_def_ctx_mutex
);
2733 /* No - check for hardcoded params */
2735 for (i
=0; dhpem
[i
].keylength
; i
++) {
2736 if ( dhpem
[i
].keylength
== key_length
) {
2737 b
= BIO_new_mem_buf( (char *)dhpem
[i
].pem
, dhpem
[i
].size
);
2743 dh
= PEM_read_bio_DHparams( b
, NULL
, NULL
, NULL
);
2747 /* Generating on the fly is expensive/slow... */
2749 dh
= DH_generate_parameters( key_length
, DH_GENERATOR_2
, NULL
, NULL
);
2752 p
= LDAP_MALLOC( sizeof(struct dhplist
) );
2754 p
->keylength
= key_length
;
2761 #ifdef LDAP_R_COMPILE
2762 ldap_pvt_thread_mutex_unlock( &tls_def_ctx_mutex
);
2768 #endif /* HAVE_OPENSSL */
2771 ldap_pvt_tls_sb_ctx( Sockbuf
*sb
)
2776 if (HAS_TLS( sb
)) {
2777 ber_sockbuf_ctrl( sb
, LBER_SB_OPT_GET_SSL
, (void *)&p
);
2786 ldap_pvt_tls_get_strength( void *s
)
2789 const SSL_CIPHER
*c
;
2791 c
= SSL_get_current_cipher((const SSL
*)s
);
2792 return SSL_CIPHER_get_bits(c
, NULL
);
2793 #elif defined(HAVE_GNUTLS)
2794 tls_session
*session
= s
;
2795 gnutls_cipher_algorithm_t c
;
2797 c
= gnutls_cipher_get( session
->session
);
2798 return gnutls_cipher_get_key_size( c
) * 8;
2806 ldap_pvt_tls_get_my_dn( void *s
, struct berval
*dn
, LDAPDN_rewrite_dummy
*func
, unsigned flags
)
2809 struct berval der_dn
;
2815 x
= SSL_get_certificate((SSL
*)s
);
2817 if (!x
) return LDAP_INVALID_CREDENTIALS
;
2819 xn
= X509_get_subject_name(x
);
2820 der_dn
.bv_len
= i2d_X509_NAME( xn
, NULL
);
2821 der_dn
.bv_val
= xn
->bytes
->data
;
2822 #elif defined(HAVE_GNUTLS)
2823 tls_session
*session
= s
;
2824 const gnutls_datum_t
*x
;
2827 x
= gnutls_certificate_get_ours( session
->session
);
2829 if (!x
) return LDAP_INVALID_CREDENTIALS
;
2831 bv
.bv_val
= x
->data
;
2832 bv
.bv_len
= x
->size
;
2834 x509_cert_get_dn( &bv
, &der_dn
, 1 );
2836 rc
= ldap_X509dn2bv(&der_dn
, dn
, (LDAPDN_rewrite_func
*)func
, flags
);
2838 #else /* !HAVE_TLS */
2839 return LDAP_NOT_SUPPORTED
;
2844 ldap_start_tls( LDAP
*ld
,
2845 LDAPControl
**serverctrls
,
2846 LDAPControl
**clientctrls
,
2849 return ldap_extended_operation( ld
, LDAP_EXOP_START_TLS
,
2850 NULL
, serverctrls
, clientctrls
, msgidp
);
2854 ldap_install_tls( LDAP
*ld
)
2857 return LDAP_NOT_SUPPORTED
;
2859 if ( ldap_tls_inplace( ld
) ) {
2860 return LDAP_LOCAL_ERROR
;
2863 return ldap_int_tls_start( ld
, ld
->ld_defconn
, NULL
);
2868 ldap_start_tls_s ( LDAP
*ld
,
2869 LDAPControl
**serverctrls
,
2870 LDAPControl
**clientctrls
)
2873 return LDAP_NOT_SUPPORTED
;
2876 char *rspoid
= NULL
;
2877 struct berval
*rspdata
= NULL
;
2879 /* XXYYZ: this initiates operation only on default connection! */
2881 if ( ldap_tls_inplace( ld
) ) {
2882 return LDAP_LOCAL_ERROR
;
2885 rc
= ldap_extended_operation_s( ld
, LDAP_EXOP_START_TLS
,
2886 NULL
, serverctrls
, clientctrls
, &rspoid
, &rspdata
);
2888 if ( rspoid
!= NULL
) {
2892 if ( rspdata
!= NULL
) {
2893 ber_bvfree( rspdata
);
2896 if ( rc
== LDAP_SUCCESS
) {
2897 rc
= ldap_int_tls_start( ld
, ld
->ld_defconn
, NULL
);
2904 /* These tags probably all belong in lber.h, but they're
2905 * not normally encountered when processing LDAP, so maybe
2906 * they belong somewhere else instead.
2909 #define LBER_TAG_OID ((ber_tag_t) 0x06UL)
2911 /* Tags for string types used in a DirectoryString.
2913 * Note that IA5string is not one of the defined choices for
2914 * DirectoryString in X.520, but it gets used for email AVAs.
2916 #define LBER_TAG_UTF8 ((ber_tag_t) 0x0cUL)
2917 #define LBER_TAG_PRINTABLE ((ber_tag_t) 0x13UL)
2918 #define LBER_TAG_TELETEX ((ber_tag_t) 0x14UL)
2919 #define LBER_TAG_IA5 ((ber_tag_t) 0x16UL)
2920 #define LBER_TAG_UNIVERSAL ((ber_tag_t) 0x1cUL)
2921 #define LBER_TAG_BMP ((ber_tag_t) 0x1eUL)
2924 find_oid( struct berval
*oid
)
2928 for ( i
=0; !BER_BVISNULL( &oids
[i
].oid
); i
++ ) {
2929 if ( oids
[i
].oid
.bv_len
!= oid
->bv_len
) continue;
2930 if ( !strcmp( oids
[i
].oid
.bv_val
, oid
->bv_val
))
2936 /* Convert a structured DN from an X.509 certificate into an LDAPV3 DN.
2937 * x509_name must be raw DER. If func is non-NULL, the
2938 * constructed DN will use numeric OIDs to identify attributeTypes,
2939 * and the func() will be invoked to rewrite the DN with the given
2942 * Otherwise the DN will use shortNames from a hardcoded table.
2945 ldap_X509dn2bv( void *x509_name
, struct berval
*bv
, LDAPDN_rewrite_func
*func
,
2950 LDAPAVA
*newAVA
, *baseAVA
;
2951 BerElementBuffer berbuf
;
2952 BerElement
*ber
= (BerElement
*)&berbuf
;
2953 char oids
[8192], *oidptr
= oids
, *oidbuf
= NULL
;
2955 char *dn_end
, *rdn_end
;
2956 int i
, navas
, nrdns
, rc
= LDAP_SUCCESS
;
2957 size_t dnsize
, oidrem
= sizeof(oids
), oidsize
= 0;
2963 struct berval Oid
, Val
, oid2
, *in
= x509_name
;
2965 assert( bv
!= NULL
);
2973 /* A DN is a SEQUENCE of RDNs. An RDN is a SET of AVAs.
2974 * An AVA is a SEQUENCE of attr and value.
2975 * Count the number of AVAs and RDNs
2977 ber_init2( ber
, in
, LBER_USE_DER
);
2978 tag
= ber_peek_tag( ber
, &len
);
2979 if ( tag
!= LBER_SEQUENCE
)
2980 return LDAP_DECODING_ERROR
;
2982 for ( tag
= ber_first_element( ber
, &len
, &dn_end
);
2984 tag
= ber_next_element( ber
, &len
, dn_end
)) {
2986 for ( tag
= ber_first_element( ber
, &len
, &rdn_end
);
2987 tag
== LBER_SEQUENCE
;
2988 tag
= ber_next_element( ber
, &len
, rdn_end
)) {
2989 tag
= ber_skip_tag( ber
, &len
);
2990 ber_skip_data( ber
, len
);
2995 /* Allocate the DN/RDN/AVA stuff as a single block */
2996 dnsize
= sizeof(LDAPRDN
) * (nrdns
+1);
2997 dnsize
+= sizeof(LDAPAVA
*) * (navas
+nrdns
);
2998 dnsize
+= sizeof(LDAPAVA
) * navas
;
2999 if (dnsize
> sizeof(ptrs
)) {
3000 newDN
= (LDAPDN
)LDAP_MALLOC( dnsize
);
3001 if ( newDN
== NULL
)
3002 return LDAP_NO_MEMORY
;
3004 newDN
= (LDAPDN
)(char *)ptrs
;
3007 newDN
[nrdns
] = NULL
;
3008 newRDN
= (LDAPRDN
)(newDN
+ nrdns
+1);
3009 newAVA
= (LDAPAVA
*)(newRDN
+ navas
+ nrdns
);
3012 /* Rewind and start extracting */
3015 tag
= ber_first_element( ber
, &len
, &dn_end
);
3016 for ( i
= nrdns
- 1; i
>= 0; i
-- ) {
3019 for ( tag
= ber_first_element( ber
, &len
, &rdn_end
);
3020 tag
== LBER_SEQUENCE
;
3021 tag
= ber_next_element( ber
, &len
, rdn_end
)) {
3024 tag
= ber_skip_tag( ber
, &len
);
3025 tag
= ber_get_stringbv( ber
, &Oid
, LBER_BV_NOTERM
);
3026 if ( tag
!= LBER_TAG_OID
) {
3027 rc
= LDAP_DECODING_ERROR
;
3031 oid2
.bv_val
= oidptr
;
3032 oid2
.bv_len
= oidrem
;
3033 if ( ber_decode_oid( &Oid
, &oid2
) < 0 ) {
3034 rc
= LDAP_DECODING_ERROR
;
3037 oidname
= find_oid( &oid2
);
3039 newAVA
->la_attr
= oid2
;
3040 oidptr
+= oid2
.bv_len
+ 1;
3041 oidrem
-= oid2
.bv_len
+ 1;
3043 /* Running out of OID buffer space? */
3045 if ( oidsize
== 0 ) {
3046 oidsize
= sizeof(oids
) * 2;
3048 oidbuf
= LDAP_MALLOC( oidsize
);
3049 if ( oidbuf
== NULL
) goto nomem
;
3053 oidbuf
= LDAP_REALLOC( oidbuf
, oidsize
*2 );
3054 if ( oidbuf
== NULL
) goto nomem
;
3055 /* Buffer moved! Fix AVA pointers */
3056 if ( old
!= oidbuf
) {
3058 long dif
= oidbuf
- old
;
3060 for (a
=baseAVA
; a
<=newAVA
; a
++){
3061 if (a
->la_attr
.bv_val
>= old
&&
3062 a
->la_attr
.bv_val
<= (old
+ oidsize
))
3063 a
->la_attr
.bv_val
+= dif
;
3066 oidptr
= oidbuf
+ oidsize
- oidrem
;
3073 newAVA
->la_attr
= oidname
->oid
;
3075 newAVA
->la_attr
= oidname
->name
;
3078 tag
= ber_get_stringbv( ber
, &Val
, LBER_BV_NOTERM
);
3080 case LBER_TAG_UNIVERSAL
:
3081 /* This uses 32-bit ISO 10646-1 */
3082 csize
= 4; goto to_utf8
;
3084 /* This uses 16-bit ISO 10646-1 */
3085 csize
= 2; goto to_utf8
;
3086 case LBER_TAG_TELETEX
:
3087 /* This uses 8-bit, assume ISO 8859-1 */
3089 to_utf8
: rc
= ldap_ucs_to_utf8s( &Val
, csize
, &newAVA
->la_value
);
3090 newAVA
->la_flags
|= LDAP_AVA_FREE_VALUE
;
3091 if (rc
!= LDAP_SUCCESS
) goto nomem
;
3092 newAVA
->la_flags
= LDAP_AVA_NONPRINTABLE
;
3095 newAVA
->la_flags
= LDAP_AVA_NONPRINTABLE
;
3096 /* This is already in UTF-8 encoding */
3098 case LBER_TAG_PRINTABLE
:
3099 /* These are always 7-bit strings */
3100 newAVA
->la_value
= Val
;
3104 newAVA
->la_private
= NULL
;
3105 newAVA
->la_flags
= LDAP_AVA_STRING
;
3109 tag
= ber_next_element( ber
, &len
, dn_end
);
3113 rc
= func( newDN
, flags
, NULL
);
3114 if ( rc
!= LDAP_SUCCESS
)
3118 rc
= ldap_dn2bv_x( newDN
, bv
, LDAP_DN_FORMAT_LDAPV3
, NULL
);
3121 for (;baseAVA
< newAVA
; baseAVA
++) {
3122 if (baseAVA
->la_flags
& LDAP_AVA_FREE_ATTR
)
3123 LDAP_FREE( baseAVA
->la_attr
.bv_val
);
3124 if (baseAVA
->la_flags
& LDAP_AVA_FREE_VALUE
)
3125 LDAP_FREE( baseAVA
->la_value
.bv_val
);
3129 LDAP_FREE( oidbuf
);
3130 if ( newDN
!= (LDAPDN
)(char *) ptrs
)