Metadata-Version: 2.4
Name: pcileech-fw-generator
Version: 0.1.7
Summary: Generate spoofed PCIe DMA firmware from real donor hardware
Author-email: Ramsey McGrath <ramseymcgrath@gmail.com>
Maintainer-email: Ramsey McGrath <ramseymcgrath@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/ramseymcgrath/PCILeechFWGenerator
Project-URL: Repository, https://github.com/ramseymcgrath/PCILeechFWGenerator
Project-URL: Documentation, https://github.com/ramseymcgrath/PCILeechFWGenerator/blob/main/README.md
Project-URL: Bug Tracker, https://github.com/ramseymcgrath/PCILeechFWGenerator/issues
Project-URL: Changelog, https://github.com/ramseymcgrath/PCILeechFWGenerator/blob/main/CHANGELOG.md
Keywords: pcie,dma,firmware,fpga,hardware,security,penetration-testing,red-team,xilinx,vivado
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Environment :: Console :: Curses
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: Intended Audience :: System Administrators
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: System :: Hardware
Classifier: Topic :: Software Development :: Embedded Systems
Classifier: Topic :: System :: Systems Administration
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: psutil>=5.9.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: tui
Requires-Dist: textual>=0.45.0; extra == "tui"
Requires-Dist: rich>=13.0.0; extra == "tui"
Requires-Dist: watchdog>=3.0.0; extra == "tui"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: pytest-mock>=3.10.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: isort>=5.12.0; extra == "dev"
Requires-Dist: flake8>=6.0.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: pre-commit>=3.0.0; extra == "dev"
Requires-Dist: build>=0.10.0; extra == "dev"
Requires-Dist: twine>=4.0.0; extra == "dev"
Provides-Extra: test
Requires-Dist: pytest>=7.0.0; extra == "test"
Requires-Dist: pytest-cov>=4.0.0; extra == "test"
Requires-Dist: pytest-mock>=3.10.0; extra == "test"
Dynamic: license-file

# PCILeech Firmware Generator

