node.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. package models
  2. import (
  3. "bytes"
  4. "math/rand"
  5. "net"
  6. "strings"
  7. "time"
  8. "golang.org/x/crypto/bcrypt"
  9. )
  10. const (
  11. // NODE_SERVER_NAME - the default server name
  12. NODE_SERVER_NAME = "netmaker"
  13. // TEN_YEARS_IN_SECONDS - ten years in seconds
  14. TEN_YEARS_IN_SECONDS = 300000000
  15. // MAX_NAME_LENGTH - max name length of node
  16. MAX_NAME_LENGTH = 62
  17. // == ACTIONS == (can only be set by server)
  18. // NODE_UPDATE_KEY - action to update key
  19. NODE_UPDATE_KEY = "updatekey"
  20. // NODE_DELETE - delete node action
  21. NODE_DELETE = "delete"
  22. // NODE_IS_PENDING - node pending status
  23. NODE_IS_PENDING = "pending"
  24. // NODE_NOOP - node no op action
  25. NODE_NOOP = "noop"
  26. // NODE_FORCE_UPDATE - indicates a node should pull all changes
  27. NODE_FORCE_UPDATE = "force"
  28. // FIREWALL_IPTABLES - indicates that iptables is the firewall in use
  29. FIREWALL_IPTABLES = "iptables"
  30. // FIREWALL_NFTABLES - indicates nftables is in use (Linux only)
  31. FIREWALL_NFTABLES = "nftables"
  32. // FIREWALL_NONE - indicates that no supported firewall in use
  33. FIREWALL_NONE = "none"
  34. )
  35. var seededRand *rand.Rand = rand.New(
  36. rand.NewSource(time.Now().UnixNano()))
  37. // NodeCheckin - struct for node checkins with server
  38. type NodeCheckin struct {
  39. Version string
  40. Connected string
  41. Ifaces []Iface
  42. }
  43. // Iface struct for local interfaces of a node
  44. type Iface struct {
  45. Name string `json:"name"`
  46. Address net.IPNet `json:"address"`
  47. AddressString string `json:"addressString"`
  48. }
  49. // Node - struct for node model
  50. type Node struct {
  51. ID string `json:"id,omitempty" bson:"id,omitempty" yaml:"id,omitempty" validate:"required,min=5,id_unique"`
  52. HostID string `json:"hostid,omitempty" bson:"id,omitempty" yaml:"hostid,omitempty" validate:"required,min=5,id_unique"`
  53. Address string `json:"address" bson:"address" yaml:"address" validate:"omitempty,ipv4"`
  54. Address6 string `json:"address6" bson:"address6" yaml:"address6" validate:"omitempty,ipv6"`
  55. LocalAddress string `json:"localaddress" bson:"localaddress" yaml:"localaddress" validate:"omitempty"`
  56. Interfaces []Iface `json:"interfaces" yaml:"interfaces"`
  57. Name string `json:"name" bson:"name" yaml:"name" validate:"omitempty,max=62,in_charset"`
  58. NetworkSettings Network `json:"networksettings" bson:"networksettings" yaml:"networksettings" validate:"-"`
  59. ListenPort int32 `json:"listenport" bson:"listenport" yaml:"listenport" validate:"omitempty,numeric,min=1024,max=65535"`
  60. LocalListenPort int32 `json:"locallistenport" bson:"locallistenport" yaml:"locallistenport" validate:"numeric,min=0,max=65535"`
  61. ProxyListenPort int32 `json:"proxy_listen_port" bson:"proxy_listen_port" yaml:"proxy_listen_port" validate:"numeric,min=0,max=65535"`
  62. PublicKey string `json:"publickey" bson:"publickey" yaml:"publickey" validate:"required,base64"`
  63. Endpoint string `json:"endpoint" bson:"endpoint" yaml:"endpoint" validate:"required,ip"`
  64. PostUp string `json:"postup" bson:"postup" yaml:"postup"`
  65. PostDown string `json:"postdown" bson:"postdown" yaml:"postdown"`
  66. AllowedIPs []string `json:"allowedips" bson:"allowedips" yaml:"allowedips"`
  67. PersistentKeepalive int32 `json:"persistentkeepalive" bson:"persistentkeepalive" yaml:"persistentkeepalive" validate:"omitempty,numeric,max=1000"`
  68. IsHub string `json:"ishub" bson:"ishub" yaml:"ishub" validate:"checkyesorno"`
  69. AccessKey string `json:"accesskey" bson:"accesskey" yaml:"accesskey"`
  70. Interface string `json:"interface" bson:"interface" yaml:"interface"`
  71. LastModified int64 `json:"lastmodified" bson:"lastmodified" yaml:"lastmodified"`
  72. ExpirationDateTime int64 `json:"expdatetime" bson:"expdatetime" yaml:"expdatetime"`
  73. LastPeerUpdate int64 `json:"lastpeerupdate" bson:"lastpeerupdate" yaml:"lastpeerupdate"`
  74. LastCheckIn int64 `json:"lastcheckin" bson:"lastcheckin" yaml:"lastcheckin"`
  75. MacAddress string `json:"macaddress" bson:"macaddress" yaml:"macaddress"`
  76. Password string `json:"password" bson:"password" yaml:"password" validate:"required,min=6"`
  77. Network string `json:"network" bson:"network" yaml:"network" validate:"network_exists"`
  78. IsRelayed string `json:"isrelayed" bson:"isrelayed" yaml:"isrelayed"`
  79. IsPending string `json:"ispending" bson:"ispending" yaml:"ispending"`
  80. IsRelay string `json:"isrelay" bson:"isrelay" yaml:"isrelay" validate:"checkyesorno"`
  81. IsDocker string `json:"isdocker" bson:"isdocker" yaml:"isdocker" validate:"checkyesorno"`
  82. IsK8S string `json:"isk8s" bson:"isk8s" yaml:"isk8s" validate:"checkyesorno"`
  83. IsEgressGateway string `json:"isegressgateway" bson:"isegressgateway" yaml:"isegressgateway" validate:"checkyesorno"`
  84. IsIngressGateway string `json:"isingressgateway" bson:"isingressgateway" yaml:"isingressgateway" validate:"checkyesorno"`
  85. EgressGatewayRanges []string `json:"egressgatewayranges" bson:"egressgatewayranges" yaml:"egressgatewayranges"`
  86. EgressGatewayNatEnabled string `json:"egressgatewaynatenabled" bson:"egressgatewaynatenabled" yaml:"egressgatewaynatenabled"`
  87. EgressGatewayRequest EgressGatewayRequest `json:"egressgatewayrequest" bson:"egressgatewayrequest" yaml:"egressgatewayrequest"`
  88. RelayAddrs []string `json:"relayaddrs" bson:"relayaddrs" yaml:"relayaddrs"`
  89. FailoverNode string `json:"failovernode" bson:"failovernode" yaml:"failovernode"`
  90. IngressGatewayRange string `json:"ingressgatewayrange" bson:"ingressgatewayrange" yaml:"ingressgatewayrange"`
  91. IngressGatewayRange6 string `json:"ingressgatewayrange6" bson:"ingressgatewayrange6" yaml:"ingressgatewayrange6"`
  92. // IsStatic - refers to if the Endpoint is set manually or dynamically
  93. IsStatic string `json:"isstatic" bson:"isstatic" yaml:"isstatic" validate:"checkyesorno"`
  94. UDPHolePunch string `json:"udpholepunch" bson:"udpholepunch" yaml:"udpholepunch" validate:"checkyesorno"`
  95. DNSOn string `json:"dnson" bson:"dnson" yaml:"dnson" validate:"checkyesorno"`
  96. IsServer string `json:"isserver" bson:"isserver" yaml:"isserver" validate:"checkyesorno"`
  97. Action string `json:"action" bson:"action" yaml:"action"`
  98. IsLocal string `json:"islocal" bson:"islocal" yaml:"islocal" validate:"checkyesorno"`
  99. LocalRange string `json:"localrange" bson:"localrange" yaml:"localrange"`
  100. IPForwarding string `json:"ipforwarding" bson:"ipforwarding" yaml:"ipforwarding" validate:"checkyesorno"`
  101. OS string `json:"os" bson:"os" yaml:"os"`
  102. MTU int32 `json:"mtu" bson:"mtu" yaml:"mtu"`
  103. Version string `json:"version" bson:"version" yaml:"version"`
  104. Server string `json:"server" bson:"server" yaml:"server"`
  105. TrafficKeys TrafficKeys `json:"traffickeys" bson:"traffickeys" yaml:"traffickeys"`
  106. FirewallInUse string `json:"firewallinuse" bson:"firewallinuse" yaml:"firewallinuse"`
  107. InternetGateway string `json:"internetgateway" bson:"internetgateway" yaml:"internetgateway"`
  108. Connected string `json:"connected" bson:"connected" yaml:"connected" validate:"checkyesorno"`
  109. PendingDelete bool `json:"pendingdelete" bson:"pendingdelete" yaml:"pendingdelete"`
  110. Proxy bool `json:"proxy" bson:"proxy" yaml:"proxy"`
  111. // == PRO ==
  112. DefaultACL string `json:"defaultacl,omitempty" bson:"defaultacl,omitempty" yaml:"defaultacl,omitempty" validate:"checkyesornoorunset"`
  113. OwnerID string `json:"ownerid,omitempty" bson:"ownerid,omitempty" yaml:"ownerid,omitempty"`
  114. Failover string `json:"failover" bson:"failover" yaml:"failover" validate:"checkyesorno"`
  115. }
  116. // NodesArray - used for node sorting
  117. type NodesArray []Node
  118. // NodesArray.Len - gets length of node array
  119. func (a NodesArray) Len() int { return len(a) }
  120. // NodesArray.Less - gets returns lower rank of two node addresses
  121. func (a NodesArray) Less(i, j int) bool { return isLess(a[i].Address, a[j].Address) }
  122. // NodesArray.Swap - swaps two nodes in array
  123. func (a NodesArray) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  124. func isLess(ipA string, ipB string) bool {
  125. ipNetA := net.ParseIP(ipA)
  126. ipNetB := net.ParseIP(ipB)
  127. return bytes.Compare(ipNetA, ipNetB) < 0
  128. }
  129. // Node.PrimaryAddress - return ipv4 address if present, else return ipv6
  130. func (node *Node) PrimaryAddress() string {
  131. if node.Address != "" {
  132. return node.Address
  133. }
  134. return node.Address6
  135. }
  136. // Node.SetDefaultConnected
  137. func (node *Node) SetDefaultConnected() {
  138. if node.Connected == "" {
  139. node.Connected = "yes"
  140. }
  141. if node.IsServer == "yes" {
  142. node.Connected = "yes"
  143. }
  144. }
  145. // Node.SetDefaultACL
  146. func (node *Node) SetDefaultACL() {
  147. if node.DefaultACL == "" {
  148. node.DefaultACL = "yes"
  149. }
  150. }
  151. // Node.SetDefaultMTU - sets default MTU of a node
  152. func (node *Node) SetDefaultMTU() {
  153. if node.MTU == 0 {
  154. node.MTU = 1280
  155. }
  156. }
  157. // Node.SetDefaultNFTablesPresent - sets default for nftables check
  158. func (node *Node) SetDefaultNFTablesPresent() {
  159. if node.FirewallInUse == "" {
  160. node.FirewallInUse = FIREWALL_IPTABLES // default to iptables
  161. }
  162. }
  163. // Node.SetDefaulIsPending - sets ispending default
  164. func (node *Node) SetDefaulIsPending() {
  165. if node.IsPending == "" {
  166. node.IsPending = "no"
  167. }
  168. }
  169. // Node.SetDefaultIsRelayed - set default is relayed
  170. func (node *Node) SetDefaultIsRelayed() {
  171. if node.IsRelayed == "" {
  172. node.IsRelayed = "no"
  173. }
  174. }
  175. // Node.SetDefaultIsRelayed - set default is relayed
  176. func (node *Node) SetDefaultIsHub() {
  177. if node.IsHub == "" {
  178. node.IsHub = "no"
  179. }
  180. }
  181. // Node.SetDefaultIsRelay - set default isrelay
  182. func (node *Node) SetDefaultIsRelay() {
  183. if node.IsRelay == "" {
  184. node.IsRelay = "no"
  185. }
  186. }
  187. // Node.SetDefaultIsDocker - set default isdocker
  188. func (node *Node) SetDefaultIsDocker() {
  189. if node.IsDocker == "" {
  190. node.IsDocker = "no"
  191. }
  192. }
  193. // Node.SetDefaultIsK8S - set default isk8s
  194. func (node *Node) SetDefaultIsK8S() {
  195. if node.IsK8S == "" {
  196. node.IsK8S = "no"
  197. }
  198. }
  199. // Node.SetDefaultEgressGateway - sets default egress gateway status
  200. func (node *Node) SetDefaultEgressGateway() {
  201. if node.IsEgressGateway == "" {
  202. node.IsEgressGateway = "no"
  203. }
  204. }
  205. // Node.SetDefaultIngressGateway - sets default ingress gateway status
  206. func (node *Node) SetDefaultIngressGateway() {
  207. if node.IsIngressGateway == "" {
  208. node.IsIngressGateway = "no"
  209. }
  210. }
  211. // Node.SetDefaultAction - sets default action status
  212. func (node *Node) SetDefaultAction() {
  213. if node.Action == "" {
  214. node.Action = NODE_NOOP
  215. }
  216. }
  217. // Node.SetRoamingDefault - sets default roaming status
  218. //func (node *Node) SetRoamingDefault() {
  219. // if node.Roaming == "" {
  220. // node.Roaming = "yes"
  221. // }
  222. //}
  223. // Node.SetIPForwardingDefault - set ip forwarding default
  224. func (node *Node) SetIPForwardingDefault() {
  225. if node.IPForwarding == "" {
  226. node.IPForwarding = "yes"
  227. }
  228. }
  229. // Node.SetIsLocalDefault - set is local default
  230. func (node *Node) SetIsLocalDefault() {
  231. if node.IsLocal == "" {
  232. node.IsLocal = "no"
  233. }
  234. }
  235. // Node.SetDNSOnDefault - sets dns on default
  236. func (node *Node) SetDNSOnDefault() {
  237. if node.DNSOn == "" {
  238. node.DNSOn = "yes"
  239. }
  240. }
  241. // Node.SetIsServerDefault - sets node isserver default
  242. func (node *Node) SetIsServerDefault() {
  243. if node.IsServer != "yes" {
  244. node.IsServer = "no"
  245. }
  246. }
  247. // Node.SetIsStaticDefault - set is static default
  248. func (node *Node) SetIsStaticDefault() {
  249. if node.IsServer == "yes" {
  250. node.IsStatic = "yes"
  251. } else if node.IsStatic != "yes" {
  252. node.IsStatic = "no"
  253. }
  254. }
  255. // Node.SetLastModified - set last modified initial time
  256. func (node *Node) SetLastModified() {
  257. node.LastModified = time.Now().Unix()
  258. }
  259. // Node.SetLastCheckIn - time.Now().Unix()
  260. func (node *Node) SetLastCheckIn() {
  261. node.LastCheckIn = time.Now().Unix()
  262. }
  263. // Node.SetLastPeerUpdate - sets last peer update time
  264. func (node *Node) SetLastPeerUpdate() {
  265. node.LastPeerUpdate = time.Now().Unix()
  266. }
  267. // Node.SetExpirationDateTime - sets node expiry time
  268. func (node *Node) SetExpirationDateTime() {
  269. node.ExpirationDateTime = time.Now().Unix() + TEN_YEARS_IN_SECONDS
  270. }
  271. // Node.SetDefaultName - sets a random name to node
  272. func (node *Node) SetDefaultName() {
  273. if node.Name == "" {
  274. node.Name = GenerateNodeName()
  275. }
  276. }
  277. // Node.SetDefaultFailover - sets default value of failover status to no if not set
  278. func (node *Node) SetDefaultFailover() {
  279. if node.Failover == "" {
  280. node.Failover = "no"
  281. }
  282. }
  283. // Node.Fill - fills other node data into calling node data if not set on calling node
  284. func (newNode *Node) Fill(currentNode *Node) { // TODO add new field for nftables present
  285. newNode.ID = currentNode.ID
  286. if newNode.Address == "" {
  287. newNode.Address = currentNode.Address
  288. }
  289. if newNode.Address6 == "" {
  290. newNode.Address6 = currentNode.Address6
  291. }
  292. if newNode.LocalAddress == "" {
  293. newNode.LocalAddress = currentNode.LocalAddress
  294. }
  295. if newNode.Name == "" {
  296. newNode.Name = currentNode.Name
  297. }
  298. if newNode.ListenPort == 0 {
  299. newNode.ListenPort = currentNode.ListenPort
  300. }
  301. if newNode.LocalListenPort == 0 {
  302. newNode.LocalListenPort = currentNode.LocalListenPort
  303. }
  304. if newNode.PublicKey == "" {
  305. newNode.PublicKey = currentNode.PublicKey
  306. }
  307. if newNode.Endpoint == "" {
  308. newNode.Endpoint = currentNode.Endpoint
  309. }
  310. if newNode.PostUp == "" {
  311. newNode.PostUp = currentNode.PostUp
  312. }
  313. if newNode.PostDown == "" {
  314. newNode.PostDown = currentNode.PostDown
  315. }
  316. if newNode.AllowedIPs == nil {
  317. newNode.AllowedIPs = currentNode.AllowedIPs
  318. }
  319. if newNode.PersistentKeepalive < 0 {
  320. newNode.PersistentKeepalive = currentNode.PersistentKeepalive
  321. }
  322. if newNode.AccessKey == "" {
  323. newNode.AccessKey = currentNode.AccessKey
  324. }
  325. if newNode.Interface == "" {
  326. newNode.Interface = currentNode.Interface
  327. }
  328. if newNode.LastModified == 0 {
  329. newNode.LastModified = currentNode.LastModified
  330. }
  331. if newNode.ExpirationDateTime == 0 {
  332. newNode.ExpirationDateTime = currentNode.ExpirationDateTime
  333. }
  334. if newNode.LastPeerUpdate == 0 {
  335. newNode.LastPeerUpdate = currentNode.LastPeerUpdate
  336. }
  337. if newNode.LastCheckIn == 0 {
  338. newNode.LastCheckIn = currentNode.LastCheckIn
  339. }
  340. if newNode.MacAddress == "" {
  341. newNode.MacAddress = currentNode.MacAddress
  342. }
  343. if newNode.Password != "" {
  344. err := bcrypt.CompareHashAndPassword([]byte(newNode.Password), []byte(currentNode.Password))
  345. if err != nil && currentNode.Password != newNode.Password {
  346. hash, err := bcrypt.GenerateFromPassword([]byte(newNode.Password), 5)
  347. if err == nil {
  348. newNode.Password = string(hash)
  349. }
  350. }
  351. } else {
  352. newNode.Password = currentNode.Password
  353. }
  354. if newNode.Network == "" {
  355. newNode.Network = currentNode.Network
  356. }
  357. if newNode.IsPending == "" {
  358. newNode.IsPending = currentNode.IsPending
  359. }
  360. if newNode.IsEgressGateway == "" {
  361. newNode.IsEgressGateway = currentNode.IsEgressGateway
  362. }
  363. if newNode.IsIngressGateway == "" {
  364. newNode.IsIngressGateway = currentNode.IsIngressGateway
  365. }
  366. if newNode.EgressGatewayRanges == nil {
  367. newNode.EgressGatewayRanges = currentNode.EgressGatewayRanges
  368. }
  369. if newNode.IngressGatewayRange == "" {
  370. newNode.IngressGatewayRange = currentNode.IngressGatewayRange
  371. }
  372. if newNode.IngressGatewayRange6 == "" {
  373. newNode.IngressGatewayRange6 = currentNode.IngressGatewayRange6
  374. }
  375. if newNode.IsStatic == "" {
  376. newNode.IsStatic = currentNode.IsStatic
  377. }
  378. if newNode.UDPHolePunch == "" {
  379. newNode.UDPHolePunch = currentNode.UDPHolePunch
  380. }
  381. if newNode.DNSOn == "" {
  382. newNode.DNSOn = currentNode.DNSOn
  383. }
  384. if newNode.IsLocal == "" {
  385. newNode.IsLocal = currentNode.IsLocal
  386. }
  387. if newNode.IPForwarding == "" {
  388. newNode.IPForwarding = currentNode.IPForwarding
  389. }
  390. if newNode.Action == "" {
  391. newNode.Action = currentNode.Action
  392. }
  393. if newNode.IsServer == "" {
  394. newNode.IsServer = currentNode.IsServer
  395. }
  396. if newNode.IsServer == "yes" {
  397. newNode.IsStatic = "yes"
  398. newNode.Connected = "yes"
  399. }
  400. if newNode.MTU == 0 {
  401. newNode.MTU = currentNode.MTU
  402. }
  403. if newNode.OS == "" {
  404. newNode.OS = currentNode.OS
  405. }
  406. if newNode.RelayAddrs == nil {
  407. newNode.RelayAddrs = currentNode.RelayAddrs
  408. }
  409. if newNode.IsRelay == "" {
  410. newNode.IsRelay = currentNode.IsRelay
  411. }
  412. if newNode.IsRelayed == "" {
  413. newNode.IsRelayed = currentNode.IsRelayed
  414. }
  415. if newNode.IsDocker == "" {
  416. newNode.IsDocker = currentNode.IsDocker
  417. }
  418. if newNode.IsK8S == "" {
  419. newNode.IsK8S = currentNode.IsK8S
  420. }
  421. if newNode.Version == "" {
  422. newNode.Version = currentNode.Version
  423. }
  424. if newNode.IsHub == "" {
  425. newNode.IsHub = currentNode.IsHub
  426. }
  427. if newNode.Server == "" {
  428. newNode.Server = currentNode.Server
  429. }
  430. if newNode.Connected == "" {
  431. newNode.Connected = currentNode.Connected
  432. }
  433. if newNode.DefaultACL == "" {
  434. newNode.DefaultACL = currentNode.DefaultACL
  435. }
  436. if newNode.Failover == "" {
  437. newNode.Failover = currentNode.Failover
  438. }
  439. newNode.Proxy = currentNode.Proxy
  440. newNode.TrafficKeys = currentNode.TrafficKeys
  441. }
  442. // StringWithCharset - returns random string inside defined charset
  443. func StringWithCharset(length int, charset string) string {
  444. b := make([]byte, length)
  445. for i := range b {
  446. b[i] = charset[seededRand.Intn(len(charset))]
  447. }
  448. return string(b)
  449. }
  450. // IsIpv4Net - check for valid IPv4 address
  451. // Note: We dont handle IPv6 AT ALL!!!!! This definitely is needed at some point
  452. // But for iteration 1, lets just stick to IPv4. Keep it simple stupid.
  453. func IsIpv4Net(host string) bool {
  454. return net.ParseIP(host) != nil
  455. }
  456. // Node.NameInNodeCharset - returns if name is in charset below or not
  457. func (node *Node) NameInNodeCharSet() bool {
  458. charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
  459. for _, char := range node.Name {
  460. if !strings.Contains(charset, strings.ToLower(string(char))) {
  461. return false
  462. }
  463. }
  464. return true
  465. }
  466. // == PRO ==
  467. // Node.DoesACLAllow - checks if default ACL on node is "yes"
  468. func (node *Node) DoesACLAllow() bool {
  469. return node.DefaultACL == "yes"
  470. }
  471. // Node.DoesACLDeny - checks if default ACL on node is "no"
  472. func (node *Node) DoesACLDeny() bool {
  473. return node.DefaultACL == "no"
  474. }