Connect active directory with the support of ssl (ldaps) - java

am trying to connect with active directory with the support of ssl.
i tried the steps from following web site.
http://confluence.atlassian.com/display/CROWD/Configuring+an+SSL+Certificate+for+Microsoft+Active+Directory
when i try to connect active directory from the java code it gives following error.
Exception in thread "main" javax.naming.CommunicationException: simple bind fail
ed: 172.16.12.4:636 [Root exception is java.net.SocketException: Connection rese
t]
at com.sun.jndi.ldap.LdapClient.authenticate(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.connect(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.<init>(Unknown Source)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(Unknown Source)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(Unknown Source)
at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(Unknown Source)
at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(Unknown Source)
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.init(Unknown Source)
at javax.naming.InitialContext.<init>(Unknown Source)
at javax.naming.directory.InitialDirContext.<init>(Unknown Source)
at ConnectActiveDirectory.main(ConnectActiveDirectory.java:39)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.waitForClose(Unknown Sourc
e)
at com.sun.net.ssl.internal.ssl.HandshakeOutStream.flush(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.kickstart(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.kickstartHandshake(Unknown
Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Un
known Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(Unknown Source
)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at com.sun.jndi.ldap.Connection.writeRequest(Unknown Source)
at com.sun.jndi.ldap.Connection.writeRequest(Unknown Source)
at com.sun.jndi.ldap.LdapClient.ldapBind(Unknown Source)
... 13 more
Code that am using is
import java.util.Hashtable;
import javax.naming.*;
import javax.naming.directory.*;
public class ConnectActiveDirectory {
public static void main(String[] args) throws NamingException {
Hashtable env = new Hashtable();
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL,"Administrator#mysite.com");
env.put(Context.SECURITY_CREDENTIALS, "password");
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldaps://172.16.12.4:636/cn=Users,dc=mysite,dc=com");
try{
java.io.InputStream in = new java.io.FileInputStream("C:\\client.crt");
java.security.cert.Certificate c = java.security.cert.CertificateFactory.getInstance("X.509").generateCertificate(in);
java.security.KeyStore ks = java.security.KeyStore.getInstance("JKS");
ks.load(null);
if (!ks.containsAlias("alias ldap")) {
ks.setCertificateEntry("alias ldap", c);
}
java.io.OutputStream out = new java.io.FileOutputStream("C:\\keystorefile.jks");
char[] kspass = "changeit".toCharArray();
ks.store(out, kspass);
out.close();
}catch(Exception e){
e.printStackTrace();
}
System.setProperty("javax.net.ssl.trustStore", "C:\\keystorefile.jks");
DirContext ctx = new InitialDirContext(env);
NamingEnumeration enm = ctx.list("");
while (enm.hasMore()) {
System.out.println(enm.next());
}
ctx.close();
}
}
does am doing any mistake?
where can i get good tutorial to do ssl connection with active directory ?
does http://confluence.atlassian.com/display/CROWD/Configuring+an+SSL+Certificate+for+Microsoft+Active+Directory site has correct steps to create and connect active directory with ssl?
could any on please help me.

I had a similar issue after my AD domain was renamed. After reinstalling certificate services, you need to delete and re-issue the certificate issued to your Domain Controller. Steps:
Open MMC
Add Snap In > Certificates > Computer > Local Computer
Navigate to Personal > Certificates
Delete any old certificates issued to this machine (in my case, these were issued by the old CA)
Right click on Certificates folder, click Request New Certificate.
Follow the steps to issue the new certificate to your domain controller.
Restart (not sure if this is necessary, but I restarted before it worked)

I had the same error message using Atlassian Crowd and Active Directory over SSL. It is not applicable to this specific question, but when I tried to find out what was happening this thread was the first Google search hit, so I will write it down here.
In my case I first tested without SSL and then changed to SSL. Turns out I forgot to change the protocol used in the Crowd Connector settings.
Before: ldap://:389
After: ldaps://:636
Accidentally using ldap://:636 gave me the "Connection reset" error.

Related

How do I update an SSL certificate - using bouncycastle for TLS1.2 in java

I have a java application that speaks TLS1.2 over SSL to a 3rd-party. Recently they updated their certificate that "broke" the app.
org.bouncycastle.tls.TlsFatalAlert: bad_certificate(42)
at org.bouncycastle.jsse.provider.ProvTlsClient$1.notifyServerCertificate(Unknown Source)
at org.bouncycastle.tls.TlsUtils.processServerCertificate(Unknown Source)
at org.bouncycastle.tls.TlsClientProtocol.handleServerCertificate(Unknown Source)
at org.bouncycastle.tls.TlsClientProtocol.handleHandshakeMessage(Unknown Source)
at org.bouncycastle.tls.TlsProtocol.processHandshakeQueue(Unknown Source)
at org.bouncycastle.tls.TlsProtocol.processRecord(Unknown Source)
at org.bouncycastle.tls.RecordStream.readRecord(Unknown Source)
at org.bouncycastle.tls.TlsProtocol.safeReadRecord(Unknown Source)
at org.bouncycastle.tls.TlsProtocol.blockForHandshake(Unknown Source)
at org.bouncycastle.tls.TlsClientProtocol.connect(Unknown Source)
at org.bouncycastle.jsse.provider.ProvSSLSocketDirect.startHandshake(Unknown Source)
at org.bouncycastle.jsse.provider.ProvSSLSocketDirect.handshakeIfNecessary(Unknown Source)
at org.bouncycastle.jsse.provider.ProvSSLSocketDirect$AppDataOutput.write(Unknown Source)
at java.io.DataOutputStream.writeBytes(DataOutputStream.java:259)
Not sure how to install the new cert, which I have in *.cer format. I tried adding to the jre using keytool, but it didn't fix it. Is there a separate bouncycastle store I need to add it to? If so how?
Security.addProvider(new BouncyCastleProvider());
Security.addProvider(new BouncyCastleJsseProvider());
SSLContext context = SSLContext.getInstance("TLSv1.2", BouncyCastleJsseProvider.PROVIDER_NAME);
context.init( null, null, new SecureRandom() );
SSLSocketFactory ssf = context.getSocketFactory();
SSLSocket s = (SSLSocket) ssf.createSocket( HOST, activePort );
DataOutputStream dos = new DataOutputStream( s.getOutputStream() );
Thanks for any help!

Java Socket Programming Exception

I'm receiving java socket programming exception. This is a code from the Book "Java Complete reference Oracle"
import java.net.*;
import java.io.*;
public class Whois {
public static void main(String[] args)throws Exception{
int c;
Socket s = new Socket("whois.internic.net",43);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
String str = (args.length == 0 ? "OraclePressBooks.com" : args[0]) + "\n";
byte buf[] = str.getBytes();
out.write(buf);
while((c=in.read())!=-1)
{
System.out.println((char)c);
}
s.close();
}
}
I'm getting following exception. But Why?
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at Whois.main(Whois.java:8)
P.S. I'm using Eclipse Photon. I tried running eclipse "as administrator" and also without it.
You do not have network connectivity to remote TCP port 43.
But since you've written that you have "proper network connection" because you are "using WiFi", we may suppose you have at least a web access (through a transparent proxy, or direct connections).
Therefore, you can simply use a Whois web service to access Whois databases.
Some registrars offer a RWS-DNRD endpoint, that is a RESTful Web Service for Domain Name Registration Data (https://tools.ietf.org/id/draft-sheng-weirds-icann-rws-dnrd-01.html). You will find many examples of RESTful clients, for instance here: https://www.javacodegeeks.com/2012/09/simple-rest-client-in-java.html
In your case, you want to access the Internic database, so you can simply query their web form, using a GET request, like that (Java 9):
URL u = new URL("https://reports.internic.net/cgi/whois?whois_nic=OraclePressBooks.com&type=domain");
try (InputStream in = u.openStream()) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}

RabbitMQ Connection reset

I'm trying to connect a simple RabbitMQ using java code to my server (which is executing the RabbitMQ service).
Executing the following code (source here) gives me the java.net.SocketException: Connection Reset exception.
import java.io.*;
import java.security.*;
import com.rabbitmq.client.*;
public class test
{
public static void main(String[] args) throws Exception
{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("myIP"); //myIP is just dummy text, I have a real IP there
factory.setPort(5672);
factory.setUsername("admin");
factory.setPassword("sesgo");
factory.setVirtualHost("vSESGO");
factory.useSslProtocol();
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
channel.queueDeclare("rabbitmq-java-test", false, true, true, null);
channel.basicPublish("", "rabbitmq-java-test", null, "Hello, World".getBytes());
GetResponse chResponse = channel.basicGet("rabbitmq-java-test", false);
if(chResponse == null) {
System.out.println("No message retrieved");
} else {
byte[] body = chResponse.getBody();
System.out.println("Recieved: " + new String(body));
}
channel.close();
conn.close();
}
}
I've looked for an answer online and I've already tried:
Verifying the server has the port I'm connecting to opened.
Verifying the client does not block my connection with firewalls, etc.
Creating a new Virtual Host on RabbitMQ and giving permissions to it.
Verifying iptables is not blocking me at the server side.
Nothing seems to work, any ideas?
Full stacktrace here:
This trust manager trusts every certificate, effectively disabling peer verification. This is convenient for local development but prone to man-in-the-middle attacks. Please see http://www.rabbitmq.com/ssl.html#validating-cerficates to learn more about peer certificate validation.
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.security.ssl.InputRecord.readFully(Unknown Source)
at sun.security.ssl.InputRecord.read(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.writeRecord(Unknown Source)
at sun.security.ssl.AppOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at java.io.DataOutputStream.flush(Unknown Source)
at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:147)
at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:153)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:294)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:63)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:99)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:921)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:880)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:838)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:990)
at test.main(test.java:25)
I had the same issue right here: RabbitMQ Connection reset Exception. Solution for Windows was to add backslash in rabbit config file for paths to certs and key.
I don't know if this applies to your situation, but I recently resolved a similar situation while testing RabbitMQ 3.8.3, and the cause was that the key I was referencing was password-protected, but I had failed to provide the password in the RabbitMQ config, like this:
ssl_options.password = password
Unfortunately there was absolutely nothing in the RabbitMQ logs about this, even with the log level set to debug. When testing via various clients, a connection was established, but RabbitMQ immediately sent a connection reset.
I had this exact same error and my issue was in the rabbitmq.conf file. I was trying to use a JKS file for the following ssl options. Generating my own self signed .pem files was able to help fix this. I followed this guide pretty closely https://www.codetd.com/en/article/12031242.
ssl_options.cacertfile = /etc/rabbitmq/ca_certificate.pem
ssl_options.certfile = /etc/rabbitmq/server_certificate.pem
ssl_options.keyfile = /etc/rabbitmq/server_key.pem

