How can I configure an Apache-Mina sftp client to use a proxy? - sftp

I want to use Apache MINA as an sftp client within a Java application. This application will make an outbound connection through a HTTPS proxy to a remote server. I will need to set authentication details for connecting to the proxy somewhere.
I want to obtain an instance of org.apache.sshd.sftp.client.SftpClient which is running over an ssh connection through the proxy.
I have these imports:
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientProxyConnector;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.sftp.client.SftpClient;
import org.apache.sshd.sftp.client.SftpClientFactory;
And this is the code that I've written thus far:
// proxy
ClientProxyConnector proxy = ????;
// ssh
SshClient sshClient = SshClient.setUpDefaultClient();
sshClient.setClientProxyConnector( proxy );
sshClient.start();
ClientSession sshSession = sshClient.connect( "example.org" ).getSession();
// sftp
SftpClientFactory factory = SftpClientFactory.instance();
SftpClient client = factory.createSftpClient(sshSession);
Questions:
Do I need an instance of ClientProxyConnector to do what I'm trying to do?
How can I obtain an instance of a ClientProxyConnector and configure it with the proxy authentication details?

To go over a proxy you should create the ClientSession with HostConfigEntry which allows to specify a proxy.
HostConfigEntry host = new HostConfigEntry("", "example.org", 22, "username",
proxyUser + "#" + proxyHost + ":" + proxyPort);
ClientSession sshSession = sshClient.connect(host).getSession();
The purpose of ClientProxyConnector is something else.

Related

Apache Kafka and ASP.Net - convert JKS to cert

I am trying to connect to an Apache Kafka server, through SSL connection and using an ASP.Net console application. This is my very first attempt at connecting to Kafka.
I have set up the producer config (shown below) but the people on Kafka side are Java shop and they use JKS certificate that apparently contains certificate and key. This is of no use to me. Is there a way to convert this to a .Net-friendly set of certificates?
var config = new ConsumerConfig
{
BootstrapServers = "kafka_broker_IP:9093",
SecurityProtocol = SecurityProtocol.Ssl,
SslCaLocation = "path/to/ca.crt",
SslCertificateLocation = "path/to/client.crt",
SslKeyLocation = "path/to/client.key"
};
Can I get ca.crt, client.cert and client.key from one single .jks file?

IdentityModel.AspNetCore problem with proxy credentials for backchannel HttpClient

I'm using IdentityModel.AspNetCore to manage client access tokens in a background service. Access to the internet is only possible through a corporate proxy server which uses windows authentication.
The proxy server is configured in Windows options and the background service detects the settings, however authentication doesn't work and I'm constantly getting The proxy tunnel request to proxy 'http://proxy:8080/' failed with status code '407'. How can I configure the HttpClient to use the windows credentials for authentication against the proxy server?
I've already tried the following, but this doesn't work:
services.AddAccessTokenManagement(options =>
{
options.Client.Clients.Add("sapci", new ClientCredentialsTokenRequest
{
Address = hostContext.Configuration["HttpProxy:TokenEndpoint"],
ClientId = hostContext.Configuration["HttpProxy:ClientId"],
ClientSecret = hostContext.Configuration["HttpProxy:ClientSecret"],
GrantType = OidcConstants.GrantTypes.ClientCredentials,
AuthorizationHeaderStyle = BasicAuthenticationHeaderStyle.Rfc2617,
ClientCredentialStyle = ClientCredentialStyle.AuthorizationHeader
});
})
.ConfigureBackchannelHttpClient(client => new HttpClient(new HttpClientHandler()
{
DefaultProxyCredentials = CredentialCache.DefaultCredentials,
}));
I believe you can do this at app startup, to ensure you capture all client usages:
HttpClient.DefaultProxy = new WebProxy()
{
Credentials = CredentialCache.DefaultCredentials
}:
I would reduce your problem to deploying a minimal console app and running it with the same user account etc as your service. Once that works your main app will also.
Sometimes these things are infrastructure related also: eg in the past, with IIS clustered environments, I've had to use a service account and register a service principal name, eg to prevent use of computer accounts. I doubt that is relevant to .Net Core / Kestrel though, which I assume you are using.

Connect to mqtt.googleapis.com:8883 via proxy and another domain

