1 /* tls_m.c - Handle tls/ssl using Mozilla NSS. */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 2008-2009 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: written 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>
48 typedef struct tlsm_ctx {
52 ldap_pvt_thread_mutex_t tc_refmutex;
56 typedef PRFileDesc tlsm_session;
58 static PRDescIdentity tlsm_layer_id;
60 static const PRIOMethods tlsm_PR_methods;
62 extern tls_impl ldap_int_tls_impl;
64 static int tslm_did_init;
73 #endif /* LDAP_R_COMPILE */
76 * Initialize TLS subsystem. Should be called only once.
83 tlsm_layer_id = PR_GetUniqueIdentity("OpenLDAP");
85 if ( !NSS_IsInitialized() ) {
90 NSS_SetDomesticPolicy();
93 /* No cipher suite handling for now */
99 * Tear down the TLS subsystem. Should only be called once.
104 /* Only if we did the actual initialization */
105 if ( tlsm_did_init ) {
115 tlsm_ctx_new ( struct ldapoptions *lo )
119 ctx = LDAP_MALLOC( sizeof (*ctx) );
121 PRFileDesc *fd = PR_CreateIOLayerStub(tlsm_layer_id, &tlsm_PR_methods);
123 ctx->tc_model = SSL_ImportFD( NULL, fd );
124 if ( ctx->tc_model ) {
126 #ifdef LDAP_R_COMPILE
127 ldap_pvt_thread_mutex_init( &ctx->tc_refmutex );
139 return (tls_ctx *)ctx;
143 tlsm_ctx_ref( tls_ctx *ctx )
145 tlsm_ctx *c = (tlsm_ctx *)ctx;
146 #ifdef LDAP_R_COMPILE
147 ldap_pvt_thread_mutex_lock( &c->tc_refmutex );
150 #ifdef LDAP_R_COMPILE
151 ldap_pvt_thread_mutex_unlock( &c->tc_refmutex );
156 tlsm_ctx_free ( tls_ctx *ctx )
158 tlsm_ctx *c = (tlsm_ctx *)ctx;
163 #ifdef LDAP_R_COMPILE
164 ldap_pvt_thread_mutex_lock( &c->tc_refmutex );
166 refcount = --c->tc_refcnt;
167 #ifdef LDAP_R_COMPILE
168 ldap_pvt_thread_mutex_unlock( &c->tc_refmutex );
172 PR_Close( c->tc_model );
173 #ifdef LDAP_R_COMPILE
174 ldap_pvt_thread_mutex_destroy( &c->tc_refmutex );
180 * initialize a new TLS context
183 tlsm_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
185 tlsm_ctx *ctx = lo->ldo_tls_ctx;
188 SSL_OptionSet( ctx->tc_model, SSL_SECURITY, PR_TRUE );
189 SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_CLIENT, !is_server );
190 SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_SERVER, is_server );
192 /* See SECMOD_OpenUserDB() */
194 if ( lo->ldo_tls_ciphersuite &&
195 tlsm_parse_ciphers( ctx, lt->lt_ciphersuite )) {
196 Debug( LDAP_DEBUG_ANY,
197 "TLS: could not set cipher list %s.\n",
198 lo->ldo_tls_ciphersuite, 0, 0 );
202 if (lo->ldo_tls_cacertdir != NULL) {
203 Debug( LDAP_DEBUG_ANY,
204 "TLS: warning: cacertdir not implemented for gnutls\n",
208 if (lo->ldo_tls_cacertfile != NULL) {
209 rc = gnutls_certificate_set_x509_trust_file(
212 GNUTLS_X509_FMT_PEM );
213 if ( rc < 0 ) return -1;
216 if ( lo->ldo_tls_certfile && lo->ldo_tls_keyfile ) {
217 rc = gnutls_certificate_set_x509_key_file(
221 GNUTLS_X509_FMT_PEM );
223 } else if ( lo->ldo_tls_certfile || lo->ldo_tls_keyfile ) {
224 Debug( LDAP_DEBUG_ANY,
225 "TLS: only one of certfile and keyfile specified\n",
230 if ( lo->ldo_tls_dhfile ) {
231 Debug( LDAP_DEBUG_ANY,
232 "TLS: warning: ignoring dhfile\n",
236 if ( lo->ldo_tls_crlfile ) {
237 rc = gnutls_certificate_set_x509_crl_file(
240 GNUTLS_X509_FMT_PEM );
241 if ( rc < 0 ) return -1;
245 gnutls_dh_params_init(&ctx->dh_params);
246 gnutls_dh_params_generate2(ctx->dh_params, DH_BITS);
253 tlsm_session_new ( tls_ctx * ctx, int is_server )
255 tlsm_ctx *c = (tlsm_ctx *)ctx;
256 tlsm_session *session;
259 fd = PR_CreateIOLayerStub(tlsm_layer_id, &tlsm_PR_methods);
264 session = SSL_ImportFD( c->tc_model, fd );
270 SSL_ResetHandshake( session, is_server );
272 return (tls_session *)session;
276 tlsm_session_accept( tls_session *session )
278 tlsm_session *s = (tlsm_session *)session;
280 return SSL_ForceHandshake( s );
284 tlsm_session_connect( LDAP *ld, tls_session *session )
286 tlsm_session *s = (tlsm_session *)session;
289 /* By default, NSS checks the cert hostname for us */
290 rc = SSL_SetURL( s, ld->ld_options.ldo_defludp->lud_host );
291 return SSL_ForceHandshake( s );
295 tlsm_session_upflags( Sockbuf *sb, tls_session *session, int rc )
297 /* Should never happen */
300 if ( rc != PR_PENDING_INTERRUPT_ERROR && rc != PR_WOULD_BLOCK_ERROR )
306 tlsm_session_errmsg( int rc, char *buf, size_t len )
311 i = PR_GetErrorTextLength();
313 char *msg = LDAP_MALLOC( i+1 );
314 PR_GetErrorText( msg );
315 memcpy( buf, msg, len );
318 PR_GetErrorText( buf );
321 return i ? buf : NULL;
325 tlsm_session_my_dn( tls_session *session, struct berval *der_dn )
327 tlsm_session *s = (tlsm_session *)session;
328 CERTCertificate *cert;
330 cert = SSL_LocalCertificate( s );
331 if (!cert) return LDAP_INVALID_CREDENTIALS;
333 der_dn->bv_val = cert->derSubject.data;
334 der_dn->bv_len = cert->derSubject.len;
335 CERT_DestroyCertificate( cert );
340 tlsm_session_peer_dn( tls_session *session, struct berval *der_dn )
342 tlsm_session *s = (tlsm_session *)session;
343 CERTCertificate *cert;
345 cert = SSL_PeerCertificate( s );
346 if (!cert) return LDAP_INVALID_CREDENTIALS;
348 der_dn->bv_val = cert->derSubject.data;
349 der_dn->bv_len = cert->derSubject.len;
350 CERT_DestroyCertificate( cert );
354 /* what kind of hostname were we given? */
360 tlsm_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
362 /* NSS already does a hostname check */
365 const gnutls_datum_t *peer_cert_list;
368 char altname[NI_MAXHOST];
371 gnutls_x509_crt_t cert;
377 struct in6_addr addr;
381 int n, len1 = 0, len2 = 0;
383 time_t now = time(0);
385 if( ldap_int_hostname &&
386 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
388 name = ldap_int_hostname;
393 peer_cert_list = gnutls_certificate_get_peers( session->session,
395 if ( !peer_cert_list ) {
396 Debug( LDAP_DEBUG_ANY,
397 "TLS: unable to get peer certificate.\n",
399 /* If this was a fatal condition, things would have
400 * aborted long before now.
404 ret = gnutls_x509_crt_init( &cert );
406 return LDAP_LOCAL_ERROR;
407 ret = gnutls_x509_crt_import( cert, peer_cert_list, GNUTLS_X509_FMT_DER );
409 gnutls_x509_crt_deinit( cert );
410 return LDAP_LOCAL_ERROR;
414 if (name[0] == '[' && strchr(name, ']')) {
415 char *n2 = ldap_strdup(name+1);
416 *strchr(n2, ']') = 0;
417 if (inet_pton(AF_INET6, n2, &addr))
422 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
423 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
426 if (ntype == IS_DNS) {
428 domain = strchr(name, '.');
430 len2 = len1 - (domain-name);
434 for ( i=0, ret=0; ret >= 0; i++ ) {
435 altnamesize = sizeof(altname);
436 ret = gnutls_x509_crt_get_subject_alt_name( cert, i,
437 altname, &altnamesize, NULL );
438 if ( ret < 0 ) break;
441 if ( altnamesize == 0 ) continue;
443 if ( ret == GNUTLS_SAN_DNSNAME ) {
444 if (ntype != IS_DNS) continue;
446 /* Is this an exact match? */
447 if ((len1 == altnamesize) && !strncasecmp(name, altname, len1)) {
451 /* Is this a wildcard match? */
452 if (domain && (altname[0] == '*') && (altname[1] == '.') &&
453 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2))
457 } else if ( ret == GNUTLS_SAN_IPADDRESS ) {
458 if (ntype == IS_DNS) continue;
461 if (ntype == IS_IP6 && altnamesize != sizeof(struct in6_addr)) {
465 if (ntype == IS_IP4 && altnamesize != sizeof(struct in_addr)) {
468 if (!memcmp(altname, &addr, altnamesize)) {
476 altnamesize = sizeof(altname);
477 ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
478 0, 0, altname, &altnamesize );
480 Debug( LDAP_DEBUG_ANY,
481 "TLS: unable to get common name from peer certificate.\n",
483 ret = LDAP_CONNECT_ERROR;
484 if ( ld->ld_error ) {
485 LDAP_FREE( ld->ld_error );
487 ld->ld_error = LDAP_STRDUP(
488 _("TLS: unable to get CN from peer certificate"));
491 ret = LDAP_LOCAL_ERROR;
492 if ( len1 == altnamesize && strncasecmp(name, altname, altnamesize) == 0 ) {
495 } else if (( altname[0] == '*' ) && ( altname[1] == '.' )) {
496 /* Is this a wildcard match? */
498 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2)) {
504 if( ret == LDAP_LOCAL_ERROR ) {
505 altname[altnamesize] = '\0';
506 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
507 "common name in certificate (%s).\n",
509 ret = LDAP_CONNECT_ERROR;
510 if ( ld->ld_error ) {
511 LDAP_FREE( ld->ld_error );
513 ld->ld_error = LDAP_STRDUP(
514 _("TLS: hostname does not match CN in peer certificate"));
517 gnutls_x509_crt_deinit( cert );
523 tlsm_session_strength( tls_session *session )
525 tlsm_session *s = (tlsm_session *)session;
528 rc = SSL_SecurityStatus( s, NULL, NULL, NULL, &keySize,
530 return rc ? 0 : keySize;
534 * TLS support for LBER Sockbufs
538 tlsm_session *session;
539 Sockbuf_IO_Desc *sbiod;
543 static PRStatus PR_CALLBACK
544 tlsm_PR_Close(PRFileDesc *fd)
549 static int PR_CALLBACK
550 tlsm_PR_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
551 PRIntervalTime timeout)
555 if ( buf == NULL || len <= 0 ) return 0;
557 p = (struct tls_data *)fd->secret;
559 if ( p == NULL || p->sbiod == NULL ) {
563 return LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
566 static int PR_CALLBACK
567 tlsm_PR_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags,
568 PRIntervalTime timeout)
572 if ( buf == NULL || len <= 0 ) return 0;
574 p = (struct tls_data *)fd->secret;
576 if ( p == NULL || p->sbiod == NULL ) {
580 return LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
583 static int PR_CALLBACK
584 tlsm_PR_Read(PRFileDesc *fd, void *buf, PRInt32 len)
586 return tlsm_PR_Recv( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
589 static int PR_CALLBACK
590 tlsm_PR_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
592 return tlsm_PR_Send( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
595 static PRStatus PR_CALLBACK
596 tlsm_PR_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
602 p = (struct tls_data *)fd->secret;
604 if ( p == NULL || p->sbiod == NULL ) {
607 len = sizeof(PRNetAddr);
608 return getpeername( p->sbiod->sbiod_sb->sb_fd, (struct sockaddr *)addr, &len );
611 static PRStatus PR_CALLBACK
614 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
618 static PRFileDesc * PR_CALLBACK
621 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
625 static PRInt16 PR_CALLBACK
628 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
632 static PRInt32 PR_CALLBACK
635 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
639 static PRInt64 PR_CALLBACK
644 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
649 static const PRIOMethods tlsm_PR_methods = {
651 tlsm_PR_Close, /* close */
652 tlsm_PR_Read, /* read */
653 tlsm_PR_Write, /* write */
654 tlsm_PR_i32_unimp, /* available */
655 tlsm_PR_i64_unimp, /* available64 */
656 tlsm_PR_prs_unimp, /* fsync */
657 tlsm_PR_i32_unimp, /* seek */
658 tlsm_PR_i64_unimp, /* seek64 */
659 tlsm_PR_prs_unimp, /* fileInfo */
660 tlsm_PR_prs_unimp, /* fileInfo64 */
661 tlsm_PR_i32_unimp, /* writev */
662 tlsm_PR_prs_unimp, /* connect */
663 tlsm_PR_pfd_unimp, /* accept */
664 tlsm_PR_prs_unimp, /* bind */
665 tlsm_PR_prs_unimp, /* listen */
666 (PRShutdownFN)tlsm_PR_Close, /* shutdown */
667 tlsm_PR_Recv, /* recv */
668 tlsm_PR_Send, /* send */
669 tlsm_PR_i32_unimp, /* recvfrom */
670 tlsm_PR_i32_unimp, /* sendto */
671 (PRPollFN)tlsm_PR_i16_unimp, /* poll */
672 tlsm_PR_i32_unimp, /* acceptread */
673 tlsm_PR_i32_unimp, /* transmitfile */
674 tlsm_PR_prs_unimp, /* getsockname */
675 tlsm_PR_GetPeerName, /* getpeername */
676 tlsm_PR_i32_unimp, /* getsockopt OBSOLETE */
677 tlsm_PR_i32_unimp, /* setsockopt OBSOLETE */
678 tlsm_PR_i32_unimp, /* getsocketoption */
679 tlsm_PR_i32_unimp, /* setsocketoption */
680 tlsm_PR_i32_unimp, /* Send a (partial) file with header/trailer*/
681 (PRConnectcontinueFN)tlsm_PR_prs_unimp, /* connectcontinue */
682 tlsm_PR_i32_unimp, /* reserved for future use */
683 tlsm_PR_i32_unimp, /* reserved for future use */
684 tlsm_PR_i32_unimp, /* reserved for future use */
685 tlsm_PR_i32_unimp /* reserved for future use */
689 tlsm_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
692 tlsm_session *session = arg;
695 assert( sbiod != NULL );
697 p = LBER_MALLOC( sizeof( *p ) );
702 fd = PR_GetIdentitiesLayer( session, tlsm_layer_id );
708 fd->secret = (PRFilePrivate *)p;
709 p->session = session;
711 sbiod->sbiod_pvt = p;
716 tlsm_sb_remove( Sockbuf_IO_Desc *sbiod )
720 assert( sbiod != NULL );
721 assert( sbiod->sbiod_pvt != NULL );
723 p = (struct tls_data *)sbiod->sbiod_pvt;
724 PR_Close( p->session );
725 LBER_FREE( sbiod->sbiod_pvt );
726 sbiod->sbiod_pvt = NULL;
731 tlsm_sb_close( Sockbuf_IO_Desc *sbiod )
735 assert( sbiod != NULL );
736 assert( sbiod->sbiod_pvt != NULL );
738 p = (struct tls_data *)sbiod->sbiod_pvt;
739 PR_Shutdown( p->session, PR_SHUTDOWN_BOTH );
744 tlsm_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
748 assert( sbiod != NULL );
749 assert( sbiod->sbiod_pvt != NULL );
751 p = (struct tls_data *)sbiod->sbiod_pvt;
753 if ( opt == LBER_SB_OPT_GET_SSL ) {
754 *((tlsm_session **)arg) = p->session;
757 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
758 PRPollDesc pd = { p->session, PR_POLL_READ, 0 };
759 if( PR_Poll( &pd, 1, 1 ) > 0 ) {
764 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
768 tlsm_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
774 assert( sbiod != NULL );
775 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
777 p = (struct tls_data *)sbiod->sbiod_pvt;
779 ret = PR_Recv( p->session, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
782 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
783 sbiod->sbiod_sb->sb_trans_needs_read = 1;
784 sock_errset(EWOULDBLOCK);
787 sbiod->sbiod_sb->sb_trans_needs_read = 0;
793 tlsm_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
799 assert( sbiod != NULL );
800 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
802 p = (struct tls_data *)sbiod->sbiod_pvt;
804 ret = PR_Send( p->session, (char *)buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
807 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
808 sbiod->sbiod_sb->sb_trans_needs_write = 1;
809 sock_errset(EWOULDBLOCK);
813 sbiod->sbiod_sb->sb_trans_needs_write = 0;
818 static Sockbuf_IO tlsm_sbio =
820 tlsm_sb_setup, /* sbi_setup */
821 tlsm_sb_remove, /* sbi_remove */
822 tlsm_sb_ctrl, /* sbi_ctrl */
823 tlsm_sb_read, /* sbi_read */
824 tlsm_sb_write, /* sbi_write */
825 tlsm_sb_close /* sbi_close */
828 tls_impl ldap_int_moznss_impl = {
840 tlsm_session_connect,
842 tlsm_session_upflags,
845 tlsm_session_peer_dn,
846 tlsm_session_chkhost,
847 tlsm_session_strength,
851 #ifdef LDAP_R_COMPILE
860 #endif /* HAVE_MOZNSS */