-
Notifications
You must be signed in to change notification settings - Fork 17
/
handshake-state.js
506 lines (418 loc) · 13 KB
/
handshake-state.js
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
/* eslint-disable camelcase */
const { sodium_malloc, sodium_memzero, sodium_free } = require('sodium-universal/memory')
const assert = require('nanoassert')
const clone = require('clone')
function createHandshake ({ dh, hash, cipher, symmetricState, cipherState }) {
const DhResult = sodium_malloc(dh.DHLEN)
function HandshakeState () {
this.symmetricState = sodium_malloc(symmetricState.STATELEN)
this.initiator = null
this.spk = null
this.ssk = null
this.epk = null
this.esk = null
this.rs = null
this.re = null
this.messagePatterns = null
}
function initialize (handshakePattern, initiator, prologue, s, e, rs, re) {
assert(Object.keys(PATTERNS).includes(handshakePattern), 'Unsupported handshake pattern')
assert(typeof initiator === 'boolean', 'Initiator must be a boolean')
assert(prologue.byteLength != null, 'prolouge must be a Buffer')
assert(e == null ? true : e.publicKey.byteLength === dh.PKLEN, `e.publicKey must be ${dh.PKLEN} bytes`)
assert(e == null ? true : e.secretKey.byteLength === dh.SKLEN, `e.secretKey must be ${dh.SKLEN} bytes`)
assert(rs == null ? true : rs.byteLength === dh.PKLEN, `rs must be ${dh.PKLEN} bytes`)
assert(re == null ? true : re.byteLength === dh.PKLEN, `re must be ${dh.PKLEN} bytes`)
const state = new HandshakeState()
const protocolName = Uint8Array.from(`Noise_${handshakePattern}_${dh.ALG}_${cipher.ALG}_${hash.ALG}`, toCharCode)
symmetricState.initializeSymmetric(state.symmetricState, protocolName)
symmetricState.mixHash(state.symmetricState, prologue)
state.role = initiator === true ? INITIATOR : RESPONDER
if (s != null) {
assert(s.publicKey.byteLength === dh.PKLEN, `s.publicKey must be ${dh.PKLEN} bytes`)
assert(s.secretKey.byteLength === dh.SKLEN, `s.secretKey must be ${dh.SKLEN} bytes`)
state.spk = sodiumBufferCopy(s.publicKey)
state.ssk = sodiumBufferCopy(s.secretKey)
}
if (e != null) {
assert(e.publicKey.byteLength === dh.PKLEN)
assert(e.secretKey.byteLength === dh.SKLEN)
state.epk = sodiumBufferCopy(e.publicKey)
state.esk = sodiumBufferCopy(e.secretKey)
}
if (rs != null) {
assert(rs.byteLength === dh.PKLEN)
state.rs = sodiumBufferCopy(rs)
}
if (re != null) {
assert(re.byteLength === dh.PKLEN)
state.re = sodiumBufferCopy(re)
}
// hashing
const pat = PATTERNS[handshakePattern]
for (const pattern of clone(pat.premessages)) {
const patternRole = pattern.shift()
for (const token of pattern) {
switch (token) {
case TOK_E:
assert(state.role === patternRole ? state.epk.byteLength != null : state.re.byteLength != null)
symmetricState.mixHash(state.symmetricState, state.role === patternRole ? state.epk : state.re)
break
case TOK_S:
assert(state.role === patternRole ? state.spk.byteLength != null : state.rs.byteLength != null)
symmetricState.mixHash(state.symmetricState, state.role === patternRole ? state.spk : state.rs)
break
default:
throw new Error('Invalid premessage pattern')
}
}
}
state.messagePatterns = clone(pat.messagePatterns)
assert(state.messagePatterns.filter(p => p[0] === INITIATOR).some(p => p.includes(TOK_S))
? (state.spk !== null && state.ssk !== null)
: true, // Default if none is found
'This handshake pattern requires a static keypair')
return state
}
function writeMessage (state, payload, messageBuffer) {
assert(state instanceof HandshakeState)
assert(payload.byteLength != null)
assert(messageBuffer.byteLength != null)
const mpat = state.messagePatterns.shift()
let moffset = 0
assert(mpat != null)
assert(state.role === mpat.shift())
for (const token of mpat) {
switch (token) {
case TOK_E:
assert(state.epk == null)
assert(state.esk == null)
state.epk = sodium_malloc(dh.PKLEN)
state.esk = sodium_malloc(dh.SKLEN)
dh.generateKeypair(state.epk, state.esk)
messageBuffer.set(state.epk, moffset)
moffset += state.epk.byteLength
symmetricState.mixHash(state.symmetricState, state.epk)
break
case TOK_S:
assert(state.spk.byteLength === dh.PKLEN)
symmetricState.encryptAndHash(state.symmetricState, messageBuffer.subarray(moffset), state.spk)
moffset += symmetricState.encryptAndHash.bytesWritten
break
case TOK_EE:
dh.dh(DhResult, state.esk, state.re)
symmetricState.mixKey(state.symmetricState, DhResult)
sodium_memzero(DhResult)
break
case TOK_ES:
if (state.role === INITIATOR) dh.dh(DhResult, state.esk, state.rs)
else dh.dh(DhResult, state.ssk, state.re)
symmetricState.mixKey(state.symmetricState, DhResult)
sodium_memzero(DhResult)
break
case TOK_SE:
if (state.role === INITIATOR) dh.dh(DhResult, state.ssk, state.re)
else dh.dh(DhResult, state.esk, state.rs)
symmetricState.mixKey(state.symmetricState, DhResult)
sodium_memzero(DhResult)
break
case TOK_SS:
dh.dh(DhResult, state.ssk, state.rs)
symmetricState.mixKey(state.symmetricState, DhResult)
sodium_memzero(DhResult)
break
default:
throw new Error('Invalid message pattern')
}
}
symmetricState.encryptAndHash(state.symmetricState, messageBuffer.subarray(moffset), payload)
moffset += symmetricState.encryptAndHash.bytesWritten
writeMessage.bytes = moffset
if (state.messagePatterns.length === 0) {
const tx = sodium_malloc(cipherState.STATELEN)
const rx = sodium_malloc(cipherState.STATELEN)
symmetricState.split(state.symmetricState, tx, rx, dh.DHLEN, dh.PKLEN)
return { tx, rx }
}
}
writeMessage.bytes = 0
function readMessage (state, message, payloadBuffer) {
assert(state instanceof HandshakeState)
assert(message.byteLength != null)
assert(payloadBuffer.byteLength != null)
const mpat = state.messagePatterns.shift()
let moffset = 0
assert(mpat != null)
assert(mpat.shift() !== state.role)
for (const token of mpat) {
switch (token) {
case TOK_E:
assert(state.re == null)
assert(message.byteLength - moffset >= dh.PKLEN)
// PKLEN instead of DHLEN since they are different in out case
state.re = sodium_malloc(dh.PKLEN)
state.re.set(message.subarray(moffset, moffset + dh.PKLEN))
moffset += dh.PKLEN
symmetricState.mixHash(state.symmetricState, state.re)
break
case TOK_S: {
assert(state.rs == null)
state.rs = sodium_malloc(dh.PKLEN)
let bytes = 0
if (symmetricState._hasKey(state.symmetricState)) {
bytes = dh.PKLEN + 16
} else {
bytes = dh.PKLEN
}
assert(message.byteLength - moffset >= bytes)
symmetricState.decryptAndHash(
state.symmetricState,
state.rs,
message.subarray(moffset, moffset + bytes) // <- called temp in noise spec
)
moffset += symmetricState.decryptAndHash.bytesRead
break
}
case TOK_EE:
dh.dh(DhResult, state.esk, state.re)
symmetricState.mixKey(state.symmetricState, DhResult)
sodium_memzero(DhResult)
break
case TOK_ES:
if (state.role === INITIATOR) dh.dh(DhResult, state.esk, state.rs)
else dh.dh(DhResult, state.ssk, state.re)
symmetricState.mixKey(state.symmetricState, DhResult)
sodium_memzero(DhResult)
break
case TOK_SE:
if (state.role === INITIATOR) dh.dh(DhResult, state.ssk, state.re)
else dh.dh(DhResult, state.esk, state.rs)
symmetricState.mixKey(state.symmetricState, DhResult)
sodium_memzero(DhResult)
break
case TOK_SS:
dh.dh(DhResult, state.ssk, state.rs)
symmetricState.mixKey(state.symmetricState, DhResult)
sodium_memzero(DhResult)
break
default:
throw new Error('Invalid message pattern')
}
}
symmetricState.decryptAndHash(state.symmetricState, payloadBuffer, message.subarray(moffset))
// How many bytes were written to payload (minus the TAG/MAC)
readMessage.bytes = symmetricState.decryptAndHash.bytesWritten
if (state.messagePatterns.length === 0) {
const tx = sodium_malloc(cipherState.STATELEN)
const rx = sodium_malloc(cipherState.STATELEN)
symmetricState.split(state.symmetricState, rx, tx, dh.DHLEN, dh.PKLEN)
return { tx, rx }
}
}
readMessage.bytes = 0
function keygen (obj, sk) {
if (!obj) {
obj = { publicKey: sodium_malloc(dh.PKLEN), secretKey: sodium_malloc(dh.SKLEN) }
return keygen(obj)
}
if (obj.publicKey) {
dh.generateKeypair(obj.publicKey, obj.secretKey)
return obj
}
if (obj.byteLength != null) dh.generateKeypair(null, obj)
}
function seedKeygen (seed) {
const obj = { publicKey: sodium_malloc(dh.PKLEN), secretKey: sodium_malloc(dh.SKLEN) }
dh.generateSeedKeypair(obj.publicKey, obj.secretKey, seed)
return obj
}
return Object.freeze({
initialize,
writeMessage,
readMessage,
destroy,
keygen,
seedKeygen,
createHandshake,
SKLEN: dh.SKLEN,
PKLEN: dh.PKLEN
})
}
const INITIATOR = Symbol('initiator')
const RESPONDER = Symbol('responder')
const TOK_S = Symbol('s')
const TOK_E = Symbol('e')
const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('es')
// initiator, ->
// responder, <-
const PATTERNS = Object.freeze({
N: {
premessages: [
[RESPONDER, TOK_S]
],
messagePatterns: [
[INITIATOR, TOK_E, TOK_ES]
]
},
K: {
premessages: [
[INITIATOR, TOK_S],
[RESPONDER, TOK_S]
],
messagePatterns: [
[INITIATOR, TOK_E, TOK_ES, TOK_SS]
]
},
X: {
premessages: [
[RESPONDER, TOK_S]
],
messagePatterns: [
[INITIATOR, TOK_E, TOK_ES, TOK_S, TOK_SS]
]
},
NN: {
premessages: [],
messagePatterns: [
[INITIATOR, TOK_E],
[RESPONDER, TOK_E, TOK_EE]
]
},
KN: {
premessages: [
[INITIATOR, TOK_S]
],
messagePatterns: [
[INITIATOR, TOK_E],
[RESPONDER, TOK_E, TOK_EE, TOK_SE]
]
},
NK: {
premessages: [
[RESPONDER, TOK_S]
],
messagePatterns: [
[INITIATOR, TOK_E, TOK_ES],
[RESPONDER, TOK_E, TOK_EE]
]
},
KK: {
premessages: [
[INITIATOR, TOK_S],
[RESPONDER, TOK_S]
],
messagePatterns: [
[INITIATOR, TOK_E, TOK_ES, TOK_SS],
[RESPONDER, TOK_E, TOK_EE, TOK_SE]
]
},
NX: {
premessages: [],
messagePatterns: [
[INITIATOR, TOK_E],
[RESPONDER, TOK_E, TOK_EE, TOK_S, TOK_ES]
]
},
KX: {
premessages: [
[INITIATOR, TOK_S]
],
messagePatterns: [
[INITIATOR, TOK_E],
[RESPONDER, TOK_E, TOK_EE, TOK_SE, TOK_S, TOK_ES]
]
},
XN: {
premessages: [],
messagePatterns: [
[INITIATOR, TOK_E],
[RESPONDER, TOK_E, TOK_EE],
[INITIATOR, TOK_S, TOK_SE]
]
},
IN: {
premessages: [],
messagePatterns: [
[INITIATOR, TOK_E, TOK_S],
[RESPONDER, TOK_E, TOK_EE, TOK_SE]
]
},
XK: {
premessages: [
[RESPONDER, TOK_S]
],
messagePatterns: [
[INITIATOR, TOK_E, TOK_ES],
[RESPONDER, TOK_E, TOK_EE],
[INITIATOR, TOK_S, TOK_SE]
]
},
IK: {
premessages: [
[RESPONDER, TOK_S]
],
messagePatterns: [
[INITIATOR, TOK_E, TOK_ES, TOK_S, TOK_SS],
[RESPONDER, TOK_E, TOK_EE, TOK_SE]
]
},
XX: {
premessages: [],
messagePatterns: [
[INITIATOR, TOK_E],
[RESPONDER, TOK_E, TOK_EE, TOK_S, TOK_ES],
[INITIATOR, TOK_S, TOK_SE]
]
},
IX: {
premessages: [],
messagePatterns: [
[INITIATOR, TOK_E, TOK_S],
[RESPONDER, TOK_E, TOK_EE, TOK_SE, TOK_S, TOK_ES]
]
}
})
function sodiumBufferCopy (src) {
const buf = sodium_malloc(src.byteLength)
buf.set(src)
return buf
}
function destroy (state) {
if (state.symmetricState != null) {
sodium_free(state.symmetricState)
state.symmetricState = null
}
state.role = null
if (state.spk != null) {
sodium_free(state.spk)
state.spk = null
}
if (state.ssk != null) {
sodium_free(state.ssk)
state.ssk = null
}
if (state.epk != null) {
sodium_free(state.epk)
state.epk = null
}
if (state.esk != null) {
sodium_free(state.esk)
state.esk = null
}
if (state.rs != null) {
sodium_free(state.rs)
state.rs = null
}
if (state.re != null) {
sodium_free(state.re)
state.re = null
}
state.messagePatterns = null
}
function toCharCode (s) {
return s.charCodeAt(0)
}
module.exports = createHandshake