Skip to content
Open
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
7a6b530
tls support
Fatumayattani Aug 15, 2025
d0345b6
update tls docs
Fatumayattani Aug 15, 2025
7dd3469
update tls support
Fatumayattani Aug 15, 2025
bfbc389
update changes
Fatumayattani Aug 15, 2025
a9b510e
tls support
Fatumayattani Aug 15, 2025
6ea3016
tls support doc #700
Fatumayattani Aug 15, 2025
77f4764
Add tls-support.rst to docs toctree
Fatumayattani Aug 17, 2025
cc68f63
Merge branch 'main' into main
seetadev Aug 18, 2025
73d44ed
Replace asyncio with trio, fix newline, and run pre-commit checks on …
Fatumayattani Aug 19, 2025
4f9eabe
Add initial Eclipse attack simulation module with tests
Fatumayattani Sep 23, 2025
d801a91
Merge branch 'main' into feature/attack-simulation
seetadev Sep 23, 2025
c1df722
Merge branch 'libp2p:main' into feature/attack-simulation
yashksaini-coder Sep 24, 2025
5691e6e
Merge branch 'main' into feature/attack-simulation
yashksaini-coder Sep 24, 2025
6312c95
Refactor code for consistency and clarity; update README and configur…
yashksaini-coder Sep 24, 2025
999d293
Add real integration tests and metrics collection for Eclipse attack …
yashksaini-coder Sep 24, 2025
b46cdef
Merge branch 'main' into feature/attack-simulation
yashksaini-coder Sep 25, 2025
44044f8
Linting errors resolved
yashksaini-coder Sep 25, 2025
efffe92
Merge remote-tracking branch 'refs/remotes/origin/feature/attack-simu…
yashksaini-coder Sep 25, 2025
ba04a4f
Refactor real metrics collector and test structure
yashksaini-coder Sep 25, 2025
32483ac
Remove non-existent file
yashksaini-coder Sep 25, 2025
16708e3
Enhance type annotations and improve metrics collection in Eclipse at…
yashksaini-coder Sep 25, 2025
fd4d578
performed more test and test suite for multiple config scenarios and …
yashksaini-coder Sep 25, 2025
7004d94
add newsfragment for PR #950 (Eclipse attack simulation module)
Fatumayattani Sep 26, 2025
e19929e
Merge branch 'main' into feature/attack-simulation
yashksaini-coder Sep 26, 2025
82531b1
Add connection exhaustion attack implementation and tests passed
yashksaini-coder Sep 27, 2025
d9bd1b7
Implement flooding attack module and corresponding tests
yashksaini-coder Sep 27, 2025
a3dfead
Add protocol attack implementation and tests
yashksaini-coder Sep 27, 2025
c417fce
Add Sybil attacks and tests
yashksaini-coder Sep 27, 2025
0cd848c
Add attack analysis framework and metrics collection with comprehensi…
yashksaini-coder Sep 27, 2025
7afdad7
Phase 2 completed:
yashksaini-coder Sep 27, 2025
950b155
Performed make fix & typecheck run to fix all linting and typechecke…
yashksaini-coder Sep 27, 2025
5ec1eec
Remove obsolete attack simulation result files to streamline testing …
yashksaini-coder Sep 30, 2025
e9d3215
Add results directory handling and update file paths in eclipse attac…
yashksaini-coder Sep 30, 2025
a1c8a31
Refactor real network builder to create multiple honest and malicious…
yashksaini-coder Sep 30, 2025
463f6ac
Fix host initialization in TLS examples by removing unnecessary await
yashksaini-coder Sep 30, 2025
a7b963e
Update test to use a random port for address changes in DHT reissue test
yashksaini-coder Sep 30, 2025
587aa6f
Merge branch 'main' into feature/attack-simulation
yashksaini-coder Oct 4, 2025
6b3a421
Merge branch 'main' into feature/attack-simulation
acul71 Oct 4, 2025
d9e51e9
Merge branch 'main' into feature/attack-simulation
yashksaini-coder Oct 5, 2025
f437fcf
Merge branch 'main' into feature/attack-simulation
yashksaini-coder Oct 5, 2025
4c36e6c
Address pacrob feedback: remove duplicate AttackMetrics and cleanup t…
Fatumayattani Oct 6, 2025
8d9e7c8
refactor: improve temporary file handling and reduce test peer count …
yashksaini-coder Oct 6, 2025
003f4e5
refactor: standardize list type annotations in AttackMetrics class an…
yashksaini-coder Oct 6, 2025
0f81749
Merge branch 'main' into feature/attack-simulation
yashksaini-coder Oct 6, 2025
8ef6ebf
update README
yashksaini-coder Oct 6, 2025
8b9c4b4
fix: correct whitespace in README and improve comment formatting in m…
yashksaini-coder Oct 7, 2025
f61574e
Merge branch 'main' into feature/attack-simulation
yashksaini-coder Oct 10, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ The Python implementation of the libp2p networking stack

