node.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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_DELETE = "delete"
  18. const NODE_IS_PENDING = "pending"
  19. var seededRand *rand.Rand = rand.New(
  20. rand.NewSource(time.Now().UnixNano()))
  21. //node struct
  22. type Node struct {
  23. ID string `json:"id,omitempty" bson:"id,omitempty"`
  24. Address string `json:"address" bson:"address" yaml:"address" validate:"omitempty,ipv4"`
  25. Address6 string `json:"address6" bson:"address6" yaml:"address6" validate:"omitempty,ipv6"`
  26. LocalAddress string `json:"localaddress" bson:"localaddress" yaml:"localaddress" validate:"omitempty,ip"`
  27. Name string `json:"name" bson:"name" yaml:"name" validate:"omitempty,max=12,in_charset"`
  28. ListenPort int32 `json:"listenport" bson:"listenport" yaml:"listenport" validate:"omitempty,numeric,min=1024,max=65535"`
  29. PublicKey string `json:"publickey" bson:"publickey" yaml:"publickey" validate:"required,base64"`
  30. Endpoint string `json:"endpoint" bson:"endpoint" yaml:"endpoint" validate:"required,ip"`
  31. PostUp string `json:"postup" bson:"postup" yaml:"postup"`
  32. PostDown string `json:"postdown" bson:"postdown" yaml:"postdown"`
  33. AllowedIPs []string `json:"allowedips" bson:"allowedips" yaml:"allowedips"`
  34. PersistentKeepalive int32 `json:"persistentkeepalive" bson:"persistentkeepalive" yaml:"persistentkeepalive" validate:"omitempty,numeric,max=1000"`
  35. SaveConfig string `json:"saveconfig" bson:"saveconfig" yaml:"saveconfig" validate:"checkyesorno"`
  36. AccessKey string `json:"accesskey" bson:"accesskey" yaml:"accesskey"`
  37. Interface string `json:"interface" bson:"interface" yaml:"interface"`
  38. LastModified int64 `json:"lastmodified" bson:"lastmodified" yaml:"lastmodified"`
  39. KeyUpdateTimeStamp int64 `json:"keyupdatetimestamp" bson:"keyupdatetimestamp" yaml:"keyupdatetimestamp"`
  40. ExpirationDateTime int64 `json:"expdatetime" bson:"expdatetime" yaml:"expdatetime"`
  41. LastPeerUpdate int64 `json:"lastpeerupdate" bson:"lastpeerupdate" yaml:"lastpeerupdate"`
  42. LastCheckIn int64 `json:"lastcheckin" bson:"lastcheckin" yaml:"lastcheckin"`
  43. MacAddress string `json:"macaddress" bson:"macaddress" yaml:"macaddress" validate:"required,mac,macaddress_unique"`
  44. CheckInInterval int32 `json:"checkininterval" bson:"checkininterval" yaml:"checkininterval"`
  45. Password string `json:"password" bson:"password" yaml:"password" validate:"required,min=6"`
  46. Network string `json:"network" bson:"network" yaml:"network" validate:"network_exists"`
  47. IsPending string `json:"ispending" bson:"ispending" yaml:"ispending"`
  48. IsEgressGateway string `json:"isegressgateway" bson:"isegressgateway" yaml:"isegressgateway"`
  49. IsIngressGateway string `json:"isingressgateway" bson:"isingressgateway" yaml:"isingressgateway"`
  50. EgressGatewayRanges []string `json:"egressgatewayranges" bson:"egressgatewayranges" yaml:"egressgatewayranges"`
  51. IngressGatewayRange string `json:"ingressgatewayrange" bson:"ingressgatewayrange" yaml:"ingressgatewayrange"`
  52. StaticIP string `json:"staticip" bson:"staticip" yaml:"staticip"`
  53. StaticPubKey string `json:"staticpubkey" bson:"staticpubkey" yaml:"staticpubkey"`
  54. UDPHolePunch string `json:"udpholepunch" bson:"udpholepunch" yaml:"udpholepunch" validate:"checkyesorno"`
  55. PullChanges string `json:"pullchanges" bson:"pullchanges" yaml:"pullchanges" validate:"checkyesorno"`
  56. DNSOn string `json:"dnson" bson:"dnson" yaml:"dnson" validate:"checkyesorno"`
  57. IsDualStack string `json:"isdualstack" bson:"isdualstack" yaml:"isdualstack" validate:"checkyesorno"`
  58. Action string `json:"action" bson:"action" yaml:"action"`
  59. IsLocal string `json:"islocal" bson:"islocal" yaml:"islocal" validate:"checkyesorno"`
  60. LocalRange string `json:"localrange" bson:"localrange" yaml:"localrange"`
  61. Roaming string `json:"roaming" bson:"roaming" yaml:"roaming" validate:"checkyesorno"`
  62. IPForwarding string `json:"ipforwarding" bson:"ipforwarding" yaml:"ipforwarding" validate:"checkyesorno"`
  63. }
  64. func (node *Node) SetRoamingDefault() {
  65. if node.Roaming == "" {
  66. node.Roaming = "no"
  67. }
  68. }
  69. func (node *Node) SetPullChangesDefault() {
  70. if node.PullChanges == "" {
  71. node.PullChanges = "no"
  72. }
  73. }
  74. func (node *Node) SetIPForwardingDefault() {
  75. if node.IPForwarding == "" {
  76. node.IPForwarding = "no"
  77. }
  78. }
  79. func (node *Node) SetIsLocalDefault() {
  80. if node.IsLocal == "" {
  81. node.IsLocal = "no"
  82. }
  83. }
  84. func (node *Node) SetDNSOnDefault() {
  85. if node.DNSOn == "" {
  86. node.DNSOn = "no"
  87. }
  88. }
  89. func (node *Node) SetIsDualStackDefault() {
  90. if node.IsDualStack == "" {
  91. node.IsDualStack = "no"
  92. }
  93. }
  94. func (node *Node) SetLastModified() {
  95. node.LastModified = time.Now().Unix()
  96. }
  97. func (node *Node) SetLastCheckIn() {
  98. node.LastCheckIn = time.Now().Unix()
  99. }
  100. func (node *Node) SetLastPeerUpdate() {
  101. node.LastPeerUpdate = time.Now().Unix()
  102. }
  103. func (node *Node) SetID() {
  104. node.ID = node.MacAddress + "###" + node.Network
  105. }
  106. func (node *Node) SetExpirationDateTime() {
  107. node.ExpirationDateTime = time.Now().Unix() + TEN_YEARS_IN_SECONDS
  108. }
  109. func (node *Node) SetDefaultName() {
  110. if node.Name == "" {
  111. nodeid := StringWithCharset(5, charset)
  112. nodename := "node-" + nodeid
  113. node.Name = nodename
  114. }
  115. }
  116. func (node *Node) GetNetwork() (Network, error) {
  117. var network Network
  118. networkData, err := database.FetchRecord(database.NETWORKS_TABLE_NAME, node.Network)
  119. if err != nil {
  120. return network, err
  121. }
  122. if err = json.Unmarshal([]byte(networkData), &network); err != nil {
  123. return Network{}, err
  124. }
  125. return network, nil
  126. }
  127. //TODO: I dont know why this exists
  128. //This should exist on the node.go struct. I'm sure there was a reason?
  129. func (node *Node) SetDefaults() {
  130. //TODO: Maybe I should make Network a part of the node struct. Then we can just query the Network object for stuff.
  131. parentNetwork, _ := node.GetNetwork()
  132. node.ExpirationDateTime = time.Now().Unix() + TEN_YEARS_IN_SECONDS
  133. if node.ListenPort == 0 {
  134. node.ListenPort = parentNetwork.DefaultListenPort
  135. }
  136. if node.SaveConfig == "" {
  137. if parentNetwork.DefaultSaveConfig != "" {
  138. node.SaveConfig = parentNetwork.DefaultSaveConfig
  139. } else {
  140. node.SaveConfig = "yes"
  141. }
  142. }
  143. if node.Interface == "" {
  144. node.Interface = parentNetwork.DefaultInterface
  145. }
  146. if node.PersistentKeepalive == 0 {
  147. node.PersistentKeepalive = parentNetwork.DefaultKeepalive
  148. }
  149. if node.PostUp == "" {
  150. postup := parentNetwork.DefaultPostUp
  151. node.PostUp = postup
  152. }
  153. if node.StaticIP == "" {
  154. node.StaticIP = "no"
  155. }
  156. if node.StaticPubKey == "" {
  157. node.StaticPubKey = "no"
  158. }
  159. if node.UDPHolePunch == "" {
  160. node.UDPHolePunch = parentNetwork.DefaultUDPHolePunch
  161. if node.UDPHolePunch == "" {
  162. node.UDPHolePunch = "yes"
  163. }
  164. }
  165. node.CheckInInterval = parentNetwork.DefaultCheckInInterval
  166. node.SetIPForwardingDefault()
  167. node.SetDNSOnDefault()
  168. node.SetIsLocalDefault()
  169. node.SetIsDualStackDefault()
  170. node.SetLastModified()
  171. node.SetDefaultName()
  172. node.SetLastCheckIn()
  173. node.SetLastPeerUpdate()
  174. node.SetRoamingDefault()
  175. node.SetPullChangesDefault()
  176. node.SetID()
  177. node.KeyUpdateTimeStamp = time.Now().Unix()
  178. }
  179. func (newNode *Node) Fill(currentNode *Node) {
  180. if newNode.ID == "" {
  181. newNode.ID = currentNode.ID
  182. }
  183. if newNode.Address == "" {
  184. newNode.Address = currentNode.Address
  185. }
  186. if newNode.Address6 == "" {
  187. newNode.Address6 = currentNode.Address6
  188. }
  189. if newNode.LocalAddress == "" {
  190. newNode.LocalAddress = currentNode.LocalAddress
  191. }
  192. if newNode.Name == "" {
  193. newNode.Name = currentNode.Name
  194. }
  195. if newNode.ListenPort == 0 {
  196. newNode.ListenPort = currentNode.ListenPort
  197. }
  198. if newNode.PublicKey == "" {
  199. newNode.PublicKey = currentNode.PublicKey
  200. } else {
  201. newNode.KeyUpdateTimeStamp = time.Now().Unix()
  202. }
  203. if newNode.Endpoint == "" {
  204. newNode.Endpoint = currentNode.Endpoint
  205. }
  206. if newNode.PostUp == "" {
  207. newNode.PostUp = currentNode.PostUp
  208. }
  209. if newNode.PostDown == "" {
  210. newNode.PostDown = currentNode.PostDown
  211. }
  212. if newNode.AllowedIPs == nil {
  213. newNode.AllowedIPs = currentNode.AllowedIPs
  214. }
  215. if newNode.PersistentKeepalive == 0 {
  216. newNode.PersistentKeepalive = currentNode.PersistentKeepalive
  217. }
  218. if newNode.SaveConfig == "" {
  219. newNode.SaveConfig = currentNode.SaveConfig
  220. }
  221. if newNode.AccessKey == "" {
  222. newNode.AccessKey = currentNode.AccessKey
  223. }
  224. if newNode.Interface == "" {
  225. newNode.Interface = currentNode.Interface
  226. }
  227. if newNode.LastModified == 0 {
  228. newNode.LastModified = currentNode.LastModified
  229. }
  230. if newNode.KeyUpdateTimeStamp == 0 {
  231. newNode.LastModified = currentNode.LastModified
  232. }
  233. if newNode.ExpirationDateTime == 0 {
  234. newNode.ExpirationDateTime = currentNode.ExpirationDateTime
  235. }
  236. if newNode.LastPeerUpdate == 0 {
  237. newNode.LastPeerUpdate = currentNode.LastPeerUpdate
  238. }
  239. if newNode.LastCheckIn == 0 {
  240. newNode.LastCheckIn = currentNode.LastCheckIn
  241. }
  242. if newNode.MacAddress == "" {
  243. newNode.MacAddress = currentNode.MacAddress
  244. }
  245. if newNode.CheckInInterval == 0 {
  246. newNode.CheckInInterval = currentNode.CheckInInterval
  247. }
  248. if newNode.Password != "" {
  249. err := bcrypt.CompareHashAndPassword([]byte(newNode.Password), []byte(currentNode.Password))
  250. if err != nil && currentNode.Password != newNode.Password {
  251. hash, err := bcrypt.GenerateFromPassword([]byte(newNode.Password), 5)
  252. if err == nil {
  253. newNode.Password = string(hash)
  254. }
  255. }
  256. } else {
  257. newNode.Password = currentNode.Password
  258. }
  259. if newNode.Network == "" {
  260. newNode.Network = currentNode.Network
  261. }
  262. if newNode.IsPending == "" {
  263. newNode.IsPending = currentNode.IsPending
  264. }
  265. if newNode.IsEgressGateway == "" {
  266. newNode.IsEgressGateway = currentNode.IsEgressGateway
  267. }
  268. if newNode.IsIngressGateway == "" {
  269. newNode.IsIngressGateway = currentNode.IsIngressGateway
  270. }
  271. if newNode.EgressGatewayRanges == nil {
  272. newNode.EgressGatewayRanges = currentNode.EgressGatewayRanges
  273. }
  274. if newNode.IngressGatewayRange == "" {
  275. newNode.IngressGatewayRange = currentNode.IngressGatewayRange
  276. }
  277. if newNode.StaticIP == "" {
  278. newNode.StaticIP = currentNode.StaticIP
  279. }
  280. if newNode.StaticIP == "" {
  281. newNode.StaticIP = currentNode.StaticIP
  282. }
  283. if newNode.StaticPubKey == "" {
  284. newNode.StaticPubKey = currentNode.StaticPubKey
  285. }
  286. if newNode.UDPHolePunch == "" {
  287. newNode.UDPHolePunch = currentNode.SaveConfig
  288. }
  289. if newNode.DNSOn == "" {
  290. newNode.DNSOn = currentNode.DNSOn
  291. }
  292. if newNode.IsDualStack == "" {
  293. newNode.IsDualStack = currentNode.IsDualStack
  294. }
  295. if newNode.IsLocal == "" {
  296. newNode.IsLocal = currentNode.IsLocal
  297. }
  298. if newNode.IPForwarding == "" {
  299. newNode.IPForwarding = currentNode.IPForwarding
  300. }
  301. if newNode.PullChanges == "" {
  302. newNode.PullChanges = currentNode.PullChanges
  303. }
  304. if newNode.Roaming == "" {
  305. newNode.Roaming = currentNode.Roaming
  306. }
  307. if newNode.Action == "" {
  308. newNode.Action = currentNode.Action
  309. }
  310. }
  311. func (currentNode *Node) Update(newNode *Node) error {
  312. newNode.Fill(currentNode)
  313. if err := newNode.Validate(true); err != nil {
  314. return err
  315. }
  316. newNode.SetID()
  317. if newNode.ID == currentNode.ID {
  318. newNode.SetLastModified()
  319. if data, err := json.Marshal(newNode); err != nil {
  320. return err
  321. } else {
  322. if err = database.Insert(newNode.ID, string(data), database.NODES_TABLE_NAME); err == nil {
  323. if network, err := GetNetwork(newNode.Network); err == nil {
  324. err = network.SetNetworkNodesLastModified()
  325. }
  326. }
  327. return err
  328. }
  329. }
  330. return errors.New("failed to update node " + newNode.MacAddress + ", cannot change macaddress.")
  331. }
  332. func StringWithCharset(length int, charset string) string {
  333. b := make([]byte, length)
  334. for i := range b {
  335. b[i] = charset[seededRand.Intn(len(charset))]
  336. }
  337. return string(b)
  338. }
  339. //Check for valid IPv4 address
  340. //Note: We dont handle IPv6 AT ALL!!!!! This definitely is needed at some point
  341. //But for iteration 1, lets just stick to IPv4. Keep it simple stupid.
  342. func IsIpv4Net(host string) bool {
  343. return net.ParseIP(host) != nil
  344. }
  345. func (node *Node) Validate(isUpdate bool) error {
  346. v := validator.New()
  347. _ = v.RegisterValidation("macaddress_unique", func(fl validator.FieldLevel) bool {
  348. if isUpdate {
  349. return true
  350. }
  351. isFieldUnique, _ := node.IsIDUnique()
  352. return isFieldUnique
  353. })
  354. _ = v.RegisterValidation("network_exists", func(fl validator.FieldLevel) bool {
  355. _, err := node.GetNetwork()
  356. return err == nil
  357. })
  358. _ = v.RegisterValidation("in_charset", func(fl validator.FieldLevel) bool {
  359. isgood := node.NameInNodeCharSet()
  360. return isgood
  361. })
  362. _ = v.RegisterValidation("checkyesorno", func(fl validator.FieldLevel) bool {
  363. return CheckYesOrNo(fl)
  364. })
  365. err := v.Struct(node)
  366. return err
  367. }
  368. func (node *Node) IsIDUnique() (bool, error) {
  369. _, err := database.FetchRecord(database.NODES_TABLE_NAME, node.ID)
  370. return database.IsEmptyRecord(err), err
  371. }
  372. func (node *Node) NameInNodeCharSet() bool {
  373. charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
  374. for _, char := range node.Name {
  375. if !strings.Contains(charset, strings.ToLower(string(char))) {
  376. return false
  377. }
  378. }
  379. return true
  380. }
  381. func GetAllNodes() ([]Node, error) {
  382. var nodes []Node
  383. collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
  384. if err != nil {
  385. if database.IsEmptyRecord(err) {
  386. return []Node{}, nil
  387. }
  388. return []Node{}, err
  389. }
  390. for _, value := range collection {
  391. var node Node
  392. if err := json.Unmarshal([]byte(value), &node); err != nil {
  393. return []Node{}, err
  394. }
  395. // add node to our array
  396. nodes = append(nodes, node)
  397. }
  398. return nodes, nil
  399. }
  400. func GetNode(macaddress string, network string) (Node, error) {
  401. var node Node
  402. key, err := GetID(macaddress, network)
  403. if err != nil {
  404. return node, err
  405. }
  406. data, err := database.FetchRecord(database.NODES_TABLE_NAME, key)
  407. if err != nil {
  408. return node, err
  409. }
  410. if err = json.Unmarshal([]byte(data), &node); err != nil {
  411. return node, err
  412. }
  413. return node, err
  414. }
  415. func GetID(macaddress string, network string) (string, error) {
  416. if macaddress == "" || network == "" {
  417. return "", errors.New("unable to get record key")
  418. }
  419. return macaddress + "###" + network, nil
  420. }