Skip to content

Commit

Permalink
Initial release
Browse files Browse the repository at this point in the history
  • Loading branch information
HeikoBornholdt committed Dec 9, 2023
0 parents commit ea0870b
Show file tree
Hide file tree
Showing 7 changed files with 1,589 additions and 0 deletions.
35 changes: 35 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Test

on:
push:
branches:
- '*'
tags:
- '*'
pull_request:

jobs:
test:
strategy:
matrix:
python: [ '3.8', '3.9', '3.10', '3.11', '3.12' ]

name: Python ${{ matrix.python }}
runs-on: ubuntu-latest
timeout-minutes: 15

steps:
- uses: actions/checkout@v4.1.1
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python }}
- name: Install dependencies
run: |
sudo apt-get -y install build-essential python3-dev libnetfilter-queue-dev
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run tests
run: |
pip install pytest pytest-cov
./test_nat.py
160 changes: 160 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2023 Heiko Bornholdt

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
109 changes: 109 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# NatPy: python-based network address translator with configurable mapping, allocation, and filtering behavior for Netfilter NFQUEUE

## Supported NAT Behaviors

Three different policies define the behavior of the network address translator.
These policies can be combined in any way:

### Mapping Policy

The mapping policy is triggered every time a packet is sent from a private endpoint behind the NAT to some external public port.
The role of a mapping policy is to decide whether a new rule will be added or an existing one will be reused.
There are three different behaviors:

* **Endpoint-Independent:** Use the same mapping for any public endpoint.
* **Host-Dependent:** Create new mapping if the public endpoint's IP address differs.
* **Port-Dependent:** Create a new mapping of the public endpoint's IP address or port differences.

### Allocation Policy

A new public endpoint is bound whenever a new rule is added.
This policy allocates a new port.
That is, the mapping policy decides when to bind a new port, and the allocation policy decides which port should be bound as follows:
* **Port-Preservation:** Allocate the same port for mapping as the private endpoint uses.
* **Port Contiguity:** Allocate random port between [1024, 65536) for first mapping. Allocate nächthöheren port für subsequenzt mappings.
* **Random:** Allocate random port between [1024, 65536).

### Filtering Policy

The filtering policy decides whether a packet from the outside world to a public endpoint of a NAT gateway should be forwarded to the corresponding private endpoint.
There are three filtering policies with the following conditions for allowing receiving:
* **Endpoint-Independent:** Every public endpoint is allowed.
* **Host-Dependent:** Every port of the same public endpoint is allowed.
* **Port-Dependent:** Only the same public endpoint is allowed.

### Popular Behaviors:

Here are examples of policies to choose to achieve common NAT type behaviors:

| **NAT type** | **Mapping Policy** | **Allocation Policy** | **Filtering Policy** |
|-----------------|-----------------------------------|-----------------------|------------------------|
| Full-cone | `endpoint_independent` | | `endpoint_independent` |
| Restricted-Cone | `endpoint_independent` | | `host_dependent` |
| Port-Restricted | `endpoint_independent` | | `port_dependent` |
| Symmetric | `host_dependent`/`port_dependent` | (`random`) | `port_dependent` |


## Installation

```bash
apt install build-essential python3-dev libnetfilter-queue-dev
pip install -r requirements.txt
```

## Example Usage

In this example, we assume your public WAN address is `93.184.216.34`, your private LAN subnet is `192.168.178.0/24`, and we want to direct packets to Netfilter queue `0`.
First, ensure your host has both WAN and LAN interfaces and IP forwarding is enabled (e.g., by run `sysctl net.ipv4.ip_forward=1`).
Then, you need to configure Netfilter to direct traffic to a Netfilter queue by running and starting NatPy.

```bash
# direct LAN -> WAN packets to queue
iptables --table filter \
--append FORWARD \
--jump NFQUEUE \
--queue-num 0 \
--source 192.168.178.0/24 \
! --destination 93.184.216.34

# direct WAN -> LAN packets to queu
iptables --table mangle \
--append PREROUTING \
--jump NFQUEUE \
--queue-num 0 \
-d 93.184.216.34

# start NatPy
./nat.py --mapping port_dependent \
--allocation random \
--filtering port_dependent \
--lan-subnet 192.168.178.0/24 \
--wan-address 93.184.216.34 \
--queue 0
```

## Help

```bash
$ ./nat.py --help
usage: nat.py [-h] [--mapping {endpoint_independent,host_dependent,port_dependent}] [--allocation {port_preservation,port_contiguity,random}] [--filtering {endpoint_independent,host_dependent,port_dependent}] [--lan-subnet LAN_SUBNET]
[--wan-address WAN_ADDRESS] [--queue QUEUE]

options:
-h, --help show this help message and exit
--mapping {endpoint_independent,host_dependent,port_dependent}
new mapping creation policy
--allocation {port_preservation,port_contiguity,random}
new mappings's port allocation policy
--filtering {endpoint_independent,host_dependent,port_dependent}
inbound packet filtering policy
--lan-subnet LAN_SUBNET
private IP address range (CIDR notation)
--wan-address WAN_ADDRESS
public IP address
--queue QUEUE queue number for Netfilter
```
## License
This is free software under the terms of the [MIT License](LICENSE).
Loading

0 comments on commit ea0870b

Please sign in to comment.