-
-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathclient.py
More file actions
561 lines (471 loc) · 17.8 KB
/
Copy pathclient.py
File metadata and controls
561 lines (471 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
"""Client to communicate with Sagemcom F@st internal APIs."""
from __future__ import annotations
import hashlib
import json
import math
import random
import urllib.parse
from collections.abc import Mapping
from types import TracebackType
from typing import Any
import backoff
import humps
from aiohttp import (
ClientConnectorError,
ClientOSError,
ClientSession,
ClientTimeout,
ServerDisconnectedError,
TCPConnector,
)
from .action_error_exception_handler import ActionErrorHandler
from .const import (
API_ENDPOINT,
DEFAULT_TIMEOUT,
DEFAULT_USER_AGENT,
UINT_MAX,
XMO_INVALID_SESSION_ERR,
XMO_REQUEST_ACTION_ERR,
XMO_REQUEST_NO_ERR,
)
from .enums import EncryptionMethod
from .exceptions import (
AuthenticationException,
BadRequestException,
InvalidSessionException,
LoginRetryErrorException,
LoginTimeoutException,
UnauthorizedException,
UnknownException,
UnknownPathException,
UnsupportedHostException,
)
from .models import Device, DeviceInfo, PortMapping
async def retry_login(invocation: Mapping[str, Any]) -> None:
"""Retry login via backoff if an exception occurs."""
await invocation["args"][0].login()
# pylint: disable=too-many-instance-attributes
class SagemcomClient:
"""Client to communicate with the Sagemcom API."""
_auth_key: str | None
# pylint: disable=too-many-arguments
def __init__(
self,
host: str,
username: str,
password: str,
authentication_method: EncryptionMethod | None = None,
session: ClientSession | None = None,
ssl: bool | None = False,
verify_ssl: bool | None = True,
):
"""Create a SagemCom client.
:param host: the host of your Sagemcom router
:param username: the username for your Sagemcom router
:param password: the password for your Sagemcom router
:param authentication_method: the auth method of your Sagemcom router
:param session: use a custom session, for example to configure the timeout
"""
self.host = host
self.username = username
self.authentication_method = authentication_method
self.password = password
self._current_nonce = None
self._password_hash = self.__generate_hash(password)
self.protocol = "https" if ssl else "http"
self._server_nonce = ""
self._session_id = 0
self._request_id = -1
self.session = (
session
if session
else ClientSession(
headers={"User-Agent": f"{DEFAULT_USER_AGENT}"},
timeout=ClientTimeout(DEFAULT_TIMEOUT),
connector=TCPConnector(verify_ssl=verify_ssl if verify_ssl is not None else True),
)
)
async def __aenter__(self) -> SagemcomClient:
"""TODO."""
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None:
"""Close session on exit."""
await self.close()
async def close(self) -> None:
"""Close the websession."""
await self.session.close()
def __generate_nonce(self, upper_limit=500000):
"""Generate pseudo random number (nonce) to avoid replay attacks."""
self._current_nonce = math.floor(random.randrange(0, upper_limit)) # noqa: S311 — router protocol requires this nonce
def __generate_request_id(self):
"""Generate sequential request ID."""
self._request_id += 1
def __generate_md5_nonce_hash(self):
"""Build MD5 with nonce hash token. UINT_MAX is hardcoded in the firmware."""
def md5(input_string):
return hashlib.md5(input_string.encode()).hexdigest() # noqa: S324 — MD5 required by router firmware
n = self.__generate_nonce(UINT_MAX) if self._current_nonce is None else self._current_nonce
f = 0
l_nonce = ""
ha1 = md5(self.username + ":" + l_nonce + ":" + md5(self.password))
return md5(ha1 + ":" + str(f) + ":" + str(n) + ":JSON:/cgi/json-req")
def __generate_hash(self, value, authentication_method=None):
"""Hash value with selected encryption method and return HEX value."""
auth_method = authentication_method or self.authentication_method
bytes_object = bytes(value, encoding="utf-8")
if auth_method == EncryptionMethod.MD5:
return hashlib.md5(bytes_object).hexdigest() # noqa: S324 — MD5 required by router firmware
if auth_method == EncryptionMethod.SHA512:
return hashlib.sha512(bytes_object).hexdigest()
if auth_method == EncryptionMethod.MD5_NONCE:
return self.__generate_md5_nonce_hash()
return value
def __get_credential_hash(self):
"""Build credential hash."""
return self.__generate_hash(self.username + ":" + self._server_nonce + ":" + self._password_hash)
def __generate_auth_key(self):
"""Build auth key."""
credential_hash = self.__get_credential_hash()
auth_string = f"{credential_hash}:{self._request_id}:{self._current_nonce}:JSON:{API_ENDPOINT}"
self._auth_key = self.__generate_hash(auth_string)
def __get_response_error(self, response):
"""Retrieve response error from result."""
try:
value = response["reply"]["error"]
except KeyError:
value = None
return value
def __get_response(self, response, index=0):
"""Retrieve response from result."""
try:
value = response["reply"]["actions"][index]["callbacks"][0]["parameters"]
except KeyError:
value = None
return value
def __get_response_value(self, response, index=0):
"""Retrieve response value from value."""
try:
value = self.__get_response(response, index)["value"]
except KeyError:
value = None
except IndexError:
value = None
# Rewrite result to snake_case
if value is not None:
value = humps.decamelize(value)
return value
@backoff.on_exception(
backoff.expo,
(ClientConnectorError, ClientOSError, ServerDisconnectedError),
max_tries=5,
)
# pylint: disable=too-many-branches
async def __post(self, url, data):
async with self.session.post(url, data=data) as response:
if response.status == 400:
result = await response.text()
raise BadRequestException(result)
if response.status == 404:
result = await response.text()
raise UnsupportedHostException(result)
if response.status != 200:
result = await response.text()
raise UnknownException(result)
result = await response.json()
error = self.__get_response_error(result)
# No errors
if error["description"] == XMO_REQUEST_NO_ERR or error["description"] == "Ok":
return result
if error["description"] == XMO_INVALID_SESSION_ERR:
self._session_id = 0
self._server_nonce = ""
self._request_id = -1
raise InvalidSessionException(error)
# Unknown error in one of the actions
if error["description"] == XMO_REQUEST_ACTION_ERR:
# leave this to the layer above as there may be multiple actions
pass
return result
async def __api_request_async(self, actions, priority=False):
"""Build request to the internal JSON-req API."""
self.__generate_request_id()
self.__generate_nonce()
self.__generate_auth_key()
api_host = f"{self.protocol}://{self.host}{API_ENDPOINT}"
payload = {
"request": {
"id": self._request_id,
"session-id": int(self._session_id),
"priority": priority,
"actions": actions,
"cnonce": self._current_nonce,
"auth-key": self._auth_key,
}
}
form_data = {"req": json.dumps(payload, separators=(",", ":"))}
try:
result = await self.__post(api_host, form_data)
return result
except (
ClientConnectorError,
ClientOSError,
ServerDisconnectedError,
) as exception:
raise ConnectionError(str(exception)) from exception
async def login(self):
"""Login to the SagemCom F@st router using a username and password."""
actions = {
"id": 0,
"method": "logIn",
"parameters": {
"user": self.username,
"persistent": True,
"session-options": {
"nss": [{"name": "gtw", "uri": "http://sagemcom.com/gateway-data"}],
"language": "ident",
"context-flags": {"get-content-name": True, "local-time": True},
"capability-depth": 2,
"capability-flags": {
"name": True,
"default-value": False,
"restriction": True,
"description": False,
},
"time-format": "ISO_8601",
"write-only-string": "_XMO_WRITE_ONLY_",
"undefined-write-only-string": "_XMO_UNDEFINED_WRITE_ONLY_",
},
},
}
try:
response = await self.__api_request_async([actions], True)
except TimeoutError as exception:
raise LoginTimeoutException(
"Login request timed-out. This could be caused by using the wrong encryption method, or using a (non) SSL connection."
) from exception
ActionErrorHandler.throw_if_error(response)
data = self.__get_response(response)
if data["id"] is not None and data["nonce"] is not None:
self._session_id = data["id"]
self._server_nonce = data["nonce"]
return True
raise UnauthorizedException(data)
async def logout(self):
"""Log out of the Sagemcom F@st device."""
actions = {"id": 0, "method": "logOut"}
response = await self.__api_request_async([actions], False)
ActionErrorHandler.throw_if_error(response)
self._session_id = -1
self._server_nonce = ""
self._request_id = -1
async def get_encryption_method(self):
"""Determine which encryption method to use for authentication and set it directly."""
for encryption_method in EncryptionMethod:
try:
self.authentication_method = encryption_method
self._password_hash = self.__generate_hash(self.password, encryption_method)
await self.login()
self._server_nonce = ""
self._session_id = 0
self._request_id = -1
return encryption_method
except (
LoginTimeoutException,
AuthenticationException,
LoginRetryErrorException,
):
pass
return None
@backoff.on_exception(
backoff.expo,
(
AuthenticationException,
LoginRetryErrorException,
LoginTimeoutException,
InvalidSessionException,
),
max_tries=1,
on_backoff=retry_login,
)
async def get_value_by_xpath(
self,
xpath: str,
options: dict | None = None,
suppress_action_errors: bool = False,
) -> Any:
"""Retrieve raw value from router using XPath.
:param xpath: path expression
:param options: optional options
"""
actions = {
"id": 0,
"method": "getValue",
"xpath": urllib.parse.quote(xpath, "/=[]'"),
"options": options if options else {},
}
response = await self.__api_request_async([actions], False)
ActionErrorHandler.throw_if_error(response, ignore_unknown_path=suppress_action_errors)
data = self.__get_response_value(response)
return data
@backoff.on_exception(
backoff.expo,
(
AuthenticationException,
LoginRetryErrorException,
LoginTimeoutException,
InvalidSessionException,
),
max_tries=1,
on_backoff=retry_login,
)
async def get_values_by_xpaths(
self,
xpaths,
options: dict | None = None,
suppress_action_errors: bool = False,
) -> dict:
"""Retrieve raw values from router using XPath.
:param xpaths: Dict of key to xpath expression
:param options: optional options
"""
actions = [
{
"id": i,
"method": "getValue",
"xpath": urllib.parse.quote(xpath, "/=[]'"),
"options": options if options else {},
}
for i, xpath in enumerate(xpaths.values())
]
response = await self.__api_request_async(actions, False)
if not suppress_action_errors:
ActionErrorHandler.throw_if_error(response)
values = [self.__get_response_value(response, i) for i in range(len(xpaths))]
else:
values = []
for i in range(len(xpaths)):
ActionErrorHandler.throw_if_error_at(response, i, ignore_unknown_path=True)
values.append(self.__get_response_value(response, i))
data = dict(zip(xpaths.keys(), values, strict=True))
return data
@backoff.on_exception(
backoff.expo,
(
AuthenticationException,
LoginRetryErrorException,
LoginTimeoutException,
InvalidSessionException,
),
max_tries=1,
on_backoff=retry_login,
)
async def set_value_by_xpath(self, xpath: str, value: str, options: dict | None = None) -> dict:
"""Retrieve raw value from router using XPath.
:param xpath: path expression
:param value: value
:param options: optional options
"""
actions = {
"id": 0,
"method": "setValue",
"xpath": urllib.parse.quote(xpath, "/=[]'"),
"parameters": {"value": str(value)},
"options": options if options else {},
}
response = await self.__api_request_async([actions], False)
ActionErrorHandler.throw_if_error(response)
return response
@backoff.on_exception(
backoff.expo,
(
AuthenticationException,
LoginRetryErrorException,
LoginTimeoutException,
InvalidSessionException,
),
max_tries=1,
on_backoff=retry_login,
)
async def get_device_info(self) -> DeviceInfo:
"""Retrieve information about Sagemcom F@st device."""
try:
data = await self.get_value_by_xpath("Device/DeviceInfo")
return DeviceInfo(**data["device_info"])
except UnknownPathException:
data = await self.get_values_by_xpaths(
{
"mac_address": "Device/DeviceInfo/MACAddress",
"model_name": "Device/DeviceInfo/ModelNumber",
"model_number": "Device/DeviceInfo/ProductClass",
"product_class": "Device/DeviceInfo/ProductClass",
"serial_number": "Device/DeviceInfo/SerialNumber",
"software_version": "Device/DeviceInfo/SoftwareVersion",
},
# missing values returned as None when action errors are suppressed
suppress_action_errors=True,
)
data["manufacturer"] = "Sagemcom"
return DeviceInfo(**data)
@backoff.on_exception(
backoff.expo,
(
AuthenticationException,
LoginRetryErrorException,
LoginTimeoutException,
InvalidSessionException,
),
max_tries=1,
on_backoff=retry_login,
)
async def get_hosts(self, only_active: bool | None = False) -> list[Device]:
"""Retrieve hosts connected to Sagemcom F@st device."""
data = await self.get_value_by_xpath("Device/Hosts/Hosts", options={"capability-flags": {"interface": True}})
devices = [Device(**d) for d in data]
if only_active:
active_devices = [d for d in devices if d.active is True]
return active_devices
return devices
@backoff.on_exception(
backoff.expo,
(
AuthenticationException,
LoginRetryErrorException,
LoginTimeoutException,
InvalidSessionException,
),
max_tries=1,
on_backoff=retry_login,
)
async def get_port_mappings(self) -> list[PortMapping]:
"""Retrieve configured Port Mappings on Sagemcom F@st device."""
data = await self.get_value_by_xpath("Device/NAT/PortMappings")
port_mappings = [PortMapping(**p) for p in data]
return port_mappings
@backoff.on_exception(
backoff.expo,
(
AuthenticationException,
LoginRetryErrorException,
LoginTimeoutException,
InvalidSessionException,
),
max_tries=1,
on_backoff=retry_login,
)
async def reboot(self):
"""Reboot Sagemcom F@st device."""
action = {
"id": 0,
"method": "reboot",
"xpath": "Device",
"parameters": {"source": "GUI"},
}
response = await self.__api_request_async([action], False)
ActionErrorHandler.throw_if_error(response)
data = self.__get_response_value(response)
return data