Self signed certificate in certificate chain - node.js

I am running a node.js service in a Kubernetes container. My service uses the token inside the service account to make calls to the API server from inside the POD. My code is like this
var fs = require('fs');
var tokenFile ='/var/run/secrets/kubernetes.io/serviceaccount/token';
var restCall = function(serviceUrl,reqMethod,callback){
var token = "";
fs.readFile(tokenFile, 'utf8', function(err, data) {
if (err) throw err;
token ='Bearer '+data;
});
var serviceUrl = https://<clusterName>/api/v1/nodes
var options = {
url: serviceUrl,
headers: {
'Content-Type': 'application/json',
'Authorization': token
},
method: reqMethod
};
I am receiving this error in response
self signed certificate in certificate chain.
I am able to make calls using the token through rest client, when I deployed to container it was returning socket connection error

You call the api with an https protocol, where most likely the certificate is not signed by external CA. This is normal. You should make sure you trust that CA before you make a call to service secured by certificate it issued. Most kube provisioners provide you back with CA certificate so you can add it to your trusted certs or provide to the client in some param.
On the other side, when you makethe call to api within your kube cluster an url like http://kubernetes.default/api/v1/nodes should be reachable.

Try using CA certificate, you will get it in following path
/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
Radek Pieczonka mentions this in his answer,

missed to pass this environment variable node_tls_unauthorized=0 which results in authentication issue

Related

"x509" SSL Issue with calling an OnPremise endpoint from Azure Function App

We are experiencing an issue calling an On-premise API endpoint from our Azure Function and I'm at a loss to the reason.
We are getting the following error: "x509 certificate signed by unknown authority" back as a 500 status code, which is strange considering we are using the appropriate code within the HttpClientHandler code.
Specifically, we have code that calls an OAuth endpoint which we get a response for, so definitely goes through our firewall and returns a 200 OK response. This endpoint has a DigiCert certificate.
In the same function, this then calls the functional endpoint to return some user data. This comes back with a 500 Internal Server error. This endpoint has a PKI certificate.
There is some level of NSG/Azure Firewall and On Premise setup involved but wondering whether anyone has experienced this before as I'm stumped on next steps.
Sample code looks this as follows
using (HttpClientHandler httpClientHandler = new HttpClientHandler() {
CheckCertificateRevocationList = false,
ServerCertificateCustomValidationCallback =
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
}) {
using (HttpClient client = new HttpClient(httpClientHandler))
{
return await GetEligibilityToken(client);
}
}
// OAuth Endpoint - This works as expected
var token = Task.Run(() => TokenRetriever.GetEligibilityToken()).GetAwaiter().GetResult();
// Call the User Endpoint - This does not work, configured by
// ConfigurePrimaryHttpMessageHandler with same
// ServerCertificateCustomValidationCallback options.
string apiEndpoint = Constants.SSOApiEndpointDomain;
string path = $#"{apiEndpoint}/v1.0/users/813229bc-3a32-4457-85d5-af7b70db85e0";
// Add the token
_httpClient.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Bearer", token.AccessToken);
var response = await _httpClient.GetAsync(path).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
string data = response.Content.ReadAsStringAsync().Result; code here
Note - I'm aware of the suboptimal use of using HttpClient, I've tried both that and ConfigurePrimaryHttpMessageHandler options.
Any help or advice you could give would be greatly appreciated. I'm even starting to wonder whether we can call services with PKI certs via Azure Functions.
J
Edit - I should say the code works fine "locally" (albeit I appreciate it needs cleaning up) and we get the desired behaviour. I do have the appropriate CA authority certs on my own VM.

How to respond to OCSPRequest when using a self signed certificate?

I'm trying to create an https server using a self signed certificate, but it seems to fail because it requires a response to the OCSPRequest callback, which I have no idea what that should contain. The documentation (https://nodejs.org/api/tls.html#tls_event_ocsprequest) is not helpful at all in my case, especially this part:
Server extracts the OCSP URL from either the certificate or issuer and performs an OCSP request to the CA.
How do I extract the OCSP URL? Do I even need to do that? What/who is the CA? Certificate Authority? No idea, I guess that's me in this case because I created the certificate myself, correct? How do I proceed?
const fs = require("fs");
const httpsServer = require("https").createServer({
key: fs.readFileSync("./key.pem"),
cert: fs.readFileSync("./cert.pem"),
});
const server = httpsServer.listen(9777);
server.on('OCSPRequest', (certificate, issuer, callback) => {
let response = 'What goes in here?';
callback(null, response);
});
All the examples that I found never mention it, for instance: https://nodejs.org/en/knowledge/HTTP/servers/how-to-create-a-HTTPS-server/
A self-signed certificate cannot be revoked, since the issuer of the certificate is the certificate itself. No revocation possible means no OCSP response. The expected behavior based on the documentation you've linked to is thus:
Alternatively, callback(null, null) may be called, indicating that there was no OCSP response.

MTLS - generate certificate to nodejs client side

We need to communicate between our ec2 server and our customer server via Mutual TLS.
The requests are sent from our server to our customer server - so we are the client here.
I read this post, talking about how to generate the files.
The first step is to create a certificate authority (CA) that both the
client and server trust. The CA is just a public and private key with
the public key wrapped up in a self-signed X.509 certificate.
Our cert and their cert - should be signed from the same root CA? who should provide it?
The code in my side should be like:
const req = https.request(
{
hostname: 'myserver.internal.net',
port: 443,
path: '/',
method: 'GET',
cert: fs.readFileSync('client.crt'),
key: fs.readFileSync('client.key'),
ca: fs.readFileSync('ca.crt')
},
res => {
res.on('data', function(data) {
// do something with response
});
}
);
So what should we provide each other? We don't exactly understand and they are not providing more details, just asked us to give them a certificate...
Our cert and their cert - should be signed from the same root CA? who should provide it?
Since the control of the client certificate is done at the TLS server side (i.e. at the customer) it depends fully on what they expect. They might require a publicly signed certificate, they might require a certificate signed by their own CA. Or they might simply check that a specific certificate gets used and will also accept self-signed certificates for this.

validate https requests using a Certificate Authority (CA)

I have deployed multiple microservices containing frontend application and backend service.
The frontend application is accessible via xyz.com domain. It calls the backend service API endpoint.
So, what I really want is to check is that if any request that is coming from the frontend application is valid and from authentic source on the basis of its domain and subdomain using Certificate Authority in Node.js.
After doing a little bit of research about how it can be done in node.js,
I found out that it can be done using nodejs https module's request method. But the problem with this approach is that nodejs maintains a list of CA certs, which easily gets out of date and there is a chance that the CA that has verified my domain certificate is not part of that list. Although they provide a way to pass additional CA's but still it is a dependency on the user side that they have to maintain the list. I am currently a little bit lost on how to do it in a proper way.
I need help on how to do this process easily and efficiently.
There are two ways to validate a domain in node.js
https.request
Nodejs https module's request method validates the domain provided against the chain of Certificate Authorities root certificate. A code example is given below:
var https = require('https');
var options = {
hostname: 'github.com/',
port: 443,
path: '/',
method: 'GET',
rejectUnauthorized: true
};
var ss;
var req = https.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
});
req.end();
req.on('error', function(e) {
console.error(e);
});
rejectUnauthorized: This means that it will validate the server/domain certificate against the chain of CA's root certificate.
The only problem with this approach is that this chain should be updated regularly otherwise a new domain that is signed by a certificate authority root certificate which is not part of the chain, marked as an invalid certificate(a common example is a self-signed certificate).
ssl-validate module
It can also be used but it requires another module to get the domain information.

