Preventing Hostname Redirects - java

I'm accessing a specific hostname in my Java application which I don't want to be redirected to somewhere else. It is using HTTP and not HTTPS. Is a redirect from the outside even possible? I thought of checking if the hosts file on Windows contains an entry that may redirect the hostname:
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.SystemUtils;
import java.io.File;
import java.io.IOException;
public class HostsFileChecker
{
public static boolean isPossiblyRedirecting(String hostName) throws IOException
{
if (!SystemUtils.IS_OS_WINDOWS)
{
return false;
}
File hostsFile = new File("C:\\Windows\\System32\\drivers\\etc\\hosts");
String hostsFileContents = FileUtils.readFileToString(hostsFile).toLowerCase();
return hostsFileContents.contains(hostName.toLowerCase());
}
}
Is there something else that should be checked or does this make no sense to even do? Java is definitely "fooled" by a redirect in this Windows hosts file and access my local web server instead:
127.0.0.1 example.com

Related

Calling a .jar from ColdFusion and run on the client machine

I am using ColdFusion 11 and I have an eSignWeb.jar file (created in java obviously) in my class path. What this .jar does is to receive a path where a file is located on the client's computer and then analyze that file using Bouncy Castle.
But when I run it, I get the following error:
Code: java.io.FileNotFoundException:
C:\Users\name\Documents\clientfile.cer (The system can not find the
specified path)
The error is because my .jar file tries to look for the clientfile.cer file on the server and not the client machine.What I need is that this .jar running on the server can search this file on the client's computer.
Important:
The clientfile.cer file can never upload to the server, so it has to be analyzed on the client side.
I have to use ColdFusion with java
My code in ColdFusion is simple:
<cfset eSign = createObject("java","eSignWeb.SignAB") />
<cfoutput>
<!--- TEST1--->
<cfdump var="#eSign#">
#eSign.callsignCF()#
<hr />
<!--- TEST2 WITH cfscript --->
<cfscript>
classLoader = createObject("java","eSignWeb.SignAB");
response = classLoader.callsignCF();
WriteOutput("Test whith CFSCRIPT " & response);
</cfscript>
</cfoutput>
The code in my .jar file:
package eSignWeb;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class SignAB {
public String callsignCF(){
String vCer;
vCer = "C:\\Users\\name\\Documents\\clientfile.cer"; //Path where the .cer file is located on the client side
Security.addProvider(new BouncyCastleProvider()); // add bc as provider
String archivoCer;
X509Certificate certificado = null;
Date fechaFinal;
Date fechaInicial;
Date fechaActual;
//start cer
archivoCer = vCer;
try {
FileInputStream is = new FileInputStream(archivoCer);
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificado = (X509Certificate)cf.generateCertificate(is);
fechaFinal = certificado.getNotAfter();
fechaInicial = certificado.getNotBefore();
fechaActual = new Date();
if(fechaActual.before(fechaInicial) && fechaActual.after(fechaFinal)){
return "Invalid date";
}else{
String myVarConRFC = "2.5.4.45";
String dn = certificado.getSubjectX500Principal().getName();
LdapName ldapDN = new LdapName(dn);
ldapDN.getRdns().forEach((index) -> {
if(index.getType().equals(myVarConRFC)){
//RFC
String myRFC = new String((byte[]) index.getValue());
}
});
}
}
catch (InvalidNameException ex) {
return "E0: Error on cer. Code: "+ ex;
}
catch(CertificateException a) {
return "E1: The specified file is not a valid certificate file. Code: " +a;
}
}
catch(FileNotFoundException fnfe) {
return "E2: Certificate file does not exist. Code: " +fnfe;
}
// End cer
return "Unknown error";
}
}
As you can see, the .jar runs on the server and that's why it does not find the .cer file. Any idea of ​​how to get a functionality that allows .jar to search the file on the client's machine?
If I could upload the .cer file to the server, it would be very easy, but that is forbidden. The .cer file should never leave the client's machine.
Thank you very much for any guidance in this regard!
CF alone won't work for that type of task, because it only operates on the CF server. It can't access client files at all. Only files uploaded to the server or a location accessible to the server (which you said you can't do).
In order to access files on a client machine, you need something like a signed Java Applet or Web Start Application, which does run on the client. The "signed" part is important. For security reasons, applets and the like can't just access files on the client machine whenever they wish. The user must explicitly grant the Applet or Web Start application permission to do so.

JNDI stuck on lookup [duplicate]

Is there any specific Glassfish configuration required to allow remote CORBA lookup across a LAN? Or, does, perhaps, the routers firewall need configuration?
How do I troubleshoot this connection?
The CORBA lookup client just hangs:
BUILD SUCCESSFUL
Total time: 3 seconds
Nov 22, 2014 3:45:26 AM aggregatorclient.AggregatorClient remoteEJB
WARNING: {org.omg.CORBA.ORBInitialPort=3700, java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, Context.SECURITY_CREDENTIALS=pass123, org.omg.CORBA.ORBInitialHost=192.168.0.119, java.naming.factory.url.pkgs=com.sun.enterprise.naming, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, Context.SECURITY_PRINCIPAL=user1}
When run from localhost (ie, from localhost, connecting to localhost), with everything on the same computer, the connection works fine.
The CORBA connection lookup parameters, in jndi.properties:
java.naming.factory.initial=com.sun.enterprise.naming.SerialInitContextFactory
java.naming.factory.url.pkgs=com.sun.enterprise.naming
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl
Context.SECURITY_PRINCIPAL=user1
Context.SECURITY_CREDENTIALS=pass123
org.omg.CORBA.ORBInitialHost=192.168.0.119
org.omg.CORBA.ORBInitialPort=3700
the connecting clients code:
package aggregatorclient;
import dur.ejb.AnswerSessionBeanRemote;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class AggregatorClient {
private static final Logger log = Logger.getLogger(AggregatorClient.class.getName());
public static void main(String[] args) {
try {
new AggregatorClient().remoteEJB();
} catch (NamingException ex) {
Logger.getLogger(AggregatorClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void remoteEJB() throws NamingException {
Context ctx = new InitialContext();
log.warning(ctx.getEnvironment().toString());
Object obj = ctx.lookup("dur.ejb.AnswerSessionBeanRemote");
AnswerSessionBeanRemote asbr = (AnswerSessionBeanRemote) obj;
log.info("answer\t" + asbr.lifeTheUniverseAndEverything());
}
}
The client is executed with Glassfish appclient.
Been having the same "hanging forever" lookup behavior with a standalone ejb client running on a remote host. It turned out to be related to the server host's ability to resolve its own hostname into its own non-loopback address. I resolved it by adding / fixing an entry in /etc/hosts:
10.0.10.102 my-server-hostname
I checked that the server could actually resolve the right ip address with hostname -i :
$ hostname -i
10.0.10.102
After restarting GlassFish, remote lookup and call to EJB worked like a charm!
Explanation
I found this solution after sniffing the traffic between my client and server. The underlying protocol is GIOP (had never heard of it).
When executing the remote lookup, my client's request was actually able to reach GlassFish. But the server replied with a misleading "Location Forward" response, indicating 127.0.1.1 as a IIOP:Profile_host. 127.0.1.1 was the loopback ip address that my server's hostname resolved to before I fixed the /etc/hosts.

"java.rmi.ConnectException: Connection refused to host" when exporting an object client-side

I'm stuck with that for at least 5 hours now and have no other resort but to ask here. I'm writing an RMI application. I'd like the server to bind a remote object (NoteBoardImpl here), that will be looked-up by the client. Client passes its listener (NoteBoardListener here) to the server, the listener is also a remote object exported by the client.
I've prepared a simple SSCCE here, so I really hope somebody can look into it. All the classes are in the same folder the default package. I know it's discouraged and I should've split the application in three jars, but I wanted to keep it as simple as possible here.
Remote interfaces:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface INoteBoard extends Remote {
public void test(INoteBoardListener listener) throws RemoteException;
}
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface INoteBoardListener extends Remote {
public void onNewText(String text) throws RemoteException;
}
Interfaces implementations:
import java.rmi.RemoteException;
public class NoteBoardImpl implements INoteBoard {
#Override
public void test(INoteBoardListener listener) throws RemoteException {
listener.onNewText("server call the listener");
}
}
import java.rmi.RemoteException;
public class NoteBoardListener implements INoteBoardListener {
#Override
public void onNewText(String text) throws RemoteException {
System.out.println(text);
}
}
Client and server:
import java.rmi.Naming;
import java.rmi.server.UnicastRemoteObject;
public class Client {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("2 arguments required:\nRMI_IP RMI_port");
return;
}
System.setProperty("java.rmi.server.hostname", args[0]);
try {
INoteBoard nb = (INoteBoard) Naming.lookup(String.format("rmi://%s:%s/note", args[0], args[1]));
INoteBoardListener l = (INoteBoardListener) UnicastRemoteObject.exportObject(new NoteBoardListener(), 0);
nb.test(l);
l.onNewText("client invokes listener");
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.rmi.Naming;
import java.rmi.server.UnicastRemoteObject;
public class Server {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("2 arguments required:\nRMI_IP RMI_port");
return;
}
System.setProperty("java.rmi.server.hostname", args[0]);
try {
INoteBoard noteBoard = (INoteBoard) UnicastRemoteObject.exportObject(new NoteBoardImpl(), 0);
Naming.rebind(String.format("rmi://%s:%s/note", args[0], args[1]), noteBoard);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I've tried to simulate a distributed system for testing purposes and ran the client on a virtual machine. The host-VM network has the following specs - host IP = 192.168.56.1, VM IP = 192.168.56.101.
First I ran the client and the server locally, using the following commands (having started rmiregistry 1099 beforehand). The working directory is the project's root and the compiled classes are in bin directory:
java -cp bin -Djava.rmi.server.codebase=http://student.agh.edu.pl/~grajewsk/bin/ Server 192.168.56.1 1099
java -cp bin Client 192.168.56.1 1099
And it worked.
Then I ran the client program on the VM using the same command and here's the exception I got:
java.rmi.ConnectException: Connection refused to host: 192.168.56.1; nested exception is:
java.net.ConnectException: Connection refused
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:128)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
at sun.proxy.$Proxy0.test(Unknown Source)
at Client.main(Client.java:14)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:327)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:193)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
at java.net.Socket.connect(Socket.java:546)
at java.net.Socket.connect(Socket.java:495)
at java.net.Socket.<init>(Socket.java:392)
at java.net.Socket.<init>(Socket.java:206)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:146)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
... 7 more
Notice how the object is successfully looked-up in the server's registry, then the client-side remote object is exported (also with success) and the execution breaks in the 14-th line, where I'm trying to invoke a method on the server-side object passing the client-side object.
I have no firewalls on either of the systems, pings in both directions go flawlessly. I know that there must be some conceptual problem here and certainly I misunderstood something about the RMI. I'd very much appreciate your help.
The binary codebase is on my student's server, as well as the source code. Thank you in advance!
Here's what I'd do to get to the bottom of this.
Run your server app
find out what port it's using for RMI (it's ephemeral, so it should change for each process you create of the server).
find the PID with ps -ef
then netstat -anp|grep This should then give you the port number. And it should be bound to 0.0.0.0
on the client VM, use nc or telnet to verify you can connect to the port. If this fails, you probably have a firewall/iptables issue.
use wireshark to verify your client is actually attempting to connect to the port/ip combo you learned from step #2.
Remember, just because you can ping, doesn't mean you can connect to a given port. Also check "iptables -L".
Also, Naming says not to put the scheme component of the URL. The format should be //host:port/name, so you should check that as well.
Ok, finally solved it. The problem was, that I was passing the same java.rmi.server.hostname argument in both programs, that means that both client and server got the address of the server here. It turned out, that if the client wants to export its own objects, it has to provide its own IP to the java.rmi.server.hostname. This way everything works fine.
So, to sum it up, I had to give 3 arguments to the server:
RMI_IP RMI_port server_hostname
And 3 analogous arguments to the client:
RMI_IP RMI_port client_hostname

httpClient proxy support in apache commons 3.1

I am using apache commons 3.1 to implement httpClient with proxy support.
I am trying to connect to a remote host through proxy. The proxy server is configured without any authentication, however the the remote host is configured with authentication.
When I am passing the proxy parameters through properties file, it gives warning while execution:
WARN - Required proxy credentials not available for BASIC #xx.xx.xx.xx
WARN - Preemptive authentication requested but no default proxy credentials availble
But the execution goes ahead.
On the other hand when I am passing the proxy parameters through the JVM arguments then the again the same warning is given and the execution is stopped.
Is there any specific reason for this behavior? Is there any difference in passing the proxy parameters through properties file and through JVM arg?
Here is the code:
if(System.getProperty("http.proxyHost") != null && System.getProperty("http.proxyPort") != null) {
httpClient.getHostConfiguration().setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort")));
}
else if(AMXAdminTask.props.getProperty("http.proxyHost") != null && AMXAdminTask.props.getProperty("http.proxyPort") != null) {
httpClient.getHostConfiguration().setProxy(Propfile.props.getProperty("http.proxyHost"), Integer.parseInt(Propfile.props.getProperty("http.proxyPort")));
}
Looks like you are trying to combine two very different things. The code you posted above properly gets you through your proxy, but the remote host requires BASIC authentication. The below example uses the Jersey client (used in an existing project for making RESTful calls), but you should get the idea of what you need to do. If you're stuck on using Apache HttpComponents, take a look at this:
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
import org.apache.commons.lang.StringUtils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import com.sun.jersey.client.apache.ApacheHttpClient;
import com.sun.jersey.client.apache.config.ApacheHttpClientConfig;
import com.sun.jersey.client.apache.config.DefaultApacheHttpClientConfig;
public abstract class BaseProxyProvider {
protected Client getHttpClient() {
final DefaultApacheHttpClientConfig cc = new DefaultApacheHttpClientConfig();
if (StringUtils.isNotEmpty(System.getProperty("http.proxyHost"))) {
cc.getProperties()
.put(ApacheHttpClientConfig.PROPERTY_PROXY_URI,
"http://" + System.getProperty("http.proxyHost") + ":"
+ System.getProperty("http.proxyPort") + "/");
}
Client c = ApacheHttpClient.create(cc);
c.addFilter(new HTTPBasicAuthFilter(WebAppPropertyReader.getProperties().getProperty(
WebAppPropertyReader.SERVICE_USER), WebAppPropertyReader.getProperties().getProperty(
WebAppPropertyReader.SERVICE_PASSWORD)));
return c;
}
}

Ubuntu - UnknownHostException when connecting to a PC, using a Socket in an Ad Hoc network

I have created a FileSystemListener that listens for files in a folder and sends them to a specified IP address. This has all been tested with a standard wireless network but I am getting an unkownhostexception when running it on an ad hoc network.
I was not sure if this was something I should ask on Superuser, or here, as I am not sure if it is an issue with my code or Ubuntu.
I can ping the other PC on the wireless network but I keep getting the above exception when connecting through java.
Not sure if it helps but here is the most basic SSCE I can think of:
import java.net.Socket;
public class ClientTester {
public static void main(String[] args) {
Socket s = new Socket("192.168.0.1", 4440);
}
}
Anyone come across this before, wanted to see if it was a Java issue before I cross posted in Superuser.
Thanks!
To compile correctly, UnknownHostException "must be caught or declared to be thrown."
For example:
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientTester {
public static void main(String[] args)
throws UnknownHostException, IOException {
Socket s = new Socket("192.168.0.1", 4440);
}
}
If this works with regular infrastructure mode, but not with ad-hoc mode you probably haven't configured the ad-hoc mode properly. Could you show us your /etc/network/interfaces config?

Categories

Resources