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.5KB

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