1 // Package netutil contains extensions to the net package.
13 log "github.com/sirupsen/logrus"
16 var lan4, lan6, special4, special6 Netlist
21 errInvalidIP = errors.New("ip is invalid")
22 errInvalidPort = errors.New("port is invalid")
26 // Lists from RFC 5735, RFC 5156,
27 // https://www.iana.org/assignments/iana-ipv4-special-registry/
28 lan4.Add("0.0.0.0/8") // "This" network
29 lan4.Add("10.0.0.0/8") // Private Use
30 lan4.Add("172.16.0.0/12") // Private Use
31 lan4.Add("192.168.0.0/16") // Private Use
32 lan6.Add("fe80::/10") // Link-Local
33 lan6.Add("fc00::/7") // Unique-Local
34 special4.Add("192.0.0.0/29") // IPv4 Service Continuity
35 special4.Add("192.0.0.9/32") // PCP Anycast
36 special4.Add("192.0.0.170/32") // NAT64/DNS64 Discovery
37 special4.Add("192.0.0.171/32") // NAT64/DNS64 Discovery
38 special4.Add("192.0.2.0/24") // TEST-NET-1
39 special4.Add("192.31.196.0/24") // AS112
40 special4.Add("192.52.193.0/24") // AMT
41 special4.Add("192.88.99.0/24") // 6to4 Relay Anycast
42 special4.Add("192.175.48.0/24") // AS112
43 special4.Add("198.18.0.0/15") // Device Benchmark Testing
44 special4.Add("198.51.100.0/24") // TEST-NET-2
45 special4.Add("203.0.113.0/24") // TEST-NET-3
46 special4.Add("255.255.255.255/32") // Limited Broadcast
48 // http://www.iana.org/assignments/iana-ipv6-special-registry/
49 special6.Add("100::/64")
50 special6.Add("2001::/32")
51 special6.Add("2001:1::1/128")
52 special6.Add("2001:2::/48")
53 special6.Add("2001:3::/32")
54 special6.Add("2001:4:112::/48")
55 special6.Add("2001:5::/32")
56 special6.Add("2001:10::/28")
57 special6.Add("2001:20::/28")
58 special6.Add("2001:db8::/32")
59 special6.Add("2002::/16")
62 // Netlist is a list of IP networks.
63 type Netlist []net.IPNet
65 // ParseNetlist parses a comma-separated list of CIDR masks.
66 // Whitespace and extra commas are ignored.
67 func ParseNetlist(s string) (*Netlist, error) {
68 ws := strings.NewReplacer(" ", "", "\n", "", "\t", "")
69 masks := strings.Split(ws.Replace(s), ",")
71 for _, mask := range masks {
75 _, n, err := net.ParseCIDR(mask)
84 // MarshalTOML implements toml.MarshalerRec.
85 func (l Netlist) MarshalTOML() interface{} {
86 list := make([]string, 0, len(l))
87 for _, net := range l {
88 list = append(list, net.String())
93 // UnmarshalTOML implements toml.UnmarshalerRec.
94 func (l *Netlist) UnmarshalTOML(fn func(interface{}) error) error {
96 if err := fn(&masks); err != nil {
99 for _, mask := range masks {
100 _, n, err := net.ParseCIDR(mask)
109 // Add parses a CIDR mask and appends it to the list. It panics for invalid masks and is
110 // intended to be used for setting up static lists.
111 func (l *Netlist) Add(cidr string) {
112 _, n, err := net.ParseCIDR(cidr)
119 // Contains reports whether the given IP is contained in the list.
120 func (l *Netlist) Contains(ip net.IP) bool {
124 for _, net := range *l {
125 if net.Contains(ip) {
132 // IsLAN reports whether an IP is a local network address.
133 func IsLAN(ip net.IP) bool {
137 if v4 := ip.To4(); v4 != nil {
138 return lan4.Contains(v4)
140 return lan6.Contains(ip)
143 // IsSpecialNetwork reports whether an IP is located in a special-use network range
144 // This includes broadcast, multicast and documentation addresses.
145 func IsSpecialNetwork(ip net.IP) bool {
146 if ip.IsMulticast() {
149 if v4 := ip.To4(); v4 != nil {
150 return special4.Contains(v4)
152 return special6.Contains(ip)
156 errInvalid = errors.New("invalid IP")
157 errUnspecified = errors.New("zero address")
158 errSpecial = errors.New("special network")
159 errLoopback = errors.New("loopback address from non-loopback host")
160 errLAN = errors.New("LAN address from WAN host")
163 // CheckRelayIP reports whether an IP relayed from the given sender IP
164 // is a valid connection target.
166 // There are four rules:
167 // - Special network addresses are never valid.
168 // - Loopback addresses are OK if relayed by a loopback host.
169 // - LAN addresses are OK if relayed by a LAN host.
170 // - All other addresses are always acceptable.
171 func CheckRelayIP(sender, addr net.IP) error {
172 if len(addr) != net.IPv4len && len(addr) != net.IPv6len {
175 if addr.IsUnspecified() {
176 return errUnspecified
178 if IsSpecialNetwork(addr) {
181 if addr.IsLoopback() && !sender.IsLoopback() {
184 if IsLAN(addr) && !IsLAN(sender) {
190 // SameNet reports whether two IP addresses have an equal prefix of the given bit length.
191 func SameNet(bits uint, ip, other net.IP) bool {
192 ip4, other4 := ip.To4(), other.To4()
194 case (ip4 == nil) != (other4 == nil):
197 return sameNet(bits, ip4, other4)
199 return sameNet(bits, ip.To16(), other.To16())
203 func sameNet(bits uint, ip, other net.IP) bool {
205 mask := ^byte(0xFF >> (bits % 8))
206 if mask != 0 && nb < len(ip) && ip[nb]&mask != other[nb]&mask {
209 return nb <= len(ip) && bytes.Equal(ip[:nb], other[:nb])
212 // DistinctNetSet tracks IPs, ensuring that at most N of them
213 // fall into the same network range.
214 type DistinctNetSet struct {
215 Subnet uint // number of common prefix bits
216 Limit uint // maximum number of IPs in each subnet
218 members map[string]uint
222 // Add adds an IP address to the set. It returns false (and doesn't add the IP) if the
223 // number of existing IPs in the defined range exceeds the limit.
224 func (s *DistinctNetSet) Add(ip net.IP) bool {
226 n := s.members[string(key)]
228 s.members[string(key)] = n + 1
234 // Remove removes an IP from the set.
235 func (s *DistinctNetSet) Remove(ip net.IP) {
237 if n, ok := s.members[string(key)]; ok {
239 delete(s.members, string(key))
241 s.members[string(key)] = n - 1
246 // Contains whether the given IP is contained in the set.
247 func (s DistinctNetSet) Contains(ip net.IP) bool {
249 _, ok := s.members[string(key)]
253 // Len returns the number of tracked IPs.
254 func (s DistinctNetSet) Len() int {
256 for _, i := range s.members {
262 // key encodes the map key for an address into a temporary buffer.
264 // The first byte of key is '4' or '6' to distinguish IPv4/IPv6 address types.
265 // The remainder of the key is the IP, truncated to the number of bits.
266 func (s *DistinctNetSet) key(ip net.IP) net.IP {
267 // Lazily initialize storage.
268 if s.members == nil {
269 s.members = make(map[string]uint)
270 s.buf = make(net.IP, 17)
272 // Canonicalize ip and bits.
274 if ip4 := ip.To4(); ip4 != nil {
278 if bits > uint(len(ip)*8) {
279 bits = uint(len(ip) * 8)
281 // Encode the prefix into s.buf.
283 mask := ^byte(0xFF >> (bits % 8))
285 buf := append(s.buf[:1], ip[:nb]...)
286 if nb < len(ip) && mask != 0 {
287 buf = append(buf, ip[nb]&mask)
292 // String implements fmt.Stringer
293 func (s DistinctNetSet) String() string {
296 keys := make([]string, 0, len(s.members))
297 for k := range s.members {
298 keys = append(keys, k)
301 for i, k := range keys {
306 ip = make(net.IP, 16)
309 fmt.Fprintf(&buf, "%vĂ—%d", ip, s.members[k])
310 if i != len(keys)-1 {
318 func CheckAndSplitAddresses(addressesStr string) []string {
319 if addressesStr == "" {
323 var addresses []string
324 splits := strings.Split(addressesStr, ",")
325 for _, address := range splits {
326 ip, port, err := net.SplitHostPort(address)
328 log.WithFields(log.Fields{"module": logModule, "err": err, "address": address}).Warn("net.SplitHostPort")
332 if validIP := net.ParseIP(ip); validIP == nil {
333 log.WithFields(log.Fields{"module": logModule, "err": errInvalidIP, "ip": ip}).Warn("net.ParseIP")
337 if _, err := strconv.ParseUint(port, 10, 16); err != nil {
338 log.WithFields(log.Fields{"module": logModule, "err": errInvalidPort, "port": port}).Warn("strconv parse port")
342 addresses = append(addresses, address)