[![PyPI version](https://badge.fury.io/py/pcileech-fw-generator.svg)](https://badge.fury.io/py/pcileech-fw-generator)
[![Python Support](https://img.shields.io/pypi/pyversions/pcileech-fw-generator.svg)](https://pypi.org/project/pcileech-fw-generator/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![CI](https://github.com/ramseymcgrath/PCILeechFWGenerator/workflows/CI/badge.svg)](https://github.com/ramseymcgrath/PCILeechFWGenerator/actions)
[![codecov](https://codecov.io/gh/ramseymcgrath/PCILeechFWGenerator/branch/main/graph/badge.svg)](https://codecov.io/gh/ramseymcgrath/PCILeechFWGenerator)

Generate spoofed PCIe DMA firmware from real donor hardware with a single command. The workflow rips the donor's configuration space, builds a personalized FPGA bit‑stream in an isolated container, and (optionally) flashes your DMA card over USB‑JTAG.

## ✨ Features

- **🎯 Donor Hardware Analysis**: Extract real PCIe device configurations and register maps
- **📊 Behavioral Profiling**: Capture dynamic device behavior patterns for enhanced realism
- **🔧 Manufacturing Variance Simulation**: Add realistic timing jitter and parameter variations
- **⚡ Advanced SystemVerilog Generation**: Comprehensive PCIe device controller with modular architecture
- **🐳 Automated Build Pipeline**: Containerized synthesis and bit-stream generation
- **🔌 USB-JTAG Flashing**: Direct firmware deployment to DMA boards
- **🖥️ Interactive TUI**: Modern text-based interface with real-time monitoring and guided workflows
- **📦 Professional Packaging**: Easy installation via pip with proper dependency management

## 🚀 Quick Start

### Installation

```bash
# Basic installation
pip install pcileech-fw-generator

# With TUI support (recommended)
pip install pcileech-fw-generator[tui]

# Development installation
pip install pcileech-fw-generator[dev]
```

### Usage

```bash
# Interactive TUI interface (recommended)
pcileech-tui

# Command line interface
pcileech-generate

# Direct build command
pcileech-build --bdf 0000:03:00.0 --board 75t
```

## 📋 Requirements

### 1.1 Software

| Tool | Why you need it | Install |
|------|----------------|---------|
| Vivado Studio | Synthesis & bit‑stream generation | Download from Xilinx (any 2022.2+ release) |
| Podman | Rootless container runtime for the build sandbox | See [`install.sh`](install.sh) in this repo |
| Python ≥ 3.9 | Host‑side orchestrator ([`generate.py`](generate.py)) | Distro package (python3) |
| λConcept usbloader | USB flashing utility for Screamer‑class boards | Installed by [`install.sh`](install.sh) |
| pciutils, usbutils | lspci / lsusb helpers | Installed by [`install.sh`](install.sh) |

> **⚠️ Security Notice**
> Never build firmware on the same operating system you plan to run the attack from. Use a separate Linux box or VM.

### Hardware

| Component | Notes |
|-----------|-------|
| Donor PCIe card | Any inexpensive NIC, sound, or capture card works. One donor → one firmware. Destroy or quarantine the donor after extraction. |
| DMA board | Supported Artix‑7 DMA boards (35T, 75T, 100T). Must expose the Screamer USB‑JTAG port. |

## 🛠️ Installation & Setup

### Method 1: pip Installation (Recommended)

```bash
# Install with TUI support
pip install pcileech-fw-generator[tui]

# Basic installation (CLI only)
pip install pcileech-fw-generator

# Development installation
git clone https://github.com/ramseymcgrath/PCILeechFWGenerator
cd PCILeechFWGenerator
pip install -e .[dev]
```

### Method 2: Manual Installation

```bash
# Clone repository
git clone https://github.com/ramseymcgrath/PCILeechFWGenerator
cd PCILeechFWGenerator

# Install system dependencies
sudo ./install.sh

# Install Python dependencies
pip install -r requirements-tui.txt  # For TUI support
# OR
pip install -r requirements.txt      # Basic installation
```

Re‑login or run `newgrp` afterwards so rootless Podman picks up subuid/subgid mappings.

## 🎮 Usage

### Interactive TUI Mode (Recommended)

The modern text-based interface provides guided workflows and real-time monitoring:

```bash
# Launch TUI (after pip installation)
sudo pcileech-tui

# Or from source
sudo python3 tui_generate.py
```

**TUI Features:**
- 🖥️ **Visual device browser** with enhanced PCIe device information
- ⚙️ **Guided configuration** with validation and profile management
- 📊 **Real-time build monitoring** with progress tracking and resource usage
- 🔍 **Intelligent error guidance** with suggested fixes
- 📡 **System status monitoring** for Podman, Vivado, USB devices, and more

See [`docs/TUI_README.md`](docs/TUI_README.md) for detailed TUI documentation.

### Command Line Mode

For automated workflows or scripting:

```bash
# Basic generation (interactive device selection)
sudo pcileech-generate

# Direct build with specific device
sudo pcileech-build --bdf 0000:03:00.0 --board 75t

# Advanced generation with enhanced features
sudo pcileech-build --bdf 0000:03:00.0 --board 75t --advanced-sv

# Device-specific generation with behavior profiling
sudo pcileech-build --bdf 0000:03:00.0 --board 75t --advanced-sv \
  --device-type network --enable-behavior-profiling

# Selective feature control
sudo pcileech-build --bdf 0000:03:00.0 --board 75t --advanced-sv \
  --disable-power-management --disable-performance-counters
```

**Output:** `output/firmware.bin` (FPGA bit‑stream ready for flashing).

### Legacy Mode (Source Installation)

```bash
# Traditional workflow (still supported)
sudo python3 generate.py
```

## 4. Flashing the DMA Board

> **Note:** These steps can run on the same machine or a different PC.

1. Power down, install the DMA card, and remove the donor.

2. Connect the USB‑JTAG port.

3. Flash:

```bash
usbloader -f output/firmware.bin      # auto‑detects Screamer VID:PID 1d50:6130
```

If multiple λConcept boards are attached, add `--vidpid <vid:pid>`.

## 5. Advanced Features

### 5.1 Manufacturing Variance Simulation

The Manufacturing Variance Simulation feature adds realistic hardware variations to make generated firmware more authentic and harder to detect. This feature models real-world manufacturing tolerances and environmental conditions.

**Key Capabilities:**
- **Device Class Support**: Consumer, Enterprise, Industrial, and Automotive grade components with appropriate variance characteristics
- **Timing Variations**: Clock jitter, register access timing, and propagation delays
- **Environmental Modeling**: Temperature drift, power supply noise, and process variations
- **Integration**: Seamlessly integrates with behavior profiling for enhanced realism

**Device Classes:**
- `CONSUMER`: Standard consumer-grade tolerances (2-5% clock jitter)
- `ENTERPRISE`: Tighter enterprise-grade specifications (1-3% variations)
- `INDUSTRIAL`: Extended temperature and reliability ranges
- `AUTOMOTIVE`: Automotive-grade specifications with enhanced stability

**Usage:**
```bash
# Enable manufacturing variance (automatically applied with --advanced-sv)
python3 src/build.py --bdf 0000:03:00.0 --board 75t --advanced-sv
```

### 5.2 Advanced SystemVerilog Generation

The Advanced SystemVerilog Generation feature provides a comprehensive, modular PCIe device controller with enterprise-grade capabilities and optimizations.

**Architecture Components:**
- **Modular Design**: Specialized components for power, error handling, and performance monitoring
- **Multiple Clock Domains**: Proper clock domain crossing with variance-aware timing
- **Device-Specific Logic**: Optimizations for Network, Storage, Graphics, and Audio devices
- **Comprehensive Integration**: All components work together seamlessly

**Power Management Features:**
- **PCIe Power States**: Full D0, D1, D2, D3hot, D3cold state support
- **ASPM (Active State Power Management)**: L0s, L1, L1.1, L1.2 link states
- **Dynamic Power Scaling**: Frequency and voltage scaling based on workload
- **Wake-on-LAN/Event**: Configurable wake event handling

**Error Handling & Recovery:**
- **Comprehensive Error Detection**: Correctable and uncorrectable error handling
- **Advanced Error Reporting (AER)**: Full PCIe AER implementation
- **Recovery Mechanisms**: Automatic error recovery and link retraining
- **Error Logging**: Detailed error tracking and reporting

**Performance Monitoring:**
- **Hardware Counters**: Transaction, bandwidth, and latency monitoring
- **Device-Specific Metrics**: Tailored counters for different device types
- **Real-time Monitoring**: Live performance data collection
- **Threshold-based Alerts**: Configurable performance thresholds

**Device-Specific Optimizations:**
- **Network Devices**: Multi-queue support, interrupt coalescing, checksum offload
- **Storage Devices**: Command queuing, wear leveling, power loss protection
- **Graphics Devices**: Memory bandwidth optimization, display timing
- **Audio Devices**: Low-latency processing, sample rate conversion

**Usage Examples:**
```bash
# Enable all advanced features
python3 src/build.py --bdf 0000:03:00.0 --board 75t --advanced-sv

# Network device with specific optimizations
python3 src/build.py --bdf 0000:03:00.0 --board 75t --advanced-sv --device-type network

# Disable specific features for minimal implementation
python3 src/build.py --bdf 0000:03:00.0 --board 75t --advanced-sv \
  --disable-power-management --disable-error-handling

# Storage device with performance monitoring
python3 src/build.py --bdf 0000:03:00.0 --board 75t --advanced-sv \
  --device-type storage --enable-behavior-profiling
```

### 5.3 Behavioral Profiling

Dynamic behavior profiling captures real device operation patterns to enhance firmware realism.

**Capabilities:**
- **Real-time Monitoring**: Captures live device register access patterns
- **Pattern Analysis**: Identifies behavioral signatures and timing characteristics
- **Integration**: Enhances register definitions with behavioral data
- **Configurable Duration**: Adjustable profiling periods (default: 10 seconds)

**Usage:**
```bash
# Enable behavior profiling with custom duration
python3 src/build.py --bdf 0000:03:00.0 --board 75t \
  --enable-behavior-profiling --profile-duration 30.0
```

### 5.4 Command-Line Options

**Core Options:**
- `--bdf`: PCIe Bus:Device.Function identifier (required)
- `--board`: Target board type (35t, 75t, 100t) (required)

**Advanced Features:**
- `--advanced-sv`: Enable advanced SystemVerilog generation
- `--device-type`: Specify device type (generic, network, storage, graphics, audio)
- `--enable-behavior-profiling`: Enable dynamic behavior profiling
- `--profile-duration`: Profiling duration in seconds (default: 10.0)

**Feature Control:**
- `--disable-power-management`: Disable power management features
- `--disable-error-handling`: Disable error handling features
- `--disable-performance-counters`: Disable performance monitoring

**Analysis & Debugging:**
- `--save-analysis`: Save detailed analysis to specified file
- `--verbose`: Enable verbose output
- `--enhanced-timing`: Enable enhanced timing models (default: enabled)

## 6. Cleanup & Safety

- Rebind the donor back to its original driver if you keep it around.
- Keep the generated firmware private; it contains identifiers from the donor.
- Advanced features require appropriate privileges for hardware access.

## 7. Disclaimer

## 📦 Development & Contributing

### Development Setup

```bash
# Clone repository
git clone https://github.com/ramseymcgrath/PCILeechFWGenerator
cd PCILeechFWGenerator

# Create virtual environment
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install development dependencies
pip install -r requirements-dev.txt

# Install pre-commit hooks
pre-commit install

# Run tests
pytest tests/
```

### Building from Source

```bash
# Build distributions
python -m build

# Install locally
pip install dist/*.whl

# Test installation
pcileech-generate --help
```

### Contributing

We welcome contributions! Please see [`CONTRIBUTING.md`](CONTRIBUTING.md) for detailed guidelines.

**Quick Start:**
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Add tests for new functionality
5. Run the test suite (`pytest`)
6. Commit your changes (`git commit -m 'feat: add amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request

### Release Process

For maintainers releasing new versions:

```bash
# Automated release (recommended)
python scripts/release.py minor --release-notes "Add new TUI features and improvements"

# Manual release
python -m build
twine upload dist/*
```

## 📚 Documentation

- **[TUI Documentation](docs/TUI_README.md)**: Detailed TUI interface guide
- **[TUI Design Document](docs/TUI_Design_Document.md)**: Technical architecture
- **[Contributing Guide](CONTRIBUTING.md)**: Development and contribution guidelines
- **[Changelog](CHANGELOG.md)**: Version history and release notes
- **[API Reference](https://pcileech-fw-generator.readthedocs.io/)**: Complete API documentation

## 🔧 Troubleshooting

### Common Issues

**Installation Problems:**
```bash
# If pip installation fails
pip install --upgrade pip setuptools wheel
pip install pcileech-fw-generator[tui]

# For development installation issues
pip install -e .[dev]
```

**TUI Not Starting:**
```bash
# Check TUI dependencies
python -c "import textual; print('TUI dependencies OK')"

# Install TUI dependencies manually
pip install textual rich psutil watchdog
```

**Permission Issues:**
```bash
# Ensure proper permissions for PCIe operations
sudo usermod -a -G vfio $USER
sudo usermod -a -G dialout $USER  # For USB-JTAG access
```

**Container Issues:**
```bash
# Check Podman installation
podman --version

# Verify rootless setup
podman info | grep rootless
```

### Getting Help

- **GitHub Issues**: [Report bugs or request features](https://github.com/ramseymcgrath/PCILeechFWGenerator/issues)
- **GitHub Discussions**: [Community support and questions](https://github.com/ramseymcgrath/PCILeechFWGenerator/discussions)
- **Documentation**: Check the docs/ directory for detailed guides

## 🏆 Acknowledgments

- **λConcept**: For the excellent usbloader utility and Screamer hardware
- **Xilinx/AMD**: For Vivado synthesis tools
- **Textual**: For the modern TUI framework
- **PCILeech Community**: For feedback and contributions

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ⚠️ Legal Notice

This tool is intended for educational research and legitimate PCIe development purposes only. Users are responsible for ensuring compliance with all applicable laws and regulations. The authors assume no liability for misuse of this software.

**Security Considerations:**
- Never build firmware on systems used for production or sensitive operations
- Use isolated build environments (VMs or dedicated hardware)
- Keep generated firmware private and secure
- Follow responsible disclosure practices for any security research

---

**Version 0.1.7** - Major release with TUI interface and professional packaging
For educational research and legitimate PCIe development only. Misuse may violate laws and void warranties. The authors assume no liability.
