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.

proxy.go 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // Copyright (c) 2020 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  2. // released under the MIT license
  3. package utils
  4. import (
  5. "crypto/tls"
  6. "encoding/binary"
  7. "errors"
  8. "io"
  9. "net"
  10. "strings"
  11. "sync"
  12. "time"
  13. )
  14. const (
  15. // https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt
  16. // "a 108-byte buffer is always enough to store all the line and a trailing zero
  17. // for string processing."
  18. maxProxyLineLenV1 = 107
  19. )
  20. // XXX implement net.Error with a Temporary() method that returns true;
  21. // otherwise, ErrBadProxyLine will cause (*http.Server).Serve() to exit
  22. type proxyLineError struct{}
  23. func (p *proxyLineError) Error() string {
  24. return "invalid PROXY line"
  25. }
  26. func (p *proxyLineError) Timeout() bool {
  27. return false
  28. }
  29. func (p *proxyLineError) Temporary() bool {
  30. return true
  31. }
  32. var (
  33. ErrBadProxyLine error = &proxyLineError{}
  34. // TODO(golang/go#4373): replace this with the stdlib ErrNetClosing
  35. ErrNetClosing = errors.New("use of closed network connection")
  36. )
  37. // ListenerConfig is all the information about how to process
  38. // incoming IRC connections on a listener.
  39. type ListenerConfig struct {
  40. TLSConfig *tls.Config
  41. ProxyDeadline time.Duration
  42. RequireProxy bool
  43. // these are just metadata for easier tracking,
  44. // they are not used by ReloadableListener:
  45. Tor bool
  46. STSOnly bool
  47. WebSocket bool
  48. }
  49. // read a PROXY header (either v1 or v2), ensuring we don't read anything beyond
  50. // the header into a buffer (this would break the TLS handshake)
  51. func readRawProxyLine(conn net.Conn, deadline time.Duration) (result []byte, err error) {
  52. // normally this is covered by ping timeouts, but we're doing this outside
  53. // of the normal client goroutine:
  54. conn.SetDeadline(time.Now().Add(deadline))
  55. defer conn.SetDeadline(time.Time{})
  56. // read the first 16 bytes of the proxy header
  57. buf := make([]byte, 16, maxProxyLineLenV1)
  58. _, err = io.ReadFull(conn, buf)
  59. if err != nil {
  60. return
  61. }
  62. switch buf[0] {
  63. case 'P':
  64. // PROXY v1: starts with "PROXY"
  65. return readRawProxyLineV1(conn, buf)
  66. case '\r':
  67. // PROXY v2: starts with "\r\n\r\n"
  68. return readRawProxyLineV2(conn, buf)
  69. default:
  70. return nil, ErrBadProxyLine
  71. }
  72. }
  73. func readRawProxyLineV1(conn net.Conn, buf []byte) (result []byte, err error) {
  74. for {
  75. i := len(buf)
  76. if i >= maxProxyLineLenV1 {
  77. return nil, ErrBadProxyLine // did not find \r\n, fail
  78. }
  79. // prepare a single byte of free space, then read into it
  80. buf = buf[0 : i+1]
  81. _, err = io.ReadFull(conn, buf[i:])
  82. if err != nil {
  83. return nil, err
  84. }
  85. if buf[i] == '\n' {
  86. return buf, nil
  87. }
  88. }
  89. }
  90. func readRawProxyLineV2(conn net.Conn, buf []byte) (result []byte, err error) {
  91. // "The 15th and 16th bytes is the address length in bytes in network endian order."
  92. addrLen := int(binary.BigEndian.Uint16(buf[14:16]))
  93. if addrLen == 0 {
  94. return buf[0:16], nil
  95. } else if addrLen <= cap(buf)-16 {
  96. buf = buf[0 : 16+addrLen]
  97. } else {
  98. // proxy source is unix domain, we don't really handle this
  99. buf2 := make([]byte, 16+addrLen)
  100. copy(buf2[0:16], buf[0:16])
  101. buf = buf2
  102. }
  103. _, err = io.ReadFull(conn, buf[16:16+addrLen])
  104. if err != nil {
  105. return
  106. }
  107. return buf[0 : 16+addrLen], nil
  108. }
  109. // ParseProxyLine parses a PROXY protocol (v1 or v2) line and returns the remote IP.
  110. func ParseProxyLine(line []byte) (ip net.IP, err error) {
  111. if len(line) == 0 {
  112. return nil, ErrBadProxyLine
  113. }
  114. switch line[0] {
  115. case 'P':
  116. return ParseProxyLineV1(string(line))
  117. case '\r':
  118. return parseProxyLineV2(line)
  119. default:
  120. return nil, ErrBadProxyLine
  121. }
  122. }
  123. // ParseProxyLineV1 parses a PROXY protocol (v1) line and returns the remote IP.
  124. func ParseProxyLineV1(line string) (ip net.IP, err error) {
  125. params := strings.Fields(line)
  126. if len(params) != 6 || params[0] != "PROXY" {
  127. return nil, ErrBadProxyLine
  128. }
  129. ip = net.ParseIP(params[2])
  130. if ip == nil {
  131. return nil, ErrBadProxyLine
  132. }
  133. return ip.To16(), nil
  134. }
  135. func parseProxyLineV2(line []byte) (ip net.IP, err error) {
  136. if len(line) < 16 {
  137. return nil, ErrBadProxyLine
  138. }
  139. // this doesn't allocate
  140. if string(line[:12]) != "\x0d\x0a\x0d\x0a\x00\x0d\x0a\x51\x55\x49\x54\x0a" {
  141. return nil, ErrBadProxyLine
  142. }
  143. // "The next byte (the 13th one) is the protocol version and command."
  144. versionCmd := line[12]
  145. // "The highest four bits contains the version [....] it must always be sent as \x2"
  146. if (versionCmd >> 4) != 2 {
  147. return nil, ErrBadProxyLine
  148. }
  149. // "The lowest four bits represents the command"
  150. switch versionCmd & 0x0f {
  151. case 0:
  152. return nil, nil // LOCAL command
  153. case 1:
  154. // PROXY command, continue below
  155. default:
  156. // "Receivers must drop connections presenting unexpected values here"
  157. return nil, ErrBadProxyLine
  158. }
  159. var addrLen int
  160. // "The 14th byte contains the transport protocol and address family."
  161. protoAddr := line[13]
  162. // "The highest 4 bits contain the address family"
  163. switch protoAddr >> 4 {
  164. case 1:
  165. addrLen = 4 // AF_INET
  166. case 2:
  167. addrLen = 16 // AF_INET6
  168. default:
  169. return nil, nil // AF_UNSPEC or AF_UNIX, either way there's no IP address
  170. }
  171. // header, source and destination address, two 16-bit port numbers:
  172. expectedLen := 16 + 2*addrLen + 4
  173. if len(line) < expectedLen {
  174. return nil, ErrBadProxyLine
  175. }
  176. // "Starting from the 17th byte, addresses are presented in network byte order.
  177. // The address order is always the same :
  178. // - source layer 3 address in network byte order [...]"
  179. if addrLen == 4 {
  180. ip = net.IP(line[16 : 16+addrLen]).To16()
  181. } else {
  182. ip = make(net.IP, addrLen)
  183. copy(ip, line[16:16+addrLen])
  184. }
  185. return ip, nil
  186. }
  187. /// WrappedConn is a net.Conn with some additional data stapled to it;
  188. // the proxied IP, if one was read via the PROXY protocol, and the listener
  189. // configuration.
  190. type WrappedConn struct {
  191. net.Conn
  192. ProxiedIP net.IP
  193. Config ListenerConfig
  194. // Secure indicates whether we believe the connection between us and the client
  195. // was secure against interception and modification (including all proxies):
  196. Secure bool
  197. }
  198. // ReloadableListener is a wrapper for net.Listener that allows reloading
  199. // of config data for postprocessing connections (TLS, PROXY protocol, etc.)
  200. type ReloadableListener struct {
  201. // TODO: make this lock-free
  202. sync.Mutex
  203. realListener net.Listener
  204. config ListenerConfig
  205. isClosed bool
  206. }
  207. func NewReloadableListener(realListener net.Listener, config ListenerConfig) *ReloadableListener {
  208. return &ReloadableListener{
  209. realListener: realListener,
  210. config: config,
  211. }
  212. }
  213. func (rl *ReloadableListener) Reload(config ListenerConfig) {
  214. rl.Lock()
  215. rl.config = config
  216. rl.Unlock()
  217. }
  218. func (rl *ReloadableListener) Accept() (conn net.Conn, err error) {
  219. conn, err = rl.realListener.Accept()
  220. rl.Lock()
  221. config := rl.config
  222. isClosed := rl.isClosed
  223. rl.Unlock()
  224. if isClosed {
  225. if err == nil {
  226. conn.Close()
  227. }
  228. err = ErrNetClosing
  229. }
  230. if err != nil {
  231. return nil, err
  232. }
  233. var proxiedIP net.IP
  234. if config.RequireProxy {
  235. // this will occur synchronously on the goroutine calling Accept(),
  236. // but that's OK because this listener *requires* a PROXY line,
  237. // therefore it must be used with proxies that always send the line
  238. // and we won't get slowloris'ed waiting for the client response
  239. proxyLine, err := readRawProxyLine(conn, config.ProxyDeadline)
  240. if err == nil {
  241. proxiedIP, err = ParseProxyLine(proxyLine)
  242. }
  243. if err != nil {
  244. conn.Close()
  245. return nil, err
  246. }
  247. }
  248. if config.TLSConfig != nil {
  249. conn = tls.Server(conn, config.TLSConfig)
  250. }
  251. return &WrappedConn{
  252. Conn: conn,
  253. ProxiedIP: proxiedIP,
  254. Config: config,
  255. }, nil
  256. }
  257. func (rl *ReloadableListener) Close() error {
  258. rl.Lock()
  259. rl.isClosed = true
  260. rl.Unlock()
  261. return rl.realListener.Close()
  262. }
  263. func (rl *ReloadableListener) Addr() net.Addr {
  264. return rl.realListener.Addr()
  265. }