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

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