node.go 15 KB

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