Skip to content

golso4243/python-ftp-server-cybersec-lab

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

10 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

FTP Server and Client - Cybersecurity Lab

This project provides a complete FTP server and client implementation for cybersecurity education and network analysis. It allows you to observe unencrypted file transfers in Wireshark and understand FTP protocol behavior.



🚨 Security Warning

This FTP implementation transmits data unencrypted for educational purposes only. Never use this setup in production environments. Always use encrypted protocols (FTPS/SFTP) for real-world applications.



πŸ“‹ Table of Contents

  1. Features

  2. Requirements

  3. Installation

  4. Virtual Environment Setup

  5. Configuration

  6. Windows Firewall Setup

  7. Folder Permissions (Windows)

  8. Usage

  9. Wireshark Analysis

  10. Troubleshooting

  11. Lab Exercises

  12. Cleanup

  13. Additional Notes

  14. Support



✨ Features

  • Custom logging for all FTP operations (connect, login, upload, download, commands)
  • DummyAuthorizer for custom credentials (no Windows user dependency)
  • Automatic server directory creation with sample structure
  • Configurable permissions and port settings
  • Real-time terminal output of all activities
  • Comprehensive log file generation

  • Command-line interface for quick operations
  • Interactive shell mode with FTP-like commands
  • Support for upload, download, directory listing, and navigation
  • Environment variable configuration
  • Both single-machine and multi-machine setup support

  • Creates realistic business files (employee records, sales data, system logs)
  • Multiple file formats (CSV, JSON, TXT, INI, LOG)
  • Dynamic content with randomized data and timestamps
  • Varied file sizes for comprehensive FTP testing
  • Auto-organized directory structure creation
  • Safe fictional data for educational use



πŸ› οΈ Requirements

  • Python 3.7 or higher (current version: 3.13.7)
  • Windows, Linux, or macOS
  • Administrator privileges (for port binding and firewall configuration)
  • Wireshark (for traffic analysis)



πŸ“¦ Installation

⚠️ HIGHLY RECOMMENDED: Run terminal as administrator.

From a terminal (PowerShell, CMD, or bash):

  1. Create and move into the project folder:

    mkdir ftp_cybersec_lab
    cd ftp_cybersec_lab

  1. Clone the repository into the current folder:

    git clone https://github.com/golso4243/python-ftp-server-cybersec-lab .

    ⚠️ The trailing . makes sure files are cloned directly into ftp_cybersec_lab instead of a nested folder.


  1. Open the project in VS Code: code .

    πŸ’‘ Tip: Enable the code command

    • The code command lets you open VS Code from your terminal (e.g., with code .).
    • On Windows: During installation of VS Code, check β€œAdd to PATH” so the code command works in PowerShell or CMD.
    • If you missed it, open VS Code, press Ctrl+Shift+P, search for β€œShell Command: Install 'code' command in PATH”, and run it.
    • After this, restart your terminal and you’ll be able to type code . to open the current folder (ftp_cybersec_lab) in VS Code.

  1. Set up virtual environment (RECOMMENDED)

  1. Install Python dependencies: pip install -r requirements.txt

  1. Verify installation: python -c "import pyftpdlib; print('Dependencies installed successfully')"



🐍 Virtual Environment Setup

⚠️ HIGHLY RECOMMENDED: Use a virtual environment to isolate project dependencies and prevent conflicts with system packages.

Why Use Virtual Environments?

  • Dependency Isolation: Prevents conflicts between different Python projects
  • Security: Reduces risk of system-wide package pollution
  • Reproducibility: Ensures consistent environment across different systems
  • Clean Uninstall: Easy to remove all project dependencies by deleting the virtual environment

Creating and Using Virtual Environment

Windows:

# Navigate to project directory
# Skip this step if the project directory is already open in your IDE.
cd ftp_cybersec_lab

# Create virtual environment
python -m venv ftp_lab_venv

# Activate virtual environment
ftp_lab_venv\Scripts\activate

# Verify activation (you should see (ftp_lab_venv) in your prompt)
where python

