[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
[tor-commits] [snowflake/master] Implement NAT discovery (RFC 5780) at the client
commit bf924445e36a1990ad1da89d99faeff17db9e42f
Author: Cecylia Bocovich <cohosh@xxxxxxxxxxxxxx>
Date: Wed Jun 10 17:16:12 2020 -0400
Implement NAT discovery (RFC 5780) at the client
Snowflake clients will now attempt NAT discovery using the provided STUN
servers and report their NAT type to the Snowflake broker for matching.
The three possibilities for NAT types are:
- unknown (the client was unable to determine their NAT type),
- restricted (the client has a restrictive NAT and can only be paired
with unrestricted NATs)
- unrestricted (the client can be paired with any other NAT).
---
client/lib/rendezvous.go | 16 +++
client/snowflake.go | 26 +++++
common/nat/nat.go | 251 +++++++++++++++++++++++++++++++++++++++++++++++
go.mod | 1 +
go.sum | 2 +
5 files changed, 296 insertions(+)
diff --git a/client/lib/rendezvous.go b/client/lib/rendezvous.go
index ca15d35..2702d4e 100644
--- a/client/lib/rendezvous.go
+++ b/client/lib/rendezvous.go
@@ -16,7 +16,9 @@ import (
"log"
"net/http"
"net/url"
+ "sync"
+ "git.torproject.org/pluggable-transports/snowflake.git/common/nat"
"git.torproject.org/pluggable-transports/snowflake.git/common/util"
"github.com/pion/webrtc/v2"
)
@@ -36,6 +38,8 @@ type BrokerChannel struct {
url *url.URL
transport http.RoundTripper // Used to make all requests.
keepLocalAddresses bool
+ NATType string
+ lock sync.Mutex
}
// We make a copy of DefaultTransport because we want the default Dial
@@ -66,6 +70,7 @@ func NewBrokerChannel(broker string, front string, transport http.RoundTripper,
bc.transport = transport
bc.keepLocalAddresses = keepLocalAddresses
+ bc.NATType = nat.NATUnknown
return bc, nil
}
@@ -110,6 +115,10 @@ func (bc *BrokerChannel) Negotiate(offer *webrtc.SessionDescription) (
if "" != bc.Host { // Set true host if necessary.
request.Host = bc.Host
}
+ // include NAT-TYPE
+ bc.lock.Lock()
+ request.Header.Set("Snowflake-NAT-TYPE", bc.NATType)
+ bc.lock.Unlock()
resp, err := bc.transport.RoundTrip(request)
if nil != err {
return nil, err
@@ -133,6 +142,13 @@ func (bc *BrokerChannel) Negotiate(offer *webrtc.SessionDescription) (
}
}
+func (bc *BrokerChannel) SetNATType(NATType string) {
+ bc.lock.Lock()
+ bc.NATType = NATType
+ bc.lock.Unlock()
+ log.Printf("NAT Type: %s", NATType)
+}
+
// Implements the |Tongue| interface to catch snowflakes, using BrokerChannel.
type WebRTCDialer struct {
*BrokerChannel
diff --git a/client/snowflake.go b/client/snowflake.go
index d66225d..02bbf1e 100644
--- a/client/snowflake.go
+++ b/client/snowflake.go
@@ -16,6 +16,7 @@ import (
pt "git.torproject.org/pluggable-transports/goptlib.git"
sf "git.torproject.org/pluggable-transports/snowflake.git/client/lib"
+ "git.torproject.org/pluggable-transports/snowflake.git/common/nat"
"git.torproject.org/pluggable-transports/snowflake.git/common/safelog"
"github.com/pion/webrtc/v2"
)
@@ -158,6 +159,8 @@ func main() {
if err != nil {
log.Fatalf("parsing broker URL: %v", err)
}
+ go updateNATType(iceServers, broker)
+
snowflakes.Tongue = sf.NewWebRTCDialer(broker, iceServers)
// Use a real logger to periodically output how much traffic is happening.
@@ -219,3 +222,26 @@ func main() {
snowflakes.End()
log.Println("snowflake is done.")
}
+
+// loop through all provided STUN servers until we exhaust the list or find
+// one that is compatable with RFC 5780
+func updateNATType(servers []webrtc.ICEServer, broker *sf.BrokerChannel) {
+
+ var restrictedNAT bool
+ var err error
+ for _, server := range servers {
+ addr := strings.TrimPrefix(server.URLs[0], "stun:")
+ restrictedNAT, err = nat.CheckIfRestrictedNAT(addr)
+ if err == nil {
+ if restrictedNAT {
+ broker.SetNATType(nat.NATRestricted)
+ } else {
+ broker.SetNATType(nat.NATUnrestricted)
+ }
+ break
+ }
+ }
+ if err != nil {
+ broker.SetNATType(nat.NATUnknown)
+ }
+}
diff --git a/common/nat/nat.go b/common/nat/nat.go
new file mode 100644
index 0000000..c9f16ad
--- /dev/null
+++ b/common/nat/nat.go
@@ -0,0 +1,251 @@
+/*
+The majority of this code is taken from a utility I wrote for pion/stun
+https://github.com/pion/stun/blob/master/cmd/stun-nat-behaviour/main.go
+
+Copyright 2018 Pion LLC
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+package nat
+
+import (
+ "errors"
+ "fmt"
+ "github.com/pion/stun"
+ "log"
+ "net"
+ "time"
+)
+
+var ErrTimedOut = errors.New("timed out waiting for response")
+
+const (
+ NATUnknown = "unknown"
+ NATRestricted = "restricted"
+ NATUnrestricted = "unrestricted"
+)
+
+// This function checks the NAT mapping and filtering
+// behaviour and returns true if the NAT is restrictive
+// (address-dependent mapping and/or port-dependent filtering)
+// and false if the NAT is unrestrictive (meaning it
+// will work with most other NATs),
+func CheckIfRestrictedNAT(server string) (bool, error) {
+ result, err := isRestrictedMapping(server)
+ if err != nil {
+ return false, err
+ }
+ if !result {
+ // if the mapping is unrestrictive, we still need to check whether
+ // the filtering is restrictive
+ result, err = isRestrictedFiltering(server)
+ }
+ return result, err
+}
+
+// Performs two tests from RFC 5780 to determine whether the mapping type
+// of the client's NAT is address-independent or address-dependent
+// Returns true if the mapping is address-dependent and false otherwise
+func isRestrictedMapping(addrStr string) (bool, error) {
+ var xorAddr1 stun.XORMappedAddress
+ var xorAddr2 stun.XORMappedAddress
+
+ mapTestConn, err := connect(addrStr)
+ if err != nil {
+ log.Printf("Error creating STUN connection: %s", err.Error())
+ return false, err
+ }
+
+ defer mapTestConn.Close()
+
+ // Test I: Regular binding request
+ message := stun.MustBuild(stun.TransactionID, stun.BindingRequest)
+
+ resp, err := mapTestConn.RoundTrip(message, mapTestConn.PrimaryAddr)
+ if err == ErrTimedOut {
+ log.Printf("Error: no response from server")
+ return false, err
+ }
+ if err != nil {
+ log.Printf("Error receiving response from server: %s", err.Error())
+ return false, err
+ }
+
+ // Decoding XOR-MAPPED-ADDRESS attribute from message.
+ if err = xorAddr1.GetFrom(resp); err != nil {
+ log.Printf("Error retrieving XOR-MAPPED-ADDRESS resonse: %s", err.Error())
+ return false, err
+ }
+
+ // Decoding OTHER-ADDRESS attribute from message.
+ var otherAddr stun.OtherAddress
+ if err = otherAddr.GetFrom(resp); err != nil {
+ log.Println("NAT discovery feature not supported by this server")
+ return false, err
+ }
+
+ if err = mapTestConn.AddOtherAddr(otherAddr.String()); err != nil {
+ log.Printf("Failed to resolve address %s\t", otherAddr.String())
+ return false, err
+ }
+
+ // Test II: Send binding request to other address
+ resp, err = mapTestConn.RoundTrip(message, mapTestConn.OtherAddr)
+ if err == ErrTimedOut {
+ log.Printf("Error: no response from server")
+ return false, err
+ }
+ if err != nil {
+ log.Printf("Error retrieving server response: %s", err.Error())
+ return false, err
+ }
+
+ // Decoding XOR-MAPPED-ADDRESS attribute from message.
+ if err = xorAddr2.GetFrom(resp); err != nil {
+ log.Printf("Error retrieving XOR-MAPPED-ADDRESS resonse: %s", err.Error())
+ return false, err
+ }
+
+ return xorAddr1.String() != xorAddr2.String(), nil
+
+}
+
+// Performs two tests from RFC 5780 to determine whether the filtering type
+// of the client's NAT is port-dependent.
+// Returns true if the filtering is port-dependent and false otherwise
+func isRestrictedFiltering(addrStr string) (bool, error) {
+ var xorAddr stun.XORMappedAddress
+
+ mapTestConn, err := connect(addrStr)
+ if err != nil {
+ log.Printf("Error creating STUN connection: %s", err.Error())
+ return false, err
+ }
+
+ defer mapTestConn.Close()
+
+ // Test I: Regular binding request
+ message := stun.MustBuild(stun.TransactionID, stun.BindingRequest)
+
+ resp, err := mapTestConn.RoundTrip(message, mapTestConn.PrimaryAddr)
+ if err == ErrTimedOut {
+ log.Printf("Error: no response from server")
+ return false, err
+ }
+ if err != nil {
+ log.Printf("Error: %s", err.Error())
+ return false, err
+ }
+
+ // Decoding XOR-MAPPED-ADDRESS attribute from message.
+ if err = xorAddr.GetFrom(resp); err != nil {
+ log.Printf("Error retrieving XOR-MAPPED-ADDRESS from resonse: %s", err.Error())
+ return false, err
+ }
+
+ // Test III: Request port change
+ message.Add(stun.AttrChangeRequest, []byte{0x00, 0x00, 0x00, 0x02})
+
+ _, err = mapTestConn.RoundTrip(message, mapTestConn.PrimaryAddr)
+ if err != ErrTimedOut && err != nil {
+ // something else went wrong
+ log.Printf("Error reading response from server: %s", err.Error())
+ return false, err
+ }
+
+ return err == ErrTimedOut, nil
+}
+
+// Given an address string, returns a StunServerConn
+func connect(addrStr string) (*StunServerConn, error) {
+ // Creating a "connection" to STUN server.
+ addr, err := net.ResolveUDPAddr("udp4", addrStr)
+ if err != nil {
+ log.Printf("Error resolving address: %s\n", err.Error())
+ return nil, err
+ }
+
+ c, err := net.ListenUDP("udp4", nil)
+ if err != nil {
+ return nil, err
+ }
+
+ mChan := listen(c)
+
+ return &StunServerConn{
+ conn: c,
+ PrimaryAddr: addr,
+ messageChan: mChan,
+ }, nil
+}
+
+type StunServerConn struct {
+ conn net.PacketConn
+ PrimaryAddr *net.UDPAddr
+ OtherAddr *net.UDPAddr
+ messageChan chan *stun.Message
+}
+
+func (c *StunServerConn) Close() {
+ c.conn.Close()
+}
+
+func (c *StunServerConn) RoundTrip(msg *stun.Message, addr net.Addr) (*stun.Message, error) {
+ _, err := c.conn.WriteTo(msg.Raw, addr)
+ if err != nil {
+ return nil, err
+ }
+
+ // Wait for response or timeout
+ select {
+ case m, ok := <-c.messageChan:
+ if !ok {
+ return nil, fmt.Errorf("error reading from messageChan")
+ }
+ return m, nil
+ case <-time.After(10 * time.Second):
+ return nil, ErrTimedOut
+ }
+}
+
+func (c *StunServerConn) AddOtherAddr(addrStr string) error {
+ addr2, err := net.ResolveUDPAddr("udp4", addrStr)
+ if err != nil {
+ return err
+ }
+ c.OtherAddr = addr2
+ return nil
+}
+
+// taken from https://github.com/pion/stun/blob/master/cmd/stun-traversal/main.go
+func listen(conn *net.UDPConn) chan *stun.Message {
+ messages := make(chan *stun.Message)
+ go func() {
+ for {
+ buf := make([]byte, 1024)
+
+ n, _, err := conn.ReadFromUDP(buf)
+ if err != nil {
+ close(messages)
+ return
+ }
+ buf = buf[:n]
+
+ m := new(stun.Message)
+ m.Raw = buf
+ err = m.Decode()
+ if err != nil {
+ close(messages)
+ return
+ }
+
+ messages <- m
+ }
+ }()
+ return messages
+}
diff --git a/go.mod b/go.mod
index 07c49a2..2ba1b2d 100644
--- a/go.mod
+++ b/go.mod
@@ -7,6 +7,7 @@ require (
github.com/golang/protobuf v1.3.1 // indirect
github.com/gorilla/websocket v1.4.1
github.com/pion/sdp/v2 v2.3.4
+ github.com/pion/stun v0.3.5
github.com/pion/webrtc/v2 v2.2.2
github.com/smartystreets/goconvey v1.6.4
github.com/xtaci/kcp-go/v5 v5.5.12
diff --git a/go.sum b/go.sum
index 6768e02..9ccfb30 100644
--- a/go.sum
+++ b/go.sum
@@ -64,6 +64,8 @@ github.com/pion/srtp v1.2.7 h1:UYyLs5MXwbFtXWduBA5+RUWhaEBX7GmetXDZSKP+uPM=
github.com/pion/srtp v1.2.7/go.mod h1:KIgLSadhg/ioogO/LqIkRjZrwuJo0c9RvKIaGQj4Yew=
github.com/pion/stun v0.3.3 h1:brYuPl9bN9w/VM7OdNzRSLoqsnwlyNvD9MVeJrHjDQw=
github.com/pion/stun v0.3.3/go.mod h1:xrCld6XM+6GWDZdvjPlLMsTU21rNxnO6UO8XsAvHr/M=
+github.com/pion/stun v0.3.5 h1:uLUCBCkQby4S1cf6CGuR9QrVOKcvUwFeemaC865QHDg=
+github.com/pion/stun v0.3.5/go.mod h1:gDMim+47EeEtfWogA37n6qXZS88L5V6LqFcf+DZA2UA=
github.com/pion/transport v0.6.0/go.mod h1:iWZ07doqOosSLMhZ+FXUTq+TamDoXSllxpbGcfkCmbE=
github.com/pion/transport v0.8.10 h1:lTiobMEw2PG6BH/mgIVqTV2mBp/mPT+IJLaN8ZxgdHk=
github.com/pion/transport v0.8.10/go.mod h1:tBmha/UCjpum5hqTWhfAEs3CO4/tHSg0MYRhSzR+CZ8=
_______________________________________________
tor-commits mailing list
tor-commits@xxxxxxxxxxxxxxxxxxxx
https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits