transport_proxy_auth.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. const HTTP_STAT_LINE_LENGTH = 12
  31. // ProxyAuthTransport provides support for proxy authentication when doing plain HTTP
  32. // by tapping into HTTP conversation and adding authentication headers to the requests
  33. // when requested by server
  34. type ProxyAuthTransport struct {
  35. *http.Transport
  36. Dial DialFunc
  37. Username string
  38. Password string
  39. }
  40. func NewProxyAuthTransport(rawTransport *http.Transport) (*ProxyAuthTransport, error) {
  41. dialFn := rawTransport.Dial
  42. if dialFn == nil {
  43. dialFn = net.Dial
  44. }
  45. tr := &ProxyAuthTransport{Dial: dialFn}
  46. proxyUrlFn := rawTransport.Proxy
  47. if proxyUrlFn != nil {
  48. wrappedDialFn := tr.wrapTransportDial()
  49. proxyUrl, err := proxyUrlFn(nil)
  50. if err != nil {
  51. return nil, err
  52. }
  53. if proxyUrl.Scheme != "http" {
  54. return nil, fmt.Errorf("Only HTTP proxy supported, for SOCKS use http.Transport with custom dialers & upstreamproxy.NewProxyDialFunc")
  55. }
  56. tr.Username = proxyUrl.User.Username()
  57. tr.Password, _ = proxyUrl.User.Password()
  58. rawTransport.Dial = wrappedDialFn
  59. }
  60. tr.Transport = rawTransport
  61. return tr, nil
  62. }
  63. func (tr *ProxyAuthTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
  64. if req.URL.Scheme != "http" {
  65. return nil, fmt.Errorf("Only plain HTTP supported, for HTTPS use http.Transport with DialTLS & upstreamproxy.NewProxyDialFunc")
  66. }
  67. return tr.Transport.RoundTrip(req)
  68. }
  69. // wrapTransportDial wraps original transport Dial function
  70. // and returns a new net.Conn interface provided by transportConn
  71. // that allows us to intercept both outgoing requests and incoming
  72. // responses and examine / mutate them
  73. func (tr *ProxyAuthTransport) wrapTransportDial() DialFunc {
  74. return func(network, addr string) (net.Conn, error) {
  75. c, err := tr.Dial("tcp", addr)
  76. if err != nil {
  77. return nil, err
  78. }
  79. tc := newTransportConn(c, tr)
  80. return tc, nil
  81. }
  82. }
  83. type transportConn struct {
  84. net.Conn
  85. requestInterceptor io.Writer
  86. reqDone chan struct{}
  87. errChannel chan error
  88. // last written request holder
  89. lastRequest *http.Request
  90. authenticator HttpAuthenticator
  91. authState HttpAuthState
  92. authCache string
  93. transport *ProxyAuthTransport
  94. }
  95. func newTransportConn(c net.Conn, tr *ProxyAuthTransport) *transportConn {
  96. tc := &transportConn{
  97. Conn: c,
  98. reqDone: make(chan struct{}),
  99. errChannel: make(chan error),
  100. transport: tr,
  101. }
  102. // Intercept outgoing request as it is written out to server and store it
  103. // in case it needs to be authenticated and replayed
  104. //NOTE that pipelining is currently not supported
  105. pr, pw := io.Pipe()
  106. tc.requestInterceptor = pw
  107. requestReader := bufio.NewReader(pr)
  108. go func() {
  109. requestInterceptLoop:
  110. for {
  111. req, err := http.ReadRequest(requestReader)
  112. if err != nil {
  113. tc.Conn.Close()
  114. pr.Close()
  115. pw.Close()
  116. tc.errChannel <- fmt.Errorf("intercept request loop http.ReadRequest error: %s", err)
  117. break requestInterceptLoop
  118. }
  119. //read and copy entire body
  120. body, _ := ioutil.ReadAll(req.Body)
  121. tc.lastRequest = req
  122. tc.lastRequest.Body = ioutil.NopCloser(bytes.NewReader(body))
  123. //Signal when we have a complete request
  124. tc.reqDone <- struct{}{}
  125. }
  126. }()
  127. return tc
  128. }
  129. // Read peeks into the new response and checks if the proxy requests authentication
  130. // If so, the last intercepted request is authenticated against the response
  131. func (tc *transportConn) Read(p []byte) (n int, err error) {
  132. n, err = tc.Conn.Read(p)
  133. if n < HTTP_STAT_LINE_LENGTH {
  134. return
  135. }
  136. select {
  137. case _ = <-tc.reqDone:
  138. line := string(p[:HTTP_STAT_LINE_LENGTH])
  139. //This is a new response
  140. //Let's see if proxy requests authentication
  141. f := strings.SplitN(line, " ", 2)
  142. readBufferReader := bytes.NewReader(p)
  143. responseReader := io.MultiReader(readBufferReader, tc.Conn)
  144. if (f[0] == "HTTP/1.0" || f[0] == "HTTP/1.1") && f[1] == "407" {
  145. resp, err := http.ReadResponse(bufio.NewReader(responseReader), 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. }
  170. // Authenticate and replay the request
  171. err = tc.authenticator.Authenticate(tc.lastRequest, resp, tc.transport.Username, tc.transport.Password)
  172. if err != nil {
  173. return 0, err
  174. }
  175. tc.lastRequest.WriteProxy(tc)
  176. return tc.Read(p)
  177. }
  178. case err = <-tc.errChannel:
  179. return 0, err
  180. default:
  181. }
  182. return
  183. }
  184. func (tc *transportConn) Write(p []byte) (n int, err error) {
  185. n, err = tc.Conn.Write(p)
  186. //also write data to the request interceptor
  187. tc.requestInterceptor.Write(p[:n])
  188. return n, err
  189. }