net.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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{} {
  84. list := make([]string, 0, len(l))
  85. for _, net := range l {
  86. list = append(list, net.String())
  87. }
  88. return list
  89. }
  90. // UnmarshalTOML implements toml.UnmarshalerRec.
  91. func (l *Netlist) UnmarshalTOML(fn func(interface{}) error) error {
  92. var masks []string
  93. if err := fn(&masks); err != nil {
  94. return err
  95. }
  96. for _, mask := range masks {
  97. _, n, err := net.ParseCIDR(mask)
  98. if err != nil {
  99. return err
  100. }
  101. *l = append(*l, *n)
  102. }
  103. return nil
  104. }
  105. // Add parses a CIDR mask and appends it to the list. It panics for invalid masks and is
  106. // intended to be used for setting up static lists.
  107. func (l *Netlist) Add(cidr string) {
  108. _, n, err := net.ParseCIDR(cidr)
  109. if err != nil {
  110. panic(err)
  111. }
  112. *l = append(*l, *n)
  113. }
  114. // Contains reports whether the given IP is contained in the list.
  115. func (l *Netlist) Contains(ip net.IP) bool {
  116. if l == nil {
  117. return false
  118. }
  119. for _, net := range *l {
  120. if net.Contains(ip) {
  121. return true
  122. }
  123. }
  124. return false
  125. }
  126. // IsLAN reports whether an IP is a local network address.
  127. func IsLAN(ip net.IP) bool {
  128. if ip.IsLoopback() {
  129. return true
  130. }
  131. if v4 := ip.To4(); v4 != nil {
  132. return lan4.Contains(v4)
  133. }
  134. return lan6.Contains(ip)
  135. }
  136. // IsSpecialNetwork reports whether an IP is located in a special-use network range
  137. // This includes broadcast, multicast and documentation addresses.
  138. func IsSpecialNetwork(ip net.IP) bool {
  139. if ip.IsMulticast() {
  140. return true
  141. }
  142. if v4 := ip.To4(); v4 != nil {
  143. return special4.Contains(v4)
  144. }
  145. return special6.Contains(ip)
  146. }
  147. var (
  148. errInvalid = errors.New("invalid IP")
  149. errUnspecified = errors.New("zero address")
  150. errSpecial = errors.New("special network")
  151. errLoopback = errors.New("loopback address from non-loopback host")
  152. errLAN = errors.New("LAN address from WAN host")
  153. )
  154. // CheckRelayIP reports whether an IP relayed from the given sender IP
  155. // is a valid connection target.
  156. //
  157. // There are four rules:
  158. // - Special network addresses are never valid.
  159. // - Loopback addresses are OK if relayed by a loopback host.
  160. // - LAN addresses are OK if relayed by a LAN host.
  161. // - All other addresses are always acceptable.
  162. func CheckRelayIP(sender, addr net.IP) error {
  163. if len(addr) != net.IPv4len && len(addr) != net.IPv6len {
  164. return errInvalid
  165. }
  166. if addr.IsUnspecified() {
  167. return errUnspecified
  168. }
  169. if IsSpecialNetwork(addr) {
  170. return errSpecial
  171. }
  172. if addr.IsLoopback() && !sender.IsLoopback() {
  173. return errLoopback
  174. }
  175. if IsLAN(addr) && !IsLAN(sender) {
  176. return errLAN
  177. }
  178. return nil
  179. }
  180. // SameNet reports whether two IP addresses have an equal prefix of the given bit length.
  181. func SameNet(bits uint, ip, other net.IP) bool {
  182. ip4, other4 := ip.To4(), other.To4()
  183. switch {
  184. case (ip4 == nil) != (other4 == nil):
  185. return false
  186. case ip4 != nil:
  187. return sameNet(bits, ip4, other4)
  188. default:
  189. return sameNet(bits, ip.To16(), other.To16())
  190. }
  191. }
  192. func sameNet(bits uint, ip, other net.IP) bool {
  193. nb := int(bits / 8)
  194. mask := ^byte(0xFF >> (bits % 8))
  195. if mask != 0 && nb < len(ip) && ip[nb]&mask != other[nb]&mask {
  196. return false
  197. }
  198. return nb <= len(ip) && bytes.Equal(ip[:nb], other[:nb])
  199. }
  200. // DistinctNetSet tracks IPs, ensuring that at most N of them
  201. // fall into the same network range.
  202. type DistinctNetSet struct {
  203. Subnet uint // number of common prefix bits
  204. Limit uint // maximum number of IPs in each subnet
  205. members map[string]uint
  206. buf net.IP
  207. }
  208. // Add adds an IP address to the set. It returns false (and doesn't add the IP) if the
  209. // number of existing IPs in the defined range exceeds the limit.
  210. func (s *DistinctNetSet) Add(ip net.IP) bool {
  211. key := s.key(ip)
  212. n := s.members[string(key)]
  213. if n < s.Limit {
  214. s.members[string(key)] = n + 1
  215. return true
  216. }
  217. return false
  218. }
  219. // Remove removes an IP from the set.
  220. func (s *DistinctNetSet) Remove(ip net.IP) {
  221. key := s.key(ip)
  222. if n, ok := s.members[string(key)]; ok {
  223. if n == 1 {
  224. delete(s.members, string(key))
  225. } else {
  226. s.members[string(key)] = n - 1
  227. }
  228. }
  229. }
  230. // Contains whether the given IP is contained in the set.
  231. func (s DistinctNetSet) Contains(ip net.IP) bool {
  232. key := s.key(ip)
  233. _, ok := s.members[string(key)]
  234. return ok
  235. }
  236. // Len returns the number of tracked IPs.
  237. func (s DistinctNetSet) Len() int {
  238. n := uint(0)
  239. for _, i := range s.members {
  240. n += i
  241. }
  242. return int(n)
  243. }
  244. // key encodes the map key for an address into a temporary buffer.
  245. //
  246. // The first byte of key is '4' or '6' to distinguish IPv4/IPv6 address types.
  247. // The remainder of the key is the IP, truncated to the number of bits.
  248. func (s *DistinctNetSet) key(ip net.IP) net.IP {
  249. // Lazily initialize storage.
  250. if s.members == nil {
  251. s.members = make(map[string]uint)
  252. s.buf = make(net.IP, 17)
  253. }
  254. // Canonicalize ip and bits.
  255. typ := byte('6')
  256. if ip4 := ip.To4(); ip4 != nil {
  257. typ, ip = '4', ip4
  258. }
  259. bits := s.Subnet
  260. if bits > uint(len(ip)*8) {
  261. bits = uint(len(ip) * 8)
  262. }
  263. // Encode the prefix into s.buf.
  264. nb := int(bits / 8)
  265. mask := ^byte(0xFF >> (bits % 8))
  266. s.buf[0] = typ
  267. buf := append(s.buf[:1], ip[:nb]...)
  268. if nb < len(ip) && mask != 0 {
  269. buf = append(buf, ip[nb]&mask)
  270. }
  271. return buf
  272. }
  273. // String implements fmt.Stringer
  274. func (s DistinctNetSet) String() string {
  275. var buf bytes.Buffer
  276. buf.WriteString("{")
  277. keys := make([]string, 0, len(s.members))
  278. for k := range s.members {
  279. keys = append(keys, k)
  280. }
  281. sort.Strings(keys)
  282. for i, k := range keys {
  283. var ip net.IP
  284. if k[0] == '4' {
  285. ip = make(net.IP, 4)
  286. } else {
  287. ip = make(net.IP, 16)
  288. }
  289. copy(ip, k[1:])
  290. fmt.Fprintf(&buf, "%v×%d", ip, s.members[k])
  291. if i != len(keys)-1 {
  292. buf.WriteString(" ")
  293. }
  294. }
  295. buf.WriteString("}")
  296. return buf.String()
  297. }