2022-01-29 04:33:30 +08:00
|
|
|
package mq
|
|
|
|
|
|
|
|
import (
|
2022-02-07 04:02:05 +08:00
|
|
|
"fmt"
|
|
|
|
|
2022-01-29 04:33:30 +08:00
|
|
|
"github.com/gravitl/netmaker/logic"
|
2022-01-29 22:14:18 +08:00
|
|
|
"github.com/gravitl/netmaker/models"
|
2022-01-29 04:33:30 +08:00
|
|
|
"github.com/gravitl/netmaker/netclient/ncutils"
|
|
|
|
)
|
|
|
|
|
2022-01-30 04:02:37 +08:00
|
|
|
func decryptMsg(node *models.Node, msg []byte) ([]byte, error) {
|
2022-02-07 04:02:05 +08:00
|
|
|
if len(msg) <= 24 { // make sure message is of appropriate length
|
|
|
|
return nil, fmt.Errorf("recieved invalid message from broker %s", string(msg))
|
|
|
|
}
|
|
|
|
|
2022-01-30 04:02:37 +08:00
|
|
|
trafficKey, trafficErr := logic.RetrievePrivateTrafficKey() // get server private key
|
2022-01-29 04:33:30 +08:00
|
|
|
if trafficErr != nil {
|
|
|
|
return nil, trafficErr
|
|
|
|
}
|
2022-01-30 04:02:37 +08:00
|
|
|
serverPrivTKey, err := ncutils.ConvertBytesToKey(trafficKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
nodePubTKey, err := ncutils.ConvertBytesToKey(node.TrafficKeys.Mine)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return ncutils.BoxDecrypt(msg, nodePubTKey, serverPrivTKey)
|
2022-01-29 04:33:30 +08:00
|
|
|
}
|
|
|
|
|
2022-01-30 04:02:37 +08:00
|
|
|
func encryptMsg(node *models.Node, msg []byte) ([]byte, error) {
|
|
|
|
// fetch server public key to be certain hasn't changed in transit
|
|
|
|
trafficKey, trafficErr := logic.RetrievePrivateTrafficKey()
|
|
|
|
if trafficErr != nil {
|
|
|
|
return nil, trafficErr
|
|
|
|
}
|
|
|
|
|
|
|
|
serverPrivKey, err := ncutils.ConvertBytesToKey(trafficKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2022-01-29 04:33:30 +08:00
|
|
|
}
|
2022-01-30 04:02:37 +08:00
|
|
|
|
|
|
|
nodePubKey, err := ncutils.ConvertBytesToKey(node.TrafficKeys.Mine)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return ncutils.BoxEncrypt(msg, nodePubKey, serverPrivKey)
|
2022-01-29 04:33:30 +08:00
|
|
|
}
|
|
|
|
|
2022-01-29 22:14:18 +08:00
|
|
|
func publish(node *models.Node, dest string, msg []byte) error {
|
2022-02-09 08:13:58 +08:00
|
|
|
client := SetupMQTT(true)
|
2022-01-29 04:33:30 +08:00
|
|
|
defer client.Disconnect(250)
|
2022-01-30 04:02:37 +08:00
|
|
|
encrypted, encryptErr := encryptMsg(node, msg)
|
2022-01-29 04:33:30 +08:00
|
|
|
if encryptErr != nil {
|
|
|
|
return encryptErr
|
|
|
|
}
|
2022-02-05 07:00:17 +08:00
|
|
|
if token := client.Publish(dest, 0, true, encrypted); token.Wait() && token.Error() != nil {
|
2022-01-29 04:33:30 +08:00
|
|
|
return token.Error()
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|