You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

net.go 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2016 Daniel Oaks <daniel@danieloaks.net>
  3. // released under the MIT license
  4. package utils
  5. import (
  6. "fmt"
  7. "net"
  8. "regexp"
  9. "strings"
  10. )
  11. var (
  12. // subnet mask for an ipv6 /128:
  13. mask128 = net.CIDRMask(128, 128)
  14. IPv4LoopbackAddress = net.ParseIP("127.0.0.1").To16()
  15. validHostnameLabelRegexp = regexp.MustCompile(`^[0-9A-Za-z.\-]+$`)
  16. )
  17. // AddrToIP returns the IP address for a net.Addr; unix domain sockets are treated as IPv4 loopback
  18. func AddrToIP(addr net.Addr) net.IP {
  19. if tcpaddr, ok := addr.(*net.TCPAddr); ok {
  20. return tcpaddr.IP.To16()
  21. } else if _, ok := addr.(*net.UnixAddr); ok {
  22. return IPv4LoopbackAddress
  23. } else {
  24. return nil
  25. }
  26. }
  27. // IPStringToHostname converts a string representation of an IP address to an IRC-ready hostname
  28. func IPStringToHostname(ipStr string) string {
  29. if 0 < len(ipStr) && ipStr[0] == ':' {
  30. // fix for IPv6 hostnames (so they don't start with a colon), same as all other IRCds
  31. ipStr = "0" + ipStr
  32. }
  33. return ipStr
  34. }
  35. // IsHostname returns whether we consider `name` a valid hostname.
  36. func IsHostname(name string) bool {
  37. name = strings.TrimSuffix(name, ".")
  38. if len(name) < 1 || len(name) > 253 {
  39. return false
  40. }
  41. // ensure each part of hostname is valid
  42. for _, part := range strings.Split(name, ".") {
  43. if len(part) < 1 || len(part) > 63 || strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  44. return false
  45. }
  46. if !validHostnameLabelRegexp.MatchString(part) {
  47. return false
  48. }
  49. }
  50. return true
  51. }
  52. // IsServerName returns whether we consider `name` a valid IRC server name.
  53. func IsServerName(name string) bool {
  54. // IRC server names specifically require a period
  55. return IsHostname(name) && strings.IndexByte(name, '.') != -1
  56. }
  57. // Convenience to test whether `ip` is contained in any of `nets`.
  58. func IPInNets(ip net.IP, nets []net.IPNet) bool {
  59. for _, network := range nets {
  60. if network.Contains(ip) {
  61. return true
  62. }
  63. }
  64. return false
  65. }
  66. // NormalizeIPToNet represents an address (v4 or v6) as the v6 /128 CIDR
  67. // containing only it.
  68. func NormalizeIPToNet(addr net.IP) (network net.IPNet) {
  69. // represent ipv4 addresses as ipv6 addresses, using the 4-in-6 prefix
  70. // (actually this should be a no-op for any address returned by ParseIP)
  71. addr = addr.To16()
  72. // the network corresponding to this address is now an ipv6 /128:
  73. return net.IPNet{
  74. IP: addr,
  75. Mask: mask128,
  76. }
  77. }
  78. // NormalizeNet normalizes an IPNet to a v6 CIDR, using the 4-in-6 prefix.
  79. // (this is like IP.To16(), but for IPNet instead of IP)
  80. func NormalizeNet(network net.IPNet) (result net.IPNet) {
  81. if len(network.IP) == 16 {
  82. return network
  83. }
  84. ones, _ := network.Mask.Size()
  85. return net.IPNet{
  86. IP: network.IP.To16(),
  87. // include the 96 bits of the 4-in-6 prefix
  88. Mask: net.CIDRMask(96+ones, 128),
  89. }
  90. }
  91. // Given a network, produce a human-readable string
  92. // (i.e., CIDR if it's actually a network, IPv6 address if it's a v6 /128,
  93. // dotted quad if it's a v4 /32).
  94. func NetToNormalizedString(network net.IPNet) string {
  95. ones, bits := network.Mask.Size()
  96. if ones == bits && ones == len(network.IP)*8 {
  97. // either a /32 or a /128, output the address:
  98. return network.IP.String()
  99. }
  100. return network.String()
  101. }
  102. // Parse a human-readable description (an address or CIDR, either v4 or v6)
  103. // into a normalized v6 net.IPNet.
  104. func NormalizedNetFromString(str string) (result net.IPNet, err error) {
  105. _, network, err := net.ParseCIDR(str)
  106. if err == nil {
  107. return NormalizeNet(*network), nil
  108. }
  109. ip := net.ParseIP(str)
  110. if ip == nil {
  111. err = &net.AddrError{
  112. Err: "Couldn't interpret as either CIDR or address",
  113. Addr: str,
  114. }
  115. return
  116. }
  117. return NormalizeIPToNet(ip), nil
  118. }
  119. // Parse a list of IPs and nets as they would appear in one of our config
  120. // files, e.g., proxy-allowed-from or a throttling exemption list.
  121. func ParseNetList(netList []string) (nets []net.IPNet, err error) {
  122. var network net.IPNet
  123. for _, netStr := range netList {
  124. if netStr == "localhost" {
  125. ipv4Loopback, _ := NormalizedNetFromString("127.0.0.0/8")
  126. ipv6Loopback, _ := NormalizedNetFromString("::1/128")
  127. nets = append(nets, ipv4Loopback)
  128. nets = append(nets, ipv6Loopback)
  129. continue
  130. }
  131. network, err = NormalizedNetFromString(netStr)
  132. if err != nil {
  133. return
  134. } else {
  135. nets = append(nets, network)
  136. }
  137. }
  138. return
  139. }
  140. // Process the X-Forwarded-For header, validating against a list of trusted IPs.
  141. // Returns the address that the request was forwarded for, or nil if no trustworthy
  142. // data was available.
  143. func HandleXForwardedFor(remoteAddr string, xForwardedFor string, whitelist []net.IPNet) (result net.IP) {
  144. // http.Request.RemoteAddr "has no defined format". with TCP it's typically "127.0.0.1:23784",
  145. // with unix domain it's typically "@"
  146. var remoteIP net.IP
  147. host, _, err := net.SplitHostPort(remoteAddr)
  148. if err != nil {
  149. remoteIP = IPv4LoopbackAddress
  150. } else {
  151. remoteIP = net.ParseIP(host)
  152. }
  153. if remoteIP == nil || !IPInNets(remoteIP, whitelist) {
  154. return remoteIP
  155. }
  156. // walk backwards through the X-Forwarded-For chain looking for an IP
  157. // that is *not* trusted. that means it was added by one of our trusted
  158. // forwarders (either remoteIP or something ahead of it in the chain)
  159. // and we can trust it:
  160. result = remoteIP
  161. forwardedIPs := strings.Split(xForwardedFor, ",")
  162. for i := len(forwardedIPs) - 1; i >= 0; i-- {
  163. proxiedIP := net.ParseIP(strings.TrimSpace(forwardedIPs[i]))
  164. if proxiedIP == nil {
  165. return
  166. } else if !IPInNets(proxiedIP, whitelist) {
  167. return proxiedIP
  168. } else {
  169. result = proxiedIP
  170. }
  171. }
  172. // no valid untrusted IPs were found in the chain;
  173. // return either the last valid and trusted IP (which must be the origin),
  174. // or nil:
  175. return
  176. }
  177. func DescribeConn(conn net.Conn) string {
  178. // XXX for unix domain sockets, this is not informative enough for an operator
  179. // to determine who holds the other side of the connection. there seems to be
  180. // no way to get either the correct file descriptor of the connection, or the
  181. // udiag_ino from `man 7 sock_diag`. maybe there's something else we can do?
  182. return fmt.Sprintf("%s <-> %s", conn.LocalAddr().String(), conn.RemoteAddr().String())
  183. }