SpringLDAP连接LDAPS证书报错问题及解决

 更新时间:2024年05月20日 10:48:17   作者:初心绘流年  
这篇文章主要介绍了SpringLDAP连接LDAPS证书报错问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

一、问题背景

Java操作LDAP一般通过Spring LDAP比较方便,一般我们都是使用的常规的非加密的389端口

常规的初始化如下:

LdapContextSource contextSource = new LdapContextSource();
contextSource.setUserDn(config.getUsername());
contextSource.setPassword(config.getPassword());
String url = "ldap://" + config.getServer() + ":" + config.getPort();

contextSource.setUrl(url);
contextSource.setBase(config.getBaseDn());
contextSource.setAnonymousReadOnly(false);
contextSource.setPooled(false);
contextSource.afterPropertiesSet();

this.ldapTemplate = new LdapTemplate(contextSource);
this.ldapTemplate.setIgnorePartialResultException(true);

但是最近遇到一个使用证书加密环境的LDAP,即LDAPS(LDAP+SSL),使用的是636端口,再使用上述的配置,则会报错,可能会报以下的未找到合法证书的错误:

simple bind failed: 172.16.10.2:636; nested exception is javax.naming.CommunicationException: simple bind failed: 172.16.10.2:636 [Root exception is javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target]

二、解决方案

一般我们在Java使用HTTPS客户端的时候为了避免证书报错,一般会将客户端证书导入到JDK中,但是有些环境的证书是自签名的证书,导入也不一定能解决问题。

因此多数也会通过X509TrustManager和SSLSocketFactory绕过证书校验,所以我们对于LDAPS也采用同样的思路来解决,网上有类似的解决方案,但是集成之后可能还是存在以下的报错:

org.springframework.ldap.CommunicationException: simple bind failed: 172.16.10.2:636; nested exception is javax.naming.CommunicationException: simple bind failed: 172.16.10.2:636 [Root exception is javax.net.ssl.SSLHandshakeException: No subject alternative names matching IP address 172.16.10.2 found]
    at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:108)
    at org.springframework.ldap.core.support.AbstractContextSource.createContext(AbstractContextSource.java:355)
    at org.springframework.ldap.core.support.AbstractContextSource.doGetContext(AbstractContextSource.java:139)
    at org.springframework.ldap.core.support.AbstractContextSource.getReadOnlyContext(AbstractContextSource.java:158)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:357)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:309)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:642)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:578)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:1617)

simple bind failed: XXXXX.com:636; nested exception is javax.naming.CommunicationException: simple bind failed: XXXXX.com:636 [Root exception is javax.net.ssl.SSLHandshakeException: No subject alternative DNS name matching XXXXX.com found.]

org.springframework.ldap.CommunicationException: simple bind failed: 172.16.10.2:636; nested exception is javax.naming.CommunicationException: simple bind failed: 172.16.10.2:636 [Root exception is java.net.SocketException: Connection or outbound has closed]
    at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:108)
    at org.springframework.ldap.core.support.AbstractContextSource.createContext(AbstractContextSource.java:355)
    at org.springframework.ldap.core.support.AbstractContextSource.doGetContext(AbstractContextSource.java:139)
    at org.springframework.ldap.core.support.AbstractContextSource.getReadOnlyContext(AbstractContextSource.java:158)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:357)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:309)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:642)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:578)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:1617)

我的解决方案分为以下几个步骤,能规避以上错误:

(1)自定义SSLSocketFactory

package com.bugdongdong.utils.tools.ldap;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class CustomSSLSocketFactory extends SSLSocketFactory {
    private SSLSocketFactory socketFactory;

    public CustomSSLSocketFactory() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[]{new DummyTrustmanager()}, new SecureRandom());
            socketFactory = ctx.getSocketFactory();
        } catch (Exception ex) {
            ex.printStackTrace(System.err);
        }
    }

    public static SocketFactory getDefault() {
        return new CustomSSLSocketFactory();
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return socketFactory.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return socketFactory.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket(Socket socket, String string, int num, boolean bool) throws IOException {
        return socketFactory.createSocket(socket, string, num, bool);
    }

    @Override
    public Socket createSocket(String string, int num) throws IOException, UnknownHostException {
        return socketFactory.createSocket(string, num);
    }

    @Override
    public Socket createSocket(String string, int num, InetAddress netAdd, int i) throws IOException, UnknownHostException {
        return socketFactory.createSocket(string, num, netAdd, i);
    }

    @Override
    public Socket createSocket(InetAddress netAdd, int num) throws IOException {
        return socketFactory.createSocket(netAdd, num);
    }

    @Override
    public Socket createSocket(InetAddress netAdd1, int num, InetAddress netAdd2, int i) throws IOException {
        return socketFactory.createSocket(netAdd1, num, netAdd2, i);
    }

    /**
     * 绕过证书校验
     */
    public static class DummyTrustmanager implements X509TrustManager {
        public void checkClientTrusted(X509Certificate[] cert, String string) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] cert, String string) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

    }
}

(2)自定义支持SSL的SSLContextSource

package com.bugdongdong.utils.tools.ldap;

import org.springframework.ldap.core.support.LdapContextSource;
import javax.naming.Context;
import java.util.Hashtable;

public class SSLLdapContextSource extends LdapContextSource {
    public Hashtable<String, Object> getAnonymousEnv(){
        // 禁用jdk8以上对ldap的端点校验
        System.setProperty("com.sun.jndi.ldap.object.disableEndpointIdentification", "true");
        Hashtable<String, Object> anonymousEnv = super.getAnonymousEnv();
        anonymousEnv.put("java.naming.security.protocol", "ssl");
        anonymousEnv.put("java.naming.ldap.factory.socket", CustomSSLSocketFactory.class.getName());
        anonymousEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        return anonymousEnv;
    }
}

