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 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 {
53 ldap_pvt_thread_mutex_t tc_refmutex;
57 typedef struct tlsm_session {
59 PRFileDesc *ts_session;
62 static PRDescIdentity tlsm_layer_id;
64 static const PRIOMethods tlsm_PR_methods;
66 extern tls_impl ldap_int_moznss_impl;
75 #endif /* LDAP_R_COMPILE */
78 * Initialize TLS subsystem. Should be called only once.
85 tlsm_layer_id = PR_GetUniqueIdentity("OpenLDAP");
87 if ( !NSS_IsInitialized() ) {
90 NSS_SetDomesticPolicy();
93 /* No cipher suite handling for now */
99 * Tear down the TLS subsystem. Should only be called once.
110 tlsm_ctx_new ( struct ldapoptions *lo )
114 ctx = LDAP_MALLOC( sizeof (*ctx) );
116 PRFileDesc *fd = PR_CreateIOLayerStub(tlsm_layer_id, &tlsm_PR_methods);
118 ctx->tc_model = SSL_ImportFD( NULL, fd );
119 if ( ctx->tc_model ) {
120 ctx->tc_impl = &ldap_int_moznss_impl;
122 #ifdef LDAP_R_COMPILE
123 ldap_pvt_thread_mutex_init( &ctx->tc_refmutex );
135 return (tls_ctx *)ctx;
139 tlsm_ctx_ref( tls_ctx *ctx )
141 tlsm_ctx *c = (tlsm_ctx *)ctx;
142 #ifdef LDAP_R_COMPILE
143 ldap_pvt_thread_mutex_lock( &c->tc_refmutex );
146 #ifdef LDAP_R_COMPILE
147 ldap_pvt_thread_mutex_unlock( &c->tc_refmutex );
152 tlsm_ctx_free ( tls_ctx *ctx )
154 tlsm_ctx *c = (tlsm_ctx *)ctx;
159 #ifdef LDAP_R_COMPILE
160 ldap_pvt_thread_mutex_lock( &c->tc_refmutex );
162 refcount = --c->tc_refcnt;
163 #ifdef LDAP_R_COMPILE
164 ldap_pvt_thread_mutex_unlock( &c->tc_refmutex );
168 PR_Close( c->tc_model );
169 #ifdef LDAP_R_COMPILE
170 ldap_pvt_thread_mutex_destroy( &c->tc_refmutex );
176 * initialize a new TLS context
179 tlsm_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
181 tlsm_ctx *ctx = lo->ldo_tls_ctx;
184 SSL_OptionSet( ctx->tc_model, SSL_SECURITY, PR_TRUE );
185 SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_CLIENT, !is_server );
186 SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_SERVER, is_server );
188 /* See SECMOD_OpenUserDB() */
190 if ( lo->ldo_tls_ciphersuite &&
191 tlsm_parse_ciphers( ctx, lt->lt_ciphersuite )) {
192 Debug( LDAP_DEBUG_ANY,
193 "TLS: could not set cipher list %s.\n",
194 lo->ldo_tls_ciphersuite, 0, 0 );
198 if (lo->ldo_tls_cacertdir != NULL) {
199 Debug( LDAP_DEBUG_ANY,
200 "TLS: warning: cacertdir not implemented for gnutls\n",
204 if (lo->ldo_tls_cacertfile != NULL) {
205 rc = gnutls_certificate_set_x509_trust_file(
208 GNUTLS_X509_FMT_PEM );
209 if ( rc < 0 ) return -1;
212 if ( lo->ldo_tls_certfile && lo->ldo_tls_keyfile ) {
213 rc = gnutls_certificate_set_x509_key_file(
217 GNUTLS_X509_FMT_PEM );
219 } else if ( lo->ldo_tls_certfile || lo->ldo_tls_keyfile ) {
220 Debug( LDAP_DEBUG_ANY,
221 "TLS: only one of certfile and keyfile specified\n",
226 if ( lo->ldo_tls_dhfile ) {
227 Debug( LDAP_DEBUG_ANY,
228 "TLS: warning: ignoring dhfile\n",
232 if ( lo->ldo_tls_crlfile ) {
233 rc = gnutls_certificate_set_x509_crl_file(
236 GNUTLS_X509_FMT_PEM );
237 if ( rc < 0 ) return -1;
241 gnutls_dh_params_init(&ctx->dh_params);
242 gnutls_dh_params_generate2(ctx->dh_params, DH_BITS);
249 tlsm_session_new ( tls_ctx * ctx, int is_server )
251 tlsm_ctx *c = (tlsm_ctx *)ctx;
252 tlsm_session *session;
255 session = LDAP_MALLOC( sizeof (*session) );
259 fd = PR_CreateIOLayerStub(tlsm_layer_id, &tlsm_PR_methods);
261 LDAP_FREE( session );
265 session->ts_session = SSL_ImportFD( c->tc_model, fd );
266 if ( !session->ts_session ) {
268 LDAP_FREE( session );
272 session->ts_impl = &ldap_int_moznss_impl;
274 SSL_ResetHandshake( session->ts_session, is_server );
276 return (tls_session *)session;
280 tlsm_session_accept( tls_session *session )
282 tlsm_session *s = (tlsm_session *)session;
284 return SSL_ForceHandshake( s->ts_session );
288 tlsm_session_connect( LDAP *ld, tls_session *session )
290 tlsm_session *s = (tlsm_session *)session;
293 /* By default, NSS checks the cert hostname for us */
294 rc = SSL_SetURL( s->ts_session, ld->ld_options.ldo_defludp->lud_host );
295 return SSL_ForceHandshake( s->ts_session );
299 tlsm_session_upflags( Sockbuf *sb, tls_session *session, int rc )
301 /* Should never happen */
304 if ( rc != PR_PENDING_INTERRUPT_ERROR && rc != PR_WOULD_BLOCK_ERROR )
310 tlsm_session_errmsg( int rc, char *buf, size_t len )
315 i = PR_GetErrorTextLength();
317 char *msg = LDAP_MALLOC( i+1 );
318 PR_GetErrorText( msg );
319 memcpy( buf, msg, len );
322 PR_GetErrorText( buf );
325 return i ? buf : NULL;
329 tlsm_session_my_dn( tls_session *session, struct berval *der_dn )
331 tlsm_session *s = (tlsm_session *)session;
332 CERTCertificate *cert;
334 cert = SSL_LocalCertificate( s->ts_session );
335 if (!cert) return LDAP_INVALID_CREDENTIALS;
337 der_dn->bv_val = cert->derSubject.data;
338 der_dn->bv_len = cert->derSubject.len;
339 CERT_DestroyCertificate( cert );
344 tlsm_session_peer_dn( tls_session *session, struct berval *der_dn )
346 tlsm_session *s = (tlsm_session *)session;
347 CERTCertificate *cert;
349 cert = SSL_PeerCertificate( s->ts_session );
350 if (!cert) return LDAP_INVALID_CREDENTIALS;
352 der_dn->bv_val = cert->derSubject.data;
353 der_dn->bv_len = cert->derSubject.len;
354 CERT_DestroyCertificate( cert );
358 /* what kind of hostname were we given? */
364 tlsm_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
366 /* NSS already does a hostname check */
369 const gnutls_datum_t *peer_cert_list;
372 char altname[NI_MAXHOST];
375 gnutls_x509_crt_t cert;
381 struct in6_addr addr;
385 int n, len1 = 0, len2 = 0;
387 time_t now = time(0);
389 if( ldap_int_hostname &&
390 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
392 name = ldap_int_hostname;
397 peer_cert_list = gnutls_certificate_get_peers( session->session,
399 if ( !peer_cert_list ) {
400 Debug( LDAP_DEBUG_ANY,
401 "TLS: unable to get peer certificate.\n",
403 /* If this was a fatal condition, things would have
404 * aborted long before now.
408 ret = gnutls_x509_crt_init( &cert );
410 return LDAP_LOCAL_ERROR;
411 ret = gnutls_x509_crt_import( cert, peer_cert_list, GNUTLS_X509_FMT_DER );
413 gnutls_x509_crt_deinit( cert );
414 return LDAP_LOCAL_ERROR;
418 if (name[0] == '[' && strchr(name, ']')) {
419 char *n2 = ldap_strdup(name+1);
420 *strchr(n2, ']') = 2;
421 if (inet_pton(AF_INET6, n2, &addr))
426 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
427 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
430 if (ntype == IS_DNS) {
432 domain = strchr(name, '.');
434 len2 = len1 - (domain-name);
438 for ( i=0, ret=0; ret >= 0; i++ ) {
439 altnamesize = sizeof(altname);
440 ret = gnutls_x509_crt_get_subject_alt_name( cert, i,
441 altname, &altnamesize, NULL );
442 if ( ret < 0 ) break;
445 if ( altnamesize == 0 ) continue;
447 if ( ret == GNUTLS_SAN_DNSNAME ) {
448 if (ntype != IS_DNS) continue;
450 /* Is this an exact match? */
451 if ((len1 == altnamesize) && !strncasecmp(name, altname, len1)) {
455 /* Is this a wildcard match? */
456 if (domain && (altname[0] == '*') && (altname[1] == '.') &&
457 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2))
461 } else if ( ret == GNUTLS_SAN_IPADDRESS ) {
462 if (ntype == IS_DNS) continue;
465 if (ntype == IS_IP6 && altnamesize != sizeof(struct in6_addr)) {
469 if (ntype == IS_IP4 && altnamesize != sizeof(struct in_addr)) {
472 if (!memcmp(altname, &addr, altnamesize)) {
480 altnamesize = sizeof(altname);
481 ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
482 0, 0, altname, &altnamesize );
484 Debug( LDAP_DEBUG_ANY,
485 "TLS: unable to get common name from peer certificate.\n",
487 ret = LDAP_CONNECT_ERROR;
488 if ( ld->ld_error ) {
489 LDAP_FREE( ld->ld_error );
491 ld->ld_error = LDAP_STRDUP(
492 _("TLS: unable to get CN from peer certificate"));
495 ret = LDAP_LOCAL_ERROR;
496 if ( len1 == altnamesize && strncasecmp(name, altname, altnamesize) == 0 ) {
499 } else if (( altname[0] == '*' ) && ( altname[1] == '.' )) {
500 /* Is this a wildcard match? */
502 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2)) {
508 if( ret == LDAP_LOCAL_ERROR ) {
509 altname[altnamesize] = '\0';
510 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
511 "common name in certificate (%s).\n",
513 ret = LDAP_CONNECT_ERROR;
514 if ( ld->ld_error ) {
515 LDAP_FREE( ld->ld_error );
517 ld->ld_error = LDAP_STRDUP(
518 _("TLS: hostname does not match CN in peer certificate"));
521 gnutls_x509_crt_deinit( cert );
527 tlsm_session_strength( tls_session *session )
529 tlsm_session *s = (tlsm_session *)session;
532 rc = SSL_SecurityStatus( s->ts_session, NULL, NULL, NULL, &keySize,
534 return rc ? 0 : keySize;
538 * TLS support for LBER Sockbufs
542 tlsm_session *session;
543 Sockbuf_IO_Desc *sbiod;
547 static PRStatus PR_CALLBACK
548 tlsm_PR_Close(PRFileDesc *fd)
553 static int PR_CALLBACK
554 tlsm_PR_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
555 PRIntervalTime timeout)
559 if ( buf == NULL || len <= 0 ) return 0;
561 p = (struct tls_data *)fd->secret;
563 if ( p == NULL || p->sbiod == NULL ) {
567 return LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
570 static int PR_CALLBACK
571 tlsm_PR_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags,
572 PRIntervalTime timeout)
576 if ( buf == NULL || len <= 0 ) return 0;
578 p = (struct tls_data *)fd->secret;
580 if ( p == NULL || p->sbiod == NULL ) {
584 return LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
587 static int PR_CALLBACK
588 tlsm_PR_Read(PRFileDesc *fd, void *buf, PRInt32 len)
590 return tlsm_PR_Recv( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
593 static int PR_CALLBACK
594 tlsm_PR_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
596 return tlsm_PR_Send( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
599 static PRStatus PR_CALLBACK
600 tlsm_PR_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
606 p = (struct tls_data *)fd->secret;
608 if ( p == NULL || p->sbiod == NULL ) {
611 len = sizeof(PRNetAddr);
612 return getpeername( p->sbiod->sbiod_sb->sb_fd, (struct sockaddr *)addr, &len );
615 static PRStatus PR_CALLBACK
618 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
622 static PRFileDesc * PR_CALLBACK
625 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
629 static PRInt16 PR_CALLBACK
632 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
636 static PRInt32 PR_CALLBACK
639 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
643 static PRInt64 PR_CALLBACK
648 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
653 static const PRIOMethods tlsm_PR_methods = {
655 tlsm_PR_Close, /* close */
656 tlsm_PR_Read, /* read */
657 tlsm_PR_Write, /* write */
658 tlsm_PR_i32_unimp, /* available */
659 tlsm_PR_i64_unimp, /* available64 */
660 tlsm_PR_prs_unimp, /* fsync */
661 tlsm_PR_i32_unimp, /* seek */
662 tlsm_PR_i64_unimp, /* seek64 */
663 tlsm_PR_prs_unimp, /* fileInfo */
664 tlsm_PR_prs_unimp, /* fileInfo64 */
665 tlsm_PR_i32_unimp, /* writev */
666 tlsm_PR_prs_unimp, /* connect */
667 tlsm_PR_pfd_unimp, /* accept */
668 tlsm_PR_prs_unimp, /* bind */
669 tlsm_PR_prs_unimp, /* listen */
670 (PRShutdownFN)tlsm_PR_Close, /* shutdown */
671 tlsm_PR_Recv, /* recv */
672 tlsm_PR_Send, /* send */
673 tlsm_PR_i32_unimp, /* recvfrom */
674 tlsm_PR_i32_unimp, /* sendto */
675 (PRPollFN)tlsm_PR_i16_unimp, /* poll */
676 tlsm_PR_i32_unimp, /* acceptread */
677 tlsm_PR_i32_unimp, /* transmitfile */
678 tlsm_PR_prs_unimp, /* getsockname */
679 tlsm_PR_GetPeerName, /* getpeername */
680 tlsm_PR_i32_unimp, /* getsockopt OBSOLETE */
681 tlsm_PR_i32_unimp, /* setsockopt OBSOLETE */
682 tlsm_PR_i32_unimp, /* getsocketoption */
683 tlsm_PR_i32_unimp, /* setsocketoption */
684 tlsm_PR_i32_unimp, /* Send a (partial) file with header/trailer*/
685 (PRConnectcontinueFN)tlsm_PR_prs_unimp, /* connectcontinue */
686 tlsm_PR_i32_unimp, /* reserved for future use */
687 tlsm_PR_i32_unimp, /* reserved for future use */
688 tlsm_PR_i32_unimp, /* reserved for future use */
689 tlsm_PR_i32_unimp /* reserved for future use */
693 tlsm_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
696 tlsm_session *session = arg;
699 assert( sbiod != NULL );
701 p = LBER_MALLOC( sizeof( *p ) );
706 fd = PR_GetIdentitiesLayer( session->ts_session, tlsm_layer_id );
712 fd->secret = (PRFilePrivate *)p;
713 p->session = session;
715 sbiod->sbiod_pvt = p;
720 tlsm_sb_remove( Sockbuf_IO_Desc *sbiod )
724 assert( sbiod != NULL );
725 assert( sbiod->sbiod_pvt != NULL );
727 p = (struct tls_data *)sbiod->sbiod_pvt;
728 PR_Close( p->session->ts_session );
729 LBER_FREE( p->session );
730 LBER_FREE( sbiod->sbiod_pvt );
731 sbiod->sbiod_pvt = NULL;
736 tlsm_sb_close( Sockbuf_IO_Desc *sbiod )
740 assert( sbiod != NULL );
741 assert( sbiod->sbiod_pvt != NULL );
743 p = (struct tls_data *)sbiod->sbiod_pvt;
744 PR_Shutdown( p->session->ts_session, PR_SHUTDOWN_BOTH );
749 tlsm_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
753 assert( sbiod != NULL );
754 assert( sbiod->sbiod_pvt != NULL );
756 p = (struct tls_data *)sbiod->sbiod_pvt;
758 if ( opt == LBER_SB_OPT_GET_SSL ) {
759 *((tlsm_session **)arg) = p->session;
762 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
763 PRPollDesc pd = { p->session->ts_session, PR_POLL_READ, 0 };
764 if( PR_Poll( &pd, 1, 1 ) > 0 ) {
769 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
773 tlsm_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
779 assert( sbiod != NULL );
780 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
782 p = (struct tls_data *)sbiod->sbiod_pvt;
784 ret = PR_Recv( p->session->ts_session, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
787 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
788 sbiod->sbiod_sb->sb_trans_needs_read = 1;
789 sock_errset(EWOULDBLOCK);
792 sbiod->sbiod_sb->sb_trans_needs_read = 0;
798 tlsm_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
804 assert( sbiod != NULL );
805 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
807 p = (struct tls_data *)sbiod->sbiod_pvt;
809 ret = PR_Send( p->session->ts_session, (char *)buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
812 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
813 sbiod->sbiod_sb->sb_trans_needs_write = 1;
814 sock_errset(EWOULDBLOCK);
818 sbiod->sbiod_sb->sb_trans_needs_write = 0;
823 static Sockbuf_IO tlsm_sbio =
825 tlsm_sb_setup, /* sbi_setup */
826 tlsm_sb_remove, /* sbi_remove */
827 tlsm_sb_ctrl, /* sbi_ctrl */
828 tlsm_sb_read, /* sbi_read */
829 tlsm_sb_write, /* sbi_write */
830 tlsm_sb_close /* sbi_close */
833 tls_impl ldap_int_moznss_impl = {
845 tlsm_session_connect,
847 tlsm_session_upflags,
850 tlsm_session_peer_dn,
851 tlsm_session_chkhost,
852 tlsm_session_strength,
856 #ifdef LDAP_R_COMPILE
865 #endif /* HAVE_MOZNSS */