@tdxvolt/volt-client-grpc 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,213 @@
1
+ /* eslint-disable no-underscore-dangle */
2
+ import debug from "debug";
3
+ import fs from "fs";
4
+ import forge from "node-forge";
5
+ import jwt from "jsonwebtoken";
6
+ import crypto from "crypto";
7
+ import * as voltUtils from "./utils.js";
8
+ import {constants} from "./constants.js";
9
+
10
+ const {pki} = forge;
11
+ const log = debug("volt-client-grpc:volt-crypto");
12
+ const aesAlgorithm = "aes-256-cbc";
13
+ const rs256Algorithm = "RS256";
14
+
15
+ export class VoltCrypto {
16
+ constructor(config, configPath) {
17
+ this._config = config;
18
+ this._voltConfig = config.volt;
19
+ this._configPath = configPath;
20
+ this._persistCache = !!configPath;
21
+
22
+ if (!this._config.crypto) {
23
+ this._cryptoCache = {};
24
+ } else {
25
+ this._cryptoCache = this._config.crypto;
26
+ }
27
+
28
+ // Determine if we're dealing with an encrypted key.
29
+ if (this._cryptoCache.key && this._cryptoCache.key.startsWith(constants.privateEncryptedKeyPrefix)) {
30
+ if (!config.p) {
31
+ throw new Error("encrypted key but no passphrase given");
32
+ }
33
+
34
+ // Need to unencrypt the private key.
35
+ const decrypted = pki.decryptRsaPrivateKey(this._cryptoCache.key, config.p);
36
+ if (!decrypted) {
37
+ throw new Error("failed to decrypt key - check passphrase");
38
+ }
39
+ this._cryptoCache.key = pki.privateKeyToPem(decrypted);
40
+ }
41
+
42
+ if (this._voltConfig.ca_pem) {
43
+ if (!this._cryptoCache.ca) {
44
+ // Copy the volt signing CA to the crypto cache.
45
+ this._cryptoCache.ca = this._voltConfig.ca_pem;
46
+ }
47
+
48
+ // Pre-cache the target Volt public key by extracting it from the signing certificate.
49
+ const voltCert = forge.pki.certificateFromPem(this._voltConfig.ca_pem);
50
+
51
+ // Extract Volt public key (used for encrypting tunnel payloads).
52
+ this._voltPublicKey = forge.pki.publicKeyToPem(voltCert.publicKey);
53
+ this._voltFingerprint = voltUtils.createPublicKeyFingerprint(this._voltPublicKey);
54
+ }
55
+ }
56
+
57
+ get cache() {
58
+ return this._cryptoCache;
59
+ }
60
+
61
+ get voltFingerprint() {
62
+ return this._voltFingerprint;
63
+ }
64
+
65
+ getKey() {
66
+ const privateKey = pki.privateKeyFromPem(this._cryptoCache.key);
67
+ const publicKey = pki.rsa.setPublicKey(privateKey.n, privateKey.e);
68
+ return {privateKey, publicKey};
69
+ }
70
+
71
+ /**
72
+ * Retrieves and re-hydrates the pub/priv key data from the crypto cache, or creates one if not found.
73
+ */
74
+ createKey() {
75
+ if (!this._cryptoCache.key) {
76
+ log("creating key");
77
+ return new Promise((resolve, reject) => {
78
+ pki.rsa.generateKeyPair({bits: 2048, workers: -1}, (err, keypair) => {
79
+ if (err) {
80
+ log("failure creating key [%s]", err.message);
81
+ reject(err);
82
+ } else {
83
+ log("successfully created key");
84
+ const pem = pki.privateKeyToPem(keypair.privateKey);
85
+ this._cryptoCache.key = pem;
86
+ resolve(keypair);
87
+ }
88
+ });
89
+ });
90
+ } else {
91
+ // Already have key data in the cache in pem format => create fully-formed pki instances.
92
+ log("createKey - key already exists");
93
+ return Promise.resolve(this.getKey());
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Create cryptocache from scratch.
99
+ */
100
+ initialise() {
101
+ return this.createKey()
102
+ .then((/* keypair */) => {
103
+ return this.saveCache();
104
+ })
105
+ .then(() => {
106
+ return this._cryptoCache;
107
+ })
108
+ .catch((err) => {
109
+ log("failure initialising crypto [%s]", err.message);
110
+ return Promise.reject(err);
111
+ });
112
+ }
113
+
114
+ get isBound() {
115
+ return !!this._cryptoCache.cert;
116
+ }
117
+
118
+ /**
119
+ * Signs the identity resource id using the private key.
120
+ * @param {*} audience the token audience (usually the target volt)
121
+ * @param {*} tunnelling flag indicating if the token is required for a tunnelled connection
122
+ * @param {*} ttl time to live in seconds (default to 1 minute)
123
+ */
124
+ getIdentityToken(audience, tunnelling = false, ttl = 60) {
125
+ if (!this._cryptoCache.key) {
126
+ throw new Error("crypto cache invalid");
127
+ }
128
+
129
+ const keyPair = this.getKey();
130
+ const publicKeyPem = pki.publicKeyToPem(keyPair.publicKey);
131
+ const base58Key = voltUtils.createPublicKeyFingerprint(publicKeyPem);
132
+
133
+ log("base58 key is %s", base58Key);
134
+
135
+ // Allow TTL either side of the current time.
136
+ // @todo - fix with server time sync on volt connection.
137
+ const payload = {
138
+ aud: audience,
139
+ iat: Math.floor(Date.now() / 1000) - ttl,
140
+ exp: Math.floor(Date.now() / 1000) + ttl,
141
+ };
142
+
143
+ let sharedKey;
144
+ if (tunnelling) {
145
+ // Initialise the tunnel encryption key.
146
+ sharedKey = VoltCrypto.aesCreateKey();
147
+
148
+ // Encrypt the key details using the target Volt public key and include this in the JWT payload.
149
+ payload.sk = VoltCrypto.rsaEncrypt(this._voltPublicKey, sharedKey.key);
150
+ payload.iv = VoltCrypto.rsaEncrypt(this._voltPublicKey, sharedKey.iv);
151
+ }
152
+
153
+ // Sign synchronously.
154
+ const token = jwt.sign(payload, this._cryptoCache.key, {algorithm: rs256Algorithm, keyid: base58Key});
155
+
156
+ // Return the token along with any encryption key details.
157
+ return {
158
+ token,
159
+ sharedKey,
160
+ };
161
+ }
162
+
163
+ /**
164
+ * Creates the metadata required for a grpc call, including the Volt authentication token
165
+ * and optionally tunnel encryption parameters.
166
+ * @param {*} grpc
167
+ * @param {*} audience
168
+ * @param {*} tunnelling
169
+ * @param {*} ttl
170
+ * @returns
171
+ */
172
+ getIdentityMetadata(grpc, audience, tunnelling = false, ttl = 10) {
173
+ const identityToken = this.getIdentityToken(audience || this._voltConfig.id, tunnelling, ttl);
174
+ const metadata = new grpc.Metadata();
175
+ metadata.add(constants.authTokenName, identityToken.token);
176
+ return {...identityToken, metadata};
177
+ }
178
+
179
+ saveCache() {
180
+ if (this._persistCache) {
181
+ const clone = {...this._config, crypto: {...this._cryptoCache}};
182
+ if (this._config.p) {
183
+ // A passphrase option exists => encrypt the key before writing the cache file.
184
+ const privateKey = pki.privateKeyFromPem(this._cryptoCache.key);
185
+ clone.crypto.key = pki.encryptRsaPrivateKey(privateKey, this._config.p);
186
+ }
187
+ fs.writeFileSync(this._configPath, JSON.stringify(clone, null, 2));
188
+ }
189
+ }
190
+
191
+ static aesCreateKey() {
192
+ // Generate random key for the AES-256 algorithm (32 bytes = 256 bits).
193
+ const key = crypto.randomBytes(32);
194
+ const iv = crypto.randomBytes(16);
195
+ return {key, iv};
196
+ }
197
+
198
+ static aesEncrypt(buffer, key, iv) {
199
+ const cipher = crypto.createCipheriv(aesAlgorithm, key, iv);
200
+ const crypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
201
+ return crypted;
202
+ }
203
+
204
+ static aesDecrypt(buffer, key, iv) {
205
+ const cipher = crypto.createDecipheriv(aesAlgorithm, key, iv);
206
+ const decrypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
207
+ return decrypted;
208
+ }
209
+
210
+ static rsaEncrypt(key, buffer) {
211
+ return crypto.publicEncrypt(key, buffer).toString("base64");
212
+ }
213
+ }