network.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. package zerotier
  14. import (
  15. "encoding/binary"
  16. "encoding/json"
  17. "fmt"
  18. "net"
  19. "sort"
  20. "strconv"
  21. "sync"
  22. )
  23. // NetworkID is a network's 64-bit unique ID
  24. type NetworkID uint64
  25. // NewNetworkIDFromString parses a network ID in string form
  26. func NewNetworkIDFromString(s string) (NetworkID, error) {
  27. if len(s) != 16 {
  28. return NetworkID(0), ErrInvalidNetworkID
  29. }
  30. n, err := strconv.ParseUint(s, 16, 64)
  31. return NetworkID(n), err
  32. }
  33. // NewNetworkIDFromBytes reads an 8-byte / 64-bit network ID.
  34. func NewNetworkIDFromBytes(b []byte) (NetworkID, error) {
  35. if len(b) < 8 {
  36. return NetworkID(0), ErrInvalidNetworkID
  37. }
  38. return NetworkID(binary.BigEndian.Uint64(b)), nil
  39. }
  40. // String returns this network ID's 16-digit hex identifier
  41. func (n NetworkID) String() string {
  42. return fmt.Sprintf("%.16x", uint64(n))
  43. }
  44. // Bytes returns this network ID as an 8-byte / 64-bit big-endian value.
  45. func (n NetworkID) Bytes() []byte {
  46. var b [8]byte
  47. binary.BigEndian.PutUint64(b[:], uint64(n))
  48. return b[:]
  49. }
  50. // MarshalJSON marshals this NetworkID as a string
  51. func (n NetworkID) MarshalJSON() ([]byte, error) {
  52. return []byte("\"" + n.String() + "\""), nil
  53. }
  54. // UnmarshalJSON unmarshals this NetworkID from a string
  55. func (n *NetworkID) UnmarshalJSON(j []byte) error {
  56. var s string
  57. err := json.Unmarshal(j, &s)
  58. if err != nil {
  59. return err
  60. }
  61. tmp, err := NewNetworkIDFromString(s)
  62. *n = tmp
  63. return err
  64. }
  65. // NetworkConfig represents the network's current configuration as distributed by its network controller.
  66. type NetworkConfig struct {
  67. // ID is this network's 64-bit globally unique identifier
  68. ID NetworkID
  69. // MAC is the Ethernet MAC address of this device on this network
  70. MAC MAC
  71. // Name is a short human-readable name set by the controller
  72. Name string
  73. // Status is a status code indicating this network's authorization status
  74. Status int
  75. // Type is this network's type
  76. Type int
  77. // MTU is the Ethernet MTU for this network
  78. MTU int
  79. // Bridge is true if this network is allowed to bridge in other devices with different Ethernet addresses
  80. Bridge bool
  81. // BroadcastEnabled is true if the broadcast (ff:ff:ff:ff:ff:ff) address works (excluding IPv4 ARP which is handled via a special path)
  82. BroadcastEnabled bool
  83. // NetconfRevision is the revision number reported by the controller
  84. NetconfRevision uint64
  85. // AssignedAddresses are static IPs assigned by the network controller to this device
  86. AssignedAddresses []net.IPNet
  87. // Routes are static routes assigned by the network controller to this device
  88. Routes []Route
  89. }
  90. // NetworkLocalSettings is settings for this network that can be changed locally
  91. type NetworkLocalSettings struct {
  92. // AllowManagedIPs determines whether managed IP assignment is allowed
  93. AllowManagedIPs bool
  94. // AllowGlobalIPs determines if managed IPs that overlap with public Internet addresses are allowed
  95. AllowGlobalIPs bool
  96. // AllowManagedRoutes determines whether managed routes can be set
  97. AllowManagedRoutes bool
  98. // AllowGlobalRoutes determines if managed routes can overlap with public Internet addresses
  99. AllowGlobalRoutes bool
  100. // AllowDefaultRouteOverride determines if the default (0.0.0.0 or ::0) route on the system can be overridden ("full tunnel" mode)
  101. AllowDefaultRouteOverride bool
  102. }
  103. // Network is a currently joined network
  104. type Network struct {
  105. node *Node
  106. id NetworkID
  107. mac MAC
  108. tap Tap
  109. config NetworkConfig
  110. settings NetworkLocalSettings // locked by configLock
  111. multicastSubscriptions map[[2]uint64]*MulticastGroup
  112. configLock sync.RWMutex
  113. multicastSubscriptionsLock sync.RWMutex
  114. }
  115. // newNetwork creates a new network with default settings
  116. func newNetwork(node *Node, id NetworkID, t Tap) (*Network, error) {
  117. m := NewMACForNetworkMember(node.Identity().address, id)
  118. n := &Network{
  119. node: node,
  120. id: id,
  121. mac: m,
  122. tap: t,
  123. config: NetworkConfig{
  124. ID: id,
  125. MAC: m,
  126. Status: NetworkStatusRequestConfiguration,
  127. Type: NetworkTypePrivate,
  128. MTU: int(defaultVirtualNetworkMTU),
  129. },
  130. settings: NetworkLocalSettings{
  131. AllowManagedIPs: true,
  132. AllowGlobalIPs: false,
  133. AllowManagedRoutes: true,
  134. AllowGlobalRoutes: false,
  135. AllowDefaultRouteOverride: false,
  136. },
  137. multicastSubscriptions: make(map[[2]uint64]*MulticastGroup),
  138. }
  139. t.AddMulticastGroupChangeHandler(func(added bool, mg *MulticastGroup) {
  140. if added {
  141. n.MulticastSubscribe(mg)
  142. } else {
  143. n.MulticastUnsubscribe(mg)
  144. }
  145. })
  146. return n, nil
  147. }
  148. // ID gets this network's unique ID
  149. func (n *Network) ID() NetworkID { return n.id }
  150. // MAC returns the assigned MAC address of this network
  151. func (n *Network) MAC() MAC { return n.mac }
  152. // Tap gets this network's tap device
  153. func (n *Network) Tap() Tap { return n.tap }
  154. // Config returns a copy of this network's current configuration
  155. func (n *Network) Config() NetworkConfig {
  156. n.configLock.RLock()
  157. defer n.configLock.RUnlock()
  158. return n.config
  159. }
  160. // SetLocalSettings modifies this network's local settings
  161. func (n *Network) SetLocalSettings(ls *NetworkLocalSettings) { n.updateConfig(nil, ls) }
  162. // LocalSettings gets this network's current local settings
  163. func (n *Network) LocalSettings() NetworkLocalSettings {
  164. n.configLock.RLock()
  165. defer n.configLock.RUnlock()
  166. return n.settings
  167. }
  168. // MulticastSubscribe subscribes to a multicast group
  169. func (n *Network) MulticastSubscribe(mg *MulticastGroup) {
  170. n.node.infoLog.Printf("%.16x joined multicast group %s", uint64(n.id), mg.String())
  171. k := mg.key()
  172. n.multicastSubscriptionsLock.Lock()
  173. if _, have := n.multicastSubscriptions[k]; have {
  174. n.multicastSubscriptionsLock.Unlock()
  175. return
  176. }
  177. n.multicastSubscriptions[k] = mg
  178. n.multicastSubscriptionsLock.Unlock()
  179. n.node.multicastSubscribe(uint64(n.id), mg)
  180. }
  181. // MulticastUnsubscribe removes a subscription to a multicast group
  182. func (n *Network) MulticastUnsubscribe(mg *MulticastGroup) {
  183. n.node.infoLog.Printf("%.16x left multicast group %s", uint64(n.id), mg.String())
  184. n.multicastSubscriptionsLock.Lock()
  185. delete(n.multicastSubscriptions, mg.key())
  186. n.multicastSubscriptionsLock.Unlock()
  187. n.node.multicastUnsubscribe(uint64(n.id), mg)
  188. }
  189. // MulticastSubscriptions returns an array of all multicast subscriptions for this network
  190. func (n *Network) MulticastSubscriptions() []*MulticastGroup {
  191. n.multicastSubscriptionsLock.RLock()
  192. mgs := make([]*MulticastGroup, 0, len(n.multicastSubscriptions))
  193. for _, mg := range n.multicastSubscriptions {
  194. mgs = append(mgs, mg)
  195. }
  196. n.multicastSubscriptionsLock.RUnlock()
  197. sort.Slice(mgs, func(a, b int) bool { return mgs[a].Less(mgs[b]) })
  198. return mgs
  199. }
  200. // leaving is called by Node when the network is being left
  201. func (n *Network) leaving() {
  202. n.tap.Close()
  203. }
  204. func (n *Network) networkConfigRevision() uint64 {
  205. n.configLock.RLock()
  206. defer n.configLock.RUnlock()
  207. return n.config.NetconfRevision
  208. }
  209. func networkManagedIPAllowed(ip net.IP, ls *NetworkLocalSettings) bool {
  210. if !ls.AllowManagedIPs {
  211. return false
  212. }
  213. switch ipClassify(ip) {
  214. case ipClassificationNone, ipClassificationLoopback, ipClassificationLinkLocal, ipClassificationMulticast:
  215. return false
  216. case ipClassificationGlobal:
  217. return ls.AllowGlobalIPs
  218. }
  219. return true
  220. }
  221. func networkManagedRouteAllowed(r *Route, ls *NetworkLocalSettings) bool {
  222. if !ls.AllowManagedRoutes {
  223. return false
  224. }
  225. bits, _ := r.Target.Mask.Size()
  226. if len(r.Target.IP) > 0 && allZero(r.Target.IP) && bits == 0 {
  227. return ls.AllowDefaultRouteOverride
  228. }
  229. switch ipClassify(r.Target.IP) {
  230. case ipClassificationNone, ipClassificationLoopback, ipClassificationLinkLocal, ipClassificationMulticast:
  231. return false
  232. case ipClassificationGlobal:
  233. return ls.AllowGlobalRoutes
  234. }
  235. return true
  236. }
  237. func (n *Network) updateConfig(nc *NetworkConfig, ls *NetworkLocalSettings) {
  238. n.configLock.Lock()
  239. defer n.configLock.Unlock()
  240. if n.tap == nil { // sanity check, should never happen
  241. return
  242. }
  243. if nc == nil {
  244. nc = &n.config
  245. }
  246. if ls == nil {
  247. ls = &n.settings
  248. }
  249. // Add IPs to tap that are newly assigned in this config update,
  250. // and remove any IPs from the tap that were assigned that are no
  251. // longer wanted. IPs assigned to the tap externally (e.g. by an
  252. // "ifconfig" command) are left alone.
  253. haveAssignedIPs := make(map[[3]uint64]*net.IPNet)
  254. wantAssignedIPs := make(map[[3]uint64]bool)
  255. if n.settings.AllowManagedIPs {
  256. for _, ip := range n.config.AssignedAddresses {
  257. if networkManagedIPAllowed(ip.IP, &n.settings) { // was it allowed?
  258. haveAssignedIPs[ipNetToKey(&ip)] = &ip
  259. }
  260. }
  261. }
  262. if ls.AllowManagedIPs {
  263. for _, ip := range nc.AssignedAddresses {
  264. if networkManagedIPAllowed(ip.IP, ls) { // should it be allowed now?
  265. k := ipNetToKey(&ip)
  266. wantAssignedIPs[k] = true
  267. if _, have := haveAssignedIPs[k]; !have {
  268. n.node.infoLog.Printf("%.16x adding managed IP %s", uint64(n.id), ip.String())
  269. _ = n.tap.AddIP(&ip)
  270. }
  271. }
  272. }
  273. }
  274. for k, ip := range haveAssignedIPs {
  275. if _, want := wantAssignedIPs[k]; !want {
  276. n.node.infoLog.Printf("%.16x removing managed IP %s", uint64(n.id), ip.String())
  277. _ = n.tap.RemoveIP(ip)
  278. }
  279. }
  280. // Do the same for managed routes
  281. haveManagedRoutes := make(map[[6]uint64]*Route)
  282. wantManagedRoutes := make(map[[6]uint64]bool)
  283. if n.settings.AllowManagedRoutes {
  284. for _, r := range n.config.Routes {
  285. if networkManagedRouteAllowed(&r, &n.settings) { // was it allowed?
  286. haveManagedRoutes[r.key()] = &r
  287. }
  288. }
  289. }
  290. if ls.AllowManagedRoutes {
  291. for _, r := range nc.Routes {
  292. if networkManagedRouteAllowed(&r, ls) { // should it be allowed now?
  293. k := r.key()
  294. wantManagedRoutes[k] = true
  295. if _, have := haveManagedRoutes[k]; !have {
  296. n.node.infoLog.Printf("%.16x adding managed route %s", uint64(n.id), r.String())
  297. _ = n.tap.AddRoute(&r)
  298. }
  299. }
  300. }
  301. }
  302. for k, r := range haveManagedRoutes {
  303. if _, want := wantManagedRoutes[k]; !want {
  304. n.node.infoLog.Printf("%.16x removing managed route %s", uint64(n.id), r.String())
  305. _ = n.tap.RemoveRoute(r)
  306. }
  307. }
  308. if nc != &n.config {
  309. n.config = *nc
  310. }
  311. if ls != &n.settings {
  312. n.settings = *ls
  313. }
  314. }