如何接受 JNDI/LDAP 连接的自签名证书?

发布于 2024-10-10 19:29:36 字数 1904 浏览 2 评论 0原文

我需要通过 SSL 连接到 LDAP 目录。

在非生产环境中,我们使用自签名证书,当然,该证书无法验证:

javax.naming.CommunicationException: simple bind failed: ldapserver:636 [Root exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target]
 at com.sun.jndi.ldap.LdapClient.authenticate(LdapClient.java:197)
 at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2694)
 at com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:293)
 at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:175)
 at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:193)
 at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:136)
 at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:66)
 at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
 at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
 at javax.naming.InitialContext.init(InitialContext.java:223)
 at javax.naming.ldap.InitialLdapContext.<init>(InitialLdapContext.java:134)

我知道如何使用 用于启用 SSL 的连接的自定义信任管理器,但不知道如何将其与 JNDI API 结合使用我不管理实际连接。也就是说,我可以在哪里插入信任管理器的以下标准设置?

提前致谢。

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldaps://ldapserver:636");
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "myUser");
env.put(Context.SECURITY_CREDENTIALS, "myPassword");
LdapContext ctx = new InitialLdapContext(env, null);
ctx.search (...)

I need to connect to an LDAP directory over SSL.

In non-production environments, we use self-signed certificates which, of course, fails to validate with:

javax.naming.CommunicationException: simple bind failed: ldapserver:636 [Root exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target]
 at com.sun.jndi.ldap.LdapClient.authenticate(LdapClient.java:197)
 at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2694)
 at com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:293)
 at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:175)
 at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:193)
 at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:136)
 at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:66)
 at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
 at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
 at javax.naming.InitialContext.init(InitialContext.java:223)
 at javax.naming.ldap.InitialLdapContext.<init>(InitialLdapContext.java:134)

I am aware of how to use a custom trust manager for SSL-enabled connections, but don't know how to use one in connection with the JNDI API where I don't manage the actual connection. That is, where is the following standard setup will I be able to plug the trust manager?

Thanks in advance.

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldaps://ldapserver:636");
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "myUser");
env.put(Context.SECURITY_CREDENTIALS, "myPassword");
LdapContext ctx = new InitialLdapContext(env, null);
ctx.search (...)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

缪败 2024-10-17 19:29:36

根据 JNDI 文档,似乎可以设置自定义 SSLSocketFactory

http://download.oracle.com/javase/1.5.0/docs/guide/jndi/jndi-ldap-gl.html#socket

public class MySSLSocketFactory extends SocketFactory {
    private static final AtomicReference<MySSLSocketFactory> defaultFactory = new AtomicReference<>();

    private SSLSocketFactory sf;

    public MySSLSocketFactory() {
        KeyStore keyStore = ... /* Get a keystore containing the self-signed certificate) */
        TrustManagerFactory tmf = TrustManagerFactory.getInstance();
        tmf.init(keyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, tmf.getTrustManagers(), null);
        sf = ctx.getSocketFactory();
    }

    public static SocketFactory getDefault() {
        final MySSLSocketFactory value = defaultFactory.get();
        if (value == null) {
            defaultFactory.compareAndSet(null, new MySSLSocketFactory());
            return defaultFactory.get();
        }
        return value;
    }

    @Override
    public Socket createSocket(final String s, final int i) throws IOException {
        return sf.createSocket(s, i);
    }

    @Override
    public Socket createSocket(final String s, final int i, final InetAddress inetAddress, final int i1) throws IOException {
        return sf.createSocket(s, i, inetAddress, i1);
    }

    @Override
    public Socket createSocket(final InetAddress inetAddress, final int i) throws IOException {
        return sf.createSocket(inetAddress, i);
    }

    @Override
    public Socket createSocket(final InetAddress inetAddress, final int i, final InetAddress inetAddress1, final int i1) throws IOException {
        return sf.createSocket(inetAddress, i, inetAddress1, i1);
    }
}

配置使用此套接字工厂的环境

