#!/usr/bin/env python3
"""Morph extractor: gathers evidence about an application from inside your own network, so Morph can understand it and
map it to Salesforce. It reads metadata, configuration and code; it never copies business records.

Run it on a machine that can reach the system, then upload the bundle it writes (morph-evidence-<name>.zip) to the
investigation in Morph. Everything it collects is listed in MANIFEST.json inside the bundle so you can check it first.

  python3 morph-extract.py oracle --dsn host:1521/SERVICE --user READONLY_USER [--schemas HR,APP] [--profile] [--source]
  python3 morph-extract.py java   --path /path/to/source-or-deployments [--copy-source]
  python3 morph-extract.py dynamics --solution exported_solution.zip
  python3 morph-extract.py files  --path /path/to/config-or-docs

Options for every command: --name NAME (bundle name), --out DIR (where to write the bundle).

Needs Python 3.8+. The oracle command also needs the python-oracledb package (pip install oracledb); it uses "thin"
mode, so no Oracle client install is needed. Use a read-only account: the extractor only runs SELECT statements on the
data dictionary (and, with --profile, counts and summary statistics, with personal-looking columns masked).
Passwords are asked for at the prompt (or read from MORPH_DB_PASSWORD) and never written anywhere.
"""
import argparse
import datetime
import getpass
import hashlib
import io
import json
import os
import re
import sys
import zipfile

VERSION = "1.0.0"
SECRET_KEY = re.compile(r"(?i)(pass(word|wd)?|secret|token|api[_-]?key|private[_-]?key|credential|auth)")
SECRET_VALUE = re.compile(r"(?i)((?:pass(?:word|wd)?|pwd|secret|token|api[._-]?key|access[._-]?key|private[._-]?key|credentials?)"
                          r"[\"']?\s*[=:]\s*[\"']?)([^\s\"'<>,;]+)")
PERSONAL = re.compile(r"(?i)(name|email|phone|mobile|address|street|postcode|zip|birth|dob|ssn|tfn|medicare|passport|licen[cs]e|"
                      r"account_?no|card|iban|bsb|salary|gender|ethnic|religion|health|diagnos|note|comment|description)")
SKIP_DIRS = {".git", "node_modules", "target", "build", ".gradle", ".idea", "__pycache__", ".svn", "dist", "out"}
CODE_EXT = {".java", ".kt", ".groovy", ".xml", ".properties", ".yml", ".yaml", ".sql", ".jsp", ".jspx", ".html", ".js", ".ts", ".json",
            ".gradle", ".md", ".cs", ".config", ".xsd", ".wsdl", ".bpmn", ".drl", ".ftl", ".vm"}
MAX_FILE = 2_000_000


