node.go 14 KB

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