transport_proxy_auth.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. "sync"
  30. )
  31. const HTTP_STAT_LINE_LENGTH = 12
  32. // ProxyAuthTransport provides support for proxy authentication when doing plain HTTP
  33. // by tapping into HTTP conversation and adding authentication headers to the requests
  34. // when requested by server
  35. type ProxyAuthTransport struct {
  36. *http.Transport
  37. Dial DialFunc
  38. Username string
  39. Password string
  40. Authenticator HttpAuthenticator
  41. mu sync.Mutex
  42. }
  43. func NewProxyAuthTransport(rawTransport *http.Transport) (*ProxyAuthTransport, error) {
  44. dialFn := rawTransport.Dial
  45. if dialFn == nil {
  46. dialFn = net.Dial
  47. }
  48. tr := &ProxyAuthTransport{Dial: dialFn}
  49. proxyUrlFn := rawTransport.Proxy
  50. if proxyUrlFn != nil {
  51. wrappedDialFn := tr.wrapTransportDial()
  52. rawTransport.Dial = wrappedDialFn
  53. proxyUrl, err := proxyUrlFn(nil)
  54. if err != nil {
  55. return nil, err
  56. }
  57. if proxyUrl.Scheme != "http" {
  58. return nil, fmt.Errorf("Only HTTP proxy supported, for SOCKS use http.Transport with custom dialers & upstreamproxy.NewProxyDialFunc")
  59. }
  60. if proxyUrl.User != nil {
  61. tr.Username = proxyUrl.User.Username()
  62. tr.Password, _ = proxyUrl.User.Password()
  63. }
  64. // strip username and password from the proxyURL because
  65. // we do not want the wrapped transport to handle authentication
  66. proxyUrl.User = nil
  67. rawTransport.Proxy = http.ProxyURL(proxyUrl)
  68. }
  69. tr.Transport = rawTransport
  70. return tr, nil
  71. }
  72. func (tr *ProxyAuthTransport) preAuthenticateRequest(req *http.Request) error {
  73. tr.mu.Lock()
  74. defer tr.mu.Unlock()
  75. if tr.Authenticator == nil {
  76. return nil
  77. }
  78. return tr.Authenticator.PreAuthenticate(req)
  79. }
  80. func (tr *ProxyAuthTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
  81. if req.URL.Scheme != "http" {
  82. return nil, fmt.Errorf("Only plain HTTP supported, for HTTPS use http.Transport with DialTLS & upstreamproxy.NewProxyDialFunc")
  83. }
  84. err = tr.preAuthenticateRequest(req)
  85. if err != nil {
  86. return nil, err
  87. }
  88. var ha HttpAuthenticator = nil
  89. //Clone request early because RoundTrip will destroy request Body
  90. newReq := cloneRequest(req)
  91. resp, err = tr.Transport.RoundTrip(newReq)
  92. if err != nil {
  93. return resp, proxyError(err)
  94. }
  95. if resp.StatusCode == 407 {
  96. tr.mu.Lock()
  97. defer tr.mu.Unlock()
  98. ha, err = NewHttpAuthenticator(resp, tr.Username, tr.Password)
  99. if err != nil {
  100. return nil, err
  101. }
  102. if ha.IsConnectionBased() {
  103. return nil, proxyError(fmt.Errorf("Connection based auth was not handled by transportConn!"))
  104. }
  105. tr.Authenticator = ha
  106. authenticationLoop:
  107. for {
  108. newReq = cloneRequest(req)
  109. err = tr.Authenticator.Authenticate(newReq, resp)
  110. if err != nil {
  111. return nil, err
  112. }
  113. resp, err = tr.Transport.RoundTrip(newReq)
  114. if err != nil {
  115. return resp, proxyError(err)
  116. }
  117. if resp.StatusCode != 407 {
  118. if tr.Authenticator != nil && tr.Authenticator.IsComplete() {
  119. tr.Authenticator.Reset()
  120. }
  121. break authenticationLoop
  122. } else {
  123. }
  124. }
  125. }
  126. return resp, err
  127. }
  128. // wrapTransportDial wraps original transport Dial function
  129. // and returns a new net.Conn interface provided by transportConn
  130. // that allows us to intercept both outgoing requests and incoming
  131. // responses and examine / mutate them
  132. func (tr *ProxyAuthTransport) wrapTransportDial() DialFunc {
  133. return func(network, addr string) (net.Conn, error) {
  134. c, err := tr.Dial("tcp", addr)
  135. if err != nil {
  136. return nil, err
  137. }
  138. tc := newTransportConn(c, tr)
  139. return tc, nil
  140. }
  141. }
  142. func cloneRequest(r *http.Request) *http.Request {
  143. // shallow copy of the struct
  144. r2 := new(http.Request)
  145. *r2 = *r
  146. // deep copy of the Header
  147. r2.Header = make(http.Header)
  148. for k, s := range r.Header {
  149. r2.Header[k] = s
  150. }
  151. if r.Body != nil {
  152. body, _ := ioutil.ReadAll(r.Body)
  153. defer r.Body.Close()
  154. // restore original request Body
  155. // drained by ReadAll()
  156. r.Body = ioutil.NopCloser(bytes.NewReader(body))
  157. r2.Body = ioutil.NopCloser(bytes.NewReader(body))
  158. }
  159. return r2
  160. }
  161. type transportConn struct {
  162. net.Conn
  163. requestInterceptor io.Writer
  164. reqDone chan struct{}
  165. errChannel chan error
  166. lastRequest *http.Request
  167. authenticator HttpAuthenticator
  168. transport *ProxyAuthTransport
  169. }
  170. func newTransportConn(c net.Conn, tr *ProxyAuthTransport) *transportConn {
  171. tc := &transportConn{
  172. Conn: c,
  173. reqDone: make(chan struct{}),
  174. errChannel: make(chan error),
  175. transport: tr,
  176. }
  177. // Intercept outgoing request as it is written out to server and store it
  178. // in case it needs to be authenticated and replayed
  179. //NOTE that pipelining is currently not supported
  180. pr, pw := io.Pipe()
  181. tc.requestInterceptor = pw
  182. requestReader := bufio.NewReader(pr)
  183. go func() {
  184. requestInterceptLoop:
  185. for {
  186. req, err := http.ReadRequest(requestReader)
  187. if err != nil {
  188. tc.Conn.Close()
  189. pr.Close()
  190. pw.Close()
  191. tc.errChannel <- fmt.Errorf("intercept request loop http.ReadRequest error: %s", err)
  192. break requestInterceptLoop
  193. }
  194. //read and copy entire body
  195. body, _ := ioutil.ReadAll(req.Body)
  196. tc.lastRequest = req
  197. tc.lastRequest.Body = ioutil.NopCloser(bytes.NewReader(body))
  198. //Signal when we have a complete request
  199. tc.reqDone <- struct{}{}
  200. }
  201. }()
  202. return tc
  203. }
  204. // Read peeks into the new response and checks if the proxy requests authentication
  205. // If so, the last intercepted request is authenticated against the response
  206. // in case of connection based auth scheme(i.e. NTLM)
  207. // All the non-connection based schemes are handled by the ProxyAuthTransport.RoundTrip()
  208. func (tc *transportConn) Read(p []byte) (n int, read_err error) {
  209. n, read_err = tc.Conn.Read(p)
  210. if n < HTTP_STAT_LINE_LENGTH {
  211. return
  212. }
  213. select {
  214. case _ = <-tc.reqDone:
  215. line := string(p[:HTTP_STAT_LINE_LENGTH])
  216. //This is a new response
  217. //Let's see if proxy requests authentication
  218. f := strings.SplitN(line, " ", 2)
  219. readBufferReader := io.NewSectionReader(bytes.NewReader(p), 0, int64(n))
  220. responseReader := bufio.NewReader(readBufferReader)
  221. if (f[0] == "HTTP/1.0" || f[0] == "HTTP/1.1") && f[1] == "407" {
  222. resp, err := http.ReadResponse(responseReader, nil)
  223. if err != nil {
  224. return 0, err
  225. }
  226. ha, err := NewHttpAuthenticator(resp, tc.transport.Username, tc.transport.Password)
  227. if err != nil {
  228. return 0, err
  229. }
  230. // If connection based auth is requested, we are going to
  231. // authenticate request on this very connection
  232. // otherwise just return what we read
  233. if !ha.IsConnectionBased() {
  234. return
  235. }
  236. // Drain the rest of the response
  237. // in order to perform auth handshake
  238. // on the connection
  239. readBufferReader.Seek(0, 0)
  240. responseReader = bufio.NewReader(io.MultiReader(readBufferReader, tc.Conn))
  241. resp, err = http.ReadResponse(responseReader, nil)
  242. if err != nil {
  243. return 0, err
  244. }
  245. ioutil.ReadAll(resp.Body)
  246. resp.Body.Close()
  247. if tc.authenticator == nil {
  248. tc.authenticator = ha
  249. }
  250. if resp.Close == true {
  251. // Server side indicated that it is closing this connection,
  252. // dial a new one
  253. addr := tc.Conn.RemoteAddr()
  254. tc.Conn.Close()
  255. tc.Conn, err = tc.transport.Dial(addr.Network(), addr.String())
  256. if err != nil {
  257. return 0, err
  258. }
  259. }
  260. // Authenticate and replay the request on the connection
  261. err = tc.authenticator.Authenticate(tc.lastRequest, resp)
  262. if err != nil {
  263. return 0, err
  264. }
  265. tc.lastRequest.WriteProxy(tc)
  266. return tc.Read(p)
  267. }
  268. case err := <-tc.errChannel:
  269. return 0, err
  270. default:
  271. }
  272. return
  273. }
  274. func (tc *transportConn) Write(p []byte) (n int, err error) {
  275. n, err = tc.Conn.Write(p)
  276. //also write data to the request interceptor
  277. tc.requestInterceptor.Write(p[:n])
  278. return n, err
  279. }