-
Notifications
You must be signed in to change notification settings - Fork 3
/
session.go
561 lines (473 loc) · 15.5 KB
/
session.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
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
package jess
import (
"errors"
"fmt"
"hash"
"strings"
"github.com/safing/jess/hashtools"
"github.com/safing/jess/tools"
)
// Session holds session information for operations using the envelope it was initialized with.
type Session struct {
envelope *Envelope
DefaultSymmetricKeySize int
SecurityLevel int
maxSecurityLevel int
toolRequirements *Requirements
// session over the wire
wire *WireSession
// instances
all []tools.ToolLogic
toolsWithState []tools.ToolLogic
kdf tools.ToolLogic
passDerivator tools.ToolLogic
keyExchangers []tools.ToolLogic
keyEncapsulators []tools.ToolLogic
integratedCiphers []tools.ToolLogic
ciphers []tools.ToolLogic
managedMACHashers map[string]*managedHasher
macs []tools.ToolLogic
managedSigningHashers map[string]*managedHasher
signers []tools.ToolLogic
}
type managedHasher struct {
tool *hashtools.HashTool
hash hash.Hash
}
// Sum returns the hash sum of the managed hasher.
func (sh *managedHasher) Sum() ([]byte, error) {
if sh == nil || sh.hash == nil {
return nil, errors.New("managed hasher is broken")
}
return sh.hash.Sum(nil), nil
}
func newSession(e *Envelope) (*Session, error) { //nolint:maintidx
if e.suite == nil {
return nil, errors.New("suite not loaded")
}
// create session
s := &Session{
envelope: e,
toolRequirements: newEmptyRequirements(),
}
// check envelope security level
if e.SecurityLevel > 0 {
err := s.checkSecurityLevel(e.SecurityLevel, func() string {
return fmt.Sprintf(`envelope "%s"`, e.Name)
})
if err != nil {
return nil, err
}
}
// check suite security level
err := s.checkSecurityLevel(e.suite.SecurityLevel, func() string {
return fmt.Sprintf(`suite "%s"`, e.suite.ID)
})
if err != nil {
return nil, err
}
// prepare variables
var (
keySourceAvailable bool
totalSignetsSeen int
requireSecurityLevel bool
requireDefaultKeySize bool
)
// tool init loop: start
for i, toolID := range s.envelope.suite.Tools {
// ====================================
// tool init loop: check for duplicates
// ====================================
for j, dupeToolID := range s.envelope.suite.Tools {
if i != j && toolID == dupeToolID {
return nil, fmt.Errorf("cannot use tool %s twice, each tool may be only specified once", toolID)
}
}
// ===================================
// tool init loop: parse, prep and get
// ===================================
var (
hashTool *hashtools.HashTool
hashSumFn func() ([]byte, error)
)
// parse ID for args
var arg string
if strings.Contains(toolID, "(") {
splitted := strings.Split(toolID, "(")
toolID = splitted[0]
arg = strings.Trim(splitted[1], "()")
}
// get tool
tool, err := tools.Get(toolID)
if err != nil {
return nil, fmt.Errorf("the specified tool %s could not be found", toolID)
}
// create logic instance and add to logic and state lists
logic := tool.Factory()
s.all = append(s.all, logic)
if tool.Info.HasOption(tools.OptionHasState) {
s.toolsWithState = append(s.toolsWithState, logic)
}
// ===========================================================
// tool init loop: assign tools to queues and add requirements
// ===========================================================
switch tool.Info.Purpose {
case tools.PurposeKeyDerivation:
if s.kdf != nil {
return nil, fmt.Errorf("cannot use %s, you may only specify one key derivation tool and %s was already specified", tool.Info.Name, s.kdf.Info().Name)
}
s.kdf = logic
case tools.PurposePassDerivation:
if s.passDerivator != nil {
return nil, fmt.Errorf("cannot use %s, you may only specify one password derivation tool and %s was already specified", tool.Info.Name, s.passDerivator.Info().Name)
}
s.passDerivator = logic
s.toolRequirements.Add(SenderAuthentication)
s.toolRequirements.Add(RecipientAuthentication)
case tools.PurposeKeyExchange:
s.keyExchangers = append(s.keyExchangers, logic)
s.toolRequirements.Add(RecipientAuthentication)
case tools.PurposeKeyEncapsulation:
s.keyEncapsulators = append(s.keyEncapsulators, logic)
s.toolRequirements.Add(RecipientAuthentication)
case tools.PurposeSigning:
s.signers = append(s.signers, logic)
s.toolRequirements.Add(Integrity)
s.toolRequirements.Add(SenderAuthentication)
case tools.PurposeIntegratedCipher:
s.integratedCiphers = append(s.integratedCiphers, logic)
s.toolRequirements.Add(Confidentiality)
s.toolRequirements.Add(Integrity)
case tools.PurposeCipher:
s.ciphers = append(s.ciphers, logic)
s.toolRequirements.Add(Confidentiality)
case tools.PurposeMAC:
s.macs = append(s.macs, logic)
s.toolRequirements.Add(Integrity)
}
// ============================================
// tool init loop: process options, get hashers
// ============================================
for _, option := range tool.Info.Options {
switch option {
case tools.OptionStreaming:
// TODO: Implementation pending.
case tools.OptionNeedsManagedHasher:
// get managed hasher list
var managedHashers map[string]*managedHasher
switch tool.Info.Purpose {
case tools.PurposeMAC:
if s.managedMACHashers == nil {
s.managedMACHashers = make(map[string]*managedHasher)
}
managedHashers = s.managedMACHashers
case tools.PurposeSigning:
if s.managedSigningHashers == nil {
s.managedSigningHashers = make(map[string]*managedHasher)
}
managedHashers = s.managedSigningHashers
default:
return nil, fmt.Errorf("only MAC and Signing tools may use managed hashers")
}
// get or assign a new managed hasher
mngdHasher, ok := managedHashers[arg]
if !ok {
// get hashtool
ht, err := hashtools.Get(arg)
if err != nil {
return nil, fmt.Errorf("the specified hashtool for %s(%s) could not be found", toolID, arg)
}
// save to managed hashers
mngdHasher = &managedHasher{
tool: ht,
hash: ht.New(),
}
managedHashers[arg] = mngdHasher
}
hashTool = mngdHasher.tool
hashSumFn = mngdHasher.Sum
case tools.OptionNeedsDedicatedHasher:
hashTool, err = hashtools.Get(arg)
if err != nil {
return nil, fmt.Errorf("the specified hashtool for %s(%s) could not be found", toolID, arg)
}
case tools.OptionNeedsSecurityLevel:
requireSecurityLevel = true
case tools.OptionNeedsDefaultKeySize:
requireDefaultKeySize = true
}
}
// ===============================
// tool init loop: initialize tool
// ===============================
// init tool
logic.Init(
tool,
&Helper{
session: s,
info: tool.Info,
},
hashTool,
hashSumFn,
)
// ==============================================
// tool init loop: calc and check security levels
// ==============================================
err = s.calcAndCheckSecurityLevel(logic, nil)
if err != nil {
return nil, err
}
// ==========================================
// tool init loop: calculate default key size
// ==========================================
// find biggest key size for default
if tool.Info.KeySize > s.DefaultSymmetricKeySize {
s.DefaultSymmetricKeySize = tool.Info.KeySize
}
} // tool init loop: end
// =======================================================
// calc and check signet security levels, default key size
// =======================================================
for _, tool := range s.all {
var err error
var seen int
// calc and check signet security levels
switch tool.Info().Purpose {
case tools.PurposePassDerivation:
//nolint:scopelint // function is executed immediately within loop
err = e.LoopSecrets(SignetSchemePassword, func(signet *Signet) error {
seen++
return s.calcAndCheckSecurityLevel(tool, signet)
})
keySourceAvailable = true
case tools.PurposeKeyExchange,
tools.PurposeKeyEncapsulation:
//nolint:scopelint // function is executed immediately within loop
err = e.LoopRecipients(tool.Info().Name, func(signet *Signet) error {
seen++
return s.calcAndCheckSecurityLevel(tool, signet)
})
keySourceAvailable = true
case tools.PurposeSigning:
//nolint:scopelint // function is executed immediately within loop
err = e.LoopSenders(tool.Info().Name, func(signet *Signet) error {
seen++
return s.calcAndCheckSecurityLevel(tool, signet)
})
keySourceAvailable = true
default:
continue
}
// check error
if err != nil {
return nil, err
}
// check if anything is here
if seen == 0 {
return nil, fmt.Errorf("tool %s requires at least one signet", tool.Info().Name)
}
totalSignetsSeen += seen
}
// key signets
err = e.LoopSecrets(SignetSchemeKey, func(signet *Signet) error {
s.toolRequirements.Add(SenderAuthentication)
s.toolRequirements.Add(RecipientAuthentication)
totalSignetsSeen++
keySourceAvailable = true
return s.calcAndCheckSecurityLevel(nil, signet)
})
if err != nil {
return nil, err
}
// ======================================================
// check security level and default key size requirements
// ======================================================
// apply manual security level
if minimumSecurityLevel > 0 && minimumSecurityLevel > s.SecurityLevel {
s.SecurityLevel = minimumSecurityLevel
}
// apply manual key size
if minimumSymmetricKeySize > 0 && minimumSymmetricKeySize > s.DefaultSymmetricKeySize {
s.DefaultSymmetricKeySize = minimumSymmetricKeySize
}
// check security level requirement
if requireSecurityLevel && s.SecurityLevel == 0 {
return nil, fmt.Errorf("this toolset requires the security level to be set manually")
}
// check default key size requirement
if requireDefaultKeySize && s.DefaultSymmetricKeySize == 0 {
return nil, fmt.Errorf("this toolset requires the default key size to be set manually")
}
// ============
// final checks
// ============
// check requirements
if s.toolRequirements.Empty() {
return nil, errors.New("envelope excludes all security requirements, no meaningful operation possible")
}
err = s.toolRequirements.CheckComplianceTo(s.envelope.suite.Provides)
if err != nil {
return nil, err
}
// check if we have recipient auth without confidentiality
if s.toolRequirements.Has(RecipientAuthentication) &&
!s.toolRequirements.Has(Confidentiality) {
return nil, errors.New("having recipient authentication without confidentiality does not make sense")
}
// check if we have confidentiality without integrity
if s.toolRequirements.Has(Confidentiality) &&
!s.toolRequirements.Has(Integrity) {
return nil, errors.New("having confidentiality without integrity does not make sense")
}
// check if we are missing a kdf, but need one
if s.kdf == nil && len(s.signers) != len(s.envelope.suite.Tools) {
return nil, errors.New("missing a key derivation tool")
}
// check if have a kdf, even if we don't need one
if len(s.integratedCiphers) == 0 &&
len(s.ciphers) == 0 &&
len(s.macs) == 0 &&
s.kdf != nil {
return nil, errors.New("key derivation tool specified, but not needed")
}
// check if we have a key source
if !keySourceAvailable &&
(s.toolRequirements.Has(Integrity) || s.toolRequirements.Has(Confidentiality)) {
return nil, errors.New("missing key source, please add a tool that provides a key or add a key signet directly")
}
// check if there are unused signets
if len(s.envelope.Secrets)+
len(s.envelope.Senders)+
len(s.envelope.Recipients) > totalSignetsSeen {
return nil, fmt.Errorf("detected signet or recipient in envelope that is not used by any tool")
}
// check session security level
// while this should never result in an error (because every part was already checked separately) this is used as a precaution to catch errors in future code changes
err = s.checkSecurityLevel(s.SecurityLevel, func() string {
return "current session"
})
if err != nil {
return nil, err
}
return s, nil
}
//nolint:gocognit
func (s *Session) calcAndCheckSecurityLevel(logic tools.ToolLogic, signet *Signet) error {
// get signet scheme
signetScheme := ""
if signet != nil {
signetScheme = signet.Scheme
}
var err error
var calculatedSecurityLevel int
switch {
case signetScheme == SignetSchemeKey:
calculatedSecurityLevel = len(signet.Key) * 8
case signetScheme == SignetSchemePassword && signet != nil:
// only check if present
// existence check is done when opening/closing
if len(signet.Key) > 0 {
switch logic.Info().Name {
case "SCRYPT-20":
// TODO: integrate this into the tool interface
calculatedSecurityLevel = CalculatePasswordSecurityLevel(string(signet.Key), 1<<20)
case "PBKDF2-SHA2-256":
// TODO: integrate this into the tool interface
calculatedSecurityLevel = CalculatePasswordSecurityLevel(string(signet.Key), 20000)
default:
calculatedSecurityLevel = CalculatePasswordSecurityLevel(string(signet.Key), 1)
}
if calculatedSecurityLevel < 0 {
return fmt.Errorf(`supplied password signet "%s" is exceptionally weak and should not be used`, signet.ID)
}
}
default:
// get tool security level
if signet == nil {
// nil interface hackery for inherited SecurityLevel() functions
calculatedSecurityLevel, err = logic.SecurityLevel(nil)
} else {
calculatedSecurityLevel, err = logic.SecurityLevel(signet)
}
if err != nil {
return err
}
}
if calculatedSecurityLevel == 0 {
// not applicable
return nil
}
if calculatedSecurityLevel < 0 {
// broken!
if signet != nil {
return fmt.Errorf(`supplied %s signet "%s" is considered broken and should not be used anymore`, signet.Scheme, signet.ID)
}
return fmt.Errorf(`tool %s is considered broken and should not be used anymore`, logic.Info().Name)
}
if signet != nil {
// signet based security level checks
err = s.checkSecurityLevel(calculatedSecurityLevel, func() string {
return fmt.Sprintf(`supplied %s signet "%s"`, signet.Scheme, signet.ID)
})
} else {
// tool based securty level checks
err = s.checkSecurityLevel(calculatedSecurityLevel, func() string {
return "tool %s" + logic.Info().Name
})
}
if err != nil {
return err
}
// adapt security level of session
// lower session security level
if s.SecurityLevel == 0 || calculatedSecurityLevel < s.SecurityLevel {
s.SecurityLevel = calculatedSecurityLevel
}
// raise session max security level
if calculatedSecurityLevel > s.maxSecurityLevel {
s.maxSecurityLevel = calculatedSecurityLevel
}
return nil
}
func (s *Session) checkSecurityLevel(levelToCheck int, subject func() string) error {
switch {
case minimumSecurityLevel > 0:
// check against minimumSecurityLevel
// (overrides other checks)
if levelToCheck < minimumSecurityLevel {
return fmt.Errorf(
`%s with a security level of %d is weaker than the desired security level of %d`,
subject(),
levelToCheck,
minimumSecurityLevel,
)
}
case s.envelope.SecurityLevel > 0:
// check against envelope's minimum security level
if levelToCheck < s.envelope.SecurityLevel {
return fmt.Errorf(
`%s with a security level of %d is weaker than the envelope's minimum security level of %d`,
subject(),
levelToCheck,
s.envelope.SecurityLevel,
)
}
case levelToCheck < defaultSecurityLevel:
// check against default security level as fallback
return fmt.Errorf(
`%s with a security level of %d is weaker than the default minimum security level of %d`,
subject(),
levelToCheck,
defaultSecurityLevel,
)
}
return nil
}
// NonceSize returns the nonce size to use for new letters.
func (s *Session) NonceSize() int {
size := s.maxSecurityLevel / 32
if size < 4 {
size = 4
}
return size
}