-
Notifications
You must be signed in to change notification settings - Fork 32
/
noise.ts
225 lines (200 loc) · 7.72 KB
/
noise.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import { publicKeyFromProtobuf } from '@libp2p/crypto/keys'
import { serviceCapabilities } from '@libp2p/interface'
import { peerIdFromPublicKey } from '@libp2p/peer-id'
import { decode } from 'it-length-prefixed'
import { lpStream, type LengthPrefixedStream } from 'it-length-prefixed-stream'
import { duplexPair } from 'it-pair/duplex'
import { pipe } from 'it-pipe'
import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'
import { NOISE_MSG_MAX_LENGTH_BYTES } from './constants.js'
import { defaultCrypto } from './crypto/index.js'
import { wrapCrypto, type ICryptoInterface } from './crypto.js'
import { uint16BEDecode, uint16BEEncode } from './encoder.js'
import { type MetricsRegistry, registerMetrics } from './metrics.js'
import { performHandshakeInitiator, performHandshakeResponder } from './performHandshake.js'
import { decryptStream, encryptStream } from './streaming.js'
import type { NoiseComponents } from './index.js'
import type { NoiseExtensions } from './proto/payload.js'
import type { HandshakeResult, ICrypto, INoiseConnection, KeyPair } from './types.js'
import type { MultiaddrConnection, SecuredConnection, PeerId, PrivateKey, PublicKey, AbortOptions } from '@libp2p/interface'
import type { Duplex } from 'it-stream-types'
import type { Uint8ArrayList } from 'uint8arraylist'
export interface NoiseInit {
/**
* x25519 private key, reuse for faster handshakes
*/
staticNoiseKey?: Uint8Array
extensions?: NoiseExtensions
crypto?: ICryptoInterface
prologueBytes?: Uint8Array
}
export class Noise implements INoiseConnection {
public protocol = '/noise'
public crypto: ICrypto
private readonly prologue: Uint8Array
private readonly staticKey: KeyPair
private readonly extensions?: NoiseExtensions
private readonly metrics?: MetricsRegistry
private readonly components: NoiseComponents
constructor (components: NoiseComponents, init: NoiseInit = {}) {
const { staticNoiseKey, extensions, crypto, prologueBytes } = init
const { metrics } = components
this.components = components
const _crypto = crypto ?? defaultCrypto
this.crypto = wrapCrypto(_crypto)
this.extensions = extensions
this.metrics = metrics ? registerMetrics(metrics) : undefined
if (staticNoiseKey) {
// accepts x25519 private key of length 32
this.staticKey = _crypto.generateX25519KeyPairFromSeed(staticNoiseKey)
} else {
this.staticKey = _crypto.generateX25519KeyPair()
}
this.prologue = prologueBytes ?? uint8ArrayAlloc(0)
}
readonly [Symbol.toStringTag] = '@chainsafe/libp2p-noise'
readonly [serviceCapabilities]: string[] = [
'@libp2p/connection-encryption',
'@chainsafe/libp2p-noise'
]
/**
* Encrypt outgoing data to the remote party (handshake as initiator)
*
* @param connection - streaming iterable duplex that will be encrypted
* @param options
* @param options.remotePeer - PeerId of the remote peer. Used to validate the integrity of the remote peer
* @param options.signal - Used to abort the operation
*/
public async secureOutbound <Stream extends Duplex<AsyncGenerator<Uint8Array | Uint8ArrayList>> = MultiaddrConnection> (connection: Stream, options?: { remotePeer?: PeerId, signal?: AbortSignal }): Promise<SecuredConnection<Stream, NoiseExtensions>> {
const wrappedConnection = lpStream(
connection,
{
lengthEncoder: uint16BEEncode,
lengthDecoder: uint16BEDecode,
maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES
}
)
const handshake = await this.performHandshakeInitiator(
wrappedConnection,
this.components.privateKey,
options?.remotePeer?.publicKey,
options
)
const conn = await this.createSecureConnection(wrappedConnection, handshake)
connection.source = conn.source
connection.sink = conn.sink
const publicKey = publicKeyFromProtobuf(handshake.payload.identityKey)
return {
conn: connection,
remoteExtensions: handshake.payload.extensions,
remotePeer: peerIdFromPublicKey(publicKey)
}
}
/**
* Decrypt incoming data (handshake as responder).
*
* @param connection - streaming iterable duplex that will be encrypted
* @param options
* @param options.remotePeer - PeerId of the remote peer. Used to validate the integrity of the remote peer
* @param options.signal - Used to abort the operation
*/
public async secureInbound <Stream extends Duplex<AsyncGenerator<Uint8Array | Uint8ArrayList>> = MultiaddrConnection> (connection: Stream, options?: { remotePeer?: PeerId, signal?: AbortSignal }): Promise<SecuredConnection<Stream, NoiseExtensions>> {
const wrappedConnection = lpStream(
connection,
{
lengthEncoder: uint16BEEncode,
lengthDecoder: uint16BEDecode,
maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES
}
)
const handshake = await this.performHandshakeResponder(
wrappedConnection,
this.components.privateKey,
options?.remotePeer?.publicKey,
options
)
const conn = await this.createSecureConnection(wrappedConnection, handshake)
connection.source = conn.source
connection.sink = conn.sink
const publicKey = publicKeyFromProtobuf(handshake.payload.identityKey)
return {
conn: connection,
remoteExtensions: handshake.payload.extensions,
remotePeer: peerIdFromPublicKey(publicKey)
}
}
/**
* Perform XX handshake as initiator.
*/
private async performHandshakeInitiator (
connection: LengthPrefixedStream,
// TODO: pass private key in noise constructor via Components
privateKey: PrivateKey,
remoteIdentityKey?: PublicKey,
options?: AbortOptions
): Promise<HandshakeResult> {
let result: HandshakeResult
try {
result = await performHandshakeInitiator({
connection,
privateKey,
remoteIdentityKey,
log: this.components.logger.forComponent('libp2p:noise:xxhandshake'),
crypto: this.crypto,
prologue: this.prologue,
s: this.staticKey,
extensions: this.extensions
}, options)
this.metrics?.xxHandshakeSuccesses.increment()
} catch (e: unknown) {
this.metrics?.xxHandshakeErrors.increment()
throw e
}
return result
}
/**
* Perform XX handshake as responder.
*/
private async performHandshakeResponder (
connection: LengthPrefixedStream,
privateKey: PrivateKey,
remoteIdentityKey?: PublicKey,
options?: AbortOptions
): Promise<HandshakeResult> {
let result: HandshakeResult
try {
result = await performHandshakeResponder({
connection,
privateKey,
remoteIdentityKey,
log: this.components.logger.forComponent('libp2p:noise:xxhandshake'),
crypto: this.crypto,
prologue: this.prologue,
s: this.staticKey,
extensions: this.extensions
}, options)
this.metrics?.xxHandshakeSuccesses.increment()
} catch (e: unknown) {
this.metrics?.xxHandshakeErrors.increment()
throw e
}
return result
}
private async createSecureConnection (
connection: LengthPrefixedStream<Duplex<AsyncGenerator<Uint8Array | Uint8ArrayList>>>,
handshake: HandshakeResult
): Promise<Duplex<AsyncGenerator<Uint8Array | Uint8ArrayList>>> {
// Create encryption box/unbox wrapper
const [secure, user] = duplexPair<Uint8Array | Uint8ArrayList>()
const network = connection.unwrap()
await pipe(
secure, // write to wrapper
encryptStream(handshake, this.metrics), // encrypt data + prefix with message length
network, // send to the remote peer
(source) => decode(source, { lengthDecoder: uint16BEDecode }), // read message length prefix
decryptStream(handshake, this.metrics), // decrypt the incoming data
secure // pipe to the wrapper
)
return user
}
}