net.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package netutil contains extensions to the net package.
  17. package netutil
  18. import (
  19. "bytes"
  20. "errors"
  21. "fmt"
  22. "net"
  23. "sort"
  24. "strings"
  25. )
  26. var lan4, lan6, special4, special6 Netlist
  27. func init() {
  28. // Lists from RFC 5735, RFC 5156,
  29. // https://www.iana.org/assignments/iana-ipv4-special-registry/
  30. lan4.Add("0.0.0.0/8") // "This" network
  31. lan4.Add("10.0.0.0/8") // Private Use
  32. lan4.Add("172.16.0.0/12") // Private Use
  33. lan4.Add("192.168.0.0/16") // Private Use
  34. lan6.Add("fe80::/10") // Link-Local
  35. lan6.Add("fc00::/7") // Unique-Local
  36. special4.Add("192.0.0.0/29") // IPv4 Service Continuity
  37. special4.Add("192.0.0.9/32") // PCP Anycast
  38. special4.Add("192.0.0.170/32") // NAT64/DNS64 Discovery
  39. special4.Add("192.0.0.171/32") // NAT64/DNS64 Discovery
  40. special4.Add("192.0.2.0/24") // TEST-NET-1
  41. special4.Add("192.31.196.0/24") // AS112
  42. special4.Add("192.52.193.0/24") // AMT
  43. special4.Add("192.88.99.0/24") // 6to4 Relay Anycast
  44. special4.Add("192.175.48.0/24") // AS112
  45. special4.Add("198.18.0.0/15") // Device Benchmark Testing
  46. special4.Add("198.51.100.0/24") // TEST-NET-2
  47. special4.Add("203.0.113.0/24") // TEST-NET-3
  48. special4.Add("255.255.255.255/32") // Limited Broadcast
  49. // http://www.iana.org/assignments/iana-ipv6-special-registry/
  50. special6.Add("100::/64")
  51. special6.Add("2001::/32")
  52. special6.Add("2001:1::1/128")
  53. special6.Add("2001:2::/48")
  54. special6.Add("2001:3::/32")
  55. special6.Add("2001:4:112::/48")
  56. special6.Add("2001:5::/32")
  57. special6.Add("2001:10::/28")
  58. special6.Add("2001:20::/28")
  59. special6.Add("2001:db8::/32")
  60. special6.Add("2002::/16")
  61. }
  62. // Netlist is a list of IP networks.
  63. type Netlist []net.IPNet
  64. // ParseNetlist parses a comma-separated list of CIDR masks.
  65. // Whitespace and extra commas are ignored.
  66. func ParseNetlist(s string) (*Netlist, error) {
  67. ws := strings.NewReplacer(" ", "", "\n", "", "\t", "")
  68. masks := strings.Split(ws.Replace(s), ",")
  69. l := make(Netlist, 0)
  70. for _, mask := range masks {
  71. if mask == "" {
  72. continue
  73. }
  74. _, n, err := net.ParseCIDR(mask)
  75. if err != nil {
  76. return nil, err
  77. }
  78. l = append(l, *n)
  79. }
  80. return &l, nil
  81. }
  82. // MarshalTOML implements toml.MarshalerRec.
  83. func (l *Netlist) MarshalTOML() (interface{}, error) {
  84. if l == nil {
  85. return nil, nil
  86. }
  87. list := make([]string, 0, len(*l))
  88. for _, net := range *l {
  89. list = append(list, net.String())
  90. }
  91. return list, nil
  92. }
  93. // UnmarshalTOML implements toml.UnmarshalerRec.
  94. func (l *Netlist) UnmarshalTOML(fn func(interface{}) error) error {
  95. var masks []string
  96. if err := fn(&masks); err != nil {
  97. return err
  98. }
  99. for _, mask := range masks {
  100. _, n, err := net.ParseCIDR(mask)
  101. if err != nil {
  102. return err
  103. }
  104. *l = append(*l, *n)
  105. }
  106. return nil
  107. }
  108. // Add parses a CIDR mask and appends it to the list. It panics for invalid masks and is
  109. // intended to be used for setting up static lists.
  110. func (l *Netlist) Add(cidr string) {
  111. _, n, err := net.ParseCIDR(cidr)
  112. if err != nil {
  113. panic(err)
  114. }
  115. *l = append(*l, *n)
  116. }
  117. // Contains reports whether the given IP is contained in the list.
  118. func (l *Netlist) Contains(ip net.IP) bool {
  119. if l == nil {
  120. return false
  121. }
  122. for _, net := range *l {
  123. if net.Contains(ip) {
  124. return true
  125. }
  126. }
  127. return false
  128. }
  129. // IsLAN reports whether an IP is a local network address.
  130. func IsLAN(ip net.IP) bool {
  131. if ip.IsLoopback() {
  132. return true
  133. }
  134. if v4 := ip.To4(); v4 != nil {
  135. return lan4.Contains(v4)
  136. }
  137. return lan6.Contains(ip)
  138. }
  139. // IsSpecialNetwork reports whether an IP is located in a special-use network range
  140. // This includes broadcast, multicast and documentation addresses.
  141. func IsSpecialNetwork(ip net.IP) bool {
  142. if ip.IsMulticast() {
  143. return true
  144. }
  145. if v4 := ip.To4(); v4 != nil {
  146. return special4.Contains(v4)
  147. }
  148. return special6.Contains(ip)
  149. }
  150. var (
  151. errInvalid = errors.New("invalid IP")
  152. errUnspecified = errors.New("zero address")
  153. errSpecial = errors.New("special network")
  154. errLoopback = errors.New("loopback address from non-loopback host")
  155. errLAN = errors.New("LAN address from WAN host")
  156. )
  157. // CheckRelayIP reports whether an IP relayed from the given sender IP
  158. // is a valid connection target.
  159. //
  160. // There are four rules:
  161. // - Special network addresses are never valid.
  162. // - Loopback addresses are OK if relayed by a loopback host.
  163. // - LAN addresses are OK if relayed by a LAN host.
  164. // - All other addresses are always acceptable.
  165. func CheckRelayIP(sender, addr net.IP) error {
  166. if len(addr) != net.IPv4len && len(addr) != net.IPv6len {
  167. return errInvalid
  168. }
  169. if addr.IsUnspecified() {
  170. return errUnspecified
  171. }
  172. if IsSpecialNetwork(addr) {
  173. return errSpecial
  174. }
  175. if addr.IsLoopback() && !sender.IsLoopback() {
  176. return errLoopback
  177. }
  178. if IsLAN(addr) && !IsLAN(sender) {
  179. return errLAN
  180. }
  181. return nil
  182. }
  183. // SameNet reports whether two IP addresses have an equal prefix of the given bit length.
  184. func SameNet(bits uint, ip, other net.IP) bool {
  185. ip4, other4 := ip.To4(), other.To4()
  186. switch {
  187. case (ip4 == nil) != (other4 == nil):
  188. return false
  189. case ip4 != nil:
  190. return sameNet(bits, ip4, other4)
  191. default:
  192. return sameNet(bits, ip.To16(), other.To16())
  193. }
  194. }
  195. func sameNet(bits uint, ip, other net.IP) bool {
  196. nb := int(bits / 8)
  197. mask := ^byte(0xFF >> (bits % 8))
  198. if mask != 0 && nb < len(ip) && ip[nb]&mask != other[nb]&mask {
  199. return false
  200. }
  201. return nb <= len(ip) && ip[:nb].Equal(other[:nb])
  202. }
  203. // DistinctNetSet tracks IPs, ensuring that at most N of them
  204. // fall into the same network range.
  205. type DistinctNetSet struct {
  206. Subnet uint // number of common prefix bits
  207. Limit uint // maximum number of IPs in each subnet
  208. members map[string]uint
  209. buf net.IP
  210. }
  211. // Add adds an IP address to the set. It returns false (and doesn't add the IP) if the
  212. // number of existing IPs in the defined range exceeds the limit.
  213. func (s *DistinctNetSet) Add(ip net.IP) bool {
  214. key := s.key(ip)
  215. n := s.members[string(key)]
  216. if n < s.Limit {
  217. s.members[string(key)] = n + 1
  218. return true
  219. }
  220. return false
  221. }
  222. // Remove removes an IP from the set.
  223. func (s *DistinctNetSet) Remove(ip net.IP) {
  224. key := s.key(ip)
  225. if n, ok := s.members[string(key)]; ok {
  226. if n == 1 {
  227. delete(s.members, string(key))
  228. } else {
  229. s.members[string(key)] = n - 1
  230. }
  231. }
  232. }
  233. // Contains whether the given IP is contained in the set.
  234. func (s DistinctNetSet) Contains(ip net.IP) bool {
  235. key := s.key(ip)
  236. _, ok := s.members[string(key)]
  237. return ok
  238. }
  239. // Len returns the number of tracked IPs.
  240. func (s DistinctNetSet) Len() int {
  241. n := uint(0)
  242. for _, i := range s.members {
  243. n += i
  244. }
  245. return int(n)
  246. }
  247. // key encodes the map key for an address into a temporary buffer.
  248. //
  249. // The first byte of key is '4' or '6' to distinguish IPv4/IPv6 address types.
  250. // The remainder of the key is the IP, truncated to the number of bits.
  251. func (s *DistinctNetSet) key(ip net.IP) net.IP {
  252. // Lazily initialize storage.
  253. if s.members == nil {
  254. s.members = make(map[string]uint)
  255. s.buf = make(net.IP, 17)
  256. }
  257. // Canonicalize ip and bits.
  258. typ := byte('6')
  259. if ip4 := ip.To4(); ip4 != nil {
  260. typ, ip = '4', ip4
  261. }
  262. bits := s.Subnet
  263. if bits > uint(len(ip)*8) {
  264. bits = uint(len(ip) * 8)
  265. }
  266. // Encode the prefix into s.buf.
  267. nb := int(bits / 8)
  268. mask := ^byte(0xFF >> (bits % 8))
  269. s.buf[0] = typ
  270. buf := append(s.buf[:1], ip[:nb]...)
  271. if nb < len(ip) && mask != 0 {
  272. buf = append(buf, ip[nb]&mask)
  273. }
  274. return buf
  275. }
  276. // String implements fmt.Stringer
  277. func (s DistinctNetSet) String() string {
  278. var buf bytes.Buffer
  279. buf.WriteString("{")
  280. keys := make([]string, 0, len(s.members))
  281. for k := range s.members {
  282. keys = append(keys, k)
  283. }
  284. sort.Strings(keys)
  285. for i, k := range keys {
  286. var ip net.IP
  287. if k[0] == '4' {
  288. ip = make(net.IP, 4)
  289. } else {
  290. ip = make(net.IP, 16)
  291. }
  292. copy(ip, k[1:])
  293. fmt.Fprintf(&buf, "%v×%d", ip, s.members[k])
  294. if i != len(keys)-1 {
  295. buf.WriteString(" ")
  296. }
  297. }
  298. buf.WriteString("}")
  299. return buf.String()
  300. }