NodeJS load PFX certificate from file - node.js

I am writing a small project using Node.JS and TypeScript, once of the requirements is to read a PFX certificate from a .pfx file and use this in the code to encrypt the payload body
I have a certificate public/private key file called cert1.pfx, my code requires this certificate as below
...
const cert = loadPfx("cert1.pfx");
const p: Payload = new Payload();
p.addReaderCertificate(cert);
...
I have searched around but cannot find a way to load the PFX for my use case, I have seen examples of loading a PFX for HTTPS server or Express.JS, I looked a node-x509 but that is for BASE64 encoded CER or PEM certificates, I also looked at node-rsa but thats for encrypt/decrypt using public/private keys.
Does anyone know if this is possible? If so would appreciate some pointers on how to accomplish.

So after a LOT of research and trawling the Google archives I came across a package called pem and this has the following method:
pem.readPkcs12(bufferOrPath, [options], callback)
This can read a PKCS#12 file (or in other words a *.pfx or *.p12 file) amongst other things, I must have missed this in my earlier research.
Usage:
const pem = require("pem");
const fs = require("fs");
const pfx = fs.readFileSync(__dirname + "/test.pfx");
pem.readPkcs12(pfx, { p12Password: "password" }, (err, cert) => {
console.log(cert);
});
Output:
{ cert: "...", ca: ["subca", "rootca"], key: "..." }
You can find more here and here.

It sounds like you only need to use Node's own https capabilities. Node can read the PFX file directly. (Https.createServer, SSL Options)
Example from Node.js site:
const https = require('https');
const fs = require('fs');
const options = {
pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
passphrase: 'sample'
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);

I was also stuck on a similar problem #neil-stevens solution helped me to read the .pfx file but what i find is one feature/bug ( i don't know exactly what it is) of pem that it returns encrypted private key mostly in RSA , but if you need actual private key you need to export encrypted key into pkcs8,which can be done using Node RSA.
Usage :
const RSAKey = cert.key;
const key = new NodeRSA(RSAKey);
const privateKey = key.exportKey("pkcs8");

Complementing the answer of Neil Stevens (Sorry, idk how to quote).
I hade that issue of getting a empty object only, but so i just observe that i was not loging the err. So i did that, after that i was able to resolve my problems
1º You need to have installed openSSL or libressl how described on https://github.com/Dexus/pem.
Tip: To install if you already have configured and instaled Chocolatey. Just Run the command: "choco install openssl". (with eleveted permissions)
2º I had to use pem.config() to set exatcly path of openSSL folder. I think you can also define in the Environment Variables, i just not tested this way yet.
3º Finally my code it was left like this:
const pem = require("pem");
const fs = require("fs");
const pfx = fs.readFileSync("./cert.pfx");
let certificate = '';
pem.config({
pathOpenSSL: 'C:\\Program Files\\OpenSSL-Win64\\bin\\openssl'
})
const getPrivateKey = async () => {
return new Promise(async (resolve, reject) => {
pem.readPkcs12(pfx, { p12Password: 'myPassWordStr' }, (err, cert) => {
console.log('err::: ', err);
// console.log('cert::: ', cert);
resolve(cert);
});
});
}
const start = async () => {
certificate = await getPrivateKey();
console.log('privateKey::: ', certificate);
}
start();

