http_proxy.go 5.5 KB

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