node.go 14 KB

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