node.go 16 KB

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