NodeJS forwarding client SSL certificates

I am working on Node.js server application which is SSL enabled and accepts client certificates. I am using following code to create https server.
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem'),
ca: fs.readFileSync('ca.pem'),
requestCert: true,
rejectUnauthorized: true
};
https.createServer(options,app).listen(8090, function(){
console.log("Listening on 8090");
});
Other Node.js based client apps are able to connect using their SSL certficate and get the service response.
However from my sever, I want to make another server call and wish to pass on the same client certificate I received. I simply want to forward the same ceritifcate, I understand I can get the certificate details in request object, but how to retrieve the crt and key from that object?
I am looking to do something like below:
app.get('/myservice', (req,res) => {
//req.socket.getPeerCertificate(true);
var agent = new https.Agent({
cert: somelibrary(req.socket.getPeerCertificate(true).??????),
key: somelibrary(req.socket.getPeerCertificate(true).??????),
});
fetch('http://AnotherServiceURL', { method: 'GET' agent}).then(function(response){
res.json(response);
});
});
Is there any library which can convert request certificate details in a way so as to forward those as key and cert? Or is there any other/better way of doing this?
I understand I can get the certificate details in request object, but how to retrieve the crt and key from that object?
While it would be possible to pass the client certificate itself it is impossible to use it again as client certificate in another TLS connection to the final target. For this you would need to have access to the private key of the client, which as the name says is private to the client. As for getting the client certificate (i.e. the public part) see Node.js: access the client certificate.

Resources