# Install dependencies
pip install -r requirements.txt

# When done working, deactivate
deactivate

Linux/macOS:

# Navigate to project directory
cd ftp_cybersec_lab

# Create virtual environment

python3 -m venv ftp_lab_venv

# Activate virtual environment

source ftp_lab_venv/bin/activate

# Verify activation (you should see (ftp_lab_venv) in your prompt)

which python

# Install dependencies

pip install -r requirements.txt

# When done working, deactivate

deactivate

Alternative: Using conda (if installed):

# Create conda environment
conda create -n ftp_lab_venv python=3.9

# Activate environment
conda activate ftp_lab_venv

# Install dependencies
pip install -r requirements.txt

# Deactivate when done
conda deactivate

Virtual Environment Best Practices

  1. Always activate before working:

    # Windows
    ftp_lab_venv\Scripts\activate
    
    # Linux/macOS
    source ftp_lab_venv/bin/activate

  1. Verify activation:
    • Your command prompt should show (ftp_lab_venv) prefix
    • python --version should show your expected Python version
    • pip list should show only project dependencies

  1. Update requirements.txt after adding packages: pip freeze > requirements.txt

  1. Recreate environment from scratch (if needed):
    # Windows
    # If "rmdir" command does not work > close IDE, delete from folder, reopen IDE, recreate virtual environment
    rmdir /s ftp_lab_venv
    python -m venv ftp_lab_venv
    ftp_lab_venv\Scripts\activate
    pip install -r requirements.txt
    
    # Linux/macOS
    rm -rf ftp_lab_venv
    python3 -m venv ftp_lab_venv
    source ftp_lab_venv/bin/activate
    pip install -r requirements.txt

IDE Integration

VS Code:

  1. Open project folder in VS Code
  2. Press Ctrl+Shift+P (Cmd+Shift+P on Mac)
  3. Type "Python: Select Interpreter"
  4. Choose the interpreter from your virtual environment:
    • Windows: ftp_lab_venv\Scripts\python.exe
    • Linux/macOS: ftp_lab_venv/bin/python

PyCharm:

  1. File β†’ Settings β†’ Project β†’ Python Interpreter
  2. Click gear icon β†’ Add
  3. Select "Existing Environment"
  4. Browse to your virtual environment's Python executable



βš™οΈ Configuration

Environment Variables

The project uses .env.development for configuration. Default settings:

FTP_HOST=127.0.0.1          # Server IP address
FTP_PORT=2121               # FTP port (non-standard for lab safety)
FTP_USER=labuser            # FTP username
FTP_PASSWORD=labpass123     # FTP password
FTP_SERVER_ROOT=ftp_server_root  # Server directory name
FTP_PERMISSIONS=elradfmwMT  # User permissions

Environment Setup

Before running the application, make sure to set up your environment variables.

Copy the development environment .env.development file to .env:

Linux / macOS / Git Bash

cp .env.development .env

Windows (PowerShell or Command Prompt)

copy .env.development .env

You can delete the .env.development afterwards.


Multi-Machine Setup

For testing across different machines:

  1. On the server machine:
    • Change FTP_HOST=0.0.0.0 in .env to bind to all interfaces
    • Note the server's IP address (e.g., ipconfig on Windows, ip addr on Linux)

  1. On the client machine:
    • Change FTP_HOST=<server-ip-address> in .env
    • Example: FTP_HOST=192.168.1.100



πŸ”₯ Windows Firewall Setup

⚠️ CRITICAL: Always disable or delete these rules after lab completion for security!

