-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathchannel_binding_test.go
More file actions
441 lines (373 loc) · 14.7 KB
/
channel_binding_test.go
File metadata and controls
441 lines (373 loc) · 14.7 KB
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
// Copyright 2025 by David A. Golden. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package scram
import (
"encoding/base64"
"errors"
"fmt"
"strings"
"testing"
)
// === Helpers ===
// Authentication flow step names
const (
stepClientFirst = "client first"
stepServerFirst = "server first"
stepClientFinal = "client final"
stepServerFinal = "server final"
stepClientValidation = "client validation"
stepFinalValidation = "final validation"
stepFinished = "finished"
)
// assertErrorContains verifies that err is non-nil and contains all specified substrings.
func assertNoError(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatalf("Expected no error, got: %v", err)
}
}
// assertErrorContains verifies that err is non-nil and contains all specified substrings.
func assertErrorContains(t *testing.T, err error, substr string) {
t.Helper()
if err == nil {
t.Fatal("Expected error, got nil")
}
if !strings.Contains(err.Error(), substr) {
t.Errorf("Expected error to contain %q, got: %v", substr, err)
}
}
func assertFinishedSuccessfully(t *testing.T, step string, err error) {
t.Helper()
assertNoError(t, err)
if step != stepFinished {
t.Errorf("Expected authentication to finish successfully, got stuck at step %q", step)
}
}
// assertErrorAtStep verifies that an error occurred at the expected step and contains expected substrings.
func assertErrorAtStep(t *testing.T, step string, err error, expectedStep string, expectedErrSubstrs ...string) {
t.Helper()
if step != expectedStep {
t.Errorf("Expected error at step %q, got %q", expectedStep, step)
}
for _, substr := range expectedErrSubstrs {
assertErrorContains(t, err, substr)
}
}
// mockCredLookupFcn returns a CredentialLookup function for testing with the given password.
// Uses a fixed salt and iteration count for consistent test behavior.
func mockCredLookupFcn(password string) CredentialLookup {
return func(username string) (StoredCredentials, error) {
client, _ := SHA256.NewClient(username, password, "")
salt := []byte("QSXCR+Q6sek8bf92")
return client.GetStoredCredentials(KeyFactors{Salt: string(salt), Iters: 4096}), nil
}
}
// setupClientServer creates a client and server for testing with standard test credentials.
func setupClientServer(t *testing.T) (*Client, *Server) {
t.Helper()
client, err := SHA256.NewClient("user", "pencil", "")
assertNoError(t, err)
server, err := SHA256.NewServer(mockCredLookupFcn("pencil"))
assertNoError(t, err)
return client, server
}
// setupConversations creates client and server conversations with the specified channel bindings.
func setupConversations(t *testing.T, client *Client, server *Server, clientCB, serverCB ChannelBinding, required bool) (*ClientConversation, *ServerConversation) {
var clientConv *ClientConversation
if clientCB.IsSupported() {
clientConv = client.NewConversationWithChannelBinding(clientCB)
} else {
clientConv = client.NewConversation()
}
var serverConv *ServerConversation
if required {
if !serverCB.IsSupported() {
t.Fatal("Server channel binding must be supported when required is true")
}
serverConv = server.NewConversationWithChannelBindingRequired(serverCB)
} else if serverCB.IsSupported() {
serverConv = server.NewConversationWithChannelBinding(serverCB)
} else {
serverConv = server.NewConversation()
}
return clientConv, serverConv
}
// runFullAuthFlow executes a complete SCRAM authentication between the given
// client and server conversations. Returns the name of the step where an error
// occurred (if any) and the error itself.
func runFullAuthFlow(clientConv *ClientConversation, serverConv *ServerConversation) (string, error) {
clientFirst, err := clientConv.Step("")
if err != nil {
return stepClientFirst, err
}
serverFirst, err := serverConv.Step(clientFirst)
if err != nil {
return stepServerFirst, err
}
clientFinal, err := clientConv.Step(serverFirst)
if err != nil {
return stepClientFinal, err
}
serverFinal, err := serverConv.Step(clientFinal)
if err != nil {
return stepServerFinal, err
}
_, err = clientConv.Step(serverFinal)
if err != nil {
return stepClientValidation, err
}
if !clientConv.Valid() || !serverConv.Valid() {
return stepFinalValidation, errors.New("authentication failed: conversations not valid")
}
return stepFinished, nil
}
// extractNonce parses the nonce from a server-first message.
// Server-first format: r=<nonce>,s=<salt>,i=<iterations>
func extractNonce(serverFirst string) string {
parts := strings.Split(serverFirst, ",")
noncePart := parts[0] // r=clientnonce123servernonce...
return noncePart[2:] // Strip "r=" prefix
}
// setupForClientFinal creates conversations and advances to the point where
// client-final is expected. Returns the server conversation ready to receive
// client-final, the nonce to use, and the GS2 header string.
func setupForClientFinal(t *testing.T, client *Client, server *Server, cb ChannelBinding) (*ServerConversation, string, string) {
t.Helper()
clientConv, serverConv := setupConversations(t, client, server, cb, cb, false)
clientFirst, err := clientConv.Step("")
assertNoError(t, err)
serverFirst, err := serverConv.Step(clientFirst)
assertNoError(t, err)
nonce := extractNonce(serverFirst)
gs2Header := "p=" + string(cb.Type) + ",,"
return serverConv, nonce, gs2Header
}
// buildClientFinal constructs a valid client-final message from components.
func buildClientFinal(nonce, gs2Header string, cbData []byte, proof string) string {
cbMsg := append([]byte(gs2Header), cbData...)
cAttr := base64.StdEncoding.EncodeToString(cbMsg)
return fmt.Sprintf("c=%s,r=%s,p=%s", cAttr, nonce, proof)
}
// === Basic method tests ===
func TestChannelBindingIsSupported(t *testing.T) {
// Positive case
if !(ChannelBinding{Type: ChannelBindingTLSExporter, Data: []byte("test")}.IsSupported()) {
t.Error("Channel binding with type and data should be supported")
}
// Negative cases
if (ChannelBinding{}.IsSupported()) {
t.Error("Empty channel binding should not be supported")
}
if (ChannelBinding{Type: ChannelBindingTLSExporter}.IsSupported()) {
t.Error("Channel binding with type but no data should not be supported")
}
}
func TestChannelBindingMatches_Data(t *testing.T) {
cb1 := ChannelBinding{Type: ChannelBindingTLSExporter, Data: []byte("test")}
cb2 := ChannelBinding{Type: ChannelBindingTLSExporter, Data: []byte("test")}
cb3 := ChannelBinding{Type: ChannelBindingTLSExporter, Data: []byte("different")}
if !cb1.Matches(cb2) {
t.Error("Identical channel bindings should match")
}
if cb1.Matches(cb3) {
t.Error("Different data should not match")
}
}
func TestChannelBindingMatches_Type(t *testing.T) {
cb1 := ChannelBinding{Type: ChannelBindingTLSUnique, Data: []byte("test")}
cb2 := ChannelBinding{Type: ChannelBindingTLSExporter, Data: []byte("test")}
if cb1.Matches(cb2) {
t.Error("Different types should not match")
}
}
// === Protocol encoding tests ===
func TestChannelBindingGS2Header(t *testing.T) {
username := "user"
password := "pencil"
// Verify that client-first messages contain correct GS2 headers per RFC 5802.
tests := []struct {
name string
setupConv func(client *Client) *ClientConversation
expectedPrefix string
authzID string
}{
{
name: "No channel binding - flag n",
setupConv: func(client *Client) *ClientConversation { return client.NewConversation() },
expectedPrefix: "n,,",
},
{
name: "No channel binding - flag n, with authzID",
setupConv: func(client *Client) *ClientConversation { return client.NewConversation() },
authzID: "admin",
expectedPrefix: "n,a=admin,",
},
{
name: "With tls-exporter channel binding - flag p",
setupConv: func(client *Client) *ClientConversation {
return client.NewConversationWithChannelBinding(ChannelBinding{
Type: ChannelBindingTLSExporter,
Data: []byte{0x01, 0x02, 0x03},
})
},
expectedPrefix: "p=tls-exporter,,",
},
{
name: "With tls-exporter channel binding - flag p, with authzID",
setupConv: func(client *Client) *ClientConversation {
return client.NewConversationWithChannelBinding(ChannelBinding{
Type: ChannelBindingTLSExporter,
Data: []byte{0x01, 0x02, 0x03},
})
},
authzID: "admin",
expectedPrefix: "p=tls-exporter,a=admin,",
},
{
name: "Advertising channel binding - flag y",
setupConv: func(client *Client) *ClientConversation { return client.NewConversationAdvertisingChannelBinding() },
expectedPrefix: "y,,",
},
{
name: "Advertising channel binding - flag y, with authzID",
setupConv: func(client *Client) *ClientConversation { return client.NewConversationAdvertisingChannelBinding() },
authzID: "admin",
expectedPrefix: "y,a=admin,",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client, err := SHA256.NewClient(username, password, tt.authzID)
assertNoError(t, err)
conv := tt.setupConv(client)
clientFirst, err := conv.Step("")
assertNoError(t, err)
if !strings.HasPrefix(clientFirst, tt.expectedPrefix) {
t.Errorf("Expected client-first to start with %q, got %q",
tt.expectedPrefix, clientFirst)
}
})
}
}
// === Channel binding conversation tests ===
func TestChannelBinding_Success_NoBinding(t *testing.T) {
client, server := setupClientServer(t)
clientConv, serverConv := setupConversations(t, client, server, ChannelBinding{}, ChannelBinding{}, false)
step, err := runFullAuthFlow(clientConv, serverConv)
assertFinishedSuccessfully(t, step, err)
}
func TestChannelBinding_Success_AllTypes(t *testing.T) {
bindingTypes := []ChannelBindingType{
ChannelBindingTLSUnique,
ChannelBindingTLSServerEndpoint,
ChannelBindingTLSExporter,
}
for _, cbType := range bindingTypes {
t.Run(string(cbType), func(t *testing.T) {
cbData := []byte("test-data-for-" + string(cbType))
cb := ChannelBinding{Type: cbType, Data: cbData}
client, server := setupClientServer(t)
clientConv, serverConv := setupConversations(t, client, server, cb, cb, false)
step, err := runFullAuthFlow(clientConv, serverConv)
assertFinishedSuccessfully(t, step, err)
})
}
}
func TestChannelBinding_Success_ClientBindingNotRequired(t *testing.T) {
serverCB := ChannelBinding{Type: ChannelBindingTLSExporter, Data: []byte("test-data")}
client, server := setupClientServer(t)
clientConv, serverConv := setupConversations(t, client, server, ChannelBinding{}, serverCB, false)
step, err := runFullAuthFlow(clientConv, serverConv)
assertFinishedSuccessfully(t, step, err)
}
func TestChannelBinding_Failure_UnsupportedType(t *testing.T) {
client, server := setupClientServer(t)
// Run authentication conversation - client with tls-exporter, server with tls-server-end-point
clientCB := ChannelBinding{
Type: ChannelBindingTLSExporter,
Data: []byte("test-data"),
}
serverCB := ChannelBinding{
Type: ChannelBindingTLSServerEndpoint,
Data: []byte("test-data"),
}
clientConv, serverConv := setupConversations(t, client, server, clientCB, serverCB, false)
// Server should reject the unsupported channel binding type, reporting both types seen.
step, err := runFullAuthFlow(clientConv, serverConv)
assertErrorAtStep(t, step, err, stepServerFirst, "tls-exporter", "tls-server-end-point")
}
func TestChannelBinding_Failure_DataMismatch(t *testing.T) {
client, server := setupClientServer(t)
// Run authentication conversation with mismatched channel binding
clientCB := ChannelBinding{
Type: ChannelBindingTLSExporter,
Data: []byte("client-data"),
}
serverCB := ChannelBinding{
Type: ChannelBindingTLSExporter,
Data: []byte("server-data"),
}
clientConv, serverConv := setupConversations(t, client, server, clientCB, serverCB, false)
step, err := runFullAuthFlow(clientConv, serverConv)
assertErrorAtStep(t, step, err, stepServerFinal, "channel binding mismatch")
}
func TestChannelBinding_Failure_Malformed(t *testing.T) {
client, server := setupClientServer(t)
cbData := []byte("test-cb-data")
cb := NewTLSUniqueBinding(cbData)
mockproof := base64.StdEncoding.EncodeToString([]byte("mock-proof"))
t.Run("Invalid base64 in c attribute", func(t *testing.T) {
serverConv, nonce, _ := setupForClientFinal(t, client, server, cb)
// Construct malformed message with invalid base64
clientFinal := fmt.Sprintf("c=not-valid-base64!!!,r=%s,p=%s", nonce, mockproof)
_, err := serverConv.Step(clientFinal)
assertErrorContains(t, err, "illegal base64 data")
})
t.Run("Truncated channel binding data", func(t *testing.T) {
serverConv, nonce, gs2Header := setupForClientFinal(t, client, server, cb)
// Use helper to build valid message structure, but with truncated data
clientFinal := buildClientFinal(nonce, gs2Header, cbData[:2], mockproof)
_, err := serverConv.Step(clientFinal)
assertErrorContains(t, err, "channel binding mismatch")
})
}
func TestChannelBinding_Failure_ServerDoesntSupportBinding(t *testing.T) {
client, server := setupClientServer(t)
// Run authentication conversation - client with channel binding, server without
clientCB := ChannelBinding{
Type: ChannelBindingTLSExporter,
Data: []byte("test-data"),
}
clientConv, serverConv := setupConversations(t, client, server, clientCB, ChannelBinding{}, false)
// Server should reject the client's channel binding request
step, err := runFullAuthFlow(clientConv, serverConv)
assertErrorAtStep(t, step, err, stepServerFirst, "client requires channel binding")
}
func TestChannelBinding_Failure_BindingRequired(t *testing.T) {
client, server := setupClientServer(t)
// Run authentication conversation - client without channel binding, server requires it
serverCB := ChannelBinding{
Type: ChannelBindingTLSExporter,
Data: []byte("test-data"),
}
clientConv, serverConv := setupConversations(t, client, server, ChannelBinding{}, serverCB, true)
// Server should reject due to channel binding being required at server first step
step, err := runFullAuthFlow(clientConv, serverConv)
assertErrorAtStep(t, step, err, stepServerFirst, "server requires channel binding")
}
func TestChannelBinding_Failure_RejectDowngrade(t *testing.T) {
client, server := setupClientServer(t)
// Server with optional channel binding, client thinks server does not have
// channel binding but advertises that client supports it.
serverCB := ChannelBinding{
Type: ChannelBindingTLSExporter,
Data: []byte("test-data"),
}
serverConv := server.NewConversationWithChannelBinding(serverCB)
clientConv := client.NewConversationAdvertisingChannelBinding()
step, err := runFullAuthFlow(clientConv, serverConv)
assertErrorAtStep(t, step, err, stepServerFirst, "downgrade attack detected")
}