1
0

http_proxy.go 5.5 KB

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