summaryrefslogtreecommitdiff
path: root/karton/android/android.py
blob: 7edbc7e44d1c016869db8479251fb530640c6359 (plain)
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
import androguard.core.bytecodes.apk  # type: ignore
from karton.core import Karton, Task  # type: ignore

from .__version__ import __version__


class Android(Karton):
    """
    Augment apk files with various metadata.
    """

    identity = "karton.android"
    version = __version__
    filters = [
        {"type": "sample", "extension": "apk"},
    ]

    def process(self, task: Task) -> None:
        sample = task.get_resource("sample")

        a = androguard.core.bytecodes.apk.APK(sample.content, raw=True)
        if not a.is_valid_APK():
            self.log.info("Not a valid APK file.")
            return

        metadata = {
            "activities": sorted(a.get_activities()),
            "main_activity": [a.get_main_activity()],
            "package": [a.package.strip()],
            "permissions": sorted(a.get_permissions()),
        }

        app_name = a.get_app_name().strip()
        if app_name:
            metadata["app_name"] = [app_name]

        if a.is_signed() or a.is_signed_v3():
            certs = a.get_certificates()
            if len(certs):
                cert = certs[0]
                sha1_cert = cert.sha1_fingerprint.replace(" ", "")
                cert_validity = cert["tbs_certificate"]["validity"]
                not_before_raw = cert_validity["not_before"]
                not_before = not_before_raw.native.strftime("%b %-d %X %Y %Z")
                not_after_raw = cert_validity["not_after"]
                not_after = not_after_raw.native.strftime("%b %-d %X %Y %Z")
                metadata.update(
                    {
                        "certificate": [sha1_cert],
                        "certificate_issuer": [cert.issuer.human_friendly],
                        "certificate_not_after": [not_after],
                        "certificate_not_before": [not_before],
                        "certificate_serial": [str(cert.serial_number)],
                        "certificate_subject": [cert.subject.human_friendly],
                    }
                )

        self.send_task(
            Task(
                headers={
                    "type": "sample",
                    "stage": "analyzed",
                },
                payload={"sample": sample, "attributes": metadata},
            )
        )