1 /* tls_o.c - Handle tls/ssl using OpenSSL */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 2008-2010 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: Rewritten by Howard Chu
23 #include "ldap_config.h"
27 #include <ac/stdlib.h>
29 #include <ac/socket.h>
30 #include <ac/string.h>
33 #include <ac/unistd.h>
35 #include <ac/dirent.h>
41 #include <ldap_pvt_thread.h>
44 #ifdef HAVE_OPENSSL_SSL_H
45 #include <openssl/ssl.h>
46 #include <openssl/x509v3.h>
47 #include <openssl/err.h>
48 #include <openssl/rand.h>
49 #include <openssl/safestack.h>
50 #elif defined( HAVE_SSL_H )
54 typedef SSL_CTX tlso_ctx;
55 typedef SSL tlso_session;
57 static int tlso_opt_trace = 1;
59 static void tlso_report_error( void );
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 RSA * tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
66 static DH * tlso_tmp_dh_cb( SSL *ssl, int is_export, int key_length );
68 typedef struct dhplist {
74 static dhplist *tlso_dhparams;
76 static int tlso_seed_PRNG( const char *randfile );
80 * provide mutexes for the OpenSSL library.
82 static ldap_pvt_thread_mutex_t tlso_mutexes[CRYPTO_NUM_LOCKS];
83 static ldap_pvt_thread_mutex_t tlso_dh_mutex;
85 static void tlso_locking_cb( int mode, int type, const char *file, int line )
87 if ( mode & CRYPTO_LOCK ) {
88 ldap_pvt_thread_mutex_lock( &tlso_mutexes[type] );
90 ldap_pvt_thread_mutex_unlock( &tlso_mutexes[type] );
94 static unsigned long tlso_thread_self( void )
96 /* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
97 * is an integral type that fits in an unsigned long
100 /* force an error if the ldap_pvt_thread_t type is too large */
101 enum { ok = sizeof( ldap_pvt_thread_t ) <= sizeof( unsigned long ) };
102 typedef struct { int dummy: ok ? 1 : -1; } Check[ok ? 1 : -1];
104 return (unsigned long) ldap_pvt_thread_self();
107 static void tlso_thr_init( void )
111 for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
112 ldap_pvt_thread_mutex_init( &tlso_mutexes[i] );
114 ldap_pvt_thread_mutex_init( &tlso_dh_mutex );
115 CRYPTO_set_locking_callback( tlso_locking_cb );
116 CRYPTO_set_id_callback( tlso_thread_self );
118 #endif /* LDAP_R_COMPILE */
120 static STACK_OF(X509_NAME) *
121 tlso_ca_list( char * bundle, char * dir )
123 STACK_OF(X509_NAME) *ca_list = NULL;
126 ca_list = SSL_load_client_CA_file( bundle );
128 #if defined(HAVE_DIRENT_H) || defined(dirent)
133 ca_list = sk_X509_NAME_new_null();
136 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
138 sk_X509_NAME_free( ca_list );
147 * Initialize TLS subsystem. Should be called only once.
152 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
155 char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
156 if ( file ) __atoe( file );
157 (void) tlso_seed_PRNG( file );
161 (void) tlso_seed_PRNG( lo->ldo_tls_randfile );
164 SSL_load_error_strings();
166 OpenSSL_add_all_digests();
168 /* FIXME: mod_ssl does this */
169 X509V3_add_standard_extensions();
175 * Tear down the TLS subsystem. Should only be called once.
180 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
186 if ( lo->ldo_tls_randfile ) {
187 LDAP_FREE( lo->ldo_tls_randfile );
188 lo->ldo_tls_randfile = NULL;
193 tlso_ctx_new( struct ldapoptions *lo )
195 return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
199 tlso_ctx_ref( tls_ctx *ctx )
201 tlso_ctx *c = (tlso_ctx *)ctx;
202 CRYPTO_add( &c->references, 1, CRYPTO_LOCK_SSL_CTX );
206 tlso_ctx_free ( tls_ctx *ctx )
208 tlso_ctx *c = (tlso_ctx *)ctx;
213 * initialize a new TLS context
216 tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
218 tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
222 SSL_CTX_set_session_id_context( ctx,
223 (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
226 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
227 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 );
228 else if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 )
229 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 );
231 if ( lo->ldo_tls_ciphersuite &&
232 !SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
234 Debug( LDAP_DEBUG_ANY,
235 "TLS: could not set cipher list %s.\n",
236 lo->ldo_tls_ciphersuite, 0, 0 );
241 if (lo->ldo_tls_cacertfile != NULL || lo->ldo_tls_cacertdir != NULL) {
242 if ( !SSL_CTX_load_verify_locations( ctx,
243 lt->lt_cacertfile, lt->lt_cacertdir ) ||
244 !SSL_CTX_set_default_verify_paths( ctx ) )
246 Debug( LDAP_DEBUG_ANY, "TLS: "
247 "could not load verify locations (file:`%s',dir:`%s').\n",
248 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
249 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
256 STACK_OF(X509_NAME) *calist;
257 /* List of CA names to send to a client */
258 calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir );
260 Debug( LDAP_DEBUG_ANY, "TLS: "
261 "could not load client CA list (file:`%s',dir:`%s').\n",
262 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
263 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
269 SSL_CTX_set_client_CA_list( ctx, calist );
273 if ( lo->ldo_tls_certfile &&
274 !SSL_CTX_use_certificate_file( ctx,
275 lt->lt_certfile, SSL_FILETYPE_PEM ) )
277 Debug( LDAP_DEBUG_ANY,
278 "TLS: could not use certificate `%s'.\n",
279 lo->ldo_tls_certfile,0,0);
284 /* Key validity is checked automatically if cert has already been set */
285 if ( lo->ldo_tls_keyfile &&
286 !SSL_CTX_use_PrivateKey_file( ctx,
287 lt->lt_keyfile, SSL_FILETYPE_PEM ) )
289 Debug( LDAP_DEBUG_ANY,
290 "TLS: could not use key file `%s'.\n",
291 lo->ldo_tls_keyfile,0,0);
296 if ( lo->ldo_tls_dhfile ) {
301 if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
302 Debug( LDAP_DEBUG_ANY,
303 "TLS: could not use DH parameters file `%s'.\n",
304 lo->ldo_tls_dhfile,0,0);
308 while (( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
309 p = LDAP_MALLOC( sizeof(dhplist) );
311 p->keylength = DH_size( dh ) * 8;
313 p->next = tlso_dhparams;
320 if ( tlso_opt_trace ) {
321 SSL_CTX_set_info_callback( ctx, tlso_info_cb );
325 if ( lo->ldo_tls_require_cert ) {
327 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
328 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
329 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
333 SSL_CTX_set_verify( ctx, i,
334 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
335 tlso_verify_ok : tlso_verify_cb );
336 SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
337 if ( lo->ldo_tls_dhfile ) {
338 SSL_CTX_set_tmp_dh_callback( ctx, tlso_tmp_dh_cb );
340 #ifdef HAVE_OPENSSL_CRL
341 if ( lo->ldo_tls_crlcheck ) {
342 X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
343 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
344 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
345 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
346 X509_STORE_set_flags( x509_s,
347 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
355 tlso_session_new( tls_ctx *ctx, int is_server )
357 tlso_ctx *c = (tlso_ctx *)ctx;
358 return (tls_session *)SSL_new( c );
362 tlso_session_connect( LDAP *ld, tls_session *sess )
364 tlso_session *s = (tlso_session *)sess;
366 /* Caller expects 0 = success, OpenSSL returns 1 = success */
367 return SSL_connect( s ) - 1;
371 tlso_session_accept( tls_session *sess )
373 tlso_session *s = (tlso_session *)sess;
375 /* Caller expects 0 = success, OpenSSL returns 1 = success */
376 return SSL_accept( s ) - 1;
380 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
382 tlso_session *s = (tlso_session *)sess;
384 /* 1 was subtracted above, offset it back now */
385 rc = SSL_get_error(s, rc+1);
386 if (rc == SSL_ERROR_WANT_READ) {
387 sb->sb_trans_needs_read = 1;
390 } else if (rc == SSL_ERROR_WANT_WRITE) {
391 sb->sb_trans_needs_write = 1;
394 } else if (rc == SSL_ERROR_WANT_CONNECT) {
401 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
404 const char *certerr=NULL;
405 tlso_session *s = (tlso_session *)sess;
407 rc = ERR_peek_error();
409 ERR_error_string_n( rc, err, sizeof(err) );
410 if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) &&
411 ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
412 int certrc = SSL_get_verify_result(s);
413 certerr = (char *)X509_verify_cert_error_string(certrc);
415 snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"",
416 certerr ? certerr : "", certerr ? ")" : "" );
423 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
425 tlso_session *s = (tlso_session *)sess;
429 x = SSL_get_certificate( s );
431 if (!x) return LDAP_INVALID_CREDENTIALS;
433 xn = X509_get_subject_name(x);
434 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
435 der_dn->bv_val = xn->bytes->data;
436 /* Don't X509_free, the session is still using it */
441 tlso_get_cert( SSL *s )
443 /* If peer cert was bad, treat as if no cert was given */
444 if (SSL_get_verify_result(s)) {
447 return SSL_get_peer_certificate(s);
451 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
453 tlso_session *s = (tlso_session *)sess;
454 X509 *x = tlso_get_cert( s );
458 return LDAP_INVALID_CREDENTIALS;
460 xn = X509_get_subject_name(x);
461 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
462 der_dn->bv_val = xn->bytes->data;
467 /* what kind of hostname were we given? */
473 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
475 tlso_session *s = (tlso_session *)sess;
476 int i, ret = LDAP_LOCAL_ERROR;
480 int ntype = IS_DNS, nlen;
482 struct in6_addr addr;
487 if( ldap_int_hostname &&
488 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
490 name = ldap_int_hostname;
496 x = tlso_get_cert(s);
498 Debug( LDAP_DEBUG_ANY,
499 "TLS: unable to get peer certificate.\n",
501 /* If this was a fatal condition, things would have
502 * aborted long before now.
508 if (name[0] == '[' && strchr(name, ']')) {
509 char *n2 = ldap_strdup(name+1);
510 *strchr(n2, ']') = 0;
511 if (inet_pton(AF_INET6, n2, &addr))
516 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
517 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
520 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
523 STACK_OF(GENERAL_NAME) *alt;
525 ex = X509_get_ext(x, i);
526 alt = X509V3_EXT_d2i(ex);
532 if (ntype == IS_DNS) {
533 domain = strchr(name, '.');
535 len2 = nlen - (domain-name);
538 n = sk_GENERAL_NAME_num(alt);
539 for (i=0; i<n; i++) {
542 gn = sk_GENERAL_NAME_value(alt, i);
543 if (gn->type == GEN_DNS) {
544 if (ntype != IS_DNS) continue;
546 sn = (char *) ASN1_STRING_data(gn->d.ia5);
547 sl = ASN1_STRING_length(gn->d.ia5);
550 if (sl == 0) continue;
552 /* Is this an exact match? */
553 if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
557 /* Is this a wildcard match? */
558 if (domain && (sn[0] == '*') && (sn[1] == '.') &&
559 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
564 } else if (gn->type == GEN_IPADD) {
565 if (ntype == IS_DNS) continue;
567 sn = (char *) ASN1_STRING_data(gn->d.ia5);
568 sl = ASN1_STRING_length(gn->d.ia5);
571 if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
575 if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
578 if (!memcmp(sn, &addr, sl)) {
584 GENERAL_NAMES_free(alt);
585 if (i < n) { /* Found a match */
591 if (ret != LDAP_SUCCESS) {
595 ASN1_STRING *cn = NULL;
598 /* find the last CN */
599 obj = OBJ_nid2obj( NID_commonName );
600 if ( !obj ) goto no_cn; /* should never happen */
602 xn = X509_get_subject_name(x);
603 navas = X509_NAME_entry_count( xn );
604 for ( i=navas-1; i>=0; i-- ) {
605 ne = X509_NAME_get_entry( xn, i );
606 if ( !OBJ_cmp( ne->object, obj )) {
607 cn = X509_NAME_ENTRY_get_data( ne );
615 Debug( LDAP_DEBUG_ANY,
616 "TLS: unable to get common name from peer certificate.\n",
618 ret = LDAP_CONNECT_ERROR;
619 if ( ld->ld_error ) {
620 LDAP_FREE( ld->ld_error );
622 ld->ld_error = LDAP_STRDUP(
623 _("TLS: unable to get CN from peer certificate"));
625 } else if ( cn->length == nlen &&
626 strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
629 } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
630 char *domain = strchr(name, '.');
634 dlen = nlen - (domain-name);
636 /* Is this a wildcard match? */
637 if ((dlen == cn->length-1) &&
638 !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
644 if( ret == LDAP_LOCAL_ERROR ) {
645 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
646 "common name in certificate (%.*s).\n",
647 name, cn->length, cn->data );
648 ret = LDAP_CONNECT_ERROR;
649 if ( ld->ld_error ) {
650 LDAP_FREE( ld->ld_error );
652 ld->ld_error = LDAP_STRDUP(
653 _("TLS: hostname does not match CN in peer certificate"));
661 tlso_session_strength( tls_session *sess )
663 tlso_session *s = (tlso_session *)sess;
666 c = SSL_get_current_cipher(s);
667 return SSL_CIPHER_get_bits(c, NULL);
671 * TLS support for LBER Sockbufs
675 tlso_session *session;
676 Sockbuf_IO_Desc *sbiod;
680 tlso_bio_create( BIO *b ) {
689 tlso_bio_destroy( BIO *b )
691 if ( b == NULL ) return 0;
693 b->ptr = NULL; /* sb_tls_remove() will free it */
700 tlso_bio_read( BIO *b, char *buf, int len )
705 if ( buf == NULL || len <= 0 ) return 0;
707 p = (struct tls_data *)b->ptr;
709 if ( p == NULL || p->sbiod == NULL ) {
713 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
715 BIO_clear_retry_flags( b );
717 int err = sock_errno();
718 if ( err == EAGAIN || err == EWOULDBLOCK ) {
719 BIO_set_retry_read( b );
727 tlso_bio_write( BIO *b, const char *buf, int len )
732 if ( buf == NULL || len <= 0 ) return 0;
734 p = (struct tls_data *)b->ptr;
736 if ( p == NULL || p->sbiod == NULL ) {
740 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
742 BIO_clear_retry_flags( b );
744 int err = sock_errno();
745 if ( err == EAGAIN || err == EWOULDBLOCK ) {
746 BIO_set_retry_write( b );
754 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
756 if ( cmd == BIO_CTRL_FLUSH ) {
757 /* The OpenSSL library needs this */
764 tlso_bio_gets( BIO *b, char *buf, int len )
770 tlso_bio_puts( BIO *b, const char *str )
772 return tlso_bio_write( b, str, strlen( str ) );
775 static BIO_METHOD tlso_bio_method =
777 ( 100 | 0x400 ), /* it's a source/sink BIO */
789 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
794 assert( sbiod != NULL );
796 p = LBER_MALLOC( sizeof( *p ) );
803 bio = BIO_new( &tlso_bio_method );
804 bio->ptr = (void *)p;
805 SSL_set_bio( p->session, bio, bio );
806 sbiod->sbiod_pvt = p;
811 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
815 assert( sbiod != NULL );
816 assert( sbiod->sbiod_pvt != NULL );
818 p = (struct tls_data *)sbiod->sbiod_pvt;
819 SSL_free( p->session );
820 LBER_FREE( sbiod->sbiod_pvt );
821 sbiod->sbiod_pvt = NULL;
826 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
830 assert( sbiod != NULL );
831 assert( sbiod->sbiod_pvt != NULL );
833 p = (struct tls_data *)sbiod->sbiod_pvt;
834 SSL_shutdown( p->session );
839 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
843 assert( sbiod != NULL );
844 assert( sbiod->sbiod_pvt != NULL );
846 p = (struct tls_data *)sbiod->sbiod_pvt;
848 if ( opt == LBER_SB_OPT_GET_SSL ) {
849 *((tlso_session **)arg) = p->session;
852 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
853 if( SSL_pending( p->session ) > 0 ) {
858 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
862 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
868 assert( sbiod != NULL );
869 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
871 p = (struct tls_data *)sbiod->sbiod_pvt;
873 ret = SSL_read( p->session, (char *)buf, len );
875 errno = WSAGetLastError();
877 err = SSL_get_error( p->session, ret );
878 if (err == SSL_ERROR_WANT_READ ) {
879 sbiod->sbiod_sb->sb_trans_needs_read = 1;
880 sock_errset(EWOULDBLOCK);
883 sbiod->sbiod_sb->sb_trans_needs_read = 0;
888 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
894 assert( sbiod != NULL );
895 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
897 p = (struct tls_data *)sbiod->sbiod_pvt;
899 ret = SSL_write( p->session, (char *)buf, len );
901 errno = WSAGetLastError();
903 err = SSL_get_error( p->session, ret );
904 if (err == SSL_ERROR_WANT_WRITE ) {
905 sbiod->sbiod_sb->sb_trans_needs_write = 1;
906 sock_errset(EWOULDBLOCK);
909 sbiod->sbiod_sb->sb_trans_needs_write = 0;
914 static Sockbuf_IO tlso_sbio =
916 tlso_sb_setup, /* sbi_setup */
917 tlso_sb_remove, /* sbi_remove */
918 tlso_sb_ctrl, /* sbi_ctrl */
919 tlso_sb_read, /* sbi_read */
920 tlso_sb_write, /* sbi_write */
921 tlso_sb_close /* sbi_close */
924 /* Derived from openssl/apps/s_cb.c */
926 tlso_info_cb( const SSL *ssl, int where, int ret )
930 char *state = (char *) SSL_state_string_long( (SSL *)ssl );
932 w = where & ~SSL_ST_MASK;
933 if ( w & SSL_ST_CONNECT ) {
935 } else if ( w & SSL_ST_ACCEPT ) {
943 state = LDAP_STRDUP( state );
947 if ( where & SSL_CB_LOOP ) {
948 Debug( LDAP_DEBUG_TRACE,
949 "TLS trace: %s:%s\n",
952 } else if ( where & SSL_CB_ALERT ) {
953 char *atype = (char *) SSL_alert_type_string_long( ret );
954 char *adesc = (char *) SSL_alert_desc_string_long( ret );
955 op = ( where & SSL_CB_READ ) ? "read" : "write";
958 atype = LDAP_STRDUP( atype );
962 adesc = LDAP_STRDUP( adesc );
966 Debug( LDAP_DEBUG_TRACE,
967 "TLS trace: SSL3 alert %s:%s:%s\n",
970 if ( atype ) LDAP_FREE( atype );
971 if ( adesc ) LDAP_FREE( adesc );
973 } else if ( where & SSL_CB_EXIT ) {
975 Debug( LDAP_DEBUG_TRACE,
976 "TLS trace: %s:failed in %s\n",
978 } else if ( ret < 0 ) {
979 Debug( LDAP_DEBUG_TRACE,
980 "TLS trace: %s:error in %s\n",
985 if ( state ) LDAP_FREE( state );
990 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
999 char *certerr = NULL;
1001 cert = X509_STORE_CTX_get_current_cert( ctx );
1002 errnum = X509_STORE_CTX_get_error( ctx );
1003 errdepth = X509_STORE_CTX_get_error_depth( ctx );
1006 * X509_get_*_name return pointers to the internal copies of
1007 * those things requested. So do not free them.
1009 subject = X509_get_subject_name( cert );
1010 issuer = X509_get_issuer_name( cert );
1011 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1012 sname = X509_NAME_oneline( subject, NULL, 0 );
1013 iname = X509_NAME_oneline( issuer, NULL, 0 );
1014 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1016 if ( sname ) __etoa( sname );
1017 if ( iname ) __etoa( iname );
1019 certerr = LDAP_STRDUP( certerr );
1023 Debug( LDAP_DEBUG_TRACE,
1024 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1026 sname ? sname : "-unknown-" );
1027 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1029 Debug( LDAP_DEBUG_ANY,
1030 "TLS certificate verification: Error, %s\n",
1034 CRYPTO_free ( sname );
1036 CRYPTO_free ( iname );
1038 if ( certerr ) LDAP_FREE( certerr );
1044 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1046 (void) tlso_verify_cb( ok, ctx );
1050 /* Inspired by ERR_print_errors in OpenSSL */
1052 tlso_report_error( void )
1059 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1060 ERR_error_string_n( l, buf, sizeof( buf ) );
1063 file = LDAP_STRDUP( file );
1064 __etoa( (char *)file );
1068 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1071 if ( file ) LDAP_FREE( (void *)file );
1077 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1080 /* FIXME: Pregenerate the key on startup */
1081 /* FIXME: Who frees the key? */
1082 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1083 BIGNUM *bn = BN_new();
1086 if ( BN_set_word( bn, RSA_F4 )) {
1087 tmp_rsa = RSA_new();
1088 if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1089 RSA_free( tmp_rsa );
1096 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1100 Debug( LDAP_DEBUG_ANY,
1101 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1102 key_length, is_export ? "export" : "domestic", 0 );
1108 tlso_seed_PRNG( const char *randfile )
1110 #ifndef URANDOM_DEVICE
1111 /* no /dev/urandom (or equiv) */
1113 char buffer[MAXPATHLEN];
1115 if (randfile == NULL) {
1116 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1117 * If $HOME is not set or buffer too small to hold the pathname,
1118 * an error occurs. - From RAND_file_name() man page.
1119 * The fact is that when $HOME is NULL, .rnd is used.
1121 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1123 } else if (RAND_egd(randfile) > 0) {
1128 if (randfile == NULL) {
1129 Debug( LDAP_DEBUG_ANY,
1130 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1135 total = RAND_load_file(randfile, -1);
1137 if (RAND_status() == 0) {
1138 Debug( LDAP_DEBUG_ANY,
1139 "TLS: PRNG not been seeded with enough data\n",
1144 /* assume if there was enough bits to seed that it's okay
1145 * to write derived bits to the file
1147 RAND_write_file(randfile);
1161 /* From the OpenSSL 0.9.7 distro */
1162 static const char tlso_dhpem512[] =
1163 "-----BEGIN DH PARAMETERS-----\n\
1164 MEYCQQDaWDwW2YUiidDkr3VvTMqS3UvlM7gE+w/tlO+cikQD7VdGUNNpmdsp13Yn\n\
1165 a6LT1BLiGPTdHghM9tgAPnxHdOgzAgEC\n\
1166 -----END DH PARAMETERS-----\n";
1168 static const char tlso_dhpem1024[] =
1169 "-----BEGIN DH PARAMETERS-----\n\
1170 MIGHAoGBAJf2QmHKtQXdKCjhPx1ottPb0PMTBH9A6FbaWMsTuKG/K3g6TG1Z1fkq\n\
1171 /Gz/PWk/eLI9TzFgqVAuPvr3q14a1aZeVUMTgo2oO5/y2UHe6VaJ+trqCTat3xlx\n\
1172 /mNbIK9HA2RgPC3gWfVLZQrY+gz3ASHHR5nXWHEyvpuZm7m3h+irAgEC\n\
1173 -----END DH PARAMETERS-----\n";
1175 static const char tlso_dhpem2048[] =
1176 "-----BEGIN DH PARAMETERS-----\n\
1177 MIIBCAKCAQEA7ZKJNYJFVcs7+6J2WmkEYb8h86tT0s0h2v94GRFS8Q7B4lW9aG9o\n\
1178 AFO5Imov5Jo0H2XMWTKKvbHbSe3fpxJmw/0hBHAY8H/W91hRGXKCeyKpNBgdL8sh\n\
1179 z22SrkO2qCnHJ6PLAMXy5fsKpFmFor2tRfCzrfnggTXu2YOzzK7q62bmqVdmufEo\n\
1180 pT8igNcLpvZxk5uBDvhakObMym9mX3rAEBoe8PwttggMYiiw7NuJKO4MqD1llGkW\n\
1181 aVM8U2ATsCun1IKHrRxynkE1/MJ86VHeYYX8GZt2YA8z+GuzylIOKcMH6JAWzMwA\n\
1182 Gbatw6QwizOhr9iMjZ0B26TE3X8LvW84wwIBAg==\n\
1183 -----END DH PARAMETERS-----\n";
1185 static const char tlso_dhpem4096[] =
1186 "-----BEGIN DH PARAMETERS-----\n\
1187 MIICCAKCAgEA/urRnb6vkPYc/KEGXWnbCIOaKitq7ySIq9dTH7s+Ri59zs77zty7\n\
1188 vfVlSe6VFTBWgYjD2XKUFmtqq6CqXMhVX5ElUDoYDpAyTH85xqNFLzFC7nKrff/H\n\
1189 TFKNttp22cZE9V0IPpzedPfnQkE7aUdmF9JnDyv21Z/818O93u1B4r0szdnmEvEF\n\
1190 bKuIxEHX+bp0ZR7RqE1AeifXGJX3d6tsd2PMAObxwwsv55RGkn50vHO4QxtTARr1\n\
1191 rRUV5j3B3oPMgC7Offxx+98Xn45B1/G0Prp11anDsR1PGwtaCYipqsvMwQUSJtyE\n\
1192 EOQWk+yFkeMe4vWv367eEi0Sd/wnC+TSXBE3pYvpYerJ8n1MceI5GQTdarJ77OW9\n\
1193 bGTHmxRsLSCM1jpLdPja5jjb4siAa6EHc4qN9c/iFKS3PQPJEnX7pXKBRs5f7AF3\n\
1194 W3RIGt+G9IVNZfXaS7Z/iCpgzgvKCs0VeqN38QsJGtC1aIkwOeyjPNy2G6jJ4yqH\n\
1195 ovXYt/0mc00vCWeSNS1wren0pR2EiLxX0ypjjgsU1mk/Z3b/+zVf7fZSIB+nDLjb\n\
1196 NPtUlJCVGnAeBK1J1nG3TQicqowOXoM6ISkdaXj5GPJdXHab2+S7cqhKGv5qC7rR\n\
1197 jT6sx7RUr0CNTxzLI7muV2/a4tGmj0PSdXQdsZ7tw7gbXlaWT1+MM2MCAQI=\n\
1198 -----END DH PARAMETERS-----\n";
1200 static const struct dhinfo tlso_dhpem[] = {
1201 { 512, tlso_dhpem512, sizeof(tlso_dhpem512) },
1202 { 1024, tlso_dhpem1024, sizeof(tlso_dhpem1024) },
1203 { 2048, tlso_dhpem2048, sizeof(tlso_dhpem2048) },
1204 { 4096, tlso_dhpem4096, sizeof(tlso_dhpem4096) },
1209 tlso_tmp_dh_cb( SSL *ssl, int is_export, int key_length )
1211 struct dhplist *p = NULL;
1216 /* Do we have params of this length already? */
1217 #ifdef LDAP_R_COMPILE
1218 ldap_pvt_thread_mutex_lock( &tlso_dh_mutex );
1220 for ( p = tlso_dhparams; p; p=p->next ) {
1221 if ( p->keylength == key_length ) {
1222 #ifdef LDAP_R_COMPILE
1223 ldap_pvt_thread_mutex_unlock( &tlso_dh_mutex );
1229 /* No - check for hardcoded params */
1231 for (i=0; tlso_dhpem[i].keylength; i++) {
1232 if ( tlso_dhpem[i].keylength == key_length ) {
1233 b = BIO_new_mem_buf( (char *)tlso_dhpem[i].pem, tlso_dhpem[i].size );
1239 dh = PEM_read_bio_DHparams( b, NULL, NULL, NULL );
1243 /* Generating on the fly is expensive/slow... */
1245 dh = DH_generate_parameters( key_length, DH_GENERATOR_2, NULL, NULL );
1248 p = LDAP_MALLOC( sizeof(struct dhplist) );
1250 p->keylength = key_length;
1252 p->next = tlso_dhparams;
1257 #ifdef LDAP_R_COMPILE
1258 ldap_pvt_thread_mutex_unlock( &tlso_dh_mutex );
1263 tls_impl ldap_int_tls_impl = {
1275 tlso_session_connect,
1276 tlso_session_accept,
1277 tlso_session_upflags,
1278 tlso_session_errmsg,
1280 tlso_session_peer_dn,
1281 tlso_session_chkhost,
1282 tlso_session_strength,
1286 #ifdef LDAP_R_COMPILE
1295 #endif /* HAVE_OPENSSL */