-
Notifications
You must be signed in to change notification settings - Fork 37
/
pac.go
441 lines (384 loc) · 11.3 KB
/
pac.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
package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/netip"
"strconv"
"strings"
"sync"
"go.starlark.net/starlark"
"golang.org/x/net/publicsuffix"
)
// handlePACFile serves an automatically-generated PAC (Proxy Auto-Config) file
// pointing to this proxy server.
func handlePACFile(w http.ResponseWriter, r *http.Request) {
proxyAddr := r.Header.Get("X-Forwarded-Host")
if len(proxyAddr) == 0 {
proxyAddr = r.Host
}
conf := getConfig()
if a := r.FormValue("a"); a != "" {
if user, pass, ok := decodeBase64Credentials(a); ok {
if conf.ValidCredentials(user, pass) {
port := conf.CustomPorts[user].Port
customPortLock.RLock()
p := customPorts[port]
customPortLock.RUnlock()
if p != nil {
remoteAddr := clientIP((r))
if remoteAddr == "" {
logAuthEvent("pac-url-param", "correct", remoteAddr, p.Port, user, "", "", "", r, "Is this request coming via a proxy that does not set X-Forwarded-For?")
} else {
p.AllowIP(remoteAddr)
logAuthEvent("pac-url-param", "correct", remoteAddr, p.Port, user, "", "", "", r, "Authenticated via query param in PAC URL")
}
proxyHost, _, err := net.SplitHostPort(proxyAddr)
if err == nil {
proxyAddr = net.JoinHostPort(proxyHost, strconv.Itoa(p.Port))
}
}
}
}
}
pacTemplate := conf.PACTemplate
if pacTemplate == "" {
pacTemplate = standardPACTemplate
}
w.Header().Set("Content-Type", "application/x-ns-proxy-autoconfig")
w.Header().Set("Content-Disposition", "attachment; filename=proxy.pac")
if strings.Contains(pacTemplate, "%s") {
fmt.Fprintf(w, pacTemplate, proxyAddr)
} else {
fmt.Fprint(w, pacTemplate)
}
}
// clientIP returns the client's IP address—either the first public IP address
// from the X-Forwarded-For headers, or the address from r.RemoteAddr.
func clientIP(r *http.Request) string {
for _, xff := range r.Header.Values("X-Forwarded-For") {
for _, addr := range strings.Split(xff, ",") {
addr = strings.TrimSpace(addr)
a, err := netip.ParseAddr(addr)
if err == nil && !a.IsLoopback() && !a.IsPrivate() {
return addr
}
}
}
client := r.RemoteAddr
host, _, err := net.SplitHostPort(client)
if err == nil {
a, err := netip.ParseAddr(host)
if err == nil && !a.IsLoopback() {
return host
}
return ""
}
return client
}
const standardPACTemplate = `function FindProxyForURL(url, host) {
if (
shExpMatch(url, "ftp:*") ||
host == "localhost" ||
isInNet(host, "127.0.0.0", "255.0.0.0") ||
isInNet(host, "10.0.0.0", "255.0.0.0") ||
isInNet(host, "172.16.0.0", "255.240.0.0") ||
isInNet(host, "192.168.0.0", "255.255.0.0")
) {
return "DIRECT";
}
return "PROXY %s";
}`
func (c *config) loadPACTemplate(filename string) error {
t, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
c.PACTemplate = string(t)
return nil
}
type perUserProxy struct {
Port int
expectedDomains map[string]bool
expectedIPBlocks []*net.IPNet
ClientPlatform string
expectedNetLock sync.RWMutex
}
func (p *perUserProxy) addExpectedNetwork(network string) {
p.expectedNetLock.Lock()
defer p.expectedNetLock.Unlock()
if _, nw, err := net.ParseCIDR(network); err == nil {
p.expectedIPBlocks = append(p.expectedIPBlocks, nw)
} else if ip := net.ParseIP(network); ip != nil {
if ip4 := ip.To4(); ip4 != nil {
p.expectedIPBlocks = append(p.expectedIPBlocks, &net.IPNet{IP: ip4, Mask: net.CIDRMask(32, 32)})
} else {
p.expectedIPBlocks = append(p.expectedIPBlocks, &net.IPNet{IP: ip, Mask: net.CIDRMask(128, 128)})
}
} else {
domain, err := publicsuffix.EffectiveTLDPlusOne(network)
if err != nil {
domain = network
}
p.expectedDomains[domain] = true
}
}
func (c *config) newPerUserProxy(user string, portInfo customPortInfo) (*perUserProxy, error) {
p := &perUserProxy{
Port: portInfo.Port,
ClientPlatform: portInfo.ClientPlatform,
expectedDomains: map[string]bool{},
}
for _, network := range portInfo.ExpectedNetworks {
p.addExpectedNetwork(network)
}
customPortLock.Lock()
customPorts[portInfo.Port] = p
customPortLock.Unlock()
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", portInfo.Port))
if err != nil {
return nil, err
}
listener = tcpKeepAliveListener{listener.(*net.TCPListener)}
go func() {
<-shutdownChan
listener.Close()
}()
server := http.Server{
Handler: p,
IdleTimeout: c.CloseIdleConnections,
}
go server.Serve(listener)
log.Printf("opened per-user listener for %s on port %d", user, portInfo.Port)
return p, nil
}
func (p *perUserProxy) AllowIP(ip string) {
user, ok := getConfig().UserForPort[p.Port]
if !ok {
return
}
authCacheLock.Lock()
usersForPort := authCache[p.Port]
if usersForPort == nil {
usersForPort = make(map[string]string)
authCache[p.Port] = usersForPort
}
usersForPort[ip] = user
authCacheLock.Unlock()
log.Printf("Added IP address %s, authenticated as %s, on port %d", ip, user, p.Port)
domain := rdnsDomain(ip)
if domain != "" {
p.expectedNetLock.Lock()
alreadyExpected := p.expectedDomains[domain]
if !alreadyExpected {
p.expectedDomains[domain] = true
}
p.expectedNetLock.Unlock()
if !alreadyExpected {
log.Printf("Added %s to the list of expected domains on port %d", domain, p.Port)
}
}
}
// rdnsDomain returns the base domain name of ip's reverse-DNS hostname (or the
// empty string if it is unavailable).
func rdnsDomain(ip string) string {
var host string
names, err := net.LookupAddr(ip)
if err == nil && len(names) > 0 {
host = names[0]
}
if host == "" {
return ""
}
host = strings.TrimSuffix(host, ".")
domain, err := publicsuffix.EffectiveTLDPlusOne(host)
if err != nil {
return host
}
return domain
}
func (p *perUserProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
activeConnections.Add(1)
defer activeConnections.Done()
configuredUser := getConfig().UserForPort[p.Port]
handler := proxyHandler{
localPort: p.Port,
}
host, _, _ := net.SplitHostPort(r.RemoteAddr)
authCacheLock.RLock()
cachedUser := authCache[p.Port][host]
authCacheLock.RUnlock()
if cachedUser == configuredUser {
handler.ServeHTTPAuthenticated(w, r, host, configuredUser)
return
}
// This client's IP address is not pre-authorized for this port, but
// maybe it sent credentials and we can authorize it now.
ui := &UserInfo{
Request: r,
}
ui.Authenticate(p)
if ui.AuthenticatedUser != "" && ui.AuthenticatedUser != configuredUser {
logAuthEvent("custom-port", "invalid", r.RemoteAddr, p.Port, ui.AuthenticatedUser, "", p.ClientPlatform, "", r, fmt.Sprint("Expected username ", configuredUser))
handler.ServeHTTPAuthenticated(w, r, host, "")
return
}
if ui.AuthenticatedUser != "" {
p.AllowIP(host)
logAuthEvent("proxy-auth-header", "correct", r.RemoteAddr, p.Port, ui.AuthenticatedUser, "", p.ClientPlatform, "", r, "Authenticated via basic credentials in http auth header")
}
handler.ServeHTTPAuthenticated(w, r, host, ui.AuthenticatedUser)
}
var customPorts = make(map[int]*perUserProxy)
var customPortLock sync.RWMutex
func (c *config) openPerUserPorts() {
for user, portInfo := range c.CustomPorts {
customPortLock.RLock()
p := customPorts[portInfo.Port]
customPortLock.RUnlock()
if p == nil {
_, err := c.newPerUserProxy(user, portInfo)
if err != nil {
log.Printf("error opening per-user listener for %s: %v", user, err)
}
} else {
p.expectedNetLock.Lock()
p.ClientPlatform = portInfo.ClientPlatform
p.expectedIPBlocks = p.expectedIPBlocks[:0]
p.expectedNetLock.Unlock()
for _, network := range portInfo.ExpectedNetworks {
p.addExpectedNetwork(network)
}
}
}
}
type portListEntry struct {
User string
Port int
Platform string
AuthenticatedClients []string
ExpectedNetworks []string
}
func handlePerUserPortList(w http.ResponseWriter, r *http.Request) {
entries := map[string]*portListEntry{}
conf := getConfig()
customPortLock.RLock()
for _, p := range customPorts {
var networks []string
p.expectedNetLock.RLock()
for d := range p.expectedDomains {
networks = append(networks, d)
}
for _, nw := range p.expectedIPBlocks {
networks = append(networks, nw.String())
}
clientPlatform := p.ClientPlatform
p.expectedNetLock.RUnlock()
user, ok := conf.UserForPort[p.Port]
if !ok {
continue
}
var authenticatedClients []string
authCacheLock.RLock()
for ip, u := range authCache[p.Port] {
if u == user {
authenticatedClients = append(authenticatedClients, ip)
}
}
authCacheLock.RUnlock()
entries[user] = &portListEntry{
User: user,
Port: p.Port,
Platform: clientPlatform,
ExpectedNetworks: networks,
AuthenticatedClients: authenticatedClients,
}
}
customPortLock.RUnlock()
var data []*portListEntry
for _, e := range entries {
data = append(data, e)
}
ServeJSON(w, r, data)
}
func handlePerUserAuthenticate(w http.ResponseWriter, r *http.Request) {
user := r.FormValue("user")
if user == "" {
http.Error(w, `You must specify which user to authenticate with the "user" form parameter.`, 400)
return
}
conf := getConfig()
port := conf.CustomPorts[user].Port
if port == 0 {
http.Error(w, user+" does not have a per-user proxy port set up.", 500)
return
}
customPortLock.RLock()
p := customPorts[port]
customPortLock.RUnlock()
if p == nil {
http.Error(w, user+" does not have a per-user proxy port open.", 500)
return
}
ip := r.FormValue("ip")
if ip == "" {
http.Error(w, `You must specify the client IP address with the "ip" form parameter.`, 400)
return
}
p.AllowIP(ip)
fmt.Fprintf(w, "Added authenticated IP address: (ip=%s, user=%s, port=%d)", ip, user, port)
logAuthEvent("api-request", "correct", ip, port, user, "", "", "", r, "Authenticated via API call on behalf of device")
}
// authCache maps from local port and remote IP address to the authenticated username.
var authCache = map[int]map[string]string{}
var authCacheLock sync.RWMutex
// String is needed to implement starlark.Value.
func (p *perUserProxy) String() string {
return fmt.Sprintf("CustomPort(%d)", p.Port)
}
// Type is needed to implement starlark.Value.
func (p *perUserProxy) Type() string {
return "CustomPort"
}
// Freeze is needed to implement starlark.Value.
func (p *perUserProxy) Freeze() {}
// Hash is needed to implement starlark.Value.
func (p *perUserProxy) Hash() (uint32, error) {
return 0, errors.New("unhashable type: CustomPort")
}
// Truth is needed to implement starlark.Value.
func (p *perUserProxy) Truth() starlark.Bool {
return starlark.True
}
var customPortAttrNames = []string{"port", "user", "platform", "expected_networks"}
func (p *perUserProxy) AttrNames() []string {
return customPortAttrNames
}
func (p *perUserProxy) Attr(name string) (starlark.Value, error) {
switch name {
case "port":
return starlark.MakeInt(p.Port), nil
case "user":
return starlark.String(getConfig().UserForPort[p.Port]), nil
case "platform":
p.expectedNetLock.RLock()
defer p.expectedNetLock.RUnlock()
return starlark.String(p.ClientPlatform), nil
case "expected_networks":
p.expectedNetLock.RLock()
defer p.expectedNetLock.RUnlock()
var networks starlark.Tuple
for d := range p.expectedDomains {
networks = append(networks, starlark.String(d))
}
for _, b := range p.expectedIPBlocks {
networks = append(networks, starlark.String(b.String()))
}
return networks, nil
default:
return nil, nil
}
}