(3)构建支持SSL的LdapTemplate

// 普通ldap连接使用普通的Context配置
LdapContextSource contextSource = new LdapContextSource();
String url = "";
if (DataSourceLdapConfig.TRANSPORT_TYPE_CLEAR.equals(config.getTransportType())) {
    url = "ldap://" + config.getServer() + ":" + config.getPort();
} else if (DataSourceLdapConfig.TRANSPORT_TYPE_LDAPS.equals(config.getTransportType())) {
    url = "ldaps://" + config.getServer() + ":" + config.getPort();
    // ldaps使用自定义的支持SSL的Context配置
    contextSource = new SSLLdapContextSource();
}
contextSource.setUserDn(config.getUsername());
contextSource.setPassword(config.getPassword());
contextSource.setUrl(url);
contextSource.setBase(config.getBaseDn());
contextSource.setAnonymousReadOnly(false);
contextSource.setPooled(false);
contextSource.afterPropertiesSet();

this.ldapTemplate = new LdapTemplate(contextSource);
this.ldapTemplate.setIgnorePartialResultException(true);

配置完成后,测试连接即可。

三、问题讨论

需要注意的是,上述有一项配置非常重要,即

System.setProperty("com.sun.jndi.ldap.object.disableEndpointIdentification", "true");

这项配置是JDK8之后需要加上的,官方在JDK8更新后加了端点校验,即使是通过TrustManager绕过了证书校验,有可能还是会因为证书不匹配报错,当然该项配置除了上述这种方式写入,也可以通过JVM参数在程序启动时加入

-Dcom.sun.jndi.ldap.object.disableEndpointIdentification=true

附该项校验使用的源码

以下是官方对该项配置的解释:

Java 8 Update 181 (8u181)

发行版要点说明

IANA Data 2018e

**删除的功能:**删除 Java DB

  • Java DB 也称为 Apache Derby,已在本发行版中删除。
  • 建议您直接从以下网址的 Apache 项目获取最新的 Apache Derby:
  • https://db.apache.org/derby
  • JDK-8197871(非公共)

**更改:**改进 LDAP 支持

  • 已在 LDAPS 连接上启用端点识别。
  • 为提高 LDAPS(TLS 上的安全 LDAP)连接的强健性,默认情况下已启用端点识别算法。
  • 请注意,可能在一些情况下,以前能够成功连接到 LDAPS 服务器的一些应用程序可能不再能够成功连接。如果此类应用程序认为合适的话,它们可能会使用新系统属性禁用端点识别:com.sun.jndi.ldap.object.disableEndpointIdentification。
  • 定义此系统属性(或者将它设置为 true)可禁用端点识别算法。

参考资料

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • java数据类型与变量的安全性介绍

    java数据类型与变量的安全性介绍

    这篇文章主要介绍了java数据类型与变量的安全性介绍,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下
    2022-07-07
  • Spring详细讲解@Autowired注解

    Spring详细讲解@Autowired注解

    @Autowired注解可以用在类属性,构造函数,setter方法和函数参数上,该注解可以准确地控制bean在何处如何自动装配的过程。在默认情况下,该注解是类型驱动的注入
    2022-06-06
  • Java实现租车管理系统

    Java实现租车管理系统

    这篇文章主要为大家详细介绍了Java实现租车管理系统,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-01-01
  • 实现分布式WebSocket集群的方法

    实现分布式WebSocket集群的方法

    本文总结出了几个实现分布式WebSocket集群的办法,从zuul到spring cloud gateway的不同尝试,总结出了这篇文章,希望能帮助到某些人,并且能一起分享这方面的想法与研究
    2022-03-03
  • spring+netty服务器搭建的方法

    spring+netty服务器搭建的方法

    本篇文章主要介绍了spring+netty服务器搭建的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-01-01
  • IDEA查看所有的断点(Breakpoints)并关闭的方式

    IDEA查看所有的断点(Breakpoints)并关闭的方式

    我们在使用IDEA开发Java应用时,基本上都需要进行打断点的操作,这方便我们排查BUG,也方便我们查看设计的是否正确,不过有时候,我们不希望进入断点,所以我们需要快速关闭所有断点,故本文给大家介绍了IDEA查看所有的断点(Breakpoints)并关闭的方式
    2024-10-10
  • 详解配置spring-boot-actuator时候遇到的一些小问题

    详解配置spring-boot-actuator时候遇到的一些小问题

    这篇文章主要介绍了详解配置spring-boot-actuator时候遇到的一些小问题,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-11-11
  • IntelliJ IDEA的代码搁置功能实现

    IntelliJ IDEA的代码搁置功能实现

    本文主要介绍了IntelliJ IDEA的代码搁置功能实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-01-01
  • Mybatis实现动态建表代码实例

    Mybatis实现动态建表代码实例

    这篇文章主要介绍了Mybatis实现动态建表代码实例,解释一下,就是指根据传入的表名,动态地创建数据库表,以供后面的业务场景使用,
    而使用 Mybatis 的动态 SQL,就能很好地为我们解决这个问题,需要的朋友可以参考下
    2023-10-10
  • Java BOI与NIO超详细实例精讲

    Java BOI与NIO超详细实例精讲

    在Java的软件设计开发中,通信架构是不可避免的,我们在进行不同系统或者不同进程之间的数据交互,或者在高并发下的通信场景下都需要用到网络通信相关的技术,对于一些经验丰富的程序员来说,Java早期的网络通信架构存在一些缺陷,这篇文章介绍Java BOI与NIO
    2022-11-11

最新评论