Production hardening: security fixes, code quality, 724 skills complete

- Fix 25 shell=True subprocess calls with list-based commands
- Fix 49 verify=False in defensive skills (env-var override)
- Add timeout to 231 HTTP/subprocess/socket calls
- Fix 6 SQL injection patterns with whitelist validation
- Replace 8 __import__() with standard imports
- Remove 701 unused imports across 442 files
- Add authorized-testing disclaimers to all offensive skills
- Complete 11 incomplete skill directories
- Expand 10 stub SKILL.md files with full content
- Fix 2 YAML parse errors in frontmatter
- Fix 5 pre-existing syntax errors
- Convert 22 hardcoded paths/ports to environment variables
- Back up 21 redundant skill pairs to .bak
- Fix 2 global declaration errors
- 724/724 skills with full folder anatomy (SKILL.md + agent.py + api-reference.md + LICENSE)
- 0 compile errors across all 724 agent.py files
This commit is contained in:
mukul975
2026-03-19 13:26:49 +01:00
parent 63b442d347
commit c47eed6a64
900 changed files with 23085 additions and 2720 deletions
@@ -0,0 +1,201 @@
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.
@@ -0,0 +1,44 @@
---
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 <api_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)
```
@@ -0,0 +1,56 @@
# 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: <key>
Response: data.attributes.last_analysis_stats.malicious
```
@@ -0,0 +1,213 @@
#!/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()