Creating Firewall Rules

  1. Open Windows Defender Firewall with Advanced Security:
    • Press Win + R, type wf.msc, press Enter
    • Or search "Windows Defender Firewall with Advanced Security"

  1. Create Inbound Rule:
    - Right-click "Inbound Rules" β†’ "New Rule..."
    - Rule Type: Port
    - Protocol: TCP
    - Specific Local Ports: 2121
    - Action: Allow the connection
    - Profile: Check all (Domain, Private, Public)
    - Name: "FTP Lab Server Port 2121"
    - Description: "Temporary rule for cybersecurity lab - DELETE AFTER USE"
    

  1. Create Outbound Rule:
    - Right-click "Outbound Rules" β†’ "New Rule..."
    - Rule Type: Port
    - Protocol: TCP
    - Specific Local Ports: 2121
    - Action: Allow the connection
    - Profile: Check all (Domain, Private, Public)
    - Name: "FTP Lab Client Port 2121"
    - Description: "Temporary rule for cybersecurity lab - DELETE AFTER USE"
    

  1. Allow FTP Data Ports (Passive Mode):
    - Create additional inbound/outbound rules for ports 60000-65535
    - Or create a rule for "FTP Server" program instead
    

Alternative: Command Line Method

Run as Administrator:

# Allow inbound FTP control port
netsh advfirewall firewall add rule name="FTP Lab Inbound" dir=in action=allow protocol=TCP localport=2121

# Allow outbound FTP control port
netsh advfirewall firewall add rule name="FTP Lab Outbound" dir=out action=allow protocol=TCP localport=2121

# Allow passive data ports (optional - for better compatibility)
netsh advfirewall firewall add rule name="FTP Lab Data Ports" dir=in action=allow protocol=TCP localport=60000-65535



πŸ“ Folder Permissions (Windows)

Using icacls Command

If you encounter permission issues with the FTP server directory:

# Grant full control to the current user
icacls ftp_server_root /grant %USERNAME%:F /T

# Grant read/write permissions to specific user
icacls ftp_server_root /grant "labuser":(OI)(CI)RX /T

# View current permissions
icacls ftp_server_root

# Reset permissions to defaults (if needed)
icacls ftp_server_root /reset /T

# Grant permissions to Everyone (least secure - only for isolated lab)
icacls ftp_server_root /grant Everyone:F /T

Permission Parameters Explained:

  • F = Full control
  • RX = Read and execute
  • RW = Read and write
  • (OI) = Object inherit
  • (CI) = Container inherit
  • /T = Apply to all files and subdirectories

GUI Method:

  1. Right-click ftp_server_root folder β†’ Properties
  2. Security tab β†’ Edit β†’ Add
  3. Enter "Everyone" or specific username
  4. Grant "Full control" permissions
  5. Apply to subfolders and files



πŸš€ Usage

Prerequisites

⚠️ IMPORTANT: Always activate your virtual environment before running scripts!

# Windows
ftp_lab_venv\Scripts\activate

# Linux/macOS
source ftp_lab_venv/bin/activate

Starting the FTP Server

python ftp_server.py

Expected output:

============================================================
           FTP SERVER - CYBERSECURITY LAB
============================================================
Server Host: 127.0.0.1
Server Port: 2121
Username: labuser
Password: labpass123
Server Root: ftp_server_root
Permissions: elradfmwMT
Log File: logs/ftp_server_20240904_143022.log
============================================================

[2024-09-04 14:30:22] Starting FTP server...
Server listening on 127.0.0.1:2121
Press Ctrl+C to stop the server

WARNING: This server transmits data unencrypted for lab purposes!
Monitor traffic with Wireshark on port 2121
------------------------------------------------------------

Confirm FTP services running: netstat -an | findstr 2121


Using the FTP Client

Interactive Mode:

python ftp_client.py

Interactive commands:

FTP> help                    # Show all commands
FTP> ls                      # List current directory
FTP> upload test.txt         # Upload file
FTP> download welcome.txt    # Download file
FTP> cd uploads             # Change directory
FTP> pwd                    # Show current directory
FTP> stats                  # Show connection status
FTP> quit                   # Exit client

Command Line Mode:

# Upload files
python ftp_client.py upload local_file.txt
python ftp_client.py upload ftp_test_data/app_config.json uploads/config.json

# Download files
python ftp_client.py download welcome.txt
python ftp_client.py download uploads/config.json local_config.json

# List directories
python ftp_client.py ls
python ftp_client.py ls uploads

# Connect to different server
python ftp_client.py connect 192.168.1.100 2121 testuser testpass

Creating Test Data

Use the provided test data generator script to create realistic files for testing: python generate_test_data.py


This will create the ftp_test_data/ directory in the root folder with the following files:

  • employee_records.csv - Employee database records (CSV format)
  • app_config.json - Application configuration (JSON format)
  • sales_data.csv - Sales transaction data (CSV format)
  • system.log - System activity logs (LOG format)
  • project_documentation.txt - Project documentation (TXT format)
  • network_config.ini - Network configuration (INI format)

The generator creates realistic test data with various file formats and sizes, perfect for comprehensive FTP testing. All data is fictional and safe for educational use.


Manual Creation (Alternative): If you prefer to create test files manually:

mkdir ftp_test_data
echo "This is a test file for FTP transfer" > ftp_test_data/test.txt
echo "Sensitive document content here" > ftp_test_data/confidential.txt



πŸ“Š Wireshark Analysis

Starting Wireshark Capture

  1. Open Wireshark

  1. Select Network Interface:

    - For localhost: Select "Loopback" or "lo0"
    - For network: Select your network adapter
    

  1. Apply Filter: tcp.port == 2121 or ftp or ftp-data

  1. Start Capture

What to Observe

FTP Control Channel (Port 2121):

  • Connection establishment: TCP 3-way handshake
  • Authentication: USER and PASS commands in plaintext
  • Commands: LIST, PWD, CWD, STOR, RETR commands
  • Responses: Server response codes (220, 230, 150, 226, etc.)

FTP Data Channel (Ephemeral Ports):

  • File content: Complete file data in plaintext
  • Directory listings: Detailed file information
  • Passive mode setup: PASV command and data port negotiation

Sample Wireshark Filters:

# FTP commands only
ftp.request

# FTP responses only

ftp.response

# File transfer data

ftp-data

# Specific file transfers

ftp-data and tcp contains "filename"

# Authentication attempts

ftp.request.command == "USER" or ftp.request.command == "PASS"


Key Security Observations:

  1. Credentials transmitted in plaintext
  2. File contents visible without encryption
  3. Directory structure exposed
  4. No integrity protection



πŸ”§ Troubleshooting

Common Issues and Solutions

Virtual Environment Issues


Error: 'python' is not recognized as an internal or external command

Solution: Activate virtual environment first:

# Windows
ftp_lab_venv\Scripts\activate

# Linux/macOS
source ftp_lab_venv/bin/activate

ModuleNotFoundError

ModuleNotFoundError: No module named 'pyftpdlib'

Solutions:

  • Ensure virtual environment is activated
  • Install dependencies: pip install -r requirements.txt
  • Verify you're in the correct environment: pip list

Server Won't Start

Error: Permission denied to bind to port 2121

Solution: Run as administrator or use a port > 1024


Connection Refused

Connection failed: [Errno 10061] No connection could be made

Solutions:


Upload/Download Failures

Upload failed: 550 Permission denied

Solutions:

  • Check folder permissions with icacls
  • Verify FTP_PERMISSIONS in .env
  • Ensure server directory exists and is writable

Passive Mode Issues

425 Can't open data connection

Solutions:


Environment Variables Not Loading

Solutions:

  • Verify .env file exists
  • Check file encoding (should be UTF-8)
  • Ensure no spaces around = in env file



🎯 Lab Exercises

Exercise 1: Basic Protocol Analysis

  1. Start server and capture traffic
  2. Connect client and authenticate
  3. Analyze: Find credentials in packet capture
  4. Question: How could this be secured?

Exercise 2: File Transfer Monitoring

  1. Upload a text file with sensitive content
  2. Download the same file
  3. Analyze: Locate file content in packets
  4. Question: What data leakage risks exist?

Exercise 3: Attack Simulation

  1. Use wrong credentials multiple times
  2. Observe server logs and Wireshark
  3. Analyze: How are failed attempts logged?
  4. Question: What brute force indicators exist?

Exercise 4: Network Reconnaissance

  1. Use different FTP commands (LIST, PWD, CWD)
  2. Analyze: What system information is revealed?
  3. Question: How could an attacker map the system?

Exercise 5: Multi-Machine Setup

  1. Configure server on one machine, client on another
  2. Analyze traffic between machines
  3. Question: What additional network risks appear?



🧹 Cleanup

After Lab Completion

1. Deactivate Virtual Environment

deactivate

2. Remove Firewall Rules

GUI Method:

  • Open Windows Defender Firewall with Advanced Security
  • Delete "FTP Lab Server Port 2121" rules
  • Delete "FTP Lab Client Port 2121" rules
  • Delete any passive port rules created

Command Line Method:

# Remove firewall rules
netsh advfirewall firewall delete rule name="FTP Lab Inbound"
netsh advfirewall firewall delete rule name="FTP Lab Outbound"  
netsh advfirewall firewall delete rule name="FTP Lab Data Ports"

3. Remove Virtual Environment (Optional)

# Windows
rmdir /s ftp_lab_venv

# Linux/macOS

rm -rf ftp_lab_venv

4. Remove Server Directory (Optional)

# Windows
rmdir /s ftp_server_root

# Linux/Mac
rm -rf ftp_server_root

5. Clean Log Files

# Remove all log files
rmdir /s logs       # Windows
rm -rf logs         # Linux/Mac

6. Security Verification

  • Confirm no FTP services running: netstat -an | findstr 2121

  • Verify firewall rules removed

  • Check for any remaining test files with sensitive content



πŸ“ Additional Notes

Complete Project Structure

ftp_cybersec_lab/
β”œβ”€β”€ ftp_server.py              # Main server application
β”œβ”€β”€ ftp_client.py              # Main client application
β”œβ”€β”€ generate_test_data.py      # Test data generator script
β”œβ”€β”€ .env                       # Configuration settings
β”œβ”€β”€ requirements.txt           # Python dependencies
β”œβ”€β”€ README.md                  # Project documentation
β”œβ”€β”€ ftp_lab_venv/              # Virtual environment (created by user)
β”œβ”€β”€ ftp_server_root/           # Server directory (auto-created)
β”‚   β”œβ”€β”€ uploads/               # Upload destination
β”‚   β”œβ”€β”€ downloads/             # Download source
β”‚   β”œβ”€β”€ shared/                # Shared files
β”‚   └── welcome.txt            # Sample file
β”œβ”€β”€ ftp_test_data/             # Test files (generated)
β”‚   β”œβ”€β”€ employee_records.csv
β”‚   β”œβ”€β”€ app_config.json
β”‚   β”œβ”€β”€ sales_data.csv
β”‚   β”œβ”€β”€ system.log
β”‚   β”œβ”€β”€ project_documentation.txt
β”‚   └── network_config.ini
└── logs/                      # Server logs (auto-created)
    └── ftp_server_*.log       # Timestamped log files

Security Best Practices Learned

  1. Never use unencrypted FTP in production
  2. Always use strong authentication mechanisms
  3. Implement proper access controls and permissions
  4. Monitor and log all file transfer activities
  5. Use encrypted protocols (FTPS/SFTP) for real applications
  6. Regularly audit firewall rules and network access
  7. Use virtual environments to isolate project dependencies

Educational Value

This lab demonstrates:

  • Network protocol analysis techniques
  • Plaintext credential interception
  • File transfer security risks
  • Firewall configuration importance
  • System monitoring and logging
  • Cybersecurity threat vectors
  • Python development best practices

πŸ†˜ Support

If you encounter issues:

  1. Ensure virtual environment is activated
  2. Check the troubleshooting section above
  3. Verify all prerequisites are met
  4. Review firewall and permissions settings
  5. Check server and client logs for detailed error messages



Remember: This is for educational purposes only. Always prioritize security in real-world applications!

About

FTP server & client built in Python for cybersecurity labs. Includes custom logging, interactive shell, and test data generator to analyze unencrypted FTP transfers with Wireshark. Perfect for protocol study, traffic analysis, and hands-on security exercises.

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors

Languages