Examples <examples>
API <libp2p>
tls-support

.. toctree::
:maxdepth: 1
Expand Down
161 changes: 161 additions & 0 deletions docs/tls-support.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
Py-libp2p – TLS Support Documentation
======================================================

.. contents::
:depth: 2
:local:

Overview of TLS in Libp2p
-------------------------

**Purpose of TLS in P2P networking**

- Encrypts data between peers.
- Authenticates peer identity using certificates.
- Prevents man-in-the-middle attacks.

**Integration in libp2p security modules**

- TLS is one of the supported secure channel protocols (alongside Noise).
- Negotiated during connection setup.

**Current status**

- **py-libp2p**: Experimental, usable for local and interop tests.
- **go-libp2p / js-libp2p**: Stable and production-ready.

Installation Requirements
-------------------------

**Python requirements**

- Python 3.8+

**Install with TLS support**

.. code-block:: bash

pip install "libp2p[tls]"

**Additional dependencies**

Ubuntu / Debian:

.. code-block:: bash

sudo apt install build-essential python3-dev libffi-dev libssl-dev

macOS:

.. code-block:: bash

brew install openssl

Enabling TLS in py-libp2p
-------------------------

**Working example – Listener and Dialer**

Listener node:

.. code-block:: python

import trio
from libp2p import new_host
from libp2p.security.tls.transport import TLSTransport

async def main():
host = await new_host(security_transports=[TLSTransport()])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

new_host is not an async function. Please verify all your examples work as expected.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove the await keywords from the example code blocks.

await host.listen("/ip4/0.0.0.0/tcp/8000")
print("TLS-enabled listener at:", host.get_addrs())

await trio.sleep_forever()

if __name__ == "__main__":
trio.run(main())

Dialer node:

.. code-block:: python

import trio
from libp2p import new_host
from libp2p.security.tls.transport import TLSTransport
from libp2p.peer.peerinfo import info_from_p2p_addr

async def main():
host = await new_host(security_transports=[TLSTransport()])

addr = "/ip4/127.0.0.1/tcp/8000/p2p/QmPeerIDHere"
peer_info = info_from_p2p_addr(addr)

await host.connect(peer_info)
print("Connected securely to", peer_info.peer_id)

if __name__ == "__main__":
trio.run(main())

**Defaults if no configuration is provided**

- Generates a self-signed certificate automatically.

Certificate Management
----------------------

**Generate a development certificate**

.. code-block:: bash

openssl req -x509 -newkey rsa:2048 \
-keyout key.pem -out cert.pem \
-days 365 -nodes -subj "/CN=py-libp2p"

- Store keys outside version control.
- Rotate certificates every 90 days in production.

Testing TLS Connections
-----------------------

**Local test steps**

1. Run the listener example.
2. Start the dialer with the listener's multiaddress.
3. Confirm the secure connection in logs.

**Interop testing**

- Ensure both nodes advertise `/tls/1.0.0`.
- Peer IDs must match certificate public keys.

Security Considerations
-----------------------

- Never disable certificate verification in production.
- Use TLS 1.3 or later.
- Pin certificates for critical peers.

Troubleshooting
---------------

.. list-table::
:header-rows: 1
:widths: 30 30 40

