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 static int tlso_seed_PRNG( const char *randfile );
66 * provide mutexes for the OpenSSL library.
68 static ldap_pvt_thread_mutex_t tlso_mutexes[CRYPTO_NUM_LOCKS];
70 static void tlso_locking_cb( int mode, int type, const char *file, int line )
72 if ( mode & CRYPTO_LOCK ) {
73 ldap_pvt_thread_mutex_lock( &tlso_mutexes[type] );
75 ldap_pvt_thread_mutex_unlock( &tlso_mutexes[type] );
79 static unsigned long tlso_thread_self( void )
81 /* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
82 * is an integral type that fits in an unsigned long
85 /* force an error if the ldap_pvt_thread_t type is too large */
86 enum { ok = sizeof( ldap_pvt_thread_t ) <= sizeof( unsigned long ) };
87 typedef struct { int dummy: ok ? 1 : -1; } Check[ok ? 1 : -1];
89 return (unsigned long) ldap_pvt_thread_self();
92 static void tlso_thr_init( void )
96 for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
97 ldap_pvt_thread_mutex_init( &tlso_mutexes[i] );
99 CRYPTO_set_locking_callback( tlso_locking_cb );
100 CRYPTO_set_id_callback( tlso_thread_self );
102 #endif /* LDAP_R_COMPILE */
104 static STACK_OF(X509_NAME) *
105 tlso_ca_list( char * bundle, char * dir )
107 STACK_OF(X509_NAME) *ca_list = NULL;
110 ca_list = SSL_load_client_CA_file( bundle );
112 #if defined(HAVE_DIRENT_H) || defined(dirent)
117 ca_list = sk_X509_NAME_new_null();
120 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
122 sk_X509_NAME_free( ca_list );
131 * Initialize TLS subsystem. Should be called only once.
136 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
139 char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
140 if ( file ) __atoe( file );
141 (void) tlso_seed_PRNG( file );
145 (void) tlso_seed_PRNG( lo->ldo_tls_randfile );
148 SSL_load_error_strings();
150 OpenSSL_add_all_digests();
152 /* FIXME: mod_ssl does this */
153 X509V3_add_standard_extensions();
159 * Tear down the TLS subsystem. Should only be called once.
164 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
170 if ( lo->ldo_tls_randfile ) {
171 LDAP_FREE( lo->ldo_tls_randfile );
172 lo->ldo_tls_randfile = NULL;
177 tlso_ctx_new( struct ldapoptions *lo )
179 return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
183 tlso_ctx_ref( tls_ctx *ctx )
185 tlso_ctx *c = (tlso_ctx *)ctx;
186 CRYPTO_add( &c->references, 1, CRYPTO_LOCK_SSL_CTX );
190 tlso_ctx_free ( tls_ctx *ctx )
192 tlso_ctx *c = (tlso_ctx *)ctx;
197 * initialize a new TLS context
200 tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
202 tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
206 SSL_CTX_set_session_id_context( ctx,
207 (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
210 #ifdef SSL_OP_NO_TLSv1
211 #ifdef SSL_OP_NO_TLSv1_1
212 #ifdef SSL_OP_NO_TLSv1_2
213 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_2)
214 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
215 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 |
219 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_1)
220 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
221 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 );
224 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_0)
225 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
229 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
230 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 );
231 else if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 )
232 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 );
234 if ( lo->ldo_tls_ciphersuite &&
235 !SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
237 Debug( LDAP_DEBUG_ANY,
238 "TLS: could not set cipher list %s.\n",
239 lo->ldo_tls_ciphersuite, 0, 0 );
244 if (lo->ldo_tls_cacertfile != NULL || lo->ldo_tls_cacertdir != NULL) {
245 if ( !SSL_CTX_load_verify_locations( ctx,
246 lt->lt_cacertfile, lt->lt_cacertdir ) ||
247 !SSL_CTX_set_default_verify_paths( ctx ) )
249 Debug( LDAP_DEBUG_ANY, "TLS: "
250 "could not load verify locations (file:`%s',dir:`%s').\n",
251 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
252 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
259 STACK_OF(X509_NAME) *calist;
260 /* List of CA names to send to a client */
261 calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir );
263 Debug( LDAP_DEBUG_ANY, "TLS: "
264 "could not load client CA list (file:`%s',dir:`%s').\n",
265 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
266 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
272 SSL_CTX_set_client_CA_list( ctx, calist );
276 if ( lo->ldo_tls_certfile &&
277 !SSL_CTX_use_certificate_file( ctx,
278 lt->lt_certfile, SSL_FILETYPE_PEM ) )
280 Debug( LDAP_DEBUG_ANY,
281 "TLS: could not use certificate `%s'.\n",
282 lo->ldo_tls_certfile,0,0);
287 /* Key validity is checked automatically if cert has already been set */
288 if ( lo->ldo_tls_keyfile &&
289 !SSL_CTX_use_PrivateKey_file( ctx,
290 lt->lt_keyfile, SSL_FILETYPE_PEM ) )
292 Debug( LDAP_DEBUG_ANY,
293 "TLS: could not use key file `%s'.\n",
294 lo->ldo_tls_keyfile,0,0);
299 if ( is_server && lo->ldo_tls_dhfile ) {
303 if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
304 Debug( LDAP_DEBUG_ANY,
305 "TLS: could not use DH parameters file `%s'.\n",
306 lo->ldo_tls_dhfile,0,0);
310 if (!( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
311 Debug( LDAP_DEBUG_ANY,
312 "TLS: could not read DH parameters file `%s'.\n",
313 lo->ldo_tls_dhfile,0,0);
319 SSL_CTX_set_tmp_dh( ctx, dh );
320 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_DH_USE );
324 if ( is_server && lo->ldo_tls_ecname ) {
326 Debug( LDAP_DEBUG_ANY,
327 "TLS: Elliptic Curves not supported.\n", 0,0,0 );
332 int nid = OBJ_sn2nid( lt->lt_ecname );
333 if ( nid == NID_undef ) {
334 Debug( LDAP_DEBUG_ANY,
335 "TLS: could not use EC name `%s'.\n",
336 lo->ldo_tls_ecname,0,0);
340 ecdh = EC_KEY_new_by_curve_name( nid );
341 if ( ecdh == NULL ) {
342 Debug( LDAP_DEBUG_ANY,
343 "TLS: could not generate key for EC name `%s'.\n",
344 lo->ldo_tls_ecname,0,0);
348 SSL_CTX_set_tmp_ecdh( ctx, ecdh );
349 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_ECDH_USE );
354 if ( tlso_opt_trace ) {
355 SSL_CTX_set_info_callback( ctx, tlso_info_cb );
359 if ( lo->ldo_tls_require_cert ) {
361 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
362 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
363 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
367 SSL_CTX_set_verify( ctx, i,
368 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
369 tlso_verify_ok : tlso_verify_cb );
370 SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
371 #ifdef HAVE_OPENSSL_CRL
372 if ( lo->ldo_tls_crlcheck ) {
373 X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
374 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
375 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
376 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
377 X509_STORE_set_flags( x509_s,
378 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
386 tlso_session_new( tls_ctx *ctx, int is_server )
388 tlso_ctx *c = (tlso_ctx *)ctx;
389 return (tls_session *)SSL_new( c );
393 tlso_session_connect( LDAP *ld, tls_session *sess )
395 tlso_session *s = (tlso_session *)sess;
397 /* Caller expects 0 = success, OpenSSL returns 1 = success */
398 return SSL_connect( s ) - 1;
402 tlso_session_accept( tls_session *sess )
404 tlso_session *s = (tlso_session *)sess;
406 /* Caller expects 0 = success, OpenSSL returns 1 = success */
407 return SSL_accept( s ) - 1;
411 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
413 tlso_session *s = (tlso_session *)sess;
415 /* 1 was subtracted above, offset it back now */
416 rc = SSL_get_error(s, rc+1);
417 if (rc == SSL_ERROR_WANT_READ) {
418 sb->sb_trans_needs_read = 1;
421 } else if (rc == SSL_ERROR_WANT_WRITE) {
422 sb->sb_trans_needs_write = 1;
425 } else if (rc == SSL_ERROR_WANT_CONNECT) {
432 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
435 const char *certerr=NULL;
436 tlso_session *s = (tlso_session *)sess;
438 rc = ERR_peek_error();
440 ERR_error_string_n( rc, err, sizeof(err) );
441 if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) &&
442 ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
443 int certrc = SSL_get_verify_result(s);
444 certerr = (char *)X509_verify_cert_error_string(certrc);
446 snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"",
447 certerr ? certerr : "", certerr ? ")" : "" );
454 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
456 tlso_session *s = (tlso_session *)sess;
460 x = SSL_get_certificate( s );
462 if (!x) return LDAP_INVALID_CREDENTIALS;
464 xn = X509_get_subject_name(x);
465 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
466 der_dn->bv_val = xn->bytes->data;
467 /* Don't X509_free, the session is still using it */
472 tlso_get_cert( SSL *s )
474 /* If peer cert was bad, treat as if no cert was given */
475 if (SSL_get_verify_result(s)) {
478 return SSL_get_peer_certificate(s);
482 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
484 tlso_session *s = (tlso_session *)sess;
485 X509 *x = tlso_get_cert( s );
489 return LDAP_INVALID_CREDENTIALS;
491 xn = X509_get_subject_name(x);
492 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
493 der_dn->bv_val = xn->bytes->data;
498 /* what kind of hostname were we given? */
504 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
506 tlso_session *s = (tlso_session *)sess;
507 int i, ret = LDAP_LOCAL_ERROR;
511 int ntype = IS_DNS, nlen;
513 struct in6_addr addr;
518 if( ldap_int_hostname &&
519 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
521 name = ldap_int_hostname;
527 x = tlso_get_cert(s);
529 Debug( LDAP_DEBUG_ANY,
530 "TLS: unable to get peer certificate.\n",
532 /* If this was a fatal condition, things would have
533 * aborted long before now.
539 if (inet_pton(AF_INET6, name, &addr)) {
543 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
544 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
547 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
550 STACK_OF(GENERAL_NAME) *alt;
552 ex = X509_get_ext(x, i);
553 alt = X509V3_EXT_d2i(ex);
559 if (ntype == IS_DNS) {
560 domain = strchr(name, '.');
562 len2 = nlen - (domain-name);
565 n = sk_GENERAL_NAME_num(alt);
566 for (i=0; i<n; i++) {
569 gn = sk_GENERAL_NAME_value(alt, i);
570 if (gn->type == GEN_DNS) {
571 if (ntype != IS_DNS) continue;
573 sn = (char *) ASN1_STRING_data(gn->d.ia5);
574 sl = ASN1_STRING_length(gn->d.ia5);
577 if (sl == 0) continue;
579 /* Is this an exact match? */
580 if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
584 /* Is this a wildcard match? */
585 if (domain && (sn[0] == '*') && (sn[1] == '.') &&
586 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
591 } else if (gn->type == GEN_IPADD) {
592 if (ntype == IS_DNS) continue;
594 sn = (char *) ASN1_STRING_data(gn->d.ia5);
595 sl = ASN1_STRING_length(gn->d.ia5);
598 if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
602 if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
605 if (!memcmp(sn, &addr, sl)) {
611 GENERAL_NAMES_free(alt);
612 if (i < n) { /* Found a match */
618 if (ret != LDAP_SUCCESS) {
622 ASN1_STRING *cn = NULL;
625 /* find the last CN */
626 obj = OBJ_nid2obj( NID_commonName );
627 if ( !obj ) goto no_cn; /* should never happen */
629 xn = X509_get_subject_name(x);
630 navas = X509_NAME_entry_count( xn );
631 for ( i=navas-1; i>=0; i-- ) {
632 ne = X509_NAME_get_entry( xn, i );
633 if ( !OBJ_cmp( ne->object, obj )) {
634 cn = X509_NAME_ENTRY_get_data( ne );
642 Debug( LDAP_DEBUG_ANY,
643 "TLS: unable to get common name from peer certificate.\n",
645 ret = LDAP_CONNECT_ERROR;
646 if ( ld->ld_error ) {
647 LDAP_FREE( ld->ld_error );
649 ld->ld_error = LDAP_STRDUP(
650 _("TLS: unable to get CN from peer certificate"));
652 } else if ( cn->length == nlen &&
653 strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
656 } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
657 char *domain = strchr(name, '.');
661 dlen = nlen - (domain-name);
663 /* Is this a wildcard match? */
664 if ((dlen == cn->length-1) &&
665 !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
671 if( ret == LDAP_LOCAL_ERROR ) {
672 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
673 "common name in certificate (%.*s).\n",
674 name, cn->length, cn->data );
675 ret = LDAP_CONNECT_ERROR;
676 if ( ld->ld_error ) {
677 LDAP_FREE( ld->ld_error );
679 ld->ld_error = LDAP_STRDUP(
680 _("TLS: hostname does not match CN in peer certificate"));
688 tlso_session_strength( tls_session *sess )
690 tlso_session *s = (tlso_session *)sess;
692 return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
696 tlso_session_unique( tls_session *sess, struct berval *buf, int is_server)
698 tlso_session *s = (tlso_session *)sess;
700 /* Usually the client sends the finished msg. But if the
701 * session was resumed, the server sent the msg.
703 if (SSL_session_reused(s) ^ !is_server)
704 buf->bv_len = SSL_get_finished(s, buf->bv_val, buf->bv_len);
706 buf->bv_len = SSL_get_peer_finished(s, buf->bv_val, buf->bv_len);
711 tlso_session_version( tls_session *sess )
713 tlso_session *s = (tlso_session *)sess;
714 return SSL_get_version(s);
718 tlso_session_cipher( tls_session *sess )
720 tlso_session *s = (tlso_session *)sess;
721 return SSL_CIPHER_get_name(SSL_get_current_cipher(s));
725 tlso_session_peercert( tls_session *sess, struct berval *der )
727 tlso_session *s = (tlso_session *)sess;
729 X509 *x = SSL_get_peer_certificate(s);
730 der->bv_len = i2d_X509(x, NULL);
731 der->bv_val = LDAP_MALLOC(der->bv_len);
740 * TLS support for LBER Sockbufs
744 tlso_session *session;
745 Sockbuf_IO_Desc *sbiod;
749 tlso_bio_create( BIO *b ) {
758 tlso_bio_destroy( BIO *b )
760 if ( b == NULL ) return 0;
762 b->ptr = NULL; /* sb_tls_remove() will free it */
769 tlso_bio_read( BIO *b, char *buf, int len )
774 if ( buf == NULL || len <= 0 ) return 0;
776 p = (struct tls_data *)b->ptr;
778 if ( p == NULL || p->sbiod == NULL ) {
782 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
784 BIO_clear_retry_flags( b );
786 int err = sock_errno();
787 if ( err == EAGAIN || err == EWOULDBLOCK ) {
788 BIO_set_retry_read( b );
796 tlso_bio_write( BIO *b, const char *buf, int len )
801 if ( buf == NULL || len <= 0 ) return 0;
803 p = (struct tls_data *)b->ptr;
805 if ( p == NULL || p->sbiod == NULL ) {
809 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
811 BIO_clear_retry_flags( b );
813 int err = sock_errno();
814 if ( err == EAGAIN || err == EWOULDBLOCK ) {
815 BIO_set_retry_write( b );
823 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
825 if ( cmd == BIO_CTRL_FLUSH ) {
826 /* The OpenSSL library needs this */
833 tlso_bio_gets( BIO *b, char *buf, int len )
839 tlso_bio_puts( BIO *b, const char *str )
841 return tlso_bio_write( b, str, strlen( str ) );
844 static BIO_METHOD tlso_bio_method =
846 ( 100 | 0x400 ), /* it's a source/sink BIO */
858 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
863 assert( sbiod != NULL );
865 p = LBER_MALLOC( sizeof( *p ) );
872 bio = BIO_new( &tlso_bio_method );
873 bio->ptr = (void *)p;
874 SSL_set_bio( p->session, bio, bio );
875 sbiod->sbiod_pvt = p;
880 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
884 assert( sbiod != NULL );
885 assert( sbiod->sbiod_pvt != NULL );
887 p = (struct tls_data *)sbiod->sbiod_pvt;
888 SSL_free( p->session );
889 LBER_FREE( sbiod->sbiod_pvt );
890 sbiod->sbiod_pvt = NULL;
895 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
899 assert( sbiod != NULL );
900 assert( sbiod->sbiod_pvt != NULL );
902 p = (struct tls_data *)sbiod->sbiod_pvt;
903 SSL_shutdown( p->session );
908 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
912 assert( sbiod != NULL );
913 assert( sbiod->sbiod_pvt != NULL );
915 p = (struct tls_data *)sbiod->sbiod_pvt;
917 if ( opt == LBER_SB_OPT_GET_SSL ) {
918 *((tlso_session **)arg) = p->session;
921 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
922 if( SSL_pending( p->session ) > 0 ) {
927 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
931 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
937 assert( sbiod != NULL );
938 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
940 p = (struct tls_data *)sbiod->sbiod_pvt;
942 ret = SSL_read( p->session, (char *)buf, len );
944 errno = WSAGetLastError();
946 err = SSL_get_error( p->session, ret );
947 if (err == SSL_ERROR_WANT_READ ) {
948 sbiod->sbiod_sb->sb_trans_needs_read = 1;
949 sock_errset(EWOULDBLOCK);
952 sbiod->sbiod_sb->sb_trans_needs_read = 0;
957 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
963 assert( sbiod != NULL );
964 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
966 p = (struct tls_data *)sbiod->sbiod_pvt;
968 ret = SSL_write( p->session, (char *)buf, len );
970 errno = WSAGetLastError();
972 err = SSL_get_error( p->session, ret );
973 if (err == SSL_ERROR_WANT_WRITE ) {
974 sbiod->sbiod_sb->sb_trans_needs_write = 1;
975 sock_errset(EWOULDBLOCK);
978 sbiod->sbiod_sb->sb_trans_needs_write = 0;
983 static Sockbuf_IO tlso_sbio =
985 tlso_sb_setup, /* sbi_setup */
986 tlso_sb_remove, /* sbi_remove */
987 tlso_sb_ctrl, /* sbi_ctrl */
988 tlso_sb_read, /* sbi_read */
989 tlso_sb_write, /* sbi_write */
990 tlso_sb_close /* sbi_close */
993 /* Derived from openssl/apps/s_cb.c */
995 tlso_info_cb( const SSL *ssl, int where, int ret )
999 char *state = (char *) SSL_state_string_long( (SSL *)ssl );
1001 w = where & ~SSL_ST_MASK;
1002 if ( w & SSL_ST_CONNECT ) {
1004 } else if ( w & SSL_ST_ACCEPT ) {
1012 state = LDAP_STRDUP( state );
1016 if ( where & SSL_CB_LOOP ) {
1017 Debug( LDAP_DEBUG_TRACE,
1018 "TLS trace: %s:%s\n",
1021 } else if ( where & SSL_CB_ALERT ) {
1022 char *atype = (char *) SSL_alert_type_string_long( ret );
1023 char *adesc = (char *) SSL_alert_desc_string_long( ret );
1024 op = ( where & SSL_CB_READ ) ? "read" : "write";
1027 atype = LDAP_STRDUP( atype );
1031 adesc = LDAP_STRDUP( adesc );
1035 Debug( LDAP_DEBUG_TRACE,
1036 "TLS trace: SSL3 alert %s:%s:%s\n",
1039 if ( atype ) LDAP_FREE( atype );
1040 if ( adesc ) LDAP_FREE( adesc );
1042 } else if ( where & SSL_CB_EXIT ) {
1044 Debug( LDAP_DEBUG_TRACE,
1045 "TLS trace: %s:failed in %s\n",
1047 } else if ( ret < 0 ) {
1048 Debug( LDAP_DEBUG_TRACE,
1049 "TLS trace: %s:error in %s\n",
1054 if ( state ) LDAP_FREE( state );
1059 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
1068 char *certerr = NULL;
1070 cert = X509_STORE_CTX_get_current_cert( ctx );
1071 errnum = X509_STORE_CTX_get_error( ctx );
1072 errdepth = X509_STORE_CTX_get_error_depth( ctx );
1075 * X509_get_*_name return pointers to the internal copies of
1076 * those things requested. So do not free them.
1078 subject = X509_get_subject_name( cert );
1079 issuer = X509_get_issuer_name( cert );
1080 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1081 sname = X509_NAME_oneline( subject, NULL, 0 );
1082 iname = X509_NAME_oneline( issuer, NULL, 0 );
1083 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1085 if ( sname ) __etoa( sname );
1086 if ( iname ) __etoa( iname );
1088 certerr = LDAP_STRDUP( certerr );
1092 Debug( LDAP_DEBUG_TRACE,
1093 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1095 sname ? sname : "-unknown-" );
1096 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1098 Debug( LDAP_DEBUG_ANY,
1099 "TLS certificate verification: Error, %s\n",
1103 CRYPTO_free ( sname );
1105 CRYPTO_free ( iname );
1107 if ( certerr ) LDAP_FREE( certerr );
1113 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1115 (void) tlso_verify_cb( ok, ctx );
1119 /* Inspired by ERR_print_errors in OpenSSL */
1121 tlso_report_error( void )
1128 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1129 ERR_error_string_n( l, buf, sizeof( buf ) );
1132 file = LDAP_STRDUP( file );
1133 __etoa( (char *)file );
1137 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1140 if ( file ) LDAP_FREE( (void *)file );
1146 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1149 /* FIXME: Pregenerate the key on startup */
1150 /* FIXME: Who frees the key? */
1151 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1152 BIGNUM *bn = BN_new();
1155 if ( BN_set_word( bn, RSA_F4 )) {
1156 tmp_rsa = RSA_new();
1157 if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1158 RSA_free( tmp_rsa );
1165 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1169 Debug( LDAP_DEBUG_ANY,
1170 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1171 key_length, is_export ? "export" : "domestic", 0 );
1177 tlso_seed_PRNG( const char *randfile )
1179 #ifndef URANDOM_DEVICE
1180 /* no /dev/urandom (or equiv) */
1182 char buffer[MAXPATHLEN];
1184 if (randfile == NULL) {
1185 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1186 * If $HOME is not set or buffer too small to hold the pathname,
1187 * an error occurs. - From RAND_file_name() man page.
1188 * The fact is that when $HOME is NULL, .rnd is used.
1190 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1192 } else if (RAND_egd(randfile) > 0) {
1197 if (randfile == NULL) {
1198 Debug( LDAP_DEBUG_ANY,
1199 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1204 total = RAND_load_file(randfile, -1);
1206 if (RAND_status() == 0) {
1207 Debug( LDAP_DEBUG_ANY,
1208 "TLS: PRNG not been seeded with enough data\n",
1213 /* assume if there was enough bits to seed that it's okay
1214 * to write derived bits to the file
1216 RAND_write_file(randfile);
1224 tls_impl ldap_int_tls_impl = {
1236 tlso_session_connect,
1237 tlso_session_accept,
1238 tlso_session_upflags,
1239 tlso_session_errmsg,
1241 tlso_session_peer_dn,
1242 tlso_session_chkhost,
1243 tlso_session_strength,
1244 tlso_session_unique,
1245 tlso_session_version,
1246 tlso_session_cipher,
1247 tlso_session_peercert,
1251 #ifdef LDAP_R_COMPILE
1260 #endif /* HAVE_OPENSSL */