node.go 15 KB

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