https.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. package goproxy
  2. import (
  3. "bufio"
  4. "crypto/tls"
  5. "errors"
  6. "io"
  7. "io/ioutil"
  8. "net"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "sync/atomic"
  17. )
  18. type ConnectActionLiteral int
  19. const (
  20. ConnectAccept = iota
  21. ConnectReject
  22. ConnectMitm
  23. ConnectHijack
  24. ConnectHTTPMitm
  25. ConnectProxyAuthHijack
  26. )
  27. var (
  28. OkConnect = &ConnectAction{Action: ConnectAccept, TLSConfig: TLSConfigFromCA(&GoproxyCa)}
  29. MitmConnect = &ConnectAction{Action: ConnectMitm, TLSConfig: TLSConfigFromCA(&GoproxyCa)}
  30. HTTPMitmConnect = &ConnectAction{Action: ConnectHTTPMitm, TLSConfig: TLSConfigFromCA(&GoproxyCa)}
  31. RejectConnect = &ConnectAction{Action: ConnectReject, TLSConfig: TLSConfigFromCA(&GoproxyCa)}
  32. httpsRegexp = regexp.MustCompile(`^https:\/\/`)
  33. )
  34. // ConnectAction enables the caller to override the standard connect flow.
  35. // When Action is ConnectHijack, it is up to the implementer to send the
  36. // HTTP 200, or any other valid http response back to the client from within the
  37. // Hijack func
  38. type ConnectAction struct {
  39. Action ConnectActionLiteral
  40. Hijack func(req *http.Request, client net.Conn, ctx *ProxyCtx)
  41. TLSConfig func(host string, ctx *ProxyCtx) (*tls.Config, error)
  42. }
  43. func stripPort(s string) string {
  44. ix := strings.IndexRune(s, ':')
  45. if ix == -1 {
  46. return s
  47. }
  48. return s[:ix]
  49. }
  50. func (proxy *ProxyHttpServer) dial(network, addr string) (c net.Conn, err error) {
  51. if proxy.Tr.Dial != nil {
  52. return proxy.Tr.Dial(network, addr)
  53. }
  54. return net.Dial(network, addr)
  55. }
  56. func (proxy *ProxyHttpServer) connectDial(network, addr string) (c net.Conn, err error) {
  57. if proxy.ConnectDial == nil {
  58. return proxy.dial(network, addr)
  59. }
  60. return proxy.ConnectDial(network, addr)
  61. }
  62. type halfClosable interface {
  63. net.Conn
  64. CloseWrite() error
  65. CloseRead() error
  66. }
  67. var _ halfClosable = (*net.TCPConn)(nil)
  68. func (proxy *ProxyHttpServer) handleHttps(w http.ResponseWriter, r *http.Request) {
  69. ctx := &ProxyCtx{Req: r, Session: atomic.AddInt64(&proxy.sess, 1), Proxy: proxy, certStore: proxy.CertStore}
  70. hij, ok := w.(http.Hijacker)
  71. if !ok {
  72. panic("httpserver does not support hijacking")
  73. }
  74. proxyClient, _, e := hij.Hijack()
  75. if e != nil {
  76. panic("Cannot hijack connection " + e.Error())
  77. }
  78. ctx.Logf("Running %d CONNECT handlers", len(proxy.httpsHandlers))
  79. todo, host := OkConnect, r.URL.Host
  80. for i, h := range proxy.httpsHandlers {
  81. newtodo, newhost := h.HandleConnect(host, ctx)
  82. // If found a result, break the loop immediately
  83. if newtodo != nil {
  84. todo, host = newtodo, newhost
  85. ctx.Logf("on %dth handler: %v %s", i, todo, host)
  86. break
  87. }
  88. }
  89. switch todo.Action {
  90. case ConnectAccept:
  91. if !hasPort.MatchString(host) {
  92. host += ":80"
  93. }
  94. targetSiteCon, err := proxy.connectDial("tcp", host)
  95. if err != nil {
  96. httpError(proxyClient, ctx, err)
  97. return
  98. }
  99. ctx.Logf("Accepting CONNECT to %s", host)
  100. proxyClient.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
  101. targetTCP, targetOK := targetSiteCon.(halfClosable)
  102. proxyClientTCP, clientOK := proxyClient.(halfClosable)
  103. if targetOK && clientOK {
  104. go copyAndClose(ctx, targetTCP, proxyClientTCP)
  105. go copyAndClose(ctx, proxyClientTCP, targetTCP)
  106. } else {
  107. go func() {
  108. var wg sync.WaitGroup
  109. wg.Add(2)
  110. go copyOrWarn(ctx, targetSiteCon, proxyClient, &wg)
  111. go copyOrWarn(ctx, proxyClient, targetSiteCon, &wg)
  112. wg.Wait()
  113. proxyClient.Close()
  114. targetSiteCon.Close()
  115. }()
  116. }
  117. case ConnectHijack:
  118. todo.Hijack(r, proxyClient, ctx)
  119. case ConnectHTTPMitm:
  120. proxyClient.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
  121. ctx.Logf("Assuming CONNECT is plain HTTP tunneling, mitm proxying it")
  122. targetSiteCon, err := proxy.connectDial("tcp", host)
  123. if err != nil {
  124. ctx.Warnf("Error dialing to %s: %s", host, err.Error())
  125. return
  126. }
  127. for {
  128. client := bufio.NewReader(proxyClient)
  129. remote := bufio.NewReader(targetSiteCon)
  130. req, err := http.ReadRequest(client)
  131. if err != nil && err != io.EOF {
  132. ctx.Warnf("cannot read request of MITM HTTP client: %+#v", err)
  133. }
  134. if err != nil {
  135. return
  136. }
  137. req, resp := proxy.filterRequest(req, ctx)
  138. if resp == nil {
  139. if err := req.Write(targetSiteCon); err != nil {
  140. httpError(proxyClient, ctx, err)
  141. return
  142. }
  143. resp, err = http.ReadResponse(remote, req)
  144. if err != nil {
  145. httpError(proxyClient, ctx, err)
  146. return
  147. }
  148. defer resp.Body.Close()
  149. }
  150. resp = proxy.filterResponse(resp, ctx)
  151. if err := resp.Write(proxyClient); err != nil {
  152. httpError(proxyClient, ctx, err)
  153. return
  154. }
  155. }
  156. case ConnectMitm:
  157. proxyClient.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
  158. ctx.Logf("Assuming CONNECT is TLS, mitm proxying it")
  159. // this goes in a separate goroutine, so that the net/http server won't think we're
  160. // still handling the request even after hijacking the connection. Those HTTP CONNECT
  161. // request can take forever, and the server will be stuck when "closed".
  162. // TODO: Allow Server.Close() mechanism to shut down this connection as nicely as possible
  163. tlsConfig := defaultTLSConfig
  164. if todo.TLSConfig != nil {
  165. var err error
  166. tlsConfig, err = todo.TLSConfig(host, ctx)
  167. if err != nil {
  168. httpError(proxyClient, ctx, err)
  169. return
  170. }
  171. }
  172. go func() {
  173. //TODO: cache connections to the remote website
  174. rawClientTls := tls.Server(proxyClient, tlsConfig)
  175. if err := rawClientTls.Handshake(); err != nil {
  176. ctx.Warnf("Cannot handshake client %v %v", r.Host, err)
  177. return
  178. }
  179. defer rawClientTls.Close()
  180. clientTlsReader := bufio.NewReader(rawClientTls)
  181. for !isEof(clientTlsReader) {
  182. req, err := http.ReadRequest(clientTlsReader)
  183. var ctx = &ProxyCtx{Req: req, Session: atomic.AddInt64(&proxy.sess, 1), Proxy: proxy, UserData: ctx.UserData}
  184. if err != nil && err != io.EOF {
  185. return
  186. }
  187. if err != nil {
  188. ctx.Warnf("Cannot read TLS request from mitm'd client %v %v", r.Host, err)
  189. return
  190. }
  191. req.RemoteAddr = r.RemoteAddr // since we're converting the request, need to carry over the original connecting IP as well
  192. ctx.Logf("req %v", r.Host)
  193. if !httpsRegexp.MatchString(req.URL.String()) {
  194. req.URL, err = url.Parse("https://" + r.Host + req.URL.String())
  195. }
  196. // Bug fix which goproxy fails to provide request
  197. // information URL in the context when does HTTPS MITM
  198. ctx.Req = req
  199. req, resp := proxy.filterRequest(req, ctx)
  200. if resp == nil {
  201. if isWebSocketRequest(req) {
  202. ctx.Logf("Request looks like websocket upgrade.")
  203. proxy.serveWebsocketTLS(ctx, w, req, tlsConfig, rawClientTls)
  204. return
  205. }
  206. if err != nil {
  207. ctx.Warnf("Illegal URL %s", "https://"+r.Host+req.URL.Path)
  208. return
  209. }
  210. removeProxyHeaders(ctx, req)
  211. resp, err = ctx.RoundTrip(req)
  212. if err != nil {
  213. ctx.Warnf("Cannot read TLS response from mitm'd server %v", err)
  214. return
  215. }
  216. ctx.Logf("resp %v", resp.Status)
  217. }
  218. resp = proxy.filterResponse(resp, ctx)
  219. defer resp.Body.Close()
  220. text := resp.Status
  221. statusCode := strconv.Itoa(resp.StatusCode) + " "
  222. if strings.HasPrefix(text, statusCode) {
  223. text = text[len(statusCode):]
  224. }
  225. // always use 1.1 to support chunked encoding
  226. if _, err := io.WriteString(rawClientTls, "HTTP/1.1"+" "+statusCode+text+"\r\n"); err != nil {
  227. ctx.Warnf("Cannot write TLS response HTTP status from mitm'd client: %v", err)
  228. return
  229. }
  230. // Since we don't know the length of resp, return chunked encoded response
  231. // TODO: use a more reasonable scheme
  232. resp.Header.Del("Content-Length")
  233. resp.Header.Set("Transfer-Encoding", "chunked")
  234. // Force connection close otherwise chrome will keep CONNECT tunnel open forever
  235. resp.Header.Set("Connection", "close")
  236. if err := resp.Header.Write(rawClientTls); err != nil {
  237. ctx.Warnf("Cannot write TLS response header from mitm'd client: %v", err)
  238. return
  239. }
  240. if _, err = io.WriteString(rawClientTls, "\r\n"); err != nil {
  241. ctx.Warnf("Cannot write TLS response header end from mitm'd client: %v", err)
  242. return
  243. }
  244. chunked := newChunkedWriter(rawClientTls)
  245. if _, err := io.Copy(chunked, resp.Body); err != nil {
  246. ctx.Warnf("Cannot write TLS response body from mitm'd client: %v", err)
  247. return
  248. }
  249. if err := chunked.Close(); err != nil {
  250. ctx.Warnf("Cannot write TLS chunked EOF from mitm'd client: %v", err)
  251. return
  252. }
  253. if _, err = io.WriteString(rawClientTls, "\r\n"); err != nil {
  254. ctx.Warnf("Cannot write TLS response chunked trailer from mitm'd client: %v", err)
  255. return
  256. }
  257. }
  258. ctx.Logf("Exiting on EOF")
  259. }()
  260. case ConnectProxyAuthHijack:
  261. proxyClient.Write([]byte("HTTP/1.1 407 Proxy Authentication Required\r\n"))
  262. todo.Hijack(r, proxyClient, ctx)
  263. case ConnectReject:
  264. if ctx.Resp != nil {
  265. if err := ctx.Resp.Write(proxyClient); err != nil {
  266. ctx.Warnf("Cannot write response that reject http CONNECT: %v", err)
  267. }
  268. }
  269. proxyClient.Close()
  270. }
  271. }
  272. func httpError(w io.WriteCloser, ctx *ProxyCtx, err error) {
  273. if _, err := io.WriteString(w, "HTTP/1.1 502 Bad Gateway\r\n\r\n"); err != nil {
  274. ctx.Warnf("Error responding to client: %s", err)
  275. }
  276. if err := w.Close(); err != nil {
  277. ctx.Warnf("Error closing client connection: %s", err)
  278. }
  279. }
  280. func copyOrWarn(ctx *ProxyCtx, dst io.Writer, src io.Reader, wg *sync.WaitGroup) {
  281. if _, err := io.Copy(dst, src); err != nil {
  282. ctx.Warnf("Error copying to client: %s", err)
  283. }
  284. wg.Done()
  285. }
  286. func copyAndClose(ctx *ProxyCtx, dst, src halfClosable) {
  287. if _, err := io.Copy(dst, src); err != nil {
  288. ctx.Warnf("Error copying to client: %s", err)
  289. }
  290. dst.CloseWrite()
  291. src.CloseRead()
  292. }
  293. func dialerFromEnv(proxy *ProxyHttpServer) func(network, addr string) (net.Conn, error) {
  294. https_proxy := os.Getenv("HTTPS_PROXY")
  295. if https_proxy == "" {
  296. https_proxy = os.Getenv("https_proxy")
  297. }
  298. if https_proxy == "" {
  299. return nil
  300. }
  301. return proxy.NewConnectDialToProxy(https_proxy)
  302. }
  303. func (proxy *ProxyHttpServer) NewConnectDialToProxy(https_proxy string) func(network, addr string) (net.Conn, error) {
  304. return proxy.NewConnectDialToProxyWithHandler(https_proxy, nil)
  305. }
  306. func (proxy *ProxyHttpServer) NewConnectDialToProxyWithHandler(https_proxy string, connectReqHandler func(req *http.Request)) func(network, addr string) (net.Conn, error) {
  307. u, err := url.Parse(https_proxy)
  308. if err != nil {
  309. return nil
  310. }
  311. if u.Scheme == "" || u.Scheme == "http" {
  312. if strings.IndexRune(u.Host, ':') == -1 {
  313. u.Host += ":80"
  314. }
  315. return func(network, addr string) (net.Conn, error) {
  316. connectReq := &http.Request{
  317. Method: "CONNECT",
  318. URL: &url.URL{Opaque: addr},
  319. Host: addr,
  320. Header: make(http.Header),
  321. }
  322. if connectReqHandler != nil {
  323. connectReqHandler(connectReq)
  324. }
  325. c, err := proxy.dial(network, u.Host)
  326. if err != nil {
  327. return nil, err
  328. }
  329. connectReq.Write(c)
  330. // Read response.
  331. // Okay to use and discard buffered reader here, because
  332. // TLS server will not speak until spoken to.
  333. br := bufio.NewReader(c)
  334. resp, err := http.ReadResponse(br, connectReq)
  335. if err != nil {
  336. c.Close()
  337. return nil, err
  338. }
  339. defer resp.Body.Close()
  340. if resp.StatusCode != 200 {
  341. resp, err := ioutil.ReadAll(resp.Body)
  342. if err != nil {
  343. return nil, err
  344. }
  345. c.Close()
  346. return nil, errors.New("proxy refused connection" + string(resp))
  347. }
  348. return c, nil
  349. }
  350. }
  351. if u.Scheme == "https" || u.Scheme == "wss" {
  352. if strings.IndexRune(u.Host, ':') == -1 {
  353. u.Host += ":443"
  354. }
  355. return func(network, addr string) (net.Conn, error) {
  356. c, err := proxy.dial(network, u.Host)
  357. if err != nil {
  358. return nil, err
  359. }
  360. c = tls.Client(c, proxy.Tr.TLSClientConfig)
  361. connectReq := &http.Request{
  362. Method: "CONNECT",
  363. URL: &url.URL{Opaque: addr},
  364. Host: addr,
  365. Header: make(http.Header),
  366. }
  367. if connectReqHandler != nil {
  368. connectReqHandler(connectReq)
  369. }
  370. connectReq.Write(c)
  371. // Read response.
  372. // Okay to use and discard buffered reader here, because
  373. // TLS server will not speak until spoken to.
  374. br := bufio.NewReader(c)
  375. resp, err := http.ReadResponse(br, connectReq)
  376. if err != nil {
  377. c.Close()
  378. return nil, err
  379. }
  380. defer resp.Body.Close()
  381. if resp.StatusCode != 200 {
  382. body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 500))
  383. if err != nil {
  384. return nil, err
  385. }
  386. c.Close()
  387. return nil, errors.New("proxy refused connection" + string(body))
  388. }
  389. return c, nil
  390. }
  391. }
  392. return nil
  393. }
  394. func TLSConfigFromCA(ca *tls.Certificate) func(host string, ctx *ProxyCtx) (*tls.Config, error) {
  395. return func(host string, ctx *ProxyCtx) (*tls.Config, error) {
  396. var err error
  397. var cert *tls.Certificate
  398. hostname := stripPort(host)
  399. config := defaultTLSConfig.Clone()
  400. ctx.Logf("signing for %s", stripPort(host))
  401. genCert := func() (*tls.Certificate, error) {
  402. return signHost(*ca, []string{hostname})
  403. }
  404. if ctx.certStore != nil {
  405. cert, err = ctx.certStore.Fetch(hostname, genCert)
  406. } else {
  407. cert, err = genCert()
  408. }
  409. if err != nil {
  410. ctx.Warnf("Cannot sign host certificate with provided CA: %s", err)
  411. return nil, err
  412. }
  413. config.Certificates = append(config.Certificates, *cert)
  414. return config, nil
  415. }
  416. }