class Bundle:
    def __init__(self, name, kind):
        self.name, self.kind = re.sub(r"[^\w.-]", "_", name)[:60], kind
        self.buf = io.BytesIO()
        self.z = zipfile.ZipFile(self.buf, "w", zipfile.ZIP_DEFLATED)
        self.items, self.redactions = [], 0

    def add(self, path, data, what):
        if isinstance(data, (dict, list)):
            data = json.dumps(data, indent=1, default=str)
        if isinstance(data, str):
            data = data.encode("utf-8")
        self.z.writestr(path, data)
        self.items.append({"path": path, "what": what, "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()})

    def redact(self, text):
        out, n = SECRET_VALUE.subn(lambda m: m.group(1) + "[removed by Morph extractor]", text)
        self.redactions += n
        return out

    def write(self, out_dir):
        manifest = {"tool": "morph-extract", "version": VERSION, "kind": self.kind, "name": self.name,
                    "created": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"),
                    "host": "(not recorded)", "secretsRedacted": self.redactions, "contains": self.items,
                    "note": "Metadata, configuration and code only. No business records are included."}
        self.z.writestr("MANIFEST.json", json.dumps(manifest, indent=1))
        self.z.close()
        path = os.path.join(out_dir, f"morph-evidence-{self.name}.zip")
        with open(path, "wb") as fh:
            fh.write(self.buf.getvalue())
        return path, manifest


# ---------------- Oracle ----------------
DICT = {
    "tables": "SELECT owner, table_name, num_rows, last_analyzed, temporary, partitioned FROM all_tables WHERE owner IN ({o})",
    "columns": "SELECT owner, table_name, column_id, column_name, data_type, data_length, data_precision, data_scale, nullable, "
               "data_default FROM all_tab_columns WHERE owner IN ({o}) ORDER BY owner, table_name, column_id",
    "comments": "SELECT owner, table_name, comments FROM all_tab_comments WHERE owner IN ({o}) AND comments IS NOT NULL",
    "column_comments": "SELECT owner, table_name, column_name, comments FROM all_col_comments WHERE owner IN ({o}) AND comments IS NOT NULL",
    "constraints": "SELECT owner, table_name, constraint_name, constraint_type, r_owner, r_constraint_name, delete_rule, status, "
                   "search_condition_vc FROM all_constraints WHERE owner IN ({o}) AND constraint_name NOT LIKE 'SYS_%'",
    "constraints_all": "SELECT owner, table_name, constraint_name, constraint_type, r_owner, r_constraint_name, delete_rule, status "
                       "FROM all_constraints WHERE owner IN ({o})",
    "constraint_columns": "SELECT owner, constraint_name, table_name, column_name, position FROM all_cons_columns WHERE owner IN ({o})",
    "indexes": "SELECT owner, index_name, table_name, uniqueness FROM all_indexes WHERE owner IN ({o})",
    "views": "SELECT owner, view_name, text_length FROM all_views WHERE owner IN ({o})",
    "objects": "SELECT owner, object_name, object_type, status, last_ddl_time FROM all_objects WHERE owner IN ({o}) "
               "AND object_type IN ('PACKAGE','PACKAGE BODY','PROCEDURE','FUNCTION','TRIGGER','TYPE','SEQUENCE','JOB','VIEW',"
               "'MATERIALIZED VIEW','SYNONYM')",
    "triggers": "SELECT owner, trigger_name, table_name, trigger_type, triggering_event, status, when_clause FROM all_triggers "
                "WHERE owner IN ({o})",
    "sequences": "SELECT sequence_owner, sequence_name, increment_by, last_number FROM all_sequences WHERE sequence_owner IN ({o})",
    "scheduler_jobs": "SELECT owner, job_name, job_type, job_action, repeat_interval, enabled FROM all_scheduler_jobs WHERE owner IN ({o})",
    "dependencies": "SELECT owner, name, type, referenced_owner, referenced_name, referenced_type FROM all_dependencies "
                    "WHERE owner IN ({o}) AND referenced_owner IN ({o})",
}


def _rows(cur, sql):
    cur.execute(sql)
    cols = [d[0].lower() for d in cur.description]
    return [dict(zip(cols, [v.read() if hasattr(v, "read") else v for v in r])) for r in cur.fetchall()]


def oracle(a, b):
    try:
        import oracledb
    except ImportError:
        sys.exit("The oracle command needs python-oracledb: pip install oracledb")
    pw = os.environ.get("MORPH_DB_PASSWORD") or getpass.getpass(f"Password for {a.user}: ")
    conn = oracledb.connect(user=a.user, password=pw, dsn=a.dsn)
    cur = conn.cursor()
    schemas = [s.strip().upper() for s in (a.schemas or a.user).split(",") if s.strip()]
    if not all(re.fullmatch(r"[A-Z0-9_$#]{1,128}", s) for s in schemas):
        sys.exit("Schema names look wrong")
    owners = ",".join(f"'{s}'" for s in schemas)
    info = {"schemas": schemas, "database": _rows(cur, "SELECT banner FROM v$version WHERE ROWNUM = 1") if a.version else []}
    oracle_dictionary(cur, owners, b, profile=a.profile, source=a.source)
    b.add("oracle/about.json", info, "What was read")
    conn.close()


def oracle_dictionary(cur, owners, b, profile=False, source=False):
    for name, sql in DICT.items():
        try:
            b.add(f"oracle/{name}.json", _rows(cur, sql.format(o=owners)), f"Oracle data dictionary: {name}")
        except Exception as e:                     # older versions lack some columns or views: note it and carry on
            b.add(f"oracle/{name}.error.txt", str(e)[:500], f"Couldn't read {name}")
    try:
        for v in _rows(cur, f"SELECT owner, view_name, text_vc FROM all_views WHERE owner IN ({owners})"):
            b.add(f"oracle/views/{v['owner']}.{v['view_name']}.sql", b.redact(str(v.get("text_vc") or "")), "View definition")
    except Exception as e:
        b.add("oracle/views.error.txt", str(e)[:500], "Couldn't read view text")
    if source:                                     # PL/SQL: packages, procedures, functions, triggers
        src = {}
        for r in _rows(cur, f"SELECT owner, name, type, line, text FROM all_source WHERE owner IN ({owners}) ORDER BY owner, name, type, line"):
            src.setdefault((r["owner"], r["name"], r["type"]), []).append(r["text"] or "")
        for (o, n, t), lines in src.items():
            b.add(f"oracle/plsql/{o}.{n}.{t.replace(' ', '_')}.sql", b.redact("".join(lines)), "PL/SQL source")
    if profile:
        b.add("oracle/profile.json", oracle_profile(cur, owners), "Data profile: counts and summary statistics only (no records)")


def oracle_profile(cur, owners):
    """Record counts, how full each column is, and the values of small code-like columns. Personal-looking columns get
    counts only."""
    out = []
    cols = _rows(cur, f"SELECT owner, table_name, column_name, data_type FROM all_tab_columns WHERE owner IN ({owners}) "
                      "ORDER BY owner, table_name, column_id")
    by_table = {}
    for c in cols:
        by_table.setdefault((c["owner"], c["table_name"]), []).append(c)
    for (o, t), cs in by_table.items():
        q = f'"{o}"."{t}"'
        try:
            n = _rows(cur, f"SELECT COUNT(*) AS n FROM {q}")[0]["n"]
        except Exception as e:
            out.append({"table": f"{o}.{t}", "error": str(e)[:200]})
            continue
        entry = {"table": f"{o}.{t}", "rows": n, "columns": []}
        for c in cs[:200]:
            col = f'"{c["column_name"]}"'
            ce = {"column": c["column_name"]}
            try:
                r = _rows(cur, f"SELECT COUNT({col}) AS filled, COUNT(DISTINCT {col}) AS distinct_values FROM {q}")[0]
                ce.update(filled=r["filled"], distinct=r["distinct_values"])
                small = r["distinct_values"] and r["distinct_values"] <= 30 and c["data_type"] in ("VARCHAR2", "CHAR", "NVARCHAR2", "NUMBER")
                if small and not PERSONAL.search(c["column_name"]):
                    ce["values"] = [v["v"] for v in _rows(cur, f"SELECT DISTINCT {col} AS v FROM {q} WHERE {col} IS NOT NULL AND ROWNUM <= 30")]
                elif PERSONAL.search(c["column_name"]):
                    ce["masked"] = True
            except Exception as e:
                ce["error"] = str(e)[:120]
            entry["columns"].append(ce)
        out.append(entry)
    return out


# ---------------- Java ----------------
ANN = re.compile(r"@(Entity|Table|Column|Id|ManyToOne|OneToMany|ManyToMany|OneToOne|JoinColumn|RestController|Controller|"
                 r"RequestMapping|GetMapping|PostMapping|PutMapping|DeleteMapping|PatchMapping|Service|Repository|Scheduled|"
                 r"Transactional|Valid|NotNull|NotBlank|Size|Pattern|Min|Max|Email|PreAuthorize|Secured|RolesAllowed|"
                 r"KafkaListener|JmsListener|WebService|Path|GET|POST|PUT|DELETE)\b(\([^)]*\))?")


def java_inventory(text, rel):
    pkg = re.search(r"^\s*package\s+([\w.]+)\s*;", text, re.M)
    classes = re.findall(r"\b(?:class|interface|enum|record)\s+(\w+)", text)
    anns = [m.group(1) + (m.group(2) or "") for m in ANN.finditer(text)]
    return {"file": rel, "package": pkg.group(1) if pkg else None, "types": classes[:20], "annotations": anns[:200],
            "methods": re.findall(r"(?:public|protected)\s+[\w<>\[\], ?]+\s+(\w+)\s*\(", text)[:200]}


def java(a, b):
    inv, files, archives = [], 0, []
    root = os.path.abspath(a.path)
    for d, dirs, fs in os.walk(root):
        dirs[:] = [x for x in dirs if x not in SKIP_DIRS]
        for f in fs:
            p = os.path.join(d, f)
            rel = os.path.relpath(p, root)
            ext = os.path.splitext(f)[1].lower()
            if ext in (".war", ".ear", ".jar"):
                archives.append(java_archive(p, rel, b))
                continue
            if ext not in CODE_EXT or os.path.getsize(p) > MAX_FILE:
                continue
            text = open(p, encoding="utf-8", errors="ignore").read()
            if ext == ".java":
                inv.append(java_inventory(text, rel))
            if a.copy_source:
                b.add("java/source/" + rel, b.redact(text), "Source or configuration file")
                files += 1
            elif ext in (".xml", ".properties", ".yml", ".yaml", ".sql", ".gradle", ".wsdl", ".xsd", ".bpmn", ".drl"):
                b.add("java/config/" + rel, b.redact(text), "Configuration, mapping or schema file")
                files += 1
    b.add("java/inventory.json", {"root": os.path.basename(root), "javaFiles": len(inv), "classes": inv, "archives": archives,
                                  "copiedFiles": files}, "Inventory of Java types, annotations and endpoints")


def java_archive(path, rel, b):
    """WAR/EAR/JAR: list classes and libraries, keep configuration and mapping files (code stays compiled: Morph's
    investigator can decompile what it needs, if the client has the right to)."""
    entry = {"archive": rel, "classes": 0, "libraries": [], "config": []}
    try:
        with zipfile.ZipFile(path) as z:
            for n in z.namelist():
                low = n.lower()
                if low.endswith(".class"):
                    entry["classes"] += 1
                elif low.endswith(".jar"):
                    entry["libraries"].append(n.rsplit("/", 1)[-1])
                elif low.endswith((".xml", ".properties", ".yml", ".yaml", ".sql", ".wsdl", ".xsd", ".jsp", ".html")) and z.getinfo(n).file_size < MAX_FILE:
                    b.add(f"java/archives/{rel}/{n}", b.redact(z.read(n).decode("utf-8", "ignore")), f"File from {rel}")
                    entry["config"].append(n)
        if os.path.getsize(path) < 200_000_000:     # a copy of the archive, with secrets removed from its text files
            out = io.BytesIO()
            with zipfile.ZipFile(path) as z, zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as w:
                for info in z.infolist():
                    data = z.read(info)
                    if info.filename.lower().endswith((".xml", ".properties", ".yml", ".yaml", ".json", ".txt", ".conf", ".jsp", ".sql")):
                        data = b.redact(data.decode("utf-8", "ignore")).encode("utf-8")
                    w.writestr(info.filename, data)
            b.add(f"java/archives/{rel}.bin/{os.path.basename(path)}", out.getvalue(), "The archive (compiled code; secrets removed from its text files)")
    except zipfile.BadZipFile:
        entry["error"] = "not a valid archive"
    return entry


# ---------------- Dynamics, other files ----------------
def dynamics(a, b):
    if not a.solution or not os.path.isfile(a.solution):
        sys.exit("Give the exported solution zip with --solution (Dynamics: Solutions > Export, unmanaged)")
    with zipfile.ZipFile(a.solution) as z:
        for n in z.namelist():
            if z.getinfo(n).file_size < 50_000_000 and not n.endswith("/"):
                data = z.read(n)
                if n.lower().endswith((".xml", ".json", ".js", ".html", ".css", ".resx")):
                    data = b.redact(data.decode("utf-8", "ignore"))
                b.add("dynamics/solution/" + n, data, "Dynamics solution component")


def files(a, b):
    root = os.path.abspath(a.path)
    for d, dirs, fs in os.walk(root):
        dirs[:] = [x for x in dirs if x not in SKIP_DIRS]
        for f in fs:
            p = os.path.join(d, f)
            if os.path.getsize(p) > 50_000_000:
                continue
            data = open(p, "rb").read()
            if os.path.splitext(f)[1].lower() in CODE_EXT | {".txt", ".csv", ".ini", ".cfg", ".conf"}:
                data = b.redact(data.decode("utf-8", "ignore"))
            b.add("files/" + os.path.relpath(p, root), data, "File")


def main(argv=None):
    ap = argparse.ArgumentParser(description="Morph extractor: gathers evidence about an application for a Morph investigation.")
    ap.add_argument("--version", action="version", version=VERSION)
    sub = ap.add_subparsers(dest="cmd", required=True)
    o = sub.add_parser("oracle", help="Oracle database: data dictionary, view and (optionally) PL/SQL source, data profile")
    o.add_argument("--dsn", required=True, help="host:port/service_name")
    o.add_argument("--user", required=True, help="a read-only account")
    o.add_argument("--schemas", help="comma-separated schemas to read (default: the user's own)")
    o.add_argument("--source", action="store_true", help="include PL/SQL source of packages, procedures and triggers")
    o.add_argument("--profile", action="store_true", help="include counts and summary statistics (no records)")
    o.add_argument("--version-info", dest="version", action="store_true", help="include the database version")
    j = sub.add_parser("java", help="Java application: source folders and WAR/EAR/JAR files")
    j.add_argument("--path", required=True)
    j.add_argument("--copy-source", action="store_true", help="include source files (secrets in them are removed)")
    d = sub.add_parser("dynamics", help="Dynamics 365: an exported solution zip")
    d.add_argument("--solution", required=True)
    f = sub.add_parser("files", help="any folder of configuration, documents or exports")
    f.add_argument("--path", required=True)
    for p in (o, j, d, f):
        p.add_argument("--name", default="")
        p.add_argument("--out", default=".")
    a = ap.parse_args(argv)
    b = Bundle(a.name or a.cmd, a.cmd)
    {"oracle": oracle, "java": java, "dynamics": dynamics, "files": files}[a.cmd](a, b)
    path, m = b.write(a.out)
    print(f"Wrote {path}: {len(m['contains'])} items, {m['secretsRedacted']} secret values removed. Check MANIFEST.json, then upload it to the investigation in Morph.")
    return path


if __name__ == "__main__":
    main()
