This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip_whitelist.go
119 lines (99 loc) · 2.19 KB
/
ip_whitelist.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
// Package ip_whitelist is a micro plugin for whitelisting ip addresses
package ip_whitelist
import (
"net"
"net/http"
"strings"
"github.com/micro/cli"
"github.com/micro/go-log"
"github.com/micro/micro/plugin"
)
type whitelist struct {
cidrs map[string]*net.IPNet
ips map[string]bool
}
func (w *whitelist) Flags() []cli.Flag {
return []cli.Flag{
cli.StringFlag{
Name: "ip_whitelist",
Usage: "Comma separated whitelist of allowed IPs",
EnvVar: "IP_WHITELIST",
},
}
}
func (w *whitelist) load(ips ...string) {
for _, ip := range ips {
parts := strings.Split(ip, "/")
switch len(parts) {
// assume just an ip
case 1:
w.ips[ip] = true
case 2:
// parse cidr
_, ipnet, err := net.ParseCIDR(ip)
if err != nil {
log.Fatalf("[ip_whitelist] failed to parse %v: %v", ip, err)
}
w.cidrs[ipnet.String()] = ipnet
default:
log.Fatalf("[ip_whitelist] failed to parse %v", ip)
}
}
}
func (w *whitelist) match(ip string) bool {
// make ip
nip := net.ParseIP(ip)
// check ips
if ok := w.ips[nip.String()]; ok {
return true
}
// check cidrs
for _, cidr := range w.cidrs {
if cidr.Contains(nip) {
return true
}
}
// no match
return false
}
func (w *whitelist) Commands() []cli.Command {
return nil
}
func (w *whitelist) Handler() plugin.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
// check remote addr; if we can't parse it passes through
if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
// reject if no match
if !w.match(ip) {
http.Error(rw, "forbidden", 403)
return
}
}
// serve the request
h.ServeHTTP(rw, r)
})
}
}
func (w *whitelist) Init(ctx *cli.Context) error {
if whitelist := ctx.String("ip_whitelist"); len(whitelist) > 0 {
w.load(strings.Split(whitelist, ",")...)
}
return nil
}
func (w *whitelist) String() string {
return "ip_whitelist"
}
func NewPlugin() plugin.Plugin {
return NewIPWhitelist()
}
func NewIPWhitelist(ips ...string) plugin.Plugin {
// create plugin
w := &whitelist{
cidrs: make(map[string]*net.IPNet),
ips: make(map[string]bool),
}
// load ips
w.load(ips...)
return w
}