env.put("java.naming.ldap.factory.socket", "com.example.MySSLSocketFactory");

According to the JNDI documentation it seems possible to set a custom SSLSocketFactory

http://download.oracle.com/javase/1.5.0/docs/guide/jndi/jndi-ldap-gl.html#socket

public class MySSLSocketFactory extends SocketFactory {
    private static final AtomicReference<MySSLSocketFactory> defaultFactory = new AtomicReference<>();

    private SSLSocketFactory sf;

    public MySSLSocketFactory() {
        KeyStore keyStore = ... /* Get a keystore containing the self-signed certificate) */
        TrustManagerFactory tmf = TrustManagerFactory.getInstance();
        tmf.init(keyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, tmf.getTrustManagers(), null);
        sf = ctx.getSocketFactory();
    }

    public static SocketFactory getDefault() {
        final MySSLSocketFactory value = defaultFactory.get();
        if (value == null) {
            defaultFactory.compareAndSet(null, new MySSLSocketFactory());
            return defaultFactory.get();
        }
        return value;
    }

    @Override
    public Socket createSocket(final String s, final int i) throws IOException {
        return sf.createSocket(s, i);
    }

    @Override
    public Socket createSocket(final String s, final int i, final InetAddress inetAddress, final int i1) throws IOException {
        return sf.createSocket(s, i, inetAddress, i1);
    }

    @Override
    public Socket createSocket(final InetAddress inetAddress, final int i) throws IOException {
        return sf.createSocket(inetAddress, i);
    }

    @Override
    public Socket createSocket(final InetAddress inetAddress, final int i, final InetAddress inetAddress1, final int i1) throws IOException {
        return sf.createSocket(inetAddress, i, inetAddress1, i1);
    }
}

Configure the environment to use this socket factory

env.put("java.naming.ldap.factory.socket", "com.example.MySSLSocketFactory");
聚集的泪 2024-10-17 19:29:36

当您覆盖 Trustmanager 时,您可以接受任何证书:

DummyTrustmanager.java

public class DummyTrustmanager implements X509TrustManager {
    public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        // do nothing
    }

    public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        // do nothing
    }

    public X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[0];
    }
}

MySSLSocketFactory.java

public class MySSLSocketFactory extends SSLSocketFactory {
    private SSLSocketFactory socketFactory;

    public MySSLSocketFactory() {
        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);
            /* handle exception */
        }
    }

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

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

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

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

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

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

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

    @Override
    public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException {
        return socketFactory.createSocket(ia, i, ia1, i1);
    }

    @Override
    public Socket createSocket() throws IOException {
        return socketFactory.createSocket();
    }
}

Main.java

public class Main {
    public static void main(String[] args) throws NamingException {
        Hashtable env = new Hashtable(11);
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldaps://ldapserver:636/");
        env.put(Context.SECURITY_PROTOCOL, "ssl");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "myUser");
        env.put(Context.SECURITY_CREDENTIALS, "myPassword");
        env.put("java.naming.ldap.factory.socket", "ldapsecure.MySSLSocketFactory");
        LdapContext ctx = new InitialLdapContext(env, null);
    }
}

You could accept any certificate when you override the Trustmanager:

DummyTrustmanager.java

public class DummyTrustmanager implements X509TrustManager {
    public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        // do nothing
    }

    public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        // do nothing
    }

    public X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[0];
    }
}

MySSLSocketFactory.java

public class MySSLSocketFactory extends SSLSocketFactory {
    private SSLSocketFactory socketFactory;

    public MySSLSocketFactory() {
        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);
            /* handle exception */
        }
    }

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

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

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

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

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

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

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

    @Override
    public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException {
        return socketFactory.createSocket(ia, i, ia1, i1);
    }

    @Override
    public Socket createSocket() throws IOException {
        return socketFactory.createSocket();
    }
}

Main.java

