-
Notifications
You must be signed in to change notification settings - Fork 3
/
core-wire.go
466 lines (406 loc) · 11.4 KB
/
core-wire.go
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
package jess
import (
"errors"
"fmt"
)
// msgNo uint64
// lastReKeyAtMsgNo uint64
//
// sendKeyCarryover []byte
// recvKeyCarryover []byte
//
// handshakeState uint8
// eKXSignetPairs [][2]*Signet
// eKESignets []*Signet
// newKey []byte
func (w *WireSession) sendHandshakeAndInitKDF(letter *Letter) error {
var err error
var keyMaterial [][]byte
var burn bool
// process handshake
switch w.handshakeState {
case wireStateInit: // client
keyMaterial, err = w.session.setupClosingKeyMaterial(letter)
if err != nil {
return fmt.Errorf("failed to setup initial sending handshake key material: %w", err)
}
fallthrough
case wireStateIdle: // client and server
if w.msgNo == 0 || (!w.server && w.reKeyNeeded()) {
err = w.generateLocalKeyExchangeSignets(letter)
if err != nil {
return fmt.Errorf("failed to generate local key exchange signets for initiating handshake: %w", err)
}
err = w.generateLocalKeyEncapsulationSignets(letter)
if err != nil {
return fmt.Errorf("failed to generate local key encapsulation signets for initiating handshake: %w", err)
}
w.handshakeState = wireStateAwaitKey
}
case wireStateSendKey: // server
err = w.generateLocalKeyExchangeSignets(letter)
if err != nil {
return fmt.Errorf("failed to generate local key exchange signets for completing handshake: %w", err)
}
// debugging:
/*
fmt.Println("key states:")
for _, kxPair := range w.eKXSignets {
fmt.Printf("kxPair: %+v\n", kxPair)
fmt.Printf("signet: %+v\n", kxPair.signet)
fmt.Printf("peer: %+v\n", kxPair.peer)
}
for _, kePair := range w.eKESignets {
fmt.Printf("kePair: %+v\n", kePair)
}
*/
keyMaterial, err = w.makeSharedKeys(keyMaterial)
if err != nil {
return fmt.Errorf("failed to create shared keys for completing handshake: %w", err)
}
err = w.generateLocalKeyEncapsulationSignets(letter)
if err != nil {
return fmt.Errorf("failed to generate local key encapsulation signets for completing handshake: %w", err)
}
keyMaterial, err = w.makeAndEncapsulateNewKeys(letter, keyMaterial)
if err != nil {
return fmt.Errorf("failed to encapsulate keys for completing handshake: %w", err)
}
w.newKeyMaterial = copyKeyMaterial(keyMaterial)
w.handshakeState = wireStatsAwaitApply
case wireStateSendApply: // client
keyMaterial = append(keyMaterial, w.newKeyMaterial...)
letter.ApplyKeys = true
burn = true
}
// add carryover key
if w.msgNo == 0 {
if w.session.DefaultSymmetricKeySize == 0 {
return fmt.Errorf("missing default key size")
}
w.sendKeyCarryover = make([]byte, w.session.DefaultSymmetricKeySize)
} else {
keyMaterial = append(keyMaterial, w.sendKeyCarryover)
}
// init KDF
err = w.session.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...)
if err != nil {
return fmt.Errorf("failed to init %s kdf: %w", w.session.kdf.Info().Name, err)
}
// derive new carryover key
err = w.session.kdf.DeriveKeyWriteTo(w.sendKeyCarryover)
if err != nil {
return fmt.Errorf("failed to iterate session key with %s: %w", w.session.kdf.Info().Name, err)
}
if w.msgNo == 0 {
// copy initial sendkey to recvkey
w.recvKeyCarryover = make([]byte, len(w.sendKeyCarryover))
copy(w.recvKeyCarryover, w.sendKeyCarryover)
}
// increase msg counter
w.msgNo++
// burn and return
if burn {
return w.burnEphemeralKeys()
}
return nil
}
//nolint:gocognit
func (w *WireSession) recvHandshakeAndInitKDF(letter *Letter) error {
var err error
var keyMaterial [][]byte
var burn bool
// process handshake
switch w.handshakeState {
case wireStateInit: // server
keyMaterial, err = w.session.setupOpeningKeyMaterial(letter)
if err != nil {
return fmt.Errorf("failed to setup initial receiving handshake key material: %w", err)
}
fallthrough
case wireStateIdle: // server
if len(letter.Keys) > 0 {
// apply keys to pairs
// check if there are the right amount of keys
if len(w.session.keyEncapsulators) == 0 {
// TODO:
// initial wire handshake is special:
// key encapsulators send two seals in the initial handshake messages
// one of them is added to the recipients
// the other is a new ephermal key
if len(letter.Keys) != len(w.eKXSignets)+len(w.eKESignets) {
return errors.New("failed to setup initial receiving handshake: incorrect amount of keys in letter")
}
}
// assign keys to kx/ke pairs
keyIndex := 0
for _, kxPair := range w.eKXSignets {
kxPair.peer = &Signet{
Version: letter.Version,
Key: letter.Keys[keyIndex].Value,
Public: true,
tool: kxPair.tool.Definition(),
}
keyIndex++
}
for _, kePair := range w.eKESignets {
// skip keys with ID
for letter.Keys[keyIndex].ID != "" {
keyIndex++
}
kePair.signet = &Signet{
Version: letter.Version,
Key: letter.Keys[keyIndex].Value,
Public: true,
tool: kePair.tool.Definition(),
}
keyIndex++
}
w.handshakeState = wireStateSendKey
}
case wireStateAwaitKey: // client
if len(letter.Keys) > 0 {
// apply keys to pairs
// check if there are the right amount of keys
if len(letter.Keys) != len(w.eKXSignets)+len(w.eKESignets) {
return errors.New("incorrect amount of keys in letter")
}
// assign keys to kx/ke pairs
keyIndex := 0
for _, kxPair := range w.eKXSignets {
kxPair.peer = &Signet{
Version: letter.Version,
Key: letter.Keys[keyIndex].Value,
Public: true,
tool: kxPair.tool.Definition(),
}
keyIndex++
}
for _, kePair := range w.eKESignets {
kePair.seal = letter.Keys[keyIndex]
keyIndex++
}
// make shared keys
keyMaterial, err = w.makeSharedKeys(keyMaterial)
if err != nil {
return err
}
// unwrap keys
keyMaterial, err = w.unwrapKeys(keyMaterial)
if err != nil {
return err
}
w.newKeyMaterial = copyKeyMaterial(keyMaterial)
w.handshakeState = wireStateSendApply
}
case wireStatsAwaitApply: // server
if letter.ApplyKeys {
keyMaterial = append(keyMaterial, w.newKeyMaterial...)
burn = true
}
}
// add carryover key
if w.msgNo == 0 {
if w.session.DefaultSymmetricKeySize == 0 {
return fmt.Errorf("missing default key size")
}
w.recvKeyCarryover = make([]byte, w.session.DefaultSymmetricKeySize)
} else {
keyMaterial = append(keyMaterial, w.recvKeyCarryover)
}
// init KDF
err = w.session.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...)
if err != nil {
return fmt.Errorf("failed to init %s kdf: %w", w.session.kdf.Info().Name, err)
}
// derive new carryover key
err = w.session.kdf.DeriveKeyWriteTo(w.recvKeyCarryover)
if err != nil {
return fmt.Errorf("failed to iterate session key with %s: %w", w.session.kdf.Info().Name, err)
}
if w.msgNo == 0 {
// copy initial recvkey to sendkey
w.sendKeyCarryover = make([]byte, len(w.recvKeyCarryover))
copy(w.sendKeyCarryover, w.recvKeyCarryover)
}
// increase msg counter
w.msgNo++
// burn and return
if burn {
return w.burnEphemeralKeys()
}
return nil
}
func (w *WireSession) generateLocalKeyExchangeSignets(letter *Letter) (err error) {
for _, kxp := range w.eKXSignets {
if kxp.signet == nil {
// generate signet
kxp.signet = NewSignetBase(kxp.tool.Definition())
err := kxp.signet.GenerateKey()
if err != nil {
return err
}
// store signet
err = kxp.signet.StoreKey()
if err != nil {
return err
}
// add to letter
rcpt, err := kxp.signet.AsRecipient() // convert to public signet
if err != nil {
return err
}
err = rcpt.StoreKey()
if err != nil {
return err
}
letter.Keys = append(letter.Keys, &Seal{
Value: rcpt.Key,
})
}
}
return nil
}
func (w *WireSession) makeSharedKeys(keyMaterial [][]byte) ([][]byte, error) {
for _, kxp := range w.eKXSignets {
// check signet
if kxp.signet == nil {
return nil, fmt.Errorf("missing key exchange signet for %s", kxp.tool.Info().Name)
}
// check peer signet
if kxp.peer == nil {
return nil, fmt.Errorf("missing key exchange recipient/peer for %s", kxp.tool.Info().Name)
}
// load peer key
err := kxp.peer.LoadKey()
if err != nil {
return nil, err
}
// make shared key
sharedKey, err := kxp.tool.MakeSharedKey(kxp.signet, kxp.peer)
if err != nil {
return nil, err
}
// append key to material
keyMaterial = append(keyMaterial, sharedKey)
}
return keyMaterial, nil
}
func (w *WireSession) generateLocalKeyEncapsulationSignets(letter *Letter) (err error) {
for _, kep := range w.eKESignets {
if kep.signet == nil {
// generate signet
kep.signet = NewSignetBase(kep.tool.Definition())
err := kep.signet.GenerateKey()
if err != nil {
return err
}
// store signet
err = kep.signet.StoreKey()
if err != nil {
return err
}
// add to letter
rcpt, err := kep.signet.AsRecipient() // convert to public signet
if err != nil {
return err
}
err = rcpt.StoreKey()
if err != nil {
return err
}
letter.Keys = append(letter.Keys, &Seal{
Value: rcpt.Key,
})
}
}
return nil
}
func (w *WireSession) makeAndEncapsulateNewKeys(letter *Letter, keyMaterial [][]byte) ([][]byte, error) {
for _, kep := range w.eKESignets {
// check signet
if kep.signet == nil {
return nil, fmt.Errorf("missing key encapsulation signet for %s", kep.tool.Info().Name)
}
// load signet key
err := kep.signet.LoadKey()
if err != nil {
return nil, err
}
// generate new key
newKey, err := RandomBytes(w.session.DefaultSymmetricKeySize)
if err != nil {
return nil, err
}
// encapsulate it
encapsulatedKey, err := kep.tool.EncapsulateKey(newKey, kep.signet)
if err != nil {
return nil, err
}
// add key to material and letter
keyMaterial = append(keyMaterial, newKey)
letter.Keys = append(letter.Keys, &Seal{Value: encapsulatedKey})
}
return keyMaterial, nil
}
func (w *WireSession) unwrapKeys(keyMaterial [][]byte) ([][]byte, error) {
for _, kep := range w.eKESignets {
// check signet
if kep.signet == nil {
return nil, fmt.Errorf("missing key encapsulation signet for %s", kep.tool.Info().Name)
}
// check seal
if kep.seal == nil {
return nil, fmt.Errorf("missing key encapsulation seal for %s", kep.tool.Info().Name)
}
// unwrap key
unwrappedKey, err := kep.tool.UnwrapKey(kep.seal.Value, kep.signet)
if err != nil {
return nil, err
}
// add key to material
keyMaterial = append(keyMaterial, unwrappedKey)
}
return keyMaterial, nil
}
// burnEphemeralKeys burns all the ephemeral key material in the session. This is currently ineffective, see known issues in the project's README.
func (w *WireSession) burnEphemeralKeys() error {
var lastErr error
// burn key exchange signets
for _, entry := range w.eKXSignets {
if entry.signet != nil {
lastErr = entry.signet.Burn()
}
entry.signet = nil
if entry.peer != nil {
lastErr = entry.peer.Burn()
}
entry.peer = nil
}
// burn key encapsulation signets
for _, entry := range w.eKESignets {
if entry.signet != nil {
lastErr = entry.signet.Burn()
}
entry.signet = nil
if entry.seal != nil {
Burn(entry.seal.Value)
}
entry.seal = nil
}
// burn new key material
for _, part := range w.newKeyMaterial {
Burn(part)
}
w.newKeyMaterial = nil
return lastErr
}
func copyKeyMaterial(keyMaterial [][]byte) [][]byte {
copied := make([][]byte, len(keyMaterial))
for index, part := range keyMaterial {
copiedPart := make([]byte, len(part))
copy(copiedPart, part)
copied[index] = copiedPart
}
return copied
}