diff --git a/.gitignore b/.gitignore index f6df315b1e4..c9480d52d3a 100644 --- a/.gitignore +++ b/.gitignore @@ -33,6 +33,7 @@ lastversion/ dist/ .idea/ .vscode/ +.autogen_ssh_key # Cache *.swp diff --git a/Release.md b/Release.md index ca8f3a72057..8e1ea863ea7 100644 --- a/Release.md +++ b/Release.md @@ -1,6 +1,6 @@ ### Features -* New command line parameter `--strict_config` is added to enable strict configuration validation mode. It will throw an error for non-existent fields instead of ignoring them. In future versions, we may set the default value of this parameter to true. +* The new command line parameter `--strict_config` has been added to enable strict configuration validation mode. It will throw an error for unknown fields instead of ignoring them. In future versions, we will set the default value of this parameter to true to avoid misconfigurations. * Support `SSH reverse tunneling`. With this feature, you can expose your local service without running frpc, only using SSH. The SSH reverse tunnel agent has many functional limitations compared to the frpc agent. The currently supported proxy types are tcp, http, https, tcpmux, and stcp. * The frpc tcpmux command line parameters have been updated to support configuring `http_user` and `http_pwd`. * The frpc stcp/sudp/xtcp command line parameters have been updated to support configuring `allow_users`. diff --git a/cmd/frpc/sub/nathole.go b/cmd/frpc/sub/nathole.go index 56fcf67b72a..fb5b08078c2 100644 --- a/cmd/frpc/sub/nathole.go +++ b/cmd/frpc/sub/nathole.go @@ -51,6 +51,7 @@ var natholeDiscoveryCmd = &cobra.Command{ cfg, _, _, _, err := config.LoadClientConfig(cfgFile, strictConfigMode) if err != nil { cfg = &v1.ClientCommonConfig{} + cfg.Complete() } if natHoleSTUNServer != "" { cfg.NatHoleSTUNServer = natHoleSTUNServer diff --git a/pkg/config/load.go b/pkg/config/load.go index b5539745931..cdbb8e916f4 100644 --- a/pkg/config/load.go +++ b/pkg/config/load.go @@ -110,8 +110,11 @@ func LoadConfigureFromFile(path string, c any, strict bool) error { // LoadConfigure loads configuration from bytes and unmarshal into c. // Now it supports json, yaml and toml format. -// TODO(fatedier): strict is not valide for ProxyConfigurer/VisitorConfigurer/ClientPluginOptions. func LoadConfigure(b []byte, c any, strict bool) error { + v1.DisallowUnknownFieldsMu.Lock() + defer v1.DisallowUnknownFieldsMu.Unlock() + v1.DisallowUnknownFields = strict + var tomlObj interface{} // Try to unmarshal as TOML first; swallow errors from that (assume it's not valid TOML). if err := toml.Unmarshal(b, &tomlObj); err == nil { diff --git a/pkg/config/load_test.go b/pkg/config/load_test.go index 9bf7dbbc5be..b3f77800449 100644 --- a/pkg/config/load_test.go +++ b/pkg/config/load_test.go @@ -111,3 +111,56 @@ func TestLoadServerConfigStrictMode(t *testing.T) { } } } + +func TestCustomStructStrictMode(t *testing.T) { + require := require.New(t) + + proxyStr := ` +serverPort = 7000 + +[[proxies]] +name = "test" +type = "tcp" +remotePort = 6000 +` + clientCfg := v1.ClientConfig{} + err := LoadConfigure([]byte(proxyStr), &clientCfg, true) + require.NoError(err) + + proxyStr += `unknown = "unknown"` + err = LoadConfigure([]byte(proxyStr), &clientCfg, true) + require.Error(err) + + visitorStr := ` +serverPort = 7000 + +[[visitors]] +name = "test" +type = "stcp" +bindPort = 6000 +serverName = "server" +` + err = LoadConfigure([]byte(visitorStr), &clientCfg, true) + require.NoError(err) + + visitorStr += `unknown = "unknown"` + err = LoadConfigure([]byte(visitorStr), &clientCfg, true) + require.Error(err) + + pluginStr := ` +serverPort = 7000 + +[[proxies]] +name = "test" +type = "tcp" +remotePort = 6000 +[proxies.plugin] +type = "unix_domain_socket" +unixPath = "/tmp/uds.sock" +` + err = LoadConfigure([]byte(pluginStr), &clientCfg, true) + require.NoError(err) + pluginStr += `unknown = "unknown"` + err = LoadConfigure([]byte(pluginStr), &clientCfg, true) + require.Error(err) +} diff --git a/pkg/config/v1/common.go b/pkg/config/v1/common.go index 72c9d0362c9..24ec9b0d825 100644 --- a/pkg/config/v1/common.go +++ b/pkg/config/v1/common.go @@ -15,9 +15,23 @@ package v1 import ( + "sync" + "github.com/fatedier/frp/pkg/util/util" ) +// TODO(fatedier): Due to the current implementation issue of the go json library, the UnmarshalJSON method +// of a custom struct cannot access the DisallowUnknownFields parameter of the parent decoder. +// Here, a global variable is temporarily used to control whether unknown fields are allowed. +// Once the v2 version is implemented by the community, we can switch to a standardized approach. +// +// https://github.com/golang/go/issues/41144 +// https://github.com/golang/go/discussions/63397 +var ( + DisallowUnknownFields = false + DisallowUnknownFieldsMu sync.Mutex +) + type AuthScope string const ( diff --git a/pkg/config/v1/plugin.go b/pkg/config/v1/plugin.go index bd5ff384a56..db9d0d1a0b2 100644 --- a/pkg/config/v1/plugin.go +++ b/pkg/config/v1/plugin.go @@ -15,6 +15,7 @@ package v1 import ( + "bytes" "encoding/json" "fmt" "reflect" @@ -49,7 +50,13 @@ func (c *TypedClientPluginOptions) UnmarshalJSON(b []byte) error { return fmt.Errorf("unknown plugin type: %s", typeStruct.Type) } options := reflect.New(v).Interface().(ClientPluginOptions) - if err := json.Unmarshal(b, options); err != nil { + + decoder := json.NewDecoder(bytes.NewBuffer(b)) + if DisallowUnknownFields { + decoder.DisallowUnknownFields() + } + + if err := decoder.Decode(options); err != nil { return err } c.ClientPluginOptions = options @@ -77,17 +84,20 @@ var clientPluginOptionsTypeMap = map[string]reflect.Type{ } type HTTP2HTTPSPluginOptions struct { + Type string `json:"type,omitempty"` LocalAddr string `json:"localAddr,omitempty"` HostHeaderRewrite string `json:"hostHeaderRewrite,omitempty"` RequestHeaders HeaderOperations `json:"requestHeaders,omitempty"` } type HTTPProxyPluginOptions struct { + Type string `json:"type,omitempty"` HTTPUser string `json:"httpUser,omitempty"` HTTPPassword string `json:"httpPassword,omitempty"` } type HTTPS2HTTPPluginOptions struct { + Type string `json:"type,omitempty"` LocalAddr string `json:"localAddr,omitempty"` HostHeaderRewrite string `json:"hostHeaderRewrite,omitempty"` RequestHeaders HeaderOperations `json:"requestHeaders,omitempty"` @@ -96,6 +106,7 @@ type HTTPS2HTTPPluginOptions struct { } type HTTPS2HTTPSPluginOptions struct { + Type string `json:"type,omitempty"` LocalAddr string `json:"localAddr,omitempty"` HostHeaderRewrite string `json:"hostHeaderRewrite,omitempty"` RequestHeaders HeaderOperations `json:"requestHeaders,omitempty"` @@ -104,11 +115,13 @@ type HTTPS2HTTPSPluginOptions struct { } type Socks5PluginOptions struct { + Type string `json:"type,omitempty"` Username string `json:"username,omitempty"` Password string `json:"password,omitempty"` } type StaticFilePluginOptions struct { + Type string `json:"type,omitempty"` LocalPath string `json:"localPath,omitempty"` StripPrefix string `json:"stripPrefix,omitempty"` HTTPUser string `json:"httpUser,omitempty"` @@ -116,5 +129,6 @@ type StaticFilePluginOptions struct { } type UnixDomainSocketPluginOptions struct { + Type string `json:"type,omitempty"` UnixPath string `json:"unixPath,omitempty"` } diff --git a/pkg/config/v1/proxy.go b/pkg/config/v1/proxy.go index 0752479f0c5..8e19d00481c 100644 --- a/pkg/config/v1/proxy.go +++ b/pkg/config/v1/proxy.go @@ -15,6 +15,7 @@ package v1 import ( + "bytes" "encoding/json" "errors" "fmt" @@ -177,7 +178,11 @@ func (c *TypedProxyConfig) UnmarshalJSON(b []byte) error { if configurer == nil { return fmt.Errorf("unknown proxy type: %s", typeStruct.Type) } - if err := json.Unmarshal(b, configurer); err != nil { + decoder := json.NewDecoder(bytes.NewBuffer(b)) + if DisallowUnknownFields { + decoder.DisallowUnknownFields() + } + if err := decoder.Decode(configurer); err != nil { return err } c.ProxyConfigurer = configurer diff --git a/pkg/config/v1/visitor.go b/pkg/config/v1/visitor.go index 90ecd86d191..a9b2411ab3d 100644 --- a/pkg/config/v1/visitor.go +++ b/pkg/config/v1/visitor.go @@ -15,6 +15,7 @@ package v1 import ( + "bytes" "encoding/json" "errors" "fmt" @@ -108,7 +109,11 @@ func (c *TypedVisitorConfig) UnmarshalJSON(b []byte) error { if configurer == nil { return fmt.Errorf("unknown visitor type: %s", typeStruct.Type) } - if err := json.Unmarshal(b, configurer); err != nil { + decoder := json.NewDecoder(bytes.NewBuffer(b)) + if DisallowUnknownFields { + decoder.DisallowUnknownFields() + } + if err := decoder.Decode(configurer); err != nil { return err } c.VisitorConfigurer = configurer @@ -120,7 +125,9 @@ func NewVisitorConfigurerByType(t VisitorType) VisitorConfigurer { if !ok { return nil } - return reflect.New(v).Interface().(VisitorConfigurer) + vc := reflect.New(v).Interface().(VisitorConfigurer) + vc.GetBaseConfig().Type = string(t) + return vc } var _ VisitorConfigurer = &STCPVisitorConfig{} diff --git a/pkg/ssh/server.go b/pkg/ssh/server.go index 042f6766f71..30e79c64318 100644 --- a/pkg/ssh/server.go +++ b/pkg/ssh/server.go @@ -56,8 +56,6 @@ type forwardedTCPPayload struct { Addr string Port uint32 - // can be default empty value but do not delete it - // because ssh protocol shoule be reserved OriginAddr string OriginPort uint32 } @@ -117,6 +115,8 @@ func (s *TunnelServer) Run() error { // join workConn and ssh channel c, err := s.openConn(addr) if err != nil { + log.Trace("open conn error: %v", err) + workConn.Close() return false } libio.Join(c, workConn) @@ -180,20 +180,16 @@ func (s *TunnelServer) waitForwardAddrAndExtraPayload( go func() { addrGot := false for req := range requests { - switch req.Type { - case RequestTypeForward: - if !addrGot { - payload := tcpipForward{} - if err := ssh.Unmarshal(req.Payload, &payload); err != nil { - return - } - addrGot = true - addrCh <- &payload - } - default: - if req.WantReply { - _ = req.Reply(true, nil) + if req.Type == RequestTypeForward && !addrGot { + payload := tcpipForward{} + if err := ssh.Unmarshal(req.Payload, &payload); err != nil { + return } + addrGot = true + addrCh <- &payload + } + if req.WantReply { + _ = req.Reply(true, nil) } } }() @@ -271,10 +267,10 @@ func (s *TunnelServer) handleNewChannel(channel ssh.NewChannel, extraPayloadCh c go s.keepAlive(ch) for req := range reqs { - if req.Type != "exec" { - continue + if req.WantReply { + _ = req.Reply(true, nil) } - if len(req.Payload) <= 4 { + if req.Type != "exec" || len(req.Payload) <= 4 { continue } end := 4 + binary.BigEndian.Uint32(req.Payload[:4]) @@ -310,6 +306,9 @@ func (s *TunnelServer) openConn(addr *tcpipForward) (net.Conn, error) { payload := forwardedTCPPayload{ Addr: addr.Host, Port: addr.Port, + // Note: Here is just for compatibility, not the real source address. + OriginAddr: addr.Host, + OriginPort: addr.Port, } channel, reqs, err := s.sshConn.OpenChannel(ChannelTypeServerOpenChannel, ssh.Marshal(&payload)) if err != nil { diff --git a/test/e2e/pkg/ssh/client.go b/test/e2e/pkg/ssh/client.go new file mode 100644 index 00000000000..1a923e9c420 --- /dev/null +++ b/test/e2e/pkg/ssh/client.go @@ -0,0 +1,89 @@ +package ssh + +import ( + "net" + + libio "github.com/fatedier/golib/io" + "golang.org/x/crypto/ssh" +) + +type TunnelClient struct { + localAddr string + sshServer string + commands string + + sshConn *ssh.Client + ln net.Listener +} + +func NewTunnelClient(localAddr string, sshServer string, commands string) *TunnelClient { + return &TunnelClient{ + localAddr: localAddr, + sshServer: sshServer, + commands: commands, + } +} + +func (c *TunnelClient) Start() error { + config := &ssh.ClientConfig{ + User: "v0", + HostKeyCallback: func(string, net.Addr, ssh.PublicKey) error { return nil }, + } + + conn, err := ssh.Dial("tcp", c.sshServer, config) + if err != nil { + return err + } + c.sshConn = conn + + l, err := conn.Listen("tcp", "0.0.0.0:80") + if err != nil { + return err + } + c.ln = l + ch, req, err := conn.OpenChannel("direct", []byte("")) + if err != nil { + return err + } + defer ch.Close() + go ssh.DiscardRequests(req) + + type command struct { + Cmd string + } + _, err = ch.SendRequest("exec", false, ssh.Marshal(command{Cmd: c.commands})) + if err != nil { + return err + } + + go c.serveListener() + return nil +} + +func (c *TunnelClient) Close() { + if c.sshConn != nil { + _ = c.sshConn.Close() + } + if c.ln != nil { + _ = c.ln.Close() + } +} + +func (c *TunnelClient) serveListener() { + for { + conn, err := c.ln.Accept() + if err != nil { + return + } + go c.hanldeConn(conn) + } +} + +func (c *TunnelClient) hanldeConn(conn net.Conn) { + defer conn.Close() + local, err := net.Dial("tcp", c.localAddr) + if err != nil { + return + } + _, _, _ = libio.Join(local, conn) +} diff --git a/test/e2e/v1/features/ssh_tunnel.go b/test/e2e/v1/features/ssh_tunnel.go new file mode 100644 index 00000000000..f67d87aaf99 --- /dev/null +++ b/test/e2e/v1/features/ssh_tunnel.go @@ -0,0 +1,193 @@ +package features + +import ( + "crypto/tls" + "fmt" + "time" + + "github.com/onsi/ginkgo/v2" + + "github.com/fatedier/frp/pkg/transport" + "github.com/fatedier/frp/test/e2e/framework" + "github.com/fatedier/frp/test/e2e/framework/consts" + "github.com/fatedier/frp/test/e2e/mock/server/httpserver" + "github.com/fatedier/frp/test/e2e/mock/server/streamserver" + "github.com/fatedier/frp/test/e2e/pkg/request" + "github.com/fatedier/frp/test/e2e/pkg/ssh" +) + +var _ = ginkgo.Describe("[Feature: SSH Tunnel]", func() { + f := framework.NewDefaultFramework() + + ginkgo.It("tcp", func() { + sshPort := f.AllocPort() + serverConf := consts.DefaultServerConfig + fmt.Sprintf(` + sshTunnelGateway.bindPort = %d + `, sshPort) + + f.RunProcesses([]string{serverConf}, nil) + + localPort := f.PortByName(framework.TCPEchoServerPort) + remotePort := f.AllocPort() + tc := ssh.NewTunnelClient( + fmt.Sprintf("127.0.0.1:%d", localPort), + fmt.Sprintf("127.0.0.1:%d", sshPort), + fmt.Sprintf("tcp --remote_port %d", remotePort), + ) + framework.ExpectNoError(tc.Start()) + defer tc.Close() + + time.Sleep(time.Second) + framework.NewRequestExpect(f).Port(remotePort).Ensure() + }) + + ginkgo.It("http", func() { + sshPort := f.AllocPort() + vhostPort := f.AllocPort() + serverConf := consts.DefaultServerConfig + fmt.Sprintf(` + vhostHTTPPort = %d + sshTunnelGateway.bindPort = %d + `, vhostPort, sshPort) + + f.RunProcesses([]string{serverConf}, nil) + + localPort := f.PortByName(framework.HTTPSimpleServerPort) + tc := ssh.NewTunnelClient( + fmt.Sprintf("127.0.0.1:%d", localPort), + fmt.Sprintf("127.0.0.1:%d", sshPort), + "http --custom_domain test.example.com", + ) + framework.ExpectNoError(tc.Start()) + defer tc.Close() + + time.Sleep(time.Second) + framework.NewRequestExpect(f).Port(vhostPort). + RequestModify(func(r *request.Request) { + r.HTTP().HTTPHost("test.example.com") + }). + Ensure() + }) + + ginkgo.It("https", func() { + sshPort := f.AllocPort() + vhostPort := f.AllocPort() + serverConf := consts.DefaultServerConfig + fmt.Sprintf(` + vhostHTTPSPort = %d + sshTunnelGateway.bindPort = %d + `, vhostPort, sshPort) + + f.RunProcesses([]string{serverConf}, nil) + + localPort := f.AllocPort() + testDomain := "test.example.com" + tc := ssh.NewTunnelClient( + fmt.Sprintf("127.0.0.1:%d", localPort), + fmt.Sprintf("127.0.0.1:%d", sshPort), + fmt.Sprintf("https --custom_domain %s", testDomain), + ) + framework.ExpectNoError(tc.Start()) + defer tc.Close() + + tlsConfig, err := transport.NewServerTLSConfig("", "", "") + framework.ExpectNoError(err) + localServer := httpserver.New( + httpserver.WithBindPort(localPort), + httpserver.WithTLSConfig(tlsConfig), + httpserver.WithResponse([]byte("test")), + ) + f.RunServer("", localServer) + + time.Sleep(time.Second) + framework.NewRequestExpect(f). + Port(vhostPort). + RequestModify(func(r *request.Request) { + r.HTTPS().HTTPHost(testDomain).TLSConfig(&tls.Config{ + ServerName: testDomain, + InsecureSkipVerify: true, + }) + }). + ExpectResp([]byte("test")). + Ensure() + }) + + ginkgo.It("tcpmux", func() { + sshPort := f.AllocPort() + tcpmuxPort := f.AllocPort() + serverConf := consts.DefaultServerConfig + fmt.Sprintf(` + tcpmuxHTTPConnectPort = %d + sshTunnelGateway.bindPort = %d + `, tcpmuxPort, sshPort) + + f.RunProcesses([]string{serverConf}, nil) + + localPort := f.AllocPort() + testDomain := "test.example.com" + tc := ssh.NewTunnelClient( + fmt.Sprintf("127.0.0.1:%d", localPort), + fmt.Sprintf("127.0.0.1:%d", sshPort), + fmt.Sprintf("tcpmux --mux=httpconnect --custom_domain %s", testDomain), + ) + framework.ExpectNoError(tc.Start()) + defer tc.Close() + + localServer := streamserver.New( + streamserver.TCP, + streamserver.WithBindPort(localPort), + streamserver.WithRespContent([]byte("test")), + ) + f.RunServer("", localServer) + + time.Sleep(time.Second) + // Request without HTTP connect should get error + framework.NewRequestExpect(f). + Port(tcpmuxPort). + ExpectError(true). + Explain("request without HTTP connect expect error"). + Ensure() + + proxyURL := fmt.Sprintf("http://127.0.0.1:%d", tcpmuxPort) + // Request with incorrect connect hostname + framework.NewRequestExpect(f).RequestModify(func(r *request.Request) { + r.Addr("invalid").Proxy(proxyURL) + }).ExpectError(true).Explain("request without HTTP connect expect error").Ensure() + + // Request with correct connect hostname + framework.NewRequestExpect(f).RequestModify(func(r *request.Request) { + r.Addr(testDomain).Proxy(proxyURL) + }).ExpectResp([]byte("test")).Ensure() + }) + + ginkgo.It("stcp", func() { + sshPort := f.AllocPort() + serverConf := consts.DefaultServerConfig + fmt.Sprintf(` + sshTunnelGateway.bindPort = %d + `, sshPort) + + bindPort := f.AllocPort() + visitorConf := consts.DefaultClientConfig + fmt.Sprintf(` + [[visitors]] + name = "stcp-test-visitor" + type = "stcp" + serverName = "stcp-test" + secretKey = "abcdefg" + bindPort = %d + `, bindPort) + + f.RunProcesses([]string{serverConf}, []string{visitorConf}) + + localPort := f.PortByName(framework.TCPEchoServerPort) + tc := ssh.NewTunnelClient( + fmt.Sprintf("127.0.0.1:%d", localPort), + fmt.Sprintf("127.0.0.1:%d", sshPort), + "stcp -n stcp-test --sk=abcdefg --allow_users=\"*\"", + ) + framework.ExpectNoError(tc.Start()) + defer tc.Close() + + time.Sleep(time.Second) + + framework.NewRequestExpect(f). + Port(bindPort). + Ensure() + }) +})