1 /* tls_o.c - Handle tls/ssl using OpenSSL */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 2008-2013 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 /* From the OpenSSL 0.9.7 distro */
63 static const char tlso_dhpem1024[] =
64 "-----BEGIN DH PARAMETERS-----\n\
65 MIGHAoGBAJf2QmHKtQXdKCjhPx1ottPb0PMTBH9A6FbaWMsTuKG/K3g6TG1Z1fkq\n\
66 /Gz/PWk/eLI9TzFgqVAuPvr3q14a1aZeVUMTgo2oO5/y2UHe6VaJ+trqCTat3xlx\n\
67 /mNbIK9HA2RgPC3gWfVLZQrY+gz3ASHHR5nXWHEyvpuZm7m3h+irAgEC\n\
68 -----END DH PARAMETERS-----\n";
70 static int tlso_seed_PRNG( const char *randfile );
74 * provide mutexes for the OpenSSL library.
76 static ldap_pvt_thread_mutex_t tlso_mutexes[CRYPTO_NUM_LOCKS];
78 static void tlso_locking_cb( int mode, int type, const char *file, int line )
80 if ( mode & CRYPTO_LOCK ) {
81 ldap_pvt_thread_mutex_lock( &tlso_mutexes[type] );
83 ldap_pvt_thread_mutex_unlock( &tlso_mutexes[type] );
87 static unsigned long tlso_thread_self( void )
89 /* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
90 * is an integral type that fits in an unsigned long
93 /* force an error if the ldap_pvt_thread_t type is too large */
94 enum { ok = sizeof( ldap_pvt_thread_t ) <= sizeof( unsigned long ) };
95 typedef struct { int dummy: ok ? 1 : -1; } Check[ok ? 1 : -1];
97 return (unsigned long) ldap_pvt_thread_self();
100 static void tlso_thr_init( void )
104 for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
105 ldap_pvt_thread_mutex_init( &tlso_mutexes[i] );
107 CRYPTO_set_locking_callback( tlso_locking_cb );
108 CRYPTO_set_id_callback( tlso_thread_self );
110 #endif /* LDAP_R_COMPILE */
112 static STACK_OF(X509_NAME) *
113 tlso_ca_list( char * bundle, char * dir )
115 STACK_OF(X509_NAME) *ca_list = NULL;
118 ca_list = SSL_load_client_CA_file( bundle );
120 #if defined(HAVE_DIRENT_H) || defined(dirent)
125 ca_list = sk_X509_NAME_new_null();
128 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
130 sk_X509_NAME_free( ca_list );
139 * Initialize TLS subsystem. Should be called only once.
144 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
147 char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
148 if ( file ) __atoe( file );
149 (void) tlso_seed_PRNG( file );
153 (void) tlso_seed_PRNG( lo->ldo_tls_randfile );
156 SSL_load_error_strings();
158 OpenSSL_add_all_digests();
160 /* FIXME: mod_ssl does this */
161 X509V3_add_standard_extensions();
167 * Tear down the TLS subsystem. Should only be called once.
172 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
178 if ( lo->ldo_tls_randfile ) {
179 LDAP_FREE( lo->ldo_tls_randfile );
180 lo->ldo_tls_randfile = NULL;
185 tlso_ctx_new( struct ldapoptions *lo )
187 return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
191 tlso_ctx_ref( tls_ctx *ctx )
193 tlso_ctx *c = (tlso_ctx *)ctx;
194 CRYPTO_add( &c->references, 1, CRYPTO_LOCK_SSL_CTX );
198 tlso_ctx_free ( tls_ctx *ctx )
200 tlso_ctx *c = (tlso_ctx *)ctx;
205 * initialize a new TLS context
208 tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
210 tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
214 SSL_CTX_set_session_id_context( ctx,
215 (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
218 #ifdef SSL_OP_NO_TLSv1
219 #ifdef SSL_OP_NO_TLSv1_1
220 #ifdef SSL_OP_NO_TLSv1_2
221 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_2)
222 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
223 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 |
227 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_1)
228 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
229 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 );
232 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_0)
233 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
237 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
238 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 );
239 else if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 )
240 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 );
242 if ( lo->ldo_tls_ciphersuite &&
243 !SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
245 Debug( LDAP_DEBUG_ANY,
246 "TLS: could not set cipher list %s.\n",
247 lo->ldo_tls_ciphersuite, 0, 0 );
252 if (lo->ldo_tls_cacertfile != NULL || lo->ldo_tls_cacertdir != NULL) {
253 if ( !SSL_CTX_load_verify_locations( ctx,
254 lt->lt_cacertfile, lt->lt_cacertdir ) ||
255 !SSL_CTX_set_default_verify_paths( ctx ) )
257 Debug( LDAP_DEBUG_ANY, "TLS: "
258 "could not load verify locations (file:`%s',dir:`%s').\n",
259 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
260 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
267 STACK_OF(X509_NAME) *calist;
268 /* List of CA names to send to a client */
269 calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir );
271 Debug( LDAP_DEBUG_ANY, "TLS: "
272 "could not load client CA list (file:`%s',dir:`%s').\n",
273 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
274 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
280 SSL_CTX_set_client_CA_list( ctx, calist );
284 if ( lo->ldo_tls_certfile &&
285 !SSL_CTX_use_certificate_file( ctx,
286 lt->lt_certfile, SSL_FILETYPE_PEM ) )
288 Debug( LDAP_DEBUG_ANY,
289 "TLS: could not use certificate `%s'.\n",
290 lo->ldo_tls_certfile,0,0);
295 /* Key validity is checked automatically if cert has already been set */
296 if ( lo->ldo_tls_keyfile &&
297 !SSL_CTX_use_PrivateKey_file( ctx,
298 lt->lt_keyfile, SSL_FILETYPE_PEM ) )
300 Debug( LDAP_DEBUG_ANY,
301 "TLS: could not use key file `%s'.\n",
302 lo->ldo_tls_keyfile,0,0);
310 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_DH_USE );
311 if ( lo->ldo_tls_dhfile ) {
313 if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
314 Debug( LDAP_DEBUG_ANY,
315 "TLS: could not use DH parameters file `%s'.\n",
316 lo->ldo_tls_dhfile,0,0);
321 bio = BIO_new_mem_buf( tlso_dhpem1024, -1 );
323 if (!( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
324 Debug( LDAP_DEBUG_ANY,
325 "TLS: could not read DH parameters file `%s'.\n",
326 lo->ldo_tls_dhfile,0,0);
332 SSL_CTX_set_tmp_dh( ctx, dh );
335 if ( tlso_opt_trace ) {
336 SSL_CTX_set_info_callback( ctx, tlso_info_cb );
340 if ( lo->ldo_tls_require_cert ) {
342 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
343 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
344 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
348 SSL_CTX_set_verify( ctx, i,
349 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
350 tlso_verify_ok : tlso_verify_cb );
351 SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
352 #ifdef HAVE_OPENSSL_CRL
353 if ( lo->ldo_tls_crlcheck ) {
354 X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
355 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
356 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
357 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
358 X509_STORE_set_flags( x509_s,
359 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
367 tlso_session_new( tls_ctx *ctx, int is_server )
369 tlso_ctx *c = (tlso_ctx *)ctx;
370 return (tls_session *)SSL_new( c );
374 tlso_session_connect( LDAP *ld, tls_session *sess )
376 tlso_session *s = (tlso_session *)sess;
378 /* Caller expects 0 = success, OpenSSL returns 1 = success */
379 return SSL_connect( s ) - 1;
383 tlso_session_accept( tls_session *sess )
385 tlso_session *s = (tlso_session *)sess;
387 /* Caller expects 0 = success, OpenSSL returns 1 = success */
388 return SSL_accept( s ) - 1;
392 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
394 tlso_session *s = (tlso_session *)sess;
396 /* 1 was subtracted above, offset it back now */
397 rc = SSL_get_error(s, rc+1);
398 if (rc == SSL_ERROR_WANT_READ) {
399 sb->sb_trans_needs_read = 1;
402 } else if (rc == SSL_ERROR_WANT_WRITE) {
403 sb->sb_trans_needs_write = 1;
406 } else if (rc == SSL_ERROR_WANT_CONNECT) {
413 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
416 const char *certerr=NULL;
417 tlso_session *s = (tlso_session *)sess;
419 rc = ERR_peek_error();
421 ERR_error_string_n( rc, err, sizeof(err) );
422 if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) &&
423 ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
424 int certrc = SSL_get_verify_result(s);
425 certerr = (char *)X509_verify_cert_error_string(certrc);
427 snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"",
428 certerr ? certerr : "", certerr ? ")" : "" );
435 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
437 tlso_session *s = (tlso_session *)sess;
441 x = SSL_get_certificate( s );
443 if (!x) return LDAP_INVALID_CREDENTIALS;
445 xn = X509_get_subject_name(x);
446 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
447 der_dn->bv_val = xn->bytes->data;
448 /* Don't X509_free, the session is still using it */
453 tlso_get_cert( SSL *s )
455 /* If peer cert was bad, treat as if no cert was given */
456 if (SSL_get_verify_result(s)) {
459 return SSL_get_peer_certificate(s);
463 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
465 tlso_session *s = (tlso_session *)sess;
466 X509 *x = tlso_get_cert( s );
470 return LDAP_INVALID_CREDENTIALS;
472 xn = X509_get_subject_name(x);
473 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
474 der_dn->bv_val = xn->bytes->data;
479 /* what kind of hostname were we given? */
485 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
487 tlso_session *s = (tlso_session *)sess;
488 int i, ret = LDAP_LOCAL_ERROR;
492 int ntype = IS_DNS, nlen;
494 struct in6_addr addr;
499 if( ldap_int_hostname &&
500 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
502 name = ldap_int_hostname;
508 x = tlso_get_cert(s);
510 Debug( LDAP_DEBUG_ANY,
511 "TLS: unable to get peer certificate.\n",
513 /* If this was a fatal condition, things would have
514 * aborted long before now.
520 if (inet_pton(AF_INET6, name, &addr)) {
524 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
525 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
528 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
531 STACK_OF(GENERAL_NAME) *alt;
533 ex = X509_get_ext(x, i);
534 alt = X509V3_EXT_d2i(ex);
540 if (ntype == IS_DNS) {
541 domain = strchr(name, '.');
543 len2 = nlen - (domain-name);
546 n = sk_GENERAL_NAME_num(alt);
547 for (i=0; i<n; i++) {
550 gn = sk_GENERAL_NAME_value(alt, i);
551 if (gn->type == GEN_DNS) {
552 if (ntype != IS_DNS) continue;
554 sn = (char *) ASN1_STRING_data(gn->d.ia5);
555 sl = ASN1_STRING_length(gn->d.ia5);
558 if (sl == 0) continue;
560 /* Is this an exact match? */
561 if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
565 /* Is this a wildcard match? */
566 if (domain && (sn[0] == '*') && (sn[1] == '.') &&
567 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
572 } else if (gn->type == GEN_IPADD) {
573 if (ntype == IS_DNS) continue;
575 sn = (char *) ASN1_STRING_data(gn->d.ia5);
576 sl = ASN1_STRING_length(gn->d.ia5);
579 if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
583 if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
586 if (!memcmp(sn, &addr, sl)) {
592 GENERAL_NAMES_free(alt);
593 if (i < n) { /* Found a match */
599 if (ret != LDAP_SUCCESS) {
603 ASN1_STRING *cn = NULL;
606 /* find the last CN */
607 obj = OBJ_nid2obj( NID_commonName );
608 if ( !obj ) goto no_cn; /* should never happen */
610 xn = X509_get_subject_name(x);
611 navas = X509_NAME_entry_count( xn );
612 for ( i=navas-1; i>=0; i-- ) {
613 ne = X509_NAME_get_entry( xn, i );
614 if ( !OBJ_cmp( ne->object, obj )) {
615 cn = X509_NAME_ENTRY_get_data( ne );
623 Debug( LDAP_DEBUG_ANY,
624 "TLS: unable to get common name from peer certificate.\n",
626 ret = LDAP_CONNECT_ERROR;
627 if ( ld->ld_error ) {
628 LDAP_FREE( ld->ld_error );
630 ld->ld_error = LDAP_STRDUP(
631 _("TLS: unable to get CN from peer certificate"));
633 } else if ( cn->length == nlen &&
634 strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
637 } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
638 char *domain = strchr(name, '.');
642 dlen = nlen - (domain-name);
644 /* Is this a wildcard match? */
645 if ((dlen == cn->length-1) &&
646 !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
652 if( ret == LDAP_LOCAL_ERROR ) {
653 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
654 "common name in certificate (%.*s).\n",
655 name, cn->length, cn->data );
656 ret = LDAP_CONNECT_ERROR;
657 if ( ld->ld_error ) {
658 LDAP_FREE( ld->ld_error );
660 ld->ld_error = LDAP_STRDUP(
661 _("TLS: hostname does not match CN in peer certificate"));
669 tlso_session_strength( tls_session *sess )
671 tlso_session *s = (tlso_session *)sess;
673 return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
677 tlso_session_unique( tls_session *sess, struct berval *buf, int is_server)
679 tlso_session *s = (tlso_session *)sess;
681 /* Usually the client sends the finished msg. But if the
682 * session was resumed, the server sent the msg.
684 if (SSL_session_reused(s) ^ !is_server)
685 buf->bv_len = SSL_get_finished(s, buf->bv_val, buf->bv_len);
687 buf->bv_len = SSL_get_peer_finished(s, buf->bv_val, buf->bv_len);
692 * TLS support for LBER Sockbufs
696 tlso_session *session;
697 Sockbuf_IO_Desc *sbiod;
701 tlso_bio_create( BIO *b ) {
710 tlso_bio_destroy( BIO *b )
712 if ( b == NULL ) return 0;
714 b->ptr = NULL; /* sb_tls_remove() will free it */
721 tlso_bio_read( BIO *b, char *buf, int len )
726 if ( buf == NULL || len <= 0 ) return 0;
728 p = (struct tls_data *)b->ptr;
730 if ( p == NULL || p->sbiod == NULL ) {
734 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
736 BIO_clear_retry_flags( b );
738 int err = sock_errno();
739 if ( err == EAGAIN || err == EWOULDBLOCK ) {
740 BIO_set_retry_read( b );
748 tlso_bio_write( BIO *b, const char *buf, int len )
753 if ( buf == NULL || len <= 0 ) return 0;
755 p = (struct tls_data *)b->ptr;
757 if ( p == NULL || p->sbiod == NULL ) {
761 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
763 BIO_clear_retry_flags( b );
765 int err = sock_errno();
766 if ( err == EAGAIN || err == EWOULDBLOCK ) {
767 BIO_set_retry_write( b );
775 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
777 if ( cmd == BIO_CTRL_FLUSH ) {
778 /* The OpenSSL library needs this */
785 tlso_bio_gets( BIO *b, char *buf, int len )
791 tlso_bio_puts( BIO *b, const char *str )
793 return tlso_bio_write( b, str, strlen( str ) );
796 static BIO_METHOD tlso_bio_method =
798 ( 100 | 0x400 ), /* it's a source/sink BIO */
810 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
815 assert( sbiod != NULL );
817 p = LBER_MALLOC( sizeof( *p ) );
824 bio = BIO_new( &tlso_bio_method );
825 bio->ptr = (void *)p;
826 SSL_set_bio( p->session, bio, bio );
827 sbiod->sbiod_pvt = p;
832 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
836 assert( sbiod != NULL );
837 assert( sbiod->sbiod_pvt != NULL );
839 p = (struct tls_data *)sbiod->sbiod_pvt;
840 SSL_free( p->session );
841 LBER_FREE( sbiod->sbiod_pvt );
842 sbiod->sbiod_pvt = NULL;
847 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
851 assert( sbiod != NULL );
852 assert( sbiod->sbiod_pvt != NULL );
854 p = (struct tls_data *)sbiod->sbiod_pvt;
855 SSL_shutdown( p->session );
860 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
864 assert( sbiod != NULL );
865 assert( sbiod->sbiod_pvt != NULL );
867 p = (struct tls_data *)sbiod->sbiod_pvt;
869 if ( opt == LBER_SB_OPT_GET_SSL ) {
870 *((tlso_session **)arg) = p->session;
873 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
874 if( SSL_pending( p->session ) > 0 ) {
879 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
883 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
889 assert( sbiod != NULL );
890 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
892 p = (struct tls_data *)sbiod->sbiod_pvt;
894 ret = SSL_read( p->session, (char *)buf, len );
896 errno = WSAGetLastError();
898 err = SSL_get_error( p->session, ret );
899 if (err == SSL_ERROR_WANT_READ ) {
900 sbiod->sbiod_sb->sb_trans_needs_read = 1;
901 sock_errset(EWOULDBLOCK);
904 sbiod->sbiod_sb->sb_trans_needs_read = 0;
909 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
915 assert( sbiod != NULL );
916 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
918 p = (struct tls_data *)sbiod->sbiod_pvt;
920 ret = SSL_write( p->session, (char *)buf, len );
922 errno = WSAGetLastError();
924 err = SSL_get_error( p->session, ret );
925 if (err == SSL_ERROR_WANT_WRITE ) {
926 sbiod->sbiod_sb->sb_trans_needs_write = 1;
927 sock_errset(EWOULDBLOCK);
930 sbiod->sbiod_sb->sb_trans_needs_write = 0;
935 static Sockbuf_IO tlso_sbio =
937 tlso_sb_setup, /* sbi_setup */
938 tlso_sb_remove, /* sbi_remove */
939 tlso_sb_ctrl, /* sbi_ctrl */
940 tlso_sb_read, /* sbi_read */
941 tlso_sb_write, /* sbi_write */
942 tlso_sb_close /* sbi_close */
945 /* Derived from openssl/apps/s_cb.c */
947 tlso_info_cb( const SSL *ssl, int where, int ret )
951 char *state = (char *) SSL_state_string_long( (SSL *)ssl );
953 w = where & ~SSL_ST_MASK;
954 if ( w & SSL_ST_CONNECT ) {
956 } else if ( w & SSL_ST_ACCEPT ) {
964 state = LDAP_STRDUP( state );
968 if ( where & SSL_CB_LOOP ) {
969 Debug( LDAP_DEBUG_TRACE,
970 "TLS trace: %s:%s\n",
973 } else if ( where & SSL_CB_ALERT ) {
974 char *atype = (char *) SSL_alert_type_string_long( ret );
975 char *adesc = (char *) SSL_alert_desc_string_long( ret );
976 op = ( where & SSL_CB_READ ) ? "read" : "write";
979 atype = LDAP_STRDUP( atype );
983 adesc = LDAP_STRDUP( adesc );
987 Debug( LDAP_DEBUG_TRACE,
988 "TLS trace: SSL3 alert %s:%s:%s\n",
991 if ( atype ) LDAP_FREE( atype );
992 if ( adesc ) LDAP_FREE( adesc );
994 } else if ( where & SSL_CB_EXIT ) {
996 Debug( LDAP_DEBUG_TRACE,
997 "TLS trace: %s:failed in %s\n",
999 } else if ( ret < 0 ) {
1000 Debug( LDAP_DEBUG_TRACE,
1001 "TLS trace: %s:error in %s\n",
1006 if ( state ) LDAP_FREE( state );
1011 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
1020 char *certerr = NULL;
1022 cert = X509_STORE_CTX_get_current_cert( ctx );
1023 errnum = X509_STORE_CTX_get_error( ctx );
1024 errdepth = X509_STORE_CTX_get_error_depth( ctx );
1027 * X509_get_*_name return pointers to the internal copies of
1028 * those things requested. So do not free them.
1030 subject = X509_get_subject_name( cert );
1031 issuer = X509_get_issuer_name( cert );
1032 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1033 sname = X509_NAME_oneline( subject, NULL, 0 );
1034 iname = X509_NAME_oneline( issuer, NULL, 0 );
1035 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1037 if ( sname ) __etoa( sname );
1038 if ( iname ) __etoa( iname );
1040 certerr = LDAP_STRDUP( certerr );
1044 Debug( LDAP_DEBUG_TRACE,
1045 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1047 sname ? sname : "-unknown-" );
1048 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1050 Debug( LDAP_DEBUG_ANY,
1051 "TLS certificate verification: Error, %s\n",
1055 CRYPTO_free ( sname );
1057 CRYPTO_free ( iname );
1059 if ( certerr ) LDAP_FREE( certerr );
1065 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1067 (void) tlso_verify_cb( ok, ctx );
1071 /* Inspired by ERR_print_errors in OpenSSL */
1073 tlso_report_error( void )
1080 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1081 ERR_error_string_n( l, buf, sizeof( buf ) );
1084 file = LDAP_STRDUP( file );
1085 __etoa( (char *)file );
1089 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1092 if ( file ) LDAP_FREE( (void *)file );
1098 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1101 /* FIXME: Pregenerate the key on startup */
1102 /* FIXME: Who frees the key? */
1103 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1104 BIGNUM *bn = BN_new();
1107 if ( BN_set_word( bn, RSA_F4 )) {
1108 tmp_rsa = RSA_new();
1109 if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1110 RSA_free( tmp_rsa );
1117 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1121 Debug( LDAP_DEBUG_ANY,
1122 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1123 key_length, is_export ? "export" : "domestic", 0 );
1129 tlso_seed_PRNG( const char *randfile )
1131 #ifndef URANDOM_DEVICE
1132 /* no /dev/urandom (or equiv) */
1134 char buffer[MAXPATHLEN];
1136 if (randfile == NULL) {
1137 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1138 * If $HOME is not set or buffer too small to hold the pathname,
1139 * an error occurs. - From RAND_file_name() man page.
1140 * The fact is that when $HOME is NULL, .rnd is used.
1142 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1144 } else if (RAND_egd(randfile) > 0) {
1149 if (randfile == NULL) {
1150 Debug( LDAP_DEBUG_ANY,
1151 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1156 total = RAND_load_file(randfile, -1);
1158 if (RAND_status() == 0) {
1159 Debug( LDAP_DEBUG_ANY,
1160 "TLS: PRNG not been seeded with enough data\n",
1165 /* assume if there was enough bits to seed that it's okay
1166 * to write derived bits to the file
1168 RAND_write_file(randfile);
1176 tls_impl ldap_int_tls_impl = {
1188 tlso_session_connect,
1189 tlso_session_accept,
1190 tlso_session_upflags,
1191 tlso_session_errmsg,
1193 tlso_session_peer_dn,
1194 tlso_session_chkhost,
1195 tlso_session_strength,
1196 tlso_session_unique,
1200 #ifdef LDAP_R_COMPILE
1209 #endif /* HAVE_OPENSSL */