node.go 12 KB

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