Skip to content

Commit 652c207

Browse files
committed
make SAS Key more specific
1 parent 27fef1d commit 652c207

16 files changed

+47
-71
lines changed

README.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ To use Azure IoT Central, you will need to create an Azure IoT Central app, crea
203203
204204
from adafruit_azureiot import IoTCentralDevice
205205
206-
device = IoTCentralDevice(wifi, secrets["id_scope"], secrets["device_id"], secrets["sas_key"])
206+
device = IoTCentralDevice(wifi, secrets["id_scope"], secrets["device_id"], secrets["device_device_sas_key"])
207207
device.connect()
208208
209209
Once the device is connected, you will regularly need to run a ``loop`` to poll for messages from the cloud.

adafruit_azureiot/device_registration.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -49,19 +49,19 @@ def __init__(
4949
iface,
5050
id_scope: str,
5151
device_id: str,
52-
key: str,
52+
device_sas_key: str,
5353
logger: Logger = None,
5454
):
5555
"""Creates an instance of the device registration service
5656
:param socket: The network socket
5757
:param str id_scope: The ID scope of the device to register
5858
:param str device_id: The device ID of the device to register
59-
:param str key: The primary or secondary key of the device to register
59+
:param str device_sas_key: The primary or secondary key of the device to register
6060
:param adafruit_logging.Logger logger: The logger to use to log messages
6161
"""
6262
self._id_scope = id_scope
6363
self._device_id = device_id
64-
self._key = key
64+
self._device_sas_key = device_sas_key
6565
self._logger = logger if logger is not None else logging.getLogger("log")
6666

