Changeset d42aac3 for server.py


Ignore:
Timestamp:
01/22/26 17:32:29 (6 months ago)
Author:
istevanoska <ilinastevanoska@…>
Branches:
master
Children:
e4c61dd
Parents:
505f39a
Message:

Added history mmanage

File:
1 edited

Legend:

Unmodified
Added
Removed
  • server.py

    r505f39a rd42aac3  
    255255        )
    256256        """)
     257
     258    # Environment settings (switch-ови по env)
     259    c.execute("""
     260        CREATE TABLE IF NOT EXISTS env_settings(
     261            tenant_id INTEGER NOT NULL,
     262            env_name TEXT NOT NULL,
     263            save_process_history INTEGER DEFAULT 0,
     264            created_at TEXT,
     265            updated_at TEXT,
     266            PRIMARY KEY(tenant_id, env_name),
     267            FOREIGN KEY(tenant_id) REFERENCES tenants(id)
     268        )
     269    """)
     270
     271    # Latest processes (only current snapshot)
     272    c.execute("""
     273        CREATE TABLE IF NOT EXISTS computer_processes_current(
     274            id INTEGER PRIMARY KEY AUTOINCREMENT,
     275            computer_id INTEGER NOT NULL,
     276            pid INTEGER,
     277            name TEXT,
     278            cpu_percent REAL,
     279            memory_mb REAL,
     280            username TEXT,
     281            cmdline TEXT,
     282            timestamp TEXT,
     283            FOREIGN KEY(computer_id) REFERENCES computers(id)
     284        )
     285    """)
     286
     287    # History processes (optional, controlled by switch)
     288    c.execute("""
     289        CREATE TABLE IF NOT EXISTS computer_processes_history(
     290            id INTEGER PRIMARY KEY AUTOINCREMENT,
     291            computer_id INTEGER NOT NULL,
     292            pid INTEGER,
     293            name TEXT,
     294            cpu_percent REAL,
     295            memory_mb REAL,
     296            username TEXT,
     297            cmdline TEXT,
     298            timestamp TEXT,
     299            FOREIGN KEY(computer_id) REFERENCES computers(id)
     300        )
     301    """)
     302
    257303
    258304    conn.commit()
     
    291337
    292338    return deco
     339def is_process_history_enabled(tenant_id: int, env_name: str) -> bool:
     340    conn = db()
     341    c = conn.cursor()
     342    c.execute("""
     343        SELECT save_process_history
     344        FROM env_settings
     345        WHERE tenant_id=? AND env_name=?
     346        LIMIT 1
     347    """, (tenant_id, env_name))
     348    row = c.fetchone()
     349    conn.close()
     350
     351    # default: OFF ако нема запис
     352    return bool(row["save_process_history"]) if row else False
    293353
    294354
     
    381441
    382442            c.execute("DELETE FROM computer_history WHERE timestamp < ?", (cutoff,))
    383             c.execute("DELETE FROM computer_processes WHERE timestamp < ?", (cutoff,))
    384443            c.execute("DELETE FROM sysmon_events WHERE timestamp < ?", (cutoff,))
    385444            c.execute("DELETE FROM network_connections WHERE timestamp < ?", (cutoff,))
     445            c.execute("DELETE FROM computer_processes_history WHERE timestamp < ?", (cutoff,))
    386446
    387447            conn.commit()
     
    569629    return jsonify({"ok": True, "env": env, "token": token})
    570630
     631@app.route("/api/admin/env-settings/<env_name>", methods=["GET"])
     632@require_tenant_admin()
     633def admin_get_env_settings(env_name):
     634    tenant_id = request.user["tenant_id"]
     635
     636    conn = db()
     637    c = conn.cursor()
     638    c.execute("""
     639        SELECT save_process_history
     640        FROM env_settings
     641        WHERE tenant_id=? AND env_name=?
     642        LIMIT 1
     643    """, (tenant_id, env_name))
     644    row = c.fetchone()
     645    conn.close()
     646
     647    return jsonify({
     648        "env": env_name,
     649        "save_process_history": bool(row["save_process_history"]) if row else False
     650    })
     651
     652@app.route("/api/admin/env-settings/<env_name>", methods=["POST"])
     653@require_tenant_admin()
     654def admin_set_env_settings(env_name):
     655    tenant_id = request.user["tenant_id"]
     656    data = request.get_json(force=True, silent=True) or {}
     657    enabled = 1 if bool(data.get("save_process_history")) else 0
     658
     659    conn = db()
     660    c = conn.cursor()
     661    c.execute("""
     662        INSERT INTO env_settings(tenant_id, env_name, save_process_history, created_at, updated_at)
     663        VALUES(?, ?, ?, datetime('now'), datetime('now'))
     664        ON CONFLICT(tenant_id, env_name) DO UPDATE SET
     665            save_process_history=excluded.save_process_history,
     666            updated_at=datetime('now')
     667    """, (tenant_id, env_name, enabled))
     668    conn.commit()
     669    conn.close()
     670
     671    return jsonify({"ok": True, "env": env_name, "save_process_history": bool(enabled)})
    571672
    572673# ----------------------------
     
    596697
    597698        # Find by (tenant_id + name)
    598         c.execute("SELECT id FROM computers WHERE tenant_id=? AND name=? LIMIT 1", (tenant_id, computer_name))
     699        c.execute(
     700            "SELECT id FROM computers WHERE tenant_id=? AND name=? LIMIT 1",
     701            (tenant_id, computer_name),
     702        )
    599703        row = c.fetchone()
    600704
     
    602706            computer_id = row["id"]
    603707            c.execute("""
    604                     UPDATE computers
    605                     SET user=?, ip=?, os=?, last_seen=?, sysmon_available=?, env_name=?
    606                     WHERE id=? AND tenant_id=?
    607                 """, (
     708                UPDATE computers
     709                SET user=?, ip=?, os=?, last_seen=?, sysmon_available=?, env_name=?
     710                WHERE id=? AND tenant_id=?
     711            """, (
    608712                info.get("user"),
    609713                info.get("ip_address"),
     
    617721        else:
    618722            c.execute("""
    619                     INSERT INTO computers(tenant_id, env_name, name, user, ip, os, first_seen, last_seen, sysmon_available)
    620                     VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)
    621                 """, (
     723                INSERT INTO computers(
     724                    tenant_id, env_name, name, user, ip, os,
     725                    first_seen, last_seen, sysmon_available
     726                )
     727                VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)
     728            """, (
    622729                tenant_id,
    623730                env_name,
     
    634741        # history row
    635742        c.execute("""
    636                 INSERT INTO computer_history(computer_id, cpu_usage, ram_usage, disk_usage,
    637                                              network_sent_mb, network_recv_mb, timestamp)
    638                 VALUES(?, ?, ?, ?, ?, ?, ?)
    639             """, (
     743            INSERT INTO computer_history(
     744                computer_id, cpu_usage, ram_usage, disk_usage,
     745                network_sent_mb, network_recv_mb, timestamp
     746            )
     747            VALUES(?, ?, ?, ?, ?, ?, ?)
     748        """, (
    640749            computer_id,
    641750            float(info.get("cpu_usage") or 0),
     
    647756        ))
    648757
    649         # processes
     758        # ----------------------------
     759        # processes: CURRENT (always)
     760        # ----------------------------
     761        # Clear old current snapshot for this computer
     762        c.execute("DELETE FROM computer_processes_current WHERE computer_id=?", (computer_id,))
     763
     764        # Insert new snapshot
    650765        for proc in (data.get("processes") or []):
    651766            c.execute("""
    652                     INSERT INTO computer_processes(computer_id, pid, name, cpu_percent, memory_mb, username, cmdline, timestamp)
    653                     VALUES(?, ?, ?, ?, ?, ?, ?, ?)
    654                 """, (
     767                INSERT INTO computer_processes_current(
     768                    computer_id, pid, name, cpu_percent, memory_mb, username, cmdline, timestamp
     769                )
     770                VALUES(?, ?, ?, ?, ?, ?, ?, ?)
     771            """, (
    655772                computer_id,
    656773                proc.get("pid"),
     
    663780            ))
    664781
     782        # ----------------------------
     783        # processes: HISTORY (optional)
     784        # ----------------------------
     785        if is_process_history_enabled(tenant_id, env_name):
     786            for proc in (data.get("processes") or []):
     787                c.execute("""
     788                    INSERT INTO computer_processes_history(
     789                        computer_id, pid, name, cpu_percent, memory_mb, username, cmdline, timestamp
     790                    )
     791                    VALUES(?, ?, ?, ?, ?, ?, ?, ?)
     792                """, (
     793                    computer_id,
     794                    proc.get("pid"),
     795                    proc.get("name"),
     796                    float(proc.get("cpu_percent") or 0),
     797                    float(proc.get("memory_mb") or 0),
     798                    proc.get("user") or proc.get("username"),
     799                    proc.get("cmdline"),
     800                    info.get("timestamp") or now_iso,
     801                ))
     802
    665803        # sysmon events
    666804        sysmon_count = 0
    667805        for ev in (security_data.get("sysmon_events") or []):
    668806            c.execute("""
    669                     INSERT INTO sysmon_events(computer_id, event_id, event_type, message, timestamp, details)
    670                     VALUES(?, ?, ?, ?, ?, ?)
    671                 """, (
     807                INSERT INTO sysmon_events(
     808                    computer_id, event_id, event_type, message, timestamp, details
     809                )
     810                VALUES(?, ?, ?, ?, ?, ?)
     811            """, (
    672812                computer_id,
    673813                ev.get("event_id"),
     
    682822        for nc in (security_data.get("network_connections") or []):
    683823            c.execute("""
    684                     INSERT INTO network_connections(computer_id, pid, local_address, remote_address, status, process_name, timestamp)
    685                     VALUES(?, ?, ?, ?, ?, ?, ?)
    686                 """, (
     824                INSERT INTO network_connections(
     825                    computer_id, pid, local_address, remote_address, status, process_name, timestamp
     826                )
     827                VALUES(?, ?, ?, ?, ?, ?, ?)
     828            """, (
    687829                computer_id,
    688830                nc.get("pid"),
     
    710852            "sysmon_events_saved": sysmon_count,
    711853            "server_time": now_iso,
     854            "process_history_enabled": bool(is_process_history_enabled(tenant_id, env_name)),
    712855        })
    713856
     
    8681011
    8691012    c.execute("""
    870             SELECT pid, name, username, cpu_percent, memory_mb, cmdline, timestamp
    871             FROM computer_processes
    872             WHERE computer_id=?
    873             ORDER BY timestamp DESC
    874             LIMIT 100
    875         """, (computer_id,))
     1013        SELECT pid, name, username, cpu_percent, memory_mb, cmdline, timestamp
     1014        FROM computer_processes_current
     1015        WHERE computer_id=?
     1016        ORDER BY timestamp DESC
     1017        LIMIT 200
     1018    """, (computer_id,))
    8761019    processes = [dict(r) for r in c.fetchall()]
    8771020
     
    9561099    out["sysmon_events"] = [dict(r) for r in c.fetchall()]
    9571100
    958     c.execute("SELECT * FROM computer_processes WHERE computer_id=? ORDER BY timestamp", (computer_id,))
    959     out["processes"] = [dict(r) for r in c.fetchall()]
     1101    c.execute("SELECT * FROM computer_processes_current WHERE computer_id=? ORDER BY timestamp", (computer_id,))
     1102    out["processes_current"] = [dict(r) for r in c.fetchall()]
     1103
     1104    c.execute("SELECT * FROM computer_processes_history WHERE computer_id=? ORDER BY timestamp", (computer_id,))
     1105    out["processes_history"] = [dict(r) for r in c.fetchall()]
    9601106
    9611107    c.execute("SELECT * FROM network_connections WHERE computer_id=? ORDER BY timestamp", (computer_id,))
     
    10091155    c.execute(f"""
    10101156            SELECT p.timestamp, p.pid, p.name, p.cpu_percent, p.memory_mb
    1011             FROM computer_processes p
     1157            FROM computer_processes_current p
    10121158            JOIN computers c2 ON c2.id = p.computer_id
    10131159            WHERE c2.tenant_id = ? {comp_clause}
     
    11061252    cleanup_thread.start()
    11071253
    1108     print("🚀 netIntel server running on 0.0.0.0:5555")
     1254    print(" netIntel server running on 0.0.0.0:5555")
    11091255    # debug=False recommended; if you need debug, set True temporarily
    11101256    app.run(host="0.0.0.0", port=5555, debug=False, threaded=True)
Note: See TracChangeset for help on using the changeset viewer.