"java.net.SocketException: Connection reset" when running a simpleSSL client

I am attempting to create a client/server using the SSL communication. I followed the instructions listed here (https://www.rabbitmq.com/ssl.html).
I am greeted with this error:
while running the server :
java.net.SocketException: Connection reset
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at java.io.DataOutputStream.flush(DataOutputStream.java:123)
at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:129)
at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:134)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:277)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:678)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:722)
while using the client :
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.security.ssl.InputRecord.readFully(Unknown Source)
at sun.security.ssl.InputRecord.read(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.waitForClose(Unknown Source)
at sun.security.ssl.HandshakeOutStream.flush(Unknown Source)
at sun.security.ssl.Handshaker.kickstart(Unknown Source)
at sun.security.ssl.SSLSocketImpl.kickstartHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.writeRecord(Unknown Source)
at sun.security.ssl.AppOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at java.io.DataOutputStream.flush(Unknown Source)
at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:129)
at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:134)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:277)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:678)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:722)
at rmqClient.simpleSSL.main(simpleSSL.java:23)
here's my rabbit.config file :
[
{ssl, [{versions, ['tlsv1.2', 'tlsv1.1']}]},
{
rabbit,
[
{ssl_listeners, [5675]},
{ssl_options, [{cacertfile,"sslConn/ca_certificate.pem"},
{certfile, "sslConn/server_certificate.pem"},
{keyfile, "sslConn/server_key.pem"},
{versions, ['tlsv1.2', 'tlsv1.1']},
{ciphers, [{ecdhe_ecdsa,aes_128_cbc,sha256},
{ecdhe_ecdsa,aes_256_cbc,sha}]}
]},
{tcp_listeners, [5672]},
{loopback_users, []}
]
}
].
here's also my client code :
factory.setHost("10.3.9.139");
factory.setPort(5673);
factory.setUsername("User1");
factory.setPassword("User1");
factory.useSslProtocol();
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
channel.queueDeclare("rabbitmq-java-test", false, true, true, null);
channel.basicPublish("", "rabbitmq-java-test", null, "Hello, World".getBytes());
java.net.SocketException: Connection reset is generally speaking caused by remote peer closed connection.
I guess your SSL config didn't fit well with server.
Suggestion here is to debug SSL connection to find root cause.
Try to append this system property to your JVM params:
-Djavax.net.debug=all
More details here
I was able to fix this in Java 1.7 by specifying:
SSLContext sc = SSLContext.getInstance("TLSv1.2");
In the v configuration you have set port 5675 for SSL listener, but in code you are using 5673.