6767
self._mqtt = None
@@ -76,7 +76,7 @@ def __init__(
7676
# pylint: disable=C0103
7777
def _on_connect(self, client, userdata, _, rc) -> None:
7878
self._logger.info(
79-
f"- device_registration :: _on_connect :: rc = {str(rc)}, userdata = {str(userdata)}"
79+
f"- device_registration :: _on_connect :: rc = {rc}, userdata = {userdata}"
8080
)
8181

8282
self._auth_response_received = True
@@ -110,7 +110,7 @@ def _connect_to_mqtt(self) -> None:
110110
self._mqtt.loop()
111111

112112
self._logger.info(
113-
f" - device_registration :: connect :: on_connect must be fired. Connected ? {str(self._mqtt.is_connected())}"
113+
f" - device_registration :: connect :: on_connect must be fired. Connected ? {self._mqtt.is_connected()}"
114114
)
115115

116116
if not self._mqtt.is_connected():
@@ -132,7 +132,7 @@ def _start_registration(self) -> None:
132132

133133
while self._operation_id is None and retry < 10:
134134
time.sleep(1)
135-
retry = retry + 1
135+
retry += 1
136136
self._mqtt.loop()
137137

138138
if self._operation_id is None:
@@ -151,7 +151,7 @@ def _wait_for_operation(self) -> None:
151151

152152
while self._hostname is None and retry < 10:
153153
time.sleep(1)
154-
retry = retry + 1
154+
retry += 1
155155
self._mqtt.loop()
156156

157157
if self._hostname is None:
@@ -175,10 +175,10 @@ def register_device(self, expiry: int) -> str:
175175
# pylint: disable=C0103
176176
sr = self._id_scope + "%2Fregistrations%2F" + self._device_id
177177
sig_no_encode = compute_derived_symmetric_key(
178-
self._key, sr + "\n" + str(expiry)
178+
self._device_sas_key, sr + "\n" + str(expiry)
179179
)
180180
sig_encoded = quote(sig_no_encode, "~()*!.'")
181-
auth_string = f"SharedAccessSignature sr={sr}&sig={sig_encoded}&se={str(expiry)}&skn=registration"
181+
auth_string = f"SharedAccessSignature sr={sr}&sig={sig_encoded}&se={expiry}&skn=registration"
182182

183183
MQTT.set_socket(self._socket, self._iface)
184184

adafruit_azureiot/hmac.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -331,12 +331,11 @@ def sha_update(sha_info: dict, buffer: Union[bytes, bytearray]) -> None:
331331
buffer_idx += i
332332

333333
sha_info["local"] += i
334-
if sha_info["local"] == SHA_BLOCKSIZE:
335-
sha_transform(sha_info)
336-
sha_info["local"] = 0
337-
else:
334+
if sha_info["local"] != SHA_BLOCKSIZE:
338335
return
339336

337+
sha_transform(sha_info)
338+
sha_info["local"] = 0
340339
while count >= SHA_BLOCKSIZE:
341340
# copy buffer
342341
sha_info["data"] = list(buffer[buffer_idx : buffer_idx + SHA_BLOCKSIZE])
@@ -351,9 +350,7 @@ def sha_update(sha_info: dict, buffer: Union[bytes, bytearray]) -> None:
351350

352351

353352
def getbuf(s: Union[str, bytes, bytearray]) -> Union[bytes, bytearray]:
354-
if isinstance(s, str):
355-
return s.encode("ascii")
356-
return bytes(s)
353+
return s.encode("ascii") if isinstance(s, str) else bytes(s)
357354

358355

359356
def sha_final(sha_info: dict) -> bytes:

adafruit_azureiot/iot_mqtt.py

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -98,17 +98,16 @@ def _gen_sas_token(self) -> str:
9898
token_expiry = int(time.time() + self._token_expires)
9999
uri = self._hostname + "%2Fdevices%2F" + self._device_id
100100
signed_hmac_sha256 = compute_derived_symmetric_key(
101-
self._key, uri + "\n" + str(token_expiry)
101+
self._device_sas_key, uri + "\n" + str(token_expiry)
102102
)
103103
signature = quote(signed_hmac_sha256, "~()*!.'")
104104
if signature.endswith(
105105
"\n"
106106
): # somewhere along the crypto chain a newline is inserted
107107
signature = signature[:-1]
108-
token = "SharedAccessSignature sr={}&sig={}&se={}".format(
108+
return "SharedAccessSignature sr={}&sig={}&se={}".format(
109109
uri, signature, token_expiry
110110
)
111-
return token
112111

113112
def _create_mqtt_client(self) -> None:
114113
MQTT.set_socket(self._socket, self._iface)
@@ -205,11 +204,7 @@ def _handle_device_twin_update(self, client, topic: str, msg: str) -> None:
205204

206205
is_patch = "desired" not in twin
207206

208-
if is_patch:
209-
desired = twin
210-
else:
211-
desired = twin["desired"]
212-
207+
desired = twin if is_patch else twin["desired"]
213208
if "$version" in desired:
214209
desired_version = desired["$version"]
215210
desired.pop("$version")
@@ -295,18 +290,18 @@ def _send_common(self, topic: str, data) -> None:
295290
break
296291
except RuntimeError as runtime_error:
297292
self._logger.info(
298-
"Could not send data, retrying after 0.5 seconds: "
299-
+ str(runtime_error)
293+
(
294+
"Could not send data, retrying after 0.5 seconds: "
295+
+ str(runtime_error)
296+
)
300297
)
301-
retry = retry + 1
302298

299+
retry += 1
303300
if retry >= 10:
304301
self._logger.error("Failed to send data")
305302
raise
306-
307303
time.sleep(0.5)
308304
continue
309-
310305
gc.collect()
311306

312307
def _get_device_settings(self) -> None:
@@ -322,7 +317,7 @@ def __init__(
322317
iface,
323318
hostname: str,
324319
device_id: str,
325-
key: str,
320+
device_sas_key: str,
326321
token_expires: int = 21600,
327322
logger: logging = None,
328323
):
@@ -332,7 +327,7 @@ def __init__(
332327
:param iface: The network interface to communicate over
333328
:param str hostname: The hostname of the MQTT broker to connect to, get this by registering the device
334329
:param str device_id: The device ID of the device to register
335-
:param str key: The primary or secondary key of the device to register
330+
:param str device_sas_key: The primary or secondary key of the device to register
336331
:param int token_expires: The number of seconds till the token expires, defaults to 6 hours
337332
:param adafruit_logging logger: The logger
338333
"""
@@ -343,7 +338,7 @@ def __init__(
343338
self._mqtts = None
344339
self._device_id = device_id
345340
self._hostname = hostname
346-
self._key = key
341+
self._device_sas_key = device_sas_key
347342
self._token_expires = token_expires
348343
self._username = "{}/{}/?api-version={}".format(
349344
self._hostname, device_id, constants.IOTC_API_VERSION
@@ -458,12 +453,12 @@ def send_device_to_cloud_message(
458453

459454
if system_properties is not None:
460455
firstProp = True
461-
for prop in system_properties:
456+
for prop, value in system_properties.items():
462457
if not firstProp:
463458
topic += "&"
464459
else:
465460
firstProp = False
466-
topic += prop + "=" + str(system_properties[prop])
461+
topic += prop + "=" + str(value)
467462

468463
# Convert message to a string
469464
if isinstance(message, dict):

adafruit_azureiot/iotcentral_device.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def __init__(
8686
iface,
8787
id_scope: str,
8888
device_id: str,
89-
key: str,
89+
device_sas_key: str,
9090
token_expires: int = 21600,
9191
logger: logging = None,
9292
):
@@ -95,15 +95,15 @@ def __init__(
9595
:param iface: The network interface
9696
:param str id_scope: The ID Scope of the device in IoT Central
9797
:param str device_id: The device ID of the device in IoT Central
98-
:param str key: The primary or secondary key of the device in IoT Central
98+
:param str device_sas_key: The primary or secondary key of the device in IoT Central
9999
:param int token_expires: The number of seconds till the token expires, defaults to 6 hours
100100
:param adafruit_logging logger: The logger
101101
"""
102102
self._socket = socket
103103
self._iface = iface
104104
self._id_scope = id_scope
105105
self._device_id = device_id
106-
self._key = key
106+
self._device_sas_key = device_sas_key
107107
self._token_expires = token_expires
108108
self._logger = logger if logger is not None else logging.getLogger("log")
109109
self._device_registration = None
@@ -140,7 +140,7 @@ def connect(self) -> None:
140140
self._iface,
141141
self._id_scope,
142142
self._device_id,
143-
self._key,
143+
self._device_sas_key,
144144
self._logger,
145145
)
146146

@@ -152,14 +152,14 @@ def connect(self) -> None:
152152
self._iface,
153153
hostname,
154154
self._device_id,
155-
self._key,
155+
self._device_sas_key,
156156
self._token_expires,
157157
self._logger,
158158
)
159159

160160
self._logger.debug("Hostname: " + hostname)
161161
self._logger.debug("Device Id: " + self._device_id)
162-
self._logger.debug("Shared Access Key: " + self._key)
162+
self._logger.debug("Shared Access Key: " + self._device_sas_key)
163163

164164
self._mqtt.connect()
165165
self._mqtt.subscribe_to_twins()
@@ -185,10 +185,7 @@ def is_connected(self) -> bool:
185185
:returns: True if there is an open connection, False if not
186186
:rtype: bool
187187
"""
188-
if self._mqtt is not None:
189-
return self._mqtt.is_connected()
190-
191-
return False
188+
return self._mqtt.is_connected() if self._mqtt is not None else False
192189

193190
def loop(self) -> None:
194191
"""Listens for MQTT messages

adafruit_azureiot/iothub_device.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -336,10 +336,7 @@ def is_connected(self) -> bool:
336336
:returns: True if there is an open connection, False if not
337337
:rtype: bool
338338
"""
339-
if self._mqtt is not None:
340-
return self._mqtt.is_connected()
341-
342-
return False
339+
return self._mqtt.is_connected() if self._mqtt is not None else False
343340

344341
def send_device_to_cloud_message(
345342
self, message: Union[str, dict], system_properties: dict = None

adafruit_azureiot/quote.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def quote(bytes_val: bytes, safe: Union[str, bytes, bytearray] = "/") -> str:
3737
# Normalize 'safe' by converting to bytes and removing non-ASCII chars
3838
safe = safe.encode("ascii", "ignore")
3939
else:
40-
safe = bytes([char for char in safe if char < 128])
40+
safe = bytes(char for char in safe if char < 128)
4141
if not bytes_val.rstrip(_ALWAYS_SAFE_BYTES + safe):
4242
return bytes_val.decode()
4343
try:

examples/ esp32spi /azureiot_central_commands.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@
9999

100100
# Create an IoT Hub device client and connect
101101
device = IoTCentralDevice(
102-
socket, esp, secrets["id_scope"], secrets["device_id"], secrets["sas_key"]
102+
socket, esp, secrets["id_scope"], secrets["device_id"], secrets["device_sas_key"]
103103
)
104104

105105
# Subscribe to commands

examples/ esp32spi /azureiot_central_notconnected.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@
103103

104104
# Create an IoT Hub device client and connect
105105
device = IoTCentralDevice(
106-
socket, esp, secrets["id_scope"], secrets["device_id"], secrets["sas_key"]
106+
socket, esp, secrets["id_scope"], secrets["device_id"], secrets["device_sas_key"]
107107
)
108108

109109
# don't connect

examples/ esp32spi /azureiot_central_properties.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@
9696

9797
# Create an IoT Hub device client and connect
9898
device = IoTCentralDevice(
99-
socket, esp, secrets["id_scope"], secrets["device_id"], secrets["sas_key"]
99+
socket, esp, secrets["id_scope"], secrets["device_id"], secrets["device_sas_key"]
100100
)
101101

102102
# Subscribe to property changes
@@ -133,16 +133,14 @@ def property_changed(property_name, property_value, version):
133133
device.send_property("Desired_Temperature", random.randint(0, 50))
134134
message_counter = 0
135135
else:
136-
message_counter = message_counter + 1
136+
message_counter += 1
137137

138138
# Poll every second for messages from the cloud
139139
device.loop()
140140
except (ValueError, RuntimeError) as e:
141141
print("Connection error, reconnecting\n", str(e))
142-
# If we lose connectivity, reset the wifi and reconnect
143142
wifi.reset()
144143
wifi.connect()
145144
device.reconnect()
146145
continue
147-
148146
time.sleep(1)

examples/ esp32spi /azureiot_central_simpletest.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@
9797

9898
# Create an IoT Hub device client and connect
9999
device = IoTCentralDevice(
100-
socket, esp, secrets["id_scope"], secrets["device_id"], secrets["sas_key"]
100+
socket, esp, secrets["id_scope"], secrets["device_id"], secrets["device_sas_key"]
101101
)
102102

103103
print("Connecting to Azure IoT Central...")
@@ -118,7 +118,7 @@
118118
device.send_telemetry(json.dumps(message))
119119
message_counter = 0
120120
else:
121-
message_counter = message_counter + 1
121+
message_counter += 1
122122

123123
# Poll every second for messages from the cloud
124124
device.loop()

examples/ esp32spi /azureiot_hub_messages.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,16 +122,14 @@ def cloud_to_device_message_received(body: str, properties: dict):
122122
device.send_device_to_cloud_message(json.dumps(message))
123123
message_counter = 0
124124
else:
125-
message_counter = message_counter + 1
125+
message_counter += 1
126126

127127
# Poll every second for messages from the cloud
128128
device.loop()
129129
except (ValueError, RuntimeError) as e:
130130
print("Connection error, reconnecting\n", str(e))
131-
# If we lose connectivity, reset the wifi and reconnect
132131
wifi.reset()
133132
wifi.connect()
134133
device.reconnect()
135134
continue
136-
137135
time.sleep(1)

examples/ esp32spi /azureiot_hub_simpletest.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,16 +112,14 @@
112112
device.send_device_to_cloud_message(json.dumps(message))
113113
message_counter = 0
114114
else:
115-
message_counter = message_counter + 1
115+
message_counter += 1
116116

117117
# Poll every second for messages from the cloud
118118
device.loop()
119119
except (ValueError, RuntimeError) as e:
120120
print("Connection error, reconnecting\n", str(e))
121-
# If we lose connectivity, reset the wifi and reconnect
122121
wifi.reset()
123122
wifi.connect()
124123
device.reconnect()
125124
continue
126-
127125
time.sleep(1)

0 commit comments

Comments
 (0)