transport_proxy_auth.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package upstreamproxy
  20. import (
  21. "bufio"
  22. "bytes"
  23. "fmt"
  24. "io"
  25. "io/ioutil"
  26. "net"
  27. "net/http"
  28. "strings"
  29. )
  30. // ProxyAuthTransport provides support for proxy authentication when doing plain HTTP
  31. // by tapping into HTTP conversation and adding authentication headers to the requests
  32. // when requested by server
  33. type ProxyAuthTransport struct {
  34. *http.Transport
  35. Dial DialFunc
  36. Username string
  37. Password string
  38. }
  39. func NewProxyAuthTransport(rawTransport *http.Transport) (*ProxyAuthTransport, error) {
  40. dialFn := rawTransport.Dial
  41. if dialFn == nil {
  42. dialFn = net.Dial
  43. }
  44. tr := &ProxyAuthTransport{Dial: dialFn}
  45. proxyUrlFn := rawTransport.Proxy
  46. if proxyUrlFn != nil {
  47. wrappedDialFn := tr.wrapTransportDial()
  48. proxyUrl, err := proxyUrlFn(nil)
  49. if err != nil {
  50. return nil, err
  51. }
  52. if proxyUrl.Scheme != "http" {
  53. return nil, fmt.Errorf("Only HTTP proxy supported, for SOCKS use http.Transport with custom dialers & upstreamproxy.NewProxyDialFunc")
  54. }
  55. tr.Username = proxyUrl.User.Username()
  56. tr.Password, _ = proxyUrl.User.Password()
  57. rawTransport.Dial = wrappedDialFn
  58. }
  59. tr.Transport = rawTransport
  60. return tr, nil
  61. }
  62. func (tr *ProxyAuthTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
  63. if req.URL.Scheme != "http" {
  64. return nil, fmt.Errorf("Only plain HTTP supported, for HTTPS use http.Transport with DialTLS & upstreamproxy.NewProxyDialFunc")
  65. }
  66. return tr.Transport.RoundTrip(req)
  67. }
  68. // wrapTransportDial wraps original transport Dial function
  69. // and returns a new net.Conn interface provided by transportConn
  70. // that allows us to intercept both outgoing requests and incoming
  71. // responses and examine / mutate them
  72. func (tr *ProxyAuthTransport) wrapTransportDial() DialFunc {
  73. return func(network, addr string) (net.Conn, error) {
  74. c, err := tr.Dial("tcp", addr)
  75. if err != nil {
  76. return nil, err
  77. }
  78. tc := newTransportConn(c, tr)
  79. return tc, nil
  80. }
  81. }
  82. type transportConn struct {
  83. net.Conn
  84. requestInterceptor io.Writer
  85. reqDone chan struct{}
  86. errChannel chan error
  87. // a buffered Reader from the raw net.Conn so we could Peek at the data
  88. // without advancing the 'read' pointer
  89. connReader *bufio.Reader
  90. // last written request holder
  91. lastRequest *http.Request
  92. authenticator HttpAuthenticator
  93. authState HttpAuthState
  94. transport *ProxyAuthTransport
  95. }
  96. func newTransportConn(c net.Conn, tr *ProxyAuthTransport) *transportConn {
  97. tc := &transportConn{
  98. Conn: c,
  99. reqDone: make(chan struct{}),
  100. errChannel: make(chan error),
  101. connReader: bufio.NewReader(c),
  102. transport: tr,
  103. }
  104. // Intercept outgoing request as it is written out to server and store it
  105. // in case it needs to be authenticated and replayed
  106. //NOTE that pipelining is currently not supported
  107. pr, pw := io.Pipe()
  108. tc.requestInterceptor = pw
  109. go func() {
  110. requestInterceptLoop:
  111. for {
  112. req, err := http.ReadRequest(bufio.NewReader(pr))
  113. if err != nil {
  114. tc.Conn.Close()
  115. pr.Close()
  116. pw.Close()
  117. tc.errChannel <- fmt.Errorf("intercept request loop http.ReadRequest error: %s", err)
  118. break requestInterceptLoop
  119. }
  120. //read and copy entire body
  121. body, _ := ioutil.ReadAll(req.Body)
  122. tc.lastRequest = req
  123. tc.lastRequest.Body = ioutil.NopCloser(bytes.NewReader(body))
  124. //Signal when we have a complete request
  125. tc.reqDone <- struct{}{}
  126. }
  127. }()
  128. return tc
  129. }
  130. // Read peeks into the new response and checks if the proxy requests authentication
  131. // If so, the last intercepted request is authenticated against the response
  132. // authentication challenge and replayed
  133. func (tc *transportConn) Read(p []byte) (int, error) {
  134. peeked, err := tc.connReader.Peek(12)
  135. if err != nil {
  136. return 0, err
  137. }
  138. line := string(peeked)
  139. select {
  140. case _ = <-tc.reqDone:
  141. //This is a new response
  142. //Let's see if proxy requests authentication
  143. f := strings.SplitN(line, " ", 2)
  144. if (f[0] == "HTTP/1.0" || f[0] == "HTTP/1.1") && f[1] == "407" {
  145. resp, err := http.ReadResponse(tc.connReader, nil)
  146. if err != nil {
  147. return 0, err
  148. }
  149. // make sure we read the body of the response so that
  150. // we don't block the reader
  151. ioutil.ReadAll(resp.Body)
  152. resp.Body.Close()
  153. if tc.authState == HTTP_AUTH_STATE_UNCHALLENGED {
  154. tc.authenticator, err = NewHttpAuthenticator(resp)
  155. if err != nil {
  156. return 0, err
  157. }
  158. tc.authState = HTTP_AUTH_STATE_CHALLENGED
  159. }
  160. if resp.Close == true {
  161. // Server side indicated that it is closing this connection,
  162. // dial a new one
  163. addr := tc.Conn.RemoteAddr()
  164. tc.Conn.Close()
  165. tc.Conn, err = tc.transport.Dial(addr.Network(), addr.String())
  166. if err != nil {
  167. return 0, err
  168. }
  169. tc.connReader = bufio.NewReader(tc.Conn)
  170. }
  171. // Authenticate and replay the request
  172. err = tc.authenticator.Authenticate(tc.lastRequest, resp, tc.transport.Username, tc.transport.Password)
  173. if err != nil {
  174. return 0, err
  175. }
  176. tc.lastRequest.WriteProxy(tc)
  177. return tc.Read(p)
  178. }
  179. case err = <-tc.errChannel:
  180. return 0, err
  181. default:
  182. }
  183. n, err := tc.connReader.Read(p)
  184. return n, err
  185. }
  186. func (tc *transportConn) Write(p []byte) (n int, err error) {
  187. n, err = tc.Conn.Write(p)
  188. //also write data to the request interceptor
  189. tc.requestInterceptor.Write(p[:n])
  190. return n, err
  191. }