http_proxy.go 5.4 KB

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