frp/pkg/plugin/client/http_proxy.go

253 lines
5.5 KiB
Go
Raw Normal View History

2017-05-30 08:37:51 +02:00
// Copyright 2017 frp team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package plugin
import (
"bufio"
2017-05-30 08:37:51 +02:00
"encoding/base64"
"io"
"net"
"net/http"
"strings"
2023-05-28 18:27:27 +02:00
"time"
2017-05-30 08:37:51 +02:00
2023-05-29 08:10:34 +02:00
libio "github.com/fatedier/golib/io"
libnet "github.com/fatedier/golib/net"
2022-08-28 19:02:53 +02:00
2023-05-29 08:10:34 +02:00
utilnet "github.com/fatedier/frp/pkg/util/net"
2023-05-28 18:27:27 +02:00
"github.com/fatedier/frp/pkg/util/util"
2017-05-30 08:37:51 +02:00
)
2020-05-24 11:48:37 +02:00
const PluginHTTPProxy = "http_proxy"
2017-05-30 08:37:51 +02:00
func init() {
2020-05-24 11:48:37 +02:00
Register(PluginHTTPProxy, NewHTTPProxyPlugin)
2017-05-30 08:37:51 +02:00
}
2020-05-24 11:48:37 +02:00
type HTTPProxy struct {
2017-05-30 08:37:51 +02:00
l *Listener
s *http.Server
AuthUser string
AuthPasswd string
}
2020-05-24 11:48:37 +02:00
func NewHTTPProxyPlugin(params map[string]string) (Plugin, error) {
2017-05-30 08:37:51 +02:00
user := params["plugin_http_user"]
passwd := params["plugin_http_passwd"]
listener := NewProxyListener()
2020-05-24 11:48:37 +02:00
hp := &HTTPProxy{
2017-05-30 08:37:51 +02:00
l: listener,
AuthUser: user,
AuthPasswd: passwd,
}
hp.s = &http.Server{
Handler: hp,
}
2022-08-28 19:02:53 +02:00
go func() {
_ = hp.s.Serve(listener)
}()
2017-05-30 08:37:51 +02:00
return hp, nil
}
2020-05-24 11:48:37 +02:00
func (hp *HTTPProxy) Name() string {
return PluginHTTPProxy
2017-05-30 08:37:51 +02:00
}
2020-05-24 11:48:37 +02:00
func (hp *HTTPProxy) Handle(conn io.ReadWriteCloser, realConn net.Conn, extraBufToLocal []byte) {
2023-05-29 08:10:34 +02:00
wrapConn := utilnet.WrapReadWriteCloserToConn(conn, realConn)
2017-05-30 08:37:51 +02:00
2023-05-29 08:10:34 +02:00
sc, rd := libnet.NewSharedConn(wrapConn)
2018-05-06 16:47:26 +02:00
firstBytes := make([]byte, 7)
_, err := rd.Read(firstBytes)
if err != nil {
wrapConn.Close()
return
}
2018-05-06 16:47:26 +02:00
if strings.ToUpper(string(firstBytes)) == "CONNECT" {
bufRd := bufio.NewReader(sc)
request, err := http.ReadRequest(bufRd)
if err != nil {
wrapConn.Close()
return
}
2023-05-29 08:10:34 +02:00
hp.handleConnectReq(request, libio.WrapReadWriteCloser(bufRd, wrapConn, wrapConn.Close))
return
}
2022-08-28 19:02:53 +02:00
_ = hp.l.PutConn(sc)
2017-05-30 08:37:51 +02:00
}
2020-05-24 11:48:37 +02:00
func (hp *HTTPProxy) Close() error {
2017-05-30 08:37:51 +02:00
hp.s.Close()
hp.l.Close()
return nil
}
2020-05-24 11:48:37 +02:00
func (hp *HTTPProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if ok := hp.Auth(req); !ok {
2017-05-30 08:37:51 +02:00
rw.Header().Set("Proxy-Authenticate", "Basic")
rw.WriteHeader(http.StatusProxyAuthRequired)
return
}
if req.Method == http.MethodConnect {
// deprecated
// Connect request is handled in Handle function.
2017-05-30 08:37:51 +02:00
hp.ConnectHandler(rw, req)
} else {
2020-05-24 11:48:37 +02:00
hp.HTTPHandler(rw, req)
2017-05-30 08:37:51 +02:00
}
}
2020-05-24 11:48:37 +02:00
func (hp *HTTPProxy) HTTPHandler(rw http.ResponseWriter, req *http.Request) {
2017-05-30 08:37:51 +02:00
removeProxyHeaders(req)
resp, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
copyHeaders(rw.Header(), resp.Header)
rw.WriteHeader(resp.StatusCode)
_, err = io.Copy(rw, resp.Body)
if err != nil && err != io.EOF {
return
}
}
// deprecated
// Hijack needs to SetReadDeadline on the Conn of the request, but if we use stream compression here,
// we may always get i/o timeout error.
2020-05-24 11:48:37 +02:00
func (hp *HTTPProxy) ConnectHandler(rw http.ResponseWriter, req *http.Request) {
2017-05-30 08:37:51 +02:00
hj, ok := rw.(http.Hijacker)
if !ok {
rw.WriteHeader(http.StatusInternalServerError)
return
}
client, _, err := hj.Hijack()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
remote, err := net.Dial("tcp", req.URL.Host)
if err != nil {
http.Error(rw, "Failed", http.StatusBadRequest)
client.Close()
return
}
2022-08-28 19:02:53 +02:00
_, _ = client.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
2017-05-30 08:37:51 +02:00
2023-05-29 08:10:34 +02:00
go libio.Join(remote, client)
2017-05-30 08:37:51 +02:00
}
2020-05-24 11:48:37 +02:00
func (hp *HTTPProxy) Auth(req *http.Request) bool {
2017-05-30 08:37:51 +02:00
if hp.AuthUser == "" && hp.AuthPasswd == "" {
return true
}
s := strings.SplitN(req.Header.Get("Proxy-Authorization"), " ", 2)
if len(s) != 2 {
return false
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
return false
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
return false
}
2023-05-28 18:27:27 +02:00
if !util.ConstantTimeEqString(pair[0], hp.AuthUser) ||
!util.ConstantTimeEqString(pair[1], hp.AuthPasswd) {
time.Sleep(200 * time.Millisecond)
2017-05-30 08:37:51 +02:00
return false
}
return true
}
2020-05-24 11:48:37 +02:00
func (hp *HTTPProxy) handleConnectReq(req *http.Request, rwc io.ReadWriteCloser) {
defer rwc.Close()
if ok := hp.Auth(req); !ok {
res := getBadResponse()
2022-08-28 19:02:53 +02:00
_ = res.Write(rwc)
if res.Body != nil {
res.Body.Close()
}
return
}
remote, err := net.Dial("tcp", req.URL.Host)
if err != nil {
res := &http.Response{
StatusCode: 400,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
}
2022-08-28 19:02:53 +02:00
_ = res.Write(rwc)
return
}
2022-08-28 19:02:53 +02:00
_, _ = rwc.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
2023-05-29 08:10:34 +02:00
libio.Join(remote, rwc)
}
2017-05-30 08:37:51 +02:00
func copyHeaders(dst, src http.Header) {
for key, values := range src {
for _, value := range values {
dst.Add(key, value)
}
}
}
func removeProxyHeaders(req *http.Request) {
req.RequestURI = ""
req.Header.Del("Proxy-Connection")
req.Header.Del("Connection")
req.Header.Del("Proxy-Authenticate")
req.Header.Del("Proxy-Authorization")
req.Header.Del("TE")
req.Header.Del("Trailers")
req.Header.Del("Transfer-Encoding")
req.Header.Del("Upgrade")
}
func getBadResponse() *http.Response {
header := make(map[string][]string)
header["Proxy-Authenticate"] = []string{"Basic"}
header["Connection"] = []string{"close"}
res := &http.Response{
Status: "407 Not authorized",
StatusCode: 407,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: header,
}
return res
}