Move encrypt and decrypt routines into tplink_utils.
[python_utils.git] / smart_home / tplink_utils.py
1 #!/usr/bin/env python3
2
3 """Wrapper functions for dealing with TPLink devices.  Based on code
4 written by Lubomir Stroetmann and Copyright 2016 softScheck GmbH which
5 was covered by the Apache 2.0 license:
6
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
10
11      http://www.apache.org/licenses/LICENSE-2.0
12
13 Modifications by Scott Gasch Copyright 2020-2022 also released under
14 the Apache 2.0 license as required by the license (see above).
15
16 Unless required by applicable law or agreed to in writing, software
17 distributed under the License is distributed on an "AS IS" BASIS,
18 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 See the License for the specific language governing permissions and
20 limitations under the License.
21
22 """
23
24 import json
25 import logging
26 import os
27 import re
28 import subprocess
29 import sys
30 from struct import pack
31 from typing import Dict, Optional
32
33 import logging_utils
34 from decorator_utils import timeout
35
36 logger = logging.getLogger(__name__)
37
38
39 @timeout(10.0, use_signals=False, error_message="Timed out waiting for tplink.py")
40 def tplink_command(command: str) -> bool:
41     result = os.system(command)
42     signal = result & 0xFF
43     if signal != 0:
44         msg = f'{command} died with signal {signal}'
45         logger.warning(msg)
46         logging_utils.hlog(msg)
47         return False
48     else:
49         exit_value = result >> 8
50         if exit_value != 0:
51             msg = f'{command} failed, exited {exit_value}'
52             logger.warning(msg)
53             logging_utils.hlog(msg)
54             return False
55     logger.debug('%s succeeded.', command)
56     return True
57
58
59 @timeout(10.0, use_signals=False, error_message="Timed out waiting for tplink.py")
60 def tplink_get_info(cmd: str) -> Optional[Dict]:
61     logger.debug('Getting tplink device status via "%s"', cmd)
62     try:
63         out = subprocess.getoutput(cmd)
64         logger.debug('RAW OUT> %s', out)
65         out = re.sub("Sent:.*\n", "", out)
66         out = re.sub("Received: *", "", out)
67         info = json.loads(out)["system"]["get_sysinfo"]
68         logger.debug("%s", json.dumps(info, indent=4, sort_keys=True))
69         return info
70     except Exception as e:
71         logger.exception(e)
72         print(out, file=sys.stderr)
73         return None
74
75
76 def encrypt(string: str) -> bytes:
77     """Encryption and Decryption of TP-Link Smart Home Protocol.
78
79     XOR Autokey Cipher with starting key = 171
80
81     >>> " ".join(hex(b).replace('0x', '') for b in encrypt('{"system":{"get_sysinfo":{}}}'))
82     '0 0 0 1d d0 f2 81 f8 8b ff 9a f7 d5 ef 94 b6 d1 b4 c0 9f ec 95 e6 8f e1 87 e8 ca f0 8b f6 8b f6'
83
84     """
85     key = 171
86     result = pack(">I", len(string))
87     for i in string:
88         a = key ^ ord(i)
89         key = a
90         result += bytes([a])
91     return result
92
93
94 def decrypt(string: bytes) -> str:
95     """Opposite of encrypt (above).
96
97     >>> b = encrypt('hi, mom')
98     >>> s = decrypt(b[4:])
99     >>> s
100     'hi, mom'
101
102     """
103     key = 171
104     result = ""
105     for i in string:
106         a = key ^ i
107         key = i
108         result += chr(a)
109     return result
110
111
112 if __name__ == '__main__':
113     import doctest
114
115     doctest.testmod()