How do I connect to the localhost using UnboundID LDAP SDK? - java

How do I connect to the localhost using UnboundID LDAP SDK? I would think it is pretty straight forward, but maybe not. I connect just fine using the following code, but I would like to have the option to just use the locahost connection and not have to authenticate.
With the connection, I perform a series of add/remove/modify, which works fine with the below connection.
public LDAPConnection connect(LdapConnectionModel connectionModel)
{
this.connectionModel = connectionModel;
try
{
// Determine is SSL port was specified
int port = connectionModel.isSslEnabled() ? SSL_PORT : PORT;
// Determined bind DN
String bindDN = connectionModel.getUsername() + "#" + connectionModel.getDomain();
// Connect
connection = new LDAPConnection(connectionModel.getHost(), port, bindDN, String.valueOf(connectionModel.getPassword()));
// Clear out our password
connectionModel.setPassword(new char[] {});
}
catch (LDAPException e)
{
LOG.warning("CONNECTION FAILED: " + e.getMessage());
LOG.warning(e.getMessage());
}
return connection;
}
For example, getting a connection like this is fine, but then I get this error:
"In order to perform this operation a successful bing must be completed on the connection."
// Connect
connection = new LDAPConnection("localhost",389);

It makes no difference where, or on which host, the directory server is running. When an LDAP client connects to a server, that connection is unauthenticated. LDAP clients must use the BIND request to request the server change the authorization state of the connection to a state that permits the operations that the LDAP client desires.
see also
LDAP: Authentication Best Practices
LDAP: Programming Practices

Related

Access refused - Login was refused using authentication mechanism PLAIN RabbitMQ Queue

I am trying to use RabbitMQ for posting messages from one application and receiving them in another.
I am able to post messages using localhost.
ex: amqp://guest:guest#localhost:5672
when i trying to post messages using different Ip getting below mention exception.
com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED-Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
sample code:
private Connection getConnection(){
Connection connection = null;
try {
ConnectionFactory factory = new ConnectionFactory();
final URI uri = URI.create(PropertyReader.read("rabbit.mq.uri").trim());
factory.setConnectionTimeout(30000);
factory.setAutomaticRecoveryEnabled(true);
factory.setTopologyRecoveryEnabled(true);
factory.setNetworkRecoveryInterval(10000);
factory.setExceptionHandler(new DefaultExceptionHandler());
factory.setRequestedHeartbeat(360);
factory.setUri(uri);
connection = factory.newConnection();
LOGGER.info("Rabbit MQ Connection established successfully");
} catch (Exception e) {
LOGGER.error("Error { }"+e);
}
return connection;
}
I need help for this.
using telnet i checked provided Ip.
The guest user can only connect to localhost by default: see the documentation.
"guest" user can only connect via localhost
By default, the guest user is prohibited from connecting to the broker remotely; it can only connect over a loopback interface (i.e. localhost). This applies both to AMQP 0-9-1 and to any other protocols enabled via plugins. Any other users you create will not (by default) be restricted in this way.
This is configured via the loopback_users item in the configuration file.
If you wish to allow the guest user to connect from a remote host, you should set the loopback_users configuration to none.
...
Add the user / pass combination to the factory:
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("user_name");
factory.setPassword("super_secret_pass");

Smack XMPP: Can't login to openfire server: "SASLErrorException: SASLError using DIGEST-MD5: not-authorized"

