node.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. // Node - struct for node model
  38. type Node struct {
  39. ID string `json:"id,omitempty" bson:"id,omitempty" yaml:"id,omitempty" validate:"required,min=5,id_unique"`
  40. Address string `json:"address" bson:"address" yaml:"address" validate:"omitempty,ipv4"`
  41. Address6 string `json:"address6" bson:"address6" yaml:"address6" validate:"omitempty,ipv6"`
  42. LocalAddress string `json:"localaddress" bson:"localaddress" yaml:"localaddress" validate:"omitempty,ip"`
  43. Name string `json:"name" bson:"name" yaml:"name" validate:"omitempty,max=62,in_charset"`
  44. NetworkSettings Network `json:"networksettings" bson:"networksettings" yaml:"networksettings" validate:"-"`
  45. ListenPort int32 `json:"listenport" bson:"listenport" yaml:"listenport" validate:"omitempty,numeric,min=1024,max=65535"`
  46. LocalListenPort int32 `json:"locallistenport" bson:"locallistenport" yaml:"locallistenport" validate:"numeric,min=0,max=65535"`
  47. PublicKey string `json:"publickey" bson:"publickey" yaml:"publickey" validate:"required,base64"`
  48. Endpoint string `json:"endpoint" bson:"endpoint" yaml:"endpoint" validate:"required,ip"`
  49. PostUp string `json:"postup" bson:"postup" yaml:"postup"`
  50. PostDown string `json:"postdown" bson:"postdown" yaml:"postdown"`
  51. AllowedIPs []string `json:"allowedips" bson:"allowedips" yaml:"allowedips"`
  52. PersistentKeepalive int32 `json:"persistentkeepalive" bson:"persistentkeepalive" yaml:"persistentkeepalive" validate:"omitempty,numeric,max=1000"`
  53. IsHub string `json:"ishub" bson:"ishub" yaml:"ishub" validate:"checkyesorno"`
  54. AccessKey string `json:"accesskey" bson:"accesskey" yaml:"accesskey"`
  55. Interface string `json:"interface" bson:"interface" yaml:"interface"`
  56. LastModified int64 `json:"lastmodified" bson:"lastmodified" yaml:"lastmodified"`
  57. ExpirationDateTime int64 `json:"expdatetime" bson:"expdatetime" yaml:"expdatetime"`
  58. LastPeerUpdate int64 `json:"lastpeerupdate" bson:"lastpeerupdate" yaml:"lastpeerupdate"`
  59. LastCheckIn int64 `json:"lastcheckin" bson:"lastcheckin" yaml:"lastcheckin"`
  60. MacAddress string `json:"macaddress" bson:"macaddress" yaml:"macaddress"`
  61. Password string `json:"password" bson:"password" yaml:"password" validate:"required,min=6"`
  62. Network string `json:"network" bson:"network" yaml:"network" validate:"network_exists"`
  63. IsRelayed string `json:"isrelayed" bson:"isrelayed" yaml:"isrelayed"`
  64. IsPending string `json:"ispending" bson:"ispending" yaml:"ispending"`
  65. IsRelay string `json:"isrelay" bson:"isrelay" yaml:"isrelay" validate:"checkyesorno"`
  66. IsDocker string `json:"isdocker" bson:"isdocker" yaml:"isdocker" validate:"checkyesorno"`
  67. IsK8S string `json:"isk8s" bson:"isk8s" yaml:"isk8s" validate:"checkyesorno"`
  68. IsEgressGateway string `json:"isegressgateway" bson:"isegressgateway" yaml:"isegressgateway" validate:"checkyesorno"`
  69. IsIngressGateway string `json:"isingressgateway" bson:"isingressgateway" yaml:"isingressgateway" validate:"checkyesorno"`
  70. EgressGatewayRanges []string `json:"egressgatewayranges" bson:"egressgatewayranges" yaml:"egressgatewayranges"`
  71. EgressGatewayNatEnabled string `json:"egressgatewaynatenabled" bson:"egressgatewaynatenabled" yaml:"egressgatewaynatenabled"`
  72. EgressGatewayRequest EgressGatewayRequest `json:"egressgatewayrequest" bson:"egressgatewayrequest" yaml:"egressgatewayrequest"`
  73. RelayAddrs []string `json:"relayaddrs" bson:"relayaddrs" yaml:"relayaddrs"`
  74. IngressGatewayRange string `json:"ingressgatewayrange" bson:"ingressgatewayrange" yaml:"ingressgatewayrange"`
  75. // IsStatic - refers to if the Endpoint is set manually or dynamically
  76. IsStatic string `json:"isstatic" bson:"isstatic" yaml:"isstatic" validate:"checkyesorno"`
  77. UDPHolePunch string `json:"udpholepunch" bson:"udpholepunch" yaml:"udpholepunch" validate:"checkyesorno"`
  78. DNSOn string `json:"dnson" bson:"dnson" yaml:"dnson" validate:"checkyesorno"`
  79. IsServer string `json:"isserver" bson:"isserver" yaml:"isserver" validate:"checkyesorno"`
  80. Action string `json:"action" bson:"action" yaml:"action"`
  81. IsLocal string `json:"islocal" bson:"islocal" yaml:"islocal" validate:"checkyesorno"`
  82. LocalRange string `json:"localrange" bson:"localrange" yaml:"localrange"`
  83. IPForwarding string `json:"ipforwarding" bson:"ipforwarding" yaml:"ipforwarding" validate:"checkyesorno"`
  84. OS string `json:"os" bson:"os" yaml:"os"`
  85. MTU int32 `json:"mtu" bson:"mtu" yaml:"mtu"`
  86. Version string `json:"version" bson:"version" yaml:"version"`
  87. Server string `json:"server" bson:"server" yaml:"server"`
  88. TrafficKeys TrafficKeys `json:"traffickeys" bson:"traffickeys" yaml:"traffickeys"`
  89. FirewallInUse string `json:"firewallinuse" bson:"firewallinuse" yaml:"firewallinuse"`
  90. InternetGateway string `json:"internetgateway" bson:"internetgateway" yaml:"internetgateway"`
  91. Connected string `json:"connected" bson:"connected" yaml:"connected" validate:"checkyesorno"`
  92. }
  93. // NodesArray - used for node sorting
  94. type NodesArray []Node
  95. // NodesArray.Len - gets length of node array
  96. func (a NodesArray) Len() int { return len(a) }
  97. // NodesArray.Less - gets returns lower rank of two node addresses
  98. func (a NodesArray) Less(i, j int) bool { return isLess(a[i].Address, a[j].Address) }
  99. // NodesArray.Swap - swaps two nodes in array
  100. func (a NodesArray) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  101. func isLess(ipA string, ipB string) bool {
  102. ipNetA := net.ParseIP(ipA)
  103. ipNetB := net.ParseIP(ipB)
  104. return bytes.Compare(ipNetA, ipNetB) < 0
  105. }
  106. // Node.PrimaryAddress - return ipv4 address if present, else return ipv6
  107. func (node *Node) PrimaryAddress() string {
  108. if node.Address != "" {
  109. return node.Address
  110. }
  111. return node.Address6
  112. }
  113. // Node.SetDefaultConnected
  114. func (node *Node) SetDefaultConnected() {
  115. if node.Connected == "" {
  116. node.Connected = "yes"
  117. }
  118. if node.IsServer == "yes" {
  119. node.Connected = "yes"
  120. }
  121. }
  122. // Node.SetDefaultMTU - sets default MTU of a node
  123. func (node *Node) SetDefaultMTU() {
  124. if node.MTU == 0 {
  125. node.MTU = 1280
  126. }
  127. }
  128. // Node.SetDefaultNFTablesPresent - sets default for nftables check
  129. func (node *Node) SetDefaultNFTablesPresent() {
  130. if node.FirewallInUse == "" {
  131. node.FirewallInUse = FIREWALL_IPTABLES // default to iptables
  132. }
  133. }
  134. // Node.SetDefaulIsPending - sets ispending default
  135. func (node *Node) SetDefaulIsPending() {
  136. if node.IsPending == "" {
  137. node.IsPending = "no"
  138. }
  139. }
  140. // Node.SetDefaultIsRelayed - set default is relayed
  141. func (node *Node) SetDefaultIsRelayed() {
  142. if node.IsRelayed == "" {
  143. node.IsRelayed = "no"
  144. }
  145. }
  146. // Node.SetDefaultIsRelayed - set default is relayed
  147. func (node *Node) SetDefaultIsHub() {
  148. if node.IsHub == "" {
  149. node.IsHub = "no"
  150. }
  151. }
  152. // Node.SetDefaultIsRelay - set default isrelay
  153. func (node *Node) SetDefaultIsRelay() {
  154. if node.IsRelay == "" {
  155. node.IsRelay = "no"
  156. }
  157. }
  158. // Node.SetDefaultIsDocker - set default isdocker
  159. func (node *Node) SetDefaultIsDocker() {
  160. if node.IsDocker == "" {
  161. node.IsDocker = "no"
  162. }
  163. }
  164. // Node.SetDefaultIsK8S - set default isk8s
  165. func (node *Node) SetDefaultIsK8S() {
  166. if node.IsK8S == "" {
  167. node.IsK8S = "no"
  168. }
  169. }
  170. // Node.SetDefaultEgressGateway - sets default egress gateway status
  171. func (node *Node) SetDefaultEgressGateway() {
  172. if node.IsEgressGateway == "" {
  173. node.IsEgressGateway = "no"
  174. }
  175. }
  176. // Node.SetDefaultIngressGateway - sets default ingress gateway status
  177. func (node *Node) SetDefaultIngressGateway() {
  178. if node.IsIngressGateway == "" {
  179. node.IsIngressGateway = "no"
  180. }
  181. }
  182. // Node.SetDefaultAction - sets default action status
  183. func (node *Node) SetDefaultAction() {
  184. if node.Action == "" {
  185. node.Action = NODE_NOOP
  186. }
  187. }
  188. // Node.SetRoamingDefault - sets default roaming status
  189. //func (node *Node) SetRoamingDefault() {
  190. // if node.Roaming == "" {
  191. // node.Roaming = "yes"
  192. // }
  193. //}
  194. // Node.SetIPForwardingDefault - set ip forwarding default
  195. func (node *Node) SetIPForwardingDefault() {
  196. if node.IPForwarding == "" {
  197. node.IPForwarding = "yes"
  198. }
  199. }
  200. // Node.SetIsLocalDefault - set is local default
  201. func (node *Node) SetIsLocalDefault() {
  202. if node.IsLocal == "" {
  203. node.IsLocal = "no"
  204. }
  205. }
  206. // Node.SetDNSOnDefault - sets dns on default
  207. func (node *Node) SetDNSOnDefault() {
  208. if node.DNSOn == "" {
  209. node.DNSOn = "yes"
  210. }
  211. }
  212. // Node.SetIsServerDefault - sets node isserver default
  213. func (node *Node) SetIsServerDefault() {
  214. if node.IsServer != "yes" {
  215. node.IsServer = "no"
  216. }
  217. }
  218. // Node.SetIsStaticDefault - set is static default
  219. func (node *Node) SetIsStaticDefault() {
  220. if node.IsServer == "yes" {
  221. node.IsStatic = "yes"
  222. } else if node.IsStatic != "yes" {
  223. node.IsStatic = "no"
  224. }
  225. }
  226. // Node.SetLastModified - set last modified initial time
  227. func (node *Node) SetLastModified() {
  228. node.LastModified = time.Now().Unix()
  229. }
  230. // Node.SetLastCheckIn - time.Now().Unix()
  231. func (node *Node) SetLastCheckIn() {
  232. node.LastCheckIn = time.Now().Unix()
  233. }
  234. // Node.SetLastPeerUpdate - sets last peer update time
  235. func (node *Node) SetLastPeerUpdate() {
  236. node.LastPeerUpdate = time.Now().Unix()
  237. }
  238. // Node.SetExpirationDateTime - sets node expiry time
  239. func (node *Node) SetExpirationDateTime() {
  240. node.ExpirationDateTime = time.Now().Unix() + TEN_YEARS_IN_SECONDS
  241. }
  242. // Node.SetDefaultName - sets a random name to node
  243. func (node *Node) SetDefaultName() {
  244. if node.Name == "" {
  245. node.Name = GenerateNodeName()
  246. }
  247. }
  248. // Node.Fill - fills other node data into calling node data if not set on calling node
  249. func (newNode *Node) Fill(currentNode *Node) { // TODO add new field for nftables present
  250. newNode.ID = currentNode.ID
  251. if newNode.Address == "" {
  252. newNode.Address = currentNode.Address
  253. }
  254. if newNode.Address6 == "" {
  255. newNode.Address6 = currentNode.Address6
  256. }
  257. if newNode.LocalAddress == "" {
  258. newNode.LocalAddress = currentNode.LocalAddress
  259. }
  260. if newNode.Name == "" {
  261. newNode.Name = currentNode.Name
  262. }
  263. if newNode.ListenPort == 0 {
  264. newNode.ListenPort = currentNode.ListenPort
  265. }
  266. if newNode.LocalListenPort == 0 {
  267. newNode.LocalListenPort = currentNode.LocalListenPort
  268. }
  269. if newNode.PublicKey == "" {
  270. newNode.PublicKey = currentNode.PublicKey
  271. }
  272. if newNode.Endpoint == "" {
  273. newNode.Endpoint = currentNode.Endpoint
  274. }
  275. if newNode.PostUp == "" {
  276. newNode.PostUp = currentNode.PostUp
  277. }
  278. if newNode.PostDown == "" {
  279. newNode.PostDown = currentNode.PostDown
  280. }
  281. if newNode.AllowedIPs == nil {
  282. newNode.AllowedIPs = currentNode.AllowedIPs
  283. }
  284. if newNode.PersistentKeepalive < 0 {
  285. newNode.PersistentKeepalive = currentNode.PersistentKeepalive
  286. }
  287. if newNode.AccessKey == "" {
  288. newNode.AccessKey = currentNode.AccessKey
  289. }
  290. if newNode.Interface == "" {
  291. newNode.Interface = currentNode.Interface
  292. }
  293. if newNode.LastModified == 0 {
  294. newNode.LastModified = currentNode.LastModified
  295. }
  296. if newNode.ExpirationDateTime == 0 {
  297. newNode.ExpirationDateTime = currentNode.ExpirationDateTime
  298. }
  299. if newNode.LastPeerUpdate == 0 {
  300. newNode.LastPeerUpdate = currentNode.LastPeerUpdate
  301. }
  302. if newNode.LastCheckIn == 0 {
  303. newNode.LastCheckIn = currentNode.LastCheckIn
  304. }
  305. if newNode.MacAddress == "" {
  306. newNode.MacAddress = currentNode.MacAddress
  307. }
  308. if newNode.Password != "" {
  309. err := bcrypt.CompareHashAndPassword([]byte(newNode.Password), []byte(currentNode.Password))
  310. if err != nil && currentNode.Password != newNode.Password {
  311. hash, err := bcrypt.GenerateFromPassword([]byte(newNode.Password), 5)
  312. if err == nil {
  313. newNode.Password = string(hash)
  314. }
  315. }
  316. } else {
  317. newNode.Password = currentNode.Password
  318. }
  319. if newNode.Network == "" {
  320. newNode.Network = currentNode.Network
  321. }
  322. if newNode.IsPending == "" {
  323. newNode.IsPending = currentNode.IsPending
  324. }
  325. if newNode.IsEgressGateway == "" {
  326. newNode.IsEgressGateway = currentNode.IsEgressGateway
  327. }
  328. if newNode.IsIngressGateway == "" {
  329. newNode.IsIngressGateway = currentNode.IsIngressGateway
  330. }
  331. if newNode.EgressGatewayRanges == nil {
  332. newNode.EgressGatewayRanges = currentNode.EgressGatewayRanges
  333. }
  334. if newNode.IngressGatewayRange == "" {
  335. newNode.IngressGatewayRange = currentNode.IngressGatewayRange
  336. }
  337. if newNode.IsStatic == "" {
  338. newNode.IsStatic = currentNode.IsStatic
  339. }
  340. if newNode.UDPHolePunch == "" {
  341. newNode.UDPHolePunch = currentNode.UDPHolePunch
  342. }
  343. if newNode.DNSOn == "" {
  344. newNode.DNSOn = currentNode.DNSOn
  345. }
  346. if newNode.IsLocal == "" {
  347. newNode.IsLocal = currentNode.IsLocal
  348. }
  349. if newNode.IPForwarding == "" {
  350. newNode.IPForwarding = currentNode.IPForwarding
  351. }
  352. if newNode.Action == "" {
  353. newNode.Action = currentNode.Action
  354. }
  355. if newNode.IsServer == "" {
  356. newNode.IsServer = currentNode.IsServer
  357. }
  358. if newNode.IsServer == "yes" {
  359. newNode.IsStatic = "yes"
  360. newNode.Connected = "yes"
  361. }
  362. if newNode.MTU == 0 {
  363. newNode.MTU = currentNode.MTU
  364. }
  365. if newNode.OS == "" {
  366. newNode.OS = currentNode.OS
  367. }
  368. if newNode.RelayAddrs == nil {
  369. newNode.RelayAddrs = currentNode.RelayAddrs
  370. }
  371. if newNode.IsRelay == "" {
  372. newNode.IsRelay = currentNode.IsRelay
  373. }
  374. if newNode.IsRelayed == "" {
  375. newNode.IsRelayed = currentNode.IsRelayed
  376. }
  377. if newNode.IsDocker == "" {
  378. newNode.IsDocker = currentNode.IsDocker
  379. }
  380. if newNode.IsK8S == "" {
  381. newNode.IsK8S = currentNode.IsK8S
  382. }
  383. if newNode.Version == "" {
  384. newNode.Version = currentNode.Version
  385. }
  386. if newNode.IsHub == "" {
  387. newNode.IsHub = currentNode.IsHub
  388. }
  389. if newNode.Server == "" {
  390. newNode.Server = currentNode.Server
  391. }
  392. if newNode.Connected == "" {
  393. newNode.Connected = currentNode.Connected
  394. }
  395. newNode.TrafficKeys = currentNode.TrafficKeys
  396. }
  397. // StringWithCharset - returns random string inside defined charset
  398. func StringWithCharset(length int, charset string) string {
  399. b := make([]byte, length)
  400. for i := range b {
  401. b[i] = charset[seededRand.Intn(len(charset))]
  402. }
  403. return string(b)
  404. }
  405. // IsIpv4Net - check for valid IPv4 address
  406. // Note: We dont handle IPv6 AT ALL!!!!! This definitely is needed at some point
  407. // But for iteration 1, lets just stick to IPv4. Keep it simple stupid.
  408. func IsIpv4Net(host string) bool {
  409. return net.ParseIP(host) != nil
  410. }
  411. // Node.NameInNodeCharset - returns if name is in charset below or not
  412. func (node *Node) NameInNodeCharSet() bool {
  413. charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
  414. for _, char := range node.Name {
  415. if !strings.Contains(charset, strings.ToLower(string(char))) {
  416. return false
  417. }
  418. }
  419. return true
  420. }