For some reasons our infra blocks mqtt.googleapis.com. That's why was deployed nginx proxy with such configuration
stream {
upstream google_mqtt {
server mgtt.googleapis.com:8883;
}
server {
listen 8883;
proxy_pass google_mqtt;
}
}
Also it has external IP with domain name fake.mqtt.com
Using example here I'm testing connectivity.
If script to run against mgtt.googleapis.com:8883 everything works fine.
But if domain switch to fake.mqtt.com got an error:
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch, certificate is not valid for 'fake.mqtt.com'
For client implementation was used paho.mqtt.client.
Auth to mqtt broker realized with JWT.
def create_jwt(project_id, private_key_file, algorithm):
token = {
# The time that the token was issued at
"iat": datetime.datetime.utcnow(),
# The time the token expires.
"exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=20),
# The audience field should always be set to the GCP project id.
"aud": project_id,
}
# Read the private key file.
with open(private_key_file, "r") as f:
private_key = f.read()
print(
"Creating JWT using {} from private key file {}".format(
algorithm, private_key_file
)
)
return jwt.encode(token, private_key, algorithm=algorithm)
Set JWT
client.username_pw_set(
username='unused',
password=create_jwt(project_id, private_key_file, algorithm))
TLS configuration:
client.tls_set(ca_certs='roots.pem', tls_version=ssl.PROTOCOL_TLSv1_2,)
Could you advise what to configure on nginx/paho-client side and is it working solution at all?
Or may be 3party brokers can connect to mqtt.googleapis.com? (from information i read here and on another resources - no)
You can not just arbitrarily change the domain name if you are just stream proxying, it needs to match the one presented in the certificate by the remote broker or as you have seen it will not validate.
You can force the client to not validate the server name by setting client.tls_insecure_set(True) but this is a VERY bad idea and should only be used for testing and never in production.

akka http SSLConfig issues with Hostname verification and cert validation

I have some issues with Akka http configuration on the client side. I am trying to connect to a server which doesn't provide:
- a public signed certificate
- a certificate corresponding to the hostname
I don't have the hand on this nginx so I cannot change the server side configuration. I can only change the client side.
After lots of investigation on configuring SSL, I have found that I need to configure SSL options in application.conf at two different levels :
akka.ssl-config.ssl.loose.acceptAnyCertificate=true
akka.ssl-config.loose.disableHostnameVerification = true
and
ssl-config.loose.acceptAnyCertificate=true
ssl-config.loose.disableHostnameVerification = true
I have checked the configuration is fine with
log-config-on-start = "on"
The problem is that I still get error at the akka debug level (not very clear)
[ingestionApiClient-akka.actor.default-dispatcher-13] [akka://ingestionApiClient/user/StreamSupervisor-0/flow-216-1-unknown-operation] closing output
Looking at wireshark I have found that's a problem of certificate validation
TLSv1 Record Layer: Alert (Level: Fatal, Description: Certificate Unknown)
I suppose the JVM configuration is overiding all I have done so I also tried to follow this method to modify JVM SSL config :
Java SSL: how to disable hostname verification
No problem with configuring the SSLContext and passing it to akka http because I can set the default HttpsContext with
val sc = SSLContext.getInstance("TLS")
*...configuration...*
val customContext =HttpsContext(sc, sslParameters = Some(params))
Http().setDefaultClientHttpsContext(customHttpsContext)
But I cannot find anyway to configure the default hostname verifier. The Http class doesn't have any method like Http().setDefaultHostnameVerifier
This how I connect to the server
val dataIngestFlow = Http().outgoingConnectionTls(config.httpEndpointHost,config.httpEndpointPort)
How can I achieve this ? Thanks a lot for your help
I don't know which version of akka and akka-http you use but have you tried to set the configuration field akka.ssl-config.hostnameVerifierClass to your specific implementation of the HostNameVerifier interface?
The simplest verifier which accepts everything looks like this:
public static class AcceptAllHostNameVerifier implements HostnameVerifier {
#Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
}
I also got stuck in similar issue and was getting similar errors. with following code I was able to get through:
val trustStoreConfig = TrustStoreConfig(None, Some("/etc/Project/keystore/my.cer")).withStoreType("PEM")
val trustManagerConfig = TrustManagerConfig().withTrustStoreConfigs(List(trustStoreConfig))
val badSslConfig = AkkaSSLConfig().mapSettings(s => s.withLoose(s.loose
.withAcceptAnyCertificate(true)
.withDisableHostnameVerification(true)
).withTrustManagerConfig(trustManagerConfig))
val badCtx = Http().createClientHttpsContext(badSslConfig)
Http().superPool[RequestTracker](badCtx)(httpMat)

Read proxy settings on WP8

Is there any way to read proxy settings for current connections on WP8?
The problem is that I'm trying to use https client from Eldos Secure BlackBox but it doesn't seem to use proxy settings defined in system so beeing behind the proxy I can't access any server.
Or maybe there is any other approaches?
Did you try using the WebProxy class?
Sample code:
WebProxy proxy = (WebProxy) WebRequest.DefaultWebProxy;
if (proxy.Address.AbsoluteUri != string.Empty)
{
Console.WriteLine("Proxy URL: " + proxy.Address.AbsoluteUri);
wc.Proxy = proxy;
}
Reference: C# auto detect proxy settings
HttpWebRequest.Proxy in Windows Phone 7?

Resources