
Conducting Network Penetration Test
- 238 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Run scoped network penetration tests on VLANs, firewalls, and exposed services to find misconfigs, weak segmentation, and lateral-movement paths before production cutover.
About
Guides authorized network penetration testing to discover misconfigured firewalls, exposed services, and lateral-movement routes, producing prioritized findings that harden infrastructure before production launch.
- Scoped network pentest
- Segmentation validation
- Service exposure checks
- Lateral-movement paths
- Remediation prioritization
Conducting Network Penetration Test by the numbers
- 238 all-time installs (skills.sh)
- +11 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #708 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill conducting-network-penetration-testAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 238 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Run scoped network penetration tests on VLANs, firewalls, and exposed services to find misconfigs, weak segmentation, and lateral-movement paths before production cutover.
Files
Conducting Network Penetration Test
When to Use
- Assessing the security posture of internal or external network infrastructure before or after deployment
- Validating firewall rules, network segmentation, and access controls under realistic attack conditions
- Identifying exploitable vulnerabilities in network services, protocols, and configurations
- Meeting compliance requirements for PCI-DSS, HIPAA, SOC 2, or ISO 27001 that mandate periodic penetration testing
- Evaluating the effectiveness of IDS/IPS, SIEM, and SOC detection capabilities against real attack traffic
Do not use for testing networks without explicit written authorization from the asset owner, against production systems without a pre-approved change window and rollback plan, or for denial-of-service testing unless explicitly scoped and authorized.
Prerequisites
- Signed Rules of Engagement (RoE) document specifying target IP ranges, excluded hosts, testing hours, and emergency contacts
- Written authorization letter (get-out-of-jail letter) from the network owner
- Dedicated testing laptop with Kali Linux or equivalent distribution with up-to-date tools
- VPN or direct network access to the target scope as defined in the RoE
- Out-of-band communication channel with the client's incident response team
- Scope document listing in-scope IP ranges, domains, and any explicitly excluded systems (medical devices, SCADA, critical infrastructure)
Workflow
Step 1: Pre-Engagement and Scope Validation
Validate the scope by confirming IP ranges with the client. Verify that all IP addresses in scope are owned by the client using ARIN/RIPE WHOIS lookups. Confirm testing windows, escalation procedures, and any sensitivity constraints. Set up the testing environment with a dedicated VM, VPN connection, and logging enabled on all tools. Create a timestamped activity log that records every command executed, every scan launched, and every exploit attempted throughout the engagement.
Step 2: Host Discovery and Network Mapping
Identify live hosts within the authorized scope using layered discovery techniques:
- ICMP sweep:
nmap -sn -PE -PP -PM 10.10.0.0/16 -oA discovery_icmpto find hosts responding to ping - ARP scan (internal networks):
nmap -sn -PR 10.10.0.0/24 -oA discovery_arporarp-scan -lfor local subnet enumeration - TCP SYN discovery:
nmap -sn -PS21,22,25,80,443,445,3389,8080 10.10.0.0/16 -oA discovery_tcpto find hosts with ICMP blocked - UDP discovery:
nmap -sn -PU53,161,500 10.10.0.0/16 -oA discovery_udpfor hosts only responding on UDP
Consolidate live hosts into a target list. Map the network topology by identifying gateways, VLAN boundaries, and trust relationships using traceroute and SNMP community string guessing where authorized.
Step 3: Port Scanning and Service Enumeration
Perform detailed port scanning on discovered hosts:
- Full TCP scan:
nmap -sS -p- --min-rate 1000 -T4 -oA full_tcp <target>to identify all open TCP ports - Top UDP ports:
nmap -sU --top-ports 200 -T4 -oA top_udp <target>for commonly exploitable UDP services - Service version detection:
nmap -sV -sC -p <open_ports> -oA service_enum <target>to fingerprint service versions and run default NSE scripts - OS fingerprinting:
nmap -O --osscan-guess -oA os_detection <target>to identify operating systems
Enumerate discovered services in depth using protocol-specific tools:
- SMB:
enum4linux -a <target>,crackmapexec smb <target> --shares - SNMP:
snmpwalk -v2c -c public <target> - DNS:
dig axfr @<dns_server> <domain>for zone transfer attempts - LDAP:
ldapsearch -x -H ldap://<target> -b "dc=example,dc=com"
Step 4: Vulnerability Identification
Correlate discovered service versions against known vulnerability databases:
- Run
nmap --script vuln -p <ports> <target>for NSE vulnerability scripts - Use
searchsploit <service> <version>to query the Exploit-DB offline database - Cross-reference with NVD (National Vulnerability Database) and CVE records for confirmed vulnerabilities
- Check for default credentials on management interfaces (Tomcat Manager, Jenkins, phpMyAdmin, database consoles)
- Test for common misconfigurations: anonymous FTP, open SMTP relays, unrestricted SNMP communities, NFS exports without authentication
Prioritize vulnerabilities by CVSS score, exploitability, and business impact. Document each finding with CVE identifier, affected host, service, and version.
Step 5: Exploitation
Attempt controlled exploitation of validated vulnerabilities using the principle of minimum necessary access:
- Metasploit Framework:
msfconsolewith appropriate exploit modules matched to confirmed vulnerabilities. Set RHOSTS, RPORT, and payload options. Prefer bind/reverse TCP Meterpreter for post-exploitation flexibility. - Manual exploitation: Use public proof-of-concept exploits from Exploit-DB after code review. Compile and modify as needed for the target environment.
- Credential attacks: Use
hydraorcrackmapexecfor password spraying against discovered services (SSH, RDP, SMB, HTTP basic auth) using common credential lists. Respect lockout policies. - Pass-the-hash / relay: If NTLM hashes are obtained, attempt pass-the-hash with
impacket-psexecor relay attacks withimpacket-ntlmrelayxwhere SMB signing is disabled.
Document every exploitation attempt including failures. Capture screenshots of successful compromises showing hostname, IP, current user, and privilege level.
Step 6: Post-Exploitation and Pivoting
After gaining access to a host, demonstrate business impact:
- Privilege escalation: Check for local privilege escalation paths using
linpeas.sh(Linux) orwinPEAS.exe(Windows). Look for misconfigured services, SUID binaries, unquoted service paths, or kernel exploits. - Credential harvesting: Extract stored credentials from memory (
mimikatz), files (config files, browser stores), or cached hashes (hashdump). - Lateral movement: Use obtained credentials to pivot to additional systems. Test network segmentation by attempting to reach out-of-scope networks from compromised hosts.
- Data access demonstration: Identify sensitive data accessible from compromised systems (PII databases, file shares, backup files) and document access without exfiltrating actual data.
Maintain detailed notes on every pivot point, credential obtained, and system accessed to build the attack chain narrative.
Step 7: Cleanup and Reporting
Remove all testing artifacts from compromised systems:
- Delete uploaded tools, shells, and temporary files
- Remove any accounts created during testing
- Revert configuration changes made during exploitation
- Verify cleanup by re-scanning affected hosts
Prepare the penetration test report with executive summary, methodology description, finding details with CVSS scores, proof-of-concept evidence, and prioritized remediation recommendations.
Key Concepts
| Term | Definition |
|---|---|
| Rules of Engagement (RoE) | Formal document defining the scope, boundaries, testing hours, authorized actions, and escalation procedures for a penetration test |
| Pivot | Using a compromised host as a relay point to access additional network segments not directly reachable from the tester's position |
| Service Enumeration | The process of identifying running services, their versions, and configurations on discovered hosts to map the attack surface |
| Credential Spraying | Testing a small number of commonly used passwords against many accounts simultaneously to avoid account lockout thresholds |
| CVSS | Common Vulnerability Scoring System; an industry-standard framework for rating the severity of vulnerabilities on a 0-10 scale |
| Lateral Movement | Techniques used to move from one compromised system to another within a network, expanding the scope of access |
| Post-Exploitation | Activities performed after initial compromise including privilege escalation, persistence, credential harvesting, and data access |
Tools & Systems
- Nmap: Network discovery, port scanning, service enumeration, and vulnerability detection via the Nmap Scripting Engine (NSE)
- Metasploit Framework: Exploitation framework providing exploit modules, payloads, encoders, and post-exploitation tools for validated vulnerability exploitation
- CrackMapExec: Swiss-army knife for Windows/Active Directory environments supporting SMB, WinRM, LDAP, and MSSQL enumeration and exploitation
- Impacket: Python library providing low-level programmatic access to network protocols (SMB, MSRPC, Kerberos) used for relay attacks and remote execution
- Burp Suite: Web application proxy used when network services expose HTTP-based management interfaces
Common Scenarios
Scenario: Internal Network Penetration Test for a Financial Institution
Context: The client is a mid-size bank requiring PCI-DSS compliance. Scope includes the internal corporate network (10.10.0.0/16), excluding payment processing systems in a separate VLAN. Testing window is Monday-Friday 20:00-06:00 to minimize impact on operations.
Approach: 1. Perform ARP-based host discovery on accessible subnets and TCP SYN discovery for hosts with ICMP disabled 2. Conduct full port scans on all discovered hosts, prioritizing Windows servers and domain controllers 3. Enumerate SMB shares, SNMP communities, and web management interfaces for quick wins 4. Identify and exploit an unpatched Apache Tomcat instance with default credentials to gain initial foothold 5. Escalate privileges via a local Windows kernel vulnerability, then extract cached domain credentials with Mimikatz 6. Demonstrate lateral movement to the database server containing customer records, proving inadequate network segmentation 7. Document the complete attack path from initial access to sensitive data, with remediation steps for each vulnerability
Pitfalls:
- Scanning too aggressively during business hours and triggering IDS alerts or service disruptions
- Failing to verify that all target IPs are actually owned by the client before scanning
- Not documenting exploitation attempts that failed, missing the opportunity to report on effective controls
- Forgetting to clean up Meterpreter sessions and uploaded tools after testing
Output Format
## Finding: Unpatched Apache Tomcat with Default Credentials
**ID**: NET-001
**Severity**: Critical (CVSS 9.8)
**Affected Host**: 10.10.5.23 (tomcat-prod.internal.corp)
**Service**: Apache Tomcat 8.5.31 on port 8080
**CVE**: CVE-2019-0232
**Description**:
The Apache Tomcat instance on 10.10.5.23:8080 is running version 8.5.31, which is
vulnerable to CVE-2019-0232 (remote code execution via CGI Servlet). Additionally,
the Tomcat Manager interface is accessible with default credentials (tomcat:tomcat),
allowing deployment of arbitrary WAR files.
**Proof of Concept**:
1. Accessed http://10.10.5.23:8080/manager/html with credentials tomcat:tomcat
2. Deployed malicious WAR file containing a reverse shell payload
3. Obtained command execution as NT AUTHORITY\SYSTEM
**Impact**:
Full system compromise of the Tomcat server. From this host, the tester
pivoted to 3 additional systems on the same subnet using harvested credentials,
ultimately accessing the customer database containing 50,000+ records.
**Remediation**:
1. Immediately change default Tomcat Manager credentials
2. Upgrade Apache Tomcat to the latest stable release (currently 10.1.x)
3. Restrict access to the Tomcat Manager interface to authorized management IPs only
4. Implement network segmentation between web servers and database tier
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.
API Reference: Network Penetration Testing Agent
Overview
Automates network penetration testing: host discovery, TCP SYN scanning with service detection, vulnerability scanning with NSE scripts, SMB enumeration, and SSL auditing. For authorized penetration testing only.
Dependencies
| Package | Version | Purpose |
|---|---|---|
| python-nmap | >=0.7.1 | Nmap scan orchestration |
CLI Usage
# Full pentest
python agent.py --target 192.168.1.0/24 --ports 1-10000 --output report.json
# Host discovery only
python agent.py --target 10.0.0.0/24 --discovery-onlyKey Functions
host_discovery(target_network)
Discovers live hosts using ARP ping and ICMP echo with TCP ACK probes on common ports.
port_scan(target, ports, scan_type)
Performs TCP SYN scan with service version detection (-sV), OS detection (-O), and banner grabbing.
vulnerability_scan(target, ports)
Runs Nmap vulnerability scripts (vulners, vulscan) to identify CVEs for detected services.
smb_enumeration(target)
Enumerates SMB shares, users, and OS information via Nmap scripts on ports 139/445.
ssl_audit(target, port)
Audits SSL/TLS cipher suites and certificate details using ssl-enum-ciphers and ssl-cert.
dns_enumeration(domain)
Performs DNS subdomain brute-forcing using dns-brute NSE script.
classify_findings(scan_results, vuln_results)
Classifies vulnerabilities by severity (Critical, High, Medium) based on script output analysis.
Nmap Scan Types Used
| Argument | Purpose |
|---|---|
-sn -PE -PA | Host discovery (ping scan) |
-sS -sV -O | SYN scan with version and OS detection |
--script=vulners | CVE vulnerability lookup |
--script=smb-enum-shares | SMB share enumeration |
--script=ssl-enum-ciphers | SSL/TLS cipher audit |
--script=dns-brute | DNS subdomain enumeration |
Output Schema
{
"hosts": [{"ip": "...", "hostname": "..."}],
"services": [{"ip": "...", "services": [{"port": 80, "service": "http"}]}],
"vulnerabilities": [{"host": "...", "severity": "Critical", "details": {...}}],
"summary": {"critical": 3, "high": 12, "medium": 45}
}#!/usr/bin/env python3
# For authorized penetration testing and lab environments only
"""Network Penetration Testing Agent - Automates host discovery, port scanning, and vuln assessment."""
import json
import logging
import argparse
from datetime import datetime
import nmap
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
def host_discovery(target_network):
"""Discover live hosts on the network using ARP ping and ICMP."""
scanner = nmap.PortScanner()
scanner.scan(hosts=target_network, arguments="-sn -PE -PA21,22,80,443")
hosts = []
for host in scanner.all_hosts():
if scanner[host].state() == "up":
hosts.append({
"ip": host,
"hostname": scanner[host].hostname(),
"state": scanner[host].state(),
})
logger.info("Host discovery: %d live hosts on %s", len(hosts), target_network)
return hosts
def port_scan(target, ports="1-10000", scan_type="-sS"):
"""Perform TCP SYN scan with service version detection."""
scanner = nmap.PortScanner()
scanner.scan(hosts=target, ports=ports, arguments=f"{scan_type} -sV -O --script=banner")
results = []
for host in scanner.all_hosts():
host_info = {
"ip": host,
"hostname": scanner[host].hostname(),
"os_match": [],
"services": [],
}
if "osmatch" in scanner[host]:
host_info["os_match"] = [
{"name": m["name"], "accuracy": m["accuracy"]}
for m in scanner[host]["osmatch"][:3]
]
for proto in scanner[host].all_protocols():
for port in scanner[host][proto]:
svc = scanner[host][proto][port]
host_info["services"].append({
"port": port,
"protocol": proto,
"state": svc["state"],
"service": svc.get("name", ""),
"version": svc.get("version", ""),
"product": svc.get("product", ""),
"extrainfo": svc.get("extrainfo", ""),
})
results.append(host_info)
logger.info("Port scan: %d hosts, %d total services",
len(results), sum(len(h["services"]) for h in results))
return results
def vulnerability_scan(target, ports="1-1024"):
"""Run Nmap vulnerability scripts against target."""
scanner = nmap.PortScanner()
scanner.scan(
hosts=target, ports=ports,
arguments="-sV --script=vulners,vulscan/vulscan.nse --script-args vulscan/vulscan.db=cve.csv"
)
vulns = []
for host in scanner.all_hosts():
for proto in scanner[host].all_protocols():
for port in scanner[host][proto]:
svc = scanner[host][proto][port]
scripts = svc.get("script", {})
if scripts:
vulns.append({
"host": host,
"port": port,
"service": svc.get("name", ""),
"version": svc.get("version", ""),
"scripts": scripts,
})
logger.info("Vulnerability scan: %d services with script output", len(vulns))
return vulns
def smb_enumeration(target):
"""Enumerate SMB shares and users via Nmap scripts."""
scanner = nmap.PortScanner()
scanner.scan(
hosts=target, ports="139,445",
arguments="--script=smb-enum-shares,smb-enum-users,smb-os-discovery"
)
results = {}
for host in scanner.all_hosts():
for proto in scanner[host].all_protocols():
for port in [139, 445]:
if port in scanner[host][proto]:
scripts = scanner[host][proto][port].get("script", {})
results[host] = scripts
logger.info("SMB enumeration: %d hosts responded", len(results))
return results
def ssl_audit(target, port=443):
"""Audit SSL/TLS configuration using Nmap ssl-enum-ciphers."""
scanner = nmap.PortScanner()
scanner.scan(
hosts=target, ports=str(port),
arguments="--script=ssl-enum-ciphers,ssl-cert"
)
results = {}
for host in scanner.all_hosts():
if port in scanner[host].get("tcp", {}):
results[host] = scanner[host]["tcp"][port].get("script", {})
return results
def dns_enumeration(domain):
"""Perform DNS enumeration via Nmap dns-brute."""
scanner = nmap.PortScanner()
scanner.scan(hosts=domain, arguments="--script=dns-brute")
return scanner.get_nmap_last_output()
def classify_findings(scan_results, vuln_results):
"""Classify and prioritize all findings by severity."""
findings = []
for vuln in vuln_results:
severity = "Medium"
scripts = vuln.get("scripts", {})
script_text = json.dumps(scripts).lower()
if "critical" in script_text or "cve-2" in script_text:
severity = "Critical"
elif "high" in script_text:
severity = "High"
findings.append({
"host": vuln["host"],
"port": vuln["port"],
"service": vuln["service"],
"severity": severity,
"details": scripts,
})
findings.sort(key=lambda x: {"Critical": 0, "High": 1, "Medium": 2, "Low": 3}.get(x["severity"], 4))
return findings
def generate_report(hosts, scan_results, vuln_findings, smb_results):
"""Generate network penetration test report."""
report = {
"timestamp": datetime.utcnow().isoformat(),
"scope": f"{len(hosts)} live hosts discovered",
"hosts": hosts,
"services": scan_results,
"vulnerabilities": vuln_findings,
"smb_enumeration": smb_results,
"summary": {
"critical": len([f for f in vuln_findings if f["severity"] == "Critical"]),
"high": len([f for f in vuln_findings if f["severity"] == "High"]),
"medium": len([f for f in vuln_findings if f["severity"] == "Medium"]),
},
}
print(f"NETWORK PENTEST REPORT: {len(hosts)} hosts, {len(vuln_findings)} vulnerabilities")
return report
def main():
parser = argparse.ArgumentParser(description="Network Penetration Testing Agent")
parser.add_argument("--target", required=True, help="Target host/network CIDR")
parser.add_argument("--ports", default="1-10000", help="Port range to scan")
parser.add_argument("--discovery-only", action="store_true", help="Only perform host discovery")
parser.add_argument("--output", default="network_pentest_report.json")
args = parser.parse_args()
hosts = host_discovery(args.target)
if args.discovery_only:
with open(args.output, "w") as f:
json.dump({"hosts": hosts}, f, indent=2)
return
scan_results = []
vuln_results = []
smb_results = {}
for host in hosts:
ip = host["ip"]
scan = port_scan(ip, args.ports)
scan_results.extend(scan)
vulns = vulnerability_scan(ip)
vuln_results.extend(vulns)
smb = smb_enumeration(ip)
smb_results.update(smb)
findings = classify_findings(scan_results, vuln_results)
report = generate_report(hosts, scan_results, findings, smb_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()