ssl-root-cas.js/README.md

428 lines
12 KiB
Markdown
Raw Normal View History

2015-07-13 19:38:02 +00:00
IMPORTANT: Try this first
=========
2015-07-13 19:48:35 +00:00
2015-Aug-22: I just discovered that the most common reason you would have the kind of problems this module solves is actually due to failing to **properly bundle the Intermediate CAs** with the server certificate.
**Incorrect Example**
2015-07-13 19:38:02 +00:00
```js
2015-07-13 19:47:28 +00:00
// INCORRECT (but might still work)
2015-07-13 19:38:02 +00:00
var server https.createServer({
key: fs.readFileSync('privkey.pem', 'ascii')
2015-07-13 19:47:28 +00:00
, cert: fs.readFileSync('cert.pem', 'ascii') // a PEM containing ONLY the SERVER certificate
2015-07-13 19:38:02 +00:00
});
```
2015-07-13 19:48:35 +00:00
**Correct Example**
2015-07-13 19:38:02 +00:00
```js
2015-07-13 19:47:28 +00:00
// CORRECT (should always work)
2015-07-13 19:38:02 +00:00
var server https.createServer({
key: fs.readFileSync('privkey.pem', 'ascii')
2015-07-13 19:47:28 +00:00
, cert: fs.readFileSync('bundle.pem', 'ascii') // a PEM containing the SERVER and ALL INTERMEDIATES
2015-07-13 19:38:02 +00:00
});
```
2015-07-13 19:48:35 +00:00
**Example `bundle.pem`**
2015-07-13 19:38:02 +00:00
```
cat \
cert.pem \
intermediate-twice-removed.pem \
interemediate-once-removed.pem \
> bundle.pem
```
2015-07-13 19:49:14 +00:00
Note that you **should not** include the `root.pem` in the bundle and that the bundle should be constructed with the least authoritative certificate first - your server's certificate, followed by the furthest removed intermediate, and then the next closest to the root, etc.
Also note that in the case of cross-signed certificates there may be more than one intermediate at equal distances, in which case either in that tier may come first.
2015-07-13 19:38:02 +00:00
2014-03-07 23:55:21 +00:00
SSL Root CAs
2014-03-07 23:41:01 +00:00
=================
2015-07-13 19:47:28 +00:00
The module you need to solve node's SSL woes when including a custom certificate. Particularly, if you need to add a **non-standard Root CA**, then this is the right module for you.
2014-03-07 23:55:21 +00:00
Let's say you're trying to connect to a site with a cheap-o SSL cert -
such as RapidSSL certificate from [name.com](http://name.com) (the **best** place to get your domains, btw) -
you'll probably get an error like `UNABLE_TO_VERIFY_LEAF_SIGNATURE` and after you google around and figure that
out you'll be able to connect to that site just fine, but now when you try to connect to other sites you get
`CERT_UNTRUSTED` or possibly other errors.
2015-07-13 19:29:49 +00:00
**Common Errors**
* `CERT_UNTRUSTED` - the common root CAs are missing, this module fixes that.
* `UNABLE_TO_VERIFY_LEAF_SIGNATURE` could be either the same as the above, or the below
* `unable to verify the first certificate` - the intermediate certificate wasn't bundled along with the server certificate, you'll need to fix that
2014-03-07 23:55:21 +00:00
This module is the solution to your woes!
2014-03-08 00:32:33 +00:00
FYI, I'm merely the publisher, not the author of this module.
See here: https://groups.google.com/d/msg/nodejs/AjkHSYmiGYs/1LfNHbMhd48J
The script downloads the same root CAs that are included with
[Mozilla Firefox](http://www.mozilla.org/en-US/about/governance/policies/security-group/certs/included/),
[Google Chrome](http://www.chromium.org/Home/chromium-security/root-ca-policy),
[`libnss`](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS#CA_certificates_pre-loaded_into_NSS),
2014-04-29 06:29:55 +00:00
and [OpenSSL](https://www.openssl.org/support/faq.html#USER16)\*:
<https://mxr.mozilla.org/nss/source/lib/ckfw/builtins/certdata.txt?raw=1>
2014-04-29 06:29:55 +00:00
\* OpenSSL doesn't actually bundle these CAs, but they suggest using them
**Other Implementations**
* Golang <https://github.com/agl/extract-nss-root-certs>
* Perl <https://github.com/bagder/curl/blob/master/lib/mk-ca-bundle.pl>
2014-09-23 06:59:42 +00:00
**Usage Examples**
* https://github.com/coolaj86/nodejs-self-signed-certificate-example
* https://github.com/coolaj86/nodejs-ssl-trusted-peer-example
Install
=====
```javascript
npm i ssl-root-cas --save
```
2014-03-07 23:55:21 +00:00
Usage
=====
```javascript
'use strict';
2014-04-25 22:14:42 +00:00
2014-03-08 02:02:25 +00:00
// This will add the well-known CAs
// to `https.globalAgent.options.ca`
2014-04-25 22:14:42 +00:00
require('ssl-root-cas/latest')
.inject()
.addFile(__dirname + '/ssl/01-cheap-ssl-intermediary-a.pem')
.addFile(__dirname + '/ssl/02-cheap-ssl-intermediary-b.pem')
.addFile(__dirname + '/ssl/03-cheap-ssl-site.pem')
;
2014-03-07 23:55:21 +00:00
```
2014-03-08 00:22:40 +00:00
For the sake of version consistency this package ships with the CA certs that were
2014-04-25 22:14:42 +00:00
available at the time it was published,
but for the sake of security I recommend you use the latest ones.
2014-03-08 00:22:40 +00:00
If you want the latest certificates (downloaded as part of the postinstall process),
2014-04-25 22:14:42 +00:00
you can require those like so:
2014-03-08 00:22:40 +00:00
```
2014-03-08 02:02:25 +00:00
require('ssl-root-cas/latest').inject();
2014-03-08 00:22:40 +00:00
```
2014-04-25 22:14:42 +00:00
You can use the ones that shippped with package like so:
```
require('ssl-root-cas').inject();
```
API
---
### inject()
I thought it might be rude to modify `https.globalAgent.options.ca` on `require`,
so I afford you the opportunity to `inject()` the certs at your leisure.
`inject()` keeps track of whether or not it's been run, so no worries about calling it twice.
### addFile(filepath)
This is just a convenience method so that you don't
have to require `fs` and `path` if you don't need them.
```javascript
require('ssl-root-cas/latest')
.addFile(__dirname + '/ssl/03-cheap-ssl-site.pem')
;
```
is the same as
```javascript
var https = require('https')
, cas
;
cas = https.globalAgent.options.ca || [];
cas.push(fs.readFileSync(path.join(__dirname, 'ssl', '03-cheap-ssl-site.pem')));
```
### rootCas
If for some reason you just want to look at the array of Root CAs without actually injecting
them, or you just prefer to
`https.globalAgent.options.ca = require('ssl-root-cas').rootCas;`
yourself, well, you can.
2015-04-01 17:24:39 +00:00
Kinda Bad Ideas
=====
```javascript
'use strict';
var request = require('request');
var agentOptions;
var agent;
agentOptions = {
2015-04-01 17:31:46 +00:00
host: 'www.example.com'
, port: '443'
2015-04-01 17:24:39 +00:00
, path: '/'
, rejectUnauthorized: false
};
agent = new https.Agent(agentOptions);
request({
url: "https://www.example.com/api/endpoint"
, method: 'GET'
, agent: agent
}, function (err, resp, body) {
// ...
});
```
2015-04-01 17:31:46 +00:00
By using an `agent` with `rejectUnauthorized` you at limit the security vulnerability to the requests that deal with that one site instead of making your entire node process completely, utterly insecure.
### Other Options
If you were using a self-signed cert you would add this option:
```javascript
agentOptions.ca = [ selfSignedRootCaPemCrtBuffer ];
```
For trusted-peer connections you would also add these 2 options:
```javascript
agentOptions.key = clientPemKeyBuffer;
agentOptions.cert = clientPemCrtSignedBySelfSignedRootCaBuffer;
```
2015-04-01 17:24:39 +00:00
REALLY Bad Ideas
2014-03-07 23:55:21 +00:00
===
2014-03-07 23:56:06 +00:00
Don't use dissolutions such as these. :-)
2014-03-07 23:55:21 +00:00
This will turn off SSL validation checking. This is not a good idea. Please do not do it.
(really I'm only providing it as a reference for search engine seo so that people who are trying
to figure out how to avoid doing that will end up here)
```javascript
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
```
The same dissolution from the terminal would be
```bash
export NODE_TLS_REJECT_UNAUTHORIZED="0"
node my-service.js
```
2014-06-26 00:24:26 +00:00
2015-04-01 17:31:46 +00:00
It's unfortunate that `process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';` is even documented. It should only be used for debugging and should never make it into in sort of code that runs in the wild. Almost every library that runs atop `https` has a way of passing agent options through. Those that don't should be fixed.
2015-07-13 19:26:10 +00:00
# Appendix
2014-06-26 00:24:26 +00:00
Other information you might want to know while you're here.
## Generating an SSL Cert
Just in case you didn't know, here's how you do it:
```
2015-07-13 15:46:31 +00:00
openssl req -new -sha256 -newkey rsa:2048 -nodes -keyout server.key -out server.csr
2014-06-26 00:24:26 +00:00
```
**DO NOT FILL OUT** email address, challenge password, or optional company name
However, you *should* fill out country name, FULL state name, locality name, organization name.
*organizational unit* is optional.
```
cat server.csr
```
2015-07-13 15:46:31 +00:00
That created a signing request with a sha-256 hash.
2014-06-26 01:08:17 +00:00
2015-07-13 15:46:31 +00:00
When you submit that to the likes of RapidSSL you'll get back an X.509 that you should call `server.crt.pem` (at least for the purposes of this mini-tutorial).
2014-06-26 01:08:17 +00:00
2015-07-13 15:46:31 +00:00
You cannot use "bundled" certificates (multiple certs in a single file) with node.js.
2014-06-26 01:08:17 +00:00
2014-06-26 01:50:42 +00:00
### A single HTTPS server
2014-06-26 01:08:17 +00:00
Here's a complete working example:
```javascript
'use strict';
var https = require('https')
, fs = require('fs')
, connect = require('connect')
, app = connect()
, sslOptions
, server
, port = 4080
;
require('ssl-root-cas/latest')
.inject()
.addFile(__dirname + '/ssl/Geotrust Cross Root CA.txt')
.addFile(__dirname + '/ssl/Rapid SSL CA.txt')
;
sslOptions = {
key: fs.readFileSync('./ssl/server.key')
, cert: fs.readFileSync('./ssl/server.crt')
};
app.use('/', function (req, res) {
res.end('<html><body><h1>Hello World</h1></body></html>');
});
server = https.createServer(sslOptions, app).listen(port, function(){
2014-06-26 01:09:42 +00:00
console.log('Listening on https://' + server.address().address + ':' + server.address().port);
2014-06-26 01:08:17 +00:00
});
```
2014-06-26 01:50:42 +00:00
### Multiple HTTPS servers using SNI
I know this works - because I just bought two SSL certs from RapidSSL (through name.com),
a Digital Ocean VPS,
and played around for an hour until it did.
:-)
2014-06-26 01:56:04 +00:00
File hierarchy:
```
webapps/
└── vhosts
├── aj.the.dj
│   └── ssl
│   ├── server.crt
│   └── server.key
├── ballprovo.com
│   └── ssl
│   ├── server.crt
│   └── server.key
├── server.js
└── ssl
├── Geotrust Cross Root CA.txt
└── Rapid SSL CA.txt
```
2014-06-26 02:17:04 +00:00
#### `server.js`
2014-06-26 01:50:42 +00:00
```javascript
'use strict';
var https = require('https')
2014-06-26 02:17:04 +00:00
, http = require('http')
2014-06-26 01:50:42 +00:00
, fs = require('fs')
, crypto = require('crypto')
, connect = require('connect')
, vhost = require('vhost')
2014-06-26 02:17:04 +00:00
// connect / express app
2014-06-26 01:50:42 +00:00
, app = connect()
2014-06-26 02:17:04 +00:00
// SSL Server
2014-06-26 01:50:42 +00:00
, secureContexts = {}
2014-06-26 02:17:04 +00:00
, secureOpts
, secureServer
, securePort = 4443
// force SSL upgrade server
2014-06-26 01:50:42 +00:00
, server
, port = 4080
2014-06-26 02:17:04 +00:00
// the ssl domains I have
, domains = ['aj.the.dj', 'ballprovo.com']
2014-06-26 01:50:42 +00:00
;
require('ssl-root-cas/latest')
.inject()
.addFile(__dirname + '/ssl/Geotrust Cross Root CA.txt')
.addFile(__dirname + '/ssl/Rapid SSL CA.txt')
;
function getAppContext(domain) {
// Really you'd want to do this:
// return require(__dirname + '/' + domain + '/app.js');
// But for this demo we'll do this:
return connect().use('/', function (req, res) {
2014-06-26 02:04:52 +00:00
console.log('req.vhost', JSON.stringify(req.vhost));
2014-06-26 01:50:42 +00:00
res.end('<html><body><h1>Welcome to ' + domain + '!</h1></body></html>');
});
}
2014-06-26 02:17:04 +00:00
domains.forEach(function (domain) {
2014-06-26 02:04:52 +00:00
secureContexts[domain] = crypto.createCredentials({
2014-06-26 01:50:42 +00:00
key: fs.readFileSync(__dirname + '/' + domain + '/ssl/server.key')
, cert: fs.readFileSync(__dirname + '/' + domain + '/ssl/server.crt')
}).context;
app.use(vhost('*.' + domain, getAppContext(domain)));
app.use(vhost(domain, getAppContext(domain)));
});
// fallback / default domain
app.use('/', function (req, res) {
res.end('<html><body><h1>Hello World</h1></body></html>');
});
//provide a SNICallback when you create the options for the https server
2014-06-26 02:17:04 +00:00
secureOpts = {
2014-06-26 01:50:42 +00:00
//SNICallback is passed the domain name, see NodeJS docs on TLS
SNICallback: function (domain) {
2014-06-26 01:56:04 +00:00
console.log('SNI:', domain);
2014-06-26 01:50:42 +00:00
return secureContexts[domain];
}
// fallback / default domain
, key: fs.readFileSync(__dirname + '/aj.the.dj/ssl/server.key')
, cert: fs.readFileSync(__dirname + '/aj.the.dj/ssl/server.crt')
};
2014-06-26 02:17:04 +00:00
secureServer = https.createServer(secureOpts, app).listen(securePort, function(){
console.log("Listening on https://localhost:" + secureServer.address().port);
});
server = http.createServer(function (req, res) {
res.setHeader(
'Location'
, 'https://' + req.headers.host.replace(/:\d+/, ':' + securePort)
);
res.statusCode = 302;
res.end();
}).listen(port, function(){
console.log("Listening on http://localhost:" + server.address().port);
2014-06-26 01:50:42 +00:00
});
```
2015-01-28 04:31:49 +00:00
Other SSL Resources
=========
Zero-Config clone 'n' run (tm) Repos:
* [io.js / node.js HTTPS SSL Example](https://github.com/coolaj86/nodejs-ssl-example)
* [io.js / node.js HTTPS SSL Self-Signed Certificate Example](https://github.com/coolaj86/nodejs-self-signed-certificate-example)
* [io.js / node.js HTTPS SSL Trusted Peer Client Certificate Example](https://github.com/coolaj86/nodejs-ssl-trusted-peer-example)
* [SSL Root CAs](https://github.com/coolaj86/node-ssl-root-cas)
Articles
* [http://greengeckodesign.com/blog/2013/06/15/creating-an-ssl-certificate-for-node-dot-js/](Creating an SSL Certificate for node.js)
* [http://www.hacksparrow.com/express-js-https-server-client-example.html/comment-page-1](HTTPS Trusted Peer Example)
* [How to Create a CSR for HTTPS SSL (demo with name.com, node.js)](http://blog.coolaj86.com/articles/how-to-create-a-csr-for-https-tls-ssl-rsa-pems/)
* [coolaj86/Painless-Self-Signed-Certificates-in-node](https://github.com/coolaj86/node-ssl-root-cas/wiki/Painless-Self-Signed-Certificates-in-node.js)