No effect in setting proxy to AuthenticationContext in KeyVaultClient java - java

I want to run my Java code to read Azure KeyVault with proxy in Windows server.
I've gone through many posts but could find any working solution. Mostly given for c# but I want for Java. My code is working fine in my local machine but when I'm trying to run same code in Pre-Prod Windows server where I need to set Proxy is not working.
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(authorization, false, service);
//added below 2 lines but don't see any effect
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.server.com", 80));
context.setProxy(proxy);
ClientCredential credentials = new ClientCredential(clientId, clientKey);
Future<AuthenticationResult> future = context.acquireToken(
resource, credentials, null);
result = future.get();
When I'm running the code in my local machine it is running fine with and without proxy setting but in that Windows server it say "Unknown host" exception.

I am not sure if the following would help, but you can have a try.
You can try to find the direct IP of the proxy, and use it in your code:
InetAddress[] allByName = InetAddress.getAllByName("proxy.server.com");
for (InetAddress address : allByName) {
System.out.println(address.getHostAddress());
}
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(allByName[0].getHostAddress(),80););
Or
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getByName("proxy.server.com"),80));
Maybe the direct IP may work.

Related

Trying to connect to an SSH server with on-premise proxy type?

I have a new project where I should connect to an SSH server, with a proxy (which is on-premise).
The problem is, that if I don't use proxy, I get an error saying "UnknownHost".
But when I use proxy, it says "JSchException ProxySOCKS5: com.jcraft.jsch.JSchException: fail in SOCKS5 proxy".
I'm pretty new to sockets, proxies and all these kinds of things, so every advice is appreciated.
JSch jsch = new JSch();
jsch.setKnownHosts("known_hosts");
com.jcraft.jsch.Session session = null;
com.jcraft.jsch.ProxySOCKS5 proxy = new ProxySOCKS5("localhost", 20004);
proxy.setUserPasswd(userName, password);
URL url = new URL("http", "<remoteUrl>", 22, filePath, null);
session = jsch.getSession(userName, hostName, 22);
session.setPassword(password);
session.setProxy(proxy );
session.connect(10000);
I did try a different direction, where I don't use jsch, only java.net. That code:
SocketAddress addr = new InetSocketAddress("localhost", 20004);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
final String encodedSubaccount = new String(Base64.encodeBase64(subaccount.getBytes()));
final String encodedLocationId = new String(Base64.encodeBase64(locationId.getBytes()));
char[] pwdHelp = [];
Authenticator.setDefault(new Authenticator() {
#Override
protected java.net.PasswordAuthentication getPasswordAuthentication() {
return new java.net.PasswordAuthentication("1." + encodedSubaccount + "." + encodedLocationId , pwdHelp);
}
});
URL url = new URL("http", "<remoteUrl>", 22, filePath, null);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
With this approach, there is no error, but when I try to getResponseMessage() or code, then it returns only -1 or null.
Can somebody help me out?
Thanks in advance
I'm not a java developer so I can help you only the infrastructure part of the problem.
UnknownHost: you cannot connect directly that's why you have to use proxy. UnknownHost means java/your machine cannot resolve DNS name to IP address, maybe that DNS name is an inside/private one.
As I see In your java code You try to connect HTTP protocol instead of SSH protocol.
What is the exact task?
Somebody was provided You an on-premise SocksProxy IP and port, and you have to connect via to an inside SSH server?
OR
You have to connect with SSH protocol to the on-premise server to create a local SocksProxy, and you have to connect to an inside server via local SocksProxy?
In the 2. case you can test the connection with ssh command and a web browser:
SSH to on-premise: ssh -D 1080 on-premise_remote_hosntame_or_IP
Setup socksproxy in a webbrowser: Socks proxy ip: 127.0.0.1, port: 1080
In the web browser try to connect to an inside webserver

Why does Apache Commons VFS consider Http Proxy and Socks5 Proxy but simply ignore Socks4 Proxy?