I am trying to create a basic connection and login to an Openfire server that I have installed. I have the following user in my users database which I created through the Openfire web admin interface:
User: user
Password: 12345678
I can connect fine to the server as the connection returns true in my sout. The problem is when it tries to log in I get the following error:
org.jivesoftware.smack.sasl.SASLErrorException: SASLError using DIGEST-MD5: not-authorized
I have the following code:
private XMPPConnection connection;
public void connect(String serverIP) {
try {
System.setProperty("smack.debugEnabled", "true");
ConnectionConfiguration config = new ConnectionConfiguration(serverIP, 5223);
config.setDebuggerEnabled(true);
config.setSocketFactory(new DummySSLSocketFactory());
config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
config.setCompressionEnabled(true);
connection = new XMPPTCPConnection(config);
connection.connect();
System.out.println("Connected: " + connection.isConnected());
connection.login("user", "12345678");
System.out.println("Logged in: " + connection.isAuthenticated());
} catch (SmackException | IOException | XMPPException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
connectionHandler test = new connectionHandler();
test.connect("localhost");
}
If anyone can correct what I am doing wrong I would be really grateful.
I have also tried the username as the email would be for example
user#localhost.com
or
user#localhost
I finally managed to find the answer to this. The problem (possibly not even a problem) was that the authentication methods weren't set in the server config and as default allowed all methods. The first one chosen in java seems to be DIGEST-MD5 which was what was causing the errors. To fix this I added:
<sasl>
<mechs> PLAIN </mechs>
</sasl>
before the last closing tag of the openfire.xml found in the config folder of the server. This can also be changed in the ofproperty database table for the column called sasl.mechs.
Hopefully this helps someone (possibly me) in the future.
P.S. this is unsecure if not using SSL (port 5223 by default)
SASLError using DIGEST-MD5: not-authorized
This is most likely caused because you did not configure the correct XMPP domain (/service name) in your ConnectionConfiguration. DIGEST-MD5 would not only fail if the username or password is wrong, but also if the wrong XMPP domain is used.

Java - connect to webpage using SSH tunneling

fellow Java coders. I have recently been faced with an interesting task - to create software that would use an SSH tunnel as a proxy for browsing webpages (over HTTPS). After reading some docs on JSCH (http://www.jcraft.com/jsch/, a Java SSH tunneling library), which all gave database connections as an example, I decided to try it myself. Here is the connection code I copied from http://kahimyang.info/kauswagan/code-blogs/1337/ssh-tunneling-with-java-a-database-connection-example
int assigned_port;
int local_port=3309;
// Remote host and port
int remote_port=3306;
String remote_host = "<SSH host goes here>";
String login = "<SSH login goes here>";
String password = "<SSH password goes here>";
try {
JSch jsch = new JSch();
// Create SSH session. Port 22 is your SSH port which
// is open in your firewall setup.
Session session = jsch.getSession(login, remote_host, 22);
session.setPassword(password);
// Additional SSH options. See your ssh_config manual for
// more options. Set options according to your requirements.
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
config.put("Compression", "yes");
config.put("ConnectionAttempts","2");
session.setConfig(config);
// Connect
session.connect();
// Create the tunnel through port forwarding.
// This is basically instructing jsch session to send
// data received from local_port in the local machine to
// remote_port of the remote_host
// assigned_port is the port assigned by jsch for use,
// it may not always be the same as
// local_port.
assigned_port = session.setPortForwardingL(local_port,
remote_host, remote_port);
} catch (JSchException e) {
System.out.println("JSch:" + e.getMessage());
return;
}
if (assigned_port == 0) {
System.out.println("Port forwarding failed!");
return;
}
Now, I am not exactly experienced with all the port forwarding stuff, but, if I understand it correctly, the code is supposed to forward all connections incoming to 127.0.0.1:3309 (or whatever the assigned_port is) through the SSH server. Now I'm stuck. How am I supposed to send a HttpsURLConnection through 127.0.0.1:3309? I tried defining it as an HTTP or HTTPS or SOCKS proxy, but neither works. Can anybody help me?
The code you have posted will forward all traffic from 127.0.0.1:3309 to port 3306 on the SSH server you have connected to.
When using port forwarding you treat the listening address:port as if it were the actual destination. So if you need to use a HttpsURLConnection you would construct it with a URL of
https://127.0.0.1:3309/
Obviously you also need to append a path to the URL depending on what you are trying to achieve. I would suggest modifying your code to use more standard HTTP ports, try with HTTP first and once that is working move to HTTPS
int local_port=8080;
// Remote host and port
int remote_port=80;
The URL for above will be
http://127.0.0.1:8080
You can always test the URL by pasting it into a browser.
One of the problems you may encounter using HTTPS is certificate validation so this is why I suggest testing plain HTTP first to prove your code is working.

Port forwarding with nginx from java

I'm trying to make a java application which uses redis as a backend. Since Redis is a really fast key-value store which I'd like to use, but redis is made to be used with 1 client so it doesn't have an option for user:pass authentication. I'd like to find a way to implement some kind of authentication, so I tried nginx with the redis2 extension. I did this because I could use client-side certficates and HTTPS. But it's making my application really slow.
I'm thinking about using some kind of tunnel which connects to redis via nginx proxy. For this redis would be listen on localhost and there would be an address which I'd like to use to reach redis, but with https authentication. So basically my current method
JAVA - Jedis - LAN - REDIS ,would be
JAVA - Jedis(with localhost as the tunnel entrance?)-
-SSL LAN - Nginx(tunnel exit) - Redis
Any tip for achieving this? I've been googled the web for the last days but i couldn't come up anything that adds only a little overhead to the native connection.
Redis is designed to work on a secure network, behind a backend application. Client applications are not supposed to connect directly to Redis. It makes Redis a poor choice for a 2-tier application.
Now if you still want to use Redis for this, you have several options. You can encapsulate the Redis server in a HTTP interface. This is what the nginx redis2 module provide. You might also want to have a look at webdis, which is similar (and does not depend on nginx). Webdis offers some access control mechanisms. See the documentation.
Another solution is to establish a tunnel, as you proposed. I would not use nginx for this, but just plain old SSH. Let's suppose Redis server runs on machine B (port 6379) and client runs on machine A.
On machine A, I can run:
ssh user#host_B -L 7008:host_B:6379 -N
It will open a tunnel from A to B from local port 7008 (arbitrary choice), and waits. The user should be declared on host B, and its password known. In another session, still on host A, we can now run:
redis-cli -p 7008 ping
Please note a standard Redis client is used. The tunnel handles authentication, encryption and optionally compression in a transparent way for the client.
Now, your client is a Java application, and you probably do not want to run SSH commands to setup the tunnel. Hopefully, you can use the Jsch package to open the tunnel directly from Java. Here is an example with Jedis:
import redis.clients.jedis.*;
import java.util.*;
import com.jcraft.jsch.*;
public class TestTunnel {
Jedis jedis;
Session session;
JSch jsch = new JSch();
int port;
// None of the following should be hardcoded
static String USER = "user"; // SSH user on the redis server host
static String PASSWD = "XXXXXXXX"; // SSH user password
static String HOST = "192.168.1.62"; // Redis server host
static int PORT = 6379; // Redis server port
public TestTunnel() {
try {
// Open the SSH session
session = jsch.getSession( USER, HOST, 22 );
session.setPassword( PASSWD );
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
config.put("Compression", "yes");
config.put("ConnectionAttempts","3");
session.setConfig(config);
session.connect();
// Setup port forwarding from localhost to the Redis server
// Local port is ephemeral (given by the OS)
// Jedis connects to localhost using the local port
port = session.setPortForwardingL( 0, HOST, PORT );
jedis = new Jedis( "127.0.0.1", port );
} catch ( JSchException e ) {
// Proper error handling omitted
System.out.println(e);
}
}
public void disconnect() {
jedis.disconnect();
try {
session.delPortForwardingL( port );
session.disconnect();
} catch ( JSchException e ) {
// Proper error handling omitted
System.out.println(e);
}
}
public void mytest( int n ) {
for ( int k = 0; k < n; k++) {
jedis.set("k" + k, "value"+k);
}
System.out.println("Read: "+jedis.get("k0") );
}
public static void main(String[] args) {
TestTunnel obj = new TestTunnel();
obj.mytest(10);
obj.disconnect();
}
}
It works fine, but please note there is an overhead due to the tunnel. The overhead is very low when the network is slow (the Internet for instance). On a fast LAN (1 GbE), it is much more noticeable: the latency can be multiplied by up to 3 when the tunnel is used. The maximum throughput the Redis server can sustain is also impacted. On server-side, the sshd daemon takes some CPU (more than Redis itself).
That said, I don't think raw performance matters much for a 2-tier application.
Note: There's an SSL version of redis called SSL-REDIS which can be found on github:
https://github.com/bbroerman30/ssl-redis 2.6ish
https://github.com/tritondigital/ssl-redis 2.4ish
With this and modifying the Jedis Java client, SSL authentication could be achieved.

JDBC Example for java

I have downloaded JDK 6 and also I have sqljdb4.jar and I have database.properties file that content the following data
database.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
database.url=jdbc:sqlserver://.;databaseName=UserInfo;integratedSecurity=true;
database.username=sa
database.password=admin
B.N : I'm installing the server on my machine and the server name = . , also I'm using Windows Authontication
My problem now is when I try to create connection I have the following error
com.microsoft.sqlserver.jdbc.SQLServerException:
The TCP/IP connection to the host
localhost, port 1433 has failed.
Error: Connection refused: connect.
Please verify the connection
properties and check that a SQL Server
instance is running on the host and
accepting TCP/IP connections at the
port, and that no firewall is blocking
TCP connections to the port. at
com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:130)
I don't know what is the exact problem here
If any one can help I will be appreciated
Thanks in Advance
That's caused by many probabilities like
1- IP is worong
2- Port is wrong
3- There is firewall prevent machine to go out and connect to another IP
4- SQL server down .
try to use
public class JdbcSQLServerDriverUrlExample
{
public static void main(String[] args)
{
Connection connection = null;
try
{
// the sql server driver string
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// the sql server url
String url = "jdbc:microsoft:sqlserver://HOST:1433;DatabaseName=DATABASE";
// get the sql server database connection
connection = DriverManager.getConnection(url,"THE_USER", "THE_PASSWORD");
// now do whatever you want to do with the connection
// ...
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(2);
}
}
}
What i need to explain is there is very good technology called " Persistence " is better than JDBC and is more than brilliant and easy to use .
The problem is that your SQL server is either
not installed,
not running or
not accepting TCP/IP connections.
Particularly the last one is nasty, as I remember that some versions of SQL Server have not configured the TCP/IP connector to run by default.
Well first and foremost we need to see your code. Second looking at the error message the database is A)not running
B) on a different port
or C) the code is incorrect.

Categories