Jetty SSL server - security

Following is my code for the secure ssl server. I have created a keystore "server" and it has the key pair generated with passwords.
public static void main(String[] args) throws Exception {
Server server = new Server();
HttpConfiguration https_config = new HttpConfiguration();
https_config.setSecureScheme("https");
https_config.setSecurePort(8443);
https_config.addCustomizer(new SecureRequestCustomizer());
https_config.setSendServerVersion(true);
File keystoreFile = new File("server");
System.out.print(keystoreFile.getAbsolutePath());
SslContextFactory sslContextFactory = new SslContextFactory();
if (keystoreFile.exists())
{
sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
sslContextFactory.setTrustStorePath(keystoreFile.getAbsolutePath());
sslContextFactory.setKeyStorePassword("secret");
sslContextFactory.setKeyManagerPassword("secret");
sslContextFactory.setTrustStorePassword("secret");
sslContextFactory.setExcludeCipherSuites(
"SSL_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_DSS_WITH_DES_CBC_SHA",
"SSL_RSA_EXPORT_WITH_RC4_40_MD5",
"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
}
ServerConnector https =
new ServerConnector(server,
new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(https_config));
https.setPort(8443);
server.setConnectors(new Connector[] { https});
ServletContextHandler scHandler = new ServletContextHandler(server,"/");
scHandler.addServlet(Testpage1.class, "/test");
server.setHandler(scHandler);
server.start();
}
}
when I tried to connect to using the https://localhost:8443/ or https://localhost:8443/test it gives me "web page not available error" and with curl it gives me "curl: (35) Unknown SSL protocol error in connection to localhost:8443"
Could some one guide me to debug this issue.

I decided to post the question after a full day of debugging and trials and but with a little suggestion from a friend I manage to solve the issue by updating the keystore. So the issue I was having was due to the keys I have generated int he key store. It seems you need to use RSA algorithm not the EC algorithm.

Related

Flutter - HttpException: Connection closed before full header was received

DISCLAIMER: I know that this question was asked before multiple times, non of the answers helped me.
In our app, we implemented SSL for more security, but we sometimes get the mentioned error, the error is not persistent, meaning that the same route can success at time but other time it throws this error.
Nothing is displayed on the server logs.
This is how I setup SSL configuration in the app:
(client.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient _client) {
SecurityContext sc = SecurityContext();
sc.setTrustedCertificatesBytes(sslCert.buffer.asInt8List());
HttpClient httpClient = HttpClient(context: sc);
httpClient.badCertificateCallback = (X509Certificate cert, String host, int port) => false;
httpClient.maxConnectionsPerHost = 10;
return httpClient;
};
client being a Dio instance
Our server is built using Node.js, with Apache on centOS

IdentityServer4 invalid_token "The issuer is invalid" on Azure, working on localhost

