diff --git a/cmd/frpc/sub/nathole.go b/cmd/frpc/sub/nathole.go new file mode 100644 index 0000000..db56d76 --- /dev/null +++ b/cmd/frpc/sub/nathole.go @@ -0,0 +1,86 @@ +// Copyright 2023 The frp Authors +// +// 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 sub + +import ( + "fmt" + "net" + "os" + "strconv" + + "github.com/spf13/cobra" + + "github.com/fatedier/frp/pkg/config" + "github.com/fatedier/frp/pkg/nathole" +) + +func init() { + RegisterCommonFlags(natholeCmd) + + rootCmd.AddCommand(natholeCmd) + natholeCmd.AddCommand(natholeDiscoveryCmd) +} + +var natholeCmd = &cobra.Command{ + Use: "nathole", + Short: "Actions about nathole", +} + +var natholeDiscoveryCmd = &cobra.Command{ + Use: "discover", + Short: "Discover nathole information by frps and stun server", + RunE: func(cmd *cobra.Command, args []string) error { + cfg, _, _, err := config.ParseClientConfig(cfgFile) + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + if err := validateForNatHoleDiscovery(cfg); err != nil { + fmt.Println(err) + os.Exit(1) + } + + addresses, err := nathole.Discover( + net.JoinHostPort(cfg.ServerAddr, strconv.Itoa(cfg.ServerUDPPort)), + []string{cfg.NatHoleSTUNServer}, + []byte(cfg.Token), + ) + if err != nil { + fmt.Println("discover error:", err) + os.Exit(1) + } + + natType, behavior, err := nathole.ClassifyNATType(addresses) + if err != nil { + fmt.Println("classify nat type error:", err) + os.Exit(1) + } + fmt.Println("Your NAT type is:", natType) + fmt.Println("Behavior is:", behavior) + fmt.Println("External address is:", addresses) + return nil + }, +} + +func validateForNatHoleDiscovery(cfg config.ClientCommonConf) error { + if cfg.NatHoleSTUNServer == "" { + return fmt.Errorf("nat_hole_stun_server can not be empty") + } + if cfg.ServerUDPPort == 0 { + return fmt.Errorf("server udp port can not be empty") + } + return nil +} diff --git a/conf/frpc_full.ini b/conf/frpc_full.ini index 49e5b47..1be0b85 100644 --- a/conf/frpc_full.ini +++ b/conf/frpc_full.ini @@ -10,6 +10,13 @@ server_port = 7000 # server_addr. # nat_hole_server_addr = 0.0.0.0 +# ServerUDPPort specifies the server port to help penetrate NAT hole. By default, this value is 0. +# This parameter is only used when executing "nathole discover" in the command line. +# server_udp_port = 0 + +# STUN server to help penetrate NAT hole. +# nat_hole_stun_server = stun.easyvoip.com:3478 + # The maximum amount of time a dial to server will wait for a connect to complete. Default value is 10 seconds. # dial_server_timeout = 10 diff --git a/go.mod b/go.mod index 41bc0b3..ba23a53 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ require ( github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 github.com/coreos/go-oidc/v3 v3.4.0 github.com/fatedier/beego v0.0.0-20171024143340-6c6a4f5bd5eb - github.com/fatedier/golib v0.1.1-0.20230311074156-2623b2569b10 + github.com/fatedier/golib v0.1.1-0.20230320133937-a7edcc8c793d github.com/fatedier/kcp-go v2.0.4-0.20190803094908-fe8645b0a904+incompatible github.com/go-playground/validator/v10 v10.11.0 github.com/google/uuid v1.3.0 @@ -15,12 +15,13 @@ require ( github.com/hashicorp/yamux v0.1.1 github.com/onsi/ginkgo/v2 v2.8.3 github.com/onsi/gomega v1.27.0 + github.com/pion/stun v0.4.0 github.com/pires/go-proxyproto v0.6.2 github.com/prometheus/client_golang v1.13.0 github.com/quic-go/quic-go v0.32.0 github.com/rodaine/table v1.0.1 github.com/spf13/cobra v1.1.3 - github.com/stretchr/testify v1.8.0 + github.com/stretchr/testify v1.8.1 golang.org/x/net v0.7.0 golang.org/x/oauth2 v0.3.0 golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 @@ -48,6 +49,7 @@ require ( github.com/klauspost/reedsolomon v1.9.15 // indirect github.com/leodido/go-urn v1.2.1 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect + github.com/pion/transport/v2 v2.0.0 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_model v0.2.0 // indirect diff --git a/go.sum b/go.sum index c8090da..d708984 100644 --- a/go.sum +++ b/go.sum @@ -121,8 +121,8 @@ github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go. github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fatedier/beego v0.0.0-20171024143340-6c6a4f5bd5eb h1:wCrNShQidLmvVWn/0PikGmpdP0vtQmnvyRg3ZBEhczw= github.com/fatedier/beego v0.0.0-20171024143340-6c6a4f5bd5eb/go.mod h1:wx3gB6dbIfBRcucp94PI9Bt3I0F2c/MyNEWuhzpWiwk= -github.com/fatedier/golib v0.1.1-0.20230311074156-2623b2569b10 h1:JjEXgytxMpWC6nK1u+Pskvaf2MPRnv/pxWmTlyVQMUI= -github.com/fatedier/golib v0.1.1-0.20230311074156-2623b2569b10/go.mod h1:Wdn1pJ0dHB1lah6FPYwt4AO9NEmWI0OzW13dpzC9g4E= +github.com/fatedier/golib v0.1.1-0.20230320133937-a7edcc8c793d h1:/m9Atycn9uKRwwOkxv4c+zaugxRgkdSG/Eg3IJWOpNs= +github.com/fatedier/golib v0.1.1-0.20230320133937-a7edcc8c793d/go.mod h1:Wdn1pJ0dHB1lah6FPYwt4AO9NEmWI0OzW13dpzC9g4E= github.com/fatedier/kcp-go v2.0.4-0.20190803094908-fe8645b0a904+incompatible h1:ssXat9YXFvigNge/IkkZvFMn8yeYKFX+uI6wn2mLJ74= github.com/fatedier/kcp-go v2.0.4-0.20190803094908-fe8645b0a904+incompatible/go.mod h1:YpCOaxj7vvMThhIQ9AfTOPW2sfztQR5WDfs7AflSy4s= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= @@ -336,6 +336,11 @@ github.com/onsi/gomega v1.27.0 h1:QLidEla4bXUuZVFa4KX6JHCsuGgbi85LC/pCHrt/O08= github.com/onsi/gomega v1.27.0/go.mod h1:i189pavgK95OSIipFBa74gC2V4qrQuvjuyGEr3GmbXA= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms= +github.com/pion/stun v0.4.0 h1:vgRrbBE2htWHy7l3Zsxckk7rkjnjOsSM7PHZnBwo8rk= +github.com/pion/stun v0.4.0/go.mod h1:QPsh1/SbXASntw3zkkrIk3ZJVKz4saBY2G7S10P3wCw= +github.com/pion/transport/v2 v2.0.0 h1:bsMYyqHCbkvHwj+eNCFBuxtlKndKfyGI2vaQmM3fIE4= +github.com/pion/transport/v2 v2.0.0/go.mod h1:HS2MEBJTwD+1ZI2eSXSvHJx/HnzQqRy2/LXxt6eVMHc= github.com/pires/go-proxyproto v0.6.2 h1:KAZ7UteSOt6urjme6ZldyFm4wDe/z0ZUP0Yv0Dos0d8= github.com/pires/go-proxyproto v0.6.2/go.mod h1:Odh9VFOZJCf9G8cLW5o435Xf1J95Jw9Gw5rnCjcwzAY= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= @@ -415,6 +420,7 @@ github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5q github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -422,8 +428,9 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5 github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161 h1:89CEmDvlq/F7SJEOqkIdNDGJXrQIhuIx9D2DBXjavSU= github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161/go.mod h1:wM7WEvslTq+iOEAMDLSzhVuOt5BRZ05WirO+b09GHQU= @@ -439,6 +446,7 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= @@ -459,6 +467,7 @@ golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.4.0 h1:UVQgzMY87xqpKNgb+kDsll2Igd33HszWHFLmpaRMq/8= golang.org/x/crypto v0.4.0/go.mod h1:3quD/ATkf6oY+rnes5c3ExXTbLc8mueNue5/DoinL80= @@ -499,6 +508,7 @@ golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -551,7 +561,9 @@ golang.org/x/net v0.0.0-20220412020605-290c469a71a5/go.mod h1:CfG3xpIq0wQ8r1q4Su golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220826154423-83b083e8dc8b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= +golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -589,6 +601,7 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -659,11 +672,15 @@ golang.org/x/sys v0.0.0-20220502124256-b6088ccd6cba/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -673,6 +690,7 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -734,6 +752,7 @@ golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/pkg/config/client.go b/pkg/config/client.go index b4cb4d1..3ee3910 100644 --- a/pkg/config/client.go +++ b/pkg/config/client.go @@ -41,6 +41,11 @@ type ClientCommonConf struct { // ServerPort specifies the port to connect to the server on. By default, // this value is 7000. ServerPort int `ini:"server_port" json:"server_port"` + // ServerUDPPort specifies the server port to help penetrate NAT hole. By default, this value is 0. + // This parameter is only used when executing "nathole discover" in the command line. + ServerUDPPort int `ini:"server_udp_port" json:"server_udp_port"` + // STUN server to help penetrate NAT hole. + NatHoleSTUNServer string `ini:"nat_hole_stun_server" json:"nat_hole_stun_server"` // The maximum amount of time a dial to server will wait for a connect to complete. DialServerTimeout int64 `ini:"dial_server_timeout" json:"dial_server_timeout"` // DialServerKeepAlive specifies the interval between keep-alive probes for an active network connection between frpc and frps. @@ -172,6 +177,7 @@ func GetDefaultClientConf() ClientCommonConf { ClientConfig: auth.GetDefaultClientConf(), ServerAddr: "0.0.0.0", ServerPort: 7000, + NatHoleSTUNServer: "stun.easyvoip.com:3478", DialServerTimeout: 10, DialServerKeepAlive: 7200, HTTPProxy: os.Getenv("http_proxy"), diff --git a/pkg/config/client_test.go b/pkg/config/client_test.go index 79eef5f..e532510 100644 --- a/pkg/config/client_test.go +++ b/pkg/config/client_test.go @@ -260,6 +260,7 @@ func Test_LoadClientCommonConf(t *testing.T) { }, ServerAddr: "0.0.0.9", ServerPort: 7009, + NatHoleSTUNServer: "stun.easyvoip.com:3478", DialServerTimeout: 10, DialServerKeepAlive: 7200, HTTPProxy: "http://user:passwd@192.168.1.128:8080", diff --git a/pkg/msg/ctl.go b/pkg/msg/ctl.go index bf0c71a..5ccee4a 100644 --- a/pkg/msg/ctl.go +++ b/pkg/msg/ctl.go @@ -42,3 +42,7 @@ func ReadMsgInto(c io.Reader, msg Message) (err error) { func WriteMsg(c io.Writer, msg interface{}) (err error) { return msgCtl.WriteMsg(c, msg) } + +func Pack(msg interface{}) (data []byte, err error) { + return msgCtl.Pack(msg) +} diff --git a/pkg/msg/msg.go b/pkg/msg/msg.go index 33e8fe5..b50c2b4 100644 --- a/pkg/msg/msg.go +++ b/pkg/msg/msg.go @@ -37,6 +37,8 @@ const ( TypeNatHoleResp = 'm' TypeNatHoleClientDetectOK = 'd' TypeNatHoleSid = '5' + TypeNatHoleBinding = 'b' + TypeNatHoleBindingResp = '6' ) var msgTypeMap = map[byte]interface{}{ @@ -58,6 +60,8 @@ var msgTypeMap = map[byte]interface{}{ TypeNatHoleResp: NatHoleResp{}, TypeNatHoleClientDetectOK: NatHoleClientDetectOK{}, TypeNatHoleSid: NatHoleSid{}, + TypeNatHoleBinding: NatHoleBinding{}, + TypeNatHoleBindingResp: NatHoleBindingResp{}, } // When frpc start, client send this message to login to server. @@ -193,3 +197,13 @@ type NatHoleClientDetectOK struct{} type NatHoleSid struct { Sid string `json:"sid,omitempty"` } + +type NatHoleBinding struct { + TransactionID string `json:"transaction_id,omitempty"` +} + +type NatHoleBindingResp struct { + TransactionID string `json:"transaction_id,omitempty"` + Address string `json:"address,omitempty"` + Error string `json:"error,omitempty"` +} diff --git a/pkg/nathole/classify.go b/pkg/nathole/classify.go new file mode 100644 index 0000000..c667e07 --- /dev/null +++ b/pkg/nathole/classify.go @@ -0,0 +1,74 @@ +// Copyright 2023 The frp Authors +// +// 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 nathole + +import ( + "fmt" + "net" +) + +const ( + EasyNAT = "EasyNAT" + HardNAT = "HardNAT" + + BehaviorNoChange = "BehaviorNoChange" + BehaviorIPChanged = "BehaviorIPChanged" + BehaviorPortChanged = "BehaviorPortChanged" + BehaviorBothChanged = "BehaviorBothChanged" +) + +// ClassifyNATType classify NAT type by given addresses. +func ClassifyNATType(addresses []string) (string, string, error) { + if len(addresses) <= 1 { + return "", "", fmt.Errorf("not enough addresses") + } + ipChanged := false + portChanged := false + + var baseIP, basePort string + for _, addr := range addresses { + ip, port, err := net.SplitHostPort(addr) + if err != nil { + return "", "", err + } + if baseIP == "" { + baseIP = ip + basePort = port + continue + } + + if baseIP != ip { + ipChanged = true + } + if basePort != port { + portChanged = true + } + + if ipChanged && portChanged { + break + } + } + + switch { + case ipChanged && portChanged: + return HardNAT, BehaviorBothChanged, nil + case ipChanged: + return HardNAT, BehaviorIPChanged, nil + case portChanged: + return HardNAT, BehaviorPortChanged, nil + default: + return EasyNAT, BehaviorNoChange, nil + } +} diff --git a/pkg/nathole/discovery.go b/pkg/nathole/discovery.go new file mode 100644 index 0000000..761ed10 --- /dev/null +++ b/pkg/nathole/discovery.go @@ -0,0 +1,192 @@ +// Copyright 2023 The frp Authors +// +// 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 nathole + +import ( + "fmt" + "net" + "time" + + "github.com/pion/stun" + + "github.com/fatedier/frp/pkg/msg" +) + +var responseTimeout = 3 * time.Second + +type Address struct { + IP string + Port int +} + +type Message struct { + Body []byte + Addr string +} + +func Discover(serverAddress string, stunServers []string, key []byte) ([]string, error) { + // parse address to net.Address + stunAddresses := make([]net.Addr, 0, len(stunServers)) + for _, stunServer := range stunServers { + addr, err := net.ResolveUDPAddr("udp4", stunServer) + if err != nil { + return nil, err + } + stunAddresses = append(stunAddresses, addr) + } + serverAddr, err := net.ResolveUDPAddr("udp4", serverAddress) + if err != nil { + return nil, err + } + + // create a discoverConn and get response from messageChan + discoverConn, err := listen() + if err != nil { + return nil, err + } + defer discoverConn.Close() + + go discoverConn.readLoop() + + addresses := make([]string, 0, len(stunServers)+1) + // get external address from frp server + externalAddr, err := discoverFromServer(discoverConn, serverAddr, key) + if err != nil { + return nil, err + } + addresses = append(addresses, externalAddr) + + for _, stunAddr := range stunAddresses { + // get external address from stun server + externalAddr, err = discoverFromStunServer(discoverConn, stunAddr) + if err != nil { + return nil, err + } + addresses = append(addresses, externalAddr) + } + return addresses, nil +} + +func discoverFromServer(c *discoverConn, addr net.Addr, key []byte) (string, error) { + m := &msg.NatHoleBinding{ + TransactionID: NewTransactionID(), + } + + buf, err := EncodeMessage(m, key) + if err != nil { + return "", err + } + + if _, err := c.conn.WriteTo(buf, addr); err != nil { + return "", err + } + + var respMsg msg.NatHoleBindingResp + select { + case rawMsg := <-c.messageChan: + if err := DecodeMessageInto(rawMsg.Body, key, &respMsg); err != nil { + return "", err + } + case <-time.After(responseTimeout): + return "", fmt.Errorf("wait response from frp server timeout") + } + + if respMsg.TransactionID == "" { + return "", fmt.Errorf("error format: no transaction id found") + } + if respMsg.Error != "" { + return "", fmt.Errorf("get externalAddr from frp server error: %s", respMsg.Error) + } + return respMsg.Address, nil +} + +func discoverFromStunServer(c *discoverConn, addr net.Addr) (string, error) { + request, err := stun.Build(stun.TransactionID, stun.BindingRequest) + if err != nil { + return "", err + } + + if err = request.NewTransactionID(); err != nil { + return "", err + } + if _, err := c.conn.WriteTo(request.Raw, addr); err != nil { + return "", err + } + + var m stun.Message + select { + case msg := <-c.messageChan: + m.Raw = msg.Body + if err := m.Decode(); err != nil { + return "", err + } + case <-time.After(responseTimeout): + return "", fmt.Errorf("wait response from stun server timeout") + } + + xorAddr := &stun.XORMappedAddress{} + mappedAddr := &stun.MappedAddress{} + if err := xorAddr.GetFrom(&m); err == nil { + return xorAddr.String(), nil + } + if err := mappedAddr.GetFrom(&m); err == nil { + return mappedAddr.String(), nil + } + return "", fmt.Errorf("no address found") +} + +type discoverConn struct { + conn *net.UDPConn + + localAddr net.Addr + messageChan chan *Message +} + +func listen() (*discoverConn, error) { + conn, err := net.ListenUDP("udp4", nil) + if err != nil { + return nil, err + } + + return &discoverConn{ + conn: conn, + localAddr: conn.LocalAddr(), + messageChan: make(chan *Message, 10), + }, nil +} + +func (c *discoverConn) Close() error { + if c.messageChan != nil { + close(c.messageChan) + c.messageChan = nil + } + return c.conn.Close() +} + +func (c *discoverConn) readLoop() { + for { + buf := make([]byte, 1024) + n, addr, err := c.conn.ReadFromUDP(buf) + if err != nil { + return + } + buf = buf[:n] + + c.messageChan <- &Message{ + Body: buf, + Addr: addr.String(), + } + } +} diff --git a/pkg/nathole/nathole.go b/pkg/nathole/nathole.go index da8b49c..2b114bc 100644 --- a/pkg/nathole/nathole.go +++ b/pkg/nathole/nathole.go @@ -1,3 +1,17 @@ +// Copyright 2023 The frp Authors +// +// 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 nathole import ( @@ -7,6 +21,7 @@ import ( "sync" "time" + "github.com/fatedier/golib/crypto" "github.com/fatedier/golib/errors" "github.com/fatedier/golib/pool" @@ -18,6 +33,11 @@ import ( // NatHoleTimeout seconds. var NatHoleTimeout int64 = 10 +func NewTransactionID() string { + id, _ := util.RandID() + return fmt.Sprintf("%d%s", time.Now().Unix(), id) +} + type SidRequest struct { Sid string NotifyCh chan struct{} @@ -29,10 +49,11 @@ type Controller struct { clientCfgs map[string]*ClientCfg sessions map[string]*Session - mu sync.RWMutex + encryptionKey []byte + mu sync.RWMutex } -func NewController(udpBindAddr string) (nc *Controller, err error) { +func NewController(udpBindAddr string, encryptionKey []byte) (nc *Controller, err error) { addr, err := net.ResolveUDPAddr("udp", udpBindAddr) if err != nil { return nil, err @@ -42,9 +63,10 @@ func NewController(udpBindAddr string) (nc *Controller, err error) { return nil, err } nc = &Controller{ - listener: lconn, - clientCfgs: make(map[string]*ClientCfg), - sessions: make(map[string]*Session), + listener: lconn, + clientCfgs: make(map[string]*ClientCfg), + sessions: make(map[string]*Session), + encryptionKey: encryptionKey, } return nc, nil } @@ -72,24 +94,30 @@ func (nc *Controller) Run() { buf := pool.GetBuf(1024) n, raddr, err := nc.listener.ReadFromUDP(buf) if err != nil { - log.Trace("nat hole listener read from udp error: %v", err) + log.Warn("nat hole listener read from udp error: %v", err) return } + plain, err := crypto.Decode(buf[:n], nc.encryptionKey) + if err != nil { + log.Warn("nathole listener decode from %s error: %v", raddr.String(), err) + continue + } - rd := bytes.NewReader(buf[:n]) - rawMsg, err := msg.ReadMsg(rd) + rawMsg, err := msg.ReadMsg(bytes.NewReader(plain)) if err != nil { - log.Trace("read nat hole message error: %v", err) + log.Warn("read nat hole message error: %v", err) continue } switch m := rawMsg.(type) { + case *msg.NatHoleBinding: + go nc.HandleBinding(m, raddr) case *msg.NatHoleVisitor: go nc.HandleVisitor(m, raddr) case *msg.NatHoleClient: go nc.HandleClient(m, raddr) default: - log.Trace("error nat hole message type") + log.Trace("unknown nat hole message type") continue } pool.PutBuf(buf) @@ -102,6 +130,29 @@ func (nc *Controller) GenSid() string { return fmt.Sprintf("%d%s", t, id) } +func (nc *Controller) HandleBinding(m *msg.NatHoleBinding, raddr *net.UDPAddr) { + log.Trace("handle binding message from %s", raddr.String()) + resp := &msg.NatHoleBindingResp{ + TransactionID: m.TransactionID, + Address: raddr.String(), + } + plain, err := msg.Pack(resp) + if err != nil { + log.Error("pack nat hole binding response error: %v", err) + return + } + buf, err := crypto.Encode(plain, nc.encryptionKey) + if err != nil { + log.Error("encode nat hole binding response error: %v", err) + return + } + _, err = nc.listener.WriteToUDP(buf, raddr) + if err != nil { + log.Error("write nat hole binding response to %s error: %v", raddr.String(), err) + return + } +} + func (nc *Controller) HandleVisitor(m *msg.NatHoleVisitor, raddr *net.UDPAddr) { sid := nc.GenSid() session := &Session{ diff --git a/pkg/nathole/utils.go b/pkg/nathole/utils.go new file mode 100644 index 0000000..40fad0e --- /dev/null +++ b/pkg/nathole/utils.go @@ -0,0 +1,48 @@ +// Copyright 2023 The frp Authors +// +// 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 nathole + +import ( + "bytes" + + "github.com/fatedier/golib/crypto" + + "github.com/fatedier/frp/pkg/msg" +) + +func EncodeMessage(m msg.Message, key []byte) ([]byte, error) { + buffer := bytes.NewBuffer(nil) + if err := msg.WriteMsg(buffer, m); err != nil { + return nil, err + } + + buf, err := crypto.Encode(buffer.Bytes(), key) + if err != nil { + return nil, err + } + return buf, nil +} + +func DecodeMessageInto(data, key []byte, m msg.Message) error { + buf, err := crypto.Decode(data, key) + if err != nil { + return err + } + + if err := msg.ReadMsgInto(bytes.NewReader(buf), m); err != nil { + return err + } + return nil +} diff --git a/server/service.go b/server/service.go index e2f8494..4ce5f99 100644 --- a/server/service.go +++ b/server/service.go @@ -293,7 +293,7 @@ func NewService(cfg config.ServerCommonConf) (svr *Service, err error) { if cfg.BindUDPPort > 0 { var nc *nathole.Controller address := net.JoinHostPort(cfg.BindAddr, strconv.Itoa(cfg.BindUDPPort)) - nc, err = nathole.NewController(address) + nc, err = nathole.NewController(address, []byte(cfg.Token)) if err != nil { err = fmt.Errorf("create nat hole controller error, %v", err) return