This repository has been archived by the owner on Feb 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ipauth.go
101 lines (81 loc) · 2.07 KB
/
ipauth.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
package network
import (
"net"
"strings"
"github.com/nats-io/nats-server/v2/server"
"github.com/sirupsen/logrus"
)
// IPAuth implements gnatsd server.Authentication interface and
// allows IP limits to be configured, connections that do not match
// the configured IP or CIDRs are not allowed to publish to the
// network targets used by clients to request actions on nodes
type IPAuth struct {
allowList []string
log *logrus.Entry
}
// Check checks and registers the incoming connection
func (a *IPAuth) Check(c server.ClientAuthentication) (verified bool) {
user := a.createUser(c)
remote := c.RemoteAddress()
if remote != nil && !a.remoteInClientAllowList(c.RemoteAddress()) {
a.setServerPermissions(user)
}
c.RegisterUser(user)
return true
}
func (a *IPAuth) setServerPermissions(user *server.User) {
user.Permissions.Subscribe = &server.SubjectPermission{
Deny: []string{
"*.reply.>",
"choria.federation.>",
"choria.lifecycle.>",
},
}
user.Permissions.Publish = &server.SubjectPermission{
Allow: []string{
">",
},
Deny: []string{
"*.broadcast.agent.>",
"*.node.>",
"choria.federation.*.federation",
},
}
}
func (a *IPAuth) remoteInClientAllowList(remote net.Addr) bool {
if len(a.allowList) == 0 {
return true
}
if remote == nil {
return false
}
host, _, err := net.SplitHostPort(remote.String())
if err != nil {
a.log.Warnf("Could not extract host from remote, not allowing access to client targets: '%s': %s", remote.String(), err)
return false
}
for _, allowed := range a.allowList {
if host == allowed {
return true
}
if strings.Contains(allowed, "/") {
_, ipnet, err := net.ParseCIDR(allowed)
if err != nil {
a.log.Warnf("Could not parse %s as a cidr: %s", allowed, err)
continue
}
if ipnet.Contains(net.ParseIP(host)) {
return true
}
}
}
return false
}
func (a *IPAuth) createUser(c server.ClientAuthentication) *server.User {
opts := c.GetOpts()
return &server.User{
Username: opts.Username,
Password: opts.Password,
Permissions: &server.Permissions{},
}
}