First off, I'm new to Spring-Boot and SSL in general, but I've spent several days researching and am basically trying to get a simple Spring-Boot application configured with Client Authentication.
I've set up a connector like so:
private Connector createSslConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
try {
File keystore = getKeyStoreFile();
File truststore = keystore;
connector.setScheme("https");
connector.setSecure(true);
connector.setPort(sslPort);
protocol.setSSLEnabled(true);
protocol.setKeystoreFile(keystore.getAbsolutePath());
protocol.setKeystorePass("changeit");
protocol.setTruststoreFile(truststore.getAbsolutePath());
protocol.setTruststorePass("changeit");
protocol.setKeyAlias("apitester");
protocol.setClientAuth("need");
return connector;
}
catch (IOException ex) {
throw new IllegalStateException("cant access keystore: [" + "keystore"
+ "] or truststore: [" + "keystore" + "]", ex);
}
}
And a controller that looks like so:
#RequestMapping("/test/{identifier}")
#ResponseBody
ResponseEntity<String> test(HttpServletRequest request, #PathVariable String identifier) {
return new ResponseEntity<String>("hello: " + identifier, HttpStatus.OK)
}
However, once I launch my application I can use a browser to navigate to localhost:sslport/hello/test/xxxx and get a response without any type of client certificate loaded. I was expecting to be prompted for a client certificate.
Spring boot uses tomcat (embedded) web container by default.
As it is called out tomcat doc, we have to set it to true to enforce the propagation of valid certificate chain from the client before accepting a connection. Setting want will allow the client to provide a certificate but not absolutely required.
I doubt if "need" makes any meaning for the container.
protocol.setClientAuth("need");
Related
I have a WCF Cloud Service running in azure which I connect to from a .NET client. This is all working nicely and I have implemented security by enabling SSL (using a self signed certificate) and using active directory authorisation.
However, I have a number of scheduled jobs using the azure scheduler and these jobs call methods in the Cloud service but I am unable to setup the scheduled jobs as HTTPS jobs. They work fine as HTTP jobs but as soon as I change it to HTTPS I get the following error:
“Http Action - Request to host '.cloudapp.net' failed: TrustFailure The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.”
I tried just accepting all certificates by adding the following code to the WCF web role’s OnStart method:
ServicePointManager.ServerCertificateValidationCallback
= delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
};
But the callback never gets invoked
So I assume I have to somehow add client certificate authentication to the scheduler job? But I cannot work out how.
I am creating the job through the Microsoft.WindowsAzure.Management.Scheduler Api e.g:
var action = new JobAction();
action.Type = JobActionType.Https;
action.Request = new JobHttpRequest();
action.Request.Method = "POST";
action.Request.Uri = new Uri(serviceURI);
action.Request.Body = soap;
action.RetryPolicy = new RetryPolicy()
{
RetryType = RetryType.None,
RetryCount = null
};
action.Request.Headers = new Dictionary<string, string>()
{
{ "Content-Type", "text/xml" },
{ "SOAPAction", "\"http://tempuri.org/" + serviceInterfaceName + "/" + methodName + "\"" }
};
var result = schedulerClient.Jobs.CreateOrUpdate(jobName, new JobCreateOrUpdateParameters()
{
action = action,
StartTime = startTime,
Recurrence = new JobRecurrence()
{
Frequency = frequency,
Interval = interval
}
});
and I see that in the JobAction class there is a property of the Request object called Authentication, I thought perhaps I might need to use that but I can find no documentation on how to use it?
Alternatively, I could create the schedule job through powershell or the azure portal interface if anyone can tell me how to successfully create an HTTPS schedule job through either of those methods?
Many thanks,
kelly
Scheduler jobs fail because it can't trust this endpoint. You need to use a trusted certificate for HTTPS calls from Scheduler.
I don't know how to programmatically disable CN checking with CXF 3.0.4 JAX-RS 2.0 client. My code is as follows:
System.setProperty("jsse.enableSNIExtension", "false");
HttpsURLConnection.setDefaultHostnameVerifier(
new HostnameVerifier(){
public boolean verify(String hostname,
SSLSession sslSession) {
return true;
}
});
Client client = ClientBuilderImpl.newClient();
String urlHost = "https://" + centralNode;
WebTarget target = client.target(urlHost).path(BASE_SERVICE_URL);
String encodedpw = Base64.encodeBase64String(passwd.getBytes());
String body = "{\"uid\" : \"" + uid + "\",\"password\": \"" + encodedpw + "\"}";
Response res = target.request(MediaType.APPLICATION_JSON).post(Entity.entity(body, MediaType.APPLICATION_JSON));
As you can see, I already tried to override the default hostnameverifier, and set jsse.enableSNIExtension to false. None of these worked, i am still getting the exception:
"The https URL hostname does not match the Common Name (CN) on the server certificate in the client's truststore. Make sure server certificate is correct, or to disable this check (NOT recommended for production) set the CXF client TLS configuration property "disableCNCheck" to true."
Please help!
You are looking for this code snippet;
HTTPConduit httpConduit=(HTTPConduit)ClientProxy.getClient(SAMPLE_PORT).getConduit();
TLSClientParameters tlsCP = new TLSClientParameters();
tlsCP.setDisableCNCheck(true);
httpConduit.setTlsClientParameters(tlsCP);
Always use this code in test environment.!
What is the best way to process HTTP GET Method with SSL using HTTP Components HTTPClient 4 Project?
what is the best way to parametrized certification info? properties file? reload method to Daemon Service?
HttpClient httpClient = new DefaultHttpClient();
String url = "https://xxx.190.2.45/index.jsp";
HttpGet get = new HttpGet(url);
try {
//TODO
HTTPHelper.addSSLSupport(httpClient);
HttpResponse response = httpClient.execute(get);
BasicResponseHandler responseHandler = new BasicResponseHandler();
String responseString = responseHandler.handleResponse(response);
} catch (ClientProtocolException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
You'll need to enable the SSL support, see the tutorial for more information
I'm under the impression that you're using a self-signed certificate for the server. What you probably should do is look at getting openssl, generate yourself a CA & server certificate. Put the CA certificate (not the private key) in a "trust store" and configure the socket factory.
If you need more detail on how to do this, just comment on this and I'll flesh out some more. I've had great success with simple local projects!
I am attempting to host a service that serves up basic web content (HTML, javascript, json) using a WebHttpBinding with minimal administrator involvement.
Thus far I have been successful, the only admin priviledges necessary are at install time (register the http reservation for the service account and to create the service itself). However, now I am running into issues with SSL. Ideally I would like to support a certificate outside the windows certificate store. I found this article - http://www.codeproject.com/KB/WCF/wcfcertificates.aspx - which seems to indicate you can specify the certificate on the service host, however at runtime navigating a browser to https://localhost/Dev/MyService results in a 404.
[ServiceContract]
public interface IWhoAmIService
{
[OperationContract]
[WebInvoke(
Method = "GET",
UriTemplate = "/")]
Stream WhoAmI();
}
public class WhoAmIService : IWhoAmIService
{
public Stream WhoAmI()
{
string html = "<html><head><title>Hello, world!</title></head><body><p>Hello from {0}</p></body></html>";
html = string.Format(html, WindowsIdentity.GetCurrent().Name);
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
return new MemoryStream(Encoding.UTF8.GetBytes(html));
}
}
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(WhoAmIService), new Uri("https://localhost:443/Dev/WhoAmI"));
host.Credentials.ServiceCertificate.Certificate = new X509Certificate2(#"D:\dev\Server.pfx", "private");
WebHttpBehavior behvior = new WebHttpBehavior();
behvior.DefaultBodyStyle = WebMessageBodyStyle.Bare;
behvior.DefaultOutgoingResponseFormat = WebMessageFormat.Json;
behvior.AutomaticFormatSelectionEnabled = false;
WebHttpBinding secureBinding = new WebHttpBinding();
secureBinding.Security.Mode = WebHttpSecurityMode.Transport;
secureBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
ServiceEndpoint secureEndpoint = host.AddServiceEndpoint(typeof(IWhoAmIService), secureBinding, "");
secureEndpoint.Behaviors.Add(behvior);
host.Open();
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
host.Close();
}
If I change my binding security to none and the base uri to start with http, it serves up okay. This post seems to indicate that an additional command needs to be executed to register a certificate with a port with netsh (http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/6907d765-7d4c-48e8-9e29-3ac5b4b9c405/). When I try this, it fails with some obscure error (1312).
C:\Windows\system32>netsh http add sslcert ipport=0.0.0.0:443 certhash=0b740a29f
29f2cc795bf4f8730b83f303f26a6d5 appid={00112233-4455-6677-8899-AABBCCDDEEFF}
SSL Certificate add failed, Error: 1312
A specified logon session does not exist. It may already have been terminated.
How can I host this service using HTTPS without the Windows Certificate Store?
It is not possible. HTTPS is provided on OS level (http.sys kernel driver) - it is the same as providing HTTP reservation and OS level demands certificate in certificate store. You must use netsh to assign the certificate to selected port and allow accessing the private key.
The article uses certificates from files because it doesn't use HTTPS. It uses message security and message security is not possible (unless you develop your own non-interoperable) with REST services and webHttpBinding.
The only way to make this work with HTTPS is not using built-in HTTP processing dependent on http.sys = you will either have to implement whole HTTP yourselves and prepare new HTTP channel for WCF or you will have to find such implementation.
My application is using Apache's HttpClient 3.1 deployed on Weblogic 10.3 to perform a POST using SSL mutual authentication. I can get this to work using the following system properties to configure the keystore & truststore:-
-Djavax.net.ssl.keyStore=C:\Keystore\KEYSTORE.jks
-Djavax.net.ssl.keyStorePassword=changeit
-Djavax.net.ssl.trustStore=C:\Truststore\TRUSTSTORE.jks
-Djavax.net.ssl.trustStorePassword=changeit
Is there any way to get HttpClient to recognize and use the Weblogic custom keystore & truststore settings (as configured in the console / config.xml). Amongst other things this would provide the ability to keep the passwords "hidden" and not visible as plain text in config files / console etc.
Can anyone enlighten me?
I have been able to get HttpClient to use the custom weblogic trust store certificates for SSL connection by implementing custom TrustStrategy:
import sun.security.provider.certpath.X509CertPath;
import weblogic.security.pk.CertPathValidatorParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertPath;
import java.security.cert.CertPathParameters;
import java.security.cert.CertPathValidator;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
public class WeblogicSSLTrustStrategy implements TrustStrategy {
#Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
validator = CertPathValidator.getInstance("WLSCertPathValidator");
CertPath certPath = new X509CertPath(Arrays.asList(chain));
// supply here the weblogic realm name, configured in weblogic console
// "myrealm" is the default one
CertPathParameters params = new CertPathValidatorParameters("myrealm", null, null);
try {
validator.validate(certPath, params);
} catch (CertPathValidatorException e) {
throw new CertificateException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new CertificateException(e);
}
return true;
}
}
This code is based on Weblogic documentation. The strategy can be passed to HttpClient via SSLSocketFactory:
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new WeblogicSSLTrustStrategy());
schemeRegistry.register(new Scheme("https", 443, sslSocketFactory));
PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry);
DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);
The only unknown parameter is the Weblogic Realm name, which can be taken from Weblogic JMX API, or simply preconfigured. This way it does not require to instantiate the trust store or to reconfigure Weblogic startup parameters.
You might be able to obtain these values via JMX using the KeyStoreMBean. Be forewarned though, this might not be a trivial exercise due to the following:
This would require storing the keystore passwords in cleartext in your JMX client (now that you would be writing one in your application). This is insecure, and a security audit might fail due to this, depending on what the audit is meant to look for.
The MBeans might not be accessible at runtime, due to the JMX service configuration, or would have to be accessed differently in different scenarios. Assuming WebLogic 11g, the values might be made read-only, by setting the value of the EditMBeanServerEnabled attribute of the JMXMBean to false.