dynsec.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package mq
  2. import (
  3. "crypto/sha512"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "os"
  9. "time"
  10. mqtt "github.com/eclipse/paho.mqtt.golang"
  11. "github.com/gravitl/netmaker/functions"
  12. "github.com/gravitl/netmaker/logger"
  13. "github.com/gravitl/netmaker/logic"
  14. "github.com/gravitl/netmaker/netclient/ncutils"
  15. "github.com/gravitl/netmaker/servercfg"
  16. "golang.org/x/crypto/pbkdf2"
  17. )
  18. // mq client for admin
  19. var mqAdminClient mqtt.Client
  20. const (
  21. // constant for client command
  22. CreateClientCmd = "createClient"
  23. // constant for disable command
  24. DisableClientCmd = "disableClient"
  25. // constant for delete client command
  26. DeleteClientCmd = "deleteClient"
  27. // constant for modify client command
  28. ModifyClientCmd = "modifyClient"
  29. // constant for create role command
  30. CreateRoleCmd = "createRole"
  31. // constant for delete role command
  32. DeleteRoleCmd = "deleteRole"
  33. // constant for admin user name
  34. mqAdminUserName = "Netmaker-Admin"
  35. // constant for server user name
  36. mqNetmakerServerUserName = "Netmaker-Server"
  37. // constant for exporter user name
  38. mqExporterUserName = "Netmaker-Exporter"
  39. // DynamicSecSubTopic - constant for dynamic security subscription topic
  40. dynamicSecSubTopic = "$CONTROL/dynamic-security/#"
  41. // DynamicSecPubTopic - constant for dynamic security subscription topic
  42. dynamicSecPubTopic = "$CONTROL/dynamic-security/v1"
  43. )
  44. // struct for dynamic security file
  45. type dynJSON struct {
  46. Clients []client `json:"clients"`
  47. Roles []role `json:"roles"`
  48. DefaultAcl defaultAccessAcl `json:"defaultACLAccess"`
  49. }
  50. // struct for client role
  51. type clientRole struct {
  52. Rolename string `json:"rolename"`
  53. }
  54. // struct for MQ client
  55. type client struct {
  56. Username string `json:"username"`
  57. TextName string `json:"textName"`
  58. Password string `json:"password"`
  59. Salt string `json:"salt"`
  60. Iterations int `json:"iterations"`
  61. Roles []clientRole `json:"roles"`
  62. }
  63. // struct for MQ role
  64. type role struct {
  65. Rolename string `json:"rolename"`
  66. }
  67. // struct for default acls
  68. type defaultAccessAcl struct {
  69. PublishClientSend bool `json:"publishClientSend"`
  70. PublishClientReceive bool `json:"publishClientReceive"`
  71. Subscribe bool `json:"subscribe"`
  72. Unsubscribe bool `json:"unsubscribe"`
  73. }
  74. // MqDynSecGroup - struct for MQ client group
  75. type MqDynSecGroup struct {
  76. Groupname string `json:"groupname"`
  77. Priority int `json:"priority"`
  78. }
  79. // MqDynSecRole - struct for MQ client role
  80. type MqDynSecRole struct {
  81. Rolename string `json:"rolename"`
  82. Priority int `json:"priority"`
  83. }
  84. // MqDynSecCmd - struct for MQ dynamic security command
  85. type MqDynSecCmd struct {
  86. Command string `json:"command"`
  87. Username string `json:"username"`
  88. Password string `json:"password"`
  89. RoleName string `json:"rolename,omitempty"`
  90. Clientid string `json:"clientid"`
  91. Textname string `json:"textname"`
  92. Textdescription string `json:"textdescription"`
  93. Groups []MqDynSecGroup `json:"groups"`
  94. Roles []MqDynSecRole `json:"roles"`
  95. }
  96. // MqDynsecPayload - struct for dynamic security command payload
  97. type MqDynsecPayload struct {
  98. Commands []MqDynSecCmd `json:"commands"`
  99. }
  100. // encodePasswordToPBKDF2 - encodes the given password with PBKDF2 hashing for MQ
  101. func encodePasswordToPBKDF2(password string, salt string, iterations int, keyLength int) string {
  102. binaryEncoded := pbkdf2.Key([]byte(password), []byte(salt), iterations, keyLength, sha512.New)
  103. return base64.StdEncoding.EncodeToString(binaryEncoded)
  104. }
  105. // Configure - configures the dynamic initial configuration for MQ
  106. func Configure() error {
  107. logger.Log(0, "Configuring MQ...")
  108. dynConfig := dynConfigInI
  109. path := functions.GetNetmakerPath() + ncutils.GetSeparator() + dynamicSecurityFile
  110. password := servercfg.GetMqAdminPassword()
  111. if password == "" {
  112. return errors.New("MQ admin password not provided")
  113. }
  114. if logic.CheckIfFileExists(path) {
  115. data, err := os.ReadFile(path)
  116. if err == nil {
  117. var cfg dynJSON
  118. err = json.Unmarshal(data, &cfg)
  119. if err == nil {
  120. logger.Log(0, "MQ config exists already, So Updating Existing Config...")
  121. dynConfig = cfg
  122. }
  123. }
  124. }
  125. exporter := false
  126. for i, cI := range dynConfig.Clients {
  127. if cI.Username == mqAdminUserName || cI.Username == mqNetmakerServerUserName {
  128. salt := logic.RandomString(12)
  129. hashed := encodePasswordToPBKDF2(password, salt, 101, 64)
  130. cI.Password = hashed
  131. cI.Iterations = 101
  132. cI.Salt = base64.StdEncoding.EncodeToString([]byte(salt))
  133. dynConfig.Clients[i] = cI
  134. } else if servercfg.Is_EE && cI.Username == mqExporterUserName {
  135. exporter = true
  136. exporterPassword := servercfg.GetLicenseKey()
  137. salt := logic.RandomString(12)
  138. hashed := encodePasswordToPBKDF2(exporterPassword, salt, 101, 64)
  139. cI.Password = hashed
  140. cI.Iterations = 101
  141. cI.Salt = base64.StdEncoding.EncodeToString([]byte(salt))
  142. dynConfig.Clients[i] = cI
  143. }
  144. }
  145. if servercfg.Is_EE && !exporter {
  146. exporterPassword := servercfg.GetLicenseKey()
  147. salt := logic.RandomString(12)
  148. hashed := encodePasswordToPBKDF2(exporterPassword, salt, 101, 64)
  149. exporterMQClient.Password = hashed
  150. exporterMQClient.Iterations = 101
  151. exporterMQClient.Salt = base64.StdEncoding.EncodeToString([]byte(salt))
  152. dynConfig.Clients = append(dynConfig.Clients, exporterMQClient)
  153. dynConfig.Roles = append(dynConfig.Roles, exporterMQRole)
  154. }
  155. data, err := json.MarshalIndent(dynConfig, "", " ")
  156. if err != nil {
  157. return err
  158. }
  159. return os.WriteFile(path, data, 0755)
  160. }
  161. // publishes the message to dynamic security topic
  162. func publishEventToDynSecTopic(payload MqDynsecPayload) error {
  163. d, err := json.Marshal(payload)
  164. if err != nil {
  165. return err
  166. }
  167. var connecterr error
  168. if token := mqAdminClient.Publish(dynamicSecPubTopic, 2, false, d); !token.WaitTimeout(MQ_TIMEOUT*time.Second) || token.Error() != nil {
  169. if token.Error() == nil {
  170. connecterr = errors.New("connect timeout")
  171. } else {
  172. connecterr = token.Error()
  173. }
  174. }
  175. return connecterr
  176. }
  177. // watchDynSecTopic - message handler for dynamic security responses
  178. func watchDynSecTopic(client mqtt.Client, msg mqtt.Message) {
  179. logger.Log(1, fmt.Sprintf("----->WatchDynSecTopic Message: %+v", string(msg.Payload())))
  180. }