node.go 17 KB

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