I am working on a application that connects to an SFTP server and downloads files using Apache Commons VFS, it works just fine, with the exception that the system needs to allow the user to specify a proxy, as needed.
Now, I know Apache Commons VFS is built on top of Jsch and I know Jsch contains the classes: com.jcraft.jsch.ProxyHTTP, com.jcraft.jsch.ProxySOCKS4 and com.jcraft.jsch.ProxySOCKS5.
The code below is an extract of VFS class org.apache.commons.vfs2.provider.sftp.SftpClientFactory:
public static Session createConnection(
...
final SftpFileSystemConfigBuilder.ProxyType proxyType = builder.getProxyType(fileSystemOptions);
...
final String proxyUser = builder.getProxyUser(fileSystemOptions);
final String proxyPassword = builder.getProxyPassword(fileSystemOptions);
Proxy proxy = null;
if (SftpFileSystemConfigBuilder.PROXY_HTTP.equals(proxyType)) {
proxy = createProxyHTTP(proxyHost, proxyPort);
((ProxyHTTP)proxy).setUserPasswd(proxyUser, proxyPassword);
} else if (SftpFileSystemConfigBuilder.PROXY_SOCKS5.equals(proxyType)) {
proxy = createProxySOCKS5(proxyHost, proxyPort);
((ProxySOCKS5)proxy).setUserPasswd(proxyUser, proxyPassword);
} else if (SftpFileSystemConfigBuilder.PROXY_STREAM.equals(proxyType)) {
proxy = createStreamProxy(proxyHost, proxyPort, fileSystemOptions, builder);
}
...
As you can you see, there's no "if" statement to instantiate ProxySOCKS4!
I have duplicated the SftpClientFactory class, set my version to load before the original class on the classpath and changed the code as follow:
public static Session createConnection(
...
final SftpFileSystemConfigBuilder.ProxyType proxyType = builder.getProxyType(fileSystemOptions);
...
final String proxyUser = builder.getProxyUser(fileSystemOptions);
final String proxyPassword = builder.getProxyPassword(fileSystemOptions);
Proxy proxy = null;
if (SftpFileSystemConfigBuilder.PROXY_HTTP.equals(proxyType)) {
proxy = createProxyHTTP(proxyHost, proxyPort);
((ProxyHTTP)proxy).setUserPasswd(proxyUser, proxyPassword);
/// change start (I also created the PROXY_SOCKS4 constant)
} else if (SftpFileSystemConfigBuilder.PROXY_SOCKS4.equals(proxyType)) {
proxy = createProxySOCKS4(proxyHost, proxyPort);
((ProxySOCKS4)proxy).setUserPasswd(proxyUser, proxyPassword);
/// change end
} else if (SftpFileSystemConfigBuilder.PROXY_SOCKS5.equals(proxyType)) {
proxy = createProxySOCKS5(proxyHost, proxyPort);
((ProxySOCKS5)proxy).setUserPasswd(proxyUser, proxyPassword);
} else if (SftpFileSystemConfigBuilder.PROXY_STREAM.equals(proxyType)) {
proxy = createStreamProxy(proxyHost, proxyPort, fileSystemOptions, builder);
}
...
.. and guess what, when I set my application to use a Socks 4 Proxy it works alright with the change above. It is important to say that setting the application to work with Socks 5 does not work if the proxy server is a Socks 4 type, and that's true not only for my application with VFS, but also any other client I tested, like Fillezila or WinSCP.
So, the main question is:
Why does VFS predicts the usage of ProxyHTTP, ProxySOCKS5 but completely ignores the JSch ProxySOCKS4 class? Am I missing some SFTP or Proxy concept here or should I consider VFS bugged? That's the first time I work with VFS.
Please consider the question in bold as the main question not to make it too broad.
I wasn't able to get or find a better answer in time, so what I did to solve my problem was exactly what I described in the question.
I duplicated the classes SftpClientFactory e SftpFileSystemConfigBuilder, made the necessary adjustments and used them instead of the original classes, it's ugly and now I am stuck with a specific VFS version, I know, but the problem was solved.
Lesson for next time: use Jsch instead of VFS.
I'll leave the question open though, in case someone else have a proper solution or answer.

Set up Firebase admin sdk with proxy (Java)

I'm trying to use firebase to authenticate my users via Google. On my Java server I'm verifying the validity of the idToken and every time I get this error:
com.google.firebase.auth.FirebaseAuthException: Error while verifying token signature.
I identified the problem as being the proxy of my server that avoid the http requests made by the sdk. I tested my code on my computer and it works so I'm pretty sure the problem is the proxy.
Here is my code:
InputStream serviceAccount = getClass().getClassLoader().getResourceAsStream(<fileName>);
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(<address>, <port>));
HttpTransport httpTransport = new NetHttpTransport.Builder().setProxy(proxy).build();
HttpTransportFactory httpTransportFactory = () -> httpTransport;
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount, httpTransportFactory))
.setDatabaseUrl(<adress>)
.setHttpTransport(httpTransport)
.build();
FirebaseApp.initializeApp(options);
FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdTokenAsync(<token>).get();
What am I doing wrong ?
I believe this is a bug. As you can see here, the token verifier does not use the HTTP transport injected through options. I'd appreciate if you can create an issue for this on GitHub.
In the meantime, you might be able to get around this limitation by configuring the HTTP/S proxy for the JVM. Try setting the https.proxyHost and https.proxyPort system properties when starting the JVM (more details here).
I've faced the same problem, and still waiting for a greater solution.
In the meantime, I've decompiled the WebSocket class (com.google.firebase.database.tubesock.WebSocket), and created an underlying socket by myself, then droped this decompiled class in a new package in my project: com.google.firebase.database.tubesock.
The creation of the SSLSocket is around the line 295 of this class.
I've created the socket this way:
SSLSocketFactory factory = (SSLSocketFactory)SSLSocketFactory.getDefault();
InetSocketAddress proxyAddr = new InetSocketAddress("200.5.92.169", 8080);
Socket underlying = new Socket(new Proxy(Proxy.Type.HTTP, proxyAddr));
underlying.connect(new InetSocketAddress(host, port));
SSLSocket sslSocket = (SSLSocket) factory.createSocket(underlying, host, port, true);