public class Main {
    public static void main(String[] args) throws NamingException {
        Hashtable env = new Hashtable(11);
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldaps://ldapserver:636/");
        env.put(Context.SECURITY_PROTOCOL, "ssl");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "myUser");
        env.put(Context.SECURITY_CREDENTIALS, "myPassword");
        env.put("java.naming.ldap.factory.socket", "ldapsecure.MySSLSocketFactory");
        LdapContext ctx = new InitialLdapContext(env, null);
    }
}
沧桑㈠ 2024-10-17 19:29:36

无需代码。只需将证书添加到测试客户端信任库即可。

不要为此编写额外的代码。它是不安全的,并且您面临着代码泄漏到生产中的重大风险。你真的不想要这样。

No code required. Just add the certificate to the test client truststores.

Don't write extra code for this. It is insecure, and you run a major risk of the code leaking into production. You really don't want that.

情魔剑神 2024-10-17 19:29:36

@Jcs 答案是正确的,但如果您不想使用自定义 TrustManager,并且您愿意将该特定自签名证书作为虚拟机内其他用途的受信任 CA,您可以:

  • 添加以下内容证书到您的默认信任库(通常是 JRE 安全目录下的 cacerts),或者
  • 在不同位置创建一个新的信任库(可能基于默认 cacerts 的副本),这将包含该特定证书,并将其用作默认信任库,但设置 javax.net.ssl.trustStore* 系统属性。

@Jcs answer is correct, but if you don't want to use a custom TrustManager, and if you're willing for that particular self-signed certificate to be a trusted CA for other uses within the VM, you can either:

  • add this certificate to your default truststore (usually cacerts under the JRE security directory) or
  • create a new truststore in a different location (possibly based on a copy of the default cacerts) which would contain that particular certificate, and use this as your default truststore, but setting the javax.net.ssl.trustStore* system properties.
夏九 2024-10-17 19:29:36

自从我上次这样做以来已经过去了大约 5 年,所以恐怕我的答案会有点模糊;但我认为如果你在 java.security 中实现了一个可信的提供者,你应该能够在 /usr/java/jre/lib/security/ 下找到它;然后它将接受该证书作为可信证书。

我目前无法访问我的笔记,但稍后我会仔细研究它们

Its been about 5 years since I last did this so my answer will be a bit vague I'm afraid; but I think if you impliment a trusted provider in the java.security which you should be able to find under /usr/java/jre/lib/security/; it will then accept the certificate as trusted.

I dont have access to my notes at the moment, but I'll have a dig through them later

梦里泪两行 2024-10-17 19:29:36

完全抛开 JNDI,一些框架将引用 LOCAL SYSTEM LDAP 配置(通常是 /etc/ldap.conf 或类似的东西)。当我说“本地”时,我指的是运行 JNDI 操作的系统。

至少在大多数支持 LDAP 的 Linux 操作系统中,此类 LDAP 配置文件的内部(通常)有一行内容:

TLS_REQCERT demand

这是默认的 TLS/SSL 关键性设置(也是最严格的),因为它会使如果证书有任何问题(包括自签名),则连接。

您可以尝试不同的设置而不是“需求”(使用“允许”或“从不”)。完成此操作后,再次尝试您的操作,看看您的问题是否消失。同样,并非所有类似的东西都会读取甚至检测您的本地系统设置。有些会,有些不会。值得一看。

我希望这会有所帮助...

麦克斯

Setting aside JNDI entirely, some frameworks will refer to the LOCAL SYSTEM LDAP configuration (this is typically /etc/ldap.conf or something like that). When I say LOCAL, I mean the system(s) on which your JNDI operation is running.

At least in the case of most LDAP-enabled Linux OSs, inside of such an LDAP config file is (usually) a line that reads:

TLS_REQCERT demand

This is the default TLS/SSL criticality setting (and the most strict), as it will fail the connection if ANYTHING WHATSOEVER is wrong with the certificate (this includes being self-signed).

You can experiment with different settings instead of 'demand' (play with 'allow' or 'never'). Once this is done, try your operation again and see if your issue subsides. Again, not all things like this will read or even detect your local system settings. Some do, some don't. Worth a look.

I hope this helps...

Max

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文