dynsec.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. Acls []Acl `json:"acls"`
  67. }
  68. // struct for default acls
  69. type defaultAccessAcl struct {
  70. PublishClientSend bool `json:"publishClientSend"`
  71. PublishClientReceive bool `json:"publishClientReceive"`
  72. Subscribe bool `json:"subscribe"`
  73. Unsubscribe bool `json:"unsubscribe"`
  74. }
  75. // MqDynSecGroup - struct for MQ client group
  76. type MqDynSecGroup struct {
  77. Groupname string `json:"groupname"`
  78. Priority int `json:"priority"`
  79. }
  80. // MqDynSecRole - struct for MQ client role
  81. type MqDynSecRole struct {
  82. Rolename string `json:"rolename"`
  83. Priority int `json:"priority"`
  84. }
  85. // Acl - struct for MQ acls
  86. type Acl struct {
  87. AclType string `json:"acltype"`
  88. Topic string `json:"topic"`
  89. Priority int `json:"priority,omitempty"`
  90. Allow bool `json:"allow"`
  91. }
  92. // MqDynSecCmd - struct for MQ dynamic security command
  93. type MqDynSecCmd struct {
  94. Command string `json:"command"`
  95. Username string `json:"username"`
  96. Password string `json:"password"`
  97. RoleName string `json:"rolename,omitempty"`
  98. Acls []Acl `json:"acls,omitempty"`
  99. Clientid string `json:"clientid"`
  100. Textname string `json:"textname"`
  101. Textdescription string `json:"textdescription"`
  102. Groups []MqDynSecGroup `json:"groups"`
  103. Roles []MqDynSecRole `json:"roles"`
  104. }
  105. // MqDynsecPayload - struct for dynamic security command payload
  106. type MqDynsecPayload struct {
  107. Commands []MqDynSecCmd `json:"commands"`
  108. }
  109. // encodePasswordToPBKDF2 - encodes the given password with PBKDF2 hashing for MQ
  110. func encodePasswordToPBKDF2(password string, salt string, iterations int, keyLength int) string {
  111. binaryEncoded := pbkdf2.Key([]byte(password), []byte(salt), iterations, keyLength, sha512.New)
  112. return base64.StdEncoding.EncodeToString(binaryEncoded)
  113. }
  114. // Configure - configures the dynamic initial configuration for MQ
  115. func Configure() error {
  116. logger.Log(0, "Configuring MQ...")
  117. dynConfig := dynConfigInI
  118. path := functions.GetNetmakerPath() + ncutils.GetSeparator() + dynamicSecurityFile
  119. password := servercfg.GetMqAdminPassword()
  120. if password == "" {
  121. return errors.New("MQ admin password not provided")
  122. }
  123. if logic.CheckIfFileExists(path) {
  124. data, err := os.ReadFile(path)
  125. if err == nil {
  126. var cfg dynJSON
  127. err = json.Unmarshal(data, &cfg)
  128. if err == nil {
  129. logger.Log(0, "MQ config exists already, So Updating Existing Config...")
  130. dynConfig = cfg
  131. }
  132. }
  133. }
  134. exporter := false
  135. for i, cI := range dynConfig.Clients {
  136. if cI.Username == mqAdminUserName || cI.Username == mqNetmakerServerUserName {
  137. salt := logic.RandomString(12)
  138. hashed := encodePasswordToPBKDF2(password, 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. } else if servercfg.Is_EE && cI.Username == mqExporterUserName {
  144. exporter = true
  145. exporterPassword := servercfg.GetLicenseKey()
  146. salt := logic.RandomString(12)
  147. hashed := encodePasswordToPBKDF2(exporterPassword, salt, 101, 64)
  148. cI.Password = hashed
  149. cI.Iterations = 101
  150. cI.Salt = base64.StdEncoding.EncodeToString([]byte(salt))
  151. dynConfig.Clients[i] = cI
  152. }
  153. }
  154. if servercfg.Is_EE && !exporter {
  155. exporterPassword := servercfg.GetLicenseKey()
  156. salt := logic.RandomString(12)
  157. hashed := encodePasswordToPBKDF2(exporterPassword, salt, 101, 64)
  158. exporterMQClient.Password = hashed
  159. exporterMQClient.Iterations = 101
  160. exporterMQClient.Salt = base64.StdEncoding.EncodeToString([]byte(salt))
  161. dynConfig.Clients = append(dynConfig.Clients, exporterMQClient)
  162. }
  163. data, err := json.MarshalIndent(dynConfig, "", " ")
  164. if err != nil {
  165. return err
  166. }
  167. return os.WriteFile(path, data, 0755)
  168. }
  169. // publishes the message to dynamic security topic
  170. func publishEventToDynSecTopic(payload MqDynsecPayload) error {
  171. d, err := json.Marshal(payload)
  172. if err != nil {
  173. return err
  174. }
  175. var connecterr error
  176. if token := mqAdminClient.Publish(dynamicSecPubTopic, 2, false, d); !token.WaitTimeout(MQ_TIMEOUT*time.Second) || token.Error() != nil {
  177. if token.Error() == nil {
  178. connecterr = errors.New("connect timeout")
  179. } else {
  180. connecterr = token.Error()
  181. }
  182. }
  183. return connecterr
  184. }
  185. // watchDynSecTopic - message handler for dynamic security responses
  186. func watchDynSecTopic(client mqtt.Client, msg mqtt.Message) {
  187. logger.Log(1, fmt.Sprintf("----->WatchDynSecTopic Message: %+v", string(msg.Payload())))
  188. }