1 /* tls_o.c - Handle tls/ssl using OpenSSL */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 2008-2012 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>
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 )
50 typedef SSL_CTX tlso_ctx;
51 typedef SSL tlso_session;
53 static int tlso_opt_trace = 1;
55 static void tlso_report_error( void );
57 static void tlso_info_cb( const SSL *ssl, int where, int ret );
58 static int tlso_verify_cb( int ok, X509_STORE_CTX *ctx );
59 static int tlso_verify_ok( int ok, X509_STORE_CTX *ctx );
60 static RSA * tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
62 static DH * tlso_tmp_dh_cb( SSL *ssl, int is_export, int key_length );
64 typedef struct dhplist {
70 static dhplist *tlso_dhparams;
72 static int tlso_seed_PRNG( const char *randfile );
76 * provide mutexes for the OpenSSL library.
78 static ldap_pvt_thread_mutex_t tlso_mutexes[CRYPTO_NUM_LOCKS];
79 static ldap_pvt_thread_mutex_t tlso_dh_mutex;
81 static void tlso_locking_cb( int mode, int type, const char *file, int line )
83 if ( mode & CRYPTO_LOCK ) {
84 ldap_pvt_thread_mutex_lock( &tlso_mutexes[type] );
86 ldap_pvt_thread_mutex_unlock( &tlso_mutexes[type] );
90 static unsigned long tlso_thread_self( void )
92 /* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
93 * is an integral type that fits in an unsigned long
96 /* force an error if the ldap_pvt_thread_t type is too large */
97 enum { ok = sizeof( ldap_pvt_thread_t ) <= sizeof( unsigned long ) };
98 typedef struct { int dummy: ok ? 1 : -1; } Check[ok ? 1 : -1];
100 return (unsigned long) ldap_pvt_thread_self();
103 static void tlso_thr_init( void )
107 for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
108 ldap_pvt_thread_mutex_init( &tlso_mutexes[i] );
110 ldap_pvt_thread_mutex_init( &tlso_dh_mutex );
111 CRYPTO_set_locking_callback( tlso_locking_cb );
112 CRYPTO_set_id_callback( tlso_thread_self );
114 #endif /* LDAP_R_COMPILE */
116 static STACK_OF(X509_NAME) *
117 tlso_ca_list( char * bundle, char * dir )
119 STACK_OF(X509_NAME) *ca_list = NULL;
122 ca_list = SSL_load_client_CA_file( bundle );
124 #if defined(HAVE_DIRENT_H) || defined(dirent)
129 ca_list = sk_X509_NAME_new_null();
132 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
134 sk_X509_NAME_free( ca_list );
143 * Initialize TLS subsystem. Should be called only once.
148 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
151 char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
152 if ( file ) __atoe( file );
153 (void) tlso_seed_PRNG( file );
157 (void) tlso_seed_PRNG( lo->ldo_tls_randfile );
160 SSL_load_error_strings();
162 OpenSSL_add_all_digests();
164 /* FIXME: mod_ssl does this */
165 X509V3_add_standard_extensions();
171 * Tear down the TLS subsystem. Should only be called once.
176 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
182 if ( lo->ldo_tls_randfile ) {
183 LDAP_FREE( lo->ldo_tls_randfile );
184 lo->ldo_tls_randfile = NULL;
189 tlso_ctx_new( struct ldapoptions *lo )
191 return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
195 tlso_ctx_ref( tls_ctx *ctx )
197 tlso_ctx *c = (tlso_ctx *)ctx;
198 CRYPTO_add( &c->references, 1, CRYPTO_LOCK_SSL_CTX );
202 tlso_ctx_free ( tls_ctx *ctx )
204 tlso_ctx *c = (tlso_ctx *)ctx;
209 * initialize a new TLS context
212 tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
214 tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
218 SSL_CTX_set_session_id_context( ctx,
219 (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
222 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
223 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 );
224 else if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 )
225 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 );
227 if ( lo->ldo_tls_ciphersuite &&
228 !SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
230 Debug( LDAP_DEBUG_ANY,
231 "TLS: could not set cipher list %s.\n",
232 lo->ldo_tls_ciphersuite, 0, 0 );
237 if (lo->ldo_tls_cacertfile != NULL || lo->ldo_tls_cacertdir != NULL) {
238 if ( !SSL_CTX_load_verify_locations( ctx,
239 lt->lt_cacertfile, lt->lt_cacertdir ) ||
240 !SSL_CTX_set_default_verify_paths( ctx ) )
242 Debug( LDAP_DEBUG_ANY, "TLS: "
243 "could not load verify locations (file:`%s',dir:`%s').\n",
244 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
245 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
252 STACK_OF(X509_NAME) *calist;
253 /* List of CA names to send to a client */
254 calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir );
256 Debug( LDAP_DEBUG_ANY, "TLS: "
257 "could not load client CA list (file:`%s',dir:`%s').\n",
258 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
259 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
265 SSL_CTX_set_client_CA_list( ctx, calist );
269 if ( lo->ldo_tls_certfile &&
270 !SSL_CTX_use_certificate_file( ctx,
271 lt->lt_certfile, SSL_FILETYPE_PEM ) )
273 Debug( LDAP_DEBUG_ANY,
274 "TLS: could not use certificate `%s'.\n",
275 lo->ldo_tls_certfile,0,0);
280 /* Key validity is checked automatically if cert has already been set */
281 if ( lo->ldo_tls_keyfile &&
282 !SSL_CTX_use_PrivateKey_file( ctx,
283 lt->lt_keyfile, SSL_FILETYPE_PEM ) )
285 Debug( LDAP_DEBUG_ANY,
286 "TLS: could not use key file `%s'.\n",
287 lo->ldo_tls_keyfile,0,0);
292 if ( lo->ldo_tls_dhfile ) {
297 if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
298 Debug( LDAP_DEBUG_ANY,
299 "TLS: could not use DH parameters file `%s'.\n",
300 lo->ldo_tls_dhfile,0,0);
304 while (( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
305 p = LDAP_MALLOC( sizeof(dhplist) );
307 p->keylength = DH_size( dh ) * 8;
309 p->next = tlso_dhparams;
316 if ( tlso_opt_trace ) {
317 SSL_CTX_set_info_callback( ctx, tlso_info_cb );
321 if ( lo->ldo_tls_require_cert ) {
323 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
324 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
325 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
329 SSL_CTX_set_verify( ctx, i,
330 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
331 tlso_verify_ok : tlso_verify_cb );
332 SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
333 if ( lo->ldo_tls_dhfile ) {
334 SSL_CTX_set_tmp_dh_callback( ctx, tlso_tmp_dh_cb );
336 #ifdef HAVE_OPENSSL_CRL
337 if ( lo->ldo_tls_crlcheck ) {
338 X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
339 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
340 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
341 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
342 X509_STORE_set_flags( x509_s,
343 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
351 tlso_session_new( tls_ctx *ctx, int is_server )
353 tlso_ctx *c = (tlso_ctx *)ctx;
354 return (tls_session *)SSL_new( c );
358 tlso_session_connect( LDAP *ld, tls_session *sess )
360 tlso_session *s = (tlso_session *)sess;
362 /* Caller expects 0 = success, OpenSSL returns 1 = success */
363 return SSL_connect( s ) - 1;
367 tlso_session_accept( tls_session *sess )
369 tlso_session *s = (tlso_session *)sess;
371 /* Caller expects 0 = success, OpenSSL returns 1 = success */
372 return SSL_accept( s ) - 1;
376 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
378 tlso_session *s = (tlso_session *)sess;
380 /* 1 was subtracted above, offset it back now */
381 rc = SSL_get_error(s, rc+1);
382 if (rc == SSL_ERROR_WANT_READ) {
383 sb->sb_trans_needs_read = 1;
386 } else if (rc == SSL_ERROR_WANT_WRITE) {
387 sb->sb_trans_needs_write = 1;
390 } else if (rc == SSL_ERROR_WANT_CONNECT) {
397 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
400 const char *certerr=NULL;
401 tlso_session *s = (tlso_session *)sess;
403 rc = ERR_peek_error();
405 ERR_error_string_n( rc, err, sizeof(err) );
406 if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) &&
407 ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
408 int certrc = SSL_get_verify_result(s);
409 certerr = (char *)X509_verify_cert_error_string(certrc);
411 snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"",
412 certerr ? certerr : "", certerr ? ")" : "" );
419 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
421 tlso_session *s = (tlso_session *)sess;
425 x = SSL_get_certificate( s );
427 if (!x) return LDAP_INVALID_CREDENTIALS;
429 xn = X509_get_subject_name(x);
430 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
431 der_dn->bv_val = xn->bytes->data;
432 /* Don't X509_free, the session is still using it */
437 tlso_get_cert( SSL *s )
439 /* If peer cert was bad, treat as if no cert was given */
440 if (SSL_get_verify_result(s)) {
443 return SSL_get_peer_certificate(s);
447 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
449 tlso_session *s = (tlso_session *)sess;
450 X509 *x = tlso_get_cert( s );
454 return LDAP_INVALID_CREDENTIALS;
456 xn = X509_get_subject_name(x);
457 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
458 der_dn->bv_val = xn->bytes->data;
463 /* what kind of hostname were we given? */
469 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
471 tlso_session *s = (tlso_session *)sess;
472 int i, ret = LDAP_LOCAL_ERROR;
476 int ntype = IS_DNS, nlen;
478 struct in6_addr addr;
483 if( ldap_int_hostname &&
484 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
486 name = ldap_int_hostname;
492 x = tlso_get_cert(s);
494 Debug( LDAP_DEBUG_ANY,
495 "TLS: unable to get peer certificate.\n",
497 /* If this was a fatal condition, things would have
498 * aborted long before now.
504 if (inet_pton(AF_INET6, name, &addr)) {
508 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
509 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
512 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
515 STACK_OF(GENERAL_NAME) *alt;
517 ex = X509_get_ext(x, i);
518 alt = X509V3_EXT_d2i(ex);
524 if (ntype == IS_DNS) {
525 domain = strchr(name, '.');
527 len2 = nlen - (domain-name);
530 n = sk_GENERAL_NAME_num(alt);
531 for (i=0; i<n; i++) {
534 gn = sk_GENERAL_NAME_value(alt, i);
535 if (gn->type == GEN_DNS) {
536 if (ntype != IS_DNS) continue;
538 sn = (char *) ASN1_STRING_data(gn->d.ia5);
539 sl = ASN1_STRING_length(gn->d.ia5);
542 if (sl == 0) continue;
544 /* Is this an exact match? */
545 if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
549 /* Is this a wildcard match? */
550 if (domain && (sn[0] == '*') && (sn[1] == '.') &&
551 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
556 } else if (gn->type == GEN_IPADD) {
557 if (ntype == IS_DNS) continue;
559 sn = (char *) ASN1_STRING_data(gn->d.ia5);
560 sl = ASN1_STRING_length(gn->d.ia5);
563 if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
567 if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
570 if (!memcmp(sn, &addr, sl)) {
576 GENERAL_NAMES_free(alt);
577 if (i < n) { /* Found a match */
583 if (ret != LDAP_SUCCESS) {
587 ASN1_STRING *cn = NULL;
590 /* find the last CN */
591 obj = OBJ_nid2obj( NID_commonName );
592 if ( !obj ) goto no_cn; /* should never happen */
594 xn = X509_get_subject_name(x);
595 navas = X509_NAME_entry_count( xn );
596 for ( i=navas-1; i>=0; i-- ) {
597 ne = X509_NAME_get_entry( xn, i );
598 if ( !OBJ_cmp( ne->object, obj )) {
599 cn = X509_NAME_ENTRY_get_data( ne );
607 Debug( LDAP_DEBUG_ANY,
608 "TLS: unable to get common name from peer certificate.\n",
610 ret = LDAP_CONNECT_ERROR;
611 if ( ld->ld_error ) {
612 LDAP_FREE( ld->ld_error );
614 ld->ld_error = LDAP_STRDUP(
615 _("TLS: unable to get CN from peer certificate"));
617 } else if ( cn->length == nlen &&
618 strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
621 } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
622 char *domain = strchr(name, '.');
626 dlen = nlen - (domain-name);
628 /* Is this a wildcard match? */
629 if ((dlen == cn->length-1) &&
630 !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
636 if( ret == LDAP_LOCAL_ERROR ) {
637 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
638 "common name in certificate (%.*s).\n",
639 name, cn->length, cn->data );
640 ret = LDAP_CONNECT_ERROR;
641 if ( ld->ld_error ) {
642 LDAP_FREE( ld->ld_error );
644 ld->ld_error = LDAP_STRDUP(
645 _("TLS: hostname does not match CN in peer certificate"));
653 tlso_session_strength( tls_session *sess )
655 tlso_session *s = (tlso_session *)sess;
657 return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
661 * TLS support for LBER Sockbufs
665 tlso_session *session;
666 Sockbuf_IO_Desc *sbiod;
670 tlso_bio_create( BIO *b ) {
679 tlso_bio_destroy( BIO *b )
681 if ( b == NULL ) return 0;
683 b->ptr = NULL; /* sb_tls_remove() will free it */
690 tlso_bio_read( BIO *b, char *buf, int len )
695 if ( buf == NULL || len <= 0 ) return 0;
697 p = (struct tls_data *)b->ptr;
699 if ( p == NULL || p->sbiod == NULL ) {
703 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
705 BIO_clear_retry_flags( b );
707 int err = sock_errno();
708 if ( err == EAGAIN || err == EWOULDBLOCK ) {
709 BIO_set_retry_read( b );
717 tlso_bio_write( BIO *b, const char *buf, int len )
722 if ( buf == NULL || len <= 0 ) return 0;
724 p = (struct tls_data *)b->ptr;
726 if ( p == NULL || p->sbiod == NULL ) {
730 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
732 BIO_clear_retry_flags( b );
734 int err = sock_errno();
735 if ( err == EAGAIN || err == EWOULDBLOCK ) {
736 BIO_set_retry_write( b );
744 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
746 if ( cmd == BIO_CTRL_FLUSH ) {
747 /* The OpenSSL library needs this */
754 tlso_bio_gets( BIO *b, char *buf, int len )
760 tlso_bio_puts( BIO *b, const char *str )
762 return tlso_bio_write( b, str, strlen( str ) );
765 static BIO_METHOD tlso_bio_method =
767 ( 100 | 0x400 ), /* it's a source/sink BIO */
779 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
784 assert( sbiod != NULL );
786 p = LBER_MALLOC( sizeof( *p ) );
793 bio = BIO_new( &tlso_bio_method );
794 bio->ptr = (void *)p;
795 SSL_set_bio( p->session, bio, bio );
796 sbiod->sbiod_pvt = p;
801 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
805 assert( sbiod != NULL );
806 assert( sbiod->sbiod_pvt != NULL );
808 p = (struct tls_data *)sbiod->sbiod_pvt;
809 SSL_free( p->session );
810 LBER_FREE( sbiod->sbiod_pvt );
811 sbiod->sbiod_pvt = NULL;
816 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
820 assert( sbiod != NULL );
821 assert( sbiod->sbiod_pvt != NULL );
823 p = (struct tls_data *)sbiod->sbiod_pvt;
824 SSL_shutdown( p->session );
829 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
833 assert( sbiod != NULL );
834 assert( sbiod->sbiod_pvt != NULL );
836 p = (struct tls_data *)sbiod->sbiod_pvt;
838 if ( opt == LBER_SB_OPT_GET_SSL ) {
839 *((tlso_session **)arg) = p->session;
842 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
843 if( SSL_pending( p->session ) > 0 ) {
848 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
852 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
858 assert( sbiod != NULL );
859 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
861 p = (struct tls_data *)sbiod->sbiod_pvt;
863 ret = SSL_read( p->session, (char *)buf, len );
865 errno = WSAGetLastError();
867 err = SSL_get_error( p->session, ret );
868 if (err == SSL_ERROR_WANT_READ ) {
869 sbiod->sbiod_sb->sb_trans_needs_read = 1;
870 sock_errset(EWOULDBLOCK);
873 sbiod->sbiod_sb->sb_trans_needs_read = 0;
878 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
884 assert( sbiod != NULL );
885 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
887 p = (struct tls_data *)sbiod->sbiod_pvt;
889 ret = SSL_write( p->session, (char *)buf, len );
891 errno = WSAGetLastError();
893 err = SSL_get_error( p->session, ret );
894 if (err == SSL_ERROR_WANT_WRITE ) {
895 sbiod->sbiod_sb->sb_trans_needs_write = 1;
896 sock_errset(EWOULDBLOCK);
899 sbiod->sbiod_sb->sb_trans_needs_write = 0;
904 static Sockbuf_IO tlso_sbio =
906 tlso_sb_setup, /* sbi_setup */
907 tlso_sb_remove, /* sbi_remove */
908 tlso_sb_ctrl, /* sbi_ctrl */
909 tlso_sb_read, /* sbi_read */
910 tlso_sb_write, /* sbi_write */
911 tlso_sb_close /* sbi_close */
914 /* Derived from openssl/apps/s_cb.c */
916 tlso_info_cb( const SSL *ssl, int where, int ret )
920 char *state = (char *) SSL_state_string_long( (SSL *)ssl );
922 w = where & ~SSL_ST_MASK;
923 if ( w & SSL_ST_CONNECT ) {
925 } else if ( w & SSL_ST_ACCEPT ) {
933 state = LDAP_STRDUP( state );
937 if ( where & SSL_CB_LOOP ) {
938 Debug( LDAP_DEBUG_TRACE,
939 "TLS trace: %s:%s\n",
942 } else if ( where & SSL_CB_ALERT ) {
943 char *atype = (char *) SSL_alert_type_string_long( ret );
944 char *adesc = (char *) SSL_alert_desc_string_long( ret );
945 op = ( where & SSL_CB_READ ) ? "read" : "write";
948 atype = LDAP_STRDUP( atype );
952 adesc = LDAP_STRDUP( adesc );
956 Debug( LDAP_DEBUG_TRACE,
957 "TLS trace: SSL3 alert %s:%s:%s\n",
960 if ( atype ) LDAP_FREE( atype );
961 if ( adesc ) LDAP_FREE( adesc );
963 } else if ( where & SSL_CB_EXIT ) {
965 Debug( LDAP_DEBUG_TRACE,
966 "TLS trace: %s:failed in %s\n",
968 } else if ( ret < 0 ) {
969 Debug( LDAP_DEBUG_TRACE,
970 "TLS trace: %s:error in %s\n",
975 if ( state ) LDAP_FREE( state );
980 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
989 char *certerr = NULL;
991 cert = X509_STORE_CTX_get_current_cert( ctx );
992 errnum = X509_STORE_CTX_get_error( ctx );
993 errdepth = X509_STORE_CTX_get_error_depth( ctx );
996 * X509_get_*_name return pointers to the internal copies of
997 * those things requested. So do not free them.
999 subject = X509_get_subject_name( cert );
1000 issuer = X509_get_issuer_name( cert );
1001 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1002 sname = X509_NAME_oneline( subject, NULL, 0 );
1003 iname = X509_NAME_oneline( issuer, NULL, 0 );
1004 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1006 if ( sname ) __etoa( sname );
1007 if ( iname ) __etoa( iname );
1009 certerr = LDAP_STRDUP( certerr );
1013 Debug( LDAP_DEBUG_TRACE,
1014 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1016 sname ? sname : "-unknown-" );
1017 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1019 Debug( LDAP_DEBUG_ANY,
1020 "TLS certificate verification: Error, %s\n",
1024 CRYPTO_free ( sname );
1026 CRYPTO_free ( iname );
1028 if ( certerr ) LDAP_FREE( certerr );
1034 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1036 (void) tlso_verify_cb( ok, ctx );
1040 /* Inspired by ERR_print_errors in OpenSSL */
1042 tlso_report_error( void )
1049 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1050 ERR_error_string_n( l, buf, sizeof( buf ) );
1053 file = LDAP_STRDUP( file );
1054 __etoa( (char *)file );
1058 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1061 if ( file ) LDAP_FREE( (void *)file );
1067 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1070 /* FIXME: Pregenerate the key on startup */
1071 /* FIXME: Who frees the key? */
1072 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1073 BIGNUM *bn = BN_new();
1076 if ( BN_set_word( bn, RSA_F4 )) {
1077 tmp_rsa = RSA_new();
1078 if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1079 RSA_free( tmp_rsa );
1086 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1090 Debug( LDAP_DEBUG_ANY,
1091 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1092 key_length, is_export ? "export" : "domestic", 0 );
1098 tlso_seed_PRNG( const char *randfile )
1100 #ifndef URANDOM_DEVICE
1101 /* no /dev/urandom (or equiv) */
1103 char buffer[MAXPATHLEN];
1105 if (randfile == NULL) {
1106 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1107 * If $HOME is not set or buffer too small to hold the pathname,
1108 * an error occurs. - From RAND_file_name() man page.
1109 * The fact is that when $HOME is NULL, .rnd is used.
1111 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1113 } else if (RAND_egd(randfile) > 0) {
1118 if (randfile == NULL) {
1119 Debug( LDAP_DEBUG_ANY,
1120 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1125 total = RAND_load_file(randfile, -1);
1127 if (RAND_status() == 0) {
1128 Debug( LDAP_DEBUG_ANY,
1129 "TLS: PRNG not been seeded with enough data\n",
1134 /* assume if there was enough bits to seed that it's okay
1135 * to write derived bits to the file
1137 RAND_write_file(randfile);
1151 /* From the OpenSSL 0.9.7 distro */
1152 static const char tlso_dhpem512[] =
1153 "-----BEGIN DH PARAMETERS-----\n\
1154 MEYCQQDaWDwW2YUiidDkr3VvTMqS3UvlM7gE+w/tlO+cikQD7VdGUNNpmdsp13Yn\n\
1155 a6LT1BLiGPTdHghM9tgAPnxHdOgzAgEC\n\
1156 -----END DH PARAMETERS-----\n";
1158 static const char tlso_dhpem1024[] =
1159 "-----BEGIN DH PARAMETERS-----\n\
1160 MIGHAoGBAJf2QmHKtQXdKCjhPx1ottPb0PMTBH9A6FbaWMsTuKG/K3g6TG1Z1fkq\n\
1161 /Gz/PWk/eLI9TzFgqVAuPvr3q14a1aZeVUMTgo2oO5/y2UHe6VaJ+trqCTat3xlx\n\
1162 /mNbIK9HA2RgPC3gWfVLZQrY+gz3ASHHR5nXWHEyvpuZm7m3h+irAgEC\n\
1163 -----END DH PARAMETERS-----\n";
1165 static const char tlso_dhpem2048[] =
1166 "-----BEGIN DH PARAMETERS-----\n\
1167 MIIBCAKCAQEA7ZKJNYJFVcs7+6J2WmkEYb8h86tT0s0h2v94GRFS8Q7B4lW9aG9o\n\
1168 AFO5Imov5Jo0H2XMWTKKvbHbSe3fpxJmw/0hBHAY8H/W91hRGXKCeyKpNBgdL8sh\n\
1169 z22SrkO2qCnHJ6PLAMXy5fsKpFmFor2tRfCzrfnggTXu2YOzzK7q62bmqVdmufEo\n\
1170 pT8igNcLpvZxk5uBDvhakObMym9mX3rAEBoe8PwttggMYiiw7NuJKO4MqD1llGkW\n\
1171 aVM8U2ATsCun1IKHrRxynkE1/MJ86VHeYYX8GZt2YA8z+GuzylIOKcMH6JAWzMwA\n\
1172 Gbatw6QwizOhr9iMjZ0B26TE3X8LvW84wwIBAg==\n\
1173 -----END DH PARAMETERS-----\n";
1175 static const char tlso_dhpem4096[] =
1176 "-----BEGIN DH PARAMETERS-----\n\
1177 MIICCAKCAgEA/urRnb6vkPYc/KEGXWnbCIOaKitq7ySIq9dTH7s+Ri59zs77zty7\n\
1178 vfVlSe6VFTBWgYjD2XKUFmtqq6CqXMhVX5ElUDoYDpAyTH85xqNFLzFC7nKrff/H\n\
1179 TFKNttp22cZE9V0IPpzedPfnQkE7aUdmF9JnDyv21Z/818O93u1B4r0szdnmEvEF\n\
1180 bKuIxEHX+bp0ZR7RqE1AeifXGJX3d6tsd2PMAObxwwsv55RGkn50vHO4QxtTARr1\n\
1181 rRUV5j3B3oPMgC7Offxx+98Xn45B1/G0Prp11anDsR1PGwtaCYipqsvMwQUSJtyE\n\
1182 EOQWk+yFkeMe4vWv367eEi0Sd/wnC+TSXBE3pYvpYerJ8n1MceI5GQTdarJ77OW9\n\
1183 bGTHmxRsLSCM1jpLdPja5jjb4siAa6EHc4qN9c/iFKS3PQPJEnX7pXKBRs5f7AF3\n\
1184 W3RIGt+G9IVNZfXaS7Z/iCpgzgvKCs0VeqN38QsJGtC1aIkwOeyjPNy2G6jJ4yqH\n\
1185 ovXYt/0mc00vCWeSNS1wren0pR2EiLxX0ypjjgsU1mk/Z3b/+zVf7fZSIB+nDLjb\n\
1186 NPtUlJCVGnAeBK1J1nG3TQicqowOXoM6ISkdaXj5GPJdXHab2+S7cqhKGv5qC7rR\n\
1187 jT6sx7RUr0CNTxzLI7muV2/a4tGmj0PSdXQdsZ7tw7gbXlaWT1+MM2MCAQI=\n\
1188 -----END DH PARAMETERS-----\n";
1190 static const struct dhinfo tlso_dhpem[] = {
1191 { 512, tlso_dhpem512, sizeof(tlso_dhpem512) },
1192 { 1024, tlso_dhpem1024, sizeof(tlso_dhpem1024) },
1193 { 2048, tlso_dhpem2048, sizeof(tlso_dhpem2048) },
1194 { 4096, tlso_dhpem4096, sizeof(tlso_dhpem4096) },
1199 tlso_tmp_dh_cb( SSL *ssl, int is_export, int key_length )
1201 struct dhplist *p = NULL;
1206 /* Do we have params of this length already? */
1207 LDAP_MUTEX_LOCK( &tlso_dh_mutex );
1208 for ( p = tlso_dhparams; p; p=p->next ) {
1209 if ( p->keylength == key_length ) {
1210 LDAP_MUTEX_UNLOCK( &tlso_dh_mutex );
1215 /* No - check for hardcoded params */
1217 for (i=0; tlso_dhpem[i].keylength; i++) {
1218 if ( tlso_dhpem[i].keylength == key_length ) {
1219 b = BIO_new_mem_buf( (char *)tlso_dhpem[i].pem, tlso_dhpem[i].size );
1225 dh = PEM_read_bio_DHparams( b, NULL, NULL, NULL );
1229 /* Generating on the fly is expensive/slow... */
1231 dh = DH_generate_parameters( key_length, DH_GENERATOR_2, NULL, NULL );
1234 p = LDAP_MALLOC( sizeof(struct dhplist) );
1236 p->keylength = key_length;
1238 p->next = tlso_dhparams;
1243 LDAP_MUTEX_UNLOCK( &tlso_dh_mutex );
1247 tls_impl ldap_int_tls_impl = {
1259 tlso_session_connect,
1260 tlso_session_accept,
1261 tlso_session_upflags,
1262 tlso_session_errmsg,
1264 tlso_session_peer_dn,
1265 tlso_session_chkhost,
1266 tlso_session_strength,
1270 #ifdef LDAP_R_COMPILE
1279 #endif /* HAVE_OPENSSL */