@libp2p/keychain 3.0.8 → 4.0.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,561 @@
1
+ /* eslint max-nested-callbacks: ["error", 5] */
2
+
3
+ import { pbkdf2, randomBytes } from '@libp2p/crypto'
4
+ import { generateKeyPair, importKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'
5
+ import { CodeError } from '@libp2p/interface'
6
+ import { peerIdFromKeys } from '@libp2p/peer-id'
7
+ import { Key } from 'interface-datastore/key'
8
+ import mergeOptions from 'merge-options'
9
+ import sanitize from 'sanitize-filename'
10
+ import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
11
+ import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
12
+ import { codes } from './errors.js'
13
+ import type { KeychainComponents, KeychainInit, Keychain, KeyInfo } from './index.js'
14
+ import type { Logger, KeyType, PeerId } from '@libp2p/interface'
15
+
16
+ const keyPrefix = '/pkcs8/'
17
+ const infoPrefix = '/info/'
18
+ const privates = new WeakMap<object, { dek: string }>()
19
+
20
+ // NIST SP 800-132
21
+ const NIST = {
22
+ minKeyLength: 112 / 8,
23
+ minSaltLength: 128 / 8,
24
+ minIterationCount: 1000
25
+ }
26
+
27
+ const defaultOptions = {
28
+ // See https://cryptosense.com/parametesr-choice-for-pbkdf2/
29
+ dek: {
30
+ keyLength: 512 / 8,
31
+ iterationCount: 10000,
32
+ salt: 'you should override this value with a crypto secure random number',
33
+ hash: 'sha2-512'
34
+ }
35
+ }
36
+
37
+ function validateKeyName (name: string): boolean {
38
+ if (name == null) {
39
+ return false
40
+ }
41
+ if (typeof name !== 'string') {
42
+ return false
43
+ }
44
+ return name === sanitize(name.trim()) && name.length > 0
45
+ }
46
+
47
+ /**
48
+ * Throws an error after a delay
49
+ *
50
+ * This assumes than an error indicates that the keychain is under attack. Delay returning an
51
+ * error to make brute force attacks harder.
52
+ */
53
+ async function randomDelay (): Promise<void> {
54
+ const min = 200
55
+ const max = 1000
56
+ const delay = Math.random() * (max - min) + min
57
+
58
+ await new Promise(resolve => setTimeout(resolve, delay))
59
+ }
60
+
61
+ /**
62
+ * Converts a key name into a datastore name
63
+ */
64
+ function DsName (name: string): Key {
65
+ return new Key(keyPrefix + name)
66
+ }
67
+
68
+ /**
69
+ * Converts a key name into a datastore info name
70
+ */
71
+ function DsInfoName (name: string): Key {
72
+ return new Key(infoPrefix + name)
73
+ }
74
+
75
+ /**
76
+ * Manages the lifecycle of a key. Keys are encrypted at rest using PKCS #8.
77
+ *
78
+ * A key in the store has two entries
79
+ * - '/info/*key-name*', contains the KeyInfo for the key
80
+ * - '/pkcs8/*key-name*', contains the PKCS #8 for the key
81
+ *
82
+ */
83
+ export class DefaultKeychain implements Keychain {
84
+ private readonly components: KeychainComponents
85
+ private readonly init: KeychainInit
86
+ private readonly log: Logger
87
+
88
+ /**
89
+ * Creates a new instance of a key chain
90
+ */
91
+ constructor (components: KeychainComponents, init: KeychainInit) {
92
+ this.components = components
93
+ this.log = components.logger.forComponent('libp2p:keychain')
94
+ this.init = mergeOptions(defaultOptions, init)
95
+
96
+ // Enforce NIST SP 800-132
97
+ if (this.init.pass != null && this.init.pass?.length < 20) {
98
+ throw new Error('pass must be least 20 characters')
99
+ }
100
+ if (this.init.dek?.keyLength != null && this.init.dek.keyLength < NIST.minKeyLength) {
101
+ throw new Error(`dek.keyLength must be least ${NIST.minKeyLength} bytes`)
102
+ }
103
+ if (this.init.dek?.salt?.length != null && this.init.dek.salt.length < NIST.minSaltLength) {
104
+ throw new Error(`dek.saltLength must be least ${NIST.minSaltLength} bytes`)
105
+ }
106
+ if (this.init.dek?.iterationCount != null && this.init.dek.iterationCount < NIST.minIterationCount) {
107
+ throw new Error(`dek.iterationCount must be least ${NIST.minIterationCount}`)
108
+ }
109
+
110
+ const dek = this.init.pass != null && this.init.dek?.salt != null
111
+ ? pbkdf2(
112
+ this.init.pass,
113
+ this.init.dek?.salt,
114
+ this.init.dek?.iterationCount,
115
+ this.init.dek?.keyLength,
116
+ this.init.dek?.hash)
117
+ : ''
118
+
119
+ privates.set(this, { dek })
120
+ }
121
+
122
+ /**
123
+ * Generates the options for a keychain. A random salt is produced.
124
+ *
125
+ * @returns {object}
126
+ */
127
+ static generateOptions (): KeychainInit {
128
+ const options = Object.assign({}, defaultOptions)
129
+ const saltLength = Math.ceil(NIST.minSaltLength / 3) * 3 // no base64 padding
130
+ options.dek.salt = uint8ArrayToString(randomBytes(saltLength), 'base64')
131
+ return options
132
+ }
133
+
134
+ /**
135
+ * Gets an object that can encrypt/decrypt protected data.
136
+ * The default options for a keychain.
137
+ *
138
+ * @returns {object}
139
+ */
140
+ static get options (): typeof defaultOptions {
141
+ return defaultOptions
142
+ }
143
+
144
+ /**
145
+ * Create a new key.
146
+ *
147
+ * @param {string} name - The local key name; cannot already exist.
148
+ * @param {string} type - One of the key types; 'rsa'.
149
+ * @param {number} [size = 2048] - The key size in bits. Used for rsa keys only
150
+ */
151
+ async createKey (name: string, type: KeyType, size = 2048): Promise<KeyInfo> {
152
+ if (!validateKeyName(name) || name === 'self') {
153
+ await randomDelay()
154
+ throw new CodeError('Invalid key name', codes.ERR_INVALID_KEY_NAME)
155
+ }
156
+
157
+ if (typeof type !== 'string') {
158
+ await randomDelay()
159
+ throw new CodeError('Invalid key type', codes.ERR_INVALID_KEY_TYPE)
160
+ }
161
+
162
+ const dsname = DsName(name)
163
+ const exists = await this.components.datastore.has(dsname)
164
+ if (exists) {
165
+ await randomDelay()
166
+ throw new CodeError('Key name already exists', codes.ERR_KEY_ALREADY_EXISTS)
167
+ }
168
+
169
+ switch (type.toLowerCase()) {
170
+ case 'rsa':
171
+ if (!Number.isSafeInteger(size) || size < 2048) {
172
+ await randomDelay()
173
+ throw new CodeError('Invalid RSA key size', codes.ERR_INVALID_KEY_SIZE)
174
+ }
175
+ break
176
+ default:
177
+ break
178
+ }
179
+
180
+ let keyInfo
181
+ try {
182
+ const keypair = await generateKeyPair(type, size)
183
+ const kid = await keypair.id()
184
+ const cached = privates.get(this)
185
+
186
+ if (cached == null) {
187
+ throw new CodeError('dek missing', codes.ERR_INVALID_PARAMETERS)
188
+ }
189
+
190
+ const dek = cached.dek
191
+ const pem = await keypair.export(dek)
192
+ keyInfo = {
193
+ name,
194
+ id: kid
195
+ }
196
+ const batch = this.components.datastore.batch()
197
+ batch.put(dsname, uint8ArrayFromString(pem))
198
+ batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))
199
+
200
+ await batch.commit()
201
+ } catch (err: any) {
202
+ await randomDelay()
203
+ throw err
204
+ }
205
+
206
+ return keyInfo
207
+ }
208
+
209
+ /**
210
+ * List all the keys.
211
+ *
212
+ * @returns {Promise<KeyInfo[]>}
213
+ */
214
+ async listKeys (): Promise<KeyInfo[]> {
215
+ const query = {
216
+ prefix: infoPrefix
217
+ }
218
+
219
+ const info = []
220
+ for await (const value of this.components.datastore.query(query)) {
221
+ info.push(JSON.parse(uint8ArrayToString(value.value)))
222
+ }
223
+
224
+ return info
225
+ }
226
+
227
+ /**
228
+ * Find a key by it's id
229
+ */
230
+ async findKeyById (id: string): Promise<KeyInfo> {
231
+ try {
232
+ const keys = await this.listKeys()
233
+ const key = keys.find((k) => k.id === id)
234
+
235
+ if (key == null) {
236
+ throw new CodeError(`Key with id '${id}' does not exist.`, codes.ERR_KEY_NOT_FOUND)
237
+ }
238
+
239
+ return key
240
+ } catch (err: any) {
241
+ await randomDelay()
242
+ throw err
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Find a key by it's name.
248
+ *
249
+ * @param {string} name - The local key name.
250
+ * @returns {Promise<KeyInfo>}
251
+ */
252
+ async findKeyByName (name: string): Promise<KeyInfo> {
253
+ if (!validateKeyName(name)) {
254
+ await randomDelay()
255
+ throw new CodeError(`Invalid key name '${name}'`, codes.ERR_INVALID_KEY_NAME)
256
+ }
257
+
258
+ const dsname = DsInfoName(name)
259
+ try {
260
+ const res = await this.components.datastore.get(dsname)
261
+ return JSON.parse(uint8ArrayToString(res))
262
+ } catch (err: any) {
263
+ await randomDelay()
264
+ this.log.error(err)
265
+ throw new CodeError(`Key '${name}' does not exist.`, codes.ERR_KEY_NOT_FOUND)
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Remove an existing key.
271
+ *
272
+ * @param {string} name - The local key name; must already exist.
273
+ * @returns {Promise<KeyInfo>}
274
+ */
275
+ async removeKey (name: string): Promise<KeyInfo> {
276
+ if (!validateKeyName(name) || name === 'self') {
277
+ await randomDelay()
278
+ throw new CodeError(`Invalid key name '${name}'`, codes.ERR_INVALID_KEY_NAME)
279
+ }
280
+ const dsname = DsName(name)
281
+ const keyInfo = await this.findKeyByName(name)
282
+ const batch = this.components.datastore.batch()
283
+ batch.delete(dsname)
284
+ batch.delete(DsInfoName(name))
285
+ await batch.commit()
286
+ return keyInfo
287
+ }
288
+
289
+ /**
290
+ * Rename a key
291
+ *
292
+ * @param {string} oldName - The old local key name; must already exist.
293
+ * @param {string} newName - The new local key name; must not already exist.
294
+ * @returns {Promise<KeyInfo>}
295
+ */
296
+ async renameKey (oldName: string, newName: string): Promise<KeyInfo> {
297
+ if (!validateKeyName(oldName) || oldName === 'self') {
298
+ await randomDelay()
299
+ throw new CodeError(`Invalid old key name '${oldName}'`, codes.ERR_OLD_KEY_NAME_INVALID)
300
+ }
301
+ if (!validateKeyName(newName) || newName === 'self') {
302
+ await randomDelay()
303
+ throw new CodeError(`Invalid new key name '${newName}'`, codes.ERR_NEW_KEY_NAME_INVALID)
304
+ }
305
+ const oldDsname = DsName(oldName)
306
+ const newDsname = DsName(newName)
307
+ const oldInfoName = DsInfoName(oldName)
308
+ const newInfoName = DsInfoName(newName)
309
+
310
+ const exists = await this.components.datastore.has(newDsname)
311
+ if (exists) {
312
+ await randomDelay()
313
+ throw new CodeError(`Key '${newName}' already exists`, codes.ERR_KEY_ALREADY_EXISTS)
314
+ }
315
+
316
+ try {
317
+ const pem = await this.components.datastore.get(oldDsname)
318
+ const res = await this.components.datastore.get(oldInfoName)
319
+
320
+ const keyInfo = JSON.parse(uint8ArrayToString(res))
321
+ keyInfo.name = newName
322
+ const batch = this.components.datastore.batch()
323
+ batch.put(newDsname, pem)
324
+ batch.put(newInfoName, uint8ArrayFromString(JSON.stringify(keyInfo)))
325
+ batch.delete(oldDsname)
326
+ batch.delete(oldInfoName)
327
+ await batch.commit()
328
+ return keyInfo
329
+ } catch (err: any) {
330
+ await randomDelay()
331
+ throw err
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Export an existing key as a PEM encrypted PKCS #8 string
337
+ */
338
+ async exportKey (name: string, password: string): Promise<string> {
339
+ if (!validateKeyName(name)) {
340
+ await randomDelay()
341
+ throw new CodeError(`Invalid key name '${name}'`, codes.ERR_INVALID_KEY_NAME)
342
+ }
343
+ if (password == null) {
344
+ await randomDelay()
345
+ throw new CodeError('Password is required', codes.ERR_PASSWORD_REQUIRED)
346
+ }
347
+
348
+ const dsname = DsName(name)
349
+ try {
350
+ const res = await this.components.datastore.get(dsname)
351
+ const pem = uint8ArrayToString(res)
352
+ const cached = privates.get(this)
353
+
354
+ if (cached == null) {
355
+ throw new CodeError('dek missing', codes.ERR_INVALID_PARAMETERS)
356
+ }
357
+
358
+ const dek = cached.dek
359
+ const privateKey = await importKey(pem, dek)
360
+ const keyString = await privateKey.export(password)
361
+
362
+ return keyString
363
+ } catch (err: any) {
364
+ await randomDelay()
365
+ throw err
366
+ }
367
+ }
368
+
369
+ /**
370
+ * Export an existing key as a PeerId
371
+ */
372
+ async exportPeerId (name: string): Promise<PeerId> {
373
+ const password = 'temporary-password'
374
+ const pem = await this.exportKey(name, password)
375
+ const privateKey = await importKey(pem, password)
376
+
377
+ return peerIdFromKeys(privateKey.public.bytes, privateKey.bytes)
378
+ }
379
+
380
+ /**
381
+ * Import a new key from a PEM encoded PKCS #8 string
382
+ *
383
+ * @param {string} name - The local key name; must not already exist.
384
+ * @param {string} pem - The PEM encoded PKCS #8 string
385
+ * @param {string} password - The password.
386
+ * @returns {Promise<KeyInfo>}
387
+ */
388
+ async importKey (name: string, pem: string, password: string): Promise<KeyInfo> {
389
+ if (!validateKeyName(name) || name === 'self') {
390
+ await randomDelay()
391
+ throw new CodeError(`Invalid key name '${name}'`, codes.ERR_INVALID_KEY_NAME)
392
+ }
393
+ if (pem == null) {
394
+ await randomDelay()
395
+ throw new CodeError('PEM encoded key is required', codes.ERR_PEM_REQUIRED)
396
+ }
397
+ const dsname = DsName(name)
398
+ const exists = await this.components.datastore.has(dsname)
399
+ if (exists) {
400
+ await randomDelay()
401
+ throw new CodeError(`Key '${name}' already exists`, codes.ERR_KEY_ALREADY_EXISTS)
402
+ }
403
+
404
+ let privateKey
405
+ try {
406
+ privateKey = await importKey(pem, password)
407
+ } catch (err: any) {
408
+ await randomDelay()
409
+ throw new CodeError('Cannot read the key, most likely the password is wrong', codes.ERR_CANNOT_READ_KEY)
410
+ }
411
+
412
+ let kid
413
+ try {
414
+ kid = await privateKey.id()
415
+ const cached = privates.get(this)
416
+
417
+ if (cached == null) {
418
+ throw new CodeError('dek missing', codes.ERR_INVALID_PARAMETERS)
419
+ }
420
+
421
+ const dek = cached.dek
422
+ pem = await privateKey.export(dek)
423
+ } catch (err: any) {
424
+ await randomDelay()
425
+ throw err
426
+ }
427
+
428
+ const keyInfo = {
429
+ name,
430
+ id: kid
431
+ }
432
+ const batch = this.components.datastore.batch()
433
+ batch.put(dsname, uint8ArrayFromString(pem))
434
+ batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))
435
+ await batch.commit()
436
+
437
+ return keyInfo
438
+ }
439
+
440
+ /**
441
+ * Import a peer key
442
+ */
443
+ async importPeer (name: string, peer: PeerId): Promise<KeyInfo> {
444
+ try {
445
+ if (!validateKeyName(name)) {
446
+ throw new CodeError(`Invalid key name '${name}'`, codes.ERR_INVALID_KEY_NAME)
447
+ }
448
+ if (peer == null) {
449
+ throw new CodeError('PeerId is required', codes.ERR_MISSING_PRIVATE_KEY)
450
+ }
451
+ if (peer.privateKey == null) {
452
+ throw new CodeError('PeerId.privKey is required', codes.ERR_MISSING_PRIVATE_KEY)
453
+ }
454
+
455
+ const privateKey = await unmarshalPrivateKey(peer.privateKey)
456
+
457
+ const dsname = DsName(name)
458
+ const exists = await this.components.datastore.has(dsname)
459
+ if (exists) {
460
+ await randomDelay()
461
+ throw new CodeError(`Key '${name}' already exists`, codes.ERR_KEY_ALREADY_EXISTS)
462
+ }
463
+
464
+ const cached = privates.get(this)
465
+
466
+ if (cached == null) {
467
+ throw new CodeError('dek missing', codes.ERR_INVALID_PARAMETERS)
468
+ }
469
+
470
+ const dek = cached.dek
471
+ const pem = await privateKey.export(dek)
472
+ const keyInfo: KeyInfo = {
473
+ name,
474
+ id: peer.toString()
475
+ }
476
+ const batch = this.components.datastore.batch()
477
+ batch.put(dsname, uint8ArrayFromString(pem))
478
+ batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))
479
+ await batch.commit()
480
+ return keyInfo
481
+ } catch (err: any) {
482
+ await randomDelay()
483
+ throw err
484
+ }
485
+ }
486
+
487
+ /**
488
+ * Gets the private key as PEM encoded PKCS #8 string
489
+ */
490
+ async getPrivateKey (name: string): Promise<string> {
491
+ if (!validateKeyName(name)) {
492
+ await randomDelay()
493
+ throw new CodeError(`Invalid key name '${name}'`, codes.ERR_INVALID_KEY_NAME)
494
+ }
495
+
496
+ try {
497
+ const dsname = DsName(name)
498
+ const res = await this.components.datastore.get(dsname)
499
+ return uint8ArrayToString(res)
500
+ } catch (err: any) {
501
+ await randomDelay()
502
+ this.log.error(err)
503
+ throw new CodeError(`Key '${name}' does not exist.`, codes.ERR_KEY_NOT_FOUND)
504
+ }
505
+ }
506
+
507
+ /**
508
+ * Rotate keychain password and re-encrypt all associated keys
509
+ */
510
+ async rotateKeychainPass (oldPass: string, newPass: string): Promise<void> {
511
+ if (typeof oldPass !== 'string') {
512
+ await randomDelay()
513
+ throw new CodeError(`Invalid old pass type '${typeof oldPass}'`, codes.ERR_INVALID_OLD_PASS_TYPE)
514
+ }
515
+ if (typeof newPass !== 'string') {
516
+ await randomDelay()
517
+ throw new CodeError(`Invalid new pass type '${typeof newPass}'`, codes.ERR_INVALID_NEW_PASS_TYPE)
518
+ }
519
+ if (newPass.length < 20) {
520
+ await randomDelay()
521
+ throw new CodeError(`Invalid pass length ${newPass.length}`, codes.ERR_INVALID_PASS_LENGTH)
522
+ }
523
+ this.log('recreating keychain')
524
+ const cached = privates.get(this)
525
+
526
+ if (cached == null) {
527
+ throw new CodeError('dek missing', codes.ERR_INVALID_PARAMETERS)
528
+ }
529
+
530
+ const oldDek = cached.dek
531
+ this.init.pass = newPass
532
+ const newDek = newPass != null && this.init.dek?.salt != null
533
+ ? pbkdf2(
534
+ newPass,
535
+ this.init.dek.salt,
536
+ this.init.dek?.iterationCount,
537
+ this.init.dek?.keyLength,
538
+ this.init.dek?.hash)
539
+ : ''
540
+ privates.set(this, { dek: newDek })
541
+ const keys = await this.listKeys()
542
+ for (const key of keys) {
543
+ const res = await this.components.datastore.get(DsName(key.name))
544
+ const pem = uint8ArrayToString(res)
545
+ const privateKey = await importKey(pem, oldDek)
546
+ const password = newDek.toString()
547
+ const keyAsPEM = await privateKey.export(password)
548
+
549
+ // Update stored key
550
+ const batch = this.components.datastore.batch()
551
+ const keyInfo = {
552
+ name: key.name,
553
+ id: key.id
554
+ }
555
+ batch.put(DsName(key.name), uint8ArrayFromString(keyAsPEM))
556
+ batch.put(DsInfoName(key.name), uint8ArrayFromString(JSON.stringify(keyInfo)))
557
+ await batch.commit()
558
+ }
559
+ this.log('keychain reconstructed')
560
+ }
561
+ }