Help please, I'm building a .NET Core API with ionic front end. I want to use ASPNET Core Identity so I was more or less following this example
https://identityserver4.readthedocs.io/en/release/quickstarts/6_aspnet_identity.html
here is what I have in Startup.cs
// Adds IdentityServer
services.AddIdentityServer()
.AddTemporarySigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients(Configuration))
.AddAspNetIdentity<ApplicationUser>();
and
app.UseIdentity();
app.UseIdentityServer();
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = API_address,
RequireHttpsMetadata = false,
ApiName = "myAPIs"
});
and in my Config.cs file for in memory configurations I have
public class Config
{
// scopes define the resources in your system
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
}
// scopes define the API resources in your system
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource(
"myAPIs", // Api resource name
"My API Set #1", // Display name
new[] { JwtClaimTypes.Name, JwtClaimTypes.Role }) // Claims to be included in access token
};
}
// client want to access resources (aka scopes)
public static IEnumerable<Client> GetClients(IConfigurationRoot configuration)
{
return new List<Client>
{
new Client
{
ClientId = "myClient",
ClientName = "My Custom Client",
AllowedCorsOrigins = new List<string>
{
"whateverINeedHere"
},
AccessTokenLifetime = 60 * 60 * 24,
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
RequireClientSecret = false,
AccessTokenType = AccessTokenType.Jwt,
AllowedScopes =
{
"myAPIs"
}
}
};
}
}
Now the problem is that when I test this locally, everything works just fine.
I hit the /connect/token endpoint, I get a token response, hit the controller that needs token authorization and my claims are there. But when I deploy it to Azure, when I want to use the token (issued from that environment) I get 401 Unauthorized with response header invalid_token "The issuer is invalid". I've Googled, but people get invalid tokens with signature problems, not issuer. I've never used identity server before and to me this looks like it's some configuration problem. I have compared tokens I get from identity server on jwt.io, they look exactly the same, only difference being the issuer localhost -> myAPIAddress.
Can someone point me to the right direction?
This smells like it could be the temporary signing credentials. I also ran into problems when deploying to Azure when my cert wasn't loading.
I suggest you create a self signed cert and add it to azure using the following instructions. (Note this can be done in the new portal).
https://azure.microsoft.com/en-us/blog/using-certificates-in-azure-websites-applications/
REMEMBER: Make sure you add the WEBSITE_LOAD_CERTIFICATES application setting!
Also for your benefit, here's the code I use to load the cert in my startup.cs. I keep a copy of the cert in the repository so I can load it from disk as a fallback (when I'm on my dev machine).
X509Certificate2 cert = null;
using (X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
certStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = certStore.Certificates.Find(
X509FindType.FindByThumbprint,
// Replace below with your cert's thumbprint
"A9781679661914B7539BE020EE9C4F6880579F42",
false);
// Get the first cert with the thumbprint
if (certCollection.Count > 0)
{
cert = certCollection[0];
// Use certificate
Log.Logger.Information($"Successfully loaded cert from registry: {cert.FriendlyName}");
}
}
// Fallback to local file for development
if (cert == null)
{
cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "myauth.pfx"), "mypassword");
Log.Logger.Information($"Falling back to cert from file. Successfully loaded : {cert.FriendlyName}");
}
services.AddIdentityServer()
.AddSigningCredential(cert)
Could be you've got an SSL/TLS issue between client and IdentityServer, are you able to view logged exceptions from IdentityServer itself? You may see something like:
"... Could not establish trust relationship for the SSL/TLS..."
If you're running IdentityServer on HTTPS you need to make sure you've got its domain/sub-domain in your certificate.
Either way, IdentityServer logs lots of useful info so turn on logging and check out what it says, that should point you in the right direction.

Connect to a SharePoint site when IIS requires client certificates

I currently have an application developed in C# that helps me in managing permissions on our Share-point 2013 site. Recently, I learned we may be loosing our local instance and moving to another instance that's behind a cac enforced IIS. I have converted one of my test sites to require certificates and have tried several way to send the cert to the IIS server but I still get
"The remote server returned and error: (403) Forbidden.
Below is a few things I have tried.
var handler = new WebRequestHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
handler.ClientCertificates.Add(pki.GetClientCertificate());
handler.UseProxy = false;
using (var client = new HttpClient(handler))
{
context connection code here
}
the pki.GetClientCertificate is a method, I made that returns a selected certificate in this case my cac cert. Its funny that SharePoint designer connects without issue or prompt. Any help on this matter would be much appreciated.
Just to add some more things I have tried
context.Credentials = new SharePointOnlineCredentials(uli.username, uli.password);
the uli username is the certificate converted to username I have a class that dose the conversion. the password is the pin converted to a secure string. I get the same message even when adding the credentials to the context.
I found a workable but slow solution here:
http://sharepoint.findincity.net/view/635399286724222582121618/ssl-certificate-error-when-using-client-object-model
The only issue with this is every time I call the context I have to send the certificate chain. One thing I changed from this users code is the following.
static void context_ExecutingWebRequest(object sender, WebRequestEventArgs e)
{
IntPtr ptr = IntPtr.Zero;
X509Certificate2 certificate = null;
X509Certificate t = null;
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
// Nothing to do if no cert found.
HttpWebRequest webReq = e.WebRequestExecutor.WebRequest;
//webReq.Proxy = new WebProxy("http://[ProxyAddress]");
//Specify a proxy address if you need to
// X509Certificate cert = pki.GetClientCertificate();
foreach (X509Certificate c in store.Certificates)
{
webReq.ClientCertificates.Add(c);
}
}
I just dumped all my certificates into the request because I didn't want to have a prompt every time I clicked something. So if anyone has a more efficient way to do this let me know.
The code below shows the use of the clientcontext and how it validates your cert
using (context = new ClientContext(siteurl))
{
ServicePointManager.ServerCertificateValidationCallback = delegate(object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
bool validationResult = true;
return validationResult;
};
context.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(context_ExecutingWebRequest);
//add all your context commands below this line
}

