forked from caddyserver/forwardproxy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathacl.go
96 lines (83 loc) · 1.99 KB
/
acl.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
package forwardproxy
import (
"errors"
"net"
"strings"
)
type aclDecision uint8
const (
aclDecisionAllow = iota
aclDecisionDeny
aclDecisionNoMatch
)
type aclRule interface {
tryMatch(ip net.IP, domain string) aclDecision
}
type aclIPRule struct {
net net.IPNet
allow bool
}
func (a *aclIPRule) tryMatch(ip net.IP, domain string) aclDecision {
if !a.net.Contains(ip) {
return aclDecisionNoMatch
}
if a.allow {
return aclDecisionAllow
}
return aclDecisionDeny
}
type aclDomainRule struct {
domain string
subdomainsAllowed bool
allow bool
}
func (a *aclDomainRule) tryMatch(ip net.IP, domain string) aclDecision {
if strings.HasSuffix(domain, ".") {
domain = domain[:len(domain)-1]
}
if domain == a.domain ||
a.subdomainsAllowed && strings.HasSuffix(domain, "."+a.domain) {
if a.allow {
return aclDecisionAllow
}
return aclDecisionDeny
}
return aclDecisionNoMatch
}
type aclAllRule struct {
allow bool
}
func (a *aclAllRule) tryMatch(ip net.IP, domain string) aclDecision {
if a.allow {
return aclDecisionAllow
}
return aclDecisionDeny
}
func newAclRule(ruleSubject string, allow bool) (aclRule, error) {
if ruleSubject == "all" {
return &aclAllRule{allow: allow}, nil
}
_, ipNet, err := net.ParseCIDR(ruleSubject)
if err != nil {
ip := net.ParseIP(ruleSubject)
// support specifying just an IP
if ip.To4() != nil {
_, ipNet, err = net.ParseCIDR(ruleSubject + "/32")
} else if ip.To16() != nil {
_, ipNet, err = net.ParseCIDR(ruleSubject + "/128")
}
}
if err == nil {
return &aclIPRule{net: *ipNet, allow: allow}, nil
}
subdomainsAllowed := false
if strings.HasPrefix(ruleSubject, `*.`) {
subdomainsAllowed = true
ruleSubject = ruleSubject[2:]
}
err = isValidDomainLite(ruleSubject)
if err != nil {
return nil, errors.New(ruleSubject + " could not be parsed as either IP, IP network, or domain: " + err.Error())
}
return &aclDomainRule{domain: ruleSubject, subdomainsAllowed: subdomainsAllowed, allow: allow}, nil
}