forked from segmentio/kafka-go
/
scram.go
81 lines (65 loc) · 1.75 KB
/
scram.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
package scram
import (
"context"
"crypto/sha256"
"crypto/sha512"
"hash"
"github.com/segmentio/kafka-go/sasl"
"github.com/xdg/scram"
)
// Algorithm determines the hash function used by SCRAM to protect the user's
// credentials.
type Algorithm interface {
// Name returns the algorithm's name, e.g. "SCRAM-SHA-256"
Name() string
// Hash returns a new hash.Hash.
Hash() hash.Hash
}
type sha256Algo struct{}
func (sha256Algo) Name() string {
return "SCRAM-SHA-256"
}
func (sha256Algo) Hash() hash.Hash {
return sha256.New()
}
type sha512Algo struct{}
func (sha512Algo) Name() string {
return "SCRAM-SHA-512"
}
func (sha512Algo) Hash() hash.Hash {
return sha512.New()
}
var (
SHA256 Algorithm = sha256Algo{}
SHA512 Algorithm = sha512Algo{}
)
type mechanism struct {
algo Algorithm
client *scram.Client
convo *scram.ClientConversation
}
// Mechanism returns a new sasl.Mechanism that will use SCRAM with the provided
// Algorithm to securely transmit the provided credentials to Kafka.
//
// SCRAM-SHA-256 and SCRAM-SHA-512 were added to Kafka in 0.10.2.0. These
// mechanisms will not work with older versions.
func Mechanism(algo Algorithm, username, password string) (sasl.Mechanism, error) {
hashGen := scram.HashGeneratorFcn(algo.Hash)
client, err := hashGen.NewClient(username, password, "")
if err != nil {
return nil, err
}
return &mechanism{
algo: algo,
client: client,
}, nil
}
func (m *mechanism) Start(ctx context.Context) (string, []byte, error) {
m.convo = m.client.NewConversation()
str, err := m.convo.Step("")
return m.algo.Name(), []byte(str), err
}
func (m *mechanism) Next(ctx context.Context, challenge []byte) (bool, []byte, error) {
str, err := m.convo.Step(string(challenge))
return m.convo.Done(), []byte(str), err
}