node.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. package models
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "github.com/go-playground/validator/v10"
  7. "github.com/gravitl/netmaker/database"
  8. "golang.org/x/crypto/bcrypt"
  9. "math/rand"
  10. "net"
  11. "strings"
  12. "time"
  13. )
  14. const charset = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  15. const TEN_YEARS_IN_SECONDS = 300000000
  16. // == ACTIONS == (can only be set by GRPC)
  17. const NODE_UPDATE_KEY = "updatekey"
  18. const NODE_SERVER_NAME = "netmaker"
  19. const NODE_DELETE = "delete"
  20. const NODE_IS_PENDING = "pending"
  21. const NODE_NOOP = "noop"
  22. var seededRand *rand.Rand = rand.New(
  23. rand.NewSource(time.Now().UnixNano()))
  24. // node struct
  25. type Node struct {
  26. ID string `json:"id,omitempty" bson:"id,omitempty"`
  27. Address string `json:"address" bson:"address" yaml:"address" validate:"omitempty,ipv4"`
  28. Address6 string `json:"address6" bson:"address6" yaml:"address6" validate:"omitempty,ipv6"`
  29. LocalAddress string `json:"localaddress" bson:"localaddress" yaml:"localaddress" validate:"omitempty,ip"`
  30. Name string `json:"name" bson:"name" yaml:"name" validate:"omitempty,max=12,in_charset"`
  31. ListenPort int32 `json:"listenport" bson:"listenport" yaml:"listenport" validate:"omitempty,numeric,min=1024,max=65535"`
  32. PublicKey string `json:"publickey" bson:"publickey" yaml:"publickey" validate:"required,base64"`
  33. Endpoint string `json:"endpoint" bson:"endpoint" yaml:"endpoint" validate:"required,ip"`
  34. PostUp string `json:"postup" bson:"postup" yaml:"postup"`
  35. PostDown string `json:"postdown" bson:"postdown" yaml:"postdown"`
  36. AllowedIPs []string `json:"allowedips" bson:"allowedips" yaml:"allowedips"`
  37. PersistentKeepalive int32 `json:"persistentkeepalive" bson:"persistentkeepalive" yaml:"persistentkeepalive" validate:"omitempty,numeric,max=1000"`
  38. SaveConfig string `json:"saveconfig" bson:"saveconfig" yaml:"saveconfig" validate:"checkyesorno"`
  39. AccessKey string `json:"accesskey" bson:"accesskey" yaml:"accesskey"`
  40. Interface string `json:"interface" bson:"interface" yaml:"interface"`
  41. LastModified int64 `json:"lastmodified" bson:"lastmodified" yaml:"lastmodified"`
  42. KeyUpdateTimeStamp int64 `json:"keyupdatetimestamp" bson:"keyupdatetimestamp" yaml:"keyupdatetimestamp"`
  43. ExpirationDateTime int64 `json:"expdatetime" bson:"expdatetime" yaml:"expdatetime"`
  44. LastPeerUpdate int64 `json:"lastpeerupdate" bson:"lastpeerupdate" yaml:"lastpeerupdate"`
  45. LastCheckIn int64 `json:"lastcheckin" bson:"lastcheckin" yaml:"lastcheckin"`
  46. MacAddress string `json:"macaddress" bson:"macaddress" yaml:"macaddress" validate:"required,min=5,macaddress_unique"`
  47. // checkin interval is depreciated at the network level. Set on server with CHECKIN_INTERVAL
  48. CheckInInterval int32 `json:"checkininterval" bson:"checkininterval" yaml:"checkininterval"`
  49. Password string `json:"password" bson:"password" yaml:"password" validate:"required,min=6"`
  50. Network string `json:"network" bson:"network" yaml:"network" validate:"network_exists"`
  51. IsRelayed string `json:"isrelayed" bson:"isrelayed" yaml:"isrelayed"`
  52. IsPending string `json:"ispending" bson:"ispending" yaml:"ispending"`
  53. IsRelay string `json:"isrelay" bson:"isrelay" yaml:"isrelay" validate:"checkyesorno"`
  54. IsEgressGateway string `json:"isegressgateway" bson:"isegressgateway" yaml:"isegressgateway"`
  55. IsIngressGateway string `json:"isingressgateway" bson:"isingressgateway" yaml:"isingressgateway"`
  56. EgressGatewayRanges []string `json:"egressgatewayranges" bson:"egressgatewayranges" yaml:"egressgatewayranges"`
  57. RelayAddrs []string `json:"relayaddrs" bson:"relayaddrs" yaml:"relayaddrs"`
  58. IngressGatewayRange string `json:"ingressgatewayrange" bson:"ingressgatewayrange" yaml:"ingressgatewayrange"`
  59. IsStatic string `json:"isstatic" bson:"isstatic" yaml:"isstatic" validate:"checkyesorno"`
  60. UDPHolePunch string `json:"udpholepunch" bson:"udpholepunch" yaml:"udpholepunch" validate:"checkyesorno"`
  61. PullChanges string `json:"pullchanges" bson:"pullchanges" yaml:"pullchanges" validate:"checkyesorno"`
  62. DNSOn string `json:"dnson" bson:"dnson" yaml:"dnson" validate:"checkyesorno"`
  63. IsDualStack string `json:"isdualstack" bson:"isdualstack" yaml:"isdualstack" validate:"checkyesorno"`
  64. IsServer string `json:"isserver" bson:"isserver" yaml:"isserver" validate:"checkyesorno"`
  65. Action string `json:"action" bson:"action" yaml:"action"`
  66. IsLocal string `json:"islocal" bson:"islocal" yaml:"islocal" validate:"checkyesorno"`
  67. LocalRange string `json:"localrange" bson:"localrange" yaml:"localrange"`
  68. Roaming string `json:"roaming" bson:"roaming" yaml:"roaming" validate:"checkyesorno"`
  69. IPForwarding string `json:"ipforwarding" bson:"ipforwarding" yaml:"ipforwarding" validate:"checkyesorno"`
  70. OS string `json:"os" bson:"os" yaml:"os"`
  71. MTU int32 `json:"mtu" bson:"mtu" yaml:"mtu"`
  72. }
  73. type NodesArray []Node
  74. func (a NodesArray) Len() int { return len(a) }
  75. func (a NodesArray) Less(i, j int) bool { return isLess(a[i].Address, a[j].Address) }
  76. func (a NodesArray) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  77. func isLess(ipA string, ipB string) bool {
  78. ipNetA := net.ParseIP(ipA)
  79. ipNetB := net.ParseIP(ipB)
  80. return bytes.Compare(ipNetA, ipNetB) < 0
  81. }
  82. func (node *Node) SetDefaultMTU() {
  83. if node.MTU == 0 {
  84. node.MTU = 1280
  85. }
  86. }
  87. func (node *Node) SetDefaulIsPending() {
  88. if node.IsPending == "" {
  89. node.IsPending = "no"
  90. }
  91. }
  92. func (node *Node) SetDefaultIsRelayed() {
  93. if node.IsRelayed == "" {
  94. node.IsRelayed = "no"
  95. }
  96. }
  97. func (node *Node) SetDefaultIsRelay() {
  98. if node.IsRelay == "" {
  99. node.IsRelay = "no"
  100. }
  101. }
  102. func (node *Node) SetDefaultEgressGateway() {
  103. if node.IsEgressGateway == "" {
  104. node.IsEgressGateway = "no"
  105. }
  106. }
  107. func (node *Node) SetDefaultIngressGateway() {
  108. if node.IsIngressGateway == "" {
  109. node.IsIngressGateway = "no"
  110. }
  111. }
  112. func (node *Node) SetDefaultAction() {
  113. if node.Action == "" {
  114. node.Action = NODE_NOOP
  115. }
  116. }
  117. func (node *Node) SetRoamingDefault() {
  118. if node.Roaming == "" {
  119. node.Roaming = "yes"
  120. }
  121. }
  122. func (node *Node) SetPullChangesDefault() {
  123. if node.PullChanges == "" {
  124. node.PullChanges = "no"
  125. }
  126. }
  127. func (node *Node) SetIPForwardingDefault() {
  128. if node.IPForwarding == "" {
  129. node.IPForwarding = "yes"
  130. }
  131. }
  132. func (node *Node) SetIsLocalDefault() {
  133. if node.IsLocal == "" {
  134. node.IsLocal = "no"
  135. }
  136. }
  137. func (node *Node) SetDNSOnDefault() {
  138. if node.DNSOn == "" {
  139. node.DNSOn = "yes"
  140. }
  141. }
  142. func (node *Node) SetIsDualStackDefault() {
  143. if node.IsDualStack == "" {
  144. node.IsDualStack = "no"
  145. }
  146. }
  147. func (node *Node) SetIsServerDefault() {
  148. if node.IsServer != "yes" {
  149. node.IsServer = "no"
  150. }
  151. }
  152. func (node *Node) SetIsStaticDefault() {
  153. if node.IsServer == "yes" {
  154. node.IsStatic = "yes"
  155. } else if node.IsStatic != "yes" {
  156. node.IsStatic = "no"
  157. }
  158. }
  159. func (node *Node) SetLastModified() {
  160. node.LastModified = time.Now().Unix()
  161. }
  162. func (node *Node) SetLastCheckIn() {
  163. node.LastCheckIn = time.Now().Unix()
  164. }
  165. func (node *Node) SetLastPeerUpdate() {
  166. node.LastPeerUpdate = time.Now().Unix()
  167. }
  168. func (node *Node) SetID() {
  169. node.ID = node.MacAddress + "###" + node.Network
  170. }
  171. func (node *Node) SetExpirationDateTime() {
  172. node.ExpirationDateTime = time.Now().Unix() + TEN_YEARS_IN_SECONDS
  173. }
  174. func (node *Node) SetDefaultName() {
  175. if node.Name == "" {
  176. node.Name = GenerateNodeName()
  177. }
  178. }
  179. func (node *Node) CheckIsServer() bool {
  180. nodeData, err := database.FetchRecords(database.NODES_TABLE_NAME)
  181. if err != nil && !database.IsEmptyRecord(err) {
  182. return false
  183. }
  184. for _, value := range nodeData {
  185. var tmpNode Node
  186. if err := json.Unmarshal([]byte(value), &tmpNode); err != nil {
  187. continue
  188. }
  189. if tmpNode.Network == node.Network && tmpNode.MacAddress != node.MacAddress {
  190. return false
  191. }
  192. }
  193. return true
  194. }
  195. func (node *Node) GetNetwork() (Network, error) {
  196. var network Network
  197. networkData, err := database.FetchRecord(database.NETWORKS_TABLE_NAME, node.Network)
  198. if err != nil {
  199. return network, err
  200. }
  201. if err = json.Unmarshal([]byte(networkData), &network); err != nil {
  202. return Network{}, err
  203. }
  204. return network, nil
  205. }
  206. //TODO: I dont know why this exists
  207. //This should exist on the node.go struct. I'm sure there was a reason?
  208. func (node *Node) SetDefaults() {
  209. //TODO: Maybe I should make Network a part of the node struct. Then we can just query the Network object for stuff.
  210. parentNetwork, _ := node.GetNetwork()
  211. node.ExpirationDateTime = time.Now().Unix() + TEN_YEARS_IN_SECONDS
  212. if node.ListenPort == 0 {
  213. node.ListenPort = parentNetwork.DefaultListenPort
  214. }
  215. if node.SaveConfig == "" {
  216. if parentNetwork.DefaultSaveConfig != "" {
  217. node.SaveConfig = parentNetwork.DefaultSaveConfig
  218. } else {
  219. node.SaveConfig = "yes"
  220. }
  221. }
  222. if node.Interface == "" {
  223. node.Interface = parentNetwork.DefaultInterface
  224. }
  225. if node.PersistentKeepalive == 0 {
  226. node.PersistentKeepalive = parentNetwork.DefaultKeepalive
  227. }
  228. if node.PostUp == "" {
  229. postup := parentNetwork.DefaultPostUp
  230. node.PostUp = postup
  231. }
  232. if node.IsStatic == "" {
  233. node.IsStatic = "no"
  234. }
  235. if node.UDPHolePunch == "" {
  236. node.UDPHolePunch = parentNetwork.DefaultUDPHolePunch
  237. if node.UDPHolePunch == "" {
  238. node.UDPHolePunch = "yes"
  239. }
  240. }
  241. // == Parent Network settings ==
  242. if node.IsDualStack == "" {
  243. node.IsDualStack = parentNetwork.IsDualStack
  244. }
  245. if node.MTU == 0 {
  246. node.MTU = parentNetwork.DefaultMTU
  247. }
  248. // == node defaults if not set by parent ==
  249. node.SetIPForwardingDefault()
  250. node.SetDNSOnDefault()
  251. node.SetIsLocalDefault()
  252. node.SetIsDualStackDefault()
  253. node.SetLastModified()
  254. node.SetDefaultName()
  255. node.SetLastCheckIn()
  256. node.SetLastPeerUpdate()
  257. node.SetRoamingDefault()
  258. node.SetPullChangesDefault()
  259. node.SetDefaultAction()
  260. node.SetID()
  261. node.SetIsServerDefault()
  262. node.SetIsStaticDefault()
  263. node.SetDefaultEgressGateway()
  264. node.SetDefaultIngressGateway()
  265. node.SetDefaulIsPending()
  266. node.SetDefaultMTU()
  267. node.SetDefaultIsRelayed()
  268. node.SetDefaultIsRelay()
  269. node.KeyUpdateTimeStamp = time.Now().Unix()
  270. }
  271. func (newNode *Node) Fill(currentNode *Node) {
  272. if newNode.ID == "" {
  273. newNode.ID = currentNode.ID
  274. }
  275. if newNode.Address == "" && newNode.IsStatic != "yes" {
  276. newNode.Address = currentNode.Address
  277. }
  278. if newNode.Address6 == "" && newNode.IsStatic != "yes" {
  279. newNode.Address6 = currentNode.Address6
  280. }
  281. if newNode.LocalAddress == "" {
  282. newNode.LocalAddress = currentNode.LocalAddress
  283. }
  284. if newNode.Name == "" {
  285. newNode.Name = currentNode.Name
  286. }
  287. if newNode.ListenPort == 0 && newNode.IsStatic != "yes" {
  288. newNode.ListenPort = currentNode.ListenPort
  289. }
  290. if newNode.PublicKey == "" && newNode.IsStatic != "yes" {
  291. newNode.PublicKey = currentNode.PublicKey
  292. } else {
  293. newNode.KeyUpdateTimeStamp = time.Now().Unix()
  294. }
  295. if newNode.Endpoint == "" && newNode.IsStatic != "yes" {
  296. newNode.Endpoint = currentNode.Endpoint
  297. }
  298. if newNode.PostUp == "" {
  299. newNode.PostUp = currentNode.PostUp
  300. }
  301. if newNode.PostDown == "" {
  302. newNode.PostDown = currentNode.PostDown
  303. }
  304. if newNode.AllowedIPs == nil {
  305. newNode.AllowedIPs = currentNode.AllowedIPs
  306. }
  307. if newNode.PersistentKeepalive == 0 {
  308. newNode.PersistentKeepalive = currentNode.PersistentKeepalive
  309. }
  310. if newNode.SaveConfig == "" {
  311. newNode.SaveConfig = currentNode.SaveConfig
  312. }
  313. if newNode.AccessKey == "" {
  314. newNode.AccessKey = currentNode.AccessKey
  315. }
  316. if newNode.Interface == "" {
  317. newNode.Interface = currentNode.Interface
  318. }
  319. if newNode.LastModified == 0 {
  320. newNode.LastModified = currentNode.LastModified
  321. }
  322. if newNode.KeyUpdateTimeStamp == 0 {
  323. newNode.LastModified = currentNode.LastModified
  324. }
  325. if newNode.ExpirationDateTime == 0 {
  326. newNode.ExpirationDateTime = currentNode.ExpirationDateTime
  327. }
  328. if newNode.LastPeerUpdate == 0 {
  329. newNode.LastPeerUpdate = currentNode.LastPeerUpdate
  330. }
  331. if newNode.LastCheckIn == 0 {
  332. newNode.LastCheckIn = currentNode.LastCheckIn
  333. }
  334. if newNode.MacAddress == "" {
  335. newNode.MacAddress = currentNode.MacAddress
  336. }
  337. if newNode.CheckInInterval == 0 {
  338. newNode.CheckInInterval = currentNode.CheckInInterval
  339. }
  340. if newNode.Password != "" {
  341. err := bcrypt.CompareHashAndPassword([]byte(newNode.Password), []byte(currentNode.Password))
  342. if err != nil && currentNode.Password != newNode.Password {
  343. hash, err := bcrypt.GenerateFromPassword([]byte(newNode.Password), 5)
  344. if err == nil {
  345. newNode.Password = string(hash)
  346. }
  347. }
  348. } else {
  349. newNode.Password = currentNode.Password
  350. }
  351. if newNode.Network == "" {
  352. newNode.Network = currentNode.Network
  353. }
  354. if newNode.IsPending == "" {
  355. newNode.IsPending = currentNode.IsPending
  356. }
  357. if newNode.IsEgressGateway == "" {
  358. newNode.IsEgressGateway = currentNode.IsEgressGateway
  359. }
  360. if newNode.IsIngressGateway == "" {
  361. newNode.IsIngressGateway = currentNode.IsIngressGateway
  362. }
  363. if newNode.EgressGatewayRanges == nil {
  364. newNode.EgressGatewayRanges = currentNode.EgressGatewayRanges
  365. }
  366. if newNode.IngressGatewayRange == "" {
  367. newNode.IngressGatewayRange = currentNode.IngressGatewayRange
  368. }
  369. if newNode.IsStatic == "" {
  370. newNode.IsStatic = currentNode.IsStatic
  371. }
  372. if newNode.UDPHolePunch == "" {
  373. newNode.UDPHolePunch = currentNode.SaveConfig
  374. }
  375. if newNode.DNSOn == "" {
  376. newNode.DNSOn = currentNode.DNSOn
  377. }
  378. if newNode.IsDualStack == "" {
  379. newNode.IsDualStack = currentNode.IsDualStack
  380. }
  381. if newNode.IsLocal == "" {
  382. newNode.IsLocal = currentNode.IsLocal
  383. }
  384. if newNode.IPForwarding == "" {
  385. newNode.IPForwarding = currentNode.IPForwarding
  386. }
  387. if newNode.PullChanges == "" {
  388. newNode.PullChanges = currentNode.PullChanges
  389. }
  390. if newNode.Roaming == "" {
  391. newNode.Roaming = currentNode.Roaming
  392. }
  393. if newNode.Action == "" {
  394. newNode.Action = currentNode.Action
  395. }
  396. if newNode.IsServer == "" {
  397. newNode.IsServer = currentNode.IsServer
  398. }
  399. if newNode.IsServer == "yes" {
  400. newNode.IsStatic = "yes"
  401. }
  402. if newNode.MTU == 0 {
  403. newNode.MTU = currentNode.MTU
  404. }
  405. if newNode.OS == "" {
  406. newNode.OS = currentNode.OS
  407. }
  408. if newNode.RelayAddrs == nil {
  409. newNode.RelayAddrs = currentNode.RelayAddrs
  410. }
  411. if newNode.IsRelay == "" {
  412. newNode.IsRelay = currentNode.IsRelay
  413. }
  414. if newNode.IsRelayed == "" {
  415. newNode.IsRelayed = currentNode.IsRelayed
  416. }
  417. }
  418. func (currentNode *Node) Update(newNode *Node) error {
  419. newNode.Fill(currentNode)
  420. if err := newNode.Validate(true); err != nil {
  421. return err
  422. }
  423. newNode.SetID()
  424. if newNode.ID == currentNode.ID {
  425. newNode.SetLastModified()
  426. if data, err := json.Marshal(newNode); err != nil {
  427. return err
  428. } else {
  429. return database.Insert(newNode.ID, string(data), database.NODES_TABLE_NAME)
  430. }
  431. }
  432. return errors.New("failed to update node " + newNode.MacAddress + ", cannot change macaddress.")
  433. }
  434. func StringWithCharset(length int, charset string) string {
  435. b := make([]byte, length)
  436. for i := range b {
  437. b[i] = charset[seededRand.Intn(len(charset))]
  438. }
  439. return string(b)
  440. }
  441. //Check for valid IPv4 address
  442. //Note: We dont handle IPv6 AT ALL!!!!! This definitely is needed at some point
  443. //But for iteration 1, lets just stick to IPv4. Keep it simple stupid.
  444. func IsIpv4Net(host string) bool {
  445. return net.ParseIP(host) != nil
  446. }
  447. func (node *Node) Validate(isUpdate bool) error {
  448. v := validator.New()
  449. _ = v.RegisterValidation("macaddress_unique", func(fl validator.FieldLevel) bool {
  450. if isUpdate {
  451. return true
  452. }
  453. isFieldUnique, _ := node.IsIDUnique()
  454. return isFieldUnique
  455. })
  456. _ = v.RegisterValidation("network_exists", func(fl validator.FieldLevel) bool {
  457. _, err := node.GetNetwork()
  458. return err == nil
  459. })
  460. _ = v.RegisterValidation("in_charset", func(fl validator.FieldLevel) bool {
  461. isgood := node.NameInNodeCharSet()
  462. return isgood
  463. })
  464. _ = v.RegisterValidation("checkyesorno", func(fl validator.FieldLevel) bool {
  465. return CheckYesOrNo(fl)
  466. })
  467. err := v.Struct(node)
  468. return err
  469. }
  470. func (node *Node) IsIDUnique() (bool, error) {
  471. _, err := database.FetchRecord(database.NODES_TABLE_NAME, node.ID)
  472. return database.IsEmptyRecord(err), err
  473. }
  474. func (node *Node) NameInNodeCharSet() bool {
  475. charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
  476. for _, char := range node.Name {
  477. if !strings.Contains(charset, strings.ToLower(string(char))) {
  478. return false
  479. }
  480. }
  481. return true
  482. }
  483. func GetAllNodes() ([]Node, error) {
  484. var nodes []Node
  485. collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
  486. if err != nil {
  487. if database.IsEmptyRecord(err) {
  488. return []Node{}, nil
  489. }
  490. return []Node{}, err
  491. }
  492. for _, value := range collection {
  493. var node Node
  494. if err := json.Unmarshal([]byte(value), &node); err != nil {
  495. return []Node{}, err
  496. }
  497. // add node to our array
  498. nodes = append(nodes, node)
  499. }
  500. return nodes, nil
  501. }
  502. func (node *Node) GetID() (string, error) {
  503. if node.MacAddress == "" || node.Network == "" {
  504. return "", errors.New("unable to get record key")
  505. }
  506. return node.MacAddress + "###" + node.Network, nil
  507. }