├── python ├── geoipsets │ ├── VERSION │ ├── __init__.py │ ├── utils.py │ ├── __main__.py │ ├── dbip.py │ └── maxmind.py ├── MANIFEST.in ├── geoipsets.conf ├── setup.py ├── README.md └── tests │ └── config_test.py ├── requirements.txt ├── .github ├── dependabot.yml └── workflows │ ├── python-tests.yaml │ └── ci.yaml ├── .gitignore ├── systemd ├── update-geoipsets.timer └── update-geoipsets.service ├── bash ├── bcs.conf ├── README.md └── build-country-sets.sh ├── CONTRIBUTING.md ├── scripts ├── generate_geoipsets_conf.sh └── integration_test.sh ├── README.md └── LICENSE /python/geoipsets/VERSION: -------------------------------------------------------------------------------- 1 | 2.4.0 2 | -------------------------------------------------------------------------------- /python/MANIFEST.in: -------------------------------------------------------------------------------- 1 | include geoipsets/VERSION 2 | -------------------------------------------------------------------------------- /python/geoipsets/__init__.py: -------------------------------------------------------------------------------- 1 | # __init__.py 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | setuptools>=51.1.2 2 | requests>=2.25.1 3 | pytest>=6.2.5 4 | beautifulsoup4>=4.10 -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | 4 | - package-ecosystem: "github-actions" 5 | directory: "/" 6 | schedule: 7 | # Check for updates to GitHub Actions every week 8 | interval: "weekly" 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/.vscode 2 | **/.idea 3 | *.iml 4 | **/.pytest_cache 5 | **/venv 6 | python/dist 7 | python/geoipsets.egg-info 8 | python/build 9 | **/__pycache__ 10 | **/setup.py.REAL 11 | .pre-commit-config.yaml 12 | -------------------------------------------------------------------------------- /systemd/update-geoipsets.timer: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Weekly geoipset refresh 3 | 4 | [Timer] 5 | OnCalendar=Tue *-*-* 22:00:00 6 | RandomizedDelaySec=600 7 | Persistent=true 8 | 9 | [Install] 10 | WantedBy=timers.target 11 | -------------------------------------------------------------------------------- /bash/bcs.conf: -------------------------------------------------------------------------------- 1 | #Build GeoIP Sets fo netfilter 2 | #Default configuration: 3 | #IPTABLES=no 4 | #NFTABLES=yes 5 | #IPv4=yes 6 | #IPv6=yes 7 | 8 | #Don't forget to set your MaxMind credentials! 9 | LICENSE_KEY=YOUR_ACCOUNT_ID:YOUR_LICENSE_KEY 10 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Geo IP sets 2 | ============ 3 | Contributions are welcome. 4 | 5 | Workflow 6 | ------------ 7 | To do so, please follow the [Git feature branch workflow](https://www.atlassian.com/git/tutorials/comparing-workflows/feature-branch-workflow). 8 | 9 | Pre-commit Linting 10 | ------------------- 11 | Please setup [flake8 linting as a pre-commit hook](https://flake8.pycqa.org/en/latest/user/using-hooks.html) in your local repo. 12 | 13 | The following minimal pre-commit-config.yaml is enough: 14 | ```yaml 15 | files: 'python/' 16 | repos: 17 | - repo: https://github.com/pycqa/flake8 18 | rev: 7.1.1 19 | hooks: 20 | - id: flake8 21 | args: ['--max-line-length', '120'] 22 | ``` -------------------------------------------------------------------------------- /python/geoipsets/utils.py: -------------------------------------------------------------------------------- 1 | # utils.py 2 | 3 | from abc import ABC, abstractmethod 4 | from enum import Enum 5 | from pathlib import Path 6 | 7 | 8 | class Firewall(Enum): 9 | IP_TABLES = 'iptables' 10 | NF_TABLES = 'nftables' 11 | 12 | 13 | class AddressFamily(Enum): 14 | IPV4 = 'ipv4' 15 | IPV6 = 'ipv6' 16 | 17 | 18 | class AbstractProvider(ABC): 19 | """Abstract base class providing common functionality for all Provider types.""" 20 | 21 | def __init__(self, firewall: set, address_family: set, checksum: bool, countries: set, output_dir: str): 22 | self.ipv4 = AddressFamily.IPV4.value in address_family 23 | self.ipv6 = AddressFamily.IPV6.value in address_family 24 | self.nf_tables = Firewall.NF_TABLES.value in firewall 25 | self.ip_tables = Firewall.IP_TABLES.value in firewall 26 | self.checksum = checksum 27 | self.countries = countries 28 | self.base_dir = Path(output_dir) / 'geoipsets' 29 | 30 | @abstractmethod 31 | def generate(self): 32 | pass 33 | -------------------------------------------------------------------------------- /systemd/update-geoipsets.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Update geoipsets 3 | Wants=network.target network-online.target 4 | After=network.target network-online.target 5 | AssertFileIsExecutable=/usr/bin/geoipsets 6 | AssertPathExists=/var/local 7 | 8 | [Service] 9 | Type=oneshot 10 | CapabilityBoundingSet= 11 | RestrictAddressFamilies=AF_INET AF_INET6 12 | #if firewall configuration is updated as part of this service, replace the 2 lines above with the 2 lines below 13 | #CapabilityBoundingSet=CAP_NET_ADMIN 14 | #RestrictAddressFamilies=AF_INET AF_INET6 AF_NETLINK 15 | RestrictNamespaces=true 16 | NoNewPrivileges=true 17 | PrivateDevices=true 18 | ProtectClock=true 19 | ProtectControlGroups=true 20 | ProtectHome=true 21 | ProtectKernelLogs=true 22 | ProtectKernelModules=true 23 | ProtectKernelTunables=true 24 | ProtectProc=invisible 25 | ProtectSystem=full 26 | MemoryDenyWriteExecute=true 27 | RestrictRealtime=true 28 | RestrictSUIDSGID=true 29 | SystemCallArchitectures=native 30 | SystemCallFilter=@system-service 31 | ProtectHostname=true 32 | LockPersonality=true 33 | ExecStart=/usr/bin/geoipsets --output-dir /var/local 34 | StandardOutput=journal 35 | StandardError=journal -------------------------------------------------------------------------------- /bash/README.md: -------------------------------------------------------------------------------- 1 | Installation 2 | ------------ 3 | Install the Bash script to your system. 4 | * curl --remote-name --location https://github.com/chr0mag/geoipsets/archive/v2.0.tar.gz 5 | * tar -zxvf v2.0.tar.gz 6 | * cp geoipsets-2.0/build-country-sets.sh /usr/local/bin/. 7 | * chown root:root /usr/local/bin/build-country-sets.sh 8 | * chmod +x /usr/local/bin/build-country-sets.sh 9 | 10 | Execution 11 | ------------ 12 | The license key can be provided either as a command line argument using the '-k' switch, or via the /etc/bcs.conf configuration file with the following format: 13 | ``` 14 | LICENSE_KEY=YOUR_KEY 15 | ``` 16 | To execute the script with and without a configuration file: 17 | * ./build-country-sets.sh 18 | * ./build-country-sets.sh -k YOUR_LICENSE_KEY 19 | 20 | The command line option takes precedence. 21 | Manual execution will create a directory with the following hierarchy in the current working directory: 22 | ``` 23 | geoipsets 24 | ├── ipset 25 | │   ├── ipv4 26 | │   └── ipv6 27 | └── nftset 28 | ├── ipv4 29 | └── ipv6 30 | ``` 31 | 32 | Environment variables limiting which sets are generated are available. See https://github.com/chr0mag/geoipsets/blob/main/bash/bcs.conf . -------------------------------------------------------------------------------- /python/geoipsets.conf: -------------------------------------------------------------------------------- 1 | [general] 2 | # specify a directory where geoipsets should be saved 3 | output-dir=/tmp 4 | # list of providers from which to acquire IP ranges 5 | # options are: 6 | # 'maxmind': www.maxmind.com 7 | # 'dbip': https://db-ip.com/ (default) 8 | provider=dbip,maxmind 9 | 10 | # list of firewalls to build sets for 11 | # valid values are: 'iptables', 'nftables' 12 | # iptables: builds 'ipset' compatible sets 13 | # nftables: builds nftables compatible sets 14 | # default: nftables 15 | firewall=iptables,nftables 16 | 17 | # list of IP protocols to build sets for 18 | # valid values are: 'ipv4', 'ipv6' 19 | # default: ipv4 20 | address-family=ipv4,ipv6 21 | 22 | # specify which countries to build sets for 23 | # countries are specified using the 2-character country codes, one per line 24 | # https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 25 | # if section doesn't exist, or exists but is empty, sets for all countries will be generated (default) 26 | [countries] 27 | #RU 28 | #CN 29 | 30 | [maxmind] 31 | # specify MaxMind license key needed to download data 32 | # required for provider type 'maxmind', ignored by other provider types 33 | account-id=098765 34 | license-key=ABCDEFTHIJKLMNOP 35 | -------------------------------------------------------------------------------- /.github/workflows/python-tests.yaml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | 3 | name: python-tests 4 | 5 | on: 6 | push: 7 | branches: [ '*' ] 8 | pull_request: 9 | branches: [ 'main' ] 10 | 11 | jobs: 12 | run-python-tests: 13 | runs-on: ubuntu-latest 14 | strategy: 15 | fail-fast: false 16 | matrix: 17 | python-version: ['3.9', '3.10', '3.11', '3.12', '3.13'] 18 | steps: 19 | - uses: actions/checkout@v6 20 | - name: Set up Python ${{ matrix.python-version }} 21 | uses: actions/setup-python@v6 22 | with: 23 | python-version: ${{ matrix.python-version }} 24 | - name: Install dependencies 25 | run: | 26 | python -m pip install --upgrade pip 27 | python -m pip install flake8 pytest 28 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 29 | - name: Lint with flake8 30 | run: | 31 | # stop the build if there are Python syntax errors or undefined names 32 | flake8 . --count --max-line-length=120 --show-source --statistics 33 | - name: Test with pytest 34 | run: | 35 | python -m pytest 36 | working-directory: ./python -------------------------------------------------------------------------------- /scripts/generate_geoipsets_conf.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | cat << EOF > /tmp/geoipsets.conf 4 | [general] 5 | # specify a directory where geoipsets should be saved 6 | output-dir=/tmp 7 | # list of providers from which to acquire IP ranges 8 | # options are: 9 | # 'maxmind': www.maxmind.com 10 | # 'dbip': https://db-ip.com/ 11 | provider=maxmind,dbip 12 | 13 | # list of firewalls to build sets for 14 | # valid values are: 'iptables', 'nftables' 15 | # iptables: builds 'ipset' compatible sets 16 | # nftables: builds nftables compatible sets 17 | # if the property doesn't exist, or exists but is empty both ip and nft sets are generated (default) 18 | firewall=iptables,nftables 19 | 20 | # list of IP protocols to build sets for 21 | # valid values are: 'ipv4', 'ipv6' 22 | # if the property doesn't exist or exists, but is empty both ipv4 and ipv6 sets will be generated (default) 23 | address-family=ipv4,ipv6 24 | 25 | # specify which countries to build sets for 26 | # countries are specified using the 2-character country codes, one per line 27 | # https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 28 | # if section doesn't exist, or exists but is empty, sets for all countries will be generated (default) 29 | [countries] 30 | #RU 31 | #CN 32 | #KP 33 | #BV 34 | 35 | [maxmind] 36 | # specify MaxMind license key needed to download data 37 | # required for provider type 'maxmind', ignored by other provider types 38 | account-id=${MAXMIND_ACCT_ID} 39 | license-key=${MAXMIND_NEW_KEY} 40 | EOF -------------------------------------------------------------------------------- /python/setup.py: -------------------------------------------------------------------------------- 1 | # setup.py 2 | 3 | import pathlib 4 | 5 | from setuptools import setup, find_packages 6 | 7 | # The directory containing this file 8 | HERE = pathlib.Path(__file__).parent 9 | 10 | # The text of the README file 11 | README = (HERE / "README.md").read_text() 12 | 13 | # The text of the VERSION file 14 | VERSION = (HERE / 'geoipsets/VERSION').read_text() 15 | 16 | # This call to setup() does all the work 17 | setup( 18 | name="geoipsets", 19 | version=VERSION, 20 | description="Utility to build country-specific IP sets for ipset/iptables and nftables.", 21 | long_description=README, 22 | long_description_content_type="text/markdown", 23 | url="https://github.com/chr0mag/geoipsets", 24 | license="GPLv3", 25 | classifiers=[ 26 | "Operating System :: POSIX :: Linux", 27 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 28 | "Programming Language :: Python :: 3", 29 | "Programming Language :: Python :: 3.9", 30 | "Programming Language :: Python :: 3.10", 31 | "Programming Language :: Python :: 3.11", 32 | "Programming Language :: Python :: 3.12", 33 | "Programming Language :: Python :: 3.13", 34 | ], 35 | packages=find_packages(exclude=("tests",)), 36 | include_package_data=True, 37 | install_requires=["requests", "beautifulsoup4"], 38 | entry_points={ 39 | "console_scripts": [ 40 | "geoipsets=geoipsets.__main__:main", 41 | ] 42 | }, 43 | ) 44 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | # This workflow will build all geoipsets, load each set into nftables/iptables and use the set in a rule 2 | 3 | name: ci 4 | 5 | on: 6 | push: 7 | branches: [ '*' ] 8 | workflow_dispatch: 9 | schedule: 10 | - cron: '14 14 * * 3' 11 | 12 | jobs: 13 | generate-geoipsets: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v6 17 | - name: Set up Python 18 | uses: actions/setup-python@v6 19 | with: 20 | python-version: '3.13' 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 25 | - name: Generate geoipsets.conf 26 | working-directory: ./scripts 27 | env: 28 | MAXMIND_ACCT_ID: ${{ secrets.MAXMIND_ACCT_ID }} 29 | MAXMIND_NEW_KEY: ${{ secrets.MAXMIND_NEW_KEY }} 30 | run: | 31 | bash generate_geoipsets_conf.sh 32 | - name: Build geoipsets 33 | run: | 34 | python -m geoipsets --config-file /tmp/geoipsets.conf 35 | if [ "$?" -ne 0 ]; then exit 1; fi 36 | ls -R /tmp/geoipsets 37 | working-directory: ./python 38 | - name: Upload geoipsets data 39 | uses: actions/upload-artifact@v6 40 | with: 41 | name: geoipsets-data 42 | path: /tmp/geoipsets 43 | 44 | run-integration-tests: 45 | needs: generate-geoipsets 46 | runs-on: ubuntu-latest 47 | strategy: 48 | fail-fast: false 49 | matrix: 50 | provider: [ dbip, maxmind ] 51 | firewall: [ nftset, ipset ] 52 | address-family: [ ipv4, ipv6 ] 53 | steps: 54 | - name: Install dependencies 55 | run: sudo apt-get install -y ipset jq 56 | - name: Download geoipsets data 57 | uses: actions/download-artifact@v7 58 | with: 59 | name: geoipsets-data 60 | path: /tmp/geoipsets 61 | - uses: actions/checkout@v6 62 | - name: Run integration tests 63 | working-directory: ./scripts 64 | run: | 65 | sudo bash integration_test.sh ${{ matrix.provider }} ${{ matrix.firewall }} ${{ matrix.address-family }} 66 | if [ "$?" -ne 0 ]; then exit 1; fi 67 | -------------------------------------------------------------------------------- /python/README.md: -------------------------------------------------------------------------------- 1 | ![badge](https://github.com/chr0mag/geoipsets/actions/workflows/ci.yaml/badge.svg) ![PyPI](https://img.shields.io/pypi/v/geoipsets) ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/geoipsets) [![Downloads](https://pepy.tech/badge/geoipsets)](https://pepy.tech/project/geoipsets) ![GitHub](https://img.shields.io/github/license/chr0mag/geoipsets) 2 | 3 | Installation 4 | ------------ 5 | 6 | ```pip install geoipsets``` 7 | 8 | Usage 9 | ------ 10 | Utility output can be controlled using a configuration file and/or command line options. For the MaxMind provider type, this configuration file is required in order to provide the license-key. See the [example](https://github.com/chr0mag/geoipsets/blob/main/python/geoipsets.conf) for details. 11 | 12 | The example file enables all options which is likely not what you want as it will generate IPv4 and IPv6 sets for both firewall types for all countries. 13 | 14 | Typically, you would want to select only one firewall type along with a short list of countries and perhaps only for the IPv4 address family. 15 | 16 | The utility will attempt to read the configuration file at */etc/geoipsets.conf* but the location can be overidden using the *--config PATH_TO_FILE* command line option. 17 | 18 | ```shell 19 | usage: geoipsets [-h] [-v] [-p {maxmind,dbip} [{maxmind,dbip} ...]] [-f {nftables,iptables} [{nftables,iptables} ...]] [-a {ipv4,ipv6} [{ipv4,ipv6} ...]] 20 | [-l COUNTRIES] [-o OUTPUT_DIR] [-c CONFIG_FILE] [--checksum] [--no-checksum] 21 | 22 | Utility to build country specific IP sets for ipset/iptables and nftables. Command line arguments take precedence over those in the configuration file. 23 | 24 | options: 25 | -h, --help show this help message and exit 26 | -v, --version show program's version number and exit 27 | -p {maxmind,dbip} [{maxmind,dbip} ...], --provider {maxmind,dbip} [{maxmind,dbip} ...] 28 | dataset provider(s) (default: dbip) 29 | -f {nftables,iptables} [{nftables,iptables} ...], --firewall {nftables,iptables} [{nftables,iptables} ...] 30 | firewall(s) to build sets for (default: nftables) 31 | -a {ipv4,ipv6} [{ipv4,ipv6} ...], --address-family {ipv4,ipv6} [{ipv4,ipv6} ...] 32 | IP protocol(s) to build sets for (default: ipv4) 33 | -l COUNTRIES, --countries COUNTRIES 34 | Path to a file containing 2-character country codes, one per line, or a comma-separated list of country codes. Argument is treated 35 | as a path first. If it does not resolve, or the resolved file is invalid, then it is parsed as a comma-separated list. 36 | -o OUTPUT_DIR, --output-dir OUTPUT_DIR 37 | directory where geoipsets should be saved (default: /tmp) 38 | -c CONFIG_FILE, --config-file CONFIG_FILE 39 | path to configuration file (default: /etc/geoipsets.conf) 40 | --checksum enable checksum validation of downloaded files (default) 41 | --no-checksum disable checksum validation of downloaded files 42 | 43 | ``` 44 | -------------------------------------------------------------------------------- /scripts/integration_test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # usage: ./integration_test.sh 4 | # eg. ./integration_test.sh dbip nftset ipv4 5 | # assume default set location under /tmp/geoipsets/. 6 | # possible paths are: 7 | #% ls -lRd /tmp/geoipsets/*/*/* 8 | #drwxr-xr-x 2 root root 4096 Dec 28 14:19 /tmp/geoipsets/dbip/ipset/ipv4 9 | #drwxr-xr-x 2 root root 4096 Dec 28 14:19 /tmp/geoipsets/dbip/ipset/ipv6 10 | #drwxr-xr-x 2 root root 4096 Dec 28 14:19 /tmp/geoipsets/dbip/nftset/ipv4 11 | #drwxr-xr-x 2 root root 4096 Dec 28 14:19 /tmp/geoipsets/dbip/nftset/ipv6 12 | #drwxr-xr-x 2 root root 4096 Dec 28 14:19 /tmp/geoipsets/maxmind/ipset/ipv4 13 | #drwxr-xr-x 2 root root 4096 Dec 28 14:19 /tmp/geoipsets/maxmind/ipset/ipv6 14 | #drwxr-xr-x 2 root root 4096 Dec 28 14:19 /tmp/geoipsets/maxmind/nftset/ipv4 15 | #drwxr-xr-x 2 root root 4096 Dec 28 14:19 /tmp/geoipsets/maxmind/nftset/ipv6 16 | 17 | # print an error and exit with failure 18 | # $1: error message 19 | function error() { 20 | echo "$0: error: $1" >&2 21 | exit 1 22 | } 23 | 24 | # ensure the programs needed to execute are available 25 | function check_progs() { 26 | local PROGS="jq ipset nft iptables ip6tables" 27 | which ${PROGS} > /dev/null 2>&1 || error "Searching PATH fails to find executables among: ${PROGS}" 28 | } 29 | 30 | function test_nftables() { 31 | set_path="/tmp/geoipsets/${1}/${2}/${3}" 32 | printf "Set location: %s.\n" "$set_path" 33 | set_list=("$set_path"/*."$3") 34 | printf "Sets to test: %s.\n" "${#set_list[@]}" 35 | 36 | for s in "${set_list[@]}"; do 37 | printf "Set: %s\t\t" "$s" 38 | file_items=$(($(wc --lines < "$s") - 2)) # first & last lines are not subnets 39 | set_name=$(basename "$s") 40 | if [ "$3" = "ipv6" ]; then 41 | ip_version="ip6" 42 | else 43 | ip_version="ip" 44 | fi 45 | 46 | cat << EOF > /tmp/nftables.conf 47 | #!/usr/bin/nft -f 48 | 49 | # clear all prior state 50 | flush ruleset 51 | 52 | include "${s}" 53 | 54 | table inet filter 55 | delete table inet filter 56 | 57 | # IPv4/IPv6 filter table 58 | table inet filter { 59 | set blacklist { 60 | type ${3}_addr 61 | flags interval 62 | elements = \$$set_name 63 | } 64 | chain input { 65 | type filter hook input priority 0; policy accept; 66 | $ip_version saddr @blacklist counter drop 67 | } 68 | } 69 | EOF 70 | 71 | nft --file /tmp/nftables.conf 72 | nft_ret_val=$? 73 | loaded_items=$(nft --json list set inet filter blacklist | jq '.nftables[1].set.elem' | jq 'length') 74 | printf "entries: %s\t loaded: %s\t\t" "$file_items" "$loaded_items" 75 | if [ "$nft_ret_val" -eq 0 ] && [ "$file_items" = "$loaded_items" ]; then 76 | printf "pass\n" 77 | else 78 | printf "fail\n" 79 | error "Set '${s} failed to load." 80 | fi 81 | done 82 | } 83 | 84 | function test_ipset() { 85 | # support running on both Arch & Ubuntu (22.04) 86 | source "/etc/os-release" 87 | if [ "$ID" = "arch" ]; then 88 | iptables --table filter --flush 89 | ip6tables --table filter --flush 90 | if [ "$3" = "ipv4" ]; then 91 | ipt_binary="iptables" 92 | else 93 | ipt_binary="ip6tables" 94 | fi 95 | elif [ "$ID" = "ubuntu" ]; then 96 | iptables-legacy --table filter --flush 97 | ip6tables-legacy --table filter --flush 98 | if [ "$3" = "ipv4" ]; then 99 | ipt_binary="iptables-legacy" 100 | else 101 | ipt_binary="ip6tables-legacy" 102 | fi 103 | fi 104 | printf "Using iptables binary: %s\n" "$ipt_binary" 105 | ipset destroy 106 | 107 | set_path="/tmp/geoipsets/${1}/${2}/${3}" 108 | printf "Set location: %s.\n" "$set_path" 109 | set_list=("$set_path"/*."$3") 110 | printf "Sets to test: %s.\n" "${#set_list[@]}" 111 | 112 | for s in "${set_list[@]}"; do 113 | printf "Set: %s\t\t" "$s" 114 | file_items=$(($(wc --lines < "$s") - 1)) # first line is not a subnet 115 | set_name=$(basename "$s") 116 | ipset restore --file "$s" 117 | ipset_ret_val=$? 118 | loaded_items=$(ipset list --terse | grep "Number of entries" | awk '{print $4}') 119 | printf "entries: %s\t loaded: %s\t\t" "$file_items" "$loaded_items" 120 | $ipt_binary --table filter --insert INPUT --match set --match-set "$set_name" src -j DROP 121 | iptables_ret_val=$? 122 | if [ "$ipset_ret_val" -eq 0 ] && [ "$iptables_ret_val" -eq 0 ] && [ "$file_items" = "$loaded_items" ]; then 123 | printf "pass\n" 124 | else 125 | printf "fail\n" 126 | error "Set '${s} failed to load." 127 | fi 128 | $ipt_binary --table filter --flush 129 | ipset destroy 130 | 131 | done 132 | } 133 | 134 | function main() { 135 | check_progs 136 | if [ "$2" = "nftset" ]; then 137 | test_nftables "$@" 138 | else 139 | test_ipset "$@" 140 | fi 141 | } 142 | 143 | main "$@" 144 | 145 | 146 | -------------------------------------------------------------------------------- /bash/build-country-sets.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # write permission to '/etc' required 4 | 5 | COUNTRY_ID_MAP="GeoLite2-Country-Locations-en.csv" 6 | ID_IPv4_RANGE_MAP="GeoLite2-Country-Blocks-IPv4.csv" 7 | ID_IPv6_RANGE_MAP="GeoLite2-Country-Blocks-IPv6.csv" 8 | readonly CONFIG_FILES="${COUNTRY_ID_MAP} ${ID_IPv4_RANGE_MAP} ${ID_IPv6_RANGE_MAP}" 9 | declare -A ID_NAME_MAP 10 | 11 | # print an error and exit with failure 12 | # $1: error message 13 | function error() { 14 | echo "$0: error: $1" >&2 15 | exit 1 16 | } 17 | 18 | # ensure the programs needed to execute are available 19 | function check_progs() { 20 | local PROGS="awk sed curl unzip sha256sum cat mktemp" 21 | which ${PROGS} > /dev/null 2>&1 || error "Searching PATH fails to find executables among: ${PROGS}" 22 | } 23 | 24 | # retrieve latest MaxMind GeoLite2 IP country database and checksum 25 | # CSV URL: https://download.maxmind.com/geoip/databases/GeoLite2-Country-CSV/download?suffix=zip 26 | # SHA256 URL: https://download.maxmind.com/geoip/databases/GeoLite2-Country-CSV/download?suffix=zip.sha256 27 | function download_geolite2_data() { 28 | local ZIPPED_FILE="GeoLite2-Country-CSV.zip" 29 | local SHA256_FILE="${ZIPPED_FILE}.sha256" 30 | local CSV_URL="https://download.maxmind.com/geoip/databases/GeoLite2-Country-CSV/download?suffix=zip" 31 | local SHA256_URL="${CSV_URL}.sha256" 32 | 33 | # download files 34 | curl --silent --location --user "${LICENSE_KEY}" --output $ZIPPED_FILE "$CSV_URL" || error "Failed to download: $CSV_URL" 35 | curl --silent --location --user "${LICENSE_KEY}" --output $SHA256_FILE "$SHA256_URL" || error "Failed to download: $SHA256_URL" 36 | 37 | # validate checksum 38 | # .sha256 file is not in expected format so 'sha256sum --check $SHA256_FILE' doesn't work 39 | [[ "$(cat ${SHA256_FILE} | awk '{print $1}')" == "$(cat ${ZIPPED_FILE} | sha256sum | awk '{print $1}')" ]] || error \ 40 | "Downloaded sha256 checksum does not match local sha256sum.\nCheck your License key!" 41 | 42 | # unzip into current working directory 43 | unzip -j -q -d . ${ZIPPED_FILE} 44 | } 45 | 46 | # ensure the configuration files needed to execute are available 47 | function check_conf_files() { 48 | local FILES=(${CONFIG_FILES}) 49 | for f in ${FILES[@]} 50 | do 51 | [[ -f $f ]] || error "Missing configuration file: $f" 52 | done 53 | } 54 | 55 | # build map of geoname_id to ISO country code 56 | # ${ID_NAME_MAP[$geoname_id]}='country_iso_code' 57 | # example row: 6251999,en,NA,"North America",CA,Canada,0 58 | function build_id_name_map() { 59 | OIFS=$IFS 60 | IFS=',' 61 | while read -ra LINE 62 | do 63 | #echo "geonameid: ${LINE[0]}, country ISO code: ${LINE[4]}" 64 | CC="${LINE[4]}" 65 | # skip geonameid's that are not country specific (eg. Europe) 66 | if [[ ! -z $CC ]]; then 67 | ID_NAME_MAP[${LINE[0]}]=${CC} 68 | fi 69 | done < <(sed -e 1d ${COUNTRY_ID_MAP}) 70 | IFS=$OIFS 71 | } 72 | 73 | # output 74 | # ./geoipsets/ipset/ipv4/CA.ipv4 75 | # ./geoipsets/nftset/ipv4/CA.ipv4 76 | function build_ipv4_sets { 77 | 78 | readonly IPV4_IPSET_DIR="./geoipsets/ipset/ipv4/" 79 | readonly IPV4_NFTSET_DIR="./geoipsets/nftset/ipv4/" 80 | 81 | if [[ $IPTABLES = "yes" ]]; then 82 | rm -rf $IPV4_IPSET_DIR 83 | mkdir --parent $IPV4_IPSET_DIR 84 | fi 85 | 86 | if [[ ! -v NFTABLES || $NFTABLES = "yes" ]]; then 87 | rm -rf $IPV4_NFTSET_DIR 88 | mkdir --parent $IPV4_NFTSET_DIR 89 | fi 90 | 91 | OIFS=$IFS 92 | IFS=',' 93 | while read -ra LINE 94 | do 95 | # prefer location over registered country 96 | ID="${LINE[1]}" 97 | if [ -z "${ID}" ]; then 98 | ID="${LINE[2]}" 99 | fi 100 | # skip entry if both location and registered country are empty 101 | if [ -z "${ID}" ]; then 102 | continue 103 | fi 104 | 105 | CC="${ID_NAME_MAP[${ID}]}" 106 | SUBNET="${LINE[0]}" 107 | SET_NAME="${CC}.ipv4" 108 | 109 | if [[ $IPTABLES = "yes" ]]; then 110 | 111 | # 112 | # iptables/ipsets 113 | # 114 | 115 | IPSET_FILE="${IPV4_IPSET_DIR}${SET_NAME}" 116 | 117 | #create ipset file if it doesn't exist 118 | if [[ ! -f $IPSET_FILE ]]; then 119 | echo "create $SET_NAME hash:net maxelem 131072 comment" > $IPSET_FILE 120 | fi 121 | echo "add ${SET_NAME} ${SUBNET} comment ${CC}" >> $IPSET_FILE 122 | fi 123 | 124 | if [[ ! -v NFTABLES || $NFTABLES = "yes" ]]; then 125 | 126 | # 127 | # nftables set 128 | # 129 | 130 | NFTSET_FILE="${IPV4_NFTSET_DIR}${SET_NAME}" 131 | 132 | #create nft set file if it doesn't exist 133 | if [[ ! -f $NFTSET_FILE ]]; then 134 | echo "define $SET_NAME = {" > $NFTSET_FILE 135 | fi 136 | echo "${SUBNET}," >> $NFTSET_FILE 137 | fi 138 | 139 | done < <(sed -e 1d "${TEMPDIR}/${ID_IPv4_RANGE_MAP}") 140 | IFS=$OIFS 141 | 142 | #end nft set -- better way? 143 | if [[ ! -v NFTABLES || $NFTABLES = "yes" ]]; then 144 | for f in "${IPV4_NFTSET_DIR}"*.ipv4 145 | do 146 | echo "}" >> "$f" 147 | done 148 | fi 149 | } 150 | 151 | # output 152 | # ./geoipsets/ipset/ipv6/CA.ipv6 153 | # ./geoipsets/nftset/ipv6/CA.ipv6 154 | function build_ipv6_sets { 155 | 156 | readonly IPV6_IPSET_DIR="./geoipsets/ipset/ipv6/" 157 | readonly IPV6_NFTSET_DIR="./geoipsets/nftset/ipv6/" 158 | 159 | if [[ $IPTABLES = "yes" ]]; then 160 | rm -rf $IPV6_IPSET_DIR 161 | mkdir --parent $IPV6_IPSET_DIR 162 | fi 163 | 164 | if [[ ! -v NFTABLES || $NFTABLES = "yes" ]]; then 165 | rm -rf $IPV6_NFTSET_DIR 166 | mkdir --parent $IPV6_NFTSET_DIR 167 | fi 168 | 169 | OIFS=$IFS 170 | IFS=',' 171 | while read -ra LINE 172 | do 173 | # prefer location over registered country 174 | ID="${LINE[1]}" 175 | if [ -z "${ID}" ]; then 176 | ID="${LINE[2]}" 177 | fi 178 | # skip entry if both location and registered country are empty 179 | if [ -z "${ID}" ]; then 180 | continue 181 | fi 182 | 183 | CC="${ID_NAME_MAP[${ID}]}" 184 | SUBNET="${LINE[0]}" 185 | SET_NAME="${CC}.ipv6" 186 | 187 | if [[ $IPTABLES = "yes" ]]; then 188 | 189 | # 190 | # iptables/ipsets 191 | # 192 | 193 | IPSET_FILE="${IPV6_IPSET_DIR}${SET_NAME}" 194 | 195 | #create ipset file if it doesn't exist 196 | if [[ ! -f $IPSET_FILE ]]; then 197 | echo "create $SET_NAME hash:net family inet6 comment" > $IPSET_FILE 198 | fi 199 | echo "add ${SET_NAME} ${SUBNET} comment ${CC}" >> $IPSET_FILE 200 | fi 201 | 202 | if [[ ! -v NFTABLES || $NFTABLES = "yes" ]]; then 203 | 204 | # 205 | # nftables set 206 | # 207 | 208 | NFTSET_FILE="${IPV6_NFTSET_DIR}${SET_NAME}" 209 | 210 | #create nft set file if it doesn't exist 211 | if [[ ! -f $NFTSET_FILE ]]; then 212 | echo "define $SET_NAME = {" > $NFTSET_FILE 213 | fi 214 | echo "${SUBNET}," >> $NFTSET_FILE 215 | fi 216 | done < <(sed -e 1d "${TEMPDIR}/${ID_IPv6_RANGE_MAP}") 217 | IFS=$OIFS 218 | 219 | #end nft set -- better way? 220 | if [[ ! -v NFTABLES || $NFTABLES = "yes" ]]; then 221 | for f in "${IPV6_NFTSET_DIR}"*.ipv6 222 | do 223 | echo "}" >> "$f" 224 | done 225 | fi 226 | } 227 | 228 | # accept an optional -k switch with argument 229 | function main() { 230 | 231 | # get license key 232 | source ./bcs.conf > /dev/null 2>&1 233 | local usage="Usage: ./build-country-sets.sh [-k ]" 234 | while getopts ":k:" opt; do 235 | case ${opt} in 236 | k ) 237 | [[ ! -z "${OPTARG}" ]] && LICENSE_KEY=$OPTARG || error "$usage" 238 | ;; 239 | \? ) 240 | error "$usage" 241 | ;; 242 | : ) 243 | error "$usage" 244 | ;; 245 | esac 246 | done 247 | shift $((OPTIND -1)) 248 | [[ -z "${LICENSE_KEY}" ]] && error "No license key provided."; 249 | 250 | 251 | # setup 252 | check_progs 253 | export TEMPDIR=$(mktemp --directory) 254 | # place geolite data in temporary directory 255 | pushd $TEMPDIR > /dev/null 2>&1 256 | download_geolite2_data 257 | check_conf_files 258 | build_id_name_map 259 | # place set output in current working directory 260 | popd > /dev/null 2>&1 261 | [[ ! -v IPv4 || $IPv4 = "yes" ]] && build_ipv4_sets 262 | [[ ! -v IPv6 || $IPv6 = "yes" ]] && build_ipv6_sets 263 | } 264 | 265 | main "$@" 266 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | geoipsets 2 | ============ 3 | ![badge](https://github.com/chr0mag/geoipsets/actions/workflows/ci.yaml/badge.svg) ![PyPI](https://img.shields.io/pypi/v/geoipsets) ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/geoipsets) [![Downloads](https://pepy.tech/badge/geoipsets)](https://pepy.tech/project/geoipsets) ![GitHub](https://img.shields.io/github/license/chr0mag/geoipsets) 4 | 5 | Utility to generate country-specific IPv4/IPv6 network ranges consumable by both *iptables/ipset* and *nftables*. Also included is a *systemd* service and timer to periodically update the IP sets. 6 | 7 | Introduction 8 | ------------ 9 | There is both a [Bash version](https://github.com/chr0mag/geoipsets/blob/main/bash/README.md) and a [Python version](https://github.com/chr0mag/geoipsets/blob/main/python/README.md) of the utility. The Python version is more flexible (and faster) so choose this unless there is a compelling reason not to. 10 | 11 | This Python version supports 2 dataset providers: [dbip](https://db-ip.com/) and [MaxMind](https://www.maxmind.com). The Bash version only supports MaxMind and is effectively legacy at this point. It continues to work but there are no plans to update it further. 12 | 13 | If you use MaxMind a [both an account id and license key are required](https://dev.maxmind.com/geoip/updating-databases/#directly-downloading-databases) to download the data. 14 | 15 | The remaining instructions apply equally to the Bash and Python versions. 16 | 17 | Updates 18 | ----------- 19 | Data is updated regularly so it's preferable to execute a weekly task to retrieve the latest geo IP sets. Install and configure the *systemd* service and timer: 20 | ``` 21 | cp geoipsets-*/update-geoipsets.* /etc/systemd/system/. 22 | chown root:root /etc/systemd/system/update-geoipsets.service /etc/systemd/system/update-geoipsets.timer 23 | systemctl start update-geoipsets.timer && systemctl enable update-geoipsets.timer 24 | ``` 25 | Execute the service once manually to initially populate the set data. 26 | ``` 27 | systemctl start update-geoipsets.service 28 | ``` 29 | Set data is placed in */tmp* by default. Use the `--output-dir` option to change this. 30 | 31 | You may need to enable the relevant network *wait* service to avoid the script running on boot before a network connection is available. eg. if using *systemd-networkd* for network management: 32 | ``` 33 | systemctl start systemd-networkd-wait-online.service && systemctl enable systemd-networkd-wait-online.service 34 | ``` 35 | 36 | Usage 37 | ------ 38 | **iptables/ipset** example: blacklist all Russian ipv4 and ipv6 IPs 39 | 40 | * Create and save the ipsets 41 | ``` 42 | ipset restore --file /var/local/geoipsets/maxmind/ipset/ipv4/RU.ipv4 43 | ipset restore --file /var/local/geoipsets/maxmind/ipset/ipv6/RU.ipv6 44 | ipset save --file /etc/ipset.conf 45 | ``` 46 | * Reference the ipsets from *iptables/ip6tables* rules and then save 47 | ``` 48 | iptables --insert INPUT --match set --match-set RU.ipv4 src -j DROP 49 | iptables-save > /etc/iptables/iptables.rules 50 | ip6tables --insert INPUT --match set --match-set RU.ipv6 src -j DROP 51 | ip6tables-save > /etc/iptables/ip6tables.rules 52 | ``` 53 | **nftables** example: blacklist all Russian ipv4 and ipv6 IPs and all Chinese ipv6 IPs 54 | 55 | * Include the set files in your main *nftables* configuration file and reference the set elements variable from a rule. 56 | ``` 57 | #!/usr/bin/nft -f 58 | flush ruleset 59 | 60 | include "/var/local/geoipsets/maxmind/nftset/ipv4/*.ipv4" 61 | include "/var/local/geoipsets/maxmind/nftset/ipv6/*.ipv6" 62 | 63 | table netdev filter { 64 | 65 | # to reference a single set 66 | set country-ipv4-blacklist { 67 | type ipv4_addr 68 | flags interval 69 | elements = $RU.ipv4 70 | } 71 | # to reference multiple sets 72 | set country-ipv6-blacklist { 73 | type ipv6_addr 74 | flags interval 75 | elements = { $RU.ipv6, $CN.ipv6 } 76 | } 77 | chain ingress { 78 | type filter hook ingress device priority 0; policy accept; 79 | ip saddr @country-ipv4-blacklist counter drop 80 | ip6 saddr @country-ipv6-blacklist counter drop 81 | } 82 | } 83 | ``` 84 | 85 | Automatic Firewall Updates 86 | ----------------- 87 | The provided *systemd* service & timer updates the set data on disk, but *nftables* and *ipset* need to be reloaded to use the updated sets. 88 | 89 | Continuing with the example above: 90 | 91 | ***ipset*** 92 | * flush, re-import the new ipsets, then save 93 | ``` 94 | ipset flush RU.ipv4 95 | ipset restore --exist --file /var/local/geoipsets/maxmind/ipset/ipv4/RU.ipv4 96 | ipset flush RU.ipv6 97 | ipset restore --exist --file /var/local/geoipsets/maxmind/ipset/ipv6/RU.ipv6 98 | ipset save --file /etc/ipset.conf 99 | ``` 100 | ***nftables*** 101 | * simply reload the ruleset 102 | ``` 103 | nft --file /etc/nftables.conf 104 | ``` 105 | * or, take advantage of *nftables'* dynamic rulset updates by flushing and reloading only the sets themsevles using an *nft* script: 106 | ``` 107 | #!/usr/bin/nft -f 108 | include "/var/local/geoipsets/maxmind/nftset/ipv4/*.ipv4" 109 | include "/var/local/geoipsets/maxmind/nftset/ipv6/*.ipv6" 110 | 111 | flush set netdev filter country-ipv4-blacklist 112 | add element netdev filter country-ipv4-blacklist $RU.ipv4 113 | flush set netdev filter country-ipv6-blacklist 114 | add element netdev filter country-ipv6-blacklist $RU.ipv6 115 | add element netdev filter country-ipv6-blacklist $CN.ipv6 116 | ``` 117 | 118 | Different options exist to automate the set refresh: 119 | 1. the above commands could be added to the provided *update-geoipsets.service* file 120 | 2. better, override *update-geoipsets.service* with a drop in file that executes the above commands after the script is run 121 | 3. alternatively, a *systemd.path* file could be created to watch the set directories for changes and trigger the above commands when the used sets are modified 122 | 123 | Option #2 is quite simple and would look like this: 124 | 125 | ***ipset*** 126 | ``` 127 | # /etc/systemd/system/update-geoipsets.service.d/override.conf 128 | [Service] 129 | ExecStart=/usr/bin/ipset flush RU.ipv4 130 | ExecStart=/usr/bin/ipset restore --exist --file /var/local/geoipsets/maxmind/ipset/ipv4/RU.ipv4 131 | ExecStart=/usr/bin/ipset flush RU.ipv6 132 | ExecStart=/usr/bin/ipset restore --exist --file /var/local/geoipsets/maxmind/ipset/ipv6/RU.ipv6 133 | ExecStart=/usr/bin/ipset save --file /etc/ipset.conf 134 | ``` 135 | ***nftables*** 136 | ``` 137 | # /etc/systemd/system/update-geoipsets.service.d/override.conf 138 | [Service] 139 | ExecStart=/usr/bin/nft --file /etc/nftables.conf 140 | ``` 141 | or... 142 | ``` 143 | # /etc/systemd/system/update-geoipsets.service.d/override.conf 144 | [Service] 145 | ExecStart=/usr/bin/nft --file /usr/local/bin/refresh-sets.nft 146 | ``` 147 | Where *refresh-sets.nft* contains the *nft* commands listed above. 148 | 149 | Note that the [example systemd service file](https://github.com/chr0mag/geoipsets/blob/main/systemd/update-geoipsets.service) is heavily sandboxed and does not have privileges to restart network services by default. See the example file for instructions showing how to loosen restrictions to enable this. 150 | 151 | Performance 152 | ----------- 153 | * The Python version is much faster than the Bash version so use this if you have the choice. 154 | * Versions > v2.3.1 include a significant performance improvement when generating MaxMind data. (See [issue #16](https://github.com/chr0mag/geoipsets/issues/16) and [PR #24](https://github.com/chr0mag/geoipsets/pull/24).) 155 | ``` 156 | # All tests below generate both ipv4 and ipv6 sets for both ipset and nftables. 157 | ## Python 158 | % time python -m geoipsets -c ~/geoipsets.conf --provider maxmind --output-dir ~/tests 159 | 1.80s user 0.07s system 56% cpu 3.315 total 160 | 161 | % time python -m geoipsets -c ~/geoipsets.conf --provider dbip --output-dir ~/tests 162 | 10.74s user 0.11s system 94% cpu 11.487 total 163 | 164 | ## Bash (maxmind only) 165 | % ./build-country-sets.sh 166 | 34.62s user 31.62s system 107% cpu 1:01.68 total 167 | ``` 168 | Sources 169 | ------------ 170 | * http://ipset.netfilter.org/ 171 | * https://dev.maxmind.com/geoip/geoipupdate/#Direct_Downloads 172 | * https://dev.maxmind.com/geoip/geoip2/geolite2/ 173 | * https://superuser.com/questions/997426/is-there-any-other-way-to-get-iptables-to-filter-ip-addresses-based-on-geolocati#997437 174 | * https://wiki.archlinux.org/index.php/Nftables 175 | * https://wiki.nftables.org/wiki-nftables/index.php/Main_Page 176 | * https://unix.stackexchange.com/questions/329971/nftables-ip-set-multiple-tables#331959 177 | * https://www.freedesktop.org/wiki/Software/systemd/NetworkTarget/ 178 | -------------------------------------------------------------------------------- /python/geoipsets/__main__.py: -------------------------------------------------------------------------------- 1 | # __main__.py 2 | 3 | import configparser 4 | from argparse import ArgumentParser 5 | from configparser import ConfigParser 6 | from pathlib import Path 7 | from sys import argv 8 | 9 | from . import utils, maxmind, dbip 10 | 11 | 12 | def get_version(): 13 | root_dir = Path(__file__).parent 14 | return (root_dir / 'VERSION').read_text() 15 | 16 | 17 | def get_config_parser(path): 18 | """ 19 | Returns a ConfigParser, or None. 20 | """ 21 | try: 22 | config_file = ConfigParser(allow_no_value=True) 23 | config_file.read(path) 24 | return config_file 25 | except configparser.Error as e: 26 | # TODO: catch each error type separately 27 | print("Problem loading config file. Ignoring...", e.message) 28 | return None 29 | 30 | 31 | def get_config(cli_args=None): 32 | """ 33 | Generate configuration 34 | """ 35 | default_config_path = "/etc/geoipsets.conf" 36 | default_output_dir = "/tmp" 37 | 38 | # to simplify unit testing 39 | if not cli_args: 40 | cli_args = argv[1:] 41 | 42 | parser = ArgumentParser(prog="geoipsets", 43 | description="""Utility to build country specific IP sets for ipset/iptables and nftables. 44 | Command line arguments take precedence over those in the configuration file.""") 45 | parser.add_argument("-v", "--version", 46 | action="version", 47 | version="%(prog)s {0}".format(get_version())) 48 | parser.add_argument("-p", "--provider", 49 | action="extend", 50 | nargs="+", 51 | type=str.lower, 52 | choices={'dbip', 'maxmind'}, 53 | help="dataset provider(s) (default: {0})".format('dbip')) 54 | parser.add_argument("-f", "--firewall", 55 | action="extend", 56 | nargs="+", 57 | type=str.lower, 58 | choices={utils.Firewall.NF_TABLES.value, utils.Firewall.IP_TABLES.value}, 59 | help="firewall(s) to build sets for (default: {0})".format(utils.Firewall.NF_TABLES.value)) 60 | parser.add_argument("-a", "--address-family", 61 | action="extend", 62 | nargs="+", 63 | type=str.lower, 64 | choices={utils.AddressFamily.IPV4.value, utils.AddressFamily.IPV6.value}, 65 | help="IP protocol(s) to build sets for (default: {0})".format(utils.AddressFamily.IPV4.value)) 66 | parser.add_argument("-l", "--countries", 67 | type=str, 68 | help="""Path to a file containing 2-character country codes, one per line, or a comma-separated 69 | list of country codes. Argument is treated as a path first. If it does not resolve, or 70 | the resolved file is invalid, then it is parsed as a comma-separated list.""") 71 | parser.add_argument("-o", "--output-dir", 72 | type=str, 73 | help="directory where geoipsets should be saved (default: {0})".format(default_output_dir)) 74 | parser.add_argument("-c", "--config-file", 75 | type=str, 76 | default=default_config_path, 77 | help="path to configuration file (default: {0})".format(default_config_path)) 78 | parser.add_argument("--checksum", 79 | dest="checksum", 80 | action="store_true", 81 | help="enable checksum validation of downloaded files (default)") 82 | parser.add_argument("--no-checksum", 83 | dest="checksum", 84 | action="store_false", 85 | help="disable checksum validation of downloaded files") 86 | parser.set_defaults(checksum=True) 87 | 88 | # set defaults 89 | default_options = dict() 90 | default_options['general'] = {''} 91 | default_options['output-dir'] = default_output_dir 92 | default_options['provider'] = {'dbip'} 93 | default_options['firewall'] = {utils.Firewall.NF_TABLES.value} 94 | default_options['address-family'] = {utils.AddressFamily.IPV4.value} 95 | default_options['countries'] = 'all' 96 | default_options['checksum'] = parser.parse_args(cli_args).checksum 97 | options = default_options 98 | 99 | # step 1: load a valid configuration file, if one exists 100 | config_file = None 101 | valid_conf_file = True 102 | if (config_file_path := parser.parse_args(cli_args).config_file) is not None: 103 | if (config_file := get_config_parser(config_file_path)) is None: 104 | valid_conf_file = False 105 | 106 | if valid_conf_file and config_file.has_section('general'): 107 | general = config_file['general'] 108 | else: 109 | valid_conf_file = False 110 | 111 | # step 2: output_dir 112 | if (output_dir := parser.parse_args(cli_args).output_dir) is not None: 113 | options['output-dir'] = output_dir 114 | else: 115 | if valid_conf_file and (output_dir := general.get('output-dir')) is not None: 116 | options['output-dir'] = output_dir 117 | 118 | # step 3: provider 119 | if (providers := parser.parse_args(cli_args).provider) is not None: 120 | options['provider'] = set(providers) 121 | else: 122 | if valid_conf_file and (providers := general.get('provider')) is not None: 123 | options['provider'] = set(providers.split(',')) 124 | 125 | # step 4: firewall 126 | if (firewalls := parser.parse_args(cli_args).firewall) is not None: 127 | options['firewall'] = set(firewalls) 128 | else: 129 | if valid_conf_file and (firewalls := general.get('firewall')) is not None: 130 | options['firewall'] = set(firewalls.split(',')) 131 | 132 | # step 5: address family 133 | if (address_family := parser.parse_args(cli_args).address_family) is not None: 134 | options['address-family'] = set(address_family) 135 | else: 136 | if valid_conf_file and (address_family := general.get('address-family')) is not None: 137 | options['address-family'] = set(address_family.split(',')) 138 | 139 | # step 6: countries 140 | if (country_arg := parser.parse_args(cli_args).countries) is not None: 141 | country_set = set() 142 | try: 143 | Path(country_arg).resolve(strict=True) 144 | with open(country_arg, 'r') as country_file: 145 | for line in country_file: 146 | line = line.strip() 147 | if not line.startswith('#'): 148 | line = line.split('#')[0].strip() 149 | if len(line) == 2 and line.isalpha(): 150 | country_set.add(line.lower()) 151 | except FileNotFoundError: 152 | print("file '{0}' does not exist, parsing as list instead".format(country_arg)) 153 | for c in country_arg.split(','): 154 | if len(c) == 2 and c.isalpha(): 155 | country_set.add(c.lower()) 156 | 157 | if len(country_set) > 0: 158 | options['countries'] = country_set 159 | 160 | else: 161 | if valid_conf_file and config_file.has_section('countries'): 162 | countries = set(config_file['countries'].keys()) 163 | if len(countries) > 0: 164 | options['countries'] = countries 165 | 166 | # step 7: provider options 167 | if valid_conf_file: 168 | for p in options.get('provider'): 169 | if config_file.has_section(p): 170 | provider_options = config_file[p] 171 | options[p] = provider_options 172 | 173 | return options 174 | 175 | 176 | def main(): 177 | opts = get_config() 178 | providers = opts.get('provider') 179 | print("Building geoipsets...") 180 | 181 | if "maxmind" in providers: 182 | mmp = maxmind.MaxMindProvider(opts.get('firewall'), 183 | opts.get('address-family'), 184 | opts.get('checksum'), 185 | opts.get('countries'), 186 | opts.get('output-dir'), 187 | opts.get('maxmind')) 188 | mmp.generate() 189 | 190 | if "dbip" in providers: 191 | dbipp = dbip.DbIpProvider(opts.get('firewall'), 192 | opts.get('address-family'), 193 | opts.get('checksum'), 194 | opts.get('countries'), 195 | opts.get('output-dir')) 196 | dbipp.generate() 197 | 198 | 199 | if __name__ == "__main__": 200 | main() 201 | -------------------------------------------------------------------------------- /python/geoipsets/dbip.py: -------------------------------------------------------------------------------- 1 | # dbip.py 2 | 3 | import gzip 4 | import hashlib 5 | import shutil 6 | from csv import DictReader 7 | from datetime import datetime 8 | from io import TextIOWrapper 9 | from ipaddress import ip_address, summarize_address_range 10 | from tempfile import NamedTemporaryFile 11 | 12 | import requests 13 | from bs4 import BeautifulSoup 14 | 15 | from . import utils 16 | 17 | 18 | class DbIpProvider(utils.AbstractProvider): 19 | """ DBIP IP range set provider. """ 20 | 21 | def __init__(self, firewall: set, address_family: set, checksum: bool, countries: set, output_dir: str): 22 | super().__init__(firewall, address_family, checksum, countries, output_dir) 23 | 24 | def generate(self): 25 | """ 26 | While nftables' set facility accepts both IPv4 and IPv6 IP ranges, ipset only accepts IPv4 IP ranges. 27 | So, for simplicity we convert all ranges into subnets. 28 | 29 | ip_start, ip_end, country 30 | """ 31 | gzip_ref = self.download() # comment out for testing 32 | # dictionary of subnet lists, indexed by filename 33 | # filename is CC.address_family -- eg. CA.ipv4 34 | country_subnets = dict() 35 | 36 | with gzip.GzipFile(gzip_ref, 'rb') as csv_file_bytes: 37 | # with gzip.GzipFile('/tmp/tmphq4qgkfp.csv.gz', 'rb') as csv_file_bytes: 38 | 39 | # validate checksum of the CSV file (not the GZIP file) 40 | if self.checksum: 41 | self.check_checksum(csv_file_bytes) 42 | 43 | rows = DictReader(TextIOWrapper(csv_file_bytes), fieldnames=("ip_start", "ip_end", "country")) 44 | for r in rows: 45 | cc = r['country'] 46 | # configparser forces keys to lower case by default 47 | if cc != 'ZZ' and (self.countries == 'all' or cc.lower() in self.countries): 48 | ip_start = ip_address(r['ip_start']) 49 | ip_version = ip_start.version 50 | if (ip_version == 4 and self.ipv4) or (ip_version == 6 and self.ipv6): 51 | inet_suffix = 'ipv' + str(ip_version) 52 | filename_key = cc + '.' + inet_suffix 53 | ip_end = ip_address(r['ip_end']) 54 | if self.ip_tables: # https://github.com/chr0mag/geoipsets/issues/25 55 | subnets = [nets.with_prefixlen for nets in summarize_address_range(ip_start, ip_end)] 56 | if filename_key in country_subnets: # append 57 | country_subnets[filename_key].extend(subnets) 58 | else: # create 59 | country_subnets[filename_key] = subnets 60 | else: # conversion not required for nftables 61 | if ip_start == ip_end: # nftables disallows intervals with the same start & end 62 | ip_range = r['ip_start'] 63 | else: 64 | ip_range = r['ip_start'] + '-' + r['ip_end'] 65 | if filename_key in country_subnets: # append 66 | country_subnets[filename_key].append(ip_range) 67 | else: # create 68 | country_subnets[filename_key] = [ip_range] 69 | 70 | self.build_sets(country_subnets) 71 | 72 | def build_sets(self, dict_of_lists): 73 | ipset_dir = self.base_dir / 'dbip/ipset' / utils.AddressFamily.IPV4.value 74 | nftset_dir = self.base_dir / 'dbip/nftset' / utils.AddressFamily.IPV4.value 75 | ip6set_dir = self.base_dir / 'dbip/ipset' / utils.AddressFamily.IPV6.value 76 | nft6set_dir = self.base_dir / 'dbip/nftset' / utils.AddressFamily.IPV6.value 77 | 78 | # remove old sets if they exist 79 | if self.ip_tables: 80 | if self.ipv4: 81 | if ipset_dir.is_dir(): 82 | shutil.rmtree(ipset_dir) 83 | ipset_dir.mkdir(parents=True) 84 | 85 | if self.ipv6: 86 | if ip6set_dir.is_dir(): 87 | shutil.rmtree(ip6set_dir) 88 | ip6set_dir.mkdir(parents=True) 89 | 90 | if self.nf_tables: 91 | if self.ipv4: 92 | if nftset_dir.is_dir(): 93 | shutil.rmtree(nftset_dir) 94 | nftset_dir.mkdir(parents=True) 95 | 96 | if self.ipv6: 97 | if nft6set_dir.is_dir(): 98 | shutil.rmtree(nft6set_dir) 99 | nft6set_dir.mkdir(parents=True) 100 | 101 | for set_name, subnets in dict_of_lists.items(): 102 | set_name_parts = set_name.split('.') 103 | country_code = set_name_parts[0] 104 | ip_version = set_name_parts[1] 105 | if ip_version == utils.AddressFamily.IPV4.value: 106 | inet_family = 'family inet' 107 | else: # AddressFamily.IPV6 108 | inet_family = 'family inet6' 109 | 110 | # write file headers 111 | if self.ip_tables: 112 | ipset_path = self.base_dir / 'dbip/ipset' / ip_version / set_name 113 | ipset_file = open(ipset_path, 'w') 114 | maxelem = max(131072, 1 if len(subnets) == 0 else (1 << (len(subnets) - 1).bit_length())) 115 | ipset_file.write("create {0} hash:net {1} maxelem {2} comment\n".format(set_name, inet_family, maxelem)) 116 | 117 | if self.nf_tables: 118 | nftset_path = self.base_dir / 'dbip/nftset' / ip_version / set_name 119 | nftset_file = open(nftset_path, 'w') 120 | nftset_file.write("define " + set_name + " = {\n") 121 | 122 | # write ranges to file(s) 123 | for subnet in subnets: 124 | if self.ip_tables: 125 | ipset_file.write("add " + set_name + " " + subnet + " comment " + country_code + "\n") 126 | 127 | if self.nf_tables: 128 | nftset_file.write(subnet + ",\n") 129 | 130 | if self.ip_tables: 131 | ipset_file.close() 132 | 133 | if self.nf_tables: 134 | nftset_file.write("}\n") 135 | nftset_file.close() 136 | 137 | def download(self): 138 | """ 139 | eg. https://download.db-ip.com/free/dbip-country-lite-2020-10.csv.gz 140 | filename: dbip-country-lite-YYYY-MM.csv.gz 141 | """ 142 | file_suffix = '.csv.gz' 143 | url = 'https://download.db-ip.com/free/dbip-country-lite-' + datetime.utcnow().strftime('%Y-%m') + file_suffix 144 | 145 | # download latest GZIP file 146 | http_response = requests.get(url) 147 | with NamedTemporaryFile(suffix=file_suffix, delete=False) as gzip_file: 148 | gzip_file.write(http_response.content) 149 | 150 | return gzip_file.name 151 | 152 | def download_checksum(self): 153 | webpage = 'https://db-ip.com/db/download/ip-to-country-lite' 154 | # download sha1sum 155 | webpage_http_response = requests.get(webpage) 156 | 157 | # the page section we're looking for looks like this: 158 | #
159 | #
Format
160 | #
CSV
161 | #
Release
162 | #
January 2022
163 | #
Supported language(s)
164 | #
English
165 | #
Number of records
166 | #
583,730
167 | #
File size
168 | #
24.7 MB
169 | #
MD5SUM
170 | #
6f58a437323f6bc891a9c8fdef96add3
171 | #
SHA1SUM
172 | #
d663790f368afa00e0ac28f2075299e1e30a5054
173 | #
174 | 175 | soup = BeautifulSoup(webpage_http_response.content, "html.parser") 176 | 177 | # we are using the CSV format, not MMDB 178 | csv_card_body = soup.find('dd', string="CSV") 179 | csv_sha1sum_tag = csv_card_body.find_next_siblings('dt', string="SHA1SUM") 180 | 181 | return csv_sha1sum_tag[0].find_next_sibling().string 182 | 183 | def check_checksum(self, csv_file_bytes): 184 | expected_sha1sum = self.download_checksum() 185 | 186 | # calculate the sha1sum of the downloaded file 187 | sha1_hash = hashlib.sha1() 188 | # Read and update hash in 8K chunks 189 | while chunk := csv_file_bytes.read(8192): 190 | sha1_hash.update(chunk) 191 | 192 | computed_sha1sum = sha1_hash.hexdigest() 193 | 194 | # reset position to beginning of file now that we're done 195 | csv_file_bytes.seek(0) 196 | 197 | # compare downloaded sha1 hash with computed version 198 | if expected_sha1sum != computed_sha1sum: 199 | raise SystemExit("ERROR: Computed CSV file digest '{0}' does not match expected value '{1}'".format( 200 | computed_sha1sum, expected_sha1sum 201 | )) 202 | -------------------------------------------------------------------------------- /python/geoipsets/maxmind.py: -------------------------------------------------------------------------------- 1 | # maxmind.py 2 | 3 | import hashlib 4 | import os 5 | import shutil 6 | from csv import DictReader 7 | from io import TextIOWrapper 8 | from pathlib import Path 9 | from tempfile import NamedTemporaryFile 10 | from zipfile import ZipFile 11 | 12 | import requests 13 | from requests.auth import HTTPBasicAuth 14 | 15 | from . import utils 16 | 17 | 18 | class MaxMindProvider(utils.AbstractProvider): 19 | """MaxMind IP range set provider.""" 20 | 21 | def __init__(self, firewall: set, address_family: set, checksum: bool, countries: set, output_dir: str, 22 | provider_options: dict): 23 | # 'provider_options' is a ConfigParser Section that can be treated as a dictionary. 24 | # Use this mechanism to introduce provider-specific options into the configuration file. 25 | super().__init__(firewall, address_family, checksum, countries, output_dir) 26 | 27 | if not (account_id := provider_options.get('account-id')): 28 | raise SystemExit("ERROR: Account ID cannot be empty") 29 | 30 | if not (license_key := provider_options.get('license-key')): 31 | raise SystemExit("ERROR: License key cannot be empty") 32 | 33 | self.auth = HTTPBasicAuth(account_id, license_key) 34 | self.base_url = 'https://download.maxmind.com/geoip/databases/GeoLite2-Country-CSV/download' 35 | 36 | def generate(self): 37 | zip_file = self.download() # comment out for testing 38 | 39 | if self.checksum: 40 | self.check_checksum(zip_file) 41 | 42 | with ZipFile(Path(zip_file.name), 'r') as zip_ref: 43 | # with ZipFile(Path("/tmp/tmp23pn2bw0.zip"), 'r') as zip_ref: # replace line above with this for testing 44 | 45 | zip_dir_prefix = os.path.commonprefix(zip_ref.namelist()) 46 | id_cc_map = self.build_id_cc_map(zip_ref, zip_dir_prefix) 47 | 48 | # TODO: run each address-family concurrently? 49 | if self.ipv4: 50 | self.build_sets(id_cc_map, zip_ref, zip_dir_prefix, utils.AddressFamily.IPV4) 51 | 52 | if self.ipv6: 53 | self.build_sets(id_cc_map, zip_ref, zip_dir_prefix, utils.AddressFamily.IPV6) 54 | 55 | def build_id_cc_map(self, zip_ref: ZipFile, dir_prefix: str): 56 | # Build dictionary mapping geoname_ids to ISO country codes 57 | # {6251999: 'CA', 1269750: 'IN'} 58 | # example row: 6251999,en,NA,"North America",CA,Canada,0 59 | # 60 | # field names: 61 | # geoname_id, locale_code, continent_code, continent_name, country_iso_code, country_name, is_in_european_union 62 | 63 | locations = 'GeoLite2-Country-Locations-en.csv' 64 | id_country_code_map = dict() 65 | with ZipFile(Path(zip_ref.filename), 'r') as zip_file: 66 | with zip_file.open(dir_prefix + locations, 'r') as csv_file_bytes: 67 | rows = DictReader(TextIOWrapper(csv_file_bytes)) 68 | for r in rows: 69 | if cc := r['country_iso_code']: 70 | # configparser forces keys to lower case by default 71 | if self.countries == 'all' or cc.lower() in self.countries: 72 | id_country_code_map[r['geoname_id']] = cc 73 | 74 | return id_country_code_map 75 | 76 | def build_sets(self, id_country_code_map: dict, zip_ref: ZipFile, dir_prefix: str, addr_fam: utils.AddressFamily): 77 | # Iterates through IP blocks and builds country-specific IP range lists. 78 | # field names: 79 | # network,geoname_id,registered_country_geoname_id,represented_country_geoname_id,is_anonymous_proxy,is_satellite_provider 80 | 81 | ipset_dir = self.base_dir / 'maxmind/ipset' / addr_fam.value 82 | nftset_dir = self.base_dir / 'maxmind/nftset' / addr_fam.value 83 | if addr_fam == utils.AddressFamily.IPV4: 84 | ip_blocks = 'GeoLite2-Country-Blocks-IPv4.csv' 85 | inet_family = 'family inet' 86 | else: # AddressFamily.IPV6 87 | ip_blocks = 'GeoLite2-Country-Blocks-IPv6.csv' 88 | inet_family = 'family inet6' 89 | 90 | # dictionary of subnet lists, indexed by filename 91 | # filename is CC.address_family -- eg. CA.ipv4 92 | country_subnets = dict() 93 | 94 | with ZipFile(Path(zip_ref.filename), 'r') as zip_file: 95 | with zip_file.open(dir_prefix + ip_blocks, 'r') as csv_file_bytes: 96 | rows = DictReader(TextIOWrapper(csv_file_bytes)) 97 | for r in rows: 98 | geo_id = r['geoname_id'] 99 | if not geo_id: 100 | geo_id = r['registered_country_geoname_id'] 101 | if not geo_id: 102 | continue 103 | 104 | try: 105 | cc = id_country_code_map[geo_id] 106 | except KeyError: 107 | continue # skip CC if not listed in the config file 108 | 109 | net = r['network'] 110 | filename_key = cc + '.' + addr_fam.value 111 | 112 | if filename_key in country_subnets: # append 113 | country_subnets[filename_key].append(net) 114 | else: # create 115 | country_subnets[filename_key] = [net] 116 | 117 | # remove old sets if they exist 118 | if self.ip_tables: 119 | if ipset_dir.is_dir(): 120 | shutil.rmtree(ipset_dir) 121 | ipset_dir.mkdir(parents=True) 122 | if self.nf_tables: 123 | if nftset_dir.is_dir(): 124 | shutil.rmtree(nftset_dir) 125 | nftset_dir.mkdir(parents=True) 126 | 127 | # 128 | # write data to disk 129 | # 130 | for set_name, subnets in country_subnets.items(): 131 | set_name_parts = set_name.split('.') 132 | country_code = set_name_parts[0] 133 | 134 | # write file headers 135 | # iptables/ipsets 136 | if self.ip_tables: 137 | ipset_file = open(ipset_dir / set_name, 'w') 138 | maxelem = max(131072, 1 if len(subnets) == 0 else (1 << (len(subnets) - 1).bit_length())) 139 | ipset_file.write("create {0} hash:net {1} maxelem {2} comment\n".format(set_name, 140 | inet_family, 141 | maxelem)) 142 | 143 | # nftables set 144 | if self.nf_tables: 145 | nftset_file = open(nftset_dir / set_name, 'w') 146 | nftset_file.write("define " + set_name + " = {\n") 147 | 148 | # write ranges to file(s) 149 | for subnet in subnets: 150 | if self.ip_tables: 151 | ipset_file.write("add " + set_name + " " + subnet + " comment " + country_code + "\n") 152 | 153 | if self.nf_tables: 154 | nftset_file.write(subnet + ",\n") 155 | 156 | if self.ip_tables: 157 | ipset_file.close() 158 | 159 | if self.nf_tables: 160 | nftset_file.write("}\n") 161 | nftset_file.close() 162 | 163 | def download(self): 164 | # URL: https://download.maxmind.com/geoip/databases/GeoLite2-Country-CSV/download 165 | # CSV query string: ?suffix=zip 166 | 167 | # The downloaded filename is available in the 'Content-Disposition' HTTP response header. 168 | # eg. Content-Disposition: attachment; filename=GeoLite2-Country-CSV_20200922.zip 169 | file_suffix = 'zip' 170 | zip_url = self.base_url + '?suffix=' + file_suffix 171 | 172 | # download latest ZIP file 173 | zip_http_response = requests.get(zip_url, auth=self.auth) 174 | with NamedTemporaryFile(suffix='.' + file_suffix, delete=False) as zip_file: 175 | zip_file.write(zip_http_response.content) 176 | 177 | return zip_file 178 | 179 | def download_checksum(self): 180 | # URL: https://download.maxmind.com/geoip/databases/GeoLite2-Country-CSV/download 181 | # SHA256 query string: ?suffix=zip.sha256 182 | file_suffix = 'zip.sha256' 183 | sha256_url = self.base_url + '?suffix=' + file_suffix 184 | sha256_http_response = requests.get(sha256_url, auth=self.auth) 185 | with NamedTemporaryFile(suffix='.' + file_suffix, delete=False) as sha256_file: 186 | sha256_file.write(sha256_http_response.content) 187 | sha256_file.seek(0) 188 | 189 | return sha256_file.read().decode('utf-8').split()[0] 190 | 191 | def check_checksum(self, zip_ref): 192 | expected_sha256sum = self.download_checksum() 193 | 194 | # calculate sha256 hash 195 | with open(zip_ref.name, 'rb') as raw_zip_file: 196 | sha256_hash = hashlib.sha256() 197 | # Read and update hash in 8K chunks 198 | while chunk := raw_zip_file.read(8192): 199 | sha256_hash.update(chunk) 200 | 201 | computed_sha256sum = sha256_hash.hexdigest() 202 | 203 | # compare downloaded sha256 hash with computed version 204 | if expected_sha256sum != computed_sha256sum: 205 | raise SystemExit("ERROR: Computed zip file digest '{0}' does not match expected value '{1}'".format( 206 | computed_sha256sum, expected_sha256sum 207 | )) 208 | -------------------------------------------------------------------------------- /python/tests/config_test.py: -------------------------------------------------------------------------------- 1 | # config_test.py 2 | 3 | import subprocess 4 | from configparser import ConfigParser 5 | from pathlib import Path 6 | 7 | import pytest 8 | 9 | from geoipsets import __main__ 10 | from geoipsets import utils 11 | 12 | 13 | def test_runas_module_help(): 14 | """ 15 | Can this package be run as a Python module? 16 | """ 17 | out = subprocess.run(['python', '-m', 'geoipsets', '--help']) 18 | assert out.returncode == 0 19 | 20 | 21 | def test_runas_module_version(): 22 | """ 23 | Does the VERSION file get read correctly when runas a module 24 | """ 25 | out = subprocess.run(['python', '-m', 'geoipsets', '--version'], capture_output=True, text=True) 26 | assert out.stdout == "geoipsets {0}".format(__main__.get_version()) 27 | 28 | 29 | def test_runas_module_invalid_option(): 30 | """ 31 | Does the script exit if an unrecognized option is provided? 32 | """ 33 | out = subprocess.run(['python', '-m', 'geoipsets', '--badopt']) 34 | assert out.returncode == 2 35 | 36 | 37 | @pytest.mark.parametrize("option", ['--provider', '--firewall', '--address-family', 38 | '--countries', '--output-dir', '--config-file']) 39 | def test_valid_option_no_value(option): 40 | """ 41 | Does the script exit if a valid option that requires a value doesn't have one? 42 | """ 43 | out = subprocess.run(['python', '-m', 'geoipsets', option]) 44 | assert out.returncode == 2 45 | 46 | 47 | @pytest.mark.parametrize("option", ['--provider', '--firewall', '--address-family']) 48 | def test_valid_option_invalid_value(option): 49 | """ 50 | Does the script exit if an invalid value is passed to a valid option 51 | """ 52 | out = subprocess.run(['python', '-m', 'geoipsets', option, 'badvalue']) 53 | assert out.returncode == 2 54 | 55 | 56 | @pytest.mark.parametrize("option, value", 57 | [('provider', 'DbIp'), 58 | ('firewall', 'NfTables'), 59 | ('address-family', 'IpV4')]) 60 | def test_cli_to_lowercase(option, value): 61 | """ 62 | Are option values lower-cased correctly? 63 | """ 64 | config = __main__.get_config(['--' + option, value]) 65 | assert config.get(option) == {value.lower()} 66 | 67 | 68 | @pytest.mark.parametrize("option, val1, val2", 69 | [('provider', 'dbip', 'maxmind'), 70 | ('firewall', utils.Firewall.NF_TABLES.value, utils.Firewall.IP_TABLES.value), 71 | ('address-family', utils.AddressFamily.IPV4.value, utils.AddressFamily.IPV6.value)]) 72 | def test_cli_single_option_multiple_values(option, val1, val2): 73 | """ 74 | Are multiple valid values passed to a single option captured correctly? 75 | """ 76 | config = __main__.get_config(['--' + option, val1, val2]) 77 | assert config.get(option) == {val1, val2} 78 | 79 | 80 | @pytest.mark.parametrize("option, val1, val2", 81 | [('provider', 'dbip', 'maxmind'), 82 | ('firewall', utils.Firewall.NF_TABLES.value, utils.Firewall.IP_TABLES.value), 83 | ('address-family', utils.AddressFamily.IPV4.value, utils.AddressFamily.IPV6.value)]) 84 | def test_cli_repeated_option_single_value(option, val1, val2): 85 | """ 86 | If the same option is specified multiple times with different values, are options captured correctly? 87 | """ 88 | config = __main__.get_config(['--' + option, val1, '--' + option, val2]) 89 | assert config.get(option) == {val1, val2} 90 | 91 | 92 | @pytest.mark.parametrize("option, value", 93 | [('provider', 'dbip'), 94 | ('firewall', utils.Firewall.IP_TABLES.value), 95 | ('address-family', utils.AddressFamily.IPV6.value)]) 96 | def test_cli_single_option_repeated_values(option, value): 97 | """ 98 | If the same value is passed to an option multiple times, is it captured correctly? 99 | """ 100 | config = __main__.get_config(['--' + option, value, value]) 101 | assert config.get(option) == {value} 102 | 103 | 104 | @pytest.mark.parametrize("option, value", 105 | [('provider', 'dbip'), 106 | ('firewall', utils.Firewall.NF_TABLES.value), 107 | ('address-family', utils.AddressFamily.IPV4.value)]) 108 | def test_cli_repeated_option_duplicate_value(option, value): 109 | """ 110 | If the same option is specified multiple times with the same valid value, are options captured correctly? 111 | """ 112 | config = __main__.get_config(['--' + option, value, '--' + option, value]) 113 | assert config.get(option) == {value} 114 | 115 | 116 | @pytest.mark.parametrize("option, expected", 117 | [('provider', {'dbip'}), 118 | ('firewall', {utils.Firewall.NF_TABLES.value}), 119 | ('address-family', {utils.AddressFamily.IPV4.value}), 120 | ('checksum', True), 121 | ('countries', 'all'), 122 | ('output-dir', '/tmp')]) 123 | def test_no_cli_opts_no_config_file(option, expected): 124 | """ 125 | Do we get all default options if no CLI opts or config file are provided? 126 | """ 127 | config = __main__.get_config() 128 | assert config.get(option) == expected 129 | 130 | 131 | @pytest.mark.parametrize("option, value, expected", 132 | [('provider', 'maxmind', {'maxmind'}), 133 | ('firewall', utils.Firewall.IP_TABLES.value, {utils.Firewall.IP_TABLES.value}), 134 | ('address-family', utils.AddressFamily.IPV6.value, {utils.AddressFamily.IPV6.value}), 135 | ('no-checksum', 'unused', False), 136 | ('countries', 'RU,CN', {'ru', 'cn'}), 137 | ('output-dir', '/var/local', '/var/local')]) 138 | def test_single_cli_opts_no_config_file(option, value, expected): 139 | """ 140 | Do single value CLI options correctly override defaults? 141 | Note: specifying 'maxmind' without license key will generate a RuntimeError during real execution 142 | """ 143 | if option == 'no-checksum': 144 | config = __main__.get_config(['--' + option]) 145 | assert not config.get('checksum') 146 | else: 147 | config = __main__.get_config(['--' + option, value]) 148 | assert config.get(option) == expected 149 | 150 | 151 | @pytest.mark.parametrize("country_list, expected", 152 | [('bad,CA', {'ca'}), 153 | ('bad1,bad2,CA', {'ca'}), 154 | ('UK,bad,CA', {'ca', 'uk'}), 155 | ('QQ,CA', {'ca', 'qq'}), # this will get ignored by providers 156 | ('CA', {'ca'}), 157 | ('bad', 'all')]) 158 | def test_invalid_country_list(country_list, expected): 159 | """ 160 | If no valid country codes are found do we correctly generate all? 161 | """ 162 | config = __main__.get_config(['-l', country_list]) 163 | assert config.get('countries') == expected 164 | 165 | 166 | @pytest.mark.parametrize("contents, expected", 167 | [('', 'all'), # empty file 168 | ('CN', {'cn'}), # no new lines 169 | ('CN ', {'cn'}), # trailing whitespace 170 | (' CN', {'cn'}), # leading whitespace 171 | ('\n\n\n CN \n\n', {'cn'}), # many empty lines 172 | ('\n\n\n CN \n\n bad\n', {'cn'}), # line with value > 2 chars 173 | ('#CN\n CA\nRU', {'ru', 'ca'}), # comment at beginning of line 174 | ('#comment\n CA # Canada\nRU \n\n', {'ru', 'ca'}) # end of line comment 175 | ]) 176 | def test_external_country_file(contents, expected, tmp_path): 177 | f_name = Path(tmp_path) / 'temp.conf' 178 | with open(f_name, 'w+t') as f: 179 | f.write(contents) 180 | 181 | config = __main__.get_config(['-l', str(f_name.resolve(strict=True))]) 182 | assert config.get('countries') == expected 183 | 184 | 185 | @pytest.mark.parametrize("option, value", 186 | [('provider', 'maxmind'), 187 | ('firewall', utils.Firewall.IP_TABLES.value), 188 | ('address-family', utils.AddressFamily.IPV6.value)]) 189 | def test_config_file_non_defaults(option, value, monkeypatch): 190 | """ 191 | If non-default options are set in a config file, and no CLI args are present, are they used? 192 | """ 193 | 194 | def mockreturn(path): 195 | cp = ConfigParser(allow_no_value=True) 196 | cp.read_string( 197 | """ 198 | [general] 199 | {0}={1} 200 | [countries] 201 | CA 202 | """.format(option, value)) 203 | return cp 204 | 205 | monkeypatch.setattr(__main__, "get_config_parser", mockreturn, raising=True) 206 | 207 | config = __main__.get_config(['-c', '/tmp/dummy.conf']) 208 | assert config.get(option) == {value} 209 | assert config.get('countries') == {'ca'} 210 | 211 | 212 | @pytest.mark.parametrize("option, value", 213 | [('provider', 'maxmind'), 214 | ('firewall', utils.Firewall.IP_TABLES.value), 215 | ('address-family', utils.AddressFamily.IPV6.value), 216 | ('no-checksum', 'unused'), 217 | ('countries', 'ru')]) 218 | def test_config_file_cli_args_precedence(option, value, monkeypatch): 219 | """ 220 | Do CLI args take precedence over config-file options? 221 | """ 222 | 223 | def mockreturn(path): 224 | cp = ConfigParser(allow_no_value=True) 225 | cp.read_string( 226 | """ 227 | [general] 228 | provider=dbip 229 | firewall=nftables 230 | address-family=ipv4 231 | checksum=True 232 | [countries] 233 | CA 234 | """) 235 | return cp 236 | 237 | monkeypatch.setattr(__main__, "get_config_parser", mockreturn, raising=True) 238 | 239 | if option == 'no-checksum': 240 | config = __main__.get_config(['--' + option, '-c', '/tmp/dummy.conf']) 241 | assert not config.get('checksum') 242 | else: 243 | config = __main__.get_config(['--' + option, value, '-c', '/tmp/dummy.conf']) 244 | assert config.get(option) == {value} 245 | 246 | 247 | @pytest.mark.parametrize("provider", 248 | ['maxmind', 'dbip']) 249 | def test_config_file_provider_options(provider, monkeypatch): 250 | """ 251 | If non-default options are set in a config file, and no CLI args are present, are they used? 252 | """ 253 | 254 | def mockreturn(path): 255 | cp = ConfigParser(allow_no_value=True) 256 | cp.read_string( 257 | """ 258 | [general] 259 | provider={0} 260 | [countries] 261 | CA 262 | [{0}] 263 | license-key=abcdefg 264 | custom-option=custom-value 265 | """.format(provider)) 266 | return cp 267 | 268 | monkeypatch.setattr(__main__, "get_config_parser", mockreturn, raising=True) 269 | 270 | config = __main__.get_config(['-c', '/tmp/dummy.conf']) 271 | assert config.get(provider) == {'license-key': 'abcdefg', 'custom-option': 'custom-value'} 272 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------