|
| 1 | +package auth |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/hmac" |
| 5 | + "crypto/sha256" |
| 6 | + "crypto/tls" |
| 7 | + "crypto/x509" |
| 8 | + "encoding/base64" |
| 9 | + "fmt" |
| 10 | + "net/url" |
| 11 | + "strings" |
| 12 | + "time" |
| 13 | + |
| 14 | + mqtt "github.com/eclipse/paho.mqtt.golang" |
| 15 | + "github.com/pkg/errors" |
| 16 | + |
| 17 | + "github.com/brocaar/lora-gateway-bridge/internal/config" |
| 18 | +) |
| 19 | + |
| 20 | +// See: |
| 21 | +// https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-mqtt-support#tlsssl-configuration |
| 22 | +// https://github.com/Azure/azure-iot-sdk-c/blob/master/certs/certs.c |
| 23 | +const digiCertBaltimoreRootCA = ` |
| 24 | +-----BEGIN CERTIFICATE----- |
| 25 | +MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ |
| 26 | +RTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD |
| 27 | +VQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX |
| 28 | +DTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y |
| 29 | +ZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy |
| 30 | +VHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr |
| 31 | +mD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr |
| 32 | +IZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK |
| 33 | +mpYcqWe4PwzV9/lSEy/CG9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSu |
| 34 | +XmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9XbIGevOF6uvUA65ehD5f/xXtabz5OTZy |
| 35 | +dc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjprl3RjM71oGDHweI12v/ye |
| 36 | +jl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoIVDaGezq1 |
| 37 | +BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3 |
| 38 | +DQEBBQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT92 |
| 39 | +9hkTI7gQCvlYpNRhcL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3Wgx |
| 40 | +jkzSswF07r51XgdIGn9w/xZchMB5hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0 |
| 41 | +Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsaY71k5h+3zvDyny67G7fyUIhz |
| 42 | +ksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9HRCwBXbsdtTLS |
| 43 | +R9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp |
| 44 | +-----END CERTIFICATE----- |
| 45 | +` |
| 46 | + |
| 47 | +// AzureIoTHubAuthentication implements the Azure IoT Hub authentication. |
| 48 | +type AzureIoTHubAuthentication struct { |
| 49 | + clientID string |
| 50 | + username string |
| 51 | + deviceKey []byte |
| 52 | + hostname string |
| 53 | + sasTokenExpiration time.Duration |
| 54 | + |
| 55 | + tlsConfig *tls.Config |
| 56 | +} |
| 57 | + |
| 58 | +// NewAzureIoTHubAuthentication creates an AzureIoTHubAuthentication. |
| 59 | +func NewAzureIoTHubAuthentication(c config.Config) (Authentication, error) { |
| 60 | + conf := c.Integration.MQTT.Auth.AzureIoTHub |
| 61 | + |
| 62 | + certpool := x509.NewCertPool() |
| 63 | + if !certpool.AppendCertsFromPEM([]byte(digiCertBaltimoreRootCA)) { |
| 64 | + return nil, errors.New("append ca cert from pem error") |
| 65 | + } |
| 66 | + |
| 67 | + if conf.DeviceConnectionString != "" { |
| 68 | + kvMap, err := parseConnectionString(conf.DeviceConnectionString) |
| 69 | + if err != nil { |
| 70 | + return nil, errors.Wrap(err, "parse connection string error") |
| 71 | + } |
| 72 | + |
| 73 | + for k, v := range kvMap { |
| 74 | + switch k { |
| 75 | + case "HostName": |
| 76 | + conf.Hostname = v |
| 77 | + case "DeviceId": |
| 78 | + conf.DeviceID = v |
| 79 | + case "SharedAccessKey": |
| 80 | + conf.DeviceKey = v |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + username := fmt.Sprintf("%s/%s", |
| 86 | + conf.Hostname, |
| 87 | + conf.DeviceID, |
| 88 | + ) |
| 89 | + |
| 90 | + deviceKeyB, err := base64.StdEncoding.DecodeString(conf.DeviceKey) |
| 91 | + if err != nil { |
| 92 | + return nil, errors.Wrap(err, "decode device key error") |
| 93 | + } |
| 94 | + |
| 95 | + return &AzureIoTHubAuthentication{ |
| 96 | + clientID: conf.DeviceID, |
| 97 | + username: username, |
| 98 | + deviceKey: deviceKeyB, |
| 99 | + hostname: conf.Hostname, |
| 100 | + tlsConfig: &tls.Config{ |
| 101 | + RootCAs: certpool, |
| 102 | + }, |
| 103 | + }, nil |
| 104 | +} |
| 105 | + |
| 106 | +// Init applies the initial configuration. |
| 107 | +func (a *AzureIoTHubAuthentication) Init(opts *mqtt.ClientOptions) error { |
| 108 | + broker := fmt.Sprintf("ssl://%s:8883", a.hostname) |
| 109 | + opts.AddBroker(broker) |
| 110 | + opts.SetClientID(a.clientID) |
| 111 | + opts.SetUsername(a.username) |
| 112 | + |
| 113 | + return nil |
| 114 | +} |
| 115 | + |
| 116 | +// Update updates the authentication options. |
| 117 | +func (a *AzureIoTHubAuthentication) Update(opts *mqtt.ClientOptions) error { |
| 118 | + resourceURI := fmt.Sprintf("%s/devices/%s", |
| 119 | + a.hostname, |
| 120 | + a.clientID, |
| 121 | + ) |
| 122 | + token, err := createSASToken(resourceURI, a.deviceKey, a.sasTokenExpiration) |
| 123 | + if err != nil { |
| 124 | + return errors.Wrap(err, "create SAS token error") |
| 125 | + } |
| 126 | + |
| 127 | + opts.SetPassword(token) |
| 128 | + |
| 129 | + return nil |
| 130 | +} |
| 131 | + |
| 132 | +// ReconnectAfter returns a time.Duration after which the MQTT client must re-connect. |
| 133 | +// Note: return 0 to disable the periodical re-connect feature. |
| 134 | +func (a *AzureIoTHubAuthentication) ReconnectAfter() time.Duration { |
| 135 | + return a.sasTokenExpiration |
| 136 | +} |
| 137 | + |
| 138 | +func createSASToken(uri string, deviceKey []byte, expiration time.Duration) (string, error) { |
| 139 | + encoded := url.QueryEscape(uri) |
| 140 | + exp := time.Now().Add(expiration).Unix() |
| 141 | + |
| 142 | + signature := fmt.Sprintf("%s\n%d", encoded, exp) |
| 143 | + |
| 144 | + mac := hmac.New(sha256.New, deviceKey) |
| 145 | + mac.Write([]byte(signature)) |
| 146 | + hash := url.QueryEscape(base64.StdEncoding.EncodeToString(mac.Sum(nil))) |
| 147 | + |
| 148 | + // IoT Hub SAS Token only needs `sr`, `sig` and `se` unlike other Azure services |
| 149 | + token := fmt.Sprintf("SharedAccessSignature sr=%s&sig=%s&se=%d", |
| 150 | + encoded, |
| 151 | + hash, |
| 152 | + exp, |
| 153 | + ) |
| 154 | + |
| 155 | + return token, nil |
| 156 | +} |
| 157 | + |
| 158 | +func parseConnectionString(str string) (map[string]string, error) { |
| 159 | + out := make(map[string]string) |
| 160 | + pairs := strings.Split(str, ";") |
| 161 | + for _, pair := range pairs { |
| 162 | + kv := strings.SplitN(pair, "=", 2) |
| 163 | + if len(kv) != 2 { |
| 164 | + return nil, fmt.Errorf("expected two items in: %+v", kv) |
| 165 | + } |
| 166 | + |
| 167 | + out[kv[0]] = kv[1] |
| 168 | + } |
| 169 | + |
| 170 | + return out, nil |
| 171 | +} |
0 commit comments