Siteminder: Java Agent API

I want to create an agent object using siteminder r.12. Want to find the values for the below parameters. Where is the value stored?
User-defined connection parameters defined in your codeā€”for example:
AgentAPI agent = new AgentAPI();
ServerDef sd = new ServerDef();
sd.serverIpAddress = POLICY_IP;
sd.connectionMin = CX_MIN;
sd.connectionMax = CX_MAX;
sd.connectionStep = CX_STEP;
sd.timeout = CX_TIMEOUT;
sd.authorizationPort = AZ_PORT;
sd.authenticationPort = AUTH_PORT;
sd.accountingPort = ACC_PORT;
InitDef init=new InitDef(AGENT_LOGIN,SHARED_SECRET,false, sd);
agent.init(init);
Thanks,
navi
To use the AgentApi you will need to know some things about your Policy Server and agent. You will have to find the host address of the Policy Server, the agent name you will use to query the PS, the authorization port and authentication port and the shared secret.
Go here for the spec of the AgentApi:
https://support.ca.com/cadocs/0/CA%20SiteMinder%2012%2052-ENU/Bookshelf_Files/programming-reference/legacy-sm-java-sdk/netegrity/siteminder/javaagent/AgentAPI.html
the parameters you are looking for are related to Host Configuration Object (HCO) and SmHost.conf settings.

How do you preform an EJB lookup with application security?

I'm trying to lookup an EJB from a standalone java application. I'm thinking in terms of WebSphere Application Server 6.1, but if someone knows how to do this for another application server, it may get me in the right direction.
What I'm currently doing:
initialContext= new InitialContext(env);
initialContext.lookup("");
lc = new LoginContext("WSLogin", new WSCallbackHandlerImpl("wasadmin", "defaultWIMFileBasedRealm", "wasadmin"));
lc.login();
subject = lc.getSubject();
WSSubject.setRunAsSubject(subject);
This isn't working... my subject is still "/UNAUTHENTICATED", and I get an error when I try to lookup the EJB. I'm also specifying the following parameters to the VM when executing the application:
-Dcom.ibm.CORBA.ConfigURL="C:\was\profiles\AppSrv01\properties\sas.client.props"
-Djava.security.auth.login.config="C:\was\profiles\AppSrv01\properties\wsjaas_client.conf"
For WebSphere 6, was trying to acceess an secured EJB from a servlet (Jersey-RESTful WAR) also deployed in the same WebSphere; Here is the code that works
Properties prop = new Properties();
prop.put("org.omg.CORBA.ORBClass", "com.ibm.CORBA.iiop.ORB");
prop.put("java.naming.factory.initial", "com.ibm.websphere.naming.WsnInitialContextFactory");
prop.put("java.naming.provider.url", "corbaloc:iiop:localhost:9810");
prop.put("com.ibm.CORBA.securityEnabled", "true");
prop.put("com.ibm.CORBA.validateBasicAuth", "true");
Context ctx;
try {
ctx = new InitialContext(prop);
System.out.println("Resolved Inital Context");
Object ejbHome = ctx.lookup("");
System.out.println("Resolved Home OperationManagerEJB");
logger.info("So far so good, tryining to Login ");
LoginContext lc;
lc = new LoginContext("WSLogin",new WSCallbackHandlerImpl("username","password"));
lc.login();
logger.info("Login Suceeded with omc_user");
WSSubject.setRunAsSubject(lc.getSubject()); //This is one key call
logger.info("Setting the authorization sibject");
References
http://pic.dhe.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=%2Fcom.ibm.websphere.express.doc%2Finfo%2Fexp%2Fae%2Frtrb_secprobs.html
http://pic.dhe.ibm.com/infocenter/wasinfo/v6r0/index.jsp?topic=%2Fcom.ibm.websphere.express.doc%2Finfo%2Fexp%2Fae%2Fxsec_jaas.html
http://pic.dhe.ibm.com/infocenter/wasinfo/v6r0/index.jsp?topic=%2Fcom.ibm.websphere.express.doc%2Finfo%2Fexp%2Fae%2Fxsec_jaas.html

Categories

Resources