Remote lookup of slsb failing from jar file, although very similar lookup from a jar file being called from same place works

I have a a number of jar files that perform rmi. These are all working except one, the problematic one attempts to look up a remote slsb in a different project.
So the code is the same here:
machineNameOrAddress = args[0];
jndiPortNumber = args[1];
action = args[2];
Properties properties = new Properties();
properties.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
properties.setProperty("java.naming.provider.url", "jnp://" + machineNameOrAddress + ":" + jndiPortNumber);
properties.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");
try {
initialContext = new InitialContext(properties);
But then the difference occurs; this is OK:
IEmailNotificationSLSBRemote notificationSLSBRemote = (IEmailNotificationSLSBRemote) initialContext.lookup("ProjectOne/EmailNotificationSLSB/remote");
This is not OK:
IEmailNotificationSLSBRemote notificationSLSBRemote = (IEmailNotificationSLSBRemote) initialContext.lookup("ProjectTwo/EmailNotificationSLSB/remote");
Everythign compiles everythign else works OK, I think have set everythign up ok (well almost everything).
This is the error, it is the same client directory. The rmi's are being invoked in the same place.
javax.naming.CommunicationException [Root exception is java.lang.ClassNotFoundException: my.path.ProjTwo.client.interfaces.IEmailNotificationSLSBRemote (no security manager: RMI class loader disabled)]
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:786)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:627)
at javax.naming.InitialContext.lookup(Unknown Source)
at uk.co.tpplc.hands.client.utils.EmailNotificationUtil.main(EmailNotificationUtil.java:47)
Caused by: java.lang.ClassNotFoundException: uk.co.tpplc.hands.client.interfaces.IEmailNotificationSLSBRemote (no security manager: RMI class loader disabled)
at sun.rmi.server.LoaderHandler.loadProxyClass(Unknown Source)
at java.rmi.server.RMIClassLoader$2.loadProxyClass(Unknown Source)
at java.rmi.server.RMIClassLoader.loadProxyClass(Unknown Source)
at sun.rmi.server.MarshalInputStream.resolveProxyClass(Unknown Source)
at java.io.ObjectInputStream.readProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at java.rmi.MarshalledObject.get(Unknown Source)
at org.jnp.interfaces.MarshalledValuePair.get(MarshalledValuePair.java:72)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:710)
... 3 more
Any help greatly appreciated. The slsbs are present in both projects, they do almost the same thing. The jar files compile fine and a located in same location.
And both a present and correct in jmx console jboss.j2ee:
ear=ProjectOne.ear,jar=ProjectOne-ejb.jar,name=EmailNotificationSLSB,service=EJB3
ear=ProjectTwo.ear,jar=ProjectTwo-ejb.jar,name=EmailNotificationSLSB,service=EJB3
ProjectTwo jar file needed to be copied to the directory containing the calling jars.

Categories