206 lines
8.0 KiB
Python
206 lines
8.0 KiB
Python
# Copyright (C) 2025 James Brotosky, Brandon Wickline
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify
|
|
# it under the terms of the GNU Affero General Public License as published
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU Affero General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
import pandas as pd
|
|
import requests
|
|
import os
|
|
import json
|
|
import utils.pathfunctions as pathf
|
|
import utils.pretty as ct
|
|
|
|
|
|
def aggregateHashes(executions_json) -> pd.DataFrame:
|
|
"""
|
|
Takes the executions, aggregates all the data with sha256 as primary, then returns aggregated dataframe
|
|
"""
|
|
data = json.loads(executions_json)
|
|
df = pd.DataFrame(data["response"]["exechistories"])
|
|
|
|
if df.empty:
|
|
return df
|
|
print(df)
|
|
# Aggregate by sha256, deduplicate lists, and preserve order
|
|
agg_df = df.groupby("sha256").agg(lambda x: list(dict.fromkeys(x))).reset_index()
|
|
|
|
# Add a column for the number of unique hostnames
|
|
agg_df["num_devices"] = agg_df["hostname"].apply(len)
|
|
|
|
# Sort by num_devices in descending order
|
|
agg_df = agg_df.sort_values("num_devices", ascending=False)
|
|
|
|
return agg_df
|
|
|
|
def augmentAggregatedHashes(url, agg_df: pd.DataFrame) -> pd.DataFrame:
|
|
"""
|
|
Takes output of aggregatedHashes, queries API for those hashes, flattens response while keeping one row per hash,
|
|
aggregate applications and baselines into lists, then merges results back into agg_df to create a
|
|
"""
|
|
if 'sha256' not in agg_df.columns or agg_df.empty:
|
|
print("⚠️ 'sha256' column missing or DataFrame is empty. Skipping API query.")
|
|
return agg_df.copy() # Return as-is to avoid breaking downstream logic
|
|
|
|
endpoint = url + '/v1/hash/query'
|
|
payload = {
|
|
"hashes": agg_df['sha256'].tolist()
|
|
}
|
|
|
|
headers = {"X-APIKey": os.getenv('APIKEY')}
|
|
payload = json.dumps(payload)
|
|
|
|
response = requests.post(endpoint, headers=headers, data=payload, verify=False)
|
|
data = response.json()
|
|
results = data.get("response", {}).get("results", [])
|
|
|
|
rows = []
|
|
for res in results:
|
|
row = {"sha256": res.get("sha256"), "result": res.get("result")}
|
|
|
|
if "data" in res:
|
|
d = res["data"]
|
|
for key in ["filename", "filepath", "description", "filesize", "md5",
|
|
"productname", "productversion", "publisher", "createtime", "modtime",
|
|
"sha128", "sha384", "sha512", "datetime"]:
|
|
row[key] = d.get(key)
|
|
|
|
row["applications"] = d.get("applications", [])
|
|
row["baselines"] = d.get("baselines", [])
|
|
|
|
reputation = d.get("reputation", {})
|
|
for k, v in reputation.items():
|
|
row[f"reputation_{k}"] = v
|
|
|
|
rows.append(row)
|
|
|
|
df_api = pd.DataFrame(rows)
|
|
|
|
if 'sha256' not in df_api.columns:
|
|
print("⚠️ API response missing 'sha256'. Skipping merge.")
|
|
return agg_df.copy()
|
|
|
|
df = agg_df.merge(df_api, on="sha256", how="left")
|
|
|
|
# Only include columns that exist to avoid KeyErrors
|
|
expected_columns = ['sha256', 'filename_x', 'description', 'productname', 'productversion',
|
|
'publisher_y', 'publisher_x', 'netdomain', 'hostname', 'username',
|
|
'reputation_lastseen', 'reputation_scannermatch', 'reputation_scannercount',
|
|
'reputation_status', 'reputation_threatlevel', 'reputation_threatname',
|
|
'reputation_timestamp', 'pprocess', 'gprocess', 'commandline']
|
|
|
|
available_columns = [col for col in expected_columns if col in df.columns]
|
|
aug_df = df[available_columns]
|
|
|
|
return aug_df
|
|
|
|
def categorizeHashes(df: pd.DataFrame, threat_tolerance: int, untrusted_publishers: list, pups: list):
|
|
if untrusted_publishers is None: untrusted_publishers = []
|
|
if pups is None: pups = []
|
|
|
|
def reputationtool(row):
|
|
val = row["reputation_scannermatch"]
|
|
if pd.isna(val) or val == "N/A":
|
|
return row["publisher"] == "Not Signed"
|
|
try:
|
|
return int(val) > threat_tolerance
|
|
except (ValueError, TypeError):
|
|
return row["publisher"] == "Not Signed"
|
|
|
|
df["reputation_flag"] = df.apply(reputationtool, axis=1)
|
|
|
|
mask_needsreview = (
|
|
((df["publisher"] == "Not Signed") & df["reputation_flag"]) |
|
|
(df["reputation_status"] == "UNKNOWN")
|
|
)
|
|
|
|
mask_approved = (
|
|
(
|
|
(df["publisher"] != "Not Signed") &
|
|
~df["publisher"].isin(untrusted_publishers) &
|
|
~df["reputation_status"].isna() &
|
|
~df["description"].str.contains(pathf.regulator(pups), case=False, na=False)
|
|
) |
|
|
(
|
|
(df["publisher"] == "Not Signed") &
|
|
~df["reputation_flag"] &
|
|
~df["publisher"].isin(untrusted_publishers) &
|
|
~df["reputation_status"].isna() &
|
|
~df["description"].str.contains(pathf.regulator(pups), case=False, na=False)
|
|
)
|
|
)
|
|
|
|
needsreview_df = df[mask_needsreview]
|
|
approved_df = df[mask_approved]
|
|
unapproved_df = df[~(mask_needsreview | mask_approved)]
|
|
|
|
return needsreview_df, approved_df, unapproved_df
|
|
|
|
|
|
|
|
def explode_and_deduplicate(df):
|
|
df['sha256'] = df['sha256'].str.split(',')
|
|
df = df.explode('sha256')
|
|
return df.drop_duplicates().reset_index(drop=True)
|
|
|
|
def clean_sha256(df, column='sha256'):
|
|
"""Discard quotes, brackets, and whitespace from sha256 values."""
|
|
df[column] = df[column].astype(str).str.strip("'[]\" ")
|
|
return df
|
|
|
|
def destinationHashes(
|
|
df_approved_paths: pd.DataFrame,
|
|
df_approved_hashes: pd.DataFrame,
|
|
df_hashes_auto_approved: pd.DataFrame,
|
|
df_hashes_manually_approved: pd.DataFrame,
|
|
):
|
|
# Deduplicate and explode all input DataFrames
|
|
df_approved_paths = explode_and_deduplicate(df_approved_paths)
|
|
df_approved_hashes = explode_and_deduplicate(df_approved_hashes)
|
|
df_hashes_auto_approved = explode_and_deduplicate(df_hashes_auto_approved)
|
|
df_hashes_manually_approved = explode_and_deduplicate(df_hashes_manually_approved)
|
|
|
|
# Clean sha256 values in all relevant DataFrames
|
|
df_approved_hashes = clean_sha256(df_approved_hashes)
|
|
df_hashes_auto_approved = clean_sha256(df_hashes_auto_approved)
|
|
df_hashes_manually_approved = clean_sha256(df_hashes_manually_approved)
|
|
|
|
# Create sets for faster lookup
|
|
auto_approved_sha256 = set(df_hashes_auto_approved['sha256'].values)
|
|
manually_approved_sha256 = set(df_hashes_manually_approved['sha256'].values)
|
|
|
|
# Debug: Print unmatched hashes
|
|
unmatched = set(df_approved_hashes['sha256']) - (auto_approved_sha256 | manually_approved_sha256)
|
|
print(f"Unmatched hashes: {unmatched}")
|
|
|
|
# Process df_approved_paths
|
|
df_paths = df_approved_paths.assign(destination='Path Exclusion')
|
|
df_paths = df_paths[['sha256', 'description', 'destination', 'grouped_directory', 'filename']]
|
|
|
|
# Process df_approved_hashes
|
|
df_hashes = df_approved_hashes.copy()
|
|
df_hashes['destination'] = df_hashes['sha256'].apply(
|
|
lambda x: 'Parent Policy Baseline' if x in auto_approved_sha256
|
|
else ('Child Policy Allowlist' if x in manually_approved_sha256 else None)
|
|
)
|
|
df_hashes = df_hashes.dropna(subset=['destination'])
|
|
df_hashes = df_hashes.assign(grouped_directory=None)
|
|
|
|
# Use 'filename_x' only if it exists, otherwise fallback to 'filename'
|
|
filename_col = 'filename_x' if 'filename_x' in df_hashes.columns else 'filename'
|
|
selected_cols = ['sha256', 'description', 'destination', 'grouped_directory', filename_col]
|
|
df_hashes = df_hashes[selected_cols]
|
|
|
|
# Concatenate results
|
|
df_hashdestination = pd.concat([df_paths, df_hashes], ignore_index=True)
|
|
return df_hashdestination
|