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;
71 #endif /* LDAP_R_COMPILE */
74 * Initialize TLS subsystem. Should be called only once.
81 tlsm_layer_id = PR_GetUniqueIdentity("OpenLDAP");
83 if ( !NSS_IsInitialized() ) {
86 NSS_SetDomesticPolicy();
89 /* No cipher suite handling for now */
95 * Tear down the TLS subsystem. Should only be called once.
106 tlsm_ctx_new ( struct ldapoptions *lo )
110 ctx = LDAP_MALLOC( sizeof (*ctx) );
112 PRFileDesc *fd = PR_CreateIOLayerStub(tlsm_layer_id, &tlsm_PR_methods);
114 ctx->tc_model = SSL_ImportFD( NULL, fd );
115 if ( ctx->tc_model ) {
117 #ifdef LDAP_R_COMPILE
118 ldap_pvt_thread_mutex_init( &ctx->tc_refmutex );
130 return (tls_ctx *)ctx;
134 tlsm_ctx_ref( tls_ctx *ctx )
136 tlsm_ctx *c = (tlsm_ctx *)ctx;
137 #ifdef LDAP_R_COMPILE
138 ldap_pvt_thread_mutex_lock( &c->tc_refmutex );
141 #ifdef LDAP_R_COMPILE
142 ldap_pvt_thread_mutex_unlock( &c->tc_refmutex );
147 tlsm_ctx_free ( tls_ctx *ctx )
149 tlsm_ctx *c = (tlsm_ctx *)ctx;
154 #ifdef LDAP_R_COMPILE
155 ldap_pvt_thread_mutex_lock( &c->tc_refmutex );
157 refcount = --c->tc_refcnt;
158 #ifdef LDAP_R_COMPILE
159 ldap_pvt_thread_mutex_unlock( &c->tc_refmutex );
163 PR_Close( c->tc_model );
164 #ifdef LDAP_R_COMPILE
165 ldap_pvt_thread_mutex_destroy( &c->tc_refmutex );
171 * initialize a new TLS context
174 tlsm_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
176 tlsm_ctx *ctx = lo->ldo_tls_ctx;
179 SSL_OptionSet( ctx->tc_model, SSL_SECURITY, PR_TRUE );
180 SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_CLIENT, !is_server );
181 SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_SERVER, is_server );
183 /* See SECMOD_OpenUserDB() */
185 if ( lo->ldo_tls_ciphersuite &&
186 tlsm_parse_ciphers( ctx, lt->lt_ciphersuite )) {
187 Debug( LDAP_DEBUG_ANY,
188 "TLS: could not set cipher list %s.\n",
189 lo->ldo_tls_ciphersuite, 0, 0 );
193 if (lo->ldo_tls_cacertdir != NULL) {
194 Debug( LDAP_DEBUG_ANY,
195 "TLS: warning: cacertdir not implemented for gnutls\n",
199 if (lo->ldo_tls_cacertfile != NULL) {
200 rc = gnutls_certificate_set_x509_trust_file(
203 GNUTLS_X509_FMT_PEM );
204 if ( rc < 0 ) return -1;
207 if ( lo->ldo_tls_certfile && lo->ldo_tls_keyfile ) {
208 rc = gnutls_certificate_set_x509_key_file(
212 GNUTLS_X509_FMT_PEM );
214 } else if ( lo->ldo_tls_certfile || lo->ldo_tls_keyfile ) {
215 Debug( LDAP_DEBUG_ANY,
216 "TLS: only one of certfile and keyfile specified\n",
221 if ( lo->ldo_tls_dhfile ) {
222 Debug( LDAP_DEBUG_ANY,
223 "TLS: warning: ignoring dhfile\n",
227 if ( lo->ldo_tls_crlfile ) {
228 rc = gnutls_certificate_set_x509_crl_file(
231 GNUTLS_X509_FMT_PEM );
232 if ( rc < 0 ) return -1;
236 gnutls_dh_params_init(&ctx->dh_params);
237 gnutls_dh_params_generate2(ctx->dh_params, DH_BITS);
244 tlsm_session_new ( tls_ctx * ctx, int is_server )
246 tlsm_ctx *c = (tlsm_ctx *)ctx;
247 tlsm_session *session;
250 fd = PR_CreateIOLayerStub(tlsm_layer_id, &tlsm_PR_methods);
255 session = SSL_ImportFD( c->tc_model, fd );
261 SSL_ResetHandshake( session, is_server );
263 return (tls_session *)session;
267 tlsm_session_accept( tls_session *session )
269 tlsm_session *s = (tlsm_session *)session;
271 return SSL_ForceHandshake( s );
275 tlsm_session_connect( LDAP *ld, tls_session *session )
277 tlsm_session *s = (tlsm_session *)session;
280 /* By default, NSS checks the cert hostname for us */
281 rc = SSL_SetURL( s, ld->ld_options.ldo_defludp->lud_host );
282 return SSL_ForceHandshake( s );
286 tlsm_session_upflags( Sockbuf *sb, tls_session *session, int rc )
288 /* Should never happen */
291 if ( rc != PR_PENDING_INTERRUPT_ERROR && rc != PR_WOULD_BLOCK_ERROR )
297 tlsm_session_errmsg( int rc, char *buf, size_t len )
302 i = PR_GetErrorTextLength();
304 char *msg = LDAP_MALLOC( i+1 );
305 PR_GetErrorText( msg );
306 memcpy( buf, msg, len );
309 PR_GetErrorText( buf );
312 return i ? buf : NULL;
316 tlsm_session_my_dn( tls_session *session, struct berval *der_dn )
318 tlsm_session *s = (tlsm_session *)session;
319 CERTCertificate *cert;
321 cert = SSL_LocalCertificate( s );
322 if (!cert) return LDAP_INVALID_CREDENTIALS;
324 der_dn->bv_val = cert->derSubject.data;
325 der_dn->bv_len = cert->derSubject.len;
326 CERT_DestroyCertificate( cert );
331 tlsm_session_peer_dn( tls_session *session, struct berval *der_dn )
333 tlsm_session *s = (tlsm_session *)session;
334 CERTCertificate *cert;
336 cert = SSL_PeerCertificate( s );
337 if (!cert) return LDAP_INVALID_CREDENTIALS;
339 der_dn->bv_val = cert->derSubject.data;
340 der_dn->bv_len = cert->derSubject.len;
341 CERT_DestroyCertificate( cert );
345 /* what kind of hostname were we given? */
351 tlsm_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
353 /* NSS already does a hostname check */
356 const gnutls_datum_t *peer_cert_list;
359 char altname[NI_MAXHOST];
362 gnutls_x509_crt_t cert;
368 struct in6_addr addr;
372 int n, len1 = 0, len2 = 0;
374 time_t now = time(0);
376 if( ldap_int_hostname &&
377 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
379 name = ldap_int_hostname;
384 peer_cert_list = gnutls_certificate_get_peers( session->session,
386 if ( !peer_cert_list ) {
387 Debug( LDAP_DEBUG_ANY,
388 "TLS: unable to get peer certificate.\n",
390 /* If this was a fatal condition, things would have
391 * aborted long before now.
395 ret = gnutls_x509_crt_init( &cert );
397 return LDAP_LOCAL_ERROR;
398 ret = gnutls_x509_crt_import( cert, peer_cert_list, GNUTLS_X509_FMT_DER );
400 gnutls_x509_crt_deinit( cert );
401 return LDAP_LOCAL_ERROR;
405 if (name[0] == '[' && strchr(name, ']')) {
406 char *n2 = ldap_strdup(name+1);
407 *strchr(n2, ']') = 2;
408 if (inet_pton(AF_INET6, n2, &addr))
413 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
414 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
417 if (ntype == IS_DNS) {
419 domain = strchr(name, '.');
421 len2 = len1 - (domain-name);
425 for ( i=0, ret=0; ret >= 0; i++ ) {
426 altnamesize = sizeof(altname);
427 ret = gnutls_x509_crt_get_subject_alt_name( cert, i,
428 altname, &altnamesize, NULL );
429 if ( ret < 0 ) break;
432 if ( altnamesize == 0 ) continue;
434 if ( ret == GNUTLS_SAN_DNSNAME ) {
435 if (ntype != IS_DNS) continue;
437 /* Is this an exact match? */
438 if ((len1 == altnamesize) && !strncasecmp(name, altname, len1)) {
442 /* Is this a wildcard match? */
443 if (domain && (altname[0] == '*') && (altname[1] == '.') &&
444 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2))
448 } else if ( ret == GNUTLS_SAN_IPADDRESS ) {
449 if (ntype == IS_DNS) continue;
452 if (ntype == IS_IP6 && altnamesize != sizeof(struct in6_addr)) {
456 if (ntype == IS_IP4 && altnamesize != sizeof(struct in_addr)) {
459 if (!memcmp(altname, &addr, altnamesize)) {
467 altnamesize = sizeof(altname);
468 ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
469 0, 0, altname, &altnamesize );
471 Debug( LDAP_DEBUG_ANY,
472 "TLS: unable to get common name from peer certificate.\n",
474 ret = LDAP_CONNECT_ERROR;
475 if ( ld->ld_error ) {
476 LDAP_FREE( ld->ld_error );
478 ld->ld_error = LDAP_STRDUP(
479 _("TLS: unable to get CN from peer certificate"));
482 ret = LDAP_LOCAL_ERROR;
483 if ( len1 == altnamesize && strncasecmp(name, altname, altnamesize) == 0 ) {
486 } else if (( altname[0] == '*' ) && ( altname[1] == '.' )) {
487 /* Is this a wildcard match? */
489 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2)) {
495 if( ret == LDAP_LOCAL_ERROR ) {
496 altname[altnamesize] = '\0';
497 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
498 "common name in certificate (%s).\n",
500 ret = LDAP_CONNECT_ERROR;
501 if ( ld->ld_error ) {
502 LDAP_FREE( ld->ld_error );
504 ld->ld_error = LDAP_STRDUP(
505 _("TLS: hostname does not match CN in peer certificate"));
508 gnutls_x509_crt_deinit( cert );
514 tlsm_session_strength( tls_session *session )
516 tlsm_session *s = (tlsm_session *)session;
519 rc = SSL_SecurityStatus( s, NULL, NULL, NULL, &keySize,
521 return rc ? 0 : keySize;
525 * TLS support for LBER Sockbufs
529 tlsm_session *session;
530 Sockbuf_IO_Desc *sbiod;
534 static PRStatus PR_CALLBACK
535 tlsm_PR_Close(PRFileDesc *fd)
540 static int PR_CALLBACK
541 tlsm_PR_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
542 PRIntervalTime timeout)
546 if ( buf == NULL || len <= 0 ) return 0;
548 p = (struct tls_data *)fd->secret;
550 if ( p == NULL || p->sbiod == NULL ) {
554 return LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
557 static int PR_CALLBACK
558 tlsm_PR_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags,
559 PRIntervalTime timeout)
563 if ( buf == NULL || len <= 0 ) return 0;
565 p = (struct tls_data *)fd->secret;
567 if ( p == NULL || p->sbiod == NULL ) {
571 return LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
574 static int PR_CALLBACK
575 tlsm_PR_Read(PRFileDesc *fd, void *buf, PRInt32 len)
577 return tlsm_PR_Recv( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
580 static int PR_CALLBACK
581 tlsm_PR_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
583 return tlsm_PR_Send( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
586 static PRStatus PR_CALLBACK
587 tlsm_PR_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
593 p = (struct tls_data *)fd->secret;
595 if ( p == NULL || p->sbiod == NULL ) {
598 len = sizeof(PRNetAddr);
599 return getpeername( p->sbiod->sbiod_sb->sb_fd, (struct sockaddr *)addr, &len );
602 static PRStatus PR_CALLBACK
605 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
609 static PRFileDesc * PR_CALLBACK
612 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
616 static PRInt16 PR_CALLBACK
619 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
623 static PRInt32 PR_CALLBACK
626 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
630 static PRInt64 PR_CALLBACK
635 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
640 static const PRIOMethods tlsm_PR_methods = {
642 tlsm_PR_Close, /* close */
643 tlsm_PR_Read, /* read */
644 tlsm_PR_Write, /* write */
645 tlsm_PR_i32_unimp, /* available */
646 tlsm_PR_i64_unimp, /* available64 */
647 tlsm_PR_prs_unimp, /* fsync */
648 tlsm_PR_i32_unimp, /* seek */
649 tlsm_PR_i64_unimp, /* seek64 */
650 tlsm_PR_prs_unimp, /* fileInfo */
651 tlsm_PR_prs_unimp, /* fileInfo64 */
652 tlsm_PR_i32_unimp, /* writev */
653 tlsm_PR_prs_unimp, /* connect */
654 tlsm_PR_pfd_unimp, /* accept */
655 tlsm_PR_prs_unimp, /* bind */
656 tlsm_PR_prs_unimp, /* listen */
657 (PRShutdownFN)tlsm_PR_Close, /* shutdown */
658 tlsm_PR_Recv, /* recv */
659 tlsm_PR_Send, /* send */
660 tlsm_PR_i32_unimp, /* recvfrom */
661 tlsm_PR_i32_unimp, /* sendto */
662 (PRPollFN)tlsm_PR_i16_unimp, /* poll */
663 tlsm_PR_i32_unimp, /* acceptread */
664 tlsm_PR_i32_unimp, /* transmitfile */
665 tlsm_PR_prs_unimp, /* getsockname */
666 tlsm_PR_GetPeerName, /* getpeername */
667 tlsm_PR_i32_unimp, /* getsockopt OBSOLETE */
668 tlsm_PR_i32_unimp, /* setsockopt OBSOLETE */
669 tlsm_PR_i32_unimp, /* getsocketoption */
670 tlsm_PR_i32_unimp, /* setsocketoption */
671 tlsm_PR_i32_unimp, /* Send a (partial) file with header/trailer*/
672 (PRConnectcontinueFN)tlsm_PR_prs_unimp, /* connectcontinue */
673 tlsm_PR_i32_unimp, /* reserved for future use */
674 tlsm_PR_i32_unimp, /* reserved for future use */
675 tlsm_PR_i32_unimp, /* reserved for future use */
676 tlsm_PR_i32_unimp /* reserved for future use */
680 tlsm_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
683 tlsm_session *session = arg;
686 assert( sbiod != NULL );
688 p = LBER_MALLOC( sizeof( *p ) );
693 fd = PR_GetIdentitiesLayer( session, tlsm_layer_id );
699 fd->secret = (PRFilePrivate *)p;
700 p->session = session;
702 sbiod->sbiod_pvt = p;
707 tlsm_sb_remove( Sockbuf_IO_Desc *sbiod )
711 assert( sbiod != NULL );
712 assert( sbiod->sbiod_pvt != NULL );
714 p = (struct tls_data *)sbiod->sbiod_pvt;
715 PR_Close( p->session );
716 LBER_FREE( sbiod->sbiod_pvt );
717 sbiod->sbiod_pvt = NULL;
722 tlsm_sb_close( Sockbuf_IO_Desc *sbiod )
726 assert( sbiod != NULL );
727 assert( sbiod->sbiod_pvt != NULL );
729 p = (struct tls_data *)sbiod->sbiod_pvt;
730 PR_Shutdown( p->session, PR_SHUTDOWN_BOTH );
735 tlsm_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
739 assert( sbiod != NULL );
740 assert( sbiod->sbiod_pvt != NULL );
742 p = (struct tls_data *)sbiod->sbiod_pvt;
744 if ( opt == LBER_SB_OPT_GET_SSL ) {
745 *((tlsm_session **)arg) = p->session;
748 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
749 PRPollDesc pd = { p->session, PR_POLL_READ, 0 };
750 if( PR_Poll( &pd, 1, 1 ) > 0 ) {
755 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
759 tlsm_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
765 assert( sbiod != NULL );
766 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
768 p = (struct tls_data *)sbiod->sbiod_pvt;
770 ret = PR_Recv( p->session, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
773 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
774 sbiod->sbiod_sb->sb_trans_needs_read = 1;
775 sock_errset(EWOULDBLOCK);
778 sbiod->sbiod_sb->sb_trans_needs_read = 0;
784 tlsm_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
790 assert( sbiod != NULL );
791 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
793 p = (struct tls_data *)sbiod->sbiod_pvt;
795 ret = PR_Send( p->session, (char *)buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
798 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
799 sbiod->sbiod_sb->sb_trans_needs_write = 1;
800 sock_errset(EWOULDBLOCK);
804 sbiod->sbiod_sb->sb_trans_needs_write = 0;
809 static Sockbuf_IO tlsm_sbio =
811 tlsm_sb_setup, /* sbi_setup */
812 tlsm_sb_remove, /* sbi_remove */
813 tlsm_sb_ctrl, /* sbi_ctrl */
814 tlsm_sb_read, /* sbi_read */
815 tlsm_sb_write, /* sbi_write */
816 tlsm_sb_close /* sbi_close */
819 tls_impl ldap_int_moznss_impl = {
831 tlsm_session_connect,
833 tlsm_session_upflags,
836 tlsm_session_peer_dn,
837 tlsm_session_chkhost,
838 tlsm_session_strength,
842 #ifdef LDAP_R_COMPILE
851 #endif /* HAVE_MOZNSS */