reverse-skills-max: initial public release (restored, redacted, hardened)
This commit is contained in:
@@ -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,376 @@
|
||||
---
|
||||
name: performing-malware-ioc-extraction
|
||||
description: Malware IOC extraction is the process of analyzing malicious software
|
||||
to identify actionable indicators of compromise including file hashes, network indicators
|
||||
(C2 domains, IP addresses, URLs), regist
|
||||
domain: cybersecurity
|
||||
subdomain: threat-intelligence
|
||||
tags:
|
||||
- threat-intelligence
|
||||
- cti
|
||||
- ioc
|
||||
- mitre-attack
|
||||
- stix
|
||||
- malware-analysis
|
||||
- yara
|
||||
- reverse-engineering
|
||||
version: '1.0'
|
||||
author: mahipal
|
||||
license: Apache-2.0
|
||||
nist_csf:
|
||||
- ID.RA-01
|
||||
- ID.RA-05
|
||||
- DE.CM-01
|
||||
- DE.AE-02
|
||||
mitre_attack:
|
||||
- T1591
|
||||
- T1592
|
||||
- T1593
|
||||
- T1589
|
||||
- T1071
|
||||
---
|
||||
# Performing Malware IOC Extraction
|
||||
|
||||
## Overview
|
||||
|
||||
Malware IOC extraction is the process of analyzing malicious software to identify actionable indicators of compromise including file hashes, network indicators (C2 domains, IP addresses, URLs), registry modifications, mutex names, embedded strings, and behavioral artifacts. This skill covers static analysis with PE parsing and string extraction, dynamic analysis with sandbox detonation, automated IOC extraction using tools like YARA, and formatting results as STIX 2.1 indicators for sharing.
|
||||
|
||||
|
||||
## When to Use
|
||||
|
||||
- When conducting security assessments that involve performing malware ioc extraction
|
||||
- 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 `pefile`, `yara-python`, `oletools`, `stix2` libraries
|
||||
- Access to malware analysis sandbox (Cuckoo, CAPE, Any.Run, Joe Sandbox)
|
||||
- VirusTotal API key for enrichment
|
||||
- Isolated analysis environment (VM or container)
|
||||
- Understanding of PE file format, common packing techniques
|
||||
- Familiarity with YARA rule syntax
|
||||
|
||||
## Key Concepts
|
||||
|
||||
### Static Analysis IOCs
|
||||
- **File Hashes**: MD5, SHA-1, SHA-256 of the sample and any dropped files
|
||||
- **Import Hash (imphash)**: Hash of imported function table, groups malware families
|
||||
- **Rich Header Hash**: PE rich header hash for compiler fingerprinting
|
||||
- **Strings**: Embedded URLs, IP addresses, domain names, registry paths, mutex names
|
||||
- **PE Metadata**: Compilation timestamp, section names, resources, digital signatures
|
||||
- **Embedded Artifacts**: PDB paths, version info, certificate details
|
||||
|
||||
### Dynamic Analysis IOCs
|
||||
- **Network Activity**: DNS queries, HTTP requests, TCP/UDP connections, SSL certificates
|
||||
- **File System**: Created/modified/deleted files and directories
|
||||
- **Registry**: Created/modified registry keys and values
|
||||
- **Process**: Spawned processes, injected processes, service creation
|
||||
- **Behavioral**: API calls, mutex creation, scheduled tasks, persistence mechanisms
|
||||
|
||||
### YARA Rules
|
||||
YARA is a pattern-matching tool for identifying and classifying malware. Rules consist of strings (text, hex, regex) and conditions that define matching logic. Rules can detect malware families, packers, exploit kits, and specific campaign tools.
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Static Analysis - PE Parsing and Hash Generation
|
||||
|
||||
```python
|
||||
import pefile
|
||||
import hashlib
|
||||
import os
|
||||
|
||||
def analyze_pe(filepath):
|
||||
"""Extract IOCs from a PE file through static analysis."""
|
||||
iocs = {"hashes": {}, "pe_info": {}, "strings": [], "imports": []}
|
||||
|
||||
# Calculate file hashes
|
||||
with open(filepath, "rb") as f:
|
||||
data = f.read()
|
||||
iocs["hashes"]["md5"] = hashlib.md5(data).hexdigest()
|
||||
iocs["hashes"]["sha1"] = hashlib.sha1(data).hexdigest()
|
||||
iocs["hashes"]["sha256"] = hashlib.sha256(data).hexdigest()
|
||||
iocs["hashes"]["file_size"] = len(data)
|
||||
|
||||
# Parse PE headers
|
||||
try:
|
||||
pe = pefile.PE(filepath)
|
||||
iocs["hashes"]["imphash"] = pe.get_imphash()
|
||||
iocs["pe_info"]["compilation_time"] = str(pe.FILE_HEADER.TimeDateStamp)
|
||||
iocs["pe_info"]["machine_type"] = hex(pe.FILE_HEADER.Machine)
|
||||
iocs["pe_info"]["subsystem"] = pe.OPTIONAL_HEADER.Subsystem
|
||||
|
||||
# Extract sections
|
||||
iocs["pe_info"]["sections"] = []
|
||||
for section in pe.sections:
|
||||
iocs["pe_info"]["sections"].append({
|
||||
"name": section.Name.decode("utf-8", errors="ignore").strip("\x00"),
|
||||
"virtual_size": section.Misc_VirtualSize,
|
||||
"raw_size": section.SizeOfRawData,
|
||||
"entropy": section.get_entropy(),
|
||||
"md5": section.get_hash_md5(),
|
||||
})
|
||||
|
||||
# Extract imports
|
||||
if hasattr(pe, "DIRECTORY_ENTRY_IMPORT"):
|
||||
for entry in pe.DIRECTORY_ENTRY_IMPORT:
|
||||
dll_name = entry.dll.decode("utf-8", errors="ignore")
|
||||
functions = [
|
||||
imp.name.decode("utf-8", errors="ignore")
|
||||
for imp in entry.imports
|
||||
if imp.name
|
||||
]
|
||||
iocs["imports"].append({"dll": dll_name, "functions": functions})
|
||||
|
||||
# Check for suspicious characteristics
|
||||
iocs["pe_info"]["is_dll"] = pe.is_dll()
|
||||
iocs["pe_info"]["is_driver"] = pe.is_driver()
|
||||
iocs["pe_info"]["is_exe"] = pe.is_exe()
|
||||
|
||||
# Version info
|
||||
if hasattr(pe, "VS_VERSIONINFO"):
|
||||
for entry in pe.FileInfo:
|
||||
for st in entry:
|
||||
for item in st.entries.items():
|
||||
key = item[0].decode("utf-8", errors="ignore")
|
||||
val = item[1].decode("utf-8", errors="ignore")
|
||||
iocs["pe_info"][f"version_{key}"] = val
|
||||
|
||||
pe.close()
|
||||
|
||||
except pefile.PEFormatError as e:
|
||||
iocs["pe_info"]["error"] = str(e)
|
||||
|
||||
return iocs
|
||||
```
|
||||
|
||||
### Step 2: String Extraction and IOC Pattern Matching
|
||||
|
||||
```python
|
||||
import re
|
||||
|
||||
def extract_ioc_strings(filepath):
|
||||
"""Extract IOC-relevant strings from binary file."""
|
||||
patterns = {
|
||||
"ipv4": re.compile(
|
||||
r"\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}"
|
||||
r"(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b"
|
||||
),
|
||||
"domain": re.compile(
|
||||
r"\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+"
|
||||
r"(?:com|net|org|io|ru|cn|tk|xyz|top|info|biz|cc|ws|pw)\b"
|
||||
),
|
||||
"url": re.compile(
|
||||
r"https?://[^\s\"'<>]{5,200}"
|
||||
),
|
||||
"email": re.compile(
|
||||
r"\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b"
|
||||
),
|
||||
"registry": re.compile(
|
||||
r"(?:HKEY_[A-Z_]+|HKLM|HKCU|HKU|HKCR|HKCC)"
|
||||
r"\\[\\a-zA-Z0-9_ .{}-]+"
|
||||
),
|
||||
"filepath_windows": re.compile(
|
||||
r"[A-Z]:\\(?:[^\\/:*?\"<>|\r\n]+\\)*[^\\/:*?\"<>|\r\n]+"
|
||||
),
|
||||
"mutex": re.compile(
|
||||
r"(?:Global\\|Local\\)[a-zA-Z0-9_\-{}.]{4,}"
|
||||
),
|
||||
"useragent": re.compile(
|
||||
r"Mozilla/[45]\.0[^\"']{10,200}"
|
||||
),
|
||||
"bitcoin": re.compile(
|
||||
r"\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b"
|
||||
),
|
||||
"pdb_path": re.compile(
|
||||
r"[A-Z]:\\[^\"]{5,200}\.pdb"
|
||||
),
|
||||
}
|
||||
|
||||
with open(filepath, "rb") as f:
|
||||
data = f.read()
|
||||
|
||||
# Extract ASCII strings (min length 4)
|
||||
ascii_strings = re.findall(rb"[\x20-\x7e]{4,}", data)
|
||||
# Extract Unicode strings
|
||||
unicode_strings = re.findall(
|
||||
rb"(?:[\x20-\x7e]\x00){4,}", data
|
||||
)
|
||||
|
||||
all_strings = [s.decode("ascii", errors="ignore") for s in ascii_strings]
|
||||
all_strings += [
|
||||
s.decode("utf-16-le", errors="ignore") for s in unicode_strings
|
||||
]
|
||||
|
||||
extracted = {category: set() for category in patterns}
|
||||
|
||||
for string in all_strings:
|
||||
for category, pattern in patterns.items():
|
||||
matches = pattern.findall(string)
|
||||
for match in matches:
|
||||
extracted[category].add(match)
|
||||
|
||||
# Convert sets to sorted lists
|
||||
return {k: sorted(v) for k, v in extracted.items() if v}
|
||||
```
|
||||
|
||||
### Step 3: YARA Rule Scanning
|
||||
|
||||
```python
|
||||
import yara
|
||||
|
||||
def scan_with_yara(filepath, rules_path):
|
||||
"""Scan file with YARA rules for malware classification."""
|
||||
rules = yara.compile(filepath=rules_path)
|
||||
matches = rules.match(filepath)
|
||||
|
||||
results = []
|
||||
for match in matches:
|
||||
result = {
|
||||
"rule": match.rule,
|
||||
"namespace": match.namespace,
|
||||
"tags": match.tags,
|
||||
"meta": match.meta,
|
||||
"strings": [],
|
||||
}
|
||||
for offset, identifier, data in match.strings:
|
||||
result["strings"].append({
|
||||
"offset": hex(offset),
|
||||
"identifier": identifier,
|
||||
"data": data.hex() if len(data) < 100 else data[:100].hex() + "...",
|
||||
})
|
||||
results.append(result)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
# Example YARA rule for common malware indicators
|
||||
SAMPLE_YARA_RULE = """
|
||||
rule Suspicious_Network_Indicators {
|
||||
meta:
|
||||
description = "Detects suspicious network-related strings"
|
||||
author = "CTI Analyst"
|
||||
severity = "medium"
|
||||
strings:
|
||||
$ua1 = "Mozilla/5.0" ascii
|
||||
$cmd1 = "cmd.exe /c" ascii nocase
|
||||
$ps1 = "powershell" ascii nocase
|
||||
$wget = "wget" ascii nocase
|
||||
$curl = "curl" ascii nocase
|
||||
$b64 = "base64" ascii nocase
|
||||
$reg1 = "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run" ascii nocase
|
||||
condition:
|
||||
uint16(0) == 0x5A4D and
|
||||
(2 of ($ua1, $cmd1, $ps1, $wget, $curl, $b64)) or $reg1
|
||||
}
|
||||
|
||||
rule Packed_Binary {
|
||||
meta:
|
||||
description = "Detects potentially packed binary"
|
||||
author = "CTI Analyst"
|
||||
condition:
|
||||
uint16(0) == 0x5A4D and
|
||||
for any section in pe.sections : (
|
||||
section.entropy >= 7.0
|
||||
)
|
||||
}
|
||||
"""
|
||||
```
|
||||
|
||||
### Step 4: Generate STIX 2.1 Indicators
|
||||
|
||||
```python
|
||||
from stix2 import (
|
||||
Bundle, Indicator, Malware, Relationship,
|
||||
File as STIXFile, DomainName, IPv4Address,
|
||||
ObservedData,
|
||||
)
|
||||
from datetime import datetime
|
||||
|
||||
def create_stix_bundle(pe_iocs, string_iocs, yara_results, sample_name):
|
||||
"""Create STIX 2.1 bundle from extracted IOCs."""
|
||||
objects = []
|
||||
|
||||
# Create Malware SDO
|
||||
malware = Malware(
|
||||
name=sample_name,
|
||||
is_family=False,
|
||||
malware_types=["unknown"],
|
||||
description=f"Malware sample analyzed: {pe_iocs['hashes']['sha256']}",
|
||||
allow_custom=True,
|
||||
)
|
||||
objects.append(malware)
|
||||
|
||||
# File hash indicator
|
||||
sha256 = pe_iocs["hashes"]["sha256"]
|
||||
hash_indicator = Indicator(
|
||||
name=f"Malware hash: {sha256[:16]}...",
|
||||
pattern=f"[file:hashes.'SHA-256' = '{sha256}']",
|
||||
pattern_type="stix",
|
||||
valid_from=datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
indicator_types=["malicious-activity"],
|
||||
allow_custom=True,
|
||||
)
|
||||
objects.append(hash_indicator)
|
||||
objects.append(Relationship(
|
||||
relationship_type="indicates",
|
||||
source_ref=hash_indicator.id,
|
||||
target_ref=malware.id,
|
||||
))
|
||||
|
||||
# Network indicators from strings
|
||||
for ip in string_iocs.get("ipv4", []):
|
||||
if not ip.startswith(("10.", "172.", "192.168.", "127.")):
|
||||
ip_indicator = Indicator(
|
||||
name=f"C2 IP: {ip}",
|
||||
pattern=f"[ipv4-addr:value = '{ip}']",
|
||||
pattern_type="stix",
|
||||
valid_from=datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
indicator_types=["malicious-activity"],
|
||||
allow_custom=True,
|
||||
)
|
||||
objects.append(ip_indicator)
|
||||
objects.append(Relationship(
|
||||
relationship_type="indicates",
|
||||
source_ref=ip_indicator.id,
|
||||
target_ref=malware.id,
|
||||
))
|
||||
|
||||
for domain in string_iocs.get("domain", []):
|
||||
domain_indicator = Indicator(
|
||||
name=f"C2 Domain: {domain}",
|
||||
pattern=f"[domain-name:value = '{domain}']",
|
||||
pattern_type="stix",
|
||||
valid_from=datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
indicator_types=["malicious-activity"],
|
||||
allow_custom=True,
|
||||
)
|
||||
objects.append(domain_indicator)
|
||||
objects.append(Relationship(
|
||||
relationship_type="indicates",
|
||||
source_ref=domain_indicator.id,
|
||||
target_ref=malware.id,
|
||||
))
|
||||
|
||||
bundle = Bundle(objects=objects, allow_custom=True)
|
||||
return bundle
|
||||
```
|
||||
|
||||
## Validation Criteria
|
||||
|
||||
- PE file parsed successfully with hashes, imports, and section analysis
|
||||
- String extraction identifies network IOCs (IPs, domains, URLs)
|
||||
- YARA rules match against known malware characteristics
|
||||
- STIX 2.1 bundle contains valid Indicator and Malware objects
|
||||
- Private IP ranges and benign strings filtered from IOC output
|
||||
- IOCs are actionable for blocking and detection rule creation
|
||||
|
||||
## References
|
||||
|
||||
- [pefile Documentation](https://github.com/erocarrera/pefile)
|
||||
- [YARA Documentation](https://yara.readthedocs.io/)
|
||||
- [MITRE ATT&CK Software](https://attack.mitre.org/software/)
|
||||
- [VirusTotal API](https://docs.virustotal.com/)
|
||||
- [CAPE Sandbox](https://github.com/kevoreilly/CAPEv2)
|
||||
- [MalwareBazaar](https://bazaar.abuse.ch/)
|
||||
@@ -0,0 +1,99 @@
|
||||
# Malware IOC Extraction Report Template
|
||||
|
||||
## Sample Information
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Filename | |
|
||||
| File Size | |
|
||||
| File Type | PE32/PE32+/ELF/Mach-O |
|
||||
| MD5 | |
|
||||
| SHA-1 | |
|
||||
| SHA-256 | |
|
||||
| Imphash | |
|
||||
| SSDeep | |
|
||||
| First Seen | |
|
||||
|
||||
## PE Analysis
|
||||
|
||||
| Attribute | Value |
|
||||
|-----------|-------|
|
||||
| Compile Time | |
|
||||
| Entry Point | |
|
||||
| Machine Type | |
|
||||
| Subsystem | |
|
||||
| Is DLL | |
|
||||
| Digital Signature | Valid/Invalid/None |
|
||||
|
||||
### Sections
|
||||
| Name | Virtual Size | Raw Size | Entropy | Suspicious |
|
||||
|------|-------------|----------|---------|------------|
|
||||
| .text | | | | |
|
||||
| .data | | | | |
|
||||
| .rsrc | | | | |
|
||||
|
||||
### Suspicious API Imports
|
||||
| DLL | Function | Purpose |
|
||||
|-----|----------|---------|
|
||||
| kernel32.dll | VirtualAlloc | Memory allocation (code injection) |
|
||||
| kernel32.dll | CreateRemoteThread | Process injection |
|
||||
| wininet.dll | InternetOpenA | Network communication |
|
||||
|
||||
## Network IOCs
|
||||
|
||||
### IP Addresses
|
||||
| IP | Context | Confidence |
|
||||
|----|---------|-----------|
|
||||
| | C2 Server | High/Med/Low |
|
||||
|
||||
### Domains
|
||||
| Domain | Context | Confidence |
|
||||
|--------|---------|-----------|
|
||||
| | C2 Domain | High/Med/Low |
|
||||
|
||||
### URLs
|
||||
| URL | Context | Confidence |
|
||||
|-----|---------|-----------|
|
||||
| | Payload Download | High/Med/Low |
|
||||
|
||||
## Host IOCs
|
||||
|
||||
### Registry Keys
|
||||
| Key Path | Value | Purpose |
|
||||
|----------|-------|---------|
|
||||
| HKLM\...\Run | | Persistence |
|
||||
|
||||
### Mutexes
|
||||
| Mutex Name | Purpose |
|
||||
|-----------|---------|
|
||||
| | Infection marker |
|
||||
|
||||
### File System Artifacts
|
||||
| Path | Description |
|
||||
|------|------------|
|
||||
| | Dropped payload |
|
||||
|
||||
## YARA Matches
|
||||
| Rule | Tags | Description |
|
||||
|------|------|------------|
|
||||
| | | |
|
||||
|
||||
## VirusTotal Results
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Detection Ratio | X / Y |
|
||||
| Threat Label | |
|
||||
| First Submission | |
|
||||
| Community Score | |
|
||||
|
||||
## MITRE ATT&CK Mapping
|
||||
| Technique | Name | Evidence |
|
||||
|-----------|------|----------|
|
||||
| T1059.001 | PowerShell | Embedded PS commands |
|
||||
| T1547.001 | Registry Run Keys | HKLM Run key modification |
|
||||
| T1071.001 | Web Protocols | HTTP C2 communication |
|
||||
|
||||
## Recommendations
|
||||
1. **Block**: Add network IOCs to firewall/proxy blocklists
|
||||
2. **Detect**: Deploy YARA rules on endpoints and email gateways
|
||||
3. **Hunt**: Search for host IOCs across the environment
|
||||
4. **Share**: Upload IOCs to MISP with TLP classification
|
||||
@@ -0,0 +1,48 @@
|
||||
# API Reference — Performing Malware IOC Extraction
|
||||
|
||||
## Libraries Used
|
||||
- **re**: Regex patterns for 16 IOC types including defanged indicators
|
||||
- **hashlib**: MD5, SHA1, SHA256 file hashing
|
||||
- **pathlib**: File reading (text and binary)
|
||||
|
||||
## CLI Interface
|
||||
```
|
||||
python agent.py text --file threat_report.txt
|
||||
python agent.py hash --file malware.exe
|
||||
python agent.py strings --file malware.exe [--min-length 6]
|
||||
python agent.py report --file malware.exe [--output iocs.json]
|
||||
```
|
||||
|
||||
## Core Functions
|
||||
|
||||
### `extract_iocs_from_text(text)` — Extract IOCs with defanging support
|
||||
Handles defanged indicators: `[.]` -> `.`, `hxxp` -> `http`. Filters private IPs.
|
||||
|
||||
### `extract_from_file(file_path)` — Extract IOCs from text/report files
|
||||
### `hash_file(file_path)` — Calculate MD5/SHA1/SHA256 hashes
|
||||
### `extract_strings(file_path, min_length)` — Binary string extraction
|
||||
Extracts ASCII and wide (UTF-16LE) strings. Identifies suspicious API calls and keywords.
|
||||
|
||||
### `generate_ioc_report(file_path, output)` — Full analysis report
|
||||
|
||||
## IOC Pattern Types (16)
|
||||
| Type | Example |
|
||||
|------|---------|
|
||||
| ipv4 | 192.168.1.1 (private filtered) |
|
||||
| domain | evil.example.com |
|
||||
| url | https://malware.example.com/payload |
|
||||
| md5/sha1/sha256 | File hashes |
|
||||
| cve | CVE-2024-12345 |
|
||||
| registry_key | HKLM\Software\... |
|
||||
| file_path_windows | C:\Windows\Temp\mal.exe |
|
||||
| mutex | Global\MutexName |
|
||||
| mitre_technique | T1059.001 |
|
||||
| bitcoin_addr | Bitcoin wallet address |
|
||||
| user_agent | Mozilla/5.0 strings |
|
||||
|
||||
## Suspicious String Keywords
|
||||
CreateRemoteThread, VirtualAlloc, WriteProcessMemory, LoadLibrary,
|
||||
GetProcAddress, WinExec, ShellExecute, powershell, cmd.exe
|
||||
|
||||
## Dependencies
|
||||
No external packages — Python standard library only.
|
||||
@@ -0,0 +1,81 @@
|
||||
# Standards and Frameworks Reference
|
||||
|
||||
## IOC Types and Classification
|
||||
|
||||
### File-Based IOCs
|
||||
| Type | Description | Example |
|
||||
|------|-------------|---------|
|
||||
| MD5 | 128-bit hash | d41d8cd98f00b204e9800998ecf8427e |
|
||||
| SHA-1 | 160-bit hash | da39a3ee5e6b4b0d3255bfef95601890afd80709 |
|
||||
| SHA-256 | 256-bit hash | e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 |
|
||||
| Imphash | Import hash | PE import table hash for family grouping |
|
||||
| SSDeep | Fuzzy hash | Context-triggered piecewise hash for similarity |
|
||||
| TLSH | Trend Micro LSH | Locality-sensitive hash for near-duplicate detection |
|
||||
|
||||
### Network IOCs
|
||||
| Type | Description | Example |
|
||||
|------|-------------|---------|
|
||||
| IPv4 Address | C2 server IP | 192.0.2.1 |
|
||||
| Domain | C2 domain | malware-c2.example.com |
|
||||
| URL | Full URL path | https://evil.com/payload.exe |
|
||||
| JA3/JA3S | TLS fingerprint | Client/server TLS handshake hash |
|
||||
| JARM | TLS server fingerprint | Active TLS server scanning fingerprint |
|
||||
| User-Agent | HTTP User-Agent | Custom UA strings in beacons |
|
||||
|
||||
### Host-Based IOCs
|
||||
| Type | Description | Example |
|
||||
|------|-------------|---------|
|
||||
| Mutex | Named mutex | Global\{GUID} |
|
||||
| Registry Key | Registry modification | HKLM\SOFTWARE\...\Run |
|
||||
| Scheduled Task | Persistence task | schtasks /create ... |
|
||||
| Service Name | Malicious service | Malicious service installation |
|
||||
| Named Pipe | IPC mechanism | \\.\pipe\name |
|
||||
| PDB Path | Debug path | C:\Users\dev\project.pdb |
|
||||
|
||||
## STIX 2.1 Indicator Patterns
|
||||
|
||||
### Pattern Syntax
|
||||
```
|
||||
[file:hashes.'SHA-256' = 'abc123...']
|
||||
[ipv4-addr:value = '1.2.3.4']
|
||||
[domain-name:value = 'evil.com']
|
||||
[url:value = 'https://evil.com/payload']
|
||||
[file:name = 'malware.exe']
|
||||
[email-addr:value = 'attacker@evil.com']
|
||||
[network-traffic:dst_ref.type = 'ipv4-addr' AND network-traffic:dst_port = 443]
|
||||
```
|
||||
|
||||
## YARA Rule Structure
|
||||
|
||||
```
|
||||
rule RuleName {
|
||||
meta:
|
||||
author = "Analyst"
|
||||
description = "Detection rule"
|
||||
reference = "URL"
|
||||
date = "YYYY-MM-DD"
|
||||
hash = "SHA256"
|
||||
tlp = "white"
|
||||
strings:
|
||||
$text = "string" ascii wide nocase
|
||||
$hex = { 4D 5A 90 00 }
|
||||
$regex = /pattern[0-9]+/
|
||||
condition:
|
||||
uint16(0) == 0x5A4D and filesize < 5MB and any of them
|
||||
}
|
||||
```
|
||||
|
||||
## PE File Format
|
||||
- **DOS Header**: MZ signature (0x5A4D)
|
||||
- **PE Header**: PE signature, machine type, timestamp
|
||||
- **Optional Header**: Entry point, image base, subsystem
|
||||
- **Section Table**: .text, .data, .rdata, .rsrc, .reloc
|
||||
- **Import Table**: DLLs and functions used
|
||||
- **Export Table**: Functions exported (DLLs)
|
||||
- **Resource Table**: Embedded resources (icons, strings, configs)
|
||||
|
||||
## References
|
||||
- [STIX 2.1 Patterning](https://docs.oasis-open.org/cti/stix/v2.1/os/stix-v2.1-os.html#_e8slinrhxcc9)
|
||||
- [YARA Documentation](https://yara.readthedocs.io/en/stable/)
|
||||
- [PE Format Specification](https://learn.microsoft.com/en-us/windows/win32/debug/pe-format)
|
||||
- [MalwareBazaar Database](https://bazaar.abuse.ch/)
|
||||
@@ -0,0 +1,70 @@
|
||||
# Malware IOC Extraction Workflows
|
||||
|
||||
## Workflow 1: Static Analysis Pipeline
|
||||
|
||||
```
|
||||
[Malware Sample] --> [Hash Generation] --> [PE Parsing] --> [String Extraction] --> [IOC Filtering]
|
||||
|
|
||||
v
|
||||
[YARA Scanning]
|
||||
|
|
||||
v
|
||||
[STIX Bundle]
|
||||
```
|
||||
|
||||
### Steps:
|
||||
1. **Sample Acquisition**: Obtain sample from MalwareBazaar, VirusTotal, or incident response
|
||||
2. **Hash Calculation**: Generate MD5, SHA-1, SHA-256, imphash, ssdeep hashes
|
||||
3. **PE Analysis**: Parse headers, sections, imports, exports, resources, timestamps
|
||||
4. **String Extraction**: Extract ASCII/Unicode strings, apply IOC regex patterns
|
||||
5. **IOC Filtering**: Remove false positives (private IPs, common DLLs, benign domains)
|
||||
6. **YARA Classification**: Scan with community and custom YARA rules
|
||||
7. **Output**: Generate STIX 2.1 bundle with extracted indicators
|
||||
|
||||
## Workflow 2: Dynamic Analysis Pipeline
|
||||
|
||||
```
|
||||
[Malware Sample] --> [Sandbox Submission] --> [Detonation] --> [Artifact Collection]
|
||||
|
|
||||
+------------+------------+
|
||||
| | |
|
||||
v v v
|
||||
[Network] [File Sys] [Registry]
|
||||
[PCAPs] [Changes] [Changes]
|
||||
| | |
|
||||
+------------+------------+
|
||||
|
|
||||
v
|
||||
[IOC Consolidation]
|
||||
```
|
||||
|
||||
### Steps:
|
||||
1. **Sandbox Setup**: Configure isolated VM with network monitoring
|
||||
2. **Sample Submission**: Submit to CAPE/Cuckoo sandbox with execution parameters
|
||||
3. **Execution Monitoring**: Monitor for 3-5 minutes of runtime behavior
|
||||
4. **Network Capture**: Extract DNS queries, HTTP/HTTPS traffic, raw connections
|
||||
5. **File System Analysis**: Identify created, modified, and deleted files
|
||||
6. **Registry Analysis**: Capture registry key changes for persistence indicators
|
||||
7. **Process Analysis**: Document spawned processes, injections, privilege escalation
|
||||
8. **Consolidation**: Merge static and dynamic IOCs into unified report
|
||||
|
||||
## Workflow 3: Automated IOC Pipeline
|
||||
|
||||
```
|
||||
[Feed/Alert] --> [Auto-Download] --> [Static Analysis] --> [Sandbox] --> [Enrichment] --> [Share]
|
||||
|
|
||||
v
|
||||
[VirusTotal Check]
|
||||
|
|
||||
v
|
||||
[MISP/OpenCTI Upload]
|
||||
```
|
||||
|
||||
### Steps:
|
||||
1. **Trigger**: New sample from malware feed, email gateway, or EDR alert
|
||||
2. **Download**: Retrieve sample securely to analysis infrastructure
|
||||
3. **Static Scan**: Automated PE parsing, string extraction, YARA scanning
|
||||
4. **Dynamic Analysis**: Submit to sandbox for behavioral analysis
|
||||
5. **Enrichment**: Check hashes against VirusTotal, cross-reference with TI platforms
|
||||
6. **Deduplication**: Remove already-known IOCs from output
|
||||
7. **Sharing**: Upload new IOCs to MISP/OpenCTI for team consumption
|
||||
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Agent for performing malware IOC extraction from files, reports, and samples."""
|
||||
|
||||
import json
|
||||
import argparse
|
||||
import re
|
||||
import hashlib
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
IOC_PATTERNS = {
|
||||
"ipv4": re.compile(r"\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b"),
|
||||
"ipv6": re.compile(r"\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b"),
|
||||
"domain": re.compile(r"\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+(?:com|net|org|io|ru|cn|xyz|top|info|biz|cc|tk|ml|ga|cf|gq|pw)\b"),
|
||||
"url": re.compile(r"https?://[^\s<>\"'\)]+"),
|
||||
"email": re.compile(r"\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b"),
|
||||
"md5": re.compile(r"\b[a-f0-9]{32}\b"),
|
||||
"sha1": re.compile(r"\b[a-f0-9]{40}\b"),
|
||||
"sha256": re.compile(r"\b[a-f0-9]{64}\b"),
|
||||
"cve": re.compile(r"CVE-\d{4}-\d{4,7}", re.I),
|
||||
"registry_key": re.compile(r"(?:HKLM|HKCU|HKCR|HKU|HKCC)\\[^\s\"']+"),
|
||||
"file_path_windows": re.compile(r"[A-Z]:\\(?:[^\s\\\"]+\\)*[^\s\\\"]+\.\w{1,5}"),
|
||||
"file_path_unix": re.compile(r"/(?:tmp|var|etc|usr|home|opt|bin|sbin)/[^\s\"']+"),
|
||||
"mutex": re.compile(r"(?:Global|Local)\\[^\s\"']+"),
|
||||
"bitcoin_addr": re.compile(r"\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b"),
|
||||
"mitre_technique": re.compile(r"T\d{4}(?:\.\d{3})?"),
|
||||
"user_agent": re.compile(r"Mozilla/5\.0[^\n\"]{20,200}"),
|
||||
}
|
||||
|
||||
DEFANGED_PATTERNS = {
|
||||
"ip_defanged": (re.compile(r"\b\d+\[\.\]\d+\[\.\]\d+\[\.\]\d+\b"), lambda m: m.group().replace("[.]", ".")),
|
||||
"url_defanged": (re.compile(r"hxxps?://[^\s]+"), lambda m: m.group().replace("hxxp", "http")),
|
||||
"domain_defanged": (re.compile(r"\b\S+\[\.\]\S+\b"), lambda m: m.group().replace("[.]", ".")),
|
||||
}
|
||||
|
||||
|
||||
def extract_iocs_from_text(text):
|
||||
"""Extract all IOC types from raw text."""
|
||||
refanged = text
|
||||
for name, (pattern, fixer) in DEFANGED_PATTERNS.items():
|
||||
refanged = pattern.sub(fixer, refanged)
|
||||
extracted = {}
|
||||
for ioc_type, pattern in IOC_PATTERNS.items():
|
||||
matches = list(set(pattern.findall(refanged)))
|
||||
if matches:
|
||||
extracted[ioc_type] = sorted(matches)[:200]
|
||||
private_ip = re.compile(r"^(?:10\.|172\.(?:1[6-9]|2\d|3[01])\.|192\.168\.|127\.)")
|
||||
if "ipv4" in extracted:
|
||||
extracted["ipv4"] = [ip for ip in extracted["ipv4"] if not private_ip.match(ip)]
|
||||
return extracted
|
||||
|
||||
|
||||
def extract_from_file(file_path):
|
||||
"""Extract IOCs from a file (text, PDF text, or report)."""
|
||||
content = Path(file_path).read_text(encoding="utf-8", errors="replace")
|
||||
iocs = extract_iocs_from_text(content)
|
||||
total = sum(len(v) for v in iocs.values())
|
||||
return {
|
||||
"source": file_path, "total_iocs": total,
|
||||
"by_type": {k: len(v) for k, v in iocs.items()},
|
||||
"indicators": iocs,
|
||||
}
|
||||
|
||||
|
||||
def hash_file(file_path):
|
||||
"""Calculate file hashes for malware sample identification."""
|
||||
data = Path(file_path).read_bytes()
|
||||
return {
|
||||
"file": file_path,
|
||||
"size_bytes": len(data),
|
||||
"md5": hashlib.md5(data).hexdigest(),
|
||||
"sha1": hashlib.sha1(data).hexdigest(),
|
||||
"sha256": hashlib.sha256(data).hexdigest(),
|
||||
}
|
||||
|
||||
|
||||
def extract_strings(file_path, min_length=6):
|
||||
"""Extract printable strings from binary file."""
|
||||
data = Path(file_path).read_bytes()
|
||||
ascii_strings = re.findall(rb"[\x20-\x7e]{%d,}" % min_length, data)
|
||||
wide_strings = re.findall(rb"(?:[\x20-\x7e]\x00){%d,}" % min_length, data)
|
||||
all_strings = [s.decode("ascii", errors="replace") for s in ascii_strings]
|
||||
all_strings += [s.decode("utf-16-le", errors="replace") for s in wide_strings]
|
||||
iocs = extract_iocs_from_text("\n".join(all_strings))
|
||||
suspicious = []
|
||||
suspicious_kw = ["http", "socket", "connect", "download", "upload", "exec", "cmd.exe",
|
||||
"powershell", "reg add", "CreateRemoteThread", "VirtualAlloc", "WriteProcessMemory",
|
||||
"LoadLibrary", "GetProcAddress", "WinExec", "ShellExecute"]
|
||||
for s in all_strings:
|
||||
if any(kw.lower() in s.lower() for kw in suspicious_kw):
|
||||
suspicious.append(s[:200])
|
||||
return {
|
||||
"file": file_path, "total_strings": len(all_strings),
|
||||
"suspicious_strings": suspicious[:30],
|
||||
"extracted_iocs": {k: len(v) for k, v in iocs.items()},
|
||||
"ioc_details": iocs,
|
||||
}
|
||||
|
||||
|
||||
def generate_ioc_report(file_path, output=None):
|
||||
"""Generate comprehensive IOC extraction report."""
|
||||
hashes = hash_file(file_path)
|
||||
strings = extract_strings(file_path)
|
||||
report = {
|
||||
"generated": datetime.now(timezone.utc).isoformat(),
|
||||
"file_info": hashes,
|
||||
"strings_analysis": {
|
||||
"total": strings["total_strings"],
|
||||
"suspicious": strings["suspicious_strings"],
|
||||
},
|
||||
"extracted_iocs": strings["ioc_details"],
|
||||
"ioc_summary": strings["extracted_iocs"],
|
||||
}
|
||||
if output:
|
||||
with open(output, "w") as f:
|
||||
json.dump(report, f, indent=2)
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Malware IOC Extraction Agent")
|
||||
sub = parser.add_subparsers(dest="command")
|
||||
t = sub.add_parser("text", help="Extract IOCs from text/report file")
|
||||
t.add_argument("--file", required=True)
|
||||
h = sub.add_parser("hash", help="Calculate file hashes")
|
||||
h.add_argument("--file", required=True)
|
||||
s = sub.add_parser("strings", help="Extract strings and IOCs from binary")
|
||||
s.add_argument("--file", required=True)
|
||||
s.add_argument("--min-length", type=int, default=6)
|
||||
r = sub.add_parser("report", help="Generate full IOC report")
|
||||
r.add_argument("--file", required=True)
|
||||
r.add_argument("--output", help="Output JSON file")
|
||||
args = parser.parse_args()
|
||||
if args.command == "text":
|
||||
result = extract_from_file(args.file)
|
||||
elif args.command == "hash":
|
||||
result = hash_file(args.file)
|
||||
elif args.command == "strings":
|
||||
result = extract_strings(args.file, args.min_length)
|
||||
elif args.command == "report":
|
||||
result = generate_ioc_report(args.file, args.output)
|
||||
else:
|
||||
parser.print_help()
|
||||
return
|
||||
print(json.dumps(result, indent=2, default=str))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,452 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Malware IOC Extraction Script
|
||||
|
||||
Performs static analysis on PE files to extract IOCs:
|
||||
- File hash generation (MD5, SHA-1, SHA-256, imphash)
|
||||
- PE header parsing and section analysis
|
||||
- String extraction with IOC pattern matching
|
||||
- YARA rule scanning
|
||||
- STIX 2.1 bundle generation
|
||||
|
||||
Requirements:
|
||||
pip install pefile yara-python stix2 requests
|
||||
|
||||
Usage:
|
||||
python process.py --file malware.exe --output iocs.json
|
||||
python process.py --file malware.exe --yara-rules rules/ --stix-output bundle.json
|
||||
python process.py --file malware.exe --vt-check --vt-key YOUR_KEY
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
try:
|
||||
import pefile
|
||||
except ImportError:
|
||||
pefile = None
|
||||
|
||||
try:
|
||||
import yara
|
||||
except ImportError:
|
||||
yara = None
|
||||
|
||||
|
||||
class MalwareIOCExtractor:
|
||||
"""Extract IOCs from malware samples via static analysis."""
|
||||
|
||||
def __init__(self, filepath: str):
|
||||
self.filepath = filepath
|
||||
self.filename = os.path.basename(filepath)
|
||||
|
||||
with open(filepath, "rb") as f:
|
||||
self.data = f.read()
|
||||
|
||||
self.hashes = self._calculate_hashes()
|
||||
self.iocs = {
|
||||
"file": {"name": self.filename, "size": len(self.data)},
|
||||
"hashes": self.hashes,
|
||||
"pe_info": {},
|
||||
"network_iocs": {},
|
||||
"host_iocs": {},
|
||||
"yara_matches": [],
|
||||
"suspicious_strings": [],
|
||||
}
|
||||
|
||||
def _calculate_hashes(self) -> dict:
|
||||
return {
|
||||
"md5": hashlib.md5(self.data).hexdigest(),
|
||||
"sha1": hashlib.sha1(self.data).hexdigest(),
|
||||
"sha256": hashlib.sha256(self.data).hexdigest(),
|
||||
}
|
||||
|
||||
def analyze_pe(self):
|
||||
"""Parse PE file structure and extract metadata IOCs."""
|
||||
if pefile is None:
|
||||
print("[-] pefile not installed, skipping PE analysis")
|
||||
return
|
||||
|
||||
try:
|
||||
pe = pefile.PE(data=self.data)
|
||||
except pefile.PEFormatError:
|
||||
print("[-] Not a valid PE file")
|
||||
return
|
||||
|
||||
self.iocs["hashes"]["imphash"] = pe.get_imphash()
|
||||
|
||||
# Compilation timestamp
|
||||
timestamp = pe.FILE_HEADER.TimeDateStamp
|
||||
try:
|
||||
compile_time = datetime.utcfromtimestamp(timestamp).isoformat()
|
||||
except (OSError, ValueError):
|
||||
compile_time = f"invalid ({timestamp})"
|
||||
|
||||
self.iocs["pe_info"] = {
|
||||
"compile_time": compile_time,
|
||||
"machine": hex(pe.FILE_HEADER.Machine),
|
||||
"is_dll": pe.is_dll(),
|
||||
"is_exe": pe.is_exe(),
|
||||
"entry_point": hex(pe.OPTIONAL_HEADER.AddressOfEntryPoint),
|
||||
"image_base": hex(pe.OPTIONAL_HEADER.ImageBase),
|
||||
"sections": [],
|
||||
"imports": [],
|
||||
"exports": [],
|
||||
}
|
||||
|
||||
# Section analysis
|
||||
for section in pe.sections:
|
||||
name = section.Name.decode("utf-8", errors="ignore").strip("\x00")
|
||||
entropy = section.get_entropy()
|
||||
self.iocs["pe_info"]["sections"].append({
|
||||
"name": name,
|
||||
"virtual_size": section.Misc_VirtualSize,
|
||||
"raw_size": section.SizeOfRawData,
|
||||
"entropy": round(entropy, 2),
|
||||
"suspicious": entropy > 7.0,
|
||||
"md5": hashlib.md5(section.get_data()).hexdigest(),
|
||||
})
|
||||
|
||||
# Import table
|
||||
if hasattr(pe, "DIRECTORY_ENTRY_IMPORT"):
|
||||
for entry in pe.DIRECTORY_ENTRY_IMPORT:
|
||||
dll = entry.dll.decode("utf-8", errors="ignore")
|
||||
funcs = []
|
||||
for imp in entry.imports:
|
||||
if imp.name:
|
||||
funcs.append(imp.name.decode("utf-8", errors="ignore"))
|
||||
self.iocs["pe_info"]["imports"].append({
|
||||
"dll": dll,
|
||||
"functions": funcs,
|
||||
})
|
||||
|
||||
# Suspicious API imports
|
||||
suspicious_apis = {
|
||||
"VirtualAlloc", "VirtualProtect", "CreateRemoteThread",
|
||||
"WriteProcessMemory", "NtUnmapViewOfSection", "IsDebuggerPresent",
|
||||
"GetProcAddress", "LoadLibraryA", "LoadLibraryW",
|
||||
"URLDownloadToFileA", "InternetOpenA", "HttpSendRequestA",
|
||||
"WinExec", "ShellExecuteA", "CreateProcessA",
|
||||
"RegSetValueExA", "CryptEncrypt", "CryptDecrypt",
|
||||
}
|
||||
|
||||
found_suspicious = set()
|
||||
for imp_entry in self.iocs["pe_info"]["imports"]:
|
||||
for func in imp_entry["functions"]:
|
||||
if func in suspicious_apis:
|
||||
found_suspicious.add(func)
|
||||
|
||||
self.iocs["pe_info"]["suspicious_apis"] = sorted(found_suspicious)
|
||||
|
||||
# Export table
|
||||
if hasattr(pe, "DIRECTORY_ENTRY_EXPORT"):
|
||||
for exp in pe.DIRECTORY_ENTRY_EXPORT.symbols:
|
||||
if exp.name:
|
||||
self.iocs["pe_info"]["exports"].append(
|
||||
exp.name.decode("utf-8", errors="ignore")
|
||||
)
|
||||
|
||||
pe.close()
|
||||
|
||||
def extract_strings(self, min_length: int = 4):
|
||||
"""Extract and classify strings from the binary."""
|
||||
patterns = {
|
||||
"ipv4": re.compile(
|
||||
r"\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}"
|
||||
r"(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b"
|
||||
),
|
||||
"domain": re.compile(
|
||||
r"\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+"
|
||||
r"(?:com|net|org|io|ru|cn|tk|xyz|top|info|biz|cc|ws|pw|"
|
||||
r"onion|bit|me|co|uk|de|fr|jp|kr|br)\b"
|
||||
),
|
||||
"url": re.compile(r"https?://[^\s\"'<>\x00]{5,200}"),
|
||||
"email": re.compile(
|
||||
r"\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b"
|
||||
),
|
||||
"registry": re.compile(
|
||||
r"(?:HKEY_[A-Z_]+|HKLM|HKCU|HKU|HKCR)"
|
||||
r"\\[\\a-zA-Z0-9_ .{}\-]+"
|
||||
),
|
||||
"filepath": re.compile(
|
||||
r"[A-Z]:\\(?:[^\\/:*?\"<>|\r\n\x00]+\\)*[^\\/:*?\"<>|\r\n\x00]+"
|
||||
),
|
||||
"mutex": re.compile(r"(?:Global\\|Local\\)[a-zA-Z0-9_\-{}.]{4,}"),
|
||||
"useragent": re.compile(r"Mozilla/[45]\.0[^\"'\x00]{10,200}"),
|
||||
"pdb_path": re.compile(r"[A-Z]:\\[^\x00\"]{5,200}\.pdb"),
|
||||
"bitcoin_wallet": re.compile(
|
||||
r"\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b"
|
||||
),
|
||||
}
|
||||
|
||||
# Extract ASCII strings
|
||||
ascii_regex = re.compile(rb"[\x20-\x7e]{%d,}" % min_length)
|
||||
ascii_strings = [
|
||||
s.decode("ascii", errors="ignore")
|
||||
for s in ascii_regex.findall(self.data)
|
||||
]
|
||||
|
||||
# Extract Unicode strings
|
||||
unicode_regex = re.compile(
|
||||
rb"(?:[\x20-\x7e]\x00){%d,}" % min_length
|
||||
)
|
||||
unicode_strings = [
|
||||
s.decode("utf-16-le", errors="ignore")
|
||||
for s in unicode_regex.findall(self.data)
|
||||
]
|
||||
|
||||
all_strings = ascii_strings + unicode_strings
|
||||
|
||||
network_iocs = {"ipv4": set(), "domain": set(), "url": set(), "email": set()}
|
||||
host_iocs = {"registry": set(), "filepath": set(), "mutex": set()}
|
||||
other = {"useragent": set(), "pdb_path": set(), "bitcoin_wallet": set()}
|
||||
|
||||
for string in all_strings:
|
||||
for category, pattern in patterns.items():
|
||||
for match in pattern.findall(string):
|
||||
if category in network_iocs:
|
||||
network_iocs[category].add(match)
|
||||
elif category in host_iocs:
|
||||
host_iocs[category].add(match)
|
||||
else:
|
||||
other[category].add(match)
|
||||
|
||||
# Filter private IPs
|
||||
private_prefixes = ("10.", "172.16.", "172.17.", "172.18.", "172.19.",
|
||||
"172.20.", "172.21.", "172.22.", "172.23.", "172.24.",
|
||||
"172.25.", "172.26.", "172.27.", "172.28.", "172.29.",
|
||||
"172.30.", "172.31.", "192.168.", "127.", "0.", "255.")
|
||||
network_iocs["ipv4"] = {
|
||||
ip for ip in network_iocs["ipv4"]
|
||||
if not ip.startswith(private_prefixes)
|
||||
}
|
||||
|
||||
# Filter common benign domains
|
||||
benign_domains = {
|
||||
"microsoft.com", "windows.com", "google.com", "w3.org",
|
||||
"xmlsoap.org", "openxmlformats.org", "schemas.microsoft.com",
|
||||
}
|
||||
network_iocs["domain"] = {
|
||||
d for d in network_iocs["domain"]
|
||||
if not any(d.endswith(b) for b in benign_domains)
|
||||
}
|
||||
|
||||
self.iocs["network_iocs"] = {k: sorted(v) for k, v in network_iocs.items() if v}
|
||||
self.iocs["host_iocs"] = {k: sorted(v) for k, v in host_iocs.items() if v}
|
||||
self.iocs["suspicious_strings"] = {k: sorted(v) for k, v in other.items() if v}
|
||||
|
||||
def scan_yara(self, rules_path: str):
|
||||
"""Scan with YARA rules."""
|
||||
if yara is None:
|
||||
print("[-] yara-python not installed, skipping YARA scan")
|
||||
return
|
||||
|
||||
try:
|
||||
if os.path.isdir(rules_path):
|
||||
rule_files = {}
|
||||
for f in os.listdir(rules_path):
|
||||
if f.endswith((".yar", ".yara")):
|
||||
rule_files[f] = os.path.join(rules_path, f)
|
||||
rules = yara.compile(filepaths=rule_files)
|
||||
else:
|
||||
rules = yara.compile(filepath=rules_path)
|
||||
|
||||
matches = rules.match(data=self.data)
|
||||
|
||||
for match in matches:
|
||||
self.iocs["yara_matches"].append({
|
||||
"rule": match.rule,
|
||||
"tags": match.tags,
|
||||
"meta": match.meta,
|
||||
"string_count": len(match.strings),
|
||||
})
|
||||
print(f"[+] YARA match: {match.rule} (tags: {match.tags})")
|
||||
|
||||
except yara.Error as e:
|
||||
print(f"[-] YARA error: {e}")
|
||||
|
||||
def check_virustotal(self, api_key: str) -> Optional[dict]:
|
||||
"""Check file hash against VirusTotal."""
|
||||
import requests
|
||||
|
||||
sha256 = self.hashes["sha256"]
|
||||
resp = requests.get(
|
||||
f"https://www.virustotal.com/api/v3/files/{sha256}",
|
||||
headers={"x-apikey": api_key},
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
if resp.status_code == 200:
|
||||
data = resp.json().get("data", {}).get("attributes", {})
|
||||
stats = data.get("last_analysis_stats", {})
|
||||
vt_result = {
|
||||
"malicious": stats.get("malicious", 0),
|
||||
"suspicious": stats.get("suspicious", 0),
|
||||
"undetected": stats.get("undetected", 0),
|
||||
"total": sum(stats.values()),
|
||||
"popular_threat_name": data.get(
|
||||
"popular_threat_classification", {}
|
||||
).get("suggested_threat_label", ""),
|
||||
"tags": data.get("tags", []),
|
||||
"type_description": data.get("type_description", ""),
|
||||
"names": data.get("names", [])[:5],
|
||||
}
|
||||
self.iocs["virustotal"] = vt_result
|
||||
print(
|
||||
f"[+] VT: {vt_result['malicious']}/{vt_result['total']} "
|
||||
f"detections - {vt_result['popular_threat_name']}"
|
||||
)
|
||||
return vt_result
|
||||
elif resp.status_code == 404:
|
||||
print(f"[!] Hash not found on VirusTotal: {sha256}")
|
||||
else:
|
||||
print(f"[-] VT API error: {resp.status_code}")
|
||||
return None
|
||||
|
||||
def generate_stix_bundle(self) -> dict:
|
||||
"""Generate STIX 2.1 bundle from extracted IOCs."""
|
||||
from stix2 import Bundle, Indicator, Malware, Relationship
|
||||
|
||||
objects = []
|
||||
|
||||
malware_obj = Malware(
|
||||
name=self.filename,
|
||||
is_family=False,
|
||||
malware_types=["unknown"],
|
||||
description=(
|
||||
f"SHA256: {self.hashes['sha256']}\n"
|
||||
f"MD5: {self.hashes['md5']}"
|
||||
),
|
||||
allow_custom=True,
|
||||
)
|
||||
objects.append(malware_obj)
|
||||
|
||||
# Hash indicator
|
||||
hash_ind = Indicator(
|
||||
name=f"File hash: {self.hashes['sha256'][:16]}...",
|
||||
pattern=f"[file:hashes.'SHA-256' = '{self.hashes['sha256']}']",
|
||||
pattern_type="stix",
|
||||
valid_from=datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
indicator_types=["malicious-activity"],
|
||||
allow_custom=True,
|
||||
)
|
||||
objects.append(hash_ind)
|
||||
objects.append(Relationship(
|
||||
relationship_type="indicates",
|
||||
source_ref=hash_ind.id,
|
||||
target_ref=malware_obj.id,
|
||||
))
|
||||
|
||||
# Network indicators
|
||||
for ip in self.iocs.get("network_iocs", {}).get("ipv4", []):
|
||||
ind = Indicator(
|
||||
name=f"C2 IP: {ip}",
|
||||
pattern=f"[ipv4-addr:value = '{ip}']",
|
||||
pattern_type="stix",
|
||||
valid_from=datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
indicator_types=["malicious-activity"],
|
||||
allow_custom=True,
|
||||
)
|
||||
objects.append(ind)
|
||||
objects.append(Relationship(
|
||||
relationship_type="indicates",
|
||||
source_ref=ind.id,
|
||||
target_ref=malware_obj.id,
|
||||
))
|
||||
|
||||
for domain in self.iocs.get("network_iocs", {}).get("domain", []):
|
||||
ind = Indicator(
|
||||
name=f"C2 Domain: {domain}",
|
||||
pattern=f"[domain-name:value = '{domain}']",
|
||||
pattern_type="stix",
|
||||
valid_from=datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
indicator_types=["malicious-activity"],
|
||||
allow_custom=True,
|
||||
)
|
||||
objects.append(ind)
|
||||
objects.append(Relationship(
|
||||
relationship_type="indicates",
|
||||
source_ref=ind.id,
|
||||
target_ref=malware_obj.id,
|
||||
))
|
||||
|
||||
bundle = Bundle(objects=objects, allow_custom=True)
|
||||
return json.loads(bundle.serialize())
|
||||
|
||||
def get_report(self) -> dict:
|
||||
"""Get complete IOC extraction report."""
|
||||
return self.iocs
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Malware IOC Extraction Tool")
|
||||
parser.add_argument("--file", required=True, help="Path to malware sample")
|
||||
parser.add_argument("--output", default="iocs.json", help="Output IOC file")
|
||||
parser.add_argument("--yara-rules", help="YARA rules file or directory")
|
||||
parser.add_argument("--vt-check", action="store_true", help="Check VirusTotal")
|
||||
parser.add_argument("--vt-key", help="VirusTotal API key")
|
||||
parser.add_argument("--stix-output", help="Output STIX 2.1 bundle file")
|
||||
parser.add_argument(
|
||||
"--min-string-length", type=int, default=4,
|
||||
help="Minimum string length for extraction",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if not os.path.isfile(args.file):
|
||||
print(f"[-] File not found: {args.file}")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"[*] Analyzing: {args.file}")
|
||||
extractor = MalwareIOCExtractor(args.file)
|
||||
|
||||
print("[*] Calculating hashes...")
|
||||
print(f" MD5: {extractor.hashes['md5']}")
|
||||
print(f" SHA1: {extractor.hashes['sha1']}")
|
||||
print(f" SHA256: {extractor.hashes['sha256']}")
|
||||
|
||||
print("[*] Parsing PE structure...")
|
||||
extractor.analyze_pe()
|
||||
|
||||
print("[*] Extracting strings and IOC patterns...")
|
||||
extractor.extract_strings(min_length=args.min_string_length)
|
||||
|
||||
if args.yara_rules:
|
||||
print(f"[*] Scanning with YARA rules: {args.yara_rules}")
|
||||
extractor.scan_yara(args.yara_rules)
|
||||
|
||||
if args.vt_check and args.vt_key:
|
||||
print("[*] Checking VirusTotal...")
|
||||
extractor.check_virustotal(args.vt_key)
|
||||
|
||||
report = extractor.get_report()
|
||||
with open(args.output, "w") as f:
|
||||
json.dump(report, f, indent=2, default=str)
|
||||
print(f"[+] IOC report saved to {args.output}")
|
||||
|
||||
if args.stix_output:
|
||||
print("[*] Generating STIX 2.1 bundle...")
|
||||
bundle = extractor.generate_stix_bundle()
|
||||
with open(args.stix_output, "w") as f:
|
||||
json.dump(bundle, f, indent=2)
|
||||
print(f"[+] STIX bundle saved to {args.stix_output}")
|
||||
|
||||
# Print summary
|
||||
net = report.get("network_iocs", {})
|
||||
host = report.get("host_iocs", {})
|
||||
print(f"\n=== IOC Summary ===")
|
||||
print(f" IPs: {len(net.get('ipv4', []))}")
|
||||
print(f" Domains: {len(net.get('domain', []))}")
|
||||
print(f" URLs: {len(net.get('url', []))}")
|
||||
print(f" Registry keys: {len(host.get('registry', []))}")
|
||||
print(f" File paths: {len(host.get('filepath', []))}")
|
||||
print(f" YARA matches: {len(report.get('yara_matches', []))}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user