-
Notifications
You must be signed in to change notification settings - Fork 10
/
auth.go
210 lines (173 loc) · 6.06 KB
/
auth.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
package pgsrv
import (
"bytes"
"crypto/md5"
"crypto/rand"
"fmt"
"github.com/panoplyio/pgsrv/protocol"
)
const errExpectedPassword = "expected password response, got message type %q"
const errWrongPassword = "password does not match for user \"%s\""
// authenticator interface defines objects able to perform user authentication
// that happens at the very beginning of every session.
type authenticator interface {
// authenticate accepts a protocol.MessageReadWriter instance and a map of args that describe
// the current session. It returns no error if the authentication succeeds,
// or an error if something fails.
//
// Authentication errors as well as welcome messages are sent by this function,
// so there is no need for the caller to send these. It is caller's responsibility
// though to terminate the session in case that an error is returned.
authenticate(rw protocol.MessageReadWriter, args map[string]interface{}) error
}
// noPasswordAuthenticator responds with auth OK immediately.
type noPasswordAuthenticator struct{}
func (np *noPasswordAuthenticator) authenticate(rw protocol.MessageReadWriter, args map[string]interface{}) error {
return rw.Write(authOKMsg())
}
// AuthType represents various types of authentication
type AuthType string
const (
// Trust is an auth type for trusted networks, it does not require a password
Trust AuthType = "trust"
// MD5 is an auth type where authentication uses md5 hashes with random salt
MD5 AuthType = "md5"
// Plain is an auth type where password is sent as plain text over network
Plain AuthType = "plain"
)
// PasswordProvider describes objects that are able to provide a password given a user name.
type PasswordProvider interface {
Type() AuthType
GetPassword(user string) ([]byte, error)
}
// constantPasswordProvider is a password provider that always returns the same password,
// which it is given during the initialization.
type constantPasswordProvider struct {
password []byte
}
func (cpp *constantPasswordProvider) Type() AuthType {
return Plain
}
func (cpp *constantPasswordProvider) GetPassword(user string) ([]byte, error) {
return cpp.password, nil
}
// md5ConstantPasswordProvider is a password provider that returns md5 hash of a given
// username and a constant password as md5(concat(password, user)).
type md5ConstantPasswordProvider struct {
password []byte
}
// Type implements PasswordProvider.
func (cpp *md5ConstantPasswordProvider) Type() AuthType {
return MD5
}
func (cpp *md5ConstantPasswordProvider) GetPassword(user string) ([]byte, error) {
pu := append(cpp.password, []byte(user)...)
puHash := md5.Sum(pu)
return puHash[:], nil
}
// clearTextAuthenticator requests and accepts a clear text password.
// It is not recommended to use it for security reasons.
//
// It requires a passwordProvider implementation to verify that the provided password is correct.
type clearTextAuthenticator struct {
pp PasswordProvider
}
func (a *clearTextAuthenticator) authenticate(rw protocol.MessageReadWriter, args map[string]interface{}) error {
// AuthenticationClearText
passwordRequest := protocol.Message{
'R',
0, 0, 0, 8, // length
0, 0, 0, 3, // clear text auth type
}
err := rw.Write(passwordRequest)
if err != nil {
return err
}
m, err := rw.Read()
if err != nil {
return err
}
if m.Type() != 'p' {
err = fmt.Errorf(errExpectedPassword, m.Type())
err = WithSeverity(fromErr(err), fatalSeverity)
rw.Write(protocol.ErrorResponse(err))
return err
}
user := args["user"].(string)
expectedPassword, err := a.pp.GetPassword(user)
actualPassword := extractPassword(m)
if !bytes.Equal(expectedPassword, actualPassword) {
err = fmt.Errorf(errWrongPassword, user)
err = WithSeverity(fromErr(err), fatalSeverity)
rw.Write(protocol.ErrorResponse(err))
return err
}
return rw.Write(authOKMsg())
}
// md5Authenticator requests and accepts an MD5 hashed password from the client.
//
// It requires a passwordProvider implementation to verify that the provided password is correct.
type md5Authenticator struct {
pp PasswordProvider
}
func (a *md5Authenticator) authenticate(rw protocol.MessageReadWriter, args map[string]interface{}) error {
// AuthenticationMD5Password
passwordRequest := protocol.Message{
'R',
0, 0, 0, 12, // length
0, 0, 0, 5, // md5 auth type
}
salt := getRandomSalt()
passwordRequest = append(passwordRequest, salt...)
err := rw.Write(passwordRequest)
if err != nil {
return err
}
m, err := rw.Read()
if err != nil {
return err
}
if m.Type() != 'p' {
err = fmt.Errorf(errExpectedPassword, m.Type())
err = WithSeverity(fromErr(err), fatalSeverity)
rw.Write(protocol.ErrorResponse(err))
return err
}
user := args["user"].(string)
storedHash, err := a.pp.GetPassword(user)
expectedHash := hashWithSalt(storedHash, salt)
actualHash := extractPassword(m)
if !bytes.Equal(expectedHash, actualHash) {
err = fmt.Errorf(errWrongPassword, user)
err = WithSeverity(fromErr(err), fatalSeverity)
rw.Write(protocol.ErrorResponse(err))
return err
}
return rw.Write(authOKMsg())
}
// authOKMsg returns a message that indicates that the client is now authenticated.
func authOKMsg() protocol.Message {
return []byte{'R', 0, 0, 0, 8, 0, 0, 0, 0}
}
// getRandomSalt returns a cryptographically secure random slice of 4 bytes.
func getRandomSalt() []byte {
salt := make([]byte, 4)
rand.Read(salt)
return salt
}
// extractPassword extracts the password from a provided 'p' message.
// It assumes that the message is valid.
func extractPassword(m protocol.Message) []byte {
// password starts after the size (4 bytes) and lasts until null-terminator
return m[5 : len(m)-1]
}
// hashWithSalt salts the provided md5 hash and hashes the result using md5.
// The provided hash must be md5(concat(password, username))
func hashWithSalt(hash, salt []byte) []byte {
// concat('md5', md5(concat(md5(concat(password, username)), random-salt)))
// the inner part (md5(concat())) is provided as hash argument
puHash := fmt.Sprintf("%x", hash)
puHashSalted := append([]byte(puHash), salt...)
finalHash := fmt.Sprintf("md5%x", md5.Sum(puHashSalted))
return []byte(finalHash)
}