File: extract_tokens.py

package info (click to toggle)
python-miio 0.5.12-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,888 kB
  • sloc: python: 23,425; makefile: 9
file content (243 lines) | stat: -rw-r--r-- 7,597 bytes parent folder | download | duplicates (2)
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
import json
import logging
import sqlite3
import tempfile
from pprint import pformat as pf
from typing import Iterator

import attr
import click
import defusedxml.ElementTree as ET
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

logging.basicConfig(level=logging.INFO)
_LOGGER = logging.getLogger(__name__)


@attr.s
class DeviceConfig:
    """A presentation of a device including its name, model, ip etc."""

    name = attr.ib()
    mac = attr.ib()
    ip = attr.ib()
    token = attr.ib()
    model = attr.ib()
    everything = attr.ib(default=None)


def read_android_yeelight(db) -> Iterator[DeviceConfig]:
    """Read tokens from Yeelight's android backup."""
    _LOGGER.info("Reading tokens from Yeelight Android DB")
    xml = ET.parse(db)
    devicelist = xml.find(".//set[@name='deviceList']")
    if not devicelist:
        _LOGGER.warning("Unable to find deviceList")
        return []

    for dev_elem in list(devicelist):
        dev = json.loads(dev_elem.text)
        ip = dev["localip"]
        mac = dev["mac"]
        model = dev["model"]
        name = dev["name"]
        token = dev["token"]

        config = DeviceConfig(
            name=name, ip=ip, mac=mac, model=model, token=token, everything=dev
        )

        yield config


class BackupDatabaseReader:
    """Main class for reading backup files.

    Example:
    .. code-block:: python

        r = BackupDatabaseReader()
        devices = r.read_tokens("/tmp/database.sqlite")
        for dev in devices:
            print("Got %s with token %s" % (dev.ip, dev.token)
    """

    def __init__(self, dump_raw=False):
        self.dump_raw = dump_raw

    @staticmethod
    def dump_raw(dev):
        """Dump whole database."""
        raw = {k: dev[k] for k in dev.keys()}
        _LOGGER.info(pf(raw))

    @staticmethod
    def decrypt_ztoken(ztoken):
        """Decrypt the given ztoken, used by apple."""
        if ztoken is None or len(ztoken) <= 32:
            return str(ztoken)

        keystring = "00000000000000000000000000000000"
        key = bytes.fromhex(keystring)
        cipher = Cipher(  # nosec
            algorithms.AES(key), modes.ECB(), backend=default_backend()
        )
        decryptor = cipher.decryptor()
        token = decryptor.update(bytes.fromhex(ztoken[:64])) + decryptor.finalize()

        return token.decode()

    def read_apple(self) -> Iterator[DeviceConfig]:
        """Read Apple-specific database file."""
        _LOGGER.info("Reading tokens from Apple DB")
        c = self.conn.execute("SELECT * FROM ZDEVICE WHERE ZTOKEN IS NOT '';")
        for dev in c.fetchall():
            if self.dump_raw:
                BackupDatabaseReader.dump_raw(dev)
            ip = dev["ZLOCALIP"]
            mac = dev["ZMAC"]
            model = dev["ZMODEL"]
            name = dev["ZNAME"]
            token = BackupDatabaseReader.decrypt_ztoken(dev["ZTOKEN"])

            config = DeviceConfig(
                name=name, mac=mac, ip=ip, model=model, token=token, everything=dev
            )
            yield config

    def read_android(self) -> Iterator[DeviceConfig]:
        """Read Android-specific database file."""
        _LOGGER.info("Reading tokens from Android DB")
        c = self.conn.execute("SELECT * FROM devicerecord WHERE token IS NOT '';")
        for dev in c.fetchall():
            if self.dump_raw:
                BackupDatabaseReader.dump_raw(dev)
            ip = dev["localIP"]
            mac = dev["mac"]
            model = dev["model"]
            name = dev["name"]
            token = dev["token"]

            config = DeviceConfig(
                name=name, ip=ip, mac=mac, model=model, token=token, everything=dev
            )
            yield config

    def read_tokens(self, db) -> Iterator[DeviceConfig]:
        """Read device information out from a given database file.

        :param str db: Database file
        """
        self.db = db
        _LOGGER.info("Reading database from %s" % db)
        self.conn = sqlite3.connect(db)

        self.conn.row_factory = sqlite3.Row
        with self.conn:
            is_android = (
                self.conn.execute(
                    "SELECT name FROM sqlite_master WHERE type='table' AND name='devicerecord';"
                ).fetchone()
                is not None
            )
            is_apple = (
                self.conn.execute(
                    "SELECT name FROM sqlite_master WHERE type='table' AND name='ZDEVICE'"
                ).fetchone()
                is not None
            )
            if is_android:
                yield from self.read_android()
            elif is_apple:
                yield from self.read_apple()
            else:
                _LOGGER.error("Error, unknown database type!")


@click.command()
@click.argument("backup")
@click.option(
    "--write-to-disk",
    type=click.File("wb"),
    help="writes sqlite3 db to a file for debugging",
)
@click.option(
    "--password", type=str, help="password if the android database is encrypted"
)
@click.option(
    "--dump-all", is_flag=True, default=False, help="dump devices without ip addresses"
)
@click.option("--dump-raw", is_flag=True, help="dumps raw rows")
def main(backup, write_to_disk, password, dump_all, dump_raw):
    """Reads device information out from an sqlite3 DB.

    If the given file is an Android backup (.ab), the database will be extracted
    automatically. If the given file is an iOS backup, the tokens will be extracted (and
    decrypted if needed) automatically.
    """

    def read_miio_database(tar):
        DBFILE = "apps/com.xiaomi.smarthome/db/miio2.db"
        try:
            db = tar.extractfile(DBFILE)
        except KeyError as ex:
            click.echo(f"Unable to find miio database file {DBFILE}: {ex}")
            return []
        if write_to_disk:
            file = write_to_disk
        else:
            file = tempfile.NamedTemporaryFile()
        with file as fp:
            click.echo("Saving database to %s" % fp.name)
            fp.write(db.read())

            return list(reader.read_tokens(fp.name))

    def read_yeelight_database(tar):
        DBFILE = "apps/com.yeelight.cherry/sp/miot.xml"
        _LOGGER.info("Trying to read %s", DBFILE)
        try:
            db = tar.extractfile(DBFILE)
        except KeyError as ex:
            click.echo(f"Unable to find yeelight database file {DBFILE}: {ex}")
            return []

        return list(read_android_yeelight(db))

    devices = []
    reader = BackupDatabaseReader(dump_raw)
    if backup.endswith(".ab"):
        try:
            from android_backup import AndroidBackup
        except ModuleNotFoundError:
            click.echo(
                "You need to install android_backup to extract "
                "tokens from Android backup files."
            )
            return

        with AndroidBackup(backup, stream=False) as f:
            tar = f.read_data(password)

            devices.extend(read_miio_database(tar))

            devices.extend(read_yeelight_database(tar))
    else:
        devices = list(reader.read_tokens(backup))

    for dev in devices:
        if dev.ip or dump_all:
            click.echo(
                "%s\n"
                "\tModel: %s\n"
                "\tIP address: %s\n"
                "\tToken: %s\n"
                "\tMAC: %s" % (dev.name, dev.model, dev.ip, dev.token, dev.mac)
            )
            if dump_raw:
                click.echo(dev)


if __name__ == "__main__":
    main()