Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
issacg committed Dec 26, 2015
0 parents commit 67a1bfd
Show file tree
Hide file tree
Showing 6 changed files with 347 additions and 0 deletions.
17 changes: 17 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
.DS_Store
release
temp
history
remote-do-not-distribute
.DS_Store
/.idea
node_modules
/newrelic_agent.log
/scripts/output
/*.komodoproject
*.pem
*.key
.otto
.ottoid
.vagrant
npm-debug*
13 changes: 13 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright 2015 Issac Goldstand <[email protected]>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
87 changes: 87 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# vault-pki-client

## Synopsis

vault-pki-client is a tool, similar to [consul-template](https://github.com/hashicorp/consul-template)
but crafted specifically for [Vault](https://vaultproject.io) and the
[PKI (certificate) secret backend](https://vaultproject.io/docs/secrets/pki/index.html)

The tool will connect to a Vault server and periodically request a x509 keypair,
save the generated keypair to files, and optionally execute a command each time
the files are updated. The tool runs as a daemon (unless the `--once` argument
is given), and will continue to run in the background and update the keypair
shortly before it expires. The idea is to enable system administrators to
request shorter TTLs, aligning with Vault's principle of short-lived one-time
secrets.

## Installation

## Configuration

### Methods

vault-pki-client makes use of the excellent [rc](https://github.com/dominictarr/rc) module,
so variables can be passed as command line parameters, environment variables or
provided via a configuration file named .vault-pki-clientrc

For more detailed information about how to set parameters, see the [rc](https://github.com/dominictarr/rc#standards) page.

### Options

| Parameter | Default Value | Description |
|-----------|---------------|-------------|
| `vault.server.address` | `http://127.0.0.1:8200` | The protocol, hostname and port of the Vault server. |
| `vault.server.ca-cert` | None | Path to a PEM-encoded CA cert file to use to verify the Vault server SSL certificate |
| `vault.server.ca-path` | None | Path to a directory of PEM-encoded CA cert files to verify the Vault server SSL certificate. |
| `vault.server.tls-skip-verify` | `false` | If set, do not verify Vault's presented certificate before communicating with it. Setting this variable is not recommended except during testing. |
| `vault.server.api-version` | `v1` | The API version to use when communicating with the Vault server. For now, only `v1` is supported. |
| `vault.pki.path` | `pki` | The path to the requested pki mount point in the Vault server. |
| `vault.pki.role` | None (**required**) | The name of the role used to request the client certificate pair. See [the Vault documentation](https://vaultproject.io/docs/secrets/pki/index.html) for details of how to configure this in the Vault server. |
| `vault.token` | None | The token used to authenticate to the Vault server. |
| `vault.token-renewable` | `false` | If `true`, vault-pki-client will attempt to renew the token based on the TTL of the token. The token will be renewed immediately on startup to determine the TTL. |
| `certCN` | The hostname of the machine running vault-pki-client | The Common Name (CN) to be used in the requested x509 keypair. For example, `foo.example.com`. The value specified here must be a valid CN based on the role defined in `vault.pki.role` or the request will be rejected by the Vault server. |
| `certTTL` | None | The TTL of the keypair being requested by the Vault server. In a production environment, this should normally be kept to a reasonably low value. See [the Vault documentation](https://vaultproject.io/docs/secrets/pki/index.html). If not specified, the Vault server will use the configured default lease TTL. Note that the value specified may not exceed the maximum TTL defined on the Vault server mount. |
| `certFile` | `client.pem` | The file to store the x509 certificate returned by the Vault server. |
| `keyFile` | `client.key` | The file to store the private key for the certificate returned by the Vault server. |
| `caFile` | None | If specified, the file to store the certificate of the CA used to sign `certFile`. If empty, the CA certificate will not be written to disk. |
| `onUpdate` | None | A command to run after updating the keypair. Can be used to restart services. For example `service httpd restart`. The command should exit quickly - if you want to start a service, don't start the service directly, but rather write a short-running script/batch file to start the service. |
| `renewalCoefficient` | `0.9` | A coefficient applied to TTLs returned by the Vault server to determine when to renew secrets returned by the vault server. A value of `1.0` means 100% of the lease time, and will almost certainly mean that secrets will expire before they can be renewed. The default value of `0.9` means that secrets will be renewed at 90% of the TTL value. This affects token renewel (if `vault.token-renewable` is set to `true`) and `certTTL` |
| `once` | `false` | If `true`, specifies that vault-pki-client will request a new keypair (including writing to disk and execuring `onUpdate`) and exit immediately without staying alive to renew the keypair when `certTTL` expires` |

###Vault environment variables

vault-pki-client will utilize the [standard Vault environment variables](https://vaultproject.io/docs/commands/environment.html) if they are defined.
Options passed directly to vault-pki-client (including by environment variables) will take precedence over these environment variables, but these environment
variables will take precedence over the defaults spefified in the Options section above.

For example if the environment variable `VAULT_TOKEN` is set to `foo`, and no
value for `vault.token` is specified, vault-pki-client will use `foo` as the
Vault token. However, if the environment variable `VAULT_TOKEN` is set to
`foo`, and the environment variable `vault-pki-client_vault__token` is set to
`bar`, vault-pki-client will use `bar` as the Vault token.

## Examples

For more information about configuration files, environment variables and arguments,
see the configuration section.

``` vault-pki-client --vault.pki.role=example.com --certFile=client.pem --keyFile=client.key --caFile=ca.pem --certCN=foo.example.com --certTTL=24h ```

This example will attempt to fetch an x509 keypair with the CN `foo.example.com`
which expires 24 hours in the future.

## License

Copyright 2015 Issac Goldstand <[email protected]>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
28 changes: 28 additions & 0 deletions config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
var rc = require("rc");

var defaults = {
vault: {
server: {
"address": process.env.VAULT_ADDR || "http://localhost:8200",
"ca-cert": process.env.VAULT_CACERT || undefined,
"ca-path": process.env.VAULT_CAPATH || undefined,
"tls-skip-verify": process.env.VAULT_SKIP_VERIFY || false,
"api-version": "v1"
}, pki: {
"path": "pki",
"role": ""
},
"token": process.env.VAULT_TOKEN || "",
"token-renewable": false
},
certCN: require("os").hostname(),
certTTL: undefined,
certFile: "client.pem",
keyFile: "client.key",
caFile: undefined,
onUpdate: undefined,
renewalCoefficient: 0.9,
once: false
};

module.exports = rc("vault-pki-client", defaults);
162 changes: 162 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
#! /usr/bin/env node

var debug = require('debug')('vault-pki-client:main'),
config = require('./config'),
Promise = require('bluebird'),
util = require('util'),
request = require('request-promise'),
pkginfo = require('./package.json'),
child = Promise.promisifyAll(require('child_process')),
fs = Promise.promisifyAll(require('fs'));

var token = config.vault.token;
function main() {
if (config.version) {
console.log(pkginfo.name + " v" + pkginfo.version);
process.exit(0);
}
Promise.resolve()
.then(config.vault["token-renewable"] ? renewVaultToken : Promise.resolve)
.then(fetchCert)
.catch(function(e) {
if (e && e.name && e.name == "StatusCodeError") {
console.error("Vault error: " + e.statusCode + " " + e.error.errors.join(" "));
} else {
console.error(e);
}
});
}

var fetchCert = (function() {
var debug = require('debug')('vault-pki-client:certRenewal');
var exec, args = [];
if (config.onUpdate) {
args = config.onUpdate.split(/\s+/);
exec = args.shift();
}
return function() {
var path = [config.vault.pki.path, "issue", config.vault.pki.role].join("/");
debug("Attempting to fetch a keypair from " + path);
var opts = {
common_name: config.certCN
}
if (config.certTTL) opts.ttl = config.certTTL;
return vaultRequest(path, 'POST', opts).then(function(data) {
return Promise.all([
saveKey(data.data.private_key),
saveCert(data.data.certificate),
saveCA(data.data.issuing_ca)
]).then(function() {
if (config.once) return Promise.resolve();
var next = data.lease_duration * config.renewalCoefficient * 1000;
debug("Next renewal in " + next + "ms");
setTimeout(fetchCert, next);
}).then(function() {
if (config.onUpdate) {
debug("Executing " + exec + " " + args.join(" "));
return child.spawnAsync(exec, args, {});
} else {
return Promise.resolve();
}
}).catch(function(e) {
debug("Failed to fetch and update keypair");
console.error(e);
});
});
};
function saveKey(data) {
debug("Writing private key to " + config.keyFile);
return fs.writeFileAsync(config.keyFile, data);
}

function saveCert(data) {
debug("Writing certificate to " + config.certFile);
return fs.writeFileAsync(config.certFile, data);
}

function saveCA(data) {
if (!config.caFile) return Promise.resolve();
debug("Writing CA certificate to " + config.caFile);
return fs.writeFileAsync(config.caFile, data);
}
})();

// Attempt to periodically renew the vault token
var renewVaultToken = (function() {
var debug = require('debug')('vault-pki-client:tokenRenewal');
return function() {
debug("Attempting to renew vault token");
return vaultRequest('auth/token/renew-self','POST').then(function(data) {
token = data.auth.client_token;
debug("Token renewal succeeded");
if (data.auth.renewable) {
var next = data.auth.lease_duration * config.renewalCoefficient * 1000;
debug("Next renewal in " + next + "ms");
setTimeout(renewVaultToken, next).unref();
}
return Promise.resolve();
}).catch(function(err) {
debug("Token renewal failed");
console.error(err);
return Promise.reject();
});
};
})();

// Build request options
function buildReqOpts() {
var reqOpts = {
ca:[],
rejectUnauthorized: !config.vault.server["tls-skip-verify"]
};

if (config.vault.server["ca-path"]) {
// This won't work for bundle files with multiple CAs in a single file...
var match = "-----BEGIN CERTIFICATE-----",
len = match.length;
fs.readdirSync(config.vault.server["ca-path"]).forEach(function(file) {
file = [config.vault.server["ca-path"], file].join("/");
if (!fs.statSync(file).isFile()) return;
var buf = fs.readFileSync(file);
if (buf.slice(0, len) == match)
reqOpts.ca.push(buf);
})
}

if (config.vault.server["ca-cert"])
reqOpts.ca.push(fs.readFileSync(config.vault.server["ca-cert"]));

// Fallback to default node-bundled CAs
if (reqOpts.ca.length == 0)
delete reqOpts.ca;

if (config.vault.server["client-cert"])
reqOpts.ca.push(fs.readFileSync(config.vault.server["client-cert"]));

if (config.vault.server["client-key"])
reqOpts.ca.push(fs.readFileSync(config.vault.server["ca-cert"]));

return reqOpts;
}

var vaultRequest = (function () {
var debug = require('debug')('vault-pki-client:http');
var defOpts = buildReqOpts();
return function(url, method, body) {
method = method || "GET";
body = body || undefined;
var opts = util._extend(defOpts, {
url: [config.vault.server['address'], config.vault.server['api-version'], url].join("/"),
headers: {
"X-Vault-Token": token
},
method: method,
body: body,
json: true
});
debug(method + "ing data to " + opts.url);
return request(opts).then(function(data) {debug("Got data: " + data); return data});
};
})();

main();
40 changes: 40 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "vault-pki-client",
"version": "1.0.0",
"description": "Tool to manage a keypair provided by HashiCorp Vault",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"nexe": "nexe"
},
"bin": "index.js",
"author": "Issac Goldstand <[email protected]>",
"license": "Apache-2.0",
"dependencies": {
"bluebird": "^3.1.1",
"debug": "^2.2.0",
"rc": "^1.1.5",
"request-promise": "^1.0.2"
},
"devDependencies": {
"nexe": "^0.4.2"
},
"nexe": {
"input": "index.js",
"output": "vault-pki-client^$",
"temp": "./temp/src",
"runtime": {
"framework": "nodejs",
"version": "4.2.4",
"ignoreFlags": true
}
},
"repository": {
"type": "git",
"url": "git+https://github.com/issacg/vault-pki-client.git"
},
"bugs": {
"url": "https://github.com/issacg/vault-pki-client/issues"
},
"homepage": "https://github.com/issacg/vault-pki-client#readme"
}

0 comments on commit 67a1bfd

Please sign in to comment.