dynsec.go 5.9 KB

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