nat.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. /*
  2. The majority of this code is taken from a utility I wrote for pion/stun
  3. https://github.com/pion/stun/blob/master/cmd/stun-nat-behaviour/main.go
  4. Copyright 2018 Pion LLC
  5. 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:
  6. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  7. 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.
  8. */
  9. package nat
  10. import (
  11. "errors"
  12. "fmt"
  13. "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/proxy"
  14. "log"
  15. "net"
  16. "net/url"
  17. "time"
  18. "github.com/pion/stun"
  19. )
  20. var ErrTimedOut = errors.New("timed out waiting for response")
  21. const (
  22. NATUnknown = "unknown"
  23. NATRestricted = "restricted"
  24. NATUnrestricted = "unrestricted"
  25. )
  26. // Deprecated: Use CheckIfRestrictedNATWithProxy Instead.
  27. func CheckIfRestrictedNAT(server string) (bool, error) {
  28. return CheckIfRestrictedNATWithProxy(server, nil)
  29. }
  30. // CheckIfRestrictedNATWithProxy checks the NAT mapping and filtering
  31. // behaviour and returns true if the NAT is restrictive
  32. // (address-dependent mapping and/or port-dependent filtering)
  33. // and false if the NAT is unrestrictive (meaning it
  34. // will work with most other NATs),
  35. func CheckIfRestrictedNATWithProxy(server string, proxy *url.URL) (bool, error) {
  36. return isRestrictedMapping(server, proxy)
  37. }
  38. // Performs two tests from RFC 5780 to determine whether the mapping type
  39. // of the client's NAT is address-independent or address-dependent
  40. // Returns true if the mapping is address-dependent and false otherwise
  41. func isRestrictedMapping(addrStr string, proxy *url.URL) (bool, error) {
  42. var xorAddr1 stun.XORMappedAddress
  43. var xorAddr2 stun.XORMappedAddress
  44. mapTestConn, err := connect(addrStr, proxy)
  45. if err != nil {
  46. return false, fmt.Errorf("Error creating STUN connection: %w", err)
  47. }
  48. defer mapTestConn.Close()
  49. // Test I: Regular binding request
  50. message := stun.MustBuild(stun.TransactionID, stun.BindingRequest)
  51. resp, err := mapTestConn.RoundTrip(message, mapTestConn.PrimaryAddr)
  52. if err != nil {
  53. return false, fmt.Errorf("Error completing roundtrip map test: %w", err)
  54. }
  55. // Decoding XOR-MAPPED-ADDRESS attribute from message.
  56. if err = xorAddr1.GetFrom(resp); err != nil {
  57. return false, fmt.Errorf("Error retrieving XOR-MAPPED-ADDRESS resonse: %w", err)
  58. }
  59. // Decoding OTHER-ADDRESS attribute from message.
  60. var otherAddr stun.OtherAddress
  61. if err = otherAddr.GetFrom(resp); err != nil {
  62. return false, fmt.Errorf("NAT discovery feature not supported: %w", err)
  63. }
  64. if err = mapTestConn.AddOtherAddr(otherAddr.String()); err != nil {
  65. return false, fmt.Errorf("Error resolving address %s: %w", otherAddr.String(), err)
  66. }
  67. // Test II: Send binding request to other address
  68. resp, err = mapTestConn.RoundTrip(message, mapTestConn.OtherAddr)
  69. if err != nil {
  70. return false, fmt.Errorf("Error retrieveing server response: %w", err)
  71. }
  72. // Decoding XOR-MAPPED-ADDRESS attribute from message.
  73. if err = xorAddr2.GetFrom(resp); err != nil {
  74. return false, fmt.Errorf("Error retrieving XOR-MAPPED-ADDRESS resonse: %w", err)
  75. }
  76. return xorAddr1.String() != xorAddr2.String(), nil
  77. }
  78. // Performs two tests from RFC 5780 to determine whether the filtering type
  79. // of the client's NAT is port-dependent.
  80. // Returns true if the filtering is port-dependent and false otherwise
  81. // Note: This function is no longer used because a client's NAT type is
  82. // determined only by their mapping type, but the functionality might
  83. // be useful in the future and remains here.
  84. func isRestrictedFiltering(addrStr string, proxy *url.URL) (bool, error) {
  85. var xorAddr stun.XORMappedAddress
  86. mapTestConn, err := connect(addrStr, proxy)
  87. if err != nil {
  88. log.Printf("Error creating STUN connection: %s", err.Error())
  89. return false, err
  90. }
  91. defer mapTestConn.Close()
  92. // Test I: Regular binding request
  93. message := stun.MustBuild(stun.TransactionID, stun.BindingRequest)
  94. resp, err := mapTestConn.RoundTrip(message, mapTestConn.PrimaryAddr)
  95. if err == ErrTimedOut {
  96. log.Printf("Error: no response from server")
  97. return false, err
  98. }
  99. if err != nil {
  100. log.Printf("Error: %s", err.Error())
  101. return false, err
  102. }
  103. // Decoding XOR-MAPPED-ADDRESS attribute from message.
  104. if err = xorAddr.GetFrom(resp); err != nil {
  105. log.Printf("Error retrieving XOR-MAPPED-ADDRESS from resonse: %s", err.Error())
  106. return false, err
  107. }
  108. // Test III: Request port change
  109. message.Add(stun.AttrChangeRequest, []byte{0x00, 0x00, 0x00, 0x02})
  110. _, err = mapTestConn.RoundTrip(message, mapTestConn.PrimaryAddr)
  111. if err != ErrTimedOut && err != nil {
  112. // something else went wrong
  113. log.Printf("Error reading response from server: %s", err.Error())
  114. return false, err
  115. }
  116. return err == ErrTimedOut, nil
  117. }
  118. // Given an address string, returns a StunServerConn
  119. func connect(addrStr string, proxyAddr *url.URL) (*StunServerConn, error) {
  120. // Creating a "connection" to STUN server.
  121. var conn net.PacketConn
  122. ResolveUDPAddr := net.ResolveUDPAddr
  123. if proxyAddr != nil {
  124. socksClient := proxy.NewSocks5UDPClient(proxyAddr)
  125. ResolveUDPAddr = socksClient.ResolveUDPAddr
  126. }
  127. addr, err := ResolveUDPAddr("udp4", addrStr)
  128. if err != nil {
  129. log.Printf("Error resolving address: %s\n", err.Error())
  130. return nil, err
  131. }
  132. if proxyAddr == nil {
  133. c, err := net.ListenUDP("udp4", nil)
  134. if err != nil {
  135. return nil, err
  136. }
  137. conn = c
  138. } else {
  139. socksClient := proxy.NewSocks5UDPClient(proxyAddr)
  140. c, err := socksClient.ListenPacket("udp", nil)
  141. if err != nil {
  142. return nil, err
  143. }
  144. conn = c
  145. }
  146. mChan := listen(conn)
  147. return &StunServerConn{
  148. conn: conn,
  149. PrimaryAddr: addr,
  150. messageChan: mChan,
  151. }, nil
  152. }
  153. type StunServerConn struct {
  154. conn net.PacketConn
  155. PrimaryAddr *net.UDPAddr
  156. OtherAddr *net.UDPAddr
  157. messageChan chan *stun.Message
  158. }
  159. func (c *StunServerConn) Close() {
  160. c.conn.Close()
  161. }
  162. func (c *StunServerConn) RoundTrip(msg *stun.Message, addr net.Addr) (*stun.Message, error) {
  163. _, err := c.conn.WriteTo(msg.Raw, addr)
  164. if err != nil {
  165. return nil, err
  166. }
  167. // Wait for response or timeout
  168. select {
  169. case m, ok := <-c.messageChan:
  170. if !ok {
  171. return nil, fmt.Errorf("error reading from messageChan")
  172. }
  173. return m, nil
  174. case <-time.After(10 * time.Second):
  175. return nil, ErrTimedOut
  176. }
  177. }
  178. func (c *StunServerConn) AddOtherAddr(addrStr string) error {
  179. addr2, err := net.ResolveUDPAddr("udp4", addrStr)
  180. if err != nil {
  181. return err
  182. }
  183. c.OtherAddr = addr2
  184. return nil
  185. }
  186. // taken from https://github.com/pion/stun/blob/master/cmd/stun-traversal/main.go
  187. func listen(conn net.PacketConn) chan *stun.Message {
  188. messages := make(chan *stun.Message)
  189. go func() {
  190. for {
  191. buf := make([]byte, 1024)
  192. n, _, err := conn.ReadFrom(buf)
  193. if err != nil {
  194. close(messages)
  195. return
  196. }
  197. buf = buf[:n]
  198. m := new(stun.Message)
  199. m.Raw = buf
  200. err = m.Decode()
  201. if err != nil {
  202. close(messages)
  203. return
  204. }
  205. messages <- m
  206. }
  207. }()
  208. return messages
  209. }