Thanks to visit codestin.com
Credit goes to github.com

Skip to content

coffeegist/opfor-iac

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

OpFor IaC - Multi-Project Kali Linux Penetration Testing Infrastructure

This repository contains Infrastructure as Code (IaC) for spinning up isolated Kali Linux penetration testing environments in AWS with integrated S3 storage using Terraform. Supports multiple simultaneous projects with complete isolation.

πŸ— Repository Structure

opfor-iac/
β”œβ”€β”€ storage/                    # Reusable storage module (S3, IAM)
β”œβ”€β”€ instance/                   # Reusable instance module (EC2, Security Groups)  
β”œβ”€β”€ projects/                   # Project-specific configurations
β”‚   β”œβ”€β”€ client-acme/           # Example: ACME Corp assessment
β”‚   β”‚   β”œβ”€β”€ storage/           # β†’ symlink to ../../storage
β”‚   β”‚   β”œβ”€β”€ instance/          # β†’ symlink to ../../instance
β”‚   β”‚   β”œβ”€β”€ storage.tfvars     # Client-specific storage config
β”‚   β”‚   β”œβ”€β”€ instance.tfvars    # Client-specific instance config
β”‚   β”‚   β”œβ”€β”€ deploy.sh          # Deployment helper script
β”‚   β”‚   └── README.md          # Project-specific documentation
β”‚   └── client-beta/           # Example: Beta Corp assessment
β”‚       └── ...
β”œβ”€β”€ create-project.sh          # Script to create new projects
└── README.md                  # This file

🎯 Features

  • Multi-project isolation - Complete separation between client assessments
  • Persistent storage - S3 buckets survive instance destruction
  • Cost optimization - Destroy expensive compute, keep cheap storage
  • Pre-configured tools - Kali Linux with penetration testing toolkit
  • S3 filesystem mounting - Assessment data automatically stored in S3
  • Security-focused - Encrypted storage, IAM roles, restricted access

πŸ— Architecture

The infrastructure uses a modular approach with shared components for multiple projects:

Storage Module (storage/)

  • S3 bucket for assessment data with folder structure
  • IAM roles for secure S3 access from Kali instances
  • Lifecycle policies for cost optimization
  • Long-lived - persists across multiple Kali deployments

Instance Module (instance/)ali Linux Penetration Testing Infrastructure

This repository contains Infrastructure as Code (IaC) for spinning up a Kali Linux penetration testing environment in AWS with integrated S3 storage using Terraform.

οΏ½ Architecture

The infrastructure is split into two components for better lifecycle management:

Storage (storage/)

  • S3 bucket for assessment data with folder structure
  • IAM roles for secure S3 access from Kali instances
  • Lifecycle policies for cost optimization
  • Long-lived - persists across multiple Kali deployments

Instance (instance/)

  • Kali Linux EC2 instance with pre-configured tools
  • Security groups optimized for pentest operations
  • S3 filesystem mounting for seamless data access
  • Short-lived - create/destroy as needed

🎯 Features

  • Separated storage and compute for cost optimization
  • Automated S3 mounting at /mnt/assessment/ on Kali box
  • Pre-configured penetration testing tools
  • VNC and RDP access for GUI operations
  • Assessment folder structure (scope, reconnaissance, vulnerabilities, etc.)
  • Encrypted storage and secure IAM access
  • SSH key pair generation for secure access

πŸ›  Prerequisites

  • Terraform >= 1.0
  • AWS CLI configured with appropriate credentials
  • AWS account with appropriate permissions
  • VNC client (for GUI access) - recommended: RealVNC, TightVNC, or macOS built-in Screen Sharing

πŸš€ Quick Start (Multi-Project)

Step 1: Create a New Project

Use the automated script to create a new client project:

./create-project.sh client-name

This will:

  • Create a new project directory under projects/client-name/
  • Set up symlinks to the shared storage and instance modules
  • Generate client-specific configuration files
  • Create deployment helper scripts

Step 2: Deploy Your Project

Navigate to your project directory and use the deployment helper:

cd projects/client-name/
./deploy.sh

The helper script will guide you through:

  1. Storage deployment - Creates S3 bucket and IAM roles
  2. Instance configuration - Updates variables for your specific needs
  3. Instance deployment - Launches the Kali Linux environment

Step 3: Access Your Kali Environment

After deployment completes:

  1. SSH Access:

    ssh -i client-name-key.pem kali@<public-ip>
  2. VNC Access (for GUI):

    • Connect to <public-ip>:5901
    • Default VNC password: kali123
  3. Assessment Data:

    • Located at /mnt/assessment/ on the Kali instance
    • Automatically backed up to S3

πŸš€ Manual Deployment (Legacy)

If you prefer manual deployment or need to understand the underlying process:

  1. Navigate to storage directory

    cd storage/
  2. Configure your variables

    cp terraform.tfvars.example terraform.tfvars
    # Edit with your client/assessment name
  3. Deploy storage

    terraform init
    terraform plan
    terraform apply
  4. Note the outputs - you'll need these for the instance deployment:

    terraform output

Step 2: Deploy Kali Instance

This creates the temporary Kali box that mounts your persistent storage.

  1. Navigate to instance directory

    cd ../instance/
  2. Configure variables

    cp terraform.tfvars.example terraform.tfvars
    # Edit with storage outputs and your preferences

    Important: Use the storage outputs in your instance terraform.tfvars:

    s3_bucket_name           = "output-from-storage-module"
    s3_instance_profile_name = "output-from-storage-module"
  3. Deploy instance

    terraform init
    terraform plan
    terraform apply

Step 3: Access Your Environment

SSH Access (Recommended):

ssh -i keys/opfor-kali-key.pem kali@<public-ip>

VNC Access (GUI):

  • Host: <public-ip>
  • Port: 5901
  • Password: Your kali_password from terraform.tfvars

Assessment Data:

  • Mounted at: /mnt/assessment/
  • Folders: scope/, reconnaissance/, vulnerabilities/, exploitation/, reports/, evidence/
  • Usage: Files saved here persist even when instance is destroyed

Step 4: Working with Assessment Data

# Example workflow on Kali box
cd /mnt/assessment/

# Store target information
echo "10.0.0.0/24" > scope/targets.txt

# Run reconnaissance
nmap -oA reconnaissance/network-scan 10.0.0.0/24

# Store vulnerability scan results
nuclei -l scope/targets.txt -o vulnerabilities/nuclei-results.txt

# Draft reports
vim reports/assessment-findings.md

πŸ“‹ What Gets Installed

Base System

  • Latest Kali Linux AMI
  • Desktop environment (XFCE)
  • VNC server (TightVNC)
  • RDP server (xrdp)

Penetration Testing Tools

  • Web Application Testing: gobuster, ffuf, nikto, sqlmap, wpscan
  • Network Scanning: nmap, rustscan, massdns
  • Vulnerability Scanning: nuclei, OpenVAS
  • Subdomain Enumeration: subfinder, amass
  • HTTP Toolkit: httpx
  • Wordlists: SecLists collection
  • Post-Exploitation: impacket, crackmapexec

Development Tools

  • Python 3 + pip
  • Go programming language
  • Node.js + npm
  • Docker + Docker Compose
  • Git, vim, tmux

πŸ”§ Configuration

Instance Types

  • t3.micro: Minimal testing (free tier eligible)
  • t3.small: Light penetration testing
  • t3.medium: Recommended for most use cases
  • t3.large/xlarge: Heavy workloads or multiple concurrent tasks

Security Configuration

⚠️ IMPORTANT SECURITY NOTE: By default, the security group allows access from anywhere (0.0.0.0/0). For production use, restrict access to your IP:

allowed_ssh_cidr_blocks = ["YOUR.IP.ADDRESS/32"]

Storage

  • Default: 50GB encrypted EBS volume
  • Adjustable via root_volume_size variable
  • Automatically deleted when instance is terminated

🌐 Access Methods

SSH Access (Recommended)

ssh -i keys/opfor-kali-key.pem kali@<public-ip>

VNC Access (GUI)

  • Host: <public-ip>
  • Port: 5901
  • Password: Set via kali_password variable
  • URL: vnc://<public-ip>:5901

RDP Access (Alternative GUI)

  • Host: <public-ip>
  • Port: 3389
  • Username: kali
  • Password: Set via kali_password variable

πŸ“ Directory Structure

/home/kali/
β”œβ”€β”€ Desktop/           # Desktop shortcuts
β”œβ”€β”€ Documents/         # Documentation
β”œβ”€β”€ Downloads/         # Downloaded files
β”œβ”€β”€ Tools/            # Custom tools and scripts
β”œβ”€β”€ Wordlists/        # SecLists and custom wordlists
β”œβ”€β”€ Scripts/          # Utility scripts
└── Reports/          # Penetration testing reports

πŸ›‘ Security Best Practices

  1. Change default passwords immediately after deployment
  2. Restrict source IP ranges in security groups
  3. Use SSH key authentication instead of passwords
  4. Enable MFA on your AWS account
  5. Regularly update the system and tools
  6. Monitor costs to avoid unexpected charges
  7. Terminate instances when not in use

πŸ’° Cost Estimation

Approximate monthly costs (us-east-1):

  • t3.micro: ~$8.50/month (free tier eligible)
  • t3.small: ~$17/month
  • t3.medium: ~$34/month
  • t3.large: ~$67/month

Additional costs:

  • EBS Storage (50GB): ~$5/month
  • Elastic IP: Free when attached to running instance
  • Data Transfer: Varies based on usage

🧹 Cleanup and Destruction

Complete Infrastructure Removal

When you're done with your penetration testing, clean up all resources to avoid ongoing charges:

  1. Save any important data first

    # SSH into the instance and backup reports/scripts
    ssh -i keys/opfor-kali-key.pem kali@<public-ip>
    
    # Copy important files to your local machine
    scp -i keys/opfor-kali-key.pem -r kali@<public-ip>:/home/kali/Reports/ ./local-reports/
  2. Destroy all infrastructure

    terraform destroy
    • Type yes when prompted
    • This will permanently delete ALL resources
    • Cannot be undone!
  3. Clean up local files (optional)

    # Remove Terraform state and keys
    rm -rf .terraform/
    rm -f terraform.tfstate*
    rm -rf keys/
    
    # Keep configuration for future use
    # Keep: terraform.tfvars, *.tf files

Partial Cleanup Options

Stop instance (keeps data, stops compute charges):

aws ec2 stop-instances --instance-ids $(terraform output -raw kali_box_instance_id)

Start stopped instance:

aws ec2 start-instances --instance-ids $(terraform output -raw kali_box_instance_id)

Remove only specific resources:

# Remove only the EC2 instance (keeps security groups, keys, etc.)
terraform destroy -target=aws_instance.kali_box

# Remove only the Elastic IP
terraform destroy -target=aws_eip.kali_eip

Verification of Cleanup

After running terraform destroy, verify all resources are removed:

# Check for any remaining EC2 instances
aws ec2 describe-instances --filters "Name=tag:Name,Values=opfor-kali-box" --query 'Reservations[*].Instances[*].[InstanceId,State.Name]' --output table

# Check for any remaining security groups
aws ec2 describe-security-groups --filters "Name=group-name,Values=opfor-kali-*" --output table

# Check for any remaining key pairs
aws ec2 describe-key-pairs --filters "Name=key-name,Values=opfor-kali-key" --output table

# Check for any remaining Elastic IPs
aws ec2 describe-addresses --filters "Name=tag:Name,Values=opfor-kali-eip" --output table

If any resources remain, manually delete them through the AWS Console or CLI to avoid ongoing charges.

πŸ“ Outputs

After successful deployment, Terraform provides:

  • Public IP address
  • SSH connection command
  • VNC connection details
  • Instance ID and other metadata

πŸ” Troubleshooting

Common Issues and Solutions

Cannot connect via SSH

# Check if the instance is running
aws ec2 describe-instances --filters "Name=tag:Name,Values=opfor-kali-box"

# Verify key permissions
chmod 600 keys/opfor-kali-key.pem

# Test connectivity
telnet <public-ip> 22

VNC connection fails

# SSH into the box and check VNC status
ssh -i keys/opfor-kali-key.pem kali@<public-ip>
sudo systemctl status vncserver@1

# Restart VNC if needed
sudo systemctl restart vncserver@1

# Check if port is listening
sudo netstat -tlnp | grep 5901

Instance not accessible after deployment

  1. Wait 10-15 minutes for full initialization
  2. Check AWS Console for instance status
  3. Verify security group rules allow your IP
  4. Check CloudWatch logs for any errors

High AWS costs

# Check instance type (should match your terraform.tfvars)
aws ec2 describe-instances --instance-ids <instance-id>

# Stop instance when not in use (will lose data on ephemeral storage)
aws ec2 stop-instances --instance-ids <instance-id>

# Terminate when done (PERMANENT - will destroy all data)
terraform destroy

πŸ›  Management Commands

Using Terraform Commands

# Check current infrastructure status
terraform show

# View all outputs
terraform output

# Get specific output (e.g., public IP)
terraform output kali_box_public_ip

# Refresh state (useful if you made manual changes)
terraform refresh

# Import existing resources (if needed)
terraform import aws_instance.kali_box <instance-id>

Using the Makefile

This repository includes a Makefile for common operations:

# Show all available commands
make help

# Initialize and validate
make init
make validate

# Plan and apply changes
make plan
make apply

# Quick SSH connection
make ssh

# Show VNC connection info
make vnc

# Check infrastructure status
make status

# Clean up everything
make destroy

AWS CLI Management

# Check instance status
aws ec2 describe-instances --filters "Name=tag:Name,Values=opfor-kali-box" --query 'Reservations[*].Instances[*].[InstanceId,State.Name,PublicIpAddress]' --output table

# Stop instance (keeps EBS volume, stops billing for compute)
aws ec2 stop-instances --instance-ids <instance-id>

# Start stopped instance
aws ec2 start-instances --instance-ids <instance-id>

# View instance console output (useful for debugging boot issues)
aws ec2 get-console-output --instance-id <instance-id>

# Check CloudWatch logs
aws logs describe-log-groups --log-group-name-prefix "/aws/ec2"

πŸ’° Cost Management

Cost Optimization Tips

  1. Use appropriate instance types:

    • t3.micro: ~$8.50/month (free tier eligible for first year)
    • t3.small: ~$17/month (good for light testing)
    • t3.medium: ~$34/month (recommended for regular use)
  2. Stop instances when not in use:

    # Stop (preserves data on EBS)
    aws ec2 stop-instances --instance-ids <instance-id>
    
    # Start when needed
    aws ec2 start-instances --instance-ids <instance-id>
  3. Use Spot Instances for cost savings (advanced):

    • Add to variables.tf and main.tf for ~70% cost reduction
    • Risk: Instance can be terminated by AWS
  4. Monitor costs:

    # Set up billing alerts in AWS Console
    # Use AWS Cost Explorer to track spending
    # Consider AWS Budgets for automatic alerts

Estimated Monthly Costs (us-east-1)

Component Cost
t3.micro instance $8.50
t3.medium instance $34.00
EBS storage (50GB) $5.00
Elastic IP (attached) $0.00
Data transfer (estimated) $1-10

Total estimated range: $14-50/month depending on instance type and usage

πŸ“š Useful Commands

# Check system status
sudo systemctl status vncserver@1
sudo systemctl status xrdp

# Restart VNC server
sudo systemctl restart vncserver@1

# Update all tools
sudo apt update && sudo apt upgrade -y

# Show installed tools
/home/kali/Scripts/pentest-toolkit.sh

🎯 Project Management

Multiple Simultaneous Assessments

You can run multiple client assessments simultaneously:

# Create projects for different clients
./create-project.sh acme-corp
./create-project.sh beta-industries  
./create-project.sh gamma-solutions

# Deploy each project independently
cd projects/acme-corp/ && ./deploy.sh
cd projects/beta-industries/ && ./deploy.sh
cd projects/gamma-solutions/ && ./deploy.sh

Each project gets:

  • Isolated S3 bucket - Complete data separation
  • Independent infrastructure - Deploy/destroy separately
  • Custom configuration - Different instance types, regions, etc.
  • Project-specific documentation - Client context and scope

Project Lifecycle Management

# List all projects
ls -la projects/

# Check project status
cd projects/client-name/
terraform plan  # in both storage/ and instance/

# Archive completed assessments
mv projects/completed-client/ archive/

# Clean up individual projects
cd projects/client-name/
terraform destroy  # Destroys instances but preserves S3 data

Scaling Operations

For larger penetration testing teams:

  1. Regional Distribution:

    # Create projects in different AWS regions
    ./create-project.sh client-west-coast
    # Edit projects/client-west-coast/storage.tfvars (set aws_region = "us-west-2")
  2. Team Collaboration:

    • Use Terraform remote state (S3 backend)
    • Implement proper IAM role separation
    • Share project credentials securely
  3. Automated Reporting:

    • S3 data can be processed by Lambda functions
    • Generate automated compliance reports
    • Integration with finding management tools

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

⚠️ Disclaimer

This infrastructure is designed for authorized penetration testing only. Users are responsible for:

  • Compliance with applicable laws and regulations
  • Proper authorization before testing any systems
  • Securing their AWS environment
  • Managing costs and resource usage

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ†˜ Support

For issues and questions:

  1. Check the troubleshooting section
  2. Review AWS CloudWatch logs
  3. Open an issue in this repository

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published