How to connect from client using CCDT and SSL to Remote Queue Manager (WebSphere MQ Server) using C#

I am fairly new to the IBM WebSphere MQ.
And my requirement (as below) :
1) I want to create and configure Client Certificate, Server Certificate, Certificate Request, Certificate Authority, Key Stores using KeyType as CMS.
2) After the above, I need to configure Remote Queue Manager for SSL (TLS_RSA_WITH_AES_128_CBC_SHA256)
2) I will be using C#.NET code to connect using the CCDT Method.
I am looking for sample program(s) for the above if any.
Thanks & Regards,
KJK
i assumed you already have your CCDT file , So sample code
public void TestSSLConnectionWithCCDT()
{
try
{
Environment.SetEnvironmentVariable("MQCHLLIB", #"D:\MQCCDT\QM_SSLConnect\");
Environment.SetEnvironmentVariable("MQCHLTAB", "AMQCLCHL.TAB");
Hashtable props = new Hashtable();
props.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT);
props.Add(MQC.SSL_CERT_STORE_PROPERTY, sslKeyRepository);
MQQueueManager qMgr = new MQQueueManager("QM_SSLConnect", props);
MQQueue queue1 = qMgr.AccessQueue("XYZ", MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING);
MQMessage msg = new MQMessage();
msg.WriteUTF("Test Message");
queue1.Put(msg);
}
catch (MQException ex)
{
Console.WriteLine("WebSphere MQ error occurred: {0}", ex.ToString());
}
catch (System.Exception ex)
{
Console.WriteLine("System error occurred: {0}", ex.ToString());
}
}
You can test Transport level security with self-signed certificates, For more details follow the link http://2freeclear.wordpress.com/2014/11/29/transport-level-security-with-ibm-websphere-mq-in-net-environment/

How to use X509Certificate2 as the credentials for a SharePointService request

I have a MOSS 2007 farm that requires a client certificate to access. I have written several methods that use the built in SharePoint services to retrieve data from the site. However, outside of my local test environment everything requires a client cert to access the services.
My method for retrieving the cert is:
private static X509Certificate2 GetCertCreds()
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
try
{
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectKeyIdentifier, "SiteIdentityCertificateSerialNumber", true);
Assert.IsNotNull(certs);
return certs[0];
}
finally
{
store.Close();
}
}
Then in use I have to have something LIKE:
using (ListsServiceProxy.Lists service = new ListsServiceProxy.Lists())
{
service.Crendentials = GetCredentials();
XmlNode idResultsNode = service.GetListItems(documentLibraryName, null, queryNode, viewNode, "1", optionNode, null);
}
This is not compiling because of the type mismatch. Am I going about this the wrong way? If not is there a way to use the certificate as the services credentials? I think in end what I'm trying to do is convert an X509Certificate2 to ICredentials. Any help or advice would be greatly appreciated.
It turns out I had it all wrong. To correctly do this I replaced:
service.Credentials = GetCertCreds()
with
service.ClientCertificates.Add(GetCretCreds());
Adding the certificate into the service's client certificates collection is all that needed to happen.

Resources