* - Problem
- Cause
- Solution
* - Certificate not trusted
- Self-signed without trust store entry
- Add cert to local trust store or disable verification **only** in testing.
* - Protocol negotiation failed
- One peer does not support `/tls/1.0.0`
- Enable TLS on both peers or use Noise.
* - SSL handshake failure
- TLS version mismatch or clock skew
- Enforce TLS 1.3, sync system clock.
* - `ImportError: No module named libp2p.security.tls`
- TLS extras not installed
- Run `pip install "libp2p[tls]"`.
* - Connection refused
- Port blocked or listener not running
- Check firewall rules and listener status.
Empty file added tests/security/__init__.py
Empty file.
215 changes: 215 additions & 0 deletions tests/security/attack_simulation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
# Network Attack Simulation Module (py-libp2p)

This module provides a **network attack simulation framework** for py-libp2p, focused on testing **P2P network security**. It is implemented as a **submodule** inside py-libp2p to simulate attacks, measure metrics, and analyze network resilience.

______________________________________________________________________

## Table of Contents

1. [Module Overview](#module-overview)
1. [Module Structure](#module-structure)
1. [Setup and Usage](#setup-and-usage)
1. [Testing](#testing)
1. [Implementation Details](#implementation-details)
1. [Metrics and Analysis](#metrics-and-analysis)
1. [Roadmap](#roadmap)
1. [Eclipse Attack Flow](#eclipse-attack-flow)
1. [Contributing](#contributing)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are all this 1s here not 1,2,3,....

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just noticed the auto-tab completion


______________________________________________________________________

## Module Overview

This module simulates network attacks in a controlled py-libp2p environment. Current focus:

- **Eclipse attacks** by poisoning DHTs
- Metrics collection for network health and attack effectiveness
- Configurable attack scenarios and network topologies
- Foundation for future attack types (Sybil, flooding, protocol exploits)

All work is **local in py-libp2p** with a planned migration path to `libp2p/interop`.

______________________________________________________________________

## Module Structure

```
tests/security/attack_simulation/
├── eclipse_attack/
│ ├── test_eclipse_simulation.py # Main test suite for Eclipse attacks
│ ├── malicious_peer.py # Malicious peer behavior implementation
│ ├── metrics_collector.py # Collects attack metrics during simulation
│ ├── attack_scenarios.py # Defines Eclipse attack scenarios
│ ├── network_builder.py # Builds test networks with honest/malicious nodes
│ ├── real_network_builder.py # Real libp2p host integration
│ ├── real_metrics_collector.py # Real network performance metrics
│ └── test_real_eclipse_simulation.py # Integration tests with actual DHTs
├── utils/
│ ├── attack_metrics.py # Metrics calculation utilities
│ ├── peer_behavior_simulator.py # Simulates peer behaviors (honest and malicious)
│ └── network_monitor.py # Monitors network state and connectivity
├── config/
│ ├── attack_configs.py # Configuration options for attacks
│ └── network_topologies.py # Predefined network topologies
└── README.md # Module documentation and usage guide
```

______________________________________________________________________

## Setup and Usage

1. **Activate py-libp2p virtual environment**:

```bash
source .venv/bin/activate
```

2. **Run the simulation framework tests**:

```bash
pytest -v tests/security/attack_simulation/eclipse_attack/test_eclipse_simulation.py
```

3. **Run the REAL integration tests** (🆕 **Actual libp2p network attacks**):

```bash
pytest -v tests/security/attack_simulation/eclipse_attack/test_real_eclipse_simulation.py
```

4. **Run individual attack demo**:

```bash
python tests/security/attack_simulation/eclipse_attack/test_real_eclipse_simulation.py demo
```

> Tests validate both simulated and real network attack scenarios.

______________________________________________________________________

## Testing

The module provides **two levels** of testing:

### **Level 1: Simulation Framework** (Original Implementation)
- Eclipse attack tests (`eclipse_attack/test_eclipse_simulation.py`)
- Utilities: metrics, network monitoring, peer behavior
- **Fast execution**, **conceptual validation**

### **Level 2: Real Integration Tests** 🆕 (New Enhancement)
- Real libp2p host creation using `HostFactory`
- Actual DHT manipulation with `KadDHT` instances
- Real network performance measurement
- **Slower execution**, **actual security testing**

Passing tests confirm:

- ✅ **Simulation Framework**: Network setup, malicious behaviors, metrics collection
- ✅ **Real Integration**: Actual libp2p attacks, DHT poisoning, performance degradation

______________________________________________________________________

## Implementation Details

### **Simulation Layer** (Original)

#### Malicious Peer
```python
class MaliciousPeer:
"""Simulates malicious peer behavior"""
```

#### Network Builder
```python
class AttackNetworkBuilder:
"""Constructs configurable test networks for attack simulations"""
```

### **Real Integration Layer** 🆕 (New Enhancement)

#### Real Malicious Peer
```python
class RealMaliciousPeer(MaliciousPeer):
"""Real malicious peer that manipulates actual DHT instances"""

async def poison_real_dht_entries(self, target_dht: KadDHT):
# Actually poison real DHT routing tables

async def flood_real_peer_table(self, target_dht: KadDHT):
# Flood real DHT with malicious entries
```

#### Real Network Builder
```python
class RealNetworkBuilder(AttackNetworkBuilder):
"""Builds networks with real libp2p hosts and DHT instances"""

async def create_real_eclipse_test_network(self):
# Uses HostFactory to create actual libp2p hosts
# Creates real KadDHT instances
# Forms realistic network topologies
```

#### Real Metrics Collector
```python
class RealAttackMetrics(AttackMetrics):
"""Collects actual performance metrics from real libp2p networks"""

async def measure_complete_attack_cycle(self):
# Measures real DHT lookup degradation
# Tracks actual network connectivity loss
# Calculates genuine recovery metrics
```

______________________________________________________________________

## Metrics and Analysis

Tracked metrics:

- DHT lookup success/failure rates
- Peer table contamination
- Network connectivity
- Attack effectiveness and recovery metrics

```python
class AttackMetrics:
"""Metrics collection and analysis framework"""
```

______________________________________________________________________

## Roadmap

**Phase 1 (Current)**: Eclipse attack simulation

**Phase 2**: Extended attacks (Sybil, flooding, connection exhaustion)

**Phase 3**: Cross-implementation testing in `libp2p/interop`

______________________________________________________________________

## Eclipse Attack Flow

```mermaid
flowchart TD
A[Network Builder] --> B[Honest Peers]
A --> C[Malicious Peers]
C --> D[Poison DHT Entries]
C --> E[Flood Peer Tables]
B --> F[Perform Lookups]
D --> F
E --> F
F --> G[Metrics Collector]
G --> H[Attack Analysis & Reporting]
```

> This flow illustrates the lifecycle of an Eclipse attack: the network is built, malicious peers poison the DHT and flood peer tables, honest peers perform lookups, and metrics are collected and analyzed.

______________________________________________________________________

## Contributing

1. Add new Eclipse attack scenarios under eclipse_attack, and shared utilities for any attack under utils.
1. Implement new metrics or monitoring tools
1. Write corresponding pytest tests
1. Submit PR to py-libp2p for review
Empty file.
Empty file.
5 changes: 5 additions & 0 deletions tests/security/attack_simulation/config/attack_configs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
DEFAULT_ECLIPSE_CONFIG = {
"honest_nodes": 10,
"malicious_nodes": 3,
"attack_intensity": 0.5,
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you try with different settings? are them handled ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some logs with different settings?
You may want to open a discussion page, and only put a link here, to not over bloat the PR

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will try with different settings and have the screenshot of the results in the Discussion page for this.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@acul71 I have done some more attack simulation test with multiple configs, and new test suite, shared the new disucssion here, #960

5 changes: 5 additions & 0 deletions tests/security/attack_simulation/config/network_topologies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
DEFAULT_TOPOLOGIES = {
"random": {"description": "Random connections among nodes"},
"ring": {"description": "Ring network topology"},
"full_mesh": {"description": "Every node connected to every other node"},
}
Empty file.
Loading