mirror of
https://github.com/mukul975/Anthropic-Cybersecurity-Skills.git
synced 2026-08-28 12:19:41 +03:00
chore: fix license, add disclaimer, quick start, GitHub topics, issue templates
This commit is contained in:
@@ -1,21 +1,201 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 Mahipal
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
1. Definitions.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
@@ -6,7 +6,7 @@ subdomain: threat-hunting
|
||||
tags: [threat-hunting, mitre-attack, pass-the-hash, credential-access, t1550, proactive-detection]
|
||||
version: "1.0"
|
||||
author: mahipal
|
||||
license: MIT
|
||||
license: Apache-2.0
|
||||
---
|
||||
|
||||
# Detecting Pass The Hash Attacks
|
||||
|
||||
@@ -1,43 +1,64 @@
|
||||
# API Reference: Detecting Pass-the-Hash Attacks
|
||||
|
||||
## python-evtx Library
|
||||
## Windows Event ID 4624 Fields
|
||||
|
||||
| Field | PtH Signal |
|
||||
|-------|------------|
|
||||
| LogonType | 3 (Network) |
|
||||
| AuthenticationPackageName | NTLM (not Kerberos) |
|
||||
| LogonProcessName | NtLmSsp |
|
||||
| IpAddress | Source of authentication |
|
||||
| TargetUserName | Account being used |
|
||||
|
||||
## python-evtx Usage
|
||||
|
||||
```python
|
||||
from Evtx.Evtx import FileHeader
|
||||
with open("Security.evtx", "rb") as f:
|
||||
fh = FileHeader(f)
|
||||
for record in fh.records():
|
||||
xml_string = record.xml()
|
||||
import Evtx.Evtx as evtx
|
||||
with evtx.Evtx("Security.evtx") as log:
|
||||
for record in log.records():
|
||||
xml = record.xml()
|
||||
# Filter EventID 4624, LogonType=3, AuthPackage=NTLM
|
||||
```
|
||||
|
||||
## Event 4624 - NTLM Network Logon (PTH Indicator)
|
||||
```xml
|
||||
<Data Name="TargetUserName">admin</Data>
|
||||
<Data Name="TargetDomainName">CORP</Data>
|
||||
<Data Name="LogonType">3</Data>
|
||||
<Data Name="AuthenticationPackageName">NTLM</Data>
|
||||
<Data Name="LmPackageName">NTLM V2</Data>
|
||||
<Data Name="LogonProcessName">NtLmSsp</Data>
|
||||
<Data Name="KeyLength">0</Data>
|
||||
<Data Name="IpAddress">10.0.0.50</Data>
|
||||
<Data Name="WorkstationName">ATTACKER-PC</Data>
|
||||
## PtH Detection Logic
|
||||
|
||||
```python
|
||||
src_targets = defaultdict(set)
|
||||
for event in ntlm_logons:
|
||||
src_targets[event["source_ip"]].add(event["computer"])
|
||||
# Alert when single source authenticates to 3+ targets via NTLM
|
||||
```
|
||||
|
||||
## PTH Detection Indicators
|
||||
| Field | PTH Value | Normal |
|
||||
|-------|-----------|--------|
|
||||
| LogonType | 3 (Network) | Various |
|
||||
| AuthenticationPackageName | NTLM | Kerberos |
|
||||
| LogonProcessName | NtLmSsp | Kerberos |
|
||||
| KeyLength | 0 | 128 |
|
||||
| LmPackageName | NTLM V1 (weaker) | NTLM V2 |
|
||||
## Splunk SPL Detection
|
||||
|
||||
## Detection Logic
|
||||
1. Filter 4624 where LogonType=3 AND AuthenticationPackageName=NTLM
|
||||
2. Flag events with KeyLength=0 (hash-only authentication)
|
||||
3. Detect same account authenticating from 3+ different source IPs
|
||||
4. Detect account used from 3+ different workstation names
|
||||
5. Correlate with process creation (4688) for post-exploitation activity
|
||||
```spl
|
||||
index=wineventlog EventCode=4624 Logon_Type=3
|
||||
| where Authentication_Package="NTLM"
|
||||
| stats dc(Computer) as targets by Source_Network_Address, Account_Name
|
||||
| where targets >= 3
|
||||
| sort -targets
|
||||
```
|
||||
|
||||
## MITRE ATT&CK
|
||||
- T1550.002 - Pass the Hash
|
||||
- T1078 - Valid Accounts
|
||||
## KQL (Microsoft Sentinel)
|
||||
|
||||
```kql
|
||||
SecurityEvent
|
||||
| where EventID == 4624 and LogonType == 3
|
||||
| where AuthenticationPackageName == "NTLM"
|
||||
| summarize TargetCount=dcount(Computer) by IpAddress, TargetUserName
|
||||
| where TargetCount >= 3
|
||||
```
|
||||
|
||||
## Mitigation
|
||||
|
||||
```powershell
|
||||
# Restrict NTLM authentication
|
||||
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" -Name "RestrictSendingNTLMTraffic" -Value 2
|
||||
```
|
||||
|
||||
## CLI Usage
|
||||
|
||||
```bash
|
||||
python agent.py --security-log Security.evtx
|
||||
python agent.py --security-log Security.evtx --target-threshold 5
|
||||
```
|
||||
|
||||
@@ -1,151 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pass-the-Hash Detection Agent - Detects PTH via NTLM Event 4624 LogonType=3 analysis."""
|
||||
"""Pass-the-Hash attack detection agent.
|
||||
|
||||
Detects NTLM hash reuse attacks by analyzing Windows Security Event ID 4624
|
||||
for Type 3 NTLM logons with anomalous patterns across multiple targets.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
|
||||
from Evtx.Evtx import FileHeader
|
||||
from lxml import etree
|
||||
try:
|
||||
import Evtx.Evtx as evtx
|
||||
except ImportError:
|
||||
evtx = None
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
NS = {"evt": "http://schemas.microsoft.com/win/2004/08/events/event"}
|
||||
LEGITIMATE_SOURCES = {"127.0.0.1", "::1", "-", ""}
|
||||
|
||||
|
||||
def parse_ntlm_logons(evtx_path):
|
||||
"""Parse Event 4624 NTLM network logons from Security EVTX."""
|
||||
ntlm_logons = []
|
||||
with open(evtx_path, "rb") as f:
|
||||
fh = FileHeader(f)
|
||||
for record in fh.records():
|
||||
try:
|
||||
xml = record.xml()
|
||||
root = etree.fromstring(xml.encode("utf-8"))
|
||||
eid = root.find(".//evt:System/evt:EventID", NS)
|
||||
if eid is None or eid.text != "4624":
|
||||
continue
|
||||
data = {}
|
||||
for elem in root.findall(".//evt:EventData/evt:Data", NS):
|
||||
data[elem.get("Name", "")] = elem.text or ""
|
||||
if data.get("LogonType") == "3" and data.get("AuthenticationPackageName") == "NTLM":
|
||||
time_elem = root.find(".//evt:System/evt:TimeCreated", NS)
|
||||
ntlm_logons.append({
|
||||
"timestamp": time_elem.get("SystemTime", "") if time_elem is not None else "",
|
||||
"account": data.get("TargetUserName", ""),
|
||||
"domain": data.get("TargetDomainName", ""),
|
||||
"source_ip": data.get("IpAddress", ""),
|
||||
"workstation": data.get("WorkstationName", ""),
|
||||
"logon_process": data.get("LogonProcessName", ""),
|
||||
"lm_package": data.get("LmPackageName", ""),
|
||||
"key_length": data.get("KeyLength", ""),
|
||||
})
|
||||
except Exception:
|
||||
def parse_logon_events(filepath):
|
||||
if evtx is None:
|
||||
return {"error": "python-evtx not installed: pip install python-evtx"}
|
||||
events = []
|
||||
with evtx.Evtx(filepath) as log:
|
||||
for record in log.records():
|
||||
xml = record.xml()
|
||||
if "<EventID>4624</EventID>" not in xml:
|
||||
continue
|
||||
logger.info("Parsed %d NTLM network logon events", len(ntlm_logons))
|
||||
return ntlm_logons
|
||||
logon_type = re.search(r'<Data Name="LogonType">(\d+)', xml)
|
||||
auth_pkg = re.search(r'<Data Name="AuthenticationPackageName">([^<]+)', xml)
|
||||
account = re.search(r'<Data Name="TargetUserName">([^<]+)', xml)
|
||||
domain = re.search(r'<Data Name="TargetDomainName">([^<]+)', xml)
|
||||
src_ip = re.search(r'<Data Name="IpAddress">([^<]+)', xml)
|
||||
computer = re.search(r'<Data Name="Computer">([^<]+)', xml)
|
||||
time_match = re.search(r'SystemTime="([^"]+)"', xml)
|
||||
lt = logon_type.group(1) if logon_type else ""
|
||||
ap = auth_pkg.group(1) if auth_pkg else ""
|
||||
if lt == "3" and "NTLM" in ap.upper():
|
||||
events.append({
|
||||
"timestamp": time_match.group(1) if time_match else "",
|
||||
"logon_type": int(lt), "auth_package": ap.strip(),
|
||||
"account": account.group(1) if account else "",
|
||||
"domain": domain.group(1) if domain else "",
|
||||
"source_ip": src_ip.group(1) if src_ip else "",
|
||||
"computer": computer.group(1) if computer else "",
|
||||
})
|
||||
return events
|
||||
|
||||
|
||||
def detect_pth_indicators(ntlm_logons):
|
||||
"""Detect Pass-the-Hash indicators in NTLM logon events."""
|
||||
pth_candidates = []
|
||||
for logon in ntlm_logons:
|
||||
indicators = []
|
||||
if logon["logon_process"].strip() == "NtLmSsp":
|
||||
indicators.append("NtLmSsp logon process")
|
||||
if logon["lm_package"].strip() == "NTLM V1":
|
||||
indicators.append("NTLMv1 (weaker, often PTH)")
|
||||
if logon["key_length"] == "0":
|
||||
indicators.append("Zero key length (PTH indicator)")
|
||||
if logon["workstation"] and logon["source_ip"]:
|
||||
indicators.append("Remote NTLM with workstation name")
|
||||
if indicators:
|
||||
logon["pth_indicators"] = indicators
|
||||
logon["confidence"] = min(len(indicators) * 25, 100)
|
||||
pth_candidates.append(logon)
|
||||
logger.info("Found %d PTH candidate events", len(pth_candidates))
|
||||
return pth_candidates
|
||||
def detect_pth_patterns(events, target_threshold=3):
|
||||
if isinstance(events, dict) and "error" in events:
|
||||
return [events]
|
||||
findings = []
|
||||
src_targets = defaultdict(lambda: {"computers": set(), "count": 0,
|
||||
"source_ip": "", "account": ""})
|
||||
for evt in events:
|
||||
src = evt.get("source_ip", "")
|
||||
if src in LEGITIMATE_SOURCES:
|
||||
continue
|
||||
key = f"{src}|{evt.get('account', '')}"
|
||||
src_targets[key]["computers"].add(evt.get("computer", ""))
|
||||
src_targets[key]["count"] += 1
|
||||
src_targets[key]["source_ip"] = src
|
||||
src_targets[key]["account"] = evt.get("account", "")
|
||||
|
||||
|
||||
def detect_lateral_movement_chains(ntlm_logons):
|
||||
"""Detect chains of NTLM logons from the same account across multiple hosts."""
|
||||
account_hosts = defaultdict(set)
|
||||
account_events = defaultdict(list)
|
||||
for logon in ntlm_logons:
|
||||
account = f"{logon['domain']}\\{logon['account']}"
|
||||
if not logon["account"].endswith("$"):
|
||||
account_hosts[account].add(logon["source_ip"])
|
||||
account_events[account].append(logon)
|
||||
chains = []
|
||||
for account, hosts in account_hosts.items():
|
||||
if len(hosts) >= 3:
|
||||
chains.append({
|
||||
"account": account,
|
||||
"unique_source_ips": len(hosts),
|
||||
"total_logons": len(account_events[account]),
|
||||
"source_ips": list(hosts),
|
||||
"indicator": "Multi-host NTLM lateral movement",
|
||||
"severity": "critical" if len(hosts) >= 5 else "high",
|
||||
for key, data in src_targets.items():
|
||||
target_count = len(data["computers"])
|
||||
if target_count >= target_threshold:
|
||||
findings.append({
|
||||
"type": "ntlm_type3_multi_target",
|
||||
"source_ip": data["source_ip"],
|
||||
"account": data["account"],
|
||||
"target_count": target_count,
|
||||
"targets": list(data["computers"])[:20],
|
||||
"total_logons": data["count"],
|
||||
"severity": "CRITICAL" if target_count >= 10 else "HIGH",
|
||||
"mitre": "T1550.002",
|
||||
})
|
||||
logger.info("Found %d lateral movement chains", len(chains))
|
||||
return chains
|
||||
|
||||
|
||||
def detect_workstation_mismatch(ntlm_logons):
|
||||
"""Detect mismatches between source workstation and expected host."""
|
||||
account_workstations = defaultdict(set)
|
||||
for logon in ntlm_logons:
|
||||
if logon["account"] and not logon["account"].endswith("$"):
|
||||
key = f"{logon['domain']}\\{logon['account']}"
|
||||
account_workstations[key].add(logon["workstation"])
|
||||
mismatches = []
|
||||
for account, workstations in account_workstations.items():
|
||||
if len(workstations) >= 3:
|
||||
mismatches.append({
|
||||
"account": account,
|
||||
"unique_workstations": len(workstations),
|
||||
"workstations": list(workstations),
|
||||
"indicator": "Account used from multiple workstations (PTH spread)",
|
||||
admin_sources = defaultdict(int)
|
||||
for evt in events:
|
||||
if evt.get("account", "").lower() in ("administrator", "admin"):
|
||||
admin_sources[evt.get("source_ip", "")] += 1
|
||||
for src, count in admin_sources.items():
|
||||
if count >= 2 and src not in LEGITIMATE_SOURCES:
|
||||
findings.append({
|
||||
"type": "admin_ntlm", "source_ip": src,
|
||||
"logon_count": count, "severity": "HIGH", "mitre": "T1550.002",
|
||||
})
|
||||
return mismatches
|
||||
|
||||
|
||||
def generate_report(ntlm_logons, pth_candidates, chains, mismatches):
|
||||
"""Generate Pass-the-Hash detection report."""
|
||||
report = {
|
||||
"timestamp": datetime.utcnow().isoformat(),
|
||||
"total_ntlm_logons": len(ntlm_logons),
|
||||
"pth_candidates": len(pth_candidates),
|
||||
"lateral_movement_chains": len(chains),
|
||||
"workstation_mismatches": len(mismatches),
|
||||
"high_confidence_pth": [p for p in pth_candidates if p.get("confidence", 0) >= 75],
|
||||
"chain_details": chains,
|
||||
"mismatch_details": mismatches,
|
||||
"sample_pth_events": pth_candidates[:20],
|
||||
}
|
||||
total = len(pth_candidates) + len(chains)
|
||||
print(f"PTH DETECTION: {len(pth_candidates)} candidates, {len(chains)} lateral chains")
|
||||
return report
|
||||
return findings
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Pass-the-Hash Detection Agent")
|
||||
parser.add_argument("--evtx-file", required=True, help="Path to Security EVTX file")
|
||||
parser.add_argument("--output", default="pth_report.json")
|
||||
parser = argparse.ArgumentParser(description="Pass-the-Hash Detector")
|
||||
parser.add_argument("--security-log", required=True, help="Windows Security EVTX")
|
||||
parser.add_argument("--target-threshold", type=int, default=3)
|
||||
args = parser.parse_args()
|
||||
|
||||
ntlm_logons = parse_ntlm_logons(args.evtx_file)
|
||||
pth_candidates = detect_pth_indicators(ntlm_logons)
|
||||
chains = detect_lateral_movement_chains(ntlm_logons)
|
||||
mismatches = detect_workstation_mismatch(ntlm_logons)
|
||||
|
||||
report = generate_report(ntlm_logons, pth_candidates, chains, mismatches)
|
||||
with open(args.output, "w") as f:
|
||||
json.dump(report, f, indent=2)
|
||||
logger.info("Report saved to %s", args.output)
|
||||
events = parse_logon_events(args.security_log)
|
||||
findings = detect_pth_patterns(events, args.target_threshold)
|
||||
ntlm_count = len(events) if isinstance(events, list) else 0
|
||||
results = {
|
||||
"timestamp": datetime.utcnow().isoformat() + "Z",
|
||||
"total_ntlm_type3_logons": ntlm_count,
|
||||
"findings": findings, "total_findings": len(findings),
|
||||
}
|
||||
print(json.dumps(results, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user