├── .dockerignore ├── .github └── workflows │ ├── docker.yml │ ├── main.yml │ ├── pypi_release.yml │ └── windows.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .travis.yml ├── AUTHORS ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── MANIFEST.in ├── README.md ├── VERSION ├── aclcheck_cmdline.py ├── capirca ├── __init__.py ├── aclgen.py ├── lib │ ├── COPYING │ ├── __init__.py │ ├── aclcheck.py │ ├── aclgenerator.py │ ├── arista.py │ ├── arista_tp.py │ ├── aruba.py │ ├── brocade.py │ ├── cisco.py │ ├── ciscoasa.py │ ├── cisconx.py │ ├── ciscoxr.py │ ├── cloudarmor.py │ ├── demo.py │ ├── fortigate.py │ ├── fortigatelocalin.py │ ├── gce.py │ ├── gce_vpc_tf.py │ ├── gcp.py │ ├── gcp_hf.py │ ├── ipset.py │ ├── iptables.py │ ├── juniper.py │ ├── juniperevo.py │ ├── junipermsmpc.py │ ├── junipersrx.py │ ├── k8s.py │ ├── nacaddr.py │ ├── naming.py │ ├── nftables.py │ ├── nsxt.py │ ├── nsxv.py │ ├── openconfig.py │ ├── packetfilter.py │ ├── paloaltofw.py │ ├── pcap.py │ ├── policy.py │ ├── policy_simple.py │ ├── policyreader.py │ ├── port.py │ ├── sonic.py │ ├── speedway.py │ ├── srxlo.py │ ├── summarizer.py │ ├── versa.py │ ├── windows.py │ ├── windows_advfirewall.py │ └── windows_ipsec.py └── utils │ ├── __init__.py │ ├── config.py │ └── iputils.py ├── def ├── LARGE_NETWORK.net ├── NETWORK.net └── SERVICES.svc ├── dev-install ├── doc ├── generator_patterns.md ├── generators │ ├── arista.md │ ├── arista_tp.md │ ├── aruba.md │ ├── brocade.md │ ├── cisco.md │ ├── ciscoasa.md │ ├── cisconx.md │ ├── ciscoxr.md │ ├── gce.md │ ├── gce_vpc_tf.md │ ├── ipset.md │ ├── iptables.md │ ├── juniper.md │ ├── juniperevo.md │ ├── junipermsmpc.md │ ├── junipersrx.md │ ├── k8s.md │ ├── nftables.md │ ├── nsxt.md │ ├── nsxv.md │ ├── packetfilter.md │ ├── paloaltofw.md │ ├── pcap.md │ ├── sonic.md │ ├── speedway.md │ ├── srxlo.md │ ├── versa.md │ └── windows_advfirewall.md └── wiki │ ├── AclCheck-library.md │ ├── Capirca-design.md │ ├── Naming-library.md │ ├── Policy-library.md │ └── PolicyReader-library.md ├── make_dist.sh ├── policies ├── includes │ └── untrusted-networks-blocking.inc └── pol │ ├── sample_arista_tp.pol │ ├── sample_cisco_lab.pol │ ├── sample_cisconx.pol │ ├── sample_cloudarmor.pol │ ├── sample_fortigate.pol │ ├── sample_fortigate_localin.pol │ ├── sample_fortigate_localin_ipv4.pol │ ├── sample_fortigate_localin_ipv6.pol │ ├── sample_gce.pol │ ├── sample_gce_vpc_tf.pol │ ├── sample_gcp_hf.pol │ ├── sample_inet6_gce.pol │ ├── sample_inet6_gcp_hf.pol │ ├── sample_ipset.pol │ ├── sample_juniper_loopback.pol │ ├── sample_juniperevo_loopback.pol │ ├── sample_k8s.pol │ ├── sample_mixed_gce.pol │ ├── sample_mixed_gcp_hf.pol │ ├── sample_msmpc.pol │ ├── sample_multitarget.pol │ ├── sample_nftables-dev.pol │ ├── sample_nftables-mixed-icmp.pol │ ├── sample_nftables-mixed-multiple-headers-combo.pol │ ├── sample_nftables.pol │ ├── sample_nsxt.pol │ ├── sample_nsxv.pol │ ├── sample_openconfig.pol │ ├── sample_packetfilter.pol │ ├── sample_paloalto.pol │ ├── sample_sonic.pol │ ├── sample_speedway.pol │ ├── sample_srx.pol │ ├── sample_stateful_multitarget_complex.pol │ ├── sample_stateful_multitarget_simple.pol │ └── sample_versa.pol ├── policy.bzl ├── requirements.txt ├── setup.cfg ├── setup.py ├── test-requirements.txt ├── tests ├── README ├── __init__.py ├── integration │ ├── __init__.py │ └── aclgen_test.py ├── lib │ ├── __init__.py │ ├── aclcheck_test.py │ ├── aclgenerator_test.py │ ├── arista_test.py │ ├── arista_tp_test.py │ ├── aruba_test.py │ ├── brocade_test.py │ ├── cgrep_test.py │ ├── cisco_test.py │ ├── ciscoasa_test.py │ ├── cisconx_test.py │ ├── ciscoxr_test.py │ ├── cloudarmor_test.py │ ├── fortigate_test.py │ ├── fortigatelocalin_test.py │ ├── gce_test.py │ ├── gce_vpc_tf_test.py │ ├── gcp_hf_test.py │ ├── gcp_test.py │ ├── ipset_test.py │ ├── iptables_test.py │ ├── juniper_test.py │ ├── juniperevo_test.py │ ├── junipermsmpc_test.py │ ├── junipersrx_test.py │ ├── k8s_test.py │ ├── nacaddr_test.py │ ├── naming_test.py │ ├── nftables_test.py │ ├── nsxt_test.py │ ├── nsxv_mocktest.py │ ├── nsxv_test.py │ ├── openconfig_test.py │ ├── packetfilter_test.py │ ├── paloaltofw_test.py │ ├── pcap_test.py │ ├── policy_simple_test.py │ ├── policy_test.py │ ├── sonic_test.py │ ├── speedway_test.py │ ├── srxlo_test.py │ ├── summarizer_test.py │ ├── versa_test.py │ ├── windows_advfirewall_test.py │ ├── windows_ipsec_test.py │ └── windows_test.py ├── unit │ └── wrapwords_test.py └── utils │ ├── __init__.py │ ├── address_exclude_test_cases.txt │ └── iputils_test.py └── tools ├── __init__.py ├── cgrep.py ├── current_lint_errors.txt ├── get-country-zones.pl ├── iputilstools.py ├── pylintrc └── run_lint.sh /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.git 2 | .git 3 | gha-creds-*.json 4 | -------------------------------------------------------------------------------- /.github/workflows/docker.yml: -------------------------------------------------------------------------------- 1 | name: Docker Publish 2 | 3 | permissions: 4 | packages: write 5 | contents: read 6 | 7 | on: 8 | push: 9 | branches: 10 | - master 11 | 12 | env: 13 | IMAGE_NAME: capirca 14 | 15 | jobs: 16 | build: 17 | name: "Build Capirca container" 18 | runs-on: ubuntu-latest 19 | 20 | steps: 21 | - uses: actions/checkout@v4 22 | - name: Log into registry 23 | run: | 24 | echo "${{ secrets.GITHUB_TOKEN }}" | docker login docker.pkg.github.com -u ${{ github.actor }} --password-stdin 25 | 26 | - name: Build and tag the image 27 | run: docker build . --tag $IMAGE_NAME 28 | 29 | - name: Push the image to the container registry 30 | run: | 31 | IMAGE_ID="docker.pkg.github.com/${{ github.repository }}/$IMAGE_NAME" 32 | 33 | # Change all uppercase to lowercase 34 | IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') 35 | 36 | VERSION=$(cat VERSION) 37 | 38 | docker tag $IMAGE_NAME $IMAGE_ID:latest 39 | docker tag $IMAGE_NAME $IMAGE_ID:$VERSION 40 | 41 | docker push $IMAGE_ID:latest 42 | docker push $IMAGE_ID:$VERSION 43 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Python package 3 | 4 | on: 5 | push: 6 | branches: [ master ] 7 | pull_request: 8 | branches: [ master ] 9 | 10 | jobs: 11 | build: 12 | timeout-minutes: 20 13 | strategy: 14 | fail-fast: true 15 | matrix: 16 | python-version: [3.6, 3.7, 3.8, 3.9] 17 | include: 18 | - os-version: ubuntu-latest 19 | - python-version: 3.6 20 | os-version: ubuntu-20.04 21 | runs-on: ${{ matrix.os-version }} 22 | 23 | 24 | steps: 25 | - name: Checkout branch with changes 26 | uses: actions/checkout@v4 27 | with: 28 | path: current 29 | - name: Checkout master branch 30 | uses: actions/checkout@v4 31 | with: 32 | path: master 33 | ref: master 34 | - name: Set up Node.js 35 | uses: actions/setup-node@v4 36 | with: 37 | node-version: '14' 38 | - name: Set up Python ${{ matrix.python-version }} 39 | uses: actions/setup-python@v5 40 | with: 41 | python-version: ${{ matrix.python-version }} 42 | - name: Setup environment variables 43 | run: | 44 | mkdir -p artifacts 45 | echo "wfdt=$(date +'%Y%m%d_%H%M%S')" >> $GITHUB_ENV 46 | - name: Install dependencies 47 | run: | 48 | sudo apt update 49 | sudo apt install unzip zip 50 | python -m pip install --upgrade pip 51 | python -m pip install setuptools wheel 52 | python -m pip install flake8 pytest 53 | cd current 54 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 55 | if [ -f test-requirements.txt ]; then pip install -r test-requirements.txt; fi 56 | - name: Lint with flake8 57 | run: | 58 | cd current 59 | flake8 . --count --select=W291,W293,W391 --statistic 60 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 61 | flake8 . --count --exit-zero --max-complexity=10 \ 62 | --max-line-length=127 --statistics 63 | - name: Test with pytest 64 | run: | 65 | cd current 66 | pytest 67 | - name: Perform end-to-end testing with current branch or pull request 68 | run: | 69 | cd current 70 | git status 71 | python setup.py sdist bdist_wheel 72 | python3 -m pip -v install dist/capirca*py3*.whl 73 | aclgen --output_directory ./output --logtostderr 74 | cd ./output/ && \ 75 | zip -r ../../artifacts/capirca_output_${{ env.wfdt }}.zip . 76 | cd .. 77 | python3 -m pip -v uninstall -y capirca 78 | - name: Perform end-to-end testing with master branch 79 | run: | 80 | cd master 81 | git status 82 | python setup.py sdist bdist_wheel 83 | python3 -m pip -v install dist/capirca*py3*.whl 84 | aclgen --output_directory ./output --logtostderr 85 | python3 -m pip -v uninstall -y capirca 86 | - name: Compare output files between the branches 87 | run: | 88 | mkdir -p artifacts-diff 89 | sudo npm install -g diff2html diff2html-cli 90 | diff2html --version 91 | diff -qr current/output master/output > \ 92 | ./artifacts-diff/policy_output.diff | true 93 | cat ./artifacts-diff/policy_output.diff | grep Files | grep differ \ 94 | | cut -d" " -f2 | cut -d "/" -f3 > ./artifacts-diff/files.list 95 | while read p; do diff -u master/output/$p current/output/$p | \ 96 | diff2html -i stdin --file ./artifacts-diff/$p.html | \ 97 | true; done < ./artifacts-diff/files.list 98 | sed -i '/Diff to HTML by/d' ./artifacts-diff/* 99 | - name: Upload generated policies 100 | uses: actions/upload-artifact@v4 101 | with: 102 | name: capirca_output_${{ matrix.python-version }}_${{ env.wfdt }} 103 | path: ./artifacts/capirca_output_${{ env.wfdt }}.zip 104 | - name: Upload policy differences 105 | uses: actions/upload-artifact@v4 106 | with: 107 | name: capirca_output_policy_diff 108 | path: ./artifacts-diff 109 | -------------------------------------------------------------------------------- /.github/workflows/pypi_release.yml: -------------------------------------------------------------------------------- 1 | name: Upload Python Package 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | deploy: 9 | 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v4 14 | - name: Set up Python 15 | uses: actions/setup-python@v5 16 | with: 17 | python-version: '3.x' 18 | - name: Install dependencies 19 | run: | 20 | python -m pip install --upgrade pip 21 | pip install setuptools wheel twine 22 | - name: Build and publish 23 | env: 24 | TWINE_USERNAME: __token__ 25 | TWINE_PASSWORD: ${{ secrets.PYPI_APIKEY }} 26 | run: | 27 | python setup.py sdist bdist_wheel 28 | twine upload dist/* 29 | -------------------------------------------------------------------------------- /.github/workflows/windows.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Python Package for Windows 3 | 4 | on: 5 | push: 6 | branches: [ master ] 7 | pull_request: 8 | branches: [ master ] 9 | 10 | jobs: 11 | build: 12 | runs-on: windows-latest 13 | timeout-minutes: 20 14 | strategy: 15 | fail-fast: true 16 | matrix: 17 | python-version: [3.8, 3.9] 18 | 19 | steps: 20 | - uses: actions/checkout@v4 21 | - name: Set up Python ${{ matrix.python-version }} 22 | uses: actions/setup-python@v5 23 | with: 24 | python-version: ${{ matrix.python-version }} 25 | - uses: actions/cache@v4 26 | with: 27 | path: ~\AppData\Local\pip\Cache 28 | key: ${{ runner.os }}-${{ matrix.python-version}}-pip-test-${{ hashFiles('setup.py','requirements.txt','test-requirements.txt') }} 29 | restore-keys: | 30 | ${{ runner.os }}-${{ matrix.python-version}}-pip-test- 31 | ${{ runner.os }}-${{ matrix.python-version}}-pip- 32 | ${{ runner.os }}-${{ matrix.python-version}}- 33 | - name: Add msbuild to PATH 34 | uses: microsoft/setup-msbuild@v1.3.3 35 | - name: Install dependencies 36 | run: | 37 | python -m pip install --upgrade pip 38 | python -m pip install setuptools wheel 39 | python -m pip install flake8 pytest 40 | python -m pip install -r test-requirements.txt 41 | python -m pip install -r requirements.txt 42 | - name: Build, install, and run 43 | run: | 44 | python setup.py sdist bdist_wheel 45 | python -m pip -v install --find-links=dist --no-index capirca 46 | aclgen --output_directory .\output --logtostderr 47 | powershell Compress-Archive -Force output\* output.zip 48 | - name: Upload generated policies 49 | uses: actions/upload-artifact@v4 50 | with: 51 | name: capirca_output_${{ matrix.python-version }} 52 | path: ./output.zip 53 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated files 2 | filters/sample_* 3 | sample_* 4 | def/AUTOGEN.net 5 | tests/characterization_data/filters_actual 6 | tools/new_lint_errors.txt 7 | 8 | # Exclude secrets 9 | gha-creds-*.json 10 | 11 | # Recommended python excludes 12 | # Byte-compiled / optimized / DLL files 13 | __pycache__/ 14 | *.py[cod] 15 | *$py.class 16 | 17 | # C extensions 18 | *.so 19 | 20 | # Distribution / packaging 21 | .Python 22 | build/ 23 | develop-eggs/ 24 | dist/ 25 | downloads/ 26 | eggs/ 27 | .eggs/ 28 | lib/ 29 | lib64/ 30 | parts/ 31 | sdist/ 32 | var/ 33 | wheels/ 34 | share/python-wheels/ 35 | *.egg-info/ 36 | .installed.cfg 37 | *.egg 38 | MANIFEST 39 | 40 | # PyInstaller 41 | # Usually these files are written by a python script from a template 42 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 43 | *.manifest 44 | *.spec 45 | 46 | # Installer logs 47 | pip-log.txt 48 | pip-delete-this-directory.txt 49 | 50 | # Unit test / coverage reports 51 | htmlcov/ 52 | .tox/ 53 | .nox/ 54 | .coverage 55 | .coverage.* 56 | .cache 57 | nosetests.xml 58 | coverage.xml 59 | *.cover 60 | *.py,cover 61 | .hypothesis/ 62 | .pytest_cache/ 63 | cover/ 64 | 65 | # Translations 66 | *.mo 67 | *.pot 68 | 69 | # Django stuff: 70 | *.log 71 | local_settings.py 72 | db.sqlite3 73 | db.sqlite3-journal 74 | 75 | # Flask stuff: 76 | instance/ 77 | .webassets-cache 78 | 79 | # Scrapy stuff: 80 | .scrapy 81 | 82 | # Sphinx documentation 83 | docs/_build/ 84 | 85 | # PyBuilder 86 | .pybuilder/ 87 | target/ 88 | 89 | # Jupyter Notebook 90 | .ipynb_checkpoints 91 | 92 | # IPython 93 | profile_default/ 94 | ipython_config.py 95 | 96 | # pyenv 97 | # For a library or package, you might want to ignore these files since the code is 98 | # intended to run in multiple environments; otherwise, check them in: 99 | # .python-version 100 | 101 | # pipenv 102 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 103 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 104 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 105 | # install all needed dependencies. 106 | #Pipfile.lock 107 | 108 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 109 | __pypackages__/ 110 | 111 | # Celery stuff 112 | celerybeat-schedule 113 | celerybeat.pid 114 | 115 | # SageMath parsed files 116 | *.sage.py 117 | 118 | # Environments 119 | .env 120 | .venv 121 | env/ 122 | venv/ 123 | ENV/ 124 | env.bak/ 125 | venv.bak/ 126 | 127 | # Spyder project settings 128 | .spyderproject 129 | .spyproject 130 | 131 | # VSCode project settings 132 | .vscode/ 133 | 134 | # Rope project settings 135 | .ropeproject 136 | 137 | # mkdocs documentation 138 | /site 139 | 140 | # mypy 141 | .mypy_cache/ 142 | .dmypy.json 143 | dmypy.json 144 | 145 | # Pyre type checker 146 | .pyre/ 147 | 148 | # pytype static type analyzer 149 | .pytype/ 150 | 151 | # Cython debug symbols 152 | cython_debug/ 153 | output/ 154 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/PyCQA/flake8 3 | rev: '3.8.3' 4 | hooks: 5 | - id: flake8 6 | - repo: https://github.com/pre-commit/pre-commit-hooks 7 | rev: v3.1.0 8 | hooks: 9 | - id: check-executables-have-shebangs 10 | - id: debug-statements 11 | - id: detect-private-key 12 | - id: end-of-file-fixer 13 | - id: requirements-txt-fixer 14 | - id: trailing-whitespace 15 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.6" 4 | - "3.7" 5 | # command to install dependencies 6 | install: "pip install -r requirements.txt -r test-requirements.txt . && pip install flake8" 7 | # command to run tests 8 | script: 9 | - pytest 10 | - flake8 . --count --select=W291,W293,W391 --statistic 11 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | # This is the official list of Capirca authors for copyright purposes. 2 | # This file is distinct from the CONTRIBUTORS files. 3 | # See the latter for an explanation. 4 | 5 | # Names should be added to this file as: 6 | # Name or Organization 7 | # The email address is not required for organizations. 8 | Google Inc 9 | VMWare Inc 10 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Before contributing to Capirca please take into mind the following. 4 | 5 | ## Contributors License Agreements 6 | 7 | We require everyone who submits code to us to sign the 8 | [Contributors License Agreement](https://cla.developers.google.com/clas). 9 | Please take the time to sign this before sending us a Pull Request. 10 | 11 | ## Code Readability 12 | 13 | Please take time to become familiar with the 14 | [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html). 15 | We try to adhere to the rules in the guide as much as possible. To help with 16 | that you can use our 17 | [lint tool](https://github.com/google/capirca/blob/master/tools/run_lint.sh). 18 | This runs pylint over the files and will display new lint errors. This will 19 | not catch certain style choices but it will find a majority of problems that 20 | are easy to fix. If you feel a lint error is incorrect let us know and we can 21 | suppress it. 22 | 23 | ## Development Environment 24 | 25 | Run the following script to install `capirca` in development environment. 26 | 27 | ```bash 28 | dev-install 29 | ``` 30 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.6-alpine 2 | 3 | WORKDIR /app 4 | 5 | COPY requirements.txt . 6 | 7 | RUN pip install -r requirements.txt 8 | 9 | COPY . /app 10 | 11 | RUN pip install . 12 | 13 | WORKDIR /data 14 | 15 | ENTRYPOINT ["aclgen"] 16 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS 2 | include LICENSE 3 | include README.md 4 | include aclcheck_cmdline.py 5 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 2.0.9 2 | -------------------------------------------------------------------------------- /aclcheck_cmdline.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Google Inc. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | 16 | """Command line interface to aclcheck library.""" 17 | 18 | from optparse import OptionParser 19 | 20 | from capirca.lib import aclcheck 21 | from capirca.lib import naming 22 | from capirca.lib import policy 23 | 24 | 25 | def main(): 26 | # TODO(robankeny): Lets move this to gflags 27 | usage = 'usage: %prog [options] arg' 28 | _parser = OptionParser(usage) 29 | _parser.add_option('--definitions-directory', dest='definitions', 30 | help='definitions directory', default='./def') 31 | _parser.add_option('-p', '--policy-file', dest='pol', 32 | help='policy file', default='./policies/sample.pol') 33 | _parser.add_option('-d', '--destination', dest='dst', 34 | help='destination IP', default='200.1.1.1') 35 | _parser.add_option('-s', '--source', dest='src', 36 | help='source IP', default='any') 37 | _parser.add_option('--proto', '--protocol', dest='proto', 38 | help='Protocol (tcp, udp, icmp, etc.)', default='tcp') 39 | _parser.add_option('--dport', '--destination-port', dest='dport', 40 | help='destination port', default='80') 41 | _parser.add_option('--sport', '--source-port', dest='sport', 42 | help='source port', default='1025') 43 | (FLAGS, unused_args) = _parser.parse_args() 44 | 45 | defs = naming.Naming(FLAGS.definitions) 46 | policy_obj = policy.ParsePolicy(open(FLAGS.pol).read(), defs) 47 | check = aclcheck.AclCheck(policy_obj, src=FLAGS.src, dst=FLAGS.dst, 48 | sport=FLAGS.sport, dport=FLAGS.dport, 49 | proto=FLAGS.proto) 50 | print(str(check)) 51 | 52 | if __name__ == '__main__': 53 | main() 54 | -------------------------------------------------------------------------------- /capirca/__init__.py: -------------------------------------------------------------------------------- 1 | """Capirca.""" 2 | -------------------------------------------------------------------------------- /capirca/lib/__init__.py: -------------------------------------------------------------------------------- 1 | """Libraries for Capirca.""" 2 | -------------------------------------------------------------------------------- /capirca/lib/arista.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Google Inc. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | 16 | """Arista generator.""" 17 | 18 | from capirca.lib import cisco 19 | 20 | 21 | class Error(Exception): 22 | """Base error class.""" 23 | 24 | 25 | class UnsupportedEosAccessListError(Error): 26 | """When a filter type is not supported in an EOS policy target.""" 27 | 28 | 29 | class Arista(cisco.Cisco): 30 | """An Arista policy object. 31 | 32 | EOS devices differ slightly from Cisco, omitting the extended argument to 33 | ACLs for example. There are other items such as 'tracked' we may want to add 34 | in the future. 35 | """ 36 | 37 | _PLATFORM = 'arista' 38 | SUFFIX = '.eacl' 39 | # Protocols should be emitted as they were in the policy (names). 40 | _PROTO_INT = False 41 | 42 | # Arista omits the "extended" access-list argument. 43 | def _AppendTargetByFilterType( 44 | self, filter_name, filter_type, configure_replace_compatible=False): 45 | """Takes in the filter name and type and appends headers. 46 | 47 | Args: 48 | filter_name: Name of the current filter 49 | filter_type: Type of current filter 50 | configure_replace_compatible: Bool indicating if the resulting config 51 | strings should be compatible with the configure replace command. 52 | 53 | Returns: 54 | list of strings 55 | 56 | Raises: 57 | UnsupportedEosAccessListError: When unknown filter type is used. 58 | """ 59 | # `configure_replace_compatible` is included to satisfy the signature 60 | # requirements for cisco.Cisco._AppendTargetByFilterType(). This is not 61 | # currently required for the arista module. 62 | del configure_replace_compatible 63 | target = [] 64 | if filter_type == 'standard': 65 | if filter_name.isdigit(): 66 | target.append('no access-list %s' % filter_name) 67 | else: 68 | target.append('no ip access-list standard %s' % filter_name) 69 | target.append('ip access-list standard %s' % filter_name) 70 | elif filter_type == 'extended': 71 | target.append('no ip access-list %s' % filter_name) 72 | target.append('ip access-list %s' % filter_name) 73 | elif filter_type == 'object-group': 74 | target.append('no ip access-list %s' % filter_name) 75 | target.append('ip access-list %s' % filter_name) 76 | elif filter_type == 'inet6': 77 | target.append('no ipv6 access-list %s' % filter_name) 78 | target.append('ipv6 access-list %s' % filter_name) 79 | else: 80 | raise UnsupportedEosAccessListError( 81 | 'access list type %s not supported by %s' % ( 82 | filter_type, self._PLATFORM)) 83 | return target 84 | 85 | def __str__(self, **kwargs): 86 | # Parent Cisco is generating "exit" at the end, which needs to be indentated 87 | # for correct Arista syntax parsing. 88 | s = super().__str__(**kwargs) 89 | lines = s.split('\n') 90 | while lines and not lines[-1]: 91 | lines = lines[:-1] 92 | if lines and lines[-1] == 'exit': 93 | lines[-1] = ' exit' 94 | lines.append('') 95 | return '\n'.join(lines) 96 | return s 97 | -------------------------------------------------------------------------------- /capirca/lib/brocade.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Google Inc. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | 16 | """Brocade generator.""" 17 | 18 | from capirca.lib import cisco 19 | 20 | 21 | class Brocade(cisco.Cisco): 22 | """A brocade policy object. 23 | 24 | Brocade devices do not like protocol numbers. Revert the protocol numbers to 25 | names just before emitting acl lines to minimize difference from Cisco logic. 26 | """ 27 | 28 | _PLATFORM = 'brocade' 29 | SUFFIX = '.bacl' 30 | # Protocols should be emitted as they were in the policy (names). 31 | _PROTO_INT = False 32 | _TERM_REMARK = False 33 | -------------------------------------------------------------------------------- /capirca/lib/cisconx.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 Google Inc. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | """CiscoNX generator.""" 16 | 17 | from capirca.lib import aclgenerator 18 | from capirca.lib import cisco 19 | 20 | 21 | class Error(Exception): 22 | """Base error class.""" 23 | 24 | 25 | class UnsupportedNXosAccessListError(Error): 26 | """When a filter type is not supported in an NXOS policy target.""" 27 | 28 | 29 | class CiscoNX(cisco.Cisco): 30 | """An CiscoNX policy object. 31 | 32 | CiscoNX devices differ slightly from Cisco, omitting the extended argument to 33 | ACLs for example. 34 | """ 35 | 36 | _PLATFORM = 'cisconx' 37 | SUFFIX = '.nxacl' 38 | # Protocols should be emitted as they were in the policy (names). 39 | _PROTO_INT = False 40 | 41 | def _RepositoryTagsHelper(self, target=None, filter_type='', filter_name=''): 42 | if target is None: 43 | target = [] 44 | target.extend(aclgenerator.AddRepositoryTags( 45 | ' remark ', rid=False, wrap=True)) 46 | return target 47 | 48 | # CiscoNX omits the "extended" access-list argument. 49 | def _AppendTargetByFilterType( 50 | self, filter_name, filter_type, configure_replace_compatible=False): 51 | """Takes in the filter name and type and appends headers. 52 | 53 | Args: 54 | filter_name: Name of the current filter 55 | filter_type: Type of current filter 56 | configure_replace_compatible: Bool indicating if the resulting config 57 | strings should be compatible with the configure replace command. 58 | 59 | Returns: 60 | list of strings 61 | 62 | Raises: 63 | UnsupportedNXosAccessListError: When unknown filter type is used. 64 | """ 65 | # `configure_replace_compatible` is included to satisfy the signature 66 | # requirements for cisco.Cisco._AppendTargetByFilterType(). This is not 67 | # currently required for the cisconx module. 68 | del configure_replace_compatible 69 | target = [] 70 | if filter_type == 'extended': 71 | target.append('no ip access-list %s' % filter_name) 72 | target.append('ip access-list %s' % filter_name) 73 | elif filter_type == 'object-group': 74 | target.append('no ip access-list %s' % filter_name) 75 | target.append('ip access-list %s' % filter_name) 76 | elif filter_type == 'inet6' or filter_type == 'object-group-inet6': 77 | target.append('no ipv6 access-list %s' % filter_name) 78 | target.append('ipv6 access-list %s' % filter_name) 79 | else: 80 | raise UnsupportedNXosAccessListError( 81 | 'access list type %s not supported by %s' % 82 | (filter_type, self._PLATFORM)) 83 | return target 84 | -------------------------------------------------------------------------------- /capirca/lib/ciscoxr.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Google Inc. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | 16 | """Cisco IOS-XR filter renderer.""" 17 | 18 | from capirca.lib import cisco 19 | 20 | 21 | class CiscoXR(cisco.Cisco): 22 | """A cisco policy object.""" 23 | 24 | _PLATFORM = 'ciscoxr' 25 | _DEFAULT_PROTOCOL = 'ip' 26 | SUFFIX = '.xacl' 27 | _PROTO_INT = False 28 | 29 | def _AppendTargetByFilterType( 30 | self, filter_name, filter_type, configure_replace_compatible=False): 31 | """Takes in the filter name and type and appends headers. 32 | 33 | Args: 34 | filter_name: Name of the current filter 35 | filter_type: Type of current filter 36 | configure_replace_compatible: Bool indicating if the resulting config 37 | strings should be compatible with the configure replace command. 38 | 39 | Returns: 40 | list of strings 41 | """ 42 | # `configure_replace_compatible` is included to satisfy the signature 43 | # requirements for cisco.Cisco._AppendTargetByFilterType(). This is not 44 | # currently required for the ciscoxr module. 45 | del configure_replace_compatible 46 | target = [] 47 | if filter_type == 'inet6' or filter_type == 'object-group-inet6': 48 | target.append('no ipv6 access-list %s' % filter_name) 49 | target.append('ipv6 access-list %s' % filter_name) 50 | else: 51 | target.append('no ipv4 access-list %s' % filter_name) 52 | target.append('ipv4 access-list %s' % filter_name) 53 | return target 54 | 55 | def _BuildTokens(self): 56 | """Build supported tokens for platform. 57 | 58 | Returns: 59 | tuple containing both supported tokens and sub tokens 60 | """ 61 | supported_tokens, supported_sub_tokens = super()._BuildTokens() 62 | 63 | supported_tokens |= {'next_ip'} 64 | 65 | return supported_tokens, supported_sub_tokens 66 | 67 | def _GetObjectGroupTerm(self, term, filter_name, af=4, verbose=True): 68 | """Returns an ObjectGroupTerm object.""" 69 | return CiscoXRObjectGroupTerm(term, filter_name, af=af, 70 | platform=self._PLATFORM, verbose=verbose) 71 | 72 | 73 | class CiscoXRObjectGroupTerm(cisco.ObjectGroupTerm): 74 | ALLOWED_PROTO_STRINGS = cisco.Term.ALLOWED_PROTO_STRINGS + ['pcp', 'esp'] 75 | -------------------------------------------------------------------------------- /capirca/lib/fortigatelocalin.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Google Inc. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Fortigate local-in generator. 16 | 17 | This is a subclass of Fortigate generator. 18 | """ 19 | 20 | from capirca.lib import fortigate 21 | 22 | 23 | class FortigateLocalIn(fortigate.Fortigate): 24 | """Fortigate local-in generator.""" 25 | 26 | _PLATFORM = 'fortigatelocalin' 27 | 28 | def __str__(self): 29 | fw_policies = self._get_fw_policies() 30 | 31 | start_sys_settings = ['config sys setting'] 32 | start_addresses_v4 = ['config firewall address'] 33 | start_addresses_v6 = ['config firewall address6'] 34 | start_addrgrps_v4 = ['config firewall addrgrp'] 35 | start_addrgrps_v6 = ['config firewall addrgrp6'] 36 | start_services = ['config firewall service custom'] 37 | start_svcgrps = ['config firewall service group'] 38 | start_schedules = ['config firewall schedule onetime'] 39 | start_policies = ['config firewall local-in-policy'] 40 | end = ['end'] 41 | 42 | sys_settings = [] 43 | if self._obj_container.get_sys_settings(): 44 | sys_settings = start_sys_settings + \ 45 | self._obj_container.get_sys_settings() + \ 46 | end + [''] 47 | 48 | fw_addresses = [] 49 | if self._obj_container.get_fw_addresses(4): 50 | fw_addresses += start_addresses_v4 + \ 51 | self._obj_container.get_fw_addresses(4) + \ 52 | end + [''] 53 | if self._obj_container.get_fw_addresses(6): 54 | fw_addresses += start_addresses_v6 + \ 55 | self._obj_container.get_fw_addresses(6) + \ 56 | end + [''] 57 | 58 | fw_addr_grps = [] 59 | if self._obj_container.get_fw_addrgrps(4): 60 | fw_addr_grps += start_addrgrps_v4 + \ 61 | self._obj_container.get_fw_addrgrps(4) + \ 62 | end + [''] 63 | if self._obj_container.get_fw_addrgrps(6): 64 | fw_addr_grps += start_addrgrps_v6 + \ 65 | self._obj_container.get_fw_addrgrps(6) + \ 66 | end + [''] 67 | 68 | fw_services = [] 69 | if self._obj_container.get_fw_services(): 70 | fw_services = start_services + \ 71 | self._obj_container.get_fw_services() + \ 72 | end + [''] 73 | 74 | fw_svc_grps = [] 75 | if self._obj_container.get_fw_svcgrps(): 76 | fw_svc_grps = start_svcgrps + \ 77 | self._obj_container.get_fw_svcgrps() + \ 78 | end + [''] 79 | 80 | fw_schedules = [] 81 | if self._obj_container.get_fw_schedules(): 82 | fw_schedules = start_schedules + \ 83 | self._obj_container.get_fw_schedules() + \ 84 | end + [''] 85 | 86 | fw_policies = start_policies + fw_policies + end 87 | 88 | target = sys_settings + fw_addresses + fw_addr_grps + \ 89 | fw_services + fw_svc_grps + fw_schedules + fw_policies 90 | 91 | return '\n'.join(target) 92 | 93 | 94 | class Term(fortigate.Term): 95 | _PLATFORM = 'fortigatelocalin' 96 | 97 | 98 | class Error(Exception): 99 | pass 100 | 101 | 102 | class FilterDirectionError(Error): 103 | pass 104 | -------------------------------------------------------------------------------- /capirca/lib/speedway.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Google Inc. All Rights Reserved. 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | # 14 | 15 | 16 | """Speedway iptables generator. This is a subclass of Iptables lib.""" 17 | 18 | from string import Template 19 | from capirca.lib import iptables 20 | 21 | 22 | class Error(Exception): 23 | pass 24 | 25 | 26 | class Term(iptables.Term): 27 | """Generate Iptables policy terms.""" 28 | _PLATFORM = 'speedway' 29 | _PREJUMP_FORMAT = None 30 | _POSTJUMP_FORMAT = Template('-A $filter -j $term') 31 | 32 | 33 | class Speedway(iptables.Iptables): 34 | """Generates filters and terms from provided policy object.""" 35 | 36 | _PLATFORM = 'speedway' 37 | _DEFAULT_PROTOCOL = 'all' 38 | SUFFIX = '.ipt' 39 | 40 | _RENDER_PREFIX = '*filter' 41 | _RENDER_SUFFIX = 'COMMIT' 42 | _DEFAULTACTION_FORMAT = ':%s %s' 43 | 44 | _TERM = Term 45 | -------------------------------------------------------------------------------- /capirca/lib/srxlo.py: -------------------------------------------------------------------------------- 1 | # Copyright 2014 Google Inc. All Rights Reserved. 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | # 14 | 15 | """Juniper SRX generator for loopback ACLs. 16 | 17 | This is a subclass of Juniper generator. Juniper SRX loopback filter 18 | uses the same syntax as regular Juniper stateless ACLs, with minor 19 | differences. This subclass effects those differences. 20 | """ 21 | 22 | from capirca.lib import juniper 23 | 24 | 25 | class Term(juniper.Term): 26 | """Single SRXlo term representation.""" 27 | 28 | _PLATFORM = 'srxlo' 29 | 30 | def __init__(self, *args, **kwargs): 31 | super().__init__(*args, **kwargs) 32 | 33 | 34 | class SRXlo(juniper.Juniper): 35 | """SRXlo generator.""" 36 | _PLATFORM = 'srxlo' 37 | SUFFIX = '.jsl' 38 | _TERM = Term 39 | 40 | def _BuildTokens(self): 41 | """Build supported tokens for platform. 42 | 43 | Returns: 44 | tuple containing both supported tokens and sub tokens 45 | """ 46 | supported_tokens, supported_sub_tokens = super()._BuildTokens() 47 | # flexible match is MX/Trio only 48 | supported_tokens.remove('flexible_match_range') 49 | # currently only support 'encapsulate' in juniper 50 | supported_tokens.remove('encapsulate') 51 | # currently only support 'decapsulate' in juniper 52 | supported_tokens.remove('decapsulate') 53 | # currently only support 'port-mirror' in juniper 54 | supported_tokens.remove('port_mirror') 55 | return supported_tokens, supported_sub_tokens 56 | -------------------------------------------------------------------------------- /capirca/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/capirca/b38903cfe24fc6b4fdbb9c4b8e84b69c938d71a5/capirca/utils/__init__.py -------------------------------------------------------------------------------- /capirca/utils/config.py: -------------------------------------------------------------------------------- 1 | """A module to handle merging file configurations with CLI configs for Capirca.""" 2 | 3 | import yaml 4 | 5 | defaults = { 6 | 'base_directory': './policies', 7 | 'definitions_directory': './def', 8 | 'policy_file': None, 9 | 'output_directory': './', 10 | 'optimize': False, 11 | 'recursive': True, 12 | 'debug': False, 13 | 'verbose': False, 14 | 'ignore_directories': ['DEPRECATED', 'def'], 15 | 'max_renderers': 10, 16 | 'shade_check': False, 17 | 'exp_info': 2 18 | } 19 | 20 | 21 | def yaml_loader(filename): 22 | with open(filename, 'r') as f: 23 | try: 24 | data = yaml.safe_load(f) 25 | except AttributeError: 26 | data = yaml.safe_load(f) 27 | 28 | return data 29 | 30 | 31 | def flags_to_dict(absl_flags): 32 | base = { 33 | 'base_directory': absl_flags.base_directory, 34 | 'definitions_directory': absl_flags.definitions_directory, 35 | 'policy_file': absl_flags.policy_file, 36 | 'output_directory': absl_flags.output_directory, 37 | 'optimize': absl_flags.optimize, 38 | 'recursive': absl_flags.recursive, 39 | 'debug': absl_flags.debug, 40 | 'verbose': absl_flags.verbose, 41 | 'ignore_directories': absl_flags.ignore_directories, 42 | 'max_renderers': absl_flags.max_renderers, 43 | 'shade_check': absl_flags.shade_check, 44 | 'exp_info': absl_flags.exp_info, 45 | } 46 | 47 | return { 48 | flag: base[flag] for flag in filter(lambda f: base[f] is not None, base) 49 | } 50 | 51 | 52 | def merge_files(*files): 53 | result = {} 54 | 55 | for item in files: 56 | data = yaml_loader(item) 57 | result.update(data) 58 | 59 | return { 60 | flag: result[flag] 61 | for flag in filter(lambda f: result[f] is not None, result) 62 | } 63 | 64 | 65 | def generate_configs(absl_flags): 66 | cli_configs = flags_to_dict(absl_flags) 67 | if absl_flags.config_file: 68 | file_configs = merge_files(*absl_flags.config_file) 69 | else: 70 | file_configs = {} 71 | 72 | result = defaults.copy() 73 | result.update(cli_configs) 74 | result.update(file_configs) 75 | 76 | return result 77 | -------------------------------------------------------------------------------- /capirca/utils/iputils.py: -------------------------------------------------------------------------------- 1 | """A module of utilities to work with IP addresses in a faster way.""" 2 | 3 | import ipaddress 4 | 5 | 6 | def exclude_address( 7 | base_net: ipaddress._BaseNetwork, # pylint disable=protected-access 8 | exclude_net: ipaddress._BaseNetwork # pylint disable=protected-access 9 | ): 10 | """ 11 | Function to exclude a subnetwork from another, returning a generator that 12 | yields all values that correspond to the base network without the exclude 13 | network. 14 | 15 | This is functionally equivalent to the _BaseNetwork "address_exclude" from the 16 | `ipaddress` standard library, but is a faster implementation since 17 | the standard library function is a O(n) operation on the length of the 18 | netmask of the excluding network, whereas this function is O(1) for all cases. 19 | 20 | Args: 21 | base_net: an object of type _BaseNetwork, the network that 22 | contains the exclude network 23 | exclude_net: an object of type _BaseNetwork, the network 24 | that is being removed from the base_net 25 | Raises: 26 | ValueError if exclude_net is not completely contained in base_net 27 | 28 | Yields: 29 | A sequence of IP networks that do not encompass the exclude_net 30 | """ 31 | 32 | if not isinstance(base_net, ipaddress._BaseNetwork): # pylint disable=protected-access 33 | raise TypeError('%s is not a network object' % base_net) 34 | 35 | if not isinstance(exclude_net, ipaddress._BaseNetwork): # pylint disable=protected-access 36 | raise TypeError('%s is not a network object' % exclude_net) 37 | 38 | if not base_net._version == exclude_net._version: # pylint disable=protected-access # pytype: disable=attribute-error 39 | raise TypeError( 40 | '%s and %s are not of the same version' % (base_net, exclude_net) 41 | ) 42 | 43 | if not exclude_net.subnet_of(base_net): # pytype: disable=attribute-error 44 | raise ValueError() 45 | if exclude_net == base_net: 46 | return 47 | 48 | include_range = base_net.network_address._ip, base_net.broadcast_address._ip # pylint disable=protected-access # pytype: disable=attribute-error 49 | exclude_range = exclude_net.network_address._ip, exclude_net.broadcast_address._ip # pylint disable=protected-access # pytype: disable=attribute-error 50 | address_class = base_net.network_address.__class__ # pylint disable=protected-access 51 | if include_range[0] == exclude_range[0]: 52 | result_start = address_class(exclude_range[1] + 1) 53 | result_end = address_class(include_range[1]) 54 | for address in ipaddress.summarize_address_range(result_start, result_end): 55 | yield address 56 | elif include_range[1] == exclude_range[1]: 57 | result_start = address_class(include_range[0]) 58 | result_end = address_class(exclude_range[0] - 1) 59 | for address in ipaddress.summarize_address_range(result_start, result_end): 60 | yield address 61 | else: 62 | first_section_start = address_class(include_range[0]) 63 | first_section_end = address_class(exclude_range[0] - 1) 64 | second_section_start = address_class(exclude_range[1] + 1) 65 | second_section_end = address_class(include_range[1]) 66 | for address in ipaddress.summarize_address_range(first_section_start, first_section_end): 67 | yield address 68 | for address in ipaddress.summarize_address_range(second_section_start, second_section_end): 69 | yield address 70 | -------------------------------------------------------------------------------- /def/SERVICES.svc: -------------------------------------------------------------------------------- 1 | # 2 | # Sample naming service definitions 3 | # 4 | WHOIS = 43/udp 5 | SSH = 22/tcp 6 | TELNET = 23/tcp 7 | SMTP = 25/tcp 8 | MAIL_SERVICES = SMTP 9 | ESMTP 10 | SMTP_SSL 11 | POP_SSL 12 | TIME = 37/tcp 37/udp 13 | TACACS = 49/tcp 14 | DNS = 53/tcp 53/udp 15 | BOOTPS = 67/udp # BOOTP server 16 | BOOTPC = 68/udp # BOOTP client 17 | DHCP = BOOTPS 18 | BOOTPC 19 | TFTP = 69/tcp 69/udp 20 | HTTP = 80/tcp 21 | WEB_SERVICES = HTTP HTTPS 22 | POP3 = 110/tcp 23 | RPC = 111/udp 24 | IDENT = 113/tcp 113/udp 25 | NNTP = 119/tcp 26 | NTP = 123/tcp 123/udp 27 | MS_RPC_EPMAP = 135/udp 135/tcp 28 | MS_137 = 137/udp 29 | MS_138 = 138/udp 30 | MS_139 = 139/tcp 31 | IMAP = 143/tcp 32 | SNMP = 161/udp 33 | SNMP_TRAP = 162/udp 34 | BGP = 179/tcp 35 | IMAP3 = 220/tcp 36 | LDAP = 389/tcp 37 | LDAP_SERVICE = LDAP 38 | LDAPS 39 | HTTPS = 443/tcp 40 | MS_445 = 445/tcp 41 | SMTP_SSL = 465/tcp 42 | IKE = 500/udp 43 | SYSLOG = 514/udp 44 | RTSP = 554/tcp 45 | ESMTP = 587/tcp 46 | LDAPS = 636/tcp 47 | IMAPS = 993/tcp 48 | POP_SSL = 995/tcp 49 | HIGH_PORTS = 1024-65535/tcp 1024-65535/udp 50 | MSSQL = 1433/tcp 51 | MSSQL_MONITOR = 1434/tcp 52 | RADIUS = 1812/tcp 1812/udp 53 | HSRP = 1985/udp 54 | NFSD = 2049/tcp 2049/udp 55 | NETFLOW = 2056/udp 56 | SQUID_PROXY = 3128/tcp 57 | MYSQL = 3306/tcp 58 | RDP = 3389/tcp 59 | IPSEC = 4500/udp 60 | POSTGRESQL = 5432/tcp 61 | TRACEROUTE = 33434-33534/udp 62 | 63 | 64 | -------------------------------------------------------------------------------- /dev-install: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | pip install -e . 4 | pip install pre-commit 5 | # Install the pre-commit hooks as well 6 | pre-commit install 7 | -------------------------------------------------------------------------------- /doc/generators/arista.md: -------------------------------------------------------------------------------- 1 | # Arista 2 | 3 | The arista header designation has the following format: 4 | 5 | ``` 6 | target:: arista [filter name] {standard|extended|object-group|inet6} 7 | ``` 8 | 9 | * _filter name_: defines the name of the arista filter. 10 | * _standard_: specifies that the output should be a standard access list 11 | * _extended_: specifies that the output should be an extended access list 12 | * _object-group_: specifies this is a arista extended access list, and that object-groups should be used for ports and addresses. 13 | * _inet6_: specifies the output be for IPv6 only filters. 14 | 15 | ## Term Format 16 | 17 | * _action::_ The action to take when matched. See Actions section for valid options. 18 | * _address::_ One or more network address tokens, matches source or destination. 19 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 20 | * _destination-address::_ One or more destination address tokens 21 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 22 | * _destination-port::_ One or more service definition tokens 23 | * _dscp_match::_ Match a DSCP number. 24 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 25 | * _icmp-code::_ Specifies the ICMP code to filter on. 26 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 27 | * _logging::_ Specify that this packet should be logged via syslog. 28 | * _name::_ Name of the term. 29 | * _option::_ See platforms supported Options section. 30 | * _owner::_ Owner of the term, used for organizational purposes. 31 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 32 | *_platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 33 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 34 | * _source-address::_ one or more source address tokens. 35 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 36 | * _source-port::_ one or more service definition tokens. 37 | * _verbatim::_ this specifies that the text enclosed within quotes should be rendered into the output without interpretation or modification. This is sometimes used as a temporary workaround while new required features are being added. 38 | 39 | ## Sub Tokens 40 | 41 | ### Actions 42 | 43 | * _accept_ 44 | * _deny_ 45 | * _next_ 46 | * _reject_ 47 | * _reject-with-tcp-rst_ 48 | 49 | ### Option 50 | 51 | * _established::_ Only match established connections, implements tcp-established for tcp and sets destination port to 1024- 65535 for udp if destination port is not defined. 52 | * _is-fragment::_ Matches on if a packet is a fragment. 53 | * _tcp-established::_ Only match established tcp connections, based on statefull match or TCP flags. Not supported for other protocols. 54 | * _tcp-initial::_ Only match initial packet for TCP protocol. 55 | -------------------------------------------------------------------------------- /doc/generators/aruba.md: -------------------------------------------------------------------------------- 1 | # Aruba 2 | 3 | The aruba header designation has the following format: 4 | ``` 5 | target:: aruba [filter name] {ipv6} 6 | ``` 7 | * _filter name_: defines the name of the arista filter. 8 | * _ipv6_: specifies the output be for IPv6 only filters. 9 | 10 | ## Term Format 11 | * _action::_ The action to take when matched. See Actions section for valid options. 12 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 13 | * _destination-address::_ One or more destination address tokens 14 | * _destination-port::_ One or more service definition tokens 15 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 16 | * _name::_ Name of the term. 17 | * _option::_ See platforms supported Options section. 18 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 19 | * _source-address::_ one or more source address tokens. 20 | * _verbatim::_ this specifies that the text enclosed within quotes should be rendered into the output without interpretation or modification. This is sometimes used as a temporary workaround while new required features are being added. 21 | ## Sub Tokens 22 | ### Actions 23 | * _accept_ 24 | * _deny_ 25 | ### Option 26 | * _destination-is-user::_ Aruba option to specify that the destination should be a user. 27 | * _negate::_ Used with DSM summarizer, negates the DSM. 28 | * _source-is-user::_ Aruba option to specify that the source should be a user. 29 | -------------------------------------------------------------------------------- /doc/generators/brocade.md: -------------------------------------------------------------------------------- 1 | # Brocade 2 | 3 | See Cisco 4 | 5 | ## Term Format 6 | 7 | * _action::_ The action to take when matched. See Actions section for valid options. 8 | * _address::_ One or more network address tokens, matches source or destination. 9 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 10 | * _destination-address::_ One or more destination address tokens 11 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 12 | * _destination-port::_ One or more service definition tokens 13 | * _dscp_match::_ Match a DSCP number. 14 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 15 | * _icmp-code::_ Specifies the ICMP code to filter on. 16 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 17 | * _logging::_ Specify that this packet should be logged via syslog. 18 | * _name::_ Name of the term. 19 | * _option::_ See platforms supported Options section. 20 | * _owner::_ Owner of the term, used for organizational purposes. 21 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 22 | *_platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 23 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 24 | * _source-address::_ one or more source address tokens. 25 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 26 | * _source-port::_ one or more service definition tokens. 27 | * _verbatim::_ this specifies that the text enclosed within quotes should be rendered into the output without interpretation or modification. This is sometimes used as a temporary workaround while new required features are being added. 28 | 29 | ## Sub Tokens 30 | 31 | ### Actions 32 | 33 | * _accept_ 34 | * _deny_ 35 | * _next_ 36 | * _reject_ 37 | * _reject-with-tcp-rst_ 38 | 39 | ### Option 40 | 41 | * _established::_ Only match established connections, implements tcp-established for tcp and sets destination port to 1024- 65535 for udp if destination port is not defined. 42 | * _is-fragment::_ Matches on if a packet is a fragment. 43 | * _tcp-established::_ Only match established tcp connections, based on statefull match or TCP flags. Not supported for other protocols. 44 | * _tcp-initial::_ Only match initial packet for TCP protocol. 45 | -------------------------------------------------------------------------------- /doc/generators/cisco.md: -------------------------------------------------------------------------------- 1 | # Cisco 2 | 3 | The cisco header designation has the following format: 4 | ``` 5 | target:: cisco [filter name] {extended|standard|object-group|object-group-inet6|inet6|mixed} {dsmo} 6 | ``` 7 | * _filter name_: defines the name or number of the cisco filter. 8 | * _extended_: specifies that the output should be an extended access list, and the filter name should be non-numeric. This is the default option. 9 | * _standard_: specifies that the output should be a standard access list, and the filter name should be numeric and in the range of 1-99. 10 | * _object-group_: specifies this is a cisco extended access list, and that object-groups should be used for ports and addresses. 11 | * _object-group-inet6_: specifies this is a cisco extended ipv6 access list, and that object-groups should be used for ports and addresses. 12 | * _inet6_: specifies the output be for IPv6 only filters. 13 | * _mixed_: specifies output will include both IPv6 and IPv4 filters. 14 | * _dsmo_: Enable discontinuous subnet mask summarization. 15 | When _inet4_ or _inet6_ is specified, naming tokens with both IPv4 and IPv6 filters will be rendered using only the specified addresses. 16 | The default format is _inet4_, and is implied if not other argument is given. 17 | 18 | ## Term Format 19 | * _action::_ The action to take when matched. See Actions section for valid options. 20 | * _address::_ One or more network address tokens, matches source or destination. 21 | * _restrict-address-family::_ Only include the term in the matching address family filter (eg. for mixed filters). 22 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 23 | * _destination-address::_ One or more destination address tokens 24 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 25 | * _destination-port::_ One or more service definition tokens 26 | * _dscp_match::_ Match a DSCP number. 27 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 28 | * _icmp-code::_ Specifies the ICMP code to filter on. 29 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 30 | * _logging::_ Specify that this packet should be logged via syslog. 31 | * _name::_ Name of the term. 32 | * _option::_ See platforms supported Options section. 33 | * _owner::_ Owner of the term, used for organizational purposes. 34 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 35 | *_platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 36 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 37 | * _source-address::_ one or more source address tokens. 38 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 39 | * _source-port::_ one or more service definition tokens. 40 | * _verbatim::_ this specifies that the text enclosed within quotes should be rendered into the output without interpretation or modification. This is sometimes used as a temporary workaround while new required features are being added. 41 | 42 | ## Sub Tokens 43 | 44 | ### Actions 45 | * _accept_ 46 | * _deny_ 47 | * _next_ 48 | * _reject_ 49 | * _reject-with-tcp-rst_ 50 | 51 | ### Option 52 | 53 | * _established::_ Only match established connections, implements tcp-established for tcp and sets destination port to 1024- 65535 for udp if destination port is not defined. 54 | * _is-fragment::_ Matches on if a packet is a fragment. 55 | * _tcp-established::_ Only match established tcp connections, based on statefull match or TCP flags. Not supported for other protocols. 56 | * _tcp-initial::_ Only match initial packet for TCP protocol. 57 | -------------------------------------------------------------------------------- /doc/generators/ciscoasa.md: -------------------------------------------------------------------------------- 1 | # CiscoASA 2 | 3 | The ciscoasa header designation has the following format: 4 | ``` 5 | target:: ciscoasa [filter name] 6 | ``` 7 | ## Term Format 8 | * _action::_ The action to take when matched. See Actions section for valid options. 9 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 10 | * _destination-address::_ One or more destination address tokens 11 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 12 | * _destination-port::_ One or more service definition tokens 13 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 14 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 15 | * _logging::_ Specify that this packet should be logged via syslog. 16 | * _name::_ Name of the term. 17 | * _option::_ See platforms supported Options section. 18 | * _owner::_ Owner of the term, used for organizational purposes. 19 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 20 | *_platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 21 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 22 | * _source-address::_ one or more source address tokens. 23 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 24 | * _source-port::_ one or more service definition tokens. 25 | * _verbatim::_ this specifies that the text enclosed within quotes should be rendered into the output without interpretation or modification. This is sometimes used as a temporary workaround while new required features are being added. 26 | ## Sub Tokens 27 | ### Actions 28 | * _accept_ 29 | * _deny_ 30 | * _next_ 31 | * _reject_ 32 | * _reject-with-tcp-rst_ 33 | ### Option 34 | * _established::_ Only match established connections, implements tcp-established for tcp and sets destination port to 1024- 65535 for udp if destination port is not defined. 35 | * _tcp-established::_ Only match established tcp connections, based on statefull match or TCP flags. Not supported for other protocols. 36 | -------------------------------------------------------------------------------- /doc/generators/cisconx.md: -------------------------------------------------------------------------------- 1 | # CiscoNX 2 | 3 | The cisconx header designation has the following format: 4 | ``` 5 | target:: cisconx [filter name] {extended|object-group|inet6|mixed} {dsmo} 6 | ``` 7 | * _filter name_: defines the name or number of the cisconx filter. 8 | * _extended_: specifies that the output should be an extended access list, and the filter name should be non-numeric. This is the default option. 9 | * _object-group_: specifies this is a cisconx extended access list, and that object-groups should be used for ports and addresses. 10 | * _inet6_: specifies the output be for IPv6 only filters. 11 | * _mixed_: specifies output will include both IPv6 and IPv4 filters. 12 | * _dsmo_: Enable discontinuous subnet mask summarization. 13 | When _inet4_ or _inet6_ is specified, naming tokens with both IPv4 and IPv6 filters will be rendered using only the specified addresses. 14 | The default format is _inet4_, and is implied if not other argument is given. 15 | 16 | ## Term Format 17 | * _action::_ The action to take when matched. See Actions section for valid options. 18 | * _address::_ One or more network address tokens, matches source or destination. 19 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 20 | * _destination-address::_ One or more destination address tokens 21 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 22 | * _destination-port::_ One or more service definition tokens 23 | * _dscp_match::_ Match a DSCP number. 24 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 25 | * _icmp-code::_ Specifies the ICMP code to filter on. 26 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 27 | * _logging::_ Specify that this packet should be logged via syslog. 28 | * _name::_ Name of the term. 29 | * _option::_ See platforms supported Options section. 30 | * _owner::_ Owner of the term, used for organizational purposes. 31 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 32 | * _platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 33 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 34 | * _source-address::_ one or more source address tokens. 35 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 36 | * _source-port::_ one or more service definition tokens. 37 | * _verbatim::_ this specifies that the text enclosed within quotes should be rendered into the output without interpretation or modification. This is sometimes used as a temporary workaround while new required features are being added. 38 | 39 | ## Sub Tokens 40 | 41 | ### Actions 42 | * _accept_ 43 | * _deny_ 44 | * _next_ 45 | * _reject_ 46 | * _reject-with-tcp-rst_ 47 | 48 | ### Option 49 | 50 | * _established::_ Only match established connections, implements tcp-established for tcp and sets destination port to 1024- 65535 for udp if destination port is not defined. 51 | * _is-fragment::_ Matches on if a packet is a fragment. 52 | * _tcp-established::_ Only match established tcp connections, based on statefull match or TCP flags. Not supported for other protocols. 53 | * _tcp-initial::_ Only match initial packet for TCP protocol. 54 | -------------------------------------------------------------------------------- /doc/generators/ciscoxr.md: -------------------------------------------------------------------------------- 1 | # CiscoXR 2 | 3 | See Cisco 4 | 5 | ## Term Format 6 | 7 | * _action::_ The action to take when matched. See Actions section for valid options. 8 | * _address::_ One or more network address tokens, matches source or destination. 9 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 10 | * _destination-address::_ One or more destination address tokens 11 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 12 | * _destination-port::_ One or more service definition tokens 13 | * _dscp_match::_ Match a DSCP number. 14 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 15 | * _icmp-code::_ Specifies the ICMP code to filter on. 16 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 17 | * _logging::_ Specify that this packet should be logged via syslog. 18 | * _name::_ Name of the term. 19 | * _option::_ See platforms supported Options section. 20 | * _owner::_ Owner of the term, used for organizational purposes. 21 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 22 | *_platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 23 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 24 | * _source-address::_ one or more source address tokens. 25 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 26 | * _source-port::_ one or more service definition tokens. 27 | * _verbatim::_ this specifies that the text enclosed within quotes should be rendered into the output without interpretation or modification. This is sometimes used as a temporary workaround while new required features are being added. 28 | 29 | ## Sub Tokens 30 | 31 | ### Actions 32 | 33 | * _accept_ 34 | * _deny_ 35 | * _next_ 36 | * _reject_ 37 | * _reject-with-tcp-rst_ 38 | 39 | ### Option 40 | 41 | * _established::_ Only match established connections, implements tcp-established for tcp and sets destination port to 1024- 65535 for udp if destination port is not defined. 42 | * _is-fragment::_ Matches on if a packet is a fragment. 43 | * _tcp-established::_ Only match established tcp connections, based on statefull match or TCP flags. Not supported for other protocols. 44 | * _tcp-initial::_ Only match initial packet for TCP protocol. 45 | -------------------------------------------------------------------------------- /doc/generators/gce.md: -------------------------------------------------------------------------------- 1 | # GCE 2 | 3 | The GCE header designation has the following format: 4 | 5 | ``` 6 | target:: gce [filter name] [direction] 7 | ``` 8 | 9 | * _filter name_: defines the name of the gce filter. 10 | * _direction_: defines the direction, valid inputs are INGRESS and EGRESS (default:INGRESS) 11 | 12 | ## Term Format 13 | 14 | * _action::_ The action to take when matched. See Actions section for valid options. 15 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 16 | * _destination-address::_ One or more destination address tokens 17 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 18 | * _destination-port::_ One or more service definition tokens 19 | * _destination_tag::_ Tag name to be used for destination filtering. 20 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 21 | * _name::_ Name of the term. 22 | * _option::_ See platforms supported Options section. 23 | * _owner::_ Owner of the term, used for organizational purposes. 24 | * _priority_ Relative priority of rules when evaluated on the platform. 25 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 26 | * _source-address::_ one or more source address tokens. 27 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 28 | * _source-port::_ one or more service definition tokens. 29 | * _source-service-accounts::_ A service account that the term applies to. 30 | * _source-tag::_ Tag name used for source filtering. 31 | * _target-service-accounts::_ A service account that may make network connections. 32 | 33 | ## Sub Tokens 34 | 35 | ### Actions 36 | 37 | * _accept_ 38 | * _deny_ 39 | -------------------------------------------------------------------------------- /doc/generators/gce_vpc_tf.md: -------------------------------------------------------------------------------- 1 | # Terraform GCE 2 | 3 | The Terraform GCE header designation has the following format: 4 | 5 | ``` 6 | target:: gce_vpc_tf [filter name] [network name] [direction] [max policy cost] 7 | ``` 8 | 9 | * _filter name_: defines the name of the gce_vpc_tf filter. 10 | * _network name_: defines the name of the network the filter applies to. 11 | * _direction_: defines the direction, valid inputs are INGRESS and EGRESS (default:INGRESS) 12 | * _max policy cost_: maximum policy cost as an integer. 13 | 14 | ## Term Format 15 | 16 | * _action::_ The action to take when matched. See Actions section for valid options. 17 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 18 | * _destination-address::_ One or more destination address tokens 19 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 20 | * _destination-port::_ One or more service definition tokens 21 | * _destination_tag::_ Tag name to be used for destination filtering. 22 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 23 | * _name::_ Name of the term. 24 | * _option::_ See platforms supported Options section. 25 | * _owner::_ Owner of the term, used for organizational purposes. 26 | * _priority_ Relative priority of rules when evaluated on the platform. 27 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 28 | * _source-address::_ one or more source address tokens. 29 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 30 | * _source-port::_ one or more service definition tokens. 31 | * _source-service-accounts::_ A service account that the term applies to. 32 | * _source-tag::_ Tag name used for source filtering. 33 | * _target-service-accounts::_ A service account that the term applies to. For ingress rules it is the destination, for egress rules it is the source. 34 | 35 | ## Sub Tokens 36 | 37 | ### Actions 38 | 39 | * _accept_ 40 | * _deny_ 41 | -------------------------------------------------------------------------------- /doc/generators/ipset.md: -------------------------------------------------------------------------------- 1 | # Ipset 2 | 3 | Ipset is a system inside the Linux kernel, which can very efficiently store and match IPv4 and IPv6 addresses. This can be used to dramatically increase performance of iptables firewall. 4 | The Ipset header designation follows the Iptables format above, but uses the target platform of 'ipset': 5 | 6 | ``` 7 | target:: ipset [INPUT|OUTPUT|FORWARD|custom] {ACCEPT|DROP} {truncatenames} {nostate} {inet|inet6} 8 | ``` 9 | 10 | ## Term Format 11 | 12 | * _action::_ The action to take when matched. See Actions section for valid options. 13 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 14 | * _counter::_ Update a counter for matching packets 15 | * _destination-address::_ One or more destination address tokens 16 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 17 | * _destination-interface::_ Specify specific interface a term should apply to (e.g. destination-interface:: eth3) 18 | * _destination-port::_ One or more service definition tokens 19 | * _destination-prefix::_ Specify destination-prefix matching (e.g. source-prefix:: configured-neighbors-only) 20 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 21 | * _fragement-offset::_ specify a fragment offset of a fragmented packet 22 | * _icmp-code::_ Specifies the ICMP code to filter on. 23 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 24 | * _logging::_ Specify that this packet should be logged via syslog. 25 | * _name::_ Name of the term. 26 | * _option::_ See platforms supported Options section. 27 | * _owner::_ Owner of the term, used for organizational purposes. 28 | * _packet-length::_ specify packet length. 29 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 30 | *_platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 31 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 32 | * _routing-instance::_ specify routing instance for matching packets. 33 | * _source-address::_ one or more source address tokens. 34 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 35 | * _source-interface::_ specify specific interface a term should apply to (e.g. source-interface:: eth3). 36 | * _source-port::_ one or more service definition tokens. 37 | * _source-prefix::_ specify source-prefix matching (e.g. source-prefix:: configured-neighbors-only). 38 | * _verbatim::_ this specifies that the text enclosed within quotes should be rendered into the output without interpretation or modification. This is sometimes used as a temporary workaround while new required features are being added. 39 | ## Sub Tokens 40 | 41 | ### Actions 42 | * _accept_ 43 | * _deny_ 44 | * _next_ 45 | * _reject_ 46 | * _reject-with-tcp-rst_ 47 | 48 | ### Option 49 | * _ack::_ Match on ACK flag being present. 50 | * _all::_ Matches all protocols. 51 | * _established::_ Only match established connections, implements tcp-established for tcp and sets destination port to 1024- 65535 for udp if destination port is not defined. 52 | * _fin::_ Match on FIN flag being present. 53 | * _first-fragment::_ Only match on first fragment of a fragmented pakcet. 54 | * _initial::_ Only matches on initial packet. 55 | * _is-fragment::_ Matches on if a packet is a fragment. 56 | * _none::_ Matches none. 57 | * _psh::_ Match on PSH flag being present. 58 | * _rst::_ Match on RST flag being present. 59 | * _sample::_ Samples traffic for netflow. 60 | * _syn::_ Match on SYN flag being present. 61 | * _tcp-established::_ Only match established tcp connections, based on statefull match or TCP flags. Not supported for other protocols. 62 | * _tcp-initial::_ Only match initial packet for TCP protocol. 63 | * _urg::_ Match on URG flag being present. 64 | 65 | -------------------------------------------------------------------------------- /doc/generators/junipermsmpc.md: -------------------------------------------------------------------------------- 1 | # Juniper MSMPC 2 | 3 | The juniper header designation has the following format: 4 | 5 | ``` 6 | target:: juniper [filter name] {inet|inet6|mixed} {noverbose} {ingress|egress} 7 | filter name: defines the name of the juniper msmpc filter. 8 | inet6: specifies the output be for IPv6 only filters. 9 | mixed: specifies the output be for IPv4 and IPv6 filters. This is the default format. 10 | noverbose: omit additional term and address comments. 11 | ingress: filter will be applied in the input direction. 12 | egress: filter will be appliced in the output direction. 13 | ``` 14 | 15 | When inet4 or inet6 is specified, naming tokens with both IPv4 and IPv6 filters will be rendered using only the specified addresses. 16 | 17 | When neither ingress or egress is specified, the filter will be applied in both (input-output) directions. This is the default. 18 | -------------------------------------------------------------------------------- /doc/generators/junipersrx.md: -------------------------------------------------------------------------------- 1 | 2 | ## JuniperSRX 3 | Note: The Juniper SRX generator is currently in beta testing. 4 | ``` 5 | target:: srx from-zone [zone name] to-zone [zone name] {inet} 6 | ``` 7 | * _from-zone_: static keyword, followed by user specified zone 8 | * _to-zone_: static keyword, followed by user specified zone 9 | * _inet_: Address family (only IPv4 tested at this time) 10 | ### Term Format 11 | * _action::_ The action to take when matched. See Actions section for valid options. 12 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 13 | * _destination-address::_ One or more destination address tokens 14 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 15 | * _destination-port::_ One or more service definition tokens 16 | * _destination-zone::_ one or more destination zones tokens. Only supported by global policy 17 | * _dscp_except::_ Do not match the DSCP number. 18 | * _dscp_match::_ Match a DSCP number. 19 | * _dscp_set::_ Match a DSCP set. 20 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 21 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 22 | * _logging::_ Specify that these packets should be logged. 23 | * Based on the input value the resulting logging actions will follow this logic: 24 | * _action_ is 'accept': 25 | * _logging_ is 'true': resulting SRX output will be 'log { session-close; }' 26 | * _logging_ is 'log-both': resulting SRX output will be 'log { session-init; session-close; }' 27 | * _action_ is 'deny': 28 | * _logging_ is 'true': resulting SRX output will be 'log { session-init; }' 29 | * _logging_ is 'log-both': resulting SRX output will be 'log { session-init; session-close; }' 30 | * See [here](https://kb.juniper.net/InfoCenter/index?page=content&id=KB16506) for explanation. 31 | * _name::_ Name of the term. 32 | * _option::_ See platforms supported Options section. 33 | * _owner::_ Owner of the term, used for organizational purposes. 34 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 35 | *_platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 36 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 37 | * _source-address::_ one or more source address tokens. 38 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 39 | * _source-port::_ one or more service definition tokens. 40 | * _source-zone::_ one or more source zones tokens. Only supported by global policy 41 | * _timeout::_ specify application timeout. (default 60) 42 | * _verbatim::_ this specifies that the text enclosed within quotes should be rendered into the output without interpretation or modification. This is sometimes used as a temporary workaround while new required features are being added. 43 | * _vpn::_ Encapsulate outgoing IP packets and decapsulate incomfing IP packets. 44 | ### Sub Tokens 45 | #### Actions 46 | * _accept_ 47 | * _count_ 48 | * _deny_ 49 | * _dscp_ 50 | * _log_ 51 | * _reject_ 52 | 53 | -------------------------------------------------------------------------------- /doc/generators/k8s.md: -------------------------------------------------------------------------------- 1 | # K8s 2 | 3 | The K8s header designation has the following format: 4 | 5 | ``` 6 | target:: k8s [direction] 7 | ``` 8 | 9 | * _direction_: defines the direction, valid inputs are INGRESS and EGRESS (default:INGRESS) 10 | 11 | ## Term Format 12 | 13 | * _action::_ The action to take when matched. See Actions section for valid options. 14 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 15 | * _destination-address::_ One or more destination address tokens 16 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 17 | * _destination-port::_ One or more service definition tokens 18 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 19 | * _name::_ Name of the term. 20 | * _owner::_ Owner of the term, used for organizational purposes. 21 | * _protocol::_ the network protocols this term will match, such as tcp, udp, or sctp. 22 | * _source-address::_ one or more source address tokens. 23 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 24 | 25 | ## Sub Tokens 26 | 27 | ### Actions 28 | 29 | * _accept_ 30 | * _deny_: Only permitted for a default deny 31 | -------------------------------------------------------------------------------- /doc/generators/nsxt.md: -------------------------------------------------------------------------------- 1 | # NSXT 2 | 3 | The nsx header designation has the following format: 4 | 5 | ``` 6 | target:: nsxt {section_name} {inet|inet6|mixed} section-id securitygroup securitygroupId 7 | section_name: specifies the name of the section all terms in this header apply to. 8 | inet: specifies that the resulting filter should only render IPv4 addresses. 9 | inet6: specifies that the resulting filter should only render IPv6 addresses. 10 | mixed: specifies that the resulting filter should render both IPv4 and IPv6 addresses. 11 | sectionId: specifies the Id for the section [optional] 12 | securitygroup: specifies that the appliedTo should be security group [optional] 13 | securitygroupId: specifies the Id of the security group [mandatory if securitygroup is given] 14 | (Required keywords option and verbatim are not supported in NSX) 15 | ``` 16 | 17 | 18 | ## Nsxt 19 | The nsxt header designation has the following format: 20 | ``` 21 | target:: nsxt {section_name} {inet|inet6|mixed} section-id securitygroup securitygroupId 22 | ``` 23 | * _section_name_: specifies the name of the dfw rule all terms in this header apply to. [mandatory field] 24 | * _inet_: specifies the output should be for IPv4 only filters. This is the default format. 25 | * _inet6_: specifies the output be for IPv6 only filters. 26 | * _mixed_: specifies that the resulting filter should render both IPv4 and IPv6 addresses. 27 | * _sectionId_: specifies the Id for the section [optional] 28 | * _securitygroup_: specifies that the appliedTo should be security group [optional] 29 | * _securitygroupId_: specifies the Id of the security group [mandatory if securitygroup is given] 30 | (Required keywords option and verbatim are not supported in NSX) 31 | ## Term Format 32 | * _action::_ The action to take when matched. See Actions section for valid options. 33 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 34 | * _destination-address::_ One or more destination address tokens 35 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 36 | * _destination-port::_ One or more service definition tokens 37 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 38 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 39 | * _logging::_ Specify that this packet should be logged via syslog. 40 | * _name::_ Name of the term. 41 | * _option::_ See platforms supported Options section. 42 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 43 | *_platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 44 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 45 | * _source-address::_ one or more source address tokens. 46 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 47 | * _source-port::_ one or more service definition tokens. 48 | * _verbatim::_ this specifies that the text enclosed within quotes should be rendered into the output without interpretation or modification. This is sometimes used as a temporary workaround while new required features are being added. 49 | ## Sub Tokens 50 | ### Actions 51 | * _accept_ 52 | * _deny_ 53 | * _reject_ 54 | * _reject-with-tcp-rst_ 55 | -------------------------------------------------------------------------------- /doc/generators/nsxv.md: -------------------------------------------------------------------------------- 1 | # NSX 2 | 3 | The nsx header designation has the following format: 4 | 5 | ``` 6 | target:: nsxv {section_name} {inet|inet6|mixed} section-id securitygroup securitygroupId 7 | section_name: specifies the name of the section all terms in this header apply to. 8 | inet: specifies that the resulting filter should only render IPv4 addresses. 9 | inet6: specifies that the resulting filter should only render IPv6 addresses. 10 | mixed: specifies that the resulting filter should render both IPv4 and IPv6 addresses. 11 | sectionId: specifies the Id for the section [optional] 12 | securitygroup: specifies that the appliedTo should be security group [optional] 13 | securitygroupId: specifies the Id of the security group [mandatory if securitygroup is given] 14 | (Required keywords option and verbatim are not supported in NSX) 15 | ``` 16 | 17 | 18 | ## Nsxv 19 | The nsxv header designation has the following format: 20 | ``` 21 | target:: nsxv {section_name} {inet|inet6|mixed} section-id securitygroup securitygroupId 22 | ``` 23 | * _section_name_: specifies the name of the section all terms in this header apply to. [mandatory field] 24 | * _inet_: specifies the output should be for IPv4 only filters. This is the default format. 25 | * _inet6_: specifies the output be for IPv6 only filters. 26 | * _mixed_: specifies that the resulting filter should render both IPv4 and IPv6 addresses. 27 | * _sectionId_: specifies the Id for the section [optional] 28 | * _securitygroup_: specifies that the appliedTo should be security group [optional] 29 | * _securitygroupId_: specifies the Id of the security group [mandatory if securitygroup is given] 30 | (Required keywords option and verbatim are not supported in NSX) 31 | ## Term Format 32 | * _action::_ The action to take when matched. See Actions section for valid options. 33 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 34 | * _destination-address::_ One or more destination address tokens 35 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 36 | * _destination-port::_ One or more service definition tokens 37 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 38 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 39 | * _logging::_ Specify that this packet should be logged via syslog. 40 | * _name::_ Name of the term. 41 | * _option::_ See platforms supported Options section. 42 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 43 | *_platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 44 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 45 | * _source-address::_ one or more source address tokens. 46 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 47 | * _source-port::_ one or more service definition tokens. 48 | * _verbatim::_ this specifies that the text enclosed within quotes should be rendered into the output without interpretation or modification. This is sometimes used as a temporary workaround while new required features are being added. 49 | ## Sub Tokens 50 | ### Actions 51 | * _accept_ 52 | * _deny_ 53 | * _reject_ 54 | * _reject-with-tcp-rst_ 55 | 56 | -------------------------------------------------------------------------------- /doc/generators/packetfilter.md: -------------------------------------------------------------------------------- 1 | # PacketFilter 2 | 3 | Note: The PF generator is currently in alpha testing. The output should be compatible with OpenBSD v4.7 PF and later. 4 | 5 | ``` 6 | target:: packetfilter filter-name {inet|inet6|mixed} {in|out} {nostate} 7 | ``` 8 | * _filter-name_: a short, descriptive policy identifier 9 | * _inet_: specifies that the resulting filter should only render IPv4 addresses. 10 | * _inet6_: specifies that the resulting filter should only render IPv6 addresses. 11 | * _mixed_: specifies that the resulting filter should only render IPv4 and IPv6 addresses (default). 12 | * _in_: match ingoing packets (default: both directions). 13 | * _out_: match outgoing packets (default: both directions). 14 | * _nostate_: do not keep state on connections (default: keep state). 15 | ## Term Format 16 | * _action::_ The action to take when matched. See Actions section for valid options. 17 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 18 | * _destination-address::_ One or more destination address tokens 19 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 20 | * _destination-interface::_ Specify the destination interface. Implicitly changes the term direction to *out* for this term. Mutually exclusive with _source-interface::_. 21 | * _source-interface::_ Specify the source interface. Implicitly changes the term direction to *in* for this term. Mutually exclusive with _destination-interface::_. 22 | * _destination-port::_ One or more service definition tokens 23 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 24 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 25 | * _logging::_ Specify that this packet should be logged via syslog. 26 | * _name::_ Name of the term. 27 | * _option::_ See platforms supported Options section. 28 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 29 | *_platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 30 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 31 | * _source-address::_ one or more source address tokens. 32 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 33 | * _source-port::_ one or more service definition tokens. 34 | * _verbatim::_ this specifies that the text enclosed within quotes should be rendered into the output without interpretation or modification. This is sometimes used as a temporary workaround while new required features are being added. 35 | ## Sub Tokens 36 | ### Actions 37 | * _accept_ 38 | * _deny_ 39 | * _next_ 40 | * _reject_ 41 | ### Option 42 | * _ack::_ Match on ACK flag being present. 43 | * _all::_ Matches all protocols. 44 | * _established::_ Only match established connections, implements tcp-established for tcp and sets destination port to 1024- 65535 for udp if destination port is not defined. 45 | * _fin::_ Match on FIN flag being present. 46 | * _is-fragment::_ Matches on if a packet is a fragment. 47 | * _psh::_ Match on PSH flag being present. 48 | * _rst::_ Match on RST flag being present. 49 | * _syn::_ Match on SYN flag being present. 50 | * _tcp-established::_ Only match established tcp connections, based on statefull match or TCP flags. Not supported for other protocols. 51 | * _urg::_ Match on URG flag being present. 52 | -------------------------------------------------------------------------------- /doc/generators/paloaltofw.md: -------------------------------------------------------------------------------- 1 | # PaloAltoFW 2 | 3 | The paloalto header designation has the following format: 4 | 5 | ``` 6 | target:: paloalto from-zone [zone name] to-zone [zone name] [address family] [address objects] 7 | ``` 8 | * _from-zone_: static keyword, followed by the source zone 9 | * _to-zone_: static keyword, followed by the destination zone 10 | * _address family_: specifies the address family for the resulting filter 11 | - _inet_: the filter should only render IPv4 addresses (default) 12 | - _inet6_: the filter should only render IPv6 addresses 13 | - _mixed_: the filter should render IPv4 and IPv6 addresses 14 | * _address objects_: specifies whether custom address objects or 15 | network/mask definitions are used in security policy source and 16 | destination fields 17 | - _addr-obj_: specifies address groups are used in the security policy 18 | source and destination fields (default) 19 | - _no-addr-obj_: specifies network/mask definitions are used in the 20 | security policy source and destination fields 21 | * _unique-term-prefixes_: specifies whether each term name should be generated 22 | with unique prefixes. The unique prefix is a hexdigest of from_zone and 23 | to_zone fields. 24 | 25 | ## Term Format 26 | * _action::_ The action to take when matched. See Actions section for valid options. 27 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 28 | * _destination-address::_ One or more destination address tokens. 29 | * _destination-port::_ One or more service definition tokens. 30 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 31 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 32 | * _logging::_ Specify that this packet should be logged via syslog. 33 | * _name::_ Name of the term. 34 | * _owner::_ Owner of the term, used for organizational purposes. 35 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 36 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 37 | * _source-address::_ one or more source address tokens. 38 | * _source-port::_ one or more service definition tokens. 39 | * _timeout::_ specify application timeout. (default 60) 40 | 41 | ## Sub Tokens 42 | ### Actions 43 | * _accept_ 44 | * _count_ 45 | * _deny_ 46 | * _log_ 47 | * _reject_ 48 | 49 | ## Terms Section 50 | ### Optionally Supported Keywords 51 | * _pan-application_:: paloalto target only. 52 | Specify applications for the security policy which can be predefined 53 | applications (https://applipedia.paloaltonetworks.com/) 54 | and custom application objects. 55 | 56 | - _Security Policy Service Setting_ 57 | 58 | When no _protocol_ is specified in the term, the service will be 59 | _application-default_. 60 | 61 | When _protocol_ is tcp or udp, and no _source-port_ or 62 | _destination-port_ is specified, the service will be custom 63 | service objects for the protocols and all ports (0-65535). 64 | 65 | When _protocol_ is tcp or udp, and a _source-port_ or 66 | _destination-port_ is specified, the service will be custom 67 | service objects for the protocols and ports. 68 | 69 | _pan-application_ can only be used when no _protocol_ is specified 70 | in the term, or the protocols tcp and udp. 71 | -------------------------------------------------------------------------------- /doc/generators/pcap.md: -------------------------------------------------------------------------------- 1 | # PcapFilter 2 | 3 | FILL ME IN 4 | 5 | ## Term Format 6 | * _action::_ The action to take when matched. See Actions section for valid options. 7 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 8 | * _destination-address::_ One or more destination address tokens 9 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 10 | * _destination-port::_ One or more service definition tokens 11 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 12 | * _icmp-code::_ Specifies the ICMP code to filter on. 13 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 14 | * _logging::_ Specify that this packet should be logged via syslog. 15 | * _name::_ Name of the term. 16 | * _option::_ See platforms supported Options section. 17 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 18 | *_platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 19 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 20 | * _source-address::_ one or more source address tokens. 21 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 22 | * _source-port::_ one or more service definition tokens. 23 | ## Sub Tokens 24 | ### Actions 25 | * _accept_ 26 | * _deny_ 27 | * _next_ 28 | * _reject_ 29 | ### Option 30 | * _ack::_ Match on ACK flag being present. 31 | * _all::_ Matches all protocols. 32 | * _established::_ Only match established connections, implements tcp-established for tcp and sets destination port to 1024- 65535 for udp if destination port is not defined. 33 | * _fin::_ Match on FIN flag being present. 34 | * _is-fragment::_ Matches on if a packet is a fragment. 35 | * _none::_ Matches none. 36 | * _psh::_ Match on PSH flag being present. 37 | * _rst::_ Match on RST flag being present. 38 | * _syn::_ Match on SYN flag being present. 39 | * _tcp-established::_ Only match established tcp connections, based on statefull match or TCP flags. Not supported for other protocols. 40 | * _urg::_ Match on URG flag being present. 41 | -------------------------------------------------------------------------------- /doc/generators/sonic.md: -------------------------------------------------------------------------------- 1 | # SONiC 2 | 3 | The SONiC header designation has the following format: 4 | 5 | ``` 6 | target:: sonic filter-name {inet|inet6|mixed} 7 | ``` 8 | 9 | * _filter-name_: defines the name of the filter. This is a required field. 10 | Note that the filter name will be present as a key of every ACE (i.e. rule) in 11 | generated policy. For example if the filter-name is 'MyPolicy', each ACE will 12 | come out like: 13 | 14 | ``` 15 | { 16 | 'ACL_RULE': { 17 | 'MyPolicy|RULE_10': {...}, 18 | 'MyPolicy|RULE_20': {...}, 19 | ... 20 | } 21 | } 22 | ``` 23 | 24 | ## Term Format 25 | 26 | * _action::_ The action to take when matched. See Actions section for valid 27 | options. 28 | * _destination-address::_ One or more destination address tokens. 29 | * _destination-port::_ One or more service definition tokens. 30 | * _expiration::_ Stop rendering this term after specified date. Date format: 31 | [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md). 32 | * _protocol::_ The network protocols this term will match, such as tcp, udp, or 33 | sctp. 34 | * _source-address::_ One or more source address tokens. 35 | * _source-port::_ One or more service definition tokens. 36 | 37 | ## Sub Tokens 38 | 39 | ### Actions 40 | 41 | * _accept_ 42 | * _deny_ 43 | 44 | ### Option 45 | 46 | * _tcp-established::_ Only match "established" connections. It is not stateful - 47 | any TCP packet with ACK and/or RST TCP flag set will match. 48 | -------------------------------------------------------------------------------- /doc/generators/srxlo.md: -------------------------------------------------------------------------------- 1 | # SRXlo 2 | 3 | SRX Loopback is a stateless Juniper ACL with minor changes. Please see code for changes. 4 | 5 | ## Term Format 6 | * _action::_ The action to take when matched. See Actions section for valid options. 7 | * _address::_ One or more network address tokens, matches source or destination. 8 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 9 | * _counter::_ Update a counter for matching packets 10 | * _destination-address::_ One or more destination address tokens 11 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 12 | * _destination-port::_ One or more service definition tokens 13 | * _destination-prefix::_ Specify destination-prefix matching (e.g. source-prefix:: configured-neighbors-only) 14 | * _destination-prefix_except::_ Specify destination-prefix exception(TODO:cmas Fill in more). 15 | * _dscp_except::_ Do not match the DSCP number. 16 | * _dscp_match::_ Match a DSCP number. 17 | * _dscp_set::_ Match a DSCP set. 18 | * _ether_type::_ Match EtherType field. 19 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 20 | * _forwarding-class::_ Specify the forwarding class to match. 21 | * _forwarding-class_except::_ Do not match the specified forwarding classes. 22 | * _fragement-offset::_ specify a fragment offset of a fragmented packet 23 | * _hop-limit::_ Match the hop limit to the specified hop limit or set of hop limits. 24 | * _icmp-code::_ Specifies the ICMP code to filter on. 25 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 26 | * _logging::_ Specify that this packet should be logged via syslog. 27 | * _loss-priority::_ Specify loss priority. 28 | * _name::_ Name of the term. 29 | * _next-ip::_ Used in filter based forwarding. 30 | * _option::_ See platforms supported Options section. 31 | * _owner::_ Owner of the term, used for organizational purposes. 32 | * _packet-length::_ specify packet length. 33 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 34 | *_platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 35 | * _policer::_ specify which policer to apply to matching packets. 36 | * _port::_ Matches on source or destination ports. Takes a service token. 37 | * _precedence::_ specify precedence of range 0-7. May be a single integer, or a space separated list. 38 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 39 | * _protocol\_except::_ allow all protocol "except" specified. 40 | * _qos::_ apply quality of service classification to matching packets (e.g. qos:: af4) 41 | * _routing-instance::_ specify routing instance for matching packets. 42 | * _source-address::_ one or more source address tokens. 43 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 44 | * _source-port::_ one or more service definition tokens. 45 | * _source-prefix::_ specify source-prefix matching (e.g. source-prefix:: configured-neighbors-only). 46 | * _source-prefix-except::_ specify destination-prefix exception(TODO:cmas Fill in more). 47 | * _traffic-class-count::_ 48 | * _traffic-type::_ specify traffic-type 49 | * _ttl::_ Matches on TTL. 50 | * _verbatim::_ this specifies that the text enclosed within quotes should be rendered into the output without interpretation or modification. This is sometimes used as a temporary workaround while new required features are being added. 51 | ## Sub Tokens 52 | ### Actions 53 | * _accept_ 54 | * _deny_ 55 | * _next_ 56 | * _reject_ 57 | * _reject-with-tcp-rst_ 58 | ### Option 59 | * _.*::_ wat 60 | * _established::_ Only match established connections, implements tcp-established for tcp and sets destination port to 1024- 65535 for udp if destination port is not defined. 61 | * _first-fragment::_ Only match on first fragment of a fragmented pakcet. 62 | * _sample::_ Samples traffic for netflow. 63 | * _tcp-established::_ Only match established tcp connections, based on statefull match or TCP flags. Not supported for other protocols. 64 | * _tcp-initial::_ Only match initial packet for TCP protocol. 65 | -------------------------------------------------------------------------------- /doc/generators/versa.md: -------------------------------------------------------------------------------- 1 | 2 | ## Versa 3 | Note: The Versa generator is currently in beta testing. 4 | ``` 5 | target:: srx from-zone [zone name] to-zone [zone name] {template templatename } {tenant tenantname} {policy policyname} { inet} 6 | ``` 7 | * _from-zone_: static keyword, followed by user specified zone 8 | * _to-zone_: static keyword, followed by user specified zone 9 | * _template_: static keyword, followed by user specified template name 10 | * _tenant_: static keyword, followed by user specified tenant name 11 | * _policy: static keyword, followed by user specified policy name 12 | * _inet_: Address family (only IPv4 tested at this time) 13 | 14 | ### Term Format 15 | * _action::_ The action to take when matched. See Actions section for valid options. 16 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 17 | * _destination-address::_ One or more destination address tokens 18 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 19 | * _destination-port::_ One or more service definition tokens 20 | * _destination-zone::_ one or more destination zones tokens. Only supported by global policy 21 | * _dscp_match::_ Match a DSCP number. 22 | * _logging::_ Specify that these packets should be logged. 23 | * Based on the input value the resulting logging actions will follow this logic: 24 | * _action_ is 'accept': 25 | * _logging_ is 'true': resulting output will be 'event start;' 26 | * _logging_ is 'log-both': resulting output will be 'event both;' 27 | * _name::_ Name of the term. 28 | * _option::_ See platforms supported Options section. 29 | * _owner::_ Owner of the term, used for organizational purposes. 30 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 31 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 32 | * _source-address::_ one or more source address tokens. 33 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 34 | * _source-port::_ one or more service definition tokens. 35 | * _source-zone::_ one or more source zones tokens. Only supported by global policy 36 | ### Sub Tokens 37 | #### Actions 38 | * _accept_ 39 | * _deny_ 40 | * _dscp_ 41 | * _log_ 42 | * _reject_ 43 | 44 | -------------------------------------------------------------------------------- /doc/generators/windows_advfirewall.md: -------------------------------------------------------------------------------- 1 | # WindowsAdvFirewall 2 | The Windows Advanced Firewall header designation has the following format: 3 | ``` 4 | target:: windows_advfirewall {out|in} {inet|inet6|mixed} 5 | ``` 6 | * _out_: Specifies that the direction of packet flow is out. (default) 7 | * _in_: Specifies that the direction of packet flow is in. 8 | * _inet_: specifies that the resulting filter should only render IPv4 addresses. 9 | * _inet6_: specifies that the resulting filter should only render IPv6 addresses. 10 | ## Term Format 11 | * _action::_ The action to take when matched. See Actions section for valid options. 12 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 13 | * _destination-address::_ One or more destination address tokens 14 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 15 | * _destination-port::_ One or more service definition tokens 16 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 17 | * _icmp-type::_ Specify icmp-type code to match, see section [ICMP TYPES](PolicyFormat#ICMP_TYPES.md) for list of valid arguments 18 | * _name::_ Name of the term. 19 | * _option::_ See platforms supported Options section. 20 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 21 | *_platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 22 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 23 | * _source-address::_ one or more source address tokens. 24 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 25 | * _source-port::_ one or more service definition tokens. 26 | ## Sub Tokens 27 | ### Actions 28 | * _accept_ 29 | * _deny_ 30 | 31 | ## WindowsIPSec 32 | The Windows IPSec header designation has the following format: 33 | ``` 34 | target:: windows_advfirewall [filter_name] 35 | ``` 36 | * _filter name_: defines the name of the Windows IPSec filter. 37 | ## Term Format 38 | * _action::_ The action to take when matched. See Actions section for valid options. 39 | * _comment::_ A text comment enclosed in double-quotes. The comment can extend over multiple lines if desired, until a closing quote is encountered. 40 | * _destination-address::_ One or more destination address tokens 41 | * _destination-exclude::_ Exclude one or more address tokens from the specified destination-address 42 | * _destination-port::_ One or more service definition tokens 43 | * _expiration::_ stop rendering this term after specified date. [YYYY](YYYY.md)-[MM](MM.md)-[DD](DD.md) 44 | * _name::_ Name of the term. 45 | * _option::_ See platforms supported Options section. 46 | * _platform::_ one or more target platforms for which this term should ONLY be rendered. 47 | *_platform-exclude:: one or more target platforms for which this term should NEVER be rendered. 48 | * _protocol::_ the network protocols this term will match, such as tcp, udp, icmp, or a numeric value. 49 | * _source-address::_ one or more source address tokens. 50 | * _source-exclude::_ exclude one or more address tokens from the specified source-address. 51 | * _source-port::_ one or more service definition tokens. 52 | ## Sub Tokens 53 | ### Actions 54 | * _accept_ 55 | * _deny_ 56 | -------------------------------------------------------------------------------- /doc/wiki/Naming-library.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | The naming library is used by the capirca system to parse definitions of network 4 | and service data. These definitions are based on 'tokens' that are used in the 5 | high-level [policy language](Policy-format.md). 6 | 7 | ## Basic Usage 8 | 9 | **Create a directory to hold the definitions files** 10 | 11 | ``` 12 | mkdir /path/to/definitions/directory 13 | ``` 14 | 15 | **Create network definitions files** 16 | _(network defintions files must end in '.net')_ 17 | 18 | ``` 19 | cat > /path/to/definitions/directory/NETWORKS.net 20 | INTERNAL = 10.0.0.0/8 # RFC1918 21 | 172.16.0.0/12 # RFC1918 22 | 192.168.0.0/16 # RFC1918 23 | WEBSERVERS = 200.3.2.1/32 # webserver-1 24 | 200.3.2.4/32 # webserver-2 25 | MAILSERVER = 200.3.2.5/32 # mailserver-1 26 | ^D 27 | ``` 28 | 29 | **Create service definitions files** 30 | _(service defintions files must end in '.svc')_ 31 | 32 | ``` 33 | cat > /path/to/definitions/directory/SERVICES.svc 34 | HTTP = 80/tcp # web traffic 35 | MAIL = 25/tcp # smtp port 36 | 465/tcp # smtp over ssl 37 | DNS = 53/tcp 38 | 53/udp 39 | ^D 40 | ``` 41 | 42 | **Create a naming object** 43 | 44 | ``` 45 | from capirca import naming 46 | defs = naming.Naming('/path/to/definitions/directory') 47 | ``` 48 | 49 | **Access Definitions From the Naming Object** 50 | 51 | ``` 52 | defs.GetNet('INTERNAL') 53 | defs.GetService('MAIL') 54 | defs.GetServiceByProto('DNS','udp') 55 | ``` 56 | 57 | ## Methods 58 | 59 | ``` 60 | **GetIpParents(self, query)** 61 | > Return network tokens that contain IP in query. 62 | > Args: 63 | > > query: an ip string ('10.1.1.1') or nacaddr.IP object 64 | > Returns: 65 | > > rval2: a list of tokens containing this IP 66 | **GetNet(self, query)** 67 | > Expand a network token into a list of nacaddr.IP objects. 68 | > Args: 69 | > > query: Network definition token which may include comment text 70 | > Raises: 71 | > > BadNetmaskTypeError: Results when an unknown netmask\_type is 72 | > > specified. Acceptable values are 'cidr', 'netmask', and 'hostmask'. 73 | > Returns: 74 | > > List of nacaddr.IP objects 75 | > Raises: 76 | > > UndefinedAddressError: for an undefined token value 77 | **GetNetAddr(self, token)** 78 | > Given a network token, return a list of nacaddr.IP objects. 79 | > Args: 80 | > > token: A name of a network definition, such as 'INTERNAL' 81 | > Returns: 82 | > > A list of nacaddr.IP objects. 83 | > Raises: 84 | > > UndefinedAddressError: if the network name isn't defined. 85 | **GetService(self, query)** 86 | > Given a service name, return a list of associated ports and protocols. 87 | > Args: 88 | > > query: Service name symbol or token. 89 | > Returns: 90 | > > A list of service values such as ['80/tcp', '443/tcp', '161/udp', ...] 91 | **GetServiceByProto(self, query, proto)** 92 | > Given a service name, return list of ports in the service by protocol. 93 | > Args: 94 | > > query: Service name to lookup. 95 | > > proto: A particular protocol to restrict results by, such as 'tcp'. 96 | > Returns: 97 | > > A list of service values of type 'proto', such as ['80', '443', ...] 98 | **GetServiceParents(self, query)** 99 | > Given a service, return any tokens containing the value. 100 | > Args: 101 | > > query: a service or token name, such as 53/tcp or DNS 102 | > Returns: 103 | > > rval2: a list of tokens that contain query or parents of query 104 | **ParseNetworkList(self, data)** 105 | > Take an array of network data and import into class. 106 | > This method allows us to pass an array of data that contains network 107 | > definitions that are appended to any definitions read from files. 108 | > Args: 109 | > > data: array of text lines containing net definitions. 110 | **ParseServiceList(self, data)** 111 | > Take an array of service data and import into class. 112 | > This method allows us to pass an array of data that contains service 113 | > definitions that are appended to any definitions read from files. 114 | > Args: 115 | > > data: array of text lines containing service definitions. 116 | ``` 117 | -------------------------------------------------------------------------------- /doc/wiki/Policy-library.md: -------------------------------------------------------------------------------- 1 | # policy library 2 | 3 | The policy library (see `policy.py`) is intended for parsing the generic 4 | high-level policy files and returning a policy object for acl rendering. 5 | The policy library depends on a [naming library](Naming-library.md) object to 6 | be able to interpret network and service tokens. 7 | 8 | ## Basic Usage 9 | 10 | A policy object is created based on a policy text file. 11 | For information on how to define policy text files, please read the 12 | [Policy Format](PolicyFormat.md) documentation. 13 | For testing, you can use the policies provided in 14 | [policies/pol/](../../../policies/pol/). directory 15 | ## Using Policy Objects in Generators 16 | The following section is intended to help developers who would like to create 17 | new output generators, or to modify existing generators. 18 | ### Policy Object 19 | A policy object is collection of sections, such as header and terms, as well 20 | as their associated properties. Each section includes a variety of properties 21 | such as source/destination addresses, protocols, ports, actions, etc. 22 | The `policy.py` module generates policy objects from policy files. 23 | The `ParsePolicy()` creates a policy object 24 | by passing a string containing a policy to the `ParsePolicy()` class. 25 | ### Creating a Policy Object 26 | The steps are: 27 | 1. Create a [naming object](Naming-library.md) 28 | 1. Read the policy definition data in 29 | 1. Generate the policy object 30 | ```py 31 | from capirca import naming 32 | from capirca import policy 33 | definitions = naming.Naming('./def/') 34 | policy_text = open('./policies/sample.pol').read() 35 | policy_object = policy.ParsePolicy(policy_text, definitions) 36 | ``` 37 | The policy object is now available for use. 38 | Typically, this policy object will next be passed to one of the output 39 | generators for rendering an access control filter. 40 | ```py 41 | from capirca import juniper 42 | print juniper.Juniper(policy_object) 43 | # Headers 44 | for header, terms in policy.filters: 45 | > header.target 46 | > header.target.filter\_name 47 | # Terms 48 | for header, terms in policy.filters: 49 | # addresses - lists of nacaddr objects 50 | terms[x].address[] 51 | terms[x].destination_address[] 52 | terms[x].destination_address_exclude[] 53 | terms[x].source_address[] 54 | terms[x].source_address_exclude[] 55 | # ports - list of tuples. e.g. [(80, 80), (1024, 65535)] 56 | terms[x].port[] 57 | terms[x].destination_port[] 58 | terms[x].source_port[] 59 | # list of strings 60 | terms[x].action[] 61 | terms[x].comment[] 62 | terms[x].destination_prefix[] 63 | terms[x].protocol[] 64 | terms[x].protocol_except[] 65 | terms[x].option[] 66 | terms[x].source_prefix[] 67 | terms[x].traffic_type[] 68 | terms[x].verbatim[x].value[] 69 | # string 70 | terms[x].name 71 | terms[x].counter 72 | terms[x].ether_type 73 | terms[x].logging 74 | terms[x].loss_priority 75 | terms[x].packet_length 76 | terms[x].policer 77 | terms[x].precedence 78 | terms[x].qos 79 | terms[x].routing_instance 80 | terms[x].source_interface 81 | # integer 82 | terms[x].fragment_offset 83 | ``` 84 | -------------------------------------------------------------------------------- /doc/wiki/PolicyReader-library.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | The policy reader library is library that allows other code to easily examine 4 | policy source files. 5 | 6 | The policy library only reads policies for the purpose of rendering objects for 7 | passing to generators. 8 | 9 | For some tools, we needed to be able to easily examine the various filters and 10 | terms for programmatically. 11 | 12 | Policy reader renders simple objects that allow us to do this handy for a 13 | variety of tools, such as rendering policies in a Web UI for example 14 | 15 | ## Overview 16 | 17 | Import the policyreader library from the top Capirca directory. 18 | 19 | Load a policy and set of definitions: 20 | 21 | ```py 22 | p = policyreader.Policy('policy_path', 'definitions_path') 23 | ``` 24 | 25 | Print out the policy: 26 | 27 | ``` 28 | print(p) 29 | ``` 30 | 31 | Search for terms matching specific criteria: 32 | 33 | ``` 34 | >>> p.Matches(src='1.1.1.1', dport='53/udp') 35 | [[0, 1]] 36 | ``` 37 | 38 | The result tuple indicates that a matching rule was found in Filter 0 at Term 1. 39 | You can print out the name of this term with: 40 | 41 | ``` 42 | print p.filter[0].term[1].name 43 | accept-to-honestdns 44 | ``` 45 | 46 | You can also display this entire specific term using: 47 | 48 | ``` 49 | print p.filter[0].term[1] 50 | Term: accept-to-honestdns 51 | Source-address:: 52 | Destination-address:: GOOGLE_DNS 53 | Source-port:: 54 | Destination-port:: DNS 55 | Protocol:: udp 56 | Option:: 57 | Action:: accept 58 | ``` 59 | 60 | You can examine the values of addresses or services as follows: 61 | 62 | ``` 63 | print p.defs.GetNet('GOOGLE_DNS') 64 | [IPv4('8.8.4.4/32'), IPv4('8.8.8.8/32'), IPv6('2001:4860:4860::8844/128'), IPv6('2001:4860:4860::8888/128')] 65 | >>> print p.defs.GetService('DNS') 66 | ['53/tcp', '53/udp'] 67 | ``` 68 | 69 | ## Example Usage 70 | 71 | ``` 72 | $ python 73 | >>> from lib import policyreader 74 | >>> p=policyreader.Policy('./policies/sample_cisco_lab.pol', './def/') 75 | >>> print p 76 | Filter: allowtointernet 77 | ----------------------- 78 | Term: accept-dhcp 79 | Source-address:: 80 | Destination-address:: 81 | Source-port:: 82 | Destination-port:: DHCP 83 | Protocol:: udp 84 | Option:: 85 | Action:: accept 86 | Term: accept-to-honestdns 87 | Source-address:: 88 | Destination-address:: GOOGLE_DNS 89 | Source-port:: 90 | Destination-port:: DNS 91 | Protocol:: udp 92 | Option:: 93 | Action:: accept 94 | Term: accept-tcp-replies 95 | Source-address:: 96 | Destination-address:: INTERNAL 97 | Source-port:: 98 | Destination-port:: 99 | Protocol:: tcp 100 | Option:: tcp-established 101 | Action:: accept 102 | Term: deny-to-internal 103 | Source-address:: 104 | Destination-address:: INTERNAL 105 | Source-port:: 106 | Destination-port:: 107 | Protocol:: 108 | Option:: 109 | Action:: deny 110 | Term: deny-to-specific_hosts 111 | Source-address:: 112 | Destination-address:: WEB_SERVERS MAIL_SERVERS 113 | Source-port:: 114 | Destination-port:: 115 | Protocol:: 116 | Option:: 117 | Action:: deny 118 | Term: default-permit 119 | Source-address:: 120 | Destination-address:: 121 | Source-port:: 122 | Destination-port:: 123 | Protocol:: 124 | Option:: 125 | Action:: accept 126 | >>> 127 | >>> p.defs.GetNet('INTERNAL') 128 | [IPv4('10.0.0.0/8'), IPv4('172.16.0.0/12'), IPv4('192.168.0.0/16')] 129 | >>> 130 | >>> p.defs.GetService('DNS') 131 | ['53/tcp', '53/udp'] 132 | ``` 133 | -------------------------------------------------------------------------------- /make_dist.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright 2011 Google Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # Author: watson@google.com (Tony Watson) 17 | 18 | rev=`svn up|awk '{print $3}'` 19 | archive="capirca-r"$rev"tgz" 20 | filedir='./capirca' 21 | 22 | echo "Building: $archive" 23 | find . -name \*.pyc -exec rm {} \; 24 | pushd . > /dev/null 25 | cd .. 26 | tar -czf $archive --exclude-vcs $filedir 27 | mv $archive $filedir 28 | popd > /dev/null 29 | ls -al $archive 30 | echo "Done." 31 | 32 | -------------------------------------------------------------------------------- /policies/includes/untrusted-networks-blocking.inc: -------------------------------------------------------------------------------- 1 | term deny-from-bogons { 2 | comment:: "this is a sample edge input filter with a very very very long and 3 | multi-line comment that" 4 | comment:: "also has multiple entries." 5 | source-address:: BOGON 6 | action:: deny 7 | } 8 | 9 | term deny-from-reserved { 10 | source-address:: RESERVED 11 | action:: deny 12 | } 13 | 14 | term deny-to-rfc1918 { 15 | destination-address:: RFC1918 16 | action:: deny 17 | } 18 | 19 | -------------------------------------------------------------------------------- /policies/pol/sample_cisco_lab.pol: -------------------------------------------------------------------------------- 1 | header { 2 | comment:: "Denies all traffic to internal IPs except established tcp replies." 3 | comment:: "Also denies access to certain public allocations." 4 | 5 | comment:: "Ideal for some internal lab/testing types of subnets that are" 6 | comment:: "not well trusted, but allowing internal users to access." 7 | 8 | comment:: "Apply to ingress interface (to filter traffic coming from lab)" 9 | target:: cisco allowtointernet 10 | } 11 | 12 | term accept-dhcp { 13 | comment:: "Optional - allow forwarding of DHCP requests." 14 | destination-port:: DHCP 15 | protocol:: udp 16 | action:: accept 17 | } 18 | 19 | term accept-to-honestdns { 20 | comment:: "Allow name resolution using honestdns." 21 | destination-address:: GOOGLE_DNS 22 | destination-port:: DNS 23 | protocol:: udp 24 | action:: accept 25 | } 26 | 27 | term accept-tcp-replies { 28 | comment:: "Allow tcp replies to internal hosts." 29 | destination-address:: INTERNAL 30 | protocol:: tcp 31 | option:: tcp-established 32 | action:: accept 33 | } 34 | 35 | term deny-to-internal { 36 | comment:: "Deny access to rfc1918/internal." 37 | destination-address:: INTERNAL 38 | action:: deny 39 | } 40 | 41 | term deny-to-specific_hosts { 42 | comment:: "Deny access to specified public." 43 | destination-address:: WEB_SERVERS MAIL_SERVERS 44 | action:: deny 45 | } 46 | 47 | term default-permit { 48 | comment:: "Allow what's left." 49 | action:: accept 50 | } 51 | 52 | -------------------------------------------------------------------------------- /policies/pol/sample_cisconx.pol: -------------------------------------------------------------------------------- 1 | header { 2 | comment:: "Denies all traffic to internal IPs except established tcp replies." 3 | comment:: "Also denies access to certain public allocations." 4 | 5 | comment:: "Ideal for some internal lab/testing types of subnets that are" 6 | comment:: "not well trusted, but allowing internal users to access." 7 | 8 | comment:: "Apply to ingress interface (to filter traffic coming from lab)" 9 | target:: cisconx allowtointernet 10 | } 11 | 12 | term accept-dhcp { 13 | comment:: "Optional - allow forwarding of DHCP requests." 14 | destination-port:: DHCP 15 | protocol:: udp 16 | action:: accept 17 | } 18 | 19 | term accept-to-honestdns { 20 | comment:: "Allow name resolution using honestdns." 21 | destination-address:: GOOGLE_DNS 22 | destination-port:: DNS 23 | protocol:: udp 24 | action:: accept 25 | } 26 | 27 | term accept-tcp-replies { 28 | comment:: "Allow tcp replies to internal hosts." 29 | destination-address:: INTERNAL 30 | protocol:: tcp 31 | option:: tcp-established 32 | action:: accept 33 | } 34 | 35 | term deny-to-internal { 36 | comment:: "Deny access to rfc1918/internal." 37 | destination-address:: INTERNAL 38 | action:: deny 39 | } 40 | 41 | term deny-to-specific_hosts { 42 | comment:: "Deny access to specified public." 43 | destination-address:: WEB_SERVERS MAIL_SERVERS 44 | action:: deny 45 | } 46 | 47 | term default-permit { 48 | comment:: "Allow what's left." 49 | action:: accept 50 | } 51 | 52 | -------------------------------------------------------------------------------- /policies/pol/sample_cloudarmor.pol: -------------------------------------------------------------------------------- 1 | # 2 | # This is an sample policy for capirca 3 | # Note: Address family 'mixed' includes both IPv4 and IPv6; use 'inet' for IPv4 4 | # and 'inet6' for IPv6 5 | # 6 | header { 7 | comment:: "This is a sample policy to generate a CloudArmor filter" 8 | target:: cloudarmor mixed 9 | } 10 | 11 | term allow-trusted-sources { 12 | comment:: "Allow access from company's trusted IP space" 13 | source-address:: PUBLIC_NAT 14 | action:: accept 15 | } 16 | 17 | term deny-bogon-sources { 18 | comment:: "Deny access to sources with bogon IP addresses" 19 | source-address:: BOGON 20 | action:: deny 21 | } 22 | 23 | term default-deny { 24 | comment:: "Default deny rule" 25 | source-address:: ANY 26 | action:: deny 27 | } 28 | 29 | -------------------------------------------------------------------------------- /policies/pol/sample_fortigate.pol: -------------------------------------------------------------------------------- 1 | # Header Option: from-id -- Tells Capirca to number firewall 2 | # policies starting at the provided integer. 3 | # Header Option: ngfw-mode -- Default is profile. 4 | # If Fortigate is using policy-based NGFW mode add 'ngfw-mode policy' 5 | 6 | header { 7 | target:: fortigate 8 | } 9 | 10 | term allow-web-outbound{ 11 | source-address:: INTERNAL 12 | destination-port:: HTTP HTTPS 13 | source-port:: HTTP 14 | protocol:: tcp udp 15 | expiration:: 2020-12-20 16 | logging:: syslog 17 | action:: accept 18 | } 19 | 20 | term customers-policy { 21 | destination-address:: INTERNAL 22 | destination-exclude:: NTP_SERVERS 23 | destination-port:: DNS HTTPS 24 | source-exclude:: NTP_SERVERS 25 | protocol:: tcp udp 26 | action:: reject 27 | } 28 | 29 | term customers-policy2 { 30 | source-interface:: port2 31 | destination-interface:: port1 32 | source-address:: INTERNAL 33 | source-port:: SMTP 34 | destination-address:: MAIL_SERVERS 35 | destination-port:: SMTP 36 | protocol:: tcp udp 37 | comment:: "this a test policy" 38 | owner:: foo@google.com 39 | action:: accept 40 | } 41 | 42 | term ipv6-outbound{ 43 | source-address:: LINKLOCAL 44 | destination-address:: SITELOCAL LINKLOCAL 45 | destination-port:: HTTP HTTPS 46 | source-port:: HTTP 47 | protocol:: tcp 48 | expiration:: 2020-12-20 49 | action:: accept 50 | } 51 | -------------------------------------------------------------------------------- /policies/pol/sample_fortigate_localin.pol: -------------------------------------------------------------------------------- 1 | # Header Option: from-id -- Tells Capirca to number firewall 2 | # policies starting at the provided integer. 3 | # Header Option: ngfw-mode -- Default is profile. 4 | # If Fortigate is using policy-based NGFW mode add 'ngfw-mode policy' 5 | 6 | header { 7 | target:: fortigatelocalin 8 | } 9 | 10 | term allow-web-outbound{ 11 | source-address:: INTERNAL 12 | destination-port:: HTTP HTTPS 13 | source-port:: HTTP 14 | protocol:: tcp udp 15 | expiration:: 2020-12-20 16 | logging:: syslog 17 | action:: accept 18 | } 19 | 20 | term customers-policy { 21 | destination-address:: INTERNAL 22 | destination-exclude:: NTP_SERVERS 23 | destination-port:: DNS HTTPS 24 | source-exclude:: NTP_SERVERS 25 | protocol:: tcp udp 26 | action:: reject 27 | } 28 | 29 | term customers-policy2 { 30 | destination-interface:: port1 31 | source-address:: INTERNAL 32 | source-port:: SMTP 33 | destination-address:: MAIL_SERVERS 34 | destination-port:: SMTP 35 | protocol:: tcp udp 36 | comment:: "this a test policy" 37 | owner:: foo@google.com 38 | action:: accept 39 | } 40 | 41 | term ipv6-outbound{ 42 | source-address:: LINKLOCAL 43 | destination-address:: SITELOCAL LINKLOCAL 44 | destination-port:: HTTP HTTPS 45 | source-port:: HTTP 46 | protocol:: tcp 47 | expiration:: 2020-12-20 48 | action:: accept 49 | } 50 | -------------------------------------------------------------------------------- /policies/pol/sample_fortigate_localin_ipv4.pol: -------------------------------------------------------------------------------- 1 | header { 2 | target:: fortigatelocalin 3 | } 4 | 5 | term accept-https-requests{ 6 | source-interface:: loopback-1 7 | destination-interface:: loopback-1 8 | source-address:: HTTPS-PROXY-NETS 9 | destination-address:: REGIONAL-LOOPBACKS 10 | destination-port:: HTTPS 11 | protocol:: tcp 12 | comment:: "accept-https-requests" 13 | action:: accept 14 | } 15 | 16 | term accept-ssh-requests{ 17 | source-interface:: loopback-1 18 | destination-interface:: loopback-1 19 | source-address:: SSH-RELAY-NET 20 | destination-address:: REGIONAL-LOOPBACKS 21 | destination-port:: SSH 22 | protocol:: tcp 23 | comment:: "accept-ssh-requests" 24 | action:: accept 25 | } 26 | 27 | term accept-snmp-requests{ 28 | source-interface:: loopback-1 29 | destination-interface:: loopback-1 30 | source-address:: SNMP-SERVERS-NETS 31 | destination-address:: REGIONAL-LOOPBACKS 32 | destination-port:: SNMP 33 | protocol:: udp 34 | comment:: "accept-snmp-requests" 35 | action:: accept 36 | } 37 | 38 | term accept-bgp-loopbacks{ 39 | source-interface:: loopback-1 40 | destination-interface:: loopback-1 41 | source-address:: REGIONAL-LOOPBACKS 42 | destination-address:: REGIONAL-LOOPBACKS 43 | destination-port:: BGP 44 | protocol:: tcp 45 | comment:: "accept-bgp-loopbacks" 46 | action:: accept 47 | } 48 | 49 | term accept-esp-ah-tunnel-wan1{ 50 | source-interface:: x1.15 51 | destination-interface:: x1.15 52 | source-address:: P2P-RANGE 53 | destination-address:: ANY 54 | destination-port:: HTTPS 55 | protocol:: tcp 56 | comment:: "accept-esp-ah-tunnel-wan1" 57 | action:: accept 58 | } 59 | 60 | term accept-ike-tunnel-wan1{ 61 | source-interface:: x1.15 62 | destination-interface:: x1.15 63 | source-address:: P2P-RANGE 64 | destination-address:: ANY 65 | destination-port:: IKE 66 | protocol:: udp 67 | comment:: "accept-ike-tunnel-wan1" 68 | action:: accept 69 | } 70 | 71 | term accept-esp-ah-tunnel-wan2{ 72 | source-interface:: x3.1 73 | destination-interface:: x3.1 74 | source-address:: P2P-RANGE 75 | destination-address:: ANY 76 | destination-port:: HTTPS 77 | protocol:: tcp 78 | comment:: "accept-esp-ah-tunnel-wan2" 79 | action:: accept 80 | } 81 | 82 | term accept-ike-tunnel-wan2{ 83 | source-interface:: x3.1 84 | destination-interface:: x3.1 85 | source-address:: P2P-RANGE 86 | destination-address:: ANY 87 | destination-port:: IKE 88 | protocol:: udp 89 | comment:: "accept-ike-tunnel-wan2" 90 | action:: accept 91 | } 92 | 93 | term accept-bgp-wan{ 94 | source-interface:: x3.2 95 | destination-interface:: x3.2 96 | source-address:: P2P-RANGE 97 | destination-address:: ANY 98 | destination-port:: BGP 99 | protocol:: tcp 100 | comment:: "accept-bgp-wan" 101 | action:: accept 102 | } 103 | 104 | term accept-Fortigate-managers-request{ 105 | source-interface:: x5.5 106 | destination-interface:: x5.5 107 | source-address:: REGIONAL-FGMS 108 | destination-address:: ANY 109 | destination-port:: HTTPS 110 | protocol:: tcp 111 | comment:: "accept-Fortigate-managers-request" 112 | action:: accept 113 | } 114 | -------------------------------------------------------------------------------- /policies/pol/sample_fortigate_localin_ipv6.pol: -------------------------------------------------------------------------------- 1 | header { 2 | target:: fortigatelocalin 3 | } 4 | 5 | term accept-https-requests-v6{ 6 | destination-interface:: loopback-1 7 | source-address:: HTTP-PROXY6-NETS 8 | destination-address:: REGIONAL-LOOPBACKS6 9 | destination-port:: HTTPS 10 | protocol:: tcp 11 | comment:: "accept-https-requests-v6" 12 | action:: accept 13 | } 14 | 15 | term accept-ssh-requests-v6{ 16 | destination-interface:: loopback-1 17 | source-address:: SSH-RELAY6-NETS 18 | destination-address:: REGIONAL-LOOPBACKS6 19 | destination-port:: SSH 20 | protocol:: tcp 21 | comment:: "accept-ssh-requests-v6" 22 | action:: accept 23 | } 24 | 25 | term accept-snmp-requests-v6{ 26 | destination-interface:: loopback-1 27 | source-address:: SNMP-SERVER6-NETS 28 | destination-address:: REGIONAL-LOOPBACKS6 29 | destination-port:: SNMP 30 | protocol:: udp 31 | comment:: "accept-snmp-requests-v6" 32 | action:: accept 33 | } 34 | 35 | term accept-bgp-to-loopbacks-v6{ 36 | destination-interface:: loopback-2 37 | source-address:: REGIONAL-LOOPBACKS6 38 | destination-address:: REGIONAL-LOOPBACKS6 39 | destination-port:: BGP 40 | protocol:: tcp 41 | comment:: "accept-bgp-to-loopbacks-v6" 42 | action:: accept 43 | } 44 | 45 | term accept-esp-ah-tunnel-wan1-v6{ 46 | destination-interface:: x1.15 47 | source-address:: P2P-RANGE6 48 | destination-address:: ANY_V6 49 | destination-port:: HTTPS 50 | protocol:: tcp 51 | comment:: "accept-esp-ah-tunnel-wan1-v6" 52 | action:: accept 53 | } 54 | 55 | term accept-ike-tunnel-wan1-v6{ 56 | destination-interface:: x1.15 57 | source-address:: P2P-RANGE6 58 | destination-address:: ANY_V6 59 | destination-port:: IKE 60 | protocol:: udp 61 | comment:: "accept-ike-tunnel-wan1-v6" 62 | action:: accept 63 | } 64 | 65 | term accept-esp-ah-tunnel-wan2-v6{ 66 | destination-interface:: x3.1 67 | source-address:: P2P-RANGE6 68 | destination-address:: ANY_V6 69 | destination-port:: HTTPS 70 | protocol:: tcp 71 | comment:: "accept-esp-ah-tunnel-wan2-v6" 72 | action:: accept 73 | } 74 | 75 | term accept-ike-tunnel-wan2-v6{ 76 | destination-interface:: x3.1 77 | source-address:: P2P-RANGE6 78 | destination-address:: ANY_V6 79 | destination-port:: IKE 80 | protocol:: udp 81 | comment:: "accept-ike-tunnel-wan2-v6" 82 | action:: accept 83 | } 84 | 85 | term accept-bgp-wan-v6{ 86 | destination-interface:: x6.15 87 | source-address:: ANY_V6 88 | destination-address:: ANY_V6 89 | destination-port:: BGP 90 | protocol:: tcp 91 | comment:: "accept-bgp-wan-v6" 92 | action:: accept 93 | } 94 | 95 | term accept-fgm-v6{ 96 | destination-interface:: v6.15 97 | source-address:: REGIONAL-FGMS6 98 | destination-address:: ANY_V6 99 | destination-port:: HTTPS 100 | protocol:: tcp 101 | comment:: "accept-fgm-v6" 102 | action:: accept 103 | } 104 | 105 | term accept-test-v6{ 106 | destination-interface:: v6.15 107 | source-address:: REGIONAL-FGMS6 108 | destination-address:: ANY_V6 109 | destination-port:: HTTP 110 | protocol:: tcp 111 | comment:: "TESTING" 112 | action:: accept 113 | } 114 | -------------------------------------------------------------------------------- /policies/pol/sample_gce.pol: -------------------------------------------------------------------------------- 1 | # 2 | # This is an example policy for capirca 3 | # Target defaults to INGRESS is not specified in the header 4 | # 5 | header { 6 | comment:: "this is a sample policy to generate GCE filter" 7 | target:: gce global/networks/default inet 8 | } 9 | 10 | term test-ssh { 11 | comment:: "Allow SSH access to all instances from company." 12 | source-address:: PUBLIC_NAT 13 | protocol:: tcp 14 | destination-port:: SSH 15 | action:: accept 16 | } 17 | 18 | term test-web { 19 | comment:: "Allow HTTP/S to instances with webserver tag." 20 | source-address:: ANY 21 | protocol:: tcp 22 | destination-port:: HTTP 23 | destination-tag:: webserver 24 | action:: accept 25 | } 26 | 27 | term test-icmp { 28 | comment:: "Allow ICMP from company." 29 | source-address:: PUBLIC_NAT 30 | protocol:: icmp 31 | action:: accept 32 | } 33 | 34 | term test-icmpv6 { 35 | comment:: "Allow ICMPv6 from company. This should not be rendered." 36 | source-address:: PUBLIC_NAT 37 | protocol:: icmpv6 38 | action:: accept 39 | } 40 | 41 | term test-igmp { 42 | comment:: "Allow IGMP from company." 43 | source-address:: PUBLIC_NAT 44 | protocol:: igmp 45 | action:: accept 46 | } 47 | 48 | term test-multiple-protocols { 49 | comment:: "Allow TCP/UDP access to all instances from company." 50 | source-address:: PUBLIC_NAT 51 | protocol:: tcp udp 52 | destination-port:: HIGH_PORTS 53 | action:: accept 54 | } 55 | 56 | term test-multiple-protocols-tcp-icmpv6 { 57 | comment:: "Allow all tcp and icmpv6. This should only render tcp." 58 | source-address:: PUBLIC_NAT 59 | protocol:: tcp icmpv6 60 | action:: accept 61 | } 62 | 63 | term test-multiple-protocols-tcp-icmp { 64 | comment:: "Allow all tcp and icmp." 65 | source-address:: PUBLIC_NAT 66 | protocol:: tcp icmp 67 | action:: accept 68 | } 69 | 70 | term test-internal { 71 | comment:: "Allow all GCE network internal traffic." 72 | source-address:: RFC1918 73 | protocol:: tcp udp 74 | action:: accept 75 | } 76 | 77 | term default-deny { 78 | action:: deny 79 | } 80 | 81 | # 82 | # Sample EGRESS policy 83 | # If source-tag is included, it maps to targetTags in the GCP Egress rule 84 | # 85 | header { 86 | comment:: "this is a sample policy to generate EGRESS GCE filter" 87 | target:: gce EGRESS global/networks/default inet 88 | } 89 | 90 | term test-egress-address { 91 | comment:: "Outbound to Mail Server" 92 | protocol:: tcp 93 | destination-port:: SMTP 94 | destination-address:: MAIL_SERVERS 95 | action:: accept 96 | } 97 | 98 | term test-egress-tag { 99 | comment:: "Outbound to RFC1918" 100 | protocol:: tcp 101 | destination-port:: SSH 102 | destination-address:: PUBLIC_NAT 103 | source-tag:: webserver 104 | action:: accept 105 | } 106 | 107 | term test-egress-address-v6-only { 108 | comment:: "Outbound to IPv6 Server. This should not be rendered." 109 | protocol:: tcp 110 | destination-port:: SMTP 111 | destination-address:: PUBLIC_IPV6_SERVERS 112 | action:: accept 113 | } 114 | 115 | term default-deny { 116 | action:: deny 117 | } 118 | -------------------------------------------------------------------------------- /policies/pol/sample_gce_vpc_tf.pol: -------------------------------------------------------------------------------- 1 | # 2 | # This is an example policy for capirca 3 | # Target defaults to INGRESS is not specified in the header 4 | # 5 | header { 6 | comment:: "this is a sample policy to generate gce_vpc_tf config" 7 | target:: gce_vpc_tf global/networks/default inet 8 | } 9 | 10 | term test-ssh { 11 | comment:: "Allow SSH access to all instances from company." 12 | source-address:: PUBLIC_NAT 13 | protocol:: tcp 14 | destination-port:: SSH 15 | action:: accept 16 | } 17 | 18 | term test-web { 19 | comment:: "Allow HTTP/S to instances with webserver tag." 20 | source-address:: ANY 21 | protocol:: tcp 22 | destination-port:: HTTP 23 | destination-tag:: webserver 24 | action:: accept 25 | } 26 | 27 | term test-icmp { 28 | comment:: "Allow ICMP from company." 29 | source-address:: PUBLIC_NAT 30 | protocol:: icmp 31 | action:: accept 32 | } 33 | 34 | term test-icmpv6 { 35 | comment:: "Allow ICMPv6 from company. This should not be rendered." 36 | source-address:: PUBLIC_NAT 37 | protocol:: icmpv6 38 | action:: accept 39 | } 40 | 41 | term test-igmp { 42 | comment:: "Allow IGMP from company." 43 | source-address:: PUBLIC_NAT 44 | protocol:: igmp 45 | action:: accept 46 | } 47 | 48 | term test-multiple-protocols { 49 | comment:: "Allow TCP/UDP access to all instances from company." 50 | source-address:: PUBLIC_NAT 51 | protocol:: tcp udp 52 | destination-port:: HIGH_PORTS 53 | action:: accept 54 | } 55 | 56 | term test-multiple-protocols-tcp-icmpv6 { 57 | comment:: "Allow all tcp and icmpv6. This should only render tcp." 58 | source-address:: PUBLIC_NAT 59 | protocol:: tcp icmpv6 60 | action:: accept 61 | } 62 | 63 | term test-multiple-protocols-tcp-icmp { 64 | comment:: "Allow all tcp and icmp." 65 | source-address:: PUBLIC_NAT 66 | protocol:: tcp icmp 67 | action:: accept 68 | } 69 | 70 | term test-internal { 71 | comment:: "Allow all GCE network internal traffic." 72 | source-address:: RFC1918 73 | protocol:: tcp udp 74 | action:: accept 75 | } 76 | 77 | term test-service-account { 78 | comment:: "Allow Service account access to SSH." 79 | source-address:: PUBLIC_NAT 80 | protocol:: tcp 81 | destination-port:: SSH 82 | target-service-accounts:: acct@blah.com 83 | action:: accept 84 | } 85 | 86 | term default-deny { 87 | action:: deny 88 | } 89 | 90 | # 91 | # Sample EGRESS policy 92 | # If source-tag is included, it maps to targetTags in the GCP Egress rule 93 | # 94 | header { 95 | comment:: "this is a sample policy to generate EGRESS GCE filter" 96 | target:: gce EGRESS global/networks/default inet 97 | } 98 | 99 | term test-egress-address { 100 | comment:: "Outbound to Mail Server" 101 | protocol:: tcp 102 | destination-port:: SMTP 103 | destination-address:: MAIL_SERVERS 104 | action:: accept 105 | } 106 | 107 | term test-egress-tag { 108 | comment:: "Outbound to RFC1918" 109 | protocol:: tcp 110 | destination-port:: SSH 111 | destination-address:: PUBLIC_NAT 112 | source-tag:: webserver 113 | action:: accept 114 | } 115 | 116 | term test-egress-address-v6-only { 117 | comment:: "Outbound to IPv6 Server. This should not be rendered." 118 | protocol:: tcp 119 | destination-port:: SMTP 120 | destination-address:: PUBLIC_IPV6_SERVERS 121 | action:: accept 122 | } 123 | 124 | term default-deny { 125 | action:: deny 126 | } 127 | -------------------------------------------------------------------------------- /policies/pol/sample_gcp_hf.pol: -------------------------------------------------------------------------------- 1 | header { 2 | comment:: "This is sample policy for GCP HF" 3 | target:: gcp_hf testhf INGRESS inet beta 200 4 | } 5 | 6 | term folder-ssh{ 7 | comment:: "Allow SSH into folder-test" 8 | source-address:: PUBLIC_NAT 9 | protocol:: tcp 10 | destination-port:: SSH 11 | action:: next 12 | } 13 | 14 | term folder-rdp { 15 | comment:: "Allow RDP to targetResources. Making long comment to show truncation." 16 | source-address:: PUBLIC_NAT 17 | protocol:: tcp 18 | destination-port:: RDP 19 | target-resources:: (proj-1,vpc1) 20 | action:: next 21 | } 22 | 23 | term test-icmp { 24 | comment:: "Allow ICMP from company." 25 | source-address:: PUBLIC_NAT 26 | protocol:: icmp 27 | action:: accept 28 | } 29 | 30 | term test-icmpv6 { 31 | comment:: "Allow ICMPv6 from company. This should not be rendered." 32 | source-address:: PUBLIC_NAT 33 | protocol:: icmpv6 34 | action:: accept 35 | } 36 | 37 | term test-igmp { 38 | comment:: "Allow IGMP from company." 39 | source-address:: PUBLIC_NAT 40 | protocol:: igmp 41 | action:: accept 42 | } 43 | 44 | term test-multiple-protocols { 45 | comment:: "Allow TCP/UDP access to all instances from company." 46 | source-address:: PUBLIC_NAT 47 | protocol:: tcp udp 48 | destination-port:: HIGH_PORTS 49 | action:: accept 50 | } 51 | 52 | term test-multiple-protocols-tcp-icmpv6 { 53 | comment:: "Allow all tcp and icmpv6. This should only render tcp." 54 | source-address:: PUBLIC_NAT 55 | protocol:: tcp icmpv6 56 | action:: accept 57 | } 58 | 59 | term test-multiple-protocols-tcp-icmp { 60 | comment:: "Allow all tcp and icmp." 61 | source-address:: PUBLIC_NAT 62 | protocol:: tcp icmp 63 | action:: accept 64 | } 65 | 66 | term default-deny { 67 | action:: deny 68 | } 69 | 70 | header { 71 | comment:: "This is sample policy for GCP HF" 72 | target:: gcp_hf testhf EGRESS inet 200 73 | } 74 | 75 | term folder-smtp{ 76 | comment:: "Allow egress to mail servers" 77 | protocol:: tcp 78 | destination-port:: SMTP 79 | destination-address:: MAIL_SERVERS 80 | action:: next 81 | } 82 | 83 | term folder-ssh-nat{ 84 | comment:: "Allow egress ssh to RFC1918" 85 | protocol:: tcp 86 | destination-port:: SSH 87 | destination-address:: PUBLIC_NAT 88 | target-resources:: (proj-2,vpc2) 89 | action:: next 90 | } 91 | 92 | term test-egress-address-v6-only { 93 | comment:: "Outbound to IPv6 Server. This should not be rendered." 94 | protocol:: tcp 95 | destination-port:: SMTP 96 | destination-address:: PUBLIC_IPV6_SERVERS 97 | action:: accept 98 | } 99 | 100 | term default-deny { 101 | action:: deny 102 | } 103 | -------------------------------------------------------------------------------- /policies/pol/sample_inet6_gce.pol: -------------------------------------------------------------------------------- 1 | # 2 | # This is an example inet6 (i.e IPv6) policy for capirca 3 | # Target defaults to INGRESS is not specified in the header 4 | # 5 | header { 6 | comment:: "this is a sample policy to generate GCE filter" 7 | target:: gce global/networks/default inet6 8 | } 9 | 10 | term test-ssh-v6 { 11 | comment:: "Allow SSH access from IPv6 server." 12 | source-address:: PUBLIC_IPV6_SERVERS 13 | protocol:: tcp 14 | destination-port:: SSH 15 | action:: accept 16 | } 17 | 18 | term test-ssh-v4 { 19 | comment:: "This term should not be rendered since it is IPv4 only." 20 | source-address:: PUBLIC_NAT 21 | protocol:: tcp 22 | destination-port:: SSH 23 | action:: accept 24 | } 25 | 26 | term test-multiple-protocols { 27 | comment:: "Allow high port access from a public IPv6 server." 28 | source-address:: PUBLIC_IPV6_SERVERS 29 | protocol:: tcp udp 30 | destination-port:: HIGH_PORTS 31 | action:: accept 32 | } 33 | 34 | term test-multiple-protocols-tcp-icmpv6 { 35 | comment:: "Allow all tcp and icmpv6 from IPv6 Server." 36 | source-address:: PUBLIC_IPV6_SERVERS 37 | protocol:: tcp icmpv6 38 | action:: accept 39 | } 40 | 41 | term test-multiple-protocols-tcp-icmp { 42 | comment:: "Allow all tcp and icmp from IPv6 server. This should only render" 43 | comment:: "tcp." 44 | source-address:: PUBLIC_IPV6_SERVERS 45 | protocol:: tcp icmp 46 | action:: accept 47 | } 48 | 49 | term test-web { 50 | comment:: "Allow HTTP/S to instances with webserver tag and any IPs." 51 | source-tag:: webserver 52 | source-address:: ANY_V6 53 | protocol:: tcp 54 | destination-port:: HTTP 55 | destination-tag:: other-webserver 56 | action:: accept 57 | } 58 | 59 | term test-web-tag-only { 60 | comment:: "Allow HTTP/S to instances with webserver tag only." 61 | source-tag:: webserver 62 | protocol:: tcp 63 | destination-port:: HTTP 64 | destination-tag:: other-webserver 65 | action:: accept 66 | } 67 | 68 | term test-web-tag-v4-only { 69 | comment:: "Allow HTTP/S to instances with webserver tag. This should not" 70 | comment:: "be rendered." 71 | source-address:: ANY 72 | source-tag:: webserver 73 | protocol:: tcp 74 | destination-port:: HTTP 75 | destination-tag:: other-webserver 76 | action:: accept 77 | } 78 | 79 | term test-icmp { 80 | comment:: "Allow ICMP from company. This should not be rendered." 81 | source-address:: PUBLIC_NAT 82 | protocol:: icmp 83 | action:: accept 84 | } 85 | 86 | term test-icmpv6 { 87 | comment:: "Allow ICMPv6 from IPv6 server." 88 | source-address:: PUBLIC_IPV6_SERVERS 89 | protocol:: icmpv6 90 | action:: accept 91 | } 92 | 93 | term test-igmp { 94 | comment:: "Allow IGMP from IPv6 server. This should not be rendered." 95 | source-address:: PUBLIC_IPV6_SERVERS 96 | protocol:: igmp 97 | action:: accept 98 | } 99 | 100 | term default-deny { 101 | action:: deny 102 | } 103 | 104 | # 105 | # Sample EGRESS policy 106 | # If source-tag is included, it maps to targetTags in the GCP Egress rule 107 | # 108 | header { 109 | comment:: "this is a sample policy to generate EGRESS GCE filter" 110 | target:: gce EGRESS global/networks/default inet6 111 | } 112 | 113 | term test-egress-address { 114 | comment:: "Outbound to IPv6 Server." 115 | protocol:: tcp 116 | destination-port:: SMTP 117 | destination-address:: PUBLIC_IPV6_SERVERS 118 | action:: accept 119 | } 120 | 121 | term test-egress-tag { 122 | comment:: "Outbound to IPv6 Server." 123 | protocol:: tcp 124 | destination-port:: SSH 125 | destination-address:: PUBLIC_IPV6_SERVERS 126 | source-tag:: webserver 127 | action:: accept 128 | } 129 | 130 | term test-egress-tag-v4-only { 131 | comment:: "Outbound to RFC1918. This should not be rendered." 132 | protocol:: tcp 133 | destination-port:: SSH 134 | destination-address:: RFC1918 135 | source-tag:: webserver 136 | action:: accept 137 | } 138 | 139 | term egress-default-deny { 140 | action:: deny 141 | } 142 | -------------------------------------------------------------------------------- /policies/pol/sample_inet6_gcp_hf.pol: -------------------------------------------------------------------------------- 1 | header { 2 | comment:: "This is sample IPv6 policy for GCP HF" 3 | target:: gcp_hf testhf INGRESS inet6 ga 200 4 | } 5 | 6 | term folder-ssh-v6 { 7 | comment:: "Allow SSH into folder-test" 8 | source-address:: PUBLIC_IPV6_SERVERS 9 | protocol:: tcp 10 | destination-port:: SSH 11 | action:: next 12 | } 13 | 14 | term test-folder-ssh-v4 { 15 | comment:: "This term should not be rendered since it is IPv4 only." 16 | source-address:: PUBLIC_NAT 17 | protocol:: tcp 18 | destination-port:: SSH 19 | action:: next 20 | } 21 | 22 | term folder-rdp { 23 | comment:: "Allow RDP to targetResources. Making long comment to show truncation." 24 | source-address:: PUBLIC_IPV6_SERVERS 25 | protocol:: tcp 26 | destination-port:: RDP 27 | target-resources:: (proj-1,vpc1) 28 | action:: next 29 | } 30 | 31 | term test-multiple-protocols { 32 | comment:: "Allow high port access from a public IPv6 server." 33 | source-address:: PUBLIC_IPV6_SERVERS 34 | protocol:: tcp udp 35 | destination-port:: HIGH_PORTS 36 | action:: accept 37 | } 38 | 39 | term test-multiple-protocols-tcp-icmpv6 { 40 | comment:: "Allow all tcp and icmpv6 from IPv6 Server." 41 | source-address:: PUBLIC_IPV6_SERVERS 42 | protocol:: tcp icmpv6 43 | action:: accept 44 | } 45 | 46 | term test-multiple-protocols-tcp-icmp { 47 | comment:: "Allow all tcp and icmp from IPv6 server. This should only render" 48 | comment:: "tcp." 49 | source-address:: PUBLIC_IPV6_SERVERS 50 | protocol:: tcp icmp 51 | action:: accept 52 | } 53 | 54 | term test-icmp { 55 | comment:: "Allow ICMP from company. This should not be rendered." 56 | source-address:: PUBLIC_NAT 57 | protocol:: icmp 58 | action:: accept 59 | } 60 | 61 | term test-icmpv6 { 62 | comment:: "Allow ICMPv6 from IPv6 server." 63 | source-address:: PUBLIC_IPV6_SERVERS 64 | protocol:: icmpv6 65 | action:: accept 66 | } 67 | 68 | term test-igmp { 69 | comment:: "Allow IGMP from IPv6 server. This should not be rendered." 70 | source-address:: PUBLIC_IPV6_SERVERS 71 | protocol:: igmp 72 | action:: accept 73 | } 74 | 75 | term default-deny { 76 | action:: deny 77 | } 78 | 79 | header { 80 | comment:: "This is sample IPv6 policy for GCP HF" 81 | target:: gcp_hf testhf EGRESS inet6 ga 200 82 | } 83 | 84 | term folder-smtp{ 85 | comment:: "Outbound SMTP to IPv6 Server." 86 | protocol:: tcp 87 | destination-port:: SMTP 88 | destination-address:: PUBLIC_IPV6_SERVERS 89 | action:: next 90 | } 91 | 92 | term folder-ssh-nat{ 93 | comment:: "Outbound to IPv6 Server." 94 | protocol:: tcp 95 | destination-port:: SSH 96 | destination-address:: PUBLIC_IPV6_SERVERS 97 | target-resources:: (proj-2,vpc2) 98 | action:: next 99 | } 100 | 101 | term test-egress-address-v4-only { 102 | comment:: "Outbound to RFC1918. This should not be rendered." 103 | protocol:: tcp 104 | destination-port:: SSH 105 | destination-address:: RFC1918 106 | action:: accept 107 | } 108 | 109 | term egress-default-deny { 110 | action:: deny 111 | } 112 | -------------------------------------------------------------------------------- /policies/pol/sample_ipset.pol: -------------------------------------------------------------------------------- 1 | header { 2 | target:: ipset OUTPUT DROP 3 | } 4 | 5 | term deny-to-reserved { 6 | destination-address:: RESERVED 7 | action:: deny 8 | } 9 | 10 | term deny-to-bogons { 11 | destination-address:: RESERVED 12 | action:: deny 13 | } 14 | 15 | term allow-web-to-mail { 16 | source-address:: WEB_SERVERS 17 | destination-address:: MAIL_SERVERS 18 | action:: accept 19 | } -------------------------------------------------------------------------------- /policies/pol/sample_k8s.pol: -------------------------------------------------------------------------------- 1 | # 2 | # This is an example policy for capirca 3 | # Target defaults to INGRESS is not specified in the header 4 | # 5 | header { 6 | comment:: "this is a sample policy to generate Kubernetes NetworkPolicy filter" 7 | target:: k8s 8 | } 9 | 10 | term test-ssh { 11 | comment:: "Allow SSH access to all pods from company." 12 | source-address:: PUBLIC_NAT 13 | protocol:: tcp 14 | destination-port:: SSH 15 | action:: accept 16 | } 17 | 18 | term test-web { 19 | comment:: "Allow HTTP to pods" 20 | source-address:: ANY 21 | protocol:: tcp 22 | destination-port:: HTTP 23 | action:: accept 24 | } 25 | 26 | term test-multiple-protocols { 27 | comment:: "Allow TCP/UDP access to all pods from company." 28 | source-address:: PUBLIC_NAT 29 | protocol:: tcp udp 30 | destination-port:: HIGH_PORTS 31 | action:: accept 32 | } 33 | 34 | term test-multiple-protocols-tcp-sctp { 35 | comment:: "Allow all tcp and sctp." 36 | source-address:: PUBLIC_NAT 37 | protocol:: tcp sctp 38 | action:: accept 39 | } 40 | 41 | 42 | term test-internal { 43 | comment:: "Allow all network internal traffic." 44 | source-address:: RFC1918 45 | protocol:: tcp udp 46 | action:: accept 47 | } 48 | 49 | term default-deny { 50 | action:: deny 51 | } 52 | 53 | # 54 | # Sample EGRESS policy 55 | # If source-tag is included, it maps to targetTags in the Kubernetes NetworkPolicy Egress rule 56 | # 57 | header { 58 | comment:: "this is a sample policy to generate EGRESS Kubernetes NetworkPolicy filter" 59 | target:: k8s EGRESS 60 | } 61 | 62 | term test-egress-address { 63 | comment:: "Outbound to Mail Server" 64 | protocol:: tcp 65 | destination-port:: SMTP 66 | destination-address:: MAIL_SERVERS 67 | action:: accept 68 | } 69 | 70 | term test-egress-tag { 71 | comment:: "Outbound to RFC1918" 72 | protocol:: tcp 73 | destination-port:: SSH 74 | destination-address:: PUBLIC_NAT 75 | action:: accept 76 | } 77 | 78 | term test-egress-address-v6-only { 79 | comment:: "Outbound to IPv6 Server" 80 | protocol:: tcp 81 | destination-port:: SMTP 82 | destination-address:: PUBLIC_IPV6_SERVERS 83 | action:: accept 84 | } 85 | 86 | term default-deny { 87 | action:: deny 88 | } 89 | -------------------------------------------------------------------------------- /policies/pol/sample_mixed_gce.pol: -------------------------------------------------------------------------------- 1 | # 2 | # This is an example inet6 (i.e IPv6) policy for capirca 3 | # Target defaults to INGRESS is not specified in the header 4 | # 5 | header { 6 | comment:: "this is a sample policy to generate GCE filter" 7 | target:: gce global/networks/default mixed 8 | } 9 | 10 | term test-ssh-mixed { 11 | comment:: "Allow SSH access from Server and Company with mixed addresses." 12 | source-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 13 | protocol:: tcp 14 | destination-port:: SSH 15 | action:: accept 16 | } 17 | 18 | term test-ssh-v6 { 19 | comment:: "Allow SSH access from IPv6 server." 20 | source-address:: PUBLIC_IPV6_SERVERS 21 | protocol:: tcp 22 | destination-port:: SSH 23 | action:: accept 24 | } 25 | 26 | term test-ssh-v4 { 27 | comment:: "Allow SSH access to all instances from company." 28 | source-address:: PUBLIC_NAT 29 | protocol:: tcp 30 | destination-port:: SSH 31 | action:: accept 32 | } 33 | 34 | term test-multiple-protocols { 35 | comment:: "Allow high port access from a public IPv6 server." 36 | source-address:: PUBLIC_IPV6_SERVERS 37 | protocol:: tcp udp 38 | destination-port:: HIGH_PORTS 39 | action:: accept 40 | } 41 | 42 | term test-multiple-protocols-tcp-icmpv6 { 43 | comment:: "Allow all tcp and icmpv6 from IPv6 Server." 44 | source-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 45 | protocol:: tcp icmpv6 46 | action:: accept 47 | } 48 | 49 | term test-multiple-protocols-tcp-icmp { 50 | comment:: "Allow all tcp and icmp." 51 | source-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 52 | protocol:: tcp icmp 53 | action:: accept 54 | } 55 | 56 | term test-multiple-protocols-tcp-icmpv6-v6-only { 57 | comment:: "Allow all tcp and icmpv6." 58 | source-address:: PUBLIC_IPV6_SERVERS 59 | protocol:: tcp icmpv6 60 | action:: accept 61 | } 62 | 63 | term test-multiple-protocols-tcp-icmp-v4-only { 64 | comment:: "Allow all tcp and icmp." 65 | source-address:: PUBLIC_NAT 66 | protocol:: tcp icmp 67 | action:: accept 68 | } 69 | 70 | term test-web { 71 | comment:: "Allow HTTP/S to instances with webserver tag and any IPs." 72 | source-tag:: webserver 73 | source-address:: ANY_MIXED 74 | protocol:: tcp 75 | destination-port:: HTTP 76 | destination-tag:: other-webserver 77 | action:: accept 78 | } 79 | 80 | term test-web-tag-only { 81 | comment:: "Allow HTTP/S to instances with webserver tag only." 82 | source-tag:: webserver 83 | protocol:: tcp 84 | destination-port:: HTTP 85 | destination-tag:: other-webserver 86 | action:: accept 87 | } 88 | 89 | term test-web-tag-v4-only { 90 | comment:: "Allow HTTP/S to instances with webserver tag." 91 | source-address:: ANY 92 | source-tag:: webserver 93 | protocol:: tcp 94 | destination-port:: HTTP 95 | destination-tag:: other-webserver 96 | action:: accept 97 | } 98 | 99 | term test-icmp { 100 | comment:: "Allow ICMP from company." 101 | source-address:: PUBLIC_NAT 102 | protocol:: icmp 103 | action:: accept 104 | } 105 | 106 | term test-icmpv6 { 107 | comment:: "Allow ICMPv6 from IPv6 server." 108 | source-address:: PUBLIC_IPV6_SERVERS 109 | protocol:: icmpv6 110 | action:: accept 111 | } 112 | 113 | term test-igmp { 114 | comment:: "Allow IGMP from server and company with mixed addresses." 115 | source-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 116 | protocol:: igmp 117 | action:: accept 118 | } 119 | 120 | term default-deny { 121 | action:: deny 122 | } 123 | 124 | # 125 | # Sample EGRESS policy 126 | # If source-tag is included, it maps to targetTags in the GCP Egress rule 127 | # 128 | header { 129 | comment:: "this is a sample policy to generate EGRESS GCE filter" 130 | target:: gce EGRESS global/networks/default mixed 131 | } 132 | 133 | term test-egress-address { 134 | comment:: "Outbound to Server with mixed addresses." 135 | protocol:: tcp 136 | destination-port:: SMTP 137 | destination-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 138 | action:: accept 139 | } 140 | 141 | term test-egress-tag { 142 | comment:: "Outbound to Server with tag." 143 | protocol:: tcp 144 | destination-port:: SSH 145 | destination-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 146 | source-tag:: webserver 147 | action:: accept 148 | } 149 | 150 | term test-egress-tag-v4-only { 151 | comment:: "Outbound to RFC1918." 152 | protocol:: tcp 153 | destination-port:: SSH 154 | destination-address:: RFC1918 155 | source-tag:: webserver 156 | action:: accept 157 | } 158 | 159 | term test-egress-tag-v6-only { 160 | comment:: "Outbound to IPv6 Server." 161 | protocol:: tcp 162 | destination-port:: SSH 163 | destination-address:: PUBLIC_IPV6_SERVERS 164 | source-tag:: webserver 165 | action:: accept 166 | } 167 | 168 | term egress-default-deny { 169 | action:: deny 170 | } 171 | -------------------------------------------------------------------------------- /policies/pol/sample_mixed_gcp_hf.pol: -------------------------------------------------------------------------------- 1 | header { 2 | comment:: "This is sample IPv6 policy for GCP HF" 3 | target:: gcp_hf testhf INGRESS mixed ga 200 4 | } 5 | 6 | term test-folder-ssh-mixed { 7 | comment:: "Allow SSH from Server and Company with mixed addresses." 8 | source-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 9 | protocol:: tcp 10 | destination-port:: SSH 11 | action:: next 12 | } 13 | 14 | term test-folder-ssh-v6 { 15 | comment:: "Allow SSH access from IPv6 server." 16 | source-address:: PUBLIC_IPV6_SERVERS 17 | protocol:: tcp 18 | destination-port:: SSH 19 | action:: next 20 | } 21 | 22 | term test-folder-ssh-v4 { 23 | comment:: "Allow SSH access to all instances from company." 24 | source-address:: PUBLIC_NAT 25 | protocol:: tcp 26 | destination-port:: SSH 27 | action:: next 28 | } 29 | 30 | term folder-rdp { 31 | comment:: "Allow RDP to targetResources. Making long comment to show truncation." 32 | source-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 33 | protocol:: tcp 34 | destination-port:: RDP 35 | target-resources:: (proj-1,vpc1) 36 | action:: next 37 | } 38 | 39 | term test-multiple-protocols { 40 | comment:: "Allow high port access from mixed address servers." 41 | source-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 42 | protocol:: tcp udp 43 | destination-port:: HIGH_PORTS 44 | action:: accept 45 | } 46 | 47 | term test-multiple-protocols-tcp-icmpv6 { 48 | comment:: "Allow all tcp and icmpv6 from mixed address servers." 49 | source-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 50 | protocol:: tcp icmpv6 51 | action:: accept 52 | } 53 | 54 | term test-multiple-protocols-tcp-icmp { 55 | comment:: "Allow all tcp and icmp from mixed address servers." 56 | source-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 57 | protocol:: tcp icmp 58 | action:: accept 59 | } 60 | 61 | term test-multiple-protocols-tcp-icmpv6-v6-only { 62 | comment:: "Allow all tcp and icmpv6." 63 | source-address:: PUBLIC_IPV6_SERVERS 64 | protocol:: tcp icmpv6 65 | action:: accept 66 | } 67 | 68 | term test-multiple-protocols-tcp-icmp-v4-only { 69 | comment:: "Allow all tcp and icmp." 70 | source-address:: PUBLIC_NAT 71 | protocol:: tcp icmp 72 | action:: accept 73 | } 74 | 75 | term test-icmp { 76 | comment:: "Allow ICMP from mixed server." 77 | source-address:: PUBLIC_NAT PUBLIC_IPV6_SERVERS 78 | protocol:: icmp 79 | action:: accept 80 | } 81 | 82 | term test-icmpv6 { 83 | comment:: "Allow ICMPv6 from mixed server." 84 | source-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 85 | protocol:: icmpv6 86 | action:: accept 87 | } 88 | 89 | term test-igmp { 90 | comment:: "Allow IGMP from mixed server. This should rendered for IPv4 only." 91 | source-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 92 | protocol:: igmp 93 | action:: accept 94 | } 95 | 96 | term default-deny { 97 | action:: deny 98 | } 99 | 100 | header { 101 | comment:: "This is sample IPv6 policy for GCP HF" 102 | target:: gcp_hf testhf EGRESS mixed ga 200 103 | } 104 | 105 | term folder-smtp{ 106 | comment:: "Outbound SMTP to mixed address servers." 107 | protocol:: tcp 108 | destination-port:: SMTP 109 | destination-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 110 | action:: next 111 | } 112 | 113 | term folder-ssh-nat{ 114 | comment:: "Outbound to mixed address servers." 115 | protocol:: tcp 116 | destination-port:: SSH 117 | destination-address:: PUBLIC_IPV6_SERVERS PUBLIC_NAT 118 | target-resources:: (proj-2,vpc2) 119 | action:: next 120 | } 121 | 122 | term test-egress-address-v4-only { 123 | comment:: "Outbound SSH to RFC1918." 124 | protocol:: tcp 125 | destination-port:: SSH 126 | destination-address:: RFC1918 127 | action:: accept 128 | } 129 | 130 | term test-egress-address-v6-only { 131 | comment:: "Outbound SSH to public IPv6 server." 132 | protocol:: tcp 133 | destination-port:: SSH 134 | destination-address:: PUBLIC_IPV6_SERVERS 135 | action:: accept 136 | } 137 | 138 | term egress-default-deny { 139 | action:: deny 140 | } 141 | -------------------------------------------------------------------------------- /policies/pol/sample_msmpc.pol: -------------------------------------------------------------------------------- 1 | header { 2 | comment:: "this is a sample edge input filter that generates" 3 | comment:: "msmpc output formats." 4 | target:: msmpc edge-inbound mixed ingress 5 | } 6 | 7 | #include 'includes/untrusted-networks-blocking.inc' 8 | 9 | term permit-mail-services { 10 | destination-address:: MAIL_SERVERS 11 | protocol:: tcp 12 | destination-port:: MAIL_SERVICES 13 | action:: accept 14 | } 15 | 16 | term permit-web-services { 17 | destination-address:: WEB_SERVERS 18 | protocol:: tcp 19 | destination-port:: WEB_SERVICES 20 | action:: accept 21 | } 22 | 23 | term permit-tcp-established { 24 | destination-address:: MAIL_SERVERS WEB_SERVERS PUBLIC_NAT 25 | protocol:: tcp 26 | option:: tcp-established 27 | action:: accept 28 | } 29 | 30 | term permit-udp-established { 31 | destination-address:: MAIL_SERVERS WEB_SERVERS PUBLIC_NAT 32 | protocol:: udp 33 | source-port:: HIGH_PORTS 34 | action:: accept 35 | } 36 | 37 | term default-deny { 38 | action:: deny 39 | logging:: true 40 | } 41 | 42 | header { 43 | comment:: "this is a sample inet edge input filter that generates" 44 | comment:: "msmpc output formats." 45 | target:: msmpc edge-inbound-ipv4 inet ingress 46 | } 47 | 48 | #include 'includes/untrusted-networks-blocking.inc' 49 | 50 | term permit-mail-services { 51 | destination-address:: MAIL_SERVERS 52 | protocol:: tcp 53 | destination-port:: MAIL_SERVICES 54 | action:: accept 55 | } 56 | 57 | term permit-web-services { 58 | destination-address:: WEB_SERVERS 59 | protocol:: tcp 60 | destination-port:: WEB_SERVICES 61 | action:: accept 62 | } 63 | 64 | term permit-tcp-established { 65 | destination-address:: MAIL_SERVERS WEB_SERVERS PUBLIC_NAT 66 | protocol:: tcp 67 | option:: tcp-established 68 | action:: accept 69 | } 70 | 71 | term permit-udp-established { 72 | destination-address:: MAIL_SERVERS WEB_SERVERS PUBLIC_NAT 73 | protocol:: udp 74 | source-port:: HIGH_PORTS 75 | action:: accept 76 | } 77 | 78 | term default-deny { 79 | action:: deny 80 | logging:: true 81 | } 82 | 83 | header { 84 | comment:: "this is a sample inet6 edge input filter that generates" 85 | comment:: "msmpc output formats." 86 | target:: msmpc edge-inbound-ipv6 inet6 ingress 87 | } 88 | 89 | #include 'includes/untrusted-networks-blocking.inc' 90 | 91 | term permit-mail-services { 92 | destination-address:: MAIL_SERVERS 93 | protocol:: tcp 94 | destination-port:: MAIL_SERVICES 95 | action:: accept 96 | } 97 | 98 | term permit-web-services { 99 | destination-address:: WEB_SERVERS 100 | protocol:: tcp 101 | destination-port:: WEB_SERVICES 102 | action:: accept 103 | } 104 | 105 | term permit-tcp-established { 106 | destination-address:: MAIL_SERVERS WEB_SERVERS PUBLIC_NAT 107 | protocol:: tcp 108 | option:: tcp-established 109 | action:: accept 110 | } 111 | 112 | term permit-udp-established { 113 | destination-address:: MAIL_SERVERS WEB_SERVERS PUBLIC_NAT 114 | protocol:: udp 115 | source-port:: HIGH_PORTS 116 | action:: accept 117 | } 118 | 119 | term default-deny { 120 | action:: deny 121 | logging:: true 122 | } 123 | 124 | header { 125 | comment:: "this is a sample msmpc output filter" 126 | target:: msmpc edge-outbound mixed egress 127 | } 128 | 129 | term deny-to-bad-destinations { 130 | destination-address:: RFC1918 BOGON RESERVED 131 | action:: deny 132 | } 133 | 134 | term default-accept { 135 | action:: accept 136 | } 137 | 138 | header { 139 | comment:: "this is a sample msmpc input-output filter" 140 | target:: msmpc edge-outbound mixed 141 | } 142 | 143 | term deny-to-bad-destinations { 144 | destination-address:: RFC1918 BOGON RESERVED 145 | action:: deny 146 | } 147 | 148 | term permit-mail-services { 149 | destination-address:: MAIL_SERVERS 150 | protocol:: tcp 151 | destination-port:: MAIL_SERVICES 152 | action:: accept 153 | } 154 | 155 | term permit-web-services { 156 | destination-address:: WEB_SERVERS 157 | protocol:: tcp 158 | destination-port:: WEB_SERVICES 159 | action:: accept 160 | } 161 | 162 | term permit-mail-outbound { 163 | source-address:: MAIL_SERVERS WEB_SERVERS PUBLIC_NAT 164 | protocol:: tcp udp 165 | action:: accept 166 | } 167 | 168 | term default-deny { 169 | action:: deny 170 | logging:: true 171 | } 172 | -------------------------------------------------------------------------------- /policies/pol/sample_multitarget.pol: -------------------------------------------------------------------------------- 1 | # 2 | # This is an example policy for capirca 3 | # 4 | header { 5 | comment:: "this is a sample edge input filter that generates" 6 | comment:: "multiple output formats." 7 | # NOTES: iptables produces filter 'lines' that must be used as args to the 8 | # '$ iptables' cmd, while Speedway produces stateful iptables filters 9 | # compatible with iptables-restore (most people will prefer speedway) 10 | target:: juniper edge-inbound inet 11 | target:: juniperevo edge-inbound inet6 ingress 12 | target:: msmpc edge-inbound mixed ingress 13 | target:: cisco edge-inbound mixed 14 | target:: speedway INPUT 15 | target:: ciscoasa asa_in 16 | target:: demo edge-inbound 17 | target:: arista edge-inbound 18 | target:: arista_tp edge-inbound 19 | target:: brocade edge-inbound 20 | target:: cisconx edge-inbound 21 | target:: ciscoxr edge-inbound 22 | target:: fortigate 23 | target:: fortigatelocalin 24 | } 25 | 26 | #include 'includes/untrusted-networks-blocking.inc' 27 | 28 | term permit-mail-services { 29 | destination-address:: MAIL_SERVERS 30 | protocol:: tcp 31 | destination-port:: MAIL_SERVICES 32 | action:: accept 33 | } 34 | 35 | term permit-web-services { 36 | destination-address:: WEB_SERVERS 37 | protocol:: tcp 38 | destination-port:: WEB_SERVICES 39 | action:: accept 40 | } 41 | 42 | term permit-tcp-established { 43 | destination-address:: MAIL_SERVERS WEB_SERVERS PUBLIC_NAT 44 | protocol:: tcp 45 | option:: tcp-established 46 | action:: accept 47 | } 48 | 49 | term permit-udp-established { 50 | destination-address:: MAIL_SERVERS WEB_SERVERS PUBLIC_NAT 51 | protocol:: udp 52 | source-port:: HIGH_PORTS 53 | action:: accept 54 | } 55 | 56 | term default-deny { 57 | action:: deny 58 | } 59 | 60 | header { 61 | comment:: "this is a sample output filter" 62 | target:: juniper edge-outbound 63 | target:: msmpc edge-outbound mixed egress 64 | target:: arista_tp edge-outbound 65 | target:: cisco edge-outbound mixed 66 | target:: speedway OUTPUT 67 | target:: ciscoasa asa_out 68 | target:: fortigate 69 | target:: fortigatelocalin 70 | } 71 | 72 | term deny-to-bad-destinations { 73 | destination-address:: RFC1918 BOGON RESERVED 74 | action:: deny 75 | } 76 | 77 | term default-accept { 78 | action:: accept 79 | } 80 | -------------------------------------------------------------------------------- /policies/pol/sample_nftables-dev.pol: -------------------------------------------------------------------------------- 1 | # 2 | # NFTables generator policy example. 3 | # Intended to render ICMP terms for both IPv4 and IPv6 families. 4 | # 5 | 6 | header { 7 | comment:: "This policy validates handling of term.option tcp-established." 8 | comment:: "and UDP 'established'" 9 | target:: nftables inet6 INPUT 10 | } 11 | 12 | term accept-webserver-traffic { 13 | comment:: "Allow webserver inbound traffic." 14 | destination-address:: WEB_SERVERS 15 | destination-port:: WEB_SERVICES 16 | protocol:: tcp 17 | action:: accept 18 | } 19 | 20 | term test-tcp-established { 21 | comment:: "Allow tcp-established traffic." 22 | destination-address:: MAIL_SERVERS WEB_SERVERS PUBLIC_NAT 23 | protocol:: tcp udp 24 | action:: accept 25 | } 26 | 27 | term permit-tcp-replies { 28 | option:: tcp-established 29 | action:: accept 30 | } 31 | 32 | term test-dns-replies { 33 | comment:: "Allow DNS replies, and test udp established option." 34 | comment:: "This should not be generated since this is a stateful policy." 35 | source-port:: DNS 36 | destination-address:: INTERNAL 37 | protocol:: udp 38 | logging:: syslog 39 | counter:: dns-counter 40 | action:: accept 41 | } 42 | 43 | -------------------------------------------------------------------------------- /policies/pol/sample_nftables-mixed-icmp.pol: -------------------------------------------------------------------------------- 1 | # 2 | # NFTables generator policy example. 3 | # Intended to render ICMP terms for both IPv4 and IPv6 families. 4 | # 5 | 6 | header { 7 | comment:: "This policy expected to test every combination of REQUIRED keywords." 8 | target:: nftables mixed INPUT 9 | } 10 | 11 | term multi-all-families { 12 | comment:: "Validate multiple protocols." 13 | protocol:: udp tcp icmp icmpv6 14 | action:: accept 15 | } 16 | 17 | term multi-proto-term { 18 | comment:: "Validate multiple protocols. IPv6 icmp should not render." 19 | protocol:: udp tcp icmp 20 | action:: accept 21 | } 22 | 23 | term test-tcp-icmp { 24 | comment:: "Allow ICMP from company." 25 | source-address:: PUBLIC_NAT 26 | protocol:: udp tcp icmp 27 | action:: accept 28 | } 29 | 30 | term test-icmp { 31 | comment:: "Allow ICMP from source-address." 32 | source-address:: PUBLIC_NAT 33 | protocol:: icmp 34 | action:: accept 35 | } 36 | 37 | term test-icmp-type-ip4 { 38 | comment:: "IPv4 icmp-type test" 39 | icmp-type:: echo-request echo-reply 40 | protocol:: icmp 41 | action:: accept 42 | } 43 | 44 | term test-icmp-type-ip6 { 45 | comment:: "IPv6 icmp-type test" 46 | icmp-type:: multicast-listener-done router-solicit router-advertisement multicast-router-solicitation multicast-router-advertisement 47 | protocol:: icmpv6 48 | action:: accept 49 | } 50 | 51 | term full-combo-term { 52 | comment:: "Test src/dest 80 - No addresses" 53 | source-address:: CLOUDFLARE_PUBLIC_DNS 54 | destination-address:: GOOGLE_PUBLIC_DNS_ANYCAST 55 | protocol:: tcp 56 | source-port:: HTTP 57 | destination-port:: HTTP 58 | action:: accept 59 | } 60 | 61 | term base-traceroute-in { 62 | comment:: "Ensure we can output a port-range." 63 | protocol:: udp 64 | source-port:: TRACEROUTE 65 | destination-port:: HIGH_PORTS 66 | action:: accept 67 | } 68 | -------------------------------------------------------------------------------- /policies/pol/sample_nftables-mixed-multiple-headers-combo.pol: -------------------------------------------------------------------------------- 1 | # Test rendering for multiple nftables policies. 2 | 3 | header { 4 | comment:: "Noverbose + custom priority policy example" 5 | target:: nftables mixed INPUT 300 6 | } 7 | 8 | term multi-all-families { 9 | comment:: "Validate multiple protocols." 10 | protocol:: udp tcp icmp icmpv6 11 | action:: accept 12 | } 13 | 14 | term multi-proto-term { 15 | comment:: "Validate multiple protocols. IPv6 icmp should not render." 16 | protocol:: udp tcp icmp 17 | action:: accept 18 | } 19 | 20 | header { 21 | comment:: "Noverbose + custom priority policy example" 22 | target:: nftables mixed INPUT 400 23 | } 24 | 25 | term test-tcp-icmp { 26 | comment:: "Allow ICMP from company." 27 | source-address:: PUBLIC_NAT 28 | protocol:: udp tcp icmp 29 | action:: accept 30 | } 31 | 32 | header { 33 | comment:: "Noverbose + custom priority policy example" 34 | target:: nftables mixed OUTPUT 35 | } 36 | 37 | term test-icmp { 38 | comment:: "Allow ICMP from company." 39 | source-address:: PUBLIC_NAT 40 | protocol:: icmp 41 | action:: accept 42 | } 43 | 44 | term test-icmp-type-ip4 { 45 | comment:: "IPv4 icmp-type test" 46 | icmp-type:: echo-request echo-reply 47 | protocol:: icmp 48 | action:: accept 49 | } 50 | 51 | term test-icmp-type-ip6 { 52 | comment:: "IPv6 icmp-type test" 53 | icmp-type:: multicast-listener-done router-solicit router-advertisement 54 | protocol:: icmpv6 55 | action:: accept 56 | } 57 | 58 | term full-combo-term { 59 | comment:: "Test src/dest 80 - with addresses" 60 | source-address:: CLOUDFLARE_PUBLIC_DNS 61 | destination-address:: GOOGLE_PUBLIC_DNS_ANYCAST 62 | protocol:: tcp 63 | source-port:: HTTP 64 | destination-port:: HTTP 65 | action:: accept 66 | } 67 | 68 | term multi-all-families { 69 | comment:: "Validate multiple protocols." 70 | protocol:: udp tcp icmp icmpv6 71 | action:: accept 72 | } 73 | 74 | term base-traceroute-in { 75 | comment:: "Ensure we can output a port-range." 76 | protocol:: udp 77 | source-port:: TRACEROUTE 78 | destination-port:: HIGH_PORTS 79 | action:: accept 80 | } 81 | -------------------------------------------------------------------------------- /policies/pol/sample_nsxt.pol: -------------------------------------------------------------------------------- 1 | header { 2 | comment:: "Sample NSXT filter" 3 | target:: nsxt sample_nsxt_filter mixed 1234 securitygroup securitygroupId 4 | } 5 | 6 | term accept-icmp { 7 | comment:: "Allow ICMPv4." 8 | protocol:: icmp 9 | action:: accept 10 | } 11 | 12 | term accept-icmpv6 { 13 | comment:: "Allow ICMPv6." 14 | protocol:: icmpv6 15 | action:: accept 16 | } 17 | 18 | term accept-icmpv6-multiple-types { 19 | comment:: "Allow specific ICMPv6 types router-solicit and echo-reply." 20 | source-address:: GOOGLE_DNS 21 | protocol:: icmpv6 22 | icmp-type:: router-solicit echo-reply 23 | action:: accept 24 | } 25 | 26 | term accept-traceroute { 27 | comment:: "Allow inbound traceroute from any source." 28 | destination-port:: TRACEROUTE 29 | protocol:: udp 30 | action:: accept 31 | expiration:: 2001-12-31 32 | owner:: jeff 33 | } 34 | 35 | term accept-bgp-requests { 36 | comment:: "Allow BGP requests from peers." 37 | destination-port:: BGP 38 | protocol:: tcp 39 | action:: accept 40 | } 41 | 42 | term accept-bgp-replies { 43 | comment:: "Allow inbound replies to BGP requests." 44 | source-port:: BGP 45 | protocol:: tcp 46 | action:: accept 47 | } 48 | 49 | term accept-ospf { 50 | comment:: "Allow outbound OSPF traffic from other RFC1918 routers." 51 | source-address:: INTERNAL 52 | protocol:: ospf 53 | action:: accept 54 | } 55 | 56 | term allow-vrrp { 57 | protocol:: vrrp 58 | action:: accept 59 | } 60 | 61 | term accept-ike { 62 | source-port:: IKE 63 | destination-port:: IKE 64 | protocol:: udp 65 | action:: accept 66 | } 67 | 68 | term accept-ipsec { 69 | protocol:: esp 70 | action:: accept 71 | } 72 | term accept-pim { 73 | source-address:: INTERNAL 74 | protocol:: pim 75 | action:: accept 76 | } 77 | 78 | term accept-igmp { 79 | source-address:: INTERNAL 80 | protocol:: igmp 81 | action:: accept 82 | } 83 | 84 | term accept-ssh-requests { 85 | source-address:: INTERNAL 86 | destination-port:: SSH 87 | protocol:: tcp 88 | action:: accept 89 | } 90 | 91 | term accept-ssh-replies { 92 | source-port:: SSH 93 | protocol:: tcp 94 | action:: accept 95 | } 96 | 97 | term accept-snmp-requests { 98 | source-address:: INTERNAL 99 | destination-address:: INTERNAL 100 | destination-port:: SNMP 101 | protocol:: udp 102 | action:: accept 103 | } 104 | 105 | term accept-dns-replies { 106 | source-address:: INTERNAL 107 | destination-address:: INTERNAL 108 | source-port:: DNS 109 | protocol:: udp 110 | action:: accept 111 | } 112 | 113 | term allow-ntp-request { 114 | source-address:: NTP_SERVERS 115 | destination-address:: INTERNAL 116 | destination-port:: NTP 117 | protocol:: udp 118 | action:: accept 119 | } 120 | 121 | term allow-ntp-replies { 122 | source-address:: INTERNAL 123 | destination-address:: NTP_SERVERS 124 | source-port:: NTP 125 | protocol:: udp 126 | action:: accept 127 | } 128 | 129 | term allow-radius-replies { 130 | source-address:: INTERNAL 131 | destination-address:: INTERNAL 132 | source-port:: RADIUS 133 | protocol:: udp 134 | action:: accept 135 | } 136 | 137 | term allow-tacacs-requests { 138 | source-address:: INTERNAL 139 | destination-address:: TACACS_SERVERS 140 | destination-port:: TACACS 141 | protocol:: tcp 142 | action:: accept 143 | } 144 | 145 | term allow-tacacs-replies { 146 | source-address:: TACACS_SERVERS 147 | destination-address:: INTERNAL 148 | source-port:: TACACS 149 | protocol:: tcp 150 | action:: accept 151 | } 152 | 153 | term allow-dns-fragments { 154 | source-address:: ANY 155 | source-exclude:: PUBLIC_NAT 156 | destination-address:: GOOGLE_DNS 157 | destination-port:: DNS 158 | protocol:: tcp udp 159 | action:: accept 160 | } 161 | 162 | term reject-large-dns { 163 | destination-address:: GOOGLE_DNS 164 | destination-port:: DNS 165 | protocol:: udp 166 | action:: reject 167 | } 168 | 169 | term reject-imap-requests { 170 | destination-address:: MAIL_SERVERS 171 | destination-port:: IMAP 172 | protocol:: tcp 173 | action:: reject-with-tcp-rst 174 | } 175 | 176 | term discard-default { 177 | action:: deny 178 | } 179 | -------------------------------------------------------------------------------- /policies/pol/sample_nsxv.pol: -------------------------------------------------------------------------------- 1 | header { 2 | comment:: "Sample NSXV filter" 3 | target:: nsxv sample_nsxv_filter mixed 1234 securitygroup securitygroupId 4 | } 5 | 6 | term accept-icmp { 7 | comment:: "Allow ICMPv4." 8 | protocol:: icmp 9 | action:: accept 10 | } 11 | 12 | term accept-icmpv6 { 13 | comment:: "Allow ICMPv6." 14 | protocol:: icmpv6 15 | action:: accept 16 | } 17 | 18 | term accept-icmpv6-multiple-types { 19 | comment:: "Allow specific ICMPv6 types router-solicit and echo-reply." 20 | source-address:: GOOGLE_DNS 21 | protocol:: icmpv6 22 | icmp-type:: router-solicit echo-reply 23 | action:: accept 24 | } 25 | 26 | term accept-traceroute { 27 | comment:: "Allow inbound traceroute from any source." 28 | destination-port:: TRACEROUTE 29 | protocol:: udp 30 | action:: accept 31 | expiration:: 2001-12-31 32 | owner:: jeff 33 | } 34 | 35 | term accept-bgp-requests { 36 | comment:: "Allow BGP requests from peers." 37 | destination-port:: BGP 38 | protocol:: tcp 39 | action:: accept 40 | } 41 | 42 | term accept-bgp-replies { 43 | comment:: "Allow inbound replies to BGP requests." 44 | source-port:: BGP 45 | protocol:: tcp 46 | action:: accept 47 | } 48 | 49 | term accept-ospf { 50 | comment:: "Allow outbound OSPF traffic from other RFC1918 routers." 51 | source-address:: INTERNAL 52 | protocol:: ospf 53 | action:: accept 54 | } 55 | 56 | term allow-vrrp { 57 | protocol:: vrrp 58 | action:: accept 59 | } 60 | 61 | term accept-ike { 62 | source-port:: IKE 63 | destination-port:: IKE 64 | protocol:: udp 65 | action:: accept 66 | } 67 | 68 | term accept-ipsec { 69 | protocol:: esp 70 | action:: accept 71 | } 72 | term accept-pim { 73 | source-address:: INTERNAL 74 | protocol:: pim 75 | action:: accept 76 | } 77 | 78 | term accept-igmp { 79 | source-address:: INTERNAL 80 | protocol:: igmp 81 | action:: accept 82 | } 83 | 84 | term accept-ssh-requests { 85 | source-address:: INTERNAL 86 | destination-port:: SSH 87 | protocol:: tcp 88 | action:: accept 89 | } 90 | 91 | term accept-ssh-replies { 92 | source-port:: SSH 93 | protocol:: tcp 94 | action:: accept 95 | } 96 | 97 | term accept-snmp-requests { 98 | source-address:: INTERNAL 99 | destination-address:: INTERNAL 100 | destination-port:: SNMP 101 | protocol:: udp 102 | action:: accept 103 | } 104 | 105 | term accept-dns-replies { 106 | source-address:: INTERNAL 107 | destination-address:: INTERNAL 108 | source-port:: DNS 109 | protocol:: udp 110 | action:: accept 111 | } 112 | 113 | term allow-ntp-request { 114 | source-address:: NTP_SERVERS 115 | destination-address:: INTERNAL 116 | destination-port:: NTP 117 | protocol:: udp 118 | action:: accept 119 | } 120 | 121 | term allow-ntp-replies { 122 | source-address:: INTERNAL 123 | destination-address:: NTP_SERVERS 124 | source-port:: NTP 125 | protocol:: udp 126 | action:: accept 127 | } 128 | 129 | term allow-radius-replies { 130 | source-address:: INTERNAL 131 | destination-address:: INTERNAL 132 | source-port:: RADIUS 133 | protocol:: udp 134 | action:: accept 135 | } 136 | 137 | term allow-tacacs-requests { 138 | source-address:: INTERNAL 139 | destination-address:: TACACS_SERVERS 140 | destination-port:: TACACS 141 | protocol:: tcp 142 | action:: accept 143 | } 144 | 145 | term allow-tacacs-replies { 146 | source-address:: TACACS_SERVERS 147 | destination-address:: INTERNAL 148 | source-port:: TACACS 149 | protocol:: tcp 150 | action:: accept 151 | } 152 | 153 | term allow-dns-fragments { 154 | source-address:: ANY 155 | source-exclude:: PUBLIC_NAT 156 | destination-address:: GOOGLE_DNS 157 | destination-port:: DNS 158 | protocol:: tcp udp 159 | action:: accept 160 | } 161 | 162 | term reject-large-dns { 163 | destination-address:: GOOGLE_DNS 164 | destination-port:: DNS 165 | protocol:: udp 166 | action:: reject 167 | } 168 | 169 | term reject-imap-requests { 170 | destination-address:: MAIL_SERVERS 171 | destination-port:: IMAP 172 | protocol:: tcp 173 | action:: reject-with-tcp-rst 174 | } 175 | 176 | term discard-default { 177 | action:: deny 178 | } 179 | -------------------------------------------------------------------------------- /policies/pol/sample_openconfig.pol: -------------------------------------------------------------------------------- 1 | header { 2 | comment:: "Accepts DHCP, DNS, HTTPS, SMTP." 3 | comment:: "Denies access to internal addressing." 4 | 5 | target:: openconfig inet 6 | } 7 | 8 | term accept-dhcp { 9 | comment:: "Optional - allow DHCP requests." 10 | destination-port:: DHCP 11 | protocol:: udp 12 | action:: accept 13 | } 14 | 15 | term accept-from-googledns { 16 | comment:: "Allow name resolution responses from Google DNS." 17 | source-address:: GOOGLE_DNS 18 | destination-address:: INTERNAL 19 | source-port:: DNS 20 | protocol:: tcp udp 21 | action:: accept 22 | } 23 | 24 | term sport-dport { 25 | comment:: "DENY SMTP." 26 | destination-address:: INTERNAL 27 | source-address:: BOGON 28 | source-port:: SMTP 29 | destination-port:: SMTP 30 | protocol:: tcp 31 | action:: deny 32 | } 33 | 34 | term deny-saddr { 35 | comment:: "Deny everything from bogons." 36 | source-address:: BOGON 37 | action:: deny 38 | } 39 | 40 | term ssh-to-internal { 41 | comment:: "Allow SSH to Internal from Internal." 42 | source-address:: INTERNAL 43 | destination-address:: INTERNAL 44 | destination-port:: SSH 45 | protocol:: tcp 46 | action:: accept 47 | } 48 | 49 | term default-deny { 50 | comment:: "Deny what's left." 51 | action:: deny 52 | } 53 | 54 | -------------------------------------------------------------------------------- /policies/pol/sample_packetfilter.pol: -------------------------------------------------------------------------------- 1 | header { 2 | comment:: "Denies all traffic to internal IPs except established tcp replies." 3 | target:: packetfilter allowtointernet 4 | } 5 | 6 | term accept-dhcp { 7 | comment:: "Optional - allow forwarding of DHCP requests." 8 | destination-port:: DHCP 9 | protocol:: udp 10 | action:: accept 11 | } 12 | 13 | term accept-to-honestdns { 14 | comment:: "Allow name resolution using honestdns." 15 | destination-address:: GOOGLE_DNS 16 | destination-port:: DNS 17 | protocol:: udp 18 | action:: accept 19 | } 20 | 21 | term deny-to-internal { 22 | comment:: "Deny access to rfc1918/internal." 23 | destination-address:: INTERNAL 24 | logging:: true 25 | action:: reject 26 | } 27 | 28 | term test-icmp { 29 | destination-address:: RFC1918 30 | protocol:: icmp 31 | icmp-type:: echo-request echo-reply 32 | action:: accept 33 | } 34 | 35 | term deny-to-specific_hosts { 36 | comment:: "Deny access to specified public." 37 | destination-address:: WEB_SERVERS MAIL_SERVERS 38 | action:: deny 39 | } 40 | 41 | term default-permit { 42 | comment:: "Allow what's left." 43 | action:: accept 44 | } 45 | 46 | -------------------------------------------------------------------------------- /policies/pol/sample_paloalto.pol: -------------------------------------------------------------------------------- 1 | ################ 2 | ### RULEBASE ### 3 | ################ 4 | 5 | # NOTE: makes sure zone names correspond to those specified in your firewall setup 6 | 7 | header { 8 | target:: paloalto from-zone internal to-zone external 9 | } 10 | 11 | term ping-gdns { 12 | source-address:: INTERNAL 13 | destination-address:: GOOGLE_DNS 14 | protocol:: icmp 15 | action:: accept 16 | } 17 | 18 | term dns-gdns { 19 | source-address:: INTERNAL 20 | destination-address:: GOOGLE_DNS 21 | destination-port:: DNS 22 | protocol:: tcp 23 | action:: accept 24 | } 25 | 26 | term allow-web-outbound { 27 | source-address:: INTERNAL 28 | destination-port:: WEB_SERVICES 29 | protocol:: tcp 30 | action:: accept 31 | } 32 | 33 | header { 34 | target:: paloalto from-zone external to-zone internal 35 | } 36 | 37 | term allow-icmp { 38 | protocol:: icmp 39 | action:: accept 40 | } 41 | 42 | # pan-application only: service application-default 43 | term allow-pan-app-01 { 44 | pan-application:: web-browsing 45 | action:: accept 46 | } 47 | 48 | # pan-application + tcp: service any-tcp 49 | term allow-pan-app-02 { 50 | pan-application:: web-browsing 51 | protocol:: tcp 52 | action:: accept 53 | } 54 | 55 | # pan-application + ports: service custom service objects 56 | term allow-pan-app-03 { 57 | pan-application:: ssl 58 | protocol:: tcp 59 | destination-port:: HTTPS IMAPS 60 | action:: accept 61 | } 62 | -------------------------------------------------------------------------------- /policies/pol/sample_sonic.pol: -------------------------------------------------------------------------------- 1 | header { 2 | comment:: "Denies all traffic to internal IPs except established tcp replies." 3 | comment:: "Also denies access to certain public allocations." 4 | 5 | comment:: "Ideal for some internal lab/testing types of subnets that are" 6 | comment:: "not well trusted, but allowing internal users to access." 7 | 8 | comment:: "Apply to ingress interface (to filter traffic coming from lab)" 9 | 10 | comment:: "MirACL version: KJ3RvLwBOkAvcGxhY2VyL3Byb2QvaG9tZS9zZWNvcHMtbmV0LWFjbC1wbGFjZXIvc25hcHNob3RzL3BhcnRpdGlvbj1zc2QvQgYIhpbdiQZKBgitkN2JBlIGCP2P3YkGWgYIgI_diQZqBgiTk92JBnIGCJKU3YkGegYIgpXdiQaCAQYI3ZHdiQY=" 11 | target:: sonic allowtointernet 12 | } 13 | 14 | term accept-dhcp { 15 | comment:: "Optional - allow forwarding of DHCP requests." 16 | destination-port:: DHCP 17 | protocol:: udp 18 | action:: accept 19 | } 20 | 21 | term accept-to-honestdns { 22 | comment:: "Allow name resolution using honestdns." 23 | destination-address:: GOOGLE_DNS 24 | destination-port:: DNS 25 | protocol:: udp 26 | action:: accept 27 | } 28 | 29 | term accept-tcp-replies { 30 | comment:: "Allow tcp replies to internal hosts." 31 | destination-address:: INTERNAL 32 | protocol:: tcp 33 | option:: tcp-established 34 | action:: accept 35 | } 36 | 37 | term deny-to-internal { 38 | comment:: "Deny access to rfc1918/internal." 39 | destination-address:: INTERNAL 40 | action:: deny 41 | } 42 | 43 | term deny-to-specific_hosts { 44 | comment:: "Deny access to specified public." 45 | destination-address:: WEB_SERVERS MAIL_SERVERS 46 | action:: deny 47 | } 48 | 49 | term default-permit { 50 | comment:: "Allow what's left." 51 | action:: accept 52 | } 53 | -------------------------------------------------------------------------------- /policies/pol/sample_speedway.pol: -------------------------------------------------------------------------------- 1 | header { 2 | comment:: "Sample policy for Speedway Iptables." 3 | comment:: "Speedway generates iptables output suitable for loading" 4 | comment:: "using the iptables-restore command" 5 | target:: speedway INPUT DROP 6 | } 7 | term base-allow-est-in { 8 | option:: established 9 | action:: accept 10 | } 11 | term base-allow-icmp-in { 12 | protocol:: icmp 13 | icmp-type:: echo-request 14 | action:: accept 15 | } 16 | term base-traceroute-in { 17 | protocol:: udp 18 | source-port:: TRACEROUTE 19 | destination-port:: HIGH_PORTS 20 | action:: accept 21 | } 22 | term base-allow-ssh-in { 23 | source-address:: INTERNAL 24 | protocol:: tcp 25 | destination-port:: SSH 26 | action:: accept 27 | } 28 | 29 | header { 30 | comment:: "Sample output filter policy for Speedway Iptables." 31 | target:: speedway OUTPUT DROP 32 | } 33 | term base-allow-lo0-out { 34 | comment:: "Allow all loopback communications" 35 | verbatim:: speedway "-A OUTPUT -o lo -j ACCEPT" 36 | } 37 | term base-allow-est-out { 38 | option:: established 39 | action:: accept 40 | } 41 | term base-allow-dns-query-out { 42 | protocol:: udp 43 | destination-port:: DNS 44 | action:: accept 45 | } 46 | term base-allow-icmp-out { 47 | protocol:: icmp 48 | action:: accept 49 | } 50 | term base-traceroute-out { 51 | protocol:: udp 52 | destination-port:: TRACEROUTE 53 | source-port:: HIGH_PORTS 54 | action:: accept 55 | } 56 | term base-allow-ssh-out { 57 | destination-address:: INTERNAL 58 | protocol:: tcp 59 | destination-port:: SSH 60 | action:: accept 61 | } 62 | 63 | header { 64 | comment:: "Sample forwarding filter policy for Speedway Iptables." 65 | target:: speedway FORWARD DROP 66 | } 67 | term base-forwarding-deny { 68 | action:: reject 69 | } 70 | 71 | -------------------------------------------------------------------------------- /policies/pol/sample_srx.pol: -------------------------------------------------------------------------------- 1 | header { 2 | comment:: "this is a sample policy to generate Juniper SRX filter" 3 | comment:: "from zone Untrust to zone DMZ." 4 | target:: srx from-zone Untrust to-zone DMZ 5 | } 6 | 7 | term test-tcp { 8 | destination-address:: RFC1918 9 | protocol:: tcp udp 10 | logging:: log-both 11 | action:: accept 12 | } 13 | 14 | term test-icmp { 15 | destination-address:: RFC1918 16 | protocol:: icmp 17 | icmp-type:: echo-request echo-reply 18 | action:: accept 19 | logging:: true 20 | } 21 | 22 | term good-term-6 { 23 | counter:: good-counter 24 | action:: accept 25 | } 26 | 27 | term default-deny { 28 | action:: deny 29 | logging:: true 30 | } 31 | -------------------------------------------------------------------------------- /policies/pol/sample_stateful_multitarget_complex.pol: -------------------------------------------------------------------------------- 1 | ################ 2 | ### RULEBASE ### 3 | ################ 4 | 5 | # NOTE: makes sure zone names correspond to those specified in your firewall setup 6 | 7 | header { 8 | comment:: "this is a sample policy for a zone based filter that generates" 9 | comment:: "multiple output formats. It checks tcp and udp rules are correctly" 10 | comment:: "generated for a large number of IPv4 IPs." 11 | target:: paloalto from-zone internal to-zone external 12 | target:: srx from-zone internal to-zone external 13 | } 14 | 15 | term test-tcp-udp-many-ipv4 { 16 | comment:: "Testing large IPv4 IPs to test address books." 17 | source-address:: MANY_IPV4 18 | destination-address:: MANY_IPV4 19 | protocol:: tcp udp 20 | action:: accept 21 | } 22 | 23 | header { 24 | comment:: "this is a sample policy for a zone based filter that generates" 25 | comment:: "multiple output formats. It checks tcp and udp rules are correctly" 26 | comment:: "generated for a large number of IPv6 IPs." 27 | target:: paloalto from-zone internal to-zone external inet6 28 | target:: srx from-zone internal to-zone external inet6 29 | } 30 | 31 | term test-tcp-udp-many-ipv6 { 32 | comment:: "Testing large IPv6 IPs to test address books." 33 | source-address:: MANY_IPV6 34 | destination-address:: MANY_IPV6 35 | protocol:: tcp udp 36 | action:: accept 37 | } 38 | 39 | header { 40 | comment:: "this is a sample policy for a zone based filter that generates" 41 | comment:: "multiple output formats. It checks tcp and udp rules are correctly" 42 | comment:: "generated for a large number of mixed IPs." 43 | target:: paloalto from-zone untrust to-zone external mixed 44 | target:: srx from-zone internal to-zone external mixed 45 | } 46 | 47 | term test-tcp-udp-many-mixed { 48 | comment:: "Testing mixed IPv4 and IPv6 IPs to test address books." 49 | source-address:: MANY_IPV4 MANY_IPV6 50 | destination-address:: MANY_IPV4 MANY_IPV6 51 | protocol:: tcp udp 52 | action:: accept 53 | } 54 | -------------------------------------------------------------------------------- /policies/pol/sample_versa.pol: -------------------------------------------------------------------------------- 1 | header { 2 | comment:: "this is a sample policy to generate Versa filter" 3 | target:: versa from-zone trust to-zone untrust template test tenant tenant1 policy Default-Policy 4 | } 5 | 6 | term test-tcp { 7 | destination-address:: WEB_SERVERS 8 | source-address:: INTERNAL 9 | destination-port:: SMTP 10 | protocol:: tcp 11 | logging:: log-both 12 | action:: accept 13 | } 14 | 15 | term test-icmp { 16 | destination-address:: RFC1918 17 | protocol:: icmp 18 | action:: accept 19 | logging:: true 20 | } 21 | term good-term-5 { 22 | destination-address:: WEB_SERVERS 23 | source-address:: INTERNAL 24 | action:: accept 25 | versa-application:: ssh who 26 | } 27 | 28 | 29 | term default-deny { 30 | action:: deny 31 | logging:: true 32 | } 33 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | # Usage: 3 | # $ pip install -r requirements.txt 4 | 5 | absl-py 6 | ply 7 | PyYAML 8 | six>=1.12.0 9 | typing_extensions 10 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | exclude = 3 | .git, 4 | .github, 5 | __pycache__, 6 | dist, 7 | build, 8 | debian, 9 | *.egg, 10 | *.egg-info, 11 | *.venv, 12 | *.archive, 13 | def, 14 | policies, 15 | doc 16 | max-line-length = 100 17 | max-complexity = 10 18 | filename = *.py 19 | ignore = 20 | E111, 21 | E114, 22 | E121, 23 | E731, 24 | C901, 25 | F821, 26 | W504, 27 | E501, 28 | 29 | 30 | [tool:pytest] 31 | markers = 32 | unit: Marks a unit test 33 | sanity: Marks a sanity test 34 | testpaths = tests 35 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2009 Google Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | """capirca installation module.""" 16 | 17 | from os import path 18 | import setuptools 19 | 20 | root_dir = path.abspath(path.dirname(__file__)) 21 | 22 | with open(path.join(root_dir, 'VERSION'), encoding='utf-8') as f: 23 | version = f.readline().strip() 24 | 25 | with open(path.join(root_dir, 'README.md'), encoding='utf-8') as f: 26 | long_description = f.read() 27 | 28 | setuptools.setup( 29 | name='capirca', 30 | version=version, 31 | description='Capirca', 32 | long_description=long_description, 33 | long_description_content_type='text/markdown', 34 | license='Apache License, Version 2.0', 35 | url='https://github.com/google/capirca/', 36 | maintainer='Capirca Team', 37 | maintainer_email='capirca-dev@google.com', 38 | packages=['capirca', 'capirca.lib', 'capirca.utils'], 39 | zip_safe=False, 40 | entry_points={ 41 | 'console_scripts': ['aclgen = capirca.aclgen:EntryPoint'], 42 | }, 43 | classifiers=[ 44 | 'Development Status :: 5 - Production/Stable', 45 | 'License :: OSI Approved :: Apache Software License', 46 | 'Operating System :: OS Independent', 47 | 'Programming Language :: Python :: 3', 48 | 'Programming Language :: Python :: 3.6', 49 | 'Topic :: Security', 50 | 'Topic :: System :: Networking :: Firewalls', 51 | ], 52 | install_requires=[ 53 | 'absl-py', 54 | 'ply', 55 | 'mock', 56 | 'six', 57 | 'PyYAML', 58 | ], 59 | python_requires='>=3.6', 60 | ) 61 | -------------------------------------------------------------------------------- /test-requirements.txt: -------------------------------------------------------------------------------- 1 | attrs==19.3.0 2 | importlib-metadata==1.6.1 3 | mock==4.0.2 4 | more-itertools==8.3.0 5 | packaging==20.4 6 | pluggy==0.13.1 7 | py==1.10.0 8 | pyparsing==2.4.7 9 | pytest==5.4.3 10 | wcwidth==0.2.3 11 | zipp==3.1.0 12 | -------------------------------------------------------------------------------- /tests/README: -------------------------------------------------------------------------------- 1 | To run all tests from trunk: 2 | python -m unittest discover -s . -p '*_test.py' 3 | 4 | Specific tests: 5 | python -m unittest discover -s . -p 'junipersrx_test.py' 6 | 7 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/capirca/b38903cfe24fc6b4fdbb9c4b8e84b69c938d71a5/tests/__init__.py -------------------------------------------------------------------------------- /tests/integration/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/capirca/b38903cfe24fc6b4fdbb9c4b8e84b69c938d71a5/tests/integration/__init__.py -------------------------------------------------------------------------------- /tests/integration/aclgen_test.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 The Capirca Project Authors All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import multiprocessing 16 | import os 17 | import pathlib 18 | import shutil 19 | import sys 20 | import tempfile 21 | from unittest import mock 22 | 23 | from absl import app 24 | from absl import flags 25 | from absl.testing import absltest 26 | from capirca import aclgen 27 | 28 | FLAGS = flags.FLAGS 29 | aclgen.SetupFlags() # Ensure flags are set up only once 30 | # Pass only the program name into absl so it uses the default flags 31 | FLAGS(sys.argv[0:1]) 32 | 33 | 34 | class TestAclGenDemo(absltest.TestCase): 35 | """Ensure Capirca demo runs successfully out-of-the-box.""" 36 | 37 | def setUp(self): 38 | super().setUp() 39 | self.test_subdirectory = tempfile.mkdtemp() 40 | self.def_dir = os.path.join(self.test_subdirectory, 'def') 41 | self.pol_dir = os.path.join(self.test_subdirectory, 'policies') 42 | shutil.rmtree(self.test_subdirectory, ignore_errors=True) 43 | os.mkdir(self.test_subdirectory) 44 | shutil.copytree('def', self.def_dir) 45 | shutil.copytree('policies', self.pol_dir) 46 | self.context = multiprocessing.get_context() 47 | self.max_renderers = 10 48 | self.exp_info = 2 49 | self.ignore_directories = ['DEPRECATED', 'def'] 50 | 51 | @mock.patch.object(aclgen, '_WriteFile', autospec=True) 52 | def test_smoke_test_generates_successfully(self, mock_writer): 53 | aclgen.Run( 54 | self.pol_dir, 55 | self.def_dir, 56 | None, 57 | self.test_subdirectory, 58 | self.exp_info, 59 | self.max_renderers, 60 | self.ignore_directories, 61 | None, 62 | None, 63 | self.context, 64 | ) 65 | files = [ 66 | 'sample_cisco_lab.acl', 67 | 'sample_cloudarmor.gca', 68 | 'sample_gce.gce', 69 | 'sample_ipset.ips', 70 | 'sample_juniper_loopback.jcl', 71 | 'sample_juniperevo_loopback.evojcl', 72 | 'sample_multitarget.acl', 73 | 'sample_multitarget.asa', 74 | 'sample_multitarget.bacl', 75 | 'sample_multitarget.eacl', 76 | 'sample_multitarget.ipt', 77 | 'sample_multitarget.jcl', 78 | 'sample_multitarget.evojcl', 79 | 'sample_multitarget.msmpc', 80 | 'sample_multitarget.xacl', 81 | 'sample_multitarget.nxacl', 82 | 'sample_nsxv.nsx', 83 | 'sample_nsxt.nsxt', 84 | 'sample_packetfilter.pf', 85 | 'sample_speedway.ipt', 86 | 'sample_srx.srx', 87 | 'sample_paloalto.xml', 88 | 'sample_nftables-mixed-icmp.nft', 89 | 'sample_nftables-mixed-multiple-headers-combo.nft', 90 | 'sample_nftables.nft', 91 | 'sample_nftables-dev.nft', 92 | 'sample_stateful_multitarget_simple.xml', 93 | 'sample_stateful_multitarget_simple.srx', 94 | 'sample_stateful_multitarget_complex.xml', 95 | 'sample_stateful_multitarget_complex.srx', 96 | 'sample_k8s.yml', 97 | ] 98 | expected = [ 99 | mock.call(pathlib.Path(self.test_subdirectory, f), mock.ANY) 100 | for f in files 101 | ] 102 | mock_writer.assert_has_calls(expected, any_order=True) 103 | 104 | @mock.patch.object(aclgen, '_WriteFile', autospec=True) 105 | def test_generate_single_policy(self, mock_writer): 106 | policy_file = os.path.join(self.test_subdirectory, 107 | 'policies/pol/sample_cisco_lab.pol') 108 | aclgen.Run( 109 | self.pol_dir, 110 | self.def_dir, 111 | policy_file, 112 | self.test_subdirectory, 113 | self.exp_info, 114 | self.max_renderers, 115 | self.ignore_directories, 116 | None, 117 | None, 118 | self.context, 119 | ) 120 | mock_writer.assert_called_with( 121 | pathlib.Path(self.test_subdirectory, 'sample_cisco_lab.acl'), mock.ANY) 122 | 123 | # Test to ensure existence of the entry point function for installed script. 124 | @mock.patch.object(aclgen, 'SetupFlags', autospec=True) 125 | @mock.patch.object(app, 'run', autospec=True) 126 | def test_entry_point(self, mock_run, mock_flags): 127 | aclgen.EntryPoint() 128 | mock_flags.assert_called_with() 129 | mock_run.assert_called_with(aclgen.main) 130 | 131 | 132 | def main(unused_argv): 133 | absltest.main() 134 | 135 | 136 | if __name__ == '__main__': 137 | app.run(main) 138 | -------------------------------------------------------------------------------- /tests/lib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/capirca/b38903cfe24fc6b4fdbb9c4b8e84b69c938d71a5/tests/lib/__init__.py -------------------------------------------------------------------------------- /tests/lib/aclcheck_test.py: -------------------------------------------------------------------------------- 1 | # Copyright 2008 Google Inc. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Unit tests for AclCheck.""" 16 | 17 | from absl.testing import absltest 18 | 19 | from capirca.lib import aclcheck 20 | from capirca.lib import naming 21 | from capirca.lib import policy 22 | from capirca.lib import port 23 | 24 | 25 | POLICYTEXT = """ 26 | header { 27 | comment:: "this is a test acl" 28 | target:: juniper test-filter 29 | } 30 | term term-1 { 31 | protocol:: tcp 32 | action:: next 33 | } 34 | term term-2 { 35 | source-address:: NET172 36 | destination-address:: NET10 37 | protocol:: tcp 38 | destination-port:: SSH 39 | option:: first-fragment tcp-established 40 | fragment-offset:: 1-6 41 | packet-length:: 1-119 42 | action:: accept 43 | } 44 | term term-3 { 45 | source-address:: NET172 46 | destination-address:: NET10 47 | protocol:: tcp 48 | destination-port:: SSH 49 | action:: accept 50 | } 51 | term term-4 { 52 | protocol:: udp 53 | action:: accept 54 | } 55 | term term-5 { 56 | action:: reject 57 | } 58 | """ 59 | 60 | 61 | class AclCheckTest(absltest.TestCase): 62 | 63 | def setUp(self): 64 | super().setUp() 65 | self.defs = naming.Naming(None) 66 | servicedata = [] 67 | servicedata.append('SSH = 22/tcp') 68 | networkdata = [] 69 | networkdata.append('NET172 = 172.16.0.0/12') 70 | networkdata.append('NET10 = 10.0.0.0/8') 71 | 72 | self.defs.ParseServiceList(servicedata) 73 | self.defs.ParseNetworkList(networkdata) 74 | self.pol = policy.ParsePolicy(POLICYTEXT, self.defs) 75 | 76 | def testExactMatches(self): 77 | check = aclcheck.AclCheck(self.pol, '172.16.1.1', '10.1.1.1', '1025', '22', 78 | 'tcp') 79 | matches = check.ExactMatches() 80 | self.assertEqual(len(matches), 1) 81 | 82 | def testAclCheck(self): 83 | srcip = '172.16.1.1' 84 | dstip = '10.2.2.10' 85 | sport = '10000' 86 | dport = '22' 87 | proto = 'tcp' 88 | check = aclcheck.AclCheck(self.pol, src=srcip, dst=dstip, sport=sport, 89 | dport=dport, proto=proto) 90 | matches = check.Matches() 91 | # Check correct number of matches 92 | self.assertEqual(len(matches), 3) 93 | 94 | # Check correct actions 95 | self.assertEqual(matches[0].action, 'next') # term-1 96 | self.assertEqual(matches[1].action, 'accept') # term-2 97 | self.assertEqual(matches[2].action, 'accept') # term-3 98 | 99 | # Check for correct 'possibles' 100 | self.assertEqual(matches[0].possibles, []) # term-1 101 | self.assertEqual(matches[1].possibles, 102 | ['first-frag', 'frag-offset', 'packet-length', 'tcp-est'] 103 | ) # term-2 104 | self.assertEqual(matches[2].possibles, []) # term-3 105 | 106 | # Check which term names match 107 | self.assertEqual(matches[0].term, 'term-1') 108 | self.assertEqual(matches[1].term, 'term-2') 109 | self.assertEqual(matches[2].term, 'term-3') 110 | # term-4 should never match 111 | self.assertNotIn('term-4', str(matches)) 112 | self.assertNotIn('term-5', str(matches)) 113 | 114 | def testExceptions(self): 115 | srcip = '172.16.1.1' 116 | dstip = '10.2.2.10' 117 | sport = '10000' 118 | dport = '22' 119 | proto = 'tcp' 120 | bad_portrange = '99999' 121 | bad_portvalue = 'port_99' 122 | self.assertRaises(port.BadPortValue, 123 | aclcheck.AclCheck, 124 | self.pol, 125 | srcip, 126 | dstip, 127 | bad_portvalue, 128 | dport, 129 | proto, 130 | ) 131 | self.assertRaises(port.BadPortRange, 132 | aclcheck.AclCheck, 133 | self.pol, 134 | srcip, 135 | dstip, 136 | sport, 137 | bad_portrange, 138 | proto, 139 | ) 140 | self.assertRaises(aclcheck.AddressError, 141 | aclcheck.AclCheck, 142 | self.pol, 143 | '300.400.500.600', 144 | dstip, 145 | sport, 146 | dport, 147 | proto, 148 | ) 149 | 150 | 151 | if __name__ == '__main__': 152 | absltest.main() 153 | -------------------------------------------------------------------------------- /tests/lib/ciscoasa_test.py: -------------------------------------------------------------------------------- 1 | # Copyright 2008 Google Inc. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Unittest for ciscoasa acl rendering module.""" 16 | 17 | from absl.testing import absltest 18 | from unittest import mock 19 | 20 | from capirca.lib import ciscoasa 21 | from capirca.lib import naming 22 | from capirca.lib import policy 23 | 24 | 25 | GOOD_HEADER = """ 26 | header { 27 | comment:: "this is a test acl" 28 | target:: ciscoasa test-filter 29 | } 30 | """ 31 | 32 | GOOD_TERM_1 = """ 33 | term good-term-1 { 34 | verbatim:: ciscoasa "mary had a little lamb" 35 | verbatim:: iptables "mary had second lamb" 36 | verbatim:: juniper "mary had third lamb" 37 | } 38 | """ 39 | 40 | GOOD_TERM_2 = """ 41 | term good-term-2 { 42 | verbatim:: ciscoasa "mary had a little lamb" 43 | policer:: batman 44 | } 45 | """ 46 | 47 | SUPPORTED_TOKENS = { 48 | 'action', 49 | 'comment', 50 | 'destination_address', 51 | 'destination_address_exclude', 52 | 'destination_port', 53 | 'expiration', 54 | 'icmp_type', 55 | 'stateless_reply', 56 | 'logging', 57 | 'name', 58 | 'option', 59 | 'owner', 60 | 'platform', 61 | 'platform_exclude', 62 | 'protocol', 63 | 'source_address', 64 | 'source_address_exclude', 65 | 'source_port', 66 | 'translated', 67 | 'verbatim', 68 | } 69 | 70 | SUPPORTED_SUB_TOKENS = { 71 | 'action': {'accept', 'deny', 'reject', 'next', 72 | 'reject-with-tcp-rst'}, 73 | 'icmp_type': { 74 | 'alternate-address', 75 | 'certification-path-advertisement', 76 | 'certification-path-solicitation', 77 | 'conversion-error', 78 | 'destination-unreachable', 79 | 'echo-reply', 80 | 'echo-request', 'mobile-redirect', 81 | 'home-agent-address-discovery-reply', 82 | 'home-agent-address-discovery-request', 83 | 'icmp-node-information-query', 84 | 'icmp-node-information-response', 85 | 'information-request', 86 | 'inverse-neighbor-discovery-advertisement', 87 | 'inverse-neighbor-discovery-solicitation', 88 | 'mask-reply', 89 | 'mask-request', 'information-reply', 90 | 'mobile-prefix-advertisement', 91 | 'mobile-prefix-solicitation', 92 | 'multicast-listener-done', 93 | 'multicast-listener-query', 94 | 'multicast-listener-report', 95 | 'multicast-router-advertisement', 96 | 'multicast-router-solicitation', 97 | 'multicast-router-termination', 98 | 'neighbor-advertisement', 99 | 'neighbor-solicit', 100 | 'packet-too-big', 101 | 'parameter-problem', 102 | 'redirect', 103 | 'redirect-message', 104 | 'router-advertisement', 105 | 'router-renumbering', 106 | 'router-solicit', 107 | 'router-solicitation', 108 | 'source-quench', 109 | 'time-exceeded', 110 | 'timestamp-reply', 111 | 'timestamp-request', 112 | 'unreachable', 113 | 'version-2-multicast-listener-report', 114 | }, 115 | 'option': {'established', 'tcp-established'}} 116 | 117 | # Print a info message when a term is set to expire in that many weeks. 118 | # This is normally passed from command line. 119 | EXP_INFO = 2 120 | 121 | 122 | class CiscoASATest(absltest.TestCase): 123 | 124 | def setUp(self): 125 | super().setUp() 126 | self.naming = mock.create_autospec(naming.Naming) 127 | 128 | def testBuildTokens(self): 129 | pol1 = ciscoasa.CiscoASA(policy.ParsePolicy(GOOD_HEADER + GOOD_TERM_1, 130 | self.naming), EXP_INFO) 131 | st, sst = pol1._BuildTokens() 132 | self.assertEqual(st, SUPPORTED_TOKENS) 133 | self.assertEqual(sst, SUPPORTED_SUB_TOKENS) 134 | 135 | def testBuildWarningTokens(self): 136 | pol1 = ciscoasa.CiscoASA(policy.ParsePolicy(GOOD_HEADER + GOOD_TERM_2, 137 | self.naming), EXP_INFO) 138 | st, sst = pol1._BuildTokens() 139 | self.assertEqual(st, SUPPORTED_TOKENS) 140 | self.assertEqual(sst, SUPPORTED_SUB_TOKENS) 141 | 142 | 143 | if __name__ == '__main__': 144 | absltest.main() 145 | -------------------------------------------------------------------------------- /tests/lib/gcp_test.py: -------------------------------------------------------------------------------- 1 | """Unittest for GCP Firewall Generator module.""" 2 | 3 | import unittest 4 | 5 | from absl.testing import absltest 6 | 7 | from absl.testing import parameterized 8 | 9 | from capirca.lib import gcp 10 | 11 | 12 | class HelperFunctionsTest(parameterized.TestCase): 13 | 14 | @parameterized.named_parameters( 15 | ('lowercase', 'project'), 16 | ('lowercase_w_hyphen', 'project-id'), 17 | ('lowercase_w_numbers', 'project123'), 18 | ('lowercase_w_numbers_hyphens', 'project-1-2-3')) 19 | def testIsProjectIDValidPasses(self, project): 20 | self.assertTrue(gcp.IsProjectIDValid(project)) 21 | 22 | @parameterized.named_parameters( 23 | ('trailing_hyphen', 'project-'), ('start_w_number', '1project'), 24 | ('start_w_hyphen', '-project'), ('uppercase', 'Project'), 25 | ('too_short_by_one_char', 'proje'), ('too_long_by_one_char', 31 * 'a')) 26 | def testIsProjectIDValidFails(self, project): 27 | self.assertFalse(gcp.IsProjectIDValid(project)) 28 | 29 | @parameterized.named_parameters( 30 | ('lowercase', 'vpc'), ('lowercase_w_hyphen', 'v-p-c'), 31 | ('lowercase_w_numbers', 'vpc123'), 32 | ('lowercase_w_numbers_hyphens', 'vpc-1-2-3'), ('one_letter', 'v')) 33 | def testIsVPCNameValidPasses(self, vpc): 34 | self.assertTrue(gcp.IsVPCNameValid(vpc)) 35 | 36 | @parameterized.named_parameters( 37 | ('trailing_hyphen', 'vpc-'), ('start_w_number', '1vpc'), 38 | ('start_w_hyphen', '-vpc'), ('uppercase', 'Vpc'), 39 | ('too_short_by_one_char', ''), ('too_long_by_one_char', 64 * 'a')) 40 | def testIsVPCNameValidFails(self, vpc): 41 | self.assertFalse(gcp.IsVPCNameValid(vpc)) 42 | 43 | @parameterized.named_parameters( 44 | ('term', 'good-term', 'good-term-v6'), 45 | ('term_with_v6_suffix', 'good-term-v6', 'good-term-v6-v6'), 46 | ('one_letter', 'v', 'v-v6')) 47 | def testGetIpv6TermName(self, term_name, expected): 48 | self.assertEqual(expected, gcp.GetIpv6TermName(term_name)) 49 | 50 | @parameterized.named_parameters( 51 | ('ipv4_mapped', ['::ffff:a02:301/128'], []), 52 | ('6to4', ['2002::/16'], []), 53 | ('ipv4_compatible', ['::0000:a02:301/128'], []), 54 | ('ipv4', ['10.2.3.4/32'], ['10.2.3.4/32']), 55 | ('ipv6', ['2001:4860:8000::5/128'], ['2001:4860:8000::5/128']), 56 | ('ipv4_wildcard', ['0.0.0.0/0'], ['0.0.0.0/0']), 57 | ('ipv6_wildcard', ['::/0'], ['::/0'])) 58 | def testFilterIPv4InIPv6FormatAddrs(self, addrs, expected): 59 | self.assertEqual(expected, gcp.FilterIPv4InIPv6FormatAddrs(addrs)) 60 | with self.assertRaises(ValueError): 61 | gcp.FilterIPv4InIPv6FormatAddrs(['dshjgsjfhgsd']) 62 | 63 | 64 | if __name__ == '__main__': 65 | absltest.main() 66 | -------------------------------------------------------------------------------- /tests/lib/nsxv_mocktest.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 The Capirca Project Authors All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | """Nsxv Mock Test terms for nsxv module.""" 16 | 17 | 18 | 19 | INET_TERM = """\ 20 | term permit-mail-services { 21 | destination-address:: MAIL_SERVERS 22 | protocol:: tcp 23 | destination-port:: MAIL_SERVICES 24 | action:: accept 25 | } 26 | """ 27 | 28 | INET6_TERM = """\ 29 | term test-icmpv6 { 30 | protocol:: icmpv6 31 | icmp-type:: echo-request echo-reply 32 | action:: accept 33 | } 34 | """ 35 | 36 | INET_FILTER = """\ 37 | header { 38 | comment:: "Sample inet NSXV filter" 39 | target:: nsxv INET_FILTER_NAME inet 40 | } 41 | 42 | term allow-ntp-request { 43 | comment::"Allow ntp request" 44 | source-address:: NTP_SERVERS 45 | source-port:: NTP 46 | destination-address:: INTERNAL 47 | destination-port:: NTP 48 | protocol:: udp 49 | action:: accept 50 | } 51 | """ 52 | 53 | INET6_FILTER = """\ 54 | header { 55 | comment:: "Sample inet6 NSXV filter" 56 | target:: nsxv INET6_FILTER_NAME inet6 57 | } 58 | 59 | term test-icmpv6 { 60 | #destination-address:: WEB_SERVERS 61 | protocol:: icmpv6 62 | icmp-type:: echo-request echo-reply 63 | action:: accept 64 | } 65 | """ 66 | 67 | MIXED_FILTER = """\ 68 | header { 69 | comment:: "Sample mixed NSXV filter" 70 | target:: nsxv MIXED_FILTER_NAME mixed 1009 71 | } 72 | 73 | term accept-to-honestdns { 74 | comment:: "Allow name resolution using honestdns." 75 | destination-address:: GOOGLE_DNS 76 | destination-port:: DNS 77 | protocol:: udp 78 | action:: accept 79 | } 80 | """ 81 | 82 | POLICY = """\ 83 | header { 84 | comment:: "Sample NSXV filter" 85 | target:: nsxv POLICY_NAME inet 1007 86 | } 87 | 88 | term reject-imap-requests { 89 | destination-address:: MAIL_SERVERS 90 | destination-port:: IMAP 91 | protocol:: tcp 92 | action:: reject-with-tcp-rst 93 | } 94 | """ 95 | 96 | POLICY_NO_SECTION_ID = """\ 97 | header { 98 | comment:: "NSXV filter without section id" 99 | target:: nsxv POLICY_NO_SECTION_ID_NAME inet 100 | } 101 | term accept-icmp { 102 | protocol:: icmp 103 | action:: accept 104 | } 105 | """ 106 | 107 | POLICY_NO_FILTERTYPE = """\ 108 | header { 109 | comment:: "Sample NSXV filter" 110 | target:: nsxv POLICY_NO_FILTERTYPE_NAME 111 | } 112 | term accept-icmp { 113 | protocol:: icmp 114 | action:: accept 115 | } 116 | """ 117 | 118 | POLICY_INCORRECT_FILTERTYPE = """\ 119 | header { 120 | comment:: "Sample NSXV filter" 121 | target:: nsxv POLICY_INCORRECT_FILTERTYPE_NAME inet1 122 | } 123 | term accept-icmp { 124 | protocol:: icmp 125 | action:: accept 126 | } 127 | """ 128 | 129 | POLICY_OPTION_KYWD = """\ 130 | header { 131 | comment:: "Sample NSXV filter" 132 | target:: nsxv POLICY_OPTION_KYWD_NAME inet 1009 133 | } 134 | term accept-bgp-replies { 135 | comment:: "Allow inbound replies to BGP requests." 136 | source-port:: BGP 137 | protocol:: tcp 138 | option:: tcp-established 139 | action:: accept 140 | } 141 | """ 142 | -------------------------------------------------------------------------------- /tests/unit/wrapwords_test.py: -------------------------------------------------------------------------------- 1 | from capirca.lib.aclgenerator import WrapWords 2 | import pytest 3 | 4 | SINGLE_LINE_OVERFLOW_TEXT_LONG = \ 5 | "http://github.com/google/capirca/commit/c5" + \ 6 | "6ddf19e2679892ff078cf27aeb18310c2697ed This " + \ 7 | "is a long header. It's long on purpose. It's " + \ 8 | "purpose is to test that the splitting works co" + \ 9 | "rrectly. It should be well over the line limit" + \ 10 | ". If it is shorter, it would not test the limit." 11 | 12 | SINGLE_LINE_OVERFLOW_TEXT_LONG_EXPECTED = [ 13 | "http://github.com/google/capirca/commit/c56ddf19e2679892ff078cf27aeb18", 14 | "310c2697ed", 15 | "This is a long header. It's long on purpose. It's purpose is to test", 16 | "that the splitting works correctly. It should be well over the line", 17 | "limit. If it is shorter, it would not test the limit." 18 | ] 19 | 20 | MULTI_LINE_OVERFLOW_TEXT_LONG = \ 21 | "this is a veryveryveryveryveryveryveryveryver" + \ 22 | "yveryveryveryveryveryveryveryveryveryveryvery" + \ 23 | "veryveryveryveryveryveryveryveryveryveryveryv" + \ 24 | "eryveryveryveryveryveryveryveryveryveryvery long word" 25 | 26 | MULTI_LINE_OVERFLOW_TEXT_LONG_EXPECTED = [ 27 | "this is a", 28 | "veryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryve", 29 | "ryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryvery", 30 | "veryveryveryveryveryveryvery", 31 | "long word" 32 | ] 33 | 34 | NO_OVERFLOW_LONG = \ 35 | "This " + \ 36 | "is a long header. It's long on purpose. It's " + \ 37 | "purpose is to test that the splitting works co" + \ 38 | "rrectly. It should be well over the line limit" + \ 39 | ". If it is shorter, it would not test the limit." 40 | 41 | NO_OVERFLOW_LONG_EXPECTED = [ 42 | "This is a long header. It's long on purpose. It's purpose is to test", 43 | "that the splitting works correctly. It should be well over the line", 44 | "limit. If it is shorter, it would not test the limit." 45 | ] 46 | 47 | NO_OVERFLOW_SHORT = \ 48 | "This is a short line of text" 49 | 50 | NO_OVERFLOW_SHORT_EXPECTED = [ 51 | "This is a short line of text" 52 | ] 53 | 54 | @pytest.mark.parametrize("test_input,expected", [ 55 | (NO_OVERFLOW_SHORT, NO_OVERFLOW_SHORT_EXPECTED), 56 | (NO_OVERFLOW_LONG, NO_OVERFLOW_LONG_EXPECTED), 57 | (SINGLE_LINE_OVERFLOW_TEXT_LONG, SINGLE_LINE_OVERFLOW_TEXT_LONG_EXPECTED), 58 | (MULTI_LINE_OVERFLOW_TEXT_LONG, MULTI_LINE_OVERFLOW_TEXT_LONG_EXPECTED) 59 | ] 60 | ) 61 | 62 | 63 | def testWrapWords(test_input, expected): 64 | result = WrapWords([test_input], 70) 65 | assert all((res == exp for res, exp in zip(result, expected))) 66 | -------------------------------------------------------------------------------- /tests/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/capirca/b38903cfe24fc6b4fdbb9c4b8e84b69c938d71a5/tests/utils/__init__.py -------------------------------------------------------------------------------- /tests/utils/iputils_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | import pathlib 4 | 5 | from capirca.utils import iputils 6 | from capirca.lib import nacaddr 7 | 8 | 9 | file_directory = pathlib.Path(__file__).parent.absolute() 10 | exclude_address_testcases = [] 11 | with open(str(file_directory)+"/address_exclude_test_cases.txt", 'r') as f: 12 | for line in f: 13 | ipstr, exstrs, restrs = line.strip().split(' ') 14 | ip = nacaddr.IP(ipstr) 15 | exclude_ips = list(map(nacaddr.IP, exstrs.split(','))) 16 | expected_results = [] 17 | for i in restrs.split(';'): 18 | result_strings = i.split(',') 19 | ip_map = map(nacaddr.IP, result_strings) 20 | ip_list = list(ip_map) 21 | expected_results.append(ip_list) 22 | for ex, res in zip(exclude_ips, expected_results): 23 | exclude_address_testcases.append((ip, ex, res)) 24 | 25 | class TestIPUtils: 26 | @pytest.mark.unit 27 | @pytest.mark.parametrize("ip,exclude,expected", exclude_address_testcases) 28 | def test_exclude_address(self, ip, exclude, expected): 29 | result = iputils.exclude_address(ip, exclude) 30 | 31 | assert list(result) == expected 32 | -------------------------------------------------------------------------------- /tools/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/capirca/b38903cfe24fc6b4fdbb9c4b8e84b69c938d71a5/tools/__init__.py -------------------------------------------------------------------------------- /tools/get-country-zones.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | # 3 | # Author: Paul Armstrong 4 | # 5 | # Downloads maps of countries to CIDR netblocks for the world and then turns 6 | # them into definition files usable by Capirca 7 | 8 | use strict; 9 | use warnings; 10 | use File::Find; 11 | 12 | my @files; 13 | my $destination = '../def/'; 14 | my $extension = '.net'; 15 | 16 | system("wget http://www.ipdeny.com/ipblocks/data/countries/all-zones.tar.gz") 17 | == 0 or die "Unable to get all-zones.tar.gz: $?\n"; 18 | 19 | system("tar -zxf all-zones.tar.gz") == 0 20 | or die "Unable to untar all-zones.tar.gz: $?\n"; 21 | 22 | # We don't need these lying around 23 | unlink("Copyrights.txt"); 24 | unlink("MD5SUM"); 25 | unlink("all-zones.tar.gz"); 26 | 27 | sub zone_files 28 | { 29 | push @files, $File::Find::name if(/\.zone$/i); 30 | } 31 | 32 | find(\&zone_files, $ENV{PWD}); 33 | 34 | for my $file (@files) 35 | { 36 | if($file =~ /^.*\/([a-z]{2})\.zone/) 37 | { 38 | my $country = $1; 39 | my $new_name = "$destination$country$extension"; 40 | my $country_uc = uc($country); 41 | die "$file is zero bytes\n" if(!-s $file); 42 | open(OLDFILE, $file) or die "Unable to open $file: $!\n"; 43 | open(NEWFILE, ">$new_name") 44 | or die "Unable to open $new_name: $!\n"; 45 | while() 46 | { 47 | chomp; 48 | if ($. == 1) 49 | { 50 | print NEWFILE "${country_uc}_NETBLOCKS = $_\n" 51 | or die "Unable to print to $new_name: $!\n"; 52 | } 53 | else 54 | { 55 | print NEWFILE " $_\n" 56 | or die "Unable to print to $new_name: $!\n"; 57 | } 58 | } 59 | close(NEWFILE) or die "$new_name didn't close properly: $!\n"; 60 | close(OLDFILE); 61 | die "$new_name is zero bytes\n" if(!-s $new_name); 62 | unlink($file); # clean up the originals. 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /tools/iputilstools.py: -------------------------------------------------------------------------------- 1 | import random 2 | import ipaddress 3 | import itertools as it 4 | 5 | 6 | def write_excludes_testcase(ipstr, excludelist='', max_prefix_range=8, max_random_subnets=30): 7 | """ 8 | Writes a testcase to the tests/utils/address_exclude_test_cases.txt file. 9 | Note that the number of prefixes to consider grows exponentially, so unless 10 | you *do* want to consider a large pool to randomly select from, keep it at the default 11 | 12 | Args: 13 | ipstr: the ip network as a string (v4 or v6) to base the test on. 14 | excludelist: optional comma-separated string of ip networks to exclude 15 | max_prefix_range: the largest number of prefixes to consider. 16 | max_random_subnets: the number of subnets to do exclusion tests for, if randomly generating 17 | Returns: 18 | None 19 | """ 20 | ip = ipaddress.ip_network(ipstr) 21 | if len(excludelist) == 0: # empty excludelist, making a random one 22 | prefixrange = min(max_prefix_range, ip.max_prefixlen - ip.prefixlen) 23 | excludelist = it.chain.from_iterable(ip.subnets(i) for i in range(1, prefixrange+1)) 24 | total_ips = 2**prefixrange 25 | ip_positions = set( 26 | random.choices( 27 | range(total_ips), 28 | k=min( 29 | max_random_subnets, 30 | total_ips 31 | ) 32 | ) 33 | ) 34 | compress_map = (1 if i in ip_positions else 0 for i in range(total_ips)) 35 | excludelist = list(it.compress(excludelist, compress_map)) 36 | else: 37 | excludelist = list(map(ipaddress.ip_network, excludelist.split(','))) 38 | 39 | result_list = [] 40 | for address in excludelist: 41 | result_list.append(ip.address_exclude(address)) 42 | 43 | ipst = str(ip) 44 | exst = ",".join(map(str, excludelist)) 45 | rest = ";".join(",".join(map(str, sorted(result))) for result in result_list) 46 | with open('tests/utils/address_exclude_test_cases.txt', 'a') as f: 47 | f.write("%s %s %s\n" % (ipst, exst, rest)) 48 | -------------------------------------------------------------------------------- /tools/run_lint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright 2016 Google Inc. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | find . -name "*.py" | sort |\ 16 | xargs pylint --rcfile tools/pylintrc --msg-template='{msg_id}:{line:4} {obj}: {msg}[{symbol}]' > ./tools/new_lint_errors.txt 17 | 18 | # Cannot disable the following errors, seems this is a known issue from searching online. 19 | sed -i ':a;N;$!ba;s/R0801.*duplicate-code]//g' ./tools/new_lint_errors.txt 20 | sed -i 's/R0904.*too-many-public-methods]//g' ./tools/new_lint_errors.txt 21 | sed -i 's/R0912.*too-many-branches]//g' ./tools/new_lint_errors.txt 22 | sed -i 's/R0914.*too-many-locals]//g' ./tools/new_lint_errors.txt 23 | sed -i 's/R0915.*too-many-statements]//g' ./tools/new_lint_errors.txt 24 | sed -i '/^\s*$/d' ./tools/new_lint_errors.txt 25 | new_diff=$(diff -u tools/current_lint_errors.txt tools/new_lint_errors.txt | grep -E "^\+[^+]") 26 | 27 | if [ "$new_diff" == "" ] 28 | then 29 | echo "[OK] The codebase passes the linter tests!"; 30 | else 31 | echo "[ERROR] There are additional new lint errors present in your changes." 32 | echo "$new_diff" 33 | exit 1 34 | fi 35 | --------------------------------------------------------------------------------