Openssl command automatically added "/openssl" before the file name in AWS nodejs that cause getting file not found error - node.js

const openssl = require('openssl-nodejs');
await openssl('openssl base64 -d -in /tmp/omnivoltaic.signature.txt -out /tmp/encodedfile.txt',function(err,buffere){
console.log('Err2..>>>',err.toString());
console.log('Successs2>>>>',buffer.toString());
});
Error :
Err2..>>> openssl//tmp/omnivoltaic.signature.txt: No such file or directory
140523322107728:error:02001002:system library:fopen:No such file or directory:bss_file.c:398:fopen('openssl//tmp/omnivoltaic.signature.txt','r')
140523322107728:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:400:

Related

Facebook SDK on Linux Unity Editor cant found Keytool

I working on Pop_OS 20.04 LTS with Unity 2019.4 LTS and I have problem, Facebook SDK cant found Keytool. In source code available on GitHub sdk trying to execute next command:
keytool -exportcert -alias androiddebugkey -keystore debug.keystore | openssl sha1 -binary | openssl base64
I can execute it from terminal or even from c# program using their code from sdk, but in unity this not working for some reason:
static void Main(string[] args)
{
var proc = new Process();
var arguments = #"""keytool -storepass {0} -keypass {1} -exportcert -alias {2} -keystore {3} | openssl sha1 -binary | openssl base64""";
proc.StartInfo.FileName = "bash";
arguments = #"-c " + arguments;
proc.StartInfo.Arguments = string.Format(arguments, "android", "android", "androiddebugkey", System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + #"/.android/debug.keystore");
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
var keyHash = new StringBuilder();
while (!proc.HasExited)
{
keyHash.Append(proc.StandardOutput.ReadToEnd());
}
switch (proc.ExitCode)
{
case 255: Console.WriteLine("Error");
return;
}
Console.WriteLine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + #"/.android/debug.keystore");
Console.WriteLine(keyHash.ToString());
}
. Can somebody help with this?
It looks like I can safely use the hash generated by this command.
keytool -exportcert -alias androiddebugkey -keystore debug.keystore | openssl sha1 -binary | openssl base64
Although I get an error stating that Facebook is not configured,but it does not prevent me from building a workable application

Node TLS socket : DEPTH_ZERO_SELF_SIGNED_CERT error

I am trying to setup a server and some clients using TLS in node. I am using self-signed certificates on the clients and the server. The server runs ok, but when I try to connect a client I end up with the following error on the client side:
Error: DEPTH_ZERO_SELF_SIGNED_CERT
Cert Generation
CA cert:
# Create key to sign our own certs. Act like as our own a CA.
echo "SecuresPassphrase" > ./tls/passphrase.txt
openssl ecparam -name secp521r1 -genkey -noout -out ./tls/certs/ca/ca.plain.key # Generate private key
openssl pkcs8 -topk8 -passout file:./tls/passphrase.txt -in ./tls/certs/ca/ca.plain.key -out ./tls/certs/ca/ca.key # Generate encrypted private key
rm ./tls/certs/ca/ca.plain.key; # Remove unencrypted private key
# Generate CA cert
openssl req -config ./openssl/oid_file -passin file:./tls/passphrase.txt -new -x509 -days 365 -key ./tls/certs/ca/ca.key -out ./tls/certs/ca/ca.crt
Server Cert:
openssl ecparam -name secp521r1 -genkey -noout -out ./tls/certs/servers/server.key # Generate server private key
openssl req -config ./openssl/oid_file -new -key ./tls/certs/servers/server.key -out ./tls/certs/servers/server.csr # Generate signing request
openssl x509 -passin file:./tls/passphrase.txt -req -days 365 -in ./tls/certs/servers/server.csr -CA ./tls/certs/ca/ca.crt -CAkey ./tls/certs/ca/ca.key -CAcreateserial -out ./tls/server.crt
mv ./tls/server.crt ./tls/certs/servers/
Client cert:
Client's certs are created inside a bash loop, the variable ${name} contains the name of the client and changes each iteration.
openssl ecparam -name secp521r1 -genkey -noout -out ./tls/certs/clients/${name}/client.key
openssl req -config ./openssl/oid_file -new -key ./tls/certs/clients/${name}/client.key -out ./tls/certs/clients/${name}/client.csr
openssl x509 -passin file:./tls/passphrase.txt -req -days 365 -in ./tls/certs/clients/${name}/client.csr -CA ./tls/certs/ca/ca.crt -CAkey ./tls/certs/ca/ca.key -CAcreateserial -out ./tls/client.crt
mv ./tls/client.crt ./tls/certs/clients/${name}/
I am also trying to use Perfect Forward Secrecy by using ephemereal Diffie-Hellman interchange. The parameters, for clients and server, are created as openssl dhparam -outform PEM -out ./tls/params/servers/server/dhparams.pem 2048
Server's code:
return new Promise(resolve => {
// Define parameters of TLS socket
const options = {
rejectUnauthorized: false,
requestCert: true,
// Secure Context Parameters
ca: [fs.readFileSync("tls/certs/ca/ca.crt")],
cert: fs.readFileSync("tls/certs/servers/server.crt"),
key: fs.readFileSync("tls/certs/servers/server.key"),
ciphers: "ECDHE-ECDSA-AES128-GCM-SHA256:!RC4:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!SRP:!CAMELLIA",
dhparam: fs.readFileSync("tls/params/servers/server/dhparams.pem"),
ecdhCurve: tls.DEFAULT_ECDH_CURVE,
minVersion: "TLSv1.2"
};
// Iniciar servidor TLS
this.SERVIDOR = tls.createServer(options, function (socket) {
console.log("Server created.");
});
this.SERVIDOR.listen(this.puerto, this.direccion, function () {
console.log("Listening");
});
this.SERVIDOR.on("secureConnection", (socket) => this.handleRequest(socket));
this.SERVIDOR.on("tlsClientError", (error) => console.log("Error client TLs. %s", error));
});
Client's code:
return new Promise(resolve => {
// Define parameters of TLS socket
const options = {
host: this.NODE,
port: this.NODE_PORT,
rejectUnauthorized: false,
secureContext: tls.createSecureContext({
ca: [fs.readFileSync("tls/certs/ca/ca.crt")],
cert: fs.readFileSync("tls/certs/clients/" + this.NAME + "/client.crt"),
key: fs.readFileSync("tls/certs/clients/" + this.NAME + "/client.key"),
ciphers: "ECDHE-ECDSA-AES128-GCM-SHA256:!RC4:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!SRP:!CAMELLIA",
dhparam: fs.readFileSync("tls/params/clients/" + this.NAME + "/dhparams.pem"),
ecdhCurve: tls.DEFAULT_ECDH_CURVE,
minVersion: "TLSv1.2"
})
};
// Initialize TLS socket
this.WEB_SOCKET = tls.connect(options, function () {
// Check if TLS auth worked
if (this.authorized) {
console.log("Connection authorized by a Cert. Authority ");
} else {
console.log("Authorization not granted. Error: " + this.authorizationError);
}
});
What I have tried:
Set rejectUnauthorized to false.
Tried to run the code with NODE_TLS_REJECT_UNAUTHORIZED = "0";. It didn't work and I think is not a good option for production.
Checked similar questions on SO, this one it looks pretty similar to my problem. But the most upvoted answer is from 2014 and I couldn't find too much information about Distinguished name on the docs.
I checked the certs using openssl x509 -in *.cert -text and they looked good.
¿Am I wrongly generating the certs? Any help is appreciated.
Thanks!
EDIT. 16/10/2019
There was a problem in the code, I didn't use resolve(); when the sockets were up. The same problem remains... BUT despite of getting an authorization error on the client, the server fires up the "secureConnection" event and messages are interchanged. ¿Does this makes sense? *Yes, it makes sense since the server accepts unauthorized connections. If I set the server to reject not certified connections the clients hung up *
The problem was I was using the same configuration file (./openssl/oid_file) for all the certificates. Using different configuration files and different Alternative names solved this issue.
I ended with an "UNABLE_TO_VERIFY_LEAF_SIGNATURE" error. The certificates were properly generated but it didn't work. I couldn't find a working example of self-signed certificates in nodejs. Most of them simply deprecated the use of certificates by disabling SSL or accepting unathorized transactions, which is the opposite of what TLS is supposed to do.
Finally, I used this tool to generate the certificates: https://github.com/FiloSottile/mkcert . The best and simplest way to generate self-signed certificates in a testing environment. You only need to set the node variable NODE_EXTRA_CA_CERTS to point the root certificate:
process.env.NODE_EXTRA_CA_CERTS = [os.homedir() + "/.local/share/mkcert/rootCA.pem"];
-

How to connect from node js to mongodb replica set using SSL

I am trying to connect to a mongodb replica set which is set up to authenticate clients using SSL. I can connect using the mongo shell, but for some reason cannot connect from node.js with the same keys.
I am using mongodb version 3.2.6 and node.js driver version 2.1.18, running on mac.
I followed this article, and was able to setup a cluster on my local machine by running the attached script:
# Prerequisites:
# a. Make sure you have MongoDB Enterprise installed.
# b. Make sure mongod/mongo are in the executable path
# c. Make sure no mongod running on 27017 port, or change the port below
# d. Run this script in a clean directory
##### Feel free to change following section values ####
# Changing this to include: country, province, city, company
dn_prefix="/C=CN/ST=GD/L=Shenzhen/O=MongoDB China"
ou_member="MyServers"
ou_client="MyClients"
mongodb_server_hosts=( "server1" "server2" "server3" )
mongodb_client_hosts=( "client1" "client2" )
mongodb_port=27017
# make a subdirectory for mongodb cluster
kill $(ps -ef | grep mongod | grep set509 | awk '{print $2}')
#rm -Rf db/*
mkdir -p db
echo "##### STEP 1: Generate root CA "
openssl genrsa -out root-ca.key 2048
# !!! In production you will want to use -aes256 to password protect the keys
# openssl genrsa -aes256 -out root-ca.key 2048
openssl req -new -x509 -days 3650 -key root-ca.key -out root-ca.crt -subj "$dn_prefix/CN=ROOTCA"
mkdir -p RootCA/ca.db.certs
echo "01" >> RootCA/ca.db.serial
touch RootCA/ca.db.index
echo $RANDOM >> RootCA/ca.db.rand
mv root-ca* RootCA/
echo "##### STEP 2: Create CA config"
# Generate CA config
cat >> root-ca.cfg <<EOF
[ RootCA ]
dir = ./RootCA
certs = \$dir/ca.db.certs
database = \$dir/ca.db.index
new_certs_dir = \$dir/ca.db.certs
certificate = \$dir/root-ca.crt
serial = \$dir/ca.db.serial
private_key = \$dir/root-ca.key
RANDFILE = \$dir/ca.db.rand
default_md = sha256
default_days = 365
default_crl_days= 30
email_in_dn = no
unique_subject = no
policy = policy_match
[ SigningCA ]
dir = ./SigningCA
certs = \$dir/ca.db.certs
database = \$dir/ca.db.index
new_certs_dir = \$dir/ca.db.certs
certificate = \$dir/signing-ca.crt
serial = \$dir/ca.db.serial
private_key = \$dir/signing-ca.key
RANDFILE = \$dir/ca.db.rand
default_md = sha256
default_days = 365
default_crl_days= 30
email_in_dn = no
unique_subject = no
policy = policy_match
[ policy_match ]
countryName = match
stateOrProvinceName = match
localityName = match
organizationName = match
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
[ v3_ca ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
basicConstraints = CA:true
EOF
echo "##### STEP 3: Generate signing key"
# We do not use root key to sign certificate, instead we generate a signing key
openssl genrsa -out signing-ca.key 2048
# !!! In production you will want to use -aes256 to password protect the keys
# openssl genrsa -aes256 -out signing-ca.key 2048
openssl req -new -days 1460 -key signing-ca.key -out signing-ca.csr -subj "$dn_prefix/CN=CA-SIGNER"
openssl ca -batch -name RootCA -config root-ca.cfg -extensions v3_ca -out signing-ca.crt -infiles signing-ca.csr
mkdir -p SigningCA/ca.db.certs
echo "01" >> SigningCA/ca.db.serial
touch SigningCA/ca.db.index
# Should use a better source of random here..
echo $RANDOM >> SigningCA/ca.db.rand
mv signing-ca* SigningCA/
# Create root-ca.pem
cat RootCA/root-ca.crt SigningCA/signing-ca.crt > root-ca.pem
echo "##### STEP 4: Create server certificates"
# Now create & sign keys for each mongod server
# Pay attention to the OU part of the subject in "openssl req" command
# You may want to use FQDNs instead of short hostname
for host in "${mongodb_server_hosts[#]}"; do
echo "Generating key for $host"
openssl genrsa -out ${host}.key 2048
openssl req -new -days 365 -key ${host}.key -out ${host}.csr -subj "$dn_prefix/OU=$ou_member/CN=${host}"
openssl ca -batch -name SigningCA -config root-ca.cfg -out ${host}.crt -infiles ${host}.csr
cat ${host}.crt ${host}.key > ${host}.pem
done
echo "##### STEP 5: Create client certificates"
# Now create & sign keys for each client
# Pay attention to the OU part of the subject in "openssl req" command
for host in "${mongodb_client_hosts[#]}"; do
echo "Generating key for $host"
openssl genrsa -out ${host}.key 2048
openssl req -new -days 365 -key ${host}.key -out ${host}.csr -subj "$dn_prefix/OU=$ou_client/CN=${host}"
openssl ca -batch -name SigningCA -config root-ca.cfg -out ${host}.crt -infiles ${host}.csr
cat ${host}.crt ${host}.key > ${host}.pem
done
echo ""
echo "##### STEP 6: Start up replicaset in non-auth mode"
mport=$mongodb_port
for host in "${mongodb_server_hosts[#]}"; do
echo "Starting server $host in non-auth mode"
mkdir -p ./db/${host}
mongod --replSet set509 --port $mport --dbpath ./db/$host \
--fork --logpath ./db/${host}.log
let "mport++"
done
sleep 3
# obtain the subject from the client key:
client_subject=`openssl x509 -in ${mongodb_client_hosts[0]}.pem -inform PEM -subject -nameopt RFC2253 | grep subject | awk '{sub("subject= ",""); print}'`
echo "##### STEP 7: setup replicaset & initial user role\n"
myhostname=`hostname`
cat > setup_auth.js <<EOF
rs.initiate();
mport=$mongodb_port;
mport++;
rs.add("$myhostname:" + mport);
mport++;
rs.add("$myhostname:" + mport);
sleep(5000);
db.getSiblingDB("\$external").runCommand(
{
createUser: "$client_subject",
roles: [
{ role: "readWrite", db: 'test' },
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "clusterAdmin", db:"admin"}
],
writeConcern: { w: "majority" , wtimeout: 5000 }
}
);
EOF
cat setup_auth.js
mongo localhost:$mongodb_port setup_auth.js
kill $(ps -ef | grep mongod | grep set509 | awk '{print $2}')
sleep 3
echo "##### STEP 8: Restart replicaset in x.509 mode\n"
mport=$mongodb_port
for host in "${mongodb_server_hosts[#]}"; do
echo "Starting server $host"
mongod --replSet set509 --port $mport --dbpath ./db/$host \
--sslMode requireSSL --clusterAuthMode x509 --sslCAFile root-ca.pem \
--sslAllowInvalidHostnames --fork --logpath ./db/${host}.log \
--sslPEMKeyFile ${host}.pem --sslClusterFile ${host}.pem
let "mport++"
done
# echo "##### STEP 9: Connecting to replicaset using certificate\n"
cat > do_login.js <<EOF
db.getSiblingDB("\$external").auth(
{
mechanism: "MONGODB-X509",
user: "$client_subject"
}
)
EOF
# mongo --ssl --sslPEMKeyFile client1.pem --sslCAFile root-ca.pem --sslAllowInvalidHostnames --shell do_login.js
After running the cluster, I am able to connect to it using the mongo shell with this command (all keys\certs were generated in ./ssl dir):
mongo --ssl --sslPEMKeyFile ssl/client1.pem --sslCAFile ssl/root-ca.pem --sslAllowInvalidHostnames
and authenticate as follows:
db.getSiblingDB("$external").auth(
{
mechanism: "MONGODB-X509",
user: "CN=client1,OU=MyClients,O=MongoDB China,L=Shenzhen,ST=GD,C=CN"
}
)
When I try to connect from node.js I keep failing. I am running the following code to connect to mongo using the native mongo driver:
'use strict';
const mongodb = require('mongodb');
const P = require('bluebird');
const fs = require('fs');
function connect_mongodb() {
let user = 'CN=client1,OU=MyClients,O=MongoDB China,L=Shenzhen,ST=GD,C=CN';
let uri = `mongodb://${encodeURIComponent(user)}#localhost:27017,localhost:27018,localhost:27019/test?replicaSet=set509&authMechanism=MONGODB-X509&ssl=true`;
var ca = [fs.readFileSync("./ssl/root-ca.pem")];
var cert = fs.readFileSync("./ssl/client1.pem");
var key = fs.readFileSync("./ssl/client1.pem");
let options = {
promiseLibrary: P,
server: {
ssl: true,
sslValidate: false,
checkServerIdentity: false,
sslCA: ca,
sslKey: key,
sslCert: cert,
},
replset: {
sslValidate: false,
checkServerIdentity: false,
ssl: true,
sslCA: ca,
sslKey: key,
sslCert: cert,
}
};
return mongodb.MongoClient.connect(uri, options);
}
connect_mongodb();
When running the script I get the following error:
Unhandled rejection MongoError: no valid seed servers in list
When checking the mongodb log I see these errors:
2017-01-17T22:48:54.191+0200 I NETWORK [initandlisten] connection accepted from 127.0.0.1:63881 #99 (5 connections now open)
2017-01-17T22:48:54.207+0200 E NETWORK [conn99] no SSL certificate provided by peer; connection rejected
2017-01-17T22:48:54.207+0200 I NETWORK [conn99] end connection 127.0.0.1:63881 (4 connections now open)
I was trying different options described here, but with no success.
Thanks for the help
Upgrading to mongodb node js driver 2.2.22 solved the problem

SSL in socket.io with express: Missing PFX or certificate + private key.

I want to socket with socket.io through SSL. I have read the other answers but nothing worked
Here is my code:
var ssl_options = {
key : fs.readFileSync(my_key_path),
cert : fs.readFileSync(my_cert_path)
};
var protocol = "https";
preparedApp = require(protocol).createServer(ssl_options,app);
var io = require('socket.io')(preparedApp);
preparedApp.listen(8080, function(){});
io.on('connection', function(socket){});
And here is the log of my ssl_options...
{ key: <Buffer 41 ...>,
cert: <Buffer 4a ...> }
This errors with the error in the title throw new Error('Missing PFX or certificate + private key.');. Does anyone know what might be happening? None of the other solutions to this answer solved my case.
Use PEM (RSA) format for your private key. Check if the private key is a base64 encoded, enclosed between "-----BEGIN RSA PRIVATE KEY-----" and "-----END RSA PRIVATE KEY-----"
From the docs:
key: A string or Buffer containing the private key of the server in PEM format
cert : A string holding the PEM encoded certificate
passphrase: A string of passphrase for the private key or pfx [optional default: null]
or
pfx : A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates
To convert a private key to RSA PEM: openssl rsa -in <PATH TO KEY> -out key.pem -outform PEM
To create a PKCS #12 bundle use openssl pkcs12 -export -in cert.pem -inkey key.pem -certfile ca.pem -out host.pfx
-- ADDITION --
To ensure the cert is PEM encoded run openssl x509 -in <PATH TO CERT> -out cert.pem -outform PEM

How do I use a self signed certificate for a HTTPS Node.js server?

I have started writing a wrapper for an API which requires all requests to be over HTTPS. Instead of making requests to the actual API while I am developing and testing it I would like to run my own server locally which mocks the responses.
I am confused about how to generate the certificates I need to create a HTTPS server and send requests to it.
My server looks something like this:
var options = {
key: fs.readFileSync('./key.pem'),
cert: fs.readFileSync('./cert.pem')
};
https.createServer(options, function(req, res) {
res.writeHead(200);
res.end('OK\n');
}).listen(8000);
The pem files were generated with:
openssl genrsa 1024 > key.pem
openssl req -x509 -new -key key.pem > cert.pem
And a request looks something like this:
var options = {
host: 'localhost',
port: 8000,
path: '/api/v1/test'
};
https.request(options, function(res) {
res.pipe(process.stdout);
}).end();
With this setup I get Error: DEPTH_ZERO_SELF_SIGNED_CERT, so I think I need to add a ca option for the request.
So my question is how should I generate the following:
The server key?
The server cert?
The ca for the request?
I have read a few things about generating self signed certificates with openssl, but can't seem to wrap my head around it and figure out which keys and certificates to use where in my node code.
Update
The API provides a CA certificate to use instead of the defaults. The following code works using their certificate and this is what I want to reproduce locally.
var ca = fs.readFileSync('./certificate.pem');
var options = {
host: 'example.com',
path: '/api/v1/test',
ca: ca
};
options.agent = new https.Agent(options);
https.request(options, function(res) {
res.pipe(process.stdout);
}).end();
Update (Nov 2018): Do you need self-signed certs?
Or would real certificates get the job done better? Have you considered any of these?
Let's Encrypt via Greenlock.js
Let's Encrypt via https://greenlock.domains
Localhost relay service such as https://telebit.cloud
(Note: Let's Encrypt can also issue certificates to private networks)
ScreenCast
https://coolaj86.com/articles/how-to-create-a-csr-for-https-tls-ssl-rsa-pems/
Full, Working example
creates certificates
runs node.js server
no warnings or errors in node.js client
no warnings or errors in cURL
https://github.com/coolaj86/nodejs-self-signed-certificate-example
Using localhost.greenlock.domains as an example (it points to 127.0.0.1):
server.js
'use strict';
var https = require('https')
, port = process.argv[2] || 8043
, fs = require('fs')
, path = require('path')
, server
, options
;
require('ssl-root-cas')
.inject()
.addFile(path.join(__dirname, 'server', 'my-private-root-ca.cert.pem'))
;
options = {
// this is ONLY the PRIVATE KEY
key: fs.readFileSync(path.join(__dirname, 'server', 'privkey.pem'))
// You DO NOT specify `ca`, that's only for peer authentication
//, ca: [ fs.readFileSync(path.join(__dirname, 'server', 'my-private-root-ca.cert.pem'))]
// This should contain both cert.pem AND chain.pem (in that order)
, cert: fs.readFileSync(path.join(__dirname, 'server', 'fullchain.pem'))
};
function app(req, res) {
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, encrypted world!');
}
server = https.createServer(options, app).listen(port, function () {
port = server.address().port;
console.log('Listening on https://127.0.0.1:' + port);
console.log('Listening on https://' + server.address().address + ':' + port);
console.log('Listening on https://localhost.greenlock.domains:' + port);
});
client.js
'use strict';
var https = require('https')
, fs = require('fs')
, path = require('path')
, ca = fs.readFileSync(path.join(__dirname, 'client', 'my-private-root-ca.cert.pem'))
, port = process.argv[2] || 8043
, hostname = process.argv[3] || 'localhost.greenlock.domains'
;
var options = {
host: hostname
, port: port
, path: '/'
, ca: ca
};
options.agent = new https.Agent(options);
https.request(options, function(res) {
res.pipe(process.stdout);
}).end();
And the script that makes the certificate files:
make-certs.sh
#!/bin/bash
FQDN=$1
# make directories to work from
mkdir -p server/ client/ all/
# Create your very own Root Certificate Authority
openssl genrsa \
-out all/my-private-root-ca.privkey.pem \
2048
# Self-sign your Root Certificate Authority
# Since this is private, the details can be as bogus as you like
openssl req \
-x509 \
-new \
-nodes \
-key all/my-private-root-ca.privkey.pem \
-days 1024 \
-out all/my-private-root-ca.cert.pem \
-subj "/C=US/ST=Utah/L=Provo/O=ACME Signing Authority Inc/CN=example.com"
# Create a Device Certificate for each domain,
# such as example.com, *.example.com, awesome.example.com
# NOTE: You MUST match CN to the domain name or ip address you want to use
openssl genrsa \
-out all/privkey.pem \
2048
# Create a request from your Device, which your Root CA will sign
openssl req -new \
-key all/privkey.pem \
-out all/csr.pem \
-subj "/C=US/ST=Utah/L=Provo/O=ACME Tech Inc/CN=${FQDN}"
# Sign the request from Device with your Root CA
openssl x509 \
-req -in all/csr.pem \
-CA all/my-private-root-ca.cert.pem \
-CAkey all/my-private-root-ca.privkey.pem \
-CAcreateserial \
-out all/cert.pem \
-days 500
# Put things in their proper place
rsync -a all/{privkey,cert}.pem server/
cat all/cert.pem > server/fullchain.pem # we have no intermediates in this case
rsync -a all/my-private-root-ca.cert.pem server/
rsync -a all/my-private-root-ca.cert.pem client/
# create DER format crt for iOS Mobile Safari, etc
openssl x509 -outform der -in all/my-private-root-ca.cert.pem -out client/my-private-root-ca.crt
For example:
bash make-certs.sh 'localhost.greenlock.domains'
Hopefully this puts the nail in the coffin on this one.
And some more explanation: https://github.com/coolaj86/node-ssl-root-cas/wiki/Painless-Self-Signed-Certificates-in-node.js
Install private cert on iOS Mobile Safari
You need to create a copy of the root ca certificate a DER format with a .crt extension:
# create DER format crt for iOS Mobile Safari, etc
openssl x509 -outform der -in all/my-private-root-ca.cert.pem -out client/my-private-root-ca.crt
Then you can simply serve that file with your webserver. When you click the link you should be asked if you want to install the certificate.
For an example of how this works you can try installing MIT's Certificate Authority: https://ca.mit.edu/mitca.crt
Related Examples
https://github.com/coolaj86/nodejs-ssl-example
https://github.com/coolaj86/nodejs-ssl-trusted-peer-example
https://github.com/coolaj86/node-ssl-root-cas
https://github.com/coolaj86/nodejs-https-sni-vhost-example
(Multiple vhosts with SSL on the same server)
https://telebit.cloud
(get REAL SSL certs you can use TODAY for testing on localhost)
Try adding this to your request options
var options = {
host: 'localhost',
port: 8000,
path: '/api/v1/test',
// These next three lines
rejectUnauthorized: false,
requestCert: true,
agent: false
};
Your key generation looks okay. You shouldn't need a ca because you aren't rejecting unsigned requests.
Add .toString() to the end of your readFileSync methods so that you are actually passing a string, not a file object.
This procedure allows you to create both a certificate authority & a certificate :
grab this ca.cnf file to use as a configuration shortcut :
wget https://raw.githubusercontent.com/anders94/https-authorized-clients/master/keys/ca.cnf
create a new certificate authority using this configuration :
openssl req -new -x509 -days 9999 -config ca.cnf -keyout ca-key.pem -out ca-cert.pem
now that we have our certificate authority in ca-key.pem and ca-cert.pem, let's generate a private key for the server :
openssl genrsa -out key.pem 4096
grab this server.cnf file to use as a configuration shortcut :
wget https://raw.githubusercontent.com/anders94/https-authorized-clients/master/keys/server.cnf
generate the certificate signing request using this configuration :
openssl req -new -config server.cnf -key key.pem -out csr.pem
sign the request :
openssl x509 -req -extfile server.cnf -days 999 -passin "pass:password" -in csr.pem -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem
I found this procedure here, along with more information on how to use these certificates.
Try adding
agent: false,
rejectUnauthorized: false
When you have the self-signed cert[s], you tell Node.js to use it with the Environment variable: NODE_EXTRA_CA_CERTS
Copy [cat] all the generated *.cert.pem files to a single file.
I put it the directory with all the keys & certs:
> (cd $keys; cat *.cert.pem > node_extra_ca_certs)
Tell node where to find them:
> export NODE_EXTRA_CA_CERTS=$keys/node_extra_ca_certs
Now, when you run node, it will accept your private certs as valid.

Resources