I arrived here while trying to find a way to configure a local web server with HTTPS for local development using the development certificate generated by the .NET CLI (as this is easily created / trusted / removed).
Thanks to Neil Stephen's answer I was able to create a working solution on Windows, using a combination of npm, dotnet CLI, openssl and npm package pem.
Git ships with a copy of OpenSSL, so I didn't need to install it separately :)
.env
OPENSSL_PATH=C:\Program Files\Git\usr\bin\openssl
CERT_PASSWORD=SecurePassword123
CERT_PFX=cert/localhost.pfx
CERT_PEM=cert/localhost.pem
CERT_KEY=cert/localhost.key
PORT=443
ENTRYPOINT=src/index.html
package.json
"scripts": {
"start": "env-cmd -x parcel $ENTRYPOINT --https --cert $CERT_PEM --key $CERT_KEY --port $PORT --open",
"build": "env-cmd -x parcel build $ENTRYPOINT",
"dev-certs": "run-s dev-certs:create dev-certs:convert",
"dev-certs:create": "env-cmd -x dotnet dev-certs https -ep $CERT_PFX -p $CERT_PASSWORD --verbose --trust",
"dev-certs:convert": "node ./cli/cert.mjs",
"dev-certs:clean": "dotnet dev-certs https --clean"
},
cert.mjs
import pem from "pem";
import { PFX2PEM } from "pem/lib/convert.js";
import fs from "fs";
import "dotenv/config";
pem.config({
pathOpenSSL: process.env.OPENSSL_PATH
});
const pass = process.env.CERT_PASSWORD;
// GET .KEY FILE - without this, HMR won't work
const pfx = fs.readFileSync(process.env.CERT_PFX);
pem.readPkcs12(pfx, { p12Password: pass }, (err, cert) => {
if (!!err) {
console.error(err);
return;
}
// console.log(cert.key);
fs.writeFileSync(process.env.CERT_KEY, cert.key);
});
// GET .PEM FILE
PFX2PEM(process.env.CERT_PFX, process.env.CERT_PEM, pass, (errPem, successPem) => {
if (!successPem) {
console.error(errPem);
return;
}
console.log(`Certificate '${process.env.CERT_PEM}' created!`);
});
Repository is here: https://github.com/zplume/parcel-https and the README contains details of how it works.

Related

how to modify https traffic in google chrome using nodejs?

Like a question, of course I didn't do it because of illegal behavior.
For example, I have a link: https://example.com/inj.php
The result I get for example is:
<h1>Hello world</h1>
How can I fix it using only nodejs code?
<h1>Hello world</h1>
<h2>inject</h2>
I think you need to create a proxy and that device needs to install and configure your self-signed CA.
I wrote a library for personal use, it works pretty well
npm i pms-proxy
As your question above, it can be written as
const https = await PPCa.generateCACertificate();
const spki = PPCa.generateSPKIFingerprint((<PPCaFileOptions>https).cert);
const userData = path.join('C:/test-chrome');
const server = new PPServerProxy({https});
const pass = new PPPassThroughHttpHandler();
pass.injectBuffer((req, buffer) => {
return {
data: buffer.toString() + "<h2>inject</h2>"
};
})
server.addRule().url('https://example.com/inj.php').then(pass);
await server.listen(1234);
// node module
child_process.exec(
`start chrome --proxy-server="http://127.0.0.1:1234" --ignore-certificate-errors-spki-list=\"${spki}\" --user-data-dir=\"${userData}\"`
);
If you don't want to use SPKI Fingerprint you can create a self-signed CA, follow the README in the package:
https://www.npmjs.com/package/pms-proxy

nodejs pem generated openssl self signed certificate generation for intranet CIPHER_MISMATCH

I am using the module "pem" for nodejs && express to generate openssl self signed certificates for a demo webserver run over a local intranet.
The issue I am having is that when I attempt to load pages off the webserver I am receiving the error: "The client and server don't support a common SSL protocol version or cipher suite."
How would I be able to utilize pem ( or other ) in a way to allow me run my webserver over https via my intranet?
I am running/testing this on a ubtuntu machine and also testing on a windows machine. Both are generating the same error - the accessible machine over the intranet would be from the linux box. I am using nodejs 10 and tested on firefox, chrome, edge and safari
...
pem.createCertificate({ days: 365, selfSigned: true }, this.start);
...
start(err, keys) {
if (err) {
throw err
}
let server = https.createServer(app,
{ key: keys.serviceKey, cert: keys.certificate });
server.listen(port,
() => console.log(`API/NG running on https://localhost:${port}`)
);
}
According to the documentation of the pem module, the order of arguments is in reverse order, like follows:
var serverOptions = {
key: keys.serviceKey,
cert: keys.certificate
};
var app = express();
var server = https.createServer(serverOptions, app);

Multiple SSL Certificates and HTTP/2 with Express.js

