transport_proxy_auth.go 9.1 KB

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