http_proxy.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // Copyright 2017 frp team
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //go:build !frps
  15. package plugin
  16. import (
  17. "bufio"
  18. "encoding/base64"
  19. "io"
  20. "net"
  21. "net/http"
  22. "strings"
  23. "time"
  24. libio "github.com/fatedier/golib/io"
  25. libnet "github.com/fatedier/golib/net"
  26. v1 "github.com/fatedier/frp/pkg/config/v1"
  27. netpkg "github.com/fatedier/frp/pkg/util/net"
  28. "github.com/fatedier/frp/pkg/util/util"
  29. )
  30. func init() {
  31. Register(v1.PluginHTTPProxy, NewHTTPProxyPlugin)
  32. }
  33. type HTTPProxy struct {
  34. opts *v1.HTTPProxyPluginOptions
  35. l *Listener
  36. s *http.Server
  37. }
  38. func NewHTTPProxyPlugin(options v1.ClientPluginOptions) (Plugin, error) {
  39. opts := options.(*v1.HTTPProxyPluginOptions)
  40. listener := NewProxyListener()
  41. hp := &HTTPProxy{
  42. l: listener,
  43. opts: opts,
  44. }
  45. hp.s = &http.Server{
  46. Handler: hp,
  47. ReadHeaderTimeout: 60 * time.Second,
  48. }
  49. go func() {
  50. _ = hp.s.Serve(listener)
  51. }()
  52. return hp, nil
  53. }
  54. func (hp *HTTPProxy) Name() string {
  55. return v1.PluginHTTPProxy
  56. }
  57. func (hp *HTTPProxy) Handle(conn io.ReadWriteCloser, realConn net.Conn, _ *ExtraInfo) {
  58. wrapConn := netpkg.WrapReadWriteCloserToConn(conn, realConn)
  59. sc, rd := libnet.NewSharedConn(wrapConn)
  60. firstBytes := make([]byte, 7)
  61. _, err := rd.Read(firstBytes)
  62. if err != nil {
  63. wrapConn.Close()
  64. return
  65. }
  66. if strings.ToUpper(string(firstBytes)) == "CONNECT" {
  67. bufRd := bufio.NewReader(sc)
  68. request, err := http.ReadRequest(bufRd)
  69. if err != nil {
  70. wrapConn.Close()
  71. return
  72. }
  73. hp.handleConnectReq(request, libio.WrapReadWriteCloser(bufRd, wrapConn, wrapConn.Close))
  74. return
  75. }
  76. _ = hp.l.PutConn(sc)
  77. }
  78. func (hp *HTTPProxy) Close() error {
  79. hp.s.Close()
  80. hp.l.Close()
  81. return nil
  82. }
  83. func (hp *HTTPProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  84. if ok := hp.Auth(req); !ok {
  85. rw.Header().Set("Proxy-Authenticate", "Basic")
  86. rw.WriteHeader(http.StatusProxyAuthRequired)
  87. return
  88. }
  89. if req.Method == http.MethodConnect {
  90. // deprecated
  91. // Connect request is handled in Handle function.
  92. hp.ConnectHandler(rw, req)
  93. } else {
  94. hp.HTTPHandler(rw, req)
  95. }
  96. }
  97. func (hp *HTTPProxy) HTTPHandler(rw http.ResponseWriter, req *http.Request) {
  98. removeProxyHeaders(req)
  99. resp, err := http.DefaultTransport.RoundTrip(req)
  100. if err != nil {
  101. http.Error(rw, err.Error(), http.StatusInternalServerError)
  102. return
  103. }
  104. defer resp.Body.Close()
  105. copyHeaders(rw.Header(), resp.Header)
  106. rw.WriteHeader(resp.StatusCode)
  107. _, err = io.Copy(rw, resp.Body)
  108. if err != nil && err != io.EOF {
  109. return
  110. }
  111. }
  112. // deprecated
  113. // Hijack needs to SetReadDeadline on the Conn of the request, but if we use stream compression here,
  114. // we may always get i/o timeout error.
  115. func (hp *HTTPProxy) ConnectHandler(rw http.ResponseWriter, req *http.Request) {
  116. hj, ok := rw.(http.Hijacker)
  117. if !ok {
  118. rw.WriteHeader(http.StatusInternalServerError)
  119. return
  120. }
  121. client, _, err := hj.Hijack()
  122. if err != nil {
  123. rw.WriteHeader(http.StatusInternalServerError)
  124. return
  125. }
  126. remote, err := net.Dial("tcp", req.URL.Host)
  127. if err != nil {
  128. http.Error(rw, "Failed", http.StatusBadRequest)
  129. client.Close()
  130. return
  131. }
  132. _, _ = client.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
  133. go libio.Join(remote, client)
  134. }
  135. func (hp *HTTPProxy) Auth(req *http.Request) bool {
  136. if hp.opts.HTTPUser == "" && hp.opts.HTTPPassword == "" {
  137. return true
  138. }
  139. s := strings.SplitN(req.Header.Get("Proxy-Authorization"), " ", 2)
  140. if len(s) != 2 {
  141. return false
  142. }
  143. b, err := base64.StdEncoding.DecodeString(s[1])
  144. if err != nil {
  145. return false
  146. }
  147. pair := strings.SplitN(string(b), ":", 2)
  148. if len(pair) != 2 {
  149. return false
  150. }
  151. if !util.ConstantTimeEqString(pair[0], hp.opts.HTTPUser) ||
  152. !util.ConstantTimeEqString(pair[1], hp.opts.HTTPPassword) {
  153. time.Sleep(200 * time.Millisecond)
  154. return false
  155. }
  156. return true
  157. }
  158. func (hp *HTTPProxy) handleConnectReq(req *http.Request, rwc io.ReadWriteCloser) {
  159. defer rwc.Close()
  160. if ok := hp.Auth(req); !ok {
  161. res := getBadResponse()
  162. _ = res.Write(rwc)
  163. if res.Body != nil {
  164. res.Body.Close()
  165. }
  166. return
  167. }
  168. remote, err := net.Dial("tcp", req.URL.Host)
  169. if err != nil {
  170. res := &http.Response{
  171. StatusCode: 400,
  172. Proto: "HTTP/1.1",
  173. ProtoMajor: 1,
  174. ProtoMinor: 1,
  175. }
  176. _ = res.Write(rwc)
  177. return
  178. }
  179. _, _ = rwc.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
  180. libio.Join(remote, rwc)
  181. }
  182. func copyHeaders(dst, src http.Header) {
  183. for key, values := range src {
  184. for _, value := range values {
  185. dst.Add(key, value)
  186. }
  187. }
  188. }
  189. func removeProxyHeaders(req *http.Request) {
  190. req.RequestURI = ""
  191. req.Header.Del("Proxy-Connection")
  192. req.Header.Del("Connection")
  193. req.Header.Del("Proxy-Authenticate")
  194. req.Header.Del("Proxy-Authorization")
  195. req.Header.Del("TE")
  196. req.Header.Del("Trailers")
  197. req.Header.Del("Transfer-Encoding")
  198. req.Header.Del("Upgrade")
  199. }
  200. func getBadResponse() *http.Response {
  201. header := make(map[string][]string)
  202. header["Proxy-Authenticate"] = []string{"Basic"}
  203. header["Connection"] = []string{"close"}
  204. res := &http.Response{
  205. Status: "407 Not authorized",
  206. StatusCode: 407,
  207. Proto: "HTTP/1.1",
  208. ProtoMajor: 1,
  209. ProtoMinor: 1,
  210. Header: header,
  211. }
  212. return res
  213. }