node.go 15 KB

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