node.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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 = "yes"
  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 = "yes"
  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. node.Name = GenerateNodeName()
  118. }
  119. }
  120. func (node *Node) GetNetwork() (Network, error) {
  121. var network Network
  122. networkData, err := database.FetchRecord(database.NETWORKS_TABLE_NAME, node.Network)
  123. if err != nil {
  124. return network, err
  125. }
  126. if err = json.Unmarshal([]byte(networkData), &network); err != nil {
  127. return Network{}, err
  128. }
  129. return network, nil
  130. }
  131. //TODO: I dont know why this exists
  132. //This should exist on the node.go struct. I'm sure there was a reason?
  133. func (node *Node) SetDefaults() {
  134. //TODO: Maybe I should make Network a part of the node struct. Then we can just query the Network object for stuff.
  135. parentNetwork, _ := node.GetNetwork()
  136. node.ExpirationDateTime = time.Now().Unix() + TEN_YEARS_IN_SECONDS
  137. if node.ListenPort == 0 {
  138. node.ListenPort = parentNetwork.DefaultListenPort
  139. }
  140. if node.SaveConfig == "" {
  141. if parentNetwork.DefaultSaveConfig != "" {
  142. node.SaveConfig = parentNetwork.DefaultSaveConfig
  143. } else {
  144. node.SaveConfig = "yes"
  145. }
  146. }
  147. if node.Interface == "" {
  148. node.Interface = parentNetwork.DefaultInterface
  149. }
  150. if node.PersistentKeepalive == 0 {
  151. node.PersistentKeepalive = parentNetwork.DefaultKeepalive
  152. }
  153. if node.PostUp == "" {
  154. postup := parentNetwork.DefaultPostUp
  155. node.PostUp = postup
  156. }
  157. if node.StaticIP == "" {
  158. node.StaticIP = "no"
  159. }
  160. if node.StaticPubKey == "" {
  161. node.StaticPubKey = "no"
  162. }
  163. if node.UDPHolePunch == "" {
  164. node.UDPHolePunch = parentNetwork.DefaultUDPHolePunch
  165. if node.UDPHolePunch == "" {
  166. node.UDPHolePunch = "yes"
  167. }
  168. }
  169. node.CheckInInterval = parentNetwork.DefaultCheckInInterval
  170. node.SetIPForwardingDefault()
  171. node.SetDNSOnDefault()
  172. node.SetIsLocalDefault()
  173. node.SetIsDualStackDefault()
  174. node.SetLastModified()
  175. node.SetDefaultName()
  176. node.SetLastCheckIn()
  177. node.SetLastPeerUpdate()
  178. node.SetRoamingDefault()
  179. node.SetPullChangesDefault()
  180. node.SetDefaultAction()
  181. node.SetID()
  182. node.KeyUpdateTimeStamp = time.Now().Unix()
  183. }
  184. func (newNode *Node) Fill(currentNode *Node) {
  185. if newNode.ID == "" {
  186. newNode.ID = currentNode.ID
  187. }
  188. if newNode.Address == "" {
  189. newNode.Address = currentNode.Address
  190. }
  191. if newNode.Address6 == "" {
  192. newNode.Address6 = currentNode.Address6
  193. }
  194. if newNode.LocalAddress == "" {
  195. newNode.LocalAddress = currentNode.LocalAddress
  196. }
  197. if newNode.Name == "" {
  198. newNode.Name = currentNode.Name
  199. }
  200. if newNode.ListenPort == 0 {
  201. newNode.ListenPort = currentNode.ListenPort
  202. }
  203. if newNode.PublicKey == "" {
  204. newNode.PublicKey = currentNode.PublicKey
  205. } else {
  206. newNode.KeyUpdateTimeStamp = time.Now().Unix()
  207. }
  208. if newNode.Endpoint == "" {
  209. newNode.Endpoint = currentNode.Endpoint
  210. }
  211. if newNode.PostUp == "" {
  212. newNode.PostUp = currentNode.PostUp
  213. }
  214. if newNode.PostDown == "" {
  215. newNode.PostDown = currentNode.PostDown
  216. }
  217. if newNode.AllowedIPs == nil {
  218. newNode.AllowedIPs = currentNode.AllowedIPs
  219. }
  220. if newNode.PersistentKeepalive == 0 {
  221. newNode.PersistentKeepalive = currentNode.PersistentKeepalive
  222. }
  223. if newNode.SaveConfig == "" {
  224. newNode.SaveConfig = currentNode.SaveConfig
  225. }
  226. if newNode.AccessKey == "" {
  227. newNode.AccessKey = currentNode.AccessKey
  228. }
  229. if newNode.Interface == "" {
  230. newNode.Interface = currentNode.Interface
  231. }
  232. if newNode.LastModified == 0 {
  233. newNode.LastModified = currentNode.LastModified
  234. }
  235. if newNode.KeyUpdateTimeStamp == 0 {
  236. newNode.LastModified = currentNode.LastModified
  237. }
  238. if newNode.ExpirationDateTime == 0 {
  239. newNode.ExpirationDateTime = currentNode.ExpirationDateTime
  240. }
  241. if newNode.LastPeerUpdate == 0 {
  242. newNode.LastPeerUpdate = currentNode.LastPeerUpdate
  243. }
  244. if newNode.LastCheckIn == 0 {
  245. newNode.LastCheckIn = currentNode.LastCheckIn
  246. }
  247. if newNode.MacAddress == "" {
  248. newNode.MacAddress = currentNode.MacAddress
  249. }
  250. if newNode.CheckInInterval == 0 {
  251. newNode.CheckInInterval = currentNode.CheckInInterval
  252. }
  253. if newNode.Password != "" {
  254. err := bcrypt.CompareHashAndPassword([]byte(newNode.Password), []byte(currentNode.Password))
  255. if err != nil && currentNode.Password != newNode.Password {
  256. hash, err := bcrypt.GenerateFromPassword([]byte(newNode.Password), 5)
  257. if err == nil {
  258. newNode.Password = string(hash)
  259. }
  260. }
  261. } else {
  262. newNode.Password = currentNode.Password
  263. }
  264. if newNode.Network == "" {
  265. newNode.Network = currentNode.Network
  266. }
  267. if newNode.IsPending == "" {
  268. newNode.IsPending = currentNode.IsPending
  269. }
  270. if newNode.IsEgressGateway == "" {
  271. newNode.IsEgressGateway = currentNode.IsEgressGateway
  272. }
  273. if newNode.IsIngressGateway == "" {
  274. newNode.IsIngressGateway = currentNode.IsIngressGateway
  275. }
  276. if newNode.EgressGatewayRanges == nil {
  277. newNode.EgressGatewayRanges = currentNode.EgressGatewayRanges
  278. }
  279. if newNode.IngressGatewayRange == "" {
  280. newNode.IngressGatewayRange = currentNode.IngressGatewayRange
  281. }
  282. if newNode.StaticIP == "" {
  283. newNode.StaticIP = currentNode.StaticIP
  284. }
  285. if newNode.StaticIP == "" {
  286. newNode.StaticIP = currentNode.StaticIP
  287. }
  288. if newNode.StaticPubKey == "" {
  289. newNode.StaticPubKey = currentNode.StaticPubKey
  290. }
  291. if newNode.UDPHolePunch == "" {
  292. newNode.UDPHolePunch = currentNode.SaveConfig
  293. }
  294. if newNode.DNSOn == "" {
  295. newNode.DNSOn = currentNode.DNSOn
  296. }
  297. if newNode.IsDualStack == "" {
  298. newNode.IsDualStack = currentNode.IsDualStack
  299. }
  300. if newNode.IsLocal == "" {
  301. newNode.IsLocal = currentNode.IsLocal
  302. }
  303. if newNode.IPForwarding == "" {
  304. newNode.IPForwarding = currentNode.IPForwarding
  305. }
  306. if newNode.PullChanges == "" {
  307. newNode.PullChanges = currentNode.PullChanges
  308. }
  309. if newNode.Roaming == "" {
  310. newNode.Roaming = currentNode.Roaming
  311. }
  312. if newNode.Action == "" {
  313. newNode.Action = currentNode.Action
  314. }
  315. }
  316. func (currentNode *Node) Update(newNode *Node) error {
  317. newNode.Fill(currentNode)
  318. if err := newNode.Validate(true); err != nil {
  319. return err
  320. }
  321. newNode.SetID()
  322. if newNode.ID == currentNode.ID {
  323. newNode.SetLastModified()
  324. if data, err := json.Marshal(newNode); err != nil {
  325. return err
  326. } else {
  327. return database.Insert(newNode.ID, string(data), database.NODES_TABLE_NAME)
  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. }