Scenario:
I have an express.js server which serves variations of the same static landing page based on where req.headers.host says the user is coming from - think sort of like A/B testing.
GET tulip.flower.com serves pages/flower.com/tulip.html
GET rose.flower.com serves pages/flower.com/rose.html
At the same time, this one IP is also responsible for:
GET potato.vegetable.com serving pages/vegetable.com/potato.html
It's important that these pages are served FAST, so they are precompiled and optimized in all sorts of ways.
The server now needs to:
Provide separate certificates for *.vegetables.com, *.fruits.com, *.rocks.net
Optionally provide no certificate for *.flowers.com
Offer HTTP2
The problem is that HTTP2 mandates a certificate, and there's now multiple certificates in play.
It appears that it's possible to use multiple certificates on one Node.js (and presumably by extension Express.js) server, but is it possible to combine it with a module like spdy, and if so, how?
Instead of hacking node, would it be smarter to pawn the task of sorting out http2 and SSL to nginx? Should the caching network like Imperva or Akamai handle this?
You can use also tls.createSecureContext, Nginx is not necassary.
MY example here:
const https = require("https");
const tls = require("tls");
const certs = {
"localhost": {
key: "./certs/localhost.key",
cert: "./certs/localhost.crt",
},
"example.com": {
key: "./certs/example.key",
cert: "./certs/example.cert",
ca: "./certs/example.ca",
},
}
function getSecureContexts(certs) {
if (!certs || Object.keys(certs).length === 0) {
throw new Error("Any certificate wasn't found.");
}
const certsToReturn = {};
for (const serverName of Object.keys(certs)) {
const appCert = certs[serverName];
certsToReturn[serverName] = tls.createSecureContext({
key: fs.readFileSync(appCert.key),
cert: fs.readFileSync(appCert.cert),
// If the 'ca' option is not given, then node.js will use the default
ca: appCert.ca ? sslCADecode(
fs.readFileSync(appCert.ca, "utf8"),
) : null,
});
}
return certsToReturn;
}
// if CA contains more certificates it will be parsed to array
function sslCADecode(source) {
if (!source || typeof (source) !== "string") {
return [];
}
return source.split(/-----END CERTIFICATE-----[\s\n]+-----BEGIN CERTIFICATE-----/)
.map((value, index: number, array) => {
if (index) {
value = "-----BEGIN CERTIFICATE-----" + value;
}
if (index !== array.length - 1) {
value = value + "-----END CERTIFICATE-----";
}
value = value.replace(/^\n+/, "").replace(/\n+$/, "");
return value;
});
}
const secureContexts = getSecureContexts(certs)
const options = {
// A function that will be called if the client supports SNI TLS extension.
SNICallback: (servername, cb) => {
const ctx = secureContexts[servername];
if (!ctx) {
log.debug(`Not found SSL certificate for host: ${servername}`);
} else {
log.debug(`SSL certificate has been found and assigned to ${servername}`);
}
if (cb) {
cb(null, ctx);
} else {
return ctx;
}
},
};
var https = require('https');
var httpsServer = https.createServer(options, (req, res) => { console.log(res, req)});
httpsServer.listen(443, function () {
console.log("Listening https on port: 443")
});
If you want test it:
edit /etc/hosts and add record 127.0.0.1 example.com
open browser with url https://example.com:443
Nginx can handle SSL termination nicely, and this will offload ssl processing power from your application servers.
If you have a secure private network between your nginx and application servers I recommend offloading ssl via nginx reverse proxy. In this practice nginx will listen on ssl, (certificates will be managed on nginx servers) then it will reverse proxy requests to application server on non ssl (so application servers dont require to have certificates on them, no ssl config and no ssl process burden).
If you don't have a secure private network between your nginx and application servers you can still use nginx as reverse proxy via configuring upstreams as ssl, but you will lose offloading benefits.
CDNs can do this too. They are basically reverse proxy + caching so I dont see a problem there.
Good read.
Let's Encrypt w/ Greenlock Express v3
I'm the author if Greenlock Express, which is Let's Encrypt for Node.js, Express, etc, and this use case is exactly what I made it for.
The basic setup looks like this:
require("greenlock-express")
.init(function getConfig() {
return {
package: require("./package.json")
manager: 'greenlock-manager-fs',
cluster: false,
configFile: '~/.config/greenlock/manager.json'
};
})
.serve(httpsWorker);
function httpsWorker(server) {
// Works with any Node app (Express, etc)
var app = require("./my-express-app.js");
// See, all normal stuff here
app.get("/hello", function(req, res) {
res.end("Hello, Encrypted World!");
});
// Serves on 80 and 443
// Get's SSL certificates magically!
server.serveApp(app);
}
It also works with node cluster so that you can take advantage of multiple cores.
It uses SNICallback to dynamically add certificates on the fly.
Site Management
The default manager plugin uses files on the file system, but there's great documentation on how to build your own.
Just to get started, the file-based plugin uses a config file that looks like this:
~/.config/greenlock/manager.json:
{
"subscriberEmail": "letsencrypt-test#therootcompany.com",
"agreeToTerms": true,
"sites": [
{
"subject": "example.com",
"altnames": ["example.com", "www.example.com"]
}
]
}
Very Extensible
I can't post all the possible options here, but it's very small and simple to start with, and very easy to scale out with advanced options as you need them.

Broken HTTPS SSL in express-js server (net::ERR_CERT_COMMON_NAME_INVALID)

I have an express js application that I want to listen on HTTPS.
I had a .key file and a .crt file that were already in PEM format (they contained readable text, as this answer says to check), so I used OpenSSL with these commands (taken from the answer linked above, and before finding that answer I had tried using the .key and .crt files I already had and using .pem files created by just renaming those two files into .pem, with no success):
openssl x509 -in public.crt -out public.pem -outform PEM
openssl rsa -in private.key -out private.pem -outform PEM
When I try to access the website at https://localhost, though, this is the error I get:
How can I make it work as intended?
Note that the certificate and key are VALID since I'm already using them on an existing website, it's not a self-signed test certificate.
Also, the client page tries to get the resource "/hey" but in addition to the HTTPS error in the certificate, instead of the resource the page gets a response that says "Cannot GET/"
Here is the code to the node.js app:
var express = require('C:/Users/f.fiore/AppData/Roaming/npm/node_modules/express');
var fs = require('fs');
var http = require('http');
var https = require('https');
var key = fs.readFileSync('./private.key');
var cert = fs.readFileSync('./public.crt')
var options = {
key: key,
cert: cert
};
var PORT = 8000;
var HOST = 'localhost';
var app = express();
var httpServer = https.createServer(app);
var httpsServer = https.createServer(options, app);
httpServer.listen(PORT);
httpsServer.listen(443);
// routes
app.get('/hey', function(req, res) {
sendToClient("HO!", res, 200, "text/plain");
});
function getHeader(type){
return {"Content-Type": type};
}
function sendToClient(data, res, code, type){
res.writeHead(code, getHeader(type));
(type === "text/html" || type === "text") ? res.end(data, "utf-8") : res.end(data);
}
Your certificate is valid, however the provider of the certificate is not the original issuer of this certificate.
So you need to provide the whole chain certificate at your localhost to make it work.
https://certificatechain.io/ seems like they are providing a service for this, but haven't tried. Better way is to check with your certificate provider.
Self signed certificates also bring such an error.
EDIT
Seems like the problem was more basics. Updating the solution
Try to play with your etc/hosts file to show the real domain name at your localhost. Right now it is looking for a domain called localhost and I don't think that you get a certificate for your localhost :) \Windows\System32\drivers\etc\hosts at windows environment
For your basic request of /hey please insert this codeblock
app.get('/hey', function(req, res){
res.send('HO!');
});

How to set connect server (node) to work on HTTPS? Error: error:0906D06C:PEM routines:PEM_read_bio:no start line

I am using connect server, and I need to create my localhost under https (even if certificates are not valid).
At the moment I am using the following script which createa a server listing at http://127.0.0.1:8080/
I need to set it up as: https://127.0.0.1:8080/
How to configure connect server?
gulp.task('dev:connect', function () {
// runs connect server for rapid development
connect.server({
root: ''
});
});
I am also trying this but with not success:
var https = require('https');
var options = {
key: fs.readFileSync('b.key'),
cert: fs.readFileSync('a.crt')
};
var app = connect(); // error here object is not a function
https.createServer(options, app).listen(8080);
Try to run the following, I think the key is protected:
$ openssl rsa -in b.key -out b-unprotected.key
$ cat b-unprotected.key a.crt > a.pem
Let me know if this works

Resources