From 32e45e07eff1bd43188837cc6d7a6f3c37cf391e Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 05:56:00 +1100 Subject: [PATCH 1/5] server: analyst role, incidents, ATT&CK coverage, Entra ID sign-in Analyst role: admin, analyst, viewer. Each route file declares its routes and permission; http/permissions.zig gates every request before a handler runs, and a test checks every route against the matrix for each role. Analysts triage, run hunts, request response actions (destructive ones can wait for admin approval, a tenant setting) and add exceptions with a reason. Incidents (migration 0008, row-level security): alerts group by the target-edr section 8 rules within 4 hours, using process.entity_id lineage from process_entities. Risk is the section 7 noisy-OR with every evidence item and its points stored. List, view, assign and status endpoints, plus alert acknowledge and resolve. ATT&CK coverage: rules/attack/coverage.yaml and a vendored subset of ATT&CK Enterprise 20.1. GET /api/attack/coverage reports telemetry, detection and response separately. Entra ID: OIDC code flow with PKCE, state, nonce and verifier in oauth_states, ID token verified with the RS256 code in crypto/jwt.zig (iss, aud, exp, nbf, nonce, tid). Users match on tid and oid; groups map to roles; no group, no account. Tenant setting limits password sign-in to break-glass admins. Client secret encrypted with TAWNY_INTEGRATION_ENCRYPTION_KEY. Co-Authored-By: Claude Opus 5.5 --- rules/attack/coverage.yaml | 172 + rules/attack/subset.py | 42 + rules/attack/techniques.json | 3119 +++++++++++++++++ server/src/db/migrate.zig | 6 +- .../src/db/migrations/0008_server_analyst.sql | 126 + server/src/detect/attack/coverage.yaml | 172 + server/src/detect/attack/techniques.json | 3119 +++++++++++++++++ server/src/detect/correlation_test.zig | 2 + server/src/detect/incidents.zig | 591 ++++ server/src/detect/incidents_test.zig | 308 ++ server/src/http/auth.zig | 56 +- server/src/http/dispatch.zig | 75 +- server/src/http/permissions.zig | 257 ++ server/src/jobs/detect.zig | 55 +- server/src/main.zig | 7 + server/src/routes/admin_jobs.zig | 6 + server/src/routes/agent_releases.zig | 7 + server/src/routes/agents.zig | 96 +- server/src/routes/ai.zig | 13 + server/src/routes/alerts.zig | 16 + server/src/routes/attack.zig | 327 ++ server/src/routes/auth.zig | 37 +- server/src/routes/feeds.zig | 10 + server/src/routes/github.zig | 7 + server/src/routes/hunts.zig | 13 + server/src/routes/incidents.zig | 328 ++ server/src/routes/lookup.zig | 6 + server/src/routes/oidc.zig | 629 ++++ server/src/routes/settings.zig | 246 ++ server/src/routes/suppressions.zig | 13 + server/src/routes/tokens.zig | 10 +- server/src/routes/users.zig | 15 +- server/src/routes/yara_rules.zig | 8 + 33 files changed, 9881 insertions(+), 13 deletions(-) create mode 100644 rules/attack/coverage.yaml create mode 100644 rules/attack/subset.py create mode 100644 rules/attack/techniques.json create mode 100644 server/src/db/migrations/0008_server_analyst.sql create mode 100644 server/src/detect/attack/coverage.yaml create mode 100644 server/src/detect/attack/techniques.json create mode 100644 server/src/detect/incidents.zig create mode 100644 server/src/detect/incidents_test.zig create mode 100644 server/src/http/permissions.zig create mode 100644 server/src/routes/attack.zig create mode 100644 server/src/routes/incidents.zig create mode 100644 server/src/routes/oidc.zig create mode 100644 server/src/routes/settings.zig diff --git a/rules/attack/coverage.yaml b/rules/attack/coverage.yaml new file mode 100644 index 0000000..be1b20b --- /dev/null +++ b/rules/attack/coverage.yaml @@ -0,0 +1,172 @@ +# ATT&CK coverage map (docs/architecture/target-edr.md section 6). +# +# For each technique: the event types whose telemetry can show it, and the +# response actions that apply to it. Names and tactics come from +# techniques.json, a subset of ATT&CK Enterprise 20.1 (see README.md). +# +# GET /api/attack/coverage reports three states per technique, each from +# its own source and never from another state: +# telemetry an agent seen in the last 15 minutes, with no failed sensor, +# sent one of these event types in the last 24 hours +# detection an enabled rule lists the technique (mitre_techniques) +# response one of the listed actions is supported on the platform +# +# Keep event types to schemas/events and actions to the ones the agent runs +# (agent/src/response_actions.zig). Platforms limit where an action applies. +attack_version: "20.1" +actions: + kill_process: [windows, linux, macos] + suspend_process: [windows, linux, macos] + quarantine_file: [windows, linux, macos] + isolate_host: [windows] +techniques: + - id: T1059.001 + telemetry: [process_start, powershell_script_block] + response: [kill_process, suspend_process, isolate_host] + - id: T1059.003 + telemetry: [process_start] + response: [kill_process, suspend_process] + - id: T1059.004 + telemetry: [process_start] + response: [kill_process, suspend_process] + - id: T1059.005 + telemetry: [process_start] + response: [kill_process, quarantine_file] + - id: T1059.007 + telemetry: [process_start] + response: [kill_process, quarantine_file] + - id: T1204.002 + telemetry: [process_start, file_create] + response: [kill_process, quarantine_file, isolate_host] + - id: T1566.001 + telemetry: [file_create, process_start] + response: [quarantine_file, isolate_host] + - id: T1047 + telemetry: [process_start] + response: [kill_process] + - id: T1053.005 + telemetry: [process_start] + response: [kill_process] + - id: T1053.003 + telemetry: [process_start, file_create] + response: [kill_process] + - id: T1543.003 + telemetry: [service_create] + response: [quarantine_file, isolate_host] + - id: T1543.001 + telemetry: [file_create] + response: [quarantine_file] + - id: T1543.004 + telemetry: [file_create] + response: [quarantine_file] + - id: T1569.002 + telemetry: [service_create, process_start] + response: [kill_process] + - id: T1547.001 + telemetry: [registry_set, file_create] + response: [quarantine_file] + - id: T1112 + telemetry: [registry_set] + response: [] + - id: T1546.004 + telemetry: [file_create] + response: [] + - id: T1548.002 + telemetry: [process_start, registry_set] + response: [kill_process] + - id: T1055 + telemetry: [] + response: [kill_process, isolate_host] + - id: T1027 + telemetry: [process_start, powershell_script_block] + response: [kill_process] + - id: T1036 + telemetry: [process_start] + response: [kill_process, quarantine_file] + - id: T1218 + telemetry: [process_start] + response: [kill_process] + - id: T1218.011 + telemetry: [process_start] + response: [kill_process] + - id: T1574.001 + telemetry: [file_create] + response: [quarantine_file] + - id: T1070 + telemetry: [process_start] + response: [] + - id: T1685 + telemetry: [sensor_health, agent_tamper, process_start] + response: [isolate_host] + - id: T1685.001 + telemetry: [sensor_health, agent_tamper] + response: [isolate_host] + - id: T1003.001 + telemetry: [process_start] + response: [kill_process, isolate_host] + - id: T1003.008 + telemetry: [process_start] + response: [kill_process] + - id: T1110 + telemetry: [user_logon] + response: [isolate_host] + - id: T1110.001 + telemetry: [user_logon] + response: [] + - id: T1110.003 + telemetry: [user_logon] + response: [] + - id: T1078 + telemetry: [user_logon] + response: [isolate_host] + - id: T1078.003 + telemetry: [user_logon] + response: [] + - id: T1098 + telemetry: [] + response: [] + - id: T1136.001 + telemetry: [process_start] + response: [] + - id: T1021.001 + telemetry: [user_logon, network_connect] + response: [isolate_host] + - id: T1021.002 + telemetry: [user_logon, network_connect] + response: [isolate_host] + - id: T1021.004 + telemetry: [user_logon, network_connect] + response: [kill_process] + - id: T1046 + telemetry: [network_connect] + response: [kill_process, isolate_host] + - id: T1082 + telemetry: [process_start] + response: [] + - id: T1033 + telemetry: [process_start] + response: [] + - id: T1071 + telemetry: [network_connect, dns_query] + response: [kill_process, isolate_host] + - id: T1071.001 + telemetry: [network_connect, dns_query] + response: [kill_process, isolate_host] + - id: T1071.004 + telemetry: [dns_query] + response: [kill_process, isolate_host] + - id: T1568 + telemetry: [dns_query] + response: [isolate_host] + - id: T1105 + telemetry: [process_start, file_create, network_connect] + response: [kill_process, quarantine_file, isolate_host] + - id: T1219 + telemetry: [process_start, network_connect] + response: [kill_process, quarantine_file] + - id: T1486 + telemetry: [file_create] + response: [kill_process, isolate_host] + - id: T1490 + telemetry: [process_start] + response: [kill_process, isolate_host] diff --git a/rules/attack/subset.py b/rules/attack/subset.py new file mode 100644 index 0000000..47a22fa --- /dev/null +++ b/rules/attack/subset.py @@ -0,0 +1,42 @@ +"""Build techniques.json from an ATT&CK Enterprise STIX bundle. + +Usage: python3 -I rules/attack/subset.py > rules/attack/techniques.json +Keeps only techniques named by rules (attack.tNNNN tags) or coverage.yaml. +Update attack_version below and in coverage.yaml when the release changes. +""" +import json,re,sys,hashlib,glob,os +src=sys.argv[1] +raw=open(src,'rb').read() +d=json.loads(raw) +repo=sys.argv[2] +used=set() +for f in glob.glob(repo+'/rules/**/*.y*ml',recursive=True): + for m in re.findall(r'attack\.(t\d{4}(?:\.\d{3})?)', open(f,encoding='utf-8',errors='ignore').read(), re.I): + used.add(m.upper()) +for m in re.findall(r'\bid:\s*(T\d{4}(?:\.\d{3})?)', open(os.path.join(repo,'rules/attack/coverage.yaml')).read()): + used.add(m) +tech={} +tactic_names={} +for o in d['objects']: + if o.get('type')=='x-mitre-tactic' and not o.get('revoked') and not o.get('x_mitre_deprecated'): + tactic_names[o['x_mitre_shortname']]=(o['name'], next(r['external_id'] for r in o['external_references'] if r.get('source_name')=='mitre-attack')) + if o.get('type')!='attack-pattern' or o.get('revoked') or o.get('x_mitre_deprecated'): continue + ext=next((r['external_id'] for r in o.get('external_references',[]) if r.get('source_name')=='mitre-attack'),None) + if not ext: continue + tech[ext]={'id':ext,'name':o['name'],'tactics':[p['phase_name'] for p in o.get('kill_chain_phases',[]) if p.get('kill_chain_name')=='mitre-attack'],'platforms':o.get('x_mitre_platforms',[])} +missing=sorted(u for u in used if u not in tech) +out=[] +for u in sorted(used): + if u in tech: + t=dict(tech[u]) + if '.' in u and u.split('.')[0] in tech: + t['name']=tech[u.split('.')[0]]['name']+': '+t['name'] + out.append(t) +byid={o['id']:o for o in d['objects']} +matrix=next(o for o in d['objects'] if o.get('type')=='x-mitre-matrix' and o.get('name')=='Enterprise ATT&CK') +order=[byid[t]['x_mitre_shortname'] for t in matrix['tactic_refs']] +tactics=[{'shortname':s,'name':tactic_names[s][0],'id':tactic_names[s][1]} for s in order if s in tactic_names] +extra_tactics=[s for s in tactic_names if s not in order] +doc={'attack_spec':'enterprise-attack','attack_version':'20.1','source':'https://github.com/mitre-attack/attack-stix-data/blob/master/enterprise-attack/enterprise-attack-20.1.json','source_sha256':hashlib.sha256(raw).hexdigest(),'note':'Subset: only techniques named by Tawny rules or rules/attack/coverage.yaml. Regenerate with rules/attack/subset.py.','tactics':tactics,'techniques':out} +print(json.dumps(doc,indent=1,sort_keys=False)) +sys.stderr.write(f"used={len(used)} vendored={len(out)} missing={missing} extra_tactics={extra_tactics}\n") diff --git a/rules/attack/techniques.json b/rules/attack/techniques.json new file mode 100644 index 0000000..b647dfc --- /dev/null +++ b/rules/attack/techniques.json @@ -0,0 +1,3119 @@ +{ + "attack_spec": "enterprise-attack", + "attack_version": "20.1", + "source": "https://github.com/mitre-attack/attack-stix-data/blob/master/enterprise-attack/enterprise-attack-20.1.json", + "source_sha256": "539a843a7b53ed9749740b2123dddae3726b1a4831841c32aca740b011b910b5", + "note": "Subset: only techniques named by Tawny rules or rules/attack/coverage.yaml. Regenerate with rules/attack/subset.py.", + "tactics": [ + { + "shortname": "reconnaissance", + "name": "Reconnaissance", + "id": "TA0043" + }, + { + "shortname": "resource-development", + "name": "Resource Development", + "id": "TA0042" + }, + { + "shortname": "initial-access", + "name": "Initial Access", + "id": "TA0001" + }, + { + "shortname": "execution", + "name": "Execution", + "id": "TA0002" + }, + { + "shortname": "persistence", + "name": "Persistence", + "id": "TA0003" + }, + { + "shortname": "privilege-escalation", + "name": "Privilege Escalation", + "id": "TA0004" + }, + { + "shortname": "stealth", + "name": "Stealth", + "id": "TA0005" + }, + { + "shortname": "defense-impairment", + "name": "Defense Impairment", + "id": "TA0112" + }, + { + "shortname": "credential-access", + "name": "Credential Access", + "id": "TA0006" + }, + { + "shortname": "discovery", + "name": "Discovery", + "id": "TA0007" + }, + { + "shortname": "lateral-movement", + "name": "Lateral Movement", + "id": "TA0008" + }, + { + "shortname": "collection", + "name": "Collection", + "id": "TA0009" + }, + { + "shortname": "command-and-control", + "name": "Command and Control", + "id": "TA0011" + }, + { + "shortname": "exfiltration", + "name": "Exfiltration", + "id": "TA0010" + }, + { + "shortname": "impact", + "name": "Impact", + "id": "TA0040" + } + ], + "techniques": [ + { + "id": "T1003", + "name": "OS Credential Dumping", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1003.001", + "name": "OS Credential Dumping: LSASS Memory", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1003.002", + "name": "OS Credential Dumping: Security Account Manager", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1003.003", + "name": "OS Credential Dumping: NTDS", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1003.004", + "name": "OS Credential Dumping: LSA Secrets", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1003.005", + "name": "OS Credential Dumping: Cached Domain Credentials", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows", + "Linux" + ] + }, + { + "id": "T1003.006", + "name": "OS Credential Dumping: DCSync", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1003.008", + "name": "OS Credential Dumping: /etc/passwd and /etc/shadow", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Linux" + ] + }, + { + "id": "T1005", + "name": "Data from Local System", + "tactics": [ + "collection" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1007", + "name": "System Service Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1012", + "name": "Query Registry", + "tactics": [ + "discovery" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1016", + "name": "System Network Configuration Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1018", + "name": "Remote System Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1021", + "name": "Remote Services", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Linux", + "macOS", + "Windows", + "IaaS", + "ESXi" + ] + }, + { + "id": "T1021.001", + "name": "Remote Services: Remote Desktop Protocol", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1021.002", + "name": "Remote Services: SMB/Windows Admin Shares", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1021.003", + "name": "Remote Services: Distributed Component Object Model", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1021.004", + "name": "Remote Services: SSH", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1021.005", + "name": "Remote Services: VNC", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Linux", + "Windows", + "macOS" + ] + }, + { + "id": "T1021.006", + "name": "Remote Services: Windows Remote Management", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1027", + "name": "Obfuscated Files or Information", + "tactics": [ + "stealth" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1027.003", + "name": "Obfuscated Files or Information: Steganography", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1027.004", + "name": "Obfuscated Files or Information: Compile After Delivery", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1027.005", + "name": "Obfuscated Files or Information: Indicator Removal from Tools", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1027.009", + "name": "Obfuscated Files or Information: Embedded Payloads", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1027.010", + "name": "Obfuscated Files or Information: Command Obfuscation", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1033", + "name": "System Owner/User Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1036", + "name": "Masquerading", + "tactics": [ + "stealth" + ], + "platforms": [ + "Containers", + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1036.002", + "name": "Masquerading: Right-to-Left Override", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1036.003", + "name": "Masquerading: Rename Legitimate Utilities", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1036.004", + "name": "Masquerading: Masquerade Task or Service", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1036.005", + "name": "Masquerading: Match Legitimate Resource Name or Location", + "tactics": [ + "stealth" + ], + "platforms": [ + "Containers", + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1036.007", + "name": "Masquerading: Double File Extension", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1037.001", + "name": "Boot or Logon Initialization Scripts: Logon Script (Windows)", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1039", + "name": "Data from Network Shared Drive", + "tactics": [ + "collection" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1040", + "name": "Network Sniffing", + "tactics": [ + "credential-access", + "discovery" + ], + "platforms": [ + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1046", + "name": "Network Service Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Containers", + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1047", + "name": "Windows Management Instrumentation", + "tactics": [ + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1048", + "name": "Exfiltration Over Alternative Protocol", + "tactics": [ + "exfiltration" + ], + "platforms": [ + "ESXi", + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1048.001", + "name": "Exfiltration Over Alternative Protocol: Exfiltration Over Symmetric Encrypted Non-C2 Protocol", + "tactics": [ + "exfiltration" + ], + "platforms": [ + "Linux", + "macOS", + "Windows", + "ESXi" + ] + }, + { + "id": "T1048.003", + "name": "Exfiltration Over Alternative Protocol: Exfiltration Over Unencrypted Non-C2 Protocol", + "tactics": [ + "exfiltration" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1049", + "name": "System Network Connections Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1053", + "name": "Scheduled Task/Job", + "tactics": [ + "execution", + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Containers", + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1053.002", + "name": "Scheduled Task/Job: At", + "tactics": [ + "execution", + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows", + "Linux", + "macOS" + ] + }, + { + "id": "T1053.003", + "name": "Scheduled Task/Job: Cron", + "tactics": [ + "execution", + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Linux", + "macOS", + "ESXi" + ] + }, + { + "id": "T1053.005", + "name": "Scheduled Task/Job: Scheduled Task", + "tactics": [ + "execution", + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1055", + "name": "Process Injection", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1055.001", + "name": "Process Injection: Dynamic-link Library Injection", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1055.012", + "name": "Process Injection: Process Hollowing", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1056.002", + "name": "Input Capture: GUI Input Capture", + "tactics": [ + "collection", + "credential-access" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1057", + "name": "Process Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1059", + "name": "Command and Scripting Interpreter", + "tactics": [ + "execution" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Identity Provider", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1059.001", + "name": "Command and Scripting Interpreter: PowerShell", + "tactics": [ + "execution" + ], + "platforms": [ + "Windows", + "Linux", + "macOS" + ] + }, + { + "id": "T1059.003", + "name": "Command and Scripting Interpreter: Windows Command Shell", + "tactics": [ + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1059.004", + "name": "Command and Scripting Interpreter: Unix Shell", + "tactics": [ + "execution" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices" + ] + }, + { + "id": "T1059.005", + "name": "Command and Scripting Interpreter: Visual Basic", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1059.006", + "name": "Command and Scripting Interpreter: Python", + "tactics": [ + "execution" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1059.007", + "name": "Command and Scripting Interpreter: JavaScript", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1068", + "name": "Exploitation for Privilege Escalation", + "tactics": [ + "privilege-escalation" + ], + "platforms": [ + "Containers", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1069", + "name": "Permission Groups Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Containers", + "IaaS", + "Identity Provider", + "Linux", + "macOS", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1069.001", + "name": "Permission Groups Discovery: Local Groups", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1069.002", + "name": "Permission Groups Discovery: Domain Groups", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1070", + "name": "Indicator Removal", + "tactics": [ + "stealth" + ], + "platforms": [ + "Containers", + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "Windows" + ] + }, + { + "id": "T1070.003", + "name": "Indicator Removal: Clear Command History", + "tactics": [ + "stealth" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1070.004", + "name": "Indicator Removal: File Deletion", + "tactics": [ + "stealth" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1070.005", + "name": "Indicator Removal: Network Share Connection Removal", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1071", + "name": "Application Layer Protocol", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "Linux", + "macOS", + "Windows", + "Network Devices", + "ESXi" + ] + }, + { + "id": "T1071.001", + "name": "Application Layer Protocol: Web Protocols", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1071.004", + "name": "Application Layer Protocol: DNS", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1072", + "name": "Software Deployment Tools", + "tactics": [ + "execution", + "lateral-movement" + ], + "platforms": [ + "Linux", + "macOS", + "Network Devices", + "SaaS", + "Windows" + ] + }, + { + "id": "T1074.001", + "name": "Data Staged: Local Data Staging", + "tactics": [ + "collection" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1078", + "name": "Valid Accounts", + "tactics": [ + "stealth", + "persistence", + "privilege-escalation", + "initial-access" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Identity Provider", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1078.002", + "name": "Valid Accounts: Domain Accounts", + "tactics": [ + "stealth", + "persistence", + "privilege-escalation", + "initial-access" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1078.003", + "name": "Valid Accounts: Local Accounts", + "tactics": [ + "stealth", + "persistence", + "privilege-escalation", + "initial-access" + ], + "platforms": [ + "Containers", + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1082", + "name": "System Information Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1083", + "name": "File and Directory Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1087", + "name": "Account Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "IaaS", + "Identity Provider", + "Linux", + "macOS", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1087.001", + "name": "Account Discovery: Local Account", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1087.002", + "name": "Account Discovery: Domain Account", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1090", + "name": "Proxy", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1090.001", + "name": "Proxy: Internal Proxy", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1090.003", + "name": "Proxy: Multi-hop Proxy", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1095", + "name": "Non-Application Layer Protocol", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1098", + "name": "Account Manipulation", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Identity Provider", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1102", + "name": "Web Service", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1102.002", + "name": "Web Service: Bidirectional Communication", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1105", + "name": "Ingress Tool Transfer", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1106", + "name": "Native API", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1110", + "name": "Brute Force", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Identity Provider", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1110.001", + "name": "Brute Force: Password Guessing", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Identity Provider", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1110.002", + "name": "Brute Force: Password Cracking", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Identity Provider", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "Windows" + ] + }, + { + "id": "T1110.003", + "name": "Brute Force: Password Spraying", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Identity Provider", + "Linux", + "Network Devices", + "Office Suite", + "SaaS", + "Windows", + "macOS" + ] + }, + { + "id": "T1112", + "name": "Modify Registry", + "tactics": [ + "defense-impairment", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1113", + "name": "Screen Capture", + "tactics": [ + "collection" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1114", + "name": "Email Collection", + "tactics": [ + "collection" + ], + "platforms": [ + "Windows", + "macOS", + "Linux", + "Office Suite" + ] + }, + { + "id": "T1115", + "name": "Clipboard Data", + "tactics": [ + "collection" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1119", + "name": "Automated Collection", + "tactics": [ + "collection" + ], + "platforms": [ + "IaaS", + "Linux", + "macOS", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1120", + "name": "Peripheral Device Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1123", + "name": "Audio Capture", + "tactics": [ + "collection" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1124", + "name": "System Time Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1127", + "name": "Trusted Developer Utilities Proxy Execution", + "tactics": [ + "stealth", + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1132.001", + "name": "Data Encoding: Standard Encoding", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1133", + "name": "External Remote Services", + "tactics": [ + "persistence", + "initial-access" + ], + "platforms": [ + "Containers", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1134", + "name": "Access Token Manipulation", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1134.001", + "name": "Access Token Manipulation: Token Impersonation/Theft", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1134.002", + "name": "Access Token Manipulation: Create Process with Token", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1134.003", + "name": "Access Token Manipulation: Make and Impersonate Token", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1134.004", + "name": "Access Token Manipulation: Parent PID Spoofing", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1135", + "name": "Network Share Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1136.001", + "name": "Create Account: Local Account", + "tactics": [ + "persistence" + ], + "platforms": [ + "Containers", + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1136.002", + "name": "Create Account: Domain Account", + "tactics": [ + "persistence" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1140", + "name": "Deobfuscate/Decode Files or Information", + "tactics": [ + "stealth" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1176.001", + "name": "Software Extensions: Browser Extensions", + "tactics": [ + "persistence" + ], + "platforms": [ + "Linux", + "Windows", + "macOS" + ] + }, + { + "id": "T1185", + "name": "Browser Session Hijacking", + "tactics": [ + "collection" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1187", + "name": "Forced Authentication", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1190", + "name": "Exploit Public-Facing Application", + "tactics": [ + "initial-access" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1195.002", + "name": "Supply Chain Compromise: Compromise Software Supply Chain", + "tactics": [ + "initial-access" + ], + "platforms": [ + "Linux", + "Windows", + "macOS" + ] + }, + { + "id": "T1197", + "name": "BITS Jobs", + "tactics": [ + "stealth", + "persistence", + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1201", + "name": "Password Policy Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Windows", + "Linux", + "macOS", + "IaaS", + "Network Devices", + "Identity Provider", + "SaaS", + "Office Suite" + ] + }, + { + "id": "T1202", + "name": "Indirect Command Execution", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1203", + "name": "Exploitation for Client Execution", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1204", + "name": "User Execution", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "Windows", + "macOS", + "IaaS", + "Containers" + ] + }, + { + "id": "T1204.001", + "name": "User Execution: Malicious Link", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1204.002", + "name": "User Execution: Malicious File", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1204.004", + "name": "User Execution: Malicious Copy and Paste", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1210", + "name": "Exploitation of Remote Services", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Linux", + "Windows", + "macOS", + "ESXi" + ] + }, + { + "id": "T1211", + "name": "Exploitation for Stealth", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "Windows", + "macOS", + "SaaS", + "IaaS" + ] + }, + { + "id": "T1212", + "name": "Exploitation for Credential Access", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Linux", + "Windows", + "macOS", + "Identity Provider" + ] + }, + { + "id": "T1216", + "name": "System Script Proxy Execution", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1216.001", + "name": "System Script Proxy Execution: PubPrn", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1217", + "name": "Browser Information Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1218", + "name": "System Binary Proxy Execution", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1218.001", + "name": "System Binary Proxy Execution: Compiled HTML File", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.002", + "name": "System Binary Proxy Execution: Control Panel", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.003", + "name": "System Binary Proxy Execution: CMSTP", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.005", + "name": "System Binary Proxy Execution: Mshta", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.007", + "name": "System Binary Proxy Execution: Msiexec", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.008", + "name": "System Binary Proxy Execution: Odbcconf", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.009", + "name": "System Binary Proxy Execution: Regsvcs/Regasm", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.010", + "name": "System Binary Proxy Execution: Regsvr32", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.011", + "name": "System Binary Proxy Execution: Rundll32", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.013", + "name": "System Binary Proxy Execution: Mavinject", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.014", + "name": "System Binary Proxy Execution: MMC", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1219", + "name": "Remote Access Tools", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1219.002", + "name": "Remote Access Tools: Remote Desktop Software", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1220", + "name": "XSL Script Processing", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1222.001", + "name": "File and Directory Permissions Modification: Windows Permissions", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1482", + "name": "Domain Trust Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1484.001", + "name": "Domain or Tenant Policy Modification: Group Policy Modification", + "tactics": [ + "defense-impairment", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1485", + "name": "Data Destruction", + "tactics": [ + "impact" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1486", + "name": "Data Encrypted for Impact", + "tactics": [ + "impact" + ], + "platforms": [ + "ESXi", + "IaaS", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1489", + "name": "Service Stop", + "tactics": [ + "impact" + ], + "platforms": [ + "ESXi", + "IaaS", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1490", + "name": "Inhibit System Recovery", + "tactics": [ + "impact" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1491.001", + "name": "Defacement: Internal Defacement", + "tactics": [ + "impact" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1496", + "name": "Resource Hijacking", + "tactics": [ + "impact" + ], + "platforms": [ + "Windows", + "IaaS", + "Linux", + "macOS", + "Containers", + "SaaS" + ] + }, + { + "id": "T1505.002", + "name": "Server Software Component: Transport Agent", + "tactics": [ + "persistence" + ], + "platforms": [ + "Linux", + "Windows" + ] + }, + { + "id": "T1505.003", + "name": "Server Software Component: Web Shell", + "tactics": [ + "persistence" + ], + "platforms": [ + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1505.004", + "name": "Server Software Component: IIS Components", + "tactics": [ + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1505.005", + "name": "Server Software Component: Terminal Services DLL", + "tactics": [ + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1518", + "name": "Software Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "IaaS", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1518.001", + "name": "Software Discovery: Security Software Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "IaaS", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1526", + "name": "Cloud Service Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "IaaS", + "Identity Provider", + "Office Suite", + "SaaS" + ] + }, + { + "id": "T1528", + "name": "Steal Application Access Token", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Containers", + "IaaS", + "Identity Provider", + "Office Suite", + "SaaS" + ] + }, + { + "id": "T1529", + "name": "System Shutdown/Reboot", + "tactics": [ + "impact" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1539", + "name": "Steal Web Session Cookie", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Linux", + "macOS", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1542.001", + "name": "Pre-OS Boot: System Firmware", + "tactics": [ + "stealth", + "persistence" + ], + "platforms": [ + "Network Devices", + "Windows" + ] + }, + { + "id": "T1542.003", + "name": "Pre-OS Boot: Bootkit", + "tactics": [ + "stealth", + "persistence" + ], + "platforms": [ + "Linux", + "Windows" + ] + }, + { + "id": "T1543", + "name": "Create or Modify System Process", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Containers", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1543.001", + "name": "Create or Modify System Process: Launch Agent", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "macOS" + ] + }, + { + "id": "T1543.003", + "name": "Create or Modify System Process: Windows Service", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1543.004", + "name": "Create or Modify System Process: Launch Daemon", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "macOS" + ] + }, + { + "id": "T1546", + "name": "Event Triggered Execution", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Linux", + "macOS", + "Windows", + "SaaS", + "IaaS", + "Office Suite" + ] + }, + { + "id": "T1546.001", + "name": "Event Triggered Execution: Change Default File Association", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1546.002", + "name": "Event Triggered Execution: Screensaver", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1546.003", + "name": "Event Triggered Execution: Windows Management Instrumentation Event Subscription", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1546.004", + "name": "Event Triggered Execution: Unix Shell Configuration Modification", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Linux", + "macOS" + ] + }, + { + "id": "T1546.007", + "name": "Event Triggered Execution: Netsh Helper DLL", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1546.008", + "name": "Event Triggered Execution: Accessibility Features", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1546.011", + "name": "Event Triggered Execution: Application Shimming", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1546.015", + "name": "Event Triggered Execution: Component Object Model Hijacking", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1547", + "name": "Boot or Logon Autostart Execution", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Linux", + "macOS", + "Windows", + "Network Devices" + ] + }, + { + "id": "T1547.001", + "name": "Boot or Logon Autostart Execution: Registry Run Keys / Startup Folder", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1547.002", + "name": "Boot or Logon Autostart Execution: Authentication Package", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1547.010", + "name": "Boot or Logon Autostart Execution: Port Monitors", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1547.014", + "name": "Boot or Logon Autostart Execution: Active Setup", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1548", + "name": "Abuse Elevation Control Mechanism", + "tactics": [ + "privilege-escalation" + ], + "platforms": [ + "Linux", + "macOS", + "Windows", + "IaaS", + "Office Suite", + "Identity Provider" + ] + }, + { + "id": "T1548.002", + "name": "Abuse Elevation Control Mechanism: Bypass User Account Control", + "tactics": [ + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1550.003", + "name": "Use Alternate Authentication Material: Pass the Ticket", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1552", + "name": "Unsecured Credentials", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows", + "SaaS", + "IaaS", + "Linux", + "macOS", + "Containers", + "Network Devices", + "Office Suite", + "Identity Provider" + ] + }, + { + "id": "T1552.001", + "name": "Unsecured Credentials: Credentials In Files", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Containers", + "IaaS", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1552.002", + "name": "Unsecured Credentials: Credentials in Registry", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1552.004", + "name": "Unsecured Credentials: Private Keys", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1552.006", + "name": "Unsecured Credentials: Group Policy Preferences", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1553", + "name": "Subvert Trust Controls", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1553.004", + "name": "Subvert Trust Controls: Install Root Certificate", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1553.005", + "name": "Subvert Trust Controls: Mark-of-the-Web Bypass", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1555", + "name": "Credentials from Password Stores", + "tactics": [ + "credential-access" + ], + "platforms": [ + "IaaS", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1555.003", + "name": "Credentials from Password Stores: Credentials from Web Browsers", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1555.004", + "name": "Credentials from Password Stores: Windows Credential Manager", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1556.002", + "name": "Modify Authentication Process: Password Filter DLL", + "tactics": [ + "defense-impairment", + "persistence", + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1557", + "name": "Adversary-in-the-Middle", + "tactics": [ + "credential-access", + "collection" + ], + "platforms": [ + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1557.001", + "name": "Adversary-in-the-Middle: Name Resolution Poisoning and SMB Relay", + "tactics": [ + "credential-access", + "collection" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1558.003", + "name": "Steal or Forge Kerberos Tickets: Kerberoasting", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1560", + "name": "Archive Collected Data", + "tactics": [ + "collection" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1560.001", + "name": "Archive Collected Data: Archive via Utility", + "tactics": [ + "collection" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1563.002", + "name": "Remote Service Session Hijacking: RDP Hijacking", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1564", + "name": "Hide Artifacts", + "tactics": [ + "stealth" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Office Suite", + "Windows" + ] + }, + { + "id": "T1564.001", + "name": "Hide Artifacts: Hidden Files and Directories", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1564.002", + "name": "Hide Artifacts: Hidden Users", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1564.003", + "name": "Hide Artifacts: Hidden Window", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1564.004", + "name": "Hide Artifacts: NTFS File Attributes", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1564.006", + "name": "Hide Artifacts: Run Virtual Instance", + "tactics": [ + "stealth" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1566", + "name": "Phishing", + "tactics": [ + "initial-access" + ], + "platforms": [ + "Identity Provider", + "Linux", + "macOS", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1566.001", + "name": "Phishing: Spearphishing Attachment", + "tactics": [ + "initial-access" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1567", + "name": "Exfiltration Over Web Service", + "tactics": [ + "exfiltration" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1567.002", + "name": "Exfiltration Over Web Service: Exfiltration to Cloud Storage", + "tactics": [ + "exfiltration" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1568", + "name": "Dynamic Resolution", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1569", + "name": "System Services", + "tactics": [ + "execution" + ], + "platforms": [ + "Windows", + "macOS", + "Linux" + ] + }, + { + "id": "T1569.002", + "name": "System Services: Service Execution", + "tactics": [ + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1570", + "name": "Lateral Tool Transfer", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1572", + "name": "Protocol Tunneling", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1574", + "name": "Hijack Execution Flow", + "tactics": [ + "stealth", + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1574.001", + "name": "Hijack Execution Flow: DLL", + "tactics": [ + "stealth", + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1574.005", + "name": "Hijack Execution Flow: Executable Installer File Permissions Weakness", + "tactics": [ + "stealth", + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1574.007", + "name": "Hijack Execution Flow: Path Interception by PATH Environment Variable", + "tactics": [ + "stealth", + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1574.008", + "name": "Hijack Execution Flow: Path Interception by Search Order Hijacking", + "tactics": [ + "stealth", + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1574.011", + "name": "Hijack Execution Flow: Services Registry Permissions Weakness", + "tactics": [ + "stealth", + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1587", + "name": "Develop Capabilities", + "tactics": [ + "resource-development" + ], + "platforms": [ + "PRE" + ] + }, + { + "id": "T1587.001", + "name": "Develop Capabilities: Malware", + "tactics": [ + "resource-development" + ], + "platforms": [ + "PRE" + ] + }, + { + "id": "T1588.002", + "name": "Obtain Capabilities: Tool", + "tactics": [ + "resource-development" + ], + "platforms": [ + "PRE" + ] + }, + { + "id": "T1590.001", + "name": "Gather Victim Network Information: Domain Properties", + "tactics": [ + "reconnaissance" + ], + "platforms": [ + "PRE" + ] + }, + { + "id": "T1593.003", + "name": "Search Open Websites/Domains: Code Repositories", + "tactics": [ + "reconnaissance" + ], + "platforms": [ + "PRE" + ] + }, + { + "id": "T1595", + "name": "Active Scanning", + "tactics": [ + "reconnaissance" + ], + "platforms": [ + "PRE" + ] + }, + { + "id": "T1608", + "name": "Stage Capabilities", + "tactics": [ + "resource-development" + ], + "platforms": [ + "PRE" + ] + }, + { + "id": "T1614.001", + "name": "System Location Discovery: System Language Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1615", + "name": "Group Policy Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1620", + "name": "Reflective Code Loading", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1622", + "name": "Debugger Evasion", + "tactics": [ + "stealth", + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1649", + "name": "Steal or Forge Authentication Certificates", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows", + "Linux", + "macOS", + "Identity Provider" + ] + }, + { + "id": "T1685", + "name": "Disable or Modify Tools", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1685.001", + "name": "Disable or Modify Tools: Disable or Modify Windows Event Log", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1685.005", + "name": "Disable or Modify Tools: Clear Windows Event Logs", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1686.003", + "name": "Disable or Modify System Firewall: Windows Host Firewall", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1689", + "name": "Downgrade Attack", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "macOS", + "Windows", + "Linux" + ] + } + ] +} diff --git a/server/src/db/migrate.zig b/server/src/db/migrate.zig index 529e534..aa8038f 100644 --- a/server/src/db/migrate.zig +++ b/server/src/db/migrate.zig @@ -15,6 +15,8 @@ const windows_response_sql = @embedFile("migrations/0006_windows_response.sql"); const windows_response_version = "0006_windows_response"; const agent_hardening_sql = @embedFile("migrations/0007_agent_hardening.sql"); const agent_hardening_version = "0007_agent_hardening"; +const server_analyst_sql = @embedFile("migrations/0008_server_analyst.sql"); +const server_analyst_version = "0008_server_analyst"; pub fn apply(allocator: std.mem.Allocator, conn: *pg.Conn) !void { try conn.execSimple( @@ -34,6 +36,7 @@ pub fn apply(allocator: std.mem.Allocator, conn: *pg.Conn) !void { try applyScript(allocator, conn, detection_engine_version, detection_engine_sql, true); try applyScript(allocator, conn, windows_response_version, windows_response_sql, true); try applyScript(allocator, conn, agent_hardening_version, agent_hardening_sql, true); + try applyScript(allocator, conn, server_analyst_version, server_analyst_sql, true); try conn.execSimple("GRANT EXECUTE ON FUNCTION tawny_purge_expired(timestamptz) TO tawny_jobs"); try ensurePartitions(conn); } @@ -170,7 +173,8 @@ pub fn migrationsCurrent(allocator: std.mem.Allocator, conn: *pg.Conn) !bool { return try migrationApplied(allocator, conn, migration_version) and try migrationApplied(allocator, conn, purge_version) and try migrationApplied(allocator, conn, ai_reasoning_version) and - try migrationApplied(allocator, conn, process_entities_version); + try migrationApplied(allocator, conn, process_entities_version) and + try migrationApplied(allocator, conn, server_analyst_version); } test "civil month of the zig 0.17 release day" { diff --git a/server/src/db/migrations/0008_server_analyst.sql b/server/src/db/migrations/0008_server_analyst.sql new file mode 100644 index 0000000..7bcf954 --- /dev/null +++ b/server/src/db/migrations/0008_server_analyst.sql @@ -0,0 +1,126 @@ +-- Server analyst work (#60): analyst role, tenant settings, Entra ID sign-in, +-- incidents. Applied as one simple-query script in a transaction. + +-- Analyst role (docs/api.md has the permission matrix). +ALTER TABLE users DROP CONSTRAINT IF EXISTS users_role_check; +ALTER TABLE users ADD CONSTRAINT users_role_check CHECK (role IN ('admin', 'analyst', 'viewer')); + +-- Break-glass admins keep password sign-in when the tenant limits it. +ALTER TABLE users ADD COLUMN break_glass boolean NOT NULL DEFAULT false; +-- Entra ID identity: object id and tenant id from the ID token. Never email. +ALTER TABLE users ADD COLUMN oidc_tid text; +ALTER TABLE users ADD COLUMN oidc_oid text; +CREATE UNIQUE INDEX users_oidc_identity_idx ON users (oidc_tid, oidc_oid) WHERE oidc_oid IS NOT NULL; +-- The bootstrap admin is the first break-glass account. +UPDATE users SET break_glass = true WHERE role = 'admin' AND password_hash IS NOT NULL + AND id = (SELECT id FROM users WHERE role = 'admin' ORDER BY created_at LIMIT 1); + +CREATE TABLE tenant_settings ( + tenant_id uuid PRIMARY KEY REFERENCES tenants (id), + -- 'all': every user with a password may sign in with it. + -- 'break_glass': only admins marked break_glass may. + password_login text NOT NULL DEFAULT 'all' CHECK (password_login IN ('all', 'break_glass')), + -- Destructive actions (isolate, quarantine) requested by an analyst wait + -- for an admin to approve them (target-edr section 9.2). + analyst_destructive_needs_approval boolean NOT NULL DEFAULT false, + updated_at timestamptz NOT NULL DEFAULT now() +); + +-- One Entra ID (OIDC) configuration per Tawny tenant. +CREATE TABLE tenant_oidc ( + tenant_id uuid PRIMARY KEY REFERENCES tenants (id), + enabled boolean NOT NULL DEFAULT false, + entra_tenant_id text NOT NULL CHECK (length(entra_tenant_id) BETWEEN 1 AND 100), + -- Null means https://login.microsoftonline.com//v2.0. + authority text, + client_id text NOT NULL CHECK (length(client_id) BETWEEN 1 AND 200), + -- secret_box v1 ciphertext under TAWNY_INTEGRATION_ENCRYPTION_KEY. + client_secret_encrypted text, + allowed_domains text[] NOT NULL DEFAULT '{}', + -- {"": "admin" | "analyst" | "viewer"} + group_roles jsonb NOT NULL DEFAULT '{}'::jsonb, + discovery_json jsonb, + jwks_json jsonb, + jwks_fetched_at timestamptz, + updated_at timestamptz NOT NULL DEFAULT now() +); + +-- oauth_states serves GitHub and OIDC. OIDC rows also carry the nonce and +-- the Tawny tenant the sign-in started for. +ALTER TABLE oauth_states ADD COLUMN provider text NOT NULL DEFAULT 'github'; +ALTER TABLE oauth_states ADD COLUMN nonce text; +ALTER TABLE oauth_states ADD COLUMN tenant_id uuid; + +-- Response approval (target-edr section 9.2, last line). +ALTER TABLE response_actions ADD COLUMN approved_by_user_id uuid; +ALTER TABLE response_actions ADD COLUMN approved_at timestamptz; + +-- Alert triage. +ALTER TABLE alerts ADD COLUMN acknowledged_at timestamptz; +ALTER TABLE alerts ADD COLUMN acknowledged_by_user_id uuid; +ALTER TABLE alerts ADD COLUMN resolved_at timestamptz; +ALTER TABLE alerts ADD COLUMN resolved_by_user_id uuid; + +-- Incidents (target-edr sections 7 and 8). +CREATE TABLE incidents ( + id uuid PRIMARY KEY, + tenant_id uuid NOT NULL REFERENCES tenants (id), + title text NOT NULL, + status text NOT NULL DEFAULT 'new' CHECK (status IN ('new', 'investigating', 'resolved', 'false_positive')), + severity text NOT NULL CHECK (severity IN ('low', 'medium', 'high', 'critical')), + risk integer NOT NULL CHECK (risk BETWEEN 0 AND 100), + -- [{"key","kind","label","weight","confidence","context","points"}] + risk_items jsonb NOT NULL DEFAULT '[]'::jsonb, + owner_user_id uuid REFERENCES users (id) ON DELETE SET NULL, + -- Which section 8 rule opened the incident: lineage, artefact, indicator, alert. + grouping text NOT NULL, + root_entity_id text, + agent_ids uuid[] NOT NULL DEFAULT '{}', + users text[] NOT NULL DEFAULT '{}', + techniques text[] NOT NULL DEFAULT '{}', + first_seen_at timestamptz NOT NULL, + last_seen_at timestamptz NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + soc_case_status text NOT NULL DEFAULT 'not_configured', + soc_synced_at timestamptz, + soc_error text +); + +CREATE INDEX incidents_tenant_seen_idx ON incidents (tenant_id, last_seen_at DESC); +CREATE INDEX incidents_open_idx ON incidents (tenant_id, last_seen_at) WHERE status IN ('new', 'investigating'); + +CREATE TABLE incident_alerts ( + tenant_id uuid NOT NULL REFERENCES tenants (id), + incident_id uuid NOT NULL REFERENCES incidents (id) ON DELETE CASCADE, + alert_id bigint NOT NULL REFERENCES alerts (id) ON DELETE CASCADE, + agent_id uuid NOT NULL, + -- Evidence keys the grouper matched on: "root:", "sha256:", + -- "domain:", "ip:", "user:". + keys text[] NOT NULL DEFAULT '{}', + reason text NOT NULL, + occurred_at timestamptz NOT NULL, + added_at timestamptz NOT NULL, + PRIMARY KEY (incident_id, alert_id) +); + +CREATE UNIQUE INDEX incident_alerts_alert_idx ON incident_alerts (alert_id); +CREATE INDEX incident_alerts_keys_idx ON incident_alerts USING gin (keys); +CREATE INDEX incident_alerts_tenant_time_idx ON incident_alerts (tenant_id, occurred_at DESC); + +DO $$ +DECLARE + t text; +BEGIN + FOREACH t IN ARRAY ARRAY['tenant_settings', 'tenant_oidc', 'incidents', 'incident_alerts'] + LOOP + EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', t); + EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY', t); + EXECUTE format('DROP POLICY IF EXISTS tenant_isolation ON %I', t); + EXECUTE format( + 'CREATE POLICY tenant_isolation ON %I USING (tenant_id = tawny_current_tenant()) WITH CHECK (tenant_id = tawny_current_tenant())', + t); + END LOOP; +END $$; + +GRANT SELECT, INSERT, UPDATE, DELETE ON tenant_settings, tenant_oidc, incidents, incident_alerts TO tawny_app, tawny_jobs; diff --git a/server/src/detect/attack/coverage.yaml b/server/src/detect/attack/coverage.yaml new file mode 100644 index 0000000..be1b20b --- /dev/null +++ b/server/src/detect/attack/coverage.yaml @@ -0,0 +1,172 @@ +# ATT&CK coverage map (docs/architecture/target-edr.md section 6). +# +# For each technique: the event types whose telemetry can show it, and the +# response actions that apply to it. Names and tactics come from +# techniques.json, a subset of ATT&CK Enterprise 20.1 (see README.md). +# +# GET /api/attack/coverage reports three states per technique, each from +# its own source and never from another state: +# telemetry an agent seen in the last 15 minutes, with no failed sensor, +# sent one of these event types in the last 24 hours +# detection an enabled rule lists the technique (mitre_techniques) +# response one of the listed actions is supported on the platform +# +# Keep event types to schemas/events and actions to the ones the agent runs +# (agent/src/response_actions.zig). Platforms limit where an action applies. +attack_version: "20.1" +actions: + kill_process: [windows, linux, macos] + suspend_process: [windows, linux, macos] + quarantine_file: [windows, linux, macos] + isolate_host: [windows] +techniques: + - id: T1059.001 + telemetry: [process_start, powershell_script_block] + response: [kill_process, suspend_process, isolate_host] + - id: T1059.003 + telemetry: [process_start] + response: [kill_process, suspend_process] + - id: T1059.004 + telemetry: [process_start] + response: [kill_process, suspend_process] + - id: T1059.005 + telemetry: [process_start] + response: [kill_process, quarantine_file] + - id: T1059.007 + telemetry: [process_start] + response: [kill_process, quarantine_file] + - id: T1204.002 + telemetry: [process_start, file_create] + response: [kill_process, quarantine_file, isolate_host] + - id: T1566.001 + telemetry: [file_create, process_start] + response: [quarantine_file, isolate_host] + - id: T1047 + telemetry: [process_start] + response: [kill_process] + - id: T1053.005 + telemetry: [process_start] + response: [kill_process] + - id: T1053.003 + telemetry: [process_start, file_create] + response: [kill_process] + - id: T1543.003 + telemetry: [service_create] + response: [quarantine_file, isolate_host] + - id: T1543.001 + telemetry: [file_create] + response: [quarantine_file] + - id: T1543.004 + telemetry: [file_create] + response: [quarantine_file] + - id: T1569.002 + telemetry: [service_create, process_start] + response: [kill_process] + - id: T1547.001 + telemetry: [registry_set, file_create] + response: [quarantine_file] + - id: T1112 + telemetry: [registry_set] + response: [] + - id: T1546.004 + telemetry: [file_create] + response: [] + - id: T1548.002 + telemetry: [process_start, registry_set] + response: [kill_process] + - id: T1055 + telemetry: [] + response: [kill_process, isolate_host] + - id: T1027 + telemetry: [process_start, powershell_script_block] + response: [kill_process] + - id: T1036 + telemetry: [process_start] + response: [kill_process, quarantine_file] + - id: T1218 + telemetry: [process_start] + response: [kill_process] + - id: T1218.011 + telemetry: [process_start] + response: [kill_process] + - id: T1574.001 + telemetry: [file_create] + response: [quarantine_file] + - id: T1070 + telemetry: [process_start] + response: [] + - id: T1685 + telemetry: [sensor_health, agent_tamper, process_start] + response: [isolate_host] + - id: T1685.001 + telemetry: [sensor_health, agent_tamper] + response: [isolate_host] + - id: T1003.001 + telemetry: [process_start] + response: [kill_process, isolate_host] + - id: T1003.008 + telemetry: [process_start] + response: [kill_process] + - id: T1110 + telemetry: [user_logon] + response: [isolate_host] + - id: T1110.001 + telemetry: [user_logon] + response: [] + - id: T1110.003 + telemetry: [user_logon] + response: [] + - id: T1078 + telemetry: [user_logon] + response: [isolate_host] + - id: T1078.003 + telemetry: [user_logon] + response: [] + - id: T1098 + telemetry: [] + response: [] + - id: T1136.001 + telemetry: [process_start] + response: [] + - id: T1021.001 + telemetry: [user_logon, network_connect] + response: [isolate_host] + - id: T1021.002 + telemetry: [user_logon, network_connect] + response: [isolate_host] + - id: T1021.004 + telemetry: [user_logon, network_connect] + response: [kill_process] + - id: T1046 + telemetry: [network_connect] + response: [kill_process, isolate_host] + - id: T1082 + telemetry: [process_start] + response: [] + - id: T1033 + telemetry: [process_start] + response: [] + - id: T1071 + telemetry: [network_connect, dns_query] + response: [kill_process, isolate_host] + - id: T1071.001 + telemetry: [network_connect, dns_query] + response: [kill_process, isolate_host] + - id: T1071.004 + telemetry: [dns_query] + response: [kill_process, isolate_host] + - id: T1568 + telemetry: [dns_query] + response: [isolate_host] + - id: T1105 + telemetry: [process_start, file_create, network_connect] + response: [kill_process, quarantine_file, isolate_host] + - id: T1219 + telemetry: [process_start, network_connect] + response: [kill_process, quarantine_file] + - id: T1486 + telemetry: [file_create] + response: [kill_process, isolate_host] + - id: T1490 + telemetry: [process_start] + response: [kill_process, isolate_host] diff --git a/server/src/detect/attack/techniques.json b/server/src/detect/attack/techniques.json new file mode 100644 index 0000000..b647dfc --- /dev/null +++ b/server/src/detect/attack/techniques.json @@ -0,0 +1,3119 @@ +{ + "attack_spec": "enterprise-attack", + "attack_version": "20.1", + "source": "https://github.com/mitre-attack/attack-stix-data/blob/master/enterprise-attack/enterprise-attack-20.1.json", + "source_sha256": "539a843a7b53ed9749740b2123dddae3726b1a4831841c32aca740b011b910b5", + "note": "Subset: only techniques named by Tawny rules or rules/attack/coverage.yaml. Regenerate with rules/attack/subset.py.", + "tactics": [ + { + "shortname": "reconnaissance", + "name": "Reconnaissance", + "id": "TA0043" + }, + { + "shortname": "resource-development", + "name": "Resource Development", + "id": "TA0042" + }, + { + "shortname": "initial-access", + "name": "Initial Access", + "id": "TA0001" + }, + { + "shortname": "execution", + "name": "Execution", + "id": "TA0002" + }, + { + "shortname": "persistence", + "name": "Persistence", + "id": "TA0003" + }, + { + "shortname": "privilege-escalation", + "name": "Privilege Escalation", + "id": "TA0004" + }, + { + "shortname": "stealth", + "name": "Stealth", + "id": "TA0005" + }, + { + "shortname": "defense-impairment", + "name": "Defense Impairment", + "id": "TA0112" + }, + { + "shortname": "credential-access", + "name": "Credential Access", + "id": "TA0006" + }, + { + "shortname": "discovery", + "name": "Discovery", + "id": "TA0007" + }, + { + "shortname": "lateral-movement", + "name": "Lateral Movement", + "id": "TA0008" + }, + { + "shortname": "collection", + "name": "Collection", + "id": "TA0009" + }, + { + "shortname": "command-and-control", + "name": "Command and Control", + "id": "TA0011" + }, + { + "shortname": "exfiltration", + "name": "Exfiltration", + "id": "TA0010" + }, + { + "shortname": "impact", + "name": "Impact", + "id": "TA0040" + } + ], + "techniques": [ + { + "id": "T1003", + "name": "OS Credential Dumping", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1003.001", + "name": "OS Credential Dumping: LSASS Memory", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1003.002", + "name": "OS Credential Dumping: Security Account Manager", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1003.003", + "name": "OS Credential Dumping: NTDS", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1003.004", + "name": "OS Credential Dumping: LSA Secrets", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1003.005", + "name": "OS Credential Dumping: Cached Domain Credentials", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows", + "Linux" + ] + }, + { + "id": "T1003.006", + "name": "OS Credential Dumping: DCSync", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1003.008", + "name": "OS Credential Dumping: /etc/passwd and /etc/shadow", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Linux" + ] + }, + { + "id": "T1005", + "name": "Data from Local System", + "tactics": [ + "collection" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1007", + "name": "System Service Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1012", + "name": "Query Registry", + "tactics": [ + "discovery" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1016", + "name": "System Network Configuration Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1018", + "name": "Remote System Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1021", + "name": "Remote Services", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Linux", + "macOS", + "Windows", + "IaaS", + "ESXi" + ] + }, + { + "id": "T1021.001", + "name": "Remote Services: Remote Desktop Protocol", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1021.002", + "name": "Remote Services: SMB/Windows Admin Shares", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1021.003", + "name": "Remote Services: Distributed Component Object Model", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1021.004", + "name": "Remote Services: SSH", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1021.005", + "name": "Remote Services: VNC", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Linux", + "Windows", + "macOS" + ] + }, + { + "id": "T1021.006", + "name": "Remote Services: Windows Remote Management", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1027", + "name": "Obfuscated Files or Information", + "tactics": [ + "stealth" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1027.003", + "name": "Obfuscated Files or Information: Steganography", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1027.004", + "name": "Obfuscated Files or Information: Compile After Delivery", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1027.005", + "name": "Obfuscated Files or Information: Indicator Removal from Tools", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1027.009", + "name": "Obfuscated Files or Information: Embedded Payloads", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1027.010", + "name": "Obfuscated Files or Information: Command Obfuscation", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1033", + "name": "System Owner/User Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1036", + "name": "Masquerading", + "tactics": [ + "stealth" + ], + "platforms": [ + "Containers", + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1036.002", + "name": "Masquerading: Right-to-Left Override", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1036.003", + "name": "Masquerading: Rename Legitimate Utilities", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1036.004", + "name": "Masquerading: Masquerade Task or Service", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1036.005", + "name": "Masquerading: Match Legitimate Resource Name or Location", + "tactics": [ + "stealth" + ], + "platforms": [ + "Containers", + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1036.007", + "name": "Masquerading: Double File Extension", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1037.001", + "name": "Boot or Logon Initialization Scripts: Logon Script (Windows)", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1039", + "name": "Data from Network Shared Drive", + "tactics": [ + "collection" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1040", + "name": "Network Sniffing", + "tactics": [ + "credential-access", + "discovery" + ], + "platforms": [ + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1046", + "name": "Network Service Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Containers", + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1047", + "name": "Windows Management Instrumentation", + "tactics": [ + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1048", + "name": "Exfiltration Over Alternative Protocol", + "tactics": [ + "exfiltration" + ], + "platforms": [ + "ESXi", + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1048.001", + "name": "Exfiltration Over Alternative Protocol: Exfiltration Over Symmetric Encrypted Non-C2 Protocol", + "tactics": [ + "exfiltration" + ], + "platforms": [ + "Linux", + "macOS", + "Windows", + "ESXi" + ] + }, + { + "id": "T1048.003", + "name": "Exfiltration Over Alternative Protocol: Exfiltration Over Unencrypted Non-C2 Protocol", + "tactics": [ + "exfiltration" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1049", + "name": "System Network Connections Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1053", + "name": "Scheduled Task/Job", + "tactics": [ + "execution", + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Containers", + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1053.002", + "name": "Scheduled Task/Job: At", + "tactics": [ + "execution", + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows", + "Linux", + "macOS" + ] + }, + { + "id": "T1053.003", + "name": "Scheduled Task/Job: Cron", + "tactics": [ + "execution", + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Linux", + "macOS", + "ESXi" + ] + }, + { + "id": "T1053.005", + "name": "Scheduled Task/Job: Scheduled Task", + "tactics": [ + "execution", + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1055", + "name": "Process Injection", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1055.001", + "name": "Process Injection: Dynamic-link Library Injection", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1055.012", + "name": "Process Injection: Process Hollowing", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1056.002", + "name": "Input Capture: GUI Input Capture", + "tactics": [ + "collection", + "credential-access" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1057", + "name": "Process Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1059", + "name": "Command and Scripting Interpreter", + "tactics": [ + "execution" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Identity Provider", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1059.001", + "name": "Command and Scripting Interpreter: PowerShell", + "tactics": [ + "execution" + ], + "platforms": [ + "Windows", + "Linux", + "macOS" + ] + }, + { + "id": "T1059.003", + "name": "Command and Scripting Interpreter: Windows Command Shell", + "tactics": [ + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1059.004", + "name": "Command and Scripting Interpreter: Unix Shell", + "tactics": [ + "execution" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices" + ] + }, + { + "id": "T1059.005", + "name": "Command and Scripting Interpreter: Visual Basic", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1059.006", + "name": "Command and Scripting Interpreter: Python", + "tactics": [ + "execution" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1059.007", + "name": "Command and Scripting Interpreter: JavaScript", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1068", + "name": "Exploitation for Privilege Escalation", + "tactics": [ + "privilege-escalation" + ], + "platforms": [ + "Containers", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1069", + "name": "Permission Groups Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Containers", + "IaaS", + "Identity Provider", + "Linux", + "macOS", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1069.001", + "name": "Permission Groups Discovery: Local Groups", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1069.002", + "name": "Permission Groups Discovery: Domain Groups", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1070", + "name": "Indicator Removal", + "tactics": [ + "stealth" + ], + "platforms": [ + "Containers", + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "Windows" + ] + }, + { + "id": "T1070.003", + "name": "Indicator Removal: Clear Command History", + "tactics": [ + "stealth" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1070.004", + "name": "Indicator Removal: File Deletion", + "tactics": [ + "stealth" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1070.005", + "name": "Indicator Removal: Network Share Connection Removal", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1071", + "name": "Application Layer Protocol", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "Linux", + "macOS", + "Windows", + "Network Devices", + "ESXi" + ] + }, + { + "id": "T1071.001", + "name": "Application Layer Protocol: Web Protocols", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1071.004", + "name": "Application Layer Protocol: DNS", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1072", + "name": "Software Deployment Tools", + "tactics": [ + "execution", + "lateral-movement" + ], + "platforms": [ + "Linux", + "macOS", + "Network Devices", + "SaaS", + "Windows" + ] + }, + { + "id": "T1074.001", + "name": "Data Staged: Local Data Staging", + "tactics": [ + "collection" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1078", + "name": "Valid Accounts", + "tactics": [ + "stealth", + "persistence", + "privilege-escalation", + "initial-access" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Identity Provider", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1078.002", + "name": "Valid Accounts: Domain Accounts", + "tactics": [ + "stealth", + "persistence", + "privilege-escalation", + "initial-access" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1078.003", + "name": "Valid Accounts: Local Accounts", + "tactics": [ + "stealth", + "persistence", + "privilege-escalation", + "initial-access" + ], + "platforms": [ + "Containers", + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1082", + "name": "System Information Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1083", + "name": "File and Directory Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1087", + "name": "Account Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "IaaS", + "Identity Provider", + "Linux", + "macOS", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1087.001", + "name": "Account Discovery: Local Account", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1087.002", + "name": "Account Discovery: Domain Account", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1090", + "name": "Proxy", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1090.001", + "name": "Proxy: Internal Proxy", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1090.003", + "name": "Proxy: Multi-hop Proxy", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1095", + "name": "Non-Application Layer Protocol", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1098", + "name": "Account Manipulation", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Identity Provider", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1102", + "name": "Web Service", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1102.002", + "name": "Web Service: Bidirectional Communication", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1105", + "name": "Ingress Tool Transfer", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1106", + "name": "Native API", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1110", + "name": "Brute Force", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Identity Provider", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1110.001", + "name": "Brute Force: Password Guessing", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Identity Provider", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1110.002", + "name": "Brute Force: Password Cracking", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Identity Provider", + "Linux", + "macOS", + "Network Devices", + "Office Suite", + "Windows" + ] + }, + { + "id": "T1110.003", + "name": "Brute Force: Password Spraying", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Identity Provider", + "Linux", + "Network Devices", + "Office Suite", + "SaaS", + "Windows", + "macOS" + ] + }, + { + "id": "T1112", + "name": "Modify Registry", + "tactics": [ + "defense-impairment", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1113", + "name": "Screen Capture", + "tactics": [ + "collection" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1114", + "name": "Email Collection", + "tactics": [ + "collection" + ], + "platforms": [ + "Windows", + "macOS", + "Linux", + "Office Suite" + ] + }, + { + "id": "T1115", + "name": "Clipboard Data", + "tactics": [ + "collection" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1119", + "name": "Automated Collection", + "tactics": [ + "collection" + ], + "platforms": [ + "IaaS", + "Linux", + "macOS", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1120", + "name": "Peripheral Device Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1123", + "name": "Audio Capture", + "tactics": [ + "collection" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1124", + "name": "System Time Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1127", + "name": "Trusted Developer Utilities Proxy Execution", + "tactics": [ + "stealth", + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1132.001", + "name": "Data Encoding: Standard Encoding", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1133", + "name": "External Remote Services", + "tactics": [ + "persistence", + "initial-access" + ], + "platforms": [ + "Containers", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1134", + "name": "Access Token Manipulation", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1134.001", + "name": "Access Token Manipulation: Token Impersonation/Theft", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1134.002", + "name": "Access Token Manipulation: Create Process with Token", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1134.003", + "name": "Access Token Manipulation: Make and Impersonate Token", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1134.004", + "name": "Access Token Manipulation: Parent PID Spoofing", + "tactics": [ + "stealth", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1135", + "name": "Network Share Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1136.001", + "name": "Create Account: Local Account", + "tactics": [ + "persistence" + ], + "platforms": [ + "Containers", + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1136.002", + "name": "Create Account: Domain Account", + "tactics": [ + "persistence" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1140", + "name": "Deobfuscate/Decode Files or Information", + "tactics": [ + "stealth" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1176.001", + "name": "Software Extensions: Browser Extensions", + "tactics": [ + "persistence" + ], + "platforms": [ + "Linux", + "Windows", + "macOS" + ] + }, + { + "id": "T1185", + "name": "Browser Session Hijacking", + "tactics": [ + "collection" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1187", + "name": "Forced Authentication", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1190", + "name": "Exploit Public-Facing Application", + "tactics": [ + "initial-access" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1195.002", + "name": "Supply Chain Compromise: Compromise Software Supply Chain", + "tactics": [ + "initial-access" + ], + "platforms": [ + "Linux", + "Windows", + "macOS" + ] + }, + { + "id": "T1197", + "name": "BITS Jobs", + "tactics": [ + "stealth", + "persistence", + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1201", + "name": "Password Policy Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Windows", + "Linux", + "macOS", + "IaaS", + "Network Devices", + "Identity Provider", + "SaaS", + "Office Suite" + ] + }, + { + "id": "T1202", + "name": "Indirect Command Execution", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1203", + "name": "Exploitation for Client Execution", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1204", + "name": "User Execution", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "Windows", + "macOS", + "IaaS", + "Containers" + ] + }, + { + "id": "T1204.001", + "name": "User Execution: Malicious Link", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1204.002", + "name": "User Execution: Malicious File", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1204.004", + "name": "User Execution: Malicious Copy and Paste", + "tactics": [ + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1210", + "name": "Exploitation of Remote Services", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Linux", + "Windows", + "macOS", + "ESXi" + ] + }, + { + "id": "T1211", + "name": "Exploitation for Stealth", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "Windows", + "macOS", + "SaaS", + "IaaS" + ] + }, + { + "id": "T1212", + "name": "Exploitation for Credential Access", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Linux", + "Windows", + "macOS", + "Identity Provider" + ] + }, + { + "id": "T1216", + "name": "System Script Proxy Execution", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1216.001", + "name": "System Script Proxy Execution: PubPrn", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1217", + "name": "Browser Information Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1218", + "name": "System Binary Proxy Execution", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1218.001", + "name": "System Binary Proxy Execution: Compiled HTML File", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.002", + "name": "System Binary Proxy Execution: Control Panel", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.003", + "name": "System Binary Proxy Execution: CMSTP", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.005", + "name": "System Binary Proxy Execution: Mshta", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.007", + "name": "System Binary Proxy Execution: Msiexec", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.008", + "name": "System Binary Proxy Execution: Odbcconf", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.009", + "name": "System Binary Proxy Execution: Regsvcs/Regasm", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.010", + "name": "System Binary Proxy Execution: Regsvr32", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.011", + "name": "System Binary Proxy Execution: Rundll32", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.013", + "name": "System Binary Proxy Execution: Mavinject", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1218.014", + "name": "System Binary Proxy Execution: MMC", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1219", + "name": "Remote Access Tools", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1219.002", + "name": "Remote Access Tools: Remote Desktop Software", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1220", + "name": "XSL Script Processing", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1222.001", + "name": "File and Directory Permissions Modification: Windows Permissions", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1482", + "name": "Domain Trust Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1484.001", + "name": "Domain or Tenant Policy Modification: Group Policy Modification", + "tactics": [ + "defense-impairment", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1485", + "name": "Data Destruction", + "tactics": [ + "impact" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1486", + "name": "Data Encrypted for Impact", + "tactics": [ + "impact" + ], + "platforms": [ + "ESXi", + "IaaS", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1489", + "name": "Service Stop", + "tactics": [ + "impact" + ], + "platforms": [ + "ESXi", + "IaaS", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1490", + "name": "Inhibit System Recovery", + "tactics": [ + "impact" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1491.001", + "name": "Defacement: Internal Defacement", + "tactics": [ + "impact" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1496", + "name": "Resource Hijacking", + "tactics": [ + "impact" + ], + "platforms": [ + "Windows", + "IaaS", + "Linux", + "macOS", + "Containers", + "SaaS" + ] + }, + { + "id": "T1505.002", + "name": "Server Software Component: Transport Agent", + "tactics": [ + "persistence" + ], + "platforms": [ + "Linux", + "Windows" + ] + }, + { + "id": "T1505.003", + "name": "Server Software Component: Web Shell", + "tactics": [ + "persistence" + ], + "platforms": [ + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1505.004", + "name": "Server Software Component: IIS Components", + "tactics": [ + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1505.005", + "name": "Server Software Component: Terminal Services DLL", + "tactics": [ + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1518", + "name": "Software Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "ESXi", + "IaaS", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1518.001", + "name": "Software Discovery: Security Software Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "IaaS", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1526", + "name": "Cloud Service Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "IaaS", + "Identity Provider", + "Office Suite", + "SaaS" + ] + }, + { + "id": "T1528", + "name": "Steal Application Access Token", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Containers", + "IaaS", + "Identity Provider", + "Office Suite", + "SaaS" + ] + }, + { + "id": "T1529", + "name": "System Shutdown/Reboot", + "tactics": [ + "impact" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1539", + "name": "Steal Web Session Cookie", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Linux", + "macOS", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1542.001", + "name": "Pre-OS Boot: System Firmware", + "tactics": [ + "stealth", + "persistence" + ], + "platforms": [ + "Network Devices", + "Windows" + ] + }, + { + "id": "T1542.003", + "name": "Pre-OS Boot: Bootkit", + "tactics": [ + "stealth", + "persistence" + ], + "platforms": [ + "Linux", + "Windows" + ] + }, + { + "id": "T1543", + "name": "Create or Modify System Process", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Containers", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1543.001", + "name": "Create or Modify System Process: Launch Agent", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "macOS" + ] + }, + { + "id": "T1543.003", + "name": "Create or Modify System Process: Windows Service", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1543.004", + "name": "Create or Modify System Process: Launch Daemon", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "macOS" + ] + }, + { + "id": "T1546", + "name": "Event Triggered Execution", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Linux", + "macOS", + "Windows", + "SaaS", + "IaaS", + "Office Suite" + ] + }, + { + "id": "T1546.001", + "name": "Event Triggered Execution: Change Default File Association", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1546.002", + "name": "Event Triggered Execution: Screensaver", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1546.003", + "name": "Event Triggered Execution: Windows Management Instrumentation Event Subscription", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1546.004", + "name": "Event Triggered Execution: Unix Shell Configuration Modification", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Linux", + "macOS" + ] + }, + { + "id": "T1546.007", + "name": "Event Triggered Execution: Netsh Helper DLL", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1546.008", + "name": "Event Triggered Execution: Accessibility Features", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1546.011", + "name": "Event Triggered Execution: Application Shimming", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1546.015", + "name": "Event Triggered Execution: Component Object Model Hijacking", + "tactics": [ + "privilege-escalation", + "persistence" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1547", + "name": "Boot or Logon Autostart Execution", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Linux", + "macOS", + "Windows", + "Network Devices" + ] + }, + { + "id": "T1547.001", + "name": "Boot or Logon Autostart Execution: Registry Run Keys / Startup Folder", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1547.002", + "name": "Boot or Logon Autostart Execution: Authentication Package", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1547.010", + "name": "Boot or Logon Autostart Execution: Port Monitors", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1547.014", + "name": "Boot or Logon Autostart Execution: Active Setup", + "tactics": [ + "persistence", + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1548", + "name": "Abuse Elevation Control Mechanism", + "tactics": [ + "privilege-escalation" + ], + "platforms": [ + "Linux", + "macOS", + "Windows", + "IaaS", + "Office Suite", + "Identity Provider" + ] + }, + { + "id": "T1548.002", + "name": "Abuse Elevation Control Mechanism: Bypass User Account Control", + "tactics": [ + "privilege-escalation" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1550.003", + "name": "Use Alternate Authentication Material: Pass the Ticket", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1552", + "name": "Unsecured Credentials", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows", + "SaaS", + "IaaS", + "Linux", + "macOS", + "Containers", + "Network Devices", + "Office Suite", + "Identity Provider" + ] + }, + { + "id": "T1552.001", + "name": "Unsecured Credentials: Credentials In Files", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Containers", + "IaaS", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1552.002", + "name": "Unsecured Credentials: Credentials in Registry", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1552.004", + "name": "Unsecured Credentials: Private Keys", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1552.006", + "name": "Unsecured Credentials: Group Policy Preferences", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1553", + "name": "Subvert Trust Controls", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1553.004", + "name": "Subvert Trust Controls: Install Root Certificate", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1553.005", + "name": "Subvert Trust Controls: Mark-of-the-Web Bypass", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1555", + "name": "Credentials from Password Stores", + "tactics": [ + "credential-access" + ], + "platforms": [ + "IaaS", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1555.003", + "name": "Credentials from Password Stores: Credentials from Web Browsers", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1555.004", + "name": "Credentials from Password Stores: Windows Credential Manager", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1556.002", + "name": "Modify Authentication Process: Password Filter DLL", + "tactics": [ + "defense-impairment", + "persistence", + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1557", + "name": "Adversary-in-the-Middle", + "tactics": [ + "credential-access", + "collection" + ], + "platforms": [ + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1557.001", + "name": "Adversary-in-the-Middle: Name Resolution Poisoning and SMB Relay", + "tactics": [ + "credential-access", + "collection" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1558.003", + "name": "Steal or Forge Kerberos Tickets: Kerberoasting", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1560", + "name": "Archive Collected Data", + "tactics": [ + "collection" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1560.001", + "name": "Archive Collected Data: Archive via Utility", + "tactics": [ + "collection" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1563.002", + "name": "Remote Service Session Hijacking: RDP Hijacking", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1564", + "name": "Hide Artifacts", + "tactics": [ + "stealth" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Office Suite", + "Windows" + ] + }, + { + "id": "T1564.001", + "name": "Hide Artifacts: Hidden Files and Directories", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1564.002", + "name": "Hide Artifacts: Hidden Users", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1564.003", + "name": "Hide Artifacts: Hidden Window", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1564.004", + "name": "Hide Artifacts: NTFS File Attributes", + "tactics": [ + "stealth" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1564.006", + "name": "Hide Artifacts: Run Virtual Instance", + "tactics": [ + "stealth" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1566", + "name": "Phishing", + "tactics": [ + "initial-access" + ], + "platforms": [ + "Identity Provider", + "Linux", + "macOS", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1566.001", + "name": "Phishing: Spearphishing Attachment", + "tactics": [ + "initial-access" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1567", + "name": "Exfiltration Over Web Service", + "tactics": [ + "exfiltration" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Office Suite", + "SaaS", + "Windows" + ] + }, + { + "id": "T1567.002", + "name": "Exfiltration Over Web Service: Exfiltration to Cloud Storage", + "tactics": [ + "exfiltration" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1568", + "name": "Dynamic Resolution", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1569", + "name": "System Services", + "tactics": [ + "execution" + ], + "platforms": [ + "Windows", + "macOS", + "Linux" + ] + }, + { + "id": "T1569.002", + "name": "System Services: Service Execution", + "tactics": [ + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1570", + "name": "Lateral Tool Transfer", + "tactics": [ + "lateral-movement" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1572", + "name": "Protocol Tunneling", + "tactics": [ + "command-and-control" + ], + "platforms": [ + "ESXi", + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1574", + "name": "Hijack Execution Flow", + "tactics": [ + "stealth", + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1574.001", + "name": "Hijack Execution Flow: DLL", + "tactics": [ + "stealth", + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1574.005", + "name": "Hijack Execution Flow: Executable Installer File Permissions Weakness", + "tactics": [ + "stealth", + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1574.007", + "name": "Hijack Execution Flow: Path Interception by PATH Environment Variable", + "tactics": [ + "stealth", + "execution" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1574.008", + "name": "Hijack Execution Flow: Path Interception by Search Order Hijacking", + "tactics": [ + "stealth", + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1574.011", + "name": "Hijack Execution Flow: Services Registry Permissions Weakness", + "tactics": [ + "stealth", + "execution" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1587", + "name": "Develop Capabilities", + "tactics": [ + "resource-development" + ], + "platforms": [ + "PRE" + ] + }, + { + "id": "T1587.001", + "name": "Develop Capabilities: Malware", + "tactics": [ + "resource-development" + ], + "platforms": [ + "PRE" + ] + }, + { + "id": "T1588.002", + "name": "Obtain Capabilities: Tool", + "tactics": [ + "resource-development" + ], + "platforms": [ + "PRE" + ] + }, + { + "id": "T1590.001", + "name": "Gather Victim Network Information: Domain Properties", + "tactics": [ + "reconnaissance" + ], + "platforms": [ + "PRE" + ] + }, + { + "id": "T1593.003", + "name": "Search Open Websites/Domains: Code Repositories", + "tactics": [ + "reconnaissance" + ], + "platforms": [ + "PRE" + ] + }, + { + "id": "T1595", + "name": "Active Scanning", + "tactics": [ + "reconnaissance" + ], + "platforms": [ + "PRE" + ] + }, + { + "id": "T1608", + "name": "Stage Capabilities", + "tactics": [ + "resource-development" + ], + "platforms": [ + "PRE" + ] + }, + { + "id": "T1614.001", + "name": "System Location Discovery: System Language Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1615", + "name": "Group Policy Discovery", + "tactics": [ + "discovery" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1620", + "name": "Reflective Code Loading", + "tactics": [ + "stealth" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1622", + "name": "Debugger Evasion", + "tactics": [ + "stealth", + "discovery" + ], + "platforms": [ + "Linux", + "macOS", + "Windows" + ] + }, + { + "id": "T1649", + "name": "Steal or Forge Authentication Certificates", + "tactics": [ + "credential-access" + ], + "platforms": [ + "Windows", + "Linux", + "macOS", + "Identity Provider" + ] + }, + { + "id": "T1685", + "name": "Disable or Modify Tools", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Containers", + "ESXi", + "IaaS", + "Linux", + "macOS", + "Network Devices", + "Windows" + ] + }, + { + "id": "T1685.001", + "name": "Disable or Modify Tools: Disable or Modify Windows Event Log", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1685.005", + "name": "Disable or Modify Tools: Clear Windows Event Logs", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1686.003", + "name": "Disable or Modify System Firewall: Windows Host Firewall", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "Windows" + ] + }, + { + "id": "T1689", + "name": "Downgrade Attack", + "tactics": [ + "defense-impairment" + ], + "platforms": [ + "macOS", + "Windows", + "Linux" + ] + } + ] +} diff --git a/server/src/detect/correlation_test.zig b/server/src/detect/correlation_test.zig index 3cbebb9..3d3ecb4 100644 --- a/server/src/detect/correlation_test.zig +++ b/server/src/detect/correlation_test.zig @@ -270,6 +270,8 @@ const restart_agent = "00000000-0000-0000-0000-0000000c00a5"; fn cleanupRestart(conn: *pg.Conn) void { const stmts = [_][]const u8{ "DELETE FROM work_queue WHERE tenant_id = $1::uuid", + "DELETE FROM incident_alerts WHERE tenant_id = $1::uuid", + "DELETE FROM incidents WHERE tenant_id = $1::uuid", "DELETE FROM alerts WHERE tenant_id = $1::uuid", "DELETE FROM sequence_state WHERE tenant_id = $1::uuid", "DELETE FROM threshold_counters WHERE tenant_id = $1::uuid", diff --git a/server/src/detect/incidents.zig b/server/src/detect/incidents.zig new file mode 100644 index 0000000..ac29395 --- /dev/null +++ b/server/src/detect/incidents.zig @@ -0,0 +1,591 @@ +//! Incident grouping and risk (docs/architecture/target-edr.md sections 7 +//! and 8). `attach` runs after each alert insert in jobs/detect.zig. +//! +//! An alert joins an open incident updated within the window (4 h) when: +//! 1. lineage: same agent and the same lineage root, the oldest ancestor +//! in `process_entities` below a session root (explorer.exe, +//! services.exe, wininit.exe, init, systemd, launchd), or +//! 2. artefact: same agent and same user, plus a shared sha256, domain or IP, or +//! 3. indicator: any agent, the same high-confidence indicator (an IOC +//! rule match) or the same file sha256. +//! Otherwise it opens a new incident. +//! +//! Risk is the section 7 noisy-OR over the incident's evidence, deduplicated +//! by key, with each item and its points stored in `risk_items`. +const std = @import("std"); +const pg = @import("../db/pg/conn.zig"); +const util = @import("../http/util.zig"); +const ast = @import("ast.zig"); + +pub const window_seconds: i64 = 4 * 3600; + +/// Session roots. Lineage stops below these, so two unrelated programs the +/// user started from Explorer are not one incident. +const session_roots = [_][]const u8{ + "explorer.exe", "services.exe", "wininit.exe", "winlogon.exe", "smss.exe", "userinit.exe", + "init", "systemd", "launchd", "sshd", "login", "csrss.exe", +}; + +pub fn isSessionRoot(image_or_name: []const u8) bool { + const base = basename(image_or_name); + for (session_roots) |r| { + if (std.ascii.eqlIgnoreCase(base, r)) return true; + } + return false; +} + +fn basename(path: []const u8) []const u8 { + const i = std.mem.lastIndexOfAny(u8, path, "\\/") orelse return path; + return path[i + 1 ..]; +} + +// ---------------------------------------------------------------- risk + +pub const Item = struct { + key: []const u8, + kind: []const u8, + label: []const u8, + weight: f64, + confidence: f64 = 1.0, + /// 0 allowlisted, 0.5 signed by a trusted vendor, 1 otherwise. + context: f64 = 1.0, + + pub fn points(self: Item) f64 { + return std.math.clamp(self.weight * self.confidence * self.context, 0, 100); + } +}; + +/// risk = 100 * (1 - prod(1 - s/100)). Items with the same key count once +/// (the highest scoring copy). Never above 100. +pub fn noisyOr(items: []const Item) f64 { + var prod: f64 = 1.0; + for (items, 0..) |it, i| { + var dup = false; + for (items[0..i]) |prev| { + if (std.mem.eql(u8, prev.key, it.key)) { + dup = true; + break; + } + } + if (dup) continue; + var best = it.points(); + for (items[i + 1 ..]) |later| { + if (std.mem.eql(u8, later.key, it.key)) best = @max(best, later.points()); + } + prod *= 1.0 - best / 100.0; + } + return 100.0 * (1.0 - prod); +} + +pub fn severityFor(risk: f64, floor: []const u8) []const u8 { + const by_risk: []const u8 = if (risk >= 85) "critical" else if (risk >= 65) "high" else if (risk >= 40) "medium" else "low"; + return if (sevRank(floor) > sevRank(by_risk)) normSev(floor) else by_risk; +} + +fn normSev(s: []const u8) []const u8 { + return switch (sevRank(s)) { + 3 => "critical", + 2 => "high", + 1 => "medium", + else => "low", + }; +} + +pub fn sevRank(s: []const u8) u8 { + if (std.ascii.eqlIgnoreCase(s, "critical")) return 3; + if (std.ascii.eqlIgnoreCase(s, "high")) return 2; + if (std.ascii.eqlIgnoreCase(s, "medium")) return 1; + return 0; +} + +/// Default weight per alert when the rule YAML has none: by rule severity. +/// IOC rules are high-confidence indicator matches (section 7: 50). +pub fn alertWeight(format: []const u8, severity: []const u8) f64 { + if (std.mem.eql(u8, format, "ioc")) return 50; + return switch (sevRank(severity)) { + 3 => 60, + 2 => 30, + 1 => 20, + else => 10, + }; +} + +// ---------------------------------------------------------------- evidence keys + +pub const Facts = struct { + entity_id: ?[]const u8 = null, + parent_entity_id: ?[]const u8 = null, + user: ?[]const u8 = null, + sha256: ?[]const u8 = null, + domain: ?[]const u8 = null, + ip: ?[]const u8 = null, +}; + +fn validEntity(s: []const u8) bool { + if (s.len != 26) return false; + for (s) |c| { + if (!((c >= 'a' and c <= 'z') or (c >= '2' and c <= '7'))) return false; + } + return true; +} + +fn validSha256(s: []const u8) bool { + if (s.len != 64) return false; + for (s) |c| if (!std.ascii.isHex(c)) return false; + return true; +} + +fn first(root: std.json.Value, paths: []const []const u8, buf: *[64]u8) ?[]const u8 { + for (paths) |p| { + if (ast.firstScalar(root, p, buf)) |v| { + if (v.len > 0) return v; + } + } + return null; +} + +/// Pull grouping facts out of an event payload. Values are copied into `arena`. +pub fn extract(arena: std.mem.Allocator, root: std.json.Value) !Facts { + var f: Facts = .{}; + var buf: [64]u8 = undefined; + if (first(root, &.{"process.entity_id"}, &buf)) |v| { + if (validEntity(v)) f.entity_id = try arena.dupe(u8, v); + } + if (first(root, &.{"parent.entity_id"}, &buf)) |v| { + if (validEntity(v)) f.parent_entity_id = try arena.dupe(u8, v); + } + if (first(root, &.{ "process.user.name", "user.name", "process.user" }, &buf)) |v| { + f.user = try std.ascii.allocLowerString(arena, v); + } + if (first(root, &.{ "file.hashes.sha256", "process.hashes.sha256", "sha256" }, &buf)) |v| { + if (validSha256(v)) f.sha256 = try std.ascii.allocLowerString(arena, v); + } + if (first(root, &.{ "dns.query", "qname" }, &buf)) |v| { + f.domain = try std.ascii.allocLowerString(arena, std.mem.trimEnd(u8, v, ".")); + } + if (first(root, &.{"network.dst_ip"}, &buf)) |v| { + if (!privateOrLocal(v)) f.ip = try arena.dupe(u8, v); + } + return f; +} + +/// Private, loopback and link-local destinations are shared by every host +/// on a network, so they are not artefacts worth grouping on. +fn privateOrLocal(ip: []const u8) bool { + const prefixes = [_][]const u8{ "10.", "127.", "192.168.", "169.254.", "0.", "::1", "fe80:", "fc", "fd" }; + for (prefixes) |p| if (std.ascii.startsWithIgnoreCase(ip, p)) return true; + if (std.mem.startsWith(u8, ip, "172.")) { + var it = std.mem.splitScalar(u8, ip[4..], '.'); + const second = std.fmt.parseInt(u8, it.next() orelse "", 10) catch return false; + return second >= 16 and second <= 31; + } + return false; +} + +// ---------------------------------------------------------------- attach + +pub const AlertRef = struct { + tenant_id: []const u8, + agent_id: []const u8, + alert_id: []const u8, + rule_id: []const u8, + rule_name: []const u8, + rule_format: []const u8, + severity: []const u8, + hostname: []const u8, + occurred_at: []const u8, + techniques_pg: []const u8 = "{}", + root: std.json.Value, +}; + +fn freeRows(allocator: std.mem.Allocator, rows: []pg.Row) void { + for (rows) |row| row.deinit(allocator); + allocator.free(rows); +} + +/// Oldest ancestor below a session root, walking `process_entities`. +/// Falls back to the entity itself when the parent chain is unknown. +pub fn lineageRoot(arena: std.mem.Allocator, conn: *pg.Conn, tenant_id: []const u8, entity_id: []const u8) ![]const u8 { + const rows = try conn.exec(arena, + \\WITH RECURSIVE chain(entity_id, parent_entity_id, image, depth) AS ( + \\ SELECT entity_id, parent_entity_id, image, 0 FROM process_entities + \\ WHERE tenant_id = $1::uuid AND entity_id = $2 + \\ UNION ALL + \\ SELECT p.entity_id, p.parent_entity_id, p.image, c.depth + 1 + \\ FROM process_entities p JOIN chain c ON p.entity_id = c.parent_entity_id + \\ WHERE p.tenant_id = $1::uuid AND c.depth < 64 + \\) + \\SELECT entity_id, coalesce(image, '') FROM chain ORDER BY depth + , &.{ .{ .text = tenant_id }, .{ .text = entity_id } }); + defer freeRows(arena, rows); + var root: []const u8 = entity_id; + for (rows) |row| { + const image = row.cols[1] orelse ""; + if (isSessionRoot(image)) break; + root = row.cols[0] orelse root; + } + return arena.dupe(u8, root); +} + +const Match = struct { id: []const u8, reason: []const u8 }; + +/// Group one new alert. Returns the incident id it landed in. +pub fn attach(allocator: std.mem.Allocator, conn: *pg.Conn, a: AlertRef, now_unix: i64) ![]u8 { + var arena_state = std.heap.ArenaAllocator.init(allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + + const f = try extract(arena, a.root); + var keys: std.ArrayList([]const u8) = .empty; + var root_entity: ?[]const u8 = null; + if (f.entity_id) |eid| { + root_entity = try lineageRoot(arena, conn, a.tenant_id, eid); + try keys.append(arena, try std.fmt.allocPrint(arena, "root:{s}", .{root_entity.?})); + } + if (f.user) |u| try keys.append(arena, try std.fmt.allocPrint(arena, "user:{s}", .{u})); + if (f.sha256) |h| try keys.append(arena, try std.fmt.allocPrint(arena, "sha256:{s}", .{h})); + if (f.domain) |d| try keys.append(arena, try std.fmt.allocPrint(arena, "domain:{s}", .{d})); + if (f.ip) |ip| try keys.append(arena, try std.fmt.allocPrint(arena, "ip:{s}", .{ip})); + const is_ioc = std.mem.eql(u8, a.rule_format, "ioc"); + if (is_ioc) try keys.append(arena, try std.fmt.allocPrint(arena, "ioc:{s}", .{a.rule_id})); + const keys_pg = try util.pgArrayText(arena, keys.items); + + var tbuf: [32]u8 = undefined; + const since = util.formatRfc3339(&tbuf, now_unix - window_seconds); + + const found: ?Match = try findIncident(arena, conn, a, f, root_entity, is_ioc, since); + var nbuf: [32]u8 = undefined; + const now_s = util.formatRfc3339(&nbuf, now_unix); + var id_text: []const u8 = undefined; + var reason: []const u8 = undefined; + if (found) |m| { + id_text = m.id; + reason = m.reason; + } else { + var idb: [36]u8 = undefined; + id_text = try arena.dupe(u8, newId(&idb, a.alert_id, now_unix)); + reason = if (root_entity != null) "lineage" else if (is_ioc) "indicator" else if (f.sha256 != null or f.domain != null or f.ip != null) "artefact" else "alert"; + const title = try std.fmt.allocPrint(arena, "{s} on {s}", .{ a.rule_name, a.hostname }); + try conn.execNoRows( + \\INSERT INTO incidents (id, tenant_id, title, status, severity, risk, grouping, root_entity_id, + \\ first_seen_at, last_seen_at, created_at, updated_at) + \\VALUES ($1::uuid, $2::uuid, $3, 'new', 'low', 0, $4, $5, $6::timestamptz, $6::timestamptz, $7::timestamptz, $7::timestamptz) + , &.{ + .{ .text = id_text }, + .{ .text = a.tenant_id }, + .{ .text = title }, + .{ .text = reason }, + if (root_entity) |r| .{ .text = r } else .{ .null = {} }, + .{ .text = a.occurred_at }, + .{ .text = now_s }, + }); + } + try conn.execNoRows( + \\INSERT INTO incident_alerts (tenant_id, incident_id, alert_id, agent_id, keys, reason, occurred_at, added_at) + \\VALUES ($1::uuid, $2::uuid, $3::bigint, $4::uuid, $5::text[], $6, $7::timestamptz, $8::timestamptz) + \\ON CONFLICT DO NOTHING + , &.{ + .{ .text = a.tenant_id }, + .{ .text = id_text }, + .{ .text = a.alert_id }, + .{ .text = a.agent_id }, + .{ .text = keys_pg }, + .{ .text = reason }, + .{ .text = a.occurred_at }, + .{ .text = now_s }, + }); + try recompute(allocator, conn, a.tenant_id, id_text, now_s); + return allocator.dupe(u8, id_text); +} + +/// Deterministic id from the first alert, so a retried detect job lands in +/// the same incident. +fn newId(buf: *[36]u8, alert_id: []const u8, now_unix: i64) []const u8 { + var dig: [32]u8 = undefined; + var h = std.crypto.hash.sha2.Sha256.init(.{}); + h.update("tawny-incident:"); + h.update(alert_id); + var nb: [20]u8 = undefined; + h.update(std.fmt.bufPrint(&nb, ":{d}", .{@divFloor(now_unix, window_seconds)}) catch ""); + h.final(&dig); + dig[6] = (dig[6] & 0x0f) | 0x40; + dig[8] = (dig[8] & 0x3f) | 0x80; + const hex = "0123456789abcdef"; + var j: usize = 0; + for (dig[0..16], 0..) |b, i| { + if (i == 4 or i == 6 or i == 8 or i == 10) { + buf[j] = '-'; + j += 1; + } + buf[j] = hex[b >> 4]; + buf[j + 1] = hex[b & 0xf]; + j += 2; + } + return buf[0..36]; +} + +fn findIncident( + arena: std.mem.Allocator, + conn: *pg.Conn, + a: AlertRef, + f: Facts, + root_entity: ?[]const u8, + is_ioc: bool, + since: []const u8, +) !?Match { + // Rule 1: same agent, same lineage root. + if (root_entity) |r| { + const key = try std.fmt.allocPrint(arena, "root:{s}", .{r}); + if (try openWith(arena, conn, a.tenant_id, a.agent_id, &.{key}, since)) |id| return .{ .id = id, .reason = "lineage" }; + } + // Rule 2: same agent and user, plus a shared artefact. + if (f.user) |u| { + var art: std.ArrayList([]const u8) = .empty; + if (f.sha256) |h| try art.append(arena, try std.fmt.allocPrint(arena, "sha256:{s}", .{h})); + if (f.domain) |d| try art.append(arena, try std.fmt.allocPrint(arena, "domain:{s}", .{d})); + if (f.ip) |ip| try art.append(arena, try std.fmt.allocPrint(arena, "ip:{s}", .{ip})); + if (art.items.len > 0) { + const user_key = try std.fmt.allocPrint(arena, "user:{s}", .{u}); + const art_pg = try util.pgArrayText(arena, art.items); + const rows = try conn.exec(arena, + \\SELECT i.id::text FROM incidents i JOIN incident_alerts ia ON ia.incident_id = i.id + \\WHERE i.tenant_id = $1::uuid AND ia.agent_id = $2::uuid + \\ AND i.status IN ('new','investigating') AND i.last_seen_at >= $3::timestamptz + \\ AND $4 = ANY(ia.keys) AND ia.keys && $5::text[] + \\ORDER BY i.last_seen_at DESC LIMIT 1 + , &.{ .{ .text = a.tenant_id }, .{ .text = a.agent_id }, .{ .text = since }, .{ .text = user_key }, .{ .text = art_pg } }); + defer freeRows(arena, rows); + if (rows.len > 0) return .{ .id = try arena.dupe(u8, rows[0].cols[0].?), .reason = "artefact" }; + } + } + // Rule 3: cross-agent, same high-confidence indicator or same file hash. + var cross: std.ArrayList([]const u8) = .empty; + if (is_ioc) try cross.append(arena, try std.fmt.allocPrint(arena, "ioc:{s}", .{a.rule_id})); + if (f.sha256) |h| try cross.append(arena, try std.fmt.allocPrint(arena, "sha256:{s}", .{h})); + if (cross.items.len > 0) { + if (try openWith(arena, conn, a.tenant_id, null, cross.items, since)) |id| return .{ .id = id, .reason = "indicator" }; + } + return null; +} + +fn openWith(arena: std.mem.Allocator, conn: *pg.Conn, tenant_id: []const u8, agent_id: ?[]const u8, keys: []const []const u8, since: []const u8) !?[]const u8 { + const keys_pg = try util.pgArrayText(arena, keys); + const rows = try conn.exec(arena, + \\SELECT i.id::text FROM incidents i JOIN incident_alerts ia ON ia.incident_id = i.id + \\WHERE i.tenant_id = $1::uuid AND ($2::uuid IS NULL OR ia.agent_id = $2::uuid) + \\ AND i.status IN ('new','investigating') AND i.last_seen_at >= $3::timestamptz + \\ AND ia.keys && $4::text[] + \\ORDER BY i.last_seen_at DESC LIMIT 1 + , &.{ + .{ .text = tenant_id }, + if (agent_id) |id| .{ .text = id } else .{ .null = {} }, + .{ .text = since }, + .{ .text = keys_pg }, + }); + defer freeRows(arena, rows); + if (rows.len == 0) return null; + return try arena.dupe(u8, rows[0].cols[0].?); +} + +/// Rebuild risk, severity, title, agents, users and techniques from the +/// incident's alerts. Evidence is one item per rule (key `rule:`), so a +/// rule that fires ten times counts once. +pub fn recompute(allocator: std.mem.Allocator, conn: *pg.Conn, tenant_id: []const u8, incident_id: []const u8, now_s: []const u8) !void { + var arena_state = std.heap.ArenaAllocator.init(allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const rows = try conn.exec(arena, + \\SELECT r.id::text, r.name, r.format, a.severity, ag.hostname, ia.agent_id::text, + \\ array_to_json(r.mitre_techniques)::text, array_to_json(ia.keys)::text, ia.occurred_at::text, a.title + \\FROM incident_alerts ia + \\JOIN alerts a ON a.id = ia.alert_id + \\JOIN alert_rules r ON r.id = a.alert_rule_id + \\JOIN agents ag ON ag.id = ia.agent_id + \\WHERE ia.tenant_id = $1::uuid AND ia.incident_id = $2::uuid + \\ORDER BY ia.occurred_at, a.id + , &.{ .{ .text = tenant_id }, .{ .text = incident_id } }); + defer freeRows(arena, rows); + if (rows.len == 0) return; + + var items: std.ArrayList(Item) = .empty; + var agents: std.ArrayList([]const u8) = .empty; + var users: std.ArrayList([]const u8) = .empty; + var techs: std.ArrayList([]const u8) = .empty; + var floor: []const u8 = "low"; + var best_title: []const u8 = rows[0].cols[1] orelse "Incident"; + var best_host: []const u8 = rows[0].cols[4] orelse ""; + var best_w: f64 = -1; + var first_seen: []const u8 = rows[0].cols[8] orelse now_s; + var last_seen: []const u8 = first_seen; + for (rows) |row| { + const c = row.cols; + const rid = c[0] orelse continue; + const sev = c[3] orelse "low"; + const w = alertWeight(c[2] orelse "", sev); + try items.append(arena, .{ + .key = try std.fmt.allocPrint(arena, "rule:{s}", .{rid}), + .kind = if (std.mem.eql(u8, c[2] orelse "", "ioc")) "indicator" else "detection", + .label = c[1] orelse "rule", + .weight = w, + }); + if (w > best_w) { + best_w = w; + best_title = c[1] orelse best_title; + best_host = c[4] orelse best_host; + } + if (sevRank(sev) == 3) floor = "critical"; + try addUnique(arena, &agents, c[5] orelse ""); + if (c[6]) |raw| { + const list = try std.json.parseFromSliceLeaky([]const []const u8, arena, raw, .{}); + for (list) |t| try addUnique(arena, &techs, t); + } + if (c[7]) |raw| { + const list = try std.json.parseFromSliceLeaky([]const []const u8, arena, raw, .{}); + for (list) |k| { + if (std.mem.startsWith(u8, k, "user:")) try addUnique(arena, &users, k[5..]); + } + } + if (c[8]) |t| { + if (std.mem.order(u8, t, first_seen) == .lt) first_seen = t; + if (std.mem.order(u8, t, last_seen) == .gt) last_seen = t; + } + } + if (std.mem.order(u8, now_s, last_seen) == .gt) last_seen = now_s; + const risk = noisyOr(items.items); + const severity = severityFor(risk, floor); + const risk_items = try itemsJson(arena, items.items); + const title = try std.fmt.allocPrint(arena, "{s} on {s}", .{ best_title, best_host }); + var rbuf: [8]u8 = undefined; + const risk_txt = try std.fmt.bufPrint(&rbuf, "{d}", .{@as(u32, @intFromFloat(@round(risk)))}); + try conn.execNoRows( + \\UPDATE incidents SET risk = $3::int, severity = $4, risk_items = $5::jsonb, title = $6, + \\ agent_ids = $7::uuid[], users = $8::text[], techniques = $9::text[], + \\ first_seen_at = least(first_seen_at, $10::timestamptz), last_seen_at = $11::timestamptz, updated_at = $11::timestamptz + \\WHERE tenant_id = $1::uuid AND id = $2::uuid + , &.{ + .{ .text = tenant_id }, + .{ .text = incident_id }, + .{ .text = risk_txt }, + .{ .text = severity }, + .{ .text = risk_items }, + .{ .text = title }, + .{ .text = try util.pgArrayText(arena, agents.items) }, + .{ .text = try util.pgArrayText(arena, users.items) }, + .{ .text = try util.pgArrayText(arena, techs.items) }, + .{ .text = first_seen }, + .{ .text = last_seen }, + }); +} + +fn addUnique(arena: std.mem.Allocator, list: *std.ArrayList([]const u8), v: []const u8) !void { + if (v.len == 0) return; + for (list.items) |x| if (std.mem.eql(u8, x, v)) return; + try list.append(arena, v); +} + +/// Each evidence item once, with its points, so the analyst sees why. +pub fn itemsJson(allocator: std.mem.Allocator, items: []const Item) ![]u8 { + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(allocator); + try out.append(allocator, '['); + var n: usize = 0; + for (items, 0..) |it, i| { + var dup = false; + for (items[0..i]) |prev| { + if (std.mem.eql(u8, prev.key, it.key)) dup = true; + } + if (dup) continue; + if (n > 0) try out.append(allocator, ','); + n += 1; + try out.appendSlice(allocator, "{\"key\":"); + try util.appendEscaped(&out, allocator, it.key); + try out.appendSlice(allocator, ",\"kind\":"); + try util.appendEscaped(&out, allocator, it.kind); + try out.appendSlice(allocator, ",\"label\":"); + try util.appendEscaped(&out, allocator, it.label); + const line = try std.fmt.allocPrint(allocator, ",\"weight\":{d},\"confidence\":{d},\"context\":{d},\"points\":{d}}}", .{ + it.weight, it.confidence, it.context, @round(it.points() * 10) / 10, + }); + defer allocator.free(line); + try out.appendSlice(allocator, line); + } + try out.append(allocator, ']'); + return out.toOwnedSlice(allocator); +} + +test "noisy-or saturates, dedupes by key and never exceeds 100" { + const one = [_]Item{.{ .key = "a", .kind = "d", .label = "x", .weight = 50 }}; + try std.testing.expectApproxEqAbs(@as(f64, 50), noisyOr(&one), 1e-9); + const two = [_]Item{ + .{ .key = "a", .kind = "d", .label = "x", .weight = 50 }, + .{ .key = "b", .kind = "d", .label = "y", .weight = 50 }, + }; + try std.testing.expectApproxEqAbs(@as(f64, 75), noisyOr(&two), 1e-9); + const dup = [_]Item{ + .{ .key = "a", .kind = "d", .label = "x", .weight = 25 }, + .{ .key = "a", .kind = "d", .label = "x", .weight = 25 }, + }; + try std.testing.expectApproxEqAbs(@as(f64, 25), noisyOr(&dup), 1e-9); + var many: [40]Item = undefined; + for (&many, 0..) |*m, i| m.* = .{ .key = &[_]u8{@intCast('A' + i)}, .kind = "d", .label = "x", .weight = 100 }; + try std.testing.expect(noisyOr(&many) <= 100.0); + const allow = [_]Item{.{ .key = "a", .kind = "d", .label = "x", .weight = 80, .context = 0 }}; + try std.testing.expectEqual(@as(f64, 0), noisyOr(&allow)); + // Section 7 example chain: Office to PowerShell 25, encoded command 20, + // unsigned exe 20, persistence 30 gives 1 - .75*.8*.8*.7 = 66.4. + const chain = [_]Item{ + .{ .key = "o", .kind = "d", .label = "office", .weight = 25 }, + .{ .key = "e", .kind = "d", .label = "enc", .weight = 20 }, + .{ .key = "u", .kind = "d", .label = "unsigned", .weight = 20 }, + .{ .key = "p", .kind = "d", .label = "persist", .weight = 30 }, + }; + try std.testing.expectApproxEqAbs(@as(f64, 66.4), noisyOr(&chain), 1e-9); + try std.testing.expectEqualStrings("high", severityFor(noisyOr(&chain), "low")); + try std.testing.expectEqualStrings("critical", severityFor(10, "critical")); + try std.testing.expectEqualStrings("medium", severityFor(40, "low")); +} + +test "evidence items list each key once with points" { + const a = std.testing.allocator; + const items = [_]Item{ + .{ .key = "rule:1", .kind = "detection", .label = "Office spawns \"shell\"", .weight = 30 }, + .{ .key = "rule:1", .kind = "detection", .label = "Office spawns \"shell\"", .weight = 30 }, + .{ .key = "rule:2", .kind = "indicator", .label = "IOC", .weight = 50, .context = 0.5 }, + }; + const json = try itemsJson(a, &items); + defer a.free(json); + var parsed = try std.json.parseFromSlice(std.json.Value, a, json, .{}); + defer parsed.deinit(); + try std.testing.expectEqual(@as(usize, 2), parsed.value.array.items.len); + const second = parsed.value.array.items[1].object; + try std.testing.expectEqual(@as(f64, 25), switch (second.get("points").?) { + .float => |v| v, + .integer => |v| @as(f64, @floatFromInt(v)), + else => -1, + }); +} + +test "session roots stop lineage and facts come from canonical fields" { + try std.testing.expect(isSessionRoot("C:\\Windows\\explorer.exe")); + try std.testing.expect(isSessionRoot("/sbin/launchd")); + try std.testing.expect(!isSessionRoot("C:\\Program Files\\Microsoft Office\\WINWORD.EXE")); + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const payload = + \\{"process":{"entity_id":"abcdefghijklmnopqrstuvwxyz","user":{"name":"CORP\\Alice"}, + \\ "hashes":{"sha256":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}, + \\ "parent":{"entity_id":"not-an-id"},"network":{"dst_ip":"192.168.1.5"},"dns":{"query":"Evil.Example."}} + ; + const v = try std.json.parseFromSliceLeaky(std.json.Value, arena, payload, .{}); + const f = try extract(arena, v); + try std.testing.expectEqualStrings("abcdefghijklmnopqrstuvwxyz", f.entity_id.?); + try std.testing.expect(f.parent_entity_id == null); + try std.testing.expectEqualStrings("corp\\alice", f.user.?); + try std.testing.expectEqual(@as(usize, 64), f.sha256.?.len); + try std.testing.expect(f.ip == null); + try std.testing.expectEqualStrings("evil.example", f.domain.?); + try std.testing.expect(!privateOrLocal("8.8.8.8")); + try std.testing.expect(privateOrLocal("172.20.0.1")); + try std.testing.expect(!privateOrLocal("172.32.0.1")); +} diff --git a/server/src/detect/incidents_test.zig b/server/src/detect/incidents_test.zig new file mode 100644 index 0000000..184e440 --- /dev/null +++ b/server/src/detect/incidents_test.zig @@ -0,0 +1,308 @@ +//! Incident grouping against Postgres. Each test runs in a transaction and +//! rolls back. Needs TAWNY_DATABASE_URL; skips without it. +const std = @import("std"); +const pg = @import("../db/pg/conn.zig"); +const detect = @import("../jobs/detect.zig"); +const incidents = @import("incidents.zig"); + +const testing = std.testing; +const tenant = "00000000-0000-0000-0000-000000000001"; +const other_tenant = "00000000-0000-0000-0000-0000000ee060"; +const agent_a = "00000000-0000-0000-0000-0000000e6001"; +const agent_b = "00000000-0000-0000-0000-0000000e6002"; +const rule_office = "00000000-0000-0000-0000-0000000e6011"; +const rule_enc = "00000000-0000-0000-0000-0000000e6012"; +const rule_ioc = "00000000-0000-0000-0000-0000000e6013"; +const rule_other = "00000000-0000-0000-0000-0000000e6014"; + +// Entity ids: 26 base32 characters. explorer > winword > powershell > child. +const e_explorer = "aaaaaaaaaaaaaaaaaaaaaaaaaa"; +const e_word = "bbbbbbbbbbbbbbbbbbbbbbbbbb"; +const e_ps = "cccccccccccccccccccccccccc"; +const e_child = "dddddddddddddddddddddddddd"; +const e_unrelated = "eeeeeeeeeeeeeeeeeeeeeeeeee"; + +fn connect() !?*pg.Conn { + const url = testing.environ.getPosix("TAWNY_DATABASE_URL") orelse return null; + if (url.len == 0) return null; + return try pg.Conn.connect(testing.allocator, testing.io, url); +} + +fn close(conn: *pg.Conn) void { + conn.close(); + testing.allocator.destroy(conn); +} + +fn exec(conn: *pg.Conn, sql: []const u8, params: []const pg.Value) !void { + conn.execNoRows(sql, params) catch |err| { + if (conn.takeError()) |msg| { + std.debug.print("postgres: {s}\n{s}\n", .{ msg, sql }); + conn.allocator.free(msg); + } + return err; + }; +} + +fn scalar(conn: *pg.Conn, sql: []const u8, params: []const pg.Value) ![]u8 { + const a = testing.allocator; + const rows = conn.exec(a, sql, params) catch |err| { + if (conn.takeError()) |msg| { + std.debug.print("postgres: {s}\n{s}\n", .{ msg, sql }); + conn.allocator.free(msg); + } + return err; + }; + defer { + for (rows) |r| r.deinit(a); + a.free(rows); + } + if (rows.len != 1) return error.UnexpectedRowCount; + return a.dupe(u8, rows[0].cols[0] orelse ""); +} + +fn seed(conn: *pg.Conn) !void { + try exec(conn, + \\INSERT INTO agents (id, tenant_id, hostname, operating_system, os_version, agent_version, architecture, enrolled_at, status) + \\VALUES ($1::uuid, $3::uuid, 'inc-host-a', 'windows', '11', '0', 'x64', now(), 'online'), + \\ ($2::uuid, $3::uuid, 'inc-host-b', 'windows', '11', '0', 'x64', now(), 'online') + , &.{ .{ .text = agent_a }, .{ .text = agent_b }, .{ .text = tenant } }); + try exec(conn, + \\INSERT INTO alert_rules (id, tenant_id, name, format, severity, operator, payload_path, match_value, event_type, mitre_techniques, created_at, updated_at) + \\VALUES ($1::uuid, $5::uuid, 'inc Office spawns PowerShell', 'tawny_predicate', 'high', 'contains', 'process.image', 'inc-office-marker', 'process_start', '{T1204.002,T1059.001}', now(), now()), + \\ ($2::uuid, $5::uuid, 'inc Encoded command', 'tawny_predicate', 'medium', 'contains', 'process.command_line', 'inc-enc-marker', 'process_start', '{T1027}', now(), now()), + \\ ($3::uuid, $5::uuid, 'inc Known bad hash', 'ioc', 'high', 'equals', 'process.hashes.sha256', 'inc-never', 'process_start', '{}', now(), now()), + \\ ($4::uuid, $5::uuid, 'inc Unrelated', 'tawny_predicate', 'low', 'contains', 'process.image', 'inc-never', 'process_start', '{}', now(), now()) + , &.{ .{ .text = rule_office }, .{ .text = rule_enc }, .{ .text = rule_ioc }, .{ .text = rule_other }, .{ .text = tenant } }); + // Lineage: explorer (session root) > winword > powershell > child. + try exec(conn, + \\INSERT INTO process_entities (tenant_id, agent_id, entity_id, parent_entity_id, pid, image, start_time) + \\VALUES ($1::uuid, $2::uuid, $3, NULL, 100, 'C:\Windows\explorer.exe', now()), + \\ ($1::uuid, $2::uuid, $4, $3, 200, 'C:\Program Files\Microsoft Office\WINWORD.EXE', now()), + \\ ($1::uuid, $2::uuid, $5, $4, 300, 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe', now()), + \\ ($1::uuid, $2::uuid, $6, $5, 400, 'C:\Users\a\AppData\Local\Temp\payload.exe', now()), + \\ ($1::uuid, $2::uuid, $7, $3, 500, 'C:\Program Files\Notepad++\notepad++.exe', now()) + , &.{ + .{ .text = tenant }, .{ .text = agent_a }, .{ .text = e_explorer }, .{ .text = e_word }, + .{ .text = e_ps }, .{ .text = e_child }, .{ .text = e_unrelated }, + }); +} + +/// Insert an event and an alert for `rule`, then group it. Returns the incident id. +fn alertOn(conn: *pg.Conn, agent: []const u8, rule: []const u8, rule_name: []const u8, format: []const u8, payload: []const u8, now_unix: i64) ![]u8 { + const a = testing.allocator; + const ev = try conn.exec(a, + \\INSERT INTO telemetry_events (received_at, tenant_id, agent_id, event_type, occurred_at, payload) + \\VALUES (now(), $1::uuid, $2::uuid, 'process_start', now(), $3::jsonb) RETURNING id::text, received_at::text + , &.{ .{ .text = tenant }, .{ .text = agent }, .{ .text = payload } }); + defer { + for (ev) |r| r.deinit(a); + a.free(ev); + } + const al = try conn.exec(a, + \\INSERT INTO alerts (tenant_id, alert_rule_id, agent_id, telemetry_event_id, telemetry_received_at, severity, title, created_at) + \\SELECT $1::uuid, $2::uuid, $3::uuid, $4::bigint, $5::timestamptz, severity, name, now() FROM alert_rules WHERE id = $2::uuid + \\RETURNING id::text, severity + , &.{ .{ .text = tenant }, .{ .text = rule }, .{ .text = agent }, .{ .text = ev[0].cols[0].? }, .{ .text = ev[0].cols[1].? } }); + defer { + for (al) |r| r.deinit(a); + a.free(al); + } + var arena_state = std.heap.ArenaAllocator.init(a); + defer arena_state.deinit(); + const root = try std.json.parseFromSliceLeaky(std.json.Value, arena_state.allocator(), payload, .{}); + var tb: [32]u8 = undefined; + return incidents.attach(a, conn, .{ + .tenant_id = tenant, + .agent_id = agent, + .alert_id = al[0].cols[0].?, + .rule_id = rule, + .rule_name = rule_name, + .rule_format = format, + .severity = al[0].cols[1].?, + .hostname = if (std.mem.eql(u8, agent, agent_a)) "inc-host-a" else "inc-host-b", + .occurred_at = @import("../http/util.zig").formatRfc3339(&tb, now_unix), + .root = root, + }, now_unix); +} + +fn nowUnix() i64 { + return @intCast(std.Io.Clock.now(.real, testing.io).toSeconds()); +} + +test "same host and lineage group into one incident with an explained score" { + const conn = (try connect()) orelse return; + defer close(conn); + try conn.execSimple("BEGIN"); + defer conn.execSimple("ROLLBACK") catch {}; + try seed(conn); + const now = nowUnix(); + const a = testing.allocator; + + // Office starts PowerShell (entity e_ps), then PowerShell's child runs + // an encoded command. Both share the lineage root winword (below explorer). + const first = try alertOn(conn, agent_a, rule_office, "inc Office spawns PowerShell", "tawny_predicate", + \\{"process":{"entity_id":"cccccccccccccccccccccccccc","image":"powershell.exe","user":{"name":"CORP\\alice"}},"parent":{"entity_id":"bbbbbbbbbbbbbbbbbbbbbbbbbb"}} + , now); + defer a.free(first); + const second = try alertOn(conn, agent_a, rule_enc, "inc Encoded command", "tawny_predicate", + \\{"process":{"entity_id":"dddddddddddddddddddddddddd","command_line":"payload.exe -enc AAAA","user":{"name":"CORP\\alice"}}} + , now + 60); + defer a.free(second); + try testing.expectEqualStrings(first, second); + + // A program started from the same Explorer is a different lineage root. + const unrelated = try alertOn(conn, agent_a, rule_other, "inc Unrelated", "tawny_predicate", + \\{"process":{"entity_id":"eeeeeeeeeeeeeeeeeeeeeeeeee","image":"notepad++.exe"}} + , now + 120); + defer a.free(unrelated); + try testing.expect(!std.mem.eql(u8, first, unrelated)); + + const root = try scalar(conn, "SELECT root_entity_id FROM incidents WHERE id = $1::uuid", &.{.{ .text = first }}); + defer a.free(root); + try testing.expectEqualStrings(e_word, root); + const count = try scalar(conn, "SELECT count(*)::text FROM incident_alerts WHERE incident_id = $1::uuid", &.{.{ .text = first }}); + defer a.free(count); + try testing.expectEqualStrings("2", count); + + // Risk: high rule 30 and medium rule 20 -> 100 * (1 - .7 * .8) = 44. + const risk = try scalar(conn, "SELECT risk::text || ' ' || severity || ' ' || jsonb_array_length(risk_items)::text FROM incidents WHERE id = $1::uuid", &.{.{ .text = first }}); + defer a.free(risk); + try testing.expectEqualStrings("44 medium 2", risk); + const points = try scalar(conn, + \\SELECT string_agg((e->>'label') || '=' || (e->>'points'), ',' ORDER BY e->>'label') + \\FROM incidents, jsonb_array_elements(risk_items) e WHERE id = $1::uuid + , &.{.{ .text = first }}); + defer a.free(points); + try testing.expectEqualStrings("inc Encoded command=20,inc Office spawns PowerShell=30", points); + const techs = try scalar(conn, "SELECT array_to_string(techniques, ',') || ' ' || array_to_string(users, ',') FROM incidents WHERE id = $1::uuid", &.{.{ .text = first }}); + defer a.free(techs); + try testing.expectEqualStrings("T1204.002,T1059.001,T1027 corp\\alice", techs); + + // A repeat of the same rule adds the alert but not the evidence. + const again = try alertOn(conn, agent_a, rule_office, "inc Office spawns PowerShell", "tawny_predicate", + \\{"process":{"entity_id":"cccccccccccccccccccccccccc"}} + , now + 180); + defer a.free(again); + try testing.expectEqualStrings(first, again); + const risk2 = try scalar(conn, "SELECT risk::text FROM incidents WHERE id = $1::uuid", &.{.{ .text = first }}); + defer a.free(risk2); + try testing.expectEqualStrings("44", risk2); + std.debug.print("incident_lineage id={s} risk={s} items={s}\n", .{ first, risk, points }); +} + +test "the window, a closed incident and artefact and indicator rules" { + const conn = (try connect()) orelse return; + defer close(conn); + try conn.execSimple("BEGIN"); + defer conn.execSimple("ROLLBACK") catch {}; + try seed(conn); + const a = testing.allocator; + const now = nowUnix(); + const lineage_payload = + \\{"process":{"entity_id":"cccccccccccccccccccccccccc"}} + ; + const first = try alertOn(conn, agent_a, rule_office, "inc Office spawns PowerShell", "tawny_predicate", lineage_payload, now - 5 * 3600); + defer a.free(first); + // Five hours later: outside the four hour window, so a new incident. + const later = try alertOn(conn, agent_a, rule_office, "inc Office spawns PowerShell", "tawny_predicate", lineage_payload, now); + defer a.free(later); + try testing.expect(!std.mem.eql(u8, first, later)); + // Resolved incidents take no new alerts. + try exec(conn, "UPDATE incidents SET status = 'resolved' WHERE id = $1::uuid", &.{.{ .text = later }}); + const after_close = try alertOn(conn, agent_a, rule_office, "inc Office spawns PowerShell", "tawny_predicate", lineage_payload, now + 10); + defer a.free(after_close); + try testing.expect(!std.mem.eql(u8, later, after_close)); + + // Artefact rule: same agent and user plus a shared domain, no entity ids. + const dom1 = try alertOn(conn, agent_b, rule_enc, "inc Encoded command", "tawny_predicate", + \\{"user":{"name":"bob"},"dns":{"query":"bad.example.net"}} + , now); + defer a.free(dom1); + const dom2 = try alertOn(conn, agent_b, rule_other, "inc Unrelated", "tawny_predicate", + \\{"process":{"user":{"name":"BOB"}},"dns":{"query":"bad.example.net."}} + , now + 30); + defer a.free(dom2); + try testing.expectEqualStrings(dom1, dom2); + // Same domain, different user: not grouped. + const dom3 = try alertOn(conn, agent_b, rule_other, "inc Unrelated", "tawny_predicate", + \\{"user":{"name":"carol"},"dns":{"query":"bad.example.net"}} + , now + 40); + defer a.free(dom3); + try testing.expect(!std.mem.eql(u8, dom1, dom3)); + + // Indicator rule: the same IOC rule on two agents is one incident. + const hash = + \\{"process":{"hashes":{"sha256":"1111111111111111111111111111111111111111111111111111111111111111"}}} + ; + const ioc_a = try alertOn(conn, agent_a, rule_ioc, "inc Known bad hash", "ioc", hash, now); + defer a.free(ioc_a); + const ioc_b = try alertOn(conn, agent_b, rule_ioc, "inc Known bad hash", "ioc", hash, now + 5); + defer a.free(ioc_b); + try testing.expectEqualStrings(ioc_a, ioc_b); + const grouping = try scalar(conn, "SELECT grouping || ' ' || cardinality(agent_ids)::text || ' ' || risk::text FROM incidents WHERE id = $1::uuid", &.{.{ .text = ioc_a }}); + defer a.free(grouping); + // One IOC rule counts once (50) even on two agents. + try testing.expectEqualStrings("indicator 2 50", grouping); +} + +test "detect job groups its alerts and incidents stay inside their tenant" { + const conn = (try connect()) orelse return; + defer close(conn); + try conn.execSimple("BEGIN"); + defer conn.execSimple("ROLLBACK") catch {}; + try seed(conn); + const a = testing.allocator; + var cache = detect.RuleCache.init(a); + defer cache.deinit(); + const payload = + \\{"process":{"entity_id":"cccccccccccccccccccccccccc","image":"inc-office-marker","command_line":"x -enc inc-enc-marker"}} + ; + const ev = try conn.exec(a, + \\INSERT INTO telemetry_events (received_at, tenant_id, agent_id, event_type, occurred_at, payload) + \\VALUES (now(), $1::uuid, $2::uuid, 'process_start', now(), $3::jsonb) RETURNING id::text, received_at::text, occurred_at::text + , &.{ .{ .text = tenant }, .{ .text = agent_a }, .{ .text = payload } }); + defer { + for (ev) |r| r.deinit(a); + a.free(ev); + } + try detect.evaluateRules(a, testing.io, conn, &cache, .{ + .tenant_id = tenant, + .agent_id = agent_a, + .hostname = "inc-host-a", + .event_type = "process_start", + .payload = payload, + .event_id = ev[0].cols[0].?, + .received_at = ev[0].cols[1].?, + .occurred_at = ev[0].cols[2].?, + }); + // Both rules matched one event: two alerts, one incident, one SOC update queued. + const n = try scalar(conn, + \\SELECT count(DISTINCT ia.incident_id)::text || '/' || count(*)::text FROM incident_alerts ia + \\JOIN alerts al ON al.id = ia.alert_id WHERE al.telemetry_event_id = $1::bigint + , &.{.{ .text = ev[0].cols[0].? }}); + defer a.free(n); + try testing.expectEqualStrings("1/2", n); + const queued = try scalar(conn, + \\SELECT count(*)::text FROM work_queue WHERE kind = 'incident_sink' + \\ AND payload->>'incident_id' = (SELECT incident_id::text FROM incident_alerts ia JOIN alerts al ON al.id = ia.alert_id + \\ WHERE al.telemetry_event_id = $1::bigint LIMIT 1) + , &.{.{ .text = ev[0].cols[0].? }}); + defer a.free(queued); + try testing.expectEqualStrings("1", queued); + + // Row-level security: the app role in another tenant sees none of it. + try exec(conn, "INSERT INTO tenants (id, slug, name, created_at) VALUES ($1::uuid, 'inc-rls', 'inc rls', now())", &.{.{ .text = other_tenant }}); + try conn.execSimple("SET LOCAL ROLE tawny_app"); + const unset = try scalar(conn, "SELECT count(*)::text FROM incidents", &.{}); + defer a.free(unset); + try testing.expectEqualStrings("0", unset); + try conn.execSimple("SELECT set_config('tawny.tenant_id', '" ++ other_tenant ++ "', true)"); + const hidden = try scalar(conn, "SELECT (SELECT count(*) FROM incidents)::text || '/' || (SELECT count(*) FROM incident_alerts)::text", &.{}); + defer a.free(hidden); + try testing.expectEqualStrings("0/0", hidden); + try conn.execSimple("SELECT set_config('tawny.tenant_id', '" ++ tenant ++ "', true)"); + const own = try scalar(conn, "SELECT (count(*) > 0)::text FROM incidents", &.{}); + defer a.free(own); + try testing.expectEqualStrings("true", own); + std.debug.print("incident_rls unset={s} other={s} own={s}\n", .{ unset, hidden, own }); +} diff --git a/server/src/http/auth.zig b/server/src/http/auth.zig index 168f124..29c7570 100644 --- a/server/src/http/auth.zig +++ b/server/src/http/auth.zig @@ -7,7 +7,37 @@ const state = @import("state.zig"); const Ed25519 = std.crypto.sign.Ed25519; const Sha256 = std.crypto.hash.sha2.Sha256; -pub const Role = enum { admin, viewer }; +pub const Role = enum { admin, analyst, viewer }; + +/// What a route needs. The matrix is in `can` and in docs/api.md; each +/// route file declares the permission of its routes (see http/permissions.zig). +pub const Permission = enum { + /// No session needed (sign-in, health, enrolment). The handler checks its own credential. + public, + /// Agent JWT routes. Web roles never reach them. + agent, + /// Any signed-in user: read agents, alerts, incidents, rules, hunts, coverage. + read, + /// Acknowledge and resolve alerts, assign incidents and change their status. + triage, + /// Run ad hoc and saved hunts. + hunt_run, + /// Request response actions. Destructive ones may wait for admin approval. + respond, + /// Add an exception (suppression rule) with a reason. + exception_create, + /// Users, API tokens, enrolment, integrations, rules, feeds, tenant settings, approvals. + admin, +}; + +pub fn can(role: Role, perm: Permission) bool { + return switch (perm) { + .public, .read => true, + .agent => false, + .triage, .hunt_run, .respond, .exception_create => role == .admin or role == .analyst, + .admin => role == .admin, + }; +} pub const WebUser = struct { user_id: []const u8, @@ -37,6 +67,7 @@ pub const session_cookie_name = "tawny_session"; pub fn roleFromText(s: []const u8) ?Role { if (std.ascii.eqlIgnoreCase(s, "admin")) return .admin; + if (std.ascii.eqlIgnoreCase(s, "analyst")) return .analyst; if (std.ascii.eqlIgnoreCase(s, "viewer")) return .viewer; return null; } @@ -44,6 +75,7 @@ pub fn roleFromText(s: []const u8) ?Role { pub fn roleText(r: Role) []const u8 { return switch (r) { .admin => "admin", + .analyst => "analyst", .viewer => "viewer", }; } @@ -515,5 +547,27 @@ test "parse session cookie" { test "role parse" { try std.testing.expect(roleFromText("Admin").? == .admin); try std.testing.expect(roleFromText("viewer").? == .viewer); + try std.testing.expect(roleFromText("Analyst").? == .analyst); try std.testing.expect(roleFromText("nope") == null); + for (std.meta.fieldNames(Role)) |name| { + const r = std.meta.stringToEnum(Role, name).?; + try std.testing.expectEqualStrings(name, roleText(r)); + try std.testing.expect(roleFromText(name).? == r); + } +} + +test "permission matrix: analyst triages and responds, never administers" { + try std.testing.expect(can(.analyst, .triage)); + try std.testing.expect(can(.analyst, .hunt_run)); + try std.testing.expect(can(.analyst, .respond)); + try std.testing.expect(can(.analyst, .exception_create)); + try std.testing.expect(!can(.analyst, .admin)); + try std.testing.expect(can(.viewer, .read)); + for ([_]Permission{ .triage, .hunt_run, .respond, .exception_create, .admin }) |p| { + try std.testing.expect(!can(.viewer, p)); + try std.testing.expect(can(.admin, p)); + } + for (std.meta.fieldNames(Role)) |name| { + try std.testing.expect(!can(std.meta.stringToEnum(Role, name).?, .agent)); + } } diff --git a/server/src/http/dispatch.zig b/server/src/http/dispatch.zig index 9f60d68..1d28811 100644 --- a/server/src/http/dispatch.zig +++ b/server/src/http/dispatch.zig @@ -18,6 +18,11 @@ const suppressions = @import("../routes/suppressions.zig"); const lookup_http = @import("../routes/lookup.zig"); const ai_http = @import("../routes/ai.zig"); const state = @import("state.zig"); +const permissions = @import("permissions.zig"); +const incidents_http = @import("../routes/incidents.zig"); +const attack_http = @import("../routes/attack.zig"); +const oidc_http = @import("../routes/oidc.zig"); +const settings_http = @import("../routes/settings.zig"); pub fn handle( allocator: std.mem.Allocator, @@ -45,6 +50,15 @@ pub fn handle( return; }; + // Role gate. Every route is declared with its permission in its route + // file; nothing undeclared reaches a handler. + const declared = permissions.lookup(method, parts[0..n]) orelse return notFound(request); + switch (permissions.decide(declared.perm, resolved)) { + .allow => {}, + .unauthorized => return util.respondJson(request, .unauthorized, "{\"title\":\"Unauthorized.\",\"status\":401}"), + .forbidden => return util.respondJson(request, .forbidden, "{\"title\":\"Forbidden.\",\"status\":403}"), + } + route(allocator, io, conn, request, method, target, parts[0..n], resolved, phase) catch |err| { if (conn.takeError()) |msg| { std.debug.print("route {s} {s} failed: {s}: {s}\n", .{ @tagName(method), path, @errorName(err), msg }); @@ -71,6 +85,15 @@ fn route( if (parts.len == 3 and std.mem.eql(u8, parts[2], "login") and method == .POST) { return session.login(allocator, io, conn, request); } + if (parts.len == 3 and std.mem.eql(u8, parts[2], "methods") and method == .GET) { + return session.methods(allocator, conn, request, target); + } + if (parts.len == 4 and std.mem.eql(u8, parts[2], "oidc") and std.mem.eql(u8, parts[3], "start") and method == .GET) { + return oidc_http.start(allocator, io, conn, request, target); + } + if (parts.len == 4 and std.mem.eql(u8, parts[2], "oidc") and std.mem.eql(u8, parts[3], "callback") and method == .GET) { + return oidc_http.callback(allocator, io, conn, request, target); + } if (parts.len == 4 and std.mem.eql(u8, parts[2], "github") and std.mem.eql(u8, parts[3], "start") and method == .GET) { return github.start(allocator, io, conn, request); } @@ -165,9 +188,14 @@ fn route( return agents.streamAgentEvents(allocator, io, conn, request, web, parts[2], phase); } if (parts.len == 4 and std.mem.eql(u8, parts[3], "actions") and method == .POST) { - const web = try needAdmin(request, resolved) orelse return; + const web = try needWeb(request, resolved) orelse return; return agents.createAction(allocator, io, conn, request, web, parts[2]); } + if (parts.len == 6 and std.mem.eql(u8, parts[3], "actions") and std.mem.eql(u8, parts[5], "approve") and method == .POST) { + const web = try needAdmin(request, resolved) orelse return; + if (try stopLimited(request, io, web, policy_web_admin_mutate)) return; + return agents.approveAction(allocator, io, conn, request, web, parts[2], parts[4]); + } if (parts.len == 4 and std.mem.eql(u8, parts[3], "actions") and method == .GET) { const web = try needWeb(request, resolved) orelse return; return listActions(allocator, conn, request, web, parts[2]); @@ -301,8 +329,8 @@ fn route( return suppressions.list(allocator, conn, request, web); } if (parts.len == 2 and method == .POST) { - const web = try needAdmin(request, resolved) orelse return; - if (try stopLimited(request, io, web, policy_web_admin_mutate)) return; + const web = try needWeb(request, resolved) orelse return; + if (try stopLimited(request, io, web, policy_web_mutate)) return; return suppressions.create(allocator, io, conn, request, web); } if (parts.len == 3 and method == .PUT) { @@ -328,6 +356,47 @@ fn route( if (try stopLimited(request, io, web, policy_web_read)) return; return alerts.getAlert(allocator, conn, request, web, parts[2]); } + if (parts.len == 4 and method == .POST and (std.mem.eql(u8, parts[3], "acknowledge") or std.mem.eql(u8, parts[3], "resolve"))) { + if (try stopLimited(request, io, web, policy_web_mutate)) return; + return incidents_http.setAlertStatus(allocator, io, conn, request, web, parts[2], parts[3]); + } + return notFound(request); + } + + if (parts.len >= 2 and std.mem.eql(u8, parts[0], "api") and std.mem.eql(u8, parts[1], "incidents")) { + const web = try needWeb(request, resolved) orelse return; + if (parts.len == 2 and method == .GET) { + if (try stopLimited(request, io, web, policy_web_read)) return; + return incidents_http.list(allocator, conn, request, web, target); + } + if (parts.len == 3 and method == .GET) { + if (try stopLimited(request, io, web, policy_web_read)) return; + return incidents_http.get(allocator, conn, request, web, parts[2]); + } + if (parts.len == 4 and method == .POST and std.mem.eql(u8, parts[3], "assign")) { + if (try stopLimited(request, io, web, policy_web_mutate)) return; + return incidents_http.assign(allocator, io, conn, request, web, parts[2]); + } + if (parts.len == 4 and method == .POST and std.mem.eql(u8, parts[3], "status")) { + if (try stopLimited(request, io, web, policy_web_mutate)) return; + return incidents_http.setStatus(allocator, io, conn, request, web, parts[2]); + } + return notFound(request); + } + + if (parts.len == 3 and std.mem.eql(u8, parts[0], "api") and std.mem.eql(u8, parts[1], "attack") and std.mem.eql(u8, parts[2], "coverage") and method == .GET) { + const web = try needWeb(request, resolved) orelse return; + if (try stopLimited(request, io, web, policy_web_read)) return; + return attack_http.coverage(allocator, conn, request, web, target); + } + + if (parts.len == 3 and std.mem.eql(u8, parts[0], "api") and std.mem.eql(u8, parts[1], "settings")) { + const web = try needAdmin(request, resolved) orelse return; + if (std.mem.eql(u8, parts[2], "tenant") and method == .GET) return settings_http.getTenant(allocator, conn, request, web); + if (std.mem.eql(u8, parts[2], "oidc") and method == .GET) return settings_http.getOidc(allocator, conn, request, web); + if (try stopLimited(request, io, web, policy_web_admin_mutate)) return; + if (std.mem.eql(u8, parts[2], "tenant") and method == .PUT) return settings_http.putTenant(allocator, io, conn, request, web); + if (std.mem.eql(u8, parts[2], "oidc") and method == .PUT) return settings_http.putOidc(allocator, io, conn, request, web); return notFound(request); } diff --git a/server/src/http/permissions.zig b/server/src/http/permissions.zig new file mode 100644 index 0000000..7ce48d5 --- /dev/null +++ b/server/src/http/permissions.zig @@ -0,0 +1,257 @@ +//! Route permission gate. Each file in `routes/` declares `pub const routes`, +//! a table of method, path pattern and the `auth.Permission` it needs. +//! Dispatch looks the request up here before it calls a handler, so a route +//! missing from every table answers 404 and a role without the permission +//! answers 403. The matrix is written out in docs/api.md. +const std = @import("std"); +const auth = @import("auth.zig"); + +pub const Route = struct { + method: std.http.Method, + /// `/api/agents/:id/actions`. `:name` matches one non-empty segment. + path: []const u8, + perm: auth.Permission, +}; + +const tables = .{ + @import("../routes/auth.zig").routes, + @import("../routes/github.zig").routes, + @import("../routes/oidc.zig").routes, + @import("../routes/users.zig").routes, + @import("../routes/tokens.zig").routes, + @import("../routes/agents.zig").routes, + @import("../routes/yara_rules.zig").routes, + @import("../routes/agent_releases.zig").routes, + @import("../routes/alerts.zig").routes, + @import("../routes/incidents.zig").routes, + @import("../routes/attack.zig").routes, + @import("../routes/hunts.zig").routes, + @import("../routes/feeds.zig").routes, + @import("../routes/suppressions.zig").routes, + @import("../routes/lookup.zig").routes, + @import("../routes/admin_jobs.zig").routes, + @import("../routes/ai.zig").routes, + @import("../routes/settings.zig").routes, +}; + +pub const all: []const Route = blk: { + var list: []const Route = &.{}; + for (tables) |t| list = list ++ t; + break :blk &list[0..list.len].*; +}; + +fn segmentsMatch(pattern: []const u8, parts: []const []const u8) bool { + var it = std.mem.splitScalar(u8, pattern, '/'); + var i: usize = 0; + while (it.next()) |seg| { + if (seg.len == 0) continue; + if (i >= parts.len) return false; + if (seg[0] == ':') { + if (parts[i].len == 0) return false; + } else if (!std.mem.eql(u8, seg, parts[i])) return false; + i += 1; + } + return i == parts.len; +} + +/// Literal segments win over `:param` ones, so `/api/agents/enroll` is not +/// read as `/api/agents/:id`. +pub fn lookup(method: std.http.Method, parts: []const []const u8) ?Route { + var best: ?Route = null; + var best_literals: usize = 0; + for (all) |r| { + if (r.method != method) continue; + if (!segmentsMatch(r.path, parts)) continue; + const lits = literalCount(r.path); + if (best == null or lits > best_literals) { + best = r; + best_literals = lits; + } + } + return best; +} + +fn literalCount(pattern: []const u8) usize { + var n: usize = 0; + var it = std.mem.splitScalar(u8, pattern, '/'); + while (it.next()) |seg| { + if (seg.len != 0 and seg[0] != ':') n += 1; + } + return n; +} + +pub const Decision = enum { allow, unauthorized, forbidden }; + +pub fn decide(perm: auth.Permission, resolved: auth.Auth) Decision { + return switch (perm) { + .public => .allow, + .agent => if (auth.requireAgent(resolved) != null) .allow else .unauthorized, + else => blk: { + const web = auth.requireWeb(resolved) orelse break :blk .unauthorized; + break :blk if (auth.can(web.role, perm)) .allow else .forbidden; + }, + }; +} + +fn split(path: []const u8, out: *[8][]const u8) []const []const u8 { + var n: usize = 0; + var it = std.mem.splitScalar(u8, path, '/'); + while (it.next()) |p| { + if (p.len == 0) continue; + out[n] = p; + n += 1; + } + return out[0..n]; +} + +fn webAs(role: auth.Role) auth.Auth { + return .{ .web = .{ .user_id = "u", .tenant_id = "t", .email = "", .role = role } }; +} + +/// One row per route: what admin, analyst and viewer get. `a` allow, `f` +/// forbidden. Public and agent routes are listed with their own markers. +const Expect = struct { method: std.http.Method, path: []const u8, admin: u8, analyst: u8, viewer: u8 }; + +const expected = [_]Expect{ + // Sign-in and session + .{ .method = .POST, .path = "/api/auth/login", .admin = 'p', .analyst = 'p', .viewer = 'p' }, + .{ .method = .GET, .path = "/api/auth/methods", .admin = 'p', .analyst = 'p', .viewer = 'p' }, + .{ .method = .GET, .path = "/api/auth/github/start", .admin = 'p', .analyst = 'p', .viewer = 'p' }, + .{ .method = .GET, .path = "/api/auth/github/callback", .admin = 'p', .analyst = 'p', .viewer = 'p' }, + .{ .method = .GET, .path = "/api/auth/oidc/start", .admin = 'p', .analyst = 'p', .viewer = 'p' }, + .{ .method = .GET, .path = "/api/auth/oidc/callback", .admin = 'p', .analyst = 'p', .viewer = 'p' }, + .{ .method = .POST, .path = "/api/auth/logout", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .GET, .path = "/api/auth/session", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .POST, .path = "/api/auth/password", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + // Users and tokens + .{ .method = .GET, .path = "/api/users", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .POST, .path = "/api/users", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .PUT, .path = "/api/users/x", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .DELETE, .path = "/api/users/x", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .POST, .path = "/api/api-tokens", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .GET, .path = "/api/api-tokens", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .GET, .path = "/api/audit-logs", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + // Agents and response + .{ .method = .POST, .path = "/api/enrollment-tokens", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .POST, .path = "/api/agents/enroll", .admin = 'p', .analyst = 'p', .viewer = 'p' }, + .{ .method = .POST, .path = "/api/agents/heartbeat", .admin = 'g', .analyst = 'g', .viewer = 'g' }, + .{ .method = .POST, .path = "/api/agents/events", .admin = 'g', .analyst = 'g', .viewer = 'g' }, + .{ .method = .POST, .path = "/api/agents/x/actions/y/result", .admin = 'g', .analyst = 'g', .viewer = 'g' }, + .{ .method = .POST, .path = "/api/agent/yara-rules", .admin = 'g', .analyst = 'g', .viewer = 'g' }, + .{ .method = .POST, .path = "/api/agent/update-check", .admin = 'g', .analyst = 'g', .viewer = 'g' }, + .{ .method = .GET, .path = "/api/agents", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .GET, .path = "/api/agents/x", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .POST, .path = "/api/agents/x/revoke", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .GET, .path = "/api/agents/x/events", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .GET, .path = "/api/agents/x/events/stream", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .GET, .path = "/api/agents/x/process-tree", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .POST, .path = "/api/agents/x/actions", .admin = 'a', .analyst = 'a', .viewer = 'f' }, + .{ .method = .GET, .path = "/api/agents/x/actions", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .GET, .path = "/api/agents/x/actions/y", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .POST, .path = "/api/agents/x/actions/y/approve", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .GET, .path = "/api/releases/latest", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .GET, .path = "/api/yara/rule-key", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + // Rules + .{ .method = .GET, .path = "/api/alert-rules", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .POST, .path = "/api/alert-rules", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .POST, .path = "/api/alert-rules/exposures", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .POST, .path = "/api/alert-rules/yara", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .POST, .path = "/api/alert-rules/sigma", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .POST, .path = "/api/alert-rules/iocs", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .PUT, .path = "/api/alert-rules/x", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .DELETE, .path = "/api/alert-rules/x", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + // Alerts and incidents + .{ .method = .GET, .path = "/api/alerts", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .GET, .path = "/api/alerts/x", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .POST, .path = "/api/alerts/x/acknowledge", .admin = 'a', .analyst = 'a', .viewer = 'f' }, + .{ .method = .POST, .path = "/api/alerts/x/resolve", .admin = 'a', .analyst = 'a', .viewer = 'f' }, + .{ .method = .GET, .path = "/api/incidents", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .GET, .path = "/api/incidents/x", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .POST, .path = "/api/incidents/x/assign", .admin = 'a', .analyst = 'a', .viewer = 'f' }, + .{ .method = .POST, .path = "/api/incidents/x/status", .admin = 'a', .analyst = 'a', .viewer = 'f' }, + .{ .method = .GET, .path = "/api/attack/coverage", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + // Hunts + .{ .method = .POST, .path = "/api/hunts/run", .admin = 'a', .analyst = 'a', .viewer = 'f' }, + .{ .method = .GET, .path = "/api/hunts", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .POST, .path = "/api/hunts", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .GET, .path = "/api/hunts/x", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .PUT, .path = "/api/hunts/x", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .DELETE, .path = "/api/hunts/x", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .POST, .path = "/api/hunts/x/run", .admin = 'a', .analyst = 'a', .viewer = 'f' }, + .{ .method = .GET, .path = "/api/hunts/x/runs", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + // Feeds, exceptions, lookup + .{ .method = .GET, .path = "/api/threat-intel-feeds", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .POST, .path = "/api/threat-intel-feeds", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .PUT, .path = "/api/threat-intel-feeds/x", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .DELETE, .path = "/api/threat-intel-feeds/x", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .POST, .path = "/api/threat-intel-feeds/x/run", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .GET, .path = "/api/suppression-rules", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .POST, .path = "/api/suppression-rules", .admin = 'a', .analyst = 'a', .viewer = 'f' }, + .{ .method = .PUT, .path = "/api/suppression-rules/x", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .DELETE, .path = "/api/suppression-rules/x", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .POST, .path = "/api/threat-intel/lookup", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + // Jobs, AI, settings + .{ .method = .GET, .path = "/api/admin/jobs", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .GET, .path = "/api/ai/config", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .PUT, .path = "/api/ai/config", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .GET, .path = "/api/ai/findings", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .GET, .path = "/api/ai/findings/x", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .GET, .path = "/api/ai/investigations", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .GET, .path = "/api/ai/investigations/x", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .GET, .path = "/api/ai/metrics", .admin = 'a', .analyst = 'a', .viewer = 'a' }, + .{ .method = .POST, .path = "/api/ai/observations", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .GET, .path = "/api/settings/tenant", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .PUT, .path = "/api/settings/tenant", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .GET, .path = "/api/settings/oidc", .admin = 'a', .analyst = 'f', .viewer = 'f' }, + .{ .method = .PUT, .path = "/api/settings/oidc", .admin = 'a', .analyst = 'f', .viewer = 'f' }, +}; + +test "every route answers each role as the matrix says" { + const agent_auth: auth.Auth = .{ .agent = .{ .agent_id = "a", .tenant_id = "t", .cv = 1, .exp = 0 } }; + for (expected) |e| { + var buf: [8][]const u8 = undefined; + const parts = split(e.path, &buf); + const r = lookup(e.method, parts) orelse { + std.debug.print("no route for {s} {s}\n", .{ @tagName(e.method), e.path }); + return error.MissingRoute; + }; + const roles = [_]struct { role: auth.Role, want: u8 }{ + .{ .role = .admin, .want = e.admin }, + .{ .role = .analyst, .want = e.analyst }, + .{ .role = .viewer, .want = e.viewer }, + }; + for (roles) |rr| { + const got = decide(r.perm, webAs(rr.role)); + const want: Decision = switch (rr.want) { + 'a', 'p' => .allow, + 'f' => .forbidden, + // Agent routes refuse every web role. + 'g' => .unauthorized, + else => unreachable, + }; + if (got != want) { + std.debug.print("{s} {s} as {s}: got {s}, want {s}\n", .{ @tagName(e.method), e.path, @tagName(rr.role), @tagName(got), @tagName(want) }); + return error.MatrixMismatch; + } + } + // Anonymous callers: public routes allow, everything else is 401. + const anon = decide(r.perm, .none); + try std.testing.expectEqual(if (e.admin == 'p') Decision.allow else Decision.unauthorized, anon); + if (e.admin == 'g') try std.testing.expectEqual(Decision.allow, decide(r.perm, agent_auth)); + } + // The matrix lists every declared route, and nothing twice. + try std.testing.expectEqual(all.len, expected.len); + for (all, 0..) |a, i| { + for (all[i + 1 ..]) |b| { + try std.testing.expect(!(a.method == b.method and std.mem.eql(u8, a.path, b.path))); + } + } +} + +test "literal segments beat parameters" { + var buf: [8][]const u8 = undefined; + const r = lookup(.POST, split("/api/agents/enroll", &buf)).?; + try std.testing.expectEqual(auth.Permission.public, r.perm); + try std.testing.expect(lookup(.GET, split("/api/nope", &buf)) == null); + try std.testing.expect(lookup(.PATCH, split("/api/users/x", &buf)) == null); +} diff --git a/server/src/jobs/detect.zig b/server/src/jobs/detect.zig index d2d5369..cb35910 100644 --- a/server/src/jobs/detect.zig +++ b/server/src/jobs/detect.zig @@ -9,6 +9,7 @@ const ast = @import("../detect/ast.zig"); const tawny_rule = @import("../detect/tawny_rule.zig"); const sequence = @import("../detect/sequence.zig"); const threshold = @import("../detect/threshold.zig"); +const incidents = @import("../detect/incidents.zig"); /// Compiled rule expressions, parsed once per drain. Keyed by rule id and /// updated_at so an edited rule is parsed again. @@ -299,7 +300,11 @@ pub fn evaluateRules( , &.{ .{ .text = sid }, .{ .text = created } }); continue; } - try raiseAlert(allocator, conn, e, row.cols[0].?, row.cols[1] orelse "rule", row.cols[2] orelse "medium", description, created); + try raiseAlert(allocator, conn, e, row.cols[0].?, row.cols[1] orelse "rule", row.cols[2] orelse "medium", description, created, .{ + .format = format, + .root = root, + .now_unix = now, + }); } } @@ -338,6 +343,7 @@ fn raiseAlert( severity: []const u8, description: ?[]const u8, created: []const u8, + group: Group, ) !void { const title = try std.fmt.allocPrint(allocator, "{s} on {s}", .{ rule_name, e.hostname }); defer allocator.free(title); @@ -365,6 +371,53 @@ fn raiseAlert( enqueueSink(allocator, conn, e.tenant_id, inserted[0].cols[0].?) catch |err| { std.debug.print("sink enqueue failed: {s}\n", .{@errorName(err)}); }; + // Group into an incident (target-edr section 8). A grouping failure must + // not lose the alert, which is already stored. + const incident_id = incidents.attach(allocator, conn, .{ + .tenant_id = e.tenant_id, + .agent_id = e.agent_id, + .alert_id = inserted[0].cols[0].?, + .rule_id = rule_id, + .rule_name = rule_name, + .rule_format = group.format, + .severity = severity, + .hostname = e.hostname, + .occurred_at = e.occurred_at, + .root = group.root, + }, group.now_unix) catch |err| { + if (conn.takeError()) |msg| { + defer conn.allocator.free(msg); + std.debug.print("incident grouping failed: {s}: {s}\n", .{ @errorName(err), msg }); + } else std.debug.print("incident grouping failed: {s}\n", .{@errorName(err)}); + return; + }; + defer allocator.free(incident_id); + enqueueIncidentSink(allocator, conn, e.tenant_id, incident_id) catch |err| { + std.debug.print("incident sink enqueue failed: {s}\n", .{@errorName(err)}); + }; +} + +const Group = struct { + format: []const u8, + root: std.json.Value, + now_unix: i64, +}; + +/// One pending Tawny-SOC update per incident: later alerts within the +/// debounce reuse the queued row (target-edr section 8, "debounced"). +fn enqueueIncidentSink(allocator: std.mem.Allocator, conn: *pg.Conn, tenant_id: []const u8, incident_id: []const u8) !void { + const id_j = try util.escapeJson(allocator, incident_id); + defer allocator.free(id_j); + const payload = try std.fmt.allocPrint(allocator, "{{\"incident_id\":{s}}}", .{id_j}); + defer allocator.free(payload); + try conn.execNoRows( + \\INSERT INTO work_queue (kind, tenant_id, payload, run_after) + \\SELECT 'incident_sink', $1::uuid, $2::jsonb, now() + interval '30 seconds' + \\WHERE NOT EXISTS ( + \\ SELECT 1 FROM work_queue WHERE kind = 'incident_sink' AND payload->>'incident_id' = $3 + \\ AND locked_until IS NULL + \\) + , &.{ .{ .text = tenant_id }, .{ .text = payload }, .{ .text = incident_id } }); } fn matchingSuppression(rules: []const pg.Row, rule_id: []const u8, agent_id: []const u8, root: std.json.Value) ?[]const u8 { diff --git a/server/src/main.zig b/server/src/main.zig index f07fce7..87b219a 100644 --- a/server/src/main.zig +++ b/server/src/main.zig @@ -462,6 +462,13 @@ comptime { _ = @import("http/dispatch.zig"); _ = @import("http/state.zig"); _ = @import("http/auth.zig"); + _ = @import("http/permissions.zig"); + _ = @import("routes/settings.zig"); + _ = @import("routes/incidents.zig"); + _ = @import("routes/attack.zig"); + _ = @import("routes/oidc.zig"); + _ = @import("detect/incidents.zig"); + _ = @import("detect/incidents_test.zig"); _ = @import("http/util.zig"); _ = @import("http/static.zig"); _ = @import("routes/admin_jobs.zig"); diff --git a/server/src/routes/admin_jobs.zig b/server/src/routes/admin_jobs.zig index 695bc7c..1e3b360 100644 --- a/server/src/routes/admin_jobs.zig +++ b/server/src/routes/admin_jobs.zig @@ -4,6 +4,12 @@ const pg = @import("../db/pg/conn.zig"); const util = @import("../http/util.zig"); const auth = @import("../http/auth.zig"); +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .GET, .path = "/api/admin/jobs", .perm = .admin }, +}; + + pub fn list( allocator: std.mem.Allocator, conn: *pg.Conn, diff --git a/server/src/routes/agent_releases.zig b/server/src/routes/agent_releases.zig index df35520..a43885b 100644 --- a/server/src/routes/agent_releases.zig +++ b/server/src/routes/agent_releases.zig @@ -5,6 +5,13 @@ const pg = @import("../db/pg/conn.zig"); const util = @import("../http/util.zig"); const auth = @import("../http/auth.zig"); +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .POST, .path = "/api/agent/update-check", .perm = .agent }, + .{ .method = .GET, .path = "/api/releases/latest", .perm = .read }, +}; + + pub fn latest( allocator: std.mem.Allocator, conn: *pg.Conn, diff --git a/server/src/routes/agents.zig b/server/src/routes/agents.zig index 89fc3c2..8735ca3 100644 --- a/server/src/routes/agents.zig +++ b/server/src/routes/agents.zig @@ -2,6 +2,7 @@ const std = @import("std"); const pg = @import("../db/pg/conn.zig"); const util = @import("../http/util.zig"); const auth = @import("../http/auth.zig"); +const settings = @import("settings.zig"); const audit = @import("../http/audit.zig"); const state = @import("../http/state.zig"); const batch_sig = @import("../crypto/batch_sig.zig"); @@ -12,6 +13,26 @@ const ingest_entity = @import("../ingest/entity.zig"); const legacy = @import("../ingest/legacy.zig"); const process_store = @import("../ingest/process_store.zig"); const agent_alerts = @import("../jobs/agent_alerts.zig"); + +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .POST, .path = "/api/enrollment-tokens", .perm = .admin }, + .{ .method = .POST, .path = "/api/agents/enroll", .perm = .public }, + .{ .method = .POST, .path = "/api/agents/heartbeat", .perm = .agent }, + .{ .method = .POST, .path = "/api/agents/events", .perm = .agent }, + .{ .method = .POST, .path = "/api/agents/:id/actions/:action/result", .perm = .agent }, + .{ .method = .GET, .path = "/api/agents", .perm = .read }, + .{ .method = .GET, .path = "/api/agents/:id", .perm = .read }, + .{ .method = .POST, .path = "/api/agents/:id/revoke", .perm = .admin }, + .{ .method = .GET, .path = "/api/agents/:id/events", .perm = .read }, + .{ .method = .GET, .path = "/api/agents/:id/events/stream", .perm = .read }, + .{ .method = .GET, .path = "/api/agents/:id/process-tree", .perm = .read }, + .{ .method = .POST, .path = "/api/agents/:id/actions", .perm = .respond }, + .{ .method = .GET, .path = "/api/agents/:id/actions", .perm = .read }, + .{ .method = .GET, .path = "/api/agents/:id/actions/:action", .perm = .read }, + .{ .method = .POST, .path = "/api/agents/:id/actions/:action/approve", .perm = .admin }, +}; + const Sha256 = std.crypto.hash.sha2.Sha256; pub fn createEnrollmentToken( @@ -1009,6 +1030,11 @@ pub fn createAction( if (try respondIdempotent(allocator, conn, request, web.tenant_id, agent_id, k)) return; } + // An analyst's destructive action waits for an admin when the tenant asks + // for that (target-edr section 9.2). The agent only receives 'pending'. + const status: []const u8 = if (web.role != .admin and isDestructive(parsed.value.action_type) and + try settings.analystNeedsApproval(allocator, conn, web.tenant_id)) "awaiting_approval" else "pending"; + var payload_buf: std.ArrayList(u8) = .empty; defer payload_buf.deinit(allocator); const payload_tmp = try std.json.Stringify.valueAlloc(allocator, parsed.value.payload, .{}); @@ -1028,7 +1054,7 @@ pub fn createAction( conn.execNoRows( \\INSERT INTO response_actions (id, agent_id, tenant_id, action_type, status, requested_by_user_id, \\ requested_at, expires_at, payload_json, payload_hash, idempotency_key) - \\VALUES ($1::uuid, $2::uuid, $3::uuid, $4, 'pending', $5::uuid, $6::timestamptz, $7::timestamptz, $8::jsonb, $9, $10) + \\VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $11, $5::uuid, $6::timestamptz, $7::timestamptz, $8::jsonb, $9, $10) , &.{ .{ .text = id }, .{ .text = agent_id }, @@ -1040,6 +1066,7 @@ pub fn createAction( .{ .text = payload_buf.items }, .{ .text = ph }, if (idem_key) |k| .{ .text = k } else .{ .null = {} }, + .{ .text = status }, }) catch |err| { if (idem_key) |k| { if (err == error.QueryFailed) { @@ -1067,12 +1094,75 @@ pub fn createAction( const ph_j = try util.escapeJson(allocator, ph); defer allocator.free(ph_j); const json = try std.fmt.allocPrint(allocator, - \\{{"id":{s},"agent_id":{s},"action_type":{s},"status":"pending","requested_at":{s},"expires_at":{s},"payload":{s},"payload_hash":{s}}} - , .{ id_j, aid_j, at_j, req_j, exp_j, payload_buf.items, ph_j }); + \\{{"id":{s},"agent_id":{s},"action_type":{s},"status":"{s}","requested_at":{s},"expires_at":{s},"payload":{s},"payload_hash":{s}}} + , .{ id_j, aid_j, at_j, status, req_j, exp_j, payload_buf.items, ph_j }); defer allocator.free(json); try util.respondJson(request, .created, json); } +/// Isolation and quarantine cut a host off or move a file. Killing or +/// suspending one process is not in this set. +pub fn isDestructive(action_type: []const u8) bool { + const set = [_][]const u8{ "isolate_host", "isolate", "quarantine_file" }; + for (set) |t| if (std.mem.eql(u8, t, action_type)) return true; + return false; +} + +/// Admin approval for an action an analyst requested. The approver must not +/// be the requester. The deadline restarts so the agent gets the full window. +pub fn approveAction( + allocator: std.mem.Allocator, + io: std.Io, + conn: *pg.Conn, + request: *std.http.Server.Request, + web: auth.WebUser, + agent_id: []const u8, + action_id: []const u8, +) !void { + if (web.session_id != null and !auth.checkCsrf(request, web)) { + try util.respondJson(request, .forbidden, "{\"error\":\"csrf\"}"); + return; + } + var t1: [32]u8 = undefined; + var t2: [32]u8 = undefined; + const now = util.nowUnix(io); + const approved = util.formatRfc3339(&t1, now); + const expires = util.formatRfc3339(&t2, now + 15 * 60); + const rows = try conn.exec(allocator, + \\UPDATE response_actions SET status = 'pending', approved_by_user_id = $4::uuid, + \\ approved_at = $5::timestamptz, expires_at = $6::timestamptz + \\WHERE tenant_id = $1::uuid AND agent_id = $2::uuid AND id = $3::uuid + \\ AND status = 'awaiting_approval' + \\ AND requested_by_user_id IS DISTINCT FROM $4::uuid + \\RETURNING id::text + , &.{ + .{ .text = web.tenant_id }, + .{ .text = agent_id }, + .{ .text = action_id }, + .{ .text = web.user_id }, + .{ .text = approved }, + .{ .text = expires }, + }); + defer { + for (rows) |row| row.deinit(allocator); + allocator.free(rows); + } + if (rows.len == 0) return util.problem(request, allocator, .conflict, "No action awaiting approval by another admin."); + try audit.add(allocator, io, conn, web.tenant_id, web.user_id, "response_action.approve", action_id, null); + const id_j = try util.escapeJson(allocator, action_id); + defer allocator.free(id_j); + const json = try std.fmt.allocPrint(allocator, "{{\"id\":{s},\"status\":\"pending\"}}", .{id_j}); + defer allocator.free(json); + try util.respondJson(request, .ok, json); +} + +test "only isolation and quarantine are destructive" { + try std.testing.expect(isDestructive("isolate_host")); + try std.testing.expect(isDestructive("quarantine_file")); + try std.testing.expect(!isDestructive("kill_process")); + try std.testing.expect(!isDestructive("release_host")); +} + /// Parse then compact-serialize a JSON payload, matching the bytes the agent /// reconstructs from the payload field. Caller frees. fn reserializePayload(allocator: std.mem.Allocator, raw: []const u8) ![]u8 { diff --git a/server/src/routes/ai.zig b/server/src/routes/ai.zig index ee6e38c..4a30899 100644 --- a/server/src/routes/ai.zig +++ b/server/src/routes/ai.zig @@ -17,6 +17,19 @@ const auth = @import("../http/auth.zig"); const reasoning = @import("../ai/reasoning.zig"); const ai_job = @import("../jobs/ai_reasoning.zig"); +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .GET, .path = "/api/ai/config", .perm = .read }, + .{ .method = .PUT, .path = "/api/ai/config", .perm = .admin }, + .{ .method = .GET, .path = "/api/ai/findings", .perm = .read }, + .{ .method = .GET, .path = "/api/ai/findings/:id", .perm = .read }, + .{ .method = .GET, .path = "/api/ai/investigations", .perm = .read }, + .{ .method = .GET, .path = "/api/ai/investigations/:id", .perm = .read }, + .{ .method = .GET, .path = "/api/ai/metrics", .perm = .read }, + .{ .method = .POST, .path = "/api/ai/observations", .perm = .admin }, +}; + + /// GET /api/ai/config — Get current AI configuration. pub fn getConfig( allocator: std.mem.Allocator, diff --git a/server/src/routes/alerts.zig b/server/src/routes/alerts.zig index ae300fb..12bba39 100644 --- a/server/src/routes/alerts.zig +++ b/server/src/routes/alerts.zig @@ -7,6 +7,22 @@ const audit = @import("../http/audit.zig"); const exposure_import = @import("../detect/exposure_import.zig"); const sigma = @import("../detect/sigma.zig"); +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .GET, .path = "/api/alert-rules", .perm = .read }, + .{ .method = .POST, .path = "/api/alert-rules", .perm = .admin }, + .{ .method = .POST, .path = "/api/alert-rules/exposures", .perm = .admin }, + .{ .method = .POST, .path = "/api/alert-rules/sigma", .perm = .admin }, + .{ .method = .POST, .path = "/api/alert-rules/iocs", .perm = .admin }, + .{ .method = .PUT, .path = "/api/alert-rules/:id", .perm = .admin }, + .{ .method = .DELETE, .path = "/api/alert-rules/:id", .perm = .admin }, + .{ .method = .GET, .path = "/api/alerts", .perm = .read }, + .{ .method = .GET, .path = "/api/alerts/:id", .perm = .read }, + .{ .method = .POST, .path = "/api/alerts/:id/acknowledge", .perm = .triage }, + .{ .method = .POST, .path = "/api/alerts/:id/resolve", .perm = .triage }, +}; + + fn ruleResponseJson(allocator: std.mem.Allocator, cols: []const ?[]u8) ![]u8 { // id name format external_id description event_type severity operator payload_path match_value source_definition is_enabled mitre created updated const id = try util.escapeJson(allocator, cols[0] orelse ""); diff --git a/server/src/routes/attack.zig b/server/src/routes/attack.zig new file mode 100644 index 0000000..a328a67 --- /dev/null +++ b/server/src/routes/attack.zig @@ -0,0 +1,327 @@ +//! GET /api/attack/coverage (docs/architecture/target-edr.md section 6). +//! +//! Three states per technique, each from its own source: +//! telemetry a healthy agent (seen in 15 minutes, no failed sensor) sent +//! one of the technique's event types in the last 24 hours +//! detection an enabled rule in this tenant lists the technique +//! response an action in coverage.yaml applies on the platform +//! No state is read from another. A technique with a rule but no telemetry +//! shows detection true and telemetry false. +//! +//! Names and tactics: rules/attack/techniques.json (ATT&CK Enterprise 20.1 +//! subset), embedded from server/src/detect/attack/ (a test checks the copy). +const std = @import("std"); +const pg = @import("../db/pg/conn.zig"); +const util = @import("../http/util.zig"); +const auth = @import("../http/auth.zig"); +const yaml = @import("../detect/yaml.zig"); + +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .GET, .path = "/api/attack/coverage", .perm = .read }, +}; + +pub const coverage_yaml = @embedFile("../detect/attack/coverage.yaml"); +pub const techniques_json = @embedFile("../detect/attack/techniques.json"); + +pub const Technique = struct { + id: []const u8, + name: []const u8, + tactics: []const []const u8, + platforms: []const []const u8, +}; +pub const Tactic = struct { shortname: []const u8, name: []const u8, id: []const u8 }; +pub const Catalog = struct { + attack_version: []const u8, + tactics: []const Tactic, + techniques: []const Technique, +}; + +pub const Entry = struct { + id: []const u8, + telemetry: []const []const u8, + response: []const []const u8, +}; + +pub const Map = struct { + attack_version: []const u8, + /// action name -> platforms + actions: []const struct { name: []const u8, platforms: []const []const u8 }, + entries: []const Entry, +}; + +pub fn loadCatalog(arena: std.mem.Allocator) !Catalog { + return std.json.parseFromSliceLeaky(Catalog, arena, techniques_json, .{ .ignore_unknown_fields = true }); +} + +fn strList(arena: std.mem.Allocator, node: ?yaml.Node) ![]const []const u8 { + const n = node orelse return &.{}; + if (n != .list) return &.{}; + var out: std.ArrayList([]const u8) = .empty; + for (n.list) |item| { + if (item.str()) |s| try out.append(arena, s); + } + return out.toOwnedSlice(arena); +} + +pub fn loadMap(arena: std.mem.Allocator) !Map { + const root = try yaml.parse(arena, coverage_yaml); + const version = (root.get("attack_version") orelse return error.BadCoverage).str() orelse return error.BadCoverage; + const ActionT = @typeInfo(@FieldType(Map, "actions")).pointer.child; + var actions: std.ArrayList(ActionT) = .empty; + if (root.get("actions")) |a| { + if (a != .map) return error.BadCoverage; + for (a.map) |e| try actions.append(arena, .{ .name = e.key, .platforms = try strList(arena, e.value) }); + } + var entries: std.ArrayList(Entry) = .empty; + const techs = root.get("techniques") orelse return error.BadCoverage; + if (techs != .list) return error.BadCoverage; + for (techs.list) |t| { + const id = (t.get("id") orelse return error.BadCoverage).str() orelse return error.BadCoverage; + try entries.append(arena, .{ + .id = id, + .telemetry = try strList(arena, t.get("telemetry")), + .response = try strList(arena, t.get("response")), + }); + } + return .{ .attack_version = version, .actions = try actions.toOwnedSlice(arena), .entries = try entries.toOwnedSlice(arena) }; +} + +fn contains(list: []const []const u8, s: []const u8) bool { + for (list) |x| if (std.ascii.eqlIgnoreCase(x, s)) return true; + return false; +} + +/// Platform names in ATT&CK are "Windows", "Linux", "macOS"; agents report +/// "windows", "linux", "macos". +fn attackPlatform(p: []const u8) []const u8 { + if (std.mem.eql(u8, p, "windows")) return "Windows"; + if (std.mem.eql(u8, p, "linux")) return "Linux"; + if (std.mem.eql(u8, p, "macos")) return "macOS"; + return p; +} + +pub const State = struct { + telemetry: bool, + telemetry_sources: []const []const u8, + detection: bool, + rules: []const []const u8, + response: bool, + actions: []const []const u8, +}; + +/// Pure state computation, so the separation of the three states is testable +/// without a database. `seen_types` are event types from healthy agents on +/// the platform; `rule_techniques` are (rule name, technique) pairs. +pub fn computeState( + arena: std.mem.Allocator, + m: Map, + entry: ?Entry, + technique_id: []const u8, + platform: ?[]const u8, + seen_types: []const []const u8, + rule_techniques: []const [2][]const u8, +) !State { + var sources: std.ArrayList([]const u8) = .empty; + var acts: std.ArrayList([]const u8) = .empty; + var rules: std.ArrayList([]const u8) = .empty; + if (entry) |e| { + for (e.telemetry) |t| { + if (contains(seen_types, t)) try sources.append(arena, t); + } + for (e.response) |a| { + for (m.actions) |def| { + if (!std.mem.eql(u8, def.name, a)) continue; + if (platform == null or contains(def.platforms, platform.?)) try acts.append(arena, a); + } + } + } + for (rule_techniques) |rt| { + // A rule tagged with a parent technique does not cover sub-techniques + // and the other way round: exact id only. + if (std.ascii.eqlIgnoreCase(rt[1], technique_id) and !contains(rules.items, rt[0])) try rules.append(arena, rt[0]); + } + return .{ + .telemetry = sources.items.len > 0, + .telemetry_sources = sources.items, + .detection = rules.items.len > 0, + .rules = rules.items, + .response = acts.items.len > 0, + .actions = acts.items, + }; +} + +fn freeRows(allocator: std.mem.Allocator, rows: []pg.Row) void { + for (rows) |row| row.deinit(allocator); + allocator.free(rows); +} + +pub fn coverage( + allocator: std.mem.Allocator, + conn: *pg.Conn, + request: *std.http.Server.Request, + web: auth.WebUser, + target: []const u8, +) !void { + var arena_state = std.heap.ArenaAllocator.init(allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const platform = util.queryParam(target, "platform"); + if (platform) |p| { + if (util.parseOs(p) == null) return util.problem(request, allocator, .bad_request, "platform must be windows, linux or macos."); + } + const catalog = try loadCatalog(arena); + const m = try loadMap(arena); + + // Telemetry: event types from healthy agents in the last 24 hours. An + // agent is healthy when it heartbeated in 15 minutes and has no sensor + // in a failed state. + const seen_rows = try conn.exec(arena, + \\SELECT DISTINCT te.event_type FROM telemetry_events te + \\JOIN agents ag ON ag.id = te.agent_id + \\WHERE te.tenant_id = $1::uuid AND te.received_at >= now() - interval '24 hours' + \\ AND ag.revoked_at IS NULL AND ag.last_heartbeat_at >= now() - interval '15 minutes' + \\ AND ($2::text IS NULL OR ag.operating_system = $2) + \\ AND NOT EXISTS ( + \\ SELECT 1 FROM sensor_status ss WHERE ss.tenant_id = ag.tenant_id AND ss.agent_id = ag.id + \\ AND ss.state IN ('failed', 'missing', 'access_denied') + \\ ) + , &.{ .{ .text = web.tenant_id }, if (platform) |p| .{ .text = p } else .{ .null = {} } }); + var seen: std.ArrayList([]const u8) = .empty; + for (seen_rows) |r| if (r.cols[0]) |t| try seen.append(arena, t); + + // Detection: enabled rules and their techniques. Platform does not + // filter rules: most rules do not say which platform they run on. + const rule_rows = try conn.exec(arena, + \\SELECT r.name, upper(t) FROM alert_rules r, unnest(r.mitre_techniques) AS t + \\WHERE r.tenant_id = $1::uuid AND r.is_enabled + , &.{.{ .text = web.tenant_id }}); + var pairs: std.ArrayList([2][]const u8) = .empty; + for (rule_rows) |r| { + if (r.cols[0] != null and r.cols[1] != null) try pairs.append(arena, .{ r.cols[0].?, r.cols[1].? }); + } + + var out: std.ArrayList(u8) = .empty; + defer out.deinit(allocator); + try out.appendSlice(allocator, "{\"attack_version\":"); + try util.appendEscaped(&out, allocator, catalog.attack_version); + try out.appendSlice(allocator, ",\"platform\":"); + if (platform) |p| try util.appendEscaped(&out, allocator, p) else try out.appendSlice(allocator, "null"); + try out.appendSlice(allocator, ",\"tactics\":"); + try out.appendSlice(allocator, try std.json.Stringify.valueAlloc(arena, catalog.tactics, .{})); + try out.appendSlice(allocator, ",\"techniques\":["); + var n: usize = 0; + for (catalog.techniques) |t| { + if (platform) |p| { + if (!contains(t.platforms, attackPlatform(p))) continue; + } + var entry: ?Entry = null; + for (m.entries) |e| { + if (std.mem.eql(u8, e.id, t.id)) entry = e; + } + const st = try computeState(arena, m, entry, t.id, platform, seen.items, pairs.items); + if (n > 0) try out.append(allocator, ','); + n += 1; + const obj = .{ + .id = t.id, + .name = t.name, + .tactics = t.tactics, + .mapped = entry != null, + .telemetry = .{ .available = st.telemetry, .sources = st.telemetry_sources, .expected = if (entry) |e| e.telemetry else &[_][]const u8{} }, + .detection = .{ .available = st.detection, .rules = st.rules }, + .response = .{ .available = st.response, .actions = st.actions }, + }; + try out.appendSlice(allocator, try std.json.Stringify.valueAlloc(arena, obj, .{})); + } + try out.appendSlice(allocator, "]}"); + try util.respondJson(request, .ok, out.items); +} + +test "coverage map and catalog agree with the pinned release" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const catalog = try loadCatalog(arena); + const m = try loadMap(arena); + try std.testing.expectEqualStrings("20.1", catalog.attack_version); + try std.testing.expectEqualStrings(catalog.attack_version, m.attack_version); + // Every mapped technique has a name, every action is defined, and every + // telemetry source is a known event type. + const event_types = [_][]const u8{ + "process_start", "process_exit", "file_create", "registry_set", "network_connect", "dns_query", + "user_logon", "service_create", "powershell_script_block", "sensor_health", "agent_tamper", + }; + for (m.entries) |e| { + var found = false; + for (catalog.techniques) |t| { + if (std.mem.eql(u8, t.id, e.id)) found = true; + } + if (!found) { + std.debug.print("coverage.yaml names {s}, not in techniques.json\n", .{e.id}); + return error.UnknownTechnique; + } + for (e.response) |a| { + var def = false; + for (m.actions) |d| { + if (std.mem.eql(u8, d.name, a)) def = true; + } + try std.testing.expect(def); + } + for (e.telemetry) |t| try std.testing.expect(contains(&event_types, t)); + } + var t1059: ?Technique = null; + for (catalog.techniques) |t| { + if (std.mem.eql(u8, t.id, "T1059.001")) t1059 = t; + } + try std.testing.expectEqualStrings("Command and Scripting Interpreter: PowerShell", t1059.?.name); + try std.testing.expectEqualStrings("execution", t1059.?.tactics[0]); +} + +test "the three states never follow from one another" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const m = try loadMap(arena); + var entry: ?Entry = null; + for (m.entries) |e| { + if (std.mem.eql(u8, e.id, "T1059.001")) entry = e; + } + // A rule, no telemetry: detection only. + const pairs = [_][2][]const u8{.{ "Encoded PowerShell", "T1059.001" }}; + const a = try computeState(arena, m, entry, "T1059.001", "windows", &.{}, &pairs); + try std.testing.expect(a.detection and !a.telemetry); + try std.testing.expect(a.response); + // Telemetry, no rule. + const b = try computeState(arena, m, entry, "T1059.001", "windows", &.{"process_start"}, &.{}); + try std.testing.expect(b.telemetry and !b.detection); + // Response depends on platform alone: isolate_host is Windows only. + var t1110: ?Entry = null; + for (m.entries) |e| { + if (std.mem.eql(u8, e.id, "T1110")) t1110 = e; + } + const c = try computeState(arena, m, t1110, "T1110", "linux", &.{"user_logon"}, &pairs); + try std.testing.expect(c.telemetry and !c.detection and !c.response); + // A rule on the parent technique is not detection for the sub-technique. + const parent = [_][2][]const u8{.{ "Any interpreter", "T1059" }}; + const d = try computeState(arena, m, entry, "T1059.001", null, &.{}, &parent); + try std.testing.expect(!d.detection); + // Unmapped technique: telemetry and response unknown, so false. + const e = try computeState(arena, m, null, "T1595", null, &.{"process_start"}, &.{}); + try std.testing.expect(!e.telemetry and !e.response and !e.detection); +} + +test "embedded attack files match rules/attack" { + const io = std.testing.io; + const files = [_]struct { name: []const u8, embedded: []const u8 }{ + .{ .name = "../rules/attack/coverage.yaml", .embedded = coverage_yaml }, + .{ .name = "../rules/attack/techniques.json", .embedded = techniques_json }, + }; + for (files) |f| { + const text = std.Io.Dir.cwd().readFileAlloc(io, f.name, std.testing.allocator, .limited(1 << 20)) catch |err| { + if (err == error.FileNotFound) return; // not run from server/ + return err; + }; + defer std.testing.allocator.free(text); + try std.testing.expectEqualStrings(text, f.embedded); + } +} diff --git a/server/src/routes/auth.zig b/server/src/routes/auth.zig index 2fa3e53..3d4e2c6 100644 --- a/server/src/routes/auth.zig +++ b/server/src/routes/auth.zig @@ -3,6 +3,17 @@ const pg = @import("../db/pg/conn.zig"); const util = @import("../http/util.zig"); const auth = @import("../http/auth.zig"); const passwords = @import("../crypto/passwords.zig"); +const settings = @import("settings.zig"); + +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .POST, .path = "/api/auth/login", .perm = .public }, + .{ .method = .GET, .path = "/api/auth/methods", .perm = .public }, + .{ .method = .POST, .path = "/api/auth/logout", .perm = .read }, + .{ .method = .GET, .path = "/api/auth/session", .perm = .read }, + .{ .method = .POST, .path = "/api/auth/password", .perm = .read }, +}; + pub fn login( allocator: std.mem.Allocator, @@ -20,7 +31,7 @@ pub fn login( defer parsed.deinit(); const rows = try conn.exec(allocator, - \\SELECT id::text, tenant_id::text, email, role, password_hash, disabled_at::text, name + \\SELECT id::text, tenant_id::text, email, role, password_hash, disabled_at::text, name, break_glass::text \\FROM users WHERE lower(email) = lower($1) LIMIT 1 , &.{.{ .text = parsed.value.email }}); defer { @@ -33,6 +44,12 @@ pub fn login( const hash = c[4] orelse return util.problem(request, allocator, .unauthorized, "Invalid email or password."); const ok = try auth.verifyLoginPassword(allocator, io, hash, parsed.value.password); if (!ok) return util.problem(request, allocator, .unauthorized, "Invalid email or password."); + // Checked after the password so the answer does not reveal who is break-glass. + const policy = try settings.loadTenant(allocator, conn, c[1].?); + const glass = std.mem.eql(u8, c[7] orelse "false", "true"); + if (!settings.passwordAllowed(policy, c[3] orelse "viewer", glass)) { + return util.problem(request, allocator, .forbidden, "Password sign-in is limited to break-glass admins. Sign in with Microsoft Entra ID."); + } // Rehash legacy scrypt on success if (!std.mem.startsWith(u8, hash, "$argon2")) { @@ -165,6 +182,24 @@ pub fn changePassword( } /// Pure SQL-shaped login lookup helper used by unit tests (no network). +/// Which sign-in methods the login page should offer. `?tenant=` picks the +/// tenant; the default tenant otherwise. Public: it names no users. +pub fn methods(allocator: std.mem.Allocator, conn: *pg.Conn, request: *std.http.Server.Request, target: []const u8) !void { + const tenant = util.queryParam(target, "tenant") orelse util.default_tenant; + if (tenant.len != 36) return util.problem(request, allocator, .bad_request, "tenant must be a UUID."); + const policy = try settings.loadTenant(allocator, conn, tenant); + const rows = try conn.exec(allocator, "SELECT 1 FROM tenant_oidc WHERE tenant_id = $1::uuid AND enabled", &.{.{ .text = tenant }}); + defer { + for (rows) |row| row.deinit(allocator); + allocator.free(rows); + } + const json = try std.fmt.allocPrint(allocator, + \\{{"password":"{s}","entra":{s}}} + , .{ if (policy.password_login_break_glass_only) "break_glass" else "all", if (rows.len > 0) "true" else "false" }); + defer allocator.free(json); + try util.respondJson(request, .ok, json); +} + pub fn loginLookupSql() []const u8 { return \\SELECT id::text, tenant_id::text, email, role, password_hash, disabled_at::text, name diff --git a/server/src/routes/feeds.zig b/server/src/routes/feeds.zig index 078e0bc..cb1273c 100644 --- a/server/src/routes/feeds.zig +++ b/server/src/routes/feeds.zig @@ -9,6 +9,16 @@ const audit = @import("../http/audit.zig"); const secrets = @import("../crypto/secret_box.zig"); const threat_intel = @import("../jobs/threat_intel.zig"); +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .GET, .path = "/api/threat-intel-feeds", .perm = .read }, + .{ .method = .POST, .path = "/api/threat-intel-feeds", .perm = .admin }, + .{ .method = .PUT, .path = "/api/threat-intel-feeds/:id", .perm = .admin }, + .{ .method = .DELETE, .path = "/api/threat-intel-feeds/:id", .perm = .admin }, + .{ .method = .POST, .path = "/api/threat-intel-feeds/:id/run", .perm = .admin }, +}; + + const feed_select = \\SELECT id::text, name, kind, url, auth_header_name, default_severity, \\ interval_minutes::text, is_enabled::text, status, diff --git a/server/src/routes/github.zig b/server/src/routes/github.zig index c96ebfb..7d86469 100644 --- a/server/src/routes/github.zig +++ b/server/src/routes/github.zig @@ -2,6 +2,13 @@ const std = @import("std"); const pg = @import("../db/pg/conn.zig"); const util = @import("../http/util.zig"); const auth = @import("../http/auth.zig"); + +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .GET, .path = "/api/auth/github/start", .perm = .public }, + .{ .method = .GET, .path = "/api/auth/github/callback", .perm = .public }, +}; + const Sha256 = std.crypto.hash.sha2.Sha256; fn envSpan(name: [*:0]const u8) ?[]const u8 { diff --git a/server/src/routes/hunts.zig b/server/src/routes/hunts.zig index b7195b8..d2cea5c 100644 --- a/server/src/routes/hunts.zig +++ b/server/src/routes/hunts.zig @@ -6,6 +6,19 @@ const auth = @import("../http/auth.zig"); const audit = @import("../http/audit.zig"); const query = @import("../hunts/query.zig"); +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .POST, .path = "/api/hunts/run", .perm = .hunt_run }, + .{ .method = .GET, .path = "/api/hunts", .perm = .read }, + .{ .method = .POST, .path = "/api/hunts", .perm = .admin }, + .{ .method = .GET, .path = "/api/hunts/:id", .perm = .read }, + .{ .method = .PUT, .path = "/api/hunts/:id", .perm = .admin }, + .{ .method = .DELETE, .path = "/api/hunts/:id", .perm = .admin }, + .{ .method = .POST, .path = "/api/hunts/:id/run", .perm = .hunt_run }, + .{ .method = .GET, .path = "/api/hunts/:id/runs", .perm = .read }, +}; + + const hunt_select = \\SELECT id::text, name, description, query, is_scheduled::text, schedule_cron, \\ alert_on_match::text, alert_severity, mitre_techniques::text, is_shared::text, diff --git a/server/src/routes/incidents.zig b/server/src/routes/incidents.zig new file mode 100644 index 0000000..6c906e7 --- /dev/null +++ b/server/src/routes/incidents.zig @@ -0,0 +1,328 @@ +//! Incidents and alert triage. Lists, one incident with its alerts and risk +//! breakdown, assign, status, and alert acknowledge and resolve. +//! Case management lives in Tawny-SOC; these routes only triage. +const std = @import("std"); +const pg = @import("../db/pg/conn.zig"); +const util = @import("../http/util.zig"); +const auth = @import("../http/auth.zig"); +const audit = @import("../http/audit.zig"); + +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .GET, .path = "/api/incidents", .perm = .read }, + .{ .method = .GET, .path = "/api/incidents/:id", .perm = .read }, + .{ .method = .POST, .path = "/api/incidents/:id/assign", .perm = .triage }, + .{ .method = .POST, .path = "/api/incidents/:id/status", .perm = .triage }, +}; + +pub const statuses = [_][]const u8{ "new", "investigating", "resolved", "false_positive" }; + +pub fn validStatus(s: []const u8) bool { + for (statuses) |x| if (std.mem.eql(u8, x, s)) return true; + return false; +} + +fn freeRows(allocator: std.mem.Allocator, rows: []pg.Row) void { + for (rows) |row| row.deinit(allocator); + allocator.free(rows); +} + +fn csrfOk(request: *std.http.Server.Request, web: auth.WebUser) bool { + return web.session_id == null or auth.checkCsrf(request, web); +} + +fn isUuid(s: []const u8) bool { + if (s.len != 36) return false; + for (s, 0..) |c, i| { + if (i == 8 or i == 13 or i == 18 or i == 23) { + if (c != '-') return false; + } else if (!std.ascii.isHex(c)) return false; + } + return true; +} + +const incident_select = + \\SELECT i.id::text, i.title, i.status, i.severity, i.risk::text, i.risk_items::text, + \\ i.owner_user_id::text, u.email, i.grouping, i.root_entity_id, + \\ array_to_json(i.agent_ids)::text, array_to_json(i.users)::text, array_to_json(i.techniques)::text, + \\ i.first_seen_at::text, i.last_seen_at::text, i.created_at::text, i.updated_at::text, + \\ (SELECT count(*) FROM incident_alerts ia WHERE ia.incident_id = i.id)::text, + \\ i.soc_case_status + \\FROM incidents i LEFT JOIN users u ON u.id = i.owner_user_id +; + +fn appendIncident(out: *std.ArrayList(u8), allocator: std.mem.Allocator, c: []const ?[]const u8) !void { + const fields = [_]struct { name: []const u8, idx: usize, raw: bool }{ + .{ .name = "id", .idx = 0, .raw = false }, + .{ .name = "title", .idx = 1, .raw = false }, + .{ .name = "status", .idx = 2, .raw = false }, + .{ .name = "severity", .idx = 3, .raw = false }, + .{ .name = "risk", .idx = 4, .raw = true }, + .{ .name = "risk_items", .idx = 5, .raw = true }, + .{ .name = "owner_user_id", .idx = 6, .raw = false }, + .{ .name = "owner_email", .idx = 7, .raw = false }, + .{ .name = "grouping", .idx = 8, .raw = false }, + .{ .name = "root_entity_id", .idx = 9, .raw = false }, + .{ .name = "agent_ids", .idx = 10, .raw = true }, + .{ .name = "users", .idx = 11, .raw = true }, + .{ .name = "techniques", .idx = 12, .raw = true }, + .{ .name = "first_seen_at", .idx = 13, .raw = false }, + .{ .name = "last_seen_at", .idx = 14, .raw = false }, + .{ .name = "created_at", .idx = 15, .raw = false }, + .{ .name = "updated_at", .idx = 16, .raw = false }, + .{ .name = "alert_count", .idx = 17, .raw = true }, + .{ .name = "soc_case_status", .idx = 18, .raw = false }, + }; + try out.append(allocator, '{'); + for (fields, 0..) |f, i| { + if (i > 0) try out.append(allocator, ','); + try out.append(allocator, '"'); + try out.appendSlice(allocator, f.name); + try out.appendSlice(allocator, "\":"); + const v = c[f.idx]; + if (v == null) { + try out.appendSlice(allocator, if (f.raw) "[]" else "null"); + } else if (f.raw) { + try out.appendSlice(allocator, v.?); + } else { + try util.appendEscaped(out, allocator, v.?); + } + } + try out.append(allocator, '}'); +} + +pub fn list( + allocator: std.mem.Allocator, + conn: *pg.Conn, + request: *std.http.Server.Request, + web: auth.WebUser, + target: []const u8, +) !void { + const status = util.queryParam(target, "status"); + if (status) |s| { + if (!validStatus(s) and !std.mem.eql(u8, s, "open")) return util.problem(request, allocator, .bad_request, "Unknown status."); + } + const limit_raw = util.queryParam(target, "limit") orelse "100"; + var limit = std.fmt.parseInt(i32, limit_raw, 10) catch 100; + limit = std.math.clamp(limit, 1, 500); + var lbuf: [12]u8 = undefined; + const lim = try std.fmt.bufPrint(&lbuf, "{d}", .{limit}); + const rows = try conn.exec(allocator, incident_select ++ + \\ WHERE i.tenant_id = $1::uuid + \\ AND ($2::text IS NULL OR i.status = $2 OR ($2 = 'open' AND i.status IN ('new','investigating'))) + \\ ORDER BY i.last_seen_at DESC LIMIT $3::int + , &.{ + .{ .text = web.tenant_id }, + if (status) |s| .{ .text = s } else .{ .null = {} }, + .{ .text = lim }, + }); + defer freeRows(allocator, rows); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(allocator); + try out.append(allocator, '['); + for (rows, 0..) |row, i| { + if (i > 0) try out.append(allocator, ','); + try appendIncident(&out, allocator, row.cols); + } + try out.append(allocator, ']'); + try util.respondJson(request, .ok, out.items); +} + +pub fn get( + allocator: std.mem.Allocator, + conn: *pg.Conn, + request: *std.http.Server.Request, + web: auth.WebUser, + id: []const u8, +) !void { + if (!isUuid(id)) return util.problem(request, allocator, .not_found, "Incident not found."); + const rows = try conn.exec(allocator, incident_select ++ " WHERE i.tenant_id = $1::uuid AND i.id = $2::uuid", &.{ + .{ .text = web.tenant_id }, + .{ .text = id }, + }); + defer freeRows(allocator, rows); + if (rows.len == 0) return util.problem(request, allocator, .not_found, "Incident not found."); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(allocator); + try appendIncident(&out, allocator, rows[0].cols); + _ = out.pop(); + + // Alerts in time order: the incident timeline. + const alerts = try conn.exec(allocator, + \\SELECT a.id::text, a.title, a.severity, a.status, ia.occurred_at::text, ia.reason, + \\ array_to_json(ia.keys)::text, a.agent_id::text, ag.hostname, r.name, + \\ array_to_json(r.mitre_techniques)::text, te.event_type, te.payload::text + \\FROM incident_alerts ia + \\JOIN alerts a ON a.id = ia.alert_id + \\JOIN alert_rules r ON r.id = a.alert_rule_id + \\JOIN agents ag ON ag.id = a.agent_id + \\LEFT JOIN telemetry_events te ON te.id = a.telemetry_event_id AND te.received_at = a.telemetry_received_at + \\WHERE ia.tenant_id = $1::uuid AND ia.incident_id = $2::uuid + \\ORDER BY ia.occurred_at, a.id + \\LIMIT 500 + , &.{ .{ .text = web.tenant_id }, .{ .text = id } }); + defer freeRows(allocator, alerts); + try out.appendSlice(allocator, ",\"alerts\":["); + for (alerts, 0..) |row, i| { + const c = row.cols; + if (i > 0) try out.append(allocator, ','); + try out.appendSlice(allocator, "{\"id\":"); + try out.appendSlice(allocator, c[0] orelse "0"); + const names = [_][]const u8{ "title", "severity", "status", "occurred_at", "reason" }; + for (names, 1..) |n, idx| { + try out.appendSlice(allocator, ",\""); + try out.appendSlice(allocator, n); + try out.appendSlice(allocator, "\":"); + if (c[idx]) |v| try util.appendEscaped(&out, allocator, v) else try out.appendSlice(allocator, "null"); + } + try out.appendSlice(allocator, ",\"keys\":"); + try out.appendSlice(allocator, c[6] orelse "[]"); + try out.appendSlice(allocator, ",\"agent_id\":"); + try util.appendEscaped(&out, allocator, c[7] orelse ""); + try out.appendSlice(allocator, ",\"hostname\":"); + try util.appendEscaped(&out, allocator, c[8] orelse ""); + try out.appendSlice(allocator, ",\"rule_name\":"); + try util.appendEscaped(&out, allocator, c[9] orelse ""); + try out.appendSlice(allocator, ",\"mitre_techniques\":"); + try out.appendSlice(allocator, c[10] orelse "[]"); + try out.appendSlice(allocator, ",\"event_type\":"); + if (c[11]) |v| try util.appendEscaped(&out, allocator, v) else try out.appendSlice(allocator, "null"); + try out.appendSlice(allocator, ",\"payload\":"); + try out.appendSlice(allocator, c[12] orelse "null"); + try out.append(allocator, '}'); + } + try out.appendSlice(allocator, "]}"); + try util.respondJson(request, .ok, out.items); +} + +pub fn assign( + allocator: std.mem.Allocator, + io: std.Io, + conn: *pg.Conn, + request: *std.http.Server.Request, + web: auth.WebUser, + id: []const u8, +) !void { + if (!csrfOk(request, web)) return util.respondJson(request, .forbidden, "{\"error\":\"csrf\"}"); + if (!isUuid(id)) return util.problem(request, allocator, .not_found, "Incident not found."); + const body = try util.readBody(allocator, request, 4096); + defer allocator.free(body); + const Req = struct { owner_user_id: ?[]const u8 = null }; + var parsed = std.json.parseFromSlice(Req, allocator, body, .{ .ignore_unknown_fields = true }) catch { + return util.problem(request, allocator, .bad_request, "owner_user_id must be a user id or null."); + }; + defer parsed.deinit(); + const owner = parsed.value.owner_user_id; + if (owner) |o| { + if (!isUuid(o)) return util.problem(request, allocator, .bad_request, "owner_user_id must be a user id or null."); + // Only someone who can triage may own an incident. + const u = try conn.exec(allocator, + \\SELECT 1 FROM users WHERE id = $1::uuid AND tenant_id = $2::uuid AND disabled_at IS NULL + \\ AND role IN ('admin', 'analyst') + , &.{ .{ .text = o }, .{ .text = web.tenant_id } }); + defer freeRows(allocator, u); + if (u.len == 0) return util.problem(request, allocator, .bad_request, "Owner must be an active admin or analyst."); + } + const rows = try conn.exec(allocator, + \\UPDATE incidents SET owner_user_id = $3::uuid, updated_at = now(), + \\ status = CASE WHEN status = 'new' AND $3::uuid IS NOT NULL THEN 'investigating' ELSE status END + \\WHERE tenant_id = $1::uuid AND id = $2::uuid RETURNING id::text + , &.{ .{ .text = web.tenant_id }, .{ .text = id }, if (owner) |o| .{ .text = o } else .{ .null = {} } }); + defer freeRows(allocator, rows); + if (rows.len == 0) return util.problem(request, allocator, .not_found, "Incident not found."); + try audit.add(allocator, io, conn, web.tenant_id, web.user_id, "incident.assign", id, null); + try queueSoc(allocator, conn, web.tenant_id, id); + return get(allocator, conn, request, web, id); +} + +pub fn setStatus( + allocator: std.mem.Allocator, + io: std.Io, + conn: *pg.Conn, + request: *std.http.Server.Request, + web: auth.WebUser, + id: []const u8, +) !void { + if (!csrfOk(request, web)) return util.respondJson(request, .forbidden, "{\"error\":\"csrf\"}"); + if (!isUuid(id)) return util.problem(request, allocator, .not_found, "Incident not found."); + const body = try util.readBody(allocator, request, 4096); + defer allocator.free(body); + const Req = struct { status: []const u8 }; + var parsed = std.json.parseFromSlice(Req, allocator, body, .{ .ignore_unknown_fields = true }) catch { + return util.problem(request, allocator, .bad_request, "status must be new, investigating, resolved or false_positive."); + }; + defer parsed.deinit(); + const st = parsed.value.status; + if (!validStatus(st)) return util.problem(request, allocator, .bad_request, "status must be new, investigating, resolved or false_positive."); + const rows = try conn.exec(allocator, + \\UPDATE incidents SET status = $3, updated_at = now() WHERE tenant_id = $1::uuid AND id = $2::uuid RETURNING id::text + , &.{ .{ .text = web.tenant_id }, .{ .text = id }, .{ .text = st } }); + defer freeRows(allocator, rows); + if (rows.len == 0) return util.problem(request, allocator, .not_found, "Incident not found."); + // Closing an incident resolves its open alerts too. + if (std.mem.eql(u8, st, "resolved") or std.mem.eql(u8, st, "false_positive")) { + try conn.execNoRows( + \\UPDATE alerts SET status = 'resolved', resolved_at = now(), resolved_by_user_id = $3::uuid + \\WHERE tenant_id = $1::uuid AND status IN ('open', 'acknowledged') + \\ AND id IN (SELECT alert_id FROM incident_alerts WHERE incident_id = $2::uuid) + , &.{ .{ .text = web.tenant_id }, .{ .text = id }, .{ .text = web.user_id } }); + } + const meta = try std.fmt.allocPrint(allocator, "{{\"status\":\"{s}\"}}", .{st}); + defer allocator.free(meta); + try audit.add(allocator, io, conn, web.tenant_id, web.user_id, "incident.status", id, meta); + try queueSoc(allocator, conn, web.tenant_id, id); + return get(allocator, conn, request, web, id); +} + +/// POST /api/alerts/{id}/acknowledge and /resolve. +pub fn setAlertStatus( + allocator: std.mem.Allocator, + io: std.Io, + conn: *pg.Conn, + request: *std.http.Server.Request, + web: auth.WebUser, + id: []const u8, + verb: []const u8, +) !void { + if (!csrfOk(request, web)) return util.respondJson(request, .forbidden, "{\"error\":\"csrf\"}"); + _ = std.fmt.parseInt(i64, id, 10) catch return util.problem(request, allocator, .not_found, "Alert not found."); + _ = util.readBody(allocator, request, 4096) catch {}; + const resolve = std.mem.eql(u8, verb, "resolve"); + const rows = if (resolve) try conn.exec(allocator, + \\UPDATE alerts SET status = 'resolved', resolved_at = now(), resolved_by_user_id = $3::uuid + \\WHERE tenant_id = $1::uuid AND id = $2::bigint RETURNING id::text, status + , &.{ .{ .text = web.tenant_id }, .{ .text = id }, .{ .text = web.user_id } }) else try conn.exec(allocator, + \\UPDATE alerts SET status = CASE WHEN status = 'resolved' THEN status ELSE 'acknowledged' END, + \\ acknowledged_at = coalesce(acknowledged_at, now()), acknowledged_by_user_id = coalesce(acknowledged_by_user_id, $3::uuid) + \\WHERE tenant_id = $1::uuid AND id = $2::bigint RETURNING id::text, status + , &.{ .{ .text = web.tenant_id }, .{ .text = id }, .{ .text = web.user_id } }); + defer freeRows(allocator, rows); + if (rows.len == 0) return util.problem(request, allocator, .not_found, "Alert not found."); + try audit.add(allocator, io, conn, web.tenant_id, web.user_id, if (resolve) "alert.resolve" else "alert.acknowledge", id, null); + const st = try util.escapeJson(allocator, rows[0].cols[1] orelse ""); + defer allocator.free(st); + const json = try std.fmt.allocPrint(allocator, "{{\"id\":{s},\"status\":{s}}}", .{ rows[0].cols[0] orelse "0", st }); + defer allocator.free(json); + try util.respondJson(request, .ok, json); +} + +/// Status and owner changes go to Tawny-SOC like new alerts do. +fn queueSoc(allocator: std.mem.Allocator, conn: *pg.Conn, tenant_id: []const u8, incident_id: []const u8) !void { + const payload = try std.fmt.allocPrint(allocator, "{{\"incident_id\":\"{s}\"}}", .{incident_id}); + defer allocator.free(payload); + try conn.execNoRows( + \\INSERT INTO work_queue (kind, tenant_id, payload) + \\SELECT 'incident_sink', $1::uuid, $2::jsonb + \\WHERE NOT EXISTS ( + \\ SELECT 1 FROM work_queue WHERE kind = 'incident_sink' AND payload->>'incident_id' = $3 AND locked_until IS NULL + \\) + , &.{ .{ .text = tenant_id }, .{ .text = payload }, .{ .text = incident_id } }); +} + +test "incident statuses are the four section 8 names" { + try std.testing.expect(validStatus("new")); + try std.testing.expect(validStatus("false_positive")); + try std.testing.expect(!validStatus("closed")); + try std.testing.expect(isUuid("00000000-0000-0000-0000-000000000001")); + try std.testing.expect(!isUuid("1; DROP TABLE")); +} diff --git a/server/src/routes/lookup.zig b/server/src/routes/lookup.zig index ea17035..22cf349 100644 --- a/server/src/routes/lookup.zig +++ b/server/src/routes/lookup.zig @@ -5,6 +5,12 @@ const pg = @import("../db/pg/conn.zig"); const util = @import("../http/util.zig"); const auth = @import("../http/auth.zig"); +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .POST, .path = "/api/threat-intel/lookup", .perm = .read }, +}; + + pub fn lookup( allocator: std.mem.Allocator, conn: *pg.Conn, diff --git a/server/src/routes/oidc.zig b/server/src/routes/oidc.zig new file mode 100644 index 0000000..776dc0f --- /dev/null +++ b/server/src/routes/oidc.zig @@ -0,0 +1,629 @@ +//! Microsoft Entra ID sign-in: OpenID Connect authorisation code flow with +//! PKCE (S256). Setup steps are in docs/entra-sso.md. +//! +//! GET /api/auth/oidc/start?tenant= +//! Reads tenant_oidc, fetches discovery (cached), stores state, nonce +//! and the PKCE verifier in oauth_states, redirects to Entra. +//! GET /api/auth/oidc/callback?code=&state= +//! Takes the state row once, exchanges the code with the client secret +//! (decrypted from TAWNY_INTEGRATION_ENCRYPTION_KEY), verifies the ID +//! token: RS256 signature against the JWKS (cached, refetched once for +//! an unknown kid), iss, aud, exp, nbf, nonce, and tid. Users match on +//! (tid, oid), never email. Groups map to a role; no matching group +//! means no account. +const std = @import("std"); +const pg = @import("../db/pg/conn.zig"); +const util = @import("../http/util.zig"); +const auth = @import("../http/auth.zig"); +const audit = @import("../http/audit.zig"); +const jwt = @import("../crypto/jwt.zig"); +const secrets = @import("../crypto/secret_box.zig"); +const settings = @import("settings.zig"); +const egress = @import("../sinks/egress.zig"); +const Sha256 = std.crypto.hash.sha2.Sha256; + +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .GET, .path = "/api/auth/oidc/start", .perm = .public }, + .{ .method = .GET, .path = "/api/auth/oidc/callback", .perm = .public }, +}; + +/// Clock skew allowed on exp and nbf. +pub const leeway_seconds: i64 = 120; +const jwks_max_age_seconds: i64 = 24 * 3600; + +fn freeRows(allocator: std.mem.Allocator, rows: []pg.Row) void { + for (rows) |row| row.deinit(allocator); + allocator.free(rows); +} + +fn envSpan(name: [*:0]const u8) ?[]const u8 { + const z = std.c.getenv(name) orelse return null; + const s = std.mem.span(z); + return if (s.len == 0) null else s; +} + +fn trimSlash(s: []const u8) []const u8 { + var end = s.len; + while (end > 0 and s[end - 1] == '/') end -= 1; + return s[0..end]; +} + +fn pct(allocator: std.mem.Allocator, text: []const u8) ![]u8 { + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(allocator); + const hex = "0123456789ABCDEF"; + for (text) |c| { + if (std.ascii.isAlphanumeric(c) or c == '-' or c == '_' or c == '.' or c == '~') { + try out.append(allocator, c); + } else { + try out.append(allocator, '%'); + try out.append(allocator, hex[c >> 4]); + try out.append(allocator, hex[c & 0xf]); + } + } + return out.toOwnedSlice(allocator); +} + +fn b64url(allocator: std.mem.Allocator, raw: []const u8) ![]u8 { + const out = try allocator.alloc(u8, std.base64.url_safe_no_pad.Encoder.calcSize(raw.len)); + _ = std.base64.url_safe_no_pad.Encoder.encode(out, raw); + return out; +} + +fn b64urlDecode(allocator: std.mem.Allocator, src: []const u8) ![]u8 { + const trimmed = std.mem.trimEnd(u8, src, "="); + const len = std.base64.url_safe_no_pad.Decoder.calcSizeForSlice(trimmed) catch return error.InvalidToken; + const out = try allocator.alloc(u8, len); + errdefer allocator.free(out); + std.base64.url_safe_no_pad.Decoder.decode(out, trimmed) catch return error.InvalidToken; + return out; +} + +pub fn pkceChallenge(allocator: std.mem.Allocator, verifier: []const u8) ![]u8 { + var dig: [32]u8 = undefined; + Sha256.hash(verifier, &dig, .{}); + return b64url(allocator, &dig); +} + +// ------------------------------------------------------------------ config + +pub const Config = struct { + tenant_id: []const u8, + entra_tenant_id: []const u8, + authority: []const u8, + client_id: []const u8, + client_secret_ct: ?[]const u8, + allowed_domains: []const []const u8, + group_roles: std.json.Value, + discovery: ?[]const u8, + jwks: ?[]const u8, + jwks_age: i64, +}; + +fn loadConfig(arena: std.mem.Allocator, conn: *pg.Conn, tenant_id: []const u8) !?Config { + const rows = try conn.exec(arena, + \\SELECT entra_tenant_id, authority, client_id, client_secret_encrypted, + \\ array_to_json(allowed_domains)::text, group_roles::text, discovery_json::text, jwks_json::text, + \\ coalesce(extract(epoch FROM now() - jwks_fetched_at)::bigint, 999999999)::text + \\FROM tenant_oidc WHERE tenant_id = $1::uuid AND enabled + , &.{.{ .text = tenant_id }}); + if (rows.len == 0) return null; + const c = rows[0].cols; + const etid = c[0] orelse return null; + const authority = if (c[1]) |a| trimSlash(a) else try std.fmt.allocPrint(arena, "https://login.microsoftonline.com/{s}/v2.0", .{etid}); + return .{ + .tenant_id = tenant_id, + .entra_tenant_id = etid, + .authority = authority, + .client_id = c[2] orelse return null, + .client_secret_ct = c[3], + .allowed_domains = try std.json.parseFromSliceLeaky([]const []const u8, arena, c[4] orelse "[]", .{}), + .group_roles = try std.json.parseFromSliceLeaky(std.json.Value, arena, c[5] orelse "{}", .{}), + .discovery = c[6], + .jwks = c[7], + .jwks_age = std.fmt.parseInt(i64, c[8] orelse "999999999", 10) catch 999999999, + }; +} + +pub const Discovery = struct { + issuer: []const u8, + authorization_endpoint: []const u8, + token_endpoint: []const u8, + jwks_uri: []const u8, +}; + +/// Endpoints must be https, except loopback for the contract test's mock +/// provider when TAWNY_ALLOW_PRIVATE_EGRESS is on. +fn endpointAllowed(url: []const u8) bool { + const private = std.mem.eql(u8, envSpan("TAWNY_ALLOW_PRIVATE_EGRESS") orelse "", "true") or + std.mem.eql(u8, envSpan("TAWNY_ALLOW_PRIVATE_EGRESS") orelse "", "1"); + if (std.mem.startsWith(u8, url, "https://")) { + const rest = url["https://".len..]; + const end = std.mem.indexOfAny(u8, rest, ":/") orelse rest.len; + return egress.allowed(rest[0..end], private); + } + if (private and std.mem.startsWith(u8, url, "http://127.0.0.1:")) return true; + return false; +} + +fn discovery(arena: std.mem.Allocator, io: std.Io, conn: *pg.Conn, cfg: Config) !Discovery { + const text = cfg.discovery orelse blk: { + const url = try std.fmt.allocPrint(arena, "{s}/.well-known/openid-configuration", .{cfg.authority}); + if (!endpointAllowed(url)) return error.EgressRefused; + const body = try fetch(arena, io, .GET, url, null, null); + _ = try std.json.parseFromSliceLeaky(Discovery, arena, body, .{ .ignore_unknown_fields = true }); + try conn.execNoRows("UPDATE tenant_oidc SET discovery_json = $2::jsonb WHERE tenant_id = $1::uuid", &.{ + .{ .text = cfg.tenant_id }, .{ .text = body }, + }); + break :blk body; + }; + const d = try std.json.parseFromSliceLeaky(Discovery, arena, text, .{ .ignore_unknown_fields = true }); + if (!endpointAllowed(d.authorization_endpoint) or !endpointAllowed(d.token_endpoint) or !endpointAllowed(d.jwks_uri)) return error.EgressRefused; + return d; +} + +fn fetch(arena: std.mem.Allocator, io: std.Io, method: std.http.Method, url: []const u8, form: ?[]const u8, _: ?[]const u8) ![]u8 { + var client: std.http.Client = .{ .allocator = arena, .io = io }; + defer client.deinit(); + var aw: std.Io.Writer.Allocating = .init(arena); + const result = client.fetch(.{ + .location = .{ .url = url }, + .method = method, + .payload = form, + .keep_alive = false, + .redirect_behavior = .unhandled, + .response_writer = &aw.writer, + .headers = .{ + .user_agent = .{ .override = "tawny-server" }, + .accept_encoding = .{ .override = "identity" }, + .content_type = if (form != null) .{ .override = "application/x-www-form-urlencoded" } else .omit, + }, + .extra_headers = &.{.{ .name = "accept", .value = "application/json" }}, + }) catch return error.ProviderUnreachable; + if (result.status != .ok) return error.ProviderRefused; + const body = aw.written(); + if (body.len > 256 * 1024) return error.ProviderRefused; + return body; +} + +// ------------------------------------------------------------------ start + +pub fn start(allocator: std.mem.Allocator, io: std.Io, conn: *pg.Conn, request: *std.http.Server.Request, target: []const u8) !void { + var arena_state = std.heap.ArenaAllocator.init(allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const tenant = util.queryParam(target, "tenant") orelse util.default_tenant; + if (tenant.len != 36 or !isUuid(tenant)) return util.problem(request, allocator, .bad_request, "tenant must be a UUID."); + const cfg = (try loadConfig(arena, conn, tenant)) orelse return util.problem(request, allocator, .not_found, "Entra ID sign-in is not configured."); + const d = discovery(arena, io, conn, cfg) catch return util.problem(request, allocator, .bad_gateway, "Entra ID discovery failed."); + + const state = try util.randomHex(io, arena, 32); + const nonce = try util.randomHex(io, arena, 32); + const verifier = try util.randomHex(io, arena, 32); + const challenge = try pkceChallenge(arena, verifier); + const now = util.nowUnix(io); + var t1: [32]u8 = undefined; + var t2: [32]u8 = undefined; + const created = util.formatRfc3339(&t1, now); + const expires = util.formatRfc3339(&t2, now + 10 * 60); + conn.execNoRows("DELETE FROM oauth_states WHERE expires_at < $1::timestamptz", &.{.{ .text = created }}) catch {}; + try conn.execNoRows( + \\INSERT INTO oauth_states (state, pkce_verifier, created_at, expires_at, provider, nonce, tenant_id) + \\VALUES ($1, $2, $3::timestamptz, $4::timestamptz, 'oidc', $5, $6::uuid) + , &.{ .{ .text = state }, .{ .text = verifier }, .{ .text = created }, .{ .text = expires }, .{ .text = nonce }, .{ .text = tenant } }); + + const redirect_uri = try redirectUri(arena); + const location = try std.fmt.allocPrint(arena, "{s}{s}client_id={s}&response_type=code&redirect_uri={s}&response_mode=query&scope=openid%20profile%20email&state={s}&nonce={s}&code_challenge={s}&code_challenge_method=S256", .{ + d.authorization_endpoint, + if (std.mem.indexOfScalar(u8, d.authorization_endpoint, '?') == null) "?" else "&", + try pct(arena, cfg.client_id), + try pct(arena, redirect_uri), + state, + nonce, + challenge, + }); + try request.respond("", .{ + .status = .found, + .extra_headers = &.{.{ .name = "location", .value = location }}, + .keep_alive = false, + }); +} + +fn redirectUri(arena: std.mem.Allocator) ![]u8 { + const public = trimSlash(envSpan("TAWNY_PUBLIC_URL") orelse "http://127.0.0.1:8080"); + return std.fmt.allocPrint(arena, "{s}/api/auth/oidc/callback", .{public}); +} + +fn isUuid(s: []const u8) bool { + if (s.len != 36) return false; + for (s, 0..) |c, i| { + if (i == 8 or i == 13 or i == 18 or i == 23) { + if (c != '-') return false; + } else if (!std.ascii.isHex(c)) return false; + } + return true; +} + +// ------------------------------------------------------------------ token checks + +pub const Expect = struct { + issuer: []const u8, + client_id: []const u8, + nonce: []const u8, + entra_tenant_id: []const u8, + now: i64, +}; + +pub const Identity = struct { + oid: []const u8, + tid: []const u8, + email: []const u8, + name: []const u8, + groups: []const []const u8, +}; + +pub const TokenError = error{ + InvalidToken, + WrongAlgorithm, + UnknownKey, + InvalidSignature, + BadIssuer, + BadAudience, + Expired, + NotYetValid, + BadNonce, + BadTenant, + MissingClaim, +}; + +const Jwk = struct { kty: []const u8 = "", kid: ?[]const u8 = null, n: ?[]const u8 = null, e: ?[]const u8 = null, use: ?[]const u8 = null }; +const Jwks = struct { keys: []const Jwk = &.{} }; + +/// Header kid of a compact JWT, or null. +pub fn tokenKid(arena: std.mem.Allocator, token: []const u8) ?[]const u8 { + const dot = std.mem.indexOfScalar(u8, token, '.') orelse return null; + const raw = b64urlDecode(arena, token[0..dot]) catch return null; + const H = struct { kid: ?[]const u8 = null }; + const h = std.json.parseFromSliceLeaky(H, arena, raw, .{ .ignore_unknown_fields = true }) catch return null; + return h.kid; +} + +/// Verify an ID token. The signature is checked first with the existing +/// RS256 code (crypto/jwt.zig); claims are read only after it passes. +pub fn verifyIdToken(arena: std.mem.Allocator, token: []const u8, jwks_text: []const u8, want: Expect) TokenError!Identity { + const jwks = std.json.parseFromSliceLeaky(Jwks, arena, jwks_text, .{ .ignore_unknown_fields = true }) catch return error.UnknownKey; + const kid = tokenKid(arena, token); + var key: ?Jwk = null; + for (jwks.keys) |k| { + if (!std.mem.eql(u8, k.kty, "RSA")) continue; + if (k.use) |u| if (!std.mem.eql(u8, u, "sig")) continue; + if (kid) |want_kid| { + if (k.kid == null or !std.mem.eql(u8, k.kid.?, want_kid)) continue; + } + key = k; + break; + } + const k = key orelse return error.UnknownKey; + const n = b64urlDecode(arena, k.n orelse return error.UnknownKey) catch return error.UnknownKey; + const e = b64urlDecode(arena, k.e orelse return error.UnknownKey) catch return error.UnknownKey; + jwt.verifyRs256(arena, token, n, e) catch |err| return switch (err) { + error.WrongAlgorithm => error.WrongAlgorithm, + error.InvalidSignature, error.InvalidKey, error.UnsupportedModulus => error.InvalidSignature, + else => error.InvalidToken, + }; + + const dot1 = std.mem.indexOfScalar(u8, token, '.') orelse return error.InvalidToken; + const dot2 = std.mem.indexOfScalarPos(u8, token, dot1 + 1, '.') orelse return error.InvalidToken; + const payload = b64urlDecode(arena, token[dot1 + 1 .. dot2]) catch return error.InvalidToken; + const v = std.json.parseFromSliceLeaky(std.json.Value, arena, payload, .{}) catch return error.InvalidToken; + if (v != .object) return error.InvalidToken; + const o = v.object; + + const iss = str(o, "iss") orelse return error.BadIssuer; + if (!std.mem.eql(u8, iss, want.issuer)) return error.BadIssuer; + // aud is a string or an array; Entra sends the client id string. + const aud_ok = switch (o.get("aud") orelse return error.BadAudience) { + .string => |s| std.mem.eql(u8, s, want.client_id), + .array => |arr| blk: { + for (arr.items) |x| { + if (x == .string and std.mem.eql(u8, x.string, want.client_id)) break :blk true; + } + break :blk false; + }, + else => false, + }; + if (!aud_ok) return error.BadAudience; + const exp = int(o, "exp") orelse return error.Expired; + if (want.now >= exp + leeway_seconds) return error.Expired; + if (int(o, "nbf")) |nbf| { + if (want.now + leeway_seconds < nbf) return error.NotYetValid; + } + const nonce = str(o, "nonce") orelse return error.BadNonce; + if (!timingEql(nonce, want.nonce)) return error.BadNonce; + const tid = str(o, "tid") orelse return error.MissingClaim; + if (!std.ascii.eqlIgnoreCase(tid, want.entra_tenant_id)) return error.BadTenant; + const oid = str(o, "oid") orelse return error.MissingClaim; + if (oid.len == 0 or oid.len > 100) return error.MissingClaim; + + var groups: std.ArrayList([]const u8) = .empty; + if (o.get("groups")) |g| { + if (g == .array) for (g.array.items) |x| { + if (x == .string) groups.append(arena, x.string) catch return error.InvalidToken; + }; + } + const email = str(o, "email") orelse str(o, "preferred_username") orelse ""; + return .{ + .oid = oid, + .tid = tid, + .email = email, + .name = str(o, "name") orelse email, + .groups = groups.items, + }; +} + +fn timingEql(a: []const u8, b: []const u8) bool { + if (a.len != b.len) return false; + var diff: u8 = 0; + for (a, b) |x, y| diff |= x ^ y; + return diff == 0; +} + +fn str(o: std.json.ObjectMap, key: []const u8) ?[]const u8 { + const v = o.get(key) orelse return null; + return if (v == .string) v.string else null; +} + +fn int(o: std.json.ObjectMap, key: []const u8) ?i64 { + const v = o.get(key) orelse return null; + return switch (v) { + .integer => |n| n, + .float => |f| @intFromFloat(f), + else => null, + }; +} + +/// Highest role among the user's groups. Null when no group is mapped. +pub fn roleForGroups(group_roles: std.json.Value, groups: []const []const u8) ?auth.Role { + if (group_roles != .object) return null; + var best: ?auth.Role = null; + for (groups) |g| { + const v = group_roles.object.get(g) orelse continue; + if (v != .string) continue; + const r = auth.roleFromText(v.string) orelse continue; + if (best == null or rank(r) > rank(best.?)) best = r; + } + return best; +} + +fn rank(r: auth.Role) u8 { + return switch (r) { + .viewer => 0, + .analyst => 1, + .admin => 2, + }; +} + +pub fn domainAllowed(allowed: []const []const u8, email: []const u8) bool { + if (allowed.len == 0) return true; + const at = std.mem.lastIndexOfScalar(u8, email, '@') orelse return false; + const domain = email[at + 1 ..]; + for (allowed) |d| { + if (std.ascii.eqlIgnoreCase(d, domain)) return true; + } + return false; +} + +// ------------------------------------------------------------------ callback + +fn refuse(request: *std.http.Server.Request, allocator: std.mem.Allocator, status: std.http.Status, title: []const u8) !void { + return util.problem(request, allocator, status, title); +} + +pub fn callback(allocator: std.mem.Allocator, io: std.Io, conn: *pg.Conn, request: *std.http.Server.Request, target: []const u8) !void { + var arena_state = std.heap.ArenaAllocator.init(allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + if (util.queryParam(target, "error") != null) return refuse(request, allocator, .unauthorized, "Entra ID sign-in was cancelled or refused."); + const code_raw = util.queryParam(target, "code") orelse return refuse(request, allocator, .bad_request, "Invalid OAuth state."); + const state = util.queryParam(target, "state") orelse return refuse(request, allocator, .bad_request, "Invalid OAuth state."); + if (code_raw.len == 0 or code_raw.len > 4096 or state.len == 0 or state.len > 128) return refuse(request, allocator, .bad_request, "Invalid OAuth state."); + const code = try util.percentDecode(arena, code_raw); + + // One use: the row is deleted as it is read. + var tbuf: [32]u8 = undefined; + const now = util.nowUnix(io); + const st_rows = try conn.exec(arena, + \\DELETE FROM oauth_states WHERE state = $1 AND provider = 'oidc' AND expires_at > $2::timestamptz + \\RETURNING pkce_verifier, nonce, tenant_id::text + , &.{ .{ .text = state }, .{ .text = util.formatRfc3339(&tbuf, now) } }); + if (st_rows.len == 0) return refuse(request, allocator, .bad_request, "Invalid OAuth state."); + const verifier = st_rows[0].cols[0] orelse return refuse(request, allocator, .bad_request, "Invalid OAuth state."); + const nonce = st_rows[0].cols[1] orelse return refuse(request, allocator, .bad_request, "Invalid OAuth state."); + const tenant = st_rows[0].cols[2] orelse return refuse(request, allocator, .bad_request, "Invalid OAuth state."); + + const cfg = (try loadConfig(arena, conn, tenant)) orelse return refuse(request, allocator, .not_found, "Entra ID sign-in is not configured."); + const d = discovery(arena, io, conn, cfg) catch return refuse(request, allocator, .bad_gateway, "Entra ID discovery failed."); + const secret_ct = cfg.client_secret_ct orelse return refuse(request, allocator, .service_unavailable, "Entra ID client secret is not set."); + const key = settings.envSecret(); + if (key.len == 0) return refuse(request, allocator, .service_unavailable, "TAWNY_INTEGRATION_ENCRYPTION_KEY is not set."); + const client_secret = secrets.unprotect(arena, key, secret_ct) catch return refuse(request, allocator, .service_unavailable, "Entra ID client secret cannot be decrypted."); + + const redirect_uri = try redirectUri(arena); + const form = try std.fmt.allocPrint(arena, "grant_type=authorization_code&client_id={s}&client_secret={s}&code={s}&redirect_uri={s}&code_verifier={s}", .{ + try pct(arena, cfg.client_id), try pct(arena, client_secret), try pct(arena, code), try pct(arena, redirect_uri), try pct(arena, verifier), + }); + const token_body = fetch(arena, io, .POST, d.token_endpoint, form, null) catch return refuse(request, allocator, .bad_gateway, "Entra ID token exchange failed."); + const Tok = struct { id_token: []const u8 = "" }; + const tok = std.json.parseFromSliceLeaky(Tok, arena, token_body, .{ .ignore_unknown_fields = true }) catch return refuse(request, allocator, .bad_gateway, "Entra ID token exchange failed."); + if (tok.id_token.len == 0) return refuse(request, allocator, .bad_gateway, "Entra ID returned no ID token."); + + // Entra's v2.0 issuer names the tenant: https://login.microsoftonline.com//v2.0. + // Discovery for a specific tenant gives that exact string. + const want: Expect = .{ .issuer = d.issuer, .client_id = cfg.client_id, .nonce = nonce, .entra_tenant_id = cfg.entra_tenant_id, .now = now }; + var jwks_text = try jwksFor(arena, io, conn, cfg, d, false); + var ident = verifyIdToken(arena, tok.id_token, jwks_text, want); + if (ident == error.UnknownKey) { + // Keys rotate. Refetch once, then give up. + jwks_text = try jwksFor(arena, io, conn, cfg, d, true); + ident = verifyIdToken(arena, tok.id_token, jwks_text, want); + } + const id = ident catch |err| { + std.debug.print("oidc: id token refused: {s}\n", .{@errorName(err)}); + return refuse(request, allocator, .unauthorized, "Entra ID token was not valid."); + }; + + if (!domainAllowed(cfg.allowed_domains, id.email)) return refuse(request, allocator, .forbidden, "This account's domain is not allowed."); + const role = roleForGroups(cfg.group_roles, id.groups) orelse { + try audit.add(allocator, io, conn, tenant, null, "oidc.refused_no_group", id.oid, null); + return refuse(request, allocator, .forbidden, "Your Entra ID groups do not grant access to Tawny."); + }; + + const user_id = try upsertUser(arena, io, conn, tenant, id, role) orelse return refuse(request, allocator, .forbidden, "This account is disabled."); + try audit.add(allocator, io, conn, tenant, user_id, "oidc.sign_in", null, null); + const sess = try auth.createSession(arena, io, conn, user_id, tenant); + const cookie_hdr = try std.fmt.allocPrint(arena, "{s}={s}; Path=/; HttpOnly; Secure; SameSite=Lax", .{ auth.session_cookie_name, sess.cookie }); + const public = trimSlash(envSpan("TAWNY_PUBLIC_URL") orelse "http://127.0.0.1:8080"); + const location = try std.fmt.allocPrint(arena, "{s}/", .{public}); + try request.respond("{\"ok\":true}", .{ + .status = .found, + .extra_headers = &.{ + .{ .name = "location", .value = location }, + .{ .name = "set-cookie", .value = cookie_hdr }, + .{ .name = "content-type", .value = "application/json" }, + }, + .keep_alive = false, + }); +} + +fn jwksFor(arena: std.mem.Allocator, io: std.Io, conn: *pg.Conn, cfg: Config, d: Discovery, force: bool) ![]const u8 { + if (!force and cfg.jwks != null and cfg.jwks_age < jwks_max_age_seconds) return cfg.jwks.?; + const body = fetch(arena, io, .GET, d.jwks_uri, null, null) catch return cfg.jwks orelse "{\"keys\":[]}"; + _ = std.json.parseFromSliceLeaky(Jwks, arena, body, .{ .ignore_unknown_fields = true }) catch return cfg.jwks orelse "{\"keys\":[]}"; + try conn.execNoRows("UPDATE tenant_oidc SET jwks_json = $2::jsonb, jwks_fetched_at = now() WHERE tenant_id = $1::uuid", &.{ + .{ .text = cfg.tenant_id }, .{ .text = body }, + }); + return body; +} + +/// Find by (tid, oid). First sign-in creates the user. The role follows the +/// groups on every sign-in, so removing someone from a group takes effect at +/// their next sign-in. Returns null for a disabled user. +fn upsertUser(arena: std.mem.Allocator, io: std.Io, conn: *pg.Conn, tenant: []const u8, id: Identity, role: auth.Role) !?[]const u8 { + const found = try conn.exec(arena, + \\SELECT id::text, disabled_at::text FROM users WHERE tenant_id = $1::uuid AND oidc_tid = $2 AND oidc_oid = $3 LIMIT 1 + , &.{ .{ .text = tenant }, .{ .text = std.ascii.allocLowerString(arena, id.tid) catch id.tid }, .{ .text = id.oid } }); + if (found.len > 0) { + if (found[0].cols[1] != null) return null; + const uid = found[0].cols[0].?; + try conn.execNoRows("UPDATE users SET role = $2, name = $3 WHERE id = $1::uuid", &.{ + .{ .text = uid }, .{ .text = auth.roleText(role) }, .{ .text = id.name }, + }); + return uid; + } + var id_buf: [36]u8 = undefined; + const uid = try arena.dupe(u8, util.newUuid(io, &id_buf)); + var tbuf: [32]u8 = undefined; + // Email is display only. It need not be unique across identities, so an + // address already held by a password user gets the oid appended. + const email = if (id.email.len > 0) id.email else try std.fmt.allocPrint(arena, "{s}@entra.invalid", .{id.oid}); + const taken = try conn.exec(arena, "SELECT 1 FROM users WHERE tenant_id = $1::uuid AND lower(email) = lower($2)", &.{ .{ .text = tenant }, .{ .text = email } }); + const stored_email = if (taken.len > 0) try std.fmt.allocPrint(arena, "{s}#{s}", .{ email, id.oid }) else email; + try conn.execNoRows( + \\INSERT INTO users (id, tenant_id, email, name, role, password_hash, created_at, oidc_tid, oidc_oid) + \\VALUES ($1::uuid, $2::uuid, $3, $4, $5, NULL, $6::timestamptz, $7, $8) + , &.{ + .{ .text = uid }, + .{ .text = tenant }, + .{ .text = stored_email }, + .{ .text = id.name }, + .{ .text = auth.roleText(role) }, + .{ .text = util.formatRfc3339(&tbuf, util.nowUnix(io)) }, + .{ .text = try std.ascii.allocLowerString(arena, id.tid) }, + .{ .text = id.oid }, + }); + return uid; +} + +// ------------------------------------------------------------------ tests + +test "pkce challenge matches rfc 7636 appendix b" { + const a = std.testing.allocator; + const c = try pkceChallenge(a, "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"); + defer a.free(c); + try std.testing.expectEqualStrings("E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", c); +} + +test "groups map to the highest role and unmapped users are refused" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const map = try std.json.parseFromSliceLeaky(std.json.Value, arena, + \\{"g-view":"viewer","g-an":"analyst","g-adm":"admin","g-bad":"owner"} + , .{}); + try std.testing.expectEqual(auth.Role.analyst, roleForGroups(map, &.{ "g-view", "g-an" }).?); + try std.testing.expectEqual(auth.Role.admin, roleForGroups(map, &.{ "g-adm", "g-view" }).?); + try std.testing.expect(roleForGroups(map, &.{ "other", "g-bad" }) == null); + try std.testing.expect(roleForGroups(map, &.{}) == null); + try std.testing.expect(domainAllowed(&.{}, "a@b.c")); + try std.testing.expect(domainAllowed(&.{"Example.com"}, "a@example.COM")); + try std.testing.expect(!domainAllowed(&.{"example.com"}, "a@evil.com")); + try std.testing.expect(!domainAllowed(&.{"example.com"}, "no-at-sign")); +} + +// Test vectors: one RS256 key made with `openssl genrsa 2048` for this test +// and then deleted, so only the public modulus is here. Claims: +// iss=https://login.example/t1/v2.0, aud=client-1, nonce=n1, tid=T1, oid=o1, +// nbf=1000, exp=5000, groups=[g1]. Each tok_ changes one claim. +const test_n = "wvND6hS2O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NTAwMCwiZW1haWwiOiJhbGljZUBleGFtcGxlLmNvbSIsIm5hbWUiOiJBbGljZSIsImdyb3VwcyI6WyJnMSJdfQ.j0iEoBzHb5TMdf0Vkwbdor0wL3j6XtNDdgOu2K1f8S0drw0JaaG7gFNh3Nfj4ivFWdz0FqbHNsd734WQrq1JXqkubMLvfAeBch1s--PKxeS2ASpNi8HFffQ1_Kfjcx1z-6CP0Ll3IZNOALY59b-lqxe6h0FmFF76QUpW3nb6oKxb_n-BweSP5XP9tWNrHVBQo8fzxc4ze_dwWhw-VX8mYqZa8EwWvvPyeD2rw8dBLXUmD2dGWDQe25f2bQWEXrlAI5ZYDT6XJ4FtjpkZcgtGnYI5BHuC_o3Bw8_0oaOdoSVsVnSUFSmh6RaDLrmduU5S__6AFb157gtVzl4CmpfePQ"; + +test "id token checks refuse a token with no matching key" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const jwks = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"other\",\"n\":\"" ++ test_n ++ "\",\"e\":\"AQAB\"}]}"; + const token = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImsxIn0.e30.AAAA"; + try std.testing.expectError(error.UnknownKey, verifyIdToken(arena, token, jwks, .{ + .issuer = "x", .client_id = "x", .nonce = "x", .entra_tenant_id = "x", .now = 0, + })); + try std.testing.expectEqualStrings("k1", tokenKid(arena, token).?); + // A key with the right kid but a forged signature fails the signature check. + const jwks2 = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"k1\",\"n\":\"" ++ test_n ++ "\",\"e\":\"AQAB\"}]}"; + try std.testing.expectError(error.InvalidSignature, verifyIdToken(arena, token, jwks2, .{ + .issuer = "x", .client_id = "x", .nonce = "x", .entra_tenant_id = "x", .now = 0, + })); +} + +test "id token: iss, aud, exp, nbf, nonce and tid are each enforced" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const jwks = "{\"keys\":[{\"kty\":\"RSA\",\"use\":\"sig\",\"kid\":\"k1\",\"n\":\"" ++ test_n ++ "\",\"e\":\"AQAB\"}]}"; + const want: Expect = .{ .issuer = "https://login.example/t1/v2.0", .client_id = "client-1", .nonce = "n1", .entra_tenant_id = "t1", .now = 2000 }; + const id = try verifyIdToken(arena, tok_valid, jwks, want); + try std.testing.expectEqualStrings("o1", id.oid); + try std.testing.expectEqualStrings("T1", id.tid); + try std.testing.expectEqualStrings("g1", id.groups[0]); + try std.testing.expectError(error.BadIssuer, verifyIdToken(arena, tok_iss, jwks, want)); + try std.testing.expectError(error.BadAudience, verifyIdToken(arena, tok_aud, jwks, want)); + try std.testing.expectError(error.Expired, verifyIdToken(arena, tok_exp, jwks, want)); + try std.testing.expectError(error.NotYetValid, verifyIdToken(arena, tok_nbf, jwks, want)); + try std.testing.expectError(error.BadNonce, verifyIdToken(arena, tok_nonce, jwks, want)); + try std.testing.expectError(error.BadTenant, verifyIdToken(arena, tok_tid, jwks, want)); + // The valid token expires: 5000 + leeway. + var late = want; + late.now = 5000 + leeway_seconds; + try std.testing.expectError(error.Expired, verifyIdToken(arena, tok_valid, jwks, late)); + // A changed payload breaks the signature. + var forged = try arena.dupe(u8, tok_valid); + const dot = std.mem.indexOfScalar(u8, forged, '.').?; + forged[dot + 5] = if (forged[dot + 5] == 'A') 'B' else 'A'; + try std.testing.expectError(error.InvalidSignature, verifyIdToken(arena, forged, jwks, want)); +} diff --git a/server/src/routes/settings.zig b/server/src/routes/settings.zig new file mode 100644 index 0000000..1d93d87 --- /dev/null +++ b/server/src/routes/settings.zig @@ -0,0 +1,246 @@ +//! Tenant settings (password sign-in policy, analyst approval) and the +//! Entra ID (OIDC) configuration. Admin only. The OIDC client secret is +//! stored as secret_box ciphertext under TAWNY_INTEGRATION_ENCRYPTION_KEY +//! and is never returned. +const std = @import("std"); +const pg = @import("../db/pg/conn.zig"); +const util = @import("../http/util.zig"); +const auth = @import("../http/auth.zig"); +const audit = @import("../http/audit.zig"); +const secrets = @import("../crypto/secret_box.zig"); + +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .GET, .path = "/api/settings/tenant", .perm = .admin }, + .{ .method = .PUT, .path = "/api/settings/tenant", .perm = .admin }, + .{ .method = .GET, .path = "/api/settings/oidc", .perm = .admin }, + .{ .method = .PUT, .path = "/api/settings/oidc", .perm = .admin }, +}; + +fn freeRows(allocator: std.mem.Allocator, rows: []pg.Row) void { + for (rows) |row| row.deinit(allocator); + allocator.free(rows); +} + +fn csrfOk(request: *std.http.Server.Request, web: auth.WebUser) bool { + return web.session_id == null or auth.checkCsrf(request, web); +} + +pub fn envSecret() []const u8 { + const z = std.c.getenv("TAWNY_INTEGRATION_ENCRYPTION_KEY") orelse return ""; + return std.mem.span(z); +} + +pub const Tenant = struct { + password_login_break_glass_only: bool = false, + analyst_destructive_needs_approval: bool = false, +}; + +pub fn loadTenant(allocator: std.mem.Allocator, conn: *pg.Conn, tenant_id: []const u8) !Tenant { + const rows = try conn.exec(allocator, + \\SELECT password_login, analyst_destructive_needs_approval::text + \\FROM tenant_settings WHERE tenant_id = $1::uuid + , &.{.{ .text = tenant_id }}); + defer freeRows(allocator, rows); + if (rows.len == 0) return .{}; + return .{ + .password_login_break_glass_only = std.mem.eql(u8, rows[0].cols[0] orelse "all", "break_glass"), + .analyst_destructive_needs_approval = std.mem.eql(u8, rows[0].cols[1] orelse "false", "true"), + }; +} + +pub fn analystNeedsApproval(allocator: std.mem.Allocator, conn: *pg.Conn, tenant_id: []const u8) !bool { + return (try loadTenant(allocator, conn, tenant_id)).analyst_destructive_needs_approval; +} + +/// Password sign-in rule. With the tenant limited to break-glass, only an +/// admin marked break_glass may use a password. +pub fn passwordAllowed(t: Tenant, role: []const u8, break_glass: bool) bool { + if (!t.password_login_break_glass_only) return true; + return break_glass and std.mem.eql(u8, role, "admin"); +} + +fn tenantJson(allocator: std.mem.Allocator, t: Tenant) ![]u8 { + return std.fmt.allocPrint(allocator, + \\{{"password_login":"{s}","analyst_destructive_needs_approval":{s}}} + , .{ + if (t.password_login_break_glass_only) "break_glass" else "all", + if (t.analyst_destructive_needs_approval) "true" else "false", + }); +} + +pub fn getTenant(allocator: std.mem.Allocator, conn: *pg.Conn, request: *std.http.Server.Request, web: auth.WebUser) !void { + const t = try loadTenant(allocator, conn, web.tenant_id); + const json = try tenantJson(allocator, t); + defer allocator.free(json); + try util.respondJson(request, .ok, json); +} + +pub fn putTenant( + allocator: std.mem.Allocator, + io: std.Io, + conn: *pg.Conn, + request: *std.http.Server.Request, + web: auth.WebUser, +) !void { + if (!csrfOk(request, web)) return util.respondJson(request, .forbidden, "{\"error\":\"csrf\"}"); + const body = try util.readBody(allocator, request, 16 * 1024); + defer allocator.free(body); + const Req = struct { + password_login: ?[]const u8 = null, + analyst_destructive_needs_approval: ?bool = null, + }; + var parsed = std.json.parseFromSlice(Req, allocator, body, .{ .ignore_unknown_fields = true }) catch { + return util.problem(request, allocator, .bad_request, "Invalid settings body."); + }; + defer parsed.deinit(); + var t = try loadTenant(allocator, conn, web.tenant_id); + if (parsed.value.password_login) |pl| { + if (std.mem.eql(u8, pl, "all")) { + t.password_login_break_glass_only = false; + } else if (std.mem.eql(u8, pl, "break_glass")) { + // Refuse a setting that would lock every admin out. + const glass = try conn.exec(allocator, + \\SELECT 1 FROM users WHERE tenant_id = $1::uuid AND role = 'admin' AND break_glass + \\ AND disabled_at IS NULL AND password_hash IS NOT NULL LIMIT 1 + , &.{.{ .text = web.tenant_id }}); + defer freeRows(allocator, glass); + if (glass.len == 0) return util.problem(request, allocator, .conflict, "Mark at least one admin as break-glass first."); + t.password_login_break_glass_only = true; + } else return util.problem(request, allocator, .bad_request, "password_login must be all or break_glass."); + } + if (parsed.value.analyst_destructive_needs_approval) |v| t.analyst_destructive_needs_approval = v; + try conn.execNoRows( + \\INSERT INTO tenant_settings (tenant_id, password_login, analyst_destructive_needs_approval, updated_at) + \\VALUES ($1::uuid, $2, $3::boolean, now()) + \\ON CONFLICT (tenant_id) DO UPDATE SET password_login = EXCLUDED.password_login, + \\ analyst_destructive_needs_approval = EXCLUDED.analyst_destructive_needs_approval, updated_at = now() + , &.{ + .{ .text = web.tenant_id }, + .{ .text = if (t.password_login_break_glass_only) "break_glass" else "all" }, + .{ .text = if (t.analyst_destructive_needs_approval) "true" else "false" }, + }); + try audit.add(allocator, io, conn, web.tenant_id, web.user_id, "tenant_settings.update", null, null); + const json = try tenantJson(allocator, t); + defer allocator.free(json); + try util.respondJson(request, .ok, json); +} + +pub fn getOidc(allocator: std.mem.Allocator, conn: *pg.Conn, request: *std.http.Server.Request, web: auth.WebUser) !void { + const rows = try conn.exec(allocator, + \\SELECT enabled::text, entra_tenant_id, authority, client_id, + \\ (client_secret_encrypted IS NOT NULL)::text, array_to_json(allowed_domains)::text, group_roles::text + \\FROM tenant_oidc WHERE tenant_id = $1::uuid + , &.{.{ .text = web.tenant_id }}); + defer freeRows(allocator, rows); + if (rows.len == 0) return util.respondJson(request, .ok, "{\"configured\":false}"); + const c = rows[0].cols; + const tid = try util.escapeJson(allocator, c[1] orelse ""); + defer allocator.free(tid); + const authority = try util.nullOrJsonString(allocator, c[2]); + defer allocator.free(authority); + const cid = try util.escapeJson(allocator, c[3] orelse ""); + defer allocator.free(cid); + const json = try std.fmt.allocPrint(allocator, + \\{{"configured":true,"enabled":{s},"entra_tenant_id":{s},"authority":{s},"client_id":{s},"client_secret_set":{s},"allowed_domains":{s},"group_roles":{s}}} + , .{ c[0] orelse "false", tid, authority, cid, c[4] orelse "false", c[5] orelse "[]", c[6] orelse "{}" }); + defer allocator.free(json); + try util.respondJson(request, .ok, json); +} + +pub fn putOidc( + allocator: std.mem.Allocator, + io: std.Io, + conn: *pg.Conn, + request: *std.http.Server.Request, + web: auth.WebUser, +) !void { + if (!csrfOk(request, web)) return util.respondJson(request, .forbidden, "{\"error\":\"csrf\"}"); + const body = try util.readBody(allocator, request, 64 * 1024); + defer allocator.free(body); + const Req = struct { + enabled: bool = false, + entra_tenant_id: []const u8, + authority: ?[]const u8 = null, + client_id: []const u8, + client_secret: ?[]const u8 = null, + allowed_domains: []const []const u8 = &.{}, + group_roles: std.json.Value = .null, + }; + var parsed = std.json.parseFromSlice(Req, allocator, body, .{ .ignore_unknown_fields = true }) catch { + return util.problem(request, allocator, .bad_request, "entra_tenant_id and client_id are required."); + }; + defer parsed.deinit(); + const v = parsed.value; + if (v.entra_tenant_id.len == 0 or v.entra_tenant_id.len > 100 or v.client_id.len == 0 or v.client_id.len > 200 or + util.hasControlChars(v.entra_tenant_id) or util.hasControlChars(v.client_id)) + { + return util.problem(request, allocator, .bad_request, "entra_tenant_id and client_id are required."); + } + if (v.authority) |a| { + if (!std.mem.startsWith(u8, a, "https://") and !std.mem.startsWith(u8, a, "http://127.0.0.1")) { + return util.problem(request, allocator, .bad_request, "authority must be an https URL."); + } + } + // Group map values must be role names. Keys are Entra group object ids. + if (v.group_roles != .null) { + if (v.group_roles != .object) return util.problem(request, allocator, .bad_request, "group_roles must map group ids to roles."); + var it = v.group_roles.object.iterator(); + while (it.next()) |e| { + if (e.value_ptr.* != .string or auth.roleFromText(e.value_ptr.string) == null or e.key_ptr.len == 0 or e.key_ptr.len > 100) { + return util.problem(request, allocator, .bad_request, "group_roles values must be admin, analyst or viewer."); + } + } + } + const groups_json = try std.json.Stringify.valueAlloc(allocator, if (v.group_roles == .null) std.json.Value{ .object = .empty } else v.group_roles, .{}); + defer allocator.free(groups_json); + var domains: std.ArrayList([]const u8) = .empty; + defer domains.deinit(allocator); + for (v.allowed_domains) |d| { + if (d.len == 0 or d.len > 253 or util.hasControlChars(d)) return util.problem(request, allocator, .bad_request, "allowed_domains has an invalid entry."); + try domains.append(allocator, d); + } + const domains_pg = try util.pgArrayText(allocator, domains.items); + defer allocator.free(domains_pg); + + var secret_ct: ?[]u8 = null; + defer if (secret_ct) |s| allocator.free(s); + if (v.client_secret) |plain| { + if (plain.len > 0) { + const key = envSecret(); + if (key.len == 0) return util.problem(request, allocator, .service_unavailable, "TAWNY_INTEGRATION_ENCRYPTION_KEY is not set."); + secret_ct = try secrets.protect(allocator, key, plain, io); + } + } + try conn.execNoRows( + \\INSERT INTO tenant_oidc (tenant_id, enabled, entra_tenant_id, authority, client_id, client_secret_encrypted, + \\ allowed_domains, group_roles, updated_at) + \\VALUES ($1::uuid, $2::boolean, $3, $4, $5, $6, $7::text[], $8::jsonb, now()) + \\ON CONFLICT (tenant_id) DO UPDATE SET enabled = EXCLUDED.enabled, entra_tenant_id = EXCLUDED.entra_tenant_id, + \\ authority = EXCLUDED.authority, client_id = EXCLUDED.client_id, + \\ client_secret_encrypted = COALESCE(EXCLUDED.client_secret_encrypted, tenant_oidc.client_secret_encrypted), + \\ allowed_domains = EXCLUDED.allowed_domains, group_roles = EXCLUDED.group_roles, + \\ discovery_json = NULL, jwks_json = NULL, jwks_fetched_at = NULL, updated_at = now() + , &.{ + .{ .text = web.tenant_id }, + .{ .text = if (v.enabled) "true" else "false" }, + .{ .text = v.entra_tenant_id }, + if (v.authority) |a| .{ .text = a } else .{ .null = {} }, + .{ .text = v.client_id }, + if (secret_ct) |s| .{ .text = s } else .{ .null = {} }, + .{ .text = domains_pg }, + .{ .text = groups_json }, + }); + try audit.add(allocator, io, conn, web.tenant_id, web.user_id, "tenant_oidc.update", null, null); + return getOidc(allocator, conn, request, web); +} + +test "password policy keeps break-glass admins only" { + const open: Tenant = .{}; + const closed: Tenant = .{ .password_login_break_glass_only = true }; + try std.testing.expect(passwordAllowed(open, "viewer", false)); + try std.testing.expect(passwordAllowed(closed, "admin", true)); + try std.testing.expect(!passwordAllowed(closed, "admin", false)); + try std.testing.expect(!passwordAllowed(closed, "analyst", true)); + try std.testing.expect(!passwordAllowed(closed, "viewer", false)); +} diff --git a/server/src/routes/suppressions.zig b/server/src/routes/suppressions.zig index 7d8aec8..8a47479 100644 --- a/server/src/routes/suppressions.zig +++ b/server/src/routes/suppressions.zig @@ -5,6 +5,15 @@ const util = @import("../http/util.zig"); const auth = @import("../http/auth.zig"); const audit = @import("../http/audit.zig"); +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .GET, .path = "/api/suppression-rules", .perm = .read }, + .{ .method = .POST, .path = "/api/suppression-rules", .perm = .exception_create }, + .{ .method = .PUT, .path = "/api/suppression-rules/:id", .perm = .admin }, + .{ .method = .DELETE, .path = "/api/suppression-rules/:id", .perm = .admin }, +}; + + const rule_select = \\SELECT s.id::text, s.name, s.reason, s.scope, s.alert_rule_id::text, ar.name, \\ s.agent_id::text, ag.hostname, s.payload_path, s.operator, s.match_value, @@ -57,6 +66,10 @@ pub fn create( }; defer fields.deinit(); if (try reject(request, allocator, fields.value)) return; + // Analysts may add exceptions, never without saying why (target-edr section 11). + if (web.role != .admin and blankToNull(fields.value.reason) == null) { + return util.problem(request, allocator, .bad_request, "reason is required."); + } var id_buf: [36]u8 = undefined; const id = util.newUuid(io, &id_buf); try write(io, conn, web, id, fields.value, true); diff --git a/server/src/routes/tokens.zig b/server/src/routes/tokens.zig index 81bbbe8..edebf13 100644 --- a/server/src/routes/tokens.zig +++ b/server/src/routes/tokens.zig @@ -4,6 +4,14 @@ const util = @import("../http/util.zig"); const auth = @import("../http/auth.zig"); const audit = @import("../http/audit.zig"); +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .POST, .path = "/api/api-tokens", .perm = .admin }, + .{ .method = .GET, .path = "/api/api-tokens", .perm = .read }, + .{ .method = .GET, .path = "/api/audit-logs", .perm = .read }, +}; + + pub fn createApiToken( allocator: std.mem.Allocator, io: std.Io, @@ -31,7 +39,7 @@ pub fn createApiToken( } const role = parsed.value.role orelse "viewer"; if (auth.roleFromText(role) == null) { - return util.problem(request, allocator, .bad_request, "role must be admin or viewer."); + return util.problem(request, allocator, .bad_request, "role must be admin, analyst or viewer."); } var raw: [32]u8 = undefined; diff --git a/server/src/routes/users.zig b/server/src/routes/users.zig index d5c6469..ce29f18 100644 --- a/server/src/routes/users.zig +++ b/server/src/routes/users.zig @@ -5,11 +5,21 @@ const auth = @import("../http/auth.zig"); const audit = @import("../http/audit.zig"); const passwords = @import("../crypto/passwords.zig"); +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .GET, .path = "/api/users", .perm = .admin }, + .{ .method = .POST, .path = "/api/users", .perm = .admin }, + .{ .method = .PUT, .path = "/api/users/:id", .perm = .admin }, + .{ .method = .DELETE, .path = "/api/users/:id", .perm = .admin }, +}; + + pub fn normalizeRole(role: ?[]const u8) error{BadRole}![]const u8 { const raw = role orelse return "viewer"; if (raw.len == 0) return "viewer"; if (std.ascii.eqlIgnoreCase(raw, "viewer")) return "viewer"; if (std.ascii.eqlIgnoreCase(raw, "admin")) return "admin"; + if (std.ascii.eqlIgnoreCase(raw, "analyst")) return "analyst"; return error.BadRole; } @@ -126,7 +136,7 @@ pub fn create( return util.problem(request, allocator, .bad_request, "password is too short."); } const role = normalizeRole(parsed.value.role) catch { - return util.problem(request, allocator, .bad_request, "role must be admin or viewer."); + return util.problem(request, allocator, .bad_request, "role must be admin, analyst or viewer."); }; const email = try std.ascii.allocLowerString(allocator, parsed.value.email); defer allocator.free(email); @@ -212,7 +222,7 @@ pub fn update( } if (parsed.value.role) |role_raw| { const role = normalizeRole(role_raw) catch { - return util.problem(request, allocator, .bad_request, "role must be admin or viewer."); + return util.problem(request, allocator, .bad_request, "role must be admin, analyst or viewer."); }; if (std.mem.eql(u8, user_id, web.user_id) and !std.mem.eql(u8, role, "admin")) { return util.problem(request, allocator, .bad_request, "cannot remove your own admin role."); @@ -316,5 +326,6 @@ test "omitted role is viewer" { try std.testing.expectEqualStrings("viewer", try normalizeRole(null)); try std.testing.expectEqualStrings("viewer", try normalizeRole("")); try std.testing.expectEqualStrings("admin", try normalizeRole("Admin")); + try std.testing.expectEqualStrings("analyst", try normalizeRole("ANALYST")); try std.testing.expectError(error.BadRole, normalizeRole("owner")); } diff --git a/server/src/routes/yara_rules.zig b/server/src/routes/yara_rules.zig index c3baf07..632c933 100644 --- a/server/src/routes/yara_rules.zig +++ b/server/src/routes/yara_rules.zig @@ -20,6 +20,14 @@ const util = @import("../http/util.zig"); const auth = @import("../http/auth.zig"); const audit = @import("../http/audit.zig"); const state = @import("../http/state.zig"); + +/// Route permissions, enforced by http/permissions.zig before the handler runs. +pub const routes = [_]@import("../http/permissions.zig").Route{ + .{ .method = .POST, .path = "/api/agent/yara-rules", .perm = .agent }, + .{ .method = .GET, .path = "/api/yara/rule-key", .perm = .read }, + .{ .method = .POST, .path = "/api/alert-rules/yara", .perm = .admin }, +}; + const Ed25519 = std.crypto.sign.Ed25519; pub const pack_format = "tawny-yara-pack-v1"; From 8265480ac4b8cda5e1f166976859cb0a75df620e Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 06:07:43 +1100 Subject: [PATCH 2/5] server: Tawny-SOC incident sink, mock OIDC contract tests Incidents go to Tawny-SOC through its existing POST /api/ingest/tawny as an alert with a stable id and the risk breakdown. Tawny-SOC's app/api/v1/cases is read-only (GET list and GET by id), so Tawny does not create cases itself. Detection queues one update per incident (30 s debounce); assign and status changes queue another. Contract suite: an analyst and a viewer against live routes, the analyst approval flow, the Office to PowerShell chain as one incident with its score, the three ATT&CK states, and Entra ID sign-in against a mock OIDC provider that signs RS256 tokens with a key from openssl genrsa at start-up (TAWNY_OIDC_ALLOW_LOOPBACK lets the server reach it on 127.0.0.1). Also: action result route pattern matches /api/agents/actions/:id/result, admins can mark break-glass users, the bootstrap admin is break-glass. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 3 + .../__pycache__/mock_oidc.cpython-314.pyc | Bin 0 -> 12729 bytes .../__pycache__/suite.cpython-314.pyc | Bin 0 -> 161570 bytes contract-tests/mock_oidc.py | 143 ++++++++ contract-tests/suite.py | 319 ++++++++++++++++++ server/src/http/auth.zig | 4 +- server/src/http/permissions.zig | 2 +- server/src/jobs/incident_sink.zig | 199 +++++++++++ server/src/main.zig | 18 + server/src/routes/agents.zig | 2 +- server/src/routes/oidc.zig | 35 +- server/src/routes/settings.zig | 2 +- server/src/routes/users.zig | 11 + server/src/sinks/tawny_soc.zig | 133 ++++++++ 14 files changed, 855 insertions(+), 16 deletions(-) create mode 100644 contract-tests/__pycache__/mock_oidc.cpython-314.pyc create mode 100644 contract-tests/__pycache__/suite.cpython-314.pyc create mode 100644 contract-tests/mock_oidc.py create mode 100644 server/src/jobs/incident_sink.zig diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6bc2922..ac1c32b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,6 +41,9 @@ jobs: # The contract suite posts unsigned batches from keyless test agents. # Signed batches are checked there and in agent-e2e with this on. TAWNY_REQUIRE_SIGNED_BATCHES: "off" + # Lets the server reach the contract suite's mock OIDC provider on + # http://127.0.0.1. Never set in production. + TAWNY_OIDC_ALLOW_LOOPBACK: "1" defaults: run: working-directory: server diff --git a/contract-tests/__pycache__/mock_oidc.cpython-314.pyc b/contract-tests/__pycache__/mock_oidc.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68a2158aa1d7b44d0037c3f5079ce1726495982c GIT binary patch literal 12729 zcmb_idvH_NnZJ6!{Fbo=h9F+X0!sp89^uu3F@z96TpSaEgCeABOCU?)-YdXLvY|7X zF6nd@leS}%%@(okPRz{C#F=)c?mt_0_m9$j^*VAY?+vrtna<8m_Ah6h4Bh^-`}@xI zm1IXi+U?QkydU5B?svY|Ih*ThogBjT*8jfvzaEbJ4HfiY)-s0q?;~@a<2ji-&+&$% zhUbj3aW&di)_M}rOAu4+_V){xVCWzj_wCI)Nf;XB@$zlX8QZ^wA0jKk{97)9_Zz9FI98W~W zw3Hr{y}i`Wd-PDidsOxg2`NF0$b#gJq`ds;1Kvx*h&O^sWKc1b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`QV<@t?2D2IDPoWvW=G0z( zay*dK0leXl?;gH1MUS}Y2^bOcnUwxG7CgUU813heo9TCSO|y+XjD|7ZI`9^AIwtL| zjN8U1hv2(p2mdsF!P^=K8DszMzFw=6?6aS7Tmi>!n*NN|FV%V+u z9gT(kOTq2C8vR#{Uow8h{3SEI%GT2yyt(tnPFMYFO|LY)w)2&p^P9be+q{T$mCHl}EkN+||fc^>(gSsO#~@ z9=~c_O|;z1ypee`_eQQ@-Q>}E6SrQC5C2eIW_Wb)Mpa)mysM8A%mqGu!LMVIg|z*P z$-guTDM!6AoM7PK=PxnoY8+Hz1x+G&QCE%ED!rQQhml%s{X=7dwnO`{M5o>QFh;Ab zdT7*Y2jK@-tF^HZ5wzOu_l@IPZ7!vgdOwz3ngI5HKaO3-YZBA%o7p9q!`@G1mr0te zy!#e*Nsa;Tr?AUZx=dr2=@cP@U1n-Ba_(ob%WO&^hh65vMEZUnyR>QwO77>g%K}Yq z!TmyZS)@tJ{;-%`YAAg8v_40h_;8ojpiO%iZ_rxr$Cqg%@0&Em<@e+0DqfSB|DhRI zAKJ8;+KumP5Ik&7)MkBHX2vT;TJ0WG+MrFokGFfYi;W*@==?A~N^AZwIZm7L(3+;* z^g*Le+pe7}xmk0gW+ka{DXH-T4L!LZ6R+K+UFar4W0&?}fmXW@sYPq^9;WNG@GTsp z(-waabKIgWn%lpUT)dQA{DFq?AYkqnXbh%nvp#*sD!vVI*1K_5IF`P;_t&OWe3jlcC9Rms zU~(=%O`5c-rCWE7m;8SOer)ra_TG;&M8}|iqvIZ!jd77z+ptxSPhE*Cx*J#IzTk_i zTZ!Aa6t{7H*c-R)>fTjD)K~WZoBeYoD@i3wNeIjCCY4=3>h6Eru;Kj-jUkhLfBt{3 Cf20Bc literal 0 HcmV?d00001 diff --git a/contract-tests/mock_oidc.py b/contract-tests/mock_oidc.py new file mode 100644 index 0000000..7b186ed --- /dev/null +++ b/contract-tests/mock_oidc.py @@ -0,0 +1,143 @@ +"""Mock OpenID Connect provider for the contract suite. + +Stands in for Microsoft Entra ID. It generates an RSA key at start-up with +`openssl genrsa` (deleted on exit), serves discovery and JWKS, and signs +RS256 ID tokens. No real tenant, app registration or secret is involved. + +Codes are handed out by the test, not by a sign-in page: + POST /_test/code {"oid","tid","email","name","groups","nonce"} -> {"code"} +Token exchange checks client_id, client_secret, redirect_uri and the PKCE +verifier against the challenge the authorise request sent (S256). + +Usage (from suite.py): MockOidc().start() then .stop(). +""" +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import secrets +import shutil +import subprocess +import tempfile +import threading +import time +import urllib.parse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + +def b64url(data: bytes) -> str: + return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") + + +class MockOidc: + client_id = "tawny-contract-client" + client_secret = "mock-client-secret-not-real" + tid = "11111111-2222-4333-8444-555555555555" + + def __init__(self) -> None: + self.dir = tempfile.mkdtemp(prefix="tawny-mock-oidc-") + self.pem = os.path.join(self.dir, "key.pem") + subprocess.run(["openssl", "genrsa", "-out", self.pem, "2048"], check=True, capture_output=True) + modulus = subprocess.run( + ["openssl", "rsa", "-in", self.pem, "-noout", "-modulus"], check=True, capture_output=True + ).stdout.decode().strip().split("=", 1)[1] + self.n = b64url(bytes.fromhex(modulus)) + self.kid = "mock-" + secrets.token_hex(4) + self.codes: dict[str, dict] = {} + self.pending: dict[str, dict] = {} + self.token_overrides: dict[str, dict] = {} + self.server: ThreadingHTTPServer | None = None + self.base = "" + + @property + def issuer(self) -> str: + return f"{self.base}/{self.tid}/v2.0" + + def sign(self, claims: dict, kid: str | None = None) -> str: + header = b64url(json.dumps({"alg": "RS256", "typ": "JWT", "kid": kid or self.kid}, separators=(",", ":")).encode()) + payload = b64url(json.dumps(claims, separators=(",", ":")).encode()) + signing_input = f"{header}.{payload}".encode() + sig = subprocess.run( + ["openssl", "dgst", "-sha256", "-sign", self.pem], input=signing_input, check=True, capture_output=True + ).stdout + return f"{header}.{payload}.{b64url(sig)}" + + def issue_code(self, *, oid: str, email: str, groups: list[str], nonce: str, challenge: str, name: str = "Mock User", overrides: dict | None = None) -> str: + code = secrets.token_urlsafe(24) + now = int(time.time()) + claims = { + "iss": self.issuer, + "aud": self.client_id, + "tid": self.tid, + "oid": oid, + "email": email, + "name": name, + "groups": groups, + "nonce": nonce, + "iat": now, + "nbf": now - 5, + "exp": now + 600, + } + claims.update(overrides or {}) + self.codes[code] = {"claims": claims, "challenge": challenge} + return code + + def start(self) -> "MockOidc": + mock = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_args) -> None: # quiet + return + + def _json(self, code: int, body: object) -> None: + raw = json.dumps(body).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(raw))) + self.end_headers() + self.wfile.write(raw) + + def do_GET(self) -> None: # noqa: N802 + path = urllib.parse.urlparse(self.path).path + if path == f"/{mock.tid}/v2.0/.well-known/openid-configuration": + return self._json(200, { + "issuer": mock.issuer, + "authorization_endpoint": f"{mock.base}/{mock.tid}/oauth2/v2.0/authorize", + "token_endpoint": f"{mock.base}/{mock.tid}/oauth2/v2.0/token", + "jwks_uri": f"{mock.base}/{mock.tid}/discovery/v2.0/keys", + "id_token_signing_alg_values_supported": ["RS256"], + }) + if path == f"/{mock.tid}/discovery/v2.0/keys": + return self._json(200, {"keys": [{"kty": "RSA", "use": "sig", "kid": mock.kid, "n": mock.n, "e": "AQAB"}]}) + return self._json(404, {"error": "not_found"}) + + def do_POST(self) -> None: # noqa: N802 + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length).decode() + path = urllib.parse.urlparse(self.path).path + if path != f"/{mock.tid}/oauth2/v2.0/token": + return self._json(404, {"error": "not_found"}) + form = {k: v[0] for k, v in urllib.parse.parse_qs(body).items()} + if form.get("grant_type") != "authorization_code": + return self._json(400, {"error": "unsupported_grant_type"}) + if form.get("client_id") != mock.client_id or form.get("client_secret") != mock.client_secret: + return self._json(401, {"error": "invalid_client"}) + entry = mock.codes.pop(form.get("code", ""), None) + if entry is None: + return self._json(400, {"error": "invalid_grant"}) + verifier = form.get("code_verifier", "") + if b64url(hashlib.sha256(verifier.encode()).digest()) != entry["challenge"]: + return self._json(400, {"error": "invalid_grant", "error_description": "PKCE"}) + return self._json(200, {"token_type": "Bearer", "id_token": mock.sign(entry["claims"]), "access_token": "unused"}) + + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.base = f"http://127.0.0.1:{self.server.server_address[1]}" + threading.Thread(target=self.server.serve_forever, daemon=True).start() + return self + + def stop(self) -> None: + if self.server: + self.server.shutdown() + shutil.rmtree(self.dir, ignore_errors=True) diff --git a/contract-tests/suite.py b/contract-tests/suite.py index d12fb27..0ef8d45 100644 --- a/contract-tests/suite.py +++ b/contract-tests/suite.py @@ -18,6 +18,7 @@ import urllib.request import uuid +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) BASE = os.environ.get("TAWNY_BASE_URL", "http://127.0.0.1:5080").rstrip("/") AUTH = os.environ.get("TAWNY_CONTRACT_AUTH", "hmac").strip().lower() HMAC_SECRET = os.environ.get("TAWNY_HMAC_SECRET", "test-hmac-secret") @@ -1959,6 +1960,323 @@ def test_rs256_heartbeat_rotates_to_eddsa(self) -> None: self.assertEqual(denied, 401, denied_raw[:400]) + +def make_user(role: str, prefix: str) -> tuple[str, str, str]: + """Create a password user with `role`; return (user_id, cookie, csrf).""" + email = f"{uniq(prefix)}@tawny.local" + code, created, raw = admin_call("POST", "/api/users", {"email": email, "password": "role-password1", "role": role}) + if code != 201 or not isinstance(created, dict): + raise AssertionError(f"create {role} user: {code} {raw[:400]}") + cookie, csrf, who = login_session(email, "role-password1") + if who.get("role") != role: + raise AssertionError(f"login role {who.get('role')} != {role}") + return str(created["id"]), cookie, csrf + + +def admin_call(method: str, path: str, body: dict) -> tuple[int, object | None, str]: + """Admin write that waits out the 30 per minute web-admin-mutate limit + the rest of the suite may have used up.""" + for _ in range(3): + code, parsed, raw = call(method, path, body) + if code != 429: + return code, parsed, raw + time.sleep(21) + return code, parsed, raw + + +class RoleAndIncidentContractTests(unittest.TestCase): + """#60: analyst role on real routes, incidents, ATT&CK coverage, Entra ID.""" + + def setUp(self) -> None: + if AUTH != "session": + self.skipTest("session auth routes run against tawny-server") + + def as_role(self, method: str, path: str, cookie: str, csrf: str, body: dict | None = None) -> tuple[int, object | None, str]: + return call(method, path, body if body is not None else ({} if method != "GET" else None), session_cookie=cookie, csrf_token=csrf) + + def test_analyst_matrix_on_live_routes(self) -> None: + _aid, a_cookie, a_csrf = make_user("analyst", "analyst") + _vid, v_cookie, v_csrf = make_user("viewer", "viewer60") + agent = windows_agent() + # (method, path, body, analyst, viewer). 403 means the gate refused; + # anything else means the handler ran. + checks = [ + ("GET", "/api/users", None, 403, 403), + ("POST", "/api/users", {"email": "x@y.z", "password": "longpassword"}, 403, 403), + ("POST", "/api/api-tokens", {"name": "t"}, 403, 403), + ("POST", "/api/enrollment-tokens", {}, 403, 403), + ("POST", "/api/alert-rules", {"name": "n"}, 403, 403), + ("POST", "/api/alert-rules/sigma", {"rule_yaml": "title: x"}, 403, 403), + ("POST", "/api/threat-intel-feeds", {"name": "n"}, 403, 403), + ("PUT", "/api/ai/config", {}, 403, 403), + ("GET", "/api/settings/tenant", None, 403, 403), + ("PUT", "/api/settings/oidc", {}, 403, 403), + ("GET", "/api/admin/jobs", None, 403, 403), + ("POST", f"/api/agents/{agent['agent_id']}/revoke", {}, 403, 403), + ("GET", "/api/agents", None, 200, 200), + ("GET", "/api/alerts", None, 200, 200), + ("GET", "/api/incidents", None, 200, 200), + ("GET", "/api/attack/coverage", None, 200, 200), + ("POST", "/api/hunts/run", {"query": "event_type:process_start"}, None, 403), + ("POST", f"/api/agents/{agent['agent_id']}/actions", {"action_type": "kill_process", "payload": {"pid": 1}}, 201, 403), + ("POST", "/api/suppression-rules", {"name": "no reason", "scope": "all_rules", "operator": "equals", "payload_path": "contract.never", "match_value": "x"}, 400, 403), + ("POST", "/api/suppression-rules", {"name": uniq("why"), "reason": "known admin script", "scope": "all_rules", "operator": "equals", "payload_path": "contract.never", "match_value": uniq("x")}, 201, 403), + ("POST", "/api/alerts/999999999/acknowledge", {}, 404, 403), + ("POST", "/api/incidents/00000000-0000-0000-0000-000000000000/status", {"status": "resolved"}, 404, 403), + ] + for method, path, body, want_analyst, want_viewer in checks: + code, made, raw = self.as_role(method, path, a_cookie, a_csrf, body) + if path == "/api/suppression-rules" and code == 201 and isinstance(made, dict): + call("DELETE", f"/api/suppression-rules/{made['id']}", {}) + if want_analyst is None: + self.assertNotIn(code, (401, 403), f"analyst {method} {path}: {raw[:300]}") + else: + self.assertEqual(code, want_analyst, f"analyst {method} {path}: {raw[:300]}") + code, _b, raw = self.as_role(method, path, v_cookie, v_csrf, body) + self.assertEqual(code, want_viewer, f"viewer {method} {path}: {raw[:300]}") + anon, _b, _raw = call("GET", "/api/incidents", auth="none") + self.assertEqual(anon, 401) + + def test_analyst_destructive_action_waits_for_admin(self) -> None: + analyst_id, a_cookie, a_csrf = make_user("analyst", "approve") + agent = windows_agent() + code, _s, raw = admin_call("PUT", "/api/settings/tenant", {"analyst_destructive_needs_approval": True}) + self.assertEqual(code, 200, raw[:300]) + try: + code, action, raw = self.as_role("POST", f"/api/agents/{agent['agent_id']}/actions", a_cookie, a_csrf, + {"action_type": "isolate_host", "payload": {"reason": "contract"}}) + self.assertEqual(code, 201, raw[:400]) + assert isinstance(action, dict) + self.assertEqual(action.get("status"), "awaiting_approval") + # Not killing a process: no approval needed. + code, kill, raw = self.as_role("POST", f"/api/agents/{agent['agent_id']}/actions", a_cookie, a_csrf, + {"action_type": "kill_process", "payload": {"pid": 4}}) + self.assertEqual(code, 201, raw[:400]) + assert isinstance(kill, dict) + self.assertEqual(kill.get("status"), "pending") + # The analyst cannot approve; an admin can. + code, _b, raw = self.as_role("POST", f"/api/agents/{agent['agent_id']}/actions/{action['id']}/approve", a_cookie, a_csrf) + self.assertEqual(code, 403, raw[:300]) + code, ok, raw = call("POST", f"/api/agents/{agent['agent_id']}/actions/{action['id']}/approve", {}) + self.assertEqual(code, 200, raw[:300]) + assert isinstance(ok, dict) + self.assertEqual(ok.get("status"), "pending") + code, _b, raw = call("POST", f"/api/agents/{agent['agent_id']}/actions/{action['id']}/approve", {}) + self.assertEqual(code, 409, raw[:300]) + finally: + admin_call("PUT", "/api/settings/tenant", {"analyst_destructive_needs_approval": False}) + del analyst_id + + def test_process_chain_becomes_one_incident(self) -> None: + agent = windows_agent() + marker = uniq("inc") + rules = [] + for name, path, value, sev, tech in ( + ("Office spawns PowerShell", "parent.image", "WINWORD.EXE", "high", ["T1204.002"]), + ("Encoded PowerShell", "process.command_line", "-enc", "medium", ["T1059.001"]), + ): + code, rule, raw = call("POST", "/api/alert-rules", { + "name": f"{marker} {name}", "event_type": "process_start", "severity": sev, "operator": "contains", + "payload_path": path, "match_value": value, "is_enabled": True, "mitre_techniques": tech, + }) + self.assertEqual(code, 201, raw[:400]) + assert isinstance(rule, dict) + rules.append(rule["id"]) + try: + fixture_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "server", "fixtures", "process-chain-office.v2.json") + with open(fixture_path, encoding="utf-8") as handle: + batch = json.load(handle) + batch["agent"]["agent_id"] = agent["agent_id"] + batch["batch_id"] = str(uuid.uuid4()) + alphabet = "abcdefghijklmnopqrstuvwxyz234567" + suffix = "".join(alphabet[b % 32] for b in secrets.token_bytes(4)) + for ev in batch["events"]: + ev["event_id"] = str(uuid.uuid4()) + ev["seq"] = 3000 + ev["seq"] + ev["ts"] = iso_now() + for key in ("process", "parent"): + obj = ev["data"].get(key, {}) + if obj.get("entity_id"): + obj["entity_id"] = obj["entity_id"][:22] + suffix + code, _p, raw = call("POST", "/api/agents/events", batch, auth="agent", bearer=agent["jwt"]) + self.assertEqual(code, 202, raw[:400]) + deadline = time.time() + 10 + mine: list[dict] = [] + while time.time() < deadline: + code, rows, raw = call("GET", "/api/incidents?status=open&limit=500") + self.assertEqual(code, 200, raw[:400]) + assert isinstance(rows, list) + mine = [r for r in rows if any(i["label"].startswith(marker) for i in r.get("risk_items") or [])] + labels = [i["label"] for r in mine for i in r["risk_items"] if i["label"].startswith(marker)] + if len(labels) >= 2: + break + time.sleep(0.5) + # Both rules fired on the chain; the alerts share one lineage + # root (WINWORD below explorer), so they are one incident. + self.assertEqual(len(mine), 1, json.dumps(mine)[:800]) + inc = mine[0] + self.assertEqual(inc["grouping"], "lineage") + self.assertGreaterEqual(inc["alert_count"], 2) + ours = sorted(i["points"] for i in inc["risk_items"] if i["label"].startswith(marker)) + self.assertEqual(ours, [20, 30]) + # The score is the noisy-OR of exactly the listed items. + prod = 1.0 + for item in inc["risk_items"]: + prod *= 1 - item["points"] / 100 + self.assertEqual(inc["risk"], round(100 * (1 - prod)), json.dumps(inc["risk_items"])) + self.assertIn("T1059.001", inc["techniques"]) + self.assertIn("T1204.002", inc["techniques"]) + code, full, raw = call("GET", f"/api/incidents/{inc['id']}") + self.assertEqual(code, 200, raw[:400]) + assert isinstance(full, dict) + self.assertEqual(len(full["alerts"]), inc["alert_count"]) + + _aid, a_cookie, a_csrf = make_user("analyst", "owner") + code, assigned, raw = self.as_role("POST", f"/api/incidents/{inc['id']}/assign", a_cookie, a_csrf, {"owner_user_id": _aid}) + self.assertEqual(code, 200, raw[:400]) + assert isinstance(assigned, dict) + self.assertEqual(assigned["status"], "investigating") + code, _b, raw = self.as_role("POST", f"/api/incidents/{inc['id']}/status", a_cookie, a_csrf, {"status": "closed"}) + self.assertEqual(code, 400, raw[:300]) + alert_id = full["alerts"][0]["id"] + code, acked, raw = self.as_role("POST", f"/api/alerts/{alert_id}/acknowledge", a_cookie, a_csrf) + self.assertEqual(code, 200, raw[:300]) + assert isinstance(acked, dict) + self.assertEqual(acked["status"], "acknowledged") + code, done, raw = self.as_role("POST", f"/api/incidents/{inc['id']}/status", a_cookie, a_csrf, {"status": "false_positive"}) + self.assertEqual(code, 200, raw[:300]) + assert isinstance(done, dict) + self.assertTrue(all(a["status"] == "resolved" for a in done["alerts"])) + finally: + for rid in rules: + call("DELETE", f"/api/alert-rules/{rid}", {}) + + def test_attack_coverage_three_states(self) -> None: + name = uniq("cov") + code, rule, raw = call("POST", "/api/alert-rules", { + "name": name, "event_type": "registry_set", "severity": "low", "operator": "exists", + "payload_path": "registry.key", "is_enabled": True, "mitre_techniques": ["T1112"], + }) + self.assertEqual(code, 201, raw[:400]) + assert isinstance(rule, dict) + try: + code, cov, raw = call("GET", "/api/attack/coverage?platform=windows") + self.assertEqual(code, 200, raw[:400]) + assert isinstance(cov, dict) + self.assertEqual(cov["attack_version"], "20.1") + self.assertIn("stealth", [t["shortname"] for t in cov["tactics"]]) + by_id = {t["id"]: t for t in cov["techniques"]} + t1112 = by_id["T1112"] + # A rule, no registry telemetry from a healthy agent, no action: + # three different answers. + self.assertTrue(t1112["detection"]["available"]) + self.assertIn(name, t1112["detection"]["rules"]) + self.assertFalse(t1112["telemetry"]["available"], json.dumps(t1112)) + self.assertFalse(t1112["response"]["available"]) + self.assertEqual(by_id["T1059.001"]["name"], "Command and Scripting Interpreter: PowerShell") + self.assertIn("isolate_host", by_id["T1110"]["response"]["actions"]) + code, lin, raw = call("GET", "/api/attack/coverage?platform=linux") + self.assertEqual(code, 200, raw[:300]) + assert isinstance(lin, dict) + lin_ids = {t["id"]: t for t in lin["techniques"]} + self.assertNotIn("T1112", lin_ids) + self.assertNotIn("isolate_host", lin_ids["T1110"]["response"]["actions"]) + bad, _b, _raw = call("GET", "/api/attack/coverage?platform=solaris") + self.assertEqual(bad, 400) + finally: + call("DELETE", f"/api/alert-rules/{rule['id']}", {}) + + def test_zz_entra_sign_in_with_mock_provider(self) -> None: + if os.environ.get("TAWNY_OIDC_ALLOW_LOOPBACK", "") not in ("1", "true"): + self.skipTest("TAWNY_OIDC_ALLOW_LOOPBACK is off on the server") + from mock_oidc import MockOidc + + mock = MockOidc().start() + g_admin, g_analyst, g_other = str(uuid.uuid4()), str(uuid.uuid4()), str(uuid.uuid4()) + try: + code, cfg, raw = admin_call("PUT", "/api/settings/oidc", { + "enabled": True, + "entra_tenant_id": mock.tid, + "authority": mock.issuer, + "client_id": mock.client_id, + "client_secret": mock.client_secret, + "allowed_domains": ["contoso.example"], + "group_roles": {g_admin: "admin", g_analyst: "analyst"}, + }) + self.assertEqual(code, 200, raw[:400]) + assert isinstance(cfg, dict) + self.assertTrue(cfg["client_secret_set"]) + self.assertNotIn(mock.client_secret, raw) + code, methods, _raw = call("GET", "/api/auth/methods", auth="none") + assert isinstance(methods, dict) + self.assertTrue(methods["entra"]) + + def sign_in(oid: str, groups: list[str], email: str = "", overrides: dict | None = None, tamper_state: bool = False) -> tuple[int, str, str]: + status, location, _c, body = open_no_redirect("GET", f"/api/auth/oidc/start?tenant={TENANT}") + self.assertEqual(status, 302, body[:300]) + self.assertTrue(location.startswith(f"{mock.base}/{mock.tid}/oauth2/v2.0/authorize?"), location) + q = {k: v[0] for k, v in urllib.parse.parse_qs(urllib.parse.urlparse(location).query).items()} + self.assertEqual(q["code_challenge_method"], "S256") + self.assertEqual(q["client_id"], mock.client_id) + code_ = mock.issue_code(oid=oid, email=email or f"{oid[:8]}@contoso.example", groups=groups, + nonce=q["nonce"], challenge=q["code_challenge"], overrides=overrides) + state = "forged" + q["state"][6:] if tamper_state else q["state"] + st, _loc, cookie, body = open_no_redirect("GET", f"/api/auth/oidc/callback?code={urllib.parse.quote(code_)}&state={state}") + return st, cookie.split(";", 1)[0], body + + oid = str(uuid.uuid4()) + st, cookie, body = sign_in(oid, [g_analyst, g_other]) + self.assertEqual(st, 302, body[:400]) + code, who, raw = call("GET", "/api/auth/session", session_cookie=cookie) + self.assertEqual(code, 200, raw[:300]) + assert isinstance(who, dict) + self.assertEqual(who["role"], "analyst") + # Same oid and tid again: same user, role follows the groups. + st, cookie2, body = sign_in(oid, [g_admin], email="renamed@contoso.example") + self.assertEqual(st, 302, body[:400]) + code, who2, _raw = call("GET", "/api/auth/session", session_cookie=cookie2) + assert isinstance(who2, dict) + self.assertEqual(who2["id"], who["id"]) + self.assertEqual(who2["role"], "admin") + + # Refusals: no mapped group, wrong domain, bad nonce, wrong audience, + # expired, replayed state. + st, _c, body = sign_in(str(uuid.uuid4()), [g_other]) + self.assertEqual(st, 403, body[:300]) + self.assertIn("groups do not grant access", body) + st, _c, body = sign_in(str(uuid.uuid4()), [g_analyst], email="eve@evil.example") + self.assertEqual(st, 403, body[:300]) + for override in ({"nonce": "wrong"}, {"aud": "someone-else"}, {"exp": int(time.time()) - 3600}, {"iss": "https://evil.example/v2.0"}): + st, _c, body = sign_in(str(uuid.uuid4()), [g_analyst], overrides=override) + self.assertEqual(st, 401, f"{override}: {body[:300]}") + st, _c, body = sign_in(str(uuid.uuid4()), [g_analyst], tamper_state=True) + self.assertEqual(st, 400, body[:300]) + + # Password sign-in limited to break-glass admins. + _vid, _vc, _vx = make_user("viewer", "glass") + email = f"{uniq('glassuser')}@tawny.local" + code, _u, raw = admin_call("POST", "/api/users", {"email": email, "password": "glass-password1", "role": "analyst"}) + self.assertEqual(code, 201, raw[:300]) + code, _s, raw = admin_call("PUT", "/api/settings/tenant", {"password_login": "break_glass"}) + self.assertEqual(code, 200, raw[:300]) + try: + with self.assertRaises(AssertionError) as ctx: + login_session(email, "glass-password1") + self.assertIn("403", str(ctx.exception)) + # The bootstrap admin is break-glass and still signs in. + login_session(os.environ.get("TAWNY_CONTRACT_EMAIL", "admin@tawny.local"), + os.environ.get("TAWNY_CONTRACT_PASSWORD", "contract-password")) + code, m2, _raw = call("GET", "/api/auth/methods", auth="none") + assert isinstance(m2, dict) + self.assertEqual(m2["password"], "break_glass") + finally: + admin_call("PUT", "/api/settings/tenant", {"password_login": "all"}) + login_session(email, "glass-password1") + finally: + admin_call("PUT", "/api/settings/oidc", {"enabled": False, "entra_tenant_id": mock.tid, "client_id": mock.client_id}) + mock.stop() + + def load_tests(loader: unittest.TestLoader, standard_tests: list, pattern: str | None): del loader, pattern rest: list[unittest.TestCase] = [] @@ -1983,6 +2301,7 @@ def load_tests(loader: unittest.TestLoader, standard_tests: list, pattern: str | [ loader.loadTestsFromTestCase(AuthContractTests), loader.loadTestsFromTestCase(ContractTests), + loader.loadTestsFromTestCase(RoleAndIncidentContractTests), ], None, ) diff --git a/server/src/http/auth.zig b/server/src/http/auth.zig index 29c7570..2bfd395 100644 --- a/server/src/http/auth.zig +++ b/server/src/http/auth.zig @@ -526,8 +526,8 @@ pub fn bootstrapAdminIfEmpty( var tbuf: [32]u8 = undefined; const created = util.formatRfc3339(&tbuf, util.nowUnix(io)); try conn.execNoRows( - \\INSERT INTO users (id, tenant_id, email, name, role, password_hash, created_at) - \\VALUES ($1::uuid, $2::uuid, $3, 'Admin', 'admin', $4, $5::timestamptz) + \\INSERT INTO users (id, tenant_id, email, name, role, password_hash, created_at, break_glass) + \\VALUES ($1::uuid, $2::uuid, $3, 'Admin', 'admin', $4, $5::timestamptz, true) \\ON CONFLICT DO NOTHING , &.{ .{ .text = uid }, diff --git a/server/src/http/permissions.zig b/server/src/http/permissions.zig index 7ce48d5..059cb99 100644 --- a/server/src/http/permissions.zig +++ b/server/src/http/permissions.zig @@ -136,7 +136,7 @@ const expected = [_]Expect{ .{ .method = .POST, .path = "/api/agents/enroll", .admin = 'p', .analyst = 'p', .viewer = 'p' }, .{ .method = .POST, .path = "/api/agents/heartbeat", .admin = 'g', .analyst = 'g', .viewer = 'g' }, .{ .method = .POST, .path = "/api/agents/events", .admin = 'g', .analyst = 'g', .viewer = 'g' }, - .{ .method = .POST, .path = "/api/agents/x/actions/y/result", .admin = 'g', .analyst = 'g', .viewer = 'g' }, + .{ .method = .POST, .path = "/api/agents/actions/y/result", .admin = 'g', .analyst = 'g', .viewer = 'g' }, .{ .method = .POST, .path = "/api/agent/yara-rules", .admin = 'g', .analyst = 'g', .viewer = 'g' }, .{ .method = .POST, .path = "/api/agent/update-check", .admin = 'g', .analyst = 'g', .viewer = 'g' }, .{ .method = .GET, .path = "/api/agents", .admin = 'a', .analyst = 'a', .viewer = 'a' }, diff --git a/server/src/jobs/incident_sink.zig b/server/src/jobs/incident_sink.zig new file mode 100644 index 0000000..d3ebfec --- /dev/null +++ b/server/src/jobs/incident_sink.zig @@ -0,0 +1,199 @@ +//! Drain `work_queue` kind `incident_sink`: send each incident to Tawny-SOC +//! (sinks/tawny_soc.zig) through its existing ingest endpoint. Rows are +//! queued by detect (30 s debounce) and by incident assign or status. +//! +//! Configured with the existing TAWNY_SOC_* variables: +//! TAWNY_SOC_ENABLED=true, TAWNY_SOC_ENDPOINT_URL, TAWNY_SOC_API_TOKEN +//! TAWNY_SOC_INCIDENTS_ENABLED (default true when the sink is enabled) +const std = @import("std"); +const pg = @import("../db/pg/conn.zig"); +const util = @import("../http/util.zig"); +const egress = @import("../sinks/egress.zig"); +const soc = @import("../sinks/tawny_soc.zig"); + +pub const Config = struct { + endpoint: []const u8 = "", + token: []const u8 = "", + public_url: []const u8 = "", + allow_private: bool = false, +}; + +const max_attempts: u32 = 5; + +fn freeRows(allocator: std.mem.Allocator, rows: []pg.Row) void { + for (rows) |row| row.deinit(allocator); + allocator.free(rows); +} + +pub fn drain(allocator: std.mem.Allocator, io: std.Io, conn: *pg.Conn, cfg: Config) !u32 { + const claimed = try conn.exec(allocator, + \\UPDATE work_queue SET locked_until = now() + interval '5 minutes', attempts = attempts + 1 + \\WHERE id IN ( + \\ SELECT id FROM work_queue + \\ WHERE kind = 'incident_sink' AND run_after <= now() + \\ AND (locked_until IS NULL OR locked_until < now()) + \\ ORDER BY id LIMIT 16 + \\ FOR UPDATE SKIP LOCKED + \\) + \\RETURNING id::text, tenant_id::text, payload->>'incident_id', attempts::text + , &.{}); + defer freeRows(allocator, claimed); + var done: u32 = 0; + for (claimed) |row| { + const qid = row.cols[0] orelse continue; + const tenant = row.cols[1] orelse ""; + const incident = row.cols[2] orelse ""; + const attempts = std.fmt.parseInt(u32, row.cols[3] orelse "1", 10) catch 1; + if (cfg.endpoint.len == 0) { + try mark(conn, tenant, incident, "not_configured", null); + try deleteJob(conn, qid); + done += 1; + continue; + } + if (sendOne(allocator, io, conn, cfg, tenant, incident)) |_| { + try mark(conn, tenant, incident, "sent", null); + try deleteJob(conn, qid); + done += 1; + } else |err| { + const permanent = err == error.EgressRefused or err == error.NotFound or attempts >= max_attempts; + if (permanent) { + try mark(conn, tenant, incident, "failed", @errorName(err)); + try deleteJob(conn, qid); + done += 1; + } else { + try conn.execNoRows( + \\UPDATE work_queue SET last_error = $2, locked_until = now() + interval '1 minute' WHERE id = $1::bigint + , &.{ .{ .text = qid }, .{ .text = @errorName(err) } }); + } + } + } + return done; +} + +fn mark(conn: *pg.Conn, tenant: []const u8, incident: []const u8, status: []const u8, err: ?[]const u8) !void { + try conn.execNoRows( + \\UPDATE incidents SET soc_case_status = $3, soc_error = $4, + \\ soc_synced_at = CASE WHEN $3 = 'sent' THEN now() ELSE soc_synced_at END + \\WHERE tenant_id = $1::uuid AND id = $2::uuid + , &.{ .{ .text = tenant }, .{ .text = incident }, .{ .text = status }, if (err) |e| .{ .text = e } else .{ .null = {} } }); +} + +fn deleteJob(conn: *pg.Conn, id: []const u8) !void { + try conn.execNoRows("DELETE FROM work_queue WHERE id = $1::bigint", &.{.{ .text = id }}); +} + +/// Build the batch for one incident. The agent block names the first agent +/// in the incident; every agent id is in `incident.agent_ids`. +pub fn buildBatch(allocator: std.mem.Allocator, conn: *pg.Conn, public_url: []const u8, tenant: []const u8, incident: []const u8, sent_at: []const u8) ![]u8 { + const rows = try conn.exec(allocator, + \\SELECT i.id::text, i.title, i.status, i.severity, i.risk::text, i.risk_items::text, + \\ array_to_json(i.techniques)::text, array_to_json(i.agent_ids)::text, + \\ i.first_seen_at::text, i.last_seen_at::text, + \\ (SELECT count(*) FROM incident_alerts ia WHERE ia.incident_id = i.id)::text, + \\ ag.id::text, ag.hostname, ag.operating_system, ag.os_version, ag.architecture, ag.agent_version + \\FROM incidents i + \\LEFT JOIN agents ag ON ag.id = i.agent_ids[1] + \\WHERE i.tenant_id = $1::uuid AND i.id = $2::uuid + , &.{ .{ .text = tenant }, .{ .text = incident } }); + defer freeRows(allocator, rows); + if (rows.len == 0) return error.NotFound; + const c = rows[0].cols; + const url = try std.fmt.allocPrint(allocator, "{s}/incidents/{s}", .{ std.mem.trimEnd(u8, public_url, "/"), c[0] orelse "" }); + defer allocator.free(url); + return soc.formatIncidentBatch(allocator, .{ + .id = c[11] orelse "", + .tenant_id = tenant, + .hostname = c[12] orelse "", + .os = c[13] orelse "", + .os_version = c[14] orelse "", + .arch = c[15] orelse "", + .version = c[16] orelse "", + }, .{ + .id = c[0] orelse "", + .tenant_id = tenant, + .title = c[1] orelse "", + .status = c[2] orelse "new", + .severity = c[3] orelse "low", + .risk = std.fmt.parseInt(i64, c[4] orelse "0", 10) catch 0, + .risk_items = c[5] orelse "[]", + .techniques = c[6] orelse "[]", + .agent_ids = c[7] orelse "[]", + .first_seen_at = c[8] orelse sent_at, + .last_seen_at = c[9] orelse sent_at, + .alert_count = std.fmt.parseInt(i64, c[10] orelse "0", 10) catch 0, + .url = url, + }, sent_at); +} + +fn sendOne(allocator: std.mem.Allocator, io: std.Io, conn: *pg.Conn, cfg: Config, tenant: []const u8, incident: []const u8) !void { + const host = hostOf(cfg.endpoint) orelse return error.EgressRefused; + if (!egress.allowed(host, cfg.allow_private)) return error.EgressRefused; + var tbuf: [32]u8 = undefined; + const body = try buildBatch(allocator, conn, cfg.public_url, tenant, incident, util.formatRfc3339(&tbuf, util.nowUnix(io))); + defer allocator.free(body); + var client: std.http.Client = .{ .allocator = allocator, .io = io }; + defer client.deinit(); + var buf: [2048]u8 = undefined; + var writer = std.Io.Writer.fixed(&buf); + var authz_buf: [512]u8 = undefined; + const authz = if (cfg.token.len > 0) std.fmt.bufPrint(&authz_buf, "Bearer {s}", .{cfg.token}) catch return error.SinkSend else ""; + const extra = [_]std.http.Header{.{ .name = "authorization", .value = authz }}; + const result = client.fetch(.{ + .location = .{ .url = cfg.endpoint }, + .method = .POST, + .payload = body, + .keep_alive = false, + .redirect_behavior = .unhandled, + .response_writer = &writer, + .headers = .{ + .user_agent = .{ .override = "tawny-server" }, + .accept_encoding = .{ .override = "identity" }, + .content_type = .{ .override = "application/json" }, + }, + .extra_headers = if (cfg.token.len > 0) &extra else &.{}, + }) catch return error.SinkSend; + if (@intFromEnum(result.status) >= 300) return error.SinkSend; +} + +fn hostOf(url: []const u8) ?[]const u8 { + const sep = std.mem.indexOf(u8, url, "://") orelse return null; + const rest = url[sep + 3 ..]; + const end = std.mem.indexOfAny(u8, rest, ":/?#") orelse rest.len; + if (end == 0 or std.mem.indexOfScalar(u8, rest[0..end], '@') != null) return null; + return rest[0..end]; +} + +test "incident sink drains without config and refuses private endpoints" { + try std.testing.expectEqualStrings("soc.example.com", hostOf("https://soc.example.com/api/ingest/tawny").?); + try std.testing.expect(hostOf("https://user@soc/x") == null); + const url = std.testing.environ.getPosix("TAWNY_DATABASE_URL") orelse return; + if (url.len == 0) return; + const allocator = std.testing.allocator; + const io = std.testing.io; + const conn = try pg.Conn.connect(allocator, io, url); + defer { + conn.close(); + allocator.destroy(conn); + } + try conn.execSimple("BEGIN"); + defer conn.execSimple("ROLLBACK") catch {}; + const tenant = "00000000-0000-0000-0000-000000000001"; + const inc = "00000000-0000-4000-8000-00000000e601"; + try conn.execNoRows( + \\INSERT INTO incidents (id, tenant_id, title, severity, risk, grouping, first_seen_at, last_seen_at, created_at, updated_at) + \\VALUES ($1::uuid, $2::uuid, 'sink test', 'low', 10, 'alert', now(), now(), now(), now()) + , &.{ .{ .text = inc }, .{ .text = tenant } }); + try conn.execNoRows("UPDATE work_queue SET locked_until = now() + interval '1 hour' WHERE kind = 'incident_sink'", &.{}); + const payload = "{\"incident_id\":\"" ++ inc ++ "\"}"; + try conn.execNoRows("INSERT INTO work_queue (kind, tenant_id, payload) VALUES ('incident_sink', $1::uuid, $2::jsonb)", &.{ .{ .text = tenant }, .{ .text = payload } }); + // Batch shape from the database row. + const body = try buildBatch(allocator, conn, "https://tawny.example", tenant, inc, "2026-11-10T00:00:00Z"); + defer allocator.free(body); + try std.testing.expect(std.mem.indexOf(u8, body, "https://tawny.example/incidents/" ++ inc) != null); + // Loopback endpoint: refused, marked failed, job removed. + try std.testing.expectEqual(@as(u32, 1), try drain(allocator, io, conn, .{ .endpoint = "http://127.0.0.1:9/api/ingest/tawny" })); + const rows = try conn.exec(allocator, "SELECT soc_case_status, soc_error FROM incidents WHERE id = $1::uuid", &.{.{ .text = inc }}); + defer freeRows(allocator, rows); + try std.testing.expectEqualStrings("failed", rows[0].cols[0].?); + try std.testing.expectEqualStrings("EgressRefused", rows[0].cols[1].?); +} diff --git a/server/src/main.zig b/server/src/main.zig index 87b219a..e87685a 100644 --- a/server/src/main.zig +++ b/server/src/main.zig @@ -6,6 +6,7 @@ const util = @import("http/util.zig"); const state = @import("http/state.zig"); const detect = @import("jobs/detect.zig"); const deliver = @import("jobs/deliver.zig"); +const incident_sink = @import("jobs/incident_sink.zig"); const purge = @import("jobs/purge.zig"); const stale = @import("jobs/stale.zig"); const agent_alerts = @import("jobs/agent_alerts.zig"); @@ -228,6 +229,9 @@ fn runJobs( if (deliver.drain(allocator, io, conn, sink_targets)) |_| {} else |err| { std.debug.print("sink drain failed: {s}\n", .{@errorName(err)}); } + if (incident_sink.drain(allocator, io, conn, socIncidentConfig())) |_| {} else |err| { + std.debug.print("incident sink drain failed: {s}\n", .{@errorName(err)}); + } const now = util.nowUnix(io); if (now - last_purge.* >= 3600) { last_purge.* = now; @@ -351,6 +355,19 @@ fn envPort(key: [*:0]const u8, fallback: u16) u16 { return std.fmt.parseInt(u16, value, 10) catch fallback; } +/// Incidents go to Tawny-SOC when TAWNY_SOC_ENABLED is on, an endpoint is +/// set and TAWNY_SOC_INCIDENTS_ENABLED is not "false". +fn socIncidentConfig() incident_sink.Config { + if (!envFlag("TAWNY_SOC_ENABLED")) return .{}; + if (std.ascii.eqlIgnoreCase(envSpan("TAWNY_SOC_INCIDENTS_ENABLED"), "false")) return .{}; + return .{ + .endpoint = envSpan("TAWNY_SOC_ENDPOINT_URL"), + .token = envSpan("TAWNY_SOC_API_TOKEN"), + .public_url = envSpanDefault("TAWNY_PUBLIC_URL", ""), + .allow_private = envFlag("TAWNY_ALLOW_PRIVATE_EGRESS"), + }; +} + fn envFlag(key: [*:0]const u8) bool { const value = envSpan(key); return std.mem.eql(u8, value, "1") or std.ascii.eqlIgnoreCase(value, "true"); @@ -469,6 +486,7 @@ comptime { _ = @import("routes/oidc.zig"); _ = @import("detect/incidents.zig"); _ = @import("detect/incidents_test.zig"); + _ = @import("jobs/incident_sink.zig"); _ = @import("http/util.zig"); _ = @import("http/static.zig"); _ = @import("routes/admin_jobs.zig"); diff --git a/server/src/routes/agents.zig b/server/src/routes/agents.zig index 8735ca3..bcd1b25 100644 --- a/server/src/routes/agents.zig +++ b/server/src/routes/agents.zig @@ -20,7 +20,7 @@ pub const routes = [_]@import("../http/permissions.zig").Route{ .{ .method = .POST, .path = "/api/agents/enroll", .perm = .public }, .{ .method = .POST, .path = "/api/agents/heartbeat", .perm = .agent }, .{ .method = .POST, .path = "/api/agents/events", .perm = .agent }, - .{ .method = .POST, .path = "/api/agents/:id/actions/:action/result", .perm = .agent }, + .{ .method = .POST, .path = "/api/agents/actions/:action/result", .perm = .agent }, .{ .method = .GET, .path = "/api/agents", .perm = .read }, .{ .method = .GET, .path = "/api/agents/:id", .perm = .read }, .{ .method = .POST, .path = "/api/agents/:id/revoke", .perm = .admin }, diff --git a/server/src/routes/oidc.zig b/server/src/routes/oidc.zig index 776dc0f..a6749a2 100644 --- a/server/src/routes/oidc.zig +++ b/server/src/routes/oidc.zig @@ -133,24 +133,26 @@ pub const Discovery = struct { jwks_uri: []const u8, }; -/// Endpoints must be https, except loopback for the contract test's mock -/// provider when TAWNY_ALLOW_PRIVATE_EGRESS is on. -fn endpointAllowed(url: []const u8) bool { - const private = std.mem.eql(u8, envSpan("TAWNY_ALLOW_PRIVATE_EGRESS") orelse "", "true") or - std.mem.eql(u8, envSpan("TAWNY_ALLOW_PRIVATE_EGRESS") orelse "", "1"); +/// Endpoints must be https to a public host. TAWNY_OIDC_ALLOW_LOOPBACK=1 +/// also allows http://127.0.0.1, for the contract suite's mock provider only. +pub fn endpointAllowed(url: []const u8, loopback_ok: bool) bool { if (std.mem.startsWith(u8, url, "https://")) { const rest = url["https://".len..]; - const end = std.mem.indexOfAny(u8, rest, ":/") orelse rest.len; - return egress.allowed(rest[0..end], private); + const end = std.mem.indexOfAny(u8, rest, ":/?#") orelse rest.len; + return egress.allowed(rest[0..end], false); } - if (private and std.mem.startsWith(u8, url, "http://127.0.0.1:")) return true; - return false; + return loopback_ok and std.mem.startsWith(u8, url, "http://127.0.0.1:"); +} + +fn loopbackOk() bool { + const v = envSpan("TAWNY_OIDC_ALLOW_LOOPBACK") orelse return false; + return std.mem.eql(u8, v, "1") or std.ascii.eqlIgnoreCase(v, "true"); } fn discovery(arena: std.mem.Allocator, io: std.Io, conn: *pg.Conn, cfg: Config) !Discovery { const text = cfg.discovery orelse blk: { const url = try std.fmt.allocPrint(arena, "{s}/.well-known/openid-configuration", .{cfg.authority}); - if (!endpointAllowed(url)) return error.EgressRefused; + if (!endpointAllowed(url, loopbackOk())) return error.EgressRefused; const body = try fetch(arena, io, .GET, url, null, null); _ = try std.json.parseFromSliceLeaky(Discovery, arena, body, .{ .ignore_unknown_fields = true }); try conn.execNoRows("UPDATE tenant_oidc SET discovery_json = $2::jsonb WHERE tenant_id = $1::uuid", &.{ @@ -159,7 +161,8 @@ fn discovery(arena: std.mem.Allocator, io: std.Io, conn: *pg.Conn, cfg: Config) break :blk body; }; const d = try std.json.parseFromSliceLeaky(Discovery, arena, text, .{ .ignore_unknown_fields = true }); - if (!endpointAllowed(d.authorization_endpoint) or !endpointAllowed(d.token_endpoint) or !endpointAllowed(d.jwks_uri)) return error.EgressRefused; + const lo = loopbackOk(); + if (!endpointAllowed(d.authorization_endpoint, lo) or !endpointAllowed(d.token_endpoint, lo) or !endpointAllowed(d.jwks_uri, lo)) return error.EgressRefused; return d; } @@ -627,3 +630,13 @@ test "id token: iss, aud, exp, nbf, nonce and tid are each enforced" { forged[dot + 5] = if (forged[dot + 5] == 'A') 'B' else 'A'; try std.testing.expectError(error.InvalidSignature, verifyIdToken(arena, forged, jwks, want)); } + +test "provider endpoints must be https to a public host" { + try std.testing.expect(endpointAllowed("https://login.microsoftonline.com/x/v2.0", false)); + try std.testing.expect(!endpointAllowed("http://login.microsoftonline.com/x", false)); + try std.testing.expect(!endpointAllowed("https://169.254.169.254/latest", false)); + try std.testing.expect(!endpointAllowed("https://localhost/x", false)); + try std.testing.expect(!endpointAllowed("http://127.0.0.1:9999/x", false)); + try std.testing.expect(endpointAllowed("http://127.0.0.1:9999/x", true)); + try std.testing.expect(!endpointAllowed("http://127.0.0.1.evil.example/x", true)); +} diff --git a/server/src/routes/settings.zig b/server/src/routes/settings.zig index 1d93d87..9bcce6e 100644 --- a/server/src/routes/settings.zig +++ b/server/src/routes/settings.zig @@ -178,7 +178,7 @@ pub fn putOidc( return util.problem(request, allocator, .bad_request, "entra_tenant_id and client_id are required."); } if (v.authority) |a| { - if (!std.mem.startsWith(u8, a, "https://") and !std.mem.startsWith(u8, a, "http://127.0.0.1")) { + if (!std.mem.startsWith(u8, a, "https://") and !std.mem.startsWith(u8, a, "http://127.0.0.1:")) { return util.problem(request, allocator, .bad_request, "authority must be an https URL."); } } diff --git a/server/src/routes/users.zig b/server/src/routes/users.zig index ce29f18..7c23dda 100644 --- a/server/src/routes/users.zig +++ b/server/src/routes/users.zig @@ -202,6 +202,7 @@ pub fn update( role: ?[]const u8 = null, password: ?[]const u8 = null, disabled: ?bool = null, + break_glass: ?bool = null, }; var parsed = std.json.parseFromSlice(Req, allocator, body, .{ .ignore_unknown_fields = true }) catch { return util.problem(request, allocator, .bad_request, "invalid user update."); @@ -258,6 +259,16 @@ pub fn update( try conn.execNoRows("UPDATE users SET disabled_at = NULL WHERE id = $1::uuid", &.{.{ .text = user_id }}); } } + if (parsed.value.break_glass) |glass| { + // Break-glass keeps password sign-in when the tenant limits it. Only + // admins with a password can hold it. + const rows = try conn.exec(allocator, + \\UPDATE users SET break_glass = $2::boolean WHERE id = $1::uuid + \\ AND (NOT $2::boolean OR (role = 'admin' AND password_hash IS NOT NULL)) RETURNING id::text + , &.{ .{ .text = user_id }, .{ .text = if (glass) "true" else "false" } }); + defer freeRows(allocator, rows); + if (rows.len == 0) return util.problem(request, allocator, .bad_request, "break_glass needs an admin with a password."); + } try audit.add(allocator, io, conn, web.tenant_id, web.user_id, "user.update", user_id, null); return getOne(allocator, conn, request, web, user_id); } diff --git a/server/src/sinks/tawny_soc.zig b/server/src/sinks/tawny_soc.zig index d86d5a2..7e484ce 100644 --- a/server/src/sinks/tawny_soc.zig +++ b/server/src/sinks/tawny_soc.zig @@ -154,3 +154,136 @@ test "tawny soc batch keys telemetry by id" { const payload = root.get("telemetry_events").?.object.get("42").?.object.get("payload").?.string; try std.testing.expect(std.mem.indexOf(u8, payload, "suspicious.exe") != null); } + +// ------------------------------------------------------------------ incidents +// +// Tawny-SOC, checked at jusso-dev/Tawny-SOC fea2da8 on 10-11-2026: +// - POST /api/ingest/tawny takes {source, kind: alert_batch | telemetry_batch, +// sent_at, tenant_id, agent, alerts[], events[], telemetry_events{}} and +// stores each alert under id "alert-". +// - app/api/v1/cases has GET (list) and GET /{id} only. There is no endpoint +// to create or update a case, so Tawny cannot create one directly. +// An incident is sent as one alert in an alert_batch, with a stable alert_id +// taken from the incident id, plus an `incident` object with the risk +// breakdown. Tawny-SOC analysts (or its agent mesh) open the case from it. +// Tawny-SOC inserts alerts with onConflictDoNothing, so a later status +// change does not update the stored alert yet: that needs a change in +// Tawny-SOC (listed in the PR). Tawny keeps no case state. + +pub const Incident = struct { + id: []const u8, + tenant_id: []const u8, + title: []const u8, + status: []const u8, + severity: []const u8, + risk: i64, + /// JSON array text, passed through. + risk_items: []const u8, + /// JSON array text of technique ids. + techniques: []const u8, + /// JSON array text of agent ids. + agent_ids: []const u8, + first_seen_at: []const u8, + last_seen_at: []const u8, + alert_count: i64, + url: []const u8, +}; + +/// Stable numeric alert id for the SOC side: the first 13 hex digits of the +/// incident uuid (52 bits, exact in a JavaScript number). +pub fn incidentAlertId(incident_id: []const u8) i64 { + var v: i64 = 0; + var n: usize = 0; + for (incident_id) |c| { + if (c == '-') continue; + const d = std.fmt.charToDigit(c, 16) catch continue; + v = v * 16 + d; + n += 1; + if (n == 13) break; + } + return v; +} + +pub fn formatIncidentBatch(allocator: std.mem.Allocator, agent: Agent, inc: Incident, sent_at: []const u8) ![]u8 { + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(allocator); + const agent_json = try formatAgent(allocator, agent); + defer allocator.free(agent_json); + try out.appendSlice(allocator, "{\"source\":\"tawny\",\"kind\":\"alert_batch\",\"sent_at\":"); + try util.appendEscaped(&out, allocator, sent_at); + try out.appendSlice(allocator, ",\"tenant_id\":"); + try util.appendEscaped(&out, allocator, inc.tenant_id); + try out.appendSlice(allocator, ",\"agent\":"); + try out.appendSlice(allocator, agent_json); + const head = try std.fmt.allocPrint(allocator, ",\"alerts\":[{{\"alert_id\":{d},\"telemetry_event_id\":0,\"kind\":\"incident\",\"severity\":", .{incidentAlertId(inc.id)}); + defer allocator.free(head); + try out.appendSlice(allocator, head); + try util.appendEscaped(&out, allocator, inc.severity); + try out.appendSlice(allocator, ",\"status\":"); + try util.appendEscaped(&out, allocator, inc.status); + try out.appendSlice(allocator, ",\"title\":"); + try util.appendEscaped(&out, allocator, inc.title); + const desc = try std.fmt.allocPrint(allocator, "Tawny incident, risk {d}, {d} alerts. {s}", .{ inc.risk, inc.alert_count, inc.url }); + defer allocator.free(desc); + try out.appendSlice(allocator, ",\"description\":"); + try util.appendEscaped(&out, allocator, desc); + try out.appendSlice(allocator, ",\"created_at\":"); + try util.appendEscaped(&out, allocator, inc.first_seen_at); + try out.appendSlice(allocator, ",\"incident\":{\"id\":"); + try util.appendEscaped(&out, allocator, inc.id); + const nums = try std.fmt.allocPrint(allocator, ",\"risk\":{d},\"alert_count\":{d},\"risk_items\":", .{ inc.risk, inc.alert_count }); + defer allocator.free(nums); + try out.appendSlice(allocator, nums); + try out.appendSlice(allocator, inc.risk_items); + try out.appendSlice(allocator, ",\"mitre_techniques\":"); + try out.appendSlice(allocator, inc.techniques); + try out.appendSlice(allocator, ",\"agent_ids\":"); + try out.appendSlice(allocator, inc.agent_ids); + try out.appendSlice(allocator, ",\"last_seen_at\":"); + try util.appendEscaped(&out, allocator, inc.last_seen_at); + try out.appendSlice(allocator, ",\"url\":"); + try util.appendEscaped(&out, allocator, inc.url); + try out.appendSlice(allocator, "}}],\"telemetry_events\":{}}"); + return out.toOwnedSlice(allocator); +} + +test "incident batch fits the tawny-soc ingest schema" { + const allocator = std.testing.allocator; + const agent = Agent{ + .id = "11111111-1111-4111-8111-111111111111", + .tenant_id = "22222222-2222-4222-8222-222222222222", + .hostname = "win-01", + .os = "windows", + .os_version = "11", + .arch = "x64", + .version = "0.1.0", + }; + const json = try formatIncidentBatch(allocator, agent, .{ + .id = "f294c8f1-a1bb-4738-8efd-79f664066674", + .tenant_id = agent.tenant_id, + .title = "Office spawns \"PowerShell\" on win-01", + .status = "investigating", + .severity = "medium", + .risk = 44, + .risk_items = "[{\"key\":\"rule:1\",\"points\":30}]", + .techniques = "[\"T1059.001\"]", + .agent_ids = "[\"11111111-1111-4111-8111-111111111111\"]", + .first_seen_at = "2026-11-10T00:00:00Z", + .last_seen_at = "2026-11-10T00:01:00Z", + .alert_count = 2, + .url = "https://tawny.example/incidents/f294c8f1-a1bb-4738-8efd-79f664066674", + }, "2026-11-10T00:02:00Z"); + defer allocator.free(json); + var parsed = try std.json.parseFromSlice(std.json.Value, allocator, json, .{}); + defer parsed.deinit(); + const root = parsed.value.object; + // The keys the SOC zod schema reads. + try std.testing.expectEqualStrings("alert_batch", root.get("kind").?.string); + try std.testing.expect(root.get("telemetry_events").? == .object); + const alert = root.get("alerts").?.array.items[0].object; + try std.testing.expectEqual(incidentAlertId("f294c8f1-a1bb-4738-8efd-79f664066674"), alert.get("alert_id").?.integer); + try std.testing.expect(alert.get("alert_id").?.integer < (1 << 53)); + try std.testing.expectEqualStrings("investigating", alert.get("status").?.string); + try std.testing.expectEqual(@as(i64, 44), alert.get("incident").?.object.get("risk").?.integer); + try std.testing.expectEqual(incidentAlertId("f294c8f1-a1bb-4738-8efd-79f664066674"), incidentAlertId("F294C8F1A1BB4738")); +} From c86d4d701460e6f8d41a1d0bae4568145e832967 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 06:07:48 +1100 Subject: [PATCH 3/5] contract-tests: drop committed bytecode, ignore __pycache__ Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + .../__pycache__/mock_oidc.cpython-314.pyc | Bin 12729 -> 0 bytes .../__pycache__/suite.cpython-314.pyc | Bin 161570 -> 0 bytes 3 files changed, 1 insertion(+) delete mode 100644 contract-tests/__pycache__/mock_oidc.cpython-314.pyc delete mode 100644 contract-tests/__pycache__/suite.cpython-314.pyc diff --git a/.gitignore b/.gitignore index 616fe89..aec0016 100644 --- a/.gitignore +++ b/.gitignore @@ -57,3 +57,4 @@ coverage/ # Zig 0.17 unpacks fetched packages into the project zig-pkg/ +__pycache__/ diff --git a/contract-tests/__pycache__/mock_oidc.cpython-314.pyc b/contract-tests/__pycache__/mock_oidc.cpython-314.pyc deleted file mode 100644 index 68a2158aa1d7b44d0037c3f5079ce1726495982c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12729 zcmb_idvH_NnZJ6!{Fbo=h9F+X0!sp89^uu3F@z96TpSaEgCeABOCU?)-YdXLvY|7X zF6nd@leS}%%@(okPRz{C#F=)c?mt_0_m9$j^*VAY?+vrtna<8m_Ah6h4Bh^-`}@xI zm1IXi+U?QkydU5B?svY|Ih*ThogBjT*8jfvzaEbJ4HfiY)-s0q?;~@a<2ji-&+&$% zhUbj3aW&di)_M}rOAu4+_V){xVCWzj_wCI)Nf;XB@$zlX8QZ^wA0jKk{97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Middler Date: Tue, 10 Nov 2026 06:10:08 +1100 Subject: [PATCH 4/5] ui: incidents, incident page, ATT&CK matrix, analyst controls Incidents list with status filter. Incident page: risk breakdown with each item's points, ATT&CK techniques, alert timeline with triage, and the process tree (opened at the lineage root) and response panel per agent. ATT&CK matrix by tactic, filterable by platform, showing telemetry, detection and response as three separate marks. Analysts get triage, response and exception controls; admins approve queued actions. Sign-in page offers Entra ID when configured and says when passwords are break-glass only. Assets renamed to new hashes since they are served as immutable. Co-Authored-By: Claude Opus 5.5 --- ci/ui-fallback.mjs | 2 + ...pp.a1de0f605695.js => app.0094e71d5061.js} | 314 +++++++++++++++++- ....fae4dea01366.css => app.d8d71bb8141b.css} | 33 ++ server/ui/index.html | 4 +- 4 files changed, 336 insertions(+), 17 deletions(-) rename server/ui/assets/{app.a1de0f605695.js => app.0094e71d5061.js} (74%) rename server/ui/assets/{app.fae4dea01366.css => app.d8d71bb8141b.css} (71%) diff --git a/ci/ui-fallback.mjs b/ci/ui-fallback.mjs index df06633..622bd61 100644 --- a/ci/ui-fallback.mjs +++ b/ci/ui-fallback.mjs @@ -39,6 +39,8 @@ const routes = [ "/enrollment", "/users", "/admin/jobs", + "/incidents", + "/attack", ]; for (const route of routes) { if (!source.includes(`"${route}"`) && !source.includes(`'${route}'`)) { diff --git a/server/ui/assets/app.a1de0f605695.js b/server/ui/assets/app.0094e71d5061.js similarity index 74% rename from server/ui/assets/app.a1de0f605695.js rename to server/ui/assets/app.0094e71d5061.js index a77e909..6677ab0 100644 --- a/server/ui/assets/app.a1de0f605695.js +++ b/server/ui/assets/app.0094e71d5061.js @@ -31,8 +31,8 @@ function nav(active) { var groups = [ - ["Operations", [["/", "Dashboard"], ["/agents", "Agents"], ["/alerts", "Alerts"]]], - ["Analysis", [["/hunt", "Hunt"]]], + ["Operations", [["/", "Dashboard"], ["/incidents", "Incidents"], ["/agents", "Agents"], ["/alerts", "Alerts"]]], + ["Analysis", [["/hunt", "Hunt"], ["/attack", "ATT&CK coverage"]]], ["Detection", [["/detections", "Detections"], ["/threat-intel", "Threat intel"], ["/suppressions", "Suppressions"]]], ["System", [["/audit", "Audit"], ["/api-tokens", "Tokens"], ["/enrollment", "Enrollment"], ["/users", "Users"], ["/admin/jobs", "Jobs"]]], ]; @@ -124,6 +124,24 @@ var github = el("a", "Continue with GitHub"); github.href = "/api/auth/github/start"; form.appendChild(github); + var entra = el("a", "Sign in with Microsoft Entra ID"); + entra.href = "/api/auth/oidc/start"; + entra.hidden = true; + form.appendChild(entra); + var note = el("p", "", "muted"); + note.hidden = true; + form.appendChild(note); + fetch("/api/auth/methods", { credentials: "same-origin", headers: { accept: "application/json" } }) + .then(function (res) { return res.ok ? res.json() : null; }) + .then(function (m) { + if (!m) return; + if (m.entra) entra.hidden = false; + if (m.password === "break_glass") { + note.hidden = false; + note.textContent = "Password sign-in is for break-glass admins only."; + } + }) + .catch(function () {}); form.addEventListener("submit", function (event) { event.preventDefault(); submit.disabled = true; @@ -220,13 +238,25 @@ listing.appendChild(table( ["Type", "Status", "Requested"], rows.map(function (a) { - return [a.action_type || "", a.status || "", a.requested_at || ""]; + var status = a.status || ""; + if (status === "awaiting_approval" && isAdmin()) { + var approve = el("button", "Approve", "linkish"); + approve.type = "button"; + approve.addEventListener("click", function () { + api("POST", "/api/agents/" + id + "/actions/" + a.id + "/approve", {}).then(function (res) { + if (res.status !== 200) return alert((res.body && res.body.title) || ("HTTP " + res.status)); + reload(); + }); + }); + status = approve; + } + return [a.action_type || "", status, a.requested_at || ""]; }) )); }); } - if (isAdmin()) { + if (canTriage()) { var form = el("div"); var select = document.createElement("select"); ACTION_TYPES.forEach(function (t) { @@ -252,6 +282,7 @@ payload: body, }).then(function (res) { if (res.status !== 201) return alert("Action failed: HTTP " + res.status); + if (res.body && res.body.status === "awaiting_approval") alert("Queued. An admin must approve this action before the agent receives it."); payload.value = ""; reload(); }); @@ -278,7 +309,7 @@ return text; } - function renderProcessTree(view, id) { + function renderProcessTree(view, id, initialEntity) { var card = el("div", null, "card"); card.appendChild(el("p", "Process tree", "muted")); var picker = document.createElement("select"); @@ -335,22 +366,251 @@ picker.appendChild(opt); }); picker.addEventListener("change", function () { show(picker.value); }); - show(list[0].entity_id); + if (initialEntity) { + if (!list.some(function (p) { return p.entity_id === initialEntity; })) { + var opt = document.createElement("option"); + opt.value = initialEntity; + opt.textContent = "Incident root " + initialEntity; + picker.insertBefore(opt, picker.firstChild); + } + picker.value = initialEntity; + show(initialEntity); + } else show(list[0].entity_id); }); } + function triageButtons(alertRow, done) { + var box = el("span", null, "row"); + if (!canTriage() || alertRow.status === "resolved") return box; + [["acknowledge", "Acknowledge"], ["resolve", "Resolve"]].forEach(function (pair) { + if (pair[0] === "acknowledge" && alertRow.status === "acknowledged") return; + var b = el("button", pair[1], "linkish"); + b.type = "button"; + b.addEventListener("click", function () { + api("POST", "/api/alerts/" + alertRow.id + "/" + pair[0], {}).then(function (res) { + if (res.status !== 200) return alert((res.body && res.body.title) || ("HTTP " + res.status)); + done(); + }); + }); + box.appendChild(b); + }); + return box; + } + function renderAlerts(view) { - api("GET", "/api/alerts?limit=100").then(function (res) { - if (res.status !== 200 || !Array.isArray(res.body)) return showError(view.main, res); + var slot = el("div"); + view.main.appendChild(slot); + function load() { + api("GET", "/api/alerts?limit=100").then(function (res) { + slot.textContent = ""; + if (res.status !== 200 || !Array.isArray(res.body)) return showError(slot, res); + slot.appendChild(table( + ["Id", "Severity", "Status", "Title", "Host", "Created", ""], + res.body.map(function (row) { + return [row.id, row.severity, row.status, row.title, row.hostname, row.created_at, triageButtons(row, load)]; + }) + )); + }); + } + load(); + } + + // Incidents (target-edr sections 7, 8 and 12). + var INCIDENT_STATUSES = ["new", "investigating", "resolved", "false_positive"]; + + function renderIncidents(view) { + var filter = document.createElement("select"); + filter.setAttribute("aria-label", "Status"); + [["open", "Open"], ["", "All"]].concat(INCIDENT_STATUSES.map(function (s) { return [s, s.replace("_", " ")]; })).forEach(function (pair) { + var opt = document.createElement("option"); + opt.value = pair[0]; + opt.textContent = pair[1]; + filter.appendChild(opt); + }); + var bar = el("div", null, "row"); + bar.appendChild(filter); + view.main.appendChild(bar); + var slot = el("div"); + view.main.appendChild(slot); + function load() { + var q = filter.value ? "?status=" + encodeURIComponent(filter.value) : ""; + api("GET", "/api/incidents" + q).then(function (res) { + slot.textContent = ""; + if (res.status !== 200 || !Array.isArray(res.body)) return showError(slot, res); + if (!res.body.length) { + slot.appendChild(el("p", "No incidents.", "card muted")); + return; + } + slot.appendChild(table( + ["Risk", "Severity", "Status", "Title", "Alerts", "Owner", "Techniques", "Last seen"], + res.body.map(function (inc) { + var link = el("a", inc.title); + link.href = "/incidents/" + inc.id; + return [String(inc.risk), inc.severity, inc.status.replace("_", " "), link, String(inc.alert_count), + inc.owner_email || "", (inc.techniques || []).join(", "), inc.last_seen_at]; + }) + )); + }); + } + filter.addEventListener("change", load); + load(); + } + + function renderIncident(view, id) { + api("GET", "/api/incidents/" + id).then(function (res) { + if (res.status !== 200 || !res.body) return showError(view.main, res); + var inc = res.body; + var head = el("div", null, "card"); + head.appendChild(el("h2", inc.title)); + head.appendChild(el("p", "Risk " + inc.risk + " (" + inc.severity + ") · " + inc.status.replace("_", " ") + + " · grouped by " + inc.grouping + " · " + inc.alert_count + " alerts", "muted")); + head.appendChild(el("p", "First seen " + inc.first_seen_at + " · last seen " + inc.last_seen_at, "muted")); + if (inc.users && inc.users.length) head.appendChild(el("p", "Users: " + inc.users.join(", "), "muted")); + view.main.appendChild(head); + + if (canTriage()) { + var controls = el("div", null, "card row"); + var status = document.createElement("select"); + status.setAttribute("aria-label", "Incident status"); + INCIDENT_STATUSES.forEach(function (s) { + var opt = document.createElement("option"); + opt.value = s; + opt.textContent = s.replace("_", " "); + if (s === inc.status) opt.selected = true; + status.appendChild(opt); + }); + var setStatus = el("button", "Set status", "linkish"); + setStatus.type = "button"; + setStatus.addEventListener("click", function () { + api("POST", "/api/incidents/" + id + "/status", { status: status.value }).then(function (r) { + if (r.status !== 200) return alert((r.body && r.body.title) || ("HTTP " + r.status)); + location.reload(); + }); + }); + var mine = el("button", inc.owner_user_id === me.id ? "Unassign" : "Assign to me", "linkish"); + mine.type = "button"; + mine.addEventListener("click", function () { + var owner = inc.owner_user_id === me.id ? null : me.id; + api("POST", "/api/incidents/" + id + "/assign", { owner_user_id: owner }).then(function (r) { + if (r.status !== 200) return alert((r.body && r.body.title) || ("HTTP " + r.status)); + location.reload(); + }); + }); + controls.appendChild(status); + controls.appendChild(setStatus); + controls.appendChild(mine); + controls.appendChild(el("span", "Owner: " + (inc.owner_email || "none"), "muted")); + view.main.appendChild(controls); + } + + // Why: every evidence item and its points (target-edr section 7). + view.main.appendChild(el("h2", "Risk breakdown")); + view.main.appendChild(table( + ["Evidence", "Kind", "Weight", "Confidence", "Context", "Points"], + (inc.risk_items || []).map(function (i) { + return [i.label, i.kind, String(i.weight), String(i.confidence), String(i.context), String(i.points)]; + }) + )); + view.main.appendChild(el("p", "Risk = 100 × (1 − Π(1 − points/100)), each item counted once.", "muted")); + + view.main.appendChild(el("h2", "ATT&CK techniques")); + var techs = el("div", null, "row"); + (inc.techniques || []).forEach(function (t) { + var a = el("a", t, "chip"); + a.href = "https://attack.mitre.org/techniques/" + t.replace(".", "/") + "/"; + a.rel = "noopener noreferrer"; + a.target = "_blank"; + techs.appendChild(a); + }); + if (!(inc.techniques || []).length) techs.appendChild(el("span", "None mapped.", "muted")); + view.main.appendChild(techs); + + view.main.appendChild(el("h2", "Timeline")); + var alerts = inc.alerts || []; view.main.appendChild(table( - ["Id", "Severity", "Status", "Title", "Host", "Created"], - res.body.map(function (alert) { - return [alert.id, alert.severity, alert.status, alert.title, alert.hostname, alert.created_at]; + ["When", "Host", "Rule", "Severity", "Status", "Event", "Grouped by", ""], + alerts.map(function (a) { + var proc = (a.payload && a.payload.process) || {}; + var what = a.event_type || ""; + if (proc.image || proc.command_line) what += ": " + (proc.command_line || proc.image); + return [a.occurred_at, a.hostname, a.rule_name, a.severity, a.status, what, a.reason, + triageButtons(a, function () { location.reload(); })]; }) )); + + // Process tree and response panel for each agent in the incident. + var agentIds = inc.agent_ids || []; + agentIds.forEach(function (agentId) { + var host = (alerts.find(function (a) { return a.agent_id === agentId; }) || {}).hostname || agentId; + view.main.appendChild(el("h2", host)); + var link = el("a", "Open agent"); + link.href = "/agents/" + agentId; + view.main.appendChild(link); + renderProcessTree(view, agentId, inc.root_entity_id); + renderActions(view, agentId); + }); }); } + // ATT&CK coverage matrix: three separate states per technique (section 6). + function renderAttack(view) { + var platform = document.createElement("select"); + platform.setAttribute("aria-label", "Platform"); + [["", "All platforms"], ["windows", "Windows"], ["linux", "Linux"], ["macos", "macOS"]].forEach(function (pair) { + var opt = document.createElement("option"); + opt.value = pair[0]; + opt.textContent = pair[1]; + platform.appendChild(opt); + }); + var only = document.createElement("input"); + only.type = "checkbox"; + var onlyLabel = el("label", "Mapped techniques only", "row"); + onlyLabel.appendChild(only); + var bar = el("div", null, "row"); + bar.appendChild(platform); + bar.appendChild(onlyLabel); + view.main.appendChild(bar); + view.main.appendChild(el("p", "T telemetry from a healthy agent · D an enabled rule · R a response action applies. Each is checked on its own.", "muted")); + var slot = el("div", null, "attack-matrix"); + view.main.appendChild(slot); + function load() { + var q = platform.value ? "?platform=" + platform.value : ""; + api("GET", "/api/attack/coverage" + q).then(function (res) { + slot.textContent = ""; + if (res.status !== 200 || !res.body) return showError(slot, res); + var data = res.body; + slot.appendChild(el("p", "ATT&CK Enterprise " + data.attack_version, "muted")); + var grid = el("div", null, "attack-grid"); + (data.tactics || []).forEach(function (tactic) { + var col = el("div", null, "attack-col"); + col.appendChild(el("h3", tactic.name)); + (data.techniques || []).filter(function (t) { + return t.tactics.indexOf(tactic.shortname) >= 0 && (!only.checked || t.mapped || t.detection.available); + }).forEach(function (t) { + var cell = el("div", null, "attack-cell"); + cell.title = t.id + " " + t.name + + "\nTelemetry: " + (t.telemetry.available ? t.telemetry.sources.join(", ") : "none (expects " + (t.telemetry.expected.join(", ") || "unmapped") + ")") + + "\nDetection: " + (t.detection.available ? t.detection.rules.join(", ") : "no enabled rule") + + "\nResponse: " + (t.response.available ? t.response.actions.join(", ") : "none"); + cell.appendChild(el("span", t.id, "attack-id")); + cell.appendChild(el("span", t.name, "attack-name")); + var states = el("span", null, "attack-states"); + [["T", t.telemetry.available], ["D", t.detection.available], ["R", t.response.available]].forEach(function (st) { + states.appendChild(el("span", st[0], st[1] ? "state on" : "state off")); + }); + cell.appendChild(states); + col.appendChild(cell); + }); + grid.appendChild(col); + }); + slot.appendChild(grid); + }); + } + platform.addEventListener("change", load); + only.addEventListener("change", load); + load(); + } + function renderAudit(view) { api("GET", "/api/audit-logs?limit=100").then(function (res) { if (res.status !== 200 || !Array.isArray(res.body)) return showError(view.main, res); @@ -431,10 +691,19 @@ password.type = "password"; password.required = true; password.placeholder = "password"; - var button = el("button", "Add viewer", "primary"); + var role = document.createElement("select"); + role.setAttribute("aria-label", "Role"); + ["viewer", "analyst", "admin"].forEach(function (r) { + var opt = document.createElement("option"); + opt.value = r; + opt.textContent = r; + role.appendChild(opt); + }); + var button = el("button", "Add user", "primary"); button.type = "submit"; form.appendChild(email); form.appendChild(password); + form.appendChild(role); form.appendChild(button); view.main.appendChild(form); var slot = el("div"); @@ -451,7 +720,7 @@ } form.addEventListener("submit", function (event) { event.preventDefault(); - api("POST", "/api/users", { email: email.value, password: password.value, role: "viewer" }).then(function (res) { + api("POST", "/api/users", { email: email.value, password: password.value, role: role.value }).then(function (res) { if (res.status !== 200 && res.status !== 201) return showError(slot, res); email.value = ""; password.value = ""; @@ -479,6 +748,11 @@ return me && me.role === "admin"; } + // Analysts and admins triage, hunt, respond and add exceptions (docs/api.md). + function canTriage() { + return me && (me.role === "admin" || me.role === "analyst"); + } + function textInput(value) { var node = document.createElement("input"); node.type = "text"; @@ -943,7 +1217,7 @@ )); }); } - if (isAdmin()) { + if (canTriage()) { var form = el("form", null, "card"); form.appendChild(el("h2", "Add suppression")); var name = textInput(""); @@ -1008,6 +1282,7 @@ csrf = res.body.csrf_token || null; var view; var agent = path.match(/^\/agents\/([0-9a-f-]{36})$/i); + var incident = path.match(/^\/incidents\/([0-9a-f-]{36})$/i); if (path === "/" || path === "") { view = shell("/", "Dashboard", "Agents and open alerts."); renderAgents(view); @@ -1021,6 +1296,15 @@ } else if (path === "/alerts") { view = shell("/alerts", "Alerts", null); renderAlerts(view); + } else if (path === "/incidents") { + view = shell("/incidents", "Incidents", "Related alerts grouped by host, lineage and shared artefacts."); + renderIncidents(view); + } else if (incident) { + view = shell("/incidents", "Incident", null); + renderIncident(view, incident[1]); + } else if (path === "/attack") { + view = shell("/attack", "ATT&CK coverage", "Telemetry, detection and response for each technique."); + renderAttack(view); } else if (path === "/hunt") { view = shell("/hunt", "Hunt across telemetry", "Write a query, run it, then save or schedule it."); renderHunt(view); @@ -1043,7 +1327,7 @@ view = shell("/enrollment", "Enrollment", "Single-use wte_ tokens."); renderEnrollment(view); } else if (path === "/users") { - view = shell("/users", "Users", "Default role is viewer. No self-service signup."); + view = shell("/users", "Users", "Roles: admin, analyst, viewer. Default is viewer. No self-service signup."); renderUsers(view); } else if (path === "/admin/jobs") { view = shell("/admin/jobs", "Jobs", "In-process scheduler. Hangfire is gone."); diff --git a/server/ui/assets/app.fae4dea01366.css b/server/ui/assets/app.d8d71bb8141b.css similarity index 71% rename from server/ui/assets/app.fae4dea01366.css rename to server/ui/assets/app.d8d71bb8141b.css index 9ef117a..76702f9 100644 --- a/server/ui/assets/app.fae4dea01366.css +++ b/server/ui/assets/app.d8d71bb8141b.css @@ -89,6 +89,39 @@ button.linkish { } .row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } .top { display: flex; justify-content: space-between; gap: 12px; align-items: flex-end; margin-bottom: 18px; } +h2 { font-size: 18px; font-weight: 600; margin: 22px 0 10px; } +.card + .card, .card + h2, .row + .card { margin-top: 12px; } +.chip { + display: inline-block; + border: 1px solid var(--color-border); + border-radius: 999px; + padding: 2px 10px; + font-size: 13px; + text-decoration: none; +} +.attack-grid { display: grid; grid-auto-flow: column; grid-auto-columns: minmax(150px, 1fr); gap: 8px; overflow-x: auto; } +.attack-col h3 { font-size: 13px; font-weight: 600; margin: 0 0 6px; color: var(--color-muted-foreground); } +.attack-cell { + display: grid; + gap: 2px; + border: 1px solid var(--color-border); + border-radius: 6px; + padding: 6px 8px; + margin-bottom: 6px; + background: var(--color-card); + font-size: 12px; +} +.attack-id { color: var(--color-muted-foreground); } +.attack-states { display: flex; gap: 4px; } +.attack-states .state { + min-width: 18px; + text-align: center; + border-radius: 4px; + font-weight: 600; + border: 1px solid var(--color-border); +} +.attack-states .state.on { background: var(--color-accent); color: white; border-color: var(--color-accent); } +.attack-states .state.off { color: var(--color-muted-foreground); text-decoration: line-through; } @media (max-width: 800px) { .shell { grid-template-columns: 1fr; } nav { border-right: 0; border-bottom: 1px solid var(--color-border); } diff --git a/server/ui/index.html b/server/ui/index.html index 4bcb3fc..2ebfdb9 100644 --- a/server/ui/index.html +++ b/server/ui/index.html @@ -4,7 +4,7 @@ Tawny - +
@@ -13,6 +13,6 @@ - + From 3c7d4bc07359f41fb458d70144cd8a22e7bd1002 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 06:19:47 +1100 Subject: [PATCH 5/5] docs: Entra ID setup, roles, incidents, Essential Eight and ISM mapping docs/entra-sso.md: app registration, groups claim, Tawny settings, break-glass admins, secret rotation and the mock provider used in tests. docs/api.md: the role and permission matrix per route, tenant settings, incidents, alert triage and the ATT&CK coverage endpoint. docs/compliance/essential-eight.md: per strategy, what Tawny shows and what it does not. Tawny is not application control, a patch scanner or an MFA product. docs/compliance/ism.md: Tawny features against September 2026 ISM controls. Every ID was checked on the cyber.gov.au 2026-09 pages and in ASD OSCAL v2026.09.4; none is left unchecked. Log retention (ISM-1988) is only partly met: raw telemetry is kept 30 days in the database. target-edr: status for sections 6, 7, 8, 11 and 12, and new 12.1 to 12.3 for the analyst role, Entra ID and compliance. Contract suite: admin writes retry past a full rate-limit window. Closes #60 Co-Authored-By: Claude Opus 5.5 --- contract-tests/suite.py | 10 +-- docs/api.md | 84 +++++++++++++++++- docs/architecture/target-edr.md | 81 +++++++++++++++++- docs/compliance/essential-eight.md | 133 +++++++++++++++++++++++++++++ docs/compliance/ism.md | 64 ++++++++++++++ docs/entra-sso.md | 104 ++++++++++++++++++++++ 6 files changed, 469 insertions(+), 7 deletions(-) create mode 100644 docs/compliance/essential-eight.md create mode 100644 docs/compliance/ism.md create mode 100644 docs/entra-sso.md diff --git a/contract-tests/suite.py b/contract-tests/suite.py index 0ef8d45..32c97c2 100644 --- a/contract-tests/suite.py +++ b/contract-tests/suite.py @@ -1976,11 +1976,12 @@ def make_user(role: str, prefix: str) -> tuple[str, str, str]: def admin_call(method: str, path: str, body: dict) -> tuple[int, object | None, str]: """Admin write that waits out the 30 per minute web-admin-mutate limit the rest of the suite may have used up.""" - for _ in range(3): + for _ in range(4): code, parsed, raw = call(method, path, body) if code != 429: return code, parsed, raw - time.sleep(21) + # The limiter uses fixed one-minute windows: 3 waits cover a full one. + time.sleep(22) return code, parsed, raw @@ -2057,11 +2058,11 @@ def test_analyst_destructive_action_waits_for_admin(self) -> None: # The analyst cannot approve; an admin can. code, _b, raw = self.as_role("POST", f"/api/agents/{agent['agent_id']}/actions/{action['id']}/approve", a_cookie, a_csrf) self.assertEqual(code, 403, raw[:300]) - code, ok, raw = call("POST", f"/api/agents/{agent['agent_id']}/actions/{action['id']}/approve", {}) + code, ok, raw = admin_call("POST", f"/api/agents/{agent['agent_id']}/actions/{action['id']}/approve", {}) self.assertEqual(code, 200, raw[:300]) assert isinstance(ok, dict) self.assertEqual(ok.get("status"), "pending") - code, _b, raw = call("POST", f"/api/agents/{agent['agent_id']}/actions/{action['id']}/approve", {}) + code, _b, raw = admin_call("POST", f"/api/agents/{agent['agent_id']}/actions/{action['id']}/approve", {}) self.assertEqual(code, 409, raw[:300]) finally: admin_call("PUT", "/api/settings/tenant", {"analyst_destructive_needs_approval": False}) @@ -2253,7 +2254,6 @@ def sign_in(oid: str, groups: list[str], email: str = "", overrides: dict | None self.assertEqual(st, 400, body[:300]) # Password sign-in limited to break-glass admins. - _vid, _vc, _vx = make_user("viewer", "glass") email = f"{uniq('glassuser')}@tawny.local" code, _u, raw = admin_call("POST", "/api/users", {"email": email, "password": "glass-password1", "role": "analyst"}) self.assertEqual(code, 201, raw[:300]) diff --git a/docs/api.md b/docs/api.md index 516daa6..91c7632 100644 --- a/docs/api.md +++ b/docs/api.md @@ -10,7 +10,54 @@ Three schemes: - **Agent JWT.** `Authorization: Bearer ` on agent endpoints. New tokens are Ed25519 (EdDSA). Tokens signed with the previous RSA key still verify until the next heartbeat rotates them. Lifetime is 60 minutes. Claims include `agent_id`, `tenant_id`, `cv`, `jti`, `iss`, `aud`, `exp`, and `iat`. Revoked agents and a stale `cv` are rejected. Telemetry batches may include an Ed25519 `signature` when a device public key was registered at enroll. - **Session.** HttpOnly, Secure, SameSite=Lax cookie `tawny_session`. Idle 8 hours, absolute 7 days. `GET /api/auth/session` returns the CSRF secret. State-changing session requests send `X-CSRF-Token`. There is no HMAC hop and no separate web process. -- **API token.** `Authorization: Bearer twny_...` on automation endpoints. Tokens inherit one tenant and an Admin or Viewer role. They do not send the session cookie or the CSRF header. +- **API token.** `Authorization: Bearer twny_...` on automation endpoints. Tokens inherit one tenant and an admin, analyst or viewer role. They do not send the session cookie or the CSRF header. +- **Microsoft Entra ID.** `GET /api/auth/oidc/start?tenant=` and `/api/auth/oidc/callback` sign a user in and set the same session cookie. Setup is in [entra-sso.md](entra-sso.md). `GET /api/auth/methods?tenant=` (public) says whether Entra ID is on and whether passwords are limited to break-glass admins. + +## Roles and permissions + +Three roles. Each route file in `server/src/routes/` declares its routes and the permission each needs (`pub const routes`). `server/src/http/permissions.zig` checks the permission before any handler runs, and its test checks every route below against each role. A route that is not declared answers 404. A signed-in user without the permission gets 403; no session gets 401. + +| Permission | admin | analyst | viewer | +|---|---|---|---| +| `read`: agents, events, process trees, alerts, incidents, rules, hunts, feeds, exceptions, audit log, ATT&CK coverage, AI findings | yes | yes | yes | +| `triage`: acknowledge and resolve alerts, assign incidents, set incident status | yes | yes | no | +| `hunt_run`: run ad hoc and saved hunts | yes | yes | no | +| `respond`: request response actions | yes | yes, destructive ones may wait for approval | no | +| `exception_create`: add a suppression rule, with a reason | yes | yes, reason required | no | +| `admin`: users, API tokens, enrolment tokens, agent revoke, rules and rule imports, saved hunt changes, feeds, exception edit and delete, AI config, tenant settings, Entra ID config, jobs, approving actions | yes | no | no | + +Per route: + +| Route | Permission | +|---|---| +| `POST /api/auth/login`, `GET /api/auth/methods`, `GET /api/auth/github/start`, `GET /api/auth/github/callback`, `GET /api/auth/oidc/start`, `GET /api/auth/oidc/callback`, `POST /api/agents/enroll` | public | +| `POST /api/agents/heartbeat`, `POST /api/agents/events`, `POST /api/agents/actions/{id}/result`, `POST /api/agent/yara-rules`, `POST /api/agent/update-check` | agent JWT | +| `POST /api/auth/logout`, `GET /api/auth/session`, `POST /api/auth/password` | read | +| `GET /api/agents`, `GET /api/agents/{id}`, `GET /api/agents/{id}/events`, `GET /api/agents/{id}/events/stream`, `GET /api/agents/{id}/process-tree`, `GET /api/agents/{id}/actions`, `GET /api/agents/{id}/actions/{actionId}` | read | +| `GET /api/alerts`, `GET /api/alerts/{id}`, `GET /api/incidents`, `GET /api/incidents/{id}`, `GET /api/attack/coverage` | read | +| `GET /api/alert-rules`, `GET /api/hunts`, `GET /api/hunts/{id}`, `GET /api/hunts/{id}/runs`, `GET /api/threat-intel-feeds`, `GET /api/suppression-rules`, `POST /api/threat-intel/lookup` | read | +| `GET /api/api-tokens`, `GET /api/audit-logs`, `GET /api/releases/latest`, `GET /api/yara/rule-key`, `GET /api/ai/config`, `GET /api/ai/findings[/{id}]`, `GET /api/ai/investigations[/{id}]`, `GET /api/ai/metrics` | read | +| `POST /api/alerts/{id}/acknowledge`, `POST /api/alerts/{id}/resolve`, `POST /api/incidents/{id}/assign`, `POST /api/incidents/{id}/status` | triage | +| `POST /api/hunts/run`, `POST /api/hunts/{id}/run` | hunt_run | +| `POST /api/agents/{id}/actions` | respond | +| `POST /api/suppression-rules` | exception_create | +| `GET/POST /api/users`, `PUT/DELETE /api/users/{id}`, `POST /api/api-tokens`, `POST /api/enrollment-tokens`, `POST /api/agents/{id}/revoke`, `POST /api/agents/{id}/actions/{actionId}/approve` | admin | +| `POST /api/alert-rules`, `POST /api/alert-rules/{sigma,iocs,yara,exposures}`, `PUT/DELETE /api/alert-rules/{id}`, `POST /api/hunts`, `PUT/DELETE /api/hunts/{id}` | admin | +| `POST /api/threat-intel-feeds`, `PUT/DELETE /api/threat-intel-feeds/{id}`, `POST /api/threat-intel-feeds/{id}/run`, `PUT/DELETE /api/suppression-rules/{id}` | admin | +| `PUT /api/ai/config`, `POST /api/ai/observations`, `GET /api/admin/jobs`, `GET/PUT /api/settings/tenant`, `GET/PUT /api/settings/oidc` | admin | + +### Tenant settings + +`GET` and `PUT /api/settings/tenant`: + +```json +{"password_login": "all", "analyst_destructive_needs_approval": false} +``` + +- `password_login`: `all`, or `break_glass` to allow passwords only for admins marked break-glass (`PUT /api/users/{id}` with `{"break_glass": true}`). Setting `break_glass` is refused while no active admin with a password is marked. The bootstrap admin is marked when it is created. +- `analyst_destructive_needs_approval`: when true, `isolate_host` and `quarantine_file` requested by an analyst are stored as `awaiting_approval`. The agent does not receive them until a different admin calls `POST /api/agents/{id}/actions/{actionId}/approve`, which sets `pending` and restarts the 15 minute deadline. + +`GET` and `PUT /api/settings/oidc` hold the Entra ID configuration; see [entra-sso.md](entra-sso.md). The client secret is write only: `GET` returns `client_secret_set`. ## Agent endpoints @@ -438,6 +485,41 @@ reports `failed` with a clear reason until nftables isolation lands (#59). Web user or any `twny_` API token (Viewer can read action history and status). +### POST `/api/alerts/{id}/acknowledge` and `/api/alerts/{id}/resolve` + +Triage. Return `{"id": 7, "status": "acknowledged"}` or `"resolved"`. Acknowledging a resolved alert leaves it resolved. + +### Incidents + +Detection groups each new alert into an incident (`server/src/detect/incidents.zig`, target-edr section 8). An alert joins an open incident (`new` or `investigating`) last seen within 4 hours when: + +1. `lineage`: same agent and the same lineage root, the oldest ancestor in `process_entities` below a session root such as `explorer.exe` or `services.exe`; +2. `artefact`: same agent and same user, and a shared file sha256, domain or public IP; +3. `indicator`: any agent, the same IOC rule or the same file sha256. + +Otherwise it opens a new incident (`grouping` is `alert` when there was nothing to group on). + +Risk is the section 7 noisy-OR: each distinct rule is one evidence item scored `weight × confidence × context`, and `risk = 100 × (1 − Π(1 − points/100))`. Weights come from rule severity (critical 60, high 30, medium 20, low 10) and IOC rules count 50. Severity is `critical` at 85 or more, `high` at 65, `medium` at 40, else `low`, and never lower than a critical alert in the incident. `risk_items` lists every item and its points. + +- `GET /api/incidents?status=open|new|investigating|resolved|false_positive&limit=100`: newest first. +- `GET /api/incidents/{id}`: the incident plus `alerts`, its timeline, with each alert's event payload. +- `POST /api/incidents/{id}/assign` `{"owner_user_id": "" | null}`: owner must be an active admin or analyst. Assigning a `new` incident moves it to `investigating`. +- `POST /api/incidents/{id}/status` `{"status": "new" | "investigating" | "resolved" | "false_positive"}`: resolving or marking false positive also resolves its open alerts. + +Incident fields: `id`, `title`, `status`, `severity`, `risk`, `risk_items`, `owner_user_id`, `owner_email`, `grouping`, `root_entity_id`, `agent_ids`, `users`, `techniques`, `first_seen_at`, `last_seen_at`, `created_at`, `updated_at`, `alert_count`, `soc_case_status`. + +When the Tawny-SOC sink is on (`TAWNY_SOC_ENABLED`, `TAWNY_SOC_ENDPOINT_URL`, `TAWNY_SOC_API_TOKEN`; `TAWNY_SOC_INCIDENTS_ENABLED=false` turns incidents off), each incident and each later change is posted to Tawny-SOC's `POST /api/ingest/tawny` as one alert with a stable `alert_id` and an `incident` object (risk, items, techniques, agents, link). Tawny-SOC's `/api/v1/cases` is read only, so the case itself is opened in Tawny-SOC. + +### GET `/api/attack/coverage?platform=windows|linux|macos` + +ATT&CK Enterprise 20.1 techniques (from `rules/attack/techniques.json`) by tactic, each with three states worked out separately: + +- `telemetry.available`: an agent on the platform that heartbeated in the last 15 minutes, with no sensor failed, missing or denied, sent one of the technique's event types (from `rules/attack/coverage.yaml`) in the last 24 hours. `sources` names them; `expected` lists what the map wants. +- `detection.available`: an enabled rule lists the exact technique id. `rules` names them. A rule on `T1059` does not count for `T1059.001`. +- `response.available`: an action listed for the technique runs on the platform. `actions` names them. + +None is read from another: a rule with no telemetry shows detection without telemetry. `mapped` is false for techniques with no coverage map entry. + ### GET `/api/alerts/{id}` Single alert, same shape as the list. Web user or `twny_` API token. diff --git a/docs/architecture/target-edr.md b/docs/architecture/target-edr.md index ba4af30..fc0209e 100644 --- a/docs/architecture/target-edr.md +++ b/docs/architecture/target-edr.md @@ -526,6 +526,18 @@ thumbprint. Expired indicators stop matching; aging job. **response available** (a response action is applicable). No state is inferred from another. +**Status (#60, Nov 2026).** `rules/attack/coverage.yaml` maps 50 techniques +to event types and response actions. Names and tactics come from +`rules/attack/techniques.json`, a subset of ATT&CK Enterprise **20.1** +(attack-stix-data, source sha256 recorded in the file, regenerated by +`rules/attack/subset.py`) covering every technique the rules tag. ATT&CK 20 +splits Defense Evasion into Stealth and Defense Impairment; the matrix +follows the release. `GET /api/attack/coverage?platform=` computes the three +states separately (`server/src/routes/attack.zig`, tests for each +combination); "healthy" is a heartbeat in 15 minutes and no failed, missing +or denied sensor. The UI matrix is at `/attack`. Rules still carry +`mitre_techniques` (ids only), not `{tactic, technique, subtechnique}`. + ## 7. Risk engine Per incident, deterministic: @@ -544,6 +556,14 @@ persistence 30). Duplicate evidence contributes once; time decay drops evidence older than the incident window. The response lists every contributing item with its points, so the analyst sees *why*. +**Status (#60, Nov 2026).** Implemented in `server/src/detect/incidents.zig` +with one evidence item per distinct rule. Weights do not come from rule YAML +yet: they come from rule severity (critical 60, high 30, medium 20, low 10) +and IOC rules count 50. Confidence and context are 1; the allowlist and +trusted-signer context values are not wired. The "definitive" floor is +approximated by never going below a critical alert. Time decay is the +4 hour grouping window. + ## 8. Incident correlation Detections are attached to an incident when, within a window (default 4 h): @@ -559,6 +579,19 @@ ATT&CK union, status (new/investigating/resolved/false_positive), owner. Alerts become views of detections inside incidents; sinks receive incidents and updates (debounced). +**Status (#60, Nov 2026).** Migration `0008_server_analyst.sql` adds +`incidents` and `incident_alerts` with row-level security. Every alert from +`jobs/detect.zig` is attached: rule 1 walks `process_entities` from the +alert's `process.entity_id` to the oldest ancestor below a session root; +rule 2 uses user plus sha256, domain or public IP; rule 3 uses the IOC rule +id or sha256 across agents. Only `new` and `investigating` incidents take +new alerts. The endpoints are `GET /api/incidents[/{id}]` and +`POST /api/incidents/{id}/assign|status`. Tawny-SOC gets each incident through +`POST /api/ingest/tawny`, debounced 30 s (`jobs/incident_sink.zig`); its +`/api/v1/cases` is read only, so the case is opened in Tawny-SOC. The +"attack chain" path and the lineage graph are not built; the incident page +shows the process tree at the root. + ## 9. Response engine ### 9.1 Actions @@ -733,6 +766,11 @@ detections are **recorded** with the matching exception id (not discarded) so the UI can show "suppressed by X because Y" and hit counts. Agent groups (tags) added for scoping. +**Status (#60, Nov 2026).** Not built beyond what suppression rules already +do. Analysts can now add a suppression rule, and must give a reason; edit +and delete stay admin only. Suppressed detections are still counted, not +recorded. + ## 12. Investigation UI - **Incident page:** header (what/why/risk breakdown/ATT&CK/TI matches), @@ -746,6 +784,47 @@ the UI can show "suppressed by X because Y" and hit counts. Agent groups - **Exceptions** page with audit trail. - Alerts triage (ack/resolve) — requires new backend endpoints. +**Status (#60, Nov 2026).** Built in `server/ui` (no build step): incidents +list with a status filter; incident page with risk breakdown, ATT&CK +techniques, alert timeline with event detail and triage, and per agent the +process tree (opened at the lineage root) and the response panel; the ATT&CK +matrix with a platform filter; alert acknowledge and resolve. Not built: the +lineage graph, the virtualised endpoint timeline, fleet health and the +exceptions page. + +### 12.1 Analyst role + +**Status (#60, Nov 2026).** Roles are `admin`, `analyst` and `viewer`. +Every route file declares its routes and permission, and +`server/src/http/permissions.zig` enforces it before the handler; the matrix +is in `docs/api.md` and tested per route and role. Analysts triage alerts +and incidents, run hunts, request response actions and add exceptions with a +reason. When the tenant setting `analyst_destructive_needs_approval` is on, +an analyst's `isolate_host` or `quarantine_file` waits as +`awaiting_approval` until a different admin approves it (section 9.2, last +line). + +### 12.2 Single sign-on with Microsoft Entra ID + +**Status (#60, Nov 2026).** OIDC code flow with PKCE in +`server/src/routes/oidc.zig`, with state, nonce and verifier in +`oauth_states`. ID tokens are checked with the RS256 code in +`crypto/jwt.zig`: signature against the cached JWKS, then `iss`, `aud`, +`exp`, `nbf`, `nonce` and `tid`. Users match on `tid` and `oid`; Entra group +object ids map to roles, and no mapped group means no account. The client +secret is encrypted with `TAWNY_INTEGRATION_ENCRYPTION_KEY`. A tenant setting +limits password sign-in to break-glass admins. Setup: `docs/entra-sso.md`. +Tested against a mock provider in the contract suite; no Entra app is +registered. + +### 12.3 Essential Eight and ISM + +**Status (#60, Nov 2026).** `docs/compliance/essential-eight.md` says per +strategy what Tawny shows and what it does not (Tawny is not application +control). `docs/compliance/ism.md` maps features to September 2026 ISM +controls, each ID checked on cyber.gov.au and in OSCAL v2026.09.4. The +optional per-agent compliance report is not built. + ## 13. Hunting Extend the DSL to canonical field names (`process.name`, `parent.name`, @@ -805,7 +884,7 @@ with current packages, agent on Zig 0.17.0, Windows service runs as | 2 | Windows service + ETW sensor (process, image, network, DNS, file, registry, auth, services, tasks, PowerShell, signatures) | Windows CI integration test sees spawned chain with correct entity IDs; budgets measured | | 3 | ProcessEntities/ActivityEdges, investigation APIs, endpoint timeline UI, process graph UI | reconstruct Office→PS→payload test chain from fixtures | | 4 | Detection engine (atomic/sequence/relationship/threshold/rarity), Sigma compiler + compat CI, Indicators table + IOC index, ATT&CK coverage | SigmaHQ windows stats published; detection fixtures pass | -| 5 | Evidence → incidents → risk; incident UI; exceptions v2; alert triage | example chain yields single incident with explained score | +| 5 | Evidence → incidents → risk; incident UI; exceptions v2; alert triage | example chain yields single incident with explained score (#60: done except exceptions v2) | | 6 | Durable response queue, long-poll, signed commands; kill/suspend/quarantine/restore/collect on Windows; WFP isolation with failsafe | fault-injection: restart agent/server mid-action, duplicate delivery, offline isolation expiry | | 7 | Key protection (DPAPI/Keychain), PoP refresh, tamper detection, signed self-update with rings | update/rollback/downgrade-rejection tests | | 8 | Bench harness and budgets in CI; Linux/macOS parity work | budgets enforced | diff --git a/docs/compliance/essential-eight.md b/docs/compliance/essential-eight.md new file mode 100644 index 0000000..d757e74 --- /dev/null +++ b/docs/compliance/essential-eight.md @@ -0,0 +1,133 @@ +# Essential Eight: what Tawny shows and what it does not + +The Essential Eight are eight mitigation strategies from the Australian Signals Directorate. Most of them are controls you configure on endpoints and in your directory: application control, macro settings, patching, admin rights, MFA, backups. Tawny does not configure or enforce any of them. Tawny is an endpoint detection and response tool: it collects telemetry, raises alerts and incidents, and can kill a process, quarantine a file or isolate a Windows host when asked. + +So for each strategy this page says what evidence Tawny can give you that the control is working or being bypassed, and what it cannot. Use it to plan; do not use it as an assessment. A maturity level is reached by implementing the controls in the [Essential Eight Maturity Model](https://www.cyber.gov.au/business-government/asds-cyber-security-frameworks/essential-eight/essential-eight-maturity-model), not by running Tawny. + +Telemetry below means what the agent sends today (`agent/src/collectors/`, `schemas/events/`). Windows detail comes from Sysmon and the Security, System and PowerShell logs; without Sysmon, Windows process telemetry comes from Security 4688 only. + +## 1. Application control + +**Tawny is not an application control product.** It does not stop anything from running. It sees programs after they start. + +What Tawny shows: + +- Every process start with image path, command line, parent, user and hashes (Sysmon 1, Security 4688, the Linux and macOS process collectors). +- Image loads with signature status and signer (Sysmon 7). +- Files written to user profiles and temp folders (Sysmon 11), and new services (System 7045), including the built-in rule for a service in a user-writable folder. +- Hunts and rules for programs running from user profiles or temporary folders, unsigned images, or a hash not seen before in the fleet. +- After the fact, `kill_process` and `quarantine_file`. + +What Tawny does not do: + +- Block execution, enforce an allow list or apply Microsoft's recommended block rules. Use WDAC (App Control for Business) or AppLocker for that. +- Collect AppLocker or WDAC events today. It cannot show which executions your application control allowed or blocked. +- Check application control on servers it has no agent on. + +## 2. Patch applications + +What Tawny shows: + +- `package_inventory`: language and developer packages (npm, pnpm, yarn, bun, Go, RubyGems, Composer, PyPI) found on the host, and OSV exposure for them through the package exposure rules and feeds (`docs/detections.md`). +- Browser and editor extensions, and MCP configuration. + +What Tawny does not show: + +- Installed desktop applications and their versions (Office, browsers, PDF readers) from Windows Installer, the Store or macOS app bundles. +- Missing vendor patches. Tawny is not a vulnerability scanner and does not match installed software to CVEs outside the package ecosystems above. +- Whether an update was installed within the time the maturity level asks for. + +## 3. Configure Microsoft Office macro settings + +What Tawny shows: + +- Office applications starting PowerShell or cmd (built-in rule `office-spawns-shell`), and Office children in general through hunts. +- Files Office writes, and network connections from Office processes (Sysmon 3 and 11). + +What Tawny does not show: + +- The macro settings themselves (Group Policy or Intune), whether macros from the internet are blocked, or Trusted Locations. +- Office's own macro events or macro antivirus scanning results. + +## 4. User application hardening + +What Tawny shows: + +- Browser extensions installed per user. +- PowerShell script block logging events (4104), reassembled, when script block logging is on. +- Children of browsers and PDF readers through process lineage. + +What Tawny does not show: + +- Browser, Office and PDF reader configuration, or whether ASD hardening guidance has been applied. +- Whether PowerShell 2.0 is removed or Constrained Language Mode is set. +- .NET Framework, Java or IE status. + +## 5. Restrict administrative privileges + +What Tawny shows: + +- Security 4672 (special privileges assigned to a new logon), mapped to `special_privileges` events, and 4624 and 4625 logons with logon type. +- Processes running elevated (`integrity_level`, `elevated` on process events where the sensor reports them). +- Inside Tawny itself: the admin, analyst and viewer roles, an audit log of admin actions, and Entra ID sign-in with group-based roles. + +What Tawny does not show: + +- Changes to admin group membership. The agent does not subscribe to Security 4728, 4732 or 4756 yet. Add them before relying on Tawny for this. +- Who should have admin rights, privileged access reviews, or just-in-time access. +- Whether privileged accounts are kept off email and the web. + +## 6. Patch operating systems + +What Tawny shows: + +- OS name, version and architecture for every agent (`GET /api/agents`). +- Agent version and update ring state for Tawny's own agent. + +What Tawny does not show: + +- Missing OS patches or build revisions mapped to vulnerabilities. +- End-of-support status for an OS version. +- Firmware and driver patch levels. + +## 7. Multi-factor authentication + +What Tawny shows: + +- Windows logon events (4624, 4625) and failed-logon rules (`failed-logons-then-success`, `failed-logons-from-one-ip`), which show password guessing against hosts. +- Inside Tawny itself: Entra ID sign-in, so the MFA policy in your directory applies to Tawny users. Tawny's own password sign-in has no second factor; limit it to break-glass admins (see [entra-sso.md](../entra-sso.md)). + +What Tawny does not show: + +- Whether MFA is enforced for your users, online services or remote access. That lives in Entra ID Conditional Access and your identity provider logs, which Tawny does not collect. +- MFA success and failure events. + +## 8. Regular backups + +What Tawny shows: + +- Commands that delete shadow copies or disable recovery (ATT&CK T1490, Inhibit System Recovery) through Sigma rules and hunts, when they are imported and enabled. +- Tawny backs up its own telemetry daily to a local path or S3 (`TAWNY_BACKUP_*`). + +What Tawny does not show: + +- Whether your backups ran, are complete, are immutable or can be restored. +- Access to backup systems. + +## Summary + +| Strategy | Tawny gives evidence of | Tawny cannot show | +|---|---|---| +| Application control | Unsigned or new executables running, programs in user-writable paths | Enforcement, AppLocker or WDAC events | +| Patch applications | Language package inventory and OSV exposure | Desktop application patch levels, CVE scanning | +| Office macro settings | Office starting shells or writing files | The macro settings | +| User application hardening | Browser extensions, PowerShell script blocks | Application configuration | +| Restrict admin privileges | 4672 special logons, elevated processes | Admin group changes (4728, 4732, 4756 not collected yet) | +| Patch operating systems | OS versions per agent | Missing OS patches | +| Multi-factor authentication | Password guessing against hosts | MFA enforcement and events | +| Regular backups | Recovery-inhibiting commands | Backup health | + +## Planned + +- Security 4728, 4732 and 4756 (group membership) and AppLocker or WDAC event subscriptions on Windows. +- A per-agent report of the checks above as pass, fail or no data (issue #60, optional item, not built). diff --git a/docs/compliance/ism.md b/docs/compliance/ism.md new file mode 100644 index 0000000..440eb64 --- /dev/null +++ b/docs/compliance/ism.md @@ -0,0 +1,64 @@ +# ISM mapping + +This maps Tawny features to controls in the Australian Government Information Security Manual (ISM), **September 2026 release**. Each control ID and its wording was checked on 10-11-2026 against two sources: the September 2026 guideline pages on cyber.gov.au (`https://www.cyber.gov.au/ism/2026-09/…`) and ASD's OSCAL catalogue release `v2026.09.4` (`AustralianCyberSecurityCentre/ism-oscal`, "based on the September 2026 Information security manual"). No row below uses an ID that was not found in both. + +"Supports" means Tawny gives you a way to meet part of the control. It does not mean Tawny meets the control for you: most of these also need process, configuration or coverage that Tawny does not provide. "Gap" says what is left. + +## Event logging and centralised logging + +| Control | Wording (short) | How Tawny supports it | Gap | +|---|---|---|---| +| ISM-0582 | Security-relevant events for Microsoft Windows are centrally logged. | The Windows agent forwards Sysmon (process, network, image load, file, registry, DNS), Security 4624, 4625, 4672, 4688, System 7045 and PowerShell 4104 to the server. | Only these event IDs. No AppLocker or WDAC, no group membership (4728, 4732, 4756), no Defender events. Hosts without an agent are not covered. | +| ISM-1977 | Security-relevant events for Linux are centrally logged. | The Linux agent sends process, network, DNS, file integrity, user and package inventory events. | No auditd or journald forwarding. | +| ISM-1976 | Security-relevant events for macOS are centrally logged. | The macOS agent sends process, network, file and user events. | No Endpoint Security framework or unified log forwarding. | +| ISM-1405 | A centralised event logging facility is implemented. | `tawny-server` with PostgreSQL stores telemetry from every agent, partitioned by month. | One server per deployment; sizing is for up to about 1,000 endpoints (target-edr section 18). | +| ISM-1983 | Event logs are sent to the central facility as soon as possible. | Agents send batches continuously, with a local spool when the server is unreachable. | Spooled events arrive late after an outage. | +| ISM-1984 | Event logs sent to the central facility are encrypted in transit with ASD-approved cryptography. | Agents talk to the server over HTTPS through the Caddy proxy (`docs/production.md`). | Cipher choice is the proxy's configuration; check it against the ISM cryptography guidelines. The compose network hop behind the proxy is plain HTTP. | +| ISM-1985 | Event logs are protected from unauthorised access. | Session and token authentication on every route, row-level security per tenant, and the admin, analyst and viewer roles (`docs/api.md`). | Database and backup access are protected by your hosting, not by Tawny. | +| ISM-1815 | Event logs are protected from unauthorised modification and deletion. | No API edits or deletes telemetry. Batches can be Ed25519 signed by the agent. The audit log is hash chained. | A database administrator can still change rows. Retention purges delete old telemetry (see below). | +| ISM-0988 | An accurate and consistent time source is used. | The server records `received_at` from its own clock and the agent's `occurred_at`, and tracks agent clock skew. | Time sync on hosts and the server is your configuration. | +| ISM-0585 | Each event captures date and time, user or process, filename, description and the equipment. | The v2 event envelope carries time, agent and host, process with entity id, user, and file path where the event has one (`schemas/events`). | Fields depend on the source event. | +| ISM-1959 | Event logs are captured and stored in a consistent, structured format. | One JSON schema per event type, versioned, with golden tests. | None known. | +| ISM-1623 | PowerShell module logging, script block logging and transcription events are centrally logged. | Script block events (4104) are collected and reassembled. | Module logging (4103) and transcription files are not collected. Script block logging must be turned on in Group Policy. | +| ISM-1509 | Privileged access events are centrally logged. | Security 4672 (special privileges for a new logon) and 4624 logons. | Only Windows, and only where the agent runs. | +| ISM-1650 | Privileged user account and security group management events are centrally logged. | | **Not supported.** The agent does not collect 4720, 4728, 4732 or 4756 yet. | + +## Event log monitoring and incidents + +| Control | Wording (short) | How Tawny supports it | Gap | +|---|---|---|---| +| ISM-0120 | Cyber security personnel have sufficient tools to detect events and identify incidents. | Rules (native, Sigma, IOC, sequence, threshold, YARA), hunts, process trees, incidents with an explained risk score, ATT&CK coverage. | Coverage depends on the rules you enable and the telemetry you collect. | +| ISM-0109 | Event logs from workstations are analysed in a timely manner. | Detection runs on every ingested event; alerts are grouped into incidents. Analysts triage in the UI. | Someone has to look. Tawny does not staff a SOC. | +| ISM-1228 | Cyber security events are analysed in a timely manner to identify incidents. | Incidents group related alerts by host, lineage and shared artefacts within 4 hours, and are sent to Tawny-SOC. | Grouping rules are fixed (target-edr section 8); tune them with exceptions. | +| ISM-2116 | Cyber threat intelligence services support detection. | Threat intel feeds become IOC rules; lookups and reputation enrichment on alerts. | Feed quality is the provider's. | +| ISM-0125 | A cyber security incident register is developed, implemented and maintained. | Tawny incidents can feed a register: each has status, owner, timeline and risk, and goes to Tawny-SOC. | Tawny's incidents are detection groups, not a register. Case management, reporting and lessons learnt live in Tawny-SOC or your own register. | + +## Endpoint detection and response + +| Control | Wording (short) | How Tawny supports it | Gap | +|---|---|---|---| +| ISM-1341 | A HIPS or EDR solution is implemented on workstations. | The Tawny agent on Windows, macOS and Linux workstations, with kill, suspend, quarantine and (Windows) isolation. | Detection is after execution; Tawny does not prevent execution (target-edr section 18, item 3). Isolation is Windows only. | +| ISM-1034 | A HIPS or EDR solution is implemented on critical servers and high-value servers. | The same agent on Windows and Linux servers. | Same as above. | +| ISM-1584 | Unprivileged users are prevented from bypassing, disabling or modifying security functionality. | The agent runs as LocalSystem or root, its service DACL and key protection are hardened, and tamper and silent-agent alerts are raised (`docs/production-agent-hardening.md`). | Tawny detects tampering; it cannot stop an administrator. | + +## Event log retention + +| Control | Wording (short) | How Tawny supports it | Gap | +|---|---|---|---| +| ISM-1988 | Event logs are retained in a searchable manner for at least 12 months. | Alerts are kept 365 days. Telemetry is backed up daily as gzip JSON lines to a local path or S3 (`TAWNY_BACKUP_*`). | **Partly met.** Raw telemetry in the database is purged after 30 days unless an alert references it. Backups are not searchable from Tawny. To meet the control, keep the backups for 12 months in a store you can search, or forward telemetry to a SIEM that keeps it. | + +## Controls Tawny gives evidence for but does not implement + +These are Essential Eight controls where Tawny's telemetry shows whether the control is working, but the control is configured elsewhere. See [essential-eight.md](essential-eight.md). + +| Control | Wording (short) | What Tawny shows | +|---|---|---| +| ISM-0843 | Application control is implemented on workstations. | Nothing about enforcement. Tawny shows unsigned or new executables running, which application control should have stopped. | +| ISM-1660 | Allowed and blocked application control events are centrally logged. | **Not supported.** AppLocker and WDAC events are not collected. | +| ISM-1667 | Microsoft Office is blocked from creating child processes. | The built-in `office-spawns-shell` rule fires when Office starts a shell, which means the block is missing or bypassed. | +| ISM-1683 | Successful and unsuccessful MFA events are centrally logged. | **Not supported.** MFA events live in the identity provider. | +| ISM-1698, ISM-1807, ISM-1808 | Vulnerability scanning and asset discovery. | Agent inventory and OSV exposure for language packages only. Tawny is not a vulnerability scanner. | + +## IDs not checked + +None. Every ID above was found on the cyber.gov.au September 2026 pages and in OSCAL `v2026.09.4`. When the ISM is next released, check each row again: ASD amends and renumbers controls each quarter. diff --git a/docs/entra-sso.md b/docs/entra-sso.md new file mode 100644 index 0000000..b173f4f --- /dev/null +++ b/docs/entra-sso.md @@ -0,0 +1,104 @@ +# Sign-in with Microsoft Entra ID + +Tawny signs users in with Microsoft Entra ID using OpenID Connect: the authorisation code flow with PKCE (S256). Nothing in this repository registers an app or holds a real secret. These are the steps to do it for a deployment. + +## How it works + +1. The sign-in page shows **Sign in with Microsoft Entra ID** when the tenant has it on. It links to `GET /api/auth/oidc/start?tenant=`. +2. Tawny reads the tenant's discovery document (`/.well-known/openid-configuration`, cached), stores a random `state`, `nonce` and PKCE verifier in `oauth_states` for 10 minutes, and redirects to Entra. +3. Entra redirects back to `GET /api/auth/oidc/callback?code=…&state=…`. Tawny deletes the state row as it reads it, so a state works once. +4. Tawny exchanges the code at the token endpoint with the client secret and the PKCE verifier. +5. Tawny checks the ID token before it reads anything else in it: + - RS256 signature against the JWKS (cached for 24 hours, fetched again once when the `kid` is unknown), using the RS256 code in `server/src/crypto/jwt.zig`; + - `iss` equals the discovery issuer, `https://login.microsoftonline.com//v2.0`; + - `aud` is the client id; + - `exp` and `nbf`, with 2 minutes of clock skew; + - `nonce` equals the stored one; + - `tid` equals the configured directory (tenant) id. +6. The user is found by `tid` and `oid`, never by email. If there is no such user, one is created. Email is kept for display only. +7. The role comes from the `groups` claim and the group map. The highest mapped role wins. No mapped group means no access, and the refusal is written to the audit log. The role is set again on every sign-in, so removing someone from a group takes effect at their next sign-in. Existing sessions last until they expire (8 hours idle, 7 days at most). + +Provider endpoints must be `https` to a public host. + +## Register the app in Entra ID + +Do this in the Microsoft Entra admin centre for the directory your users are in. + +1. **App registrations > New registration.** + - Name: `Tawny`. + - Supported account types: **Accounts in this organisational directory only** (single tenant). + - Redirect URI: platform **Web**, value `/api/auth/oidc/callback`, for example `https://tawny.example.com.au/api/auth/oidc/callback`. It must match `TAWNY_PUBLIC_URL` exactly. +2. Note the **Application (client) ID** and the **Directory (tenant) ID** from the overview page. +3. **Certificates & secrets > Client secrets > New client secret.** Pick an expiry your organisation allows and put a reminder in the calendar before it. Copy the value once; it is not shown again. Do not paste it into tickets, chat or this repository. +4. **Token configuration > Add groups claim.** Choose **Security groups** (or **Groups assigned to the application**), and for the ID token pick **Group ID**. Tawny maps group object ids, not names. + - Users in more than 200 groups get an overage claim instead of the list, and Tawny refuses them. Use **Groups assigned to the application** and assign only the Tawny groups to keep the list short. +5. **API permissions:** `openid`, `profile` and `email` (Microsoft Graph, delegated) are enough. Grant admin consent if your directory needs it. +6. **Enterprise applications > Tawny > Properties:** set **Assignment required** to **Yes** if only assigned users and groups should be able to try. +7. Create three security groups, or reuse existing ones, for example `Tawny admins`, `Tawny analysts` and `Tawny viewers`. Note each group's **Object ID**. + +## Configure Tawny + +The server needs `TAWNY_INTEGRATION_ENCRYPTION_KEY` set. The client secret is stored encrypted with it (AES-256-GCM, the same scheme as other integration secrets). Keep the key with your database backups: a new key cannot decrypt old rows. + +As an admin, send: + +```http +PUT /api/settings/oidc +Content-Type: application/json +X-CSRF-Token: + +{ + "enabled": true, + "entra_tenant_id": "", + "client_id": "", + "client_secret": "", + "allowed_domains": ["example.com.au"], + "group_roles": { + "": "admin", + "": "analyst", + "": "viewer" + } +} +``` + +- `authority` is optional and defaults to `https://login.microsoftonline.com//v2.0`. Leave it unset for Entra. +- `allowed_domains` limits sign-in to those email domains. An empty list allows any account in the directory. +- Leave `client_secret` out of a later `PUT` to keep the stored one. `GET /api/settings/oidc` never returns it, only `client_secret_set`. +- Changing the configuration clears the cached discovery document and keys. + +Then sign out and use **Sign in with Microsoft Entra ID** with a test account in each group. + +## Keep a break-glass admin + +Entra ID can be unavailable, or misconfigured. Keep at least one admin who can sign in with a password: + +1. The bootstrap admin is marked break-glass when it is created. To mark another, `PUT /api/users/{id}` with `{"break_glass": true}`. Only admins with a password can be marked. +2. Store the break-glass password offline, the way your organisation stores other emergency credentials. +3. To stop everyone else using passwords: `PUT /api/settings/tenant` with `{"password_login": "break_glass"}`. Tawny refuses this while no active break-glass admin with a password exists. Other users then get 403 from `POST /api/auth/login` and are told to use Entra ID. +4. To undo: `{"password_login": "all"}`. + +Test the break-glass sign-in after any change, and after rotating the password. + +## Rotate the client secret + +1. In Entra, add a new client secret before the old one expires. +2. `PUT /api/settings/oidc` with the same settings and the new `client_secret`. +3. Sign in with Entra ID to check it. +4. Delete the old secret in Entra. + +## Testing without Entra + +`contract-tests/mock_oidc.py` is a small provider the contract suite starts on `127.0.0.1`. It makes an RSA key with `openssl genrsa` at start-up and deletes it on exit, serves discovery and JWKS, checks the client secret and PKCE verifier at the token endpoint, and signs RS256 ID tokens. The suite signs in through it and checks the group mapping, the `tid` and `oid` match, refusals for a missing group, a wrong domain, a wrong `nonce`, `aud`, `iss` or an expired token, a reused `state`, and the break-glass setting. + +The server only talks to a plain `http://127.0.0.1` provider when `TAWNY_OIDC_ALLOW_LOOPBACK=1`. CI sets it for the contract job. Never set it in production. + +## Troubleshooting + +| Symptom | Check | +|---|---| +| "Entra ID sign-in is not configured." | `enabled` is true in `/api/settings/oidc` for this tenant, and the sign-in link has the right `?tenant=`. | +| "Entra ID discovery failed." | The server can reach `login.microsoftonline.com` over HTTPS, and `entra_tenant_id` is right. | +| "Entra ID token exchange failed." | The client secret has not expired, and the redirect URI in Entra matches `TAWNY_PUBLIC_URL` exactly. | +| "Entra ID token was not valid." | The server log line `oidc: id token refused: ` names the failed check. `BadTenant` means the account is from another directory. Clock drift beyond 2 minutes gives `Expired` or `NotYetValid`. | +| "Your Entra ID groups do not grant access to Tawny." | The groups claim is configured with Group ID, the user is in a mapped group, and the object ids in `group_roles` are right. | +| "This account's domain is not allowed." | `allowed_domains`. |