-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathauth.go
363 lines (310 loc) · 9.25 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
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
package main
import (
"bufio"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
"go.starlark.net/starlark"
)
// HTTP proxy authentication.
func (c *config) readPasswordFile(filename string) error {
f, err := os.Open(filename)
if err != nil {
return fmt.Errorf("could not open %s: %s", filename, err)
}
defer f.Close()
cr := newConfigReader(f)
for {
line, err := cr.ReadLine()
if err != nil {
break
}
words := strings.Fields(line)
switch len(words) {
case 2:
c.Passwords[words[0]] = words[1]
case 3:
user, pass, portStr := words[0], words[1], words[2]
c.Passwords[user] = pass
port, err := strconv.Atoi(portStr)
if err != nil {
log.Printf("invalid port number %q in password file line: %s", portStr, line)
continue
}
c.CustomPorts[user] = customPortInfo{
Port: port,
}
c.UserForPort[port] = user
case 4:
user, pass, portStr, clientPlatform := words[0], words[1], words[2], words[3]
c.Passwords[user] = pass
port, err := strconv.Atoi(portStr)
if err != nil {
log.Printf("invalid port number %q in password file line: %s", portStr, line)
continue
}
c.CustomPorts[user] = customPortInfo{
Port: port,
ClientPlatform: clientPlatform,
}
c.UserForPort[port] = user
case 5:
user, pass, portStr, clientPlatform, networks := words[0], words[1], words[2], words[3], words[4]
c.Passwords[user] = pass
port, err := strconv.Atoi(portStr)
if err != nil {
log.Printf("invalid port number %q in password file line: %s", portStr, line)
continue
}
c.CustomPorts[user] = customPortInfo{
Port: port,
ClientPlatform: clientPlatform,
ExpectedNetworks: strings.Split(networks, ","),
}
c.UserForPort[port] = user
default:
log.Println("malformed line in password file:", line)
}
}
return nil
}
func send407(w http.ResponseWriter) {
c := getConfig()
w.Header().Set("Proxy-Authenticate", "Basic realm="+c.AuthRealm)
http.Error(w, "Proxy authentication required", http.StatusProxyAuthRequired)
}
// ProxyCredentials returns the username and password from r's
// Proxy-Authorization header.
func ProxyCredentials(r *http.Request) (user, pass string, ok bool) {
auth := r.Header.Get("Proxy-Authorization")
if auth == "" || !strings.HasPrefix(auth, "Basic ") {
return "", "", false
}
return decodeBase64Credentials(strings.TrimPrefix(auth, "Basic "))
}
// decodeBase64Credentials decodes a base64-encoded username:password pair
// such as those used in HTTP basic authentication.
func decodeBase64Credentials(auth string) (user, pass string, ok bool) {
auth = strings.TrimSpace(auth)
enc := base64.StdEncoding
buf := make([]byte, enc.DecodedLen(len(auth)))
n, err := enc.Decode(buf, []byte(auth))
if err != nil {
return "", "", false
}
auth = string(buf[:n])
colon := strings.Index(auth, ":")
if colon == -1 {
return "", "", false
}
return auth[:colon], auth[colon+1:], true
}
// ValidCredentials returns whether user and password are a valid combination.
func (conf *config) ValidCredentials(user, password string) bool {
conf.PasswordLock.RLock()
ok := password == conf.Passwords[user] && password != ""
conf.PasswordLock.RUnlock()
if ok {
return true
}
for _, a := range conf.Authenticators {
if a(user, password) {
if _, ok := conf.Passwords[user]; !ok {
// Cache the password for later use.
conf.PasswordLock.Lock()
conf.Passwords[user] = password
conf.PasswordLock.Unlock()
}
return true
}
}
return false
}
func (conf *config) addAuthenticator(path string) error {
conf.Authenticators = append(conf.Authenticators, func(user, password string) bool {
cmd := exec.Command(path, user, password)
err := cmd.Run()
return err == nil
})
return nil
}
func (conf *config) addHTTPAuthenticator(endpoint string) error {
var client http.Client
client.Transport = transportWithExtraRootCerts
conf.Authenticators = append(conf.Authenticators, func(user, password string) bool {
formData := make(url.Values)
formData.Set("username", user)
formData.Set("password", password)
resp, err := client.Post(endpoint, "application/x-www-form-urlencoded", strings.NewReader(formData.Encode()))
if err != nil {
log.Printf("Error communicating with authentication API endpoint %s: %v", endpoint, err)
return false
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return false
}
var userInfo struct {
DeviceGroups []string `json:"device_groups"`
}
if err := json.NewDecoder(resp.Body).Decode(&userInfo); err == nil {
conf.ACLs.ExternalDGLock.Lock()
if conf.ACLs.ExternalDeviceGroups == nil {
conf.ACLs.ExternalDeviceGroups = map[string][]string{}
}
conf.ACLs.ExternalDeviceGroups[user] = userInfo.DeviceGroups
conf.ACLs.ExternalDGLock.Unlock()
} else {
log.Printf("Error decoding authenticator-api response for %s: %v", user, err)
}
return true
})
return nil
}
func (c *config) loadIPToUser(filename string) error {
f, err := os.Open(filename)
if err != nil {
return fmt.Errorf("could not open %s: %s\n", filename, err)
}
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
line := strings.TrimSpace(s.Text())
if line == "" || line[0] == '#' {
continue
}
fields := strings.Fields(line)
if len(fields) > 2 && strings.HasPrefix(fields[2], "#") {
fields = fields[:2]
}
if len(fields) != 2 {
log.Printf("Syntax error in %s: %q", filename, line)
continue
}
c.IPToUser[fields[0]] = fields[1]
}
return s.Err()
}
// UserInfo represents a user who is attempting to authenticate with the proxy.
type UserInfo struct {
ClientIP string
AuthenticatedUser string
Request *http.Request
frozen bool
}
// Authenticate uses the information from u.Request to attempt to authenticate the user.
// It fills in ClientIP, and (if the authentication is successful) AuthenticatedUser.
func (u *UserInfo) Authenticate(p *perUserProxy) {
u.ClientIP = u.Request.RemoteAddr
if host, _, err := net.SplitHostPort(u.ClientIP); err == nil {
u.ClientIP = host
}
if u.Request.Header.Get("Proxy-Authorization") != "" {
user, pass, ok := ProxyCredentials(u.Request)
if ok {
if getConfig().ValidCredentials(user, pass) {
u.AuthenticatedUser = user
} else {
logAuthEvent("proxy-auth-header", "invalid", u.Request.RemoteAddr, 0, user, pass, "", "", u.Request, "Incorrect username or password")
}
} else {
logAuthEvent("proxy-auth-header", "invalid", u.Request.RemoteAddr, 0, "", "", "", "", u.Request, "Invalid auth header")
}
} else if user, ok := getConfig().IPToUser[u.ClientIP]; ok {
u.AuthenticatedUser = user
}
if p != nil && u.AuthenticatedUser == "" {
configuredUser := getConfig().UserForPort[p.Port]
expectedNetwork := false
ip := net.ParseIP(u.ClientIP)
p.expectedNetLock.RLock()
expectedPlatform := p.ClientPlatform
for _, nw := range p.expectedIPBlocks {
if nw.Contains(ip) {
expectedNetwork = true
break
}
}
p.expectedNetLock.RUnlock()
domain := rdnsDomain(u.ClientIP)
if !expectedNetwork && domain != "" {
p.expectedNetLock.RLock()
expectedNetwork = p.expectedDomains[domain]
p.expectedNetLock.RUnlock()
}
if expectedNetwork {
derivedPlatform := platform(u.Request.Header.Get("User-Agent"))
if expectedPlatform != "" && derivedPlatform == expectedPlatform || darwinPlatforms[expectedPlatform] && derivedPlatform == "Darwin" {
logAuthEvent("expected-network", "correct", u.ClientIP, p.Port, configuredUser, "", derivedPlatform, domain, u.Request, "Authenticated via expected platform and network")
u.AuthenticatedUser = configuredUser
}
}
}
if p == nil {
callStarlarkFunctions("authenticate", u, starlark.None)
} else {
callStarlarkFunctions("authenticate", u, p)
}
}
func (u *UserInfo) String() string {
return fmt.Sprintf("UserInfo(%s)", u.Request.RemoteAddr)
}
func (u *UserInfo) Type() string {
return "UserInfo"
}
func (u *UserInfo) Freeze() {
if !u.frozen {
u.frozen = true
}
}
func (u *UserInfo) Truth() starlark.Bool {
return starlark.True
}
func (u *UserInfo) Hash() (uint32, error) {
return 0, errors.New("unhashable type: UserInfo")
}
var userInfoAttrNames = []string{"authenticated_user", "ip", "user_agent", "platform", "proxy_auth"}
func (u *UserInfo) AttrNames() []string {
return userInfoAttrNames
}
func (u *UserInfo) Attr(name string) (starlark.Value, error) {
switch name {
case "authenticated_user":
return starlark.String(u.AuthenticatedUser), nil
case "ip":
return starlark.String(u.ClientIP), nil
case "user_agent":
return starlark.String(u.Request.Header.Get("User-Agent")), nil
case "platform":
return starlark.String(platform(u.Request.Header.Get("User-Agent"))), nil
case "proxy_auth":
user, pass, ok := ProxyCredentials(u.Request)
if ok {
return starlark.Tuple{starlark.String(user), starlark.String(pass)}, nil
} else {
return starlark.None, nil
}
default:
return nil, nil
}
}
func (u *UserInfo) SetField(name string, val starlark.Value) error {
if u.frozen {
return errors.New("can't set a field of a frozen object")
}
switch name {
case "authenticated_user":
return assignStarlarkString(&u.AuthenticatedUser, val)
default:
return starlark.NoSuchAttrError(fmt.Sprintf("can't assign